blob: 607e2148e05bb23b1eafb3142d3de01f58188900 [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
21#include <dirent.h>
22#include <fcntl.h>
23#include <inttypes.h>
24#include <log/log.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <sys/mman.h>
28#include <sys/stat.h>
29#include <time.h>
30#include <unistd.h>
31#include <utime.h>
32
33#include <algorithm>
34#include <chrono>
35#include <limits>
36#include <locale>
37
38#include <utils/JenkinsHash.h>
39
40using namespace std::literals;
41
Cody Northrop999db232023-02-27 17:02:50 -070042constexpr uint32_t kMultifileMagic = 'MFB$';
43constexpr uint32_t kCrcPlaceholder = 0;
44
Cody Northrop6cca6c22023-02-08 20:23:13 -070045namespace {
46
Cody Northrop6cca6c22023-02-08 20:23:13 -070047// Helper function to close entries or free them
48void freeHotCacheEntry(android::MultifileHotCache& entry) {
49 if (entry.entryFd != -1) {
50 // If we have an fd, then this entry was added to hot cache via INIT or GET
51 // We need to unmap and close the entry
52 munmap(entry.entryBuffer, entry.entrySize);
53 close(entry.entryFd);
54 } else {
55 // Otherwise, this was added to hot cache during SET, so it was never mapped
56 // and fd was only on the deferred thread.
57 delete[] entry.entryBuffer;
58 }
59}
60
61} // namespace
62
63namespace android {
64
65MultifileBlobCache::MultifileBlobCache(size_t maxTotalSize, size_t maxHotCacheSize,
66 const std::string& baseDir)
67 : mInitialized(false),
68 mMaxTotalSize(maxTotalSize),
69 mTotalCacheSize(0),
70 mHotCacheLimit(maxHotCacheSize),
71 mHotCacheSize(0),
72 mWorkerThreadIdle(true) {
73 if (baseDir.empty()) {
74 ALOGV("INIT: no baseDir provided in MultifileBlobCache constructor, returning early.");
75 return;
76 }
77
78 // Establish the name of our multifile directory
79 mMultifileDirName = baseDir + ".multifile";
80
81 // Set a limit for max key and value, ensuring at least one entry can always fit in hot cache
82 mMaxKeySize = mHotCacheLimit / 4;
83 mMaxValueSize = mHotCacheLimit / 2;
84
85 ALOGV("INIT: Initializing multifile blobcache with maxKeySize=%zu and maxValueSize=%zu",
86 mMaxKeySize, mMaxValueSize);
87
88 // Initialize our cache with the contents of the directory
89 mTotalCacheSize = 0;
90
91 // Create the worker thread
92 mTaskThread = std::thread(&MultifileBlobCache::processTasks, this);
93
94 // See if the dir exists, and initialize using its contents
95 struct stat st;
96 if (stat(mMultifileDirName.c_str(), &st) == 0) {
97 // Read all the files and gather details, then preload their contents
98 DIR* dir;
99 struct dirent* entry;
100 if ((dir = opendir(mMultifileDirName.c_str())) != nullptr) {
101 while ((entry = readdir(dir)) != nullptr) {
102 if (entry->d_name == "."s || entry->d_name == ".."s) {
103 continue;
104 }
105
106 std::string entryName = entry->d_name;
107 std::string fullPath = mMultifileDirName + "/" + entryName;
108
109 // The filename is the same as the entryHash
110 uint32_t entryHash = static_cast<uint32_t>(strtoul(entry->d_name, nullptr, 10));
111
112 ALOGV("INIT: Checking entry %u", entryHash);
113
114 // Look up the details of the file
115 struct stat st;
116 if (stat(fullPath.c_str(), &st) != 0) {
117 ALOGE("Failed to stat %s", fullPath.c_str());
118 return;
119 }
120
Cody Northrop999db232023-02-27 17:02:50 -0700121 // If the cache entry is damaged or no good, remove it
122 if (st.st_size <= 0 || st.st_atime <= 0) {
123 ALOGE("INIT: Entry %u has invalid stats! Removing.", entryHash);
124 if (remove(fullPath.c_str()) != 0) {
125 ALOGE("Error removing %s: %s", fullPath.c_str(), std::strerror(errno));
126 }
127 continue;
128 }
129
Cody Northrop6cca6c22023-02-08 20:23:13 -0700130 // Open the file so we can read its header
131 int fd = open(fullPath.c_str(), O_RDONLY);
132 if (fd == -1) {
133 ALOGE("Cache error - failed to open fullPath: %s, error: %s", fullPath.c_str(),
134 std::strerror(errno));
135 return;
136 }
137
Cody Northrop999db232023-02-27 17:02:50 -0700138 // Read the beginning of the file to get header
139 MultifileHeader header;
140 size_t result = read(fd, static_cast<void*>(&header), sizeof(MultifileHeader));
141 if (result != sizeof(MultifileHeader)) {
142 ALOGE("Error reading MultifileHeader from cache entry (%s): %s",
143 fullPath.c_str(), std::strerror(errno));
144 return;
145 }
146
147 // Verify header magic
148 if (header.magic != kMultifileMagic) {
149 ALOGE("INIT: Entry %u has bad magic (%u)! Removing.", entryHash, header.magic);
150 if (remove(fullPath.c_str()) != 0) {
151 ALOGE("Error removing %s: %s", fullPath.c_str(), std::strerror(errno));
152 }
153 continue;
154 }
155
156 // Note: Converting from off_t (signed) to size_t (unsigned)
157 size_t fileSize = static_cast<size_t>(st.st_size);
158
159 // Memory map the file
160 uint8_t* mappedEntry = reinterpret_cast<uint8_t*>(
161 mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0));
162 if (mappedEntry == MAP_FAILED) {
163 ALOGE("Failed to mmap cacheEntry, error: %s", std::strerror(errno));
164 return;
165 }
166
167 // Ensure we have a good CRC
168 if (header.crc !=
169 crc32c(mappedEntry + sizeof(MultifileHeader),
170 fileSize - sizeof(MultifileHeader))) {
171 ALOGE("INIT: Entry %u failed CRC check! Removing.", entryHash);
172 if (remove(fullPath.c_str()) != 0) {
173 ALOGE("Error removing %s: %s", fullPath.c_str(), std::strerror(errno));
174 }
175 continue;
176 }
Cody Northrop6cca6c22023-02-08 20:23:13 -0700177
178 // If the cache entry is damaged or no good, remove it
Cody Northrop999db232023-02-27 17:02:50 -0700179 if (header.keySize <= 0 || header.valueSize <= 0) {
180 ALOGE("INIT: Entry %u has a bad header keySize (%lu) or valueSize (%lu), "
181 "removing.",
182 entryHash, header.keySize, header.valueSize);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700183 if (remove(fullPath.c_str()) != 0) {
184 ALOGE("Error removing %s: %s", fullPath.c_str(), std::strerror(errno));
185 }
186 continue;
187 }
188
189 ALOGV("INIT: Entry %u is good, tracking it now.", entryHash);
190
Cody Northrop6cca6c22023-02-08 20:23:13 -0700191 // Track details for rapid lookup later
Cody Northrop999db232023-02-27 17:02:50 -0700192 trackEntry(entryHash, header.valueSize, fileSize, st.st_atime);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700193
194 // Track the total size
195 increaseTotalCacheSize(fileSize);
196
197 // Preload the entry for fast retrieval
198 if ((mHotCacheSize + fileSize) < mHotCacheLimit) {
Cody Northrop6cca6c22023-02-08 20:23:13 -0700199 ALOGV("INIT: Populating hot cache with fd = %i, cacheEntry = %p for "
200 "entryHash %u",
201 fd, mappedEntry, entryHash);
202
203 // Track the details of the preload so they can be retrieved later
204 if (!addToHotCache(entryHash, fd, mappedEntry, fileSize)) {
205 ALOGE("INIT Failed to add %u to hot cache", entryHash);
206 munmap(mappedEntry, fileSize);
207 close(fd);
208 return;
209 }
210 } else {
Cody Northrop999db232023-02-27 17:02:50 -0700211 // If we're not keeping it in hot cache, unmap it now
212 munmap(mappedEntry, fileSize);
Cody Northrop6cca6c22023-02-08 20:23:13 -0700213 close(fd);
214 }
215 }
216 closedir(dir);
217 } else {
218 ALOGE("Unable to open filename: %s", mMultifileDirName.c_str());
219 }
220 } else {
221 // If the multifile directory does not exist, create it and start from scratch
222 if (mkdir(mMultifileDirName.c_str(), 0755) != 0 && (errno != EEXIST)) {
223 ALOGE("Unable to create directory (%s), errno (%i)", mMultifileDirName.c_str(), errno);
224 }
225 }
226
227 mInitialized = true;
228}
229
230MultifileBlobCache::~MultifileBlobCache() {
231 if (!mInitialized) {
232 return;
233 }
234
235 // Inform the worker thread we're done
236 ALOGV("DESCTRUCTOR: Shutting down worker thread");
237 DeferredTask task(TaskCommand::Exit);
238 queueTask(std::move(task));
239
240 // Wait for it to complete
241 ALOGV("DESCTRUCTOR: Waiting for worker thread to complete");
242 waitForWorkComplete();
243 if (mTaskThread.joinable()) {
244 mTaskThread.join();
245 }
246}
247
248// Set will add the entry to hot cache and start a deferred process to write it to disk
249void MultifileBlobCache::set(const void* key, EGLsizeiANDROID keySize, const void* value,
250 EGLsizeiANDROID valueSize) {
251 if (!mInitialized) {
252 return;
253 }
254
255 // Ensure key and value are under their limits
256 if (keySize > mMaxKeySize || valueSize > mMaxValueSize) {
257 ALOGV("SET: keySize (%lu vs %zu) or valueSize (%lu vs %zu) too large", keySize, mMaxKeySize,
258 valueSize, mMaxValueSize);
259 return;
260 }
261
262 // Generate a hash of the key and use it to track this entry
263 uint32_t entryHash = android::JenkinsHashMixBytes(0, static_cast<const uint8_t*>(key), keySize);
264
265 size_t fileSize = sizeof(MultifileHeader) + keySize + valueSize;
266
267 // If we're going to be over the cache limit, kick off a trim to clear space
268 if (getTotalSize() + fileSize > mMaxTotalSize) {
269 ALOGV("SET: Cache is full, calling trimCache to clear space");
270 trimCache(mMaxTotalSize);
271 }
272
273 ALOGV("SET: Add %u to cache", entryHash);
274
275 uint8_t* buffer = new uint8_t[fileSize];
276
Cody Northrop999db232023-02-27 17:02:50 -0700277 // Write placeholders for magic and CRC until deferred thread complets the write
278 android::MultifileHeader header = {kMultifileMagic, kCrcPlaceholder, keySize, valueSize};
Cody Northrop6cca6c22023-02-08 20:23:13 -0700279 memcpy(static_cast<void*>(buffer), static_cast<const void*>(&header),
280 sizeof(android::MultifileHeader));
Cody Northrop999db232023-02-27 17:02:50 -0700281
282 // Write the key and value after the header
Cody Northrop6cca6c22023-02-08 20:23:13 -0700283 memcpy(static_cast<void*>(buffer + sizeof(MultifileHeader)), static_cast<const void*>(key),
284 keySize);
285 memcpy(static_cast<void*>(buffer + sizeof(MultifileHeader) + keySize),
286 static_cast<const void*>(value), valueSize);
287
288 std::string fullPath = mMultifileDirName + "/" + std::to_string(entryHash);
289
290 // Track the size and access time for quick recall
291 trackEntry(entryHash, valueSize, fileSize, time(0));
292
293 // Update the overall cache size
294 increaseTotalCacheSize(fileSize);
295
296 // Keep the entry in hot cache for quick retrieval
297 ALOGV("SET: Adding %u to hot cache.", entryHash);
298
299 // Sending -1 as the fd indicates we don't have an fd for this
300 if (!addToHotCache(entryHash, -1, buffer, fileSize)) {
301 ALOGE("GET: Failed to add %u to hot cache", entryHash);
302 return;
303 }
304
305 // Track that we're creating a pending write for this entry
306 // Include the buffer to handle the case when multiple writes are pending for an entry
307 mDeferredWrites.insert(std::make_pair(entryHash, buffer));
308
309 // Create deferred task to write to storage
310 ALOGV("SET: Adding task to queue.");
311 DeferredTask task(TaskCommand::WriteToDisk);
312 task.initWriteToDisk(entryHash, fullPath, buffer, fileSize);
313 queueTask(std::move(task));
314}
315
316// Get will check the hot cache, then load it from disk if needed
317EGLsizeiANDROID MultifileBlobCache::get(const void* key, EGLsizeiANDROID keySize, void* value,
318 EGLsizeiANDROID valueSize) {
319 if (!mInitialized) {
320 return 0;
321 }
322
323 // Ensure key and value are under their limits
324 if (keySize > mMaxKeySize || valueSize > mMaxValueSize) {
325 ALOGV("GET: keySize (%lu vs %zu) or valueSize (%lu vs %zu) too large", keySize, mMaxKeySize,
326 valueSize, mMaxValueSize);
327 return 0;
328 }
329
330 // Generate a hash of the key and use it to track this entry
331 uint32_t entryHash = android::JenkinsHashMixBytes(0, static_cast<const uint8_t*>(key), keySize);
332
333 // See if we have this file
334 if (!contains(entryHash)) {
335 ALOGV("GET: Cache MISS - cache does not contain entry: %u", entryHash);
336 return 0;
337 }
338
339 // Look up the data for this entry
340 MultifileEntryStats entryStats = getEntryStats(entryHash);
341
342 size_t cachedValueSize = entryStats.valueSize;
343 if (cachedValueSize > valueSize) {
344 ALOGV("GET: Cache MISS - valueSize not large enough (%lu) for entry %u, returning required"
345 "size (%zu)",
346 valueSize, entryHash, cachedValueSize);
347 return cachedValueSize;
348 }
349
350 // We have the file and have enough room to write it out, return the entry
351 ALOGV("GET: Cache HIT - cache contains entry: %u", entryHash);
352
353 // Look up the size of the file
354 size_t fileSize = entryStats.fileSize;
355 if (keySize > fileSize) {
356 ALOGW("keySize (%lu) is larger than entrySize (%zu). This is a hash collision or modified "
357 "file",
358 keySize, fileSize);
359 return 0;
360 }
361
362 std::string fullPath = mMultifileDirName + "/" + std::to_string(entryHash);
363
364 // Open the hashed filename path
365 uint8_t* cacheEntry = 0;
366
367 // Check hot cache
368 if (mHotCache.find(entryHash) != mHotCache.end()) {
369 ALOGV("GET: HotCache HIT for entry %u", entryHash);
370 cacheEntry = mHotCache[entryHash].entryBuffer;
371 } else {
372 ALOGV("GET: HotCache MISS for entry: %u", entryHash);
373
374 if (mDeferredWrites.find(entryHash) != mDeferredWrites.end()) {
375 // Wait for writes to complete if there is an outstanding write for this entry
376 ALOGV("GET: Waiting for write to complete for %u", entryHash);
377 waitForWorkComplete();
378 }
379
380 // Open the entry file
381 int fd = open(fullPath.c_str(), O_RDONLY);
382 if (fd == -1) {
383 ALOGE("Cache error - failed to open fullPath: %s, error: %s", fullPath.c_str(),
384 std::strerror(errno));
385 return 0;
386 }
387
388 // Memory map the file
389 cacheEntry =
390 reinterpret_cast<uint8_t*>(mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0));
391 if (cacheEntry == MAP_FAILED) {
392 ALOGE("Failed to mmap cacheEntry, error: %s", std::strerror(errno));
393 close(fd);
394 return 0;
395 }
396
397 ALOGV("GET: Adding %u to hot cache", entryHash);
398 if (!addToHotCache(entryHash, fd, cacheEntry, fileSize)) {
399 ALOGE("GET: Failed to add %u to hot cache", entryHash);
400 return 0;
401 }
402
403 cacheEntry = mHotCache[entryHash].entryBuffer;
404 }
405
406 // Ensure the header matches
407 MultifileHeader* header = reinterpret_cast<MultifileHeader*>(cacheEntry);
408 if (header->keySize != keySize || header->valueSize != valueSize) {
409 ALOGW("Mismatch on keySize(%ld vs. cached %ld) or valueSize(%ld vs. cached %ld) compared "
410 "to cache header values for fullPath: %s",
411 keySize, header->keySize, valueSize, header->valueSize, fullPath.c_str());
412 removeFromHotCache(entryHash);
413 return 0;
414 }
415
416 // Compare the incoming key with our stored version (the beginning of the entry)
417 uint8_t* cachedKey = cacheEntry + sizeof(MultifileHeader);
418 int compare = memcmp(cachedKey, key, keySize);
419 if (compare != 0) {
420 ALOGW("Cached key and new key do not match! This is a hash collision or modified file");
421 removeFromHotCache(entryHash);
422 return 0;
423 }
424
425 // Remaining entry following the key is the value
426 uint8_t* cachedValue = cacheEntry + (keySize + sizeof(MultifileHeader));
427 memcpy(value, cachedValue, cachedValueSize);
428
429 return cachedValueSize;
430}
431
432void MultifileBlobCache::finish() {
433 if (!mInitialized) {
434 return;
435 }
436
437 // Wait for all deferred writes to complete
438 ALOGV("FINISH: Waiting for work to complete.");
439 waitForWorkComplete();
440
441 // Close all entries in the hot cache
442 for (auto hotCacheIter = mHotCache.begin(); hotCacheIter != mHotCache.end();) {
443 uint32_t entryHash = hotCacheIter->first;
444 MultifileHotCache entry = hotCacheIter->second;
445
446 ALOGV("FINISH: Closing hot cache entry for %u", entryHash);
447 freeHotCacheEntry(entry);
448
449 mHotCache.erase(hotCacheIter++);
450 }
451}
452
453void MultifileBlobCache::trackEntry(uint32_t entryHash, EGLsizeiANDROID valueSize, size_t fileSize,
454 time_t accessTime) {
455 mEntries.insert(entryHash);
456 mEntryStats[entryHash] = {valueSize, fileSize, accessTime};
457}
458
459bool MultifileBlobCache::contains(uint32_t hashEntry) const {
460 return mEntries.find(hashEntry) != mEntries.end();
461}
462
463MultifileEntryStats MultifileBlobCache::getEntryStats(uint32_t entryHash) {
464 return mEntryStats[entryHash];
465}
466
467void MultifileBlobCache::increaseTotalCacheSize(size_t fileSize) {
468 mTotalCacheSize += fileSize;
469}
470
471void MultifileBlobCache::decreaseTotalCacheSize(size_t fileSize) {
472 mTotalCacheSize -= fileSize;
473}
474
475bool MultifileBlobCache::addToHotCache(uint32_t newEntryHash, int newFd, uint8_t* newEntryBuffer,
476 size_t newEntrySize) {
477 ALOGV("HOTCACHE(ADD): Adding %u to hot cache", newEntryHash);
478
479 // Clear space if we need to
480 if ((mHotCacheSize + newEntrySize) > mHotCacheLimit) {
481 ALOGV("HOTCACHE(ADD): mHotCacheSize (%zu) + newEntrySize (%zu) is to big for "
482 "mHotCacheLimit "
483 "(%zu), freeing up space for %u",
484 mHotCacheSize, newEntrySize, mHotCacheLimit, newEntryHash);
485
486 // Wait for all the files to complete writing so our hot cache is accurate
487 waitForWorkComplete();
488
489 // Free up old entries until under the limit
490 for (auto hotCacheIter = mHotCache.begin(); hotCacheIter != mHotCache.end();) {
491 uint32_t oldEntryHash = hotCacheIter->first;
492 MultifileHotCache oldEntry = hotCacheIter->second;
493
494 // Move our iterator before deleting the entry
495 hotCacheIter++;
496 if (!removeFromHotCache(oldEntryHash)) {
497 ALOGE("HOTCACHE(ADD): Unable to remove entry %u", oldEntryHash);
498 return false;
499 }
500
501 // Clear at least half the hot cache
502 if ((mHotCacheSize + newEntrySize) <= mHotCacheLimit / 2) {
503 ALOGV("HOTCACHE(ADD): Freed enough space for %zu", mHotCacheSize);
504 break;
505 }
506 }
507 }
508
509 // Track it
510 mHotCache[newEntryHash] = {newFd, newEntryBuffer, newEntrySize};
511 mHotCacheSize += newEntrySize;
512
513 ALOGV("HOTCACHE(ADD): New hot cache size: %zu", mHotCacheSize);
514
515 return true;
516}
517
518bool MultifileBlobCache::removeFromHotCache(uint32_t entryHash) {
519 if (mHotCache.find(entryHash) != mHotCache.end()) {
520 ALOGV("HOTCACHE(REMOVE): Removing %u from hot cache", entryHash);
521
522 // Wait for all the files to complete writing so our hot cache is accurate
523 waitForWorkComplete();
524
525 ALOGV("HOTCACHE(REMOVE): Closing hot cache entry for %u", entryHash);
526 MultifileHotCache entry = mHotCache[entryHash];
527 freeHotCacheEntry(entry);
528
529 // Delete the entry from our tracking
530 mHotCacheSize -= entry.entrySize;
531 mHotCache.erase(entryHash);
532
533 return true;
534 }
535
536 return false;
537}
538
539bool MultifileBlobCache::applyLRU(size_t cacheLimit) {
540 // Walk through our map of sorted last access times and remove files until under the limit
541 for (auto cacheEntryIter = mEntryStats.begin(); cacheEntryIter != mEntryStats.end();) {
542 uint32_t entryHash = cacheEntryIter->first;
543
544 ALOGV("LRU: Removing entryHash %u", entryHash);
545
546 // Track the overall size
547 MultifileEntryStats entryStats = getEntryStats(entryHash);
548 decreaseTotalCacheSize(entryStats.fileSize);
549
550 // Remove it from hot cache if present
551 removeFromHotCache(entryHash);
552
553 // Remove it from the system
554 std::string entryPath = mMultifileDirName + "/" + std::to_string(entryHash);
555 if (remove(entryPath.c_str()) != 0) {
556 ALOGE("LRU: Error removing %s: %s", entryPath.c_str(), std::strerror(errno));
557 return false;
558 }
559
560 // Increment the iterator before clearing the entry
561 cacheEntryIter++;
562
563 // Delete the entry from our tracking
564 size_t count = mEntryStats.erase(entryHash);
565 if (count != 1) {
566 ALOGE("LRU: Failed to remove entryHash (%u) from mEntryStats", entryHash);
567 return false;
568 }
569
570 // See if it has been reduced enough
571 size_t totalCacheSize = getTotalSize();
572 if (totalCacheSize <= cacheLimit) {
573 // Success
574 ALOGV("LRU: Reduced cache to %zu", totalCacheSize);
575 return true;
576 }
577 }
578
579 ALOGV("LRU: Cache is emptry");
580 return false;
581}
582
583// When removing files, what fraction of the overall limit should be reached when removing files
584// A divisor of two will decrease the cache to 50%, four to 25% and so on
585constexpr uint32_t kCacheLimitDivisor = 2;
586
587// Calculate the cache size and remove old entries until under the limit
588void MultifileBlobCache::trimCache(size_t cacheByteLimit) {
589 // Start with the value provided by egl_cache
590 size_t limit = cacheByteLimit;
591
592 // Wait for all deferred writes to complete
593 waitForWorkComplete();
594
595 size_t size = getTotalSize();
596
597 // If size is larger than the threshold, remove files using LRU
598 if (size > limit) {
599 ALOGV("TRIM: Multifile cache size is larger than %zu, removing old entries",
600 cacheByteLimit);
601 if (!applyLRU(limit / kCacheLimitDivisor)) {
602 ALOGE("Error when clearing multifile shader cache");
603 return;
604 }
605 }
606}
607
608// This function performs a task. It only knows how to write files to disk,
609// but it could be expanded if needed.
610void MultifileBlobCache::processTask(DeferredTask& task) {
611 switch (task.getTaskCommand()) {
612 case TaskCommand::Exit: {
613 ALOGV("DEFERRED: Shutting down");
614 return;
615 }
616 case TaskCommand::WriteToDisk: {
617 uint32_t entryHash = task.getEntryHash();
618 std::string& fullPath = task.getFullPath();
619 uint8_t* buffer = task.getBuffer();
620 size_t bufferSize = task.getBufferSize();
621
622 // Create the file or reset it if already present, read+write for user only
623 int fd = open(fullPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
624 if (fd == -1) {
625 ALOGE("Cache error in SET - failed to open fullPath: %s, error: %s",
626 fullPath.c_str(), std::strerror(errno));
627 return;
628 }
629
630 ALOGV("DEFERRED: Opened fd %i from %s", fd, fullPath.c_str());
631
Cody Northrop999db232023-02-27 17:02:50 -0700632 // Add CRC check to the header (always do this last!)
633 MultifileHeader* header = reinterpret_cast<MultifileHeader*>(buffer);
634 header->crc =
635 crc32c(buffer + sizeof(MultifileHeader), bufferSize - sizeof(MultifileHeader));
636
Cody Northrop6cca6c22023-02-08 20:23:13 -0700637 ssize_t result = write(fd, buffer, bufferSize);
638 if (result != bufferSize) {
639 ALOGE("Error writing fileSize to cache entry (%s): %s", fullPath.c_str(),
640 std::strerror(errno));
641 return;
642 }
643
644 ALOGV("DEFERRED: Completed write for: %s", fullPath.c_str());
645 close(fd);
646
647 // Erase the entry from mDeferredWrites
648 // Since there could be multiple outstanding writes for an entry, find the matching one
649 typedef std::multimap<uint32_t, uint8_t*>::iterator entryIter;
650 std::pair<entryIter, entryIter> iterPair = mDeferredWrites.equal_range(entryHash);
651 for (entryIter it = iterPair.first; it != iterPair.second; ++it) {
652 if (it->second == buffer) {
653 ALOGV("DEFERRED: Marking write complete for %u at %p", it->first, it->second);
654 mDeferredWrites.erase(it);
655 break;
656 }
657 }
658
659 return;
660 }
661 default: {
662 ALOGE("DEFERRED: Unhandled task type");
663 return;
664 }
665 }
666}
667
668// This function will wait until tasks arrive, then execute them
669// If the exit command is submitted, the loop will terminate
670void MultifileBlobCache::processTasksImpl(bool* exitThread) {
671 while (true) {
672 std::unique_lock<std::mutex> lock(mWorkerMutex);
673 if (mTasks.empty()) {
674 ALOGV("WORKER: No tasks available, waiting");
675 mWorkerThreadIdle = true;
676 mWorkerIdleCondition.notify_all();
677 // Only wake if notified and command queue is not empty
678 mWorkAvailableCondition.wait(lock, [this] { return !mTasks.empty(); });
679 }
680
681 ALOGV("WORKER: Task available, waking up.");
682 mWorkerThreadIdle = false;
683 DeferredTask task = std::move(mTasks.front());
684 mTasks.pop();
685
686 if (task.getTaskCommand() == TaskCommand::Exit) {
687 ALOGV("WORKER: Exiting work loop.");
688 *exitThread = true;
689 mWorkerThreadIdle = true;
690 mWorkerIdleCondition.notify_one();
691 return;
692 }
693
694 lock.unlock();
695 processTask(task);
696 }
697}
698
699// Process tasks until the exit task is submitted
700void MultifileBlobCache::processTasks() {
701 while (true) {
702 bool exitThread = false;
703 processTasksImpl(&exitThread);
704 if (exitThread) {
705 break;
706 }
707 }
708}
709
710// Add a task to the queue to be processed by the worker thread
711void MultifileBlobCache::queueTask(DeferredTask&& task) {
712 std::lock_guard<std::mutex> queueLock(mWorkerMutex);
713 mTasks.emplace(std::move(task));
714 mWorkAvailableCondition.notify_one();
715}
716
717// Wait until all tasks have been completed
718void MultifileBlobCache::waitForWorkComplete() {
719 std::unique_lock<std::mutex> lock(mWorkerMutex);
720 mWorkerIdleCondition.wait(lock, [this] { return (mTasks.empty() && mWorkerThreadIdle); });
721}
722
Cody Northrop999db232023-02-27 17:02:50 -0700723}; // namespace android