blob: 02ca861b6b21ab5beb914f6d04927e8ae7723afd [file] [log] [blame]
Lev Proleev900c28a2021-01-26 19:40:20 +00001/*
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
47namespace aidl::android::hardware::neuralnetworks::utils {
48
49namespace {
50
51nn::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
67nn::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
75nn::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
83nn::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
91nn::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
100nn::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.numDataCache, numberOfCacheFiles.numModelCache);
123}
124
125} // namespace
126
127nn::GeneralResult<std::shared_ptr<const Device>> Device::create(
128 std::string name, std::shared_ptr<aidl_hal::IDevice> device) {
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), deviceType,
147 std::move(extensions), std::move(capabilities), numberOfCacheFilesNeeded,
148 std::move(device), std::move(deathHandler));
149}
150
151Device::Device(PrivateConstructorTag /*tag*/, std::string name, std::string versionString,
152 nn::DeviceType deviceType, std::vector<nn::Extension> extensions,
153 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 kDeviceType(deviceType),
159 kExtensions(std::move(extensions)),
160 kCapabilities(std::move(capabilities)),
161 kNumberOfCacheFilesNeeded(numberOfCacheFilesNeeded),
162 kDevice(std::move(device)),
163 kDeathHandler(std::move(deathHandler)) {}
164
165const std::string& Device::getName() const {
166 return kName;
167}
168
169const std::string& Device::getVersionString() const {
170 return kVersionString;
171}
172
173nn::Version Device::getFeatureLevel() const {
174 return nn::Version::ANDROID_S;
175}
176
177nn::DeviceType Device::getType() const {
178 return kDeviceType;
179}
180
181bool Device::isUpdatable() const {
182 return false;
183}
184
185const std::vector<nn::Extension>& Device::getSupportedExtensions() const {
186 return kExtensions;
187}
188
189const nn::Capabilities& Device::getCapabilities() const {
190 return kCapabilities;
191}
192
193std::pair<uint32_t, uint32_t> Device::getNumberOfCacheFilesNeeded() const {
194 return kNumberOfCacheFilesNeeded;
195}
196
197nn::GeneralResult<void> Device::wait() const {
198 const auto ret = ndk::ScopedAStatus::fromStatus(AIBinder_ping(kDevice->asBinder().get()));
199 HANDLE_ASTATUS(ret) << "ping failed";
200 return {};
201}
202
203nn::GeneralResult<std::vector<bool>> Device::getSupportedOperations(const nn::Model& model) const {
204 // Ensure that model is ready for IPC.
205 std::optional<nn::Model> maybeModelInShared;
206 const nn::Model& modelInShared =
207 NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));
208
209 const auto aidlModel = NN_TRY(convert(modelInShared));
210
211 std::vector<bool> supportedOperations;
212 const auto ret = kDevice->getSupportedOperations(aidlModel, &supportedOperations);
213 HANDLE_ASTATUS(ret) << "getSupportedOperations failed";
214
215 return supportedOperations;
216}
217
218nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModel(
219 const nn::Model& model, nn::ExecutionPreference preference, nn::Priority priority,
220 nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
221 const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token) const {
222 // Ensure that model is ready for IPC.
223 std::optional<nn::Model> maybeModelInShared;
224 const nn::Model& modelInShared =
225 NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));
226
227 const auto aidlModel = NN_TRY(convert(modelInShared));
228 const auto aidlPreference = NN_TRY(convert(preference));
229 const auto aidlPriority = NN_TRY(convert(priority));
230 const auto aidlDeadline = NN_TRY(convert(deadline));
231 const auto aidlModelCache = NN_TRY(convert(modelCache));
232 const auto aidlDataCache = NN_TRY(convert(dataCache));
233 const auto aidlToken = NN_TRY(convert(token));
234
235 const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>();
236 const auto scoped = kDeathHandler.protectCallback(cb.get());
237
238 const auto ret = kDevice->prepareModel(aidlModel, aidlPreference, aidlPriority, aidlDeadline,
239 aidlModelCache, aidlDataCache, aidlToken, cb);
240 HANDLE_ASTATUS(ret) << "prepareModel failed";
241
242 return cb->get();
243}
244
245nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModelFromCache(
246 nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
247 const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token) const {
248 const auto aidlDeadline = NN_TRY(convert(deadline));
249 const auto aidlModelCache = NN_TRY(convert(modelCache));
250 const auto aidlDataCache = NN_TRY(convert(dataCache));
251 const auto aidlToken = NN_TRY(convert(token));
252
253 const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>();
254 const auto scoped = kDeathHandler.protectCallback(cb.get());
255
256 const auto ret = kDevice->prepareModelFromCache(aidlDeadline, aidlModelCache, aidlDataCache,
257 aidlToken, cb);
258 HANDLE_ASTATUS(ret) << "prepareModelFromCache failed";
259
260 return cb->get();
261}
262
263nn::GeneralResult<nn::SharedBuffer> Device::allocate(
264 const nn::BufferDesc& desc, const std::vector<nn::SharedPreparedModel>& preparedModels,
265 const std::vector<nn::BufferRole>& inputRoles,
266 const std::vector<nn::BufferRole>& outputRoles) const {
267 const auto aidlDesc = NN_TRY(convert(desc));
268 const auto aidlPreparedModels = NN_TRY(convert(preparedModels));
269 const auto aidlInputRoles = NN_TRY(convert(inputRoles));
270 const auto aidlOutputRoles = NN_TRY(convert(outputRoles));
271
272 std::vector<IPreparedModelParcel> aidlPreparedModelParcels;
273 aidlPreparedModelParcels.reserve(aidlPreparedModels.size());
274 for (const auto& preparedModel : aidlPreparedModels) {
275 aidlPreparedModelParcels.push_back({.preparedModel = preparedModel});
276 }
277
278 DeviceBuffer buffer;
279 const auto ret = kDevice->allocate(aidlDesc, aidlPreparedModelParcels, aidlInputRoles,
280 aidlOutputRoles, &buffer);
281 HANDLE_ASTATUS(ret) << "IDevice::allocate failed";
282
283 if (buffer.token < 0) {
284 return NN_ERROR() << "IDevice::allocate returned negative token";
285 }
286
287 return Buffer::create(buffer.buffer, static_cast<nn::Request::MemoryDomainToken>(buffer.token));
288}
289
290DeathMonitor* Device::getDeathMonitor() const {
291 return kDeathHandler.getDeathMonitor().get();
292}
293
294} // namespace aidl::android::hardware::neuralnetworks::utils