Linux disable file cache

Is it possible in linux to disable filesystem caching for specific files? [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 3 years ago .

I have some large files and i am ok with them being read at disk I/O capacity. I wish to have file system cache free for other files. Is it possible to turn of file system caching for specific files in linux ?

2 Answers 2

Your question hints that you might not be the author of the program you wish to control. If that’s the case the answer is «not easily». If you are looking for something where you just mark (e.g. via extended attributes) a particular set of files «nocache» the answer is no. At best you are limited to having a LD_PRELOAD wrapper around the program and the wrapper would have to be written carefully to avoid impacting all files the program would try to open etc.

If you ARE the author of the program you should take a look at using fadvise (or the equivalent madvise if you’re using mmap ) because after you have finished reading the data you can hint to the kernel that it should discard the pieces it cached by using the FADV_DONTNEED parameter (why not use FADV_NOREUSE ? Because with Linux kernels available at the time of writing it’s a no-op).

Another technique if you’re the author would be to open the file with the O_DIRECT flag set but I do not recommend this unless you really know what you’re doing. O_DIRECT comes with a large set of usage constraints and conditions on its use (which people often don’t notice or understand the impact of until it’s too late):

  • You MUST do I/O in multiples of the disk’s block size (no smaller than 512 bytes but not unusual for it to be 4Kbytes and it can be some other larger multiple) and you must only use offsets that are similarly well aligned.
  • The buffers of your program will have to conform to an alignment rule.
  • Filesystems can choose not to support O_DIRECT so your program has to handle that.
  • Filesystems may simply choose to put your I/O through the page cache anyway ( O_DIRECT is a «best effort» hint).
Читайте также:  Почему центр обновления windows не устанавливается обновления

Источник

Is it possible in linux to disable filesystem caching for specific files?

I have some large files and i am ok with them being read at disk I/O capacity. I wish to have file-system cache free for other files. Is it possible to turn off file-system caching for specific files, on Linux? I wish to do this programmatically via native lib + java.

2 Answers 2

You can do so for an opened instance of the file, but not persistently for the file itself. You do so per instance of the opened file by using direct IO. I’m not sure how to do this in Java, but in C and C++, you pass the O_DIRECT flag to the open() call.

Note however that this has a couple of potentially problematic implications, namely:

  • It’s downright dangerous on certain filesystems. Most notably, current versions of BTRFS have serious issues with direct IO when you’re writing to the file.
  • You can’t mix direct IO with regular cached I/O unless you use some form of synchronization. Cached writes won’t show up for certain to direct IO reads until you call fsync() or fdatasync() , and direct IO writes may not show up for cached IO reads ever.

There is however an alternative method if you can tolerate having the data temporarily in cache. You can use the POSIX fadvise interface (through the posix_fadvise system call on Linux) to tell the kernel you don’t need data from the file when you’re done reading it. By using the POSIX_FADV_DONTNEED flag, you can tell the kernel to drop a specific region of a particular file from cache. You can actually do this as you are processing the file too (by reading a chunk, and then immediately after reading calling posix_fadvise on that region of the file), though the regions you call this on have to be aligned to the system’s page size. This is generally the preferred portable method of handling things, as it works on any POSIX compliant system with the real-time extensions (which is pretty much any POSIX compliant system).

Источник

ext4 отключить кэш диска

Имеется ли возможность отключения кэширования для раздела с файловой системой ext4 ? На нём расположены файлы БД, и кэш обеспечивается самой СУБД. Возникает ситуация, когда ненужный мне кэш ext4 занимает лишнюю память, провоцируя своппинг и общую потерю производительности.

CentOs 2.6.32-279.9.1.el6.x86_64 #1 SMP Tue Sep 25 21:43:11 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux СУБД Progress (OpenEdge)

На нём расположены файлы БД, и кэш обеспечивается самой СУБД

use raw devices, Luke

1. В ФС нет кэша по сути, есть page cache данных с диска, он независим от FS.

Читайте также:  Windows 10 64 bit build 1909

2. Выставь vm.swappiness=0 и кеш ни при каких условиях не будет вызывать своппинг т.к. будет очищаться при первом требовании.

В общем проблема надуманная.

1. В ФС нет кэша по сути, есть page cache данных с диска, он независим от FS.

значит я неверно диагностировал причину своппинга, но для СУБД я выделяю буфер 32 гига (из семидесяти), что-то же «отжирает остальное. » может быть как раз page cache

2. Выставь vm.swappiness=0 и кеш ни при каких условиях не будет вызывать
своппинг т.к. будет очищаться при первом требовании

выставлял 1-ку, попробую 0

Имеется ли возможность отключения кэширования для раздела с файловой системой ext4 ?

Но, насколько я понимаю, это не отменяет кеш чтения, хотя при записи кеширования не будет.

сейчас стоИт RAID из четырёх дисков SSD.

База лежит на раиде ssd, операционка на раиде SAS. Оперативки 72 гига, размер базы 460 гигов, клиентских подключений 600. Для буфера СУБД выделяю половину от оперативки. Все прекрасно работает, пока не появляется своп (расположен на SAS). Предположил, что причиной свопа явился кэш файловой системы. Иными словами цель — определить что занимает оставшуюся оперативку и прекратить своппинг. Нууу, и совсем шикарно было бы использовать под буфер СУБД не половину оперативы, а бОльшую ее часть.

Отключи своп вообще, если он тебе мешает.

думал над этим, но не решился использовать, т.к. не знаю как себя поведет сервер

Отлично себе поведёт, это же не винда.

Предположил, что причиной свопа явился кэш файловой системы.

Источник

How to clear the buffer/pagecache (disk cache) under Linux

Are you facing a performance issue and you suspect it might be related to cache usage? High cache usage should not normally cause performance issues, but it might be the root cause in some rare cases.

What is Memory Cache

In order to speed operations and reduce disk I/O, the kernel usually does as much caching as it has memory By design, pages containing cached data can be repurposed on-demand for other uses (e.g., apps) Repurposing memory for use in this way is no slower than claiming pristine untouched pages.

What is the purpose of /proc/sys/vm/drop_caches

Writing to /proc/sys/vm/drop_caches allows one to request the kernel immediately drop as much clean cached data as possible. This will usually result in some memory becoming more obviously available; however, under normal circumstances, this should not be necessary.

How to clear the Memory Cache using /proc/sys/vm/drop_caches

Writing the appropriate value to the file /proc/sys/vm/drop_caches causes the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.

1. In order to clear PageCache only run:

2. In order to clear dentries (Also called as Directory Cache) and inodes run:

Читайте также:  Macbook linux and windows

3. In order to clear PageCache, dentries and inodes run:

Running sync writes out dirty pages to disks. Normally dirty pages are the memory in use, so they are not available for freeing. So, running sync can help the ensuing drop operations to free more memory.

Page cache is memory held after reading files. Linux kernel prefers to keep unused page cache assuming files being read once will most likely to be read again in the near future, hence avoiding the performance impact on disk IO.

dentry and inode_cache are memory held after reading directory/file attributes, such as open() and stat(). dentry is common across all file systems, but inode_cache is on a per-file-system basis. Linux kernel prefers to keep this information assuming it will be needed again in the near future, hence avoiding disk IO.

How to clear the Memory Cache using sysctl

You can also Trigger cache-dropping by using sysctl -w vm.drop_caches=[number] command.

1. To free pagecache, dentries and inodes, use the below command.

2. To free dentries and inodes only, use the below command.

3. To free the pagecache only, use the below command.

Источник

Отключить linux чтения и записи кэша файлов на разделе

Как отключить кэш файлов linux на XFS-разделе (оба читают запись).

У нас есть раздел xfs над аппаратным RAID, который хранит наши RAW HD видео.
Большинство побегов 50-300gb каждый так Кэш linux имеет скорость попадания 0.001%.

Я попробовал опцию синхронизировать, но он по-прежнему заполняет кэш, когда copinging файлов.

(около 30x за съемки: P)

/ dev / sdb1 / видео XFS sync, noatime, nodiratime, logbufs=8 0 1

Я запускаю debian lenny, если это помогает.

4 ответов

существует решение, которое идеально подходит для вашего случая использования:http://code.google.com/p/pagecache-mangagement/

после проверки исходного кода:

затем, вы можете начать любое приложение, которое вы хотите с

и приложение не будет заполнить ваши кэши!

nocache инструмент предназначен для аналогичной цели: предотвращение определенных команд от порчи текущего буферного кэша. Просто вставить ./nocache команды:

обратите внимание, что аналогичный инструмент pagecache-mangagement-инструмент для управления использованием кэша страниц произвольных приложений, как отметил рметцгер, все еще находится в том же состоянии, что и в 2008 году. Конечно, это может быть хорошо или плохо, или смесь 🙂 у меня нет прямое сравнение, но у меня попросил nocache людей для одного

это нельзя сделать чисто. Если вам требуется для некоторых приложений, то они должны быть изменены, чтобы передать O_DIRECT их open(2) звонки.

man raw . С ним можно связать необработанное устройство, которое обходит кэш. Он имеет некоторые ограничения. Я использовал его только с CD / DVD-устройствами, поэтому я не знаю, насколько хорошо он будет работать для вас.

Источник

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