blob: 5b7ec4ebd79b5ff41a02f7c2a4ea0b822f90fdff [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 }
Lev Proleev3fd4ec42021-06-28 13:10:54 +0100122 return std::make_pair(numberOfCacheFiles.numModelCache, numberOfCacheFiles.numDataCache);
Lev Proleev900c28a2021-01-26 19:40:20 +0000123}
124
125} // namespace
126
127nn::GeneralResult<std::shared_ptr<const Device>> Device::create(
Xusong Wang9763a952021-10-05 10:07:12 -0700128 std::string name, std::shared_ptr<aidl_hal::IDevice> device, nn::Version featureLevel) {
Lev Proleev900c28a2021-01-26 19:40:20 +0000129 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>(
Xusong Wang9763a952021-10-05 10:07:12 -0700146 PrivateConstructorTag{}, std::move(name), std::move(versionString), featureLevel,
147 deviceType, std::move(extensions), std::move(capabilities), numberOfCacheFilesNeeded,
Lev Proleev900c28a2021-01-26 19:40:20 +0000148 std::move(device), std::move(deathHandler));
149}
150
151Device::Device(PrivateConstructorTag /*tag*/, std::string name, std::string versionString,
Xusong Wang9763a952021-10-05 10:07:12 -0700152 nn::Version featureLevel, nn::DeviceType deviceType,
153 std::vector<nn::Extension> extensions, nn::Capabilities capabilities,
Lev Proleev900c28a2021-01-26 19:40:20 +0000154 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)),
Xusong Wang9763a952021-10-05 10:07:12 -0700158 kFeatureLevel(featureLevel),
Lev Proleev900c28a2021-01-26 19:40:20 +0000159 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
166const std::string& Device::getName() const {
167 return kName;
168}
169
170const std::string& Device::getVersionString() const {
171 return kVersionString;
172}
173
174nn::Version Device::getFeatureLevel() const {
Xusong Wang9763a952021-10-05 10:07:12 -0700175 return kFeatureLevel;
Lev Proleev900c28a2021-01-26 19:40:20 +0000176}
177
178nn::DeviceType Device::getType() const {
179 return kDeviceType;
180}
181
Lev Proleev900c28a2021-01-26 19:40:20 +0000182const std::vector<nn::Extension>& Device::getSupportedExtensions() const {
183 return kExtensions;
184}
185
186const nn::Capabilities& Device::getCapabilities() const {
187 return kCapabilities;
188}
189
190std::pair<uint32_t, uint32_t> Device::getNumberOfCacheFilesNeeded() const {
191 return kNumberOfCacheFilesNeeded;
192}
193
194nn::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
200nn::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
215nn::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) const {
219 // Ensure that model is ready for IPC.
220 std::optional<nn::Model> maybeModelInShared;
221 const nn::Model& modelInShared =
222 NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));
223
224 const auto aidlModel = NN_TRY(convert(modelInShared));
225 const auto aidlPreference = NN_TRY(convert(preference));
226 const auto aidlPriority = NN_TRY(convert(priority));
227 const auto aidlDeadline = NN_TRY(convert(deadline));
228 const auto aidlModelCache = NN_TRY(convert(modelCache));
229 const auto aidlDataCache = NN_TRY(convert(dataCache));
230 const auto aidlToken = NN_TRY(convert(token));
231
232 const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>();
233 const auto scoped = kDeathHandler.protectCallback(cb.get());
234
235 const auto ret = kDevice->prepareModel(aidlModel, aidlPreference, aidlPriority, aidlDeadline,
236 aidlModelCache, aidlDataCache, aidlToken, cb);
237 HANDLE_ASTATUS(ret) << "prepareModel failed";
238
239 return cb->get();
240}
241
242nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModelFromCache(
243 nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
244 const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token) const {
245 const auto aidlDeadline = NN_TRY(convert(deadline));
246 const auto aidlModelCache = NN_TRY(convert(modelCache));
247 const auto aidlDataCache = NN_TRY(convert(dataCache));
248 const auto aidlToken = NN_TRY(convert(token));
249
250 const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>();
251 const auto scoped = kDeathHandler.protectCallback(cb.get());
252
253 const auto ret = kDevice->prepareModelFromCache(aidlDeadline, aidlModelCache, aidlDataCache,
254 aidlToken, cb);
255 HANDLE_ASTATUS(ret) << "prepareModelFromCache failed";
256
257 return cb->get();
258}
259
260nn::GeneralResult<nn::SharedBuffer> Device::allocate(
261 const nn::BufferDesc& desc, const std::vector<nn::SharedPreparedModel>& preparedModels,
262 const std::vector<nn::BufferRole>& inputRoles,
263 const std::vector<nn::BufferRole>& outputRoles) const {
264 const auto aidlDesc = NN_TRY(convert(desc));
265 const auto aidlPreparedModels = NN_TRY(convert(preparedModels));
266 const auto aidlInputRoles = NN_TRY(convert(inputRoles));
267 const auto aidlOutputRoles = NN_TRY(convert(outputRoles));
268
269 std::vector<IPreparedModelParcel> aidlPreparedModelParcels;
270 aidlPreparedModelParcels.reserve(aidlPreparedModels.size());
271 for (const auto& preparedModel : aidlPreparedModels) {
272 aidlPreparedModelParcels.push_back({.preparedModel = preparedModel});
273 }
274
275 DeviceBuffer buffer;
276 const auto ret = kDevice->allocate(aidlDesc, aidlPreparedModelParcels, aidlInputRoles,
277 aidlOutputRoles, &buffer);
278 HANDLE_ASTATUS(ret) << "IDevice::allocate failed";
279
280 if (buffer.token < 0) {
281 return NN_ERROR() << "IDevice::allocate returned negative token";
282 }
283
284 return Buffer::create(buffer.buffer, static_cast<nn::Request::MemoryDomainToken>(buffer.token));
285}
286
287DeathMonitor* Device::getDeathMonitor() const {
288 return kDeathHandler.getDeathMonitor().get();
289}
290
291} // namespace aidl::android::hardware::neuralnetworks::utils