flashburn
flashburn

Reputation: 4508

communicating with a memory mapped device in 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.

Upvotes: 2

Views: 2950

Answers (3)

a3f
a3f

Reputation: 8657

You got a memory mapped device at address MMIO_ADDR which occupies MMIO_LEN of bytes. You need to toggle the 123rd byte in the device's address space. This could look like this:

#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;

Upvotes: 2

David Grayson
David Grayson

Reputation: 87386

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

Upvotes: 0

ypnos
ypnos

Reputation: 52317

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.

Upvotes: 1

Related Questions