blob: 9bddcd99274802ee8ab43c8c318bdba68bd9dd12 [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
Xusong Wang062ec502019-11-27 11:44:03 -080021#include <algorithm>
Michael Butler90fddbd2019-08-02 15:04:00 -070022#include <memory>
Xusong Wang062ec502019-11-27 11:44:03 -080023#include <set>
24#include <tuple>
Michael Butler90fddbd2019-08-02 15:04:00 -070025#include <utility>
Xusong Wang062ec502019-11-27 11:44:03 -080026#include <vector>
27
28#include "CompilationBuilder.h"
Xusong Wang52b860b2019-11-27 16:23:36 -080029#include "CpuExecutor.h"
Michael Butler50032c02019-03-14 17:34:48 -070030#include "ExecutionBurstController.h"
Xusong Wang550e2a52019-11-27 12:18:19 -080031#include "Manager.h"
Slava Shklyaev79534bc2019-05-22 11:10:13 +010032#include "MemoryUtils.h"
Xusong Wang062ec502019-11-27 11:44:03 -080033#include "TypeManager.h"
Jean-Luc Brouillet4fb1e852017-08-20 18:16:36 -070034#include "Utils.h"
35
36namespace android {
37namespace nn {
38
Michael Butler6bf05b22019-07-11 11:45:01 -070039using namespace hal;
40
Xusong Wangd39f9192019-11-27 15:45:42 -080041namespace {
42
43// The validator for a client-managed single-dimensional memory pool with a known size.
44// The memory may be used for request inputs, request outputs, or model constants.
45class SizedMemoryValidator : public MemoryValidatorBase {
46 public:
47 SizedMemoryValidator(uint32_t size) : kSize(size) {}
48
49 bool validate(const CompilationBuilder*, IOType, uint32_t, const ANeuralNetworksOperandType*,
50 uint32_t offset, uint32_t length) const override {
51 NN_RET_CHECK(offset + length <= kSize) << "request size larger than the memory size.";
52 NN_RET_CHECK(offset != 0 || length != 0) << "memory size cannot be implied.";
53 return true;
54 }
55
Xusong Wang52b860b2019-11-27 16:23:36 -080056 Metadata getMetadata() const override { return {.logicalSize = kSize}; }
57 bool updateMetadata(const Metadata& metadata) override {
58 return metadata.logicalSize == 0 || metadata.logicalSize == kSize;
59 }
60
Xusong Wangd39f9192019-11-27 15:45:42 -080061 private:
62 const uint32_t kSize;
63};
64
65// The validator for an AHardwareBuffer with Non-BLOB format.
66// We require the memory only used for request inputs or request outputs,
67// with both offset and length set to zero.
68class AHardwareBufferNonBlobValidator : public MemoryValidatorBase {
69 public:
70 AHardwareBufferNonBlobValidator() = default;
71
72 bool validate(const CompilationBuilder* compilation, IOType, uint32_t,
73 const ANeuralNetworksOperandType*, uint32_t offset,
74 uint32_t length) const override {
75 NN_RET_CHECK(compilation != nullptr)
76 << "cannot use Non-BLOB AHardwareBuffer as model constant";
77 NN_RET_CHECK(offset == 0 && length == 0)
78 << "non-zero offset (" << offset << ") and/or length (" << length
79 << ") for Non-BLOB format AHardwareBuffer.";
80 return true;
81 }
Xusong Wang52b860b2019-11-27 16:23:36 -080082
83 Metadata getMetadata() const override { return {}; }
84 bool updateMetadata(const Metadata&) override { return true; }
Xusong Wangd39f9192019-11-27 15:45:42 -080085};
86
87// The validator for a memory created from ANNMemory_createFromDesc.
88// We require the memory only used as one of the pre-specified roles,
89// with both offset and length set to zero.
90class DeviceMemoryValidator : public MemoryValidatorBase {
91 public:
Xusong Wang52b860b2019-11-27 16:23:36 -080092 DeviceMemoryValidator(std::set<CompilationRole> roles, Operand operand,
Xusong Wangd39f9192019-11-27 15:45:42 -080093 std::vector<uint32_t> dimensions)
94 : kCompilationRoles(std::move(roles)),
Xusong Wang52b860b2019-11-27 16:23:36 -080095 kOperand(std::move(operand)),
Xusong Wangd39f9192019-11-27 15:45:42 -080096 kInitialDimensions(std::move(dimensions)),
97 mUpdatedDimensions(kInitialDimensions) {}
98
99 bool validate(const CompilationBuilder* compilation, IOType ioType, uint32_t index,
100 const ANeuralNetworksOperandType* type, uint32_t offset,
101 uint32_t length) const override {
102 NN_RET_CHECK(kCompilationRoles.count({compilation, ioType, index}) > 0)
103 << "invalid compilation role.";
104 NN_RET_CHECK(offset == 0 && length == 0)
105 << "non-zero offset and/or length for driver-allocated memory.";
106 if (type) {
Xusong Wang52b860b2019-11-27 16:23:36 -0800107 const bool isTensor = TypeManager::get()->isTensorType(kOperand.type);
Xusong Wangd39f9192019-11-27 15:45:42 -0800108 NN_RET_CHECK(isTensor || type->dimensionCount == 0)
109 << "invalid dimensions for scalar memory.";
110 std::vector<uint32_t> dimensions(type->dimensions,
111 type->dimensions + type->dimensionCount);
112 // We only check against kInitialDimensions here.
113 // For input memories, mUpdatedDimensions will be checked in validateInputDimensions
114 // at the beginning of a computation.
115 const auto combined = combineDimensions(dimensions, kInitialDimensions);
116 NN_RET_CHECK(combined.has_value())
117 << "incompatible dimensions between request and memory. (request: "
118 << toString(dimensions) << ", memory: " << toString(kInitialDimensions) << ")";
119 }
120 return true;
121 }
122
123 bool validateInputDimensions(const std::vector<uint32_t>& dimensions) const override {
124 NN_RET_CHECK(mInitialized) << "using an uninitialized memory as input";
125 NN_RET_CHECK(dimensions == mUpdatedDimensions)
126 << "incompatible input dimensions between request and memory. (request: "
127 << toString(dimensions) << ", memory: " << toString(mUpdatedDimensions) << ")";
128 return true;
129 }
130
Xusong Wang52b860b2019-11-27 16:23:36 -0800131 Metadata getMetadata() const override {
132 CHECK(mInitialized);
133 return {.logicalSize = TypeManager::get()->getSizeOfData(kOperand.type, mUpdatedDimensions),
134 .dimensions = mUpdatedDimensions,
135 .operand = kOperand};
136 }
137
138 bool updateMetadata(const Metadata& metadata) override {
139 NN_RET_CHECK(!metadata.operand.has_value() ||
140 (metadata.operand->type == kOperand.type &&
141 metadata.operand->scale == kOperand.scale &&
142 metadata.operand->zeroPoint == kOperand.zeroPoint &&
143 metadata.operand->extraParams == kOperand.extraParams));
144
145 NN_RET_CHECK(metadata.dimensions.empty() ||
146 TypeManager::get()->isTensorType(kOperand.type));
147 auto combined = combineDimensions(metadata.dimensions, kInitialDimensions);
Xusong Wangd39f9192019-11-27 15:45:42 -0800148 NN_RET_CHECK(combined.has_value());
Xusong Wang52b860b2019-11-27 16:23:36 -0800149 NN_RET_CHECK(metadata.logicalSize == 0 ||
150 metadata.logicalSize ==
151 TypeManager::get()->getSizeOfData(kOperand.type, combined.value()));
Xusong Wangd39f9192019-11-27 15:45:42 -0800152 mUpdatedDimensions = std::move(combined.value());
153 return true;
154 }
155
156 void setInitialized(bool initialized) override { mInitialized = initialized; }
Xusong Wang52b860b2019-11-27 16:23:36 -0800157 bool isInitialized() const override { return mInitialized; }
Xusong Wangd39f9192019-11-27 15:45:42 -0800158
159 private:
160 const std::set<CompilationRole> kCompilationRoles;
Xusong Wang52b860b2019-11-27 16:23:36 -0800161
162 // Keep track of the data type, scale, zero point, and extra parameters of the target operand.
163 // Other fields will be ignored, including dimensions, lifetime, location, etc.
164 const Operand kOperand;
Xusong Wangd39f9192019-11-27 15:45:42 -0800165
166 // The dimensions of the memory when the memory object is created.
167 // May have unknown dimensions or rank.
168 const std::vector<uint32_t> kInitialDimensions;
169
170 // The updated dimensions after a successful execution or memory copying.
171 std::vector<uint32_t> mUpdatedDimensions;
172
173 bool mInitialized = false;
174};
175
176} // namespace
177
178Memory::Memory(hal::hidl_memory memory)
179 : kHidlMemory(std::move(memory)),
180 mValidator(std::make_unique<SizedMemoryValidator>(kHidlMemory.size())) {}
181
182Memory::Memory(hal::hidl_memory memory, std::unique_ptr<MemoryValidatorBase> validator)
183 : kHidlMemory(std::move(memory)), mValidator(std::move(validator)) {}
184
Michael Butler7f621bb2020-02-04 16:08:11 -0800185Memory::Memory(sp<hal::IBuffer> buffer, uint32_t token)
Xusong Wangd39f9192019-11-27 15:45:42 -0800186 : kBuffer(std::move(buffer)), kToken(token) {}
187
Michael Butler50032c02019-03-14 17:34:48 -0700188Memory::~Memory() {
189 for (const auto [ptr, weakBurst] : mUsedBy) {
190 if (const std::shared_ptr<ExecutionBurstController> burst = weakBurst.lock()) {
191 burst->freeMemory(getKey());
192 }
193 }
194}
195
Xusong Wang085d0002020-01-08 16:52:37 -0800196hal::Request::MemoryPool Memory::getMemoryPool() const {
197 hal::Request::MemoryPool pool;
198 if (kToken > 0) {
199 pool.token(kToken);
200 } else {
201 pool.hidlMemory(kHidlMemory);
202 }
203 return pool;
204}
205
Slava Shklyaev342358d2020-03-05 18:02:19 +0000206std::optional<RunTimePoolInfo> Memory::getRunTimePoolInfo() const {
207 // TODO(b/147777318): Cache memory mapping within the memory object.
208 return RunTimePoolInfo::createFromHidlMemory(kHidlMemory);
209}
210
Michael Butler50032c02019-03-14 17:34:48 -0700211intptr_t Memory::getKey() const {
212 return reinterpret_cast<intptr_t>(this);
213}
214
215void Memory::usedBy(const std::shared_ptr<ExecutionBurstController>& burst) const {
216 std::lock_guard<std::mutex> guard(mMutex);
217 mUsedBy.emplace(burst.get(), burst);
218}
219
Xusong Wang52b860b2019-11-27 16:23:36 -0800220static int copyHidlMemories(const hidl_memory& src, const hidl_memory& dst) {
221 if (src.size() != dst.size()) {
222 LOG(ERROR) << "ANeuralNetworksMemory_copy -- incompatible memory size";
223 return ANEURALNETWORKS_BAD_DATA;
224 }
225 auto srcPool = RunTimePoolInfo::createFromHidlMemory(src);
226 auto dstPool = RunTimePoolInfo::createFromHidlMemory(dst);
227 if (!srcPool.has_value() || !dstPool.has_value()) {
228 LOG(ERROR) << "ANeuralNetworksMemory_copy -- unable to map memory";
229 return ANEURALNETWORKS_UNMAPPABLE;
230 }
231 CHECK(srcPool->getBuffer() != nullptr);
232 CHECK(dstPool->getBuffer() != nullptr);
233 std::copy(srcPool->getBuffer(), srcPool->getBuffer() + src.size(), dstPool->getBuffer());
234 dstPool->flush();
235 return ANEURALNETWORKS_NO_ERROR;
236}
237
238static int copyIBufferToHidlMemory(const sp<IBuffer>& src, const hidl_memory& dst) {
239 const auto ret = src->copyTo(dst);
240 if (!ret.isOk()) {
241 LOG(ERROR) << "ANeuralNetworksMemory_copy failure: " << ret.description();
242 return ANEURALNETWORKS_OP_FAILED;
243 }
244 return convertErrorStatusToResultCode(static_cast<ErrorStatus>(ret));
245}
246
247static int copyHidlMemoryToIBuffer(const hidl_memory& src, const sp<IBuffer>& dst,
248 const std::vector<uint32_t>& dimensions) {
249 const auto ret = dst->copyFrom(src, dimensions);
250 if (!ret.isOk()) {
251 LOG(ERROR) << "ANeuralNetworksMemory_copy failure: " << ret.description();
252 return ANEURALNETWORKS_OP_FAILED;
253 }
254 return convertErrorStatusToResultCode(static_cast<ErrorStatus>(ret));
255}
256
257static int copyIBuffers(const sp<IBuffer>& src, const sp<IBuffer>& dst,
258 const MemoryValidatorBase::Metadata& srcMetadata) {
259 // TODO(xusongw): Use BLOB mode AHardwareBuffer.
260 hidl_memory hidlMemory = allocateSharedMemory(srcMetadata.logicalSize);
261 if (!hidlMemory.valid()) return ANEURALNETWORKS_OUT_OF_MEMORY;
262 NN_RETURN_IF_ERROR(copyIBufferToHidlMemory(src, hidlMemory));
263 NN_RETURN_IF_ERROR(copyHidlMemoryToIBuffer(hidlMemory, dst, srcMetadata.dimensions));
264 return ANEURALNETWORKS_NO_ERROR;
265}
266
267static int copyInternal(const Memory& src, const Memory& dst) {
268 if (&src == &dst) return ANEURALNETWORKS_NO_ERROR;
269
270 if (!src.getValidator().isInitialized()) {
271 LOG(ERROR) << "ANeuralNetworksMemory_copy -- uninitialized source memory";
272 return ANEURALNETWORKS_BAD_DATA;
273 }
274
275 const auto srcMetadata = src.getValidator().getMetadata();
276 if (!dst.getValidator().updateMetadata(srcMetadata)) {
277 LOG(ERROR) << "ANeuralNetworksMemory_copy -- incompatible memories";
278 return ANEURALNETWORKS_BAD_DATA;
279 }
280
281 bool srcHasHidlMemory = src.getHidlMemory().valid();
282 bool dstHasHidlMemory = dst.getHidlMemory().valid();
283 bool srcHasIBuffer = src.getIBuffer() != nullptr;
284 bool dstHasIBuffer = dst.getIBuffer() != nullptr;
285 if (srcHasIBuffer && dstHasIBuffer) {
286 return copyIBuffers(src.getIBuffer(), dst.getIBuffer(), srcMetadata);
287 } else if (srcHasHidlMemory && dstHasHidlMemory) {
288 return copyHidlMemories(src.getHidlMemory(), dst.getHidlMemory());
289 } else if (srcHasHidlMemory && dstHasIBuffer) {
290 return copyHidlMemoryToIBuffer(src.getHidlMemory(), dst.getIBuffer(),
291 srcMetadata.dimensions);
292 } else if (srcHasIBuffer && dstHasHidlMemory) {
293 return copyIBufferToHidlMemory(src.getIBuffer(), dst.getHidlMemory());
294 }
295 return ANEURALNETWORKS_OP_FAILED;
296}
297
298int Memory::copy(const Memory& src, const Memory& dst) {
299 int n = copyInternal(src, dst);
300 dst.getValidator().setInitialized(n == ANEURALNETWORKS_NO_ERROR);
301 return n;
302}
303
Xusong Wang062ec502019-11-27 11:44:03 -0800304bool MemoryBuilder::badState(const char* name) const {
305 if (mFinished) {
306 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << name << " can't modify after finished";
307 return true;
308 }
309 return false;
310}
311
312int MemoryBuilder::addRole(const CompilationBuilder& compilation, IOType ioType, uint32_t index,
313 float freq) {
314 const char* tag = ioType == IOType::INPUT ? "addInputRole" : "addOutputRole";
315 if (badState(tag)) {
316 return ANEURALNETWORKS_BAD_STATE;
317 }
318 if (mRoles.count({&compilation, ioType, index}) > 0) {
319 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag
320 << " -- the same operand is specified twice.";
321 return ANEURALNETWORKS_BAD_DATA;
322 }
323
324 std::vector<std::tuple<const PreparedModel*, IOType, uint32_t>> roles;
325 auto callback = [&roles](const auto* preparedModel, IOType type, uint32_t index) {
326 roles.emplace_back(preparedModel, type, index);
327 };
328 if (ioType == IOType::INPUT) {
329 if (compilation.forEachStepRoleOfInput(index, callback) != ANEURALNETWORKS_NO_ERROR) {
330 return ANEURALNETWORKS_BAD_DATA;
331 }
332 } else {
333 if (compilation.forEachStepRoleOfOutput(index, callback) != ANEURALNETWORKS_NO_ERROR) {
334 return ANEURALNETWORKS_BAD_DATA;
335 }
336 }
337
338 const ModelBuilder* model = compilation.getModel();
339 CHECK(model != nullptr);
340 Operand operand;
341 if (ioType == IOType::INPUT) {
342 if (index >= model->inputCount()) {
343 LOG(ERROR) << "ANeuralNetworksMemoryDesc_addInputRole -- input index out of range.";
344 return ANEURALNETWORKS_BAD_DATA;
345 }
346 operand = model->getInputOperand(index);
347 } else {
348 if (index >= model->outputCount()) {
349 LOG(ERROR) << "ANeuralNetworksMemoryDesc_addOutputRole -- output index out of range.";
350 return ANEURALNETWORKS_BAD_DATA;
351 }
352 operand = model->getOutputOperand(index);
353 }
354 if (mOperand.has_value()) {
355 if (operand.type != mOperand->type || operand.scale != mOperand->scale ||
356 operand.zeroPoint != mOperand->zeroPoint ||
357 operand.extraParams != mOperand->extraParams) {
358 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag
359 << " -- incompatible operand metadata.";
360 return ANEURALNETWORKS_BAD_DATA;
361 }
362 }
363 if (!TypeManager::get()->isTensorType(operand.type) && !mDesc.dimensions.empty()) {
364 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- incompatible dimensions.";
365 return ANEURALNETWORKS_BAD_DATA;
366 }
367 auto combined = combineDimensions(mDesc.dimensions, operand.dimensions);
368 if (!combined.has_value()) {
369 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- incompatible dimensions.";
370 return ANEURALNETWORKS_BAD_DATA;
371 }
372
373 if (freq > 1.0f || freq <= 0.0f) {
374 LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- invalid frequency " << freq;
375 return ANEURALNETWORKS_BAD_DATA;
376 }
377
378 mRoles.emplace(&compilation, ioType, index);
379 for (const auto [preparedModel, type, ind] : roles) {
380 uint32_t modelIndex = mDesc.preparedModels.add(preparedModel);
381 BufferRole role = {.modelIndex = modelIndex, .ioIndex = ind, .frequency = freq};
382 if (type == IOType::INPUT) {
383 mDesc.inputRoles.push_back(role);
384 } else {
385 mDesc.outputRoles.push_back(role);
386 }
387 }
388 mOperand = std::move(operand);
389 mDesc.dimensions = std::move(combined.value());
390 return ANEURALNETWORKS_NO_ERROR;
391}
392
393int MemoryBuilder::setDimensions(const std::vector<uint32_t>& dimensions) {
394 if (badState("setDimensions")) return ANEURALNETWORKS_BAD_STATE;
395 if (mOperand.has_value() && !TypeManager::get()->isTensorType(mOperand->type) &&
396 !dimensions.empty()) {
397 LOG(ERROR) << "ANeuralNetworksMemoryDesc_setDimensions -- incompatible dimensions for "
398 "scalars.";
399 return ANEURALNETWORKS_BAD_DATA;
400 }
401 auto combined = combineDimensions(mDesc.dimensions, dimensions);
402 if (!combined.has_value()) {
403 LOG(ERROR) << "ANeuralNetworksMemoryDesc_setDimensions -- incompatible dimensions.";
404 return ANEURALNETWORKS_BAD_DATA;
405 }
406 mDesc.dimensions = std::move(combined.value());
407 return ANEURALNETWORKS_NO_ERROR;
408}
409
Xusong Wang550e2a52019-11-27 12:18:19 -0800410static void logMemoryDescriptorToInfo(const MemoryDescriptor& desc, const Operand& operand) {
411 LOG(INFO) << "MemoryDescriptor start";
412 LOG(INFO) << " Data type: " << toString(operand.type);
413 LOG(INFO) << " Scale: " << toString(operand.scale);
414 LOG(INFO) << " Zero point: " << toString(operand.zeroPoint);
415 LOG(INFO) << " Extra params: " << toString(operand.extraParams);
416 LOG(INFO) << " Dimensions: " << toString(desc.dimensions);
417 LOG(INFO) << " Submodels [" << desc.preparedModels.size() << "]:";
418 for (const auto* preparedModel : desc.preparedModels) {
419 LOG(INFO) << " service = " << preparedModel->getDevice()->getName();
420 }
421 LOG(INFO) << " Input roles [" << desc.inputRoles.size() << "]:";
422 for (const auto& usage : desc.inputRoles) {
423 LOG(INFO) << " " << toString(usage);
424 }
425 LOG(INFO) << " Output roles [" << desc.outputRoles.size() << "]:";
426 for (const auto& usage : desc.outputRoles) {
427 LOG(INFO) << " " << toString(usage);
428 }
429 LOG(INFO) << "MemoryDescriptor end";
430}
431
432static const Device* selectDeviceMemoryAllocator(const MemoryDescriptor& desc) {
433 const Device* allocator = nullptr;
434 for (const auto* preparedModel : desc.preparedModels) {
435 const auto* device = preparedModel->getDevice();
436 if (allocator == nullptr) {
437 allocator = device;
438 } else if (allocator != device) {
439 LOG(INFO) << "selectDeviceMemoryAllocator -- cannot handle multiple devices.";
440 return nullptr;
441 }
442 }
443 CHECK(allocator != nullptr);
444 VLOG(MEMORY) << "Using " << allocator->getName() << " as allocator.";
445 return allocator;
446}
447
Xusong Wang062ec502019-11-27 11:44:03 -0800448int MemoryBuilder::finish() {
449 if (badState("finish")) return ANEURALNETWORKS_BAD_STATE;
450 if (mRoles.empty()) {
451 LOG(ERROR) << "ANeuralNetworksMemoryDesc_finish -- no role has been specified.";
452 return ANEURALNETWORKS_BAD_DATA;
453 }
Xusong Wang550e2a52019-11-27 12:18:19 -0800454 CHECK(mOperand.has_value());
455 if (VLOG_IS_ON(MEMORY)) {
456 logMemoryDescriptorToInfo(mDesc, mOperand.value());
457 }
458 mAllocator = selectDeviceMemoryAllocator(mDesc);
Xusong Wang4dce1662020-02-06 15:14:59 -0800459 mShouldFallback = std::none_of(mRoles.begin(), mRoles.end(), [](const auto& role) {
460 const auto* cb = std::get<const CompilationBuilder*>(role);
461 return cb->createdWithExplicitDeviceList();
462 });
Xusong Wang062ec502019-11-27 11:44:03 -0800463 mFinished = true;
464 return ANEURALNETWORKS_NO_ERROR;
465}
466
Xusong Wang550e2a52019-11-27 12:18:19 -0800467std::pair<int, std::unique_ptr<Memory>> MemoryBuilder::allocate() const {
468 if (!mFinished) {
469 LOG(ERROR) << "ANeuralNetworksMemory_createFromDesc -- passed an unfinished descriptor";
470 return {ANEURALNETWORKS_BAD_STATE, nullptr};
471 }
472
473 // TODO(xusongw): Does not support dynamic output shape for now.
474 CHECK(mOperand.has_value());
475 uint32_t size = TypeManager::get()->getSizeOfData(mOperand->type, mDesc.dimensions);
476 if (size == 0) {
477 LOG(ERROR)
478 << "ANeuralNetworksMemory_createFromDesc -- does not support unknown dimensions.";
479 return {ANEURALNETWORKS_OP_FAILED, nullptr};
480 }
481
482 int n = ANEURALNETWORKS_OP_FAILED;
483 std::unique_ptr<Memory> memory;
484
485 // Try allocate the memory on device.
486 if (mAllocator != nullptr) {
Xusong Wang4dce1662020-02-06 15:14:59 -0800487 std::tie(n, memory) = mAllocator->allocate(mDesc, mOperand->type);
Xusong Wang550e2a52019-11-27 12:18:19 -0800488 }
489
490 // If failed, fallback to ashmem.
Xusong Wang550e2a52019-11-27 12:18:19 -0800491 // TODO(xusongw): Use BLOB mode hardware buffer when possible.
Xusong Wang4dce1662020-02-06 15:14:59 -0800492 if (n != ANEURALNETWORKS_NO_ERROR && mShouldFallback) {
Xusong Wang550e2a52019-11-27 12:18:19 -0800493 VLOG(MEMORY) << "MemoryBuilder::allocate -- fallback to ashmem.";
494 std::tie(n, memory) = MemoryAshmem::create(size);
495 }
Xusong Wangd39f9192019-11-27 15:45:42 -0800496
497 if (n == ANEURALNETWORKS_NO_ERROR) {
498 CHECK(memory != nullptr);
499 auto validator =
Xusong Wang52b860b2019-11-27 16:23:36 -0800500 std::make_unique<DeviceMemoryValidator>(mRoles, mOperand.value(), mDesc.dimensions);
Xusong Wangd39f9192019-11-27 15:45:42 -0800501 memory->setValidator(std::move(validator));
502 }
Xusong Wang550e2a52019-11-27 12:18:19 -0800503 return {n, std::move(memory)};
504}
505
Michael Butler90fddbd2019-08-02 15:04:00 -0700506std::pair<int, std::unique_ptr<MemoryAshmem>> MemoryAshmem::create(uint32_t size) {
507 hidl_memory hidlMemory = allocateSharedMemory(size);
508 sp<IMemory> mapped = mapMemory(hidlMemory);
509 if (mapped == nullptr || mapped->getPointer() == nullptr) {
510 LOG(ERROR) << "Memory::create failed";
511 return {ANEURALNETWORKS_OUT_OF_MEMORY, nullptr};
David Grossf9a33a82017-11-22 11:41:55 -0800512 }
Michael Butler90fddbd2019-08-02 15:04:00 -0700513 return {ANEURALNETWORKS_NO_ERROR,
514 std::make_unique<MemoryAshmem>(std::move(mapped), std::move(hidlMemory))};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700515}
516
Michael Butler90fddbd2019-08-02 15:04:00 -0700517uint8_t* MemoryAshmem::getPointer() const {
518 return static_cast<uint8_t*>(static_cast<void*>(kMappedMemory->getPointer()));
519}
520
521MemoryAshmem::MemoryAshmem(sp<IMemory> mapped, hidl_memory memory)
522 : Memory(std::move(memory)), kMappedMemory(std::move(mapped)) {}
523
524std::pair<int, std::unique_ptr<MemoryFd>> MemoryFd::create(size_t size, int prot, int fd,
525 size_t offset) {
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700526 if (size == 0 || fd < 0) {
527 LOG(ERROR) << "Invalid size or fd";
Michael Butler90fddbd2019-08-02 15:04:00 -0700528 return {ANEURALNETWORKS_BAD_DATA, nullptr};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700529 }
Michael Butler90fddbd2019-08-02 15:04:00 -0700530
531 // Duplicate the file descriptor so MemoryFd owns its own version.
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700532 int dupfd = dup(fd);
533 if (dupfd == -1) {
534 LOG(ERROR) << "Failed to dup the fd";
Michael Butler90fddbd2019-08-02 15:04:00 -0700535 // TODO(b/120417090): is ANEURALNETWORKS_UNEXPECTED_NULL the correct
536 // error to return here?
537 return {ANEURALNETWORKS_UNEXPECTED_NULL, nullptr};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700538 }
539
Michael Butler90fddbd2019-08-02 15:04:00 -0700540 // Create a temporary native handle to own the dupfd.
541 native_handle_t* nativeHandle = native_handle_create(1, 3);
542 if (nativeHandle == nullptr) {
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700543 LOG(ERROR) << "Failed to create native_handle";
Michael Butler90fddbd2019-08-02 15:04:00 -0700544 // TODO(b/120417090): is ANEURALNETWORKS_UNEXPECTED_NULL the correct
545 // error to return here?
546 return {ANEURALNETWORKS_UNEXPECTED_NULL, nullptr};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700547 }
Michael Butler90fddbd2019-08-02 15:04:00 -0700548 nativeHandle->data[0] = dupfd;
549 nativeHandle->data[1] = prot;
550 const uint64_t bits = static_cast<uint64_t>(offset);
551 nativeHandle->data[2] = (int32_t)(uint32_t)(bits & 0xffffffff);
552 nativeHandle->data[3] = (int32_t)(uint32_t)(bits >> 32);
553
554 // Create a hidl_handle which owns the native handle and fd so that we don't
555 // have to manually clean either the native handle or the fd.
556 hardware::hidl_handle hidlHandle;
557 hidlHandle.setTo(nativeHandle, /*shouldOwn=*/true);
558
559 // Push the hidl_handle into a hidl_memory object. The hidl_memory object is
560 // responsible for cleaning the hidl_handle, the native handle, and the fd.
561 hidl_memory hidlMemory = hidl_memory("mmap_fd", std::move(hidlHandle), size);
562
563 return {ANEURALNETWORKS_NO_ERROR, std::make_unique<MemoryFd>(std::move(hidlMemory))};
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700564}
565
Michael Butler90fddbd2019-08-02 15:04:00 -0700566MemoryFd::MemoryFd(hidl_memory memory) : Memory(std::move(memory)) {}
David Grossf9a33a82017-11-22 11:41:55 -0800567
Michael Butler90fddbd2019-08-02 15:04:00 -0700568std::pair<int, std::unique_ptr<MemoryAHWB>> MemoryAHWB::create(const AHardwareBuffer& ahwb) {
569 AHardwareBuffer_Desc bufferDesc;
570 AHardwareBuffer_describe(&ahwb, &bufferDesc);
571 const native_handle_t* handle = AHardwareBuffer_getNativeHandle(&ahwb);
572 hidl_memory hidlMemory;
Xusong Wangd39f9192019-11-27 15:45:42 -0800573 std::unique_ptr<MemoryAHWB> memory;
574 std::unique_ptr<MemoryValidatorBase> validator;
Michael Butler90fddbd2019-08-02 15:04:00 -0700575 if (bufferDesc.format == AHARDWAREBUFFER_FORMAT_BLOB) {
576 hidlMemory = hidl_memory("hardware_buffer_blob", handle, bufferDesc.width);
Xusong Wangd39f9192019-11-27 15:45:42 -0800577 validator = std::make_unique<SizedMemoryValidator>(bufferDesc.width);
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700578 } else {
Michael Butler90fddbd2019-08-02 15:04:00 -0700579 // memory size is not used.
580 hidlMemory = hidl_memory("hardware_buffer", handle, 0);
Xusong Wangd39f9192019-11-27 15:45:42 -0800581 validator = std::make_unique<AHardwareBufferNonBlobValidator>();
Jean-Luc Brouilletd409e2c2017-09-27 23:59:20 -0700582 }
Xusong Wangd39f9192019-11-27 15:45:42 -0800583 memory = std::make_unique<MemoryAHWB>(std::move(hidlMemory), std::move(validator));
Michael Butler90fddbd2019-08-02 15:04:00 -0700584 return {ANEURALNETWORKS_NO_ERROR, std::move(memory)};
585};
586
Xusong Wang550e2a52019-11-27 12:18:19 -0800587std::pair<int, std::unique_ptr<MemoryFromDevice>> MemoryFromDevice::create(sp<hal::IBuffer> buffer,
Michael Butler7f621bb2020-02-04 16:08:11 -0800588 uint32_t token) {
Xusong Wang550e2a52019-11-27 12:18:19 -0800589 if (buffer == nullptr) {
590 LOG(ERROR) << "nullptr IBuffer for device memory.";
591 return {ANEURALNETWORKS_BAD_DATA, nullptr};
592 }
593 if (token <= 0) {
594 LOG(ERROR) << "Invalid token for device memory: " << token;
595 return {ANEURALNETWORKS_BAD_DATA, nullptr};
596 }
597 return {ANEURALNETWORKS_NO_ERROR, std::make_unique<MemoryFromDevice>(std::move(buffer), token)};
598};
599
Michael Butler7f621bb2020-02-04 16:08:11 -0800600MemoryFromDevice::MemoryFromDevice(sp<hal::IBuffer> buffer, uint32_t token)
Xusong Wang550e2a52019-11-27 12:18:19 -0800601 : Memory(std::move(buffer), token) {}
602
Michael Butlerf20c5b52019-07-22 18:59:46 -0700603} // namespace nn
604} // namespace android