Skip to content
Advertisement

Segmentation fault when maping /dev/mem

I’m trying to mmap a memory from my FPGA on a linux running on my Zedboard SoC. I can read the contents correctly using devmem on the command line, but when trying to read it through C I get a segmentation fault.

The barebones code shown below throws the segmentation fault when trying to print the contents of the memory. I’m careful to use a multiple of the page size to avoid issues from that:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>

typedef unsigned int u32;

int main()
{
    int page_size = sysconf(_SC_PAGESIZE);
    printf("PAGESIZE = %dnr", page_size);

    off_t bram_pbase = 0x42000000; // physical base address

    u32 *bram32_vptr;

    int fd = open("/dev/mem", O_SYNC);
    printf("FD openednr");

    bram32_vptr = (u32 *)mmap(NULL, 2*page_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, bram_pbase);

    printf("%d nr", bram32_vptr[0]);

    close(fd);
    return 0;
}

Why can’t I read the memory?

Advertisement

Answer

I feel the issue is flags passed to open it should look like this

fd = open("/dev/mem", O_RDWR|O_SYNC);

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement