Android应用程序访问linux驱动第一步:实现并测试Linux驱动

来源:互联网 发布:mysql联合主键怎么设置 编辑:程序博客网 时间:2024/06/14 18:47

一直都想亲自做一次使用android应用程序访问Linux内核驱动的尝试,但总是没能做到。最近抽出时间,下决心重新尝试一次。尝试的开始当然是先写一个Linux内核驱动了。
我希望写一个简单测驱动程序,实现写一个字符串进去,然后再把它读出来的功能。驱动中会创建dev/hello设备节点和/sys/class/hello/hello/val 设备节点,没有实现proc/下的对应的设备节点。/sys/class/hello/hello/val 主要用于快速测试,而dev/hello则主要用于供上层应用调用。
这篇博客参考了老罗的android之旅相关博客:http://blog.csdn.net/luoshengyang/article/details/6568411。

一。驱动源码

代码我已经在android6.0的linux kernel上测试过了,代码中有响应的注释,所以这里直接贴出代码:

hello.c

文件如下:

#include <linux/init.h>  #include <linux/module.h>  #include <linux/types.h>  #include <linux/fs.h>  #include <linux/proc_fs.h>  #include <linux/device.h>  #include <linux/sched.h>#include <linux/errno.h>#include <linux/fcntl.h>#include <linux/poll.h>#include <linux/seq_file.h>#include <linux/mutex.h>#include <linux/workqueue.h>#include <asm/uaccess.h>#include <linux/slab.h>#include "hello.h"  /*定义主设备和从设备号变量*/  static int hello_major = 0;  static int hello_minor = 0;  /*设备类别和设备变量*/  static struct class* hello_class = NULL;  static struct hello_test_dev* hello_dev = NULL;  /*传统的设备文件操作方法*/  static int hello_open(struct inode* inode, struct file* filp);  static int hello_release(struct inode* inode, struct file* filp);  static ssize_t hello_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos);  static ssize_t hello_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos);  /*设备文件操作方法表*/  static struct file_operations hello_fops = {      .owner = THIS_MODULE,      .open = hello_open,      .release = hello_release,      .read = hello_read,      .write = hello_write,   };  /*访问设置属性方法*/  static ssize_t hello_val_show(struct device* dev, struct device_attribute* attr,  char* buf);  static ssize_t hello_val_store(struct device* dev, struct device_attribute* attr, const char* buf, size_t count);  /*定义设备属性*/  static DEVICE_ATTR(val, S_IRUGO | S_IWUSR, hello_val_show, hello_val_store); /*打开设备方法*/  static int hello_open(struct inode* inode, struct file* filp) {      struct hello_test_dev* dev;              /*将自定义设备结构体保存在文件指针的私有数据域中,以便访问设备时拿来用*/      dev = container_of(inode->i_cdev, struct hello_test_dev, dev);      filp->private_data = dev;      return 0;  }  /*设备文件释放时调用,空实现*/  static int hello_release(struct inode* inode, struct file* filp) {      return 0;  }  /*读内存*/  static ssize_t hello_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos) {      ssize_t err = 0;      struct hello_test_dev* dev = filp->private_data;              /*同步访问*/      if(down_interruptible(&(dev->sem))) {          return -ERESTARTSYS;      }      if(count < sizeof(dev->val)) {          goto out;      }              /*读字符串*/      if(copy_to_user(buf, dev->val, sizeof(dev->val))) {          err = -EFAULT;          goto out;      }      err = sizeof(dev->val);  out:      up(&(dev->sem));      return err;  }  /*写字符串*/  static ssize_t hello_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos) {      struct hello_test_dev* dev = filp->private_data;      ssize_t err = 0;              /*同步访问*/      if(down_interruptible(&(dev->sem))) {          return -ERESTARTSYS;              }              if(count != sizeof(dev->val)) {          goto out;              }              /*将用户写进来的字符串保存到驱动的内存中*/      if(copy_from_user(dev->val, buf, count)) {          err = -EFAULT;          goto out;      }      err = sizeof(dev->val);  out:      up(&(dev->sem));      return err;  }  /*写字符串到内存*/  static ssize_t __hello_set_val(struct hello_test_dev* dev, const char* buf, size_t count) {           /*同步访问*/              if(down_interruptible(&(dev->sem))) {                          return -ERESTARTSYS;              }              printk(KERN_ALERT"__hello_set_val.buf: %s  count:%d\n",buf,count);    printk(KERN_ALERT"__hello_set_val.dev->val: %s  count:%d\n",dev->val,count);    strncpy(dev->val,buf, count);    printk(KERN_ALERT"__hello_set_val.dev->val: %s  count:%d\n",dev->val,count);    up(&(dev->sem));      return count;  }  /*读取设备属性val*/  static ssize_t hello_val_show(struct device* dev, struct device_attribute* attr, char* buf) {      struct hello_test_dev* hdev = (struct hello_test_dev*)dev_get_drvdata(dev);              printk(KERN_ALERT"hello_val_show.\n");    printk(KERN_ALERT"%s\n",hdev->val);    return 0;}  /*写设备属性val*/  static ssize_t hello_val_store(struct device* dev, struct device_attribute* attr, const char* buf, size_t count) {       struct hello_test_dev* hdev = (struct hello_test_dev*)dev_get_drvdata(dev);        printk(KERN_ALERT"hello_val_store.buf: %s  count:%d\n",buf,count);    return __hello_set_val(hdev, buf, count);  }  /*初始化设备*/  static int  __hello_setup_dev(struct hello_test_dev* dev) {      int err;      dev_t devno = MKDEV(hello_major, hello_minor);      memset(dev, 0, sizeof(struct hello_test_dev));      cdev_init(&(dev->dev), &hello_fops);      dev->dev.owner = THIS_MODULE;      dev->dev.ops = &hello_fops;              /*注册字符设备*/      err = cdev_add(&(dev->dev),devno, 1);      if(err) {          return err;      }              /*初始化信号量和寄存器val的值*/      init_MUTEX(&(dev->sem));      dev->val = kmalloc(10,GFP_KERNEL);      strncpy(dev->val,"hello",sizeof("hello"));    return 0;  }  /*模块加载方法*/  static int __init hello_init(void){       int err = -1;      dev_t dev = 0;      struct device* temp = NULL;      printk(KERN_ALERT"hello_init.\n");              /*动态分配主设备和从设备号*/      err = alloc_chrdev_region(&dev, 0, 1, HELLO_DEVICE_NODE_NAME);      if(err < 0) {          printk(KERN_ALERT"Failed to alloc char dev region.\n");          goto fail;      }      hello_major = MAJOR(dev);      hello_minor = MINOR(dev);              /*分配helo设备结构体变量*/      hello_dev = kmalloc(sizeof(struct hello_test_dev), GFP_KERNEL);      if(!hello_dev) {          err = -ENOMEM;          printk(KERN_ALERT"Failed to alloc hello_dev.\n");          goto unregister;      }              /*初始化设备*/      err = __hello_setup_dev(hello_dev);      if(err) {          printk(KERN_ALERT"Failed to setup dev: %d.\n", err);          goto cleanup;      }              /*在/sys/class/目录下创建设备类别目录hello*/      hello_class = class_create(THIS_MODULE, HELLO_DEVICE_CLASS_NAME);      if(IS_ERR(hello_class)) {          err = PTR_ERR(hello_class);          printk(KERN_ALERT"Failed to create hello class.\n");          goto destroy_cdev;      }              /*在/dev/目录和/sys/class/hello目录下分别创建设备文件hello*/      temp = device_create(hello_class, NULL, dev, "%s", HELLO_DEVICE_FILE_NAME);      if(IS_ERR(temp)) {          err = PTR_ERR(temp);          printk(KERN_ALERT"Failed to create hello device.");          goto destroy_class;      }              /*在/sys/class/hello/hello目录下创建属性文件val*/      err = device_create_file(temp, &dev_attr_val);      if(err < 0) {          printk(KERN_ALERT"Failed to create attribute val.");                          goto destroy_device;      }      dev_set_drvdata(temp, hello_dev);              printk(KERN_ALERT"Succedded to initialize hello device.\n");      return 0;  destroy_device:      device_destroy(hello_class, dev);  destroy_class:      class_destroy(hello_class);  destroy_cdev:      cdev_del(&(hello_dev->dev));  cleanup:      kfree(hello_dev);  unregister:      unregister_chrdev_region(MKDEV(hello_major, hello_minor), 1);  fail:      return err;  }  /*模块卸载方法*/  static void __exit hello_exit(void) {      dev_t devno = MKDEV(hello_major, hello_minor);      printk(KERN_ALERT"hello_exit\n");              /*销毁设备类别和设备*/      if(hello_class) {          device_destroy(hello_class, MKDEV(hello_major, hello_minor));          class_destroy(hello_class);      }              /*删除字符设备和释放设备内存*/      if(hello_dev) {          cdev_del(&(hello_dev->dev));          kfree(hello_dev);      }              if(hello_dev->val != NULL){     kfree(hello_dev->val);    }    /*释放设备号*/      unregister_chrdev_region(devno, 1);  }  MODULE_LICENSE("GPL");  MODULE_DESCRIPTION("Test Driver");  module_init(hello_init);  module_exit(hello_exit);  

hello.h

文件如下:

#ifndef _HELLO_TEST_H_  #define _HELLO_ANDROID_H_  #include <linux/cdev.h>  #include <linux/semaphore.h>  #define HELLO_DEVICE_NODE_NAME  "hello"  #define HELLO_DEVICE_FILE_NAME  "hello"  #define HELLO_DEVICE_CLASS_NAME "hello"  struct hello_test_dev {      char * val;      struct semaphore sem;      struct cdev dev;  };  #endif  

二。编译驱动

在linux源码目录的driver下新建hello目录,把hello.c和hello.h文件放入其中。新增Makefile和Kconfig文件:

1.Makefile,用于编译驱动

obj-$(CONFIG_HELLO) += hello.o

2.Kconfig

       config HELLO           tristate "Test Driver"           default n           help           This is the test driver.

3修改driver目录下的Makefile:

添加如下一项:

obj-$(CONFIG_HELLO) += hello/

4.修改driver目录下的Kconfig

添加如下一项:

source "drivers/hello/Kconfig"

5.make menuconfig

如果对编译linux kernel不熟悉请自行百度。
配置界面如下:
这里写图片描述

可以看到这里出现了我们在Kconfig中添加的Test Driver选项,我们把它选择成以模块的形式编译,这更有利于我们的测试,这样我们就不需要重新少些linux kernel了。Android的linux kernel一般是打包进boot.img文件的,如果想把模块编译进Linux内核,并且重写烧写linux kernel ,建议把kernel放到out/target/product/xxx/目录下,然后使用make bootimage-nodeps能快速生成boot.img文件,具体kernel放置的位置还需要看android编译系统相关配置,这里就不深究了。

6.make -j16

执行make -j16(-j16标示使用16个cpu来编译,只是个请求),这个过程还是很快的,几分钟就可以编译成功。编译后的hello目录如下:
这里写图片描述
可以看到生成了hello.ko文件。

三.使用/sys/class/hello/hello/val 进行测试

1.把hello.ko拷贝到android设备上

建议直接使用adb push hello.ko /data 即可,也可以用U盘拷贝。总之,把它放到android设备上。

2.装载驱动

cd /data
insmod hello.ko
这个时候可以看到/dev/hello /sys/class/hello/hello/val文件已经出现

3.测试

输入命令:echo haha > val
打印如下:
[ 9641.053505] hello_val_store.buf: haha
[ 9641.053505] count:5
[ 9641.060167] __hello_set_val.buf: haha
[ 9641.060167] count:5
[ 9641.066841] __hello_set_val.dev->val: hello count:5
[ 9641.073088] __hello_set_val.dev->val: haha
[ 9641.073088] count:5
可以看到数据已经写入,
使用cat val 读取:
打印如下:
[ 9644.953496] hello_val_show.
[ 9644.957127] haha
[ 9644.957127]
可以看到haha打印出来了,书名写入是成功的。

四.使用/dev/hello测试

首先在android源码的packages目录下新建一个hellotest目录,该目录下新建hellotest.c和Android.mk两个文件。

1.hellotest.c

这个文件用来打开/dev/hello文件并尝试读和写字符串操作,并打印相关信息,源码如下:

#include <stdio.h>  #include <stdlib.h>  #include <fcntl.h>  #define HELLO_DEVICE "/dev/hello"  int main(int argc, char** argv)  {      int fd = -1;      char * str = malloc(10);    //打开/dev/hello    fd = open(HELLO_DEVICE, O_RDWR);      if(fd == -1) {          printf("Failed to open device %s.\n", HELLO_DEVICE);          return -1;      }      printf("Read original value:\n");     //先读一次数据看看    read(fd, str, 10);      printf("read data: %s\n", str);      strncpy(str,"nihao",sizeof("nihao"));      printf("write nihao\n");      //写nihao进去    write(fd, str, sizeof(str));      printf("Read the value again:\n");      //读看看是不是nihao        read(fd, str, 10);          printf("read data: %s\n", str);      close(fd);      return 0;  }  

2.Android.mk

android下编译应用程序使用Android.mk还是很方便的:

      LOCAL_PATH := $(call my-dir)      include $(CLEAR_VARS)      LOCAL_MODULE_TAGS := optional      LOCAL_MODULE := hellotest      LOCAL_SRC_FILES := $(call all-subdir-c-files)      include $(BUILD_EXECUTABLE)

3.编译

执行mm命令即可
编译后的文件在out/target/product/xxx/obj/EXECUTABLES/hellotest_intermediates/目录下,该目录编译后如图:
这里写图片描述
关于mm命令编译执行文件的过程,可以参考我的这篇博客: Android编译系统<二>-mm编译单个模块

4.测试

使用adb push hellotest /data把hellotest 推送到android设备上来,然后chmod +x hellotest添加可执行权限。
最后./hellotest
打印如下:

Read original value:read data: hellwrite nihaoRead the value again:read data: nihao

可见测试成功。

2 0
原创粉丝点击