« Back to Memory

Swap memory information

Physical RAM is used to store information. Linux divides this RAM into smaller chunks, named memory pages. When there is no more normal memory available, the Linux kernel might need to temporarily store information aside. This is called paging or swap space.

During the process of paging, memory pages will be moved from the RAM to the disk. This way memory is freed up for active processes, while older information is temporarily stored on the disk. A disk is much slower than RAM, so typically you want to avoid paging as much as possible.

Swap size and usage

Basic information about the size of the swap is available via free. It also a quick overview of memory details. The source of the information is the file /proc/meminfo.

# free
               total        used        free      shared  buff/cache   available
Mem:          980412      169752      211584         988      599076      661372
Swap:        1959932       42216     1917716

Slightly more detailed information can be retrieved using the vmstat command.

# vmstat --stats | grep swap
       529192 K swap cache
      1959932 K total swap
        42216 K used swap
      1917716 K free swap
        18986 pages swapped in
        32724 pages swapped out

Which processes are using the most swap?

To see which processes are using swap, consider using smem to retrieve the details.

smem --columns="pid swap"

An alternative is to do it without, and select a process that has high memory usage (e.g. from top output). Retrieve the pid with pidof or pgrep, then look in the ‘/proc/PID/status’ file.

To automate this step, use a script like this:

for I in $(pidof firefox); do awk -v PID=${I} '/^VmSwap/{print PID"="$2$3}' /proc/${I}/status; done

When in doubt what processes are using swap, we can retrieve the output for all processes.

awk '/Name|VmSwap/{printf (/Name/?"\n":" ")$2$3} END{ print "\n"}' /proc/*/status \
  | awk 'NF>1' \
  | sort --human-numeric-sort --key=2 --reverse \
  | column --table

This command retrieves the lines with Name or VmSwap and replaces the line feeds, so that we can print the name, and the size on one line. Some kernel processes will not have a VmSwap value, so those entries we filter out by only showing the entries that have two fields (name and swap size). Finally we sort on the second column, and present a nice table.

Relevant commands in this article

Like to learn more about the commands that were used in this article? Have a look, for some there is also a cheat sheet available.

Feedback

Small picture of Michael Boelen

This article has been written by our Linux security expert Michael Boelen. With focus on creating high-quality articles and relevant examples, he wants to improve the field of Linux security. No more web full of copy-pasted blog posts.

Discovered outdated information or have a question? Share your thoughts. Thanks for your contribution!

Mastodon icon