字符驱动程序

来源:互联网 发布:wingide ubuntu 编辑:程序博客网 时间:2024/06/06 00:54
要求:掌握添加设备驱动程序的方法

内容:
采用模块方法,添加一个新的设备驱动程序。
要求添加字符设备的驱动。

编写一个应用程序,测试添加的驱动程序。

linxu系统中,在应用程序看来,硬件设备只是一个设备文件,应用程序可以象操作普通文件一样对硬件设备进行操作。设备驱动程序是内核的一部分,它完成以下的功能:

  1. 对设备初始化和释放.

  2. 把数据从内核传送到硬件和从硬件读取数据.

  3. 读取应用程序传送给设备文件的数据和回送应用程序请求的数据.

  4. 检测和处理设备出现的错误.

          设备分为两种:字符设备和块设备,这里就以简单的字符设备为例。

在设备驱动程序中有一个非常重要的结构file_operations,该结构的每个域都对应着一个系统调用。用户进程利用系统调用在对设备文件进行诸如read/write操作时,系统调用通过设备文件的主设备号找到相应的设备驱动程序,然后读取这个数据结构相应的函数指针,接着把控制权交给该函数。

struct file_operations {

int(*seek) (struct inode * ,structfile *, off_t ,int);
int (*read) (struct inode * ,structfile *, char ,int);
int (*write) (struct inode * ,structfile *, off_t ,int);

……

           }

编写设备驱动程序的主要工作是编写子函数,并填充file_operations的各个域

例如:

Structfile_operations my_fops={

.read=my_read,

.write=my_write,

.open=my_open,

.release=my_release

}

然后再定义函数my_read,my_write,my_open,my_release相应的函数体。

例如:

  staticssize_t my_open(struct inode *inode,struct file *file){

staticint counter=0;

if(Device_Open)

return-EBUSY;

Device_Open++;

/*写入设备的信息*/

sprintf(msg,"the device hasbeen called %d times\n",counter++);

msg_ptr=msg;

return0;

}

同时对于可卸载的内核模块(LKM),至少还有两个基本的模块:

my_init用于注册设备,获得设备的主设备号

调用register_chrdev(0,“sky_driver(设备名)”,&my_fops);

my_exit用于注销设备

调用unregister_chrdev(my_major,“sky_driver(设备名)”);

然后在程序尾再调用这两个函数

Module_init(my_init);

Module_exit(my_exit)

MODULE_LICENSE(“GPL”);

不过如果使用特殊函数名

init_module 和cleanup_module,

就不用在程序最后加上上面那三行代码了。


废话少说,以下是实验过程:

首先编写驱动程序。


将后面附上的3个源程序放在一个文件夹中后(也可直接打包下载http://download.csdn.net/detail/creazyapple/4088141)

,开始进行实验:

1.编译驱动程序。   

在控制台下进入文件所在目录,输入命令make。如图:


             看到了吗?提示错误。原来需要用超级用户权限。

没有错误提示,说明make成功,进入文件夹下可以看到多了一些.k,.ko之类的文件。这就是编译好的模块。


2.  装载模块。

同样,必须要是root下才能进行。装载前,我们可以先看看系统中的模块:lsmod 

装载,输入命令:   insmod devDrv.ko 

完成后,再看看系统中的模块,发现多了一个模块“devDrv”,表示我们成功加载了!

可以用命令查看系统日志信息:dmesg

看到如下信息:

这正是在我们的驱动程序中注册函数输出的内容哦!

3.分配次设备号。

每个文件都有两个设备号,第一个是主设备号,标识驱动程序,第二个是从设备号,标识使用同一个设备驱动程序的不同的硬件设备比如有两个软盘,就可以用从设备号来区分他们.设备文件的的主设备号必须与设备驱动程序在登记时申请的主设备号一致,否则用户进程将无法访问到驱动程序.。

分配前,我们必须要知道主设备号(其实在上一步中我们从dmesg中已经看到主设备好为250):      cat  /proc/devices 

可见到这一行:250 myDevice,是了,主设备号为250.

现在我们分配从设备号:mknod /dev/myDevice c 250 0

实际上就是在虚拟文件夹/dev/中加一个设备(在系统看来是文件)myDevice ,注意,这个是设备名,在测试文件中真是要利用这个设备名打开设备。最后的0表示从设备号。可以随便分配(只要不冲突)。

此后便可以在/dev/目录下看到新建的设备myDevice了:ls /dev/


一切成功的话,就可以测试我们的驱动程序啦!

4.测试驱动程序。


首先要编译测试程序:gcc drvTest.c -o sb 

得到sb可执行程序,再执行 :./sb

测试程序首先列出所有的设备名,让我们选中一个,当然输入myDevice啦:


正确读出之前存放在设备中的字符串!然后提示让我们输入一个字符串,随便啦:

  

最后是不是正确保存、读出了呢?of course !而且还告诉我们调用了几次这个设备呢!

5.删除设备、模块。

首先删除设备。就像删除普通文件一样:rm /dev/myDevice 

删除后,看看/dev/目录下是佛已经木有myDevice 啦?:ls /dev/

接着删除模块:rmmod devDrv.

看看模块列表中是否已经没有devDrv模块了?:lsmod



在本次实验中,还特别添加了一些代码来给设备上锁,实现互斥,以免同时有多个进程读取设备造成混乱。(一般来说,字符设备如打印机是不能共享滴。。)观察驱动程序devDrv.c中两个函数

static int my_open(struct inode *inode, struct file *file)
{
        if(mutex)
                return -EBUSY;
        mutex = 1;//上锁
    printk("<1>main  device : %d\n", MAJOR(inode->i_rdev));
    printk("<1>slave device : %d\n", MINOR(inode->i_rdev));
    printk("<1>%d times to call the device\n", ++counter);
    try_module_get(THIS_MODULE);
    return 0;
}
/* 每次使用完后会release */
static int my_release(struct inode *inode, struct file *file)
{
    printk("Device released!\n");
    module_put(THIS_MODULE);
        mutex = 0;//开锁
    return 0;
}

int 型mutex就是用来上锁的,它被初始化为0,一旦使用该设备,就首先要调用my_open函数,将mutex设置为1,如果此后还想使用该设备,必然因为mutex为1而返回-EBUSY,而终止。使用完该设备后,调用my_release释放设备,将mutex重新设回0.

特别注意,还有一个counter变量,使用来计量使用次数的。

makefile的格式相当严格,比如不能用8个空格来代替一个table键等。

makefile最后有一句:


devDrv一定要对应我们要编译的驱动程序devDrv.c的文件名。

源代码附上。共三个文件,将其放在一个文件夹中

1.驱动程序devDrv.c
[cpp] view plain copy
 print?
  1. /* 
  2.  *  devDrv.c 
  3.  *  threeProcess 
  4.  *  Created on: 2012-2-24 
  5.  *      Author: zhushengben 
  6.  */  
  7.   
  8. #include "linux/kernel.h"  
  9. #include "linux/module.h"  
  10. #include "linux/fs.h"  
  11. #include "linux/init.h"  
  12. #include "linux/types.h"  
  13. #include "linux/errno.h"  
  14. #include "linux/uaccess.h"  
  15. #include "linux/kdev_t.h"  
  16. #define MAX_SIZE 1024  
  17.   
  18. static int my_open(struct inode *inode, struct file *file);  
  19. static int my_release(struct inode *inode, struct file *file);  
  20. static ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f);  
  21. static ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f);  
  22.   
  23. static char message[MAX_SIZE] = "-------congratulations--------!";  
  24. static int device_num = 0;//设备号  
  25. static int counter = 0;//计数用  
  26. static int mutex = 0;//互斥用  
  27. static char* devName = "myDevice";//设备名  
  28.   
  29. struct file_operations pStruct =  
  30. { open:my_open, release:my_release, read:my_read, write:my_write, };  
  31.   
  32. /* 注册模块 */  
  33. int init_module()  
  34. {  
  35.     int ret;  
  36.     /* 函数中第一个参数是告诉系统,新注册的设备的主设备号由系统分配, 
  37.      * 第二个参数是新设备注册时的设备名字, 
  38.      * 第三个参数是指向file_operations的指针, 
  39.      * 当用设备号为0创建时,系统一个可以用的设备号创建模块 */  
  40.     ret = register_chrdev(0, devName, &pStruct);  
  41.     if (ret < 0)  
  42.     {  
  43.         printk("regist failure!\n");  
  44.         return -1;  
  45.     }  
  46.     else  
  47.     {  
  48.         printk("the device has been registered!\n");  
  49.         device_num = ret;  
  50.         printk("<1>the virtual device's major number %d.\n", device_num);  
  51.         printk("<1>Or you can see it by using\n");  
  52.         printk("<1>------more /proc/devices-------\n");  
  53.         printk("<1>To talk to the driver,create a dev file with\n");  
  54.         printk("<1>------'mknod /dev/myDevice c %d 0'-------\n", device_num);  
  55.         printk("<1>Use \"rmmode\" to remove the module\n");  
  56.   
  57.         return 0;  
  58.     }  
  59. }  
  60. /* 注销模块,函数名很特殊 */  
  61. void cleanup_module()  
  62. {  
  63.     unregister_chrdev(device_num, devName);  
  64.     printk("unregister it success!\n");  
  65. }  
  66.   
  67. static int my_open(struct inode *inode, struct file *file)  
  68. {  
  69.     if (mutex)  
  70.         return -EBUSY;  
  71.     mutex = 1;//上锁  
  72.     printk("<1>main  device : %d\n", MAJOR(inode->i_rdev));  
  73.     printk("<1>slave device : %d\n", MINOR(inode->i_rdev));  
  74.     printk("<1>%d times to call the device\n", ++counter);  
  75.     try_module_get(THIS_MODULE);  
  76.     return 0;  
  77. }  
  78. /* 每次使用完后会release */  
  79. static int my_release(struct inode *inode, struct file *file)  
  80. {  
  81.     printk("Device released!\n");  
  82.     module_put(THIS_MODULE);  
  83.     mutex = 0;//开锁  
  84.     return 0;  
  85. }  
  86.   
  87. static ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f)  
  88. {  
  89.     if(copy_to_user(user,message,sizeof(message)))  
  90.     {  
  91.         return -EFAULT;  
  92.     }  
  93.     return sizeof(message);  
  94. }  
  95.   
  96. static ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f)  
  97. {  
  98.     if(copy_from_user(message,user,sizeof(message)))  
  99.     {  
  100.         return -EFAULT;  
  101.     }  
  102.     return sizeof(message);  
  103. }  

2.makefile文件。注意,文件名就叫makefile或者Makefile,大小写不可随意更改,关于makefile的编写,参考

http://wiki.ubuntu.org.cn/index.php?title=%E8%B7%9F%E6%88%91%E4%B8%80%E8%B5%B7%E5%86%99Makefile:MakeFile%E4%BB%8B%E7%BB%8D&variant=zh-cn


[cpp] view plain copy
 print?
  1. # If KERNELRELEASE is defined, we've been invoked from the  
  2. # kernel build system and can use its language.  
  3. ifeq ($(KERNELRELEASE),)  
  4.     # Assume the source tree is where the running kernel was built  
  5.     # You should set KERNELDIR in the environment if it's elsewhere  
  6.     KERNELDIR ?= /lib/modules/$(shell uname -r)/build  
  7.     # The current directory is passed to sub-makes as argument  
  8.     PWD := $(shell pwd)  
  9. modules:  
  10.     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules  
  11. modules_install:  
  12.     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install  
  13. clean:  
  14.     rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions  
  15. .PHONY: modules modules_install clean  
  16. else  
  17.     # called from kernel build system: just declare what our modules are  
  18.     obj-m := devDrv.o  
  19. endif  

3.测试程序test.c

[cpp] view plain copy
 print?
  1. /* 
  2.  *  drvTest.c 
  3.  *  threeProcess 
  4.  *  Created on: 2012-2-24 
  5.  *      Author: zhushengben 
  6.  */  
  7.   
  8. #include <sys/types.h>  
  9. #include <sys/stat.h>  
  10. #include <stdlib.h>  
  11. #include <string.h>  
  12. #include <stdio.h>  
  13. #include <fcntl.h>  
  14. #include <unistd.h>  
  15. #define MAX_SIZE 1024  
  16.   
  17. int main(void)  
  18. {  
  19.     int fd;  
  20.     char buf[MAX_SIZE];  
  21.     char get[MAX_SIZE];  
  22.     char devName[20], dir[50] = "/dev/";  
  23.     system("ls /dev/");  
  24.     printf("Please input the device's name you wanna to use :");  
  25.     gets(devName);  
  26.     strcat(dir, devName);  
  27.     fd = open(dir, O_RDWR | O_NONBLOCK);  
  28.     if (fd != -1)  
  29.     {  
  30.         read(fd, buf, sizeof(buf));  
  31.         printf("The device was inited with a string : %s\n", buf);  
  32.         /* 测试写 */  
  33.         printf("Please input a string  :\n");  
  34.         gets(get);  
  35.         write(fd, get, sizeof(get));  
  36.         /* 测试读 */  
  37.         read(fd, buf, sizeof(buf));  
  38.         system("dmesg");  
  39.         printf("\nThe string in the device now is : %s\n", buf);  
  40.         close(fd);  
  41.         return 0;  
  42.     }  
  43.     else  
  44.     {  
  45.         printf("Device open failed\n");  
  46.         return -1;  
  47.     }  
  48. }  
0 0