#!/bin/bash

P=tlbflush-install
DEFAULT_VERSION=0
. $SHELLPACK_INCLUDE/common.sh
TIME_CMD=`which time`
if [ "$TIME_CMD" = "" ]; then
        TIMEFORMAT="%2Uuser %2Ssystem %Relapsed %P%%CPU"
        TIME_CMD="time"
fi

# Basic argument parser
TASKSET_SERVER=
TASKSET_CLIENT=
SERVERSIDE_COMMAND=none
SERVERSIDE_NAME=`date +%Y%m%d-%H%M-%S`

while [ "$1" != "" ]; do
	case "$1" in
	-v)
		VERSION=$2
		shift 2
		;;
	--serverside-command)
		SERVERSIDE_COMMAND=$2
		shift 2
		;;
	--serverside-name)
		SERVERSIDE_NAME=$2
		shift 2
		;;
	*)
		echo Unrecognised option: $1
		shift
	esac
done
if [ "$TASKSET_SERVER" != "" ]; then
	echo TASKSET_SERVER: $TASKSET_SERVER
	echo TASKSET_CLIENT: $TASKSET_CLIENT
fi
if [ -z "$VERSION" ]; then
	VERSION=$DEFAULT_VERSION
fi

mkdir -p $SHELLPACK_SOURCES/tlbflush-${VERSION}-installed
cd $SHELLPACK_SOURCES/tlbflush-${VERSION}-installed || die Failed to create install directory
wget -O tlbflush.c.in "http://marc.info/?l=linux-kernel&m=133727348217113&q=raw" || die Failed to download source code

START_LINE=`grep -n ^---$ tlbflush.c.in | cut -f1 -d:`
END_LINE=`grep -n ^--$ tlbflush.c.in | cut -f1 -d:`
head -$((END_LINE-1)) tlbflush.c.in | tail -$((END_LINE-START_LINE-1)) | grep -v "define FILE_SIZE" > tlbflush.c

echo '--- tlbflush.c.orig	2013-12-15 11:05:08.813821030 +0000
+++ tlbflush.c	2013-12-15 11:04:46.504926426 +0000
@@ -67,13 +67,17 @@
 	char x;
 	int i, k;
 	int randn[PAGE_SIZE];
+	int count = 0;
 	
 	for (i=0;i<PAGE_SIZE; i++)
 		randn[i] = rand();
 
 	actimes = malloc(sizeof(long));
 
-	while (*threadstart == 0 )
+	while (*threadstart == 0) {
+		if (++count > 1000000)
+			break;
 		usleep(1);
+	}
 
 	if (d->rw == 0)
@@ -180,6 +181,7 @@
 	threadstart = malloc(sizeof(int));
 	*threadstart = 0;
 	data.readp = &p; data.startaddr = startaddr; data.rw = rw; data.loop = l;
+	sleep(1);
 	for (i=0; i< t; i++)
 		if(pthread_create(&pid[i], NULL, accessmm, &data))
 			perror("pthread create");
' | patch -p0 || die Failed to patch

gcc -DFILE_SIZE=$((128*1048576)) -g -O2 tlbflush.c -lpthread -o tlbflush || die Failed to build tlbflush binary

exit $SHELLPACK_SUCCESS
#### Description Alex Shis tlb range flush benchmark
#### Details tlbflush 32
