ILD

ramfs & tmpfs
作者:Yuan Jianpeng 邮箱:yuanjianpeng1@gmail.com
发布时间:2026-2-6 站点:Inside Linux Development

挂载一个ramfs:

# mount -t ramfs none /mnt/ramfs


挂载一个tmpfs

# mount -t tmpfs none tmpfs


这两者似乎没有区别,debian有一篇文档将ramfs讲的很清晰。

https://wiki.debian.org/ramfs


ramfs是一个非常简单的文件系统,它将linux的disk cacheing机制(page cache和dentry cache)导出为一个动态可调整大小的ram-based filesystem。


通常Linux将文件缓存到内存,文件的pages从文件的backing store(通常是一个block deivce)读取,并且被标记为clean,意味着可回收。


ramfs没有backing store,ramfs的文件一样的分配dentries and page cache,但是由于没有地方可以写入,所以不会标记为clean,因此VM不会收回这些内存。


实现ramfs所需要的代码是非常小的,因为所有的工作,已经由linux caching infrastructure实现了。

因此ramfs没有menuconfig选项来打开,它默认是打开的:

fs/Makefile可以证明:

obj-y                           += ramfs/


老的ram disk,它从内存模拟一个block device,然后挂载一个真实的文件系统。这种做法相比ramfs效率太低了。而且会浪费内存。


tmpfs是ramfs的一个衍生物,添加size limits等特性,而且允许data保存到swap space。


tmpfs有menuconfig,见fs/Kconfig

config TMPFS

        bool "Tmpfs virtual memory file system support (former shm fs)"

        depends on SHMEM

        select MEMFD_CREATE

        help

          Tmpfs is a file system which keeps all files in virtual memory.


看内核代码,tmpfs实现在:mm/shmem.c,并且调用了ramfs的接口:

static struct file_system_type shmem_fs_type = {

        .name           = "tmpfs",

        .init_fs_context = ramfs_init_fs_context,

        .parameters     = ramfs_fs_parameters,

        .kill_sb        = ramfs_kill_sb,

        .fs_flags       = FS_USERNS_MOUNT,

};


ramfs的源码有意思的注释:

fs/ramfs/file-mmu.c


/*

 * NOTE! This filesystem is probably most useful

 * not as a real filesystem, but as an example of

 * how virtual filesystems can be written.

 *

 * It doesn't get much simpler than this. Consider

 * that this file implements the full semantics of

 * a POSIX-compliant read-write filesystem.

 *

 * Note in particular how the filesystem does not

 * need to implement any data structures of its own

 * to keep track of the virtual data: using the VFS

 * caches is sufficient.

 */


Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.