How to clear Memory used by the Linux File Cache
- Glen
- Jan 11, 2022
- 2 min read
Updated: Jan 12, 2022
While it may appear that kernel file buffering/caching has consumed your Linux system available memory, generally, there is little need to clear the memory used by Linux Kernel caching.
It is normal (and beneficial) for the Kernel to use available memory for file cache, and the kernel will free that memory on demand when needed by running applications.
But there are times when you do want to manually clear the cache, I do this most often when:
Performance testing, there are times when you want to test the speed of an application managing/reading/writing data without the help of kernel file caching.
Development/Testing, otherwise the kernel may return cached data and file information having bypassed your application.
NFSv4 issues, NFSv4 clients cache based on ctime, sometimes the NFSv4 client shows old/incorrect information, clearing the cache on the NFS server can help to determine if it's a caching issue.
I'm sure there are many other times you need to do this, feel free to add them in the comments.
Three types of cached data
The Kernel caches three types of file data:
File data itself, known as the PageCache. This will normally consume the most amount of memory.
Filesystem Directory listings, known as dentries. Speeds up directory listings.
File Information, known as inodes. Contains the information returned by the stat command, such as file owner, basic permissions, file size, last access, modified and change times etc.
Clearing the cache
You can decide if you want to clear:
just the PageCache
just the dentries and the inodes
or all three.
Before you clear the cache you will likely want to flush any unwritten data held by the kernel to disks, this will ensure that the maximum memory is freed, this is simply done by running the sync command.
Clearing the cache is as simple as writing the option number which corresponds to the data types you want to be removed from the cache to the special file /proc/sys/vm/drop_caches.
The options are are:
1 = PageCache
2 = dentries and inodes
3 = PageCache, dentries and inodes
So to clear just the file data (PageCache), run:
sync; echo 1 > /proc/sys/vm/drop_caches
To clear just directory entries and file information (dentries and inodes), run:
sync; echo 2 > /proc/sys/vm/drop_caches
And to clear everything (PageCache, dentries and inodes), run:
sync; echo 3 > /proc/sys/vm/drop_caches
And remember that as soon as the cache has been cleared, the kernel will start to re-populate it.
About the Author
Glen Olsen has almost 30 years of expertise working with Linux & Unix systems, storage, network and security. Glen Olsen created, developed and maintains the Nexfs Linux FileSystem http://www.nexustorage.com
Connect with Glen Olsen on LinkedIn
Comments