3

I've been shortly using the following on Linux Debian Jessie to create a "RAM disk":

mount -o size=1G -t tmpfs none /mnt/tmpfs

But I was told it doesn't reserve memory, which I didn't know.

I would like a solution, which does reserve memory.

2 Answers2

1

In fact it does not reserve any memory. That behaviour was present when using ramdisks initiated at boot time, but it was removed a long time ago.

Currently, only the kernel and its modules can allocate a specific RAM region, or reserve an actual RAM area. Other methods will allocate memory which can be swapped to disk.

My previous answer suggested allocating a file over a tmpfs mount point, which was then mounted as a loopback device. While it works at pre-allocating memory for the purpose of a "ramdisk", its content will be swapped, and the solution will not work if there is any swap enabled.

Btw, this works at allocating memory because tmpfs only allocates memory as it is required to store the files it contains, which happens when the disk file is created.

----------------- Non working solution ------------------------------

One thing you could do is to create a loopback file with the desired size inside the tmpfs.

It would be something like this:

mount -o size=1G -t tmpfs none /mnt/tmpfs
dd if=/dev/zero of=/mnt/tmpfs/disk
losetup /dev/loop0 /mnt/tmpfs/disk
mkfs.ext2 /dev/loop0
mount /dev/loop0 /mnt/static_ramdisk
OluaJho
  • 174
  • use ramfs in place of tmpfs, or use brd. https://unix.stackexchange.com/questions/66329/creating-a-ram-disk-on-linux/470720#470720 https://unix.stackexchange.com/questions/433712/how-do-you-create-block-ram-disks-on-demand – sourcejedi Sep 28 '18 at 00:32
1

Add it to your /etc/fstab:

none    /mnt/tmpfs  tmpfs   defaults,size=1g,mode=1777  0 0

You may also need to rebuild your initramfs, e.g.:

sudo update-initramfs -u -k $(uname -r)

or, to rebuild the initramfs for all kernels:

sudo update-initramfs -u -k all

BTW, tmpfs doesn't reserve any memory - a tmpfs filesystem only uses as much memory as required by the files it contains (and any file/directory overhead).

cas
  • 78,579
  • why do you need to update initramfs? – mikeserv Oct 27 '15 at 00:20
  • so that the tmpfs is mounted and available very early in the boot process. if that's not required then there's no need to update the initramfs just for that - but apart from taking a little time, there's no harm in doing it. it will get done next time the kernel is updated or something else triggers an update-initramfs – cas Oct 27 '15 at 00:22
  • how can it be mounted any sooner than /? – mikeserv Oct 27 '15 at 00:23
  • 3
    Note, that there is no need for update-initramfs, consider removing it from your answer for future readers. – Vlastimil Burián Sep 27 '18 at 22:56