首页 > 解决方案 > 尝试映射设备的 BAR-0 时出现“错误的文件描述符”错误

问题描述

我正在尝试将 PCI 设备的 BAR-0 映射到虚拟地址空间,以便读取(并稍后修改)其内容。但是,当我映射它时,我收到以下错误:

Path to BAR-0: /sys/bus/pci/devices/0000:00:16.0/resource0
Error at line 42, file src/main.c (9) [Bad file descriptor]

我正在使用 Debian 9.1 32 位。我使用的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h> 
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "../include/eeprom.h"
#include "../include/pci.h"
#include "../include/i2c.h"
#include "../include/types.h"

#define PRINT_ERROR \
    do { \
        fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
        __LINE__, __FILE__, errno, strerror(errno)); exit(1);\
    } while(0)

#define MAP_SIZE 4096
#define MAP_MASK (MAP_SIZE - 1)

int main (int argc, char* argv[]) {
    uint32_t pci_dev;
    void *mmap_base;
    char *file = {"/sys/bus/pci/devices/0000:00:16.0/resource0"};
    int i;

    printf ("Path to BAR-0: %s\n", file);

    //Open Bar-0 of PCI device
    pci_dev = open (file, O_RDWR | O_SYNC);
    if (pci_dev < 0)
    {
        PRINT_ERROR;
    }

    //Map BAR-0 from physical memory to virtual address space
    mmap_base = mmap (NULL, MAP_SIZE, PROT_WRITE, MAP_SHARED, pci_dev, 0);
    if (mmap_base == (void *)-1 || mmap_base == NULL)  //error here
    {
        PRINT_ERROR;
    }
    printf ("Mapped on address %p of size %d Byte\n", mmap_base, MAP_SIZE);

    return 0;
}

我已经可以说,我删除了设备使用的内核模块,所以这不是问题。

有人可以帮助我吗?提前致谢。

标签: cdebianmmapvirtual-address-space

解决方案


我在学习 Linux Kernal 编程时遇到了类似的问题。以超级用户权限运行程序对我有用。


推荐阅读