stunpix

Персональный бортжурнал

Dropping caches in linux before going sleep

As you maybe know linux has a cache and it occupies unused RAM. This isn't a problem when you run linux on real h/w, but it could be a problem when linux runs in virtual machine (VM). Usually when you suspend VM it dumps all RAM used by guest OS to disk and VM doesn't distinguish what kind of memory it dumps, so caches are dumped also and they could be huge. This fact slowdowns VM suspending/resume time and impacts SSD lifetime by writing huge amount of data. The solution is: drop caches before suspending VMs. Here are how you can do that.

NOTE: This method applicable only for distros with systemd.

  1. Create file sudo nano /lib/systemd/system-sleep/dropcaches with following content:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    #!/bin/sh
    set -e
    
    _cache() {
        free -m | awk '{if ($1 == "Mem:") print $6;}'
    }
    
    case $1 in
        pre)
            _before=$(_cache)
            sync && echo 3 > /proc/sys/vm/drop_caches
            _after=$(_cache)
            echo "Dropped $(($_before-$_after)) Mb of caches..."
            ;;
    esac
    
  2. Make this file executable: sudo chmod a+x /lib/systemd/system-sleep/dropcaches.

  3. Add to ~/.bashrc (or ~/.bash_aliases): alias susp='systemctl suspend -i

If you're running some RAM-eating daemon (like DB) in VM you could add in case pre) a line that stops this daemon. Optionally you can add case post) to start this daemon back:

pre)
    ...
    systemctl stop daemond
    sync && echo 3 > /proc/sys/vm/drop_caches
    ...
    ;;
post)
    ...
    systemctl start daemond
    ....
    ;;

Now you can suspend your VM with susp command from terminal. Once you resume your VM, you can check how much caches were dropped last time using journalctl -ru systemd-suspend | grep Dropped command.

Happy using!

Коментарии