Acccessing reserved memory from userspace.

I have reserved several nodes of memory through the device tree. I added the following to the device tree. This is with Jetpack 3.2.

reserved-memory {
		#address-cells = <2>;
		#size-cells = <2>;
		ranges;

		reserved_h2cbd: h2cbd@0x90000000 {
			reg = <0x0 0x90000000 0x0 0x10000>; /* 64 kiB */
		};
		reserved_c2hbd: c2hbd@0x90010000 {
			reg = <0x0 0x90010000 0x0 0x10000>; /* 64 kiB */
		};
		reserved_h2cmem: h2cmem@0xa0000000{
			reg = <0x0 0xa0000000 0x0 0x10000000>; /* 256 MiB */
		};
		reserved_c2hmem: c2hmem@0xb0000000 {
			reg = <0x0 0xb0000000 0x0 0x10000000>; /* 256 MiB */
		};

	};

I compiled the device tree, flashed it on the tx2, and verified that the device tree is indeed updated on the tx2.

$ ll /proc/device-tree/reserved-memory/

total 0
drwxr-xr-x  10 root root  0 May  6 06:16 ./
drwxr-xr-x 195 root root  0 Feb 11 16:28 ../
-r--r--r--   1 root root  4 May  6 06:15 #address-cells
drwxr-xr-x   2 root root  0 May  6 06:15 adsp_carveout/
drwxr-xr-x   2 root root  0 May  6 06:15 c2hbd@0x90010000/
drwxr-xr-x   2 root root  0 May  6 06:15 c2hmem@0xb0000000/
drwxr-xr-x   2 root root  0 May  6 06:15 generic_carveout/
drwxr-xr-x   2 root root  0 May  6 06:15 h2cbd@0x90000000/
drwxr-xr-x   2 root root  0 May  6 06:15 h2cmem@0xa0000000/
-r--r--r--   1 root root 16 May  6 06:15 name
drwxr-xr-x   2 root root  0 May  6 06:15 ramoops_carveout/
-r--r--r--   1 root root  0 May  6 06:15 ranges
-r--r--r--   1 root root  4 May  6 06:15 #size-cells
drwxr-xr-x   2 root root  0 May  6 06:15 vpr-carveout/

Now I am trying to access the reserved memory in user space with mmap. Here is some code where I am trying to map the h2cbd@0x90000000 node.

int main(int argc, char *argv[]) {

    void *addr = NULL;
    size_t len= 0x10000;
    off_t offset = 0x90000000;

    int fd = open("/dev/mem", O_SYNC);
    if (fd < 0)
    {
        perror("Can't open /dev/mem");
        return -1;
    }
    unsigned char *mem = mmap(addr, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
    if (mem == MAP_FAILED) {
        perror("Can't map memory");
        return -1;
    }

    size_t i;
    for (i = 0; i < len; ++i)
        printf("%02x ", (int)mem[i]);
    return 0;
}

When I run this I get (I am running it with sudo).

Can't map memory: Permission denied

Can someone please advise me on how to access these reserved nodes from user space?

Thank you

EDIT

I solved the problem. I needed to add the O_RDWR flag to open

open("/dev/mem", o_RDWR | O_SYNC)

Glad to hear that you’ve resolved it.