#!/bin/sh
# DF-5132 static verifier: assert the fail-open response validation in
# amdgpu_kv_notify_message_to_smu() and the two facts that make it a defect.
# Exits non-zero if any assertion fails or the source drifts.
ROOT="${1:-/home/maxx/dfbsd/dfbsd}"
KV="$ROOT/sys/dev/drm/amd/amdgpu/kv_smc.c"
CI="$ROOT/sys/dev/drm/amd/amdgpu/ci_smc.c"
PP="$ROOT/sys/dev/drm/amd/amdgpu/ppsmc.h"
fail=0

echo "== DF-5132: amdgpu_kv_notify_message_to_smu fail-open response validation =="

# 1. PPSMC_Result_OK == 0x01 (so resp 0x00 cannot mean success)
if rg -q 'define PPSMC_Result_OK[[:space:]]+\(\(uint8_t\)0x01\)' "$PP"; then
	echo "PASS  PPSMC_Result_OK == 0x01 ($(rg -n 'define PPSMC_Result_OK' "$PP" | head -1 | cut -d: -f1-2))"
else
	echo "FAIL  PPSMC_Result_OK definition not found/changed in ppsmc.h"; fail=1
fi

# 2. the validator body rejects ONLY 0xFF and 0xFE and then returns 0
body=$(sed -n '47,54p' "$KV")
echo2=$(printf '%s' "$body" | rg -c 'return -EINVAL' || true)
if printf '%s' "$body" | rg -q 'if \(tmp != 1\)' && \
   [ "$echo2" = "2" ] && \
   printf '%s' "$body" | tail -1 | rg -q '^[[:space:]]*return 0;'; then
	echo "PASS  kv_smc.c:47-54: nested ifs reject only 0xFF/0xFE; 'return 0' reachable with tmp==0x00 (timeout) and 0x02..0xFD"
else
	echo "FAIL  kv_smc.c:47-54 structure drifted — re-inspect"; fail=1
fi

# 3. wait loop polls for != 0, i.e. 0x00 is the not-yet-responded state
if sed -n '40,44p' "$KV" | rg -q 'SMC_RESP_0__SMC_RESP_MASK\) != 0'; then
	echo "PASS  kv_smc.c:40-44: loop breaks on any nonzero response; exhausting it leaves tmp==0"
else
	echo "FAIL  wait-loop structure drifted"; fail=1
fi

# 4. contrast: ci sibling propagates the raw result (timeout observable upstream)
if rg -q 'return \(PPSMC_Result\)tmp;' "$CI"; then
	echo "PASS  ci_smc.c amdgpu_ci_send_msg_to_smc returns raw result (timeout != PPSMC_Result_OK is visible to callers)"
else
	echo "FAIL  ci contrast assertion drifted"; fail=1
fi

# 5. the radeon twin is byte-identical (same defect, twin-file candidate)
if sed -n '44,51p' "$ROOT/sys/dev/drm/radeon/kv_smc.c" | rg -q 'if \(tmp == 0xFF\)'; then
	echo "NOTE  radeon/kv_smc.c:44-51 twin carries the same fall-through"
fi

echo "== result: $([ $fail = 0 ] && echo ALL STATIC ASSERTIONS PASS || echo DRIFT/FAIL) =="
exit $fail
