Linux Swap – How to Read Swap Back into Memory

kernellinuxmemoryswapsysfs

The Linux kernel swaps out most pages from memory when I run an application that uses most of the 16GB of physical memory. After the application finishes, every action (typing commands, switching workspaces, opening a new web page, etc.) takes very long to complete because the relevant pages first need to be read back in from swap.

Is there a way to tell the Linux kernel to copy pages from swap back into physical memory without manually touching (and waiting for) each application? I run lots of applications so the wait is always painful.

I often use swapoff -a && swapon -a to make the system responsive again, but this clears the pages from swap, so they need to be written again the next time I run the script.

Is there a kernel interface, perhaps using sysfs, to instruct the kernel to read all pages from swap?

Edit: I am indeed looking for a way to make all of swap swapcached. (Thanks derobert!)

[P.S.
serverfault.com/questions/153946/… and serverfault.com/questions/100448/… are related topics but do not address the question of how to get the Linux kernel to copy pages from swap back into memory without clearing swap.]

Best Answer

Based on memdump program originally found here I've created a script to selectively read specified applications back into memory. remember:

#!/bin/bash
declare -A Q
for i in "$@"; do
    E=$(readlink /proc/$i/exe);
    if [ -z "$E" ]; then
        #echo skipped $i;
        continue;
    fi
    if echo $E | grep -qF memdump; then
        #echo skipped $i >&2;
        continue;
    fi
    if [ -n "${Q[${E}]}" ]; then
        #echo already $i >&2;
        continue;
    fi
    echo "$i $E" >&2
    memdump $i 2> /dev/null
    Q[$E]=$i
done | pv -c -i 2 > /dev/null

Usage: something like

# ./remember $(< /mnt/cgroup/tasks )
1 /sbin/init
882 /bin/bash
1301 /usr/bin/hexchat
...
2.21GiB 0:00:02 [ 1.1GiB/s] [  <=>     ]
...
6838 /sbin/agetty
11.6GiB 0:00:10 [1.16GiB/s] [      <=> ]
...
23.7GiB 0:00:38 [ 637MiB/s] [   <=>    ]
# 

It quickly skips over non-swapped memory (gigabytes per second) and slows down when swap is needed.

Related Question