Ram диск в линукс

Using the RAM disk block device with Linux¶

The RAM disk driver is a way to use main system memory as a block device. It is required for initrd, an initial filesystem used if you need to load modules in order to access the root filesystem (see Using the initial RAM disk (initrd) ). It can also be used for a temporary filesystem for crypto work, since the contents are erased on reboot.

The RAM disk dynamically grows as more space is required. It does this by using RAM from the buffer cache. The driver marks the buffers it is using as dirty so that the VM subsystem does not try to reclaim them later.

The RAM disk supports up to 16 RAM disks by default, and can be reconfigured to support an unlimited number of RAM disks (at your own risk). Just change the configuration symbol BLK_DEV_RAM_COUNT in the Block drivers config menu and (re)build the kernel.

To use RAM disk support with your system, run ‘./MAKEDEV ram’ from the /dev directory. RAM disks are all major number 1, and start with minor number 0 for /dev/ram0, etc. If used, modern kernels use /dev/ram0 for an initrd.

The new RAM disk also has the ability to load compressed RAM disk images, allowing one to squeeze more programs onto an average installation or rescue floppy disk.

2) Parameters¶

2a) Kernel Command Line Parameters

ramdisk_size=N

Size of the ramdisk.

This parameter tells the RAM disk driver to set up RAM disks of N k size. The default is 4096 (4 MB).

rd_nr

/dev/ramX devices created.

max_part

Maximum partition number.

rd_size

See ramdisk_size.

3) Using «rdev»¶

«rdev» is an obsolete, deprecated, antiquated utility that could be used to set the boot device in a Linux kernel image.

Instead of using rdev, just place the boot device information on the kernel command line and pass it to the kernel from the bootloader.

You can also pass arguments to the kernel by setting FDARGS in arch/x86/boot/Makefile and specify in initrd image by setting FDINITRD in arch/x86/boot/Makefile.

Some of the kernel command line boot options that may apply here are:

ramdisk_start=N ramdisk_size=M

If you make a boot disk that has LILO, then for the above, you would use:

append = "ramdisk_start=N ramdisk_size=M"

4) An Example of Creating a Compressed RAM Disk¶

To create a RAM disk image, you will need a spare block device to construct it on. This can be the RAM disk device itself, or an unused disk partition (such as an unmounted swap partition). For this example, we will use the RAM disk device, «/dev/ram0».

Note: This technique should not be done on a machine with less than 8 MB of RAM. If using a spare disk partition instead of /dev/ram0, then this restriction does not apply.

Читайте также:  Драйвера для linux fedora

    Decide on the RAM disk size that you want. Say 2 MB for this example. Create it by writing to the RAM disk device. (This step is not currently required, but may be in the future.) It is wise to zero out the area (esp. for disks) so that maximal compression is achieved for the unused blocks of the image that you are about to create:

dd if=/dev/zero of=/dev/ram0 bs=1k count=2048
dd if=/dev/ram0 bs=1k count=2048 | gzip -v9 > /tmp/ram_image.gz
dd if=zImage of=/dev/fd0 bs=1k
dd if=/tmp/ram_image.gz of=/dev/fd0 bs=1k seek=400

That is it. You now have your boot/root compressed RAM disk floppy. Some users may wish to combine steps (d) and (f) by using a pipe.

Changelog:¶

Updated to reflect changes in command line options, remove obsolete references, general cleanup. James Nelson (james4765 @ gmail . com)

Источник

How to Easily Create RAM Disk on Debian, Ubuntu, Linux Mint, CentOS

This tutorial will show you how to quickly create a RAM disk in any Linux distro (Debian, Ubuntu, Linux, Fedora, Arch Linux, CentOS, etc). Compared to commercial Windows RAM disk software that costs money, Linux can utilize this cool feature 100% free of charge.

What is RAM Disk?

RAM disk is also known as RAM drive. It’s a portion of your RAM that are formated with a file system. You can mount it to a directory on your Linux system and use it as a disk partition.

Why use RAM disk?

RAM is ultra-fast compared to even the fastest solid state drive (SSD). As you may know, the main performance bottleneck in today’s computer is the speed of hard drive, so moving programs and files to the RAM disk yields super fast computing experience.

  • RAM is volatile which means all data in RAM disk will be lost when the computer shutdowns or reboots. However, this can be a pro in some situations, if you use it wisely.
  • RAM is expensive so it has limited capacity. You need to make sure not allocate too much space for RAM disk, or the operating system would run out of RAM.

You can do a lot of interesting things with RAM disk.

  • RAM disk is best suited for temporary data or caching directories, such as Nginx FastCGI cache, and Debian package downloads ( /var/cache/apt/archive/ ). If you use a SSD and there will be a lot of writes to a particular directory, you can mount that directory as a RAM disk to reduce wear out of SSD.
  • I also use RAM disk to temporarily store screenshots when writing articles on this blog, so when my computer shut down, those screenshots will automatically be deleted on my computer.
  • You might not believe it, but I use RAM disk to run virtual machines inside VirtualBox. My SSD is about 250G. I can’t run many VMs directly on the SSD and I’m not happy about the speed of my 2TB mechanical hard drive (HDD). I can move the VM from HDD to RAM disk before starting the VM, so the VM can run much faster. After shutting down the VM, I move the VM files back to HDD, which takes less than 1 minute. This of course requires your computer to have a large capacity RAM.
Читайте также:  Linux check virtualization support

How to Create a RAM Disk in Any Linux Distro

First make a directory which can be anywhere in the file system such as

If you want to let every user on your Linux system use the RAM disk, then change its permission to 777.

sudo chmod 777 /tmp/ramdisk

Next, check how much free RAM are left on your system with htop command line utility because we don’t want to use too much RAM.

easily create ram disk linux

Then all left to do is to specify the file system type, RAM disk size, device name and mount it to the above directory. You can see from the screenshot above that I have plenty of free RAM, so I can easily allocate 1GB for my RAM disk. This can be done with the following one-liner. It will be using tmpfs file system and its size is set to 1024MB. myramdisk is the device name I gave to it.

sudo mount -t tmpfs -o size=1024m myramdisk /tmp/ramdisk

To allocate 10G for the RAM disk, run this instead.

sudo mount -t tmpfs -o size=10G myramdisk /tmp/ramdisk

If we issue the following command

We can see it’s successfully mounted.

create linux ramdisk

Now if I copy my VirtualBox machines file (5.8G) into the RAM disk, my RAM usage suddenly goes up to 9.22G.

linux automount ramdisk

Everything in that directory will be lost and RAM usage goes down to original.

linux ramdisk file system

This is how you can test if your RAM disk is working.

Test RAM Disk Speed

To test write speed of RAM disk, you can use dd utility.

sudo dd if=/dev/zero of=/tmp/ramdisk/zero bs=4k count=100000

Which gave me 2.8GB/s write speed.

linux ramdisk speed test

sudo dd if=/tmp/ramdisk/zero of=/dev/null bs=4k count=100000

Which gave me 3.1 GB/s read speed.

I also did a speed test on my SSD. The write speed is 534MB/s and read speed 1.6GB/s.

Auto-mount on System Boot

myramdisk /tmp/ramdisk tmpfs defaults,size=1G,x-gvfs-show 0 0

x-gvfs-show will let you see your RAM disk in file manager. Save and close the file. Your Linux system will automatically mount the RAM disk when your computer boots up.

To mount it immediately without reboot, run the following command.

Using RAM Disk to Reduce SSD Wear Out

To increase the lifespan of your SSD, you should avoid write and delete operations on the SSD as much as possible. The Linux operating system has two activities that make up the most write and delete operations.

If you use a Debian-based Linux distribution, the temporary download directory for software packages is /var/cache/apt/archives/ . Once the package is installed, APT package manager automatically deletes the .deb files in this directory. You can add the following line in /etc/fstab file to mount this directory in RAM.

package_archive /var/cache/apt/archives tmpfs defaults,size=6G 0 0

Fedora stores temporary package downloads under /var/cache/dnf/ directory, so you can add the following line in /etc/fstab file to mount this directory in RAM.

package_archive /var/cache/dnf tmpfs defaults,size=6G 0 0

Some folks might wonder if mounting this directory will prevent Fedora from upgrading to a new release, because Fedora requires reboot to install system upgrade packages. The answer is No. It won’t prevent system upgrades, as Fedora stores system upgrade pacakges under a different directory /var/lib/dnf/system-upgrade/ .

The logging directory on Linux is usually /var/log/ . It’s not safe to mount the entire /var/log/ directory in RAM. Change to this directory.

Читайте также:  Сочетание клавиш открыть терминал линукс

You will find that the /var/log/journal/ sub-directory uses the most disk space. It’s used for logging systemd services and safe to mount in RAM, so you can add the following in in the /etc/fstab file.

systemd_journal /var/log/journal tmpfs defaults,size=6G 0 0

If you run Nginx web server, you might want to mount the /var/log/nginx/ directory into RAM. On one of my servers, this directory is 2.2G in size.

nginx_logs /var/log/nginx/ tmpfs defaults,size=6G 0 0

After saving the /etc/fstab file, run the following command to mount all file systems.

How to Run VirtualBox VM on RAM Disk

Note that this requires a large-capacity RAM.

When you create a brand new virtual machine, you should set the machine folder to the RAM disk directory ( /tmp/ramdisk/ ). If you can’t find the Machine folder option, then you need to install the latest version of Virtualbox on your system.

Run VirtualBox VM on RAM Disk

If you have an existing VM, then select the VM in the main VirtualBox Manager window and go to the menu bar and select Machine -> Move, or right-click the VM and select Move from the context menu. You will be prompted to choose a new folder for the virtual machine. Select /tmp/ramdisk/ as the new folder.

Virtualbox move virtual machine folder

Remember to move your VM back to the original folder before shutting down your computer, or your VM will be deleted.

Wrapping Up

And that’s the basics of creating RAM disk in Linux. If you found this post useful, then subscribe to our free newsletter or follow us Twitter or like our Facebook page. Thanks for visiting!

Источник

Как создать ramdisk в Linux или виртуальный диск в RAM

Иногда попадаются задачи, когда нужно работать с большим количеством мелких файлов или некоторое небольшое время хранить объемные данные и делать это по возможности быстро, без завязок на медленную файловую подсистему и/или диски. Многие вспомнят, что есть такой виртуальный диск, он же – RAM-дисках (ramdisk), а сделать ramdisk в *nix системах можно очень быстро и просто.

Изначально, в ядре должна быть поддержка tmpfs.

Как создать диск:
В первую очередь создаем новую точку монтирования:

mkdir /cache chmod 777 /cache

и даём все права на использование.

После этого даём команду на монтирование, для примера, я создам диск на 1 Gb

# mount -t tmpfs -o size=1024M tmpfs /cache или $ sudo mount -t tmpfs -o size=1024M tmpfs /cache

где 1024M – это и есть размер RAMdisk в Мегабайтах.

Аккуратнее с размером и не размахивайтесь слишком широко: если вы попросите создать ramdisk больше, чем имеете оперативной памяти, система начнёт сгружать всё в swap-файл и дела пойдут очень медленно и грустно. Кстати, если ОЗУ в системе достаточно, swap можно и вовсе отключить, см. Как отключить SWAP

Если же вы хотите изменить размер ramdisk – это просто:

# mount -o remount -o size=2048M /cache или $ sudo mount -o remount -o size=2048M /cache

При этом содержимое RAM-диска не пропадёт, но и его размер тут же увеличится (при уменьшении также ничего не пропадёт, если только данных не больше, чем диск).

ВАЖНО.
RAM-диск это хранение в OЗУ, и это значит, что всё его содержимое после отключения питания машины будет безвозвратно потеряно. По возможности используйте резервное питание, что бы успеть сохранить важные данные.

Источник

Оцените статью
Adblock
detector