blob: ebbb8c407dbc82edaed3b2f63521bbafedde8df6 [file] [log] [blame]
Cody Northrop6cca6c22023-02-08 20:23:13 -07001/*
2 ** Copyright 2022, 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// #define LOG_NDEBUG 0
18
19#include "MultifileBlobCache.h"
20
Cody Northrop027f2422023-11-12 22:51:01 -070021#include <android-base/properties.h>
Cody Northrop6cca6c22023-02-08 20:23:13 -070022#include <dirent.h>
23#include <fcntl.h>
24#include <inttypes.h>
25#include <log/log.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <sys/mman.h>
29#include <sys/stat.h>
30#include <time.h>
31#include <unistd.h>
32#include <utime.h>
33
34#include <algorithm>
35#include <chrono>
36#include <limits>
37#include <locale>
38
39#include <utils/JenkinsHash.h>
40
Cody Northrop4ee63862024-11-19 22:41:23 -070041#include <com_android_graphics_egl_flags.h>
42
43using namespace com::android::graphics::egl;
44
Cody Northrop6cca6c22023-02-08 20:23:13 -070045using namespace std::literals;
46
Cody Northrop999db232023-02-27 17:02:50 -070047constexpr uint32_t kMultifileMagic = 'MFB$';
48constexpr uint32_t kCrcPlaceholder = 0;
49
Cody Northrop6cca6c22023-02-08 20:23:13 -070050namespace {
51
Cody Northrop6cca6c22023-02-08 20:23:13 -070052// Helper function to close entries or free them
53void freeHotCacheEntry(android::MultifileHotCache& entry) {
54 if (entry.entryFd != -1) {
55 // If we have an fd, then this entry was added to hot cache via INIT or GET
Cody Northrop5f8117a2023-09-26 20:48:59 -060056 // We need to unmap the entry
Cody Northrop6cca6c22023-02-08 20:23:13 -070057 munmap(entry.entryBuffer, entry.entrySize);
Cody Northrop6cca6c22023-02-08 20:23:13 -070058 } else {
59 // Otherwise, this was added to hot cache during SET, so it was never mapped
60 // and fd was only on the deferred thread.
61 delete[] entry.entryBuffer;
62 }
63}
64
65} // namespace
66
67namespace android {
68
Cody Northrop5dbcfa72023-03-24 15:34:09 -060069MultifileBlobCache::MultifileBlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize,
Cody Northropb5267032023-10-24 10:11:21 -060070 size_t maxTotalEntries, const std::string& baseDir)
Cody Northrop6cca6c22023-02-08 20:23:13 -070071 : mInitialized(false),
Cody Northrop027f2422023-11-12 22:51:01 -070072 mCacheVersion(0),
Cody Northrop5dbcfa72023-03-24 15:34:09 -060073 mMaxKeySize(maxKeySize),
74 mMaxValueSize(maxValueSize),
Cody Northrop6cca6c22023-02-08 20:23:13 -070075 mMaxTotalSize(maxTotalSize),
Cody Northropb5267032023-10-24 10:11:21 -060076 mMaxTotalEntries(maxTotalEntries),
Cody Northrop6cca6c22023-02-08 20:23:13 -070077 mTotalCacheSize(0),
Cody Northropb5267032023-10-24 10:11:21 -060078 mTotalCacheEntries(0),
Cody Northrop5dbcfa72023-03-24 15:34:09 -060079 mHotCacheLimit(0),
Cody Northrop6cca6c22023-02-08 20:23:13 -070080 mHotCacheSize(0),
81 mWorkerThreadIdle(true) {
82 if (baseDir.empty()) {
83 ALOGV("INIT: no baseDir provided in MultifileBlobCache constructor, returning early.");
84 return;
85 }
86
Cody Northrop4ee63862024-11-19 22:41:23 -070087 // Set the cache version
Cody Northrop027f2422023-11-12 22:51:01 -070088 mCacheVersion = kMultifileBlobCacheVersion;
Cody Northrop4ee63862024-11-19 22:41:23 -070089 // Bump the version if we're using flagged features
90 if (flags::multifile_blobcache_advanced_usage()) {
91 mCacheVersion++;
92 }
93 // Override if debug value set
Cody Northrop027f2422023-11-12 22:51:01 -070094 int debugCacheVersion = base::GetIntProperty("debug.egl.blobcache.cache_version", -1);
95 if (debugCacheVersion >= 0) {
96 ALOGV("INIT: Using %u as cacheVersion instead of %u", debugCacheVersion, mCacheVersion);
97 mCacheVersion = debugCacheVersion;
98 }
99
100 // Set the platform build ID, override if debug value set
101 mBuildId = base::GetProperty("ro.build.id", "");
102 std::string debugBuildId = base::GetProperty("debug.egl.blobcache.build_id", "");
103 if (!debugBuildId.empty()) {
104 ALOGV("INIT: Using %s as buildId instead of %s", debugBuildId.c_str(), mBuildId.c_str());
105 if (debugBuildId.length() > PROP_VALUE_MAX) {
106 ALOGV("INIT: debugBuildId is too long (%zu), reduce it to %u", debugBuildId.length(),
107 PROP_VALUE_MAX);
108 }
109 mBuildId = debugBuildId;
110 }
111
Cody Northrop6cca6c22023-02-08 20:23:13 -0700112 // Establish the name of our multifile directory
113 mMultifileDirName = baseDir + ".multifile";
114
Cody Northrop5dbcfa72023-03-24 15:34:09 -0600115 // Set the hotcache limit to be large enough to contain one max entry
116 // This ensure the hot cache is always large enough for single entry
117 mHotCacheLimit = mMaxKeySize + mMaxValueSize + sizeof(MultifileHeader);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700118
119 ALOGV("INIT: Initializing multifile blobcache with maxKeySize=%zu and maxValueSize=%zu",
120 mMaxKeySize, mMaxValueSize);
121
122 // Initialize our cache with the contents of the directory
123 mTotalCacheSize = 0;
124
125 // Create the worker thread
126 mTaskThread = std::thread(&MultifileBlobCache::processTasks, this);
127
128 // See if the dir exists, and initialize using its contents
Cody Northrop027f2422023-11-12 22:51:01 -0700129 bool statusGood = false;
130
131 // Check that our cacheVersion and buildId match
Cody Northrop6cca6c22023-02-08 20:23:13 -0700132 struct stat st;
133 if (stat(mMultifileDirName.c_str(), &st) == 0) {
Cody Northrop027f2422023-11-12 22:51:01 -0700134 if (checkStatus(mMultifileDirName.c_str())) {
135 statusGood = true;
136 } else {
137 ALOGV("INIT: Cache status has changed, clearing the cache");
138 if (!clearCache()) {
139 ALOGE("INIT: Unable to clear cache");
140 return;
141 }
142 }
143 }
144
145 if (statusGood) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700146 // Read all the files and gather details, then preload their contents
147 DIR* dir;
148 struct dirent* entry;
149 if ((dir = opendir(mMultifileDirName.c_str())) != nullptr) {
150 while ((entry = readdir(dir)) != nullptr) {
Cody Northrop027f2422023-11-12 22:51:01 -0700151 if (entry->d_name == "."s || entry->d_name == ".."s ||
152 strcmp(entry->d_name, kMultifileBlobCacheStatusFile) == 0) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700153 continue;
154 }
155
156 std::string entryName = entry->d_name;
157 std::string fullPath = mMultifileDirName + "/" + entryName;
158
159 // The filename is the same as the entryHash
160 uint32_t entryHash = static_cast<uint32_t>(strtoul(entry->d_name, nullptr, 10));
161
162 ALOGV("INIT: Checking entry %u", entryHash);
163
164 // Look up the details of the file
165 struct stat st;
166 if (stat(fullPath.c_str(), &st) != 0) {
167 ALOGE("Failed to stat %s", fullPath.c_str());
168 return;
169 }
170
Cody Northrop999db232023-02-27 17:02:50 -0700171 // If the cache entry is damaged or no good, remove it
172 if (st.st_size <= 0 || st.st_atime <= 0) {
173 ALOGE("INIT: Entry %u has invalid stats! Removing.", entryHash);
174 if (remove(fullPath.c_str()) != 0) {
Cody Northrop027f2422023-11-12 22:51:01 -0700175 ALOGE("INIT: Error removing %s: %s", fullPath.c_str(),
176 std::strerror(errno));
Cody Northrop999db232023-02-27 17:02:50 -0700177 }
178 continue;
179 }
180
Cody Northrop6cca6c22023-02-08 20:23:13 -0700181 // Open the file so we can read its header
182 int fd = open(fullPath.c_str(), O_RDONLY);
183 if (fd == -1) {
184 ALOGE("Cache error - failed to open fullPath: %s, error: %s", fullPath.c_str(),
185 std::strerror(errno));
186 return;
187 }
188
Cody Northrop999db232023-02-27 17:02:50 -0700189 // Read the beginning of the file to get header
190 MultifileHeader header;
191 size_t result = read(fd, static_cast<void*>(&header), sizeof(MultifileHeader));
192 if (result != sizeof(MultifileHeader)) {
Cody Northrop027f2422023-11-12 22:51:01 -0700193 ALOGE("INIT: Error reading MultifileHeader from cache entry (%s): %s",
Cody Northrop999db232023-02-27 17:02:50 -0700194 fullPath.c_str(), std::strerror(errno));
Cody Northrop5f8117a2023-09-26 20:48:59 -0600195 close(fd);
Cody Northrop999db232023-02-27 17:02:50 -0700196 return;
197 }
198
199 // Verify header magic
200 if (header.magic != kMultifileMagic) {
201 ALOGE("INIT: Entry %u has bad magic (%u)! Removing.", entryHash, header.magic);
202 if (remove(fullPath.c_str()) != 0) {
Cody Northrop027f2422023-11-12 22:51:01 -0700203 ALOGE("INIT: Error removing %s: %s", fullPath.c_str(),
204 std::strerror(errno));
Cody Northrop999db232023-02-27 17:02:50 -0700205 }
Cody Northrop5f8117a2023-09-26 20:48:59 -0600206 close(fd);
Cody Northrop999db232023-02-27 17:02:50 -0700207 continue;
208 }
209
210 // Note: Converting from off_t (signed) to size_t (unsigned)
211 size_t fileSize = static_cast<size_t>(st.st_size);
212
213 // Memory map the file
214 uint8_t* mappedEntry = reinterpret_cast<uint8_t*>(
215 mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0));
Cody Northrop5f8117a2023-09-26 20:48:59 -0600216
217 // We can close the file now and the mmap will remain
218 close(fd);
219
Cody Northrop999db232023-02-27 17:02:50 -0700220 if (mappedEntry == MAP_FAILED) {
221 ALOGE("Failed to mmap cacheEntry, error: %s", std::strerror(errno));
222 return;
223 }
224
225 // Ensure we have a good CRC
Jisun Lee88a1b762024-10-17 20:12:29 +0900226 if (header.crc != GenerateCRC32(mappedEntry + sizeof(MultifileHeader),
227 fileSize - sizeof(MultifileHeader))) {
Cody Northrop027f2422023-11-12 22:51:01 -0700228 ALOGV("INIT: Entry %u failed CRC check! Removing.", entryHash);
Cody Northrop999db232023-02-27 17:02:50 -0700229 if (remove(fullPath.c_str()) != 0) {
230 ALOGE("Error removing %s: %s", fullPath.c_str(), std::strerror(errno));
231 }
232 continue;
233 }
Cody Northrop6cca6c22023-02-08 20:23:13 -0700234
235 // If the cache entry is damaged or no good, remove it
Cody Northrop999db232023-02-27 17:02:50 -0700236 if (header.keySize <= 0 || header.valueSize <= 0) {
Cody Northrop027f2422023-11-12 22:51:01 -0700237 ALOGV("INIT: Entry %u has a bad header keySize (%lu) or valueSize (%lu), "
Cody Northrop999db232023-02-27 17:02:50 -0700238 "removing.",
239 entryHash, header.keySize, header.valueSize);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700240 if (remove(fullPath.c_str()) != 0) {
Cody Northrop027f2422023-11-12 22:51:01 -0700241 ALOGE("INIT: Error removing %s: %s", fullPath.c_str(),
242 std::strerror(errno));
Cody Northrop6cca6c22023-02-08 20:23:13 -0700243 }
244 continue;
245 }
246
247 ALOGV("INIT: Entry %u is good, tracking it now.", entryHash);
248
Cody Northrop6cca6c22023-02-08 20:23:13 -0700249 // Track details for rapid lookup later
Cody Northrop999db232023-02-27 17:02:50 -0700250 trackEntry(entryHash, header.valueSize, fileSize, st.st_atime);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700251
252 // Track the total size
253 increaseTotalCacheSize(fileSize);
254
255 // Preload the entry for fast retrieval
256 if ((mHotCacheSize + fileSize) < mHotCacheLimit) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700257 ALOGV("INIT: Populating hot cache with fd = %i, cacheEntry = %p for "
258 "entryHash %u",
259 fd, mappedEntry, entryHash);
260
261 // Track the details of the preload so they can be retrieved later
262 if (!addToHotCache(entryHash, fd, mappedEntry, fileSize)) {
263 ALOGE("INIT Failed to add %u to hot cache", entryHash);
264 munmap(mappedEntry, fileSize);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700265 return;
266 }
267 } else {
Cody Northrop999db232023-02-27 17:02:50 -0700268 // If we're not keeping it in hot cache, unmap it now
269 munmap(mappedEntry, fileSize);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700270 }
271 }
272 closedir(dir);
273 } else {
274 ALOGE("Unable to open filename: %s", mMultifileDirName.c_str());
275 }
276 } else {
277 // If the multifile directory does not exist, create it and start from scratch
278 if (mkdir(mMultifileDirName.c_str(), 0755) != 0 && (errno != EEXIST)) {
279 ALOGE("Unable to create directory (%s), errno (%i)", mMultifileDirName.c_str(), errno);
Cody Northrop027f2422023-11-12 22:51:01 -0700280 return;
281 }
282
283 // Create new status file
284 if (!createStatus(mMultifileDirName.c_str())) {
285 ALOGE("INIT: Failed to create status file!");
286 return;
Cody Northrop6cca6c22023-02-08 20:23:13 -0700287 }
288 }
289
Cody Northrop027f2422023-11-12 22:51:01 -0700290 ALOGV("INIT: Multifile BlobCache initialization succeeded");
Cody Northrop6cca6c22023-02-08 20:23:13 -0700291 mInitialized = true;
292}
293
294MultifileBlobCache::~MultifileBlobCache() {
295 if (!mInitialized) {
296 return;
297 }
298
299 // Inform the worker thread we're done
300 ALOGV("DESCTRUCTOR: Shutting down worker thread");
301 DeferredTask task(TaskCommand::Exit);
302 queueTask(std::move(task));
303
304 // Wait for it to complete
305 ALOGV("DESCTRUCTOR: Waiting for worker thread to complete");
306 waitForWorkComplete();
307 if (mTaskThread.joinable()) {
308 mTaskThread.join();
309 }
310}
311
312// Set will add the entry to hot cache and start a deferred process to write it to disk
313void MultifileBlobCache::set(const void* key, EGLsizeiANDROID keySize, const void* value,
314 EGLsizeiANDROID valueSize) {
315 if (!mInitialized) {
316 return;
317 }
318
319 // Ensure key and value are under their limits
320 if (keySize > mMaxKeySize || valueSize > mMaxValueSize) {
Cody Northrop5dbcfa72023-03-24 15:34:09 -0600321 ALOGW("SET: keySize (%lu vs %zu) or valueSize (%lu vs %zu) too large", keySize, mMaxKeySize,
Cody Northrop6cca6c22023-02-08 20:23:13 -0700322 valueSize, mMaxValueSize);
323 return;
324 }
325
326 // Generate a hash of the key and use it to track this entry
327 uint32_t entryHash = android::JenkinsHashMixBytes(0, static_cast<const uint8_t*>(key), keySize);
328
329 size_t fileSize = sizeof(MultifileHeader) + keySize + valueSize;
330
331 // If we're going to be over the cache limit, kick off a trim to clear space
Cody Northropb5267032023-10-24 10:11:21 -0600332 if (getTotalSize() + fileSize > mMaxTotalSize || getTotalEntries() + 1 > mMaxTotalEntries) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700333 ALOGV("SET: Cache is full, calling trimCache to clear space");
Cody Northropf2588a82023-03-27 23:03:49 -0600334 trimCache();
Cody Northrop6cca6c22023-02-08 20:23:13 -0700335 }
336
337 ALOGV("SET: Add %u to cache", entryHash);
338
339 uint8_t* buffer = new uint8_t[fileSize];
340
Cody Northrop45ce6802023-03-23 11:07:09 -0600341 // Write placeholders for magic and CRC until deferred thread completes the write
Cody Northrop999db232023-02-27 17:02:50 -0700342 android::MultifileHeader header = {kMultifileMagic, kCrcPlaceholder, keySize, valueSize};
Cody Northrop6cca6c22023-02-08 20:23:13 -0700343 memcpy(static_cast<void*>(buffer), static_cast<const void*>(&header),
344 sizeof(android::MultifileHeader));
Cody Northrop999db232023-02-27 17:02:50 -0700345 // Write the key and value after the header
Cody Northrop6cca6c22023-02-08 20:23:13 -0700346 memcpy(static_cast<void*>(buffer + sizeof(MultifileHeader)), static_cast<const void*>(key),
347 keySize);
348 memcpy(static_cast<void*>(buffer + sizeof(MultifileHeader) + keySize),
349 static_cast<const void*>(value), valueSize);
350
351 std::string fullPath = mMultifileDirName + "/" + std::to_string(entryHash);
352
353 // Track the size and access time for quick recall
354 trackEntry(entryHash, valueSize, fileSize, time(0));
355
356 // Update the overall cache size
357 increaseTotalCacheSize(fileSize);
358
359 // Keep the entry in hot cache for quick retrieval
360 ALOGV("SET: Adding %u to hot cache.", entryHash);
361
362 // Sending -1 as the fd indicates we don't have an fd for this
363 if (!addToHotCache(entryHash, -1, buffer, fileSize)) {
Cody Northropbe163732023-03-22 10:14:26 -0600364 ALOGE("SET: Failed to add %u to hot cache", entryHash);
Cody Northrop45ce6802023-03-23 11:07:09 -0600365 delete[] buffer;
Cody Northrop6cca6c22023-02-08 20:23:13 -0700366 return;
367 }
368
369 // Track that we're creating a pending write for this entry
370 // Include the buffer to handle the case when multiple writes are pending for an entry
Cody Northropbe163732023-03-22 10:14:26 -0600371 {
372 // Synchronize access to deferred write status
373 std::lock_guard<std::mutex> lock(mDeferredWriteStatusMutex);
374 mDeferredWrites.insert(std::make_pair(entryHash, buffer));
375 }
Cody Northrop6cca6c22023-02-08 20:23:13 -0700376
377 // Create deferred task to write to storage
378 ALOGV("SET: Adding task to queue.");
379 DeferredTask task(TaskCommand::WriteToDisk);
380 task.initWriteToDisk(entryHash, fullPath, buffer, fileSize);
381 queueTask(std::move(task));
382}
383
384// Get will check the hot cache, then load it from disk if needed
385EGLsizeiANDROID MultifileBlobCache::get(const void* key, EGLsizeiANDROID keySize, void* value,
386 EGLsizeiANDROID valueSize) {
387 if (!mInitialized) {
388 return 0;
389 }
390
391 // Ensure key and value are under their limits
392 if (keySize > mMaxKeySize || valueSize > mMaxValueSize) {
Cody Northrop5dbcfa72023-03-24 15:34:09 -0600393 ALOGW("GET: keySize (%lu vs %zu) or valueSize (%lu vs %zu) too large", keySize, mMaxKeySize,
Cody Northrop6cca6c22023-02-08 20:23:13 -0700394 valueSize, mMaxValueSize);
395 return 0;
396 }
397
398 // Generate a hash of the key and use it to track this entry
399 uint32_t entryHash = android::JenkinsHashMixBytes(0, static_cast<const uint8_t*>(key), keySize);
400
401 // See if we have this file
402 if (!contains(entryHash)) {
403 ALOGV("GET: Cache MISS - cache does not contain entry: %u", entryHash);
404 return 0;
405 }
406
407 // Look up the data for this entry
408 MultifileEntryStats entryStats = getEntryStats(entryHash);
409
410 size_t cachedValueSize = entryStats.valueSize;
411 if (cachedValueSize > valueSize) {
412 ALOGV("GET: Cache MISS - valueSize not large enough (%lu) for entry %u, returning required"
413 "size (%zu)",
414 valueSize, entryHash, cachedValueSize);
415 return cachedValueSize;
416 }
417
418 // We have the file and have enough room to write it out, return the entry
419 ALOGV("GET: Cache HIT - cache contains entry: %u", entryHash);
420
421 // Look up the size of the file
422 size_t fileSize = entryStats.fileSize;
423 if (keySize > fileSize) {
424 ALOGW("keySize (%lu) is larger than entrySize (%zu). This is a hash collision or modified "
425 "file",
426 keySize, fileSize);
427 return 0;
428 }
429
430 std::string fullPath = mMultifileDirName + "/" + std::to_string(entryHash);
431
432 // Open the hashed filename path
433 uint8_t* cacheEntry = 0;
434
435 // Check hot cache
436 if (mHotCache.find(entryHash) != mHotCache.end()) {
437 ALOGV("GET: HotCache HIT for entry %u", entryHash);
438 cacheEntry = mHotCache[entryHash].entryBuffer;
439 } else {
440 ALOGV("GET: HotCache MISS for entry: %u", entryHash);
441
Cody Northropbe163732023-03-22 10:14:26 -0600442 // Wait for writes to complete if there is an outstanding write for this entry
443 bool wait = false;
444 {
445 // Synchronize access to deferred write status
446 std::lock_guard<std::mutex> lock(mDeferredWriteStatusMutex);
447 wait = mDeferredWrites.find(entryHash) != mDeferredWrites.end();
448 }
449
450 if (wait) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700451 ALOGV("GET: Waiting for write to complete for %u", entryHash);
452 waitForWorkComplete();
453 }
454
455 // Open the entry file
456 int fd = open(fullPath.c_str(), O_RDONLY);
457 if (fd == -1) {
458 ALOGE("Cache error - failed to open fullPath: %s, error: %s", fullPath.c_str(),
459 std::strerror(errno));
460 return 0;
461 }
462
463 // Memory map the file
464 cacheEntry =
465 reinterpret_cast<uint8_t*>(mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0));
Cody Northrop5f8117a2023-09-26 20:48:59 -0600466
467 // We can close the file now and the mmap will remain
468 close(fd);
469
Cody Northrop6cca6c22023-02-08 20:23:13 -0700470 if (cacheEntry == MAP_FAILED) {
471 ALOGE("Failed to mmap cacheEntry, error: %s", std::strerror(errno));
Cody Northrop6cca6c22023-02-08 20:23:13 -0700472 return 0;
473 }
474
475 ALOGV("GET: Adding %u to hot cache", entryHash);
476 if (!addToHotCache(entryHash, fd, cacheEntry, fileSize)) {
477 ALOGE("GET: Failed to add %u to hot cache", entryHash);
478 return 0;
479 }
480
481 cacheEntry = mHotCache[entryHash].entryBuffer;
482 }
483
484 // Ensure the header matches
485 MultifileHeader* header = reinterpret_cast<MultifileHeader*>(cacheEntry);
486 if (header->keySize != keySize || header->valueSize != valueSize) {
487 ALOGW("Mismatch on keySize(%ld vs. cached %ld) or valueSize(%ld vs. cached %ld) compared "
488 "to cache header values for fullPath: %s",
489 keySize, header->keySize, valueSize, header->valueSize, fullPath.c_str());
490 removeFromHotCache(entryHash);
491 return 0;
492 }
493
494 // Compare the incoming key with our stored version (the beginning of the entry)
495 uint8_t* cachedKey = cacheEntry + sizeof(MultifileHeader);
496 int compare = memcmp(cachedKey, key, keySize);
497 if (compare != 0) {
498 ALOGW("Cached key and new key do not match! This is a hash collision or modified file");
499 removeFromHotCache(entryHash);
500 return 0;
501 }
502
503 // Remaining entry following the key is the value
504 uint8_t* cachedValue = cacheEntry + (keySize + sizeof(MultifileHeader));
505 memcpy(value, cachedValue, cachedValueSize);
506
507 return cachedValueSize;
508}
509
510void MultifileBlobCache::finish() {
511 if (!mInitialized) {
512 return;
513 }
514
515 // Wait for all deferred writes to complete
516 ALOGV("FINISH: Waiting for work to complete.");
517 waitForWorkComplete();
518
519 // Close all entries in the hot cache
520 for (auto hotCacheIter = mHotCache.begin(); hotCacheIter != mHotCache.end();) {
521 uint32_t entryHash = hotCacheIter->first;
522 MultifileHotCache entry = hotCacheIter->second;
523
524 ALOGV("FINISH: Closing hot cache entry for %u", entryHash);
525 freeHotCacheEntry(entry);
526
527 mHotCache.erase(hotCacheIter++);
528 }
529}
530
Cody Northrop027f2422023-11-12 22:51:01 -0700531bool MultifileBlobCache::createStatus(const std::string& baseDir) {
532 // Populate the status struct
533 struct MultifileStatus status;
534 memset(&status, 0, sizeof(status));
535 status.magic = kMultifileMagic;
536 status.cacheVersion = mCacheVersion;
537
538 // Copy the buildId string in, up to our allocated space
539 strncpy(status.buildId, mBuildId.c_str(),
540 mBuildId.length() > PROP_VALUE_MAX ? PROP_VALUE_MAX : mBuildId.length());
541
542 // Finally update the crc, using cacheVersion and everything the follows
Jisun Lee88a1b762024-10-17 20:12:29 +0900543 status.crc = GenerateCRC32(
544 reinterpret_cast<uint8_t *>(&status) + offsetof(MultifileStatus, cacheVersion),
545 sizeof(status) - offsetof(MultifileStatus, cacheVersion));
Cody Northrop027f2422023-11-12 22:51:01 -0700546
547 // Create the status file
548 std::string cacheStatus = baseDir + "/" + kMultifileBlobCacheStatusFile;
549 int fd = open(cacheStatus.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
550 if (fd == -1) {
551 ALOGE("STATUS(CREATE): Unable to create status file: %s, error: %s", cacheStatus.c_str(),
552 std::strerror(errno));
553 return false;
554 }
555
556 // Write the buffer contents to disk
557 ssize_t result = write(fd, &status, sizeof(status));
558 close(fd);
559 if (result != sizeof(status)) {
560 ALOGE("STATUS(CREATE): Error writing cache status file: %s, error %s", cacheStatus.c_str(),
561 std::strerror(errno));
562 return false;
563 }
564
565 ALOGV("STATUS(CREATE): Created status file: %s", cacheStatus.c_str());
566 return true;
567}
568
569bool MultifileBlobCache::checkStatus(const std::string& baseDir) {
570 std::string cacheStatus = baseDir + "/" + kMultifileBlobCacheStatusFile;
571
572 // Does status exist
573 struct stat st;
574 if (stat(cacheStatus.c_str(), &st) != 0) {
575 ALOGV("STATUS(CHECK): Status file (%s) missing", cacheStatus.c_str());
576 return false;
577 }
578
579 // If the status entry is damaged or no good, remove it
580 if (st.st_size <= 0 || st.st_atime <= 0) {
581 ALOGE("STATUS(CHECK): Cache status has invalid stats!");
582 return false;
583 }
584
585 // Open the file so we can read its header
586 int fd = open(cacheStatus.c_str(), O_RDONLY);
587 if (fd == -1) {
588 ALOGE("STATUS(CHECK): Cache error - failed to open cacheStatus: %s, error: %s",
589 cacheStatus.c_str(), std::strerror(errno));
590 return false;
591 }
592
593 // Read in the status header
594 MultifileStatus status;
595 size_t result = read(fd, static_cast<void*>(&status), sizeof(MultifileStatus));
596 close(fd);
597 if (result != sizeof(MultifileStatus)) {
598 ALOGE("STATUS(CHECK): Error reading cache status (%s): %s", cacheStatus.c_str(),
599 std::strerror(errno));
600 return false;
601 }
602
603 // Verify header magic
604 if (status.magic != kMultifileMagic) {
605 ALOGE("STATUS(CHECK): Cache status has bad magic (%u)!", status.magic);
606 return false;
607 }
608
609 // Ensure we have a good CRC
Jisun Lee88a1b762024-10-17 20:12:29 +0900610 if (status.crc != GenerateCRC32(reinterpret_cast<uint8_t *>(&status) +
611 offsetof(MultifileStatus, cacheVersion),
612 sizeof(status) - offsetof(MultifileStatus, cacheVersion))) {
Cody Northrop027f2422023-11-12 22:51:01 -0700613 ALOGE("STATUS(CHECK): Cache status failed CRC check!");
614 return false;
615 }
616
617 // Check cacheVersion
618 if (status.cacheVersion != mCacheVersion) {
619 ALOGV("STATUS(CHECK): Cache version has changed! old(%u) new(%u)", status.cacheVersion,
620 mCacheVersion);
621 return false;
622 }
623
624 // Check buildId
625 if (strcmp(status.buildId, mBuildId.c_str()) != 0) {
626 ALOGV("STATUS(CHECK): BuildId has changed! old(%s) new(%s)", status.buildId,
627 mBuildId.c_str());
628 return false;
629 }
630
631 // All checks passed!
632 ALOGV("STATUS(CHECK): Status file is good! cacheVersion(%u), buildId(%s) file(%s)",
633 status.cacheVersion, status.buildId, cacheStatus.c_str());
634 return true;
635}
636
Cody Northrop6cca6c22023-02-08 20:23:13 -0700637void MultifileBlobCache::trackEntry(uint32_t entryHash, EGLsizeiANDROID valueSize, size_t fileSize,
638 time_t accessTime) {
639 mEntries.insert(entryHash);
640 mEntryStats[entryHash] = {valueSize, fileSize, accessTime};
641}
642
643bool MultifileBlobCache::contains(uint32_t hashEntry) const {
644 return mEntries.find(hashEntry) != mEntries.end();
645}
646
647MultifileEntryStats MultifileBlobCache::getEntryStats(uint32_t entryHash) {
648 return mEntryStats[entryHash];
649}
650
651void MultifileBlobCache::increaseTotalCacheSize(size_t fileSize) {
652 mTotalCacheSize += fileSize;
Cody Northropb5267032023-10-24 10:11:21 -0600653 mTotalCacheEntries++;
Cody Northrop6cca6c22023-02-08 20:23:13 -0700654}
655
656void MultifileBlobCache::decreaseTotalCacheSize(size_t fileSize) {
657 mTotalCacheSize -= fileSize;
Cody Northropb5267032023-10-24 10:11:21 -0600658 mTotalCacheEntries--;
Cody Northrop6cca6c22023-02-08 20:23:13 -0700659}
660
661bool MultifileBlobCache::addToHotCache(uint32_t newEntryHash, int newFd, uint8_t* newEntryBuffer,
662 size_t newEntrySize) {
663 ALOGV("HOTCACHE(ADD): Adding %u to hot cache", newEntryHash);
664
665 // Clear space if we need to
666 if ((mHotCacheSize + newEntrySize) > mHotCacheLimit) {
667 ALOGV("HOTCACHE(ADD): mHotCacheSize (%zu) + newEntrySize (%zu) is to big for "
668 "mHotCacheLimit "
669 "(%zu), freeing up space for %u",
670 mHotCacheSize, newEntrySize, mHotCacheLimit, newEntryHash);
671
672 // Wait for all the files to complete writing so our hot cache is accurate
Cody Northropbe163732023-03-22 10:14:26 -0600673 ALOGV("HOTCACHE(ADD): Waiting for work to complete for %u", newEntryHash);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700674 waitForWorkComplete();
675
676 // Free up old entries until under the limit
677 for (auto hotCacheIter = mHotCache.begin(); hotCacheIter != mHotCache.end();) {
678 uint32_t oldEntryHash = hotCacheIter->first;
679 MultifileHotCache oldEntry = hotCacheIter->second;
680
681 // Move our iterator before deleting the entry
682 hotCacheIter++;
683 if (!removeFromHotCache(oldEntryHash)) {
684 ALOGE("HOTCACHE(ADD): Unable to remove entry %u", oldEntryHash);
685 return false;
686 }
687
688 // Clear at least half the hot cache
689 if ((mHotCacheSize + newEntrySize) <= mHotCacheLimit / 2) {
690 ALOGV("HOTCACHE(ADD): Freed enough space for %zu", mHotCacheSize);
691 break;
692 }
693 }
694 }
695
696 // Track it
697 mHotCache[newEntryHash] = {newFd, newEntryBuffer, newEntrySize};
698 mHotCacheSize += newEntrySize;
699
700 ALOGV("HOTCACHE(ADD): New hot cache size: %zu", mHotCacheSize);
701
702 return true;
703}
704
705bool MultifileBlobCache::removeFromHotCache(uint32_t entryHash) {
706 if (mHotCache.find(entryHash) != mHotCache.end()) {
707 ALOGV("HOTCACHE(REMOVE): Removing %u from hot cache", entryHash);
708
709 // Wait for all the files to complete writing so our hot cache is accurate
Cody Northropbe163732023-03-22 10:14:26 -0600710 ALOGV("HOTCACHE(REMOVE): Waiting for work to complete for %u", entryHash);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700711 waitForWorkComplete();
712
713 ALOGV("HOTCACHE(REMOVE): Closing hot cache entry for %u", entryHash);
714 MultifileHotCache entry = mHotCache[entryHash];
715 freeHotCacheEntry(entry);
716
717 // Delete the entry from our tracking
718 mHotCacheSize -= entry.entrySize;
719 mHotCache.erase(entryHash);
720
721 return true;
722 }
723
724 return false;
725}
726
Cody Northropb5267032023-10-24 10:11:21 -0600727bool MultifileBlobCache::applyLRU(size_t cacheSizeLimit, size_t cacheEntryLimit) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700728 // Walk through our map of sorted last access times and remove files until under the limit
729 for (auto cacheEntryIter = mEntryStats.begin(); cacheEntryIter != mEntryStats.end();) {
730 uint32_t entryHash = cacheEntryIter->first;
731
732 ALOGV("LRU: Removing entryHash %u", entryHash);
733
734 // Track the overall size
735 MultifileEntryStats entryStats = getEntryStats(entryHash);
736 decreaseTotalCacheSize(entryStats.fileSize);
737
738 // Remove it from hot cache if present
739 removeFromHotCache(entryHash);
740
741 // Remove it from the system
742 std::string entryPath = mMultifileDirName + "/" + std::to_string(entryHash);
743 if (remove(entryPath.c_str()) != 0) {
744 ALOGE("LRU: Error removing %s: %s", entryPath.c_str(), std::strerror(errno));
745 return false;
746 }
747
748 // Increment the iterator before clearing the entry
749 cacheEntryIter++;
750
751 // Delete the entry from our tracking
752 size_t count = mEntryStats.erase(entryHash);
753 if (count != 1) {
754 ALOGE("LRU: Failed to remove entryHash (%u) from mEntryStats", entryHash);
755 return false;
756 }
757
758 // See if it has been reduced enough
759 size_t totalCacheSize = getTotalSize();
Cody Northropb5267032023-10-24 10:11:21 -0600760 size_t totalCacheEntries = getTotalEntries();
761 if (totalCacheSize <= cacheSizeLimit && totalCacheEntries <= cacheEntryLimit) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700762 // Success
Cody Northropb5267032023-10-24 10:11:21 -0600763 ALOGV("LRU: Reduced cache to size %zu entries %zu", totalCacheSize, totalCacheEntries);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700764 return true;
765 }
766 }
767
Cody Northropf2588a82023-03-27 23:03:49 -0600768 ALOGV("LRU: Cache is empty");
Cody Northrop6cca6c22023-02-08 20:23:13 -0700769 return false;
770}
771
Cody Northrop027f2422023-11-12 22:51:01 -0700772// Clear the cache by removing all entries and deleting the directory
773bool MultifileBlobCache::clearCache() {
774 DIR* dir;
775 struct dirent* entry;
776 dir = opendir(mMultifileDirName.c_str());
777 if (dir == nullptr) {
778 ALOGE("CLEAR: Unable to open multifile dir: %s", mMultifileDirName.c_str());
779 return false;
780 }
781
782 // Delete all entries and the status file
783 while ((entry = readdir(dir)) != nullptr) {
784 if (entry->d_name == "."s || entry->d_name == ".."s) {
785 continue;
786 }
787
788 std::string entryName = entry->d_name;
789 std::string fullPath = mMultifileDirName + "/" + entryName;
790 if (remove(fullPath.c_str()) != 0) {
791 ALOGE("CLEAR: Error removing %s: %s", fullPath.c_str(), std::strerror(errno));
792 return false;
793 }
794 }
795
796 // Delete the directory
797 if (remove(mMultifileDirName.c_str()) != 0) {
798 ALOGE("CLEAR: Error removing %s: %s", mMultifileDirName.c_str(), std::strerror(errno));
799 return false;
800 }
801
802 ALOGV("CLEAR: Cleared the multifile blobcache");
803 return true;
804}
805
Cody Northrop6cca6c22023-02-08 20:23:13 -0700806// When removing files, what fraction of the overall limit should be reached when removing files
807// A divisor of two will decrease the cache to 50%, four to 25% and so on
Cody Northropb5267032023-10-24 10:11:21 -0600808// We use the same limit to manage size and entry count
Cody Northrop6cca6c22023-02-08 20:23:13 -0700809constexpr uint32_t kCacheLimitDivisor = 2;
810
811// Calculate the cache size and remove old entries until under the limit
Cody Northropf2588a82023-03-27 23:03:49 -0600812void MultifileBlobCache::trimCache() {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700813 // Wait for all deferred writes to complete
Cody Northropbe163732023-03-22 10:14:26 -0600814 ALOGV("TRIM: Waiting for work to complete.");
Cody Northrop6cca6c22023-02-08 20:23:13 -0700815 waitForWorkComplete();
816
Cody Northropb5267032023-10-24 10:11:21 -0600817 ALOGV("TRIM: Reducing multifile cache size to %zu, entries %zu",
818 mMaxTotalSize / kCacheLimitDivisor, mMaxTotalEntries / kCacheLimitDivisor);
819 if (!applyLRU(mMaxTotalSize / kCacheLimitDivisor, mMaxTotalEntries / kCacheLimitDivisor)) {
Cody Northropf2588a82023-03-27 23:03:49 -0600820 ALOGE("Error when clearing multifile shader cache");
821 return;
Cody Northrop6cca6c22023-02-08 20:23:13 -0700822 }
823}
824
825// This function performs a task. It only knows how to write files to disk,
826// but it could be expanded if needed.
827void MultifileBlobCache::processTask(DeferredTask& task) {
828 switch (task.getTaskCommand()) {
829 case TaskCommand::Exit: {
830 ALOGV("DEFERRED: Shutting down");
831 return;
832 }
833 case TaskCommand::WriteToDisk: {
834 uint32_t entryHash = task.getEntryHash();
835 std::string& fullPath = task.getFullPath();
836 uint8_t* buffer = task.getBuffer();
837 size_t bufferSize = task.getBufferSize();
838
839 // Create the file or reset it if already present, read+write for user only
840 int fd = open(fullPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
841 if (fd == -1) {
842 ALOGE("Cache error in SET - failed to open fullPath: %s, error: %s",
843 fullPath.c_str(), std::strerror(errno));
844 return;
845 }
846
847 ALOGV("DEFERRED: Opened fd %i from %s", fd, fullPath.c_str());
848
Cody Northrop999db232023-02-27 17:02:50 -0700849 // Add CRC check to the header (always do this last!)
850 MultifileHeader* header = reinterpret_cast<MultifileHeader*>(buffer);
Jisun Lee88a1b762024-10-17 20:12:29 +0900851 header->crc = GenerateCRC32(buffer + sizeof(MultifileHeader),
852 bufferSize - sizeof(MultifileHeader));
Cody Northrop999db232023-02-27 17:02:50 -0700853
Cody Northrop6cca6c22023-02-08 20:23:13 -0700854 ssize_t result = write(fd, buffer, bufferSize);
855 if (result != bufferSize) {
856 ALOGE("Error writing fileSize to cache entry (%s): %s", fullPath.c_str(),
857 std::strerror(errno));
858 return;
859 }
860
861 ALOGV("DEFERRED: Completed write for: %s", fullPath.c_str());
862 close(fd);
863
864 // Erase the entry from mDeferredWrites
865 // Since there could be multiple outstanding writes for an entry, find the matching one
Cody Northropbe163732023-03-22 10:14:26 -0600866 {
867 // Synchronize access to deferred write status
868 std::lock_guard<std::mutex> lock(mDeferredWriteStatusMutex);
869 typedef std::multimap<uint32_t, uint8_t*>::iterator entryIter;
870 std::pair<entryIter, entryIter> iterPair = mDeferredWrites.equal_range(entryHash);
871 for (entryIter it = iterPair.first; it != iterPair.second; ++it) {
872 if (it->second == buffer) {
873 ALOGV("DEFERRED: Marking write complete for %u at %p", it->first,
874 it->second);
875 mDeferredWrites.erase(it);
876 break;
877 }
Cody Northrop6cca6c22023-02-08 20:23:13 -0700878 }
879 }
880
881 return;
882 }
883 default: {
884 ALOGE("DEFERRED: Unhandled task type");
885 return;
886 }
887 }
888}
889
890// This function will wait until tasks arrive, then execute them
891// If the exit command is submitted, the loop will terminate
892void MultifileBlobCache::processTasksImpl(bool* exitThread) {
893 while (true) {
894 std::unique_lock<std::mutex> lock(mWorkerMutex);
895 if (mTasks.empty()) {
896 ALOGV("WORKER: No tasks available, waiting");
897 mWorkerThreadIdle = true;
898 mWorkerIdleCondition.notify_all();
899 // Only wake if notified and command queue is not empty
900 mWorkAvailableCondition.wait(lock, [this] { return !mTasks.empty(); });
901 }
902
903 ALOGV("WORKER: Task available, waking up.");
904 mWorkerThreadIdle = false;
905 DeferredTask task = std::move(mTasks.front());
906 mTasks.pop();
907
908 if (task.getTaskCommand() == TaskCommand::Exit) {
909 ALOGV("WORKER: Exiting work loop.");
910 *exitThread = true;
911 mWorkerThreadIdle = true;
912 mWorkerIdleCondition.notify_one();
913 return;
914 }
915
916 lock.unlock();
917 processTask(task);
918 }
919}
920
921// Process tasks until the exit task is submitted
922void MultifileBlobCache::processTasks() {
923 while (true) {
924 bool exitThread = false;
925 processTasksImpl(&exitThread);
926 if (exitThread) {
927 break;
928 }
929 }
930}
931
932// Add a task to the queue to be processed by the worker thread
933void MultifileBlobCache::queueTask(DeferredTask&& task) {
934 std::lock_guard<std::mutex> queueLock(mWorkerMutex);
935 mTasks.emplace(std::move(task));
936 mWorkAvailableCondition.notify_one();
937}
938
939// Wait until all tasks have been completed
940void MultifileBlobCache::waitForWorkComplete() {
941 std::unique_lock<std::mutex> lock(mWorkerMutex);
942 mWorkerIdleCondition.wait(lock, [this] { return (mTasks.empty() && mWorkerThreadIdle); });
943}
944
Cody Northrop999db232023-02-27 17:02:50 -0700945}; // namespace android