zoukankan      html  css  js  c++  java
  • Android应用程序访问linux驱动第一步:实现并测试Linux驱动

    一直都想亲自做一次使用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
    ",buf,count);
        printk(KERN_ALERT"__hello_set_val.dev->val: %s  count:%d
    ",dev->val,count);
        strncpy(dev->val,buf, count);
        printk(KERN_ALERT"__hello_set_val.dev->val: %s  count:%d
    ",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.
    ");
        printk(KERN_ALERT"%s
    ",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
    ",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.
    ");          
    
        /*动态分配主设备和从设备号*/  
        err = alloc_chrdev_region(&dev, 0, 1, HELLO_DEVICE_NODE_NAME);  
        if(err < 0) {  
            printk(KERN_ALERT"Failed to alloc char dev region.
    ");  
            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.
    ");  
            goto unregister;  
        }          
    
        /*初始化设备*/  
        err = __hello_setup_dev(hello_dev);  
        if(err) {  
            printk(KERN_ALERT"Failed to setup dev: %d.
    ", 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.
    ");  
            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.
    ");  
        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
    ");          
    
        /*销毁设备类别和设备*/  
        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);  
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291

    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  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    二。编译驱动

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

    1.Makefile,用于编译驱动

    obj-$(CONFIG_HELLO) += hello.o
    • 1

    2.Kconfig

           config HELLO
               tristate "Test Driver"
               default n
               help
               This is the test driver.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3修改driver目录下的Makefile:

    添加如下一项:

    obj-$(CONFIG_HELLO) += hello/
    • 1

    4.修改driver目录下的Kconfig

    添加如下一项:

    source "drivers/hello/Kconfig"
    • 1

    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.
    ", HELLO_DEVICE);  
            return -1;  
        }  
    
        printf("Read original value:
    "); 
        //先读一次数据看看
        read(fd, str, 10);  
        printf("read data: %s
    ", str);  
        strncpy(str,"nihao",sizeof("nihao"));  
        printf("write nihao
    ");  
        //写nihao进去
        write(fd, str, sizeof(str));  
    
        printf("Read the value again:
    ");  
        //读看看是不是nihao
            read(fd, str, 10);  
            printf("read data: %s
    ", str);  
        close(fd);  
        return 0;  
    }  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    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)
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    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: hell
    write nihao
    Read the value again:
    read data: nihao
    • 1
    • 2
    • 3
    • 4
    • 5

    可见测试成功。

    版权声明:本文为博主原创文章,未经博主允许不得转载。
  • 相关阅读:
    C语言函数手册—函数分类列表
    HTTP协议详解(一直在用可是这篇太好了转一下)
    Substance风格实例大全javaswing皮肤风格大全(原)
    Component creation must be done on Event Dispatch Thread错误解决方法
    用开源Look&Feel (Substance)写 漂亮的Swing应用程序
    Swift翻译之-关于Swift
    Swift翻译之-Swift语法入门 Swift语法介绍
    Swift语言简介+快速上手
    JDK各个版本的新特性jdk1.5-jdk8
    5个常用Java代码混淆器 助你保护你的代码
  • 原文地址:https://www.cnblogs.com/wanghuaijun/p/7710332.html
Copyright © 2011-2022 走看看