#!/bin/bash 

# start script with "./gpu_debug4.sh >gpu_debug4_output.txt 2>&1"

trace-cmd stop
timeout 3 cat /sys/kernel/debug/tracing/trace_pipe >>/dev/null

# enable DPM, making the 3-fps-video replay unstable:
echo "auto" >/sys/class/drm/card0/device/power_dpm_force_performance_level

echo "starting trace-cmd"
trace-cmd start -e dma_fence -e gpu_scheduler \
   -e amdgpu -v -e "amdgpu:amdgpu_mm_rreg" \
        -e "amdgpu:amdgpu_mm_wreg" -e "amdgpu:amdgpu_iv" &

dmesg -w &

cat /sys/kernel/debug/tracing/trace_pipe &

sleep 5

echo ""
echo "starting 3-fps-video test"
./othan_test.sh >/dev/null 2>/dev/null </dev/null &
OPID=$!

echo ""
echo "waiting for the crash"
GRES=""
GRES=$(timeout 600 dmesg -w | grep -v EDID | grep -m 1 -e "amdgpu.*GPU" -e "amdgpu.*ERROR" )

if [[ "x${GRES}" == "x" ]] ; then
  killall mpv
  kill -9 $OPID
  echo "timeout, try again."
  exit 0
fi

echo ""
echo "crash detected!"
echo ""

echo "executing umr -O halt_waves -wa"
umr -O halt_waves -wa
echo ""

echo ""
echo "executing umr -O verbose -R gfx[.]"
umr -O verbose -R gfx[.]
echo ""

echo "trying to get ADR from dmesg output for 'umr -O verbose -vm ...'"
ADR=$(dmesg | grep -m 1 -e "VM_CONTEXT1_PROTECTION_FAULT_ADDR[ ]*0x[0-9A-F]*" \
         | grep -o -e '0x[0-9A-F]*')
echo "trying to get VMID from dmesg output for 'umr -O verbose -vm ...'"
VMID=$(dmesg | grep -m 1 -o -e ", vmid [0-9]*" | grep -o -e "[0-9]*")

if [ "x${VMID}x${ADR}" != "xx" ] ; then 
  echo "executing umr -O verbose -vm ${VMID}@${ADR}000 1"
  umr -O verbose -vm ${VMID}@${ADR}000 1
fi


echo ""
echo "done after crash."

sync

exit 20


