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_NDEBUG 0
18 
19 #include "egl_cache.h"
20 
21 #include <android-base/properties.h>
22 #include <inttypes.h>
23 #include <log/log.h>
24 #include <private/EGL/cache.h>
25 #include <unistd.h>
26 
27 #include <thread>
28 
29 #include "../egl_impl.h"
30 #include "egl_display.h"
31 
32 // Monolithic cache size limits.
33 static const size_t kMaxMonolithicKeySize = 12 * 1024;
34 static const size_t kMaxMonolithicValueSize = 64 * 1024;
35 static const size_t kMaxMonolithicTotalSize = 2 * 1024 * 1024;
36 
37 // The time in seconds to wait before saving newly inserted monolithic cache entries.
38 static const unsigned int kDeferredMonolithicSaveDelay = 4;
39 
40 // Multifile cache size limits
41 constexpr uint32_t kMaxMultifileKeySize = 1 * 1024 * 1024;
42 constexpr uint32_t kMaxMultifileValueSize = 8 * 1024 * 1024;
43 constexpr uint32_t kMaxMultifileTotalSize = 32 * 1024 * 1024;
44 constexpr uint32_t kMaxMultifileTotalEntries = 4 * 1024;
45 
46 namespace android {
47 
48 #define BC_EXT_STR "EGL_ANDROID_blob_cache"
49 
50 // called from android_view_ThreadedRenderer.cpp
egl_set_cache_filename(const char * filename)51 void egl_set_cache_filename(const char* filename) {
52     egl_cache_t::get()->setCacheFilename(filename);
53 }
54 
55 //
56 // Callback functions passed to EGL.
57 //
setBlob(const void * key,EGLsizeiANDROID keySize,const void * value,EGLsizeiANDROID valueSize)58 static void setBlob(const void* key, EGLsizeiANDROID keySize, const void* value,
59                     EGLsizeiANDROID valueSize) {
60     egl_cache_t::get()->setBlob(key, keySize, value, valueSize);
61 }
62 
getBlob(const void * key,EGLsizeiANDROID keySize,void * value,EGLsizeiANDROID valueSize)63 static EGLsizeiANDROID getBlob(const void* key, EGLsizeiANDROID keySize, void* value,
64                                EGLsizeiANDROID valueSize) {
65     return egl_cache_t::get()->getBlob(key, keySize, value, valueSize);
66 }
67 
68 //
69 // egl_cache_t definition
70 //
egl_cache_t()71 egl_cache_t::egl_cache_t()
72       : mInitialized(false), mMultifileMode(false), mCacheByteLimit(kMaxMonolithicTotalSize) {}
73 
~egl_cache_t()74 egl_cache_t::~egl_cache_t() {}
75 
76 egl_cache_t egl_cache_t::sCache;
77 
get()78 egl_cache_t* egl_cache_t::get() {
79     return &sCache;
80 }
81 
initialize(egl_display_t * display)82 void egl_cache_t::initialize(egl_display_t* display) {
83     std::lock_guard<std::mutex> lock(mMutex);
84 
85     egl_connection_t* const cnx = &gEGLImpl;
86     if (display && cnx->dso && cnx->major >= 0 && cnx->minor >= 0) {
87         const char* exts = display->disp.queryString.extensions;
88         size_t bcExtLen = strlen(BC_EXT_STR);
89         size_t extsLen = strlen(exts);
90         bool equal = !strcmp(BC_EXT_STR, exts);
91         bool atStart = !strncmp(BC_EXT_STR " ", exts, bcExtLen + 1);
92         bool atEnd = (bcExtLen + 1) < extsLen &&
93                 !strcmp(" " BC_EXT_STR, exts + extsLen - (bcExtLen + 1));
94         bool inMiddle = strstr(exts, " " BC_EXT_STR " ") != nullptr;
95         if (equal || atStart || atEnd || inMiddle) {
96             PFNEGLSETBLOBCACHEFUNCSANDROIDPROC eglSetBlobCacheFuncsANDROID;
97             eglSetBlobCacheFuncsANDROID = reinterpret_cast<PFNEGLSETBLOBCACHEFUNCSANDROIDPROC>(
98                     cnx->egl.eglGetProcAddress("eglSetBlobCacheFuncsANDROID"));
99             if (eglSetBlobCacheFuncsANDROID == nullptr) {
100                 ALOGE("EGL_ANDROID_blob_cache advertised, "
101                       "but unable to get eglSetBlobCacheFuncsANDROID");
102                 return;
103             }
104 
105             eglSetBlobCacheFuncsANDROID(display->disp.dpy, android::setBlob, android::getBlob);
106             EGLint err = cnx->egl.eglGetError();
107             if (err != EGL_SUCCESS) {
108                 ALOGE("eglSetBlobCacheFuncsANDROID resulted in an error: "
109                       "%#x",
110                       err);
111             }
112         }
113     }
114 
115     mInitialized = true;
116 }
117 
terminate()118 void egl_cache_t::terminate() {
119     std::lock_guard<std::mutex> lock(mMutex);
120     if (mBlobCache) {
121         mBlobCache->writeToFile();
122     }
123     mBlobCache = nullptr;
124     if (mMultifileBlobCache) {
125         mMultifileBlobCache->finish();
126     }
127     mMultifileBlobCache = nullptr;
128     mInitialized = false;
129 }
130 
setBlob(const void * key,EGLsizeiANDROID keySize,const void * value,EGLsizeiANDROID valueSize)131 void egl_cache_t::setBlob(const void* key, EGLsizeiANDROID keySize, const void* value,
132                           EGLsizeiANDROID valueSize) {
133     std::lock_guard<std::mutex> lock(mMutex);
134 
135     if (keySize < 0 || valueSize < 0) {
136         ALOGW("EGL_ANDROID_blob_cache set: negative sizes are not allowed");
137         return;
138     }
139 
140     updateMode();
141 
142     if (mInitialized) {
143         if (mMultifileMode) {
144             MultifileBlobCache* mbc = getMultifileBlobCacheLocked();
145             mbc->set(key, keySize, value, valueSize);
146         } else {
147             BlobCache* bc = getBlobCacheLocked();
148             bc->set(key, keySize, value, valueSize);
149 
150             if (!mSavePending) {
151                 mSavePending = true;
152                 std::thread deferredSaveThread([this]() {
153                     sleep(kDeferredMonolithicSaveDelay);
154                     std::lock_guard<std::mutex> lock(mMutex);
155                     if (mInitialized && mBlobCache) {
156                         mBlobCache->writeToFile();
157                     }
158                     mSavePending = false;
159                 });
160                 deferredSaveThread.detach();
161             }
162         }
163     }
164 }
165 
getBlob(const void * key,EGLsizeiANDROID keySize,void * value,EGLsizeiANDROID valueSize)166 EGLsizeiANDROID egl_cache_t::getBlob(const void* key, EGLsizeiANDROID keySize, void* value,
167                                      EGLsizeiANDROID valueSize) {
168     std::lock_guard<std::mutex> lock(mMutex);
169 
170     if (keySize < 0 || valueSize < 0) {
171         ALOGW("EGL_ANDROID_blob_cache get: negative sizes are not allowed");
172         return 0;
173     }
174 
175     updateMode();
176 
177     if (mInitialized) {
178         if (mMultifileMode) {
179             MultifileBlobCache* mbc = getMultifileBlobCacheLocked();
180             return mbc->get(key, keySize, value, valueSize);
181         } else {
182             BlobCache* bc = getBlobCacheLocked();
183             return bc->get(key, keySize, value, valueSize);
184         }
185     }
186 
187     return 0;
188 }
189 
setCacheMode(EGLCacheMode cacheMode)190 void egl_cache_t::setCacheMode(EGLCacheMode cacheMode) {
191     mMultifileMode = (cacheMode == EGLCacheMode::Multifile);
192 }
193 
setCacheFilename(const char * filename)194 void egl_cache_t::setCacheFilename(const char* filename) {
195     std::lock_guard<std::mutex> lock(mMutex);
196     mFilename = filename;
197 }
198 
setCacheLimit(int64_t cacheByteLimit)199 void egl_cache_t::setCacheLimit(int64_t cacheByteLimit) {
200     std::lock_guard<std::mutex> lock(mMutex);
201 
202     if (!mMultifileMode) {
203         // If we're not in multifile mode, ensure the cache limit is only being lowered,
204         // not increasing above the hard coded platform limit
205         if (cacheByteLimit > kMaxMonolithicTotalSize) {
206             return;
207         }
208     }
209 
210     mCacheByteLimit = cacheByteLimit;
211 }
212 
getCacheSize()213 size_t egl_cache_t::getCacheSize() {
214     std::lock_guard<std::mutex> lock(mMutex);
215     if (mMultifileBlobCache) {
216         return mMultifileBlobCache->getTotalSize();
217     }
218     if (mBlobCache) {
219         return mBlobCache->getSize();
220     }
221     return 0;
222 }
223 
updateMode()224 void egl_cache_t::updateMode() {
225     // We don't set the mode in the constructor because these checks have
226     // a non-trivial cost, and not all processes that instantiate egl_cache_t
227     // will use it.
228 
229     // If we've already set the mode, skip these checks
230     static bool checked = false;
231     if (checked) {
232         return;
233     }
234     checked = true;
235 
236     // Check the device config to decide whether multifile should be used
237     if (base::GetBoolProperty("ro.egl.blobcache.multifile", false)) {
238         mMultifileMode = true;
239         ALOGV("Using multifile EGL blobcache");
240     }
241 
242     // Allow forcing the mode for debug purposes
243     std::string mode = base::GetProperty("debug.egl.blobcache.multifile", "");
244     if (mode == "true") {
245         ALOGV("Forcing multifile cache due to debug.egl.blobcache.multifile == %s", mode.c_str());
246         mMultifileMode = true;
247     } else if (mode == "false") {
248         ALOGV("Forcing monolithic cache due to debug.egl.blobcache.multifile == %s", mode.c_str());
249         mMultifileMode = false;
250     }
251 
252     if (mMultifileMode) {
253         mCacheByteLimit = static_cast<size_t>(
254                 base::GetUintProperty<uint32_t>("ro.egl.blobcache.multifile_limit",
255                                                 kMaxMultifileTotalSize));
256 
257         // Check for a debug value
258         int debugCacheSize = base::GetIntProperty("debug.egl.blobcache.multifile_limit", -1);
259         if (debugCacheSize >= 0) {
260             ALOGV("Overriding cache limit %zu with %i from debug.egl.blobcache.multifile_limit",
261                   mCacheByteLimit, debugCacheSize);
262             mCacheByteLimit = debugCacheSize;
263         }
264 
265         ALOGV("Using multifile EGL blobcache limit of %zu bytes", mCacheByteLimit);
266     }
267 }
268 
getBlobCacheLocked()269 BlobCache* egl_cache_t::getBlobCacheLocked() {
270     if (mBlobCache == nullptr) {
271         mBlobCache.reset(new FileBlobCache(kMaxMonolithicKeySize, kMaxMonolithicValueSize,
272                                            mCacheByteLimit, mFilename));
273     }
274     return mBlobCache.get();
275 }
276 
getMultifileBlobCacheLocked()277 MultifileBlobCache* egl_cache_t::getMultifileBlobCacheLocked() {
278     if (mMultifileBlobCache == nullptr) {
279         mMultifileBlobCache.reset(new MultifileBlobCache(kMaxMultifileKeySize,
280                                                          kMaxMultifileValueSize, mCacheByteLimit,
281                                                          kMaxMultifileTotalEntries, mFilename));
282     }
283     return mMultifileBlobCache.get();
284 }
285 
286 }; // namespace android
287