做块设备驱动就不得不和文件系统打交道,这里就整理下有关文件系统读写的流程和代码。
先简单的介绍下vfs,就是虚拟文件系统,虚拟文件系统屏蔽了底层的各种文件系统的差异性,让上层应用程序可以忽略底层用的是哪种文件系统。
首先是系统读调用:
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;
}
struct file 和struct file_struct结构体可以看下
http://blog.csdn.net/yuzhihui_no1/article/details/51272563 。大概的说下:struct files_struct 是表示一个进程的所有打开的文件列表结构体;而struct filet则是某个文件的某个状态下的结构体,一个文件可以被打开多次,也就是说可以有多个状态,多个struct file结构体;
struct file *fget_light(unsigned int fd, int *fput_needed)
{
struct file *file;
//进程文件表
struct files_struct *files = current->files;
*fput_needed = 0;
if (atomic_read(&files->count) == 1) {//如果只有一个人用files结构体,就不需要加锁了
file = fcheck_files(files, fd);//通过fd来获取进程文件表中
if (file && (file->f_mode & FMODE_PATH))
file = NULL;
} else {
rcu_read_lock();//加rcu锁
file = fcheck_files(files, fd);
if (file) {
if (!(file->f_mode & FMODE_PATH) &&
atomic_long_inc_not_zero(&file->f_count))
*fput_needed = 1;
else