NVIDIA: Difference between revisions

From NixOS Wiki
Ruby0b (talk | contribs)
Fix the lspci command to actually list all GPUs. On laptops, NVIDIA GPUs are sometimes not listed as VGA controllers.
 
(21 intermediate revisions by 8 users not shown)
Line 1: Line 1:
There are several kernel drivers that allow Nvidia GPUs to work:
This page attempts to cover everything related to the use of NVIDIA GPUs on NixOS.


* Nouveau is the stable 3rd-party open-source driver. You probably have it by default.
== Enabling ==
* Nvidia's proprietary kernel module. Better 3D performance than nouveau.
* Nvidia's open-source kernel module, which is beta-quality and x11-only.


This article aims to explain how to use all three of the non-default drivers, and how to disable the Nvidia GPU if you don't want it to make heat.
=== Kernel modules from NVIDIA ===
Kernel modules from NVIDIA offer better performance than other alternatives, but make the system unfree by requiring proprietary userspace libraries that can interface with the kernel modules. Users that want to have a fully free and open-source system should use [[NVIDIA#Nouveau|Nouveau]] instead.


(A GPU driver is not ''purely'' kernel-mode; there are also userspace parts that allow the graphics API to use the kernel part. Mesa, for example, has serspace parts for Nouveau and NVK; they are automatically used when appropriate, so no configuration is needed.<ref>If you insist on checking which driver is in use, try running <code>vulkaninfo | grep -i "deviceName\|driverID"</code>. If you see DRIVER_ID_MESA_NVK, that means you are on the shiny new open-source Vulkan driver.</ref> Nvidia's two kernel drivers also need to be hooked up using userspace libraries provided by Nvidia.)
To enable them, add <code>"nvidia"</code> to the list of enabled video drivers defined by the <code>services.xserver.videoDrivers</code> option.


= The proprietary driver =
{{Note|<code>hardware.graphics.enable</code> was named <code>hardware.opengl.enable</code> '''until NixOS 24.11'''.}}


NixOS uses a functional package management approach &ndash; this section, like many others, will tell you how to change your <code>configuration.nix</code> to define what kind of environment you want on your system.
{{Note|Since driver version 560, you also will need to decide whether to use the open-source or proprietary modules by setting the <code>hardware.nvidia.open</code> option to either <code>true</code> or <code>false</code> respectively.<br><br>Open-source kernel modules are preferred over and planned to steadily replace proprietary modules<ref>https://developer.nvidia.com/blog/nvidia-transitions-fully-towards-open-source-gpu-kernel-modules/</ref>, although they only support GPUs of the Turing architecture or newer (from GeForce RTX 20 series and GeForce GTX 16 series onwards). Data center GPUs starting from Grace Hopper or Blackwall must use open-source modules — proprietary modules are no longer supported.<br><br>''If you're using proprietary modules'', make sure to allow [[Unfree software|unfree software]]. The unfree NVIDIA packages include <code>nvidia-x11</code>, <code>nvidia-settings</code>, and <code>nvidia-persistenced</code>.
}}{{Warning|If you use a laptop with both dedicated and integrated GPUs, remember to [[#Hybrid_graphics_with_PRIME|configure PRIME]] in order to make your dedicated NVIDIA GPU work properly with your integrated GPU. Your configuration '''might not work''' if you skip this step.}}{{file|configuration.nix|nix|<nowiki>
{
  hardware.graphics.enable = true;


For the impatient:
  services.xserver.videoDrivers = [ "nvidia" ];
* [https://nixos.org/manual/nixos/unstable/#sec-x11-graphics-cards-nvidia Nvidia section] in the NixOS Manual offers a shorter guide.
  hardware.nvidia.open = true; # Set to false for proprietary drivers
* Basic installation is as simple as <code>services.xserver.videoDrivers = [ "nvidia" ];</code> (once you have unfree software enabled), which causes the default stable version to be pulled in.
}
* Older cards may need an older driver; see [[#Determining the correct driver version]], which describes <code>hardware.nvidia.package</code>.
</nowiki>}}
* [[#Modifying the NixOS Configuration]] puts it all together and shows the other <code>hardware.nvidia</code> settings, some irrelevant to this driver (e.g. <code>hardware.nvidia.open</code>, which takes you to the Nvidia open kernel driver.)
==== Legacy branches ====
GPUs of the Kepler architecture or older (most GeForce 600/700/800M cards and older) are no longer supported by latest proprietary modules. Instead, users of these GPUs must use legacy branches that may still receive updates, as long as the GPUs themselves remain supported by NVIDIA. You can find which legacy branch you need to use by searching for your GPU model on [https://www.nvidia.com/en-us/drivers/unix/legacy-gpu/ NVIDIA's official legacy driver support list].


== Enable unfree software repositories ==
To use legacy branches, you need to set the <code>hardware.nvidia.package</code> option to a package set named <code>config.boot.kernelPackages.nvidiaPackages.legacy_<branch></code>.{{file|configuration.nix|nix|<nowiki>
{ config, ... }: # ← Required to get the packages used by the currently configured kernel, including drivers
{
  # Last version that supports Kepler GPUs
  hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_470;
}
</nowiki>}}Nixpkgs does not endeavor to support all legacy branches since older, unmaintained legacy branches can become incompatible with newer kernel and X server versions, and at some point it becomes infeasible to patch them to cooperate with modern software. You can find the list of supported legacy branches under [https://github.com/NixOS/nixpkgs/blob/master/pkgs/os-specific/linux/nvidia-x11/default.nix in the Nixpkgs repository].


Make sure to allow [[Unfree Software|unfree software]]. The unfree NVIDIA packages include <code>nvidia-x11</code>, <code>nvidia-settings</code>, and <code>nvidia-persistenced</code>.
==== Beta/production branches ====
By default, modules from the stable branch are used, which come from latest release available for the current architecture — while x86-64 and aarch64 systems follow the "New Feature Branch" releases as they remain actively developed, 32-bit x86 and ARM systems remain on the 390.xx branch as that is the last branch with 32-bit support.  


== Determining the correct driver version ==
Instead of the stable branch, users can also switch to the beta branch, which has more new features and experimental changes at the risk of containing more bugs, or the production branch, a more conservative, well-tested stable version that is suitable for production use with minimum breakage, at the cost of being behind in terms of new features.


You will next need to determine the appropriate driver version for your card. The following options are available:
Using the beta and production branches are similar to how one would use legacy branches:{{file|configuration.nix|nix|<nowiki>
{ config, ... }:
{
  #hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.stable; # Default
  hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.beta;
  hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.production;
}
</nowiki>}}


<syntaxhighlight lang="nix">
=== Nouveau ===
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.stable;
Nouveau is a set of free and open-source drivers for NVIDIA GPUs that provide 2D/3D acceleration for all NVIDIA GPUs. Its use is in general not recommended due to its considerably worse performance compared to NVIDIA's kernel modules, as it does not support reclocking (changing the GPU clock frequency on-demand) for many NVIDIA GPUs<ref>https://www.phoronix.com/forums/forum/linux-graphics-x-org-drivers/open-source-nvidia-linux-nouveau/998310-nouveau-persevered-in-2017-for-open-source-nvidia-but-2018-could-be-much-better#post998316</ref>. Nevertheless it remains a viable option for users who want a fully free and open-source operating system as it does not contain any proprietary components, unlike NVIDIA's kernel modules and userspace libraries.
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.beta;
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.production;  # (installs 550)
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.vulkan_beta;
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_470;
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_390;
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_340;
</syntaxhighlight>


Out of the above, `stable` and `beta` will work for the latest RTX cards and some lower cards so long as they're not considered "legacy" by Nvidia. For "legacy" cards, you can consult the [https://www.nvidia.com/en-us/drivers/unix/legacy-gpu/ Nvidia official legacy driver list] and check whether your device is supported by the 470, 390 or 340 branches. If so, you can use the corresponding <code>legacy_470</code>, <code>legacy_390</code> or <code>legacy_340</code> driver. For a full list of options, consult the [https://github.com/NixOS/nixpkgs/blob/nixos-unstable/pkgs/os-specific/linux/nvidia-x11/default.nix nvidia-x11 module repository].
Nouveau is enabled by default whenever graphics are enabled, and does not need any extra configuration.{{file|configuration.nix|nix|<nowiki>
 
{{note|As of early March 2024 the <code>production</code> driver has been updated from <code>535</code> to <code>550</code>. This is a breaking change for some people, especially those on Wayland.
To resolve this, follow the steps under [[Nvidia#Running the new RTX SUPER on NixOS stable|Running the new RTX SUPER on NixOS stable]]}}
 
Once you've determined the correct driver version, note it down; you'll need it in the next step.
 
== Modifying NixOS configuration ==
 
Ensure that the following is in your NixOS configuration file (customizing as you prefer):
 
{{warning|If you are using a laptop, the below configuration update is not sufficient to get your Nvidia card running! Once you've entered it, please continue reading, as there are important adjustments that must then be made to the configuration''' before your laptop graphics will work properly.}}
 
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{ config, lib, pkgs, ... }:
{
{
 
   hardware.graphics.enable = true;
  # Enable OpenGL
  hardware.opengl = {
    enable = true;
    driSupport = true;
    driSupport32Bit = true;
  };
 
  # Load "nvidia" driver for Xorg and Wayland
  services.xserver.videoDrivers = ["nvidia"];
 
   hardware.nvidia = {
 
    # Modesetting is required.
    modesetting.enable = true;
 
    # Nvidia power management. Experimental, and can cause sleep/suspend to fail.
    # Enable this if you have graphical corruption issues or application crashes after waking
    # up from sleep. This fixes it by saving the entire VRAM memory to /tmp/ instead
    # of just the bare essentials.
    powerManagement.enable = false;
 
    # Fine-grained power management. Turns off GPU when not in use.
    # Experimental and only works on modern Nvidia GPUs (Turing or newer).
    powerManagement.finegrained = false;
 
    # Use the NVidia open source kernel module (not to be confused with the
    # independent third-party "nouveau" open source driver).
    # Support is limited to the Turing and later architectures. Full list of
    # supported GPUs is at:
    # https://github.com/NVIDIA/open-gpu-kernel-modules#compatible-gpus
    # Only available from driver 515.43.04+
    # Currently "beta quality", so false is currently the recommended setting.
    open = false;
 
    # Enable the Nvidia settings menu,
# accessible via `nvidia-settings`.
    nvidiaSettings = true;
 
    # Optionally, you may need to select the appropriate driver version for your specific GPU.
    package = config.boot.kernelPackages.nvidiaPackages.stable;
  };
  ...
}
}
</nowiki>}}
</nowiki>}}


== Laptop configuration: hybrid graphics (Optimus PRIME) ==
== Configuring ==
 
In order to correctly finish configuring your Nvidia graphics driver, you must follow the below steps, which differ depending on whether or not you are using a hybrid graphics setup or not. A laptop with hybrid graphics possesses both an integrated GPU (often part of the central processor) and a discrete, more powerful Nvidia GPU, typically for performance-intensive tasks. This dual-GPU setup allows for power-saving during basic tasks and higher graphics performance when needed.
 
'''Nvidia Optimus PRIME''' is a technology developed by Nvidia to optimize the power consumption and performance of laptops equipped with their GPUs. It seamlessly switches between the integrated graphics, usually from Intel, for lightweight tasks to save power, and the discrete Nvidia GPU for performance-intensive tasks like gaming or video editing. By dynamically balancing graphics power and battery life, Optimus provides the best of both worlds, ensuring that users get longer battery life without sacrificing graphical performance.
 
=== Optimus PRIME: bus ID values (mandatory) ===
 
Before we can continue, we must first determine the bus ID values for both your Nvidia and Intel and AMD GPUs. This step will be essential regardless of which configuration you later adopt.
 
First, install the <code>lshw</code> package in order to be able to use the <code>lshw</code> command, then run:
 
<code>sudo lshw -c display</code>
 
You will likely get something like this:


<syntaxhighlight lang="bash">
=== Power management ===
*-display
description: i915drmfb
physical id: 0
bus info: pci@0000:0e:00.0
logical name: /dev/fb0
version: a1
width: 64 bits
clock: 33MHz
capabilities: pm msi pciexpress bus_master cap_list rom fb
configuration: depth=32 driver=nvidia latency=0 mode=2560x1600 visual=truecolor xres=2560 yres=1600
resources: iomemory:600-5ff iomemory:620-61f irq:220 memory:85000000-85ffffff memory:6000000000-61ffffffff memory:6200000000-6201ffffff ioport:5000(size=128) memory:86000000-8607ffff


*-display
=== Hybrid graphics with PRIME ===
product: i915drmfb
Laptops often feature both an integrated GPU (iGPU) and a dedicated GPU (dGPU) in order to strive a balance between performance and power consumption ­— while the dGPU is used for performance-intensive tasks such as gaming, video editing, 3D rendering, compute jobs, etc., the iGPU can be used to render common 2D elements like application windows and the desktop environment.
physical id: 2
bus info: pci@0000:00:02.0
logical name: /dev/fb0
version: 04
width: 64 bits
clock: 33MHz
capabilities: pciexpress msi pm bus_master cap_list rom fb
configuration: depth=32 driver=i915 latency=0 resolution=2560,1600
resources: iomemory:620-61f iomemory:400-3ff irq:221 memory:622e000000-622effffff memory:4000000000-400fffffff ioport:6000(size=64) memory:c0000-dffff memory:4010000000-4016ffffff memory:4020000000-40ffffffff
</syntaxhighlight>


Note the two values under "bus info" above, which may differ from laptop to laptop. Our Nvidia Bus ID is <code>0e:00.0</code> and our Intel Bus ID is <code>00:02.0</code>. Watch out for the formatting; convert them from hexadecimal to decimal, remove the padding (leading zeroes), replace the dot with a colon, then add them like this:
PRIME, therefore, is a technology developed to facilitate the cooperation between the two GPUs and is critical for the laptop's graphical performance. Depending on your needs, you can configure PRIME in one of three modes, which have different tradeoffs in terms of performance and battery life.


{{file|/etc/nixos/configuration.nix|nix|<nowiki>
==== Common setup ====
All PRIME configurations require setting the PCI bus IDs of the two GPUs. One easy way to do find their IDs is by running <code>lspci</code> from the <code>pciutils</code> package, and then finding devices that are classified as VGA controllers. After double checking that the listed devices are indeed your integrated and dedicated GPUs, you can then find the PCI IDs at the beginning of each line. Exact results may vary, but an example output might look like:<syntaxhighlight lang="console">
$ nix shell nixpkgs#pciutils -c lspci -d ::03xx
0000:00:02.0 VGA compatible controller: Intel Corporation TigerLake-H GT1 [UHD Graphics] (rev 01)
0000:01:00.0 VGA compatible controller: NVIDIA Corporation GA106M [GeForce RTX 3060 Mobile / Max-Q] (rev a1)
</syntaxhighlight>Before putting them into your configuration, however, '''they must first be reformatted''' — take the last three numbers, convert them from hexadecimal to decimal, remove the leading zeroes, concatenate them with colons, and then add a <code>PCI:</code> prefix. Then, they can be set under <code>intelBusId</code>, <code>nvidiaBusId</code>, or <code>amdgpuBusId</code> in <code>hardware.nvidia.prime</code>, depending on the manufacturer of the GPU:{{file|configuration.nix|nix|<nowiki>
{
{
hardware.nvidia.prime = {
  hardware.nvidia.prime = {
# Make sure to use the correct Bus ID values for your system!
    intelBusId = "PCI:0:2:0";
intelBusId = "PCI:0:2:0";
    nvidiaBusId = "PCI:1:0:0";
nvidiaBusId = "PCI:14:0:0";
    #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
        # amdgpuBusId = "PCI:54:0:0"; For AMD GPU
  };
};
}
}
</nowiki>}}
</nowiki>}}
=== Optimus PRIME modes ===


==== Offload mode ====
==== Offload mode ====
{{Note|Offload mode is available '''since NixOS 20.09 and NVIDIA driver version 435.21''', and requires an NVIDIA GPU of the Turing generation, or newer and a compatible CPU — either an Intel CPU from the Coffee Lake generation or newer, or an AMD Ryzen. Offload mode is '''incompatible''' with sync mode.}}
Offload mode puts your dGPU to sleep and lets the iGPU handle all tasks, except if you call the dGPU specifically by "offloading" an application to it. For example, you can run your laptop normally and it will use the energy-efficient iGPU all day, and then you can offload a game from Steam onto the dGPU to make the dGPU run that game only. For many, this is the most desirable option.


:''Offload mode is available in NixOS 20.09 and higher, and requires an Nvidia card of the Turing generation or newer, an Intel chipset from the Coffee Lake generation or newer, or an AMD Ryzen CPU like the 5800H .''
To enable offload mode, set the <code>hardware.nvidia.prime.offload.enable</code> option to <code>true</code>:


Offload mode puts your Nvidia GPU to sleep and lets the Intel GPU handle all tasks, except if you call the Nvidia GPU specifically by "offloading" an application to it. For example, you can run your laptop normally and it will use the energy-efficient Intel GPU all day, and then you can offload a game from Steam onto the Nvidia GPU to make the Nvidia GPU run that game only. For many, this is the most desirable option.
{{file|configuration.nix|nix|<nowiki>
 
{
Offload mode is enabled by running your programs with specific environment variables. Here's a sample script called <code>nvidia-offload</code> that you can run wrapped around your executable, for example <code>nvidia-offload glxgears</code>:
  hardware.nvidia.prime = {
 
    offload.enable = true;
{{file|nvidia-offload|bash|<nowiki>
   
    intelBusId = "PCI:0:2:0";
    nvidiaBusId = "PCI:1:0:0";
    #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
  };
}
</nowiki>}}When you want to run a program on the dGPU, you only need to set a few environment variables for the driver to recognize that offload mode should be used. If <code>hardware.nvidia.prime.offload.enableOffloadCmd</code> is set to true, NixOS will generate a wrapper script named <code>nvidia-offload</code> that sets the right variables for you:{{file|nvidia-offload|bash|<nowiki>
export __NV_PRIME_RENDER_OFFLOAD=1
export __NV_PRIME_RENDER_OFFLOAD=1
export __NV_PRIME_RENDER_OFFLOAD_PROVIDER=NVIDIA-G0
export __NV_PRIME_RENDER_OFFLOAD_PROVIDER=NVIDIA-G0
Line 170: Line 99:
export __VK_LAYER_NV_optimus=NVIDIA_only
export __VK_LAYER_NV_optimus=NVIDIA_only
exec "$@"
exec "$@"
</nowiki>}}
</nowiki>}}If everything is configured correctly, then running a program like <code>glxgears</code> should use the iGPU, while running <code>nvidia-offload glxgears</code> should only use the dGPU.
To enable offload mode, finish configuring your Nvidia driver by adding the following to your NixOS configuration file:
 
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{
hardware.nvidia.prime = {
offload = {
enable = true;
enableOffloadCmd = true;
};
# Make sure to use the correct Bus ID values for your system!
intelBusId = "PCI:0:2:0";
nvidiaBusId = "PCI:14:0:0";
        # amdgpuBusId = "PCI:54:0:0"; For AMD GPU.  
};
}
</nowiki>}}


==== Sync mode ====
==== Sync mode ====
{{Note|Sync mode is available '''since NixOS 19.03 and NVIDIA driver version 390.67''', and is '''incompatible''' with both offload and reverse sync modes. Sync mode also requires using a desktop manager that respects the <code>services.xserver.displayManager.setupCommands</code> option, including LightDM, GDM and SDDM.}}In sync mode, rendering is completely delegated to the dGPU, while the iGPU only displays the rendered framebuffers copied from the dGPU. Sync mode offers better performance and greatly reduces screen tearing, at the expense of higher power consumption since the dGPU will not go to sleep when not needed, as is the case in offload mode. Sync mode may also solve some issues with connecting a display in clamshell mode directly to the GPU.


Enabling PRIME sync introduces better performance and greatly reduces screen tearing, at the expense of higher power consumption since the Nvidia GPU will not go to sleep completely unless called for, as is the case in Offload Mode. It may also cause its own issues in rare cases. '''PRIME Sync and Offload Mode cannot be enabled at the same time.'''
To enable sync mode, set the <code>hardware.nvidia.prime.sync.enable</code> option to <code>true</code>:
 
PRIME sync may also solve some issues with connecting a display in clamshell mode directly to the GPU.


{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
Line 199: Line 110:
   hardware.nvidia.prime = {
   hardware.nvidia.prime = {
     sync.enable = true;
     sync.enable = true;
 
      
     # Make sure to use the correct Bus ID values for your system!
    nvidiaBusId = "PCI:14:0:0";
     intelBusId = "PCI:0:2:0";
     intelBusId = "PCI:0:2:0";
     # amdgpuBusId = "PCI:54:0:0"; For AMD GPU
    nvidiaBusId = "PCI:1:0:0";
     #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
   };
   };
}
}
</nowiki>}}
</nowiki>}}


==== Reverse sync mode (experimental) ====
==== Reverse sync mode ====
{{Note|Reverse sync mode is available '''since NixOS 23.05 and NVIDIA driver version 460.39''' and is still an experimental, buggy feature<ref>https://forums.developer.nvidia.com/t/the-all-new-outputsink-feature-aka-reverse-prime/129828/67</ref>. '''Your mileage may vary.''' Reverse sync mode is '''incompatible''' with sync mode and requires using a desktop manager that respects the <code>services.xserver.displayManager.setupCommands</code> option, including LightDM, GDM and SDDM.}}The difference between regular sync mode and reverse sync mode is that the '''dGPU''' is configured as the primary output device, allowing displaying to external displays wired to it and not the iGPU (more common). 


This feature is relatively new and may not work properly on all systems ([https://forums.developer.nvidia.com/t/the-all-new-outputsink-feature-aka-reverse-prime/129828 see discussion]). It is only available on driver 460.39 or newer. Reverse sync only works with <code>services.xserver.displayManager.setupCommands</code> compatible Display Managers (LightDM, GDM and SDDM).
To enable sync mode, set the <code>hardware.nvidia.prime.reverseSync.enable</code> option to <code>true</code>:


{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
Line 216: Line 127:
   hardware.nvidia.prime = {
   hardware.nvidia.prime = {
     reverseSync.enable = true;
     reverseSync.enable = true;
    # Enable if using an external GPU
    allowExternalGpu = false;


    # Make sure to use the correct Bus ID values for your system!
     intelBusId = "PCI:0:2:0";
     intelBusId = "PCI:0:2:0";
     nvidiaBusId = "PCI:14:0:0";
     nvidiaBusId = "PCI:1:0:0";
     # amdgpuBusId = "PCI:54:0:0"; For AMD GPU
     #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
   };
   };
}
}
</nowiki>}}
</nowiki>}}


== Useful tips ==
== Tips and tricks ==


=== Check nixos-hardware ===
=== Check nixos-hardware ===
You should check the [https://github.com/NixOS/nixos-hardware nixos-hardware] GitHub repository. It is possible that someone already wrote a hardware configuration for your device and that usually takes care of drivers. If so, follow the upstream documentation to enable the required modules.   
The [https://github.com/NixOS/nixos-hardware nixos-hardware] project attempts to provide configurations that address specific hardware quirks for different devices. It is possible that someone already wrote a hardware configuration for your device and that usually takes care of drivers. If so, follow the upstream documentation to enable the required modules.   


=== Multiple boot configurations ===
=== Multiple boot configurations ===
Line 241: Line 149:
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{
{
 
  specialisation.on-the-go.configuration = {
specialisation = {
  on-the-go.configuration = {
     system.nixos.tags = [ "on-the-go" ];
     system.nixos.tags = [ "on-the-go" ];
     hardware.nvidia = {
     hardware.nvidia.prime = {
       prime.offload.enable = lib.mkForce true;
       offload = {
      prime.offload.enableOffloadCmd = lib.mkForce true;
        enable = lib.mkForce true;
       prime.sync.enable = lib.mkForce false;
        enableOffloadCmd = lib.mkForce true;
       };
      sync.enable = lib.mkForce false;  
     };
     };
   };
   };
};
}
}
</nowiki>}}
</nowiki>}}


(You can also add other settings here totally unrelated to Nvidia, such as power profiles, etc.)
(You can also add other settings here totally unrelated to NVIDIA, such as power profiles, etc.)


After rebuilding and rebooting, you'll see in your boot menu under each Generation an "on-the-go" option, which will let you boot into the on-to-go specialisation for that generation.
After rebuilding and rebooting, you'll see in your boot menu under each Generation an "on-the-go" option, which will let you boot into the on-to-go specialisation for that generation.
Line 263: Line 169:
If you're using Nix-packaged software on a non-NixOS system, you'll need a workaround to get everything up-and-running. The [https://github.com/guibou/nixGL nixGL project] provides wrapper to use GL drivers on non-NixOS systems. You need to have GPU drivers installed on your distro (for kernel modules). With nixGL installed, you'll run <code>nixGL foobar</code> instead of  <code>foobar</code>.
If you're using Nix-packaged software on a non-NixOS system, you'll need a workaround to get everything up-and-running. The [https://github.com/guibou/nixGL nixGL project] provides wrapper to use GL drivers on non-NixOS systems. You need to have GPU drivers installed on your distro (for kernel modules). With nixGL installed, you'll run <code>nixGL foobar</code> instead of  <code>foobar</code>.


Note that nixGL is not specific to Nvidia GPUs, and should work with just about any GPU.
Note that nixGL is not specific to NVIDIA GPUs, and should work with just about any GPU.


=== CUDA and using your GPU for compute ===
=== CUDA and using your GPU for compute ===
See the [[CUDA]] wiki page.
See the [[CUDA]] wiki page.


=== Using Steam in offload mode ===
=== Running Specific NVIDIA Driver Versions ===
In order to automatically launch Steam in offload mode, you need to add the following to your <code>~/.bashrc</code>:
<syntaxhighlight lang="bash">
export XDG_DATA_HOME="$HOME/.local/share"
</syntaxhighlight>   
 
Then, if you are using NixOS Steam, run:
 
<syntaxhighlight lang="bash">
mkdir -p ~/.local/share/applications
sed 's/^Exec=/&nvidia-offload /' /run/current-system/sw/share/applications/steam.desktop > ~/.local/share/applications/steam.desktop
</syntaxhighlight>


For Flatpak Steam, run:
To run a specific version of the NVIDIA driver in NixOS, you can customize your configuration by specifying the desired version along with the corresponding SHA256 hashes. Below is an example configuration for using NVIDIA driver version <code>555.58.02</code>:
 
<syntaxhighlight lang="bash">
mkdir -p ~/.local/share/applications
sed 's/^Exec=/&nvidia-offload /' /var/lib/flatpak/exports/share/applications/com.valvesoftware.Steam.desktop > ~/.local/share/applications/com.valvesoftware.steam.desktop
</syntaxhighlight>
 
Then restart your graphical environment session (or simply reboot).
 
=== Running the new RTX SUPER on NixOS stable ===
 
The new RTX Super cards are not supported by the 545 driver. On NixOS stable, you want to use the 535 driver that come from unstable branch or the 550 (beta).
To do that you need to manually call the driver you want in your config.
Check on this link to choose the driver you want and change your config accordingly :
https://github.com/NixOS/nixpkgs/blob/979a311fbd179b86200e412a3ed266b64808df4e/pkgs/os-specific/linux/nvidia-x11/default.nix#L36


{{file|/etc/nixos/nvidia.nix|nix|<nowiki>
{{file|/etc/nixos/nvidia.nix|nix|<nowiki>
{ pkgs, config, libs, ... }:
{ config, ... }:
 
{
{
 
   hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.mkDriver {
# Enable OpenGL
     version = "555.58.02";
   hardware.opengl = {
    sha256_64bit = "sha256-xctt4TPRlOJ6r5S54h5W6PT6/3Zy2R4ASNFPu8TSHKM=";
     enable = true;
     sha256_aarch64 = "sha256-xctt4TPRlOJ6r5S54h5W6PT6/3Zy2R4ASNFPu8TSHKM=";
     driSupport = true;
     openSha256 = "sha256-ZpuVZybW6CFN/gz9rx+UJvQ715FZnAOYfHn5jt5Z2C8=";
     driSupport32Bit = true;
    settingsSha256 = "sha256-ZpuVZybW6CFN/gz9rx+UJvQ715FZnAOYfHn5jt5Z2C8=";
    persistencedSha256 = lib.fakeSha256;
   };
   };
};
</nowiki>}}


# Load nvidia driver for Xorg and Wayland
In this configuration:
  services.xserver.videoDrivers = ["nvidia"];
 
  hardware.nvidia.modesetting.enable = true;
  hardware.nvidia.powerManagement.enable = false;
  hardware.nvidia.powerManagement.finegrained = false;
  hardware.nvidia.open = false;
  hardware.nvidia.nvidiaSettings = true;
# Special config to load the latest (535 or 550) driver for the support of the 4070 SUPER
  hardware.nvidia.package = let
  rcu_patch = pkgs.fetchpatch {
    url = "https://github.com/gentoo/gentoo/raw/c64caf53/x11-drivers/nvidia-drivers/files/nvidia-drivers-470.223.02-gpl-pfn_valid.patch";
    hash = "sha256-eZiQQp2S/asE7MfGvfe6dA/kdCvek9SYa/FFGp24dVg=";
  };
in config.boot.kernelPackages.nvidiaPackages.mkDriver {
    version = "535.154.05";
    sha256_64bit = "sha256-fpUGXKprgt6SYRDxSCemGXLrEsIA6GOinp+0eGbqqJg=";
    sha256_aarch64 = "sha256-G0/GiObf/BZMkzzET8HQjdIcvCSqB1uhsinro2HLK9k=";
    openSha256 = "sha256-wvRdHguGLxS0mR06P5Qi++pDJBCF8pJ8hr4T8O6TJIo=";
    settingsSha256 = "sha256-9wqoDEWY4I7weWW05F4igj1Gj9wjHsREFMztfEmqm10=";
    persistencedSha256 = "sha256-d0Q3Lk80JqkS1B54Mahu2yY/WocOqFFbZVBh+ToGhaE=";


    #version = "550.40.07";
* Replace <code>version</code> with the desired driver version.
    #sha256_64bit = "sha256-KYk2xye37v7ZW7h+uNJM/u8fNf7KyGTZjiaU03dJpK0=";
* Update the SHA256 hashes to match the new version you want to use.
    #sha256_aarch64 = "sha256-AV7KgRXYaQGBFl7zuRcfnTGr8rS5n13nGUIe3mJTXb4=";
* After updating the configuration, run <code>sudo nixos-rebuild switch</code> to apply the changes and load the specified NVIDIA driver version.
    #openSha256 = "sha256-mRUTEWVsbjq+psVe+kAT6MjyZuLkG2yRDxCMvDJRL1I=";
    #settingsSha256 = "sha256-c30AQa4g4a1EHmaEu1yc05oqY01y+IusbBuq+P6rMCs=";
    #persistencedSha256 = "sha256-11tLSY8uUIl4X/roNnxf5yS2PQvHvoNjnd2CB67e870=";


    patches = [ rcu_patch ];
This allows you to pin the specific driver version being used in your NixOS installation.
};
}
</nowiki>}}


== Troubleshooting ==
== Troubleshooting ==


=== Booting to text mode ===
=== Booting to text mode ===
If you encounter the problem of booting to text mode you might try adding the Nvidia kernel module manually with:
If you encounter the problem of booting to text mode you might try adding the NVIDIA kernel module manually with:


<syntaxHighlight lang="nix">
<syntaxHighlight lang="nix">
Line 373: Line 230:
<code>powerManagement.enable = true</code> can sometimes fix this, but is itself unstable and is known to cause suspend issues.
<code>powerManagement.enable = true</code> can sometimes fix this, but is itself unstable and is known to cause suspend issues.


If you have a modern Nvidia GPU (Turing [https://en.wikipedia.org/wiki/Turing_(microarchitecture)#Products_using_Turing] or later), you may also want to investigate the <code>hardware.nvidia.powerManagement.finegrained</code> option: [https://download.nvidia.com/XFree86/Linux-x86_64/460.73.01/README/dynamicpowermanagement.html]
If you have a modern NVIDIA GPU (Turing [https://en.wikipedia.org/wiki/Turing_(microarchitecture)#Products_using_Turing] or later), you may also want to investigate the <code>hardware.nvidia.powerManagement.finegrained</code> option: [https://download.nvidia.com/XFree86/Linux-x86_64/460.73.01/README/dynamicpowermanagement.html]


=== Black screen or 'nothing works' on laptops ===
=== Black screen or 'nothing works' on laptops ===
The kernel module<code>i915</code>for Intel or<code>amdgpu</code>for AMD may interfere with the Nvidia driver. This may result in a black screen when switching to the virtual terminal, or when exiting the X session. A possible workaround is to disable the integrated GPU by blacklisting the module, using the following configuration option (see also [https://discourse.nixos.org/t/nvidia-gpu-and-i915-kernel-module/21307/3]):
The kernel module<code>i915</code>for Intel or<code>amdgpu</code>for AMD may interfere with the NVIDIA driver. This may result in a black screen when switching to the virtual terminal, or when exiting the X session. A possible workaround is to disable the integrated GPU by blacklisting the module, using the following configuration option (see also [https://discourse.nixos.org/t/nvidia-gpu-and-i915-kernel-module/21307/3]):


<syntaxHighlight lang="nix">
<syntaxHighlight lang="nix">
Line 385: Line 242:
</syntaxHighlight>
</syntaxHighlight>


= The Nvidia open driver =
== Disabling ==
The Nvidia open driver is enabled via:
<syntaxHighlight lang="nix">
services.xserver.videoDrivers = [ "nvidia" ];
hardware.nvidia.open = true;
</syntaxHighlight>
 
The Nvidia open driver is ''very'' similar to its proprietary sibling. Most content in the proprietary section above apply; just copy over the proprietary config above and toggle the "open" option, and you are set.


Like its proprietary sibling, it also requires some non-free userspace packages that allow software to talk to the kernel driver. As a result, you still need to enable unfree packages.
=== Kernel modules from NVIDIA ===
Normally, NVIDIA's kernel modules should be completely disabled by removing <code>"nvidia"</code> from <code>services.xserver.videoDrivers</code>. If that fails to work, you can also manually blacklist the corresponding kernel modules:<syntaxhighlight lang="nix">
{
  boot.blacklistedKernelModules = [
    "nvidia"
    "nvidiafb"
    "nvidia-drm"
    "nvidia-uvm"
    "nvidia-modeset"
  ];
}
</syntaxhighlight>


Be warned that the Nvidia open driver is considered "beta quality". Performance may be very slightly lower.
=== Nouveau ===
 
Nouveau can be disabled by blacklisting the <code>nouveau</code> kernel module:<syntaxhighlight lang="nix">
= Disable Nvidia dGPU completely =
{  
 
   boot.blacklistedKernelModules = [ "nouveau" ];
It's possible to completely disable the dGPU, saving battery. Probably not all configurations and module blacklists are required but this worked successfully:
}
 
</syntaxhighlight>Note that disabling both NVIDIA kernel modules and Nouveau effectively disables the GPU entirely.
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
boot.extraModprobeConfig = ''
  blacklist nouveau
  options nouveau modeset=0
'';
 
services.udev.extraRules = ''
  # Remove NVIDIA USB xHCI Host Controller devices, if present
  ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x0c0330", ATTR{power/control}="auto", ATTR{remove}="1"
  # Remove NVIDIA USB Type-C UCSI devices, if present
  ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x0c8000", ATTR{power/control}="auto", ATTR{remove}="1"
   # Remove NVIDIA Audio devices, if present
  ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x040300", ATTR{power/control}="auto", ATTR{remove}="1"
  # Remove NVIDIA VGA/3D controller devices
  ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x03[0-9]*", ATTR{power/control}="auto", ATTR{remove}="1"
'';
boot.blacklistedKernelModules = [ "nouveau" "nvidia" "nvidia_drm" "nvidia_modeset" ];
</nowiki>}}


== Footnotes ==
[[Category:Video]]
[[Category:Video]]

Latest revision as of 16:35, 22 December 2024

This page attempts to cover everything related to the use of NVIDIA GPUs on NixOS.

Enabling

Kernel modules from NVIDIA

Kernel modules from NVIDIA offer better performance than other alternatives, but make the system unfree by requiring proprietary userspace libraries that can interface with the kernel modules. Users that want to have a fully free and open-source system should use Nouveau instead.

To enable them, add "nvidia" to the list of enabled video drivers defined by the services.xserver.videoDrivers option.

Note: hardware.graphics.enable was named hardware.opengl.enable until NixOS 24.11.
Note: Since driver version 560, you also will need to decide whether to use the open-source or proprietary modules by setting the hardware.nvidia.open option to either true or false respectively.

Open-source kernel modules are preferred over and planned to steadily replace proprietary modules[1], although they only support GPUs of the Turing architecture or newer (from GeForce RTX 20 series and GeForce GTX 16 series onwards). Data center GPUs starting from Grace Hopper or Blackwall must use open-source modules — proprietary modules are no longer supported.

If you're using proprietary modules, make sure to allow unfree software. The unfree NVIDIA packages include nvidia-x11, nvidia-settings, and nvidia-persistenced.
Warning: If you use a laptop with both dedicated and integrated GPUs, remember to configure PRIME in order to make your dedicated NVIDIA GPU work properly with your integrated GPU. Your configuration might not work if you skip this step.
configuration.nix
{
  hardware.graphics.enable = true;

  services.xserver.videoDrivers = [ "nvidia" ];
  hardware.nvidia.open = true; # Set to false for proprietary drivers
}

Legacy branches

GPUs of the Kepler architecture or older (most GeForce 600/700/800M cards and older) are no longer supported by latest proprietary modules. Instead, users of these GPUs must use legacy branches that may still receive updates, as long as the GPUs themselves remain supported by NVIDIA. You can find which legacy branch you need to use by searching for your GPU model on NVIDIA's official legacy driver support list.

To use legacy branches, you need to set the hardware.nvidia.package option to a package set named config.boot.kernelPackages.nvidiaPackages.legacy_<branch>.

configuration.nix
{ config, ... }: # ← Required to get the packages used by the currently configured kernel, including drivers
{ 
  # Last version that supports Kepler GPUs
  hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_470;
}

Nixpkgs does not endeavor to support all legacy branches since older, unmaintained legacy branches can become incompatible with newer kernel and X server versions, and at some point it becomes infeasible to patch them to cooperate with modern software. You can find the list of supported legacy branches under in the Nixpkgs repository.

Beta/production branches

By default, modules from the stable branch are used, which come from latest release available for the current architecture — while x86-64 and aarch64 systems follow the "New Feature Branch" releases as they remain actively developed, 32-bit x86 and ARM systems remain on the 390.xx branch as that is the last branch with 32-bit support.

Instead of the stable branch, users can also switch to the beta branch, which has more new features and experimental changes at the risk of containing more bugs, or the production branch, a more conservative, well-tested stable version that is suitable for production use with minimum breakage, at the cost of being behind in terms of new features.

Using the beta and production branches are similar to how one would use legacy branches:

configuration.nix
{ config, ... }:
{ 
  #hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.stable; # Default
  hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.beta;
  hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.production;
}

Nouveau

Nouveau is a set of free and open-source drivers for NVIDIA GPUs that provide 2D/3D acceleration for all NVIDIA GPUs. Its use is in general not recommended due to its considerably worse performance compared to NVIDIA's kernel modules, as it does not support reclocking (changing the GPU clock frequency on-demand) for many NVIDIA GPUs[2]. Nevertheless it remains a viable option for users who want a fully free and open-source operating system as it does not contain any proprietary components, unlike NVIDIA's kernel modules and userspace libraries.

Nouveau is enabled by default whenever graphics are enabled, and does not need any extra configuration.

configuration.nix
{
  hardware.graphics.enable = true;
}

Configuring

Power management

Hybrid graphics with PRIME

Laptops often feature both an integrated GPU (iGPU) and a dedicated GPU (dGPU) in order to strive a balance between performance and power consumption ­— while the dGPU is used for performance-intensive tasks such as gaming, video editing, 3D rendering, compute jobs, etc., the iGPU can be used to render common 2D elements like application windows and the desktop environment.

PRIME, therefore, is a technology developed to facilitate the cooperation between the two GPUs and is critical for the laptop's graphical performance. Depending on your needs, you can configure PRIME in one of three modes, which have different tradeoffs in terms of performance and battery life.

Common setup

All PRIME configurations require setting the PCI bus IDs of the two GPUs. One easy way to do find their IDs is by running lspci from the pciutils package, and then finding devices that are classified as VGA controllers. After double checking that the listed devices are indeed your integrated and dedicated GPUs, you can then find the PCI IDs at the beginning of each line. Exact results may vary, but an example output might look like:

$ nix shell nixpkgs#pciutils -c lspci -d ::03xx
0000:00:02.0 VGA compatible controller: Intel Corporation TigerLake-H GT1 [UHD Graphics] (rev 01)
0000:01:00.0 VGA compatible controller: NVIDIA Corporation GA106M [GeForce RTX 3060 Mobile / Max-Q] (rev a1)

Before putting them into your configuration, however, they must first be reformatted — take the last three numbers, convert them from hexadecimal to decimal, remove the leading zeroes, concatenate them with colons, and then add a PCI: prefix. Then, they can be set under intelBusId, nvidiaBusId, or amdgpuBusId in hardware.nvidia.prime, depending on the manufacturer of the GPU:

configuration.nix
{
  hardware.nvidia.prime = {
    intelBusId = "PCI:0:2:0";
    nvidiaBusId = "PCI:1:0:0";
    #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
  };
}

Offload mode

Note: Offload mode is available since NixOS 20.09 and NVIDIA driver version 435.21, and requires an NVIDIA GPU of the Turing generation, or newer and a compatible CPU — either an Intel CPU from the Coffee Lake generation or newer, or an AMD Ryzen. Offload mode is incompatible with sync mode.

Offload mode puts your dGPU to sleep and lets the iGPU handle all tasks, except if you call the dGPU specifically by "offloading" an application to it. For example, you can run your laptop normally and it will use the energy-efficient iGPU all day, and then you can offload a game from Steam onto the dGPU to make the dGPU run that game only. For many, this is the most desirable option.

To enable offload mode, set the hardware.nvidia.prime.offload.enable option to true:

configuration.nix
{
  hardware.nvidia.prime = {
    offload.enable = true;
    
    intelBusId = "PCI:0:2:0";
    nvidiaBusId = "PCI:1:0:0";
    #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
  };
}

When you want to run a program on the dGPU, you only need to set a few environment variables for the driver to recognize that offload mode should be used. If hardware.nvidia.prime.offload.enableOffloadCmd is set to true, NixOS will generate a wrapper script named nvidia-offload that sets the right variables for you:

nvidia-offload
export __NV_PRIME_RENDER_OFFLOAD=1
export __NV_PRIME_RENDER_OFFLOAD_PROVIDER=NVIDIA-G0
export __GLX_VENDOR_LIBRARY_NAME=nvidia
export __VK_LAYER_NV_optimus=NVIDIA_only
exec "$@"

If everything is configured correctly, then running a program like glxgears should use the iGPU, while running nvidia-offload glxgears should only use the dGPU.

Sync mode

Note: Sync mode is available since NixOS 19.03 and NVIDIA driver version 390.67, and is incompatible with both offload and reverse sync modes. Sync mode also requires using a desktop manager that respects the services.xserver.displayManager.setupCommands option, including LightDM, GDM and SDDM.

In sync mode, rendering is completely delegated to the dGPU, while the iGPU only displays the rendered framebuffers copied from the dGPU. Sync mode offers better performance and greatly reduces screen tearing, at the expense of higher power consumption since the dGPU will not go to sleep when not needed, as is the case in offload mode. Sync mode may also solve some issues with connecting a display in clamshell mode directly to the GPU.

To enable sync mode, set the hardware.nvidia.prime.sync.enable option to true:

/etc/nixos/configuration.nix
{
  hardware.nvidia.prime = {
    sync.enable = true;
    
    intelBusId = "PCI:0:2:0";
    nvidiaBusId = "PCI:1:0:0";
    #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
  };
}

Reverse sync mode

Note: Reverse sync mode is available since NixOS 23.05 and NVIDIA driver version 460.39 and is still an experimental, buggy feature[3]. Your mileage may vary. Reverse sync mode is incompatible with sync mode and requires using a desktop manager that respects the services.xserver.displayManager.setupCommands option, including LightDM, GDM and SDDM.

The difference between regular sync mode and reverse sync mode is that the dGPU is configured as the primary output device, allowing displaying to external displays wired to it and not the iGPU (more common).

To enable sync mode, set the hardware.nvidia.prime.reverseSync.enable option to true:

/etc/nixos/configuration.nix
{
  hardware.nvidia.prime = {
    reverseSync.enable = true;

    intelBusId = "PCI:0:2:0";
    nvidiaBusId = "PCI:1:0:0";
    #amdgpuBusId = "PCI:54:0:0"; # If you have an AMD iGPU
  };
}

Tips and tricks

Check nixos-hardware

The nixos-hardware project attempts to provide configurations that address specific hardware quirks for different devices. It is possible that someone already wrote a hardware configuration for your device and that usually takes care of drivers. If so, follow the upstream documentation to enable the required modules.

Multiple boot configurations

Imagine you have a laptop that you mostly use in clamshell mode (docked, connected to an external display and plugged into a charger) but that you sometimes use on the go.

In clamshell mode, using PRIME Sync is likely to lead to better performance, external display support, etc., at the cost of potentially (but not always) lower battery life. However, when using the laptop on the go, you may prefer to use offload mode.

NixOS supports "specialisations", which allow you to automatically generate different boot profiles when rebuilding your system. We can, for example, enable PRIME sync by default, but also create a "on-the-go" specialization that disables PRIME sync and instead enables offload mode:

/etc/nixos/configuration.nix
{
  specialisation.on-the-go.configuration = {
    system.nixos.tags = [ "on-the-go" ];
    hardware.nvidia.prime = {
      offload = {
        enable = lib.mkForce true;
        enableOffloadCmd = lib.mkForce true;
      };
      sync.enable = lib.mkForce false;    
    };
  };
}

(You can also add other settings here totally unrelated to NVIDIA, such as power profiles, etc.)

After rebuilding and rebooting, you'll see in your boot menu under each Generation an "on-the-go" option, which will let you boot into the on-to-go specialisation for that generation.

Using GPUs on non-NixOS

If you're using Nix-packaged software on a non-NixOS system, you'll need a workaround to get everything up-and-running. The nixGL project provides wrapper to use GL drivers on non-NixOS systems. You need to have GPU drivers installed on your distro (for kernel modules). With nixGL installed, you'll run nixGL foobar instead of foobar.

Note that nixGL is not specific to NVIDIA GPUs, and should work with just about any GPU.

CUDA and using your GPU for compute

See the CUDA wiki page.

Running Specific NVIDIA Driver Versions

To run a specific version of the NVIDIA driver in NixOS, you can customize your configuration by specifying the desired version along with the corresponding SHA256 hashes. Below is an example configuration for using NVIDIA driver version 555.58.02:

/etc/nixos/nvidia.nix
{ config, ... }:
{
  hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.mkDriver {
    version = "555.58.02";
    sha256_64bit = "sha256-xctt4TPRlOJ6r5S54h5W6PT6/3Zy2R4ASNFPu8TSHKM=";
    sha256_aarch64 = "sha256-xctt4TPRlOJ6r5S54h5W6PT6/3Zy2R4ASNFPu8TSHKM=";
    openSha256 = "sha256-ZpuVZybW6CFN/gz9rx+UJvQ715FZnAOYfHn5jt5Z2C8=";
    settingsSha256 = "sha256-ZpuVZybW6CFN/gz9rx+UJvQ715FZnAOYfHn5jt5Z2C8=";
    persistencedSha256 = lib.fakeSha256;
  };
};

In this configuration:

  • Replace version with the desired driver version.
  • Update the SHA256 hashes to match the new version you want to use.
  • After updating the configuration, run sudo nixos-rebuild switch to apply the changes and load the specified NVIDIA driver version.

This allows you to pin the specific driver version being used in your NixOS installation.

Troubleshooting

Booting to text mode

If you encounter the problem of booting to text mode you might try adding the NVIDIA kernel module manually with:

boot.initrd.kernelModules = [ "nvidia" ];
boot.extraModulePackages = [ config.boot.kernelPackages.nvidia_x11 ];

Screen tearing issues

First, try to switch to PRIME sync mode, as described above. If that doesn't work, try forcing a composition pipeline.

Note: Forcing a full composition pipeline has been reported to reduce the performance of some OpenGL applications and may produce issues in WebGL. It also drastically increases the time the driver needs to clock down after load.
/etc/nixos/configuration.nix
hardware.nvidia.forceFullCompositionPipeline = true;

Flickering with Picom

~/.config/picom/picom.conf
unredir-if-possible = false;
backend = "xrender"; # try "glx" if xrender doesn't help
vsync = true;

Graphical corruption and system crashes on suspend/resume

powerManagement.enable = true can sometimes fix this, but is itself unstable and is known to cause suspend issues.

If you have a modern NVIDIA GPU (Turing [1] or later), you may also want to investigate the hardware.nvidia.powerManagement.finegrained option: [2]

Black screen or 'nothing works' on laptops

The kernel modulei915for Intel oramdgpufor AMD may interfere with the NVIDIA driver. This may result in a black screen when switching to the virtual terminal, or when exiting the X session. A possible workaround is to disable the integrated GPU by blacklisting the module, using the following configuration option (see also [3]):

# intel
boot.kernelParams = [ "module_blacklist=i915" ];
# AMD
boot.kernelParams = [ "module_blacklist=amdgpu" ];

Disabling

Kernel modules from NVIDIA

Normally, NVIDIA's kernel modules should be completely disabled by removing "nvidia" from services.xserver.videoDrivers. If that fails to work, you can also manually blacklist the corresponding kernel modules:

{ 
  boot.blacklistedKernelModules = [
    "nvidia"
    "nvidiafb"
    "nvidia-drm"
    "nvidia-uvm"
    "nvidia-modeset"
  ];
}

Nouveau

Nouveau can be disabled by blacklisting the nouveau kernel module:

{ 
  boot.blacklistedKernelModules = [ "nouveau" ];
}

Note that disabling both NVIDIA kernel modules and Nouveau effectively disables the GPU entirely.

Footnotes