- Using the RAM disk block device with Linux¶
- 1) Overview¶
- 2) Parameters¶
- 3) Using “rdev”¶
- 4) An Example of Creating a Compressed RAM Disk¶
- Как создать ramdisk в Linux или виртуальный диск в RAM
- Создаём RAMdisk на Ubuntu 18.04
- Подключение RAM-диска на UBUNTU 18.04 автоматически, при загрузке системы
- Сохранение данных RAM-диска:
- How to Easily Create RAM Disk on Debian, Ubuntu, Linux Mint, CentOS
- What is RAM Disk?
- Why use RAM disk?
- How to Create a RAM Disk in Any Linux Distro
- Test RAM Disk Speed
- Auto-mount on System Boot
- How to Run VirtualBox VM on RAM Disk
- Wrapping Up
- JamesCoyle.net Limited
- Create a RAM disk in Linux
- Create a RAM disk in Linux
Using the RAM disk block device with Linux¶
1) Overview¶
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
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).
2b) Module parameters
/dev/ramX devices created.
Maximum partition number.
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:
If you make a boot disk that has LILO, then for the above, you would use:
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.
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:
Make a filesystem on it. Say ext2fs for this example:
Mount it, copy the files you want to it (eg: /etc/* /dev/* …) and unmount it again.
Compress the contents of the RAM disk. The level of compression will be approximately 50% of the space used by the files. Unused space on the RAM disk will compress to almost nothing:
Put the kernel onto the floppy:
Put the RAM disk image onto the floppy, after the kernel. Use an offset that is slightly larger than the kernel, so that you can put another (possibly larger) kernel onto the same floppy later without overlapping the RAM disk image. An offset of 400 kB for kernels about 350 kB in size would be reasonable. Make sure offset+size of ram_image.gz is not larger than the total space on your floppy (usually 1440 kB):
Make sure that you have already specified the boot information in FDARGS and FDINITRD or that you use a bootloader to pass kernel command line boot options to the kernel.
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.
Источник
Как создать ramdisk в Linux или виртуальный диск в RAM
Иногда попадаются задачи, когда нужно работать с большим количеством мелких файлов или некоторое небольшое время хранить объемные данные и делать это по возможности быстро, без завязок на медленную файловую подсистему и/или диски. Многие вспомнят, что есть такой виртуальный диск, он же – RAM-дисках (ramdisk), а сделать ramdisk в *nix системах можно очень быстро и просто.
Изначально, в ядре должна быть поддержка tmpfs.
Как создать диск:
В первую очередь создаем новую точку монтирования:
и даём все права на использование.
После этого даём команду на монтирование, для примера, я создам диск на 1 Gb
где 1024M – это и есть размер RAMdisk в Мегабайтах.
Аккуратнее с размером и не размахивайтесь слишком широко: если вы попросите создать ramdisk больше, чем имеете оперативной памяти, система начнёт сгружать всё в swap-файл и дела пойдут очень медленно и грустно. Кстати, если ОЗУ в системе достаточно, swap можно и вовсе отключить, см. Как отключить SWAP
Если же вы хотите изменить размер ramdisk – это просто:
При этом содержимое RAM-диска не пропадёт, но и его размер тут же увеличится (при уменьшении также ничего не пропадёт, если только данных не больше, чем диск).
ВАЖНО.
RAM-диск это хранение в OЗУ, и это значит, что всё его содержимое после отключения питания машины будет безвозвратно потеряно. По возможности используйте резервное питание, что бы успеть сохранить важные данные.
Источник
Создаём RAMdisk на Ubuntu 18.04
Создаем папку для рамдиска (точку монтирования):
ВНИМАНИЕ: Здесь: size=2G это значит, что рамдиск будет иметь размер 2 Гб. Для создание рамдиска размером 256Мб следует вписать:
size=256M
После чего проверяем правильность создания рамдиска командой:
И видим следующий результат:
Теперь вы можете использовать рамдиск как вы используете обычные разделы жесткого диска. Вы даже можете редактировать любые файлы прямо из РАМДИСКА.
Чтобы отключить виртуальный диск (РАМДИСК), выполните следующую команду (все ваши файлы на этом разделе будут моментально удалены):
Подключение RAM-диска на UBUNTU 18.04 автоматически, при загрузке системы
Вы можете использовать файл /etc/fstab для автоматического монтирования виртуального диска при загрузке системы.
Во-первых, сделайте резервную копию файла /etc/fstab. Можно с помощью следующей команды:
Резервная опия файла /etc/fstab сохранится в /etc/fstab.backup. Теперь если что-то случится в процессе, вы сможете просто восстановить файл /etc/fstab.
Открываем файл /etc/fstab:
После чего в конце файла добавляем следующую строчку:
После чего перезагружаем сервер командой:
После загрузки системы РАМдиск должен быть автоматически смонтирован (нужно проверить):
Сохранение данных RAM-диска:
Далее я покажу, как сохранить данные рамдиска на десткий диск при завершении работы системы и загрузить данные с жесткого диска в RAM-диск при загрузке системы.
Для этого создадим каталог, где диск будет смонтирован и где резервные копии данных будут сохраняться должны иметь одинаковый набор прав доступа к файлам.
Сначала создайте каталог, где данных RAM-диска будет сохранен при выключении системы с помощью следующей команды:
Теперь создайте файл системной службы с помощью следующей команды:
Источник
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.
Pros of RAM disk:
- Ultra-fast
- Can sustain countless reads and writes
Cons of RAM disk:
- 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. 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 temporary store screenshots when writing articles on this blog, so when my computer shut down, those screenshots will automatically be deleted on my computer.
- You may 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.
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.
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.
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.
To allocate 10G for the RAM disk, run this instead.
If we issue the following command
We can see it’s successfully mounted.
Now if I copy my VirtualBox machines file (5.8G) into the RAM disk, my RAM usage suddenly goes up to 9.22G.
If I unmount RAM disk,
Everything in that directory will be lost and RAM usage goes down to original.
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.
Which gave me 2.8GB/s write speed.
To test read speed, run:
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
Edit /etc/fstab file.
Add an entry like this:
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.
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.
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.
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!
Источник
JamesCoyle.net Limited
Data Integration and Virtualisation
Create a RAM disk in Linux
Create a RAM disk in Linux
There are many reasons for creating a memory based file system in Linux, not least of which is to provide a near zero latency and extremely fast area to story files. A prime use of a RAM disk is for application caching directories or work areas.
There are two main types of RAM disk which can be used in Linux and each have their own benefits and weaknesses:
Check the amount of free RAM you have left on your machine before creating a RAM disk. Use the Linux command free to see the unused RAM. The below is an example of a 31GB of ram in a production server.
The free command shows the amount of RAM availale on your system in addition to the amount of memory used, free and used for caching. SWAP space is also displayed and shows if your system is writing memory to disk.
Create a folder to use as a mount point for your RAM disk.
Then use the mount command to create a RAM disk.
Substitute the following attirbutes for your own values:
- [TYPE] is the type of RAM disk to use; either tmpfs or ramfs.
- [SIZE] is the size to use for the file system. Remember that ramfs does not have a physical limit and is specified as a starting size.
- [FSTYPE] is the type of RAM disk to use; either tmpfs, ramfs, ext4, etc.
You can add the mount entry into /etc/fstab to make the RAM disk persist over reboots. Remember however, that the data will disappear each time the machine is restarted.
Источник