communicating with a memory mapped device in linux

时间:2016-07-11 22:14:59

标签: c linux

I have a memory mapped device and I need to communicate with it. My boss told me that it is possible to it through /dev/mem. I looked online and didn't find anything related to it. Is it possible to do it or my boss was wrong?

Assume that you have superuser permissions.

Any help is appreciated.

3 个答案:

答案 0 :(得分:2)

你在地址MMIO_ADDR有一个占用MMIO_LEN个字节的内存映射设备。您需要在设备的地址空间中切换第123个字节。这看起来像这样:

#define MMIO_ADDR 0xDEAD0000
#define MMIO_LEN  0x400

// open a handle into physical memory, requires root
int memfd = open("/dev/mem", O_RDWR);
// map the range [MMIO_ADDR, MMIO_ADDR+MMIO_LEN] into your virtual address space
unsigned char* shmem = mmap(0, MMIO_LEN, PROT_WRITE | PROT_READ, MAP_SHARED, memfd, MMIO_ADDR);

// do your deed
unsigned char *magic_toggle_byte = &shmem[123];
*magic_toggle_byte = !*magic_toggle_byte;

答案 1 :(得分:1)

The device node /dev/mem gives you direct access to the system's physical memory.

You can find device memory mappings in /proc/iomem. Note that there is also /dev/ports and its counterpart /proc/ioports. Through the files in /proc you would determine at which position in /dev/mem your device's memory is mapped.

It is certainly possible to use /dev/mem for accessing mapped regions (often, access is explicitely restricted to memory-mapped regions) using regular file operations. I cannot tell you if it is the best way to do it though.

答案 2 :(得分:0)

The file /dev/mem has a man page. It sounds like you just open /dev/mem and do regular file operations to read and write from memory. You would probably use the open system call to open it, lseek to go to a particular address, and read or write to access the memory at that address.

It looks like the kernel source code that powers /dev/mem is here:

http://lxr.free-electrons.com/source/drivers/char/mem.c