【问题标题】:Linux driver with multiple device attributes linking to same function具有多个设备属性链接到相同功能的 Linux 驱动程序
【发布时间】:2014-09-12 09:31:56
【问题描述】:

我正在编写一个具有多个设备属性的简单 Linux 驱动程序。现在独立于您读取或写入的属性,最终您将在设备内存的某个位置读取或写入。只有定义确切位置的偏移量从一个属性更改为另一个属性。用几行代码就更容易解释了:

/* General read function evoked by attributes */
static const ssize_t foo_show(struct device *dev,
    struct device_attribute *attr, char *buf)
{
    u32 offset;

    if (attr->attr.name == "control")
        offset = OFFSET_CTRL;
    else if (attr->attr.name == "status")
        offset = OFFSET_STATUS;

    u32 data = ioread32(dev_mem + offset);
    ...
}

...

/* declaring attributes, all linking to the same function */
static DEVICE_ATTR(control, S_IWUGO | S_IRUGO, foo_show, foo_set);
static DEVICE_ATTR(status, S_IRUGO, foo_show, NULL);

现在您可能会猜到,使用 attr->attr.name == foo 并不是一个很好的方法,尤其是因为我收到警告“与字符串文字比较会导致未指定的行为”telling me 使用 strcmp。你知道有什么更好的方法来确定哪个属性负责调用吗?

【问题讨论】:

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


    【解决方案1】:

    这似乎在现有驱动程序中完成的方式是直接与全局属性进行比较。

    static DEVICE_ATTR(control, S_IWUGO | S_IRUGO, foo_show, foo_set);
    static DEVICE_ATTR(status, S_IRUGO, foo_show, NULL);
    
    static const ssize_t foo_show(struct device *dev,
        struct device_attribute *attr, char *buf)
    {
        u32 offset;
    
        if (attr == &dev_attr_control)
            offset = OFFSET_CTRL;
        else if (attr == &dev_attr_status)
            offset = OFFSET_STATUS;
    

    【讨论】:

      【解决方案2】:

      属性只能基于名称来识别。因为默认情况下attribute 中只有两个字段可用。 http://lxr.free-electrons.com/source/include/linux/sysfs.h#L29

      strcmp() 的内核空间实现可用。所以使用它会起作用。 http://lxr.free-electrons.com/source/lib/string.c#L245

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        相关资源
        最近更新 更多