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 的檔案系統
static struct file_system_type tmpfs_fs_type = {.owner= THIS_MODULE,.name= "tmpfs",.get_sb= shmem_get_sb,.kill_sb= kill_litter_super,};
在函數init_tmpfs 裡,通過 register_filesystem 吧tmpfs的註冊到檔案系統中
2. 更改file 的結構體的file_operations
在shmem_file_setup函數中,更改了 file->f_op = &shmem_file_operations; 下面來看具體的結構體
static struct file_operations shmem_file_operations = {.mmap= shmem_mmap,#ifdef CONFIG_TMPFS.llseek= generic_file_llseek,.read= shmem_file_read,.write= shmem_file_write,.fsync= simple_sync_file,.sendfile= shmem_file_sendfile,#endif};
也就是說在操作在 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.