歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

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.

Copyright © Linux教程網 All Rights Reserved