EGL: implement loading and saving the cache

This change adds support for saving and loading the contents of the EGL
cache.  It also adds some simple tests for the EGL cache.

Change-Id: I18e5e789e0897a0783d29d1c1e64d26de2dd44c4
diff --git a/opengl/libs/EGL/egl_cache.cpp b/opengl/libs/EGL/egl_cache.cpp
index adb2a13..aa40d58 100644
--- a/opengl/libs/EGL/egl_cache.cpp
+++ b/opengl/libs/EGL/egl_cache.cpp
@@ -19,11 +19,21 @@
 #include "egl_impl.h"
 #include "egldefs.h"
 
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
 // Cache size limits.
 static const size_t maxKeySize = 1024;
 static const size_t maxValueSize = 4096;
 static const size_t maxTotalSize = 64 * 1024;
 
+// Cache file header
+static const char* cacheFileMagic = "EGL$";
+static const size_t cacheFileHeaderSize = 8;
+
 // ----------------------------------------------------------------------------
 namespace android {
 // ----------------------------------------------------------------------------
@@ -54,9 +64,10 @@
 egl_cache_t::~egl_cache_t() {
 }
 
+egl_cache_t egl_cache_t::sCache;
+
 egl_cache_t* egl_cache_t::get() {
-    static egl_cache_t theCache;
-    return &theCache;
+    return &sCache;
 }
 
 void egl_cache_t::initialize(egl_display_t *display) {
@@ -136,6 +147,11 @@
     return 0;
 }
 
+void egl_cache_t::setCacheFilename(const char* filename) {
+    Mutex::Autolock lock(mMutex);
+    mFilename = filename;
+}
+
 sp<BlobCache> egl_cache_t::getBlobCacheLocked() {
     if (mBlobCache == NULL) {
         mBlobCache = new BlobCache(maxKeySize, maxValueSize, maxTotalSize);
@@ -144,10 +160,154 @@
     return mBlobCache;
 }
 
+static uint32_t crc32c(const uint8_t* buf, size_t len) {
+    const uint32_t polyBits = 0x82F63B78;
+    uint32_t r = 0;
+    for (size_t i = 0; i < len; i++) {
+        r ^= buf[i];
+        for (int j = 0; j < 8; j++) {
+            if (r & 1) {
+                r = (r >> 1) ^ polyBits;
+            } else {
+                r >>= 1;
+            }
+        }
+    }
+    return r;
+}
+
 void egl_cache_t::saveBlobCacheLocked() {
+    if (mFilename.length() > 0) {
+        size_t cacheSize = mBlobCache->getFlattenedSize();
+        size_t headerSize = cacheFileHeaderSize;
+        const char* fname = mFilename.string();
+
+        // Try to create the file with no permissions so we can write it
+        // without anyone trying to read it.
+        int fd = open(fname, O_CREAT | O_EXCL | O_RDWR, 0);
+        if (fd == -1) {
+            if (errno == EEXIST) {
+                // The file exists, delete it and try again.
+                if (unlink(fname) == -1) {
+                    // No point in retrying if the unlink failed.
+                    LOGE("error unlinking cache file %s: %s (%d)", fname,
+                            strerror(errno), errno);
+                    return;
+                }
+                // Retry now that we've unlinked the file.
+                fd = open(fname, O_CREAT | O_EXCL | O_RDWR, 0);
+            }
+            if (fd == -1) {
+                LOGE("error creating cache file %s: %s (%d)", fname,
+                        strerror(errno), errno);
+                return;
+            }
+        }
+
+        size_t fileSize = headerSize + cacheSize;
+        if (ftruncate(fd, fileSize) == -1) {
+            LOGE("error setting cache file size: %s (%d)", strerror(errno),
+                    errno);
+            close(fd);
+            unlink(fname);
+            return;
+        }
+
+        uint8_t* buf = reinterpret_cast<uint8_t*>(mmap(NULL, fileSize,
+                PROT_WRITE, MAP_SHARED, fd, 0));
+        if (buf == MAP_FAILED) {
+            LOGE("error mmaping cache file: %s (%d)", strerror(errno),
+                    errno);
+            close(fd);
+            unlink(fname);
+            return;
+        }
+
+        status_t err = mBlobCache->flatten(buf + headerSize, cacheSize, NULL,
+                0);
+        if (err != OK) {
+            LOGE("error writing cache contents: %s (%d)", strerror(-err),
+                    -err);
+            munmap(buf, fileSize);
+            close(fd);
+            unlink(fname);
+            return;
+        }
+
+        // Write the file magic and CRC
+        memcpy(buf, cacheFileMagic, 4);
+        uint32_t* crc = reinterpret_cast<uint32_t*>(buf + 4);
+        *crc = crc32c(buf + headerSize, cacheSize);
+
+        munmap(buf, fileSize);
+        fchmod(fd, S_IRUSR);
+        close(fd);
+    }
 }
 
 void egl_cache_t::loadBlobCacheLocked() {
+    if (mFilename.length() > 0) {
+        size_t headerSize = cacheFileHeaderSize;
+
+        int fd = open(mFilename.string(), O_RDONLY, 0);
+        if (fd == -1) {
+            if (errno != ENOENT) {
+                LOGE("error opening cache file %s: %s (%d)", mFilename.string(),
+                        strerror(errno), errno);
+            }
+            return;
+        }
+
+        struct stat statBuf;
+        if (fstat(fd, &statBuf) == -1) {
+            LOGE("error stat'ing cache file: %s (%d)", strerror(errno), errno);
+            close(fd);
+            return;
+        }
+
+        // Sanity check the size before trying to mmap it.
+        size_t fileSize = statBuf.st_size;
+        if (fileSize > maxTotalSize * 2) {
+            LOGE("cache file is too large: %#llx", statBuf.st_size);
+            close(fd);
+            return;
+        }
+
+        uint8_t* buf = reinterpret_cast<uint8_t*>(mmap(NULL, fileSize,
+                PROT_READ, MAP_PRIVATE, fd, 0));
+        if (buf == MAP_FAILED) {
+            LOGE("error mmaping cache file: %s (%d)", strerror(errno),
+                    errno);
+            close(fd);
+            return;
+        }
+
+        // Check the file magic and CRC
+        size_t cacheSize = fileSize - headerSize;
+        if (memcmp(buf, cacheFileMagic, 4) != 0) {
+            LOGE("cache file has bad mojo");
+            close(fd);
+            return;
+        }
+        uint32_t* crc = reinterpret_cast<uint32_t*>(buf + 4);
+        if (crc32c(buf + headerSize, cacheSize) != *crc) {
+            LOGE("cache file failed CRC check");
+            close(fd);
+            return;
+        }
+
+        status_t err = mBlobCache->unflatten(buf + headerSize, cacheSize, NULL, 0);
+        if (err != OK) {
+            LOGE("error reading cache contents: %s (%d)", strerror(-err),
+                    -err);
+            munmap(buf, fileSize);
+            close(fd);
+            return;
+        }
+
+        munmap(buf, fileSize);
+        close(fd);
+    }
 }
 
 // ----------------------------------------------------------------------------