建立驱动sysfs接口

来源:互联网 发布:linux codeblocks教程 编辑:程序博客网 时间:2024/06/01 17:19


原文地址 http://blog.sina.com.cn/s/blog_6a16c0ae0101b93s.html

在调试驱动,或驱动涉及一些参数的输入输出时,难免需要对驱动里的某些变量进行读写,或函数调用。此时sysfs接口就很有用了,它可以使得可以在用户空间直接对驱动的这些变量读写或调用驱动的某些函数。

其他不说,直接上鄙人写的helloworld例程

 

//  Start------------------------------------------------------------------------

#include <linux/module.h>
#include <linux/types.h>
#include <linux/kobject.h>


static ssize_t sysfs_read(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
 return sprintf(buf, "%s\n", "sysfs test read,created by vincent");
}

static ssize_t sysfs_write(struct kobject *kobj, struct kobj_attribute *attr, const char *buf,ssize_t  count)
{
 int i;
 printk("\nfrom user,length=0x%X,content=%s\n",count,buf);
 if(count)
  return count;
 else
  return 1 ;
}

static struct kobj_attribute my_sysfs_read =__ATTR(read, S_IRUGO, sysfs_read, NULL);

static struct kobj_attribute my_sysfs_write =__ATTR(write, S_IWUGO, NULL,sysfs_write);


static struct attribute *my_sysfs_test[] = {
 &my_sysfs_read.attr,
 &my_sysfs_write.attr,
 NULL,
};


static struct attribute_group my_attr_group = {
 .attrs = my_sysfs_test,
};

static int sysfs_status = 0 ;
struct kobject *soc_kobj = NULL;
int helloworld_init(void)
{
 int ret = 0;
 printk("\nHello Android driver : %s\n",__func__);
 printk("Compile Driver Via eclipse IDE: %s\n",__func__);

 soc_kobj = kobject_create_and_add("my_sysfs_test", NULL);
 if (!soc_kobj)
  goto err_board_obj;

 ret = sysfs_create_group(soc_kobj, &my_attr_group);
 if (ret)
  goto err_soc_sysfs_create;
 sysfs_status = 1;
 
 return 0;

 sysfs_status = 0;
err_soc_sysfs_create:
 kobject_put(soc_kobj);
 sysfs_remove_group(soc_kobj, &my_attr_group);
 printk("\nsysfs_create_group ERROR : %s\n",__func__);
 return 0;
err_board_obj:
 printk("\nobject_create_and_add ERROR : %s\n",__func__);
 return 0;
}

void helloworld_exit(void)
{
 printk("\nExit Android driver : %s\n",__func__);
 printk("Compile Driver Via eclipse IDE: %s\n",__func__);

 if(sysfs_status == 1)
 {
  sysfs_status = 0;
  kobject_put(soc_kobj);
  sysfs_remove_group(soc_kobj, &my_attr_group);
 }
}


MODULE_AUTHOR("vincent wu");
MODULE_LICENSE("Dual BSD/GPL");
module_init(helloworld_init);
module_exit(helloworld_exit);

 

// End------------------------------------------------------------------------

 

使用:

1.编译,insmod 驱动。

2.cd /sys ,发现多了一个创建的"my_sysfs_test"目录。

3.cd my_sysfs_test,发现多了两个创建的"read","write"目录。

4.cat read ,控制台输出"sysfs test read,created by vincent",这里实际会调用上面的sysfs_read函数。

5.echo hi sysfs > write ,这里实际会调用上面的sysfs_write函数输出。

注意:

以上代码中有颜色的地方,两两要一致,不能随意填写。具体原因不详。

 

 

上一个TI OMAP4平台的sysfs程序段,写不错。

直接上source insight图,视觉感受好点。

 

建立sysfs接口

 

 

对于一些基于platform总线类型的驱动,创建sysfs目录时候可以参考如SPI驱动的一些创建方式,如下:

 

sysfs_create_group(&spi->dev.kobj, ts->attr_group);

0 0