在Ubuntu上爲Android系統編寫Linux內核驅動程序

在智能手機時代,每個品牌的手機都有自己的個性特點。正是依靠這種與衆不同的個性來吸引用戶,營造品牌凝聚力和用戶忠城度,典型的代表非iphone莫屬了。據統計,截止2011年5月,AppStore的應用軟件數量達381062個,位居第一,而Android Market的應用軟件數量達294738,緊隨AppStore後面,並有望在8月份越過AppStore。隨着Android系統逐步擴大市場佔有率,終端設備的多樣性亟需更多的移動開發人員的參與。據業內統計,Android研發人才缺口至少30萬。目前,對Android人才需求一類是偏向硬件驅動的Android人才需求,一類是偏向軟件應用的Android人才需求。總的來說,對有志於從事Android硬件驅動的開發工程師來說,現在是一個大展拳腳的機會。那麼,就讓我們一起來看看如何爲Android系統編寫內核驅動程序吧。

        這裏,我們不會爲真實的硬件設備編寫內核驅動程序。爲了方便描述爲Android系統編寫內核驅動程序的過程,我們使用一個虛擬的硬件設備,這個設備只有一個4字節的寄存器,它可讀可寫。想起我們第一次學習程序語言時,都喜歡用“Hello, World”作爲例子,這裏,我們就把這個虛擬的設備命名爲“hello”,而這個內核驅動程序也命名爲hello驅動程序。其實,Android內核驅動程序和一般Linux內核驅動程序的編寫方法是一樣的,都是以Linux模塊的形式實現的,具體可參考前面Android學習啓動篇一文中提到的Linux Device Drivers一書。不過,這裏我們還是從Android系統的角度來描述Android內核驅動程序的編寫和編譯過程。

       一. 參照前面兩篇文章在Ubuntu上下載、編譯和安裝Android最新源代碼在Ubuntu上下載、編譯和安裝Android最新內核源代碼(Linux Kernel)準備好Android內核驅動程序開發環境。

       二. 進入到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文件:

  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文件系統來訪問。下面分段描述該驅動程序的實現。

   首先是包含必要的頭文件和定義三種訪問設備的方法:

  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這四個打開、釋放、讀和寫設備文件的方法:

  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:

  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. }  

        定義通過proc文件系統訪問方法,主要實現了hello_proc_read和hello_proc_write兩個方法,同時定義了在proc文件系統創建和刪除文件的方法hello_create_proc和hello_remove_proc:

  1. /*讀取設備寄存器val的值,保存在page緩衝區中*/  
  2. static ssize_t hello_proc_read(char* page, char** start, off_t off, int count, int* eof, void* data) {  
  3.     if(off > 0) {  
  4.         *eof = 1;  
  5.         return 0;  
  6.     }  
  7.   
  8.     return __hello_get_val(hello_dev, page);  
  9. }  
  10.   
  11. /*把緩衝區的值buff保存到設備寄存器val中去*/  
  12. static ssize_t hello_proc_write(struct file* filp, const char __user *buff, unsigned long len, void* data) {  
  13.     int err = 0;  
  14.     char* page = NULL;  
  15.   
  16.     if(len > PAGE_SIZE) {  
  17.         printk(KERN_ALERT"The buff is too large: %lu.\n", len);  
  18.         return -EFAULT;  
  19.     }  
  20.   
  21.     page = (char*)__get_free_page(GFP_KERNEL);  
  22.     if(!page) {                  
  23.         printk(KERN_ALERT"Failed to alloc page.\n");  
  24.         return -ENOMEM;  
  25.     }          
  26.   
  27.     /*先把用戶提供的緩衝區值拷貝到內核緩衝區中去*/  
  28.     if(copy_from_user(page, buff, len)) {  
  29.         printk(KERN_ALERT"Failed to copy buff from user.\n");                  
  30.         err = -EFAULT;  
  31.         goto out;  
  32.     }  
  33.   
  34.     err = __hello_set_val(hello_dev, page, len);  
  35.   
  36. out:  
  37.     free_page((unsigned long)page);  
  38.     return err;  
  39. }  
  40.   
  41. /*創建/proc/hello文件*/  
  42. static void hello_create_proc(void) {  
  43.     struct proc_dir_entry* entry;  
  44.       
  45.     entry = create_proc_entry(HELLO_DEVICE_PROC_NAME, 0, NULL);  
  46.     if(entry) {  
  47.         entry->owner = THIS_MODULE;  
  48.         entry->read_proc = hello_proc_read;  
  49.         entry->write_proc = hello_proc_write;  
  50.     }  
  51. }  
  52.   
  53. /*刪除/proc/hello文件*/  
  54. static void hello_remove_proc(void) {  
  55.     remove_proc_entry(HELLO_DEVICE_PROC_NAME, NULL);  
  56. }  

   最後,定義模塊加載和卸載方法,這裏只要是執行設備註冊和初始化操作:

  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.     dev->val = 0;  
  21.   
  22.     return 0;  
  23. }  
  24.   
  25. /*模塊加載方法*/  
  26. static int __init hello_init(void){   
  27.     int err = -1;  
  28.     dev_t dev = 0;  
  29.     struct device* temp = NULL;  
  30.   
  31.     printk(KERN_ALERT"Initializing hello device.\n");          
  32.   
  33.     /*動態分配主設備和從設備號*/  
  34.     err = alloc_chrdev_region(&dev, 0, 1, HELLO_DEVICE_NODE_NAME);  
  35.     if(err < 0) {  
  36.         printk(KERN_ALERT"Failed to alloc char dev region.\n");  
  37.         goto fail;  
  38.     }  
  39.   
  40.     hello_major = MAJOR(dev);  
  41.     hello_minor = MINOR(dev);          
  42.   
  43.     /*分配helo設備結構體變量*/  
  44.     hello_dev = kmalloc(sizeof(struct hello_android_dev), GFP_KERNEL);  
  45.     if(!hello_dev) {  
  46.         err = -ENOMEM;  
  47.         printk(KERN_ALERT"Failed to alloc hello_dev.\n");  
  48.         goto unregister;  
  49.     }          
  50.   
  51.     /*初始化設備*/  
  52.     err = __hello_setup_dev(hello_dev);  
  53.     if(err) {  
  54.         printk(KERN_ALERT"Failed to setup dev: %d.\n", err);  
  55.         goto cleanup;  
  56.     }          
  57.   
  58.     /*在/sys/class/目錄下創建設備類別目錄hello*/  
  59.     hello_class = class_create(THIS_MODULE, HELLO_DEVICE_CLASS_NAME);  
  60.     if(IS_ERR(hello_class)) {  
  61.         err = PTR_ERR(hello_class);  
  62.         printk(KERN_ALERT"Failed to create hello class.\n");  
  63.         goto destroy_cdev;  
  64.     }          
  65.   
  66.     /*在/dev/目錄和/sys/class/hello目錄下分別創建設備文件hello*/  
  67.     temp = device_create(hello_class, NULL, dev, "%s", HELLO_DEVICE_FILE_NAME);  
  68.     if(IS_ERR(temp)) {  
  69.         err = PTR_ERR(temp);  
  70.         printk(KERN_ALERT"Failed to create hello device.");  
  71.         goto destroy_class;  
  72.     }          
  73.   
  74.     /*在/sys/class/hello/hello目錄下創建屬性文件val*/  
  75.     err = device_create_file(temp, &dev_attr_val);  
  76.     if(err < 0) {  
  77.         printk(KERN_ALERT"Failed to create attribute val.");                  
  78.         goto destroy_device;  
  79.     }  
  80.   
  81.     dev_set_drvdata(temp, hello_dev);          
  82.   
  83.     /*創建/proc/hello文件*/  
  84.     hello_create_proc();  
  85.   
  86.     printk(KERN_ALERT"Succedded to initialize hello device.\n");  
  87.     return 0;  
  88.   
  89. destroy_device:  
  90.     device_destroy(hello_class, dev);  
  91.   
  92. destroy_class:  
  93.     class_destroy(hello_class);  
  94.   
  95. destroy_cdev:  
  96.     cdev_del(&(hello_dev->dev));  
  97.   
  98. cleanup:  
  99.     kfree(hello_dev);  
  100.   
  101. unregister:  
  102.     unregister_chrdev_region(MKDEV(hello_major, hello_minor), 1);  
  103.   
  104. fail:  
  105.     return err;  
  106. }  
  107.   
  108. /*模塊卸載方法*/  
  109. static void __exit hello_exit(void) {  
  110.     dev_t devno = MKDEV(hello_major, hello_minor);  
  111.   
  112.     printk(KERN_ALERT"Destroy hello device.\n");          
  113.   
  114.     /*刪除/proc/hello文件*/  
  115.     hello_remove_proc();          
  116.   
  117.     /*銷燬設備類別和設備*/  
  118.     if(hello_class) {  
  119.         device_destroy(hello_class, MKDEV(hello_major, hello_minor));  
  120.         class_destroy(hello_class);  
  121.     }          
  122.   
  123.     /*刪除字符設備和釋放設備內存*/  
  124.     if(hello_dev) {  
  125.         cdev_del(&(hello_dev->dev));  
  126.         kfree(hello_dev);  
  127.     }          
  128.   
  129.     /*釋放設備號*/  
  130.     unregister_chrdev_region(devno, 1);  
  131. }  
  132.   
  133. MODULE_LICENSE("GPL");  
  134. MODULE_DESCRIPTION("First Android Driver");  
  135.   
  136. module_init(hello_init);  
  137. 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的值,執行不同的編譯方法。
      六. 修改arch/arm/Kconfig和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驅動。
        十. 參照在Ubuntu上下載、編譯和安裝Android最新內核源代碼(Linux Kernel)一文所示,運行新編譯的內核文件,驗證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
        進入到proc目錄,可以看到hello文件:
        root@android:/ # cd proc
        root@android:/proc # ls
        訪問hello文件的值:
        root@android:/proc # cat hello
        0
        root@android:/proc # echo '5' > hello
        root@android:/proc # cat hello
        5
        進入到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內核驅動程序就完成了,並且驗證一切正常。這裏我們採用的是系統提供的方法和驅動程序進行交互,也就是通過proc文件系統和devfs文件系統的方法,下一篇文章中,我們將通過自己編譯的C語言程序來訪問/dev/hello文件來和hello驅動程序交互,敬請期待。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章