在kernel 4.0中,当遍历sysfs_create_bin_file的内核源代码时,我注意到它传递给sysfs_add_file(kobj->sd, &attr->attr, true);结构中的&attr->attr结构。
这在我访问直接从struct attribute调用的bin_attribute之前是有意义的,并且在line #277上设置温度变量sysfs_add_file_mode_ns
这不是指向一个sysfs_add_file吗?它是如何将其解析为正确的结构的(由于使用stuct bin_attribute *battr = (void*)attr;online #483调用struct attribute)?
代码

int sysfs_create_bin_file(struct kobject *kobj,
              const struct bin_attribute *attr)
{
    BUG_ON(!kobj || !kobj->sd || !attr);

    return sysfs_add_file(kobj->sd, &attr->attr, true);
}

int sysfs_add_file(struct kernfs_node *parent, const struct attribute *attr,
           bool is_bin)
{
    return sysfs_add_file_mode_ns(parent, attr, is_bin, attr->mode, NULL);
}

int sysfs_add_file_mode_ns(struct kernfs_node *parent,
               const struct attribute *attr, bool is_bin,
               umode_t mode, const void *ns)
{
    struct lock_class_key *key = NULL;
    const struct kernfs_ops *ops;
    struct kernfs_node *kn;
    loff_t size;

    if (!is_bin) {
        ...
    } else {


        struct bin_attribute *battr = (void *)attr;
         ...
    }

最佳答案

生产线

stuct bin_attribute *battr = (void*)attr;

从指向bin_attribute类型的第一个字段attr的指针中正确获取指向struct attribute结构的指针。
通常,Linux内核开发人员倾向于使用container_of宏来获取指向结构类型的指针,知道指向其字段的指针。以上转换的更“规范”的方式是:
stuct bin_attribute *battr = container_of(attr, struct device_attribute, attr);

(在这个调用中,第一个attr参数引用指针,第三个attr参数引用字段名)。

07-28 03:04
查看更多