1 { config, lib, pkgs, ... }:
6 devices = map (nr: "zram${toString nr}") (lib.range 0 (cfg.swapDevices - 1));
13 (lib.mkRemovedOptionModule [ "zramSwap" "numDevices" ] "Using ZRAM devices as general purpose ephemeral block devices is no longer supported")
22 enable = lib.mkOption {
24 type = lib.types.bool;
26 Enable in-memory compressed devices and swap space provided by the zram
29 https://www.kernel.org/doc/Documentation/blockdev/zram.txt
30 ](https://www.kernel.org/doc/Documentation/blockdev/zram.txt).
34 swapDevices = lib.mkOption {
38 Number of zram devices to be used as swap, recommended is 1.
42 memoryPercent = lib.mkOption {
46 Maximum total amount of memory that can be stored in the zram swap devices
47 (as a percentage of your total memory). Defaults to 1/2 of your total
48 RAM. Run `zramctl` to check how good memory is compressed.
49 This doesn't define how much memory will be used by the zram swap devices.
53 memoryMax = lib.mkOption {
55 type = with lib.types; nullOr int;
57 Maximum total amount of memory (in bytes) that can be stored in the zram
59 This doesn't define how much memory will be used by the zram swap devices.
63 priority = lib.mkOption {
67 Priority of the zram swap devices. It should be a number higher than
68 the priority of your disk-based swap devices (so that the system will
69 fill the zram swap devices before falling back to disk swap).
73 algorithm = lib.mkOption {
76 type = with lib.types; either (enum [ "842" "lzo" "lzo-rle" "lz4" "lz4hc" "zstd" ]) str;
78 Compression algorithm. `lzo` has good compression,
79 but is slow. `lz4` has bad compression, but is fast.
80 `zstd` is both good compression and fast, but requires newer kernel.
81 You can check what other algorithms are supported by your zram device with
82 {command}`cat /sys/class/block/zram*/comp_algorithm`
86 writebackDevice = lib.mkOption {
88 example = "/dev/zvol/tarta-zoot/swap-writeback";
89 type = lib.types.nullOr lib.types.path;
91 Write incompressible pages to this device,
92 as there's no gain from keeping them in RAM.
99 config = lib.mkIf cfg.enable {
103 assertion = cfg.writebackDevice == null || cfg.swapDevices <= 1;
104 message = "A single writeback device cannot be shared among multiple zram devices";
108 services.zram-generator.enable = true;
110 services.zram-generator.settings = lib.listToAttrs
116 size = "${toString cfg.memoryPercent} / 100 * ram";
119 zram-size = if cfg.memoryMax != null then "min(${size}, ${toString cfg.memoryMax} / 1024 / 1024)" else size;
120 compression-algorithm = cfg.algorithm;
121 swap-priority = cfg.priority;
122 } // lib.optionalAttrs (cfg.writebackDevice != null) {
123 writeback-device = cfg.writebackDevice;