驱动原理(应用程序访问驱动程序)

以read为例:

  read是一个系统调用,系统调用之前在应用程序当中(或者叫用户空间当中),read的实现代码在内核中,read是如何找到内核的实现代码呢?

/*********************************************
*filename:read_mem.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 >dump

  找到主函数:vim dump -> /main

  

  找到libc_read函数

     

  关注两行代码:

  mov r7,#3

  svc 0x00000000

  read的系统调用在应用程序当中主要做了两项工作,3传给了r7,然后使用svc指令。

  svc系统调用指令,系统会从用户空间进入到内核空间,而且入口是固定的,3就是代表read要实现的代码,根据3查表,查出3代表的函数,然后调用这个函数。

  打开entry_common.S;找到其中的ENTRY(vector_swi)

    在这个函数中得到调用标号

    根据标号找到一个调用表

    然后找到进入表

    打开calls.S文件,会得到一张系统调用列表(部分图示)

  3代表的就是read;

  分析sys_read,原函数在read_write.c文件中(/linux/kernel code/linux-2.6.39/fs)

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;
}

  函数fd进去后,利用fd找到文件所对应的struct file,利用struct file调用vfs_read();

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);
        else
            ret = do_sync_read(file, buf, count, pos);
        if (ret > 0) {
            fsnotify_access(file);
            add_rchar(current, ret);
        }
        inc_syscr(current);
    }

    return ret;
}

 

posted @ 2019-04-18 14:10  dongry  阅读(1531)  评论(0编辑  收藏  举报