Linux Tmpfs 源码分析


Tmpfs是linux 系统中基于内存/交换分区作的文件系统,与ramdisk不同的是,ramdisk是作为块设备,基于ext的文件系统,所以不可绕过的是page cache的内存复制,具体可以参考前面写的关于ramdisk, 对tmpfs来说就是直接操作内存做为文件系统的,而不是基于块设备的。

如何绕过page cache,实际上很简单,只要直接在setup文件系统的时候,设置自己的file的const struct file_operations,让我们来看tmpfs是如何实现的。

在linux 2.6.18中tmpfs的源码主要在 shmem.c文件中

1.定义tmpfs 的文件系统

  1. static struct file_system_type tmpfs_fs_type = {  
  2.     .owner      = THIS_MODULE,  
  3.     .name       = "tmpfs",  
  4.     .get_sb     = shmem_get_sb,  
  5.     .kill_sb    = kill_litter_super,  
  6. };  

在函数init_tmpfs 里,通过 register_filesystem 吧tmpfs的注册到文件系统中

2. 更改file 的结构体的file_operations

在shmem_file_setup函数中,更改了 file->f_op = &shmem_file_operations; 下面来看具体的结构体

  1. static struct file_operations shmem_file_operations = {  
  2.     .mmap       = shmem_mmap,  
  3. #ifdef CONFIG_TMPFS   
  4.     .llseek     = generic_file_llseek,  
  5.     .read       = shmem_file_read,  
  6.     .write      = shmem_file_write,  
  7.     .fsync      = simple_sync_file,  
  8.     .sendfile   = shmem_file_sendfile,  
  9. #endif   
  10. };  

也就是说在操作在 tmpfs 文件时候,并没有使用常用的ext文件系统中的函数do_sync_read (read_write.c),而是调用了tmpfs 自己封装的函数shmem_file_read,当然在shmem_file_read 并没有对page cache进行操作,虽然里面还是使用了page cache中maping,file, inode等结构体和算法。

 3. 函数shmem_file_read主要是调用do_shmem_file_read函数,在do_shmem_file_read函数中核心是shmem_getpage,通过索引和inode快速找到page.

相关内容