memory empty but swap full?

I'm on Ubuntu mate 21.04 with swappiness set to default 60. Why is the system predominantly using the swap if there is ~55 GB of empty memory? The swap file is on nvme drive but memory is still faster so why with the default swappiness it is not being used more?

enter image description here


Solution 1:

Indeed, a lot of swap is used despite low memory use and plenty of free memory. The current status depends on the history of use, though. If earlier in the session, memory was heavily used, unused pages would be swapped to disk. These pages will not be removed from swap, unless they are needed again. If not needed, they just will remain in swap even if a lot of free memory has become available again.

Solution 2:

Historically, a 2G /swapfile has never been enough.

Let's increase your /swapfile from 2G to 4G, and change your vm.swappiness value...

/swapfile

Note: Incorrect use of the rm and dd commands can cause data loss. Suggest copy/paste.

In the terminal...

sudo swapoff -a           # turn off swap
sudo rm -i /swapfile      # remove old /swapfile

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

sudo chmod 600 /swapfile  # set proper file protections
sudo mkswap /swapfile     # init /swapfile
sudo swapon /swapfile     # turn on swap
free -h                   # confirm 64G RAM and 4G swap

Edit /etc/fstab, using sudo -H gedit /etc/fstab or sudo pico /etc/fstab.

Confirm this /swapfile line in /etc/fstab... and confirm no other “swap” lines... use SPACES in this line... confirm NO TABS...

/swapfile  none  swap  sw  0  0

reboot                    # reboot and verify operation

vm.swappiness

Because you have so much RAM, set your vm.swappiness=10. This will reduce swapping on your configuration. It sounds like you know how to do this (edit /etc/sysctl.conf), but if not, please ask for further instructions.