summaryrefslogtreecommitdiff
path: root/neuralnetworks/aidl/utils/src/Device.cpp
blob: f3f4fdbba1ca8aab11e2282481c915f6a80c3df5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Device.h"

#include "Buffer.h"
#include "Callbacks.h"
#include "Conversions.h"
#include "PreparedModel.h"
#include "ProtectCallback.h"
#include "Utils.h"

#include <aidl/android/hardware/neuralnetworks/IDevice.h>
#include <android/binder_auto_utils.h>
#include <android/binder_interface_utils.h>
#include <nnapi/IBuffer.h>
#include <nnapi/IDevice.h>
#include <nnapi/IPreparedModel.h>
#include <nnapi/OperandTypes.h>
#include <nnapi/Result.h>
#include <nnapi/Types.h>
#include <nnapi/hal/CommonUtils.h>

#include <any>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <vector>

// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface
// lifetimes across processes and for protecting asynchronous calls across AIDL.

namespace aidl::android::hardware::neuralnetworks::utils {

namespace {

nn::GeneralResult<std::vector<std::shared_ptr<IPreparedModel>>> convert(
        const std::vector<nn::SharedPreparedModel>& preparedModels) {
    std::vector<std::shared_ptr<IPreparedModel>> aidlPreparedModels(preparedModels.size());
    for (size_t i = 0; i < preparedModels.size(); ++i) {
        std::any underlyingResource = preparedModels[i]->getUnderlyingResource();
        if (const auto* aidlPreparedModel =
                    std::any_cast<std::shared_ptr<aidl_hal::IPreparedModel>>(&underlyingResource)) {
            aidlPreparedModels[i] = *aidlPreparedModel;
        } else {
            return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
                   << "Unable to convert from nn::IPreparedModel to aidl_hal::IPreparedModel";
        }
    }
    return aidlPreparedModels;
}

nn::GeneralResult<nn::Capabilities> getCapabilitiesFrom(IDevice* device) {
    CHECK(device != nullptr);
    Capabilities capabilities;
    const auto ret = device->getCapabilities(&capabilities);
    HANDLE_ASTATUS(ret) << "getCapabilities failed";
    return nn::convert(capabilities);
}

nn::GeneralResult<std::string> getVersionStringFrom(aidl_hal::IDevice* device) {
    CHECK(device != nullptr);
    std::string version;
    const auto ret = device->getVersionString(&version);
    HANDLE_ASTATUS(ret) << "getVersionString failed";
    return version;
}

nn::GeneralResult<nn::DeviceType> getDeviceTypeFrom(aidl_hal::IDevice* device) {
    CHECK(device != nullptr);
    DeviceType deviceType;
    const auto ret = device->getType(&deviceType);
    HANDLE_ASTATUS(ret) << "getDeviceType failed";
    return nn::convert(deviceType);
}

nn::GeneralResult<std::vector<nn::Extension>> getSupportedExtensionsFrom(
        aidl_hal::IDevice* device) {
    CHECK(device != nullptr);
    std::vector<Extension> supportedExtensions;
    const auto ret = device->getSupportedExtensions(&supportedExtensions);
    HANDLE_ASTATUS(ret) << "getExtensions failed";
    return nn::convert(supportedExtensions);
}

nn::GeneralResult<std::pair<uint32_t, uint32_t>> getNumberOfCacheFilesNeededFrom(
        aidl_hal::IDevice* device) {
    CHECK(device != nullptr);
    NumberOfCacheFiles numberOfCacheFiles;
    const auto ret = device->getNumberOfCacheFilesNeeded(&numberOfCacheFiles);
    HANDLE_ASTATUS(ret) << "getNumberOfCacheFilesNeeded failed";

    if (numberOfCacheFiles.numDataCache < 0 || numberOfCacheFiles.numModelCache < 0) {
        return NN_ERROR() << "Driver reported negative numer of cache files needed";
    }
    if (static_cast<uint32_t>(numberOfCacheFiles.numModelCache) > nn::kMaxNumberOfCacheFiles) {
        return NN_ERROR() << "getNumberOfCacheFilesNeeded returned numModelCache files greater "
                             "than allowed max ("
                          << numberOfCacheFiles.numModelCache << " vs "
                          << nn::kMaxNumberOfCacheFiles << ")";
    }
    if (static_cast<uint32_t>(numberOfCacheFiles.numDataCache) > nn::kMaxNumberOfCacheFiles) {
        return NN_ERROR() << "getNumberOfCacheFilesNeeded returned numDataCache files greater "
                             "than allowed max ("
                          << numberOfCacheFiles.numDataCache << " vs " << nn::kMaxNumberOfCacheFiles
                          << ")";
    }
    return std::make_pair(numberOfCacheFiles.numModelCache, numberOfCacheFiles.numDataCache);
}

}  // namespace

nn::GeneralResult<std::shared_ptr<const Device>> Device::create(
        std::string name, std::shared_ptr<aidl_hal::IDevice> device, nn::Version featureLevel) {
    if (name.empty()) {
        return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
               << "aidl_hal::utils::Device::create must have non-empty name";
    }
    if (device == nullptr) {
        return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT)
               << "aidl_hal::utils::Device::create must have non-null device";
    }

    auto versionString = NN_TRY(getVersionStringFrom(device.get()));
    const auto deviceType = NN_TRY(getDeviceTypeFrom(device.get()));
    auto extensions = NN_TRY(getSupportedExtensionsFrom(device.get()));
    auto capabilities = NN_TRY(getCapabilitiesFrom(device.get()));
    const auto numberOfCacheFilesNeeded = NN_TRY(getNumberOfCacheFilesNeededFrom(device.get()));

    auto deathHandler = NN_TRY(DeathHandler::create(device));
    return std::make_shared<const Device>(
            PrivateConstructorTag{}, std::move(name), std::move(versionString), featureLevel,
            deviceType, std::move(extensions), std::move(capabilities), numberOfCacheFilesNeeded,
            std::move(device), std::move(deathHandler));
}

Device::Device(PrivateConstructorTag /*tag*/, 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)
    : kName(std::move(name)),
      kVersionString(std::move(versionString)),
      kFeatureLevel(featureLevel),
      kDeviceType(deviceType),
      kExtensions(std::move(extensions)),
      kCapabilities(std::move(capabilities)),
      kNumberOfCacheFilesNeeded(numberOfCacheFilesNeeded),
      kDevice(std::move(device)),
      kDeathHandler(std::move(deathHandler)) {}

const std::string& Device::getName() const {
    return kName;
}

const std::string& Device::getVersionString() const {
    return kVersionString;
}

nn::Version Device::getFeatureLevel() const {
    return kFeatureLevel;
}

nn::DeviceType Device::getType() const {
    return kDeviceType;
}

const std::vector<nn::Extension>& Device::getSupportedExtensions() const {
    return kExtensions;
}

const nn::Capabilities& Device::getCapabilities() const {
    return kCapabilities;
}

std::pair<uint32_t, uint32_t> Device::getNumberOfCacheFilesNeeded() const {
    return kNumberOfCacheFilesNeeded;
}

nn::GeneralResult<void> Device::wait() const {
    const auto ret = ndk::ScopedAStatus::fromStatus(AIBinder_ping(kDevice->asBinder().get()));
    HANDLE_ASTATUS(ret) << "ping failed";
    return {};
}

nn::GeneralResult<std::vector<bool>> Device::getSupportedOperations(const nn::Model& model) const {
    // Ensure that model is ready for IPC.
    std::optional<nn::Model> maybeModelInShared;
    const nn::Model& modelInShared =
            NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));

    const auto aidlModel = NN_TRY(convert(modelInShared));

    std::vector<bool> supportedOperations;
    const auto ret = kDevice->getSupportedOperations(aidlModel, &supportedOperations);
    HANDLE_ASTATUS(ret) << "getSupportedOperations failed";

    return supportedOperations;
}

nn::GeneralResult<nn::SharedPreparedModel> Device::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) const {
    // Ensure that model is ready for IPC.
    std::optional<nn::Model> maybeModelInShared;
    const nn::Model& modelInShared =
            NN_TRY(hal::utils::flushDataFromPointerToShared(&model, &maybeModelInShared));

    const auto aidlModel = NN_TRY(convert(modelInShared));
    const auto aidlPreference = NN_TRY(convert(preference));
    const auto aidlPriority = NN_TRY(convert(priority));
    const auto aidlDeadline = NN_TRY(convert(deadline));
    auto aidlModelCache = NN_TRY(convert(modelCache));
    auto aidlDataCache = NN_TRY(convert(dataCache));
    const auto aidlToken = NN_TRY(convert(token));

    const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(kFeatureLevel);
    const auto scoped = kDeathHandler.protectCallback(cb.get());

    if (kFeatureLevel.level >= nn::Version::Level::FEATURE_LEVEL_8) {
        auto aidlHints = NN_TRY(convert(hints));
        auto aidlExtensionPrefix = NN_TRY(convert(extensionNameToPrefix));
        const auto ret = kDevice->prepareModelWithConfig(
                aidlModel,
                {aidlPreference, aidlPriority, aidlDeadline, std::move(aidlModelCache),
                 std::move(aidlDataCache), aidlToken, std::move(aidlHints),
                 std::move(aidlExtensionPrefix)},
                cb);
        HANDLE_ASTATUS(ret) << "prepareModel failed";
        return cb->get();
    }
    const auto ret = kDevice->prepareModel(aidlModel, aidlPreference, aidlPriority, aidlDeadline,
                                           aidlModelCache, aidlDataCache, aidlToken, cb);
    HANDLE_ASTATUS(ret) << "prepareModel failed";
    return cb->get();
}

nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModelFromCache(
        nn::OptionalTimePoint deadline, const std::vector<nn::SharedHandle>& modelCache,
        const std::vector<nn::SharedHandle>& dataCache, const nn::CacheToken& token) const {
    const auto aidlDeadline = NN_TRY(convert(deadline));
    const auto aidlModelCache = NN_TRY(convert(modelCache));
    const auto aidlDataCache = NN_TRY(convert(dataCache));
    const auto aidlToken = NN_TRY(convert(token));

    const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(kFeatureLevel);
    const auto scoped = kDeathHandler.protectCallback(cb.get());

    const auto ret = kDevice->prepareModelFromCache(aidlDeadline, aidlModelCache, aidlDataCache,
                                                    aidlToken, cb);
    HANDLE_ASTATUS(ret) << "prepareModelFromCache failed";

    return cb->get();
}

nn::GeneralResult<nn::SharedBuffer> Device::allocate(
        const nn::BufferDesc& desc, const std::vector<nn::SharedPreparedModel>& preparedModels,
        const std::vector<nn::BufferRole>& inputRoles,
        const std::vector<nn::BufferRole>& outputRoles) const {
    const auto aidlDesc = NN_TRY(convert(desc));
    const auto aidlPreparedModels = NN_TRY(convert(preparedModels));
    const auto aidlInputRoles = NN_TRY(convert(inputRoles));
    const auto aidlOutputRoles = NN_TRY(convert(outputRoles));

    std::vector<IPreparedModelParcel> aidlPreparedModelParcels;
    aidlPreparedModelParcels.reserve(aidlPreparedModels.size());
    for (const auto& preparedModel : aidlPreparedModels) {
        aidlPreparedModelParcels.push_back({.preparedModel = preparedModel});
    }

    DeviceBuffer buffer;
    const auto ret = kDevice->allocate(aidlDesc, aidlPreparedModelParcels, aidlInputRoles,
                                       aidlOutputRoles, &buffer);
    HANDLE_ASTATUS(ret) << "IDevice::allocate failed";

    if (buffer.token < 0) {
        return NN_ERROR() << "IDevice::allocate returned negative token";
    }

    return Buffer::create(buffer.buffer, static_cast<nn::Request::MemoryDomainToken>(buffer.token));
}

DeathMonitor* Device::getDeathMonitor() const {
    return kDeathHandler.getDeathMonitor().get();
}

}  // namespace aidl::android::hardware::neuralnetworks::utils