tmpfs in Linux

tmpfs

1.0 tmpfs

tmpfs is a filesystem that resides in the main memory of a Linux system. In the case of disk files, a file is first fetched into the kernel pagecache and the delivered to the requesting process. The fetch part is not there in the case of tmpfs as the files are created and updated directly in kernel caches. The downside is that the files are lost when the system is shutdown. But that's OK if the files are temporary and are not required once the concerned software is not running. The advantage is that, if the software is heavily using those temporary files, it will run a lot faster if those files are a part of a tmpfs filesystem.

2.0 tmpfs size

At the start, a tmpfs filesystem occupies zero bytes. As files grow in it, the size of the tmpfs increases. There is a size attribute for any tmpfs filesystem, the maximum size to which it can grow in physical memory. If it grows beyond that, it is swapped to the swap partition on disk. If that happens, the advantage of using a tmpfs filesystem is lost. So, a tmpfs filesystem should be used only when there is adequate amount of RAM in the system. You can specify the size of a tmpfs filesystem. However, if you don't specify, a default size equal to half of the size of physical RAM is used.

3.0 Creating a tmpfs filesystem

First, we need a directory where the tmpfs would be mounted. Let's say it is /var/mycache,

$ sudo mkdir /var/mycache

We can create the tmpfs by simply mounting it using the mount command. We assume that the login id of the user is alice and user id and group id for alice, both, have a value of 1000. Also, we go with the default size of tmpfs, which is half the size of the physical RAM.

$ sudo mount -t tmpfs -o rw,nosuid,nodev,noexec,mode=0755,uid=1000,gid=1000 tmpfs /var/mycache $ # Checking whether it has been mounted $ mount ... tmpfs on /var/mycache type tmpfs (rw,nosuid,nodev,noexec,relatime,mode=755,uid=1000,gid=1000) $ df Filesystem 1K-blocks Used Available Use% Mounted on ... tmpfs 1982720 0 1982720 0% /var/mycache $ ls -ls /var total 44 ... 0 drwxr-xr-x 2 alice alice 40 May 20 16:55 mycache ...

4.0 Mounting tmpfs at the boot time

Ultimately, we want the tmpfs to be mounted at /var/mycache automatically at the boot time. For that we need to add the following line in the /etc/fstab file.

tmpfs /var/mycache tmpfs rw,nosuid,nodev,noexec,mode=0755,uid=1000,gid=1000 0 0

Software: