#!/bin/sh
# Nothing should dirty the page cache when fs is frozen.
# sync should not block - it should find the page cache clean and return immediately
# Original mmapped part from Toshiyuki Okajima, sent on #ext4ml.

FS=ext4
gcc -o ./write ./write.c
dd if=/dev/zero of=/tmp/loop.$$ bs=1k seek=64k count=1 > /dev/null 2>&1
/sbin/mkfs.$FS -Fq /tmp/loop.$$
/sbin/losetup /dev/loop7 /tmp/loop.$$
mkdir -p mnt
mount -t $FS /dev/loop7 mnt
########################################################
## Test freeze followed by an immediate sync
dd if=/dev/zero of=mnt/file bs=4k count=100 > /dev/null 2>&1
/sbin/fsfreeze -f mnt
echo "testing freeze, sync"
echo "does fsfreeze really clean the page cache?"
sync
echo "sync is over - it did not deadlock with fsfreeze. Works correctly"
/sbin/fsfreeze -u mnt &
wait
echo "###########################"
########################################################
## Test freeze, mmapped write, sync , unfreeze in parallel
./write mnt/file &
pid=$!
# write 0
/bin/kill -SIGUSR1 $pid
echo "testing freeze, mmapped write, sync, unfreeze - in parallel"
/sbin/fsfreeze -f mnt &
# should not be able to write 1
/bin/kill -SIGUSR1 $pid &
echo "does fsfreeze really stop an mmapped write from happening?"
sync  &
/sbin/fsfreeze -u mnt 
echo -n "thawing of fs done too - it did not deadlock with sync - page" \
	" cache not dirtied"
/bin/kill -SIGTERM $pid
wait
echo "###########################"
#################################
## Test freeze, aio write, sync , unfreeze in parallel
echo "testing freeze, aio write, sync, unfreeze in parallel"
/sbin/fsfreeze -f mnt &
# dd must block as fs is frozen!
{
dd if=/dev/zero of=mnt/aio-writes bs=4k count=100 > /dev/null 2>&1 
}&
echo -n "does fsfreeze really stop an aio write from happening?"
echo " sync should wait on vfs_check_frozen when the page cache is dirty"
sync & 
/sbin/fsfreeze -u mnt 
echo -n "thawing of fs done too - it did not deadlock with sync - page" \
	" cache not dirtied"
wait
echo "###########################"
#################################
### Test read a file when the fs is frozen - test the touch_atime path
echo "Testing freeze, touch_atime, sync and unfreeze in parallel"
/sbin/fsfreeze -f mnt &
cat mnt/aio-writes & # this should ideally stop on the journal_start
#if this does not stop on the journal_start then the page cache is dirty. sync
# should hang on vfs_check_frozen
pid=$!
echo -n "does fsfreeze really stop an aio write from happening?"
echo " sync should wait on vfs_check_frozen when the page cache is dirty"
sync & 
pid2=$!
/sbin/fsfreeze -u mnt 
echo -n "thawing of fs done too - it did not deadlock with sync - page" \
	" cache not dirtied"
wait
echo "###########################"
#################################
exit 0
