#!/bin/sh
#
#
TEST_LIST=test_list	# File containing unixperf tests to run
COUNT=200000		# Number of iterations within each unixperf test
REPEAT=2		# Each test is repeated two times.

TOOLPATH=/usr/stress/perf
export _SPEEDSHOP_LIBSS_PATH=$TOOLPATH
export LD_LIBRARY_PATH=$TOOLPATH
if [ `expr "$PATH" : ".*$TOOLPATH"` -eq 0 ]; then
	export PATH=$PATH:$TOOLPATH
fi

#
# Check that all tools are visible
#
cant_find=""
for bin in prfstat prfld kernprof rtmond rtmon-client ssrun prof; do
	if  ! which $bin >/dev/null || ! [ -x `which $bin` ]; then
		cant_find="$cant_find $bin"
	fi
done
if [ "$cant_find" ]; then
	echo "$0: Can't find:$cant_find"
	exit 1
fi
KERNPROF=`which kernprof`

#
# Each of the following files are generated for each of the tests run.
#
PRFOUT=prof.out		# Output after running through prof
UPOUT=unixperf.out

#
# Process input args.
#
if [ "$1" = "" ]
then
	echo "usage: $0 <unix_pathname> <output_dir> [<parallelism>]"
	exit
else
	UNIX=$1
fi
if [ "$2" = "" ]
then
	echo "usage: $0 <unix_pathname> <output_dir> [<parallelism>]"
	exit
else
	OUTDIR=$2
fi
echo Unix pathname is $UNIX
echo Output directory is $OUTDIR
echo Running tests specified by $TEST_LIST
if [ "$3" = "" ]; then
	COPIES=1
else
	COPIES=$3
	echo Spawning $COPIES instances
fi

NPROC=`hinv -t cpu | wc -l`
NPROCRANGE=0-`expr $NPROC - 1`
echo Test machine has $NPROC processors

#
# Make the output directory.
#
if [ -r "$OUTDIR" ]
then
	echo Moving existing $OUTDIR directory to $OUTDIR.old
	if [ -r "$OUTDIR.old" ]
	then
		rm -rf "$OUTDIR.old"
	fi
	mv $OUTDIR $OUTDIR.old
fi
mkdir $OUTDIR
cp $TEST_LIST $OUTDIR

#
# Load the Unix name list and start stack profiling and data collection.
#
prfld $UNIX 2>&1 >/dev/null
if ! ps -ale | grep -q rtmond; then
	rtmond
fi
prfstat stack 2>&1 >/dev/null 

#
# Run the tests.
#
grep -v "^#" $TEST_LIST | while read TEST args
do
	if [ "$args" = "" ]; then
		ARGS="-loop $COUNT -repeat $REPEAT"
	else
		ARGS=$args
	fi
	echo `date "+%H:%M:%S"` "Running $TEST ($ARGS) test..."
	mkdir $OUTDIR/$TEST
	sync;sync		# strive for reproducibility
	rtmon-client -h `hostname` -f $OUTDIR/$TEST/rtmon -p $NPROCRANGE -m 0x80 &
	rtmod_cli_pid=$!
	i=$COPIES
	(   # Spawn copies from a sub-shell.
	    while [ $i -gt 0 ]; do 
		/usr/stress/unixperf -$TEST $ARGS >> $OUTDIR/$TEST/$UPOUT &
		i=`expr $i - 1`
	    done
	    wait
	)
	kill -INT $rtmod_cli_pid
done
echo `date "+%H:%M:%S"` ...tests done, post-processing...

#
# Do speedshop post-processing of the stack data.
#
grep -v "^#" $TEST_LIST | while read TEST ARGS
do
	cd $OUTDIR/$TEST
	ssrun -usertime $KERNPROF -f rtmon.*
	prof -gprof $UNIX kernprof.usertime.* > $PRFOUT
	rm rtmon.* kernprof.usertime.*
done
echo `date "+%H:%M:%S"` ...done
