#!/bin/bash
# install.sh: sets up a Gigabyte G292-Z20 (Debian 13) with fuse-burned CMP 170HX 8 GB cards the way our server is set up.
# Installs: nvidia-open 615.71.09 (apt, pinned), the patched module (cmpunlocker 2c7e2ec + fb-geometry-80g: 80 GiB by the
# card's own masks) with the driver's CMP BAR1 unlock disabled, the services cmp-bar1-boot (BAR1 128 GiB before the
# driver) and cmp-pcie-boot (Gen4 x16, fast parallel variant), a block on automatic nvidia loading, kernel parameters.
# Run as root:  ./install.sh
# Afterwards do a COLD power cycle (power off and on through the BMC), not a reboot.
#
# STATUS: steps 0, 1, 3, 4, 5 are what ran on our server. Step 2 was REWRITTEN for this public repository (it now
# fetches cmpunlocker and the 80 GB patch from their authors instead of unpacking our private tarball) and has NOT been
# run in this form. The whole script has NOT been run on a second machine yet. First run: watch it.
set -euo pipefail
[ "$EUID" = 0 ] || { echo "root required"; exit 1; }
export PATH=/usr/local/sbin:/usr/sbin:/sbin:$PATH DEBIAN_FRONTEND=noninteractive NO_COLOR=1
K=$(cd "$(dirname "$0")" && pwd); KVER=$(uname -r); VER=615.71.09
CMPUNLOCKER_COMMIT=2c7e2ecd7944e791fec040d2680036beb4a9327b
FBG_COMMIT=f422f80a716fff2c1dc112abcf2e9d43a04b6614
FBG_SHA256=55a6bedd120545ab5c1e3b41aae402c889a3e161c74d85a7940e1b04df12b675
step() { echo; echo "=== $*"; }

step "0. Checks"
[ -d /sys/firmware/efi ] || echo "WARNING: not booted in UEFI mode: BAR1 128 GiB may not fit"
N=$(lspci -D -d 10de:20c2 | wc -l); echo "10de:20c2 cards: $N"; [ "$N" -gt 0 ] || { echo "no cards"; exit 1; }
echo "kernel $KVER (kit was made on $(cat "$K/etc/kernel.txt"))"
if pgrep -x nvidia-smi >/dev/null || [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then echo "there are processes on the cards: stop them first"; exit 1; fi

step "1. Packages: NVIDIA repository, driver $VER, kernel headers"
if ! apt-cache madison nvidia-open 2>/dev/null | grep -q "$VER"; then
  if [ ! -f /usr/share/keyrings/cuda-archive-keyring.gpg ]; then
    curl -fsSL -o /tmp/cuda-keyring.deb https://developer.download.nvidia.com/compute/cuda/repos/debian13/x86_64/cuda-keyring_1.1-1_all.deb
    dpkg -i /tmp/cuda-keyring.deb
  fi
  apt-get update -q
  apt-cache madison nvidia-open | grep -q "$VER" || { echo "apt has no nvidia-open $VER"; exit 1; }
fi
apt-get install -y -q build-essential dkms pciutils python3-yaml curl git patch "linux-headers-$KVER"
for p in $(dpkg -l | awk '/^ii +nvidia-driver-pinning-/ {print $2}'); do [ "$p" = "nvidia-driver-pinning-$VER" ] || apt-get remove -y -q "$p"; done
apt-get install -y -q "nvidia-driver-pinning-$VER"
apt-get install -y -q -o Dpkg::Options::=--force-confnew nvidia-open || { apt-get -y -q -o Dpkg::Options::=--force-confnew -f install; apt-get install -y -q -o Dpkg::Options::=--force-confnew nvidia-open nvidia-settings; }
dpkg -l nvidia-open firmware-nvidia-gsp nvidia-kernel-open-dkms | awk '/^ii/ {print "  " $2, $3}'
for v in $(dkms status 2>/dev/null | grep -o 'nvidia/[0-9.]*' | cut -d/ -f2 | sort -u); do dkms remove "nvidia/$v" --all 2>/dev/null || true; done

step "2. Patched module (cmpunlocker $CMPUNLOCKER_COMMIT + fb-geometry-80g, driver BAR1 unlock disabled)"
if [ -d /root/cmpunlocker ] && [ ! -f /root/cmpunlocker/.kit ]; then mv /root/cmpunlocker "/root/cmpunlocker.before-kit-$(date +%Y%m%d-%H%M)"; fi
if [ ! -f /root/cmpunlocker/.kit ]; then
  git clone https://github.com/amoghmunikote/cmpunlocker /root/cmpunlocker
  ( cd /root/cmpunlocker && git checkout -q "$CMPUNLOCKER_COMMIT" )
  curl -fsSL -o /root/cmpunlocker/driver/patches/fb-geometry-80g.patch \
    "https://raw.githubusercontent.com/darkmaniac7/cmp170hx-8gb-vfi-tools/$FBG_COMMIT/driver/fb-geometry-80g.patch"
  echo "$FBG_SHA256  /root/cmpunlocker/driver/patches/fb-geometry-80g.patch" | sha256sum -c -
  ( cd /root/cmpunlocker && patch -p1 < "$K/cmpunlocker/cmpunlocker-local.patch" )
  touch /root/cmpunlocker/.kit
fi
grep -q 'local: CMP BAR1 unlock off' /root/cmpunlocker/driver/build.sh || { echo "build.sh lacks the local BAR1 change"; exit 1; }
grep -q 'fb-geometry-80g.patch' /root/cmpunlocker/driver/build.sh || { echo "build.sh lacks the 80 GB patch"; exit 1; }
# the hold file goes in BEFORE the build: build.sh tries to hot-reload the module at the end, and on burned cards that hangs
install -m 0644 "$K/modprobe/cmp-nvidia-hold.conf" /etc/modprobe.d/cmp-nvidia-hold.conf
BDFS=$(lspci -D -d 10de:20c2 | awk '{print $1}')
INV=$(for b in $BDFS; do echo "$b 20c2 8gb 81920"; done)
( cd /root/cmpunlocker && CMPUNLOCKER_DRIVER_VERSION=$VER CMPUNLOCKER_CARD_PROFILE=8gb CMPUNLOCKER_GPU_INVENTORY="$INV" ./driver/build.sh 2>&1 | grep -v -E 'objtool|^\s+(CC|LD|AR|CXX|SYMLINK|CONFTEST|MODPOST|BTF|HOSTCC)' | tail -25 ) || true
[ -f "/lib/modules/$KVER/updates/cmpunlocker/nvidia.ko" ] || { echo "module was not built"; exit 1; }
strings "/lib/modules/$KVER/updates/cmpunlocker/nvidia.ko" | grep -q 'FB geometry' || { echo "the module lacks the geometry patch"; exit 1; }
echo "  module: $(modinfo -F version /lib/modules/$KVER/updates/cmpunlocker/nvidia.ko)"

step "3. Module parameters (card list by the BDFs of this machine)"
PD=$(for b in $BDFS; do printf 'pci=%s;RMPcieLinkSpeed=0x5;' "$b"; done); PD=${PD%;}
cat > /etc/modprobe.d/cmp-pcie-gen2.conf <<E2
# $(date +%Y-%m-%d), cmp170hx-kit: fuse-burned cards. CmpFbGeometry: key absent = automatic 80 GiB; =2 log only; =0 all 64 GiB.
# After moving or adding cards: update the BDF list below, update-initramfs -u, cold power cycle.
options nvidia NVreg_RegistryDwords="RmForceEnableGen2=1"
options nvidia NVreg_RegistryDwordsPerDevice="$PD"
E2
grep -c RMPcieLinkSpeed /etc/modprobe.d/cmp-pcie-gen2.conf

step "4. Tools and services"
install -m 0755 "$K"/sbin/cmp-* /usr/local/sbin/
SRC=/root/cmpunlocker/driver/.build/open-gpu-kernel-modules-$VER
cc -std=gnu11 -O2 -I"$SRC/src/common/sdk/nvidia/inc" "$K/src/set_pcie_speed.c" -o /usr/local/sbin/cmp-pcie-speed && echo "  cmp-pcie-speed built"
install -m 0644 "$K/systemd/cmp-bar1-boot.service" "$K/systemd/cmp-pcie-boot.service" /etc/systemd/system/
mkdir -p /etc/systemd/system/cmp-pcie-boot.service.d && install -m 0644 "$K"/systemd/cmp-pcie-boot.service.d/*.conf /etc/systemd/system/cmp-pcie-boot.service.d/
mkdir -p /var/lib/cmp-pcie-boot /var/log/cmp-pcie
systemctl disable gen2.service 2>/dev/null || true
systemctl daemon-reload
systemctl enable cmp-bar1-boot.service cmp-pcie-boot.service

step "5. Kernel parameters"
G=/etc/default/grub; cp -a $G "$G.before-kit-$(date +%Y%m%d-%H%M)"
for p in pcie_port_pm=off pci=realloc amd_iommu=on iommu=pt iomem=relaxed; do
  grep -q "^GRUB_CMDLINE_LINUX_DEFAULT=.*\b${p}\b" $G || sed -i "s/^GRUB_CMDLINE_LINUX_DEFAULT=\"\(.*\)\"/GRUB_CMDLINE_LINUX_DEFAULT=\"\1 $p\"/" $G
done
grep ^GRUB_CMDLINE_LINUX_DEFAULT $G; update-grub 2>&1 | tail -1
update-initramfs -u -k "$KVER" 2>&1 | tail -1; sync

step "DONE. Now a COLD power cycle through the BMC (power off, 20 s, power on)."
cat <<E3
After boot (SSH in about 2.5 min, about 1 more minute for BAR1 and Gen4) check:
  systemctl is-active cmp-bar1-boot cmp-pcie-boot
  nvidia-smi --query-gpu=index,pci.bus_id,vbios_version,memory.total --format=csv     # 81920 MiB on burned 80 GB cards
  nvidia-smi -q | grep -A3 'BAR1 Memory' | grep Total                                  # 131072 MiB
  for d in /sys/bus/pci/devices/*; do [ "\$(cat \$d/device 2>/dev/null)" = 0x20c2 ] && echo "\$(basename \$d) \$(cat \$d/current_link_speed) x\$(cat \$d/current_link_width)"; done   # 16.0 GT/s x16
  journalctl -u cmp-bar1-boot -u cmp-pcie-boot -b --no-pager | tail -30
If not all cards are visible or CUDA hangs, see docs/06-troubleshooting.md.
E3
