Tmpfs

Содержание:

Введение в протокол SNMP

SNMP есть Simple Network Management Protocol, он же Простой Протокол Сетевого Управления. Протокол создан в 1988 г. с целью управления большим количеством сетевых устройств. С того момента протокол набрал соответствующую популярность и стал стандартом. С момента разработки протокол SNMP был 3 раза переработан с версии SNMPv1, SNMPv2 и SNMPv3. На самом деле, версий было больше, например v2 была пересмотрена 2 раза (или даже более). Так же стоит отметить, что кроме SNMP были и другие попытки создать коммерческие и не коммерческие протоколы управления (CORBA, TMN …) не увенчавшиеся успехом.

Кроме управления устройствами, очень часто всегда SNMP используют для мониторинга. SNMP может получать различную информацию от любых сетевых устройств, будь то роутер, свич или просто компьютер (в которых имеется поддержка данного протокола (читай — запущен агент SNMP). Содержимое получаемой информации может быть очень разнообразно, например: время аптайма, различные счетчики производительности CPU, сети и др., сетевые параметры устройств…

Preface

This article aims to document the process of creating a customized Ubuntu that loads an image from the hard disk to RAM, then boots an entire Ubuntu session out of RAM. It is intended for intermediate to advanced Ubuntu users who are familiar with the shell, and may have limited experience customizing the livecd (LiveCDCustomization) and shell scripting. We will customize a LiveCD and copy it to the hard drive, and make a few modifications to bootup scripts so that it copies to RAM via our good friend tmpfs.

WARNING: The author asserts that this procedure works for him, but cannot guarantee that this procedure works for anyone else. Although this procedure is meant to be 100% safe, it is feasible that there may be mistakes, or a chance of misunderstanding the instructions in a manner that causes loss of data. Please make a backup and do not attempt on mission critical systems. Read through this article thoroughly, and do not attempt if you do not comprehend or feel comfortable about any of the instructions!

CAUTION: I hope this is intuitively obvious, but I’ll humor you and state it bluntly: Changes you make under the live session are NOT saved and WILL BE LOST when you reboot or shut down. Don’t save anything important to the «home directory» and expect it to still be around! If you want to save data permanently, mount a permanent medium (such as your hard drive), plug in a thumbdrive, or use some network functionality built into Ubuntu to save your data to a non-volatile destination.

Advancements in technology

Some hardware manufactures provide devices that are slower than RAM but faster than SSD to be used as cache drives. These devices are usually incorporated on a PCIe add-in card and have either an adapter from PCIe to M.2 slot or the entire memory device is embedded into the PCIe card.

If users need a non-volatile high speed versatile solution faster than SSD/SAS/SATA then these high speed solutions should be considered. Of course users should not mount these devices with tmpfs but instead use a conventional partitioning filesystem.

Technology such as the Intel 3Dx Optane memory cache can be used too, but this technology, although more versatile than SSD, is still subject to wearing out. It does however provide a brilliant midway point that will only get better as the technology progresses in the future and provides us with a much faster computing experience when setup correctly.

Examples

Note: The actual memory/swap consumption depends on how much is used, as tmpfs partitions do not consume any memory until it is actually needed.

By default, a tmpfs partition has its maximum size set to half of the available RAM, however it is possible to overrule this value.
To explicitly set a maximum size, in this example to override the default mount, use the mount option:

/etc/fstab
tmpfs   /tmp         tmpfs   rw,nodev,nosuid,size=2G          0  0

To specify a more secure mounting, specify the following mount option:

/etc/fstab
tmpfs   /www/cache    tmpfs  rw,size=1G,nr_inodes=5k,noexec,nodev,nosuid,uid=user,gid=group,mode=1700 0 0

See the man page and for more information.

Reboot for the changes to take effect. Note that although it may be tempting to simply run to make the changes effective immediately, this will make any files currently residing in these directories inaccessible (this is especially problematic for running programs with lockfiles, for example). However, if all of them are empty, it should be safe to run instead of rebooting (or mount them individually).

After applying changes, verify that they took effect by looking at and using :

$ findmnt /tmp
TARGET SOURCE FSTYPE OPTIONS
/tmp   tmpfs  tmpfs  rw,nosuid,nodev,relatime

The tmpfs can also be temporarily resized without the need to reboot, for example when a large compile job needs to run soon. In this case, run:

# mount -o remount,size=4G,noatime /tmp

Use Cases

There are many cases where one would like to boot Ubuntu to RAM:

  • Performance: The desktop performance is dramatically improved. A 400MB squashed filesystem in RAM, that holds 1200MB of data, is read back on a 1.6GHz Core Duo in about 3 seconds, including decompression time.
  • Power, Noise, Durability: Although modern hard disks don’t use much power compared to other system components, this may still be important for some. In laptops, hard disks are often the noisiest components, so this setup can reduce system noise. With the hard disk spun down, a laptop can potentially withstand greater shocks without damage.
  • Abrupt poweroff: Since the hard disk is only momentarily used in read-only mode during boot, then never touched again, there are few or no negative consequences of an abrupt poweroff. If a system is used where power is inconsistent, or the system is regularly used in a context where fast shutoffs are required, this is very handy.
  • Privacy: Anything you do in this session are lost when you reboot or power off. This is great for kiosks or other systems where permanent modification are not desired. (Note that by default the livecd user has full sudo access, so potentially a malicious user can still make permanent changes by mounting the hard drive and following this HOWTO)

Installation

Users need to activate the following kernel options:

KERNEL Enable tmpfs support

File systems  --->
     Pseudo filesystems  --->
           Tmpfs virtual memory file system support (former shm fs)
           Optional drivers
Optional drivers
Option Description
Tmpfs POSIX Access Control Lists Enable permissions.
Tmpfs extended attributes Enable metadata support.

Usage

Generate and mount tmpfs in one step:

Users can specify the mount option size to control the maximum size of the filesystem (default: half of your memory). Note that tmpfs doesn’t reserve this memory, but allocates only the needed memory.

systemd

When using systemd the /tmp directory is mounted by default as tmpfs and given a default size which is deemed big enough without chewing up too much RAM.

Users can view mounted temporary filesystems using the following command:

This will show if the /tmp mount point is a tmpfs filesystem and the size of such filesystem.

In order to disable this behaviour and take back control of the directory by using /etc/fstab the user needs to run the following command:

This command will now not mount /tmp as a tmpfs and will automatically switch back to a block device.

Users should now add a new line in /etc/fstab which will create a tmpfs for /tmp manually.

FILE tmpfs fstab example

tmpfs /tmp tmpfs rw,nosuid,noatime,nodev,size=4G,mode=1777 0 0

OpenRC

OpenRC users should simply add the mount point into /etc/fstab:

FILE tmpfs fstab example

tmpfs /tmp tmpfs rw,nosuid,noatime,nodev,size=4G,mode=1777 0 0

Other directories to consider

Here are a few other directories users may mount as a tmpfs in order to boost their system performance.
Use the findmnt command to check if they are already use tmpfs before attempting to manually mount them in /etc/fstab.

Directory Purpose
/run Run-time variable data. Information about the running system since last boot, e.g., currently logged-in users and running daemons.
/var/run Run-time variable data. This directory contains system information data describing the system since it was booted.
/var/lock Lock files. Files keeping track of resources currently in use.

3) Using “rdev -r”¶

The usage of the word (two bytes) that “rdev -r” sets in the kernel image is
as follows. The low 11 bits (0 -> 10) specify an offset (in 1 k blocks) of up
to 2 MB (2^11) of where to find the RAM disk (this used to be the size). Bit
14 indicates that a RAM disk is to be loaded, and bit 15 indicates whether a
prompt/wait sequence is to be given before trying to read the RAM disk. Since
the RAM disk dynamically grows as data is being written into it, a size field
is not required. Bits 11 to 13 are not currently used and may as well be zero.
These numbers are no magical secrets, as seen below:

./arch/x86/kernel/setup.c:#define RAMDISK_IMAGE_START_MASK     0x07FF
./arch/x86/kernel/setup.c:#define RAMDISK_PROMPT_FLAG          0x8000
./arch/x86/kernel/setup.c:#define RAMDISK_LOAD_FLAG            0x4000

Consider a typical two floppy disk setup, where you will have the
kernel on disk one, and have already put a RAM disk image onto disk #2.

Hence you want to set bits 0 to 13 as 0, meaning that your RAM disk
starts at an offset of 0 kB from the beginning of the floppy.
The command line equivalent is: “ramdisk_start=0”

You want bit 14 as one, indicating that a RAM disk is to be loaded.
The command line equivalent is: “load_ramdisk=1”

You want bit 15 as one, indicating that you want a prompt/keypress
sequence so that you have a chance to switch floppy disks.
The command line equivalent is: “prompt_ramdisk=1”

Putting that together gives 2^15 + 2^14 + 0 = 49152 for an rdev word.
So to create disk one of the set, you would do:

/usr/src/linux# cat arch/x86/boot/zImage > /dev/fd0
/usr/src/linux# rdev /dev/fd0 /dev/fd0
/usr/src/linux# rdev -r /dev/fd0 49152

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

append = "ramdisk_start=0 load_ramdisk=1 prompt_ramdisk=1"

Since the default start = 0 and the default prompt = 1, you could use:

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 (). 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 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.

The Difference Between a tmpfs and ramfs RAM Disk

Category : Knowledge

Get Social!

There are two file system types built into most modern Linux distributions which allow you to create a RAM based storage area which can be mounted and used link a normal folder.

Before using this type of file system you must understand the benefits and problems of memory file system in general, as well as the two different types. The two types of RAM disk file systems are tmpfs and ramfs and each type has it’s own strengths and weaknesses.

See my other post for details on how to create a RAM disk in Linux.

What is a memory based file system (RAM disk)?

A memory based file system is something which creates a storage area directly in a computers RAM as if it were a partition on a disk drive. As RAM is a volatile type of memory which means when the system is restarted or crashes the file system is lost along with all it’s data.

The major benefit to memory based file systems is that they are very fast – 10s of times faster than modern SSDs. Read and write performance is massively increased for all workload types. These types of fast storage areas are ideally suited for applications which need repetitively small data areas for caching or using as temporary space. As the data is lost when the machine reboots the data must not be  precious as even scheduling backups cannot guarantee that all the data will be replicated in the even of a system crash.

tmpfs vs. ramfs

The two main RAM based file system types in Linux are tmpfs and ramfs. ramfs is the older file system type and is largely replaced in most scenarios by tmpfs.

ramfs

ramfs creates an in memory file system which uses the same mechanism and storage space as Linux file system cache. Running the command free in Linux will show you the amount of RAM you have on your system, including the amount of file system cache in use. The below is an example of a 31GB of ram in a production server.

free -g
       total used free shared buffers cached
Mem:   31    29   2    0      0       8
-/+ buffers/cache: 20 11
Swap:  13    6    7

Currently 8GB of file system cache is in use on the system. This memory is generally used by Linux to cache recently accessed files so that the next time they are requested then can be fetched from RAM very quickly. ramfs uses this same memory and exactly the same mechanism which causes Linux to cache files with the exception that it is not removed when the memory used exceeds threshold set by the system.

ramfs file systems cannot be limited in size like a disk base file system which is limited by it’s capacity. ramfs will continue using memory storage until the system runs out of RAM and likely crashes or becomes unresponsive. This is a problem if the application writing to the file system cannot be limited in total size. Another issue is you cannot see the size of the file system in df and it can only be estimated by looking at the cached entry in free.

tmpfs

tmpfs is a more recent RAM file system which overcomes many of the drawbacks with ramfs. You can specify a size limit in tmpfs which will give a ‘disk full’ error when the limit is reached. This behaviour is exactly the same as a partition of a physical disk.

The size and used amount of space on  a tmpfs partition is also displayed in df. The below example shows an empty 512MB RAM disk.

df -h /mnt/ramdisk
Filesystem Size Used Avail Use% Mounted on
tmpfs      512M 0    512M  0%   /mnt/ramdisk

These two differences between ramfs and tmpfs make tmpfs much more manageable  however this is one major drawback; tmpfs may use SWAP space. If your system runs out of physical RAM, files in your tmpfs partitions may be written to disk based SWAP partitions and will have to be read from disk when the file is next accessed. In some environments this can be seen as a benefit as you are less likely to get out of memory exceptions as you could with ramfs because more ‘memory’ is available to use.

See my other post for details on how to create a RAM disk in Linux.

Lucid Updates

For trying this out in Lucid, it’s easier to just go into edit mode in grub2 having booted the live cd/usb and change the options to

kernel /casper/vmlinuz boot=casper toram splash
initrd /casper/initrd.gz

Else you’ll need to get grub legacy packages and use that to create the grub install cd stage2_eltorito can be extracted from http://packages.ubuntu.com/lucid/i386/grub/download

When making the iso use -J option to Generate Joliet directory information so that you can use usb-creator-gtk (Startup disk creator) and not waste CDs!

mkisofs -R -J -b boot/grub/stage2_eltorito -no-emul-boot \
         -boot-load-size 4 -boot-info-table -o grub.iso iso

Pitfalls:

  • remember to set permissions on all the files before you create the iso as these will be honored when imaged
  • Make sure your chroot doesn’t end up on the iso

Variations:

loading the squashfs from a cheap usb stick or cd can be slow, so if you do have a hard drive use that instead e.g.

if ; then
#live_dest="ram"
      echo "Copying contents to ram.."
      mkdir /store
      mount -t tmpfs -o size=2G none /store 
      mkdir /store/casper
      mkdir /mnt
# A use for my old windows recovery partition!
      mount /dev/sda3 /mnt/
      cp /mnt/casper/*.squashfs /store/casper/
      echo "Copy done.. safe to eject boot medium"
      umount /cdrom
      umount /mnt
      mount -o bin /store /cdrom

    elif ; then

Безопасность протокола SNMP (или версии протокола SNMP)

Безопасность протокола SNMP — это самый изменяемый раздел спецификации протокола со времени его создания. С каждой версией SNMP, производились попытки усилить безопасность. Первая версия протокола SNMPv1 была самой простой и небезопасной.  Сообщения протокола могли быть подвержены возможности модификации, подмене или прослушиванию. Безопасность протокола базировалась на модели безопасности на основе сообществ (т.н. Community-based Security Model), что подразумевало аутентификацию на основе единой текстовой строки — своеобразного пароля (т.н. community-sting), которая передавалась в теле сообщения в открытом виде. Хотя, данная версия протокола самая незащищенная, она довольно часто применяется в современных сетях, т.к. является самой простой.

В одной из вторых версий SNMP (SNMPv2p) была попытка реализовать аутентификацию на основе сторон (т.н.Party-based Security Model). Технология кроме аутентификации, так же поддерживала возможность шифрования трафика. Данная технология не прижилась, как «сложная и запутанная» ) и в данный момент не используется. После чего SNMP второй версии вернулась к Community-based Security и стала именоваться SNMPv2c и применяется по сей день. SNMPv2 была переписана чуть более чем полностью, в результате чего существенно повышено быстродействие протокола, безопасность.

Третья версия протокола (SNMPv3) была более удачно доработана и поддерживает как аутентификацию на основе имени пользователя (т.н. User-based Security Model), так и шифрование трафика. Хотя их можно и не использовать.

Версии протокола между собой не совместимы. Несовместимость заключается в разнице пакетов PDU, в наличии дополнительных команд в более новых версиях протокола (возможно, в других…). В RFC 2576 имеется некоторая информация, позволяющая организовать возможность совместного использования SNMPv1 и v2. Для этого есть 2 пути: 1. Использование прокси-агентов (агент преобразует PDU SNMPv2 в PDU SNMPv1), 2. Использование менеджера с поддержкой 2х версий (менеджер для каждого хоста должен помнить версию агента).

Давайте рассмотрим работу протокола SNMPv2c (и SNMPv1) с точки зрения безопасности. При рассмотрении структуры пакета PDU было видно, что каждая единица PDU содержит community строку. При этом, SNMP агент содержит список (часто данный список состоит из одного значения) разрешенных строк и описание того, что каждая из строк может делать (фактически – набор прав). В большинстве случаев – это права read/write. При активации функций SNMP на каком-либо хосте, стандартные строки community – это public и private для возможности чтения и для возможности чтения-записи соответственно. Это строки очень желательно менять на свои. Часто, при конфигурировании SNMP о , в котором для каждой переменной в поле связанные переменные подставлены установленные значения переменных. В поле error-status помещается значение NoError, а в поле error-index — 0. Значение поля request-id в ответном PDU совпадает с идентификатором в принятом сообщении.пределяют различные community строки для чтения переменных и для записи.

Requirements

The most obvious increased requirement is RAM. For best performance, I recommend having 256MB RAM + enough RAM to hold a customized image. Stripping Openoffice and some fonts and documentation from a stock Ubuntu LiveCD results in a 400MB compressed image, which fits in RAM comfortably on a system with 1GB RAM.

Tmpfs can fall back on swap (Ubuntu LiveCD scripts will mount any swap it finds), which is excellent for a bit of overflow, but if you regularly need to fall back on swap, performance will naturally suffer.

I have not investigated CPU requirements, but squashfs is compressed and decompressing takes some CPU power, so this is probably not a great idea on systems older than the Pentium III era.

As far as setting this system up, the requirements would be:

  1. Having an Ubuntu LiveCD ISO or CD handy. I used a Ubuntu LiveCD, but I see no reason why Xubuntu, Kubuntu, etc wouldn’t work (they don’t have differing casper boot scripts, as far as I know). This procedure should work on all LiveCD’s Dapper and later, with appropriate minor adaptations.
  2. About 2-4GB of free space
  3. A combined 1GB or so of RAM and swap available.

Additional configuration

Periodic fstrim jobs

There are multiple ways how to setup a periodic block discarding process. As of 2018, the default recommended frequency is once a week.

cron

Run fstrim on all mounted devices that support discard on a weekly basis:

FILE Run fstrim once per week

# Mins  Hours  Days   Months  Day of the week   Command
  15    13     *      *       1                 /sbin/fstrim --all

Similarly, it is possible to run fstrim only for a selected mount point:

FILE Run fstrim once per week on rootfs

# Mins  Hours  Days   Months  Day of the week   Command
  15    13     *      *       1                 /sbin/fstrim -v /

SSDcronTRIM

  • Distribution independent script (developed on a Gentoo system).
  • The script decides every time depending on the disk usage how often (monthly, weekly, daily, hourly) each partition has to be trimmed.
  • Recognizes if it should install itself into /etc/cron.{monthly,weekly,daily,hourly}, /etc/cron.d or any other defined directory and if it should make an entry into crontab.
  • Checks if the kernel meets the requirements, the filesystem is able to and if the SSD supports trimming.

systemd timer

When running a system with systemd version 212 or newer, a persistent can be created that will run fstrim weekly. Thanks to timer’s persistency it will be issued immediately if a scheduled run was missed.

Two systemd unit files need to be created in the /etc/systemd/system directory:

Service called which actually executes the fstrim:

FILE Service executing fstrim

Description=Run fstrim on all mounted devices that support discard


Type=oneshot
ExecStart=/bin/sh -c '/sbin/fstrim --all'

Timer which wakes up the service weekly:

FILE Timer starting the fstrim service

Description=Run fstrim.service weekly


OnCalendar=weekly
Persistent=true


WantedBy=multi-user.target

Make sure the permissions are correct:

Tell systemd to reload its unit files, then enable it:

It is now possible to see if it has been run and when the next time it will be ran by issuing:

Also the journalctl command can be used to verify the timer is running successfully.

Reducing amount of writes

The flash-based SSDs have a limited write lifetime — the number of writes performed. Thus when using a SSD, administrators generally want to reduce the amount of writes.

Portage TMPDIR on tmpfs

When building packages via Portage it is possible to perform the operations on tmpfs and get the tmpfs’ benefits. See Portage TMPDIR on tmpfs guide.

Temporal files on tmpfs

WarningRemember that all data in tmpfs reside in volatile memory. So data on tmpfs will be lost after system reboot, shutdown or crash!

It is possible to mount desired mount points as tmpfs. Since tmpfs stores files in volatile memory all the I/O operations directed to the given mount points are not performed on the solid state disk. This reduces the amount of writes and also improves performance.

This is an example of both /tmp and /var/tmp being mounted as tmpfs:

FILE

# temporal mountpoints on tmpfs
tmpfs           /tmp            tmpfs           size=16G,noatime        0 0
tmpfs           /var/tmp        tmpfs           size=1G,noatime         0 0

XDG cache on tmpfs

When running a Gentoo desktop, many programs, using X Window System (Chromium, Firefox, Skype, etc.) are making frequent disk I/O every few seconds to cache.

The cache directory location usually complies to XDG Base Directory Specification, namely to the XDG_CACHE_HOME environment variable. The default cache location is ~/.cache, which is usually mounted on a hard drive and could be moved to tmpfs.

To remap the cache directory location create file /etc/profile.d/xdg_cache_home.sh:

FILE

if  $USER ; then
  export XDG_CACHE_HOME="/tmp/${USER}/.cache"
fi

Warning is required, so that no is created by root and apps don’t misbehave trying to acquire access to it.

Warning

With the above change, auto unlocking the gnome keyring didn’t work anymore.
/var/log/messages said the following:

  May  5 10:02:52 localhost gnome-keyring-daemon: couldn't bind to control socket: /home/david/.cache/keyring-hRt5QC/control: No such file or directory

Web browser profile/s and cache on tmpfs

The web browser profile/s, cache, etc. can be relocated to tmpfs. The corresponding I/O associated with using the browser gets redirected from the SSD drive to tmpfs’ volatile memory, resulting in reduced wear to the physical drive and also improving browser speed and responsiveness.

systemd

Close all the browsers, start and enable the daemon.

Now it is possible to view all symlinks by printing the status of the started daemon:

OpenRC

Next add the users whose browser/s profile/s will get symlinked to a tmpfs or another mountpoint in the variable :

FILE

USERS="user user2 root"

Finally, close all the browsers, start and enable the daemon.

Now it is possible to view all symlinks by printing the status of the started daemon:

Примеры

По умолчанию раздел TMPFS имеет максимальный размер устанавленный от половины всей вашей оперативной памяти, но это можно настроить

Обратите внимание, что фактическое потребление памяти/подкачки зависит от того, на сколько вы заполните её, так как разделы TMPFS не потребляют память до тех пор, пока это будет на самом деле необходимо.. Чтобы точно установить максимальный размер, в данном примере, чтобы переопределить значение по умолчанию для монтирования , используем опцию монтирования :

Чтобы точно установить максимальный размер, в данном примере, чтобы переопределить значение по умолчанию для монтирования , используем опцию монтирования :

/etc/fstab
tmpfs   /tmp         tmpfs   nodev,nosuid,size=2G          0  0
Limiting the size, and specifying uid and gid + mode is very secure. For more information on this subject, follow the links listed in the  section.

Вот более сложный пример, показывающий, как добавить монтирование TMPFS для пользователей. Это полезно для веб-сайтов, MySQL TMP файлов, , и многое другое

Очень важно, попытаться получить идеальные параметры монтирования для того, что вы пытаетесь достичь. Цель состоит в том, чтобы получить безопасные параметры, насколько это возможно, чтобы предотвратить повышенное использование

Будет безопасным ограничить размер, указать Uid и GID + mode. Для получения дополнительной информации по этому вопросу, пройдите по ссылкам перечисленным в секции .

/etc/fstab
tmpfs   /www/cache    tmpfs  rw,size=1G,nr_inodes=5k,noexec,nodev,nosuid,uid=648,gid=648,mode=1700   0  0

Смотрите справочную страницу для получения дополнительной информации. Полезная опция монтирования из справочной страницы является опция . По крайней мере понятная.

Перезагрузитесь, для того чтобы изменения вступили в силу

Обратите внимание, что может быть заманчивым, выполнить , чтобы сделанные изменения вступили в силу немедленно, это сделает недоступными какие-либо файлы, которые в настоящее время находятся в этих каталогах (например, особенно проблематично для запуска программ с файлами блокировки). Тем не менее, если все они пусты, она должна быть безопасной для запуска , вместо перезагрузки (или смонтируйте их в индивидуальном порядке).

После применения изменений, вы можете убедиться в том, что они вступили в силу, посмотрев в и используя :

$ findmnt --target /tmp
TARGET SOURCE FSTYPE OPTIONS
/tmp   tmpfs  tmpfs  rw,nosuid,nodev,relatime

TMPFS также может быть временно изменен, без необходимости в перезагрузке, например, когда в ближайшее время необходимо выполнить большую работу компиляции. В этом случае вы можете запустить:

# mount -o remount,size=4G,noatime /tmp

Introduction

The term Solid State Drive is commonly used for flash-based block devices. Compared to conventional HDD, flash-based technology offers a much faster access time, lower latency, silent operation, power savings (no moving parts), and more. However, the flash-based technology brings a few issues which require some special system attention and care.

Dealing with empty blocks

Generally, traditional filesystems do not erase deleted data blocks but only flags them as such. Due to nature of flash memory cells any write operation has to be done to empty cells only. Thus writing to physically non-empty cells, flagged as deleted by a filesystem, requires their erasure which makes the operation slower than writing to empty cells. This problem is further amplified by hardware limitations.

For modern kernels it is possible to hint the deleted (not-used) data blocks to SSD. The described mechanism is called discard. Names of implementations differ — TRIM for ATAPI and UNMAP for SCSI. Filesystem’s support is required in order to use discard. Majority of modern filesystems (like Ext4, XFS or Btrfs) support discard. Also there are filesystems developed primarily for flash-based devices, such as F2FS.

There are two basic approaches to issue the discard command — using mount option () for continuous discard or periodic calls of fstrim utility.

Slowing wear out

Each write operation performed on a NAND flash cell causes its wear. This fact limits the SSD lifespan. The cell endurance varies with used technology. On the other hand, read operations are straightforward and do not cause cell wear.

A basic method increasing SSD lifespan is to uniformly distribute writes across all the blocks. This method is called wear leveling and is deployed via SSD firmware.

From system point of view, it is appropriate to generally reduce amount of writes.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *