-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathhaos-swapfile
More file actions
executable file
·66 lines (54 loc) · 2.09 KB
/
haos-swapfile
File metadata and controls
executable file
·66 lines (54 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/bin/sh
set -e
size2kilobytes() {
bytes="$(echo "$1" | awk \
'BEGIN{IGNORECASE = 1}
function tobytes(n,b,p) {printf "%u\n", n*b^p/1024}
/[0-9]B?$/{tobytes($1, 1, 0); next};
/K(i?B)?$/{tobytes($1, 2, 10); next};
/M(i?B)?$/{tobytes($1, 2, 20); next};
/G(i?B)?$/{tobytes($1, 2, 30); next};
{print -1}')"
echo "$bytes"
}
if [ -f /etc/default/haos-swapfile ]; then
# shellcheck disable=SC1091
. /etc/default/haos-swapfile
fi
SWAPFILE="/mnt/data/swapfile"
# Swap size in kilobytes (as it's also what meminfo shows)
SWAPSIZE="$(size2kilobytes "${SWAPSIZE}")"
SWAPSIZE_TOLERANCE=0
if [ -z "${SWAPSIZE}" ] || [ "${SWAPSIZE}" = "-1" ]; then
# Default to 33% of total memory
SWAPSIZE="$(awk '/MemTotal/{ print int($2 * 0.33) }' /proc/meminfo)"
echo "[INFO] Using default swapsize of 33% RAM (${SWAPSIZE} kB)"
SWAPSIZE_TOLERANCE=$((32*1024)) # allow for 32MB fluctuations
fi
# Swap space in 4k blocks
SWAPSIZE_BLOCKS=$((SWAPSIZE / 4))
if [ "${SWAPSIZE_BLOCKS}" -lt 10 ]; then
echo "[INFO] Requested swap size smaller than 40kB, disabling swap"
if [ -f "${SWAPFILE}" ]; then
echo "[INFO] Removing existing swapfile"
rm -f "${SWAPFILE}"
fi
exit 0
fi
CURRENT_SIZE="$([ -f "${SWAPFILE}" ] && stat "${SWAPFILE}" -c '%s' || echo 0)"
if [ -s "${SWAPFILE}" ] && [ "${CURRENT_SIZE}" -ge $(((SWAPSIZE - SWAPSIZE_TOLERANCE) * 1024)) ] \
&& [ "${CURRENT_SIZE}" -le $(((SWAPSIZE + SWAPSIZE_TOLERANCE) * 1024)) ]; then
echo "[INFO] Swapfile already exists with size ${CURRENT_SIZE} bytes"
elif [ ! -s "${SWAPFILE}" ] || [ "${CURRENT_SIZE}" -ne $((SWAPSIZE_BLOCKS * 4096)) ]; then
# Check free space (in 4k blocks)
if [ "$(stat -f /mnt/data -c '%f')" -lt "${SWAPSIZE_BLOCKS}" ]; then
echo "[ERROR] Not enough space to allocate swapfile"
exit 1
fi
echo "[INFO] Creating swapfile of size ${SWAPSIZE} kB (rounded to ${SWAPSIZE_BLOCKS} blocks)"
umask 0077
dd if=/dev/zero of="${SWAPFILE}" bs=4k count="${SWAPSIZE_BLOCKS}"
fi
if ! swaplabel "${SWAPFILE}" > /dev/null 2>&1; then
/usr/lib/systemd/systemd-makefs swap "${SWAPFILE}"
fi