How to free cached memory and dirty pages in Linux
When an application reads a file, Linux kernel keeps cache of file contents in memory. The Linux keeps the cache even after application closes the file to improve performance for further read operations of same file. This cache is freed slowly as when Linux finds no free memory during it operation.
Similarly when an application write a file, Linux doesn’t write the contents to disk immediately and waits for some time before it actually writes to the disk. These buffers are called dirty buffers.
User can manually initiate the writing of dirty buffers to disk executing “sync” command few times.
From kernel version 2.6.16 onwards, Linux provided a PROC based mechanism to free up such cached memory. Linux provides a file /proc/sys/vm/drop_caches which can be written with a number to free up cached memory.
To free page cache:
[root@techpulp ~]# echo 1 > /proc/sys/vm/drop_caches
To free dentries and inodes:
[root@techpulp ~]# echo 2 > /proc/sys/vm/drop_caches
To free page cache, dentries and inodes:
[root@techpulp ~]# echo 3 > /proc/sys/vm/drop_caches
This can be combined with “sync” command to fully free up diretry buffers.
This behaviour does not necessarily slow the system as Linux frees up such memory on demand. It should not really make much difference for a desktop user. However in case of embedded systems, it takes most of the memory present in the system as there would be lot of files read during system boot up. This also causes memory fragmentation as Linux frees up this memory on demand. In such cases, Linux fails to allocate relatively big chunks of contiguous memory though it shows enough free memory. One way to get rid of such problem is to free up the page cache right after the system comes up. However if the applications running the embedded device are not properly designed and allocates and frees small chunks of memory more frequently, memory fragmentation is inevitable.
For Linux 2.4.x kernels, Linux has an internal function “free_more_memory” which can be called multiple times to achieve similar effect. However that function is not exported by Linux kernel. So kernel needs to be recompiled.
Recent Comments