- tmpfs
- Contents
- Usage
- Examples
- Disable automatic mount
- Troubleshooting
- Opening symlinks in tmpfs as root fails
- tmpfs (Русский)
- Contents
- Использование
- Примеры
- Отключить автоматическое монтирование
- Решение проблем
- Не получается открытие символьных ссылок в tmpfs от root
- TmpfsВ¶
- Linux tmpfs
- The most brilliant idea: use VM to store files
- Not a block device
- Tmpfs advantages
- Using tmpfs
- Low VM: the solution
- Mounting on top of existing mountpoints
- Bind mounting parts of filesystems
- NEWS CONTENTS
- Old News 😉
- [Feb 25, 2016] What Is -dev-shm And Its Practical Usage
- Recommend readings:
- [Aug 10, 2011] fstab — ArchWiki
- [Aug 09, 2011] Create turbocharged storage using tmpfs by Kevin van Zonneveld (kvz)
- Recommended Links
- Google matched content
- Softpanorama Recommended
- Top articles
- Sites
tmpfs
tmpfs is a temporary filesystem that resides in memory and/or swap partition(s). Mounting directories as tmpfs can be an effective way of speeding up accesses to their files, or to ensure that their contents are automatically cleared upon reboot.
Contents
Usage
Some directories where tmpfs(5) is commonly used are /tmp, /var/lock and /var/run. Do not use it on /var/tmp, because that folder is meant for temporary files that are preserved across reboots.
Arch uses a tmpfs /run directory, with /var/run and /var/lock simply existing as symlinks for compatibility. It is also used for /tmp by the default systemd setup and does not require an entry in fstab unless a specific configuration is needed.
glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for POSIX shared memory. Mounting tmpfs at /dev/shm is handled automatically by systemd and manual configuration in fstab is not necessary.
Generally, tasks and programs that run frequent read/write operations can benefit from using a tmpfs folder. Some applications can even receive a substantial gain by offloading some (or all) of their data onto the shared memory. For example, relocating the Firefox profile into RAM shows a significant improvement in performance.
Examples
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 /tmp mount, use the size mount option:
To specify a more secure mounting, specify the following mount option:
See the tmpfs(5) man page and Security#File systems for more information.
Reboot for the changes to take effect. Note that although it may be tempting to simply run mount -a 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 mount -a instead of rebooting (or mount them individually).
After applying changes, verify that they took effect by looking at /proc/mounts and using findmnt :
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:
Disable automatic mount
Under systemd, /tmp is automatically mounted as a tmpfs, if it is not already a dedicated mountpoint (either tmpfs or on-disk) in /etc/fstab . To disable the automatic mount, mask the tmp.mount systemd unit.
Files will no longer be stored in a tmpfs, but on the block device instead. The /tmp contents will now be preserved between reboots, which might not be the desired behavior. To regain the previous behavior and clean the /tmp folder automatically when restarting, consider using tmpfiles.d(5) :
Troubleshooting
Opening symlinks in tmpfs as root fails
Considering /tmp is using tmpfs, change the current directory to /tmp , then create a file and create a symlink to that file in the same /tmp directory. Permission denied errors are to be expected when attempting to read the symlink due to /tmp having the sticky bit set.
Источник
tmpfs (Русский)
tmpfs — это временная файловая система, которая находится в памяти и/или вашем разделе(ах) подкачки, в зависимости от того, насколько вы её заполнили. Монтирование каталогов как TMPFS — это эффективный способ ускорения доступа к своим файлам. Также это полезно, если вам нужно, чтобы содержимое каталогов автоматически удалялось при перезагрузке.
Contents
Использование
Некоторые каталоги, где TMPFS обычно используются: /tmp, /var/lock и /var/run. Не используйте его на /var/tmp, так как этот каталог предназначен для временных файлов, которые сохраняются после перезагрузки.
Arch использует tmpfs в каталоге /run , с симлинками для совместимости /var/run и /var/lock . Он также используется для /tmp в настройках по умолчанию Systemd и не требует записи в fstab, если не требуется конкрентная настройка.
glibc 2.2 и выше ожидает что /dev/shm будет смонтирован tmpfs для POSIX разделяемой памяти. Монтирование /dev/shm в tmpfs выполняется автоматически systemd, поэтому ручная настройка в fstab больше не требуется.
Как правило, интенсивные задачи и программы ввода/вывода, которые выполняют частые операции чтения/записи могут получить пользу используя каталог TMPFS. Некоторые приложения могут даже получить существенную выгоду, снимая нагрузку некоторых (или всех) своих данных на общую память. Например, перемещение профиля Firefox в оперативную память показывает значительное улучшение производительности.
Примеры
По умолчанию раздел TMPFS имеет максимальный размер устанавленный от половины всей вашей оперативной памяти, но это можно настроить. Обратите внимание, что фактическое потребление памяти/подкачки зависит от того, на сколько вы заполните её, так как разделы TMPFS не потребляют память до тех пор, пока это будет на самом деле необходимо.
Чтобы точно установить максимальный размер, в данном примере, чтобы переопределить значение по умолчанию для монтирования /tmp , используем опцию монтирования size :
Вот более сложный пример, показывающий, как добавить монтирование TMPFS для пользователей. Это полезно для веб-сайтов, MySQL TMP файлов,
/.vim/ , и многое другое. Очень важно, попытаться получить идеальные параметры монтирования для того, что вы пытаетесь достичь. Цель состоит в том, чтобы получить безопасные параметры, насколько это возможно, чтобы предотвратить повышенное использование. Будет безопасным ограничить размер, указать Uid и GID + mode. Для получения дополнительной информации по этому вопросу, пройдите по ссылкам перечисленным в секции #Смотрите также.
Смотрите справочную страницу mount для получения дополнительной информации. Полезная опция монтирования из справочной страницы является опция default . По крайней мере понятная.
Перезагрузитесь, для того чтобы изменения вступили в силу. Обратите внимание, что может быть заманчивым, выполнить mount -a , чтобы сделанные изменения вступили в силу немедленно, это сделает недоступными какие-либо файлы, которые в настоящее время находятся в этих каталогах (например, особенно проблематично для запуска программ с файлами блокировки). Тем не менее, если все они пусты, она должна быть безопасной для запуска mount -a , вместо перезагрузки (или смонтируйте их в индивидуальном порядке).
После применения изменений, вы можете убедиться в том, что они вступили в силу, посмотрев в /proc/mounts и используя findmnt :
TMPFS также может быть временно изменен, без необходимости в перезагрузке, например, когда в ближайшее время необходимо выполнить большую работу компиляции. В этом случае вы можете запустить:
Отключить автоматическое монтирование
Systemd, может автоматически устанавливать /tmp как tmpfs, даже если у вас нет записи в вашем /etc/fstab .
Для отключения автоматического монтирования, выполните следующую команду:
Файлы больше не будут хранится в tmpfs, но будут на вашем блочном устройстве. Содержание /tmp теперь будет сохранятся между перезагрузками, чего вам бы не хотелось. Чтобы сохранить прежнее поведение и очищать каталог /tmp атоматически когда вы перезагружаете машину, рассмотрите возможность использования tmpfiles.d(5) :
Решение проблем
Не получается открытие символьных ссылок в tmpfs от root
Учитывая что /tmp использует TMPFS, измените текущую директорию на /tmp , а затем создайте файл и создайте символическую ссылку на этот файл в том же каталог /tmp . При попытке открыть файл, созданный с помощью символической ссылки, вы получите ошибку «доступ запрещён». Ожидается, что это как /tmp содержит «прилипший» набор битов.
Источник
TmpfsВ¶
Tmpfs is a file system which keeps all of its files in virtual memory.
Everything in tmpfs is temporary in the sense that no files will be created on your hard drive. If you unmount a tmpfs instance, everything stored therein is lost.
tmpfs puts everything into the kernel internal caches and grows and shrinks to accommodate the files it contains and is able to swap unneeded pages out to swap space. It has maximum size limits which can be adjusted on the fly via вЂmount -o remount …’
If you compare it to ramfs (which was the template to create tmpfs) you gain swapping and limit checking. Another similar thing is the RAM disk (/dev/ram*), which simulates a fixed size hard disk in physical RAM, where you have to create an ordinary filesystem on top. Ramdisks cannot swap and you do not have the possibility to resize them.
Since tmpfs lives completely in the page cache and on swap, all tmpfs pages will be shown as “Shmem” in /proc/meminfo and “Shared” in free(1). Notice that these counters also include shared memory (shmem, see ipcs(1)). The most reliable way to get the count is using df(1) and du(1).
tmpfs has the following uses:
There is always a kernel internal mount which you will not see at all. This is used for shared anonymous mappings and SYSV shared memory.
This mount does not depend on CONFIG_TMPFS. If CONFIG_TMPFS is not set, the user visible part of tmpfs is not built. But the internal mechanisms are always present.
glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for POSIX shared memory (shm_open, shm_unlink). Adding the following line to /etc/fstab should take care of this:
Remember to create the directory that you intend to mount tmpfs on if necessary.
This mount is _not_ needed for SYSV shared memory. The internal mount is used for that. (In the 2.3 kernel versions it was necessary to mount the predecessor of tmpfs (shm fs) to use SYSV shared memory.)
Some people (including me) find it very convenient to mount it e.g. on /tmp and /var/tmp and have a big swap partition. And now loop mounts of tmpfs files do work, so mkinitrd shipped by most distributions should succeed with a tmpfs /tmp.
And probably a lot more I do not know about 🙂
tmpfs has three mount options for sizing:
The limit of allocated bytes for this tmpfs instance. The default is half of your physical RAM without swap. If you oversize your tmpfs instances the machine will deadlock since the OOM handler will not be able to free that memory.
The same as size, but in blocks of PAGE_SIZE.
The maximum number of inodes for this instance. The default is half of the number of your physical RAM pages, or (on a machine with highmem) the number of lowmem RAM pages, whichever is the lower.
These parameters accept a suffix k, m or g for kilo, mega and giga and can be changed on remount. The size parameter also accepts a suffix % to limit this tmpfs instance to that percentage of your physical RAM: the default, when neither size nor nr_blocks is specified, is size=50%
If nr_blocks=0 (or size=0), blocks will not be limited in that instance; if nr_inodes=0, inodes will not be limited. It is generally unwise to mount with such options, since it allows any user with write access to use up all the memory on the machine; but enhances the scalability of that instance in a system with many CPUs making intensive use of it.
tmpfs has a mount option to set the NUMA memory allocation policy for all files in that instance (if CONFIG_NUMA is enabled) — which can be adjusted on the fly via вЂmount -o remount …’
use the process allocation policy (see set_mempolicy(2))
prefers to allocate memory from the given Node
allocates memory only from nodes in NodeList
prefers to allocate from each node in turn
allocates from each node of NodeList in turn
prefers to allocate memory from the local node
NodeList format is a comma-separated list of decimal numbers and ranges, a range being two hyphen-separated decimal numbers, the smallest and largest node numbers in the range. For example, mpol=bind:0-3,5,7,9-15
A memory policy with a valid NodeList will be saved, as specified, for use at file creation time. When a task allocates a file in the file system, the mount option memory policy will be applied with a NodeList, if any, modified by the calling task’s cpuset constraints [See CPUSETS ] and any optional flags, listed below. If the resulting NodeLists is the empty set, the effective memory policy for the file will revert to “default” policy.
NUMA memory allocation policies have optional flags that can be used in conjunction with their modes. These optional flags can be specified when tmpfs is mounted by appending them to the mode before the NodeList. See NUMA Memory Policy for a list of all available memory allocation policy mode flags and their effect on memory policy.
For example, mpol=bind=static:NodeList, is the equivalent of an allocation policy of MPOL_BIND | MPOL_F_STATIC_NODES.
Note that trying to mount a tmpfs with an mpol option will fail if the running kernel does not support NUMA; and will fail if its nodelist specifies a node which is not online. If your system relies on that tmpfs being mounted, but from time to time runs a kernel built without NUMA capability (perhaps a safe recovery kernel), or with fewer nodes online, then it is advisable to omit the mpol option from automatic mount options. It can be added later, when the tmpfs is already mounted on MountPoint, by вЂmount -o remount,mpol=Policy:NodeList MountPoint’.
To specify the initial root directory you can use the following mount options:
The permissions as an octal number
These options do not have any effect on remount. You can change these parameters with chmod(1), chown(1) and chgrp(1) on a mounted filesystem.
tmpfs has a mount option to select whether it will wrap at 32- or 64-bit inode numbers:
Use 64-bit inode numbers
Use 32-bit inode numbers
On a 32-bit kernel, inode32 is implicit, and inode64 is refused at mount time. On a 64-bit kernel, CONFIG_TMPFS_INODE64 sets the default. inode64 avoids the possibility of multiple files with the same inode number on a single device; but risks glibc failing with EOVERFLOW once 33-bit inode numbers are reached — if a long-lived tmpfs is accessed by 32-bit applications so ancient that opening a file larger than 2GiB fails with EINVAL.
So вЂmount -t tmpfs -o size=10G,nr_inodes=10k,mode=700 tmpfs /mytmpfs’ will give you tmpfs instance on /mytmpfs which can allocate 10GB RAM/SWAP in 10240 inodes and it is only accessible by root.
Источник
Linux tmpfs
Tmpfs was pioneered in Solaris is designed primarily as a performance enhancement to allow short lived files to be written and accessed without generating disk or network I/O. Tmpfs maximizes file manipulation speed while preserving UNIX file semantics. It does not require dedicated disk space for files and has no negative performance impact. The most brilliant idea, that was somewhat reminiscent of Multics, was to use virtual memory system facilities for file storage and access. Tmpfs files are written and accessed directly from the memory maintained by the kernel; they are not differentiated from other uses of physical memory. This means tmpfs file data can be ‘‘swapped’’ or paged to disk, freeing VM resources for other needs. General VM system routines are used to perform many low level tmpfs file system operations. This reduces the amount of code needed to maintain the file system, and ensures that tmpfs resource demands may coexist with other VM resource users with no adverse effects. As such it is more advanced then ramdisk, and more dynamic. tmpfs can use both RAM and swap file pushing inactive files to disk. It was invented in Solaris and reimplemented in linux is slightly different form.
Linux reimplementation of tmpfs is somewhat more flexible then Solaris. It coexists with older concept of ramdisk which was borrowed from MS DOS. Ramdisk is a block device that requires a mkfs command or similar command before you can use it. tmpfs is a filesystem, not a block device; you just mount it, and it is usable instantly. In this sense it is more like virtual folder then virtual filesystem.
The most brilliant idea: use VM to store files
tmpfs is also known as the «virtual memory filesystem». Virtual memory consists of pages that reside in RAM and swap devices. The VM subsystem in the kernel allocates these resources transparently moving RAM pages to swap and vice-versa depending of thier usage. This idea actually originated in Multics, which served as one of Unix prototypes.
The tmpfs filesystem requests pages from the VM subsystem to store files. tmpfs itself doesn’t know whether these pages are on swap or in RAM; it’s the VM subsystem’s job to make those kinds of decisions.
Not a block device
tmpfs does not exist on top of an underlying block device. Because tmpfs sits on top of VM directly, you can create a tmpfs filesystem with a simple mount command:
After executing this command, you’ll have a new tmpfs filesystem mounted at /mnt/tmpfs, ready for use. Note that there’s no need to run mkfs.tmpfs; in fact, it’s impossible, as no such command exists. Immediately after the mount command, the filesystem is mounted and available for use, and is of type tmpfs. This is very different from how Linux ramdisks are used; standard Linux ramdisks are block devices, so they must be formatted with a filesystem of your choice before you can use them. In contrast, tmpfs is a filesystem. So, you can just mount it and go.
Tmpfs advantages
Dynamic filesystem size
You’re probably wondering about how big that tmpfs filesystem was that we mounted at /mnt/tmpfs, above. The answer to that question is a bit unexpected, especially when compared to disk-based filesystems. /mnt/tmpfs will initially have a very small capacity, but as files are copied and created, the tmpfs filesystem driver will allocate more VM and will dynamically increase the filesystem capacity as needed. And, as files are removed from /mnt/tmpfs, the tmpfs filesystem driver will dynamically shrink the size of the filesystem and free VM resources, and by doing so return VM into circulation so that it can be used by other parts of the system as needed. Since VM is a precious resource, you don’t want anything hogging more VM than it actually needs, and the great thing about tmpfs is that this all happens automatically.
The other major benefit of tmpfs is its blazing speed. Because a typical tmpfs filesystem will reside completely in RAM, reads and writes can be almost instantaneous. Even if some swap is used, performance is still excellent and those parts of the tmpfs filesystem will be moved to RAM as more free VM resources become available. Having the VM subsystem automatically move parts of the tmpfs filesystem to swap can actually be good for performance, since by doing so, the VM subsystem can free up RAM for processes that need it. This, along with its dynamic resizing abilities, allow for much better overall OS performance and flexibility than the alternative of using a traditional RAM disk.
While this may not seem like a positive, tmpfs data is not preserved between reboots, because virtual memory is volatile in nature. I guess you probably figured that tmpfs was called «tmpfs» for a reason, didn’t you? However, this can actually be a good thing. It makes tmpfs an excellent filesystem for holding data that you don’t need to keep, such as temporary files (those found in /tmp) and parts of the /var filesystem tree.
Using tmpfs
To use tmpfs, all you need is a 2.4 series kernel with «Virtual memory file system support (former shm fs)» enabled; this option lives under the «File systems» section of the kernel configuration options. Once you have a tmpfs-enabled kernel, you can go ahead and mount tmpfs filesystems. In fact, it’s a good idea to enable tmpfs in all your 2.4 kernels, whether you plan to use tmpfs or not. This is because you need to have kernel tmpfs support in order to use POSIX shared memory. System V shared memory will work without tmpfs in your kernel, however. Note that you do not need a tmpfs filesystem to be mounted for POSIX shared memory to work; you simply need the support in your kernel. POSIX shared memory isn’t used too much right now, but this situation will likely change as time goes on.
The fact that tmpfs dynamically grows and shrinks as needed makes one wonder: what happens when your tmpfs filesystem grows to the point where it exhausts all of your virtual memory, and you have no RAM or swap left? Well, generally, this kind of situation is a bit ugly. With kernel 2.4.4, the kernel would immediately lock up. With kernel 2.4.6, the VM subsystem has in many ways been fixed, and while exhausting VM isn’t exactly a wonderful experience, things don’t blow up completely, either. When 2.4.6 gets to the point where it can’t allocate any more VM, you obviously won’t be unable to write any new data to your tmpfs filesystem. In addition, it’s likely that some other things will happen. First, the other processes on the system will be unable to allocate much more memory; generally, this means that the system will most likely become extremely sluggish and almost unresponsive. Thus, it may be tricky or unusually time-consuming for the superuser to take the necessary steps to alleviate this low-VM condition.
In addition, the kernel has a built-in last-ditch system for freeing memory when no more is available; it’ll find a process that’s hogging VM resources and kill it. Unfortunately, this «kill a process» solution generally backfires when tmpfs growth is to blame for VM exhaustion. Here’s the reason. Tmpfs itself can’t (and shouldn’t) be killed, since it is part of the kernel and not a user process, and there’s no easy way for the kernel to find out which process is filling up the tmpfs filesystem. So, the kernel mistakenly attacks the biggest VM-hog of a process it can find, which is generally your X server if you happen to be running one. So, your X server dies, and the root cause of the low-VM condition (tmpfs) isn’t addressed. Ick.
Low VM: the solution
Fortunately, tmpfs allows you to specify a maximum upper bound for the filesystem size when a filesystem is mounted or remounted. Actually, as of kernel 2.4.6 and util-linux-2.11g, these parameters can only be set on mount, not on remount, but we can expect them to be settable on remount sometime in the near future. The optimal maximum tmpfs size setting depends on the resources and usage pattern of your particular Linux box; the idea is to prevent a completely full tmpfs filesystem from exhausting all virtual memory and thus causing the ugly low-VM conditions that we talked about earlier. A good way to find a good tmpfs upper-bound is to use top to monitor your system’s swap usage during peak usage periods. Then, make sure that you specify a tmpfs upper-bound that’s slightly less than the sum of all free swap and free RAM during these peak usage times.
Creating a tmpfs filesystem with a maximum size is easy. To create a new tmpfs filesystem with a maximum filesystem size of 32 MB, type:
This time, instead of mounting our new tmpfs filesystem at /mnt/tmpfs, we created it at /dev/shm, which is a directory that happens to be the «official» mountpoint for a tmpfs filesystem. If you happen to be using devfs, you’ll find that this directory has already been created for you.
Also, if we want to limit the filesystem size to 512 KB or 1 GB, we can specify size=512k and size=1g, respectively. In addition to limiting size, we can also limit the number of inodes (filesystem objects) by specifying the nr_inodes=x parameter. When using nr_inodes, x can be a simple integer, and can also be followed with a k, m, or g to specify thousands, millions, or billions (!) of inodes.
Also, if you’d like to add the equivalent of the above mount tmpfs command to your /etc/fstab, it’d look like this:
Mounting on top of existing mountpoints
Back in the 2.2 days, any attempt to mount something to a mountpoint where something had already been mounted resulted in an error. However, thanks to a rewrite of the kernel mounting code, using mountpoints multiple times is not a problem. Here’s an example scenario: let’s say that we have an existing filesystem mounted at /tmp. However, we decide that we’d like to start using tmpfs for /tmp storage. In the old days, your only option would be to unmount /tmp and remount your new tmpfs /tmp filesystem in its place, as follows:
However, this solution may not work for you. Maybe there are a number of running processes that have open files in /tmp; if so, when trying to unmount /tmp, you’d get the following error:
However, with recent 2.4 kernels, you can mount your new /tmp filesystem without getting the «device is busy» error:
With a single command, your new tmpfs /tmp filesystem is mounted at /tmp, on top of the already-mounted partition, which can no longer be directly accessed. However, while you can’t get to the original /tmp, any processes that still have open files on this original filesystem can continue to access them. And, if you umount your tmpfs-based /tmp, your original mounted /tmp filesystem will reappear. In fact, you can mount any number of filesystems to the same mountpoint, and the mountpoint will act like a stack; unmount the current filesystem, and the last-most-recently mounted filesystem will reappear from underneath.
Using bind mounts, we can mount all, or even part of an already-mounted filesystem to another location, and have the filesystem accessible from both mountpoints at the same time! For example, you can use bind mounts to mount your existing root filesystem to /home/drobbins/nifty, as follows:
Now, if you look inside /home/drobbins/nifty, you’ll see your root filesystem (/home/drobbins/nifty/etc, /home/drobbins/nifty/opt, etc.). And if you modify a file on your root filesystem, you’ll see the modifications in /home/drobbins/nifty as well. This is because they are one and the same filesystem; the kernel is simply mapping the filesystem to two different mountpoints for us. Note that when you mount a filesystem somewhere else, any filesystems that were mounted to mountpoints inside the bind-mounted filesystem will not be moved along. In other words, if you have /usr on a separate filesystem, the bind mount we performed above will leave /home/drobbins/nifty/usr empty. You’ll need an additional bind mount command to allow you to browse the contents of /usr at /home/drobbins/nifty/usr:
Bind mounting parts of filesystems
Bind mounting makes even more neat things possible. Let’s say that you have a tmpfs filesystem mounted at /dev/shm, its traditional location, and you decide that you’d like to start using tmpfs for /tmp, which currently lives on your root filesystem. Rather than mounting a new tmpfs filesystem to /tmp (which is possible), you may decide that you’d like the new /tmp to share the currently mounted /dev/shm filesystem. However, while you could bind mount /dev/shm to /tmp and be done with it, your /dev/shm contains some directories that you don’t want to appear in /tmp. So, what do you do? How about this:
In this example, we first create a /dev/shm/tmp directory and then give it 1777 perms, the proper permissions for /tmp. Now that our directory is ready, we can mount /dev/shm/tmp, and only /dev/shm/tmp to /tmp. So, while /tmp/foo would map to /dev/shm/tmp/foo, there’s no way for you to access the /dev/shm/bar file from /tmp.
As you can see, bind mounts are extremely powerful and make it easy to make modifications to your filesystem layout without any fuss. Next article, we’ll check out devfs; for now, you may want to check out the following resources.
Top Visited Your browser does not support iframes. NEWS CONTENTS
Old News 😉[Feb 25, 2016] What Is -dev-shm And Its Practical UsageMarch 14, 2006 | cyberciti.biz/dev/shm is nothing but implementation of traditional shared memory concept. It is an efficient means of passing data between programs. One program will create a memory portion, which other processes (if permitted) can access. This will result into speeding up things on Linux. shm / shmfs is also known as tmpfs, which is a common name for a temporary file storage facility on many Unix-like operating systems. It is intended to appear as a mounted file system, but one which uses virtual memory instead of a persistent storage device. If you type the mount command you will see /dev/shm as a tempfs file system. Therefore, it is a file system, which keeps all files in virtual memory. Everything in tmpfs is temporary in the sense that no files will be created on your hard drive. If you unmount a tmpfs instance, everything stored therein is lost. By default almost all Linux distros configured to use /dev/shm: Nevertheless, where can I use /dev/shm? You can use /dev/shm to improve the performance of application software such as Oracle or overall Linux system performance. On heavily loaded system, it can make tons of difference. For example VMware workstation/server can be optimized to improve your Linux host’s performance (i.e. improve the performance of your virtual machines). In this example, remount /dev/shm with 8G size as follows: # mount -o remount,size=8G /dev/shm To be frank, if you have more than 2GB RAM + multiple Virtual machines, this hack always improves performance. In this example, you will give you tmpfs instance on /disk2/tmpfs which can allocate 5GB RAM/SWAP in 5K inodes and it is only accessible by root:
How do I restrict or modify size of /dev/shm permanently? You need to add or modify entry in /etc/fstab file so that system can read it after the reboot. Edit, /etc/fstab as a root user, enter: Append or modify /dev/shm entry as follows to set size to 8G Save and close the file. For the changes to take effect immediately remount /dev/shm: Recommend readings:[Aug 10, 2011] fstab — ArchWiki
Some directories where tmpfs is commonly used are /tmp, /var/lock and /var/run. Do NOT use it on /var/tmp, because that folder is meant for temporary files that are preserved across reboots. By default, a tmpfs partition has its maximum size set to half your total RAM, but this can be customized. Note that the actual memory/swap consumption depends on how much you fill it up, as tmpfs partitions don’t consume any memory until it is actually needed. To use tmpfs for /tmp, add this line to /etc/fstab: File: /etc/fstab You may or may not want to specify the size here, but you should leave the mode option alone in these cases to ensure that they have the correct permissions (1777). In the example above, /tmp will be set to use up to half of your total RAM. To explicitly set a maximum size, use the size mount option: File: /etc/fstab See the mount command man page for more information. Reboot for the changes to take effect. Note that although it may be tempting to simply run mount -a 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 mount -a instead of rebooting (or mount them individually). After applying changes, you may want to verify that they took effect with findmnt: $ findmnt —target /tmp To use tmpfs for /var/lock and /var/run, you can simply symlink them to /run. Make sure to close anything important before doing this, because you will have to reboot, and daemons may not stop cleanly. # ln -sf /run/lock /var/lock # ln -sf /run /var/run # reboot Note: Arch will likely do this by default in the future. See https://bugs.archlinux [Aug 09, 2011] Create turbocharged storage using tmpfs by Kevin van Zonneveld (kvz)Kevin van ZonneveldAs told before, you probably already have a /dev/shm on your linux system. So just copy a file to it: And now it’s in your RAM! Using this file will be 30 times faster than before! Enlarge current volume But maybe the limit of half of your physical RAM just does not cut it for you. Then you might want to increase the maximum size of this volume to 4GB: Create a new volume Another possibility is to create a brand new memory device. We can do this with the filesystem type: tmpfs. Let’s say you want to create a tmpfs instance on /var/www/www.mysite.com/ramdrive that can allocate a max of 500MB RAM and that can only be changed by root, but accessed by everyone (like Apache): Restore that volume everytime your server boots Easy, just make sure the directory exists, and add the following line to your /etc/fstab : This will create a ramdrive of max 500MB in /var/www/www.mysite.com/ramdrive everytime your server boots. The mode 0777 will give it full access for everybody on your system, so just change that to a suitable umask. Recommended LinksGoogle matched contentSoftpanorama RecommendedTop articlesSitestmpfs and bind mounts are relatively new and for the most part undocumented new kernel features, the best way to learn more about them is to study relevant parts of the Linux kernel sources. Источник |