LLI Wiki — My Digital Knowledge Base

Linux: clear page cache and swap, monitor swap usage

Drop the page cache, dentries and inodes, reset swap, schedule the cleanup and monitor swap usage per process.

Linux uses free memory for the page cache, dentries and inodes, and can move inactive pages to swap. The kernel reclaims cache automatically when needed, so dropping caches is mainly useful for testing or troubleshooting. The commands below drop the caches, reset swap and show which processes use swap.

Drop the caches

Run sync first to write dirty pages to disk, then write a value to /proc/sys/vm/drop_caches as root:

Value What is dropped
1 Page cache only
2 Dentries and inodes
3 Page cache, dentries and inodes
sync; echo 1 > /proc/sys/vm/drop_caches

Clear the RAM cache and swap

This drops the caches, then turns swap off and on again so that swapped pages are moved back to RAM:

sudo su root -c "echo 3 > /proc/sys/vm/drop_caches && swapoff -a && swapon -a && printf '\n%s\n' 'Ram-cache and Swap Cleared'"

swapoff -a needs enough free RAM to hold every swapped page. Without it, the command can fail or make the system very slow.

Schedule the cleanup with cron

Create a script:

#!/bin/bash
# echo 3 is used here; echo 1 is recommended in production
sync
echo 3 > /proc/sys/vm/drop_caches

Make it executable and add it to the crontab:

chmod 755 /path/to/clearcache.sh
crontab -e

The following crontab line runs the script every day at 02:00:

0 2 * * * /path/to/clearcache.sh

Monitor swap usage per process

List the processes sorted by swap usage (in kB), largest first, and show the top 10:

for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | head -n 10

The output lists the process name followed by its swap size, for example mysqld 2260 kB.

See also: How to find which process is using swap.

atop logs

atop stores daily logs that can be replayed to review past memory and swap usage:

atop -r /var/log/atop/atop_YYYYMMDD

High memory usage on a VMware guest

If a VM shows high memory use but no process accounts for it, check the memory reclaimed by the balloon driver:

vmware-toolbox-cmd stat balloon

The result is given in MB, for example 3264 MB. See also High memory usage but no process is using it.

Notes

Mastodon LLIMastodon SocialFosstodon