summaryrefslogtreecommitdiff
path: root/zram-swap
blob: 90bda43d39b13878718cd683fa94c6bd61091e44 (plain)
    1 #!/usr/bin/env bash
    2 # Zram-swap automatically compresses half of ram for swap usage
    3 # Copyright (C)  2021  Aaron Ball <nullspoon@oper.io>
    4 #
    5 # This program is free software: you can redistribute it and/or modify
    6 # it under the terms of the GNU General Public License as published by
    7 # the Free Software Foundation, either version 3 of the License, or
    8 # (at your option) any later version.
    9 #
   10 # This program is distributed in the hope that it will be useful,
   11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
   12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   13 # GNU General Public License for more details.
   14 #
   15 # You should have received a copy of the GNU General Public License
   16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
   17 
   18 set -euo pipefail
   19 export IFS=$'\n\t'
   20 
   21 RUNFILE='/var/run/zram-swap'
   22 MEMTOTAL=$(sed -n 's/^MemTotal: \+\([0-9]\+\) kB/\1/p' /proc/meminfo)
   23 
   24 status() {
   25   if [ -f "${RUNFILE}" ]; then
   26     zramctl $(cat "${RUNFILE}")
   27   else
   28     printf 'stopped\n'
   29   fi
   30 }
   31 
   32 start() {
   33   [ $(status) != 'stopped' ] && printf 'Already running\n' && return 1
   34 
   35   local unused="$(zramctl -f)"
   36   # Size is 1/2 of total memory
   37   local size="$(( MEMTOTAL / 1024 / 2 ))M"
   38   # Thread count is half of cpu
   39   local threads="$(( $(nproc) / 2 ))"
   40 
   41   # Make sure the zram module is loaded
   42   modprobe zram
   43 
   44   # Create the zram device
   45   zramctl "${unused}" -s "${size}" -t "${threads}"
   46   mkswap "${unused}"
   47   swapon "${unused}"
   48   printf '%s\n' "${unused}" > "${RUNFILE}"
   49 }
   50 
   51 stop() {
   52   [ $(status) = 'stopped' ] && printf 'Already stopped\n' && return 1
   53   local zram="$(cat ${RUNFILE})"
   54   swapoff ${zram}
   55   zramctl -r "${zram}"
   56   rm -f "${RUNFILE}"
   57   # Note: We do not want to try to remove the zram kernel module in case other
   58   # devices are in use.
   59 }
   60 
   61 main() {
   62   if [ ${UID} -ne 0 ]; then
   63     printf 'Must be run as root\n' >&2
   64     return 1
   65   fi
   66 
   67   if [ "${1:-}" = 'start' ]; then
   68     start
   69   elif [ "${1:-}" = 'stop' ]; then
   70     stop
   71   elif [ "${1:-}" = 'status' ]; then
   72     status
   73   else
   74     printf 'usage: %s [start|stop|status]\n' "${0}"
   75     exit 1
   76   fi
   77 }
   78 
   79 main ${@}

Generated by cgit