#!/bin/bash
# cmp-pcie-fast: same steps as cmp-pcie-boot (darkmaniac7/cmp170hx-8gb-vfi-tools), but for ALL cards in parallel and with
# short settle times (Gen3 10 s, Gen4 10 s): about 40 s instead of about 13 min for 8 cards.
# Steps: cmp-pcie-pre (AER, Gen1->Gen2), cmp-rmwalk (->Gen3), cmp-e1steps (PHY), cmp-gen4retrain-fast (->Gen4).
# Safety: a marker $D/inflight-fast is written before the pass and removed after it. If the host hangs during the parallel
# pass, the marker stays, and on the next boot (and later ones) the stock sequential cmp-pcie-boot runs with its own
# per-card protection. To return to the fast mode: rm /var/lib/cmp-pcie-boot/slow
# Disable everything: touch /var/lib/cmp-pcie-boot/off ; Gen4 only: touch /var/lib/cmp-pcie-boot/off-g4
PATH=/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin
D=/var/lib/cmp-pcie-boot; L=/var/log/cmp-pcie; mkdir -p $D $L
[ -e $D/off ] && { echo "off flag set, nothing done"; exit 0; }
/usr/local/sbin/cmp-pcie-pre
if [ -e $D/inflight-fast ]; then mv $D/inflight-fast $D/slow; echo "previous parallel pass did not finish (hang?): switching to sequential mode"; fi
if [ -e $D/slow ]; then echo "slow mode: stock cmp-pcie-boot"; exec /usr/local/sbin/cmp-pcie-boot; fi
cards=$(nvidia-smi --query-gpu=pci.bus_id,pci.device_id --format=csv,noheader | tr -d ' ' | awk -F, '$2=="0x20C210DE" {print tolower(substr($1,10,2))}')
: > $D/inflight-fast; sync
# a clean shutdown or service stop in the middle of the pass is not a hang: remove the marker
trap 'rm -f $D/inflight-fast; sync; echo "stopped by signal, marker removed"; exit 0' TERM INT
one() {
  local b=$1 r s
  [ -e $D/disabled-$b ] && { echo "card $b disabled, skipped"; return; }
  SETTLE=10 cmp-rmwalk $b > $L/fast-walk-$b.log 2>&1; r=$?
  [ $r = 0 ] || { echo "card $b Gen3 walk rc $r, LnkSta $(setpci -s $b:00.0 CAP_EXP+12.w 2>/dev/null)"; return; }
  if [ -e $D/off-g4 ] || [ -e $D/disabled-g4-$b ]; then echo "card $b Gen3 ok, Gen4 is off"; return; fi
  [ "$(python3 -I /usr/local/sbin/cmp-gen23read 0000:$b:00.0 2>/dev/null)" = 0 ] || { echo "card $b Gen3 ok, GEN23 fuse is set: Gen4 not possible"; return; }
  python3 -I -u /usr/local/sbin/cmp-e1steps 0000:$b:00.0 > $L/fast-e1-$b.log 2>&1; r=$?
  [ $r = 0 ] || { echo "card $b Gen3 ok, e1 rc $r: stays at Gen3"; return; }
  bash /usr/local/sbin/cmp-gen4retrain-fast 0000:$b:00.0 > $L/fast-g4-$b.log 2>&1; r=$?
  s=$(setpci -s $b:00.0 CAP_EXP+12.w 2>/dev/null)
  if [ $r = 2 ] || ! [[ $s =~ ^[[:xdigit:]]{4}$ ]] || [ "${s,,}" = ffff ]; then : > $D/disabled-g4-$b; echo "card $b LOST at the Gen4 step (rc $r): Gen4 disabled for this slot"; return; fi
  echo "card $b Gen4: retrain rc $r, link $s"
}
t0=$(date +%s)
for b in $cards; do one $b & done; wait
rm -f $D/inflight-fast; sync
echo "done in $(( $(date +%s) - t0 )) s: $(for b in $cards; do echo -n "$b=$(setpci -s $b:00.0 CAP_EXP+12.w) "; done)"
exit 0
