1 /*
2  * Copyright (C) 2021 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 "ShimBufferTracker"
18 
19 #include "ShimBufferTracker.h"
20 #include "ShimDevice.h"
21 
22 #include <android-base/logging.h>
23 
24 #include <algorithm>
25 #include <memory>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 using namespace ::android::nn::sl_wrapper;
31 
32 namespace aidl::android::hardware::neuralnetworks {
33 
add(std::shared_ptr<::android::nn::sl_wrapper::Memory> buffer)34 std::unique_ptr<ShimBufferTracker::Token> ShimBufferTracker::add(
35         std::shared_ptr<::android::nn::sl_wrapper::Memory> buffer) {
36     if (buffer == nullptr) {
37         return nullptr;
38     }
39     std::lock_guard<std::mutex> guard(mMutex);
40     uint32_t token = 0;
41     if (mFreeTokens.empty()) {
42         token = mTokenToBuffers.size();
43         mTokenToBuffers.push_back(std::move(buffer));
44     } else {
45         token = mFreeTokens.top();
46         mFreeTokens.pop();
47         mTokenToBuffers[token] = std::move(buffer);
48     }
49     return std::make_unique<Token>(token, shared_from_this());
50 }
51 
get(uint32_t token) const52 std::shared_ptr<::android::nn::sl_wrapper::Memory> ShimBufferTracker::get(uint32_t token) const {
53     std::lock_guard<std::mutex> guard(mMutex);
54     if (mTokenToBuffers.size() <= token || mTokenToBuffers[token] == nullptr) {
55         LOG(ERROR) << "ShimBufferTracker::get -- unknown token " << token;
56         return nullptr;
57     }
58     return mTokenToBuffers[token];
59 }
60 
free(uint32_t token)61 void ShimBufferTracker::free(uint32_t token) {
62     std::lock_guard<std::mutex> guard(mMutex);
63     CHECK_LT(token, mTokenToBuffers.size());
64     CHECK(mTokenToBuffers[token] != nullptr);
65     mTokenToBuffers[token] = nullptr;
66     mFreeTokens.push(token);
67 }
68 
69 }  // namespace aidl::android::hardware::neuralnetworks
70