#!/usr/bin/env python3
"""DF-2540 arithmetic verification: signed-overflow in amdsb_watchdog.

Simulates the C expression  timeout = (period * 1000) / ms_per_tick
with int32 arithmetic and unsigned-int assignment, showing that
period=4294967 produces timeout=0 (count=0 -> immediate reboot on
real AMD SB hardware).
"""
import ctypes, sys

ms_per_tick = 1000
max_ticks = 65535

print(f"ms_per_tick={ms_per_tick}, max_ticks={max_ticks}")
print(f"{'period':>10} {'int32(p*1000)':>15} {'/ms_per_tick':>14} "
      f"{'uint':>12} {'clamped':>8} {'HW_count':>9} {'FIRE?':>6}")
print("-" * 80)

interesting = sorted(set(
    [2147483, 2147484, 2147485,
     3000000, 4000000,
     4294966, 4294967, 4294968] +
    list(range(4294960, 4294975))
))

for period in interesting:
    prod = ctypes.c_int32(period * 1000).value
    # C integer division truncates toward zero
    if prod < 0:
        cdiv = -((-prod) // ms_per_tick)
    else:
        cdiv = prod // ms_per_tick
    uint = ctypes.c_uint32(cdiv).value
    clamped = uint > max_ticks
    final = max_ticks if clamped else uint
    hw_count = final & 0xffff
    fire = "*** FIRE (count=0) ***" if hw_count == 0 else ""
    print(f"{period:>10} {prod:>15} {cdiv:>14} {uint:>12} "
          f"{'YES' if clamped else 'no':>8} {hw_count:>9} {fire:>6}")
