c - 从设备属性读取时调试在 container_of 上失败的简单字符驱动程序

标签 c linux linux-kernel kernel linux-device-driver

我正在编写一个访问 PCI 卡的简单字符驱动程序。它在新类的帮助下注册到 sysfs。现在我想以一种方便的方式访问设备的多个参数(即版本、状态、控制......)。我想向设备注册多个属性(通过 device_create_file() )。 为此,我创建了自己的设备结构 foo_dev我为此分配内存并将所有设备信息存储在其中(即 struct device )。一旦属性被调用,我想通过使用 container_of() 来恢复我的结构,如我的代码所示(为了可读性而去除了返回验证):

static const ssize_t foo_show(struct device *dev,
    struct device_attribute *attr, char *buf)
{
    struct foo_dev *foo_dev = container_of(dev, struct foo_dev,
        dev);
    mutex_lock(&mutex);

    u32 data = ioread32(foo_dev->bar + 0x2020);

    mutex_unlock(&mutex);
    return sprintf(buf, "%d\n", data);
}

问题:我一写入设备,内核就中止并显示 Bad IO access at port 0x2020 (return inl(port))来自 ioread32()称呼。进一步调查并打印了存储在foo_dev中的其他信息我看到结构完全是空的 - container_of()显然没有重建我原来的结构。为了完整起见,probe() 函数中的设备初始化:

...
foo_dev->dev = device_create(fooClass, NULL, foo_dev->devNbr,
    foo_dev, DEVICE_NAME);

cdev_init(&foo_dev->cdev, &foo_fops);
rv = cdev_add(&foo_dev->cdev, foo_dev->devNbr, 1);

rv = pci_enable_device(dev);
...
device_create_file(foo_dev->dev, &dev_attr_bar);
...

我可能错了什么?我如何进一步调查我实际收到的 struct dev在 foo_show() 中?

最佳答案

container_of() 使用嵌入式指针。

它仅适用于直接嵌入另一个结构的结构:

struct foo_dev {
    ...
    struct device dev;
    ...
};

(然后您必须使用 device_initialize()。)

关于c - 从设备属性读取时调试在 container_of 上失败的简单字符驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25740748/

相关文章:

c - linux函数openat vs open, "at"是什么意思?

c - 运行 make install 时出错 - 缺少 include/generated/autoconf.h 或 include/config/auto.conf

linux-kernel - 如何获得内核线程ID?

c - 如何将二维数组的引用作为参数传递

c - 更快地阅读关键字列表的方法

c++ - 在非托管 C/C++ 中获取已签名 EXE 的 X509 代码签名证书序列号

c - *nix 伪终端如何工作?什么是主/从 channel ?

c - 原始套接字发送和接收

linux - 来自 Linux 用户空间的 PEBS 的 x86-64 "linear address"?

c - 如何在 Linux 2.6.29 中解码 ioctl() 系统调用中的 arg 指针?