1/*
2 * Copyright (C) 2017 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#include "ShaderCache.h"
18#include <algorithm>
19#include <log/log.h>
20#include <thread>
21#include "FileBlobCache.h"
22#include "Properties.h"
23#include "utils/TraceUtils.h"
24
25namespace android {
26namespace uirenderer {
27namespace skiapipeline {
28
29// Cache size limits.
30static const size_t maxKeySize = 1024;
31static const size_t maxValueSize = 64 * 1024;
32static const size_t maxTotalSize = 512 * 1024;
33
34ShaderCache::ShaderCache() {
35    // There is an "incomplete FileBlobCache type" compilation error, if ctor is moved to header.
36}
37
38ShaderCache ShaderCache::sCache;
39
40ShaderCache& ShaderCache::get() {
41    return sCache;
42}
43
44void ShaderCache::initShaderDiskCache() {
45    ATRACE_NAME("initShaderDiskCache");
46    std::lock_guard<std::mutex> lock(mMutex);
47
48    // Emulators can switch between different renders either as part of config
49    // or snapshot migration. Also, program binaries may not work well on some
50    // desktop / laptop GPUs. Thus, disable the shader disk cache for emulator builds.
51    if (!Properties::runningInEmulator && mFilename.length() > 0) {
52        mBlobCache.reset(new FileBlobCache(maxKeySize, maxValueSize, maxTotalSize, mFilename));
53        mInitialized = true;
54    }
55}
56
57void ShaderCache::setFilename(const char* filename) {
58    std::lock_guard<std::mutex> lock(mMutex);
59    mFilename = filename;
60}
61
62BlobCache* ShaderCache::getBlobCacheLocked() {
63    LOG_ALWAYS_FATAL_IF(!mInitialized, "ShaderCache has not been initialized");
64    return mBlobCache.get();
65}
66
67sk_sp<SkData> ShaderCache::load(const SkData& key) {
68    ATRACE_NAME("ShaderCache::load");
69    size_t keySize = key.size();
70    std::lock_guard<std::mutex> lock(mMutex);
71    if (!mInitialized) {
72        return nullptr;
73    }
74
75    // mObservedBlobValueSize is reasonably big to avoid memory reallocation
76    // Allocate a buffer with malloc. SkData takes ownership of that allocation and will call free.
77    void* valueBuffer = malloc(mObservedBlobValueSize);
78    if (!valueBuffer) {
79        return nullptr;
80    }
81    BlobCache* bc = getBlobCacheLocked();
82    size_t valueSize = bc->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
83    int maxTries = 3;
84    while (valueSize > mObservedBlobValueSize && maxTries > 0) {
85        mObservedBlobValueSize = std::min(valueSize, maxValueSize);
86        void *newValueBuffer = realloc(valueBuffer, mObservedBlobValueSize);
87        if (!newValueBuffer) {
88            free(valueBuffer);
89            return nullptr;
90        }
91        valueBuffer = newValueBuffer;
92        valueSize = bc->get(key.data(), keySize, valueBuffer, mObservedBlobValueSize);
93        maxTries--;
94    }
95    if (!valueSize) {
96        free(valueBuffer);
97        return nullptr;
98    }
99    if (valueSize > mObservedBlobValueSize) {
100        ALOGE("ShaderCache::load value size is too big %d", (int) valueSize);
101        free(valueBuffer);
102        return nullptr;
103    }
104    return SkData::MakeFromMalloc(valueBuffer, valueSize);
105}
106
107void ShaderCache::store(const SkData& key, const SkData& data) {
108    ATRACE_NAME("ShaderCache::store");
109    std::lock_guard<std::mutex> lock(mMutex);
110
111    if (!mInitialized) {
112        return;
113    }
114
115    size_t valueSize = data.size();
116    size_t keySize = key.size();
117    if (keySize == 0 || valueSize == 0 || valueSize >= maxValueSize) {
118        ALOGW("ShaderCache::store: sizes %d %d not allowed", (int)keySize, (int)valueSize);
119        return;
120    }
121
122    const void* value = data.data();
123
124    BlobCache* bc = getBlobCacheLocked();
125    bc->set(key.data(), keySize, value, valueSize);
126
127    if (!mSavePending && mDeferredSaveDelay > 0) {
128        mSavePending = true;
129        std::thread deferredSaveThread([this]() {
130            sleep(mDeferredSaveDelay);
131            std::lock_guard<std::mutex> lock(mMutex);
132            ATRACE_NAME("ShaderCache::saveToDisk");
133            if (mInitialized && mBlobCache) {
134                mBlobCache->writeToFile();
135            }
136            mSavePending = false;
137        });
138        deferredSaveThread.detach();
139    }
140}
141
142} /* namespace skiapipeline */
143} /* namespace uirenderer */
144} /* namespace android */
145