Tmpfs

From Segfault
Jump to: navigation, search

FreeBSD

On FreeBSD there are at least two ways to create a RAM disk.

mdconfig

With mdconfig:

$ mdconfig -a -t malloc -s 3072m
md1
$ newfs -U /dev/md1
$ mount -t ufs /dev/md1 /mnt

$ df -h /mnt
Filesystem    Size    Used   Avail Capacity  Mounted on
/dev/md1      2.9G    8.0k    2.7G     0%    /mnt

Tear down with:

umount /mnt
mdconfig -d -u /dev/md1

mdmfs

mdmfs saves a few steps:

$ mdmfs -M -s 3072m md /mnt
$ df -h /mnt
Filesystem    Size    Used   Avail Capacity  Mounted on
/dev/md1      2.9G    8.0k    2.7G     0%    /mnt

Tear down with:

umount /mnt
mdconfig -d -u md1

Linux

In Linux there are different volatile storage backends:

  • tmpfs[1] - uses internal caches, will swap if necessary
  • ramfs[2] - uses internal caches, won't swap but return ENOSPC[3]
  • ramdisk[4] - presents blockdevice, where a regular filesystem can be created on.

tmpfs

mkdir -p /mnt/tmpfs
mount -t tmpfs -o size=1G tmpfs /mnt/tmpfs

ramfs

mkdir -p /mnt/ramfs
mount -t ramfs -o size=1G ramfs /mnt/ramfs

While both filesystems are now mounted, ramfs would only show up in df(1) when queried directly:

$ df -h /mnt/tmpfs /mnt/ramfs
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           2.0G     0  2.0G   0% /mnt/tmpfs
ramfs              0     0     0    - /mnt/ramfs

ramdisk

Initialize /dev/ramN:

$ modprobe brd rd_size=$((1 * 1024 * 1024))                   # 1 GB
$ blockdev --getsize64 /dev/ram0 | awk '{print $1/1024/1024}'
1024

Now we can use it like a real block device:

mkfs.ext4 -m 0 /dev/ram0
mount -t ext4 /dev/ram0 /mnt/ramdisk

This is how it should look like now:

$ df -h /mnt/ramdisk
Filesystem      Size  Used Avail Use% Mounted on
/dev/ram0       976M  1.3M  975M   1% /mnt/ramdisk

MacOS

Apparently, there is no tmpfs like filesystem for MacOS X. The best bet is to put tmp in a RAM disk. However, the comment to this gist describes exactly what's wrong with this approach:

 > tmpfs is swap-backed. Memory pressure on the system will result in the contents of
 > tmpfs getting pushed out to your on-disk swap partition. By way of contrast, 
 > what you've done above is to create a locked-in-memory ramdisk, which will not 
 > get swapped out, making that chunk of memory unavailable until the ramdisk is discarded.
        -- behanna on https://gist.github.com/koshigoe/822455

In short:

$ hdid -nomount ram://$(expr 128 \* 1024 \* 1024 / 512)          # 128 MB RAM
/dev/disk3

$ newfs_hfs /dev/disk3
Initialized /dev/rdisk3 as a 128 MB HFS Plus volume

As root:

mv /private/tmp/private/tmp.old && mkdir -m1777 /private/tmp
mount -t hfs /dev/disk3 /private/tmp

Note: if we want to replace /tmp, we should execute the earlier commands as root too!

To unmount:

umount /private/tmp
hdiutil detach /dev/disk3

Links

References