#!/bin/sh
# The disk's swap partition: fstab's swap entry (noauto: this script activates it)
# PS3_VSWAP_DM=1 in /etc/default/ps3-vswap (off when unset): the VRAM swap's backing is a device-mapper
# device, ps3vswap-back (dm-linear over the partition's first vswap_size_mb, all the VRAM swap uses),
# instead of the partition itself. The backing is set once per boot, but the table under it can be
# switched while the VRAM swap is off: the bench's SSD swap arm (bench/harness/ssd-arm.sh,
# docs/GAMEOS-HDD.md "Test drive, Phase A"). Without dmsetup or dm-mod, or if the device fails,
# the partition as before. PS3_VSWAP_ROOT: a prefix for /etc and /sys (host tests only).
R=${PS3_VSWAP_ROOT:-}
dev=$(awk '$3 == "swap" && $1 !~ "zram" { print $1; exit }' $R/etc/fstab)
[ -n "$dev" ] || exit 0
part=$(findfs "$dev" 2>/dev/null || echo "$dev")
[ -b "$part" ] || exit 0
grep -q "^$part " /proc/swaps && swapoff "$part"
B=$R/sys/block/ps3vswap0/backing
PS3_VSWAP_DM=0
[ -r $R/etc/default/ps3-vswap ] && . $R/etc/default/ps3-vswap
back=$part
if [ "$PS3_VSWAP_DM" = 1 ] && [ -e $B ] && [ -z "$(cat $B)" ]; then
	mb=$(cat $R/sys/module/ps3rsx/parameters/vswap_size_mb 2>/dev/null || echo 1024)
	n=$(blockdev --getsz "$part" 2>/dev/null || echo 0)
	[ "$n" -gt $((mb * 2048)) ] && n=$((mb * 2048))
	modprobe dm-mod 2>/dev/null
	if [ "$n" -gt 0 ] && command -v dmsetup >/dev/null &&
	   dmsetup create ps3vswap-back --table "0 $n linear $part 0" 2>/dev/null; then
		back=/dev/mapper/ps3vswap-back
	fi
fi
if [ -e $B ] && [ -z "$(cat $B)" ]; then
	if ! echo "$back" > $B 2>/dev/null && [ "$back" != "$part" ]; then
		dmsetup remove ps3vswap-back 2>/dev/null	# the device-mapper backing refused: the partition
		back=$part
		echo "$back" > $B 2>/dev/null
	fi
	if [ "$(cat $B)" = "$back" ]; then
		mkswap /dev/ps3vswap0 >/dev/null
		exec swapon -p 300 --discard=pages /dev/ps3vswap0
	fi
fi
# no VRAM swap: the partition itself (its header is gone once VRAM swap had it: swap
# contents never outlive a boot anyway)
swapon -p 200 "$part" 2>/dev/null || { mkswap "$part" >/dev/null && swapon -p 200 "$part"; }
