自 2025 年 3 月 27 日起,我们建议您使用 android-latest-release
而非 aosp-main
构建 AOSP 并为其做出贡献。如需了解详情,请参阅 AOSP 的变更。
HIDL MemoryBlock
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
HIDL MemoryBlock
是一个在 hidl_memory
、HIDL
@1.0::IAllocator
和 HIDL @1.0::IMapper
的基础上构建而成的抽象层。它专为有多个内存块共用单个内存堆的 HIDL 服务而设计。
在应用中使用 MemoryBlock
可显著减少 mmap
/munmap
数量和用户空间细分错误,从而提升性能。例如:
- 对每项缓冲区分配使用一个
hidl_memory
,则每次分配平均用时 238 微秒。
- 使用
MemoryBlock
并共享单个 hidl_memory
,则每次分配平均用时 2.82 微秒。
架构
HIDL MemoryBlock
架构包括一些有多个内存块共用单个内存堆的 HIDL 服务:
图 1. HIDL MemoryBlock 架构
常规用法
本部分提供了一个关于如何通过以下方式使用 MemoryBlock
的示例:先声明 HAL,然后实现 HAL。
声明 HAL
对于以下示例 IFoo HAL:
import android.hidl.memory.block@1.0::MemoryBlock;
interface IFoo {
getSome() generates(MemoryBlock block);
giveBack(MemoryBlock block);
};
Android.bp
如下所示:
hidl_interface {
...
srcs: [
"IFoo.hal",
],
interfaces: [
"android.hidl.memory.block@1.0",
...
};
实现 HAL
要实现示例 HAL,请执行以下操作:
获取 hidl_memory
(如需了解详情,请参阅 HIDL C++)。
#include <android/hidl/allocator/1.0/IAllocator.h>
using ::android::hidl::allocator::V1_0::IAllocator;
using ::android::hardware::hidl_memory;
...
sp<IAllocator> allocator = IAllocator::getService("ashmem");
allocator->allocate(2048, [&](bool success, const hidl_memory& mem)
{
if (!success) { /* error */ }
// you can now use the hidl_memory object 'mem' or pass it
}));
使用获取的 hidl_memory
创建 HidlMemoryDealer
实例:
#include <hidlmemory/HidlMemoryDealer.h>
using ::android::hardware::HidlMemoryDealer
/* The mem argument is acquired in the Step1, returned by the ashmemAllocator->allocate */
sp<HidlMemoryDealer> memory_dealer = HidlMemoryDealer::getInstance(mem);
分配 MemoryBlock
(使用 HIDL 定义的结构体)。
MemoryBlock
示例:
struct MemoryBlock {
IMemoryToken token;
uint64_t size;
uint64_t offset;
};
使用 MemoryDealer
分配 MemoryBlock
的示例:
#include <android/hidl/memory/block/1.0/types.h>
using ::android::hidl::memory::block::V1_0::MemoryBlock;
Return<void> Foo::getSome(getSome_cb _hidl_cb) {
MemoryBlock block = memory_dealer->allocate(1024);
if(HidlMemoryDealer::isOk(block)){
_hidl_cb(block);
...
取消分配 MemoryBlock
:
Return<void> Foo::giveBack(const MemoryBlock& block) {
memory_dealer->deallocate(block.offset);
...
操控数据:
#include <hidlmemory/mapping.h>
#include <android/hidl/memory/1.0/IMemory.h>
using ::android::hidl::memory::V1_0::IMemory;
sp<IMemory> memory = mapMemory(block);
uint8_t* data =
static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
配置 Android.bp
:
shared_libs: [
"android.hidl.memory@1.0",
"android.hidl.memory.block@1.0"
"android.hidl.memory.token@1.0",
"libhidlbase",
"libhidlmemory",
查看流程,确定是否需要 lockMemory
。
通常,MemoryBlock
使用引用计数来维护共享的 hidl_memory
:当整个锁定生命周期内有任一 MemoryBlock
instances is mapped and is
munmap()-ed when nothing refers to it. To keep
hidl_memoryalways mapped, you can use
lockMemory, a RAII style object
that keeps the corresponding
hidl_memory` 首次被映射时,系统会对该内存执行 mmap()
操作。示例:
#include <hidlmemory/mapping.h>
sp<RefBase> lockMemory(const sp<IMemoryToken> key);
扩展用法
本部分详细介绍了 MemoryBlock
的扩展用法。
使用引用计数管理 MemoryBlock
在大多数情况下,要使用 MemoryBlock
,最高效的方法是明确分配/解除分配。不过,在复杂应用中,使用引用计数进行垃圾回收可能会更好。要获得 MemoryBlock
的引用计数,您可将 MemoryBlock
与 binder 对象绑定,这有助于对引用进行计数,并在计数降至零时解除 MemoryBlock
分配。
声明 HAL
声明 HAL 时,请描述包含 MemoryBlock
实例和 IBase 的 HIDL 结构体:
import android.hidl.memory.block@1.0::MemoryBlock;
struct MemoryBlockAllocation {
MemoryBlock block;
IBase refcnt;
};
使用 MemoryBlockAllocation
替换 MemoryBlock
,并移除用于释放 MemoryBlock
的方法。它由引用计数功能通过 MemoryBlockAllocation
取消分配。示例:
interface IFoo {
allocateSome() generates(MemoryBlockAllocation allocation);
};
实现 HAL
HAL 服务端实现示例:
class MemoryBlockRefCnt: public virtual IBase {
MemoryBlockRefCnt(uint64_t offset, sp<MemoryDealer> dealer)
: mOffset(offset), mDealer(dealer) {}
~MemoryBlockRefCnt() {
mDealer->deallocate(mOffset);
}
private:
uint64_t mOffset;
sp<MemoryDealer> mDealer;
};
Return<void> Foo::allocateSome(allocateSome_cb _hidl_cb) {
MemoryBlockAllocation allocation;
allocation.block = memory_dealer->allocate(1024);
if(HidlMemoryDealer::isOk(block)){
allocation.refcnt= new MemoryBlockRefCnt(...);
_hidl_cb(allocation);
HAL 客户端实现示例:
ifoo->allocateSome([&](const MemoryBlockAllocation& allocation){
...
);
某些应用需要额外的数据才能与所分配的 MemoryBlock
绑定。您可以使用以下两种方法附加和检索元数据:
如果应用访问元数据的频率与访问内存块本身的频率相同,请附加元数据并以结构体的形式传递所有元数据。示例:
import android.hidl.memory.block@1.0::MemoryBlock;
struct MemoryBlockWithMetaData{
MemoryBlock block;
MetaDataStruct metaData;
};
如果应用访问元数据的频率远低于访问内存块的频率,则使用接口被动传递元数据会更加高效。示例:
import android.hidl.memory.block@1.0::MemoryBlock;
struct MemoryBlockWithMetaData{
MemoryBlock block;
IMetaData metaData;
};
接下来,使用 MemoryDealer
将元数据与 MemoryBlock
绑定。示例:
MemoryBlockWithMetaData memory_block;
memory_block.block = dealer->allocate(size);
if(HidlMemoryDealer::isOk(block)){
memory_block.metaData = new MetaData(...);
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-03-04。
[null,null,["最后更新时间 (UTC):2025-03-04。"],[],[],null,["# HIDL MemoryBlock\n\nThe HIDL `MemoryBlock` is an abstract layer built on `hidl_memory`, `HIDL\n@1.0::IAllocator`, and `HIDL @1.0::IMapper`. It is designed for HIDL services\nthat have multiple memory blocks to share a single memory heap.\n\nPerformance improvements\n------------------------\n\nUsing `MemoryBlock` in apps can significantly reduce the number of\n`mmap`/`munmap` and user space segmentation faults, thus improving performance.\nFor example:\n\n- Using per `hidl_memory` for each buffer allocation averages 238 us/1 allocation.\n- Using `MemoryBlock` and sharing a single `hidl_memory` averages 2.82 us/1 allocation.\n\nArchitecture\n------------\n\nThe HIDL `MemoryBlock` architecture includes HIDL services with multiple memory\nblocks sharing a single memory heap:\n\n**Figure 1.** HIDL MemoryBlock architecture\n\nNormal usage\n------------\n\nThis section provides an example of using `MemoryBlock` by first declaring the\nHAL then implementing the HAL.\n\n### Declare the HAL\n\nFor the following example IFoo HAL: \n\n import android.hidl.memory.block@1.0::MemoryBlock;\n\n interface IFoo {\n getSome() generates(MemoryBlock block);\n giveBack(MemoryBlock block);\n };\n\nThe `Android.bp` is as follows: \n\n hidl_interface {\n ...\n srcs: [\n \"IFoo.hal\",\n ],\n interfaces: [\n \"android.hidl.memory.block@1.0\",\n ...\n };\n\n### Implement the HAL\n\nTo implement the example HAL:\n\n1. Get the `hidl_memory` (for details, refer to [HIDL\n C++](/docs/core/architecture/hidl-cpp)).\n\n #include \u003candroid/hidl/allocator/1.0/IAllocator.h\u003e\n\n using ::android::hidl::allocator::V1_0::IAllocator;\n using ::android::hardware::hidl_memory;\n ...\n sp\u003cIAllocator\u003e allocator = IAllocator::getService(\"ashmem\");\n allocator-\u003eallocate(2048, [&](bool success, const hidl_memory& mem)\n {\n if (!success) { /* error */ }\n // you can now use the hidl_memory object 'mem' or pass it\n }));\n\n2. Make a `HidlMemoryDealer` instance with the acquired `hidl_memory`:\n\n #include \u003chidlmemory/HidlMemoryDealer.h\u003e\n\n using ::android::hardware::HidlMemoryDealer\n /* The mem argument is acquired in the Step1, returned by the ashmemAllocator-\u003eallocate */\n sp\u003cHidlMemoryDealer\u003e memory_dealer = HidlMemoryDealer::getInstance(mem);\n\n3. Allocate `MemoryBlock`, which is a struct defined with HIDL.\n\n Example `MemoryBlock`: \n\n struct MemoryBlock {\n IMemoryToken token;\n uint64_t size;\n uint64_t offset;\n };\n\n Example using the `MemoryDealer` to allocate a `MemoryBlock`: \n\n #include \u003candroid/hidl/memory/block/1.0/types.h\u003e\n\n using ::android::hidl::memory::block::V1_0::MemoryBlock;\n\n Return\u003cvoid\u003e Foo::getSome(getSome_cb _hidl_cb) {\n MemoryBlock block = memory_dealer-\u003eallocate(1024);\n if(HidlMemoryDealer::isOk(block)){\n _hidl_cb(block);\n ...\n\n4. Deallocate `MemoryBlock`:\n\n Return\u003cvoid\u003e Foo::giveBack(const MemoryBlock& block) {\n memory_dealer-\u003edeallocate(block.offset);\n ...\n\n5. Manipulate the data:\n\n #include \u003chidlmemory/mapping.h\u003e\n #include \u003candroid/hidl/memory/1.0/IMemory.h\u003e\n\n using ::android::hidl::memory::V1_0::IMemory;\n\n sp\u003cIMemory\u003e memory = mapMemory(block);\n uint8_t* data =\n\n static_cast\u003cuint8_t*\u003e(static_cast\u003cvoid*\u003e(memory-\u003egetPointer()));\n\n6. Config `Android.bp`:\n\n shared_libs: [\n \"android.hidl.memory@1.0\",\n\n \"android.hidl.memory.block@1.0\"\n\n \"android.hidl.memory.token@1.0\",\n \"libhidlbase\",\n \"libhidlmemory\",\n\n7. Review the flow to determine if you need to `lockMemory`.\n\n Normally, `MemoryBlock` uses reference count to maintain the shared\n `hidl_memory` which is `mmap()`-ed the first time one of its `MemoryBlock\n instances is mapped and is`munmap()`-ed when nothing refers to it. To keep`hidl_memory`always mapped, you can use`lockMemory`, a RAII style object\n that keeps the corresponding`hidl_memory\\` mapped throughout the lock\n lifecycle. Example: \n\n #include \u003chidlmemory/mapping.h\u003e\n\n sp\u003cRefBase\u003e lockMemory(const sp\u003cIMemoryToken\u003e key);\n\nExtended usage\n--------------\n\nThis section provides details about the extended usage of `MemoryBlock`.\n\n### Use reference count to manage MemoryBlock\n\nIn most situations, the most efficient way to use `MemoryBlock` is to explicitly\nallocate/deallocate. However, in complicated apps using reference count\nfor garbage collection might be a better idea. To have reference count on\n`MemoryBlock`, you can bind `MemoryBlock` with a binder object, which helps to\ncount the references and deallocate the `MemoryBlock` when the count decreases\nto zero.\n\n### Declare the HAL\n\nWhen declaring the HAL, describe a HIDL struct that contains a `MemoryBlock`\ninstance and an IBase: \n\n import android.hidl.memory.block@1.0::MemoryBlock;\n\n struct MemoryBlockAllocation {\n MemoryBlock block;\n IBase refcnt;\n };\n\nUse `MemoryBlockAllocation` to replace `MemoryBlock` and remove the method\nto give back `MemoryBlock`. It's deallocated by reference counting\nwith `MemoryBlockAllocation`. Example: \n\n interface IFoo {\n allocateSome() generates(MemoryBlockAllocation allocation);\n };\n\n### Implement the HAL\n\nExample of the service side implementation of the HAL: \n\n class MemoryBlockRefCnt: public virtual IBase {\n MemoryBlockRefCnt(uint64_t offset, sp\u003cMemoryDealer\u003e dealer)\n : mOffset(offset), mDealer(dealer) {}\n ~MemoryBlockRefCnt() {\n mDealer-\u003edeallocate(mOffset);\n }\n private:\n uint64_t mOffset;\n sp\u003cMemoryDealer\u003e mDealer;\n };\n\n Return\u003cvoid\u003e Foo::allocateSome(allocateSome_cb _hidl_cb) {\n MemoryBlockAllocation allocation;\n allocation.block = memory_dealer-\u003eallocate(1024);\n if(HidlMemoryDealer::isOk(block)){\n allocation.refcnt= new MemoryBlockRefCnt(...);\n _hidl_cb(allocation);\n\nExample of the client side implementation of the HAL: \n\n ifoo-\u003eallocateSome([&](const MemoryBlockAllocation& allocation){\n ...\n );\n\n### Attach and retrieve metadata\n\nSome apps need additional data to bind with the allocated `MemoryBlock`.\nYou can append and retrieve metadata using two methods:\n\n- If the app accesses the metadata as often as the block itself,\n append the metadata and pass them all in a struct. Example:\n\n import android.hidl.memory.block@1.0::MemoryBlock;\n\n struct MemoryBlockWithMetaData{\n MemoryBlock block;\n MetaDataStruct metaData;\n };\n\n- If the app accesses the metadata much less frequently than the\n block, it is more efficient to pass the metadata passively with an\n interface. Example:\n\n import android.hidl.memory.block@1.0::MemoryBlock;\n\n struct MemoryBlockWithMetaData{\n MemoryBlock block;\n IMetaData metaData;\n };\n\n Next, bind the metadata with the `MemoryBlock` using `MemoryDealer`.\n Example: \n\n MemoryBlockWithMetaData memory_block;\n memory_block.block = dealer-\u003eallocate(size);\n if(HidlMemoryDealer::isOk(block)){\n memory_block.metaData = new MetaData(...);"]]