Working with mem-mapped i/o

I want to open /dev/mem on linux with a memmap::MmapMut over a specific I/O-mapped area of memory. Because of I/O side-effects I want all my reads/writes to be volatile. Is there a better way than

// mmap is a MmapMut
ptr::write_volatile(mmap.as_ptr().offset(my_offset))

, for example without using raw pointers?

1 Like

If these writes are safe, then you could implement Index & IndexMut for the object owning the pointer.

2 Likes

How do I know if they are safe - I'm not an expert on raw i/o

One way would be to restrict the memory access of the pointer-owning object to the memory-mapped I/O address range, and to make sure that the user can only spawn at most one such object during the entire lifetime of an application.

But as alto's README reminds us, the latter can be tricky...

You also add (unsafe) helper methods to the mmap object, so that you can have mmap.set(offset, value) for example.

Either wrap the object in a newtype (struct MyMmap(memmap::MmapMut)) and implement helper methods on the newtype, or create your own a trait and implement the trait for memmap::MmapMut.

2 Likes

I think I have to mark my wrapper methods as unsafe, since they assume they own access and there's no way to do that cross-process (or at least not easily). At least I can stop out-of-bounds errors.

This is the approach I think I'll take. Thanks all!