字符驱动分析

来源:互联网 发布:淘宝免费注册账号申请 编辑:程序博客网 时间:2024/06/06 17:57
1.使用字符设备驱动程序
   1) 编译/安装驱动
   2)创建设备文件
   3)访问设备
   
  1) 在linux系统中,驱动程序通常采用内核模块的程序结构进行编码。
  因此,编译/安装一个驱动程序,其实质就是编译/安装一个内核模块。
  
 驱动名 memdev.c  #include <linux/module.h>#include <linux/fs.h>#include <linux/init.h>#include <linux/cdev.h>#include <asm/uaccess.h>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 ={  .llseek = mem_llseek,  .read = mem_read,  .write = mem_write,  .open = mem_open,  .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);Makefile文件:obj-m := memdev.o  KDIR := /home/S5-driver/lesson7/TQ210/linuxall:make -C $(KDIR) M=$(PWD) modules CROSS_COMPILE=arm-linux- ARCH=armclean:rm -f *.ko *.o *.mod.o *.mod.c *.symvers *.bak *.order   insmod memdev.ko  应用程序: mem_write.c #include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int main(){int fd = 0;int src = 2013;/*打开设备文件*/fd = open("/dev/memdev0",O_RDWR);/*写入数据*/write(fd, &src, sizeof(int));/*关闭设备*/close(fd);return 0;}   arm-linux-readelf -d  mem_write.c  检查动态链接库   一般采用静态编译   arm-linux-gcc -static mem_write.c -o mem_write应用程序: mem_read.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);/*写入数据*/read(fd, &dst, sizeof(int));printf("dst is %d\n",dst);/*关闭设备*/close(fd);return 0;}





创建字符设备文件
1.  使用mknod命令  mknod  /dev/文件名   c 主设备号  次设备号
2.   使用函数在驱动程序中创建。后面会提到。
 
 2.字符设备文件
 
  应用程序{文件名}  ---> 字符设备文件  --->(主设备号) ----> 设备驱动程序
 
  通过字符设备文件,应用程序可以使用相应的字符设备驱动程序来控制字符设备。创建字符设备
    文件的方法一般有两种:
       1.使用mknod命令
        mknod  /dev/文件名   c   主设备号  次设备号
       
        cat  /proc/devices   
       
        第一列               第二列
        数字(主设备号)        设备名字
       
       
       


2.字符驱动编程模型:

字符驱动编程模型:1.设备描述结构cdev
 2.字符设备驱动模型
 3.范例驱动分析
 
1.设备描述结构cdev  
1.1   结构定义
1.2    设备号
1.3   设备操作集

1.驱动模型
在Linux系统中,设备的类型非常繁多,如:字符设备,块设备,网络接口设备,USB设备,PCI设备
   平台设备,混杂设备....,设备类型不同,也意味着其对应的驱动程序模型不同,这样就导致了我们需要去
   掌握众多的驱动程序模型。那么能不能从这些众多的驱动模型中提炼出一些具有共性的规则,则是
   我们能不能学好Linux驱动的关键。
   
驱动初始化:
2.1.1  分配设备描述结构
2.1.2  初始化设备描述结构
2.1.3  注册设备描述结构
2.1.4  硬件初始化  

   2.1.1   设备描述结构
在任何一种驱动模型中,设备都会用内核中的一种结构来描述。我们的字符设备在内核中使用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; //设备数
     
     };
     
     1.1 设备号
      查看/dev目录下 设备号
      字符设备文件   ----->>>>>       字符设备驱动
     
      主设备号:  字符设备文件与字符驱动程序如何建立起对应关系?
      主设备号。
     
      串口1
               串口驱动程序
      串口2 
     
           驱动程序什么来区分串口1和串口2:  次设备号。
           
     设备号 --- 操作
      Linux内核中使用dev_t类型来定义设备号,dev_t这种类型其实质为32位的unsigned int,
    其中高12位为设备号,低20位为次设备号。
    
    问1:如果知道主设备号,次设备号,怎么组合成dev_t类型
    dev_t  dev  = MKDEV(主设备号,次设备号)
   
    问2:如何从dev_t 中分解出主设备号?
    主设备号 = MAJOR(dev_t dev)
   
    问3: 如何从dev_t中分解出次设备号
    次设备号 = MINOR(dev_t dev)
   
   
      1.2设备号 -- 分配
      
      如何为设备分配一个主设备号?
        静态申请:开发者自己选择一个数字作为主设备号,然后通过函数register_chrdev_region
      向内核申请使用。缺点:如果申请使用的设备号已经被内核中的其他驱动使用了,则申请失败。 
     
       动态分配:使用alloc_chrdev_region由内核分配一个可用的主设备号。
            优点:因为内核知道哪些号已经被使用了,所以不会导致分配到已经被使用的号。  
     
     
     1.1设备号 -- 注销
     
      不论使用何种方法分配设备号,都应该在驱动退出时,使用unregister_chrdev_region函数释放这些设备号。
     
   应用程序
    read    
                                 如何响应?
    write      字符设备文件       ----------->      字符设备驱动    分析file_operations 定义。
   
    open    
   
   
   
   /* * NOTE: * all file operations except setlease can be called without * the big kernel lock held in all filesystems. */struct file_operations {struct module *owner;loff_t (*llseek) (struct file *, loff_t, int);重定位读写指针,响应lseek系统调用ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);从设备读取数据,响应read系统调用ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);向设备写入数据,响应write系统调用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 *);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 *);打开设备,响应open系统调用int (*flush) (struct file *, fl_owner_t id);int (*release) (struct inode *, struct file *);关闭设备,响应close系统调用int (*fsync) (struct file *, 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 **);long (*fallocate)(struct file *file, int mode, loff_t offset,  loff_t len);}; 





1.2操作函数集
struct file_operations是一个函数指针的集合,定义能在设备上进行的操作。结构上的函数指针指向
    驱动中的函数,这些函数实现一个针对设备的操作,对于不支持的操作则设置函数指针为NULL,例如:
    
    struct file_operations   dev_fops = {
    
    .llseek = NULL,
    .read  = dev_read,
    .write = dev_write,
    .ioctl = dev_ioctl,
    .open  = dev_open,
    .release = dev_release,
    };
    
    
2.1 描述结构 - 分配
cdev变量的定义可以采用静态和动态两种方法:
静态分配
struct cdev mdev;
动态分配
struct cdev *pdev = cdev_alloc();

2.2描述结构 -- 初始化
struct cdev 的初始化使用cdev_init函数来完成。

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

参数:
cdev: 待初始化的cdev结构。
fops: 设备对应的操作函数集。


2.3 描述函数结构 -- 注册


字符设备的注册使用cdev_add函数来完成。

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

参数:
p:待添加到内核的字符设备结构

dev:设备号

count: 该类设备的设备个数。

2.4 硬件初始化
根据相应硬件的芯片手册,完成初始化。





2.2  struct file
在linux系统中,每一个打开的文件,在内核中都会关联一个struct file,它由内核在打开文件时创建,在文件关闭后释放。





重要成员:
loff_t   f_pos;   文件读写指针

struct file_operations  *f_op;   该文件所对应的操作

2.3   struct inode
每一个存在文件系统里面的文件都会关联一个inode结构,该结构主要用来记录文件物理上的信息。因此,它和代表打开文件
的file结构是不同的。一个文件没有被打开时不会关联file结构,但是却会关联一个inode结构。


重要成员:
dev_t   i_rdev;  设备号

3.2 设备操作 - open
open设备方法是驱动程序用来为以后的操作完成初始化准备工作的。在大部分驱动程序中,open完成如下工作:
标明次设备号
启动设备


3.2 设备操作 - release
release 方法的作用正好与open相反。这个设备方法有时也称为close,它应该:
关闭设备。
  
  
2.2 设备操作 - read
read设备方法通常完成2件事情:
从设备中读取数据(属于硬件访问类操作)
将读取到的数据返回给应用程序。

       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);
         
2.3 设备操作 -- write
write设备方法通常完成2件事情

从应用程序提供的地址中取出数据
将数据写入设备(属于硬件访问类操作)
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);



2.5:驱动注销

当我们从内核中卸载驱动程序的时候,需要使用cdev_del函数来完成字符设备的注销。



         
       
编码思维导图:

设备驱动模型:    驱动初始化  --->   2.11 分配cdev   --->  静态分配和动态分配
    2.12 初始化cdev  ---->  cdev_init
    2.13 注销cdev   ----->  cdev_add
    2.14 硬件初始化
    
实现设备操作:
2.2.2  open
2.2.3  read ---->  copy_to_user
2.2.4  write ---->  copy_from_user
2.2.5  lseek
2.2.6  close

驱动注销:     cdev_del
unregister_chrdev_region   
       
               struct inode {/* RCU path lookup touches following: */umode_ti_mode;uid_ti_uid;gid_ti_gid;const struct inode_operations*i_op;struct super_block*i_sb;spinlock_ti_lock;/* i_blocks, i_bytes, maybe i_size */unsigned inti_flags;struct mutexi_mutex;unsigned longi_state;unsigned longdirtied_when;/* jiffies of first dirtying */struct hlist_nodei_hash;struct list_headi_wb_list;/* backing dev IO list */struct list_headi_lru;/* inode LRU list */struct list_headi_sb_list;union {struct list_headi_dentry;struct rcu_headi_rcu;};unsigned longi_ino;atomic_ti_count;unsigned inti_nlink;dev_ti_rdev;unsigned inti_blkbits;u64i_version;loff_ti_size;#ifdef __NEED_I_SIZE_ORDEREDseqcount_ti_size_seqcount;#endifstruct timespeci_atime;struct timespeci_mtime;struct timespeci_ctime;blkcnt_ti_blocks;unsigned short          i_bytes;struct rw_semaphorei_alloc_sem;const struct file_operations*i_fop;/* former ->i_op->default_file_ops */struct file_lock*i_flock;struct address_space*i_mapping;struct address_spacei_data;#ifdef CONFIG_QUOTAstruct dquot*i_dquot[MAXQUOTAS];#endifstruct list_headi_devices;union {struct pipe_inode_info*i_pipe;struct block_device*i_bdev;struct cdev             *i_cdev; };__u32i_generation;#ifdef CONFIG_FSNOTIFY__u32i_fsnotify_mask; /* all events this inode cares about */struct hlist_headi_fsnotify_marks;#endif#ifdef CONFIG_IMAatomic_ti_readcount; /* struct files open RO */#endifatomic_ti_writecount;#ifdef CONFIG_SECURITYvoid*i_security;#endif#ifdef CONFIG_FS_POSIX_ACLstruct posix_acl*i_acl;struct posix_acl*i_default_acl;#endifvoid*i_private; /* fs or device private pointer */};struct file {/* * fu_list becomes invalid after file_free is called and queued via * fu_rcuhead for RCU freeing */union {struct list_headfu_list;struct rcu_head fu_rcuhead;} f_u;struct pathf_path;#define f_dentryf_path.dentry#define f_vfsmntf_path.mntconst struct file_operations*f_op;spinlock_tf_lock;  /* f_ep_links, f_flags, no IRQ */#ifdef CONFIG_SMPintf_sb_list_cpu;#endifatomic_long_tf_count;unsigned int f_flags;fmode_tf_mode;loff_tf_pos;struct fown_structf_owner;const struct cred*f_cred;struct file_ra_statef_ra;u64f_version;#ifdef CONFIG_SECURITYvoid*f_security;#endif/* needed for tty driver, and maybe others */void*private_data;#ifdef CONFIG_EPOLL/* Used by fs/eventpoll.c to link all the hooks to this file */struct list_headf_ep_links;#endif /* #ifdef CONFIG_EPOLL */struct address_space*f_mapping;#ifdef CONFIG_DEBUG_WRITECOUNTunsigned long f_mnt_write_state;#endif};






驱动程序和应用程序的桥梁到底怎么建立的?


 例如:应用程序: mem_read.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);/*写入数据*/read(fd, &dst, sizeof(int));printf("dst is %d\n",dst);/*关闭设备*/close(fd);return 0;}     首先:我们静态编译 arm-linux-gcc  -static  -g  read_mem.c  -o  read_mem      接着反汇编:arm-linux-objdump -D -S read_mem > tmp                        read_mem:     file format elf32-littlearmDisassembly of section .note.ABI-tag:000080f4 <.note.ABI-tag>:    80f4:00000004 .word0x00000004    80f8:00000010 .word0x00000010    80fc:00000001 .word0x00000001    8100:00554e47 .word0x00554e47    8104:00000000 .word0x00000000    8108:00000002 .word0x00000002    810c:00000006 .word0x00000006    8110:0000000e .word0x0000000eDisassembly of section .init:00008228 <main>:#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int main(){    8228:e92d4800 push{fp, lr}    822c:e28db004 addfp, sp, #4; 0x4    8230:e24dd008 subsp, sp, #8; 0x8int fd = 0;    8234:e3a03000 movr3, #0; 0x0    8238:e50b3008 strr3, [fp, #-8]int dst = 0;    823c:e3a03000 movr3, #0; 0x0    8240:e50b300c strr3, [fp, #-12]/*打开设备文件*/fd = open("/dev/memdev0",O_RDWR);    8244:e59f004c ldrr0, [pc, #76]; 8298 <main+0x70>    8248:e3a01002 movr1, #2; 0x2    824c:eb0028a3 bl124e0 <__libc_open>    8250:e1a03000 movr3, r0    8254:e50b3008 strr3, [fp, #-8]/*写入数据*/read(fd, &dst, sizeof(int));    8258:e24b300c subr3, fp, #12; 0xc    825c:e51b0008 ldrr0, [fp, #-8]    8260:e1a01003 movr1, r3    8264:e3a02004 movr2, #4 ; 0x4    8268:       eb0028c0        bl      12570<libc_read>        参数个数小于4    采用通用寄存器。 r0,r1,r2,r3           00012600 <__libc_read>:   12600:e51fc028 ldrip, [pc, #-40]; 125e0 <__libc_close+0x70>   12604:e79fc00c ldrip, [pc, ip]   12608:e33c0000 teqip, #0; 0x0   1260c:1a000006 bne1262c <__libc_read+0x2c>   12610:e1a0c007 movip, r7   12614:e3a07003 movr7, #3; 0x3   12618:ef000000 svc0x00000000   1261c:e1a0700c movr7, ip         在应用程序中r7 = 3   svc是系统调用指令   ----> 用户空间进入内核空间。       1.入口: 在arch\arm\kernel\entry-common.S  中的vector_swi   2.取NO.   3.查表(依据是NO.)         ENTRY(vector_swi)subsp, sp, #S_FRAME_SIZEstmiasp, {r0 - r12}@ Calling r0 - r12 ARM(addr8, sp, #S_PC) ARM(stmdbr8, {sp, lr}^)@ Calling sp, lr THUMB(movr8, sp) THUMB(store_user_sp_lr r8, r10, S_SP)@ calling sp, lrmrsr8, spsr@ called from non-FIQ mode, so ok.strlr, [sp, #S_PC]@ Save calling PCstrr8, [sp, #S_PSR]@ Save CPSRstrr0, [sp, #S_OLD_R0]@ Save OLD_R0zero_fp/* * Get the system call number. *//* * If the swi argument is zero, this is an EABI call and we do nothing. * * If this is an old ABI call, get the syscall number into scno and * get the old ABI syscall table address. */bicsr10, r10, #0xff000000eornescno, r10, #__NR_OABI_SYSCALL_BASEldrnetbl, =sys_oabi_call_table/* * If the swi argument is zero, this is an EABI call and we do nothing. * * If this is an old ABI call, get the syscall number into scno and * get the old ABI syscall table address. */bicsr10, r10, #0xff000000eornescno, r10, #__NR_OABI_SYSCALL_BASEldrnetbl, =sys_oabi_call_tableENTRY(sys_call_table)#include "calls.S"#undef ABI#undef OBSOLETE/*============================================================================ * Special system call wrappers */@ r0 = syscall number@ r8 = syscall tablesys_syscall: *  linux/arch/arm/kernel/calls.S * *  Copyright (C) 1995-2005 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * *  This file is included thrice in entry-common.S *//* 0 */CALL(sys_restart_syscall)CALL(sys_exit)CALL(sys_fork_wrapper)CALL(sys_read)CALL(sys_write)/* 5 */CALL(sys_open)CALL(sys_close)CALL(sys_ni_syscall)/* was sys_waitpid */CALL(sys_creat)CALL(sys_link)/* 10 */CALL(sys_unlink)CALL(sys_execve_wrapper)CALL(sys_chdir)CALL(OBSOLETE(sys_time))/* used by libc4 */CALL(sys_mknod)/* 15 */CALL(sys_chmod)CALL(sys_lchown16)CALL(sys_ni_syscall)/* was sys_break */CALL(sys_ni_syscall)/* was sys_stat */CALL(sys_lseek)/* 20 */CALL(sys_getpid)CALL(sys_mount)CALL(OBSOLETE(sys_oldumount))/* used by libc4 */找到 sys_read 函数。asmlinkage long sys_read(unsigned int fd, char __user *buf, size_t count);SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count){struct file *file;ssize_t ret = -EBADF;int fput_needed;file = fget_light(fd, &fput_needed);if (file) {loff_t pos = file_pos_read(file);ret = vfs_read(file, buf, count, &pos);file_pos_write(file, pos);fput_light(file, fput_needed);}return ret;}在read_write.c中  ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos){ssize_t ret;if (!(file->f_mode & FMODE_READ))return -EBADF;if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read))return -EINVAL;if (unlikely(!access_ok(VERIFY_WRITE, buf, count)))return -EFAULT;ret = rw_verify_area(READ, file, pos, count);if (ret >= 0) {count = ret;if (file->f_op->read)ret = file->f_op->read(file, buf, count, pos);elseret = do_sync_read(file, buf, count, pos);if (ret > 0) {fsnotify_access(file);add_rchar(current, ret);}inc_syscr(current);}return ret;}




0 0