My original problem with swap(piness) was that it was swapping too often (even with swappiness=1
! ).
I also thought 0 would turn off the swappiness - which was a misconception,
Swap still works even if you set sudo sysctl -w vm.swappiness=0
! :-)
(To set permanently, edit /etc/sysctl.conf
and add/update vm.swappiness = 0
- for GUI text editor I recommend a "linux notepad" "gedit", you can then do sudo gedit /etc/sysctl.conf
)
Only with swappiness 0
it started to behave more like one would expect (swapping starting at about 98% of RAM full), however I am still experiencing one more problem - and that when enough RAM is actually freed again, the swap does not automatically go back to RAM, not even over time.
Of course you could manually do sudo swapoff -a; sudo swapon -a
every time which turns off the swap which ultimatelly forces the swap to be emptied out to the RAM and then swap gets started again.
However that's unhandy for 2 reasons a) the swap gets turned off for a moment b) it's a manual extra checking/running
Is there a way how to achieve this in some, preferably "native", way automatically?
Afaik, no setting is available to change the tendency to return swapped pages to RAM. You could, if you wish that, work with a script that checks RAM and SWAP, and turns swap off/back on when it is safe. On a memory limited system, that may be never: the only option there to clear swapped memory is to close down processes that own them.
It is not clear what the benefits will be for you to immediately move SWAP back to RAM whenever it is possible. Linux automatically manages the swap. If it does not release the occupied swap, it is because that swapped memory is not needed and thus can happily remain on the disk until needed. This way, ram and processor time are spared for use of the applications where it matters. Your disk is spared in that swap operations are minimized.
How fast swap kicks in depends on your
swappiness
setting, but also depends on the amount of RAM you have. You did not mention the amount of RAM you have. Based on your experience, one can assume that either you have little RAM (perhaps 2 GB or less), or that you are using specific applications that have unusual memory needs.In the first case, you may need to change your computer use habits to account for the limitations of low RAM, until you can upgrade physical RAM. Swap is in no way a replacement of RAM, it is only a trick to extend it somewhat and allow somewhat more on a RAM limited system.
In the second case, then leave it alone: your system behaves optimally, swapping out unused RAM to leave it to your memory hogging work.
If you must do it, then
swapoff
is the way to go. You can automate this process by implementing a bash script like so:Run the script with
sudo bash scriptfile.sh
or add asystemd
service to run the script automatically when the system starts.