#!/bin/sh
# - events
# - time
# - command
# - list_pmu_events

. $LKP_SRC/lib/env.sh
. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/tests/pmu-tools.sh
is_virt && die "Don't run pmu-tools on virtual machine"

# pmu-tools runs on top of Linux perf
set_perf_path "$BENCHMARK_ROOT/pmu-tools/perf"
export PATH=$BENCHMARK_ROOT/pmu-tools:$PATH

ocperf=$BENCHMARK_ROOT/pmu-tools/ocperf.py
[ -x "$ocperf" ] || die "Can't find pmu-tools"

#
# pmu-tools needs to download CPU map file from
# https://download.01.org/perfmon to $XDG_HOME_CACHE/pmu-events at
# first run. But test machine may not have external network
# connection. So we will pre-downloaded CPU map files into
# $BENCHMARK_ROOT and copy it to user's cache directory.
#

[ -n "$HOME" ] || export HOME=/root

[ -d "$HOME/.cache/pmu-events" ] || {
	mkdir -p "$HOME/.cache"
	cp -af "$BENCHMARK_ROOT/pmu-tools/pmu-events" "$HOME/.cache"
}

if [ -n "$list_pmu_events" ]; then
    create_links
    python "$BENCHMARK_ROOT/pmu-tools/list-events.py" > "$TMP_RESULT_ROOT/pmu-events-list"
fi

# perf may consume lots of fd
ulimit -n 102400

if [ -z "$events" ]; then
	# default event list
	events="inst_retired.any cpu_clk_unhalted.thread cpu_clk_unhalted.ref_tsc"
fi

opt_events="-e $(echo $events | sed 's/ / -e /g')"

[ "$run" = 0 ] && exit 0

$ocperf stat $opt_events --log-fd 1 true 2>&1 |
grep 'invalid or unsupported event' &&
exit 99

. $LKP_SRC/lib/wait.sh

[ -n "$time" ] && {
	setup_wait
	command="$WAIT_POST_TEST_CMD --timeout $time"
}

disable_nmi_watchdog

exec $ocperf stat -a --scale -I 1000 -x' ' $opt_events --log-fd 1 -- $command
