When Linux needs to find RAM to store something, it looks for the pages in RAM that have been unused for the longest time. If these pages belong to files, they're freed. If these pages are process memory, they're moved to swap.
Linux doesn't know what pages are going to be used soon, and doesn't know what pages are going to be needed quickly (e.g. for interactive programs to be reactive). I don't think there's any way to give a priority for a particular process to stay in RAM. Pages can be locked to RAM (this requires root or the appropriate capability), but locking stuff to RAM is not recommended since it makes less room for the rest.
You can force a specific process to be loaded into RAM by reading its memory — see my unswap
script.
You can reduce the propensity to swap by setting the vm.swappiness
sysctl parameter. However, beware that reducing swappiness is by no means guaranteed to make your system snappier. There's no miracle: if your system swaps less, it spends more time loading data from files (such as program code).
If you have a relatively large amount of memory, one setting that I've found not to be well-tuned by default in 3.0–3.16+ kernels is another vm sysctl parameter: vm.vfs_cache_pressure
. This parameter is somewhat similar to swappiness, but concerns kernel objects, especially the inode and dentry cache. Increasing the value effectively reduces the amount of memory devoted to this cache. You can see how much memory is used by the inode and dentry cache with slabtop
or with
</proc/slabinfo awk '{print $1, $3*$4}' |sort -k2n | tail
If you find your system sluggish in the morning, this may be because nightly cron jobs such as updatedb
filled the memory with inode cache entries. Try something like sysctl vm.swappiness=500
. You can do a one-time flush of the cache with echo 2 >|/proc/sys/vm/drop_caches
(don't do this on a regular basis as it can kill performance).