The Linux kernel uses unused main memory as a cache to keep page cache, filesystem dentries and inodes. The use of the cache or buffer memory accelerates access to files stored on non volatile storage such as hard disks. The cached items can be cleared from memory by sending a signal to the Linux kernel using the /proc
filesystem or the sysctl
command.
There are 2 main types of cached items – page cache and slab objects (filesystem dentries and inodes). To free the page cache:
1 |
# echo 1 > /proc/sys/vm/drop_caches |
To free reclaimable slab objects (includes dentries and inodes):
1 |
# echo 2 > /proc/sys/vm/drop_caches |
To free both page cache and slab objects:
1 |
# echo 3 > /proc/sys/vm/drop_caches |
This is a non-destructive operation and dirty objects are not freed. To increase the amount of released memory, we can try to minimise the number of dirty objects by running the sync
command prior to writing to /proc/sys/vm/drop_caches
. So, to free both page cache and slab objects after flushing file system buffers, include the sync
command at the beginning.
1 |
# sync && echo 3 > /proc/sys/vm/drop_caches |
The sysctl
utility can also be used instead of writing to the /proc
filesystem. You will just need to set the vm.drop_caches
kernel parameter accordingly.
1 |
# sync && sysctl vm.drop_caches=3 |
The drop_caches
file cannot be used to control the various kernel cache types (page cache, dentries, inodes, etc…). So, if you write 1 to the file to clear the page cache, you are not telling the kernel to disable the use of page cache anymore. You are just telling the kernel to clear the page cache at the instant. The kernel will start reclaiming the memory and build the page cache again after the call to drop the cache has been completed.
The kernel log files may contain informational messages whenever the parameter is changed.
1 2 3 |
# dmesg | grep drop_caches [ 98.273329] sysctl (2109): drop_caches: 1 [ 1462.707002] bash (2093): drop_caches: 3 |
1 2 3 |
# cat /var/log/kern.log | grep drop_caches Nov 15 08:26:21 linux kernel: [ 98.273329] sysctl (2109): drop_caches: 1 Nov 15 08:49:06 linux kernel: [ 1462.707002] bash (2093): drop_caches: 3 |
To disable such logs, set bit 3 (or echo 4) and write to drop_caches.
1 |
# echo 4 > /proc/sys/vm/drop_caches |
Based on the current kernel source code found in drop_caches.c, after disabling the logs, you will not be able to enable the logs again unless the system is restarted.
Use of this feature can cause performance problems. Since it discards cached objects, it may cause a significant increase in I/O operations and CPU cycles to recreate the dropped objects, especially if they were under heavy use. Because of this, use outside of a testing or debugging environment is not recommended. Do not use this feature unless you know what you are doing.