[英]Using mmap to read/write Registers
我正在嘗試學習使用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 ++
該大小是硬件寄存器的大小,因此當前您是說有50 x 32位寄存器。 在實踐中,此數字會四舍五入為體系結構的頁面大小,通常為4KB。
如果只有一個寄存器是無符號長的,則應將其設置為sizeof(unsigned long)
-不應映射超出實際需要的內容-即使系統將其“增長”到4KB。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.