Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mmap: Operation not permitted

Tags:

c

linux

I am trying to use mmap in user space to read the physical memory where 'mem_map' starts. It's an array that contains all the physical pages. This is a i386 machine running 3.0 kernel.

The code is like this:

....

//define page size
//
#define PAGE_SIZE 0x1000 //4096 bytes
#define PAGE_MASK (PAGE_SIZE - 1)

....

  /* open /dev/mem file*/
  if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) {
        printf("/dev/mem could not be opened.\n");
    perror("open");
        exit(1);
  } else {
    printf("/dev/mem opened.\n");
  }

  /* Map one page */
  printf(" mem_map is at physical addr: 0x%x\n", mem_map_phy_addr);

  map_base = mmap(0, PAGE_SIZE, PROT_READ, MAP_SHARED, fd, (mem_map_phy_addr & ~PAGE_MASK)); //mem_map_phy_addr is at 0x356f2000

  if(map_base == (void *) -1) {
    printf("Memory map failed. err num = %d\n",errno);
    perror("mmap"); //failed here
  } else {
    printf("Memory mapped at address %p.\n", map_base);
  }

I ran this as a root. The output is:

/dev/mem opened.
 mem_map is at physical addr: 0x356f2000
Memory map failed. err num = 1
mmap: Operation not permitted

To be sure, I googled the problem and added the following line to my /etc/sysctl.conf file:

vm.mmap_min_addr = 0

But this doesn't work either.

Anyone knows why mem_map operation like this is not permitted and how I can get around it?

Thanks.

like image 494
user899159 Avatar asked Nov 21 '11 14:11

user899159


2 Answers

It sounds like the kernel has been compiled with CONFIG_STRICT_DEVMEM enabled. This is a security feature to prevent user space access to (possibly sensitive) physical memory above 1MB (IIRC). You might be able to disable this with sysctl dev.mem.restricted.

like image 102
Brett Hale Avatar answered Sep 29 '22 20:09

Brett Hale


I had a similar problem which occured when I was trying use flashrom on an APU2c4 Board with Arch Linux.

The sysctl option dev.mem.restricted wasn't available in my system and using a self compiled kernel was no option for me.

I worked around the problem by setting the iomem Kernelparameter to relaxed via Grub:

# /boot/grub/grub.cfg
linux   /boot/vmlinuz-linux iomem=relaxed

Of course a reboot is nessesary for this solution.

Reference:
https://www.reddit.com/r/libreboot/comments/6wvyry/flashrom_failures_to_access/
https://www.flashrom.org/FAQ
https://www.kernel.org/doc/Documentation/admin-guide/kernel-parameters.txt

like image 38
Benibr Avatar answered Sep 29 '22 20:09

Benibr