Linux字符设备简单示例

1. Linux字符设备是一种按字节来访问的设备,字符驱动则负责驱动字符设备,这样的驱动通常实现open、close、read和write系统调用。例如:串口、Led、按键等。

 

2. 通过字符设备文件(/dev/xxx),应用程序可以使用相应的字符设备驱动来控制字符设备

3. 创建字符设备文件的方法一般有两种

(1)使用命令mknod : mknod /dev/文件名  c 主设备号 次设备号 (查看主设备号:cat /proc/devices)

(2)使用函数创建:mknod()

int mknod(const char *pathname, mode_t mode, dev_t dev);

 

4. 文件系统与字符设备驱动程序之间的关系

(1)在Linux系统中,每一个打开的文件,在内核中都会关联一个struct file结构,它是由内核在打开文件时创建,在文件关闭后释放。

  struct file结构中的重要成员

  * struct file_operations* f_op;  //文件操作函数集

  * loff_t   f_pos;         //文件读写指针

(2)每一个存在于文件系统中的文件都会关联一个inode结构,该结构主要用来记录文件物理上的信息。因此,它和代表打开文件的file结构是不同的,一个文件没有被打开时不会关联file结构,但是会关联一个inode结构(存于磁盘,操作文件时在内存中建立相应的映射结构)

注:inode用于存储文件的元信息(除了文件名的所有信息),中文译名索引节点

(3)从上图可知,系统实质上是把字符设备的注册表看成了文件。其中chrdevs[]在内核的定义如下

static struct char_device_struct {
    struct char_device_struct *next;
    unsigned int major;
    unsigned int baseminor;
    int minorct;
    char name[64];
    struct cdev *cdev;        /* will die */
} *chrdevs[CHRDEV_MAJOR_HASH_SIZE];

 

5. 在任何一种驱动模型中,设备都会用内核中的一种结构来描述。字符设备在内核中使用struct cdev来描述

struct cdev {
    struct kobject kobj;
    struct module *owner;
    const struct file_operations *ops;  //设备操作函数集
    struct list_head list;
    dev_t dev;                //设备号
    unsigned int count;           //设备数
};

 

6. Linux内核中使用dev_t类型来定义设备号,dev_t其实质为32位unsigned int类型,其中高12位为主设备号,低20位为次设备号。

(1)MKDEV(主设备号,次设备号)

(2)MAJOR(dev_t dev)

(3)MINOR(dev_t dev)

注:字符设备文件与字符设备驱动是通过主设备号建立对应关系;驱动程序用次设备号来区分同类型的设备

 

7. 设备号的申请与注销

(1)静态申请:开发者自己选择一个数字作为主设备号,通过函数 register_chardev_region 向内核申请

(2)动态分配:使用 alloc_chrdev_region 由内核分配一个可用的主设备号(推荐使用)

(3)不论使用何种方法分配设备号,都应该在驱动退出时,使用 unregister_chrdev_region 函数释放这些设备

 

8. 操作函数集:struct file_operations是一个函数指针的集合,定义能在设备上进行的操作。

 

9. 字符设备描述结构的分配、注册与注销

(1)cdev变量的定义可以采用静态和动态两种方法

  * 静态分配:struct cdev mdev;

  * 动态分配:struct cdev* pdev = cdev_alloc();(可以通过命令:cat /proc/devices查看主设备号)

(2)cdev变量的初始化使用cdev_init()函数来完成

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

  cdev: 待初始化的cdev结构

  fops: 设备对应的操作函数集

(3)字符设备的注册使用cdev_add()函数来完成

(4)字符设备的注销使用cdev_del()函数来完成

 

10. 设计Linux字符设备驱动程序的主要工作:

(1)根据外部设备的特点,实现file_operations结构所需要的函数

(2)调用函数cdev_alloc()函数向系统动态申请一个cdev结构实例

(3)调用函数cdev_init()初始化cdev实例,并建立cdev实例与file_operations实例之间的连接

(4)调用函数alloc_chrdev_region()向系统申请一个设备号

(5)调用函数cdev_add()向系统添加一个设备

(6)调用函数cdev_del()从系统删除一个cdev结构实例

注:如果把驱动程序制作成一个内核模块,上述的第(2)、(3)、(4)、(5)步应在模块的初始化函数中实现,而第(6)步应在模块的卸载函数中实现

 

11. 设备操作:struct file_operations

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 (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
    ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
    int (*readdir) (struct file *, void *, filldir_t);
    unsigned int (*poll) (struct file *, struct poll_table_struct *);
    int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);
    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 (*open) (struct inode *, struct file *);
    int (*flush) (struct file *, fl_owner_t id);
    int (*release) (struct inode *, struct file *);
    int (*fsync) (struct file *, struct dentry *, 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 **);
};

(1)open: int (*open) (struct inode *, struct file *);(打开设备,响应open系统调用)
   open方法是驱动程序用来为以后的操作完成初始化准备工作的。在大部分驱动程序红,open主要完成以下工作:

  * 标明次设备号

  * 启动设备

(2)release: int (*release) (struct inode *, struct file *);(关闭设备,响应close系统调用)

(3)llseek: loff_t (*llseek) (struct file *, loff_t, int);(重定位读写指针,响应lseek系统调用)

(4)read:ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);(从设备读取数据,响应read系统调用)

  ① read设备方法通常完成两件事情

  * 从设备中读取数据(属于硬件访问类操作)

  * 将读取到的数据返回给应用程序

  ② ssize_t (*read) (struct file *filp, char __user *buff, size_t count, loff_t *offp)

  filp:与字符设备文件关联的file结构,由内核创建

  buff:从设备文件读取到的数据,需要保存到的位置。由read系统调用提供该参数

  count:请求传输的数据量,由read系统调用提供该参数

  offp:文件的读写位置,由内核从file结构中取出后,传递进来

  ③ buff参数是来源于用户空间的指针,这类指针都不能被内核代码直接引用,必须使用专门的函数

  

int copy_from_user(void *to, const void __user *from, int n)
int copy_to_user(void __user *to, const void *from, int n)


 

(5)write:ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);(向设备写入数据,响应write系统调用)
  ① write设备方法通常完成2件事情

  * 从应用程序提供的地址中取出数据

  * 将数据写入设备(属于硬件访问类操作)

  ② 其参数类似于read

 

12. 字符设备简单示例

① 驱动程序 MemDev.c

#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
#include <linux/slab.h>

/* We suppose this is the two device's registers */
int dev1_registers[5];
int dev2_registers[5];

struct cdev cdev; 
dev_t devno;

/*文件打开函数*/
int mem_open(struct inode *inode, struct file *filp)
{
    /*获取次设备号*/
    int num = MINOR(inode->i_rdev);
    
    if (num == 0)
        filp->private_data = dev1_registers;
    else if(num == 1)
        filp->private_data = dev2_registers;
    else
        return -ENODEV;  //无效的次设备号
    
    return 0; 
}

/*文件释放函数*/
int mem_release(struct inode *inode, struct file *filp)
{
    return 0;
}

/*读函数*/
static ssize_t mem_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
    unsigned long p = *ppos;
    unsigned int count = size;
    int ret = 0;
    int *register_addr = filp->private_data; /*获取设备的寄存器基地址*/

    /*判断读位置是否有效*/
    if (p >= 5 * sizeof(int))
        return 0;
    if (count > 5 * sizeof(int) - p)
        count = 5 * sizeof(int) - p;

  /*读数据到用户空间*/
    if (copy_to_user(buf, register_addr + p, count))
    {
        ret = -EFAULT;
    }
    else
    {
        *ppos += count;
        ret = count;
    }
    
    return ret;
}

/*写函数*/
static ssize_t mem_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
{
    unsigned long p =  *ppos;
    unsigned int count = size;
    int ret = 0;
    int *register_addr = filp->private_data; /*获取设备的寄存器地址*/
  
    /*分析和获取有效的写长度*/
    if (p >= 5*sizeof(int))
        return 0;
    
    if (count > 5 * sizeof(int) - p)
        count = 5 * sizeof(int) - p;
    
    /*从用户空间写入数据*/
    if (copy_from_user(register_addr + p, buf, count))
        ret = -EFAULT;
    else
    {
        *ppos += count;
        ret = count;
    }
    
    return ret;
}

/* seek文件定位函数 */
static loff_t mem_llseek(struct file *filp, loff_t offset, int whence)
{ 
    loff_t newpos;

    switch(whence) {
        case SEEK_SET: 
            newpos = offset;
            break;

        case SEEK_CUR: 
            newpos = filp->f_pos + offset;
            break;

        case SEEK_END: 
            newpos = 5 * sizeof(int) - 1 + offset;
            break;
        
        default: 
            return -EINVAL;
    }
    
    if ((newpos < 0) || (newpos > 5 * sizeof(int)))
        return -EINVAL;
        
    filp->f_pos = newpos;
    
    return newpos;
}

/*文件操作结构体*/
static const struct file_operations mem_fops =
{
    .open = mem_open,    
    .read = mem_read,
    .write = mem_write,
    .llseek = mem_llseek,
    .release = mem_release,
};

/*设备驱动模块加载函数*/
static int memdev_init(void)
{
    /*初始化cdev结构*/
    cdev_init(&cdev, &mem_fops);
  
    /* 注册字符设备 */
    alloc_chrdev_region(&devno, 0, 2, "memdev");
    
    cdev_add(&cdev, devno, 2);
}

/*模块卸载函数*/
static void memdev_exit(void)
{
    cdev_del(&cdev);   /*注销设备*/
    unregister_chrdev_region(devno, 2); /*释放设备号*/
}

MODULE_LICENSE("GPL");

module_init(memdev_init);
module_exit(memdev_exit);

② 测试代码MemWrite.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd = 0;
    int src0[] = {0, 1, 2, 3, 4};
    int src1[] = {10, 11, 12, 13, 14};
    
    /*打开设备文件*/
    fd = open("/dev/memdev0", O_RDWR);
    
    /*写入数据*/
    write(fd, src0, sizeof(src0));
    
    /*关闭设备*/
    close(fd);
    
    fd = open("/dev/memdev1", O_RDWR);
    
    /*写入数据*/
    write(fd, src1, sizeof(src1));
    
    /*关闭设备*/
    close(fd);
    
    return 0;    
}

③测试代码MemRead.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd = 0;
    int dst = 0;
    
    /*打开设备文件*/
    fd = open("/dev/memdev0", O_RDWR);
    
    lseek(fd, 2, SEEK_SET);
    
    /*写入数据*/
    read(fd, &dst, sizeof(int));
    
    printf("dst0 is %d\n", dst);
    
    /*关闭设备*/
    close(fd);
    
    /*打开设备文件*/
    fd = open("/dev/memdev1", O_RDWR);
    
    lseek(fd, 3, SEEK_SET);
    /*写入数据*/
    read(fd, &dst, sizeof(int));
    
    printf("dst1 is %d\n", dst);
    
    /*关闭设备*/
    close(fd);
    
    return 0;    
}

④ 测试步骤

(1)安装驱动模块:insmod MemDev.ko

(2)查看主设备号:cat /proc/devices(查找memdev对应的主设备号)

(3)创建设备文件:mknod /dev/memdev0 c 主设备号 0

(4)运行测试代码进行测试

 

posted @ 2018-08-18 18:33  99度的水  阅读(17570)  评论(0编辑  收藏  举报