1{
2 config,
3 lib,
4 pkgs,
5 ...
6}:
7
8let
9 cfg = config.boot.tmp;
10in
11{
12 options = {
13 boot.tmp = {
14 useZram = lib.mkOption {
15 type = lib.types.bool;
16 default = false;
17 example = true;
18 description = ''
19 Whether to mount a zram device on {file}`/tmp` during boot.
20
21 ::: {.note}
22 Large Nix builds can fail if the mounted zram device is not large enough.
23 In such a case either increase the zramSettings.zram-size or disable this option.
24 :::
25 '';
26 };
27
28 zramSettings = {
29 zram-size = lib.mkOption {
30 type = lib.types.str;
31 default = "ram * 0.5";
32 example = "min(ram / 2, 4096)";
33 description = ''
34 The size of the zram device, as a function of MemTotal, both in MB.
35 For example, if the machine has 1 GiB, and zram-size=ram/4,
36 then the zram device will have 256 MiB.
37 Fractions in the range 0.1–0.5 are recommended
38
39 See: <https://github.com/systemd/zram-generator/blob/main/zram-generator.conf.example>
40 '';
41 };
42
43 compression-algorithm = lib.mkOption {
44 type = lib.types.str;
45 default = "zstd";
46 example = "lzo-rle";
47 description = ''
48 The compression algorithm to use for the zram device.
49
50 See: <https://github.com/systemd/zram-generator/blob/main/zram-generator.conf.example>
51 '';
52 };
53
54 fs-type = lib.mkOption {
55 type = lib.types.str;
56 default = "ext4";
57 example = "ext2";
58 description = ''
59 The file system to put on the device.
60
61 See: <https://github.com/systemd/zram-generator/blob/main/zram-generator.conf.example>
62 '';
63 };
64
65 options = lib.mkOption {
66 type = lib.types.str;
67 default = "X-mount.mode=1777,discard";
68 description = ''
69 By default, file systems and swap areas are trimmed on-the-go
70 by setting "discard".
71 Setting this to the empty string clears the option.
72
73 See: <https://github.com/systemd/zram-generator/blob/main/zram-generator.conf.example>
74 '';
75 };
76 };
77 };
78 };
79
80 config = lib.mkIf (cfg.useZram) {
81 assertions = [
82 {
83 assertion = !cfg.useTmpfs;
84 message = "boot.tmp.useTmpfs is unnecessary if useZram=true";
85 }
86 ];
87
88 services.zram-generator.enable = true;
89 services.zram-generator.settings =
90 let
91 cfgz = cfg.zramSettings;
92 in
93 {
94 "zram${toString (if config.zramSwap.enable then config.zramSwap.swapDevices else 0)}" = {
95 mount-point = "/tmp";
96 zram-size = cfgz.zram-size;
97 compression-algorithm = cfgz.compression-algorithm;
98 options = cfgz.options;
99 fs-type = cfgz.fs-type;
100 };
101 };
102 systemd.services."systemd-zram-setup@".path = [ pkgs.util-linux ] ++ config.system.fsPackages;
103
104 };
105}