Why does Linux write to swap space even if the system has available storage while copying a big file to somewhere

swap

I have been noticing that if I copy a file to some storage device (the system's HDD, SSD, or to a thumbdrive) a small amount of data (20 – 30 MB) is written to the swap space – and the count increases. Yes, even the systems have available RAM.

Writing to the swap space makes the device very slow. Thrashing is the obvious case.

If I turn swap off before copying, the files gets copied just fine!

Here's a screenshot:

enter image description here

I am copying a big file to /dev/sda2. I have available RAM, yet some data is always written to the swap. This behaviour is same across all the devices I own, and the devices I got time to play around.

I tried changing the swappiness with this command command:

sysctl vm.swappiness=n # n for a value from 0..100

Tried turning the swappiness to 0, and also tried turning the swappiness to 100. The behaviour doesn't change. Any system monitor says I am having a good amount of available RAM. It still writes data to the swap.

Best Answer

In general, that behavior is application-dependent on whether the copying application gives proper indication to the kernel as to how it will read the file that it will copy.

In your case I see your file is just slightly bigger than your overall memory, so it might be that your GUI’s file manager requests a full generic mmap on the file instead of copying it in chunks.

Try copying it with cp from a terminal window. The cp command diligently gives indications to the kernel and copies the file in whatever chunks it detects to be the most appropriate for the system. You might still see the cache filling the memory but swapping should not be triggered, if not for just a bunch of bytes due to a spike in memory pressure.

Related Question