Page 1 of 1

mmap register access in C

Posted: Wed May 16, 2018 1:15 pm
by skywalker
Hi everyone,
I'm quite new to C-Programming and I'm trying to understand how the access to the RAM registers works in the PID-application.
In fpga_pid.c, the pointer to the register is set using mmap:

Code: Select all

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

page_addr = PID_BASE_ADDR & (~(page_size-1));
page_off  = PID_BASE_ADDR - page_addr;

page_ptr = mmap(NULL, PID_BASE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, g_pid_fd, page_addr);

g_pid_reg = page_ptr + page_off;
I have several questions:
1) Why is page_addr calculated this way? The &-operator seems to apply some mask but I don't see what it is used for (same question for the inversion of page_size in the calculation).
2) What is page_off?
3) In the RedPitaya Memory Map, all registers are said to have a 4 byte offset. How does this come into play when accessing the registers via mmap?

Any help would be greatly appreciated!

Best,
skywalker

Re: mmap register access in C

Posted: Thu May 17, 2018 3:00 pm
by jmadsenee
Hi skywalker,

I believe what is happening is:

1. page_size = 4096 for the RP. That is 0x00001000. page_size-1 = 4095 = 0x00000FFF. (~(page_size-1)) = 0xFFFFF000. page_addr = PID_BASE_ADDR & (~(page_size-1)); makes page_addr = PID_BASE_ADDR with the bottom 12 bits cleared, putting it on a page boundary.

2. page_off is page offset. page_off = PID_BASE_ADDR - page_addr; calculates how far offset PID_BASE_ADDR is from the page boundary.

3. Each register is 32 bits, or 4 bytes. So you need to add 4 to the pointer to access each consecutive register.

Cheers!

John

Re: mmap register access in C

Posted: Tue May 22, 2018 11:51 am
by skywalker
Thanks a lot John, this really helped!! :)
Cheers
skywalker