通过在用户客户端子类(在驱动程序侧)中实现IOUserClient :: CopyClientMemoryForType,然后从用户空间应用程序调用IOConnectMapMemory64,可以从驱动程序扩展内存映射到应用程序。这已经在this related answer中非常好地解释了。
唯一缺少的部分是获取与所需PCI BAR相对应的IOMemoryDescriptor,以便从
CopyClientMemoryForType
实现返回它。
示例代码
换句话说,假设有以下简化的代码,那么imaginaryFunctionWhichReturnsTheBARBuffer
的实现是什么?
kern_return_t IMPL(MyUserClient, CopyClientMemoryForType) //(uint64_t type, uint64_t *options, IOMemoryDescriptor **memory)
{
IOMemoryDescriptor* buffer = nullptr;
imaginaryFunctionWhichReturnsTheBARBuffer(ivars->pciDevice /* IOPCIDevice */, kPCIMemoryRangeBAR0, &buffer);
*memory = buffer;
return kIOReturnSuccess;
}
在先前的代码中,
ivars->pciDevice
指的是一个已准备好使用的IOPCIDevice(例如:它已成功匹配、打开并根据最佳实践进行配置)。这意味着已经可以使用各种配置和内存读/写方法来访问所需PCI BAR内存的显式偏移量。缺少的是如何使用这些API(或等效的API)将对应于PCI BAR的整个缓冲区映射到用户空间应用程序。
可能相关的随机注释
This answer from the related question: How to allocate memory in a DriverKit system extension and map it to another process? contains the following quote:
[...] The returned memory descriptor need not be an IOBufferMemoryDescriptor as I've used in the example, it can also be a PCI BAR or whatever.
This is exactly what I want to do, so at least it sounds like it should be possible. The only remaining question is how to implement it.
A similar question has been posted on the Apple forums and even though it hasn't received any answers yet (as of the time of this writing), it does contain some useful pointers.
It looks like there is a private function in PCIDriverKit with the following signature:
virtual kern_return_t IOPCIDevice::_CopyDeviceMemoryWithIndex(uint64_t memoryIndex, IOMemoryDescriptor** memory, IOService* forClient)
It's hard to tell what it's supposed to do exactly (since it is undocumented), but the signature does seem to match with the function I'm looking for. However, trying to use it always results in an error code (similar to the one reported in the original forum post). The error code seems to be different depending on which argument is passed as
IOService *forClient
).Another good point from that post is that there is a getDeviceMemoryWithIndex available to kernel extensions (KEXT) which could be used to accomplish what we need (if the driver was implemented as a PCI kernel extension which seems to be deprecated now).
However, this function doesn't seem to be available to driver extensions (DEXT). So another question of framing this question could be: What's the equivalent
getDeviceMemoryWithIndex
for PCIDriverKit driver extensions?
IOPCIDevice
上的MemoryRead*
和MemoryWrite*
方法系列。就我所知,在总线上发生的事情方面,这是有道理的。如果您的设备希望通过BAR交换大量数据,则这很不幸,因为这正是DMA的用途。而DMA在ARM上的工作方式与以前相同(IODMACommand
等)。 - pmdj