1 /*
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 
21 #include <android-base/scopeguard.h>
22 #include <android/hardware_buffer.h>
23 #include <cutils/native_handle.h>
24 #include <vndk/hardware_buffer.h>
25 
26 #include <algorithm>
27 #include <memory>
28 #include <set>
29 #include <tuple>
30 #include <utility>
31 #include <vector>
32 
33 #include "CompilationBuilder.h"
34 #include "CpuExecutor.h"
35 #include "ExecutionBurstController.h"
36 #include "Manager.h"
37 #include "MemoryUtils.h"
38 #include "TypeManager.h"
39 #include "Utils.h"
40 
41 namespace android {
42 namespace nn {
43 
44 using namespace hal;
45 
46 namespace {
47 
48 // The validator for a client-managed single-dimensional memory pool with a known size.
49 // The memory may be used for request inputs, request outputs, or model constants.
50 class SizedMemoryValidator : public MemoryValidatorBase {
51    public:
SizedMemoryValidator(uint32_t size)52     SizedMemoryValidator(uint32_t size) : kSize(size) {}
53 
validate(const CompilationBuilder *,IOType,uint32_t,const ANeuralNetworksOperandType *,uint32_t offset,uint32_t length) const54     bool validate(const CompilationBuilder*, IOType, uint32_t, const ANeuralNetworksOperandType*,
55                   uint32_t offset, uint32_t length) const override {
56         NN_RET_CHECK(offset + length <= kSize) << "request size larger than the memory size.";
57         NN_RET_CHECK(offset != 0 || length != 0) << "memory size cannot be implied.";
58         return true;
59     }
60 
getMetadata() const61     Metadata getMetadata() const override { return {.logicalSize = kSize}; }
updateMetadata(const Metadata & metadata)62     bool updateMetadata(const Metadata& metadata) override {
63         return metadata.logicalSize == 0 || metadata.logicalSize == kSize;
64     }
65 
66    private:
67     const uint32_t kSize;
68 };
69 
70 // The validator for an AHardwareBuffer with Non-BLOB format.
71 // We require the memory only used for request inputs or request outputs,
72 // with both offset and length set to zero.
73 class AHardwareBufferNonBlobValidator : public MemoryValidatorBase {
74    public:
75     AHardwareBufferNonBlobValidator() = default;
76 
validate(const CompilationBuilder * compilation,IOType,uint32_t,const ANeuralNetworksOperandType *,uint32_t offset,uint32_t length) const77     bool validate(const CompilationBuilder* compilation, IOType, uint32_t,
78                   const ANeuralNetworksOperandType*, uint32_t offset,
79                   uint32_t length) const override {
80         NN_RET_CHECK(compilation != nullptr)
81                 << "cannot use Non-BLOB AHardwareBuffer as model constant";
82         NN_RET_CHECK(offset == 0 && length == 0)
83                 << "non-zero offset (" << offset << ") and/or length (" << length
84                 << ") for Non-BLOB format AHardwareBuffer.";
85         return true;
86     }
87 
getMetadata() const88     Metadata getMetadata() const override { return {}; }
updateMetadata(const Metadata &)89     bool updateMetadata(const Metadata&) override { return true; }
90 };
91 
92 // The validator for a memory created from ANNMemory_createFromDesc.
93 // We require the memory only used as one of the pre-specified roles,
94 // with both offset and length set to zero.
95 class DeviceMemoryValidator : public MemoryValidatorBase {
96    public:
DeviceMemoryValidator(std::set<CompilationRole> roles,Operand operand,std::vector<uint32_t> dimensions)97     DeviceMemoryValidator(std::set<CompilationRole> roles, Operand operand,
98                           std::vector<uint32_t> dimensions)
99         : kCompilationRoles(std::move(roles)),
100           kOperand(std::move(operand)),
101           kInitialDimensions(std::move(dimensions)),
102           mUpdatedDimensions(kInitialDimensions) {}
103 
validate(const CompilationBuilder * compilation,IOType ioType,uint32_t index,const ANeuralNetworksOperandType * type,uint32_t offset,uint32_t length) const104     bool validate(const CompilationBuilder* compilation, IOType ioType, uint32_t index,
105                   const ANeuralNetworksOperandType* type, uint32_t offset,
106                   uint32_t length) const override {
107         NN_RET_CHECK(kCompilationRoles.count({compilation, ioType, index}) > 0)
108                 << "invalid compilation role.";
109         NN_RET_CHECK(offset == 0 && length == 0)
110                 << "non-zero offset and/or length for driver-allocated memory.";
111         if (type) {
112             const bool isTensor = TypeManager::get()->isTensorType(kOperand.type);
113             NN_RET_CHECK(isTensor || type->dimensionCount == 0)
114                     << "invalid dimensions for scalar memory.";
115             std::vector<uint32_t> dimensions(type->dimensions,
116                                              type->dimensions + type->dimensionCount);
117             // We only check against kInitialDimensions here.
118             // For input memories, mUpdatedDimensions will be checked in validateInputDimensions
119             // at the beginning of a computation.
120             const auto combined = combineDimensions(dimensions, kInitialDimensions);
121             NN_RET_CHECK(combined.has_value())
122                     << "incompatible dimensions between request and memory. (request: "
123                     << toString(dimensions) << ", memory: " << toString(kInitialDimensions) << ")";
124         }
125         return true;
126     }
127 
validateInputDimensions(const std::vector<uint32_t> & dimensions) const128     bool validateInputDimensions(const std::vector<uint32_t>& dimensions) const override {
129         NN_RET_CHECK(mInitialized) << "using an uninitialized memory as input";
130         NN_RET_CHECK(dimensions == mUpdatedDimensions)
131                 << "incompatible input dimensions between request and memory. (request: "
132                 << toString(dimensions) << ", memory: " << toString(mUpdatedDimensions) << ")";
133         return true;
134     }
135 
getMetadata() const136     Metadata getMetadata() const override {
137         return {.logicalSize = TypeManager::get()->getSizeOfData(kOperand.type, mUpdatedDimensions),
138                 .dimensions = mUpdatedDimensions,
139                 .operand = kOperand};
140     }
141 
updateMetadata(const Metadata & metadata)142     bool updateMetadata(const Metadata& metadata) override {
143         NN_RET_CHECK(!metadata.operand.has_value() ||
144                      (metadata.operand->type == kOperand.type &&
145                       metadata.operand->scale == kOperand.scale &&
146                       metadata.operand->zeroPoint == kOperand.zeroPoint &&
147                       metadata.operand->extraParams == kOperand.extraParams));
148 
149         NN_RET_CHECK(metadata.dimensions.empty() ||
150                      TypeManager::get()->isTensorType(kOperand.type));
151         auto combined = combineDimensions(metadata.dimensions, kInitialDimensions);
152         NN_RET_CHECK(combined.has_value());
153         NN_RET_CHECK(metadata.logicalSize == 0 ||
154                      metadata.logicalSize ==
155                              TypeManager::get()->getSizeOfData(kOperand.type, combined.value()));
156         mUpdatedDimensions = std::move(combined.value());
157         return true;
158     }
159 
createdWithUnknownShape() const160     bool createdWithUnknownShape() const override {
161         return TypeManager::get()->getSizeOfData(kOperand.type, kInitialDimensions) == 0;
162     }
163 
setInitialized(bool initialized)164     void setInitialized(bool initialized) override { mInitialized = initialized; }
isInitialized() const165     bool isInitialized() const override { return mInitialized; }
166 
167    private:
168     const std::set<CompilationRole> kCompilationRoles;
169 
170     // Keep track of the data type, scale, zero point, and extra parameters of the target operand.
171     // Other fields will be ignored, including dimensions, lifetime, location, etc.
172     const Operand kOperand;
173 
174     // The dimensions of the memory when the memory object is created.
175     // May have unknown dimensions or rank.
176     const std::vector<uint32_t> kInitialDimensions;
177 
178     // The updated dimensions after a successful execution or memory copying.
179     std::vector<uint32_t> mUpdatedDimensions;
180 
181     bool mInitialized = false;
182 };
183 
184 }  // namespace
185 
Memory(hal::hidl_memory memory)186 Memory::Memory(hal::hidl_memory memory)
187     : kHidlMemory(std::move(memory)),
188       mValidator(std::make_unique<SizedMemoryValidator>(kHidlMemory.size())) {}
189 
Memory(hal::hidl_memory memory,std::unique_ptr<MemoryValidatorBase> validator)190 Memory::Memory(hal::hidl_memory memory, std::unique_ptr<MemoryValidatorBase> validator)
191     : kHidlMemory(std::move(memory)), mValidator(std::move(validator)) {}
192 
Memory(sp<hal::IBuffer> buffer,uint32_t token)193 Memory::Memory(sp<hal::IBuffer> buffer, uint32_t token)
194     : kBuffer(std::move(buffer)), kToken(token) {}
195 
~Memory()196 Memory::~Memory() {
197     for (const auto& [ptr, weakBurst] : mUsedBy) {
198         if (const std::shared_ptr<ExecutionBurstController> burst = weakBurst.lock()) {
199             burst->freeMemory(getKey());
200         }
201     }
202 }
203 
getMemoryPool() const204 Request::MemoryPool Memory::getMemoryPool() const {
205     Request::MemoryPool pool;
206     if (kToken > 0) {
207         pool.token(kToken);
208     } else {
209         pool.hidlMemory(kHidlMemory);
210     }
211     return pool;
212 }
213 
getRunTimePoolInfo() const214 std::optional<RunTimePoolInfo> Memory::getRunTimePoolInfo() const {
215     std::lock_guard<std::mutex> guard(mMutex);
216     if (!mHasCachedRunTimePoolInfo) {
217         mCachedRunTimePoolInfo = RunTimePoolInfo::createFromHidlMemory(kHidlMemory);
218         mHasCachedRunTimePoolInfo = true;
219     }
220     return mCachedRunTimePoolInfo;
221 }
222 
getKey() const223 intptr_t Memory::getKey() const {
224     return reinterpret_cast<intptr_t>(this);
225 }
226 
usedBy(const std::shared_ptr<ExecutionBurstController> & burst) const227 void Memory::usedBy(const std::shared_ptr<ExecutionBurstController>& burst) const {
228     std::lock_guard<std::mutex> guard(mMutex);
229     mUsedBy.emplace(burst.get(), burst);
230 }
231 
copyHidlMemories(const std::optional<RunTimePoolInfo> & src,const std::optional<RunTimePoolInfo> & dst)232 static int copyHidlMemories(const std::optional<RunTimePoolInfo>& src,
233                             const std::optional<RunTimePoolInfo>& dst) {
234     if (!src.has_value() || !dst.has_value()) {
235         LOG(ERROR) << "ANeuralNetworksMemory_copy -- unable to map memory";
236         return ANEURALNETWORKS_UNMAPPABLE;
237     }
238     if (src->getSize() != dst->getSize()) {
239         LOG(ERROR) << "ANeuralNetworksMemory_copy -- incompatible memory size";
240         return ANEURALNETWORKS_BAD_DATA;
241     }
242     CHECK(src->getBuffer() != nullptr);
243     CHECK(dst->getBuffer() != nullptr);
244     std::copy(src->getBuffer(), src->getBuffer() + src->getSize(), dst->getBuffer());
245     dst->flush();
246     return ANEURALNETWORKS_NO_ERROR;
247 }
248 
copyIBufferToHidlMemory(const sp<IBuffer> & src,const hidl_memory & dst)249 int copyIBufferToHidlMemory(const sp<IBuffer>& src, const hidl_memory& dst) {
250     const auto ret = src->copyTo(dst);
251     if (!ret.isOk()) {
252         LOG(ERROR) << "ANeuralNetworksMemory_copy failure: " << ret.description();
253         return ANEURALNETWORKS_OP_FAILED;
254     }
255     return convertErrorStatusToResultCode(static_cast<ErrorStatus>(ret));
256 }
257 
copyHidlMemoryToIBuffer(const hidl_memory & src,const sp<IBuffer> & dst,const std::vector<uint32_t> & dimensions)258 int copyHidlMemoryToIBuffer(const hidl_memory& src, const sp<IBuffer>& dst,
259                             const std::vector<uint32_t>& dimensions) {
260     const auto ret = dst->copyFrom(src, dimensions);
261     if (!ret.isOk()) {
262         LOG(ERROR) << "ANeuralNetworksMemory_copy failure: " << ret.description();
263         return ANEURALNETWORKS_OP_FAILED;
264     }
265     return convertErrorStatusToResultCode(static_cast<ErrorStatus>(ret));
266 }
267 
copyIBuffers(const sp<IBuffer> & src,const sp<IBuffer> & dst,const MemoryValidatorBase::Metadata & srcMetadata)268 static int copyIBuffers(const sp<IBuffer>& src, const sp<IBuffer>& dst,
269                         const MemoryValidatorBase::Metadata& srcMetadata) {
270     const auto [n, memory] = MemoryRuntimeAHWB::create(srcMetadata.logicalSize);
271     NN_RETURN_IF_ERROR(n);
272     const hidl_memory& hidlMemory = memory->getHidlMemory();
273     if (!hidlMemory.valid()) return ANEURALNETWORKS_OUT_OF_MEMORY;
274     NN_RETURN_IF_ERROR(copyIBufferToHidlMemory(src, hidlMemory));
275     NN_RETURN_IF_ERROR(copyHidlMemoryToIBuffer(hidlMemory, dst, srcMetadata.dimensions));
276     return ANEURALNETWORKS_NO_ERROR;
277 }
278 
copyInternal(const Memory & src,const Memory & dst)279 static int copyInternal(const Memory& src, const Memory& dst) {
280     if (&src == &dst) return ANEURALNETWORKS_NO_ERROR;
281 
282     if (!src.getValidator().isInitialized()) {
283         LOG(ERROR) << "ANeuralNetworksMemory_copy -- uninitialized source memory";
284         return ANEURALNETWORKS_BAD_DATA;
285     }
286 
287     const auto srcMetadata = src.getValidator().getMetadata();
288     if (!dst.getValidator().updateMetadata(srcMetadata)) {
289         LOG(ERROR) << "ANeuralNetworksMemory_copy -- incompatible memories";
290         return ANEURALNETWORKS_BAD_DATA;
291     }
292 
293     bool srcHasHidlMemory = src.getHidlMemory().valid();
294     bool dstHasHidlMemory = dst.getHidlMemory().valid();
295     bool srcHasIBuffer = src.getIBuffer() != nullptr;
296     bool dstHasIBuffer = dst.getIBuffer() != nullptr;
297     if (srcHasIBuffer && dstHasIBuffer) {
298         return copyIBuffers(src.getIBuffer(), dst.getIBuffer(), srcMetadata);
299     } else if (srcHasHidlMemory && dstHasHidlMemory) {
300         return copyHidlMemories(src.getRunTimePoolInfo(), dst.getRunTimePoolInfo());
301     } else if (srcHasHidlMemory && dstHasIBuffer) {
302         return copyHidlMemoryToIBuffer(src.getHidlMemory(), dst.getIBuffer(),
303                                        srcMetadata.dimensions);
304     } else if (srcHasIBuffer && dstHasHidlMemory) {
305         return copyIBufferToHidlMemory(src.getIBuffer(), dst.getHidlMemory());
306     }
307     return ANEURALNETWORKS_OP_FAILED;
308 }
309 
copy(const Memory & src,const Memory & dst)310 int Memory::copy(const Memory& src, const Memory& dst) {
311     int n = copyInternal(src, dst);
312     dst.getValidator().setInitialized(n == ANEURALNETWORKS_NO_ERROR);
313     return n;
314 }
315 
badState(const char * name) const316 bool MemoryBuilder::badState(const char* name) const {
317     if (mFinished) {
318         LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << name << " can't modify after finished";
319         return true;
320     }
321     return false;
322 }
323 
addRole(const CompilationBuilder & compilation,IOType ioType,uint32_t index,float freq)324 int MemoryBuilder::addRole(const CompilationBuilder& compilation, IOType ioType, uint32_t index,
325                            float freq) {
326     const char* tag = ioType == IOType::INPUT ? "addInputRole" : "addOutputRole";
327     if (badState(tag)) {
328         return ANEURALNETWORKS_BAD_STATE;
329     }
330     if (mRoles.count({&compilation, ioType, index}) > 0) {
331         LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag
332                    << " -- the same operand is specified twice.";
333         return ANEURALNETWORKS_BAD_DATA;
334     }
335 
336     std::vector<std::tuple<const PreparedModel*, IOType, uint32_t>> roles;
337     auto callback = [&roles](const auto* preparedModel, IOType type, uint32_t index) {
338         roles.emplace_back(preparedModel, type, index);
339     };
340     if (ioType == IOType::INPUT) {
341         if (compilation.forEachStepRoleOfInput(index, callback) != ANEURALNETWORKS_NO_ERROR) {
342             return ANEURALNETWORKS_BAD_DATA;
343         }
344     } else {
345         if (compilation.forEachStepRoleOfOutput(index, callback) != ANEURALNETWORKS_NO_ERROR) {
346             return ANEURALNETWORKS_BAD_DATA;
347         }
348     }
349 
350     const ModelBuilder* model = compilation.getModel();
351     CHECK(model != nullptr);
352     Operand operand;
353     if (ioType == IOType::INPUT) {
354         if (index >= model->inputCount()) {
355             LOG(ERROR) << "ANeuralNetworksMemoryDesc_addInputRole -- input index out of range.";
356             return ANEURALNETWORKS_BAD_DATA;
357         }
358         operand = model->getInputOperand(index);
359     } else {
360         if (index >= model->outputCount()) {
361             LOG(ERROR) << "ANeuralNetworksMemoryDesc_addOutputRole -- output index out of range.";
362             return ANEURALNETWORKS_BAD_DATA;
363         }
364         operand = model->getOutputOperand(index);
365     }
366     if (mOperand.has_value()) {
367         if (operand.type != mOperand->type || operand.scale != mOperand->scale ||
368             operand.zeroPoint != mOperand->zeroPoint ||
369             operand.extraParams != mOperand->extraParams) {
370             LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag
371                        << " -- incompatible operand metadata.";
372             return ANEURALNETWORKS_BAD_DATA;
373         }
374     }
375     if (!TypeManager::get()->isTensorType(operand.type) && !mDesc.dimensions.empty()) {
376         LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- incompatible dimensions.";
377         return ANEURALNETWORKS_BAD_DATA;
378     }
379     auto combined = combineDimensions(mDesc.dimensions, operand.dimensions);
380     if (!combined.has_value()) {
381         LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- incompatible dimensions.";
382         return ANEURALNETWORKS_BAD_DATA;
383     }
384 
385     if (freq > 1.0f || freq <= 0.0f) {
386         LOG(ERROR) << "ANeuralNetworksMemoryDesc_" << tag << " -- invalid frequency " << freq;
387         return ANEURALNETWORKS_BAD_DATA;
388     }
389 
390     mRoles.emplace(&compilation, ioType, index);
391     for (const auto& [preparedModel, type, ind] : roles) {
392         uint32_t modelIndex = mDesc.preparedModels.add(preparedModel);
393         BufferRole role = {.modelIndex = modelIndex, .ioIndex = ind, .frequency = freq};
394         if (type == IOType::INPUT) {
395             mDesc.inputRoles.push_back(role);
396         } else {
397             mDesc.outputRoles.push_back(role);
398         }
399     }
400     mOperand = std::move(operand);
401     mDesc.dimensions = std::move(combined.value());
402     return ANEURALNETWORKS_NO_ERROR;
403 }
404 
setDimensions(const std::vector<uint32_t> & dimensions)405 int MemoryBuilder::setDimensions(const std::vector<uint32_t>& dimensions) {
406     if (badState("setDimensions")) return ANEURALNETWORKS_BAD_STATE;
407     if (mOperand.has_value() && !TypeManager::get()->isTensorType(mOperand->type) &&
408         !dimensions.empty()) {
409         LOG(ERROR) << "ANeuralNetworksMemoryDesc_setDimensions -- incompatible dimensions for "
410                       "scalars.";
411         return ANEURALNETWORKS_BAD_DATA;
412     }
413     auto combined = combineDimensions(mDesc.dimensions, dimensions);
414     if (!combined.has_value()) {
415         LOG(ERROR) << "ANeuralNetworksMemoryDesc_setDimensions -- incompatible dimensions.";
416         return ANEURALNETWORKS_BAD_DATA;
417     }
418     mDesc.dimensions = std::move(combined.value());
419     return ANEURALNETWORKS_NO_ERROR;
420 }
421 
logMemoryDescriptorToInfo(const MemoryDescriptor & desc,const Operand & operand)422 static void logMemoryDescriptorToInfo(const MemoryDescriptor& desc, const Operand& operand) {
423     LOG(INFO) << "MemoryDescriptor start";
424     LOG(INFO) << "    Data type: " << toString(operand.type);
425     LOG(INFO) << "    Scale: " << toString(operand.scale);
426     LOG(INFO) << "    Zero point: " << toString(operand.zeroPoint);
427     LOG(INFO) << "    Extra params: " << toString(operand.extraParams);
428     LOG(INFO) << "    Dimensions: " << toString(desc.dimensions);
429     LOG(INFO) << "    Prepared models [" << desc.preparedModels.size() << "]:";
430     for (const auto* preparedModel : desc.preparedModels) {
431         LOG(INFO) << "        service = " << preparedModel->getDevice()->getName();
432     }
433     LOG(INFO) << "    Input roles [" << desc.inputRoles.size() << "]:";
434     for (const auto& usage : desc.inputRoles) {
435         LOG(INFO) << "        " << toString(usage);
436     }
437     LOG(INFO) << "    Output roles [" << desc.outputRoles.size() << "]:";
438     for (const auto& usage : desc.outputRoles) {
439         LOG(INFO) << "        " << toString(usage);
440     }
441     LOG(INFO) << "MemoryDescriptor end";
442 }
443 
getDevices(const MemoryDescriptor & desc)444 static std::set<const Device*> getDevices(const MemoryDescriptor& desc) {
445     std::set<const Device*> devices;
446     for (const auto* preparedModel : desc.preparedModels) {
447         const auto* device = preparedModel->getDevice();
448         devices.insert(device);
449     }
450     return devices;
451 }
452 
finish()453 int MemoryBuilder::finish() {
454     if (badState("finish")) return ANEURALNETWORKS_BAD_STATE;
455     if (mRoles.empty()) {
456         LOG(ERROR) << "ANeuralNetworksMemoryDesc_finish -- no role has been specified.";
457         return ANEURALNETWORKS_BAD_DATA;
458     }
459     CHECK(mOperand.has_value());
460     if (VLOG_IS_ON(MEMORY)) {
461         logMemoryDescriptorToInfo(mDesc, mOperand.value());
462     }
463     std::set<const Device*> devices = getDevices(mDesc);
464     if (devices.empty()) {
465         // This can happen with interpreted control flow.
466         mAllocator = nullptr;
467     } else if (devices.size() == 1) {
468         mAllocator = *devices.begin();
469         VLOG(MEMORY) << "Using " << mAllocator->getName() << " as allocator.";
470     } else {
471         LOG(INFO) << "MemoryBuilder::finish -- cannot handle multiple devices.";
472         mAllocator = nullptr;
473     }
474     mSupportsAhwb = std::all_of(devices.begin(), devices.end(), [](const auto* device) {
475         return device->getFeatureLevel() >= __ANDROID_API_R__;
476     });
477     mShouldFallback = std::none_of(mRoles.begin(), mRoles.end(), [](const auto& role) {
478         const auto* cb = std::get<const CompilationBuilder*>(role);
479         return cb->createdWithExplicitDeviceList();
480     });
481     const uint32_t size = TypeManager::get()->getSizeOfData(mOperand->type, mDesc.dimensions);
482     mShouldFallback &= (size != 0);
483     mFinished = true;
484     return ANEURALNETWORKS_NO_ERROR;
485 }
486 
allocate() const487 std::pair<int, std::unique_ptr<Memory>> MemoryBuilder::allocate() const {
488     if (!mFinished) {
489         LOG(ERROR) << "ANeuralNetworksMemory_createFromDesc -- passed an unfinished descriptor";
490         return {ANEURALNETWORKS_BAD_STATE, nullptr};
491     }
492 
493     int n = ANEURALNETWORKS_OP_FAILED;
494     std::unique_ptr<Memory> memory;
495     CHECK(mOperand.has_value());
496 
497     // Try allocate the memory on device.
498     if (mAllocator != nullptr) {
499         std::tie(n, memory) = mAllocator->allocate(mDesc, mOperand->type);
500     }
501 
502     // If failed, fallback to ashmem or BLOB mode AHWB.
503     if (n != ANEURALNETWORKS_NO_ERROR && mShouldFallback) {
504         const uint32_t size = TypeManager::get()->getSizeOfData(mOperand->type, mDesc.dimensions);
505         if (mSupportsAhwb) {
506             VLOG(MEMORY) << "MemoryBuilder::allocate -- fallback to BLOB mode AHWB.";
507             std::tie(n, memory) = MemoryRuntimeAHWB::create(size);
508         } else {
509             VLOG(MEMORY) << "MemoryBuilder::allocate -- fallback to ashmem.";
510             std::tie(n, memory) = MemoryAshmem::create(size);
511         }
512     }
513 
514     if (n == ANEURALNETWORKS_NO_ERROR) {
515         CHECK(memory != nullptr);
516         auto validator =
517                 std::make_unique<DeviceMemoryValidator>(mRoles, mOperand.value(), mDesc.dimensions);
518         memory->setValidator(std::move(validator));
519     }
520     return {n, std::move(memory)};
521 }
522 
create(uint32_t size)523 std::pair<int, std::unique_ptr<MemoryAshmem>> MemoryAshmem::create(uint32_t size) {
524     hidl_memory hidlMemory = allocateSharedMemory(size);
525     sp<IMemory> mapped = mapMemory(hidlMemory);
526     if (mapped == nullptr || mapped->getPointer() == nullptr) {
527         LOG(ERROR) << "Memory::create failed";
528         return {ANEURALNETWORKS_OUT_OF_MEMORY, nullptr};
529     }
530     return {ANEURALNETWORKS_NO_ERROR,
531             std::make_unique<MemoryAshmem>(std::move(mapped), std::move(hidlMemory))};
532 }
533 
getPointer() const534 uint8_t* MemoryAshmem::getPointer() const {
535     return static_cast<uint8_t*>(static_cast<void*>(kMappedMemory->getPointer()));
536 }
537 
MemoryAshmem(sp<IMemory> mapped,hidl_memory memory)538 MemoryAshmem::MemoryAshmem(sp<IMemory> mapped, hidl_memory memory)
539     : Memory(std::move(memory)), kMappedMemory(std::move(mapped)) {}
540 
create(size_t size,int prot,int fd,size_t offset)541 std::pair<int, std::unique_ptr<MemoryFd>> MemoryFd::create(size_t size, int prot, int fd,
542                                                            size_t offset) {
543     if (size == 0 || fd < 0) {
544         LOG(ERROR) << "Invalid size or fd";
545         return {ANEURALNETWORKS_BAD_DATA, nullptr};
546     }
547 
548     // Duplicate the file descriptor so MemoryFd owns its own version.
549     int dupfd = dup(fd);
550     if (dupfd == -1) {
551         LOG(ERROR) << "Failed to dup the fd";
552         // TODO(b/120417090): is ANEURALNETWORKS_UNEXPECTED_NULL the correct
553         // error to return here?
554         return {ANEURALNETWORKS_UNEXPECTED_NULL, nullptr};
555     }
556 
557     // Create a temporary native handle to own the dupfd.
558     native_handle_t* nativeHandle = native_handle_create(1, 3);
559     if (nativeHandle == nullptr) {
560         LOG(ERROR) << "Failed to create native_handle";
561         // TODO(b/120417090): is ANEURALNETWORKS_UNEXPECTED_NULL the correct
562         // error to return here?
563         return {ANEURALNETWORKS_UNEXPECTED_NULL, nullptr};
564     }
565     nativeHandle->data[0] = dupfd;
566     nativeHandle->data[1] = prot;
567     const uint64_t bits = static_cast<uint64_t>(offset);
568     nativeHandle->data[2] = (int32_t)(uint32_t)(bits & 0xffffffff);
569     nativeHandle->data[3] = (int32_t)(uint32_t)(bits >> 32);
570 
571     // Create a hidl_handle which owns the native handle and fd so that we don't
572     // have to manually clean either the native handle or the fd.
573     hardware::hidl_handle hidlHandle;
574     hidlHandle.setTo(nativeHandle, /*shouldOwn=*/true);
575 
576     // Push the hidl_handle into a hidl_memory object. The hidl_memory object is
577     // responsible for cleaning the hidl_handle, the native handle, and the fd.
578     hidl_memory hidlMemory = hidl_memory("mmap_fd", std::move(hidlHandle), size);
579 
580     return {ANEURALNETWORKS_NO_ERROR, std::make_unique<MemoryFd>(std::move(hidlMemory))};
581 }
582 
MemoryFd(hidl_memory memory)583 MemoryFd::MemoryFd(hidl_memory memory) : Memory(std::move(memory)) {}
584 
create(const AHardwareBuffer & ahwb)585 std::pair<int, std::unique_ptr<MemoryAHWB>> MemoryAHWB::create(const AHardwareBuffer& ahwb) {
586     AHardwareBuffer_Desc bufferDesc;
587     AHardwareBuffer_describe(&ahwb, &bufferDesc);
588     const native_handle_t* handle = AHardwareBuffer_getNativeHandle(&ahwb);
589     hidl_memory hidlMemory;
590     std::unique_ptr<MemoryValidatorBase> validator;
591     if (bufferDesc.format == AHARDWAREBUFFER_FORMAT_BLOB) {
592         hidlMemory = hidl_memory("hardware_buffer_blob", handle, bufferDesc.width);
593         validator = std::make_unique<SizedMemoryValidator>(bufferDesc.width);
594     } else {
595         // memory size is not used.
596         hidlMemory = hidl_memory("hardware_buffer", handle, 0);
597         validator = std::make_unique<AHardwareBufferNonBlobValidator>();
598     }
599     auto memory = std::make_unique<MemoryAHWB>(std::move(hidlMemory), std::move(validator));
600     return {ANEURALNETWORKS_NO_ERROR, std::move(memory)};
601 };
602 
create(uint32_t size)603 std::pair<int, std::unique_ptr<MemoryRuntimeAHWB>> MemoryRuntimeAHWB::create(uint32_t size) {
604     AHardwareBuffer* ahwb = nullptr;
605     const auto usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;
606     const AHardwareBuffer_Desc desc = {
607             .width = size,
608             .height = 1,
609             .layers = 1,
610             .format = AHARDWAREBUFFER_FORMAT_BLOB,
611             .usage = usage,
612             .stride = size,
613     };
614     int err = AHardwareBuffer_allocate(&desc, &ahwb);
615     if (err != 0 || ahwb == nullptr) {
616         LOG(ERROR) << "Failed to allocate BLOB mode AHWB.";
617         return {ANEURALNETWORKS_OP_FAILED, nullptr};
618     }
619     auto allocateGuard = base::make_scope_guard([&ahwb]() { AHardwareBuffer_release(ahwb); });
620 
621     void* buffer = nullptr;
622     err = AHardwareBuffer_lock(ahwb, usage, -1, nullptr, &buffer);
623     if (err != 0 || buffer == nullptr) {
624         LOG(ERROR) << "Failed to lock BLOB mode AHWB.";
625         return {ANEURALNETWORKS_OP_FAILED, nullptr};
626     }
627     auto lockGuard = base::make_scope_guard([&ahwb]() { AHardwareBuffer_unlock(ahwb, nullptr); });
628 
629     const native_handle_t* handle = AHardwareBuffer_getNativeHandle(ahwb);
630     if (handle == nullptr) {
631         LOG(ERROR) << "Failed to retrieve the native handle from the AHWB.";
632         return {ANEURALNETWORKS_OP_FAILED, nullptr};
633     }
634 
635     hidl_memory hidlMemory = hidl_memory("hardware_buffer_blob", handle, desc.width);
636     auto memory = std::make_unique<MemoryRuntimeAHWB>(std::move(hidlMemory), ahwb,
637                                                       static_cast<uint8_t*>(buffer));
638     allocateGuard.Disable();
639     lockGuard.Disable();
640     return {ANEURALNETWORKS_NO_ERROR, std::move(memory)};
641 }
642 
MemoryRuntimeAHWB(hal::hidl_memory memory,AHardwareBuffer * ahwb,uint8_t * buffer)643 MemoryRuntimeAHWB::MemoryRuntimeAHWB(hal::hidl_memory memory, AHardwareBuffer* ahwb,
644                                      uint8_t* buffer)
645     : Memory(std::move(memory)), mAhwb(ahwb), mBuffer(buffer) {
646     CHECK(mAhwb != nullptr);
647     CHECK(mBuffer != nullptr);
648 }
649 
~MemoryRuntimeAHWB()650 MemoryRuntimeAHWB::~MemoryRuntimeAHWB() {
651     AHardwareBuffer_unlock(mAhwb, nullptr);
652     AHardwareBuffer_release(mAhwb);
653 }
654 
create(sp<hal::IBuffer> buffer,uint32_t token)655 std::pair<int, std::unique_ptr<MemoryFromDevice>> MemoryFromDevice::create(sp<hal::IBuffer> buffer,
656                                                                            uint32_t token) {
657     if (buffer == nullptr) {
658         LOG(ERROR) << "nullptr IBuffer for device memory.";
659         return {ANEURALNETWORKS_OP_FAILED, nullptr};
660     }
661     if (token <= 0) {
662         LOG(ERROR) << "Invalid token for device memory: " << token;
663         return {ANEURALNETWORKS_OP_FAILED, nullptr};
664     }
665     return {ANEURALNETWORKS_NO_ERROR, std::make_unique<MemoryFromDevice>(std::move(buffer), token)};
666 };
667 
MemoryFromDevice(sp<hal::IBuffer> buffer,uint32_t token)668 MemoryFromDevice::MemoryFromDevice(sp<hal::IBuffer> buffer, uint32_t token)
669     : Memory(std::move(buffer), token) {}
670 
671 }  // namespace nn
672 }  // namespace android
673