首页 > 代码库 > linux设备模型

linux设备模型

device_driver和device必须依附总线。总线、驱动、设备最终会落实为sysfs中的一个目录。kobject对应sysfs的一个目录。

attribute直接落实sysfs中的一个文件,如果attribute非常多,show/sore函数里的分支会很凌乱。解决这个问题,提供kobj——attribute:

struct

struct kobj_attribute{struct  attribute attr;ssize_t (*show)(struct kobject *kobj,struct kobj_attribute *attr, char *buf);ssize_t (*store)(struct kobject *kobj,struct kobj_attribute *attr ,const char *buf, size_t count);};

每一个attribute会对 应自己的show、store函数,这样就极大的提高了灵活性 。sysfs是通过kobject里的kobj_type->sysfs_ops来读写attribute的,那如果利用kobj_attribute中的show/store来读写attribute,就必须在kobj_type->sysfs_ops里面指定。

static ssize_t kobj_attr_show(struct kobjct *kobj, struct attribute *attr,char *buf ){struct kobj_attribute *kattr;ssize _t ret=-EIO;kattr=container_of(attr,struct kobj_attribute,attr);if(kattr->show)ret=kattr->show(kobj,kattr,buf);return ret;}static ssize_t kobj_attr_store(struct kobject *kobj, struct attribute *attr,                   const char *buf, size_t count){    struct kobj_attribute *kattr;    ssize_t ret = -EIO;     kattr = container_of(attr, struct kobj_attribute, attr);    if (kattr->store)        ret = kattr->store(kobj, kattr, buf, count);    return ret;}const struct sysfs_ops kobj_sysfs_ops = {    .show   = kobj_attr_show,    .store  = kobj_attr_store,};static void dynamic_kobj_release(struct kobject *kobj){    pr_debug("kobject: (%p): %s\n", kobj, __func__);    kfree(kobj);}static struct kobj_type dynamic_kobj_ktype = {    .release    = dynamic_kobj_release,    .sysfs_ops  = &kobj_sysfs_ops,}; 


kobj_attribute是内核提供的更加灵活的attribute方式还要使用kobject_create来创建kobject。

struct my_attributte{struct attribute attr;ssize_t (*sbow)(struct my_kobj kobj, struct my_attribute *attr,char *buf);ssize_t(*store)(struct my_kobj *obj,struct my_attribute *attr,char *buf,size_t count);}

 

 

先创建接口:sysfs_creat_group(&xxdev->dev.kobj,&dev_attr_grp);

封装:static struct attribute_group dev_attr_grp={.attrs=dev_attrs,}

结构体:static Strut attribute *dev_attrs[]={&dev_attr_polling.attr,null,}

节点:static device_attr(polling,666,show_polling,set_polling).

读写:size_t show_polling(kobj,attribute,buf);

 

linux设备模型