NixOS on ARM/Raspberry Pi 4: Difference between revisions

From NixOS Wiki
imported>Samueldr
m (Removed stray newline)
imported>Christoph-heiss
m (fix more angle brackets in code sample)
(41 intermediate revisions by 23 users not shown)
Line 4: Line 4:
!colspan="2" class="title"|Raspberry Pi 4 Family
!colspan="2" class="title"|Raspberry Pi 4 Family
|-
|-
|colspan="2"|(Image not available)
|colspan="2"|[[File:Raspberry_Pi_4,_2_GB_RAM_version_4.jpg|frameless|256px|A Raspberry Pi 4.]]
|-
|-
!Manufacturer
!Manufacturer
Line 27: Line 27:
|}
|}
</div>
</div>
The Raspberry Pi family of devices is a series of single-board computers made by the Raspberry Pi Foundation. They are all based on Broadcom System-on-a-chip (SOCs).  
The Raspberry Pi family of devices is a series of single-board computers made by the Raspberry Pi Foundation. They are all based on Broadcom System-on-a-chip (SoCs).


== Status ==
== Status ==
{{note|The Raspberry Pi 4 is currently <em>unsupported</em> though the NixOS distribution provides upstream beta-quality images.}}
The default Linux kernel in use, is the Raspberry Pi Foundation's fork. This will change for the mainline kernel once its support for the Raspberry Pi 4 Family is good enough to allow the user to boot, configure, and rebuild a system.


The Raspberry Pi 4 Family is only supported as '''AArch64'''. Use as armv7 is community supported.
The Raspberry Pi 4 Family is only supported as '''AArch64'''. Use as armv7 is community supported.
Line 41: Line 37:
First follow the [[NixOS_on_ARM#Installation|generic installation steps]] to get the installer image and install using the [[NixOS_on_ARM#NixOS_installation_.26_configuration|installation and configuration steps]].
First follow the [[NixOS_on_ARM#Installation|generic installation steps]] to get the installer image and install using the [[NixOS_on_ARM#NixOS_installation_.26_configuration|installation and configuration steps]].


Until the generic image works, a [https://hydra.nixos.org/job/nixos/trunk-combined/nixos.sd_image_raspberrypi4.aarch64-linux temporary device-specific image is build on Hydra]. Note that this image is not using u-boot, but rather the Raspberry Pi specific bootloader configuration.
The Raspberry Pi 4B works with the [https://hydra.nixos.org/job/nixos/trunk-combined/nixos.sd_image.aarch64-linux generic SD image].
 
Sample instructions for [https://nix.dev/tutorials/installing-nixos-on-a-raspberry-pi installing NixOS on a Raspberry Pi] are available at nix.dev.
 
{{warning| Note that the Raspberry Pi 4 has two HDMI outputs, and apparently sometimes the user prompt for the console/TTY is displayed on HDMI 1 while the boot process is displayed on HDMI 0 (this may even [https://raspberrypi.stackexchange.com/a/112071/149250 be the case] with the official (non NixOs) non-graphical lite image). So if after the message "Welcome on NixOs" at the end of phase 2 your screen goes black/disconnects, try to use the other HDMI port. See the related bug [https://github.com/NixOS/nixpkgs/issues/179701 here].}}
 
=== Configuration ===
 
Using <code>nixos-generate-config</code> will generate the required minimal configuration.
 
For better GPU support and some deviceTree quirks add the nixos-hardware channel:


=== Minimal configuration ===
<code>
nix-channel --add https://github.com/NixOS/nixos-hardware/archive/master.tar.gz nixos-hardware


Using <code>nixos-generate-config</code> will not generate the required minimal configuration. Change the lines about booting to the following (from [https://github.com/NixOS/nixpkgs/pull/68265#issuecomment-532040372 this PR comment]) (and don't forget to set a user).
nix-channel --update
</code>


{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{ pkgs, ... }:
{ config, pkgs, lib, ... }:
 
{
{
   # Assuming this is installed on top of the disk image.
   imports =
   fileSystems = {
    [
     "/" = {
      </nowiki><<nowiki>nixos-hardware/raspberry-pi/4</nowiki>><nowiki>
       device = "/dev/disk/by-label/NIXOS_SD";
      ./hardware-configuration.nix
       fsType = "ext4";
    ];
   hardware = {
     raspberry-pi."4".apply-overlays-dtmerge.enable = true;
    deviceTree = {
       enable = true;
       filter = "*rpi-4-*.dtb";
     };
     };
   };
   };
   boot.loader.grub.enable = false;
   console.enable = false;
   boot.loader.raspberryPi.enable = true;
   environment.systemPackages = with pkgs; [
  boot.loader.raspberryPi.version = 4;
     libraspberrypi
  # Mainline doesn't work yet
     raspberrypi-eeprom
  boot.kernelPackages = pkgs.linuxPackages_rpi4;
 
  # ttyAMA0 is the serial console broken out to the GPIO
  boot.kernelParams = [
     "8250.nr_uarts=1" # may be required only when using u-boot
     "console=ttyAMA0,115200"
    "console=tty1"
   ];
   ];
 
   system.stateVersion = "23.11";
   # Required for the Wireless firmware
  hardware.enableRedistributableFirmware = true;
}
}
</nowiki>}}
</nowiki>}}
=== USB boot ===
=== USB boot ===


For USB booting to work properly, firmware update might be needed:
For USB booting to work properly, a firmware update might be needed:


{{commands|<nowiki>
{{commands|<nowiki>
nix-shell -p raspberrypi-eeprom
$ nix-shell -p raspberrypi-eeprom
rpi-eeprom-update -d -a
$ rpi-eeprom-update -d -a
</nowiki>}}
</nowiki>}}


Now reboot the device so it can update the firmware from boot partition.
Now reboot the device so it can update the firmware from the boot partition.
 
When running from USB device without SD card present, kernel spams log about missing SD card, workaround for this is to set:
 
{{commands|<nowiki>
boot.loader.raspberryPi.firmwareConfig = "dtparam=sd_poll_once=on";
</nowiki>}}


=== GPU support ===
=== GPU support ===
Line 102: Line 99:
     enable = true;
     enable = true;
     displayManager.lightdm.enable = true;
     displayManager.lightdm.enable = true;
     desktopManager.gnome3.enable = true;
     desktopManager.gnome.enable = true;
     videoDrivers = [ "fbdev" ];
     videoDrivers = [ "fbdev" ];
   };
   };
Line 108: Line 105:
</nowiki>}}
</nowiki>}}
==== With GPU ====
==== With GPU ====
Warning: The device tree overlays provided with the RaspberryPi Kernel don't seem to be compatible with dtc. We might need to add support for the `dtmerge` tool as an alternative, or ask upstream to fix their overlays (or dtc).


See https://github.com/NixOS/nixpkgs/pull/107637#issuecomment-752635965 for details.
In [https://github.com/NixOS/nixos-hardware/pull/261 nixos-hardware#261] an option has been added to use the <code>fkms-3d</code> ([https://wiki.archlinux.org/title/Kernel_mode_setting modesetting]) overlay which uses the [https://www.raspberrypi.com/news/vc4-and-v3d-opengl-drivers-for-raspberry-pi-an-update/ V3D renderer]. This will only work with the vendor kernel, which is the default in NixOS.
 
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{ pkgs, ... }:
{ pkgs, ... }:


{
{
   hardware.opengl = {
   imports = [
     enable = true;
     .../nixos-hardware/raspberry-pi/4
    setLdLibraryPath = true;
   ];
    package = pkgs.mesa_drivers;
 
   };
   hardware.raspberry-pi."4".fkms-3d.enable = true;
   hardware.deviceTree = {
 
    kernelPackage = pkgs.linux_rpi4;
    overlays = [ "${pkgs.device-tree_rpi.overlays}/vc4-fkms-v3d.dtbo" ];
  };
   services.xserver = {
   services.xserver = {
     enable = true;
     enable = true;
     displayManager.lightdm.enable = true;
     displayManager.lightdm.enable = true;
     desktopManager.gnome3.enable = true;
     desktopManager.gnome.enable = true;
    videoDrivers = [ "modesetting" ];
   };
   };
  boot.loader.raspberryPi.firmwareConfig = ''
    gpu_mem=192
  '';
}
}
</nowiki>}}
</nowiki>}}
==== Tools ====
 
=== Tools ===


The raspberry tools are available in the <code>libraspberrypi</code> package and include commands like <code>vcgencmd</code> to measure temperature and CPU frequency.
The raspberry tools are available in the <code>libraspberrypi</code> package and include commands like <code>vcgencmd</code> to measure temperature and CPU frequency.


==== Audio ====
=== Audio ===


In addition to the usual config, you will need to enable audio support explicitly in the firmwareConfig.
In addition to the usual config, you will need to enable hardware audio support:


{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
   sound.enable = true;
   sound.enable = true;
   hardware.pulseaudio.enable = true;
   hardware.pulseaudio.enable = true;
  hardware.raspberry-pi."4".audio.enable = true;
</nowiki>}}
=== Using GPIO pins as non-root ===
By default, the GPIO pins are enabled, but can only be accessed by the root user.
This can be addressed by adding a [https://wiki.archlinux.org/title/Udev udev] rule to your configuration that changes the ownership of <code>/dev/gpiomem</code> and the other required devices.
The following code adds a group <code>gpio</code> and adds the user <code>mygpiouser</code> to that group. You probably want to put your own user name here.
The <code>extraRules</code> changes the owner of <code>gpiomem</code> and all other files needed for GPIO to work to <code>root:gpio</code> and changes the permissions to <code>0660</code>.
Therefore, the root user and anyone in the gpio group can now access the GPIO pins.
<syntaxHighlight lang="nix">
  # Create gpio group
  users.groups.gpio = {};


   boot.loader.raspberryPi.firmwareConfig = ''
   # Change permissions gpio devices
     dtparam=audio=on
  services.udev.extraRules = ''
    SUBSYSTEM=="bcm2835-gpiomem", KERNEL=="gpiomem", GROUP="gpio",MODE="0660"
    SUBSYSTEM=="gpio", KERNEL=="gpiochip*", ACTION=="add", RUN+="${pkgs.bash}/bin/bash -c 'chown root:gpio /sys/class/gpio/export /sys/class/gpio/unexport ; chmod 220 /sys/class/gpio/export /sys/class/gpio/unexport'"
     SUBSYSTEM=="gpio", KERNEL=="gpio*", ACTION=="add",RUN+="${pkgs.bash}/bin/bash -c 'chown root:gpio /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value ; chmod 660 /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value'"
   '';
   '';
</nowiki>}}
== Troubleshooting ==


=== Power issues ===
  # Add user to group
  users = {
    users.mygpiouser = {
      extraGroups = [ "gpio" ... ];
      ....
    };
  };
</syntaxHighlight>
 
=== Enabling the SPI ===
 
To enable the SPI, you would normally add <code>dtparam=spi=on</code> to <code>/boot/config.txt</code>.
This is not possbible on NixOS, and instead you have to apply a device tree overlay.
For this we use the <code>hardware.deviceTree.overlays</code> option.
After applying the overlay, we add an <code>spi</code> group and change the owner of the <code>spidev</code> device to it, similarly to [[#Using GPIO pins as non root |GPIO]].
 
<syntaxHighlight lang="nix">
hardware.raspberry-pi."4".apply-overlays-dtmerge.enable = true;
hardware.deviceTree = {
  enable = true;
  filter = "*-rpi-*.dtb";
  overlays = [
    {
      name = "spi";
      dtsoFile = ./spi0-0cd.dtso;
    }
  ];
};
 
users.groups.spi = {};
 
services.udev.extraRules = ''
  SUBSYSTEM=="spidev", KERNEL=="spidev0.0", GROUP="spi", MODE="0660"
'';
</syntaxHighlight>
 
The the <code>spi0-0cd.dtso</code> file can be downloaded [https://github.com/raspberrypi/firmware/blob/master/boot/overlays/spi0-0cs.dtbo here].
You might have to change the <code>compatible</code> field to "raspberrypi" in the dtbo file.
 
=== HDMI-CEC ===
 
A few bits and pieces for using HDMI-CEC on the Pi4:
 
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{ pkgs, ... }:
 
{
  # an overlay to enable raspberrypi support in libcec, and thus cec-client
  nixpkgs.overlays = [
    # nixos-22.05
    # (self: super: { libcec = super.libcec.override { inherit (self) libraspberrypi; }; })
    # nixos-22.11
    (self: super: { libcec = super.libcec.override { withLibraspberrypi = true; }; })
  ];
 
  # install libcec, which includes cec-client (requires root or "video" group, see udev rule below)
  # scan for devices: `echo 'scan' | cec-client -s -d 1`
  # set pi as active source: `echo 'as' | cec-client -s -d 1`
  environment.systemPackages = with pkgs; [
    libcec
  ];


The Raspberry Pi 4B is as power-hungry, if not more, as its predecessors. It is important to have a [https://www.raspberrypi.org/documentation/hardware/raspberrypi/power/README.md sufficient enough power supply] or ''weirdness'' may happen. Weirdness may include:
  services.udev.extraRules = ''
    # allow access to raspi cec device for video group (and optionally register it as a systemd device, used below)
    KERNEL=="vchiq", GROUP="video", MODE="0660", TAG+="systemd", ENV{SYSTEMD_ALIAS}="/dev/vchiq"
  '';


* Lightning bolt icon on HDMI output "breaking" the display.
  # optional: attach a persisted cec-client to `/run/cec.fifo`, to avoid the CEC ~1s startup delay per command
* Screen switching back to u-boot text
  # scan for devices: `echo 'scan' </nowiki>><nowiki> /run/cec.fifo ; journalctl -u cec-client.service`
** Fixable temporarily when power is sufficient by switching VT (alt+F2 / alt+F1)
  # set pi as active source: `echo 'as' </nowiki>><nowiki> /run/cec.fifo`
* Random hangs
  systemd.sockets."cec-client" = {
    after = [ "dev-vchiq.device" ];
    bindsTo = [ "dev-vchiq.device" ];
    wantedBy = [ "sockets.target" ];
    socketConfig = {
      ListenFIFO = "/run/cec.fifo";
      SocketGroup = "video";
      SocketMode = "0660";
    };
  };
  systemd.services."cec-client" = {
    after = [ "dev-vchiq.device" ];
    bindsTo = [ "dev-vchiq.device" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      ExecStart = ''${pkgs.libcec}/bin/cec-client -d 1'';
      ExecStop = ''/bin/sh -c "echo q </nowiki>><nowiki> /run/cec.fifo"'';
      StandardInput = "socket";
      StandardOutput = "journal";
      Restart="no";
  };
}
</nowiki>}}


{{note|A ''properly rated'' USB power supply, AND a good cable are necessary. The cable has to be short enough to not incur power losses through the length. Do note that thin and cheap cables usually have thinner copper wires, which in turn accentuates power losses.}}
== Notes about the boot process ==


Note that the Type-C USB receptacle for the Raspberry Pi 4B '''does not implement Power Delivery (USB PD)'''. This means that it is limited to whatever the power supply will provide when not negotiating power, which is most likely 5V at some undetermined power level.
Unless using an extremely early WIP image, the Raspberry Pi 4B boots using the U-Boot platform firmware.


===First Install Issues===
=== Updating U-Boot/Firmware ===


Make sure that you resize the <code>NIXOS_SD</code> partition and expand the filesystem so that the initial install will have enough space for the <code>/nix/store</code>. Assuming you only have the SD card plugged in:
{{commands| <nowiki>
<nowiki>
$ nix-shell -p raspberrypi-eeprom
$ sudo parted resizepart 2 100%
$ sudo mount /dev/disk/by-label/FIRMWARE /mnt
$ sudo resize2fs /dev/disk/by-label/NIXOS_SD</nowiki>
$ sudo BOOTFS=/mnt FIRMWARE_RELEASE_STATUS=stable rpi-eeprom-update -d -a
</nowiki>}} [https://nix.dev/tutorials/installing-nixos-on-a-raspberry-pi#updating-firmware source]


You might also have to add the nix channels manually.
== Troubleshooting ==
<nowiki>
$ sudo mkdir -p /nix/var/nix/profiles/per-user/root/channels/
$ nix-channel --add https://nixos.org/channels/nixos-unstable nixpkgs
$ nix-channel --update</nowiki>


Finally, the <code>nixos-install</code> program might fail to copy your <code>configuration.nix</code> and <code>hardware-configuration.nix</code> files automatically to <code>/etc/nixos/</code>. You can do this yourself by <code>sudo cp /mnt/etc/nixos/* /etc/nixos/</code>.
=== Audio not playing and Bluetooth: no controller available ===


<hr />
On the Raspberry Pi kernel, the jack may never play audio, and no Bluetooth devices may ever be found. To get this to work, it is recommended to switch to the mainline kernel. See [https://github.com/NixOS/nixpkgs/issues/123725 nixpkgs#123725] for more info.

Revision as of 18:33, 22 March 2024

Raspberry Pi 4 Family
A Raspberry Pi 4.
Manufacturer Raspberry Pi Foundation
Architecture AArch64
Bootloader Custom or U-Boot
Boot order Configurable; SD, USB, Netboot
Maintainer
Raspberry Pi 4B
SoC BCM2711

The Raspberry Pi family of devices is a series of single-board computers made by the Raspberry Pi Foundation. They are all based on Broadcom System-on-a-chip (SoCs).

Status

The Raspberry Pi 4 Family is only supported as AArch64. Use as armv7 is community supported.

Board-specific installation notes

First follow the generic installation steps to get the installer image and install using the installation and configuration steps.

The Raspberry Pi 4B works with the generic SD image.

Sample instructions for installing NixOS on a Raspberry Pi are available at nix.dev.

Warning: Note that the Raspberry Pi 4 has two HDMI outputs, and apparently sometimes the user prompt for the console/TTY is displayed on HDMI 1 while the boot process is displayed on HDMI 0 (this may even be the case with the official (non NixOs) non-graphical lite image). So if after the message "Welcome on NixOs" at the end of phase 2 your screen goes black/disconnects, try to use the other HDMI port. See the related bug here.

Configuration

Using nixos-generate-config will generate the required minimal configuration.

For better GPU support and some deviceTree quirks add the nixos-hardware channel:

nix-channel --add https://github.com/NixOS/nixos-hardware/archive/master.tar.gz nixos-hardware

nix-channel --update

/etc/nixos/configuration.nix
{ config, pkgs, lib, ... }:
{
  imports =
    [
      <nixos-hardware/raspberry-pi/4>
      ./hardware-configuration.nix
    ];
  hardware = {
    raspberry-pi."4".apply-overlays-dtmerge.enable = true;
    deviceTree = {
      enable = true;
      filter = "*rpi-4-*.dtb";
    };
  };
  console.enable = false;
  environment.systemPackages = with pkgs; [
    libraspberrypi
    raspberrypi-eeprom
  ];
  system.stateVersion = "23.11";
}

USB boot

For USB booting to work properly, a firmware update might be needed:

 $ nix-shell -p raspberrypi-eeprom
 $ rpi-eeprom-update -d -a

Now reboot the device so it can update the firmware from the boot partition.

GPU support

The following configuration samples are built on the assumption that they are added to an already working configuration. They are not complete configurations.

Without GPU

/etc/nixos/configuration.nix
{
  services.xserver = {
    enable = true;
    displayManager.lightdm.enable = true;
    desktopManager.gnome.enable = true;
    videoDrivers = [ "fbdev" ];
  };
}

With GPU

In nixos-hardware#261 an option has been added to use the fkms-3d (modesetting) overlay which uses the V3D renderer. This will only work with the vendor kernel, which is the default in NixOS.

/etc/nixos/configuration.nix
{ pkgs, ... }:

{
  imports = [
    .../nixos-hardware/raspberry-pi/4
  ];

  hardware.raspberry-pi."4".fkms-3d.enable = true;

  services.xserver = {
    enable = true;
    displayManager.lightdm.enable = true;
    desktopManager.gnome.enable = true;
  };
}

Tools

The raspberry tools are available in the libraspberrypi package and include commands like vcgencmd to measure temperature and CPU frequency.

Audio

In addition to the usual config, you will need to enable hardware audio support:

/etc/nixos/configuration.nix
  sound.enable = true;
  hardware.pulseaudio.enable = true;
  hardware.raspberry-pi."4".audio.enable = true;

Using GPIO pins as non-root

By default, the GPIO pins are enabled, but can only be accessed by the root user. This can be addressed by adding a udev rule to your configuration that changes the ownership of /dev/gpiomem and the other required devices.

The following code adds a group gpio and adds the user mygpiouser to that group. You probably want to put your own user name here.

The extraRules changes the owner of gpiomem and all other files needed for GPIO to work to root:gpio and changes the permissions to 0660. Therefore, the root user and anyone in the gpio group can now access the GPIO pins.

  # Create gpio group
  users.groups.gpio = {};

  # Change permissions gpio devices
  services.udev.extraRules = ''
    SUBSYSTEM=="bcm2835-gpiomem", KERNEL=="gpiomem", GROUP="gpio",MODE="0660"
    SUBSYSTEM=="gpio", KERNEL=="gpiochip*", ACTION=="add", RUN+="${pkgs.bash}/bin/bash -c 'chown root:gpio /sys/class/gpio/export /sys/class/gpio/unexport ; chmod 220 /sys/class/gpio/export /sys/class/gpio/unexport'"
    SUBSYSTEM=="gpio", KERNEL=="gpio*", ACTION=="add",RUN+="${pkgs.bash}/bin/bash -c 'chown root:gpio /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value ; chmod 660 /sys%p/active_low /sys%p/direction /sys%p/edge /sys%p/value'"
  '';

  # Add user to group
  users = {
    users.mygpiouser = {
      extraGroups = [ "gpio" ... ];
      ....
    };
  };

Enabling the SPI

To enable the SPI, you would normally add dtparam=spi=on to /boot/config.txt. This is not possbible on NixOS, and instead you have to apply a device tree overlay. For this we use the hardware.deviceTree.overlays option. After applying the overlay, we add an spi group and change the owner of the spidev device to it, similarly to GPIO.

hardware.raspberry-pi."4".apply-overlays-dtmerge.enable = true;
hardware.deviceTree = {
  enable = true;
  filter = "*-rpi-*.dtb";
  overlays = [
    {
      name = "spi";
      dtsoFile = ./spi0-0cd.dtso;
    }
  ];
};

users.groups.spi = {};

services.udev.extraRules = ''
  SUBSYSTEM=="spidev", KERNEL=="spidev0.0", GROUP="spi", MODE="0660"
'';

The the spi0-0cd.dtso file can be downloaded here. You might have to change the compatible field to "raspberrypi" in the dtbo file.

HDMI-CEC

A few bits and pieces for using HDMI-CEC on the Pi4:

/etc/nixos/configuration.nix
{ pkgs, ... }:

{
  # an overlay to enable raspberrypi support in libcec, and thus cec-client
  nixpkgs.overlays = [
    # nixos-22.05
    # (self: super: { libcec = super.libcec.override { inherit (self) libraspberrypi; }; })
    # nixos-22.11
    (self: super: { libcec = super.libcec.override { withLibraspberrypi = true; }; })
  ];

  # install libcec, which includes cec-client (requires root or "video" group, see udev rule below)
  # scan for devices: `echo 'scan' | cec-client -s -d 1`
  # set pi as active source: `echo 'as' | cec-client -s -d 1`
  environment.systemPackages = with pkgs; [
    libcec
  ];

  services.udev.extraRules = ''
    # allow access to raspi cec device for video group (and optionally register it as a systemd device, used below)
    KERNEL=="vchiq", GROUP="video", MODE="0660", TAG+="systemd", ENV{SYSTEMD_ALIAS}="/dev/vchiq"
  '';

  # optional: attach a persisted cec-client to `/run/cec.fifo`, to avoid the CEC ~1s startup delay per command
  # scan for devices: `echo 'scan' > /run/cec.fifo ; journalctl -u cec-client.service`
  # set pi as active source: `echo 'as' > /run/cec.fifo`
  systemd.sockets."cec-client" = {
    after = [ "dev-vchiq.device" ];
    bindsTo = [ "dev-vchiq.device" ];
    wantedBy = [ "sockets.target" ];
    socketConfig = {
      ListenFIFO = "/run/cec.fifo";
      SocketGroup = "video";
      SocketMode = "0660";
    };
  };
  systemd.services."cec-client" = {
    after = [ "dev-vchiq.device" ];
    bindsTo = [ "dev-vchiq.device" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      ExecStart = ''${pkgs.libcec}/bin/cec-client -d 1'';
      ExecStop = ''/bin/sh -c "echo q > /run/cec.fifo"'';
      StandardInput = "socket";
      StandardOutput = "journal";
      Restart="no";
  };
}

Notes about the boot process

Unless using an extremely early WIP image, the Raspberry Pi 4B boots using the U-Boot platform firmware.

Updating U-Boot/Firmware

 
$ nix-shell -p raspberrypi-eeprom
$ sudo mount /dev/disk/by-label/FIRMWARE /mnt
$ sudo BOOTFS=/mnt FIRMWARE_RELEASE_STATUS=stable rpi-eeprom-update -d -a

source

Troubleshooting

Audio not playing and Bluetooth: no controller available

On the Raspberry Pi kernel, the jack may never play audio, and no Bluetooth devices may ever be found. To get this to work, it is recommended to switch to the mainline kernel. See nixpkgs#123725 for more info.