Dropping the disk cache in Linux
Tagged:  •    •    •  

In Linux the (physical) memory is not only a place for processes to dump their data onto. It also acts as an extra layer between the processes in memory and relatively slow hard disks. Free space in RAM will be filled with data from the harddisk, so they are quickly accessible whenever a process wants data which was retrieved earlier from disk. This greatly improves the performance of your system.

However, sometimes this is undesirable. For example if you want to measure the performance of an application reading files from disk. If you run that application twice, you'll see that the second invocation shows a (much) better performance because data was still in the disk cache from the first invocation.

Since Linux 2.6.16, an interface is provided to wipe the disk cache. Enter /proc/sys/vm/drop_caches.

When you have root access, you can pass three different values to this (virtual) file:

  • # echo 1 > /proc/sys/vm/drop_caches

    Erase the page cache. This part of the disk cache contains actual file contents.

  • # echo 2 > /proc/sys/vm/drop_caches

    Erase the inode and dentry caches (short: dcache). An inode is the data structure used by the kernel to represent a file. It does not contain the file's data, only attributes like the name, dates and permissions. A dentry is a data structure to represent a file path, which maps to an actual file.

  • # echo 3 > /proc/sys/vm/drop_caches

    Erase both the page cache, as the inode cache and dcache.

You may notice that there's still a little of cache left after passing the value 3 to the drop_caches file. This is because there's some dirty data in the cache which cannot be freed at that moment. Use the sync(1) before emptying the caches in order to make the caches completely empty.

Thanks

I'm working on a microcontroller project that looks like a USB mass storage device to linux. My micro code writes files 'behind the back' of the linux and I needed a way to re-read the fat table. You're posting here is exactly what I needed, thanks!