about summary refs log tree commit diff
path: root/nixpkgs/nixos/modules/system/boot/kernel.nix
blob: 950cff386d02502f3d319de4f559673b8125af8d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
{ config, lib, pkgs, ... }:

with lib;

let

  inherit (config.boot) kernelPatches;
  inherit (config.boot.kernel) features randstructSeed;
  inherit (config.boot.kernelPackages) kernel;

  kernelModulesConf = pkgs.writeText "nixos.conf"
    ''
      ${concatStringsSep "\n" config.boot.kernelModules}
    '';

in

{

  ###### interface

  options = {
    boot.kernel.enable = mkEnableOption (lib.mdDoc "the Linux kernel. This is useful for systemd-like containers which do not require a kernel") // {
      default = true;
    };

    boot.kernel.features = mkOption {
      default = {};
      example = literalExpression "{ debug = true; }";
      internal = true;
      description = lib.mdDoc ''
        This option allows to enable or disable certain kernel features.
        It's not API, because it's about kernel feature sets, that
        make sense for specific use cases. Mostly along with programs,
        which would have separate nixos options.
        `grep features pkgs/os-specific/linux/kernel/common-config.nix`
      '';
    };

    boot.kernelPackages = mkOption {
      default = pkgs.linuxPackages;
      type = types.raw;
      apply = kernelPackages: kernelPackages.extend (self: super: {
        kernel = super.kernel.override (originalArgs: {
          inherit randstructSeed;
          kernelPatches = (originalArgs.kernelPatches or []) ++ kernelPatches;
          features = lib.recursiveUpdate super.kernel.features features;
        });
      });
      # We don't want to evaluate all of linuxPackages for the manual
      # - some of it might not even evaluate correctly.
      defaultText = literalExpression "pkgs.linuxPackages";
      example = literalExpression "pkgs.linuxKernel.packages.linux_5_10";
      description = lib.mdDoc ''
        This option allows you to override the Linux kernel used by
        NixOS.  Since things like external kernel module packages are
        tied to the kernel you're using, it also overrides those.
        This option is a function that takes Nixpkgs as an argument
        (as a convenience), and returns an attribute set containing at
        the very least an attribute {var}`kernel`.
        Additional attributes may be needed depending on your
        configuration.  For instance, if you use the NVIDIA X driver,
        then it also needs to contain an attribute
        {var}`nvidia_x11`.

        Please note that we strictly support kernel versions that are
        maintained by the Linux developers only. More information on the
        availability of kernel versions is documented
        [in the Linux section of the manual](https://nixos.org/manual/nixos/unstable/index.html#sec-kernel-config).
      '';
    };

    boot.kernelPatches = mkOption {
      type = types.listOf types.attrs;
      default = [];
      example = literalExpression ''
        [
          {
            name = "foo";
            patch = ./foo.patch;
            extraStructuredConfig.FOO = lib.kernel.yes;
            features.foo = true;
          }
          {
            name = "foo-ml-mbox";
            patch = (fetchurl {
              url = "https://lore.kernel.org/lkml/19700205182810.58382-1-email@domain/t.mbox.gz";
              hash = "sha256-...";
            });
          }
        ]
      '';
      description = lib.mdDoc ''
        A list of additional patches to apply to the kernel.

        Every item should be an attribute set with the following attributes:

        ```nix
        {
          name = "foo";                 # descriptive name, required

          patch = ./foo.patch;          # path or derivation that contains the patch source
                                        # (required, but can be null if only config changes
                                        # are needed)

          extraStructuredConfig = {     # attrset of extra configuration parameters without the CONFIG_ prefix
            FOO = lib.kernel.yes;       # (optional)
          };                            # values should generally be lib.kernel.yes,
                                        # lib.kernel.no or lib.kernel.module

          features = {                  # attrset of extra "features" the kernel is considered to have
            foo = true;                 # (may be checked by other NixOS modules, optional)
          };

          extraConfig = "FOO y";        # extra configuration options in string form without the CONFIG_ prefix
                                        # (optional, multiple lines allowed to specify multiple options)
                                        # (deprecated, use extraStructuredConfig instead)
        }
        ```

        There's a small set of existing kernel patches in Nixpkgs, available as `pkgs.kernelPatches`,
        that follow this format and can be used directly.
      '';
    };

    boot.kernel.randstructSeed = mkOption {
      type = types.str;
      default = "";
      example = "my secret seed";
      description = lib.mdDoc ''
        Provides a custom seed for the {var}`RANDSTRUCT` security
        option of the Linux kernel. Note that {var}`RANDSTRUCT` is
        only enabled in NixOS hardened kernels. Using a custom seed requires
        building the kernel and dependent packages locally, since this
        customization happens at build time.
      '';
    };

    boot.kernelParams = mkOption {
      type = types.listOf (types.strMatching ''([^"[:space:]]|"[^"]*")+'' // {
        name = "kernelParam";
        description = "string, with spaces inside double quotes";
      });
      default = [ ];
      description = lib.mdDoc "Parameters added to the kernel command line.";
    };

    boot.consoleLogLevel = mkOption {
      type = types.int;
      default = 4;
      description = lib.mdDoc ''
        The kernel console `loglevel`. All Kernel Messages with a log level smaller
        than this setting will be printed to the console.
      '';
    };

    boot.vesa = mkOption {
      type = types.bool;
      default = false;
      description = lib.mdDoc ''
        (Deprecated) This option, if set, activates the VESA 800x600 video
        mode on boot and disables kernel modesetting. It is equivalent to
        specifying `[ "vga=0x317" "nomodeset" ]` in the
        {option}`boot.kernelParams` option. This option is
        deprecated as of 2020: Xorg now works better with modesetting, and
        you might want a different VESA vga setting, anyway.
      '';
    };

    boot.extraModulePackages = mkOption {
      type = types.listOf types.package;
      default = [];
      example = literalExpression "[ config.boot.kernelPackages.nvidia_x11 ]";
      description = lib.mdDoc "A list of additional packages supplying kernel modules.";
    };

    boot.kernelModules = mkOption {
      type = types.listOf types.str;
      default = [];
      description = lib.mdDoc ''
        The set of kernel modules to be loaded in the second stage of
        the boot process.  Note that modules that are needed to
        mount the root file system should be added to
        {option}`boot.initrd.availableKernelModules` or
        {option}`boot.initrd.kernelModules`.
      '';
    };

    boot.initrd.availableKernelModules = mkOption {
      type = types.listOf types.str;
      default = [];
      example = [ "sata_nv" "ext3" ];
      description = lib.mdDoc ''
        The set of kernel modules in the initial ramdisk used during the
        boot process.  This set must include all modules necessary for
        mounting the root device.  That is, it should include modules
        for the physical device (e.g., SCSI drivers) and for the file
        system (e.g., ext3).  The set specified here is automatically
        closed under the module dependency relation, i.e., all
        dependencies of the modules list here are included
        automatically.  The modules listed here are available in the
        initrd, but are only loaded on demand (e.g., the ext3 module is
        loaded automatically when an ext3 filesystem is mounted, and
        modules for PCI devices are loaded when they match the PCI ID
        of a device in your system).  To force a module to be loaded,
        include it in {option}`boot.initrd.kernelModules`.
      '';
    };

    boot.initrd.kernelModules = mkOption {
      type = types.listOf types.str;
      default = [];
      description = lib.mdDoc "List of modules that are always loaded by the initrd.";
    };

    boot.initrd.includeDefaultModules = mkOption {
      type = types.bool;
      default = true;
      description = lib.mdDoc ''
        This option, if set, adds a collection of default kernel modules
        to {option}`boot.initrd.availableKernelModules` and
        {option}`boot.initrd.kernelModules`.
      '';
    };

    system.modulesTree = mkOption {
      type = types.listOf types.path;
      internal = true;
      default = [];
      description = lib.mdDoc ''
        Tree of kernel modules.  This includes the kernel, plus modules
        built outside of the kernel.  Combine these into a single tree of
        symlinks because modprobe only supports one directory.
      '';
      # Convert the list of path to only one path.
      apply = let
        kernel-name = config.boot.kernelPackages.kernel.name or "kernel";
      in modules: (pkgs.aggregateModules modules).override { name = kernel-name + "-modules"; };
    };

    system.requiredKernelConfig = mkOption {
      default = [];
      example = literalExpression ''
        with config.lib.kernelConfig; [
          (isYes "MODULES")
          (isEnabled "FB_CON_DECOR")
          (isEnabled "BLK_DEV_INITRD")
        ]
      '';
      internal = true;
      type = types.listOf types.attrs;
      description = lib.mdDoc ''
        This option allows modules to specify the kernel config options that
        must be set (or unset) for the module to work. Please use the
        lib.kernelConfig functions to build list elements.
      '';
    };

  };


  ###### implementation

  config = mkMerge
    [ (mkIf config.boot.initrd.enable {
        boot.initrd.availableKernelModules =
          optionals config.boot.initrd.includeDefaultModules ([
            # Note: most of these (especially the SATA/PATA modules)
            # shouldn't be included by default since nixos-generate-config
            # detects them, but I'm keeping them for now for backwards
            # compatibility.

            # Some SATA/PATA stuff.
            "ahci"
            "sata_nv"
            "sata_via"
            "sata_sis"
            "sata_uli"
            "ata_piix"
            "pata_marvell"

            # NVMe
            "nvme"

            # Standard SCSI stuff.
            "sd_mod"
            "sr_mod"

            # SD cards and internal eMMC drives.
            "mmc_block"

            # Support USB keyboards, in case the boot fails and we only have
            # a USB keyboard, or for LUKS passphrase prompt.
            "uhci_hcd"
            "ehci_hcd"
            "ehci_pci"
            "ohci_hcd"
            "ohci_pci"
            "xhci_hcd"
            "xhci_pci"
            "usbhid"
            "hid_generic" "hid_lenovo" "hid_apple" "hid_roccat"
            "hid_logitech_hidpp" "hid_logitech_dj" "hid_microsoft" "hid_cherry"
            "hid_corsair"

          ] ++ optionals pkgs.stdenv.hostPlatform.isx86 [
            # Misc. x86 keyboard stuff.
            "pcips2" "atkbd" "i8042"

            # x86 RTC needed by the stage 2 init script.
            "rtc_cmos"
          ]);

        boot.initrd.kernelModules =
          optionals config.boot.initrd.includeDefaultModules [
            # For LVM.
            "dm_mod"
          ];
      })

      (mkIf config.boot.kernel.enable {
        system.build = { inherit kernel; };

        system.modulesTree = [ kernel ] ++ config.boot.extraModulePackages;

        # Not required for, e.g., containers as they don't have their own kernel or initrd.
        # They boot directly into stage 2.
        system.systemBuilderArgs.kernelParams = config.boot.kernelParams;
        system.systemBuilderCommands =
          let
            kernelPath = "${config.boot.kernelPackages.kernel}/" +
              "${config.system.boot.loader.kernelFile}";
            initrdPath = "${config.system.build.initialRamdisk}/" +
              "${config.system.boot.loader.initrdFile}";
          in
          ''
            if [ ! -f ${kernelPath} ]; then
              echo "The bootloader cannot find the proper kernel image."
              echo "(Expecting ${kernelPath})"
              false
            fi

            ln -s ${kernelPath} $out/kernel
            ln -s ${config.system.modulesTree} $out/kernel-modules
            ${optionalString (config.hardware.deviceTree.package != null) ''
              ln -s ${config.hardware.deviceTree.package} $out/dtbs
            ''}

            echo -n "$kernelParams" > $out/kernel-params

            ln -s ${initrdPath} $out/initrd

            ln -s ${config.system.build.initialRamdiskSecretAppender}/bin/append-initrd-secrets $out

            ln -s ${config.hardware.firmware}/lib/firmware $out/firmware
          '';

        # Implement consoleLogLevel both in early boot and using sysctl
        # (so you don't need to reboot to have changes take effect).
        boot.kernelParams =
          [ "loglevel=${toString config.boot.consoleLogLevel}" ] ++
          optionals config.boot.vesa [ "vga=0x317" "nomodeset" ];

        boot.kernel.sysctl."kernel.printk" = mkDefault config.boot.consoleLogLevel;

        boot.kernelModules = [ "loop" "atkbd" ];

        # Create /etc/modules-load.d/nixos.conf, which is read by
        # systemd-modules-load.service to load required kernel modules.
        environment.etc =
          { "modules-load.d/nixos.conf".source = kernelModulesConf;
          };

        systemd.services.systemd-modules-load =
          { wantedBy = [ "multi-user.target" ];
            restartTriggers = [ kernelModulesConf ];
            serviceConfig =
              { # Ignore failed module loads.  Typically some of the
                # modules in ‘boot.kernelModules’ are "nice to have but
                # not required" (e.g. acpi-cpufreq), so we don't want to
                # barf on those.
                SuccessExitStatus = "0 1";
              };
          };

        lib.kernelConfig = {
          isYes = option: {
            assertion = config: config.isYes option;
            message = "CONFIG_${option} is not yes!";
            configLine = "CONFIG_${option}=y";
          };

          isNo = option: {
            assertion = config: config.isNo option;
            message = "CONFIG_${option} is not no!";
            configLine = "CONFIG_${option}=n";
          };

          isModule = option: {
            assertion = config: config.isModule option;
            message = "CONFIG_${option} is not built as a module!";
            configLine = "CONFIG_${option}=m";
          };

          ### Usually you will just want to use these two
          # True if yes or module
          isEnabled = option: {
            assertion = config: config.isEnabled option;
            message = "CONFIG_${option} is not enabled!";
            configLine = "CONFIG_${option}=y";
          };

          # True if no or omitted
          isDisabled = option: {
            assertion = config: config.isDisabled option;
            message = "CONFIG_${option} is not disabled!";
            configLine = "CONFIG_${option}=n";
          };
        };

        # The config options that all modules can depend upon
        system.requiredKernelConfig = with config.lib.kernelConfig;
          [
            # !!! Should this really be needed?
            (isYes "MODULES")
            (isYes "BINFMT_ELF")
          ] ++ (optional (randstructSeed != "") (isYes "GCC_PLUGIN_RANDSTRUCT"));

        # nixpkgs kernels are assumed to have all required features
        assertions = if config.boot.kernelPackages.kernel ? features then [] else
          let cfg = config.boot.kernelPackages.kernel.config; in map (attrs:
            { assertion = attrs.assertion cfg; inherit (attrs) message; }
          ) config.system.requiredKernelConfig;

      })

    ];

}