How to access physical addresses from user space in Linux?
You can map a device file to a user process memory using mmap(2)
system call. Usually, device files are mappings of physical memory to the file system.
Otherwise, you have to write a kernel module which creates such a file or provides a way to map the needed memory to a user process.
Another way is remapping parts of /dev/mem to a user memory.
Edit:
Example of mmaping /dev/mem (this program must have access to /dev/mem, e.g. have root rights):
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: %s <phys_addr> <offset>\n", argv[0]);
return 0;
}
off_t offset = strtoul(argv[1], NULL, 0);
size_t len = strtoul(argv[2], NULL, 0);
// Truncate offset to a multiple of the page size, or mmap will fail.
size_t pagesize = sysconf(_SC_PAGE_SIZE);
off_t page_base = (offset / pagesize) * pagesize;
off_t page_offset = offset - page_base;
int fd = open("/dev/mem", O_SYNC);
unsigned char *mem = mmap(NULL, page_offset + len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, page_base);
if (mem == MAP_FAILED) {
perror("Can't map memory");
return -1;
}
size_t i;
for (i = 0; i < len; ++i)
printf("%02x ", (int)mem[page_offset + i]);
return 0;
}
using O_DIRECT with IO memory
I think, that it all happens because of VM_PFNMAP
flag ( http://elixir.free-electrons.com/linux/v4.11.7/source/include/linux/mm.h#L174 )
When you use io_remap_pfn_range
, it sets VM_PFNMAP
flag ( http://elixir.free-electrons.com/linux/v4.11.7/source/mm/memory.c#L1914 ), that tells "those pages aren't regular pages with usual struct page" ( see comment in the code above )
And __get_user_pages
checks this flag and returns error ( http://elixir.free-electrons.com/linux/v4.11.7/source/mm/nommu.c#L136 )
P.S. There is VM_IO
flag too in both io_remap_pfn_range
and __get_user_pages
, so there won't be any I/O on kernel pages, mapped to user-space, or anyone will rewrite kernel memory
Related Topics
Trouble Ssh Tunneling to Remote Server
Need Explanation on Pri Standard Format Specifier for Ps - Possible Bug in Documentation
Differences Between Sponge and Tee
Setup Sftp to Use Public-Key Authentication
Tickless Kernel, Isolcpus,Nohz_Full,And Rcu_Nocbs
How to Set Folder Permissions for a Particular Container on Elastic Beanstalk
Check for Existence of Wget/Curl
Question About Zombie Processess and Threads
How to Pass Local Variable to Remote Using Ssh and Bash Script
Why Are Both "True" and "False" Tests True
How to Add My Scheduler to Linux Kernel
What Is The Maximum Number of Subdirectories Allowed in Ext4
Vimdiff: How to Put All Changes Inside a Particular Function from One File to Another