使用mmap读/写寄存器

时间:2014-09-04 07:15:42

标签: c++ mmap

我正在尝试学习使用mmap来读写一些寄存器。我有以下代码。

#define MY_BASE_ADDRESS  0xC0000000 //Base Address for the PCIe
#define LED_ADDRESS      0x00010000 //Offset for LEDS  0x00010000
#define MAPPED_FILE_SIZE  (50 * sizeof(int)) //Guess
#define PAGE_SIZE (sysconf( _SC_PAGESIZE));

void *mapped_region, *mapped_LED_base;

off_t dev_base = (  MY_BASE_ADDRESS | LED_ADDRESS);
unsigned long readback = 0;

首先,我打开/ dev / mem

//The O_SYNC option prevents Linux from caching the contents of /dev/mem
memoryFileDescriptor = open("/dev/mem", O_RDWR | O_SYNC);
    if (memoryFileDescriptor == -1)
        {
        printf("Can't open /dev/mem. %d\n", memoryFileDescriptor );
        exit(0);
        }

// Map one page of memory into user space such that the device is in that page, but  
//it    may not
// be at the start of the page.
mapped_region = mmap(NULL,
                    MAPPED_FILE_SIZE,  //How to know size?
                    PROT_READ | PROT_WRITE,
                    MAP_SHARED,  //File may not be updated until msync or munmap is 
                                                                          // called.
                    memoryFileDescriptor,
                    dev_base);  //How to know the offset?

// get the address of the device in user space which will be an offset from the base
// that was mapped as memory is mapped at the start of a page
mapped_LED_base = mapped_region + dev_base;

然后我会写信到地址:

*((volatile unsigned long *) (mapped_LED_base)) = 0xFFFFF;

并阅读

readback = *((volatile unsigned long *) (mapped_LED_base));

我无法知道什么是MAP_SIZE及其偏移量?文件不是那么清楚。当前代码给出了分段错误错误。

我正在使用Linux和C ++

1 个答案:

答案 0 :(得分:0)

大小是硬件寄存器的大小,所以目前你说你有50 x 32位寄存器。在实践中,此数字向上舍入到体系结构的页面大小,通常为4KB。

如果你只有一个无符号长的寄存器,那么你应该将它设置为sizeof(unsigned long) - 你不应该映射超过实际需要的数量 - 即使系统“增长”到4KB。