1{ config, lib, ... }:
2let
3
4 sysctlOption = lib.mkOptionType {
5 name = "sysctl option value";
6 check =
7 val:
8 let
9 checkType = x: lib.isBool x || lib.isString x || lib.isInt x || x == null;
10 in
11 checkType val || (val._type or "" == "override" && checkType val.content);
12 merge = loc: defs: lib.mergeOneOption loc (lib.filterOverrides defs);
13 };
14
15in
16
17{
18
19 options = {
20
21 boot.kernel.sysctl = lib.mkOption {
22 type =
23 let
24 highestValueType = lib.types.ints.unsigned // {
25 merge =
26 loc: defs:
27 lib.foldl (a: b: if b.value == null then null else lib.max a b.value) 0 (lib.filterOverrides defs);
28 };
29 in
30 lib.types.submodule {
31 freeformType = lib.types.attrsOf sysctlOption;
32 options = {
33 "net.core.rmem_max" = lib.mkOption {
34 type = lib.types.nullOr highestValueType;
35 default = null;
36 description = "The maximum receive socket buffer size in bytes. In case of conflicting values, the highest will be used.";
37 };
38
39 "net.core.wmem_max" = lib.mkOption {
40 type = lib.types.nullOr highestValueType;
41 default = null;
42 description = "The maximum send socket buffer size in bytes. In case of conflicting values, the highest will be used.";
43 };
44 };
45 };
46 default = { };
47 example = lib.literalExpression ''
48 { "net.ipv4.tcp_syncookies" = false; "vm.swappiness" = 60; }
49 '';
50 description = ''
51 Runtime parameters of the Linux kernel, as set by
52 {manpage}`sysctl(8)`. Note that sysctl
53 parameters names must be enclosed in quotes
54 (e.g. `"vm.swappiness"` instead of
55 `vm.swappiness`). The value of each
56 parameter may be a string, integer, boolean, or null
57 (signifying the option will not appear at all).
58 '';
59
60 };
61
62 };
63
64 config = {
65
66 environment.etc."sysctl.d/60-nixos.conf".text = lib.concatStrings (
67 lib.mapAttrsToList (
68 n: v: lib.optionalString (v != null) "${n}=${if v == false then "0" else toString v}\n"
69 ) config.boot.kernel.sysctl
70 );
71
72 systemd.services.systemd-sysctl = {
73 wantedBy = [ "multi-user.target" ];
74 restartTriggers = [ config.environment.etc."sysctl.d/60-nixos.conf".source ];
75 };
76
77 # Hide kernel pointers (e.g. in /proc/modules) for unprivileged
78 # users as these make it easier to exploit kernel vulnerabilities.
79 boot.kernel.sysctl."kernel.kptr_restrict" = lib.mkDefault 1;
80
81 # Improve compatibility with applications that allocate
82 # a lot of memory, like modern games
83 boot.kernel.sysctl."vm.max_map_count" = lib.mkDefault 1048576;
84 };
85}