Linux驱动入门-最简单字符设备驱动(基于pc ubuntu)

Posted Wireless_Link

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux驱动入门-最简单字符设备驱动(基于pc ubuntu)相关的知识,希望对你有一定的参考价值。

一.字符设备驱动概念

字符设备是 Linux 驱动中最基本的一类设备驱动,字符设备就是一个一个字节,按照字节流进行读写操作的设备,读写数据是分先后顺序的。比如我们最常见的点灯、按键、 IIC、 SPI,LCD 等等都是字符设备,这些设备的驱动就叫做字符设备驱动。
在详细的学习字符设备驱动架构之前,我们先来简单的了解一下 Linux 下的应用程序是如何调用驱动程序的,Linux 应用程序对驱动程序的调用如图

在 Linux 中一切皆为文件,驱动加载成功以后会在“/dev”目录下生成一个相应的文件,应用程序通过对这个名为“/dev/xxx” (xxx 是具体的驱动文件名字)的文件进行相应的操作即可实现对硬件的操作。比如现在有个叫做/dev/led 的驱动文件,此文件是 led 灯的驱动文件。应用程序使用 open 函数来打开文件/dev/led,使用完成以后使用 close 函数关闭/dev/led 这个文件。 open和 close 就是打开和关闭 led 驱动的函数,如果要点亮或关闭 led,那么就使用 write 函数来操作,也就是向此驱动写入数据,这个数据就是要关闭还是要打开 led 的控制参数。如果要获取led 灯的状态,就用 read 函数从驱动中读取相应的状态。
应用程序运行在用户空间,而 Linux 驱动属于内核的一部分,因此驱动运行于内核空间。当我们在用户空间想要实现对内核的操作,比如使用 open 函数打开/dev/led 这个驱动,因为用户空间不能直接对内核进行操作,因此必须使用一个叫做“系统调用”的方法来实现从用户空间“陷入” 到内核空间,这样才能实现对底层驱动的操作。 open、 close、 write 和 read 等这些函数是由 C 库提供的,在 Linux 系统中,系统调用作为 C 库的一部分。当我们调用 open 函数的时候流程如图

其中关于 C 库以及如何通过系统调用“陷入” 到内核空间这个我们不用去管,我们重点关注的是应用程序和具体的驱动,应用程序使用到的函数在具体驱动程序中都有与之对应的函数,比如应用程序中调用了 open 这个函数,那么在驱动程序中也得有一个名为 open 的函数。每一个系统调用,在驱动中都有与之对应的一个驱动函数,在 Linux 内核文件 include/linux/fs.h 中有个叫做 file_operations 的结构体,此结构体就是 Linux 内核驱动操作函数集合,内容如下所示:

struct file_operations 
	struct module *owner;
	loff_t (*llseek) (struct file *, loff_t, int);
	ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
	ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
	ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
	ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
	int (*iterate) (struct file *, struct dir_context *);
	unsigned int (*poll) (struct file *, struct poll_table_struct *);
	long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
	long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
	int (*mmap) (struct file *, struct vm_area_struct *);
	int (*mremap)(struct file *, struct vm_area_struct *);
	int (*open) (struct inode *, struct file *);
	int (*flush) (struct file *, fl_owner_t id);
	int (*release) (struct inode *, struct file *);
	int (*fsync) (struct file *, loff_t, loff_t, int datasync);
	int (*aio_fsync) (struct kiocb *, int datasync);
	int (*fasync) (int, struct file *, int);
	int (*lock) (struct file *, int, struct file_lock *);
	ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
	unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
	int (*check_flags)(int);
	int (*flock) (struct file *, int, struct file_lock *);
	ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
	ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
	int (*setlease)(struct file *, long, struct file_lock **, void **);
	long (*fallocate)(struct file *file, int mode, loff_t offset,
			  loff_t len);
	void (*show_fdinfo)(struct seq_file *m, struct file *f);
#ifndef CONFIG_MMU
	unsigned (*mmap_capabilities)(struct file *);
#endif

简单介绍一下 file_operation 结构体中比较重要的、常用的函数:
owner 拥有该结构体的模块的指针,一般设置为 THIS_MODULE。
llseek 函数用于修改文件当前的读写位置。
read 函数用于读取设备文件。
write 函数用于向设备文件写入(发送)数据。
poll 是个轮询函数,用于查询设备是否可以进行非阻塞的读写。
unlocked_ioctl 函数提供对于设备的控制功能,与应用程序中的 ioctl 函数对应。
compat_ioctl 函数与 unlocked_ioctl 函数功能一样,区别在于在 64 位系统上,32 位的应用程序调用将会使用此函数。在 32 位的系统上运行 32 位的应用程序调用的是unlocked_ioctl。
mmap 函数用于将将设备的内存映射到进程空间中(也就是用户空间),一般帧缓冲设备会使用此函数,比如 LCD 驱动的显存,将帧缓冲(LCD 显存)映射到用户空间中以后应用程序就可以直接操作显存了,这样就不用在用户空间和内核空间之间来回复制。
open 函数用于打开设备文件。
release 函数用于释放(关闭)设备文件,与应用程序中的 close 函数对应。
fasync 函数用于刷新待处理的数据,用于将缓冲区中的数据刷新到磁盘中。
aio_fsync 函数与 fasync 函数的功能类似,只是 aio_fsync 是异步刷新待处理的数据。
在字符设备驱动开发中最常用的就是上面这些函数,关于其他的函数大家可以查阅相关文档。我们在字符设备驱动开发中最主要的工作就是实现上面这些函数,不一定全部都要实现,
但是像 open、 release、 write、 read 等都是需要实现的,当然了,具体需要实现哪些函数还是要看具体的驱动要求。

二.字符设备驱动开发步骤

我们简单的介绍了一下字符设备驱动,那么字符设备驱动开发都有哪些步骤呢?我们在学习裸机或者 STM32 的时候关于驱动的开发就是初始化相应的外设寄存器,在 Linux 驱动开发中肯定也是要初始化相应的外设寄存器,这个是毫无疑问的。只是在 Linux 驱动开发中我们需要按照其规定的框架来编写驱动,所以说学 Linux 驱动开发重点是学习其驱动框架。

1.驱动模块的加载和卸载

Linux 驱动有两种运行方式,第一种就是将驱动编译进 Linux 内核中,这样当 Linux 内核启动的时候就会自动运行驱动程序。第二种就是将驱动编译成模块(Linux 下模块扩展名为.ko),在Linux 内核启动以后使用“insmod”命令加载驱动模块。在调试驱动的时候一般都选择将其编译为模块,这样我们修改驱动以后只需要编译一下驱动代码即可,不需要编译整个 Linux 代码。而且在调试的时候只需要加载或者卸载驱动模块即可,不需要重启整个系统。总之,将驱动编译为模块最大的好处就是方便开发,当驱动开发完成,确定没有问题以后就可以将驱动编译进
Linux 内核中,当然也可以不编译进 Linux 内核中,具体看自己的需求。模块有加载和卸载两种操作,我们在编写驱动的时候需要注册这两种操作函数,模块的加载和卸载注册函数如下:

module_init(xxx_init); //注册模块加载函数
module_exit(xxx_exit); //注册模块卸载函数

module_init 函数用来向 Linux 内核注册一个模块加载函数,参数 xxx_init 就是需要注册的具体函数,当使用“insmod”命令加载驱动的时候, xxx_init 这个函数就会被调用。 module_exit()函数用来向 Linux 内核注册一个模块卸载函数,参数 xxx_exit 就是需要注册的具体函数,当使用“rmmod”命令卸载具体驱动的时候 xxx_exit 函数就会被调用。字符设备驱动模块加载和卸载模板如下所示:

/* 驱动入口函数 */
static int __init xxx_init(void)

    /* 入口函数的具体内容 */
	return 0;


/* 驱动出口函数 */
static void __exit xxx_deinit(void)

	/* 出口函数的具体内容 */



module_init(xxx_init);
module_exit(xxx_deinit);

驱动编译完成以后扩展名为.ko,有两种命令可以加载驱动模块: insmod和 modprobe, insmod是最简单的模块加载命令,此命令用于加载指定的.ko 模块,比如加载 drv.ko 这个驱动模块,命令如下:

insmod drv.ko

insmod 命令不能解决模块的依赖关系,比如 drv.ko 依赖 first.ko 这个模块,就必须先使用insmod 命令加载 first.ko 这个模块,然后再加载 drv.ko 这个模块。 但是 modprobe 就不会存在这个问题, modprobe 会分析模块的依赖关系,然后会将所有的依赖模块都加载到内核中,因此modprobe 命令相比 insmod 要智能一些。 modprobe 命令主要智能在提供了模块的依赖性分析、错误检查、错误报告等功能,推荐使用 modprobe 命令来加载驱动。 modprobe 命令默认会去/lib/modules/<kernel-version>目录中查找模块,比如本书使用的 Linux kernel 的版本号为 4.1.15,因此 modprobe 命令默认会到/lib/modules/4.1.15 这个目录中查找相应的驱动模块,一般自己制作的根文件系统中是不会有这个目录的,所以需要自己手动创建。
驱动模块的卸载使用命令“rmmod”即可,比如要卸载 drv.ko,使用如下命令即可:

rmmod drv.ko

也可以使用“modprobe -r”命令卸载驱动,比如要卸载 drv.ko,命令如下:

modprobe -r drv.ko

使用 modprobe 命令可以卸载掉驱动模块所依赖的其他模块,前提是这些依赖模块已经没有被其他模块所使用,否则就不能使用 modprobe 来卸载驱动模块。所以对于模块的卸载,还是推荐使用 rmmod 命令。

2.添加LICENSE以及作者信息

写完基本的框架后,我们要加上LICENSE信息以及作者信息,LICENSE 是必须添加的 ,否则的话编译的时候会报错 作者信息不是必选,LICENSE 和作者信息的添加使用如下两个函数

MODULE_LICENSE() //添加模块 LICENSE 信息
MODULE_AUTHOR() //添加模块作者信息

其中LICENSE填写GPL,因为Linux本身就是GPL协议的,实例如下:

MODULE_LICENSE("GPL");

3.在ubuntu巩固小节1-2内容

学习完以上的内容,我们就可以写程序,光说不练假把式,所以我们直接来实践

我们在ubuntu来写一个程序来体验下(由于最开始的简单的字符设备驱动,不需要操作特定的板子,所以我们在ubuntu直接写程序比较简单验证)

3.1 写一个hello_driver.c

#include <linux/module.h>

static int __init hello_driver_init(void)

	printk("hello_driver_init\\r\\n");
	return 0;


static void __exit hello_driver_cleanup(void)

	printk("hello_driver_cleanup\\r\\n");



module_init(hello_driver_init);
module_exit(hello_driver_cleanup);
MODULE_LICENSE("GPL");

就是这么简单,内容我们之前都见过,只有printk我们没有见过,printk是内核打印log的机制,类似于app层面的printf.

3.2 写makefile

写完hello_driver.c,我们要写一个makefile来编译以下文件,makefile内容如下:

KERNELDIR := /lib/modules/$(shell uname -r)/build
CURRENT_PATH := $(shell pwd)
obj-m := hello_driver.o

build: kernel_modules

kernel_modules:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules
clean:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean

其中KERNELDIR就是ubuntu build内核的路径,至于什么作用下,先不用管,先暂时照着写,后续再介绍

3.3 编译

make

3.4 加载

sudo insmod hello_driver.ko

可以看到并没有我们printk的log输出,那么怎么能确定我们加载成功了呢?lsmod |grep hello_driver

可以看到我们加载成功了,那么printk的打印内容呢?那是因为你如果没有配置printk的等级,他不会打印到terminal上,查看用dmesg来查看就可以看到了

另外注意的一点在ubuntu需要用sudo来加载

3.5 卸载

sudo rmmod hello_driver

好了,简单吧,我们来继续学下字符设备注册跟注销用上file_operations

4.字符设备注册与注销

对于字符设备驱动而言,当驱动模块加载成功以后需要注册字符设备,同样,卸载驱动模块的时候也需要注销掉字符设备。字符设备的注册和注销函数原型如下所示 :

static inline int register_chrdev(unsigned int major, const char *name,const struct file_operations *fops)
static inline void unregister_chrdev(unsigned int major, const char *name)

register_chrdev 函数用于注册字符设备,此函数一共有三个参数,这三个参数的含义如下:
major: 主设备号, Linux 下每个设备都有一个设备号,设备号分为主设备号和次设备号两部分,关于设备号后面会详细讲解。
name:设备名字,指向一串字符串。
fops: 结构体 file_operations 类型指针,指向设备的操作函数集合变量。
unregister_chrdev 函数用户注销字符设备,此函数有两个参数,这两个参数含义如下:
major: 要注销的设备对应的主设备号。
name: 要注销的设备对应的设备名。
一般字符设备的注册在驱动模块的入口函数 xxx_init 中进行,字符设备的注销在驱动模块的出口函数 xxx_exit 中进行

4.1 设备号的组成

为了方便管理, Linux 中每个设备都有一个设备号,设备号由主设备号和次设备号两部分组成,主设备号表示某一个具体的驱动,次设备号表示使用这个驱动的各个设备。 Linux 提供了一个名为 dev_t 的数据类型表示设备号, dev_t 定义在文件 include/linux/types.h 里面,定义如下:

typedef __u32 __kernel_dev_t;
typedef __kernel_dev_t dev_t;

可以看出 dev_t 是__u32 类型的,而__u32 定义在文件 include/uapi/asm-generic/int-ll64.h 里面,定义如下:

typedef unsigned int __u32;

综上所述, dev_t 其实就是 unsigned int 类型,是一个 32 位的数据类型。这 32 位的数据构 成了主设备号和次设备号两部分,其中高 12 位为主设备号, 低 20 位为次设备号。因此 Linux系统中主设备号范围为 0~4095,所以大家在选择主设备号的时候一定不要超过这个范围。在文件 include/linux/kdev_t.h 中提供了几个关于设备号的操作函数(本质是宏),如下所示:

#define MINORBITS 20
#define MINORMASK ((1U << MINORBITS) - 1)
#define MAJOR(dev) ((unsigned int) ((dev) >> MINORBITS))
#define MINOR(dev) ((unsigned int) ((dev) & MINORMASK))
#define MKDEV(ma,mi) (((ma) << MINORBITS) | (mi))

宏 MINORBITS 表示次设备号位数,一共是 20 位。
宏 MINORMASK 表示次设备号掩码。
宏 MAJOR 用于从 dev_t 中获取主设备号,将 dev_t 右移 20 位即可。
宏 MINOR 用于从 dev_t 中获取次设备号,取 dev_t 的低 20 位的值即可。
宏 MKDEV 用于将给定的主设备号和次设备号的值组合成 dev_t 类型的设备号

5.内核空间跟用户空间交互数据

我们有了file_operations的概念后,但是有两个函数指针read/write,那么用户空间可以直接用内核空间的buffer指针吗?内核空间可以直接使用用户空间的buffer指针吗?答案是不能哈,所以要有两个函数来做转换,函数分别如下:

unsigned long copy_to_user(void  *dst, const void *src, unsigned long len)
unsigned long copy_from_user(void *to, const void *from, unsigned long n)

copy_to_user 函数来完成内核空间的数据到用户空间的复制 ,参数 to 表示目的,参数 from 表示源,参数 n 表示要复制的数据长度

copy_from_user函数来完成用户空间的数据到内核空间的复制,参数to表示目的,参数 from 表示源,参数 n 表示要复制的数据长度

6.在ubuntu巩固小节4-5内容

6.1 hello_driver.c的内容

#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>


#define CHRDEVBASE_MAJOR	200
uint8_t kernel_buffer[1024] = 0;

static int hello_world_open(struct inode * inode, struct file * file)

	printk("hello_world_open\\r\\n");
	return 0;


static int hello_world_release (struct inode * inode, struct file * file)

	printk("hello_world_release\\r\\n");
	return 0;


static ssize_t hello_world_read (struct file * file, char __user * buffer, size_t size, loff_t * ppos)

	printk("hello_world_read size:%ld\\r\\n",size);
	copy_to_user(buffer,kernel_buffer,size);
	return size;


static ssize_t hello_world_write(struct file * file, const char __user * buffer, size_t size, loff_t *ppos)

	printk("hello_world_write size:%ld\\r\\n",size);
	copy_from_user(kernel_buffer,buffer,size);
	return size;



static const struct file_operations hello_world_fops = 
	.owner		= THIS_MODULE,
	.open		= hello_world_open,
	.release = hello_world_release,
	.read		= hello_world_read,
	.write	= hello_world_write,
;


static int __init hello_driver_init(void)

	int ret;
	printk("hello_driver_init\\r\\n");
	ret = register_chrdev(CHRDEVBASE_MAJOR,"hello_driver",&hello_world_fops);

	return 0;


static void __exit hello_driver_cleanup(void)

	unregister_chrdev(CHRDEVBASE_MAJOR,"hello_driver");
	printk("hello_driver_cleanup\\r\\n");



module_init(hello_driver_init);
module_exit(hello_driver_cleanup);
MODULE_LICENSE("GPL");

hello_driver.c是驱动,用于编译出来ko,以上的内容就是我们4-5小节学习的内容,如果看不懂移步前面巩固内容

6.2 test_app.c内容

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>


/* mknod /dev/hello c 200 0 */

uint8_t buffer[512] = 0;

int main(int argc, char *argv[])

	int fd;
	int ret;
	
	fd  = open(argv[1], O_RDWR);

	if(!strcmp("read",argv[2]))
	
		printf("read data from kernel\\r\\n");
		ret = read(fd,buffer,sizeof(buffer));
		printf("ret len:%d data:%s\\r\\n",ret,buffer);
	

	if(!strcmp("write",argv[2]))
	
		printf("write data to kernel %s len:%d\\r\\n",argv[3],strlen(argv[3]));
		ret = write(fd,argv[3],strlen(argv[3]));
		printf("ret len:%d\\r\\n",ret);
	

	
	close(fd);

	

test_app.c的内容是用户态的app,用于跟驱动的节点去交互

此程序的用法是 test_app /dev/xxx write/read 数据

6.3 makefile

KERNELDIR := /lib/modules/$(shell uname -r)/build
CURRENT_PATH := $(shell pwd)
obj-m := hello_driver.o

build: kernel_modules

kernel_modules:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules
	$(CROSS_COMPILE)gcc -o test_app test_app.c
clean:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean
	rm -rf test_app

此makefile跟之前的差不多,只不过多了一个编译test_app.c的动作,应用程序生成的名称为test_app

6.4 验证程序

加载ko: sudo insmod hello_driver.ko

命令行生成节点名称:sudo mknod /dev/hello c 200 0

其中c 200 0代表是字符设备驱动,主设备号是200,次设备号是0,200这个是驱动中我们写的#define CHRDEVBASE_MAJOR 200,也可以通过cat /proc/devices命令行来确认

应用程序写数据:sudo ./test_app /dev/hello write 1234567890

应用程序读取数据:sudo ./test_app /dev/hello read

卸载驱动:sudo rmmod hello_driver

删除节点:sudo rm -rf /dev/hello

7.自动创建节点

在前面的 Linux 驱动实验中,当我们使用 modprobe 加载驱动程序以后还需要使用命令“mknod”手动创建设备节点。本节就来讲解一下如何实现自动创建设备节点,在驱动中实现自动创建设备节点的功能以后,使用 modprobe 加载驱动模块成功的话就会自动在/dev 目录下创建对应的设备文件。

7.1 创建和删除类

自动创建设备节点的工作是在驱动程序的入口函数中完成的,一般在 cdev_add 函数后面添加自动创建设备节点相关代码。首先要创建一个 class 类, class 是个结构体,定义在文件include/linux/device.h 里面。 class_create 是类创建函数, class_create 是个宏定义,内容如下:

 

#define class_create(owner, name) \\
( \\
	static struct lock_class_key __key; \\
	__class_create(owner, name, &__key); \\
)

struct class *__class_create(struct module *owner, const char *name,struct lock_class_key *key)

根据上述代码,将宏 class_create 展开以后内容如下:

struct class *class_create (struct module *owner, const char *name)

class_create 一共有两个参数,参数 owner 一般为 THIS_MODULE,参数 name 是类名字。返回值是个指向结构体 class 的指针,也就是创建的类。卸载驱动程序的时候需要删除掉类,类删除函数为 class_destroy,函数原型如下:

void class_destroy(struct class *cls);

参数 cls 就是要删除的类。

7.2 创建设备

上一小节创建好类以后还不能实现自动创建设备节点,我们还需要在这个类下创建一个设备。使用 device_create 函数在类下面创建设备, device_create 函数原型如下:

struct device *device_create(struct class *class,struct device *parent,dev_t devt,void *drvdata,const char *fmt, ...)

device_create 是个可变参数函数,参数 class 就是设备要创建哪个类下面;参数 parent 是父设备,一般为 NULL,也就是没有父设备;参数 devt 是设备号;参数 drvdata 是设备可能会使用的一些数据,一般为 NULL; 参数 fmt 是设备名字,如果设置 fmt=xxx 的话,就会生成/dev/xxx这个设备文件。返回值就是创建好的设备。
同样的,卸载驱动的时候需要删除掉创建的设备,设备删除函数为 device_destroy,函数原型如下:

void device_destroy(struct class *class, dev_t devt)

参数 classs 是要删除的设备所处的类,参数 devt 是要删除的设备号。

8.巩固小节7的内容

我们就来修改下小节6的hello_driver.c就好了,其他都跟小节6一样(包括test_app.c makefile)

hello_driver.c的内容如下:

#include <linux/types.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/device.h>



#define CHRDEVBASE_MAJOR	200
uint8_t kernel_buffer[1024] = 0;
static struct class *hello_class;


static int hello_world_open(struct inode * inode, struct file * file)

	printk("hello_world_open\\r\\n");
	return 0;


static int hello_world_release (struct inode * inode, struct file * file)

	printk("hello_world_release\\r\\n");
	return 0;


static ssize_t hello_world_read (struct file * file, char __user * buffer, size_t size, loff_t * ppos)

	printk("hello_world_read size:%ld\\r\\n",size);
	copy_to_user(buffer,kernel_buffer,size);
	return size;


static ssize_t hello_world_write(struct file * file, const char __user * buffer, size_t size, loff_t *ppos)

	printk("hello_world_write size:%ld\\r\\n",size);
	copy_from_user(kernel_buffer,buffer,size);
	return size;



static const struct file_operations hello_world_fops = 
	.owner		= THIS_MODULE,
	.open		= hello_world_open,
	.release = hello_world_release,
	.read		= hello_world_read,
	.write	= hello_world_write,
;


static int __init hello_driver_init(void)

	int ret;
	printk("hello_driver_init\\r\\n");
	ret = register_chrdev(CHRDEVBASE_MAJOR,"hello_driver",&hello_world_fops);

	hello_class = class_create(THIS_MODULE,"hello_class");

	device_create(hello_class,NULL,MKDEV(CHRDEVBASE_MAJOR,0),NULL,"hello"); /* /dev/hello */

	return 0;


static void __exit hello_driver_cleanup(void)

	printk("hello_driver_cleanup\\r\\n");
	device_destroy(hello_class,MKDEV(CHRDEVBASE_MAJOR,0));
	class_destroy(hello_class);
	unregister_chrdev(CHRDEVBASE_MAJOR,"hello_driver");
	



module_init(hello_driver_init);
module_exit(hello_driver_cleanup);
MODULE_LICENSE("GPL");

做完这个步骤后就可以insmod后自动生成/dev/hello的节点,直接可以用test_app做测试了

9.新的字符设备驱动

9.1 设备号的分配

使用 register_chrdev 函数注册字符设备的时候只需要给定一个主设备号即可,但是这样会带来两个问题:
①、需要我们事先确定好哪些主设备号没有使用。
②、会将一个主设备号下的所有次设备号都使用掉,比如现在设置 LED 这个主设备号为
200,那么 0~1048575(2^20-1)这个区间的次设备号就全部都被 LED 一个设备分走了。这样太浪
费次设备号了!一个 LED 设备肯定只能有一个主设备号,一个次设备号。

分配的方式有以下两种,但是我们推荐尽量用动态分配设备号的方式

9.1.1 静态分配设备号

本小节讲的设备号分配主要是主设备号的分配。前面讲解字符设备驱动的时候说过了,注册字符设备的时候需要给设备指定一个设备号,这个设备号可以是驱动开发者静态的指定一个设备号,比如选择 200 这个主设备号。有一些常用的设备号已经被 Linux 内核开发者给分配掉了,具体分配的内容可以查看文档 Documentation/devices.txt。并不是说内核开发者已经分配掉的主设备号我们就不能用了,具体能不能用还得看我们的硬件平台运行过程中有没有使用这个设备号,使用“cat /proc/devices”命令即可查看当前系统中所有已经使用了的设备号。

9.1.2 动态分配设备号

静态分配设备号需要我们检查当前系统中所有被使用了的设备号,然后挑选一个没有使用的。而且静态分配设备号很容易带来冲突问题, Linux 社区推荐使用动态分配设备号,在注册字符设备之前先申请一个设备号,系统会自动给你一个没有被使用的设备号,这样就避免了冲突。卸载驱动的时候释放掉这个设备号即可,设备号的申请函数如下:

int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name)

函数 alloc_chrdev_region 用于申请设备号,此函数有 4 个参数:
dev:保存申请到的设备号。
baseminor: 次设备号起始地址, alloc_chrdev_region 可以申请一段连续的多个设备号,这些设备号的主设备号一样,但是次设备号不同,次设备号以 baseminor 为起始地址地址开始递增。一般 baseminor 为 0,也就是说次设备号从 0 开始。
count: 要申请的设备号数量。
name:设备名字。
注销字符设备之后要释放掉设备号,设备号释放函数如下:

void unregister_chrdev_region(dev_t from, unsigned count)

此函数有两个参数:
from:要释放的设备号。
count: 表示从 from 开始,要释放的设备号数量。

9.2 新的字符设备注册方法

9.2.1 cdev结构体

在 Linux 中使用 cdev 结构体表示一个字符设备, cdev 结构体在 include/linux/cdev.h 文件中,的定义如下:

struct cdev 
	struct kobject kobj;
	struct module *owner;
	const struct file_operations *ops;
	struct list_head list;
	dev_t dev;
	unsigned int count;
;

在 cdev 中有两个重要的成员变量: ops 和 dev,这两个就是字符设备文件操作函数集合file_operations 以及设备号 dev_t,其中file_operations跟dev_t我们在前面已经介绍了!

9.2.2 cdev_init函数

定义好 cdev 变量以后就要使用 cdev_init 函数对其进行初始化, cdev_init 函数原型如下:

void cdev_init(struct cdev *cdev, const struct file_operations *fops)

参数 cdev 就是要初始化的 cdev 结构体变量,参数 fops 就是字符设备文件操作函数集合。

9.2.3 cdev_add 函数

cdev_add 函数用于向 Linux 系统添加字符设备(cdev 结构体变量),首先使用 cdev_init 函数 完成对 cdev 结构体变量的初始化,然后使用 cdev_add 函数向 Linux 系统添加这个字符设备。cdev_add 函数原型如下:

int cdev_add(struct cdev *p, dev_t dev, unsigned count)

参数 p 指向要添加的字符设备(cdev 结构体变量),参数 dev 就是设备所使用的设备号,参数 count 是要添加的设备数量

9.2.4 cdev_del 函数

卸载驱动的时候一定要使用 cdev_del 函数从 Linux 内核中删除相应的字符设备, cdev_del函数原型如下:

void cdev_del(struct cdev *p)

参数 p 就是要删除的字符设备

下面我们写个代码来巩固下这个小节的内容,主要跟前面程序的差异还是hello_driver.c

#include <linux/types.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/cdev.h>


dev_t hello_devid;
struct cdev hello_cdev;
int hello_major = 0;
int hello_minor;


uint8_t kernel_buffer[1024] = 0;
static struct class *hello_class;



static int hello_world_open(struct inode * inode, struct file * file)

	printk("hello_world_open\\r\\n");
	return 0;


static int hello_world_release (struct inode * inode, struct file * file)

	printk("hello_world_release\\r\\n");
	return 0;


static ssize_t hello_world_read (struct file * file, char __user * buffer, size_t size, loff_t * ppos)

	printk("hello_world_read size:%ld\\r\\n",size);
	copy_to_user(buffer,kernel_buffer,size);
	return size;


static ssize_t hello_world_write(struct file * file, const char __user * buffer, size_t size, loff_t *ppos)

	printk("hello_world_write size:%ld\\r\\n",size);
	copy_from_user(kernel_buffer,buffer,size);
	return size;



static const struct file_operations hello_world_fops = 
	.owner		= THIS_MODULE,
	.open		= hello_world_open,
	.release = hello_world_release,
	.read		= hello_world_read,
	.write	= hello_world_write,
;


static int __init hello_driver_init(void)

	int ret;
	printk("hello_driver_init\\r\\n");

	alloc_chrdev_region(&hello_devid, 0, 1, "hello");
	hello_major = MAJOR(hello_devid);
	hello_minor = MINOR(hello_devid);
	printk("hello driver major=%d,minor=%d\\r\\n",hello_major, hello_minor);	

	hello_cdev.owner = THIS_MODULE;
	cdev_init(&hello_cdev, &hello_world_fops);
	cdev_add(&hello_cdev, hello_devid, 1);
	
	hello_class = class_create(THIS_MODULE,"hello_class");

	device_create(hello_class,NULL,hello_devid,NULL,"hello"); /* /dev/hello */

	return 0;


static void __exit hello_driver_cleanup(void)

	printk("hello_driver_cleanup\\r\\n");
	cdev_del(&hello_cdev);
	unregister_chrdev_region(hello_devid, 1);
	
	device_destroy(hello_class,hello_devid);
	class_destroy(hello_class);
	



module_init(hello_driver_init);
module_exit(hello_driver_cleanup);
MODULE_LICENSE("GPL");

三. 总结

在网上找了一个非常不错的图片,基本涵盖了很多内容,在这里贴出来:

参考内容:

1.正点原子imx6ull嵌入式Linux驱动开发指南.pdf

2.韦东山视频:01_Hello驱动(不涉及硬件操作)

 

以上是关于Linux驱动入门-最简单字符设备驱动(基于pc ubuntu)的主要内容,如果未能解决你的问题,请参考以下文章

深入理解Linux字符设备驱动

深入理解Linux字符设备驱动

android 底层开发入门

自己动手写最简单的Android驱动---LED驱动的编写

DRV_03_编写最简单的触摸屏驱动程序_基于QEMU

BLDC驱动入门最简教程