How to purge disk I/O caches on Linux?

Solution 1:

Sounds like you want the sync command, or the sync() function.

If you want disk cache flushing: echo 3 | sudo tee /proc/sys/vm/drop_caches

Solution 2:

You can do it like this:

# sync # (move data, modified through FS -> HDD cache) + flush HDD cache
# echo 3 > /proc/sys/vm/drop_caches # (slab + pagecache) -> HDD (https://www.kernel.org/doc/Documentation/sysctl/vm.txt)
# blockdev --flushbufs /dev/sda
# hdparm -F /dev/sda

# NEXT COMMAND IS NOT FOR BENCHMARKING:
# should be run before unplug, flushes everything possible guaranteed.
# echo 1 > /sys/block/sdX/device/delete

You may use strace to see that these are three different syscalls

Also, it may be desirable to turn off HDD cache using hdparm, not sure what thing you benchmarking.

In any way, you cannot prevent HDD to cache last 64/32/16 MB of recently used data. In order to kill that cache, just write some amount of zeroes (and flush) + read some unrelated place from HDD. This is required since cache may be divided to read-part and write-part. After that you can benchmark HDD.