Jump to content

ZFS: Difference between revisions

From NixOS Wiki
imported>CptMikky
update config from dropbear ssh to openssh + mention hostkeyPath format
Tie-ling (talk | contribs)
Take snapshots automatically: add services.zfs.autoSnapshot
 
(144 intermediate revisions by 55 users not shown)
Line 1: Line 1:
[[NixOS]] has native support for ZFS ([[wikipedia:ZFS]]). It uses the code from the [http://zfsonlinux.org/ ZFS on Linux project], including kernel modules and userspace utilities. The installation isos also come with zfs.
[https://zfsonlinux.org/ {{PAGENAME}}] ([[wikipedia:en:{{PAGENAME}}]]), also known as [https://openzfs.org/ OpenZFS] ([[wikipedia:en:OpenZFS]]), is a modern filesystem which is well supported on [[NixOS]].
[[category:filesystem]]
Besides the {{nixos:package|zfs}} package (''ZFS Filesystem Linux Kernel module'') itself, there are many packages in the ZFS ecosystem available.


== What works ==
ZFS integrates into NixOS via the {{nixos:option|boot.zfs}} and {{nixos:option|services.zfs}} options.


All functionality supported by ZFS on Linux, including:
== Limitations ==
* Using ZFS as the root filesystem (using either MS-DOS or GPT partitions)
* Encrypted ZFS pools (using either native encryption or Linux's dm-crypt)
* All the other ZFS goodies (cheap snapshotting, checksumming, compression, RAID-Z, …)
* Auto-snapshotting service


== Known issues ==
==== Latest Kernel compatible with ZFS ====
{{note|Setting <code><nowiki>boot.zfs.enableUnstable = true;</nowiki></code> is required if you are running an newer kernel which is not yet officially supported by zfs, otherwise the zfs module will refuse to evaluate and show up as ''broken''. This will install a pre-release of zfs. This might be not as stable as a released version. However in the past this rarely lead to problems/stability issues}}
ZFS often does not support the latest Kernel versions. It is recommended to use an LTS Kernel version whenever possible; the NixOS default Kernel is generally suitable. See [[Linux kernel|Linux Kernel]] for more information about configuring a specific Kernel version.
 
If your config specifies a Kernel version that is not officially supported by upstream ZFS, the ZFS module will fail to evaluate with an error that the ZFS package is "broken". Upstream ZFS changed in 2.3 to refuse to build by default, regardless of Nixpkgs’ broken marking (or ignoring).  
 
===== Selecting the latest ZFS-compatible Kernel =====
{{Warning|This will often result in the Kernel version going backwards as Kernel versions become end-of-life and are removed from Nixpkgs. If you need more control over the Kernel version due to hardware requirements, consider simply pinning a specific version rather than calculating it as below.}}
To use the latest ZFS-compatible Kernel currently available, the following configuration may be used.


* Using NixOS on a ZFS root file system might result in the boot error ''external pointer tables not supported'' when the number of hardlinks in the nix store gets very high. This can be avoided by adding this option to your <code>configuration.nix</code> file:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
boot.loader.grub.copyKernels = true;
{
  config,
  lib,
  pkgs,
  ...
}:
 
let
  zfsCompatibleKernelPackages = lib.filterAttrs (
    name: kernelPackages:
    (builtins.match "linux_[0-9]+_[0-9]+" name) != null
    && (builtins.tryEval kernelPackages).success
    && (!kernelPackages.${config.boot.zfs.package.kernelModuleAttribute}.meta.broken)
  ) pkgs.linuxKernel.packages;
  latestKernelPackage = lib.last (
    lib.sort (a: b: (lib.versionOlder a.kernel.version b.kernel.version)) (
      builtins.attrValues zfsCompatibleKernelPackages
    )
  );
in
{
  # Note this might jump back and forth as kernels are added or removed.
  boot.kernelPackages = latestKernelPackage;
}
</syntaxhighlight>
</syntaxhighlight>


* In contrast to many native Linux filesystems, ZFS misses support for freeze/thaw operations.This means that using ZFS together with hibernation (suspend to disk) may cause filesystem corruption.See https://github.com/openzfs/zfs/issues/260.  
===== Using unstable, pre-release ZFS =====
{{Warning|Pre-release ZFS versions may be less well-tested, and may have critical bugs that may cause data loss.}}{{Warning|Running ZFS with a Kernel unsupported by upstream “is considered EXPERIMENTAL by the OpenZFS project. Even if it appears to build and run correctly, there may be bugs that can cause SERIOUS DATA LOSS.”}}
In some cases, a pre-release version of ZFS may be available that supports a newer Kernel. Use it with <code>boot.zfs.package = pkgs.zfs_unstable;</code>. Using zfs_unstable may allow the use of an unsupported Kernel; as warned above, [https://github.com/openzfs/zfs/blob/6a2f7b38442b42f4bc9a848f8de10fc792ce8d76/config/kernel.m4#L473-L487 upstream considers this experimental].
 
==== Partial support for swap on ZFS ====


ZFS does not support swapfiles. swap devices can be used instead. Additionally, hibernation is disabled by default due to a [https://github.com/NixOS/nixpkgs/pull/208037 high risk] of data corruption. Note that even if that pull request is merged, it does not fully mitigate the risk. If you wish to enable hibernation regardless and made sure that swapfiles on ZFS are not used, set <code>boot.zfs.allowHibernation = true</code>.


== Caveats ==  
==== Zpool not found ====


* (ZFS, unrelated to Nix- see https://github.com/openzfs/zfs/issues/7734) You shouldn't use a ZVol as a swap device, as it can deadlock under memory pressure.
If NixOS fails to import the zpool on reboot, you may need to add <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-path";</syntaxhighlight> or <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-partuuid";</syntaxhighlight> to your configuration.nix file.
* You should set the <code>mountpoint</code> property of your ZFS filesystems to be <code>legacy</code> and let NixOS mount them like any other filesystem (such as ''ext4'' or ''btrfs''), otherwise some filesystems may fail to mount due to ordering issues.
* By default, all ZFS pools available to the system will be forcibly imported during boot, regardless if you had imported them before or not. You should be careful not to have any other system accessing them at the same time, otherwise it will corrupt your pools. Normally (for the common desktop user) this should not be a problem, as a hard disk is usually only directly connected to one machine. This behaviour can be disabled by setting <code>boot.zfs.forceImportAll = false</code>.
* If you create a zpool in the installer, make sure you run `zpool export <pool name>` after `nixos-install`, or else when you reboot into your new system, zfs will fail to import the zpool.


The differences can be tested by running <code>zpool import -d /dev/disk/by-id</code> when none of the pools are discovered, eg. a live iso.


== How to use it ==
==== ZFS conflicting with systemd ====


{{warning|Add all mounts to your configuration as legacy mounts as described in this article instead of zfs's own mount mechanism. Otherwise mounts might be not mounted in the correct order during boot!}}
ZFS will manage mounting non-legacy ZFS filesystems, but NixOS tries to manage mounting with systemd. ZFS native mountpoints are not managed as part of the system configuration (but better support hibernation with a separate swap partition). This can lead to conflicts if the ZFS mount service is also enabled for the same datasets.  


Just add the following to your <code>configuration.nix</code> file:
Disable the mount service with <code>systemd.services.zfs-mount.enable = false;</code> or remove the <code>fileSystems</code> entries in hardware-configuration.nix. Otherwise, use legacy mountpoints (created with e.g. <code>zfs create -o mountpoint=legacy</code>). Mountpoints must be specified with <code>fileSystems."/mount/point" = {};</code> or with <code>nixos-generate-config</code>.
<syntaxhighlight lang="nix">
boot.initrd.supportedFilesystems = ["zfs"]; # boot from zfs
boot.supportedFilesystems = [ "zfs" ];
</syntaxhighlight>


Be sure to also set <code>networking.hostId</code>, see https://nixos.org/nixos/manual/options.html#opt-networking.hostId (Why- https://discourse.nixos.org/t/feedback-on-a-user-guide-i-created-on-installing-nixos-with-zfs/5986/4?u=srgom)
== Guides ==


To activate the configuration and load the ZFS kernel module, run:
=== Root on ZFS with disko ===
<syntaxhighlight lang="bash">
nixos-rebuild switch
</syntaxhighlight>


All ZFS functionality should now be available.
disko[https://github.com/nix-community/disko/blob/master/example/zfs.nix] can partition disks declaratively and handle mount points at install time.


If you want NixOS to auto-mount your ZFS filesystems during boot, you should set their <code>mountpoint</code> property to <code>legacy</code> and treat it like if it were any other filesystem, i.e.: mount the filesystem manually and regenerate your list of filesystems, as such:
Don't follow the Root on ZFS guide found in OpenZFS documentation. It was abandoned and has not been updated in years. See commit log for the openzfs-docs repo for details.


<syntaxhighlight lang="bash">
=== Simple NixOS ZFS on root installation ===
zfs set mountpoint=legacy <pool>/<fs>
Start from here in the NixOS manual: [https://nixos.org/manual/nixos/stable/#sec-installation-manual].
</syntaxhighlight>
Under manual partitioning [https://nixos.org/manual/nixos/stable/#sec-installation-manual-partitioning] do this instead:


<syntaxhighlight lang="bash">
==== Partition the disk ====
mount -t zfs <pool>/<fs> <mountpoint>
We need the following partitions:
</syntaxhighlight>


This will regenerate your /etc/nixos/hardware-configuration.nix file:
* 1G for boot partition with "boot" as the partition label (also called name in some tools) and ef00 as partition code
<syntaxhighlight lang="bash">
* 4G for a swap partition with "swap" as the partition label and 8200 as partition code. We will encrypt this with a random secret on each boot.
nixos-generate-config
* The rest of disk space for zfs with "root" as the partition label and 8300 as partition code (default code)
</syntaxhighlight>


<syntaxhighlight lang="bash">
Reason for swap partition: ZFS does use a caching mechanism that is different from the normal Linux cache infrastructure.
nixos-rebuild switch
In low-memory situations, ZFS therefore might need a bit longer to free up memory from its cache. The swap partition will help with that.
</syntaxhighlight>


NixOS will now make sure that your filesystem is always mounted during boot.
Example with gdisk using <code>/dev/nvme0n1</code> as the device (use <code>lsblk</code> to find the device</code>):


The <code>nixos-generate-config</code> command regenerates your <code>/etc/nixos/hardware-configuration.nix</code> file, which includes the list of filesystems for NixOS to mount during boot, e.g.:
<syntaxhighlight lang="bash">
<syntaxhighlight lang="nix">
sudo gdisk /dev/nvme0n1
  fileSystems."/home" =
GPT fdisk (gdisk) version 1.0.10
    { device = "rpool/home";
...
      fsType = "zfs";
# boot partition
    };
Command (? for help): n
Partition number (1-128, default 1):  
First sector (2048-1000215182, default = 2048) or {+-}size{KMGTP}:
Last sector (2048-1000215182, default = 1000215175) or {+-}size{KMGTP}: +1G
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300): ef00
Changed type of partition to 'EFI system partition'


  fileSystems."/backup" =
# Swap partition
    { device = "rpool/backup";
Command (? for help): n
      fsType = "zfs";
Partition number (2-128, default 2):
    };
First sector (2099200-1000215182, default = 2099200) or {+-}size{KMGTP}:
</syntaxhighlight>
Last sector (2099200-1000215182, default = 1000215175) or {+-}size{KMGTP}: +4G
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300): 8200
Changed type of partition to 'Linux swap'


== Changing the Cache Size ==
# root partition
Command (? for help): n
Partition number (3-128, default 3):
First sector (10487808-1000215182, default = 10487808) or {+-}size{KMGTP}:
Last sector (10487808-1000215182, default = 1000215175) or {+-}size{KMGTP}:
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300):
Changed type of partition to 'Linux filesystem'


ZFS has a complicated cache system.  The cache you're most likely to want to fiddle with is the called Adaptive Replacement Cache, usually abbreviated ARC.  This is the first-level (fastest) of ZFS's caches.
# write changes
Command (? for help): w


You can increase or decrease a parameter which represents approximately the maximum size of the ARC cache. You can't set its actual size (ZFS does that adaptively according to its workload), nor can you set its exact maximum size.
Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING
PARTITIONS!!


To change the maximum size of the ARC cache to (for example) 12 GB, add this to your NixOS configuration:
Do you want to proceed? (Y/N): y
<syntaxhighlight lang="nix">
OK; writing new GUID partition table (GPT) to /dev/nvme0n1.
boot.kernelParams = ["zfs.zfs_arc_max=12884901888"];
The operation has completed successfully.
</syntaxhighlight>
Final partition table (<code>fdisk -l /dev/nvme0n1</code>):
<syntaxhighlight lang=bash>
Number  Start (sector)    End (sector)  Size      Code  Name
  1            2048        2099199  1024.0 MiB  EF00  EFI system partition
  2        2099200        10487807  4.0 GiB    8200  Linux swap
  3        10487808      1000215175  471.9 GiB  8300  Linux filesystem
</syntaxhighlight>
</syntaxhighlight>


In some versions of ZFS, you can change the maximum size of the ARC on the fly, but in NixOS 18.03 this is not possible.  (Nor is it possible in other versions of ZFS on Linux yet, according to Stack Exchange.)
'''Let's use variables from now on for simplicity.''' Get the device ID in <code>/dev/disk/by-id/</code> (using {{ic|blkid}}), in our case here it is <code>nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O</code>


== Automatic Scrubbing ==
<syntaxhighlight lang=bash>
 
BOOT=/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part1
Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:
SWAP=/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part2
<syntaxhighlight lang="nix">
DISK=/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part3
services.zfs.autoScrub.enable = true;
</syntaxhighlight>
</syntaxhighlight>


You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
{{note|It is often recommended to specify the drive using the device ID/UUID to prevent incorrect configuration, but it is also possible to use the device name (e.g. /dev/sda). See also: [[#Zpool created with bus-based disk names]], [https://wiki.archlinux.org/title/Persistent_block_device_naming Persistent block device naming - ArchWiki]}}


== Reservations ==
==== Make a ZFS pool with encryption and mount points ====


Since zfs is a copy-on-write filesystem even for deleting files disk space is needed. Therefore it should be avoided to run out of disk space. Luckily it is possible to reserve disk space for datasets to prevent this.
{{Note|zpool config can significantly affect performance (especially the ashift option) so you may want to do some research. The ZFS tuning cheatsheet or ArchWiki is a good place to start.}}


To reserve space create a new unused dataset that gets a guaranteed disk space of 1GB.
<syntaxhighlight lang="bash">
zpool create -O encryption=on -O keyformat=passphrase -O keylocation=prompt -O compression=zstd -O mountpoint=none -O xattr=sa -O acltype=posixacl -o ashift=12 zpool $DISK
# enter the password to decrypt the pool at boot
Enter new passphrase:
Re-enter new passphrase:


<syntaxhighlight lang="bash">
# Create datasets
zfs create -o refreservation=1G -o mountpoint=none zroot/reserved
zfs create zpool/root
</syntaxhighlight>
zfs create zpool/nix
zfs create zpool/var
zfs create zpool/home


where <code>zroot</code> should be replaced by a dataset in your pool.
# Mount root
The dataset itself should not be used. In case you would run out of space you can shrink the reservation to reclaim enough disk space to cleanup the other data from the pool:
mkdir -p /mnt
mount -t zfs zpool/root /mnt -o zfsutil


<syntaxhighlight lang="bash">
# Mount nix, var, home
zfs set refreservation=none zroot/reserved
mkdir /mnt/nix /mnt/var /mnt/home
mount -t zfs zpool/nix /mnt/nix -o zfsutil
mount -t zfs zpool/var /mnt/var -o zfsutil
mount -t zfs zpool/home /mnt/home -o zfsutil
</syntaxhighlight>
</syntaxhighlight>


== How to use the auto-snapshotting service ==
Output from <syntaxhighlight lang="bash" inline>zpool status</syntaxhighlight>:
<syntaxhighlight >
zpool status
  pool: zpool
state: ONLINE
...
config:


To auto-snapshot a ZFS filesystem or a ZVol, set its <code>com.sun:auto-snapshot</code> property to <code>true</code>, like this:
NAME                              STATE    READ WRITE CKSUM
zpool                              ONLINE      0    0    0
  nvme-eui.0025384b21406566-part2  ONLINE      0    0    0


<syntaxhighlight lang="bash">
zfs set com.sun:auto-snapshot=true <pool>/<fs>
</syntaxhighlight>
</syntaxhighlight>


(Note that by default this property will be inherited by all descendent datasets, but you can set their properties to false if you prefer.)
==== Format boot partition and enable swap ====
 
<syntaxhighlight lang="bash">
Then, to enable the auto-snapshot service, add this to your <code>configuration.nix</code>:
mkfs.fat -F 32 -n boot $BOOT
<syntaxhighlight lang="nix">
services.zfs.autoSnapshot.enable = true;
</syntaxhighlight>
</syntaxhighlight>


And finally, run <code>nixos-rebuild switch</code> to activate the new configuration!
<syntaxhighlight lang="bash">
 
mkswap -L swap $SWAP
By default, the auto-snapshot service will keep the latest four 15-minute, 24 hourly, 7 daily, 4 weekly and 12 monthly snapshots.
swapon $SWAP
You can globally override this configuration by setting the desired number of snapshots in your <code>configuration.nix</code>, like this:
 
<syntaxhighlight lang="nix">
services.zfs.autoSnapshot = {
  enable = true;
  frequent = 8; # keep the latest eight 15-minute snapshots (instead of four)
  monthly = 1;  # keep only one monthly snapshot (instead of twelve)
};
</syntaxhighlight>
</syntaxhighlight>


You can also disable a given type of snapshots on a per-dataset basis by setting a ZFS property, like this:
==== Installation ====
<syntaxhighlight lang="bash">
# Mount boot
mkdir -p /mnt/boot
mount $BOOT /mnt/boot


<syntaxhighlight lang="bash">
# Generate the nixos config
zfs set com.sun:auto-snapshot:weekly=false <pool>/<fs>
nixos-generate-config --root /mnt
...
writing /mnt/etc/nixos/hardware-configuration.nix...
writing /mnt/etc/nixos/configuration.nix...
For more hardware-specific settings, see https://github.com/NixOS/nixos-hardware.
</syntaxhighlight>
</syntaxhighlight>


This would disable only weekly snapshots on the given filesystem.
Now edit the configuration.nix that was just created in <code>/mnt/etc/nixos/configuration.nix</code> and make sure to have at least the following content in it.
 
== How to install NixOS on a ZFS root filesystem ==


Another guide titled "Encrypted ZFS mirror with mirrored boot on NixOS" is available at https://elis.nu/blog/2019/08/encrypted-zfs-mirror-with-mirrored-boot-on-nixos/.
{{file|/mnt/etc/nixos/configuration.nix|diff|3=
=== Pool Layout Considerations ===
{
...
  # Boot loader config for configuration.nix:
  boot.loader.systemd-boot.enable = true;


it is important to keep <code>/nix</code> and the rest of the filesystem in
  # for local disks that are not shared over the network, we don't need this to be random
different sections of the dataset hierarchy, like this:
  # without this, "ZFS requires networking.hostId to be set" will be raised
+  networking.hostId = "8425e349";
...
}
}}


<syntaxhighlight lang="none">
Now check the hardware-configuration.nix in <code>/mnt/etc/nixos/hardware-configuration.nix</code> and add whats missing e.g. <code>options = [ "zfsutil" ]</code> for all filesystems except boot and <code>randomEncryption = true;</code> for the swap partition. Also change the generated swap device to the partition we created e.g. <code>/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part2</code> in this case and <code>/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part1</code> for boot.
rpool/
      local/
            nix        mounted to /nix
      safe/
            root        mounted to /
            home        mounted to /home
            ...
</syntaxhighlight>


the name of `local` and `safe` can change, but them being peers
{{file|/mnt/etc/nixos/configuration.nix|diff|3=
is important.
{
...
  fileSystems."/" = {
    device = "zpool/root";
    fsType = "zfs";
    # the zfsutil option is needed when mounting zfs datasets without "legacy" mountpoints
+    options = [ "zfsutil" ];
  };


ZFS can take consistent and atomic snapshots recursively down a
  fileSystems."/nix" = {
dataset's hierarchy. Since Nix is good at being Nix, most users will want their server's ''data'' backed up, and don't
    device = "zpool/nix";
mind reinstalling NixOS and then restoring data. If this is sufficient, only snapshot and back up the <code>safe</code> hierarchy. Users who want to be able to restore a service with only ZFS snapshots will want to snapshot the entire tree, at the significant expense of snapshotting the Nix store.
    fsType = "zfs";
+    options = [ "zfsutil" ];
  };


=== Dataset Properties ===
  fileSystems."/var" = {
    device = "zpool/var";
    fsType = "zfs";
+    options = [ "zfsutil" ];
  };


The following is a list of recommended dataset properties which have no drawbacks under regular uses:
  fileSystems."/home" = {
    device = "zpool/home";
    fsType = "zfs";
+    options = [ "zfsutil" ];
  };


* <code>compression=lz4</code>
  fileSystems."/boot" = {
* <code>xattr=sa</code> for Journald
  device = "/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part1";
* <code>acltype=posixacl</code> also for Journald
  fsType = "vfat";
  };


The following is a list of dataset properties which are often useful, but do have drawbacks:
  swapDevices = [{
+    device = "/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part2";
+    randomEncryption = true;
  }];
}
}}


* <code>atime=off</code> disables if a file's access time is updated when the file is read. This can result in significant performance gains, but might confuse some software like mailers.
Now you may install NixOS with <code>nixos-install</code>.


==== Journald ====
== Importing on boot ==


Journald requires some properties for <code>journalctl</code> to work for non-root users. The dataset containing <code>/var/log/journal</code> (probably the <code>/</code> dataset for simple configurations) should be created with <code>xattr=sa</code> and <code>acltype=posixacl</code>.
If you create a zpool, it will not be imported on the next boot unless you either add the zpool name to <syntaxhighlight lang="nix" inline>boot.zfs.extraPools</syntaxhighlight>:


For example:
<syntaxhighlight lang="nix">
## In /etc/nixos/configuration.nix:
boot.zfs.extraPools = [ "zpool_name" ];
</syntaxhighlight>


<syntaxhighlight lang="console">
or if you are using legacy mountpoints, add a <syntaxhighlight lang="nix" inline>fileSystems</syntaxhighlight> entry and NixOS will automatically detect that the pool needs to be imported:
$ zpool create  -O xattr=sa -O acltype=posixacl rpool ...
</syntaxhighlight>


or:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="console">
## In /etc/nixos/configuration.nix:
$ zfs create -o xattr=sa -o acltype=posixacl rpool/root
fileSystems."/mount/point" = {
  device = "zpool_name";
  fsType = "zfs";
};
</syntaxhighlight>
</syntaxhighlight>


If you have already created the dataset, these properties can be set later:
=== Zpool created with bus-based disk names ===
If you used bus-based disk names in the <syntaxhighlight inline>zpool create</syntaxhighlight> command, e.g., <syntaxhighlight inline>/dev/sda</syntaxhighlight>, NixOS may run into issues importing the pool if the names change. Even if the pool is able to be mounted (with <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-partuuid";</syntaxhighlight> set), this may manifest as a <syntaxhighlight inline>FAULTED</syntaxhighlight> disk and a <syntaxhighlight inline>DEGRADED</syntaxhighlight> pool reported by <syntaxhighlight inline>zpool status</syntaxhighlight>. The fix is to re-import the pool using disk IDs:


<syntaxhighlight lang="console">
<syntaxhighlight>
$ zfs set xattr=sa acltype=posixacl rpool/root
# zpool export zpool_name
# zpool import -d /dev/disk/by-id zpool_name
</syntaxhighlight>
</syntaxhighlight>


=== Single-disk ===
The import setting is reflected in <syntaxhighlight inline="" lang="bash">/etc/zfs/zpool.cache</syntaxhighlight>, so it should persist through subsequent boots.


These instructions will get you started with a single-disk ZFS setup. If you're interested in setting up RAID, see below.
=== Zpool created with disk IDs ===
If you used disk IDs to refer to disks in the <code>zpool create</code> command, e.g., <code>/dev/disk/by-id</code>, then NixOS may consistently fail to import the pool unless <code>boot.zfs.devNodes = "/dev/disk/by-id"</code> is also set.


<syntaxhighlight lang="bash">
== Mount datasets at boot ==
# Always use the by-id aliases for devices, otherwise ZFS can choke on imports.
zfs-mount service is enabled by default on NixOS 22.05.
DISK=/dev/disk/by-id/...


# Partition 2 will be the boot partition, needed for legacy (BIOS) boot
To automatically mount a dataset at boot, you only need to set <code>canmount=on</code> and <code>mountpoint=/mount/point</code> on the respective datasets.
sgdisk -a1 -n2:34:2047 -t2:EF02 $DISK
# If you need EFI support, make an EFI partition:
sgdisk -n3:1M:+512M -t3:EF00 $DISK
# Partition 1 will be the main ZFS partition, using up the remaining space on the drive.
sgdisk -n1:0:0 -t1:BF01 $DISK


# Create the pool. If you want to tweak this a bit and you're feeling adventurous, you
== Changing the Adaptive Replacement Cache size ==
# might try adding one or more of the following additional options:
# To disable writing access times:
#  -O atime=off
# To enable filesystem compression:
#  -O compression=lz4
# To improve performance of certain extended attributes:
#  -O xattr=sa
# For systemd-journald posixacls are required
#  -O  acltype=posixacl
# To specify that your drive uses 4K sectors instead of relying on the size reported
# by the hardware (note small 'o'):
#  -o ashift=12
#
# The 'mountpoint=none' option disables ZFS's automount machinery; we'll use the
# normal fstab-based mounting machinery in Linux.
# '-R /mnt' is not a persistent property of the FS, it'll just be used while we're installing.
zpool create -O mountpoint=none rpool $DISK-part1


# Create the filesystems. This layout is designed so that /home is separate from the root
To change the maximum size of the ARC to (for example) 12 GB, add this to your NixOS configuration:
# filesystem, as you'll likely want to snapshot it differently for backup purposes. It also
<syntaxhighlight lang="nix">
# makes a "nixos" filesystem underneath the root, to support installing multiple OSes if
boot.kernelParams = [ "zfs.zfs_arc_max=12884901888" ];
# that's something you choose to do in future.
</syntaxhighlight>
zfs create -o mountpoint=legacy rpool/root
zfs create -o mountpoint=legacy rpool/root/nixos
zfs create -o mountpoint=legacy rpool/home


# Mount the filesystems manually. The nixos installer will detect these mountpoints
== Tuning other parameters ==
# and save them to /mnt/nixos/hardware-configuration.nix during the install process.
mount -t zfs rpool/root/nixos /mnt
mkdir /mnt/home
mount -t zfs rpool/home /mnt/home


# If you need to boot EFI, you'll need to set up /boot as a non-ZFS partition.
To tune other attributes of ARC, L2ARC or of ZFS itself via runtime modprobe config, add this to your NixOS configuration (keys and values are examples only!):
mkfs.vfat $DISK-part3
<syntaxhighlight lang="nix">
mkdir /mnt/boot
    boot.extraModprobeConfig = ''
mount $DISK-part3 /mnt/boot
      options zfs l2arc_noprefetch=0 l2arc_write_boost=33554432 l2arc_write_max=16777216 zfs_arc_max=2147483648
 
    '';
# Generate the NixOS configuration, as per the NixOS manual.
</syntaxhighlight>
nixos-generate-config --root /mnt


# Edit /mnt/etc/nixos/configuration.nix and add the following line:
You can confirm whether any specified configuration/tuning got applied via commands like <code>arc_summary</code> and <code>arcstat -a -s " "</code>.
## ---8<-------------------------8<---
  boot.supportedFilesystems = [ "zfs" ];
## ---8<-------------------------8<---


# Also, make sure you set the networking.hostId option, which ZFS requires:
== Automatic scrubbing ==
## ---8<-------------------------8<---
  networking.hostId = "<random 8-digit hex string>";
## ---8<-------------------------8<---
# See https://nixos.org/nixos/manual/options.html#opt-networking.hostId for more.


# Continue with installation!
Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:
nixos-install
<syntaxhighlight lang="nix">
services.zfs.autoScrub.enable = true;
</syntaxhighlight>
</syntaxhighlight>


=== With RAID ===
You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
== Remote unlock ==
=== Unlock encrypted ZFS via SSH on boot ===


Here's an example of how to create a ZFS root pool using 4 disks in RAID-10 mode (striping+mirroring), create a ZFS root+home filesystems and install NixOS on them:
{{note|As of 22.05, rebuilding your config with the below directions may result in a situation where, if you want to revert the changes, you may need to do some pretty hairy nix-store manipulation to be able to successfully rebuild, see https://github.com/NixOS/nixpkgs/issues/101462#issuecomment-1172926129}}
(thanks to Danny Wilson for the instructions)


<syntaxhighlight lang="bash">
In case you want unlock a machine remotely (after an update), having an ssh service in initrd for the password prompt is handy:
# Verify that the installer environment has loaded the ZFS kernel module (default since 18.09)
lsmod | grep zfs


# Create boot partition and (zfs) data partition
<syntaxhighlight lang="nix">
# For information on the ZFS partitions see https://openzfs.github.io/openzfs-docs/Getting%20Started/Ubuntu/Ubuntu%2018.04%20Root%20on%20ZFS.html#step-2-disk-formatting
boot = {
# The linked guide assumes a pure ZFS setup which is not the same suitable for this guide. You will have to create the partitions for the /boot raid by yourself.
  initrd.network = {
fdisk /dev/sda
    # This will use udhcp to get an ip address.
 
    # Make sure you have added the kernel module for your network driver to `boot.initrd.availableKernelModules`,
# Copy the partition table to the other disks
    # so your initrd can load it!
sfdisk --dump /dev/sda | sfdisk /dev/sdb
    # Static ip addresses might be configured using the ip argument in kernel command line:
sfdisk --dump /dev/sda | sfdisk /dev/sdc
    # https://www.kernel.org/doc/Documentation/filesystems/nfs/nfsroot.txt
sfdisk --dump /dev/sda | sfdisk /dev/sdd
    enable = true;
 
    ssh = {
# Create a RAID-10 ZFS pool. Use "-o ashift=12" to create your ZFS pool with 4K sectors
      enable = true;
# enable posixacls, otherwise journalctl is broken for users
      # To prevent ssh clients from freaking out because a different host key is used,
zpool create -o ashift=12 -o altroot=/mnt -O  acltype=posixacl -O xattr=sa rpool mirror /dev/sda2 /dev/sdb2 mirror /dev/sdc2 /dev/sdd2
      # a different port for ssh is useful (assuming the same host has also a regular sshd running)
 
      port = 2222;
# Create the filesystems
      # hostKeys paths must be unquoted strings, otherwise you'll run into issues with boot.initrd.secrets
zfs create -o mountpoint=none rpool/root
      # the keys are copied to initrd from the path specified; multiple keys can be set
zfs create -o mountpoint=legacy rpool/root/nixos
      # you can generate any number of host keys using
zfs create -o mountpoint=legacy rpool/home
      # `ssh-keygen -t ed25519 -N "" -f /path/to/ssh_host_ed25519_key`
zfs set compression=lz4 rpool/home    # compress the home directories automatically
      hostKeys = [ /path/to/ssh_host_rsa_key ];
 
       # public ssh key used for login
# Mount the filesystems manually
      authorizedKeys = [ "ssh-rsa AAAA..." ];
mount -t zfs rpool/root/nixos /mnt
 
mkdir /mnt/home
mount -t zfs rpool/home /mnt/home
 
# Create a raid mirror of the first partitions for /boot (GRUB)
mdadm --create /dev/md127 --metadata=0.90 --level=1 --raid-devices=4 /dev/sd[a,b,c,d]1
mkfs.ext4 -m 0 -L boot -j /dev/md127
 
mkdir /mnt/boot
mount /dev/md127 /mnt/boot
 
# Generate the NixOS configuration, as per the NixOS manual
nixos-generate-config --root /mnt
 
# Now edit the generated hardware config:
nano /mnt/etc/nixos/hardware-configuration.nix
 
## ---8<-------------------------8<---
# This is what you want:
 
  fileSystems."/" =
    { device = "rpool/root/nixos";
       fsType = "zfs";
     };
     };
  };
};
</syntaxhighlight>
* In order to use DHCP in the initrd, network manager must not be enabled and <syntaxhighlight lang="nix" inline>networking.useDHCP = true;</syntaxhighlight> must be set.
* If your network card isn't started, you'll need to add the according Kernel module to the Kernel and initrd as well, e.g. <syntaxhighlight lang="nix">
boot.kernelModules = [ "r8169" ];
boot.initrd.kernelModules = [ "r8169" ];</syntaxhighlight>To know what kernel modules are needed, run <code>nix shell nixpkgs#pciutils --command lspci -v | grep -iA8 'network\|ethernet'</code> .


  fileSystems."/home" =
After that you can unlock your datasets using the following ssh command:
    { device = "rpool/home";
      fsType = "zfs";
    };


  fileSystems."/boot" =
<syntaxhighlight>
    { device = "/dev/md127";
ssh -p 2222 root@host "zpool import -a; zfs load-key -a && killall zfs"
      fsType = "ext4";
</syntaxhighlight>
    };
## ---8<-------------------------8<---


# configuration.nix needs an adjustment:
Alternatively you could also add the commands as postCommands to your configuration.nix, then you just have to ssh into the initrd:
nano /mnt/etc/nixos/configuration.nix


## ---8<-------------------------8<---
<syntaxhighlight>
# This is some more of what you want:
boot = {
  initrd.network = {
    postCommands = ''
    # Import all pools
    zpool import -a
    # Or import selected pools
    zpool import pool2
    zpool import pool3
    zpool import pool4
    # Add the load-key command to the .profile
    echo "zfs load-key -a; killall zfs" >> /root/.profile
    '';
  };
};
</syntaxhighlight>


  boot.loader.grub.devices = [ "/dev/sda" "/dev/sdb" "/dev/sdc" "/dev/sdd" ];
After that you can unlock your datasets using the following ssh command:
  boot.supportedFilesystems = [ "zfs" ];
## ---8<-------------------------8<---


# Ready to go!
<syntaxhighlight>
nixos-install
ssh -p 2222 root@host
</syntaxhighlight>
</syntaxhighlight>


== Encrypted ZFS ==
== Reservations ==


Assuming that a zpool named <code>zroot</code> has been already created as described.
On ZFS, the performance will deteriorate significantly when more than 80% of the available space is usedTo avoid this, reserve disk space beforehand.
Encrypted datasets can be added on top as follow:
: posixacl are needed for journald
<syntaxhighlight lang="bash">
zfs create -o acltype=posixacl -o xattr=sa -o encryption=aes-256-gcm -o keyformat=passphrase -o mountpoint=none zroot/root
</syntaxHighlight>


Instead of encrypting just a dataset (and all its child datasets) you can also directly encrypt the whole pool upon creation:
To reserve space create a new unused dataset that gets a guaranteed disk space of 10GB.
<syntaxhighlight lang="bash">
zpool create -o ashift=12 -o altroot="/mnt" -O mountpoint=none -O encryption=aes-256-gcm -O keyformat=passphrase zroot /dev/sdxy
</syntaxHighlight>


All child datasets will inherit the encryption.
<syntaxhighlight lang="console">
# zfs create -o refreservation=10G -o mountpoint=none zroot/reserved
</syntaxhighlight>


Note that using grub to boot directly from zfs with encryption enabled might not work at the moment, so a separate boot partition is required.
== Auto ZFS trimming ==


A full encrypted nixos installation on an UEFI system could look like this:
<syntaxhighlight lang="nix" inline>services.zfs.trim.enable = true;</syntaxhighlight>.
<syntaxhighlight lang="bash">
zfs create -o mountpoint=legacy -o sync=disabled zroot/root/tmp
zfs create -o mountpoint=legacy -o com.sun:auto-snapshot=true zroot/root/home
zfs create -o mountpoint=legacy -o com.sun:auto-snapshot=true zroot/root/nixos
</syntaxHighlight>


<syntaxhighlight lang="bash">
This will periodically run <code>zpool trim</code>. Note that this is different from the <code>autotrim</code> pool property. For further information, see the <code>zpool-trim</code> and <code>zpoolprops</code> man pages.
mount -t zfs zroot/root/nixos /mnt
mkdir /mnt/{home,tmp,boot}
</syntaxHighlight>
: assuming that /dev/sda1 is the boot partition
<syntaxhighlight lang="bash">
mkfs.vfat /dev/sda1
mount /dev/sda1 /mnt/boot/
</syntaxHighlight>


<syntaxhighlight lang="bash">
== Take snapshots automatically ==
mount -t zfs zroot/root/home /mnt/home/
mount -t zfs zroot/root/tmp /mnt/tmp/
</syntaxHighlight>


<syntaxhighlight lang="bash">
See {{nixos:option|services.zfs.autoSnapshot}} or {{nixos:option|services.sanoid}} section in <code>man configuration.nix</code>.
nixos-generate-config  --root /mnt
</syntaxHighlight>


To unlock the zfs dataset at root also the <code>boot.zfs.requestEncryptionCredentials</code> option must be set to <code>true</code>. Note that at the moment one can only use passphrases (<code>keylocation=prompt</code>) for pools that are mounted as the root fs. Data pools are mounted by a background systemd service and need a key (<code>keylocation=file://</code>). A key file could be for example put on a root filesystem if it is encrypted.
== NFS share ==


If the key is not on the root filesystem, you will also need to set <code>zfs-import-poolname.serviceConfig.RequiresMountsFor=/path/to/key</code>, where <code>poolname</code> is the name of the data pool. This makes sure that systemd will mount the filesystem for <code>/path/to/key</code> first before importing the zfs pool.
With <code>sharenfs</code> property, ZFS has build-in support for generating <code>/etc/exports.d/zfs.exports</code> file, which in turn is processed by NFS service automatically.


=== Unlock encrypted zfs via ssh on boot ===
{{warning|If you are intending on defining an IPv6 subnet as part of your sharenfs rule, as of ZFS 2.0.6 (2021-09-23) please note that due to a bug in openzfs '''your rule will not correctly apply''', and may result in a security vulnerability (CVE-2013-20001). A fix has been implemented in the next yet-to-be-released upstream version - [https://github.com/openzfs/zfs/pull/11939 openzfs/zfs#11939]}}


In case you want unlock a machine remotely (after an update), having an ssh service in initrd for the password prompt is handy:
To enable NFS share on a dataset, only two steps are needed:


First, enable [[NFS|NFS service]]:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
boot = {
services.nfs.server.enable = true;
  initrd.network = {
</syntaxhighlight>
    # This will use udhcp to get an ip address.
Only this line is needed. Configure firewall if necessary, as described in [[NFS]] article.
    # Make sure you have added the kernel module for your network driver to `boot.initrd.availableKernelModules`,
 
    # so your initrd can load it!
{{warning|<code>zfs share</code> or <code>sharenfs</code> does not work if the <code>mountpoint</code> is set to <code>legacy</code> (or <code>none</code>, of course). I was unable to find a source for this behaviour, but I was stuck on the problem for days, until I realized the problem.  ::Reply: sharenfs controlls what
    # Static ip addresses might be configured using the ip argument in kernel command line:
is written into <code>/etc/exports</code>. If ZFS does not know the mountpoint, as is the case in
    # https://www.kernel.org/doc/Documentation/filesystems/nfs/nfsroot.txt
mountpoint legacy or none, the contents of <code>/etc/exports</code> would be wrong}}
    enable = true;
    ssh = {
        enable = true;
        # To prevent ssh clients from freaking out because a different host key is used,
        # a different port for ssh is useful (assuming the same host has also a regular sshd running)
        port = 2222;
        # hostKeys paths must be unquoted strings, otherwise you'll run into issues with boot.initrd.secrets
        # the keys are copied to initrd from the path specified; multiple keys can be set
        # you can generate any number of host keys using
        # `ssh-keygen -t ed25519 -N "" -f /path/to/ssh_host_ed25519_key`
        hostKeys = [ /path/to/ssh_host_rsa_key ];
        # public ssh key used for login
        authorizedKeys = [ "ssh-rsa AAAA..." ];
    };
    # this will automatically load the zfs password prompt on login
    # and kill the other prompt so boot can continue
    postCommands = ''
      echo "zfs load-key -a; killall zfs" >> /root/.profile
    '';
  };
};
</syntaxHighlight>
* In order to use DHCP in the initrd, network manager must not be enabled and <code>networking.useDHCP = true;</code> must be set.
* If your network card isn't started, you'll need to add the according kernel module to the initrd as well, e.g. <code>boot.initrd.kernelModules = [ "r8169" ];</code>


=== Import and unlock multiple encrypted pools/dataset at boot ===
Then, set <code>sharenfs</code> property:
<syntaxhighlight lang="console">
zfs set sharenfs="ro=192.168.1.0/24,all_squash,anonuid=70,anongid=70" rpool/myData
</syntaxhighlight>
For more options, see <code>man 5 exports</code>.


If you have not only one encrypted pool/dataset but multiple ones and you want to import and unlock them at boot, so that they can be automounted using the hardware-configuration.nix, you could just amend the <code>boot.initrd.network.postCommands</code> option.
Todo: sharesmb property for Samba.


Unfortunately having an unlock key file stored in an encrypted zfs dataset cannot be used directly, so the pool must use <code>keyformat=passphrase</code> and <code>keylocation=prompt</code>.
== Mail notifications (ZFS Event Daemon) ==


The following example follows the remote unlocking with OpenSSH, but imports another pool also and prompts for unlocking (either when at the machine itself or when logging in remotely:
ZFS Event Daemon (zed) monitors events generated by the ZFS Kernel module and runs configured tasks. It can be configured to send an email when a pool scrub is finished or a disk has failed. [https://search.nixos.org/options?query=services.zfs.zed zed options]


First, we need to configure a mail transfer agent, the program that sends email:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
boot = {
{
  initrd.network = {
  age.secrets.msmtp = {
    enable = true;
    file = "${inputs.self.outPath}/secrets/msmtp.age";
    ssh = {
  };
        enable = true;
        port = 2222;
        hostKeys = [ /path/to/ssh_host_rsa_key ];
        authorizedKeys = [ "ssh-rsa AAAA..." ];
    };
    postCommands = ''
      zpool import tankXXX
      echo "zfs load-key -a; killall zfs" >> /root/.profile
    '';
  };
};
</syntaxHighlight>


When you login by SSH into the box or when you have physical access to the machine itself, you will be prompted to supply the unlocking password for your zroot and tankXXX pools.
  # for zed enableMail, enable sendmailSetuidWrapper
  services.mail.sendmailSetuidWrapper.enable = true;


== ZFS Trim Support for SSDs ==
  programs.msmtp = {
    enable = true;
    setSendmail = true;
    defaults = {
      aliases = "/etc/aliases";
      port = 587;
      auth = "plain";
      tls = "on";
      tls_starttls = "on";
    };
    accounts = {
      default = {
        host = "smtp.mail.example.com";
        passwordeval = "cat ${config.age.secrets.msmtp.path}";
        user = "myname@example.com";
        from = "myname@example.com";
      };
    };
  };
}
</syntaxhighlight>


ZFS 0.8 now also features trim support for SSDs.
Then, configure an alias for root account. With this alias configured, all mails sent to root, such as cron job results and failed sudo login events, will be redirected to the configured email account.


=== How to use ZFS trimming ===
<syntaxhighlight lang="nix">
{
  environment.etc.aliases.text = ''
    root: admin@example.com
  '';
}
</syntaxhighlight>


ZFS trimming works on one or more zpools and will trim each ssd inside it. There are two modes of it. One mode will manually trim the specified pool and the other will auto-trim pools. However the main difference is, that auto-trim will skip ranges that it considers too small while manually issued trim will trim all ranges.
Finally, enable zed mail notification:
<syntaxhighlight lang="nix">
{
  services.zfs.zed. = {
    enableMail = true;
    settings = {
      ZED_EMAIL_ADDR = [ "root" ];
      # send notification if scrub succeeds
      ZED_NOTIFY_VERBOSE = true;
    };
  };
}
</syntaxhighlight>


To manually start trimming of a zpool run: <code>zpool trim tank</code>.
You can now test this by performing a scrub
Since [https://github.com/NixOS/nixpkgs/pull/65331 PR-65331] this can be also done periodically (by default once a week) by setting <code>services.zfs.trim.enable = true</code>.
<syntaxhighlight lang="console">
# zpool scrub $pool
</syntaxhighlight>


To set a pool for auto-trim run: <code>zpool set autotrim=on tank</code>
To check the status of the manual trim, you can just run <code>zpool status -t</code>
To see the effects of trimming, you can run <code>zpool iostat -r</code> and <code>zpool iostat -w</code>
To see whether auto-trimming works, just run <code>zpool iostat -r</code> note the results and run it later again. The trim entries should change.
For further information read the [https://github.com/zfsonlinux/zfs/pull/8419 PR description].


[[Category:Guide]]
[[Category:Guide]]
Following are a few discourse posts on zfs, serving as pointers, form your own opinion
* https://discourse.nixos.org/t/zfs-dedup-on-nix-store-is-it-worth-it/4959
* https://discourse.nixos.org/t/how-to-add-extra-build-input-to-linux-kernel/8208/3

Latest revision as of 21:54, 6 October 2025

ZFS (wikipedia:en:ZFS), also known as OpenZFS (wikipedia:en:OpenZFS), is a modern filesystem which is well supported on NixOS. Besides the zfs package (ZFS Filesystem Linux Kernel module) itself, there are many packages in the ZFS ecosystem available.

ZFS integrates into NixOS via the boot.zfs and services.zfs options.

Limitations

Latest Kernel compatible with ZFS

ZFS often does not support the latest Kernel versions. It is recommended to use an LTS Kernel version whenever possible; the NixOS default Kernel is generally suitable. See Linux Kernel for more information about configuring a specific Kernel version.

If your config specifies a Kernel version that is not officially supported by upstream ZFS, the ZFS module will fail to evaluate with an error that the ZFS package is "broken". Upstream ZFS changed in 2.3 to refuse to build by default, regardless of Nixpkgs’ broken marking (or ignoring).

Selecting the latest ZFS-compatible Kernel
⚠︎
Warning: This will often result in the Kernel version going backwards as Kernel versions become end-of-life and are removed from Nixpkgs. If you need more control over the Kernel version due to hardware requirements, consider simply pinning a specific version rather than calculating it as below.

To use the latest ZFS-compatible Kernel currently available, the following configuration may be used.

{
  config,
  lib,
  pkgs,
  ...
}:

let
  zfsCompatibleKernelPackages = lib.filterAttrs (
    name: kernelPackages:
    (builtins.match "linux_[0-9]+_[0-9]+" name) != null
    && (builtins.tryEval kernelPackages).success
    && (!kernelPackages.${config.boot.zfs.package.kernelModuleAttribute}.meta.broken)
  ) pkgs.linuxKernel.packages;
  latestKernelPackage = lib.last (
    lib.sort (a: b: (lib.versionOlder a.kernel.version b.kernel.version)) (
      builtins.attrValues zfsCompatibleKernelPackages
    )
  );
in
{
  # Note this might jump back and forth as kernels are added or removed.
  boot.kernelPackages = latestKernelPackage;
}
Using unstable, pre-release ZFS
⚠︎
Warning: Pre-release ZFS versions may be less well-tested, and may have critical bugs that may cause data loss.
⚠︎
Warning: Running ZFS with a Kernel unsupported by upstream “is considered EXPERIMENTAL by the OpenZFS project. Even if it appears to build and run correctly, there may be bugs that can cause SERIOUS DATA LOSS.”

In some cases, a pre-release version of ZFS may be available that supports a newer Kernel. Use it with boot.zfs.package = pkgs.zfs_unstable;. Using zfs_unstable may allow the use of an unsupported Kernel; as warned above, upstream considers this experimental.

Partial support for swap on ZFS

ZFS does not support swapfiles. swap devices can be used instead. Additionally, hibernation is disabled by default due to a high risk of data corruption. Note that even if that pull request is merged, it does not fully mitigate the risk. If you wish to enable hibernation regardless and made sure that swapfiles on ZFS are not used, set boot.zfs.allowHibernation = true.

Zpool not found

If NixOS fails to import the zpool on reboot, you may need to add boot.zfs.devNodes = "/dev/disk/by-path"; or boot.zfs.devNodes = "/dev/disk/by-partuuid"; to your configuration.nix file.

The differences can be tested by running zpool import -d /dev/disk/by-id when none of the pools are discovered, eg. a live iso.

ZFS conflicting with systemd

ZFS will manage mounting non-legacy ZFS filesystems, but NixOS tries to manage mounting with systemd. ZFS native mountpoints are not managed as part of the system configuration (but better support hibernation with a separate swap partition). This can lead to conflicts if the ZFS mount service is also enabled for the same datasets.

Disable the mount service with systemd.services.zfs-mount.enable = false; or remove the fileSystems entries in hardware-configuration.nix. Otherwise, use legacy mountpoints (created with e.g. zfs create -o mountpoint=legacy). Mountpoints must be specified with fileSystems."/mount/point" = {}; or with nixos-generate-config.

Guides

Root on ZFS with disko

disko[1] can partition disks declaratively and handle mount points at install time.

Don't follow the Root on ZFS guide found in OpenZFS documentation. It was abandoned and has not been updated in years. See commit log for the openzfs-docs repo for details.

Simple NixOS ZFS on root installation

Start from here in the NixOS manual: [2]. Under manual partitioning [3] do this instead:

Partition the disk

We need the following partitions:

  • 1G for boot partition with "boot" as the partition label (also called name in some tools) and ef00 as partition code
  • 4G for a swap partition with "swap" as the partition label and 8200 as partition code. We will encrypt this with a random secret on each boot.
  • The rest of disk space for zfs with "root" as the partition label and 8300 as partition code (default code)

Reason for swap partition: ZFS does use a caching mechanism that is different from the normal Linux cache infrastructure. In low-memory situations, ZFS therefore might need a bit longer to free up memory from its cache. The swap partition will help with that.

Example with gdisk using /dev/nvme0n1 as the device (use lsblk to find the device):

sudo gdisk /dev/nvme0n1
GPT fdisk (gdisk) version 1.0.10
...
# boot partition
Command (? for help): n
Partition number (1-128, default 1): 
First sector (2048-1000215182, default = 2048) or {+-}size{KMGTP}: 
Last sector (2048-1000215182, default = 1000215175) or {+-}size{KMGTP}: +1G
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300): ef00
Changed type of partition to 'EFI system partition'

# Swap partition
Command (? for help): n
Partition number (2-128, default 2): 
First sector (2099200-1000215182, default = 2099200) or {+-}size{KMGTP}: 
Last sector (2099200-1000215182, default = 1000215175) or {+-}size{KMGTP}: +4G
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300): 8200
Changed type of partition to 'Linux swap'

# root partition
Command (? for help): n
Partition number (3-128, default 3): 
First sector (10487808-1000215182, default = 10487808) or {+-}size{KMGTP}: 
Last sector (10487808-1000215182, default = 1000215175) or {+-}size{KMGTP}: 
Current type is 8300 (Linux filesystem)
Hex code or GUID (L to show codes, Enter = 8300): 
Changed type of partition to 'Linux filesystem'

# write changes
Command (? for help): w

Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING
PARTITIONS!!

Do you want to proceed? (Y/N): y
OK; writing new GUID partition table (GPT) to /dev/nvme0n1.
The operation has completed successfully.

Final partition table (fdisk -l /dev/nvme0n1):

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048         2099199   1024.0 MiB  EF00  EFI system partition
   2         2099200        10487807   4.0 GiB     8200  Linux swap
   3        10487808      1000215175   471.9 GiB   8300  Linux filesystem

Let's use variables from now on for simplicity. Get the device ID in /dev/disk/by-id/ (using blkid), in our case here it is nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O

BOOT=/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part1
SWAP=/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part2
DISK=/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part3
Note: It is often recommended to specify the drive using the device ID/UUID to prevent incorrect configuration, but it is also possible to use the device name (e.g. /dev/sda). See also: #Zpool created with bus-based disk names, Persistent block device naming - ArchWiki

Make a ZFS pool with encryption and mount points

Note: zpool config can significantly affect performance (especially the ashift option) so you may want to do some research. The ZFS tuning cheatsheet or ArchWiki is a good place to start.
zpool create -O encryption=on -O keyformat=passphrase -O keylocation=prompt -O compression=zstd -O mountpoint=none -O xattr=sa -O acltype=posixacl -o ashift=12 zpool $DISK
# enter the password to decrypt the pool at boot
Enter new passphrase:
Re-enter new passphrase:

# Create datasets
zfs create zpool/root
zfs create zpool/nix
zfs create zpool/var
zfs create zpool/home

# Mount root
mkdir -p /mnt
mount -t zfs zpool/root /mnt -o zfsutil

# Mount nix, var, home
mkdir /mnt/nix /mnt/var /mnt/home
mount -t zfs zpool/nix /mnt/nix -o zfsutil
mount -t zfs zpool/var /mnt/var -o zfsutil
mount -t zfs zpool/home /mnt/home -o zfsutil

Output from zpool status:

zpool status
  pool: zpool
 state: ONLINE
...
config:

	NAME                               STATE     READ WRITE CKSUM
	zpool                              ONLINE       0     0     0
	  nvme-eui.0025384b21406566-part2  ONLINE       0     0     0

Format boot partition and enable swap

mkfs.fat -F 32 -n boot $BOOT
mkswap -L swap $SWAP
swapon $SWAP

Installation

# Mount boot
mkdir -p /mnt/boot
mount $BOOT /mnt/boot

# Generate the nixos config
nixos-generate-config --root /mnt
...
writing /mnt/etc/nixos/hardware-configuration.nix...
writing /mnt/etc/nixos/configuration.nix...
For more hardware-specific settings, see https://github.com/NixOS/nixos-hardware.

Now edit the configuration.nix that was just created in /mnt/etc/nixos/configuration.nix and make sure to have at least the following content in it.

≡︎ /mnt/etc/nixos/configuration.nix
{
...
  # Boot loader config for configuration.nix:
  boot.loader.systemd-boot.enable = true;

  # for local disks that are not shared over the network, we don't need this to be random
  # without this, "ZFS requires networking.hostId to be set" will be raised
+  networking.hostId = "8425e349";
...
}

Now check the hardware-configuration.nix in /mnt/etc/nixos/hardware-configuration.nix and add whats missing e.g. options = [ "zfsutil" ] for all filesystems except boot and randomEncryption = true; for the swap partition. Also change the generated swap device to the partition we created e.g. /dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part2 in this case and /dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part1 for boot.

≡︎ /mnt/etc/nixos/configuration.nix
{
...
  fileSystems."/" = { 
    device = "zpool/root";
    fsType = "zfs";
    # the zfsutil option is needed when mounting zfs datasets without "legacy" mountpoints
+    options = [ "zfsutil" ];
  };

  fileSystems."/nix" = { 
    device = "zpool/nix";
    fsType = "zfs";
+    options = [ "zfsutil" ];
  };

  fileSystems."/var" = { 
    device = "zpool/var";
    fsType = "zfs";
+    options = [ "zfsutil" ];
  };

  fileSystems."/home" = {
    device = "zpool/home";
    fsType = "zfs";
+    options = [ "zfsutil" ];
  };

  fileSystems."/boot" = { 
   device = "/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part1";
   fsType = "vfat";
  };

  swapDevices = [{
+    device = "/dev/disk/by-id/nvme-SKHynix_HFS512GDE9X081N_FNB6N634510106K5O-part2";
+    randomEncryption = true;
  }];
}

Now you may install NixOS with nixos-install.

Importing on boot

If you create a zpool, it will not be imported on the next boot unless you either add the zpool name to boot.zfs.extraPools:

## In /etc/nixos/configuration.nix:
boot.zfs.extraPools = [ "zpool_name" ];

or if you are using legacy mountpoints, add a fileSystems entry and NixOS will automatically detect that the pool needs to be imported:

## In /etc/nixos/configuration.nix:
fileSystems."/mount/point" = {
  device = "zpool_name";
  fsType = "zfs";
};

Zpool created with bus-based disk names

If you used bus-based disk names in the zpool create command, e.g., /dev/sda, NixOS may run into issues importing the pool if the names change. Even if the pool is able to be mounted (with boot.zfs.devNodes = "/dev/disk/by-partuuid"; set), this may manifest as a FAULTED disk and a DEGRADED pool reported by zpool status. The fix is to re-import the pool using disk IDs:

# zpool export zpool_name
# zpool import -d /dev/disk/by-id zpool_name

The import setting is reflected in /etc/zfs/zpool.cache, so it should persist through subsequent boots.

Zpool created with disk IDs

If you used disk IDs to refer to disks in the zpool create command, e.g., /dev/disk/by-id, then NixOS may consistently fail to import the pool unless boot.zfs.devNodes = "/dev/disk/by-id" is also set.

Mount datasets at boot

zfs-mount service is enabled by default on NixOS 22.05.

To automatically mount a dataset at boot, you only need to set canmount=on and mountpoint=/mount/point on the respective datasets.

Changing the Adaptive Replacement Cache size

To change the maximum size of the ARC to (for example) 12 GB, add this to your NixOS configuration:

boot.kernelParams = [ "zfs.zfs_arc_max=12884901888" ];

Tuning other parameters

To tune other attributes of ARC, L2ARC or of ZFS itself via runtime modprobe config, add this to your NixOS configuration (keys and values are examples only!):

    boot.extraModprobeConfig = ''
      options zfs l2arc_noprefetch=0 l2arc_write_boost=33554432 l2arc_write_max=16777216 zfs_arc_max=2147483648
    '';

You can confirm whether any specified configuration/tuning got applied via commands like arc_summary and arcstat -a -s " ".

Automatic scrubbing

Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:

services.zfs.autoScrub.enable = true;

You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).

Remote unlock

Unlock encrypted ZFS via SSH on boot

Note: As of 22.05, rebuilding your config with the below directions may result in a situation where, if you want to revert the changes, you may need to do some pretty hairy nix-store manipulation to be able to successfully rebuild, see https://github.com/NixOS/nixpkgs/issues/101462#issuecomment-1172926129

In case you want unlock a machine remotely (after an update), having an ssh service in initrd for the password prompt is handy:

boot = {
  initrd.network = {
    # This will use udhcp to get an ip address.
    # Make sure you have added the kernel module for your network driver to `boot.initrd.availableKernelModules`, 
    # so your initrd can load it!
    # Static ip addresses might be configured using the ip argument in kernel command line:
    # https://www.kernel.org/doc/Documentation/filesystems/nfs/nfsroot.txt
    enable = true;
    ssh = {
      enable = true;
      # To prevent ssh clients from freaking out because a different host key is used,
      # a different port for ssh is useful (assuming the same host has also a regular sshd running)
      port = 2222; 
      # hostKeys paths must be unquoted strings, otherwise you'll run into issues with boot.initrd.secrets
      # the keys are copied to initrd from the path specified; multiple keys can be set
      # you can generate any number of host keys using 
      # `ssh-keygen -t ed25519 -N "" -f /path/to/ssh_host_ed25519_key`
      hostKeys = [ /path/to/ssh_host_rsa_key ];
      # public ssh key used for login
      authorizedKeys = [ "ssh-rsa AAAA..." ];
    };
  };
};
  • In order to use DHCP in the initrd, network manager must not be enabled and networking.useDHCP = true; must be set.
  • If your network card isn't started, you'll need to add the according Kernel module to the Kernel and initrd as well, e.g.
    boot.kernelModules = [ "r8169" ];
    boot.initrd.kernelModules = [ "r8169" ];
    
    To know what kernel modules are needed, run nix shell nixpkgs#pciutils --command lspci -v | grep -iA8 'network\|ethernet' .

After that you can unlock your datasets using the following ssh command:

ssh -p 2222 root@host "zpool import -a; zfs load-key -a && killall zfs"

Alternatively you could also add the commands as postCommands to your configuration.nix, then you just have to ssh into the initrd:

boot = {
  initrd.network = {
    postCommands = ''
    # Import all pools
    zpool import -a
    # Or import selected pools
    zpool import pool2
    zpool import pool3
    zpool import pool4
    # Add the load-key command to the .profile
    echo "zfs load-key -a; killall zfs" >> /root/.profile
    '';
  };
};

After that you can unlock your datasets using the following ssh command:

ssh -p 2222 root@host

Reservations

On ZFS, the performance will deteriorate significantly when more than 80% of the available space is used. To avoid this, reserve disk space beforehand.

To reserve space create a new unused dataset that gets a guaranteed disk space of 10GB.

# zfs create -o refreservation=10G -o mountpoint=none zroot/reserved

Auto ZFS trimming

services.zfs.trim.enable = true;.

This will periodically run zpool trim. Note that this is different from the autotrim pool property. For further information, see the zpool-trim and zpoolprops man pages.

Take snapshots automatically

See services.zfs.autoSnapshot or services.sanoid section in man configuration.nix.

NFS share

With sharenfs property, ZFS has build-in support for generating /etc/exports.d/zfs.exports file, which in turn is processed by NFS service automatically.

⚠︎
Warning: If you are intending on defining an IPv6 subnet as part of your sharenfs rule, as of ZFS 2.0.6 (2021-09-23) please note that due to a bug in openzfs your rule will not correctly apply, and may result in a security vulnerability (CVE-2013-20001). A fix has been implemented in the next yet-to-be-released upstream version - openzfs/zfs#11939

To enable NFS share on a dataset, only two steps are needed:

First, enable NFS service:

services.nfs.server.enable = true;

Only this line is needed. Configure firewall if necessary, as described in NFS article.

⚠︎
Warning: zfs share or sharenfs does not work if the mountpoint is set to legacy (or none, of course). I was unable to find a source for this behaviour, but I was stuck on the problem for days, until I realized the problem.  ::Reply: sharenfs controlls what

is written into /etc/exports. If ZFS does not know the mountpoint, as is the case in

mountpoint legacy or none, the contents of /etc/exports would be wrong

Then, set sharenfs property:

zfs set sharenfs="ro=192.168.1.0/24,all_squash,anonuid=70,anongid=70" rpool/myData

For more options, see man 5 exports.

Todo: sharesmb property for Samba.

Mail notifications (ZFS Event Daemon)

ZFS Event Daemon (zed) monitors events generated by the ZFS Kernel module and runs configured tasks. It can be configured to send an email when a pool scrub is finished or a disk has failed. zed options

First, we need to configure a mail transfer agent, the program that sends email:

{
  age.secrets.msmtp = {
    file = "${inputs.self.outPath}/secrets/msmtp.age";
  };

  # for zed enableMail, enable sendmailSetuidWrapper
  services.mail.sendmailSetuidWrapper.enable = true;

  programs.msmtp = {
    enable = true;
    setSendmail = true;
    defaults = {
      aliases = "/etc/aliases";
      port = 587;
      auth = "plain";
      tls = "on";
      tls_starttls = "on";
    };
    accounts = {
      default = {
        host = "smtp.mail.example.com";
        passwordeval = "cat ${config.age.secrets.msmtp.path}";
        user = "myname@example.com";
        from = "myname@example.com";
      };
    };
  };
}

Then, configure an alias for root account. With this alias configured, all mails sent to root, such as cron job results and failed sudo login events, will be redirected to the configured email account.

{
  environment.etc.aliases.text = ''
    root: admin@example.com
  '';
}

Finally, enable zed mail notification:

{
  services.zfs.zed. = {
    enableMail = true;
    settings = {
      ZED_EMAIL_ADDR = [ "root" ];
      # send notification if scrub succeeds
      ZED_NOTIFY_VERBOSE = true;
    };
  };
}

You can now test this by performing a scrub

# zpool scrub $pool