#!/bin/sh

# This script applies NVIDIA kernel module options based on module version and
# connected hardware.
#
# Two independent decisions:
# 1. PreserveVideoMemoryAllocations=1 is enabled for Turing (RTX 20/GTX 16) and
# newer GPUs. Without it, modern cards resume from S3 with broken application
# graphics.
#
# 2. UseKernelSuspendNotifiers=1 is enabled for open kernel module version 595+.
# With it, VRAM is saved/restored inside the kernel PM callbacks, before
# user.slice is thawed. Fixes the old path restoring VRAM after X is already
# running, which can leave the X screen unusable after resume from S4.
#
# Options:
#   NVIDIA_SLEEP_DEBUG=1 - print the decision, load nothing
#   NVIDIA_SLEEP_KO=/path/to/nvidia.ko - decide against specified kernel module

set -u

kernel_version=$(uname -r)
ko=${NVIDIA_SLEEP_KO:-/lib/modules/$kernel_version/nVidia/nvidia.ko}
opts=""

# 1. Enable PreserveVideoMemoryAllocations for Turing and newer GPUs
pvma=0
for d in /sys/bus/pci/devices/*; do
    [ -r "$d/uevent" ] || continue

    # Read the PCI_ID line (e.g., PCI_ID=10DE:1F99)
    line=$(grep "^PCI_ID=10DE:" "$d/uevent" 2>/dev/null) || continue

    # 10DE is nvidia vendor hex;
    # We extract the 4 hex digits of the device ID (e.g., "1F99")
    dev_id="${line#PCI_ID=10DE:}"

    # Ensure it's exactly 4 hex digits
    case "$dev_id" in
        [0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]) ;;
        *) continue ;;
    esac

    # Get the first two hex digits (the GPU generation)
    prefix="${dev_id%??}"

    # Turing or newer: generation prefix >= 0x1E
    if [ $((0x$prefix)) -ge $((0x1E)) ]; then
        pvma=1
        break
    fi
done

[ "$pvma" -eq 1 ] && opts="$opts NVreg_PreserveVideoMemoryAllocations=1"


# 2. Enable UseKernelSuspendNotifiers for open 595+ module
have_param=0
is_open=0

# Scan through modinfo output to make sure the parameter exists
modinfo -p "$ko" 2>/dev/null | grep -q '^NVreg_UseKernelSuspendNotifiers:' && have_param=1

# Make sure we're on the open kernel module
license=$(modinfo -F license "$ko" 2>/dev/null)
if [ "${license:-}" = "Dual MIT/GPL" ]; then
    is_open=1
fi

# Both must be true.
if [ "$have_param" -eq 1 ] && [ "$is_open" -eq 1 ]; then
    opts="$opts NVreg_UseKernelSuspendNotifiers=1"
fi

# Apply any additional options supplied externally
for a in "$@"; do
    opts="$opts $a"
done

# Dry run if NVIDIA_SLEEP_DEBUG is set.
if [ -n "${NVIDIA_SLEEP_DEBUG:-}" ]; then
    echo "ko=$ko pvma=$pvma have_param=$have_param is_open=$is_open license=$license opts=$opts"
    exit 0
fi

exec modprobe --ignore-install nvidia $opts
