#!/bin/bash
# cmp-pcie-pre: preparation before cmp-pcie-boot / cmp-pcie-fast on a Gigabyte G292-Z20.
# 1) The Switchtec switch ports above the cards come up with sticky AER bits (UE 0x00100000 Unsupported Request):
#    the platform owns AER and does not clear them, and cmp-e1steps stops with rc 4 because of them. Clear them
#    (write-1-to-clear).
# 2) Without the unlocker's gen2.service the cards sit at Gen1 after boot, and cmp-rmwalk requires Gen2: raise them
#    through RM (cmp-pcie-speed 2).
PATH=/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin
nvidia-smi > /dev/null 2>&1 || { echo "pre: nvidia-smi does not answer"; exit 0; }
for dev in /sys/bus/pci/devices/*; do
  [ "$(cat $dev/vendor 2>/dev/null)" = 0x10de ] && [ "$(cat $dev/device 2>/dev/null)" = 0x20c2 ] || continue
  G=$(basename $dev); B=${G:5:2}; RP=$(basename "$(dirname "$(readlink -f $dev)")")
  for off in 04 10; do
    v=$(setpci -s $RP ECAP_AER+$off.l 2>/dev/null) || continue
    [[ $v =~ ^[[:xdigit:]]{8}$ ]] && [ "$v" != 00000000 ] && [ "${v,,}" != ffffffff ] && setpci -s $RP ECAP_AER+$off.l=$v
  done
  s=$(setpci -s $G CAP_EXP+12.w 2>/dev/null); [[ $s =~ ^[[:xdigit:]]{4}$ ]] || { echo "pre: $G LnkSta not readable"; continue; }
  if [ $((16#$s & 15)) = 1 ]; then
    M=$(awk -F: '/Device Minor/ {gsub(/[[:space:]]/,"",$2); print $2}' /proc/driver/nvidia/gpus/$G/information 2>/dev/null)
    [[ $M =~ ^[0-9]+$ ]] || { echo "pre: $G no device minor"; continue; }
    cmp-pcie-speed 2 $M $B > /dev/null 2>&1; r=$?; sleep 1
    echo "pre: $G Gen1 -> RM speed 2 (rc $r), LnkSta $(setpci -s $G CAP_EXP+12.w), port $RP AER cleared"
  else
    echo "pre: $G already Gen$((16#$s & 15)), port $RP AER cleared"
  fi
done
exit 0
