#!/bin/sh
#
# Reproduce qemu slowdown bug
#
# Prerequisite packages:
#
#   git-base
#   glib2
#   gmake
#   pkgconf
#   python27
#   wget
#

# qemu git revisions to compare
revs="21a03d17f2edb1e63f7137d97ba355cc6f19d79f 05e514b1d4d5bd4209e2c8bbc76ff05c85a235f3"

set -ex

# Create directories for logs
test -d buildlog || mkdir buildlog
test -d runlog || mkdir runlog
test -d bin || mkdir bin

# Find the number of CPUs
case $(uname -a) in
    NetBSD*) ncpu=$(sysctl -n hw.ncpu) ;;
    *)       ncpu=$(grep -c ^processor /proc/cpuinfo) ;;
esac
export ncpu

# Check out the qemu sources
test -d qemu || git clone git://git.qemu.org/qemu.git

# Build qemu binaries for the revisions of interest
for rev in $revs
do
    test -f bin/qemu-system-x86_64.$rev ||
    (
	cd qemu
	git checkout $rev
	git clean -q -d -x -f

	(
	    case $(uname -a) in
		NetBSD*)
		    platform_configure_args="--python=/usr/pkg/bin/python2.7"
		    make="gmake"
		    ;;
		*)
		    platform_configure_args=""
		    make="make"
		    ;;
	    esac

	    sh configure --disable-sdl --target-list=i386-softmmu,x86_64-softmmu,sparc-softmmu $platform_configure_args
	    time $make -j$ncpu # CFLAGS="-g -O2"
	) >../buildlog/$rev.log 2>&1 || { tail ../buildlog/$rev.log; false; }

        cp x86_64-softmmu/qemu-system-x86_64 ../bin/qemu-system-x86_64.$rev
    )
done
    
# Get a NetBSD image that runs the ATF tests and then powers off
image=NetBSD-6.0.1-i386-test.img
test -f $image || ( wget http://www.gson.org/bugs/qemu/${image}.gz && gunzip ${image}.gz )

image=./NetBSD-6.0.1-i386-test.img

# Build a program for generating CPU load

cat >load.c <<EOF
int main(int argc, char **argv) {
    for (;;)
        ;
}
EOF
cc load.c -o load

# Start the CPU load
: >load.pids
(
    # Two processes per CPU
    for i in $(seq $ncpu) $(seq $ncpu)
    do
	nice ./load & echo $! >>load.pids
    done
)

# Kill the CPU load on exit
trap "kill $(cat load.pids | tr '\n' ' ')" 0

# Run the test for each qemu revision
for rev in $revs
do
    /usr/bin/time -p bin/qemu-system-x86_64.$rev -L ./qemu/pc-bios -m 128 -nographic -snapshot -hda $image >runlog/log.$rev 2>&1
done

# Report the results
set +x
for rev in $revs
do
    echo $rev
    tail runlog/log.$rev | tr -d '\r' | egrep '^real|^user|^sys'
done
