blob: 0041234fc803006401d0da24ec7e6bd75d34537f (
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 # Create the zram device
42 zramctl "${unused}" -s "${size}" -t "${threads}"
43 mkswap "${unused}"
44 swapon "${unused}"
45 printf '%s\n' "${unused}" > "${RUNFILE}"
46 }
47
48 stop() {
49 [ $(status) = 'stopped' ] && printf 'Already stopped\n' && return 1
50 local zram="$(cat ${RUNFILE})"
51 swapoff ${zram}
52 zramctl -r "${zram}"
53 rm -f "${RUNFILE}"
54 }
55
56 main() {
57 if [ ${UID} -ne 0 ]; then
58 printf 'Must be run as root\n' >&2
59 return 1
60 fi
61
62 # Make sure the zram module is loaded
63 modprobe zram
64
65 if [ "${1:-}" = 'start' ]; then
66 start
67 elif [ "${1:-}" = 'stop' ]; then
68 stop
69 elif [ "${1:-}" = 'status' ]; then
70 status
71 else
72 printf 'usage: %s [start|stop|status]\n' "${0}"
73 exit 1
74 fi
75 }
76
77 main ${@}
|