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 #include "Device.h"
18
19 #include "Buffer.h"
20 #include "Callbacks.h"
21 #include "Conversions.h"
22 #include "PreparedModel.h"
23 #include "ProtectCallback.h"
24 #include "Utils.h"
25
26 #include <aidl/android/hardware/neuralnetworks/IDevice.h>
27 #include <android/binder_auto_utils.h>
28 #include <android/binder_interface_utils.h>
29 #include <nnapi/IBuffer.h>
30 #include <nnapi/IDevice.h>
31 #include <nnapi/IPreparedModel.h>
32 #include <nnapi/OperandTypes.h>
33 #include <nnapi/Result.h>
34 #include <nnapi/Types.h>
35 #include <nnapi/hal/CommonUtils.h>
36
37 #include <any>
38 #include <functional>
39 #include <memory>
40 #include <optional>
41 #include <string>
42 #include <vector>
43
44 // See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface
45 // lifetimes across processes and for protecting asynchronous calls across AIDL.
46
47 namespace aidl::android::hardware::neuralnetworks::utils {
48
49 namespace {
50
convert(const std::vector<nn::SharedPreparedModel> & preparedModels)51 nn::GeneralResult<std::vector<std::shared_ptr<IPreparedModel>>> convert(
52 const std::vector<nn::SharedPreparedModel>& preparedModels) {
53 std::vector<std::shared_ptr<IPreparedModel>> aidlPreparedModels(preparedModels.size());
54 for (size_t i = 0; i < preparedModels.size(); ++i) {
55 std::any underlyingResource = preparedModels[i]->getUnderlyingResource();
56 if (const auto* aidlPreparedModel =
57 std::any_cast<std::shared_ptr<aidl_hal::IPreparedModel>>(&underlyingResource)) {
58 aidlPreparedModels[i] = *aidlPreparedModel;
59 } else {
60 return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
61 << "Unable to convert from nn::IPreparedModel to aidl_hal::IPreparedModel";
62 }
63 }
64 return aidlPreparedModels;
65 }
66
getCapabilitiesFrom(IDevice * device)67 nn::GeneralResult<nn::Capabilities> getCapabilitiesFrom(IDevice* device) {
68 CHECK(device != nullptr);
69 Capabilities capabilities;
70 const auto ret = device->getCapabilities(&capabilities);
71 HANDLE_ASTATUS(ret) << "getCapabilities failed";
72 return nn::convert(capabilities);
73 }
74
getVersionStringFrom(aidl_hal::IDevice * device)75 nn::GeneralResult<std::string> getVersionStringFrom(aidl_hal::IDevice* device) {
76 CHECK(device != nullptr);
77 std::string version;
78 const auto ret = device->getVersionString(&version);
79 HANDLE_ASTATUS(ret) << "getVersionString failed";
80 return version;
81 }
82
getDeviceTypeFrom(aidl_hal::IDevice * device)83 nn::GeneralResult<nn::DeviceType> getDeviceTypeFrom(aidl_hal::IDevice* device) {
84 CHECK(device != nullptr);
85 DeviceType deviceType;
86 const auto ret = device->getType(&deviceType);
87 HANDLE_ASTATUS(ret) << "getDeviceType failed";
88 return nn::convert(deviceType);
89 }
90
getSupportedExtensionsFrom(aidl_hal::IDevice * device)91 nn::GeneralResult<std::vector<nn::Extension>> getSupportedExtensionsFrom(
92 aidl_hal::IDevice* device) {
93 CHECK(device != nullptr);
94 std::vector<Extension> supportedExtensions;
95 const auto ret = device->getSupportedExtensions(&supportedExtensions);
96 HANDLE_ASTATUS(ret) << "getExtensions failed";
97 return nn::convert(supportedExtensions);
98 }
99
getNumberOfCacheFilesNeededFrom(aidl_hal::IDevice * device)100 nn::GeneralResult<std::pair<uint32_t, uint32_t>> getNumberOfCacheFilesNeededFrom(
101 aidl_hal::IDevice* device) {
102 CHECK(device != nullptr);
103 NumberOfCacheFiles numberOfCacheFiles;
104 const auto ret = device->getNumberOfCacheFilesNeeded(&numberOfCacheFiles);
105 HANDLE_ASTATUS(ret) << "getNumberOfCacheFilesNeeded failed";
106
107 if (numberOfCacheFiles.numDataCache < 0 || numberOfCacheFiles.numModelCache < 0) {
108 return NN_ERROR() << "Driver reported negative numer of cache files needed";
109 }
110 if (static_cast<uint32_t>(numberOfCacheFiles.numModelCache) > nn::kMaxNumberOfCacheFiles) {
111 return NN_ERROR() << "getNumberOfCacheFilesNeeded returned numModelCache files greater "
112 "than allowed max ("
113 << numberOfCacheFiles.numModelCache << " vs "
114 << nn::kMaxNumberOfCacheFiles << ")";
115 }
116 if (static_cast<uint32_t>(numberOfCacheFiles.numDataCache) > nn::kMaxNumberOfCacheFiles) {
117 return NN_ERROR() << "getNumberOfCacheFilesNeeded returned numDataCache files greater "
118 "than allowed max ("
119 << numberOfCacheFiles.numDataCache << " vs " << nn::kMaxNumberOfCacheFiles
120 << ")";
121 }
122 return std::make_pair(numberOfCacheFiles.numModelCache, numberOfCacheFiles.numDataCache);
123 }
124
125 } // namespace
126
create(std::string name,std::shared_ptr<aidl_hal::IDevice> device,nn::Version featureLevel)127 nn::GeneralResult<std::shared_ptr<const Device>> Device::create(
128 std::string name, std::shared_ptr<aidl_hal::IDevice> device, nn::Version featureLevel) {
129 if (name.empty()) {
130 return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
131 << "aidl_hal::utils::Device::create must have non-empty name";
132 }
133 if (device == nullptr) {
134 return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
135 << "aidl_hal::utils::Device::create must have non-null device";
136 }
137
138 auto versionString = NN_TRY(getVersionStringFrom(device.get()));
139 const auto deviceType = NN_TRY(getDeviceTypeFrom(device.get()));
140 auto extensions = NN_TRY(getSupportedExtensionsFrom(device.get()));
141 auto capabilities = NN_TRY(getCapabilitiesFrom(device.get()));
142 const auto numberOfCacheFilesNeeded = NN_TRY(getNumberOfCacheFilesNeededFrom(device.get()));
143
144 auto deathHandler = NN_TRY(DeathHandler::create(device));
145 return std::make_shared<const Device>(
146 PrivateConstructorTag{}, std::move(name), std::move(versionString), featureLevel,
147 deviceType, std::move(extensions), std::move(capabilities), numberOfCacheFilesNeeded,
148 std::move(device), std::move(deathHandler));
149 }
150
Device(PrivateConstructorTag,std::string name,std::string versionString,nn::Version featureLevel,nn::DeviceType deviceType,std::vector<nn::Extension> extensions,nn::Capabilities capabilities,std::pair<uint32_t,uint32_t> numberOfCacheFilesNeeded,std::shared_ptr<aidl_hal::IDevice> device,DeathHandler deathHandler)151 Device::Device(PrivateConstructorTag /*tag*/, std::string name, std::string versionString,
152 nn::Version featureLevel, nn::DeviceType deviceType,
153 std::vector<nn::Extension> extensions, nn::Capabilities capabilities,
154 std::pair<uint32_t, uint32_t> numberOfCacheFilesNeeded,
155 std::shared_ptr<aidl_hal::IDevice> device, DeathHandler deathHandler)
156 : kName(std::move(name)),
157 kVersionString(std::move(versionString)),
158 kFeatureLevel(featureLevel),
159 kDeviceType(deviceType),
160 kExtensions(std::move(extensions)),
161 kCapabilities(std::move(capabilities)),
162 kNumberOfCacheFilesNeeded(numberOfCacheFilesNeeded),
163 kDevice(std::move(device)),
164 kDeathHandler(std::move(deathHandler)) {}
165
getName() const166 const std::string& Device::getName() const {
167 return kName;
168 }
169
getVersionString() const170 const std::string& Device::getVersionString() const {
171 return kVersionString;
172 }
173
getFeatureLevel() const174 nn::Version Device::getFeatureLevel() const {
175 return kFeatureLevel;
176 }
177
getType() const178 nn::DeviceType Device::getType() const {
179 return kDeviceType;
180 }
181
getSupportedExtensions() const182 const std::vector<nn::Extension>& Device::getSupportedExtensions() const {
183 return kExtensions;
184 }
185
getCapabilities() const186 const nn::Capabilities& Device::getCapabilities() const {
187 return kCapabilities;
188 }
189
getNumberOfCacheFilesNeeded() const190 std::pair<uint32_t, uint32_t> Device::getNumberOfCacheFilesNeeded() const {
191 return kNumberOfCacheFilesNeeded;
192 }
193
wait() const194 nn::GeneralResult<void> Device::wait() const {
195 const auto ret = ndk::ScopedAStatus::fromStatus(AIBinder_ping(kDevice->asBinder().get()));
196 HANDLE_ASTATUS(ret) << "ping failed";
197 return {};
198 }
199
getSupportedOperations(const nn::Model & model) const200 nn::GeneralResult<std::vector<bool>> Device::getSupportedOperations(const nn::Model& model) const {
201 // Ensure that model is ready for IPC.
202 std::optional<nn::Model> maybeModelInShared;
203 const nn::Model& modelInShared =
204 NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));
205
206 const auto aidlModel = NN_TRY(convert(modelInShared));
207
208 std::vector<bool> supportedOperations;
209 const auto ret = kDevice->getSupportedOperations(aidlModel, &supportedOperations);
210 HANDLE_ASTATUS(ret) << "getSupportedOperations failed";
211
212 return supportedOperations;
213 }
214
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,const std::vector<nn::TokenValuePair> & hints,const std::vector<nn::ExtensionNameAndPrefix> & extensionNameToPrefix) const215 nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModel(
216 const nn::Model& model, nn::ExecutionPreference preference, nn::Priority priority,
217 nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
218 const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token,
219 const std::vector<nn::TokenValuePair>& hints,
220 const std::vector<nn::ExtensionNameAndPrefix>& extensionNameToPrefix) const {
221 // Ensure that model is ready for IPC.
222 std::optional<nn::Model> maybeModelInShared;
223 const nn::Model& modelInShared =
224 NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));
225
226 const auto aidlModel = NN_TRY(convert(modelInShared));
227 const auto aidlPreference = NN_TRY(convert(preference));
228 const auto aidlPriority = NN_TRY(convert(priority));
229 const auto aidlDeadline = NN_TRY(convert(deadline));
230 auto aidlModelCache = NN_TRY(convert(modelCache));
231 auto aidlDataCache = NN_TRY(convert(dataCache));
232
233 const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(kFeatureLevel);
234 const auto scoped = kDeathHandler.protectCallback(cb.get());
235
236 if (kFeatureLevel.level >= nn::Version::Level::FEATURE_LEVEL_8) {
237 auto aidlHints = NN_TRY(convert(hints));
238 auto aidlExtensionPrefix = NN_TRY(convert(extensionNameToPrefix));
239 const auto ret = kDevice->prepareModelWithConfig(
240 aidlModel,
241 {aidlPreference, aidlPriority, aidlDeadline, std::move(aidlModelCache),
242 std::move(aidlDataCache), token, std::move(aidlHints),
243 std::move(aidlExtensionPrefix)},
244 cb);
245 HANDLE_ASTATUS(ret) << "prepareModel failed";
246 return cb->get();
247 }
248 const auto aidlToken = NN_TRY(convert(token));
249 const auto ret = kDevice->prepareModel(aidlModel, aidlPreference, aidlPriority, aidlDeadline,
250 aidlModelCache, aidlDataCache, aidlToken, cb);
251 HANDLE_ASTATUS(ret) << "prepareModel failed";
252 return cb->get();
253 }
254
prepareModelFromCache(nn::OptionalTimePoint deadline,const std::vector<nn::SharedHandle> & modelCache,const std::vector<nn::SharedHandle> & dataCache,const nn::CacheToken & token) const255 nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModelFromCache(
256 nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
257 const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token) const {
258 const auto aidlDeadline = NN_TRY(convert(deadline));
259 const auto aidlModelCache = NN_TRY(convert(modelCache));
260 const auto aidlDataCache = NN_TRY(convert(dataCache));
261 const auto aidlToken = NN_TRY(convert(token));
262
263 const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(kFeatureLevel);
264 const auto scoped = kDeathHandler.protectCallback(cb.get());
265
266 const auto ret = kDevice->prepareModelFromCache(aidlDeadline, aidlModelCache, aidlDataCache,
267 aidlToken, cb);
268 HANDLE_ASTATUS(ret) << "prepareModelFromCache failed";
269
270 return cb->get();
271 }
272
allocate(const nn::BufferDesc & desc,const std::vector<nn::SharedPreparedModel> & preparedModels,const std::vector<nn::BufferRole> & inputRoles,const std::vector<nn::BufferRole> & outputRoles) const273 nn::GeneralResult<nn::SharedBuffer> Device::allocate(
274 const nn::BufferDesc& desc, const std::vector<nn::SharedPreparedModel>& preparedModels,
275 const std::vector<nn::BufferRole>& inputRoles,
276 const std::vector<nn::BufferRole>& outputRoles) const {
277 const auto aidlDesc = NN_TRY(convert(desc));
278 const auto aidlPreparedModels = NN_TRY(convert(preparedModels));
279 const auto aidlInputRoles = NN_TRY(convert(inputRoles));
280 const auto aidlOutputRoles = NN_TRY(convert(outputRoles));
281
282 std::vector<IPreparedModelParcel> aidlPreparedModelParcels;
283 aidlPreparedModelParcels.reserve(aidlPreparedModels.size());
284 for (const auto& preparedModel : aidlPreparedModels) {
285 aidlPreparedModelParcels.push_back({.preparedModel = preparedModel});
286 }
287
288 DeviceBuffer buffer;
289 const auto ret = kDevice->allocate(aidlDesc, aidlPreparedModelParcels, aidlInputRoles,
290 aidlOutputRoles, &buffer);
291 HANDLE_ASTATUS(ret) << "IDevice::allocate failed";
292
293 if (buffer.token < 0) {
294 return NN_ERROR() << "IDevice::allocate returned negative token";
295 }
296
297 return Buffer::create(buffer.buffer, static_cast<nn::Request::MemoryDomainToken>(buffer.token));
298 }
299
getDeathMonitor() const300 DeathMonitor* Device::getDeathMonitor() const {
301 return kDeathHandler.getDeathMonitor().get();
302 }
303
304 } // namespace aidl::android::hardware::neuralnetworks::utils
305