我正在编写一个访问 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/