#!/bin/bash
# cmp-bar1-boot: large BAR1 (128 GiB by default) on all CMP 170HX cards BEFORE nvidia is loaded.
# Why before the driver: the cards sit in pairs behind switches; the kernel can widen the bridge windows only if it
# re-enumerates the whole branch (remove the root port + rescan), and with the driver loaded the second card of a pair
# is not resized.
# Steps: cmp-bar1set on each card (ReBAR unlock through BAR0 + size in ReBAR ctrl) -> remove the root ports -> rescan ->
# check -> modprobe nvidia. Automatic loading of nvidia is blocked in /etc/modprobe.d/cmp-nvidia-hold.conf, the driver is
# loaded only by this script (modprobe --ignore-install).
# Flags in /var/lib/cmp-pcie-boot: no-bar1 = leave BAR1 alone (64 MiB, stock); inflight-bar1 left after a hang = the
# same, automatically (the no-bar1 file is created for you). Size: /etc/default/cmp-bar1 (CMP_BAR1_GB=64|128).
PATH=/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin
D=/var/lib/cmp-pcie-boot; mkdir -p $D; GB=128; [ -r /etc/default/cmp-bar1 ] && . /etc/default/cmp-bar1; GB=${CMP_BAR1_GB:-$GB}
load() { modprobe --ignore-install nvidia && modprobe --ignore-install nvidia_uvm; echo "nvidia loaded (rc $?)"; }
if grep -q '^nvidia ' /proc/modules; then echo "nvidia already loaded: BAR1 left alone"; exit 0; fi
if [ -e $D/inflight-bar1 ]; then mv $D/inflight-bar1 $D/no-bar1; echo "previous BAR1 pass did not finish: continuing without the large BAR1 (rm $D/no-bar1 to bring it back)"; fi
if [ -e $D/no-bar1 ]; then echo "no-bar1: BAR1 stays stock"; load; exit 0; fi
cards=(); declare -A rps
for dev in /sys/bus/pci/devices/*; do
  [ "$(cat $dev/vendor 2>/dev/null)" = 0x10de ] && [ "$(cat $dev/device 2>/dev/null)" = 0x20c2 ] || continue
  cards+=("$(basename $dev)"); rp=$(readlink -f $dev | cut -d/ -f5); rps[$rp]=1
done
[ ${#cards[@]} -gt 0 ] || { echo "no 10de:20c2 cards"; load; exit 0; }
: > $D/inflight-bar1; sync
trap 'rm -f $D/inflight-bar1; sync; exit 0' TERM INT
fail=0
for c in "${cards[@]}"; do python3 -I /usr/local/sbin/cmp-bar1set $c $GB | sed 's/: CYA.*cfg-space/: cfg-space/' ; [ ${PIPESTATUS[0]} = 0 ] || fail=1; done
for rp in "${!rps[@]}"; do [[ $rp =~ ^0000:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$ ]] && echo 1 > /sys/bus/pci/devices/$rp/remove; done
sleep 1; echo 1 > /sys/bus/pci/rescan; sleep 3
for c in "${cards[@]}"; do
  s=$(lspci -s $c -vv 2>/dev/null | grep 'Region 1' | grep -o 'size=[0-9]*[MG]')
  [ "$s" = "size=${GB}G" ] || { echo "ERROR: $c Region 1 = '${s:-none}' instead of ${GB}G"; fail=1; }
done
rm -f $D/inflight-bar1; sync
if [ $fail = 1 ]; then echo "BAR1 could not be laid out: NOT loading nvidia (CUDA would hang). Fix: touch $D/no-bar1 and cold power cycle"; exit 1; fi
echo "BAR1 ${GB}G on ${#cards[@]} cards, ${#rps[@]} root ports"
load
