1 /*
2  * Copyright (C) 2020 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 "Device.h"
18 
19 #include "Buffer.h"
20 #include "Callbacks.h"
21 #include "Conversions.h"
22 #include "PreparedModel.h"
23 #include "Utils.h"
24 
25 #include <android/hardware/neuralnetworks/1.0/types.h>
26 #include <android/hardware/neuralnetworks/1.1/types.h>
27 #include <android/hardware/neuralnetworks/1.2/types.h>
28 #include <android/hardware/neuralnetworks/1.3/IDevice.h>
29 #include <android/hardware/neuralnetworks/1.3/types.h>
30 #include <nnapi/IBuffer.h>
31 #include <nnapi/IDevice.h>
32 #include <nnapi/IPreparedModel.h>
33 #include <nnapi/OperandTypes.h>
34 #include <nnapi/Result.h>
35 #include <nnapi/Types.h>
36 #include <nnapi/hal/1.1/Conversions.h>
37 #include <nnapi/hal/1.2/Conversions.h>
38 #include <nnapi/hal/1.2/Device.h>
39 #include <nnapi/hal/1.2/Utils.h>
40 #include <nnapi/hal/CommonUtils.h>
41 #include <nnapi/hal/HandleError.h>
42 #include <nnapi/hal/ProtectCallback.h>
43 
44 #include <any>
45 #include <functional>
46 #include <memory>
47 #include <optional>
48 #include <string>
49 #include <vector>
50 
51 // See hardware/interfaces/neuralnetworks/utils/README.md for more information on HIDL interface
52 // lifetimes across processes and for protecting asynchronous calls across HIDL.
53 
54 namespace android::hardware::neuralnetworks::V1_3::utils {
55 namespace {
56 
convert(const std::vector<nn::SharedPreparedModel> & preparedModels)57 nn::GeneralResult<hidl_vec<sp<IPreparedModel>>> convert(
58         const std::vector<nn::SharedPreparedModel>& preparedModels) {
59     hidl_vec<sp<IPreparedModel>> hidlPreparedModels(preparedModels.size());
60     for (size_t i = 0; i < preparedModels.size(); ++i) {
61         std::any underlyingResource = preparedModels[i]->getUnderlyingResource();
62         if (const auto* hidlPreparedModel =
63                     std::any_cast<sp<IPreparedModel>>(&underlyingResource)) {
64             hidlPreparedModels[i] = *hidlPreparedModel;
65         } else {
66             return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
67                    << "Unable to convert from nn::IPreparedModel to V1_3::IPreparedModel";
68         }
69     }
70     return hidlPreparedModels;
71 }
72 
capabilitiesCallback(ErrorStatus status,const Capabilities & capabilities)73 nn::GeneralResult<nn::Capabilities> capabilitiesCallback(ErrorStatus status,
74                                                          const Capabilities& capabilities) {
75     HANDLE_HAL_STATUS(status) << "getting capabilities failed with " << toString(status);
76     return nn::convert(capabilities);
77 }
78 
getCapabilitiesFrom(V1_3::IDevice * device)79 nn::GeneralResult<nn::Capabilities> getCapabilitiesFrom(V1_3::IDevice* device) {
80     CHECK(device != nullptr);
81 
82     auto cb = hal::utils::CallbackValue(capabilitiesCallback);
83 
84     const auto ret = device->getCapabilities_1_3(cb);
85     HANDLE_TRANSPORT_FAILURE(ret);
86 
87     return cb.take();
88 }
89 
allocationCallback(ErrorStatus status,const sp<IBuffer> & buffer,uint32_t token)90 nn::GeneralResult<nn::SharedBuffer> allocationCallback(ErrorStatus status,
91                                                        const sp<IBuffer>& buffer, uint32_t token) {
92     HANDLE_HAL_STATUS(status) << "IDevice::allocate failed with " << toString(status);
93     return Buffer::create(buffer, static_cast<nn::Request::MemoryDomainToken>(token));
94 }
95 
96 }  // namespace
97 
create(std::string name,sp<V1_3::IDevice> device)98 nn::GeneralResult<std::shared_ptr<const Device>> Device::create(std::string name,
99                                                                 sp<V1_3::IDevice> device) {
100     if (name.empty()) {
101         return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
102                << "V1_3::utils::Device::create must have non-empty name";
103     }
104     if (device == nullptr) {
105         return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
106                << "V1_3::utils::Device::create must have non-null device";
107     }
108 
109     auto versionString = NN_TRY(V1_2::utils::getVersionStringFrom(device.get()));
110     const auto deviceType = NN_TRY(V1_2::utils::getDeviceTypeFrom(device.get()));
111     auto extensions = NN_TRY(V1_2::utils::getSupportedExtensionsFrom(device.get()));
112     auto capabilities = NN_TRY(getCapabilitiesFrom(device.get()));
113     const auto numberOfCacheFilesNeeded =
114             NN_TRY(V1_2::utils::getNumberOfCacheFilesNeededFrom(device.get()));
115 
116     auto deathHandler = NN_TRY(hal::utils::DeathHandler::create(device));
117     return std::make_shared<const Device>(
118             PrivateConstructorTag{}, std::move(name), std::move(versionString), deviceType,
119             std::move(extensions), std::move(capabilities), numberOfCacheFilesNeeded,
120             std::move(device), std::move(deathHandler));
121 }
122 
Device(PrivateConstructorTag,std::string name,std::string versionString,nn::DeviceType deviceType,std::vector<nn::Extension> extensions,nn::Capabilities capabilities,std::pair<uint32_t,uint32_t> numberOfCacheFilesNeeded,sp<V1_3::IDevice> device,hal::utils::DeathHandler deathHandler)123 Device::Device(PrivateConstructorTag /*tag*/, std::string name, std::string versionString,
124                nn::DeviceType deviceType, std::vector<nn::Extension> extensions,
125                nn::Capabilities capabilities,
126                std::pair<uint32_t, uint32_t> numberOfCacheFilesNeeded, sp<V1_3::IDevice> device,
127                hal::utils::DeathHandler deathHandler)
128     : kName(std::move(name)),
129       kVersionString(std::move(versionString)),
130       kDeviceType(deviceType),
131       kExtensions(std::move(extensions)),
132       kCapabilities(std::move(capabilities)),
133       kNumberOfCacheFilesNeeded(numberOfCacheFilesNeeded),
134       kDevice(std::move(device)),
135       kDeathHandler(std::move(deathHandler)) {}
136 
getName() const137 const std::string& Device::getName() const {
138     return kName;
139 }
140 
getVersionString() const141 const std::string& Device::getVersionString() const {
142     return kVersionString;
143 }
144 
getFeatureLevel() const145 nn::Version Device::getFeatureLevel() const {
146     return nn::Version::ANDROID_R;
147 }
148 
getType() const149 nn::DeviceType Device::getType() const {
150     return kDeviceType;
151 }
152 
getSupportedExtensions() const153 const std::vector<nn::Extension>& Device::getSupportedExtensions() const {
154     return kExtensions;
155 }
156 
getCapabilities() const157 const nn::Capabilities& Device::getCapabilities() const {
158     return kCapabilities;
159 }
160 
getNumberOfCacheFilesNeeded() const161 std::pair<uint32_t, uint32_t> Device::getNumberOfCacheFilesNeeded() const {
162     return kNumberOfCacheFilesNeeded;
163 }
164 
wait() const165 nn::GeneralResult<void> Device::wait() const {
166     const auto ret = kDevice->ping();
167     HANDLE_TRANSPORT_FAILURE(ret);
168     return {};
169 }
170 
getSupportedOperations(const nn::Model & model) const171 nn::GeneralResult<std::vector<bool>> Device::getSupportedOperations(const nn::Model& model) const {
172     // Ensure that model is ready for IPC.
173     std::optional<nn::Model> maybeModelInShared;
174     const nn::Model& modelInShared =
175             NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));
176 
177     const auto hidlModel = NN_TRY(convert(modelInShared));
178 
179     auto cb = hal::utils::CallbackValue(supportedOperationsCallback);
180 
181     const auto ret = kDevice->getSupportedOperations_1_3(hidlModel, cb);
182     HANDLE_TRANSPORT_FAILURE(ret);
183 
184     return cb.take();
185 }
186 
prepareModel(const nn::Model & model,nn::ExecutionPreference preference,nn::Priority priority,nn::OptionalTimePoint deadline,const std::vector<nn::SharedHandle> & modelCache,const std::vector<nn::SharedHandle> & dataCache,const nn::CacheToken & token) const187 nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModel(
188         const nn::Model& model, nn::ExecutionPreference preference, nn::Priority priority,
189         nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
190         const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token) const {
191     // Ensure that model is ready for IPC.
192     std::optional<nn::Model> maybeModelInShared;
193     const nn::Model& modelInShared =
194             NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));
195 
196     const auto hidlModel = NN_TRY(convert(modelInShared));
197     const auto hidlPreference = NN_TRY(convert(preference));
198     const auto hidlPriority = NN_TRY(convert(priority));
199     const auto hidlDeadline = NN_TRY(convert(deadline));
200     const auto hidlModelCache = NN_TRY(convert(modelCache));
201     const auto hidlDataCache = NN_TRY(convert(dataCache));
202     const auto hidlToken = V1_2::utils::CacheToken{token};
203 
204     const auto cb = sp<PreparedModelCallback>::make();
205     const auto scoped = kDeathHandler.protectCallback(cb.get());
206 
207     const auto ret =
208             kDevice->prepareModel_1_3(hidlModel, hidlPreference, hidlPriority, hidlDeadline,
209                                       hidlModelCache, hidlDataCache, hidlToken, cb);
210     const auto status = HANDLE_TRANSPORT_FAILURE(ret);
211     HANDLE_HAL_STATUS(status) << "model preparation failed with " << toString(status);
212 
213     return cb->get();
214 }
215 
prepareModelFromCache(nn::OptionalTimePoint deadline,const std::vector<nn::SharedHandle> & modelCache,const std::vector<nn::SharedHandle> & dataCache,const nn::CacheToken & token) const216 nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModelFromCache(
217         nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
218         const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token) const {
219     const auto hidlDeadline = NN_TRY(convert(deadline));
220     const auto hidlModelCache = NN_TRY(convert(modelCache));
221     const auto hidlDataCache = NN_TRY(convert(dataCache));
222     const auto hidlToken = V1_2::utils::CacheToken{token};
223 
224     const auto cb = sp<PreparedModelCallback>::make();
225     const auto scoped = kDeathHandler.protectCallback(cb.get());
226 
227     const auto ret = kDevice->prepareModelFromCache_1_3(hidlDeadline, hidlModelCache, hidlDataCache,
228                                                         hidlToken, cb);
229     const auto status = HANDLE_TRANSPORT_FAILURE(ret);
230     HANDLE_HAL_STATUS(status) << "model preparation from cache failed with " << toString(status);
231 
232     return cb->get();
233 }
234 
allocate(const nn::BufferDesc & desc,const std::vector<nn::SharedPreparedModel> & preparedModels,const std::vector<nn::BufferRole> & inputRoles,const std::vector<nn::BufferRole> & outputRoles) const235 nn::GeneralResult<nn::SharedBuffer> Device::allocate(
236         const nn::BufferDesc& desc, const std::vector<nn::SharedPreparedModel>& preparedModels,
237         const std::vector<nn::BufferRole>& inputRoles,
238         const std::vector<nn::BufferRole>& outputRoles) const {
239     const auto hidlDesc = NN_TRY(convert(desc));
240     const auto hidlPreparedModels = NN_TRY(convert(preparedModels));
241     const auto hidlInputRoles = NN_TRY(convert(inputRoles));
242     const auto hidlOutputRoles = NN_TRY(convert(outputRoles));
243 
244     auto cb = hal::utils::CallbackValue(allocationCallback);
245 
246     const auto ret =
247             kDevice->allocate(hidlDesc, hidlPreparedModels, hidlInputRoles, hidlOutputRoles, cb);
248     HANDLE_TRANSPORT_FAILURE(ret);
249 
250     return cb.take();
251 }
252 
253 }  // namespace android::hardware::neuralnetworks::V1_3::utils
254