1 /*
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
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <utils/BlobCache.h>
24 #include <utils/Errors.h>
25 #include <utils/Log.h>
26
27 namespace android {
28
29 // BlobCache::Header::mMagicNumber value
30 static const uint32_t blobCacheMagic = '_Bb$';
31
32 // BlobCache::Header::mBlobCacheVersion value
33 static const uint32_t blobCacheVersion = 1;
34
35 // BlobCache::Header::mDeviceVersion value
36 static const uint32_t blobCacheDeviceVersion = 1;
37
BlobCache(size_t maxKeySize,size_t maxValueSize,size_t maxTotalSize)38 BlobCache::BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize):
39 mMaxKeySize(maxKeySize),
40 mMaxValueSize(maxValueSize),
41 mMaxTotalSize(maxTotalSize),
42 mTotalSize(0) {
43 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
44 #ifdef _WIN32
45 srand(now);
46 #else
47 mRandState[0] = (now >> 0) & 0xFFFF;
48 mRandState[1] = (now >> 16) & 0xFFFF;
49 mRandState[2] = (now >> 32) & 0xFFFF;
50 #endif
51 ALOGV("initializing random seed using %lld", now);
52 }
53
set(const void * key,size_t keySize,const void * value,size_t valueSize)54 void BlobCache::set(const void* key, size_t keySize, const void* value,
55 size_t valueSize) {
56 if (mMaxKeySize < keySize) {
57 ALOGV("set: not caching because the key is too large: %d (limit: %d)",
58 keySize, mMaxKeySize);
59 return;
60 }
61 if (mMaxValueSize < valueSize) {
62 ALOGV("set: not caching because the value is too large: %d (limit: %d)",
63 valueSize, mMaxValueSize);
64 return;
65 }
66 if (mMaxTotalSize < keySize + valueSize) {
67 ALOGV("set: not caching because the combined key/value size is too "
68 "large: %d (limit: %d)", keySize + valueSize, mMaxTotalSize);
69 return;
70 }
71 if (keySize == 0) {
72 ALOGW("set: not caching because keySize is 0");
73 return;
74 }
75 if (valueSize <= 0) {
76 ALOGW("set: not caching because valueSize is 0");
77 return;
78 }
79
80 sp<Blob> dummyKey(new Blob(key, keySize, false));
81 CacheEntry dummyEntry(dummyKey, NULL);
82
83 while (true) {
84 ssize_t index = mCacheEntries.indexOf(dummyEntry);
85 if (index < 0) {
86 // Create a new cache entry.
87 sp<Blob> keyBlob(new Blob(key, keySize, true));
88 sp<Blob> valueBlob(new Blob(value, valueSize, true));
89 size_t newTotalSize = mTotalSize + keySize + valueSize;
90 if (mMaxTotalSize < newTotalSize) {
91 if (isCleanable()) {
92 // Clean the cache and try again.
93 clean();
94 continue;
95 } else {
96 ALOGV("set: not caching new key/value pair because the "
97 "total cache size limit would be exceeded: %d "
98 "(limit: %d)",
99 keySize + valueSize, mMaxTotalSize);
100 break;
101 }
102 }
103 mCacheEntries.add(CacheEntry(keyBlob, valueBlob));
104 mTotalSize = newTotalSize;
105 ALOGV("set: created new cache entry with %d byte key and %d byte value",
106 keySize, valueSize);
107 } else {
108 // Update the existing cache entry.
109 sp<Blob> valueBlob(new Blob(value, valueSize, true));
110 sp<Blob> oldValueBlob(mCacheEntries[index].getValue());
111 size_t newTotalSize = mTotalSize + valueSize - oldValueBlob->getSize();
112 if (mMaxTotalSize < newTotalSize) {
113 if (isCleanable()) {
114 // Clean the cache and try again.
115 clean();
116 continue;
117 } else {
118 ALOGV("set: not caching new value because the total cache "
119 "size limit would be exceeded: %d (limit: %d)",
120 keySize + valueSize, mMaxTotalSize);
121 break;
122 }
123 }
124 mCacheEntries.editItemAt(index).setValue(valueBlob);
125 mTotalSize = newTotalSize;
126 ALOGV("set: updated existing cache entry with %d byte key and %d byte "
127 "value", keySize, valueSize);
128 }
129 break;
130 }
131 }
132
get(const void * key,size_t keySize,void * value,size_t valueSize)133 size_t BlobCache::get(const void* key, size_t keySize, void* value,
134 size_t valueSize) {
135 if (mMaxKeySize < keySize) {
136 ALOGV("get: not searching because the key is too large: %d (limit %d)",
137 keySize, mMaxKeySize);
138 return 0;
139 }
140 sp<Blob> dummyKey(new Blob(key, keySize, false));
141 CacheEntry dummyEntry(dummyKey, NULL);
142 ssize_t index = mCacheEntries.indexOf(dummyEntry);
143 if (index < 0) {
144 ALOGV("get: no cache entry found for key of size %d", keySize);
145 return 0;
146 }
147
148 // The key was found. Return the value if the caller's buffer is large
149 // enough.
150 sp<Blob> valueBlob(mCacheEntries[index].getValue());
151 size_t valueBlobSize = valueBlob->getSize();
152 if (valueBlobSize <= valueSize) {
153 ALOGV("get: copying %d bytes to caller's buffer", valueBlobSize);
154 memcpy(value, valueBlob->getData(), valueBlobSize);
155 } else {
156 ALOGV("get: caller's buffer is too small for value: %d (needs %d)",
157 valueSize, valueBlobSize);
158 }
159 return valueBlobSize;
160 }
161
align4(size_t size)162 static inline size_t align4(size_t size) {
163 return (size + 3) & ~3;
164 }
165
getFlattenedSize() const166 size_t BlobCache::getFlattenedSize() const {
167 size_t size = sizeof(Header);
168 for (size_t i = 0; i < mCacheEntries.size(); i++) {
169 const CacheEntry& e(mCacheEntries[i]);
170 sp<Blob> keyBlob = e.getKey();
171 sp<Blob> valueBlob = e.getValue();
172 size = align4(size);
173 size += sizeof(EntryHeader) + keyBlob->getSize() +
174 valueBlob->getSize();
175 }
176 return size;
177 }
178
flatten(void * buffer,size_t size) const179 status_t BlobCache::flatten(void* buffer, size_t size) const {
180 // Write the cache header
181 if (size < sizeof(Header)) {
182 ALOGE("flatten: not enough room for cache header");
183 return BAD_VALUE;
184 }
185 Header* header = reinterpret_cast<Header*>(buffer);
186 header->mMagicNumber = blobCacheMagic;
187 header->mBlobCacheVersion = blobCacheVersion;
188 header->mDeviceVersion = blobCacheDeviceVersion;
189 header->mNumEntries = mCacheEntries.size();
190
191 // Write cache entries
192 uint8_t* byteBuffer = reinterpret_cast<uint8_t*>(buffer);
193 off_t byteOffset = align4(sizeof(Header));
194 for (size_t i = 0; i < mCacheEntries.size(); i++) {
195 const CacheEntry& e(mCacheEntries[i]);
196 sp<Blob> keyBlob = e.getKey();
197 sp<Blob> valueBlob = e.getValue();
198 size_t keySize = keyBlob->getSize();
199 size_t valueSize = valueBlob->getSize();
200
201 size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
202 if (byteOffset + entrySize > size) {
203 ALOGE("flatten: not enough room for cache entries");
204 return BAD_VALUE;
205 }
206
207 EntryHeader* eheader = reinterpret_cast<EntryHeader*>(
208 &byteBuffer[byteOffset]);
209 eheader->mKeySize = keySize;
210 eheader->mValueSize = valueSize;
211
212 memcpy(eheader->mData, keyBlob->getData(), keySize);
213 memcpy(eheader->mData + keySize, valueBlob->getData(), valueSize);
214
215 byteOffset += align4(entrySize);
216 }
217
218 return OK;
219 }
220
unflatten(void const * buffer,size_t size)221 status_t BlobCache::unflatten(void const* buffer, size_t size) {
222 // All errors should result in the BlobCache being in an empty state.
223 mCacheEntries.clear();
224
225 // Read the cache header
226 if (size < sizeof(Header)) {
227 ALOGE("unflatten: not enough room for cache header");
228 return BAD_VALUE;
229 }
230 const Header* header = reinterpret_cast<const Header*>(buffer);
231 if (header->mMagicNumber != blobCacheMagic) {
232 ALOGE("unflatten: bad magic number: %d", header->mMagicNumber);
233 return BAD_VALUE;
234 }
235 if (header->mBlobCacheVersion != blobCacheVersion ||
236 header->mDeviceVersion != blobCacheDeviceVersion) {
237 // We treat version mismatches as an empty cache.
238 return OK;
239 }
240
241 // Read cache entries
242 const uint8_t* byteBuffer = reinterpret_cast<const uint8_t*>(buffer);
243 off_t byteOffset = align4(sizeof(Header));
244 size_t numEntries = header->mNumEntries;
245 for (size_t i = 0; i < numEntries; i++) {
246 if (byteOffset + sizeof(EntryHeader) > size) {
247 mCacheEntries.clear();
248 ALOGE("unflatten: not enough room for cache entry headers");
249 return BAD_VALUE;
250 }
251
252 const EntryHeader* eheader = reinterpret_cast<const EntryHeader*>(
253 &byteBuffer[byteOffset]);
254 size_t keySize = eheader->mKeySize;
255 size_t valueSize = eheader->mValueSize;
256 size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
257
258 if (byteOffset + entrySize > size) {
259 mCacheEntries.clear();
260 ALOGE("unflatten: not enough room for cache entry headers");
261 return BAD_VALUE;
262 }
263
264 const uint8_t* data = eheader->mData;
265 set(data, keySize, data + keySize, valueSize);
266
267 byteOffset += align4(entrySize);
268 }
269
270 return OK;
271 }
272
blob_random()273 long int BlobCache::blob_random() {
274 #ifdef _WIN32
275 return rand();
276 #else
277 return nrand48(mRandState);
278 #endif
279 }
280
clean()281 void BlobCache::clean() {
282 // Remove a random cache entry until the total cache size gets below half
283 // the maximum total cache size.
284 while (mTotalSize > mMaxTotalSize / 2) {
285 size_t i = size_t(blob_random() % (mCacheEntries.size()));
286 const CacheEntry& entry(mCacheEntries[i]);
287 mTotalSize -= entry.getKey()->getSize() + entry.getValue()->getSize();
288 mCacheEntries.removeAt(i);
289 }
290 }
291
isCleanable() const292 bool BlobCache::isCleanable() const {
293 return mTotalSize > mMaxTotalSize / 2;
294 }
295
Blob(const void * data,size_t size,bool copyData)296 BlobCache::Blob::Blob(const void* data, size_t size, bool copyData):
297 mData(copyData ? malloc(size) : data),
298 mSize(size),
299 mOwnsData(copyData) {
300 if (data != NULL && copyData) {
301 memcpy(const_cast<void*>(mData), data, size);
302 }
303 }
304
~Blob()305 BlobCache::Blob::~Blob() {
306 if (mOwnsData) {
307 free(const_cast<void*>(mData));
308 }
309 }
310
operator <(const Blob & rhs) const311 bool BlobCache::Blob::operator<(const Blob& rhs) const {
312 if (mSize == rhs.mSize) {
313 return memcmp(mData, rhs.mData, mSize) < 0;
314 } else {
315 return mSize < rhs.mSize;
316 }
317 }
318
getData() const319 const void* BlobCache::Blob::getData() const {
320 return mData;
321 }
322
getSize() const323 size_t BlobCache::Blob::getSize() const {
324 return mSize;
325 }
326
CacheEntry()327 BlobCache::CacheEntry::CacheEntry() {
328 }
329
CacheEntry(const sp<Blob> & key,const sp<Blob> & value)330 BlobCache::CacheEntry::CacheEntry(const sp<Blob>& key, const sp<Blob>& value):
331 mKey(key),
332 mValue(value) {
333 }
334
CacheEntry(const CacheEntry & ce)335 BlobCache::CacheEntry::CacheEntry(const CacheEntry& ce):
336 mKey(ce.mKey),
337 mValue(ce.mValue) {
338 }
339
operator <(const CacheEntry & rhs) const340 bool BlobCache::CacheEntry::operator<(const CacheEntry& rhs) const {
341 return *mKey < *rhs.mKey;
342 }
343
operator =(const CacheEntry & rhs)344 const BlobCache::CacheEntry& BlobCache::CacheEntry::operator=(const CacheEntry& rhs) {
345 mKey = rhs.mKey;
346 mValue = rhs.mValue;
347 return *this;
348 }
349
getKey() const350 sp<BlobCache::Blob> BlobCache::CacheEntry::getKey() const {
351 return mKey;
352 }
353
getValue() const354 sp<BlobCache::Blob> BlobCache::CacheEntry::getValue() const {
355 return mValue;
356 }
357
setValue(const sp<Blob> & value)358 void BlobCache::CacheEntry::setValue(const sp<Blob>& value) {
359 mValue = value;
360 }
361
362 } // namespace android
363