访问PCIe设备的内部寄存器

时间:2018-10-23 17:11:43

标签: c linux memory-management linux-kernel linux-device-driver

我在这里没有找到有关此主题的话题,但是都没有人解释我遇到的问题。 我只是试图通过将其映射到Linux中的用户内存空间来访问PCIe设备的内部状态寄存器。 这是我的系统配置:

# uname -a
Linux localhost.localdomain 4.18.13-200.fc28.x86_64 #1 SMP Wed Oct 10 17:29:59 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

# lspci -tv
-[0000:00]-+-00.0  Intel Corporation Device 1980
       +-04.0  Intel Corporation Device 19a1
       <...>
       +-1f.2  Intel Corporation Device 19de

# cat /proc/iomem
df570000-df573fff : 0000:00:1f.2

# lspci -s 00:1f.2 -x
00:1f.2 Memory controller: Intel Corporation Device 19de (rev 11)
00: 86 80 de 19 00 00 00 00 11 00 80 05 00 00 80 00
10: 00 00 57 df 00 00 00 00 00 00 00 00 00 00 00 00
20: 00 00 00 00 00 00 00 00 00 00 00 00 d9 15 69 09
30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

因此,该设备位于00:1f.2上,并且对系统可见。我尝试访问内存控制器偏移量为0x110的内部“ ERRCORSTS”寄存器,该寄存器显示PCI Express设备 page1673 上各个可纠正错误源的错误状态(此处为manual for my SoC )。我从程序中得到的输出是:

数据= ffffffff
PCI BAR0 0x0000 = 0xffff

看来我在理解linux内存映射方面缺少一些东西,或者可能是它们只是在4.18内核中进行了更改,所以它并不像以前那样容易。
有人可以帮我吗?

这是我的代码:

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

#define BASE_ADDR 0xdf570000
#define DATA_OFFSET 0x110
extern int errno;
int main()
{
    int i;
    int fd = open("/dev/mem",O_RDWR|O_SYNC);
    if(fd < 0) {
            printf("Can't open /dev/mem\n");
            return 1;
    }

    u_int32_t* mapped_base = (u_int32_t *) mmap(0, 4096UL, PROT_READ|PROT_WRITE, MAP_SHARED, fd, BASE_ADDR);

    // Trying to get access to device memory
    if(mapped_base == NULL) {
            printf("Can't mmap\n");
            return 1;
    } else {
            unsigned int status_register0 = *(int *)(mapped_base + DATA_OFFSET  );
            printf("data = %lx \n",status_register0);
    }

    // Trying to get access to DevID
    int fb = open("/sys/devices/pci0000:00/0000:00:1f.2/resource0", O_RDWR | O_SYNC);                   
    u_int32_t* ptr = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fb, 0);
    printf("PCI BAR0 0x0000 = 0x%4x\n",  *((unsigned short *) ptr) );

    return 0;
}

2 个答案:

答案 0 :(得分:1)

这将执行指针算术。

mapped_base + DATA_OFFSET

偏移量会自动乘以元素大小,该大小可能是基于4的

u_int32_t* mapped_base

但是,您的文档似乎指定了以字节为单位的偏移量。

因此,您需要阅读0xdf570110,但实际上是在阅读0xdf570440

答案 1 :(得分:0)

当我尝试使用它时,似乎弄乱了内存。因此,重新启动计算机后一切正常。

相关问题