#!/bin/sh

modulename=taskmonitor
debugfsdir=/sys/kernel/debug/$modulename
file=${debugfsdir}/control

printf "%s" '
#include <math.h>
#include <stdlib.h>

int main() {
	double acc = 0;
	for (int i = 0; i < 1000000000; i++) {
		acc += sqrt((double)random());
	}
	return acc;
}
' > stress.c

if ! gcc -o stress stress.c -lm; then
	echo "failed to compile user program"
	echo "please contact lkp@os.rwth-aachen.de"
	exit 1
fi

./stress &
pid1=$!

./stress &
pid2=$!

./stress &
pid3=$!

./stress &
pid4=$!

if ! modprobe $modulename; then
	echo "Could not load module $modulename.ko!"
	exit 1
fi

if ! [ -f "$file" ]; then
	echo "control file not created!"
	echo "($file)"
	exit 1
fi


for pid in $pid1 $pid2 $pid3 $pid4; do
	if ! echo "$pid" > "$file"; then
		echo "error while using $file"
		exit 1
	fi
	if ! [ -f "${debugfsdir}/$pid" ]; then
		echo "file for $pid not created!"
		exit 1
	fi
	if ! echo "-$pid" > "$file"; then
		echo "error while using $file"
		exit 1
	fi
	if [ -f "${debugfsdir}/$pid" ]; then
		echo "file for $pid should be removed!"
		exit 1
	fi
	if ! echo "$pid" > "$file"; then
		echo "error while using $file"
		exit 1
	fi
done

ls -l /sys/kernel/debug/taskmonitor/

# The line below is executed by the LKP Maintainers CI. HIDDEN replaces the real value the CI uses.
# sleep HIDDEN

for pid in $pid1 $pid2 $pid3 $pid4; do
	output=$(grep -oP 'usr \K[0-9]+' "${debugfsdir}/$pid")
	nb=$(wc -l "${debugfsdir}/$pid" | cut -f 1 -d ' ')

	if [ -z "$nb" ]; then
		echo "nothing found!"
		exit 1
	fi
	# check that the number of lines produced is somewhat similar to the amount of seconds we slept
	# if [ "$nb" -ne HIDDEN ] && [ "$nb" -ne HIDDEN ] && [ "$nb" -ne HIDDEN ] ; then
	# 	echo "file for pid $pid contains an unexpected number of lines ($nb)!"
	# 	echo "it should produce one line per second"
	# 	exit 1
	# fi

	prev=0
	for val in $output; do
		if [ "$val" -le "$prev" ]; then
			echo "Error, usr times are wrong!"
			exit 1
		fi
		prev=$val
	done

done

if ! rmmod $modulename; then
	echo "Fail while unloading module"
	exit 1
fi

echo scan > /sys/kernel/debug/kmemleak
sleep 60
cat /sys/kernel/debug/kmemleak
