#!/bin/sh
# DF-2463 run: drive so_input pdu_alloc under memory pressure.
# Run as root (needs /dev/iscsi + sysctl vm.swap_enabled).
#
# Expected (bug present): kernel panic "Fatal trap 12: page fault" at
#   so_input (NULL deref of pq at isc_soc.c:545) once pdu_alloc(M_NOWAIT)
#   fails twice under low memory.
# Expected (fixed / pressure race lost): no panic; idrv completes.
set -e
echo "DF-2463 run: swap off -> memhog -> pressure -> mtarget+idrv"
sysctl -w vm.swap_enabled=0 2>&1 || true

# 1. start memhog to drive v_free_count toward v_free_min
./memhog 8 > memhog.log 2>&1 &
MH=$!
echo "memhog pid=$MH; waiting for pressure..."
# poll until v_free_count drops below ~12000 pages (~48MB) or 25s elapse
i=0
while [ $i -lt 50 ]; do
    fc=$(sysctl -n vm.stats.vm.v_free_count)
    echo "  v_free_count=$fc"
    if [ "$fc" -lt 12000 ]; then echo "  pressure reached"; break; fi
    sleep 1
    i=$((i+1))
done

# 2. start the malicious target (streams NOP-IN continuously)
./mtarget2463 3260 > mtarget2463.log 2>&1 &
MT=$!
sleep 1

# 3. drive the kernel receiver for 30s; pdu_alloc runs each PDU under pressure
echo "--- starting idrv (receiver) under pressure ---"
./idrv2463 127.0.0.1 3260 30
RC=$?
echo "IDRV_EXIT=$RC"

# cleanup
kill $MT 2>/dev/null || true
kill $MH 2>/dev/null || true
sysctl -w vm.swap_enabled=1 2>&1 || true
echo "DF-2463 run complete (if we got here, no panic)"
