#!/bin/sh
# - events
# - period
# - freq
# - delay
# - duration
# - callgraph
# - children
# - inline

. $LKP_SRC/lib/env.sh
. $LKP_SRC/lib/common.sh

set_perf_path "/lkp/benchmarks/perf/perf"

is_virt && exit 0

default_events()
{
	for event in cycles:pp cycles:p; do
		$perf record -q --freq=800 -e $event -- sleep 0.01 >/dev/null 2>&1 && {
			echo $event
			return
		}
	done
	echo cycles
}

: ${events:=$(default_events)}
: ${duration:=10}
: ${period:=1000003}
: ${children:=yes}
: ${callgraph:=folded,0.5,callee}

if [ -z "$delay" ]; then
	if [ -n "$runtime" ]; then
		delay=$((runtime / 2))
	elif [ -n "$testtime" ]; then
		delay=$((testtime / 2))
	else
		delay=100
	fi
fi

[ -n "$freq" ] &&
opt_freq="--freq=$freq"

[ -n "$period" ] &&
opt_period="--count=$period"

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

if parse_bool -q "$children"; then
	opt_children="--children"
else
	opt_children="--no-children"
fi

[ -n "$inline" ] && opt_inline="--inline"

# perf may consume lots of fd
ulimit -n 102400

. $LKP_SRC/lib/wait.sh
setup_wait

perf_data=$TMP/perf.data

# Perf report may not have the permission to parse kernel symbols due to
# kptr restriction
kptr_restrict_file=/proc/sys/kernel/kptr_restrict
kptr_restrict=0
[ -f "$kptr_restrict_file" ] && kptr_restrict=$(cat "$kptr_restrict_file")
[ "$kptr_restrict" -ne 0 ] && echo 0 > "$kptr_restrict_file"

$perf -v || die 'perf command failed'
# WAIT_POST_TEST_CMD will start at the same time with perf
# the former will wait for (delay+duration) before exit
# the latter will wait for (delay) before collecting samples
$perf record -q -ag --realtime=1 -m 256 $opt_freq $opt_period $opt_events \
	-o $perf_data -D $((delay * 1000)) -- \
	$WAIT_POST_TEST_CMD --timeout $((delay + duration))

cat > "$TMP_RESULT_ROOT/post-run.perf-profile" <<EOF
[ -s "$perf_data" ] && {
	$perf report $opt_inline $opt_children --header -U -g $callgraph --sort=dso,symbol -i $perf_data |
	gzip > $TMP_RESULT_ROOT/perf-profile.gz && {
		[ "$lite_mode" = 1 ] || cp $perf_data $TMP_RESULT_ROOT
		cp /proc/kallsyms $TMP_RESULT_ROOT
	}
[ "$kptr_restrict" -ne 0 ] && echo "$kptr_restrict" > "$kptr_restrict_file"
}
EOF
