blob: 126995b8cc2b15b8b4bcc2adf5c4df23c844513e [file] [log] [blame]
Jamie Gennis1a209932011-04-28 16:19:45 -07001/*
2 ** Copyright 2011, 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_TAG "BlobCache"
18//#define LOG_NDEBUG 0
19
Mark Salyzyn387c5612014-04-17 08:32:11 -070020#include <inttypes.h>
Jamie Gennis1a209932011-04-28 16:19:45 -070021#include <stdlib.h>
22#include <string.h>
23
24#include <utils/BlobCache.h>
Jamie Gennis7451bb42011-05-12 17:39:03 -070025#include <utils/Errors.h>
Jamie Gennis1a209932011-04-28 16:19:45 -070026#include <utils/Log.h>
27
Michael Lentine60788052015-05-18 13:04:01 -070028#include <cutils/properties.h>
29
Jamie Gennis1a209932011-04-28 16:19:45 -070030namespace android {
31
Jamie Gennis7451bb42011-05-12 17:39:03 -070032// BlobCache::Header::mMagicNumber value
Mark Salyzyn5bed8032014-04-30 11:10:46 -070033static const uint32_t blobCacheMagic = ('_' << 24) + ('B' << 16) + ('b' << 8) + '$';
Jamie Gennis7451bb42011-05-12 17:39:03 -070034
35// BlobCache::Header::mBlobCacheVersion value
Michael Lentine60788052015-05-18 13:04:01 -070036static const uint32_t blobCacheVersion = 3;
Jamie Gennis7451bb42011-05-12 17:39:03 -070037
38// BlobCache::Header::mDeviceVersion value
39static const uint32_t blobCacheDeviceVersion = 1;
40
Jamie Gennis1a209932011-04-28 16:19:45 -070041BlobCache::BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize):
42 mMaxKeySize(maxKeySize),
43 mMaxValueSize(maxValueSize),
44 mMaxTotalSize(maxTotalSize),
45 mTotalSize(0) {
46 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Kenny Root967ad862011-06-15 20:41:15 -070047#ifdef _WIN32
48 srand(now);
49#else
Jamie Gennis1a209932011-04-28 16:19:45 -070050 mRandState[0] = (now >> 0) & 0xFFFF;
51 mRandState[1] = (now >> 16) & 0xFFFF;
52 mRandState[2] = (now >> 32) & 0xFFFF;
Kenny Root967ad862011-06-15 20:41:15 -070053#endif
Mark Salyzyn5bed8032014-04-30 11:10:46 -070054 ALOGV("initializing random seed using %lld", (unsigned long long)now);
Jamie Gennis1a209932011-04-28 16:19:45 -070055}
56
57void BlobCache::set(const void* key, size_t keySize, const void* value,
58 size_t valueSize) {
59 if (mMaxKeySize < keySize) {
Mark Salyzyn387c5612014-04-17 08:32:11 -070060 ALOGV("set: not caching because the key is too large: %zu (limit: %zu)",
Jamie Gennis1a209932011-04-28 16:19:45 -070061 keySize, mMaxKeySize);
62 return;
63 }
64 if (mMaxValueSize < valueSize) {
Mark Salyzyn387c5612014-04-17 08:32:11 -070065 ALOGV("set: not caching because the value is too large: %zu (limit: %zu)",
Jamie Gennis1a209932011-04-28 16:19:45 -070066 valueSize, mMaxValueSize);
67 return;
68 }
69 if (mMaxTotalSize < keySize + valueSize) {
Steve Blockb37fbe92011-10-20 11:56:00 +010070 ALOGV("set: not caching because the combined key/value size is too "
Mark Salyzyn387c5612014-04-17 08:32:11 -070071 "large: %zu (limit: %zu)", keySize + valueSize, mMaxTotalSize);
Jamie Gennis1a209932011-04-28 16:19:45 -070072 return;
73 }
74 if (keySize == 0) {
Steve Block61d341b2012-01-05 23:22:43 +000075 ALOGW("set: not caching because keySize is 0");
Jamie Gennis1a209932011-04-28 16:19:45 -070076 return;
77 }
78 if (valueSize <= 0) {
Steve Block61d341b2012-01-05 23:22:43 +000079 ALOGW("set: not caching because valueSize is 0");
Jamie Gennis1a209932011-04-28 16:19:45 -070080 return;
81 }
82
Jamie Gennis1a209932011-04-28 16:19:45 -070083 sp<Blob> dummyKey(new Blob(key, keySize, false));
84 CacheEntry dummyEntry(dummyKey, NULL);
85
86 while (true) {
Jamie Gennis1a209932011-04-28 16:19:45 -070087 ssize_t index = mCacheEntries.indexOf(dummyEntry);
88 if (index < 0) {
89 // Create a new cache entry.
90 sp<Blob> keyBlob(new Blob(key, keySize, true));
91 sp<Blob> valueBlob(new Blob(value, valueSize, true));
92 size_t newTotalSize = mTotalSize + keySize + valueSize;
93 if (mMaxTotalSize < newTotalSize) {
94 if (isCleanable()) {
95 // Clean the cache and try again.
96 clean();
97 continue;
98 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +010099 ALOGV("set: not caching new key/value pair because the "
Mark Salyzyn387c5612014-04-17 08:32:11 -0700100 "total cache size limit would be exceeded: %zu "
101 "(limit: %zu)",
Jamie Gennis1a209932011-04-28 16:19:45 -0700102 keySize + valueSize, mMaxTotalSize);
103 break;
104 }
105 }
106 mCacheEntries.add(CacheEntry(keyBlob, valueBlob));
107 mTotalSize = newTotalSize;
Mark Salyzyn387c5612014-04-17 08:32:11 -0700108 ALOGV("set: created new cache entry with %zu byte key and %zu byte value",
Jamie Gennis1a209932011-04-28 16:19:45 -0700109 keySize, valueSize);
110 } else {
111 // Update the existing cache entry.
112 sp<Blob> valueBlob(new Blob(value, valueSize, true));
113 sp<Blob> oldValueBlob(mCacheEntries[index].getValue());
114 size_t newTotalSize = mTotalSize + valueSize - oldValueBlob->getSize();
115 if (mMaxTotalSize < newTotalSize) {
116 if (isCleanable()) {
117 // Clean the cache and try again.
118 clean();
119 continue;
120 } else {
Steve Blockb37fbe92011-10-20 11:56:00 +0100121 ALOGV("set: not caching new value because the total cache "
Mark Salyzyn387c5612014-04-17 08:32:11 -0700122 "size limit would be exceeded: %zu (limit: %zu)",
Jamie Gennis1a209932011-04-28 16:19:45 -0700123 keySize + valueSize, mMaxTotalSize);
124 break;
125 }
126 }
127 mCacheEntries.editItemAt(index).setValue(valueBlob);
128 mTotalSize = newTotalSize;
Mark Salyzyn387c5612014-04-17 08:32:11 -0700129 ALOGV("set: updated existing cache entry with %zu byte key and %zu byte "
Jamie Gennis1a209932011-04-28 16:19:45 -0700130 "value", keySize, valueSize);
131 }
132 break;
133 }
134}
135
136size_t BlobCache::get(const void* key, size_t keySize, void* value,
137 size_t valueSize) {
138 if (mMaxKeySize < keySize) {
Mark Salyzyn387c5612014-04-17 08:32:11 -0700139 ALOGV("get: not searching because the key is too large: %zu (limit %zu)",
Jamie Gennis1a209932011-04-28 16:19:45 -0700140 keySize, mMaxKeySize);
141 return 0;
142 }
Jamie Gennis1a209932011-04-28 16:19:45 -0700143 sp<Blob> dummyKey(new Blob(key, keySize, false));
144 CacheEntry dummyEntry(dummyKey, NULL);
145 ssize_t index = mCacheEntries.indexOf(dummyEntry);
146 if (index < 0) {
Mark Salyzyn387c5612014-04-17 08:32:11 -0700147 ALOGV("get: no cache entry found for key of size %zu", keySize);
Jamie Gennis1a209932011-04-28 16:19:45 -0700148 return 0;
149 }
150
151 // The key was found. Return the value if the caller's buffer is large
152 // enough.
153 sp<Blob> valueBlob(mCacheEntries[index].getValue());
154 size_t valueBlobSize = valueBlob->getSize();
155 if (valueBlobSize <= valueSize) {
Mark Salyzyn387c5612014-04-17 08:32:11 -0700156 ALOGV("get: copying %zu bytes to caller's buffer", valueBlobSize);
Jamie Gennis1a209932011-04-28 16:19:45 -0700157 memcpy(value, valueBlob->getData(), valueBlobSize);
158 } else {
Mark Salyzyn387c5612014-04-17 08:32:11 -0700159 ALOGV("get: caller's buffer is too small for value: %zu (needs %zu)",
Jamie Gennis1a209932011-04-28 16:19:45 -0700160 valueSize, valueBlobSize);
161 }
162 return valueBlobSize;
163}
164
Jamie Gennis7451bb42011-05-12 17:39:03 -0700165static inline size_t align4(size_t size) {
166 return (size + 3) & ~3;
167}
168
169size_t BlobCache::getFlattenedSize() const {
Michael Lentine60788052015-05-18 13:04:01 -0700170 size_t size = align4(sizeof(Header) + PROPERTY_VALUE_MAX);
Jamie Gennis7451bb42011-05-12 17:39:03 -0700171 for (size_t i = 0; i < mCacheEntries.size(); i++) {
172 const CacheEntry& e(mCacheEntries[i]);
173 sp<Blob> keyBlob = e.getKey();
174 sp<Blob> valueBlob = e.getValue();
Christopher Ferrisde722e52014-09-24 13:06:35 -0700175 size += align4(sizeof(EntryHeader) + keyBlob->getSize() +
176 valueBlob->getSize());
Jamie Gennis7451bb42011-05-12 17:39:03 -0700177 }
178 return size;
179}
180
Mathias Agopian6d611a82013-07-29 21:24:40 -0700181status_t BlobCache::flatten(void* buffer, size_t size) const {
Jamie Gennis7451bb42011-05-12 17:39:03 -0700182 // Write the cache header
183 if (size < sizeof(Header)) {
Steve Block1b781ab2012-01-06 19:20:56 +0000184 ALOGE("flatten: not enough room for cache header");
Jamie Gennis7451bb42011-05-12 17:39:03 -0700185 return BAD_VALUE;
186 }
187 Header* header = reinterpret_cast<Header*>(buffer);
188 header->mMagicNumber = blobCacheMagic;
189 header->mBlobCacheVersion = blobCacheVersion;
190 header->mDeviceVersion = blobCacheDeviceVersion;
191 header->mNumEntries = mCacheEntries.size();
Michael Lentine60788052015-05-18 13:04:01 -0700192 char buildId[PROPERTY_VALUE_MAX];
193 header->mBuildIdLength = property_get("ro.build.id", buildId, "");
194 memcpy(header->mBuildId, buildId, header->mBuildIdLength);
Jamie Gennis7451bb42011-05-12 17:39:03 -0700195
196 // Write cache entries
197 uint8_t* byteBuffer = reinterpret_cast<uint8_t*>(buffer);
Michael Lentine60788052015-05-18 13:04:01 -0700198 off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
Jamie Gennis7451bb42011-05-12 17:39:03 -0700199 for (size_t i = 0; i < mCacheEntries.size(); i++) {
200 const CacheEntry& e(mCacheEntries[i]);
201 sp<Blob> keyBlob = e.getKey();
202 sp<Blob> valueBlob = e.getValue();
203 size_t keySize = keyBlob->getSize();
204 size_t valueSize = valueBlob->getSize();
205
206 size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
Christopher Ferrisde722e52014-09-24 13:06:35 -0700207 size_t totalSize = align4(entrySize);
208 if (byteOffset + totalSize > size) {
Steve Block1b781ab2012-01-06 19:20:56 +0000209 ALOGE("flatten: not enough room for cache entries");
Jamie Gennis7451bb42011-05-12 17:39:03 -0700210 return BAD_VALUE;
211 }
212
213 EntryHeader* eheader = reinterpret_cast<EntryHeader*>(
214 &byteBuffer[byteOffset]);
215 eheader->mKeySize = keySize;
216 eheader->mValueSize = valueSize;
217
218 memcpy(eheader->mData, keyBlob->getData(), keySize);
219 memcpy(eheader->mData + keySize, valueBlob->getData(), valueSize);
220
Antoine Labour5f6ebc22014-07-28 15:35:15 -0700221 if (totalSize > entrySize) {
222 // We have padding bytes. Those will get written to storage, and contribute to the CRC,
223 // so make sure we zero-them to have reproducible results.
224 memset(eheader->mData + keySize + valueSize, 0, totalSize - entrySize);
225 }
226
227 byteOffset += totalSize;
Jamie Gennis7451bb42011-05-12 17:39:03 -0700228 }
229
230 return OK;
231}
232
Mathias Agopian6d611a82013-07-29 21:24:40 -0700233status_t BlobCache::unflatten(void const* buffer, size_t size) {
Jamie Gennis7451bb42011-05-12 17:39:03 -0700234 // All errors should result in the BlobCache being in an empty state.
235 mCacheEntries.clear();
236
Jamie Gennis7451bb42011-05-12 17:39:03 -0700237 // Read the cache header
238 if (size < sizeof(Header)) {
Steve Block1b781ab2012-01-06 19:20:56 +0000239 ALOGE("unflatten: not enough room for cache header");
Jamie Gennis7451bb42011-05-12 17:39:03 -0700240 return BAD_VALUE;
241 }
242 const Header* header = reinterpret_cast<const Header*>(buffer);
243 if (header->mMagicNumber != blobCacheMagic) {
Mark Salyzyn387c5612014-04-17 08:32:11 -0700244 ALOGE("unflatten: bad magic number: %" PRIu32, header->mMagicNumber);
Jamie Gennis7451bb42011-05-12 17:39:03 -0700245 return BAD_VALUE;
246 }
Michael Lentine60788052015-05-18 13:04:01 -0700247 char buildId[PROPERTY_VALUE_MAX];
248 int len = property_get("ro.build.id", buildId, "");
Jamie Gennis7451bb42011-05-12 17:39:03 -0700249 if (header->mBlobCacheVersion != blobCacheVersion ||
Michael Lentine60788052015-05-18 13:04:01 -0700250 header->mDeviceVersion != blobCacheDeviceVersion ||
251 len != header->mBuildIdLength ||
252 strncmp(buildId, header->mBuildId, len)) {
Jamie Gennis7451bb42011-05-12 17:39:03 -0700253 // We treat version mismatches as an empty cache.
254 return OK;
255 }
256
257 // Read cache entries
258 const uint8_t* byteBuffer = reinterpret_cast<const uint8_t*>(buffer);
Michael Lentine60788052015-05-18 13:04:01 -0700259 off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
Jamie Gennis7451bb42011-05-12 17:39:03 -0700260 size_t numEntries = header->mNumEntries;
261 for (size_t i = 0; i < numEntries; i++) {
262 if (byteOffset + sizeof(EntryHeader) > size) {
263 mCacheEntries.clear();
Steve Block1b781ab2012-01-06 19:20:56 +0000264 ALOGE("unflatten: not enough room for cache entry headers");
Jamie Gennis7451bb42011-05-12 17:39:03 -0700265 return BAD_VALUE;
266 }
267
268 const EntryHeader* eheader = reinterpret_cast<const EntryHeader*>(
269 &byteBuffer[byteOffset]);
270 size_t keySize = eheader->mKeySize;
271 size_t valueSize = eheader->mValueSize;
272 size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
273
Christopher Ferrisde722e52014-09-24 13:06:35 -0700274 size_t totalSize = align4(entrySize);
275 if (byteOffset + totalSize > size) {
Jamie Gennis7451bb42011-05-12 17:39:03 -0700276 mCacheEntries.clear();
Steve Block1b781ab2012-01-06 19:20:56 +0000277 ALOGE("unflatten: not enough room for cache entry headers");
Jamie Gennis7451bb42011-05-12 17:39:03 -0700278 return BAD_VALUE;
279 }
280
281 const uint8_t* data = eheader->mData;
282 set(data, keySize, data + keySize, valueSize);
283
Christopher Ferrisde722e52014-09-24 13:06:35 -0700284 byteOffset += totalSize;
Jamie Gennis7451bb42011-05-12 17:39:03 -0700285 }
286
287 return OK;
288}
289
Kenny Root967ad862011-06-15 20:41:15 -0700290long int BlobCache::blob_random() {
291#ifdef _WIN32
292 return rand();
293#else
294 return nrand48(mRandState);
295#endif
296}
297
Jamie Gennis1a209932011-04-28 16:19:45 -0700298void BlobCache::clean() {
299 // Remove a random cache entry until the total cache size gets below half
300 // the maximum total cache size.
301 while (mTotalSize > mMaxTotalSize / 2) {
Kenny Root967ad862011-06-15 20:41:15 -0700302 size_t i = size_t(blob_random() % (mCacheEntries.size()));
Jamie Gennis1a209932011-04-28 16:19:45 -0700303 const CacheEntry& entry(mCacheEntries[i]);
304 mTotalSize -= entry.getKey()->getSize() + entry.getValue()->getSize();
305 mCacheEntries.removeAt(i);
306 }
307}
308
309bool BlobCache::isCleanable() const {
310 return mTotalSize > mMaxTotalSize / 2;
311}
312
313BlobCache::Blob::Blob(const void* data, size_t size, bool copyData):
314 mData(copyData ? malloc(size) : data),
315 mSize(size),
316 mOwnsData(copyData) {
Jamie Gennis7451bb42011-05-12 17:39:03 -0700317 if (data != NULL && copyData) {
Jamie Gennis1a209932011-04-28 16:19:45 -0700318 memcpy(const_cast<void*>(mData), data, size);
319 }
320}
321
322BlobCache::Blob::~Blob() {
323 if (mOwnsData) {
324 free(const_cast<void*>(mData));
325 }
326}
327
328bool BlobCache::Blob::operator<(const Blob& rhs) const {
329 if (mSize == rhs.mSize) {
330 return memcmp(mData, rhs.mData, mSize) < 0;
331 } else {
332 return mSize < rhs.mSize;
333 }
334}
335
336const void* BlobCache::Blob::getData() const {
337 return mData;
338}
339
340size_t BlobCache::Blob::getSize() const {
341 return mSize;
342}
343
344BlobCache::CacheEntry::CacheEntry() {
345}
346
347BlobCache::CacheEntry::CacheEntry(const sp<Blob>& key, const sp<Blob>& value):
348 mKey(key),
349 mValue(value) {
350}
351
352BlobCache::CacheEntry::CacheEntry(const CacheEntry& ce):
353 mKey(ce.mKey),
354 mValue(ce.mValue) {
355}
356
357bool BlobCache::CacheEntry::operator<(const CacheEntry& rhs) const {
358 return *mKey < *rhs.mKey;
359}
360
361const BlobCache::CacheEntry& BlobCache::CacheEntry::operator=(const CacheEntry& rhs) {
362 mKey = rhs.mKey;
363 mValue = rhs.mValue;
364 return *this;
365}
366
367sp<BlobCache::Blob> BlobCache::CacheEntry::getKey() const {
368 return mKey;
369}
370
371sp<BlobCache::Blob> BlobCache::CacheEntry::getValue() const {
372 return mValue;
373}
374
375void BlobCache::CacheEntry::setValue(const sp<Blob>& value) {
376 mValue = value;
377}
378
379} // namespace android