blob: 33f3ab74483de999fce9188b138530b2fbba513c [file] [log] [blame]
Jean-Luc Brouillet4fb1e852017-08-20 18:16:36 -07001/*
2 * Copyright (C) 2017 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#define LOG_TAG "Memory"
18
19#include "Memory.h"
20
Slava Shklyaevc958cd82020-12-10 16:55:55 +000021#include <CpuExecutor.h>
Slava Shklyaevc958cd82020-12-10 16:55:55 +000022#include <LegacyUtils.h>
Xusong Wang1b836a22020-02-06 13:17:33 -080023#include <android-base/scopeguard.h>
Michael Butlerc4c57d92021-02-11 20:09:15 -080024#include <android/hardware_buffer.h>
Michael Butler7d1ae272021-02-17 18:00:31 -080025#include <nnapi/IBurst.h>
Slava Shklyaev3698ad42020-11-06 13:50:31 +000026#include <nnapi/SharedMemory.h>
27#include <nnapi/TypeUtils.h>
28#include <nnapi/Types.h>
Xusong Wang1b836a22020-02-06 13:17:33 -080029
Xusong Wang062ec502019-11-27 11:44:03 -080030#include <algorithm>
Michael Butler90fddbd2019-08-02 15:04:00 -070031#include <memory>
Xusong Wang062ec502019-11-27 11:44:03 -080032#include <set>
33#include <tuple>
Michael Butler90fddbd2019-08-02 15:04:00 -070034#include <utility>
Xusong Wang062ec502019-11-27 11:44:03 -080035#include <vector>
36
37#include "CompilationBuilder.h"
Xusong Wang550e2a52019-11-27 12:18:19 -080038#include "Manager.h"
Xusong Wang062ec502019-11-27 11:44:03 -080039#include "TypeManager.h"
Slava Shklyaevc958cd82020-12-10 16:55:55 +000040
Jean-Luc Brouillet4fb1e852017-08-20 18:16:36 -070041namespace android {
42namespace nn {
Xusong Wangd39f9192019-11-27 15:45:42 -080043namespace {
44
45// The validator for a client-managed single-dimensional memory pool with a known size.
46// The memory may be used for request inputs, request outputs, or model constants.
47class SizedMemoryValidator : public MemoryValidatorBase {
48 public:
Michael Butlerb3082a52021-02-07 00:10:23 -080049 explicit SizedMemoryValidator(uint32_t size) : kSize(size) {}
Xusong Wangd39f9192019-11-27 15:45:42 -080050
51 bool validate(const CompilationBuilder*, IOType, uint32_t, const ANeuralNetworksOperandType*,
52 uint32_t offset, uint32_t length) const override {
53 NN_RET_CHECK(offset + length <= kSize) << "request size larger than the memory size.";
54 NN_RET_CHECK(offset != 0 || length != 0) << "memory size cannot be implied.";
55 return true;
56 }
57
Xusong Wang52b860b2019-11-27 16:23:36 -080058 Metadata getMetadata() const override { return {.logicalSize = kSize}; }
59 bool updateMetadata(const Metadata& metadata) override {
60 return metadata.logicalSize == 0 || metadata.logicalSize == kSize;
61 }
62
Xusong Wangd39f9192019-11-27 15:45:42 -080063 private:
64 const uint32_t kSize;
65};
66
67// The validator for an AHardwareBuffer with Non-BLOB format.
68// We require the memory only used for request inputs or request outputs,
69// with both offset and length set to zero.
70class AHardwareBufferNonBlobValidator : public MemoryValidatorBase {
71 public:
72 AHardwareBufferNonBlobValidator() = default;
73
74 bool validate(const CompilationBuilder* compilation, IOType, uint32_t,
75 const ANeuralNetworksOperandType*, uint32_t offset,
76 uint32_t length) const override {
77 NN_RET_CHECK(compilation != nullptr)
78 << "cannot use Non-BLOB AHardwareBuffer as model constant";
79 NN_RET_CHECK(offset == 0 && length == 0)
80 << "non-zero offset (" << offset << ") and/or length (" << length
81 << ") for Non-BLOB format AHardwareBuffer.";
82 return true;
83 }
Xusong Wang52b860b2019-11-27 16:23:36 -080084
85 Metadata getMetadata() const override { return {}; }
86 bool updateMetadata(const Metadata&) override { return true; }
Xusong Wangd39f9192019-11-27 15:45:42 -080087};
88
89// The validator for a memory created from ANNMemory_createFromDesc.
90// We require the memory only used as one of the pre-specified roles,
91// with both offset and length set to zero.
92class DeviceMemoryValidator : public MemoryValidatorBase {
93 public:
Xusong Wang52b860b2019-11-27 16:23:36 -080094 DeviceMemoryValidator(std::set<CompilationRole> roles, Operand operand,
Xusong Wangd39f9192019-11-27 15:45:42 -080095 std::vector<uint32_t> dimensions)
96 : kCompilationRoles(std::move(roles)),
Xusong Wang52b860b2019-11-27 16:23:36 -080097 kOperand(std::move(operand)),
Xusong Wangd39f9192019-11-27 15:45:42 -080098 kInitialDimensions(std::move(dimensions)),
99 mUpdatedDimensions(kInitialDimensions) {}
100
101 bool validate(const CompilationBuilder* compilation, IOType ioType, uint32_t index,
102 const ANeuralNetworksOperandType* type, uint32_t offset,
103 uint32_t length) const override {
104 NN_RET_CHECK(kCompilationRoles.count({compilation, ioType, index}) > 0)
105 << "invalid compilation role.";
106 NN_RET_CHECK(offset == 0 && length == 0)
107 << "non-zero offset and/or length for driver-allocated memory.";
108 if (type) {
Xusong Wang52b860b2019-11-27 16:23:36 -0800109 const bool isTensor = TypeManager::get()->isTensorType(kOperand.type);
Xusong Wangd39f9192019-11-27 15:45:42 -0800110 NN_RET_CHECK(isTensor || type->dimensionCount == 0)
111 << "invalid dimensions for scalar memory.";
112 std::vector<uint32_t> dimensions(type->dimensions,
113 type->dimensions + type->dimensionCount);
114 // We only check against kInitialDimensions here.
115 // For input memories, mUpdatedDimensions will be checked in validateInputDimensions
116 // at the beginning of a computation.
117 const auto combined = combineDimensions(dimensions, kInitialDimensions);
118 NN_RET_CHECK(combined.has_value())
119 << "incompatible dimensions between request and memory. (request: "
120 << toString(dimensions) << ", memory: " << toString(kInitialDimensions) << ")";
121 }
122 return true;
123 }
124
125 bool validateInputDimensions(const std::vector<uint32_t>& dimensions) const override {
126 NN_RET_CHECK(mInitialized) << "using an uninitialized memory as input";
127 NN_RET_CHECK(dimensions == mUpdatedDimensions)
128 << "incompatible input dimensions between request and memory. (request: "
129 << toString(dimensions) << ", memory: " << toString(mUpdatedDimensions) << ")";
130 return true;
131 }
132
Xusong Wang52b860b2019-11-27 16:23:36 -0800133 Metadata getMetadata() const override {
Xusong Wang52b860b2019-11-27 16:23:36 -0800134 return {.logicalSize = TypeManager::get()->getSizeOfData(kOperand.type, mUpdatedDimensions),
135 .dimensions = mUpdatedDimensions,
136 .operand = kOperand};
137 }
138
139 bool updateMetadata(const Metadata& metadata) override {
140 NN_RET_CHECK(!metadata.operand.has_value() ||
141 (metadata.operand->type == kOperand.type &&
142 metadata.operand->scale == kOperand.scale &&
143 metadata.operand->zeroPoint == kOperand.zeroPoint &&
144 metadata.operand->extraParams == kOperand.extraParams));
145
146 NN_RET_CHECK(metadata.dimensions.empty() ||
147 TypeManager::get()->isTensorType(kOperand.type));
148 auto combined = combineDimensions(metadata.dimensions, kInitialDimensions);
Xusong Wangd39f9192019-11-27 15:45:42 -0800149 NN_RET_CHECK(combined.has_value());
Xusong Wang52b860b2019-11-27 16:23:36 -0800150 NN_RET_CHECK(metadata.logicalSize == 0 ||
151 metadata.logicalSize ==
152 TypeManager::get()->getSizeOfData(kOperand.type, combined.value()));
Xusong Wangd39f9192019-11-27 15:45:42 -0800153 mUpdatedDimensions = std::move(combined.value());
154 return true;
155 }
156
Xusong Wangb3f9c622020-02-20 12:37:51 -0800157 bool createdWithUnknownShape() const override {
158 return TypeManager::get()->getSizeOfData(kOperand.type, kInitialDimensions) == 0;
159 }
160
Xusong Wangd39f9192019-11-27 15:45:42 -0800161 void setInitialized(bool initialized) override { mInitialized = initialized; }
Xusong Wang52b860b2019-11-27 16:23:36 -0800162 bool isInitialized() const override { return mInitialized; }
Xusong Wangd39f9192019-11-27 15:45:42 -0800163
164 private:
165 const std::set<CompilationRole> kCompilationRoles;
Xusong Wang52b860b2019-11-27 16:23:36 -0800166
167 // Keep track of the data type, scale, zero point, and extra parameters of the target operand.
168 // Other fields will be ignored, including dimensions, lifetime, location, etc.
169 const Operand kOperand;
Xusong Wangd39f9192019-11-27 15:45:42 -0800170
171 // The dimensions of the memory when the memory object is created.
172 // May have unknown dimensions or rank.
173 const std::vector<uint32_t> kInitialDimensions;
174
175 // The updated dimensions after a successful execution or memory copying.
176 std::vector<uint32_t> mUpdatedDimensions;
177
178 bool mInitialized = false;
179};
180
181} // namespace
182
Michael Butlerb3082a52021-02-07 00:10:23 -0800183RuntimeMemory::RuntimeMemory(SharedMemory memory) : kMemory(std::move(memory)) {
184 CHECK(kMemory != nullptr);
Michael Butler81550a92021-03-25 15:28:52 -0700185 mValidator = std::make_unique<SizedMemoryValidator>(nn::getSize(kMemory));
Michael Butlerb3082a52021-02-07 00:10:23 -0800186}
Xusong Wangd39f9192019-11-27 15:45:42 -0800187
Michael Butlerb3082a52021-02-07 00:10:23 -0800188RuntimeMemory::RuntimeMemory(SharedMemory memory, std::unique_ptr<MemoryValidatorBase> validator)
189 : kMemory(std::move(memory)), mValidator(std::move(validator)) {
190 CHECK(kMemory != nullptr);
191}
Xusong Wangd39f9192019-11-27 15:45:42 -0800192
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000193RuntimeMemory::RuntimeMemory(SharedBuffer buffer) : kBuffer(std::move(buffer)) {}
Xusong Wangd39f9192019-11-27 15:45:42 -0800194
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000195Request::MemoryPool RuntimeMemory::getMemoryPool() const {
196 if (kBuffer != nullptr) {
197 return kBuffer->getToken();
Xusong Wang085d0002020-01-08 16:52:37 -0800198 }
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000199 return kMemory;
Xusong Wang085d0002020-01-08 16:52:37 -0800200}
201
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100202std::optional<RunTimePoolInfo> RuntimeMemory::getRunTimePoolInfo() const {
Xusong Wang13df2032020-02-06 18:24:01 -0800203 std::lock_guard<std::mutex> guard(mMutex);
204 if (!mHasCachedRunTimePoolInfo) {
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000205 mCachedRunTimePoolInfo = RunTimePoolInfo::createFromMemory(kMemory);
Xusong Wang13df2032020-02-06 18:24:01 -0800206 mHasCachedRunTimePoolInfo = true;
207 }
208 return mCachedRunTimePoolInfo;
Slava Shklyaev342358d2020-03-05 18:02:19 +0000209}
210
Michael Butler7d1ae272021-02-17 18:00:31 -0800211void RuntimeMemory::hold(const IBurst::OptionalCacheHold& cacheHold) const {
212 if (cacheHold != nullptr) {
213 std::lock_guard<std::mutex> guard(mMutex);
214 mHold.insert(cacheHold);
215 }
Michael Butler50032c02019-03-14 17:34:48 -0700216}
217
Xusong Wang13df2032020-02-06 18:24:01 -0800218static int copyHidlMemories(const std::optional<RunTimePoolInfo>& src,
219 const std::optional<RunTimePoolInfo>& dst) {
220 if (!src.has_value() || !dst.has_value()) {
Xusong Wang52b860b2019-11-27 16:23:36 -0800221 LOG(ERROR) << "ANeuralNetworksMemory_copy -- unable to map memory";
222 return ANEURALNETWORKS_UNMAPPABLE;
223 }
Xusong Wang13df2032020-02-06 18:24:01 -0800224 if (src->getSize() != dst->getSize()) {
225 LOG(ERROR) << "ANeuralNetworksMemory_copy -- incompatible memory size";
226 return ANEURALNETWORKS_BAD_DATA;
227 }
228 CHECK(src->getBuffer() != nullptr);
229 CHECK(dst->getBuffer() != nullptr);
230 std::copy(src->getBuffer(), src->getBuffer() + src->getSize(), dst->getBuffer());
231 dst->flush();
Xusong Wang52b860b2019-11-27 16:23:36 -0800232 return ANEURALNETWORKS_NO_ERROR;
233}
234
Michael Butlerb3082a52021-02-07 00:10:23 -0800235int copyIBufferToMemory(const SharedBuffer& src, const SharedMemory& dst) {
Xusong Wang52b860b2019-11-27 16:23:36 -0800236 const auto ret = src->copyTo(dst);
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000237 if (!ret.has_value()) {
238 LOG(ERROR) << "ANeuralNetworksMemory_copy failure: " << ret.error().message;
239 return convertErrorStatusToResultCode(ret.error().code);
Xusong Wang52b860b2019-11-27 16:23:36 -0800240 }
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000241 return ANEURALNETWORKS_NO_ERROR;
Xusong Wang52b860b2019-11-27 16:23:36 -0800242}
243
Michael Butlerb3082a52021-02-07 00:10:23 -0800244int copyMemoryToIBuffer(const SharedMemory& src, const SharedBuffer& dst,
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000245 const std::vector<uint32_t>& dimensions) {
Xusong Wang52b860b2019-11-27 16:23:36 -0800246 const auto ret = dst->copyFrom(src, dimensions);
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000247 if (!ret.has_value()) {
248 LOG(ERROR) << "ANeuralNetworksMemory_copy failure: " << ret.error().message;
249 return convertErrorStatusToResultCode(ret.error().code);
Xusong Wang52b860b2019-11-27 16:23:36 -0800250 }
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000251 return ANEURALNETWORKS_NO_ERROR;
Xusong Wang52b860b2019-11-27 16:23:36 -0800252}
253
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000254static int copyIBuffers(const SharedBuffer& src, const SharedBuffer& dst,
Xusong Wang52b860b2019-11-27 16:23:36 -0800255 const MemoryValidatorBase::Metadata& srcMetadata) {
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000256 const auto [n, memoryAHWB] = MemoryRuntimeAHWB::create(srcMetadata.logicalSize);
Xusong Wang1b836a22020-02-06 13:17:33 -0800257 NN_RETURN_IF_ERROR(n);
Michael Butlerb3082a52021-02-07 00:10:23 -0800258 const SharedMemory& memory = memoryAHWB->getMemory();
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000259 if (!validate(memory).ok()) return ANEURALNETWORKS_OUT_OF_MEMORY;
260 NN_RETURN_IF_ERROR(copyIBufferToMemory(src, memory));
261 NN_RETURN_IF_ERROR(copyMemoryToIBuffer(memory, dst, srcMetadata.dimensions));
Xusong Wang52b860b2019-11-27 16:23:36 -0800262 return ANEURALNETWORKS_NO_ERROR;
263}
264
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100265static int copyInternal(const RuntimeMemory& src, const RuntimeMemory& dst) {
Xusong Wang52b860b2019-11-27 16:23:36 -0800266 if (&src == &dst) return ANEURALNETWORKS_NO_ERROR;
267
268 if (!src.getValidator().isInitialized()) {
269 LOG(ERROR) << "ANeuralNetworksMemory_copy -- uninitialized source memory";
270 return ANEURALNETWORKS_BAD_DATA;
271 }
272
273 const auto srcMetadata = src.getValidator().getMetadata();
274 if (!dst.getValidator().updateMetadata(srcMetadata)) {
275 LOG(ERROR) << "ANeuralNetworksMemory_copy -- incompatible memories";
276 return ANEURALNETWORKS_BAD_DATA;
277 }
278
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000279 bool srcHasMemory = validate(src.getMemory()).ok();
280 bool dstHasMemory = validate(dst.getMemory()).ok();
Xusong Wang52b860b2019-11-27 16:23:36 -0800281 bool srcHasIBuffer = src.getIBuffer() != nullptr;
282 bool dstHasIBuffer = dst.getIBuffer() != nullptr;
283 if (srcHasIBuffer && dstHasIBuffer) {
284 return copyIBuffers(src.getIBuffer(), dst.getIBuffer(), srcMetadata);
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000285 } else if (srcHasMemory && dstHasMemory) {
Xusong Wang13df2032020-02-06 18:24:01 -0800286 return copyHidlMemories(src.getRunTimePoolInfo(), dst.getRunTimePoolInfo());
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000287 } else if (srcHasMemory && dstHasIBuffer) {
288 return copyMemoryToIBuffer(src.getMemory(), dst.getIBuffer(), srcMetadata.dimensions);
289 } else if (srcHasIBuffer && dstHasMemory) {
290 return copyIBufferToMemory(src.getIBuffer(), dst.getMemory());
Xusong Wang52b860b2019-11-27 16:23:36 -0800291 }
292 return ANEURALNETWORKS_OP_FAILED;
293}
294
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100295int RuntimeMemory::copy(const RuntimeMemory& src, const RuntimeMemory& dst) {
Xusong Wang52b860b2019-11-27 16:23:36 -0800296 int n = copyInternal(src, dst);
297 dst.getValidator().setInitialized(n == ANEURALNETWORKS_NO_ERROR);
298 return n;
299}
300
Xusong Wang062ec502019-11-27 11:44:03 -0800301bool MemoryBuilder::badState(const char* name) const {
302 if (mFinished) {
303 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << name << " can't modify after finished";
304 return true;
305 }
306 return false;
307}
308
309int MemoryBuilder::addRole(const CompilationBuilder& compilation, IOType ioType, uint32_t index,
Xusong Wang13bed552021-03-19 14:10:18 -0700310 float prob) {
Xusong Wang062ec502019-11-27 11:44:03 -0800311 const char* tag = ioType == IOType::INPUT ? "addInputRole" : "addOutputRole";
312 if (badState(tag)) {
313 return ANEURALNETWORKS_BAD_STATE;
314 }
315 if (mRoles.count({&compilation, ioType, index}) > 0) {
316 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag
317 << " -- the same operand is specified twice.";
318 return ANEURALNETWORKS_BAD_DATA;
319 }
320
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100321 std::vector<std::tuple<const RuntimePreparedModel*, IOType, uint32_t>> roles;
Xusong Wang062ec502019-11-27 11:44:03 -0800322 auto callback = [&roles](const auto* preparedModel, IOType type, uint32_t index) {
323 roles.emplace_back(preparedModel, type, index);
324 };
325 if (ioType == IOType::INPUT) {
326 if (compilation.forEachStepRoleOfInput(index, callback) != ANEURALNETWORKS_NO_ERROR) {
327 return ANEURALNETWORKS_BAD_DATA;
328 }
329 } else {
330 if (compilation.forEachStepRoleOfOutput(index, callback) != ANEURALNETWORKS_NO_ERROR) {
331 return ANEURALNETWORKS_BAD_DATA;
332 }
333 }
334
335 const ModelBuilder* model = compilation.getModel();
336 CHECK(model != nullptr);
337 Operand operand;
338 if (ioType == IOType::INPUT) {
339 if (index >= model->inputCount()) {
340 LOG(ERROR) << "ANeuralNetworksMemoryDesc_addInputRole -- input index out of range.";
341 return ANEURALNETWORKS_BAD_DATA;
342 }
343 operand = model->getInputOperand(index);
344 } else {
345 if (index >= model->outputCount()) {
346 LOG(ERROR) << "ANeuralNetworksMemoryDesc_addOutputRole -- output index out of range.";
347 return ANEURALNETWORKS_BAD_DATA;
348 }
349 operand = model->getOutputOperand(index);
350 }
351 if (mOperand.has_value()) {
352 if (operand.type != mOperand->type || operand.scale != mOperand->scale ||
353 operand.zeroPoint != mOperand->zeroPoint ||
354 operand.extraParams != mOperand->extraParams) {
355 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag
356 << " -- incompatible operand metadata.";
357 return ANEURALNETWORKS_BAD_DATA;
358 }
359 }
360 if (!TypeManager::get()->isTensorType(operand.type) && !mDesc.dimensions.empty()) {
361 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- incompatible dimensions.";
362 return ANEURALNETWORKS_BAD_DATA;
363 }
364 auto combined = combineDimensions(mDesc.dimensions, operand.dimensions);
365 if (!combined.has_value()) {
366 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- incompatible dimensions.";
367 return ANEURALNETWORKS_BAD_DATA;
368 }
369
Xusong Wang13bed552021-03-19 14:10:18 -0700370 if (prob > 1.0f || prob <= 0.0f) {
371 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- invalid frequency " << prob;
Xusong Wang062ec502019-11-27 11:44:03 -0800372 return ANEURALNETWORKS_BAD_DATA;
373 }
374
375 mRoles.emplace(&compilation, ioType, index);
Stuart Langley79f80422020-06-12 16:07:16 +1000376 for (const auto& [preparedModel, type, ind] : roles) {
Xusong Wang062ec502019-11-27 11:44:03 -0800377 uint32_t modelIndex = mDesc.preparedModels.add(preparedModel);
Xusong Wang13bed552021-03-19 14:10:18 -0700378 BufferRole role = {.modelIndex = modelIndex, .ioIndex = ind, .probability = prob};
Xusong Wang062ec502019-11-27 11:44:03 -0800379 if (type == IOType::INPUT) {
380 mDesc.inputRoles.push_back(role);
381 } else {
382 mDesc.outputRoles.push_back(role);
383 }
384 }
385 mOperand = std::move(operand);
386 mDesc.dimensions = std::move(combined.value());
387 return ANEURALNETWORKS_NO_ERROR;
388}
389
390int MemoryBuilder::setDimensions(const std::vector<uint32_t>& dimensions) {
391 if (badState("setDimensions")) return ANEURALNETWORKS_BAD_STATE;
392 if (mOperand.has_value() && !TypeManager::get()->isTensorType(mOperand->type) &&
393 !dimensions.empty()) {
394 LOG(ERROR) << "ANeuralNetworksMemoryDesc_setDimensions -- incompatible dimensions for "
395 "scalars.";
396 return ANEURALNETWORKS_BAD_DATA;
397 }
398 auto combined = combineDimensions(mDesc.dimensions, dimensions);
399 if (!combined.has_value()) {
400 LOG(ERROR) << "ANeuralNetworksMemoryDesc_setDimensions -- incompatible dimensions.";
401 return ANEURALNETWORKS_BAD_DATA;
402 }
403 mDesc.dimensions = std::move(combined.value());
404 return ANEURALNETWORKS_NO_ERROR;
405}
406
Xusong Wang550e2a52019-11-27 12:18:19 -0800407static void logMemoryDescriptorToInfo(const MemoryDescriptor& desc, const Operand& operand) {
408 LOG(INFO) << "MemoryDescriptor start";
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100409 LOG(INFO) << " Data type: " << operand.type;
410 LOG(INFO) << " Scale: " << operand.scale;
411 LOG(INFO) << " Zero point: " << operand.zeroPoint;
412 LOG(INFO) << " Extra params: " << operand.extraParams;
Xusong Wang550e2a52019-11-27 12:18:19 -0800413 LOG(INFO) << " Dimensions: " << toString(desc.dimensions);
Slava Shklyaevc874ca92020-03-03 11:59:41 +0000414 LOG(INFO) << " Prepared models [" << desc.preparedModels.size() << "]:";
Xusong Wang550e2a52019-11-27 12:18:19 -0800415 for (const auto* preparedModel : desc.preparedModels) {
416 LOG(INFO) << " service = " << preparedModel->getDevice()->getName();
417 }
418 LOG(INFO) << " Input roles [" << desc.inputRoles.size() << "]:";
419 for (const auto& usage : desc.inputRoles) {
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100420 LOG(INFO) << " " << usage;
Xusong Wang550e2a52019-11-27 12:18:19 -0800421 }
422 LOG(INFO) << " Output roles [" << desc.outputRoles.size() << "]:";
423 for (const auto& usage : desc.outputRoles) {
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100424 LOG(INFO) << " " << usage;
Xusong Wang550e2a52019-11-27 12:18:19 -0800425 }
426 LOG(INFO) << "MemoryDescriptor end";
427}
428
Xusong Wang1b836a22020-02-06 13:17:33 -0800429static std::set<const Device*> getDevices(const MemoryDescriptor& desc) {
430 std::set<const Device*> devices;
Xusong Wang550e2a52019-11-27 12:18:19 -0800431 for (const auto* preparedModel : desc.preparedModels) {
432 const auto* device = preparedModel->getDevice();
Xusong Wang1b836a22020-02-06 13:17:33 -0800433 devices.insert(device);
Xusong Wang550e2a52019-11-27 12:18:19 -0800434 }
Xusong Wang1b836a22020-02-06 13:17:33 -0800435 return devices;
Xusong Wang550e2a52019-11-27 12:18:19 -0800436}
437
Xusong Wang062ec502019-11-27 11:44:03 -0800438int MemoryBuilder::finish() {
439 if (badState("finish")) return ANEURALNETWORKS_BAD_STATE;
440 if (mRoles.empty()) {
441 LOG(ERROR) << "ANeuralNetworksMemoryDesc_finish -- no role has been specified.";
442 return ANEURALNETWORKS_BAD_DATA;
443 }
Xusong Wang550e2a52019-11-27 12:18:19 -0800444 CHECK(mOperand.has_value());
445 if (VLOG_IS_ON(MEMORY)) {
446 logMemoryDescriptorToInfo(mDesc, mOperand.value());
447 }
Xusong Wang1b836a22020-02-06 13:17:33 -0800448 std::set<const Device*> devices = getDevices(mDesc);
Slava Shklyaevc874ca92020-03-03 11:59:41 +0000449 if (devices.empty()) {
450 // This can happen with interpreted control flow.
451 mAllocator = nullptr;
452 } else if (devices.size() == 1) {
Xusong Wang1b836a22020-02-06 13:17:33 -0800453 mAllocator = *devices.begin();
454 VLOG(MEMORY) << "Using " << mAllocator->getName() << " as allocator.";
455 } else {
456 LOG(INFO) << "MemoryBuilder::finish -- cannot handle multiple devices.";
457 mAllocator = nullptr;
458 }
459 mSupportsAhwb = std::all_of(devices.begin(), devices.end(), [](const auto* device) {
Przemysław Szczepaniaka6c206a2021-01-13 18:03:15 +0000460 return device->getFeatureLevel() >= kHalVersionV1_3ToApi.featureLevel;
Xusong Wang1b836a22020-02-06 13:17:33 -0800461 });
Xusong Wang4dce1662020-02-06 15:14:59 -0800462 mShouldFallback = std::none_of(mRoles.begin(), mRoles.end(), [](const auto& role) {
463 const auto* cb = std::get<const CompilationBuilder*>(role);
464 return cb->createdWithExplicitDeviceList();
465 });
Xusong Wang7ad067b2020-04-09 14:52:23 -0700466 const uint32_t size = TypeManager::get()->getSizeOfData(mOperand->type, mDesc.dimensions);
467 mShouldFallback &= (size != 0);
Xusong Wang062ec502019-11-27 11:44:03 -0800468 mFinished = true;
469 return ANEURALNETWORKS_NO_ERROR;
470}
471
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100472std::pair<int, std::unique_ptr<RuntimeMemory>> MemoryBuilder::allocate() const {
Xusong Wang550e2a52019-11-27 12:18:19 -0800473 if (!mFinished) {
474 LOG(ERROR) << "ANeuralNetworksMemory_createFromDesc -- passed an unfinished descriptor";
475 return {ANEURALNETWORKS_BAD_STATE, nullptr};
476 }
477
Xusong Wang550e2a52019-11-27 12:18:19 -0800478 int n = ANEURALNETWORKS_OP_FAILED;
Slava Shklyaev9f29f432020-08-13 13:16:03 +0100479 std::unique_ptr<RuntimeMemory> memory;
Xusong Wang7ad067b2020-04-09 14:52:23 -0700480 CHECK(mOperand.has_value());
Xusong Wang550e2a52019-11-27 12:18:19 -0800481
482 // Try allocate the memory on device.
483 if (mAllocator != nullptr) {
Xusong Wang4dce1662020-02-06 15:14:59 -0800484 std::tie(n, memory) = mAllocator->allocate(mDesc, mOperand->type);
Xusong Wang550e2a52019-11-27 12:18:19 -0800485 }
486
Xusong Wang1b836a22020-02-06 13:17:33 -0800487 // If failed, fallback to ashmem or BLOB mode AHWB.
Xusong Wang4dce1662020-02-06 15:14:59 -0800488 if (n != ANEURALNETWORKS_NO_ERROR && mShouldFallback) {
Xusong Wang7ad067b2020-04-09 14:52:23 -0700489 const uint32_t size = TypeManager::get()->getSizeOfData(mOperand->type, mDesc.dimensions);
Xusong Wang1b836a22020-02-06 13:17:33 -0800490 if (mSupportsAhwb) {
491 VLOG(MEMORY) << "MemoryBuilder::allocate -- fallback to BLOB mode AHWB.";
492 std::tie(n, memory) = MemoryRuntimeAHWB::create(size);
493 } else {
494 VLOG(MEMORY) << "MemoryBuilder::allocate -- fallback to ashmem.";
495 std::tie(n, memory) = MemoryAshmem::create(size);
496 }
Xusong Wang550e2a52019-11-27 12:18:19 -0800497 }
Xusong Wangd39f9192019-11-27 15:45:42 -0800498
499 if (n == ANEURALNETWORKS_NO_ERROR) {
500 CHECK(memory != nullptr);
501 auto validator =
Xusong Wang52b860b2019-11-27 16:23:36 -0800502 std::make_unique<DeviceMemoryValidator>(mRoles, mOperand.value(), mDesc.dimensions);
Xusong Wangd39f9192019-11-27 15:45:42 -0800503 memory->setValidator(std::move(validator));
504 }
Xusong Wang550e2a52019-11-27 12:18:19 -0800505 return {n, std::move(memory)};
506}
507
Michael Butler90fddbd2019-08-02 15:04:00 -0700508std::pair<int, std::unique_ptr<MemoryAshmem>> MemoryAshmem::create(uint32_t size) {
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000509 auto memory = createSharedMemory(size);
510 if (!memory.has_value()) {
511 LOG(ERROR) << "RuntimeMemory::create() failed: " << memory.error().message;
512 return {convertErrorStatusToResultCode(memory.error().code), nullptr};
513 }
514 auto mapping = map(memory.value());
515 if (!mapping.has_value()) {
516 LOG(ERROR) << "RuntimeMemory::create() map failed: " << mapping.error().message;
517 return {convertErrorStatusToResultCode(mapping.error().code), nullptr};
David Grossf9a33a82017-11-22 11:41:55 -0800518 }
Michael Butler90fddbd2019-08-02 15:04:00 -0700519 return {ANEURALNETWORKS_NO_ERROR,
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000520 std::make_unique<MemoryAshmem>(std::move(memory).value(), std::move(mapping).value())};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700521}
522
Michael Butler90fddbd2019-08-02 15:04:00 -0700523uint8_t* MemoryAshmem::getPointer() const {
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000524 return static_cast<uint8_t*>(std::get<void*>(kMapping.pointer));
Michael Butler90fddbd2019-08-02 15:04:00 -0700525}
526
Michael Butlerb3082a52021-02-07 00:10:23 -0800527MemoryAshmem::MemoryAshmem(SharedMemory memory, Mapping mapping)
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000528 : RuntimeMemory(std::move(memory)), kMapping(std::move(mapping)) {}
Michael Butler90fddbd2019-08-02 15:04:00 -0700529
530std::pair<int, std::unique_ptr<MemoryFd>> MemoryFd::create(size_t size, int prot, int fd,
531 size_t offset) {
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000532 auto memory = createSharedMemoryFromFd(size, prot, fd, offset);
533 if (!memory.has_value()) {
534 LOG(ERROR) << "Failed to create memory from fd: " << memory.error().message;
535 return {convertErrorStatusToResultCode(memory.error().code), nullptr};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700536 }
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000537 return {ANEURALNETWORKS_NO_ERROR, std::make_unique<MemoryFd>(std::move(memory).value())};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700538}
539
Michael Butlerb3082a52021-02-07 00:10:23 -0800540MemoryFd::MemoryFd(SharedMemory memory) : RuntimeMemory(std::move(memory)) {}
David Grossf9a33a82017-11-22 11:41:55 -0800541
Michael Butler90fddbd2019-08-02 15:04:00 -0700542std::pair<int, std::unique_ptr<MemoryAHWB>> MemoryAHWB::create(const AHardwareBuffer& ahwb) {
Michael Butler09160fd2021-02-04 22:05:22 -0800543 auto memory = createSharedMemoryFromAHWB(const_cast<AHardwareBuffer*>(&ahwb),
544 /*takeOwnership=*/false);
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000545 if (!memory.has_value()) {
546 LOG(ERROR) << "Failed to create memory from AHWB: " << memory.error().message;
547 return {convertErrorStatusToResultCode(memory.error().code), nullptr};
548 }
549
Xusong Wangd39f9192019-11-27 15:45:42 -0800550 std::unique_ptr<MemoryValidatorBase> validator;
Michael Butler81550a92021-03-25 15:28:52 -0700551 if (isAhwbBlob(memory.value())) {
552 validator = std::make_unique<SizedMemoryValidator>(nn::getSize(memory.value()));
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700553 } else {
Xusong Wangd39f9192019-11-27 15:45:42 -0800554 validator = std::make_unique<AHardwareBufferNonBlobValidator>();
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700555 }
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000556
557 auto memoryAHWB = std::make_unique<MemoryAHWB>(std::move(memory).value(), std::move(validator));
558 return {ANEURALNETWORKS_NO_ERROR, std::move(memoryAHWB)};
559}
Michael Butler90fddbd2019-08-02 15:04:00 -0700560
Xusong Wang1b836a22020-02-06 13:17:33 -0800561std::pair<int, std::unique_ptr<MemoryRuntimeAHWB>> MemoryRuntimeAHWB::create(uint32_t size) {
562 AHardwareBuffer* ahwb = nullptr;
563 const auto usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;
564 const AHardwareBuffer_Desc desc = {
565 .width = size,
566 .height = 1,
567 .layers = 1,
568 .format = AHARDWAREBUFFER_FORMAT_BLOB,
569 .usage = usage,
570 .stride = size,
571 };
572 int err = AHardwareBuffer_allocate(&desc, &ahwb);
573 if (err != 0 || ahwb == nullptr) {
574 LOG(ERROR) << "Failed to allocate BLOB mode AHWB.";
575 return {ANEURALNETWORKS_OP_FAILED, nullptr};
576 }
Xusong Wang1b836a22020-02-06 13:17:33 -0800577
Michael Butler09160fd2021-02-04 22:05:22 -0800578 auto memory = createSharedMemoryFromAHWB(ahwb, /*takeOWnership=*/true);
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000579 if (!memory.has_value()) {
580 LOG(ERROR) << "Failed to allocate BLOB mode AHWB: " << memory.error().message;
581 return {convertErrorStatusToResultCode(memory.error().code), nullptr};
Xusong Wang1b836a22020-02-06 13:17:33 -0800582 }
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000583 auto mapping = map(memory.value());
584 if (!mapping.has_value()) {
585 LOG(ERROR) << "Failed to map BLOB mode AHWB: " << mapping.error().message;
586 return {convertErrorStatusToResultCode(mapping.error().code), nullptr};
Xusong Wang1b836a22020-02-06 13:17:33 -0800587 }
Michael Butler09160fd2021-02-04 22:05:22 -0800588 auto memoryAHWB = std::make_unique<MemoryRuntimeAHWB>(std::move(memory).value(),
589 std::move(mapping).value());
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000590 return {ANEURALNETWORKS_NO_ERROR, std::move(memoryAHWB)};
Xusong Wang1b836a22020-02-06 13:17:33 -0800591}
592
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000593uint8_t* MemoryRuntimeAHWB::getPointer() const {
594 return static_cast<uint8_t*>(std::get<void*>(kMapping.pointer));
Xusong Wang1b836a22020-02-06 13:17:33 -0800595}
596
Michael Butler09160fd2021-02-04 22:05:22 -0800597MemoryRuntimeAHWB::MemoryRuntimeAHWB(SharedMemory memory, Mapping mapping)
598 : RuntimeMemory(std::move(memory)), kMapping(std::move(mapping)) {}
Xusong Wang1b836a22020-02-06 13:17:33 -0800599
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000600std::pair<int, std::unique_ptr<MemoryFromDevice>> MemoryFromDevice::create(SharedBuffer buffer) {
Xusong Wang550e2a52019-11-27 12:18:19 -0800601 if (buffer == nullptr) {
602 LOG(ERROR) << "nullptr IBuffer for device memory.";
Xusong Wang7ad067b2020-04-09 14:52:23 -0700603 return {ANEURALNETWORKS_OP_FAILED, nullptr};
Xusong Wang550e2a52019-11-27 12:18:19 -0800604 }
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000605 return {ANEURALNETWORKS_NO_ERROR, std::make_unique<MemoryFromDevice>(std::move(buffer))};
606}
Xusong Wang550e2a52019-11-27 12:18:19 -0800607
Slava Shklyaev3698ad42020-11-06 13:50:31 +0000608MemoryFromDevice::MemoryFromDevice(SharedBuffer buffer) : RuntimeMemory(std::move(buffer)) {}
Xusong Wang550e2a52019-11-27 12:18:19 -0800609
Michael Butlerf20c5b52019-07-22 18:59:46 -0700610} // namespace nn
611} // namespace android