(一)为Android系统编写Linux内核驱动程序HelloWorld

来源:互联网 发布:js绘制流程图的插件 编辑:程序博客网 时间:2024/06/05 02:55

请根据学习目录进行学习:android平台硬件驱动原理学习(总)

android基于Linux内核,故该驱动与Linux驱动没有任何不同,为了保证流程的完整性,故这里写一个Hello驱动,供后面的android学习使用,对于已经熟悉linux驱动的朋友,可以跳过此部分的学习,复制驱动编译即可;

一、进入到kernel/common/drivers目录,新建hello目录:

       USER-NAME@MACHINE-NAME:~/Android$ cd kernel/common/drivers

       USER-NAME@MACHINE-NAME:~/Android/kernel/common/drivers$ mkdir hello

       二、在hello目录中增加hello.h文件:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #ifndef _HELLO_ANDROID_H_  
  2. #define _HELLO_ANDROID_H_  
  3.   
  4. #include <linux/cdev.h>  
  5. #include <linux/semaphore.h>  
  6.   
  7. #define HELLO_DEVICE_NODE_NAME  "hello"  
  8. #define HELLO_DEVICE_FILE_NAME  "hello"  
  9. #define HELLO_DEVICE_PROC_NAME  "hello"  
  10. #define HELLO_DEVICE_CLASS_NAME "hello"  
  11.   
  12. struct hello_android_dev {  
  13.     int val;  
  14.     struct semaphore sem;  
  15.     struct cdev dev;  
  16. };  
  17.   
  18. #endif  

   这个头文件定义了一些字符串常量宏,在后面我们要用到。此外,还定义了一个字符设备结构体hello_android_dev,这个就是我们虚拟的硬件设备了,val成员变量就代表设备里面的寄存器,它的类型为int,sem成员变量是一个信号量,是用同步访问寄存器val的,dev成员变量是一个内嵌的字符设备,这个Linux驱动程序自定义字符设备结构体的标准方法。

   三、在hello目录中增加hello.c文件,这是驱动程序的实现部分。驱动程序的功能主要是向上层提供访问设备的寄存器的值,包括读和写。这里,提供了三种访问设备寄存器的方法,一是通过proc文件系统来访问,二是通过传统的设备文件的方法来访问,三是通过devfs文件系统来访问。下面分段描述该驱动程序的实现。

   首先是包含必要的头文件和定义三种访问设备的方法:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <linux/init.h>  
  2. #include <linux/module.h>  
  3. #include <linux/types.h>  
  4. #include <linux/fs.h>  
  5. #include <linux/proc_fs.h>  
  6. #include <linux/device.h>  
  7. #include <asm/uaccess.h>  
  8.   
  9. #include "hello.h"  
  10.   
  11. /*主设备和从设备号变量*/  
  12. static int hello_major = 0;  
  13. static int hello_minor = 0;  
  14.   
  15. /*设备类别和设备变量*/  
  16. static struct class* hello_class = NULL;  
  17. static struct hello_android_dev* hello_dev = NULL;  
  18.   
  19. /*传统的设备文件操作方法*/  
  20. static int hello_open(struct inode* inode, struct file* filp);  
  21. static int hello_release(struct inode* inode, struct file* filp);  
  22. static ssize_t hello_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos);  
  23. static ssize_t hello_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos);  
  24.   
  25. /*设备文件操作方法表*/  
  26. static struct file_operations hello_fops = {  
  27.     .owner = THIS_MODULE,  
  28.     .open = hello_open,  
  29.     .release = hello_release,  
  30.     .read = hello_read,  
  31.     .write = hello_write,   
  32. };  
  33.   
  34. /*访问设置属性方法*/  
  35. static ssize_t hello_val_show(struct device* dev, struct device_attribute* attr,  char* buf);  
  36. static ssize_t hello_val_store(struct device* dev, struct device_attribute* attr, const char* buf, size_t count);  
  37.   
  38. /*定义设备属性*/  
  39. static DEVICE_ATTR(val, S_IRUGO | S_IWUSR, hello_val_show, hello_val_store);  

        定义传统的设备文件访问方法,主要是定义hello_open、hello_release、hello_read和hello_write这四个打开、释放、读和写设备文件的方法:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /*打开设备方法*/  
  2. static int hello_open(struct inode* inode, struct file* filp) {  
  3.     struct hello_android_dev* dev;          
  4.       
  5.     /*将自定义设备结构体保存在文件指针的私有数据域中,以便访问设备时拿来用*/  
  6.     dev = container_of(inode->i_cdev, struct hello_android_dev, dev);  
  7.     filp->private_data = dev;  
  8.       
  9.     return 0;  
  10. }  
  11.   
  12. /*设备文件释放时调用,空实现*/  
  13. static int hello_release(struct inode* inode, struct file* filp) {  
  14.     return 0;  
  15. }  
  16.   
  17. /*读取设备的寄存器val的值*/  
  18. static ssize_t hello_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos) {  
  19.     ssize_t err = 0;  
  20.     struct hello_android_dev* dev = filp->private_data;          
  21.   
  22.     /*同步访问*/  
  23.     if(down_interruptible(&(dev->sem))) {  
  24.         return -ERESTARTSYS;  
  25.     }  
  26.   
  27.     if(count < sizeof(dev->val)) {  
  28.         goto out;  
  29.     }          
  30.   
  31.     /*将寄存器val的值拷贝到用户提供的缓冲区*/  
  32.     if(copy_to_user(buf, &(dev->val), sizeof(dev->val))) {  
  33.         err = -EFAULT;  
  34.         goto out;  
  35.     }  
  36.   
  37.     err = sizeof(dev->val);  
  38.   
  39. out:  
  40.     up(&(dev->sem));  
  41.     return err;  
  42. }  
  43.   
  44. /*写设备的寄存器值val*/  
  45. static ssize_t hello_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos) {  
  46.     struct hello_android_dev* dev = filp->private_data;  
  47.     ssize_t err = 0;          
  48.   
  49.     /*同步访问*/  
  50.     if(down_interruptible(&(dev->sem))) {  
  51.         return -ERESTARTSYS;          
  52.     }          
  53.   
  54.     if(count != sizeof(dev->val)) {  
  55.         goto out;          
  56.     }          
  57.   
  58.     /*将用户提供的缓冲区的值写到设备寄存器去*/  
  59.     if(copy_from_user(&(dev->val), buf, count)) {  
  60.         err = -EFAULT;  
  61.         goto out;  
  62.     }  
  63.   
  64.     err = sizeof(dev->val);  
  65.   
  66. out:  
  67.     up(&(dev->sem));  
  68.     return err;  
  69. }  

        定义通过devfs文件系统访问方法,这里把设备的寄存器val看成是设备的一个属性,通过读写这个属性来对设备进行访问,主要是实现hello_val_show和hello_val_store两个方法,同时定义了两个内部使用的访问val值的方法__hello_get_val和__hello_set_val:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /*读取寄存器val的值到缓冲区buf中,内部使用*/  
  2. static ssize_t __hello_get_val(struct hello_android_dev* dev, char* buf) {  
  3.     int val = 0;          
  4.   
  5.     /*同步访问*/  
  6.     if(down_interruptible(&(dev->sem))) {                  
  7.         return -ERESTARTSYS;          
  8.     }          
  9.   
  10.     val = dev->val;          
  11.     up(&(dev->sem));          
  12.   
  13.     return snprintf(buf, PAGE_SIZE, "%d\n", val);  
  14. }  
  15.   
  16. /*把缓冲区buf的值写到设备寄存器val中去,内部使用*/  
  17. static ssize_t __hello_set_val(struct hello_android_dev* dev, const char* buf, size_t count) {  
  18.     int val = 0;          
  19.   
  20.     /*将字符串转换成数字*/          
  21.     val = simple_strtol(buf, NULL, 10);          
  22.   
  23.     /*同步访问*/          
  24.     if(down_interruptible(&(dev->sem))) {                  
  25.         return -ERESTARTSYS;          
  26.     }          
  27.   
  28.     dev->val = val;          
  29.     up(&(dev->sem));  
  30.   
  31.     return count;  
  32. }  
  33.   
  34. /*读取设备属性val*/  
  35. static ssize_t hello_val_show(struct device* dev, struct device_attribute* attr, char* buf) {  
  36.     struct hello_android_dev* hdev = (struct hello_android_dev*)dev_get_drvdata(dev);          
  37.   
  38.     return __hello_get_val(hdev, buf);  
  39. }  
  40.   
  41. /*写设备属性val*/  
  42. static ssize_t hello_val_store(struct device* dev, struct device_attribute* attr, const char* buf, size_t count) {   
  43.     struct hello_android_dev* hdev = (struct hello_android_dev*)dev_get_drvdata(dev);    
  44.       
  45.     return __hello_set_val(hdev, buf, count);  
  46. }  

   最后,定义模块加载和卸载方法,这里只要是执行设备注册和初始化操作:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /*初始化设备*/  
  2. static int  __hello_setup_dev(struct hello_android_dev* dev) {  
  3.     int err;  
  4.     dev_t devno = MKDEV(hello_major, hello_minor);  
  5.   
  6.     memset(dev, 0, sizeof(struct hello_android_dev));  
  7.   
  8.     cdev_init(&(dev->dev), &hello_fops);  
  9.     dev->dev.owner = THIS_MODULE;  
  10.     dev->dev.ops = &hello_fops;          
  11.   
  12.     /*注册字符设备*/  
  13.     err = cdev_add(&(dev->dev),devno, 1);  
  14.     if(err) {  
  15.         return err;  
  16.     }          
  17.   
  18.     /*初始化信号量和寄存器val的值*/  
  19.     //init_MUTEX(&(dev->sem));
  20.     sema_init(sem, 1);  
  21.     
  22.     dev->val = 0;  
  23.   
  24.     return 0;  
  25. }  
  26.   
  27. /*模块加载方法*/  
  28. static int __init hello_init(void){   
  29.     int err = -1;  
  30.     dev_t dev = 0;  
  31.     struct device* temp = NULL;  
  32.   
  33.     printk(KERN_ALERT"Initializing hello device.\n");          
  34.   
  35.     /*动态分配主设备和从设备号*/  
  36.     err = alloc_chrdev_region(&dev, 0, 1, HELLO_DEVICE_NODE_NAME);  
  37.     if(err < 0) {  
  38.         printk(KERN_ALERT"Failed to alloc char dev region.\n");  
  39.         goto fail;  
  40.     }  
  41.   
  42.     hello_major = MAJOR(dev);  
  43.     hello_minor = MINOR(dev);          
  44.   
  45.     /*分配helo设备结构体变量*/  
  46.     hello_dev = kmalloc(sizeof(struct hello_android_dev), GFP_KERNEL);  
  47.     if(!hello_dev) {  
  48.         err = -ENOMEM;  
  49.         printk(KERN_ALERT"Failed to alloc hello_dev.\n");  
  50.         goto unregister;  
  51.     }          
  52.   
  53.     /*初始化设备*/  
  54.     err = __hello_setup_dev(hello_dev);  
  55.     if(err) {  
  56.         printk(KERN_ALERT"Failed to setup dev: %d.\n", err);  
  57.         goto cleanup;  
  58.     }          
  59.   
  60.     /*在/sys/class/目录下创建设备类别目录hello*/  
  61.     hello_class = class_create(THIS_MODULE, HELLO_DEVICE_CLASS_NAME);  
  62.     if(IS_ERR(hello_class)) {  
  63.         err = PTR_ERR(hello_class);  
  64.         printk(KERN_ALERT"Failed to create hello class.\n");  
  65.         goto destroy_cdev;  
  66.     }          
  67.   
  68.     /*在/dev/目录和/sys/class/hello目录下分别创建设备文件hello*/  
  69.     temp = device_create(hello_class, NULL, dev, "%s", HELLO_DEVICE_FILE_NAME);  
  70.     if(IS_ERR(temp)) {  
  71.         err = PTR_ERR(temp);  
  72.         printk(KERN_ALERT"Failed to create hello device.");  
  73.         goto destroy_class;  
  74.     }          
  75.   
  76.     /*在/sys/class/hello/hello目录下创建属性文件val*/  
  77.     err = device_create_file(temp, &dev_attr_val);  
  78.     if(err < 0) {  
  79.         printk(KERN_ALERT"Failed to create attribute val.");                  
  80.         goto destroy_device;  
  81.     }  
  82.   
  83.     dev_set_drvdata(temp, hello_dev);             
  84.   
  85.     printk(KERN_ALERT"Succedded to initialize hello device.\n");  
  86.     return 0;  
  87.   
  88. destroy_device:  
  89.     device_destroy(hello_class, dev);  
  90.   
  91. destroy_class:  
  92.     class_destroy(hello_class);  
  93.   
  94. destroy_cdev:  
  95.     cdev_del(&(hello_dev->dev));  
  96.   
  97. cleanup:  
  98.     kfree(hello_dev);  
  99.   
  100. unregister:  
  101.     unregister_chrdev_region(MKDEV(hello_major, hello_minor), 1);  
  102.   
  103. fail:  
  104.     return err;  
  105. }  
  106.   
  107. /*模块卸载方法*/  
  108. static void __exit hello_exit(void) {  
  109.     dev_t devno = MKDEV(hello_major, hello_minor);  
  110.   
  111.     printk(KERN_ALERT"Destroy hello device.\n");                   
  112.   
  113.     /*销毁设备类别和设备*/  
  114.     if(hello_class) {  
  115.         device_destroy(hello_class, MKDEV(hello_major, hello_minor));  
  116.         class_destroy(hello_class);  
  117.     }          
  118.   
  119.     /*删除字符设备和释放设备内存*/  
  120.     if(hello_dev) {  
  121.         cdev_del(&(hello_dev->dev));  
  122.         kfree(hello_dev);  
  123.     }          
  124.   
  125.     /*释放设备号*/  
  126.     unregister_chrdev_region(devno, 1);  
  127. }  
  128.   
  129. MODULE_LICENSE("GPL");  
  130. MODULE_DESCRIPTION("First Android Driver");  
  131.   
  132. module_init(hello_init);  
  133. module_exit(hello_exit);  

    四.在hello目录中新增Kconfig和Makefile两个文件,其中Kconfig是在编译前执行配置命令make menuconfig时用到的,而Makefile是执行编译命令make是用到的:

       Kconfig文件的内容

       config HELLO
           tristate "First Android Driver"
           default n
           help
           This is the first android driver.
      Makefile文件的内容
      obj-$(CONFIG_HELLO) += hello.o
      在Kconfig文件中,tristate表示编译选项HELLO支持在编译内核时,hello模块支持以模块、内建和不编译三种编译方法,默认是不编译,因此,在编译内核前,我们还需要执行make menuconfig命令来配置编译选项,使得hello可以以模块或者内建的方法进行编译。
      在Makefile文件中,根据选项HELLO的值,执行不同的编译方法。
      五. 修改drivers/kconfig文件,在menu "Device Drivers"和endmenu之间添加一行:
      source "drivers/hello/Kconfig"
        这样,执行make menuconfig时,就可以配置hello模块的编译选项了。. 
        六. 修改drivers/Makefile文件,添加一行:
        obj-$(CONFIG_HELLO) += hello/
        七. 配置编译选项:
        USER-NAME@MACHINE-NAME:~/Android/kernel/common$ make menuconfig
        找到"Device Drivers" => "First Android Drivers"选项,设置为y。
        注意,如果内核不支持动态加载模块,这里不能选择m,虽然我们在Kconfig文件中配置了HELLO选项为tristate。要支持动态加载模块选项,必须要在配置菜单中选择Enable loadable module support选项;在支持动态卸载模块选项,必须要在Enable loadable module support菜单项中,选择Module unloading选项。
        八. 编译:
        USER-NAME@MACHINE-NAME:~/Android/kernel/common$ make
        编译成功后,就可以在hello目录下看到hello.o文件了,这时候编译出来的zImage已经包含了hello驱动。
        九. 编译和安装Android最新内核源代码,运行新编译的内核文件,验证hello驱动程序是否已经正常安装:
        USER-NAME@MACHINE-NAME:~/Android$ emulator -kernel ./kernel/common/arch/arm/boot/zImage &
        USER-NAME@MACHINE-NAME:~/Android$ adb shell
        进入到dev目录,可以看到hello设备文件:
        root@android:/ # cd dev
        root@android:/dev # ls
        进入到sys/class目录,可以看到hello目录:
        root@android:/ # cd sys/class
        root@android:/sys/class # ls
        进入到hello目录,可以看到hello目录:
        root@android:/sys/class # cd hello
        root@android:/sys/class/hello # ls
        进入到下一层hello目录,可以看到val文件:
        root@android:/sys/class/hello # cd hello
        root@android:/sys/class/hello/hello # ls
        访问属性文件val的值:
        root@android:/sys/class/hello/hello # cat val
        5
        root@android:/sys/class/hello/hello # echo '0'  > val
        root@android:/sys/class/hello/hello # cat val
        0
        至此,我们的hello内核驱动程序就完成了,并且验证了部分功能。接下来,通过自己编译的C语言程序来访问/dev/hello文件来和hello驱动程序交互;并验证/dev/hello驱动的正确性;

进入到Android源代码工程的external目录,创建hello目录:

      USER-NAME@MACHINE-NAME:~/Android$ cd external

      USER-NAME@MACHINE-NAME:~/Android/external$ mkdir hello

在hello目录中新建hello.c文件:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <fcntl.h>  
  4. #define DEVICE_NAME "/dev/hello"  
  5. int main(int argc, char** argv)  
  6. {  
  7.     int fd = -1;  
  8.     int val = 0;  
  9.     fd = open(DEVICE_NAME, O_RDWR);  
  10.     if(fd == -1) {  
  11.         printf("Failed to open device %s.\n", DEVICE_NAME);  
  12.         return -1;  
  13.     }  
  14.       
  15.     printf("Read original value:\n");  
  16.     read(fd, &val, sizeof(val));  
  17.     printf("%d.\n\n", val);  
  18.     val = 5;  
  19.     printf("Write value %d to %s.\n\n", val, DEVICE_NAME);  
  20.         write(fd, &val, sizeof(val));  
  21.       
  22.     printf("Read the value again:\n");  
  23.         read(fd, &val, sizeof(val));  
  24.         printf("%d.\n\n", val);  
  25.     close(fd);  
  26.     return 0;  
  27. }  

      这个程序的作用中,打开/dev/hello文件,然后先读出/dev/hello文件中的值,接着写入值5到/dev/hello中去,最后再次读出/dev/hello文件中的值,看看是否是我们刚才写入的值5。从/dev/hello文件读写的值实际上就是我们虚拟的硬件的寄存器val的值。

      四. 在hello目录中新建Android.mk文件:

      LOCAL_PATH := $(call my-dir)

      include $(CLEAR_VARS)

      LOCAL_MODULE_TAGS := optional

      LOCAL_MODULE := hello

      LOCAL_SRC_FILES := $(call all-subdir-c-files)

      include $(BUILD_EXECUTABLE)

      注意,BUILD_EXECUTABLE表示我们要编译的是可执行程序。 

      五. 参照如何单独编译Android源代码中的模块一文,使用mmm命令进行编译:

      USER-NAME@MACHINE-NAME:~/Android$ mmm ./external/hello

      编译成功后,就可以在out/target/product/gerneric/system/bin目录下,看到可执行文件hello了。

      六. 重新打包Android系统文件system.img:

      USER-NAME@MACHINE-NAME:~/Android$ make snod

      这样,重新打包后的system.img文件就包含刚才编译好的hello可执行文件了。

      七. 运行模拟器,使用/system/bin/hello可执行程序来访问Linux内核驱动程序:

      USER-NAME@MACHINE-NAME:~/Android$ emulator -kernel ./kernel/common/arch/arm/boot/zImage &

      USER-NAME@MACHINE-NAME:~/Android$ adb shell

      root@android:/ # cd system/bin

      root@android:/system/bin # ./hello

      Read the original value:

      0.

      Write value 5 to /dev/hello.

      Read the value again:

      5.

      看到这个结果,就说我们编写的C可执行程序可以访问我们编写的Linux内核驱动程序了。

本章结束。


0 0