#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# description: ftrace - test for function event triggers
# flags: instance
#
# The triggers are set within the set_ftrace_filter file
# requires: set_ftrace_filter
#
# Ftrace allows to add triggers to functions, such as enabling or disabling
# tracing, enabling or disabling trace events, or recording a stack trace
# within the ring buffer.
#
# This test is designed to test event triggers

do_reset() {
    reset_ftrace_filter
    reset_tracer
    disable_events
    clear_trace
    enable_tracing
}

fail() { # mesg
    echo $1
    exit_fail
}

SLEEP_TIME=".1"

echo "Testing function probes with events:"

EVENT="sched:sched_switch"
EVENT_ENABLE="events/sched/sched_switch/enable"

cnt_trace() {
    grep -v '^#' trace | wc -l
}

test_event_enabled() {
    val=$1
    check_times=10		# wait for 10 * SLEEP_TIME at most

    while [ $check_times -ne 0 ]; do
	e=`cat $EVENT_ENABLE`
	if [ "$e" = $val ]; then
	    return 0
	fi
	sleep $SLEEP_TIME
	check_times=$((check_times - 1))
    done

    fail "Expected $val but found $e"
}

run_enable_disable() {
    enable=$1			# enable
    Enable=$2			# Enable
    check_disable=$3		# 0
    check_enable_star=$4	# 1*
    check_disable_star=$5	# 0*

    cnt=`cnt_trace`
    if [ $cnt -ne 0 ]; then
	fail "Found junk in trace file"
    fi

    echo "$Enable event all the time"

    echo $check_disable > $EVENT_ENABLE
    sleep $SLEEP_TIME

    test_event_enabled $check_disable

    echo "schedule:${enable}_event:$EVENT" > set_ftrace_filter
    if [ -d ../../instances ]; then # Check instances
	cur=`cat set_ftrace_filter`
	top=`cat ../../set_ftrace_filter`
	if [ "$cur" = "$top" ]; then
	    echo "This kernel is too old to support per instance filter"
	    reset_ftrace_filter
	    exit_unsupported
	fi
    fi

    echo " make sure it works 5 times"

    for i in `seq 5`; do
	sleep $SLEEP_TIME
	echo "  test $i"
	test_event_enabled $check_enable_star

	echo $check_disable > $EVENT_ENABLE
    done
    sleep $SLEEP_TIME
    echo " make sure it still works"
    test_event_enabled $check_enable_star

    reset_ftrace_filter

    echo " make sure it only works 3 times"

    echo $check_disable > $EVENT_ENABLE
    sleep $SLEEP_TIME

    echo "schedule:${enable}_event:$EVENT:3" > set_ftrace_filter

    for i in `seq 3`; do
	sleep $SLEEP_TIME
	echo "  test $i"
	test_event_enabled $check_enable_star

	echo $check_disable > $EVENT_ENABLE
    done

    sleep $SLEEP_TIME
    echo " make sure it stop working"
    test_event_enabled $check_disable_star

    do_reset
}

run_enable_disable enable Enable 0 "1*" "0*"
run_enable_disable disable Disable 1 "0*" "1*"