1{
2 config,
3 lib,
4 pkgs,
5 ...
6}:
7
8with lib;
9
10let
11 cpupower = config.boot.kernelPackages.cpupower;
12 cfg = config.powerManagement;
13in
14
15{
16 ###### interface
17
18 options.powerManagement = {
19
20 # TODO: This should be aliased to powerManagement.cpufreq.governor.
21 # https://github.com/NixOS/nixpkgs/pull/53041#commitcomment-31825338
22 cpuFreqGovernor = mkOption {
23 type = types.nullOr types.str;
24 default = null;
25 example = "ondemand";
26 description = ''
27 Configure the governor used to regulate the frequency of the
28 available CPUs. By default, the kernel configures the
29 performance governor, although this may be overwritten in your
30 hardware-configuration.nix file.
31
32 Often used values: "ondemand", "powersave", "performance"
33 '';
34 };
35
36 cpufreq = {
37
38 max = mkOption {
39 type = types.nullOr types.ints.unsigned;
40 default = null;
41 example = 2200000;
42 description = ''
43 The maximum frequency the CPU will use. Defaults to the maximum possible.
44 '';
45 };
46
47 min = mkOption {
48 type = types.nullOr types.ints.unsigned;
49 default = null;
50 example = 800000;
51 description = ''
52 The minimum frequency the CPU will use.
53 '';
54 };
55 };
56
57 };
58
59 ###### implementation
60
61 config =
62 let
63 governorEnable = cfg.cpuFreqGovernor != null;
64 maxEnable = cfg.cpufreq.max != null;
65 minEnable = cfg.cpufreq.min != null;
66 enable = !config.boot.isContainer && (governorEnable || maxEnable || minEnable);
67 in
68 mkIf enable {
69
70 boot.kernelModules = optional governorEnable "cpufreq_${cfg.cpuFreqGovernor}";
71
72 environment.systemPackages = [ cpupower ];
73
74 systemd.services.cpufreq = {
75 description = "CPU Frequency Setup";
76 after = [ "systemd-modules-load.service" ];
77 wantedBy = [ "multi-user.target" ];
78 path = [
79 cpupower
80 pkgs.kmod
81 ];
82 unitConfig.ConditionVirtualization = false;
83 serviceConfig = {
84 Type = "oneshot";
85 RemainAfterExit = "yes";
86 ExecStart =
87 "${cpupower}/bin/cpupower frequency-set "
88 + optionalString governorEnable "--governor ${cfg.cpuFreqGovernor} "
89 + optionalString maxEnable "--max ${toString cfg.cpufreq.max} "
90 + optionalString minEnable "--min ${toString cfg.cpufreq.min} ";
91 SuccessExitStatus = "0 237";
92 };
93 };
94
95 };
96}