Power management/Processor/ru

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Power management/Processor and the translation is 20% complete.
Outdated translations are marked like this.
Other languages:

Эта статья описывает настройку управления питанием для процессоров.

Изменение частоты процессора

Изменение частоты процессора — это метод, в котором частота процессора может быть автоматически изменена "на лету" для сохранения энергии, а также это уменьшит количество выделяемого чипом тепла.

The ACPI specification describes the scaling mechanism as performance states - P-states or Processor Performance States.[1] The state labeled as P0 is used for the processor's highest possible frequency and P1-Pn states are used for lower frequencies.

Заметка
Lower processor frequency leads to lower number of instruction processed over a unit of time. This means finding a balance between frequency and performance is necessary.

The kernel CPUFreq subsystem[2] is responsible for handling the frequency scaling. This subsystem provides two basic means of changing the scaling behavior:

  • Scaling Governors - provide different approaches to estimate the desired processor frequency using different scaling algorithms.
  • Scaling Drivers - provide an interface between scaling governors and the specific hardware. Scaling driver can read/write hardware-specific values on behalf of the governor.


The CPUFreq subsystem exposes multiple sysfs interfaces. The most useful is created per-processor /sys/devices/system/cpu/cpu*/cpufreq/. This directory contains various files, like:

  • cpuinfo_cur_freq - current frequency in KHz as reported by the processor.
  • cpuinfo_min_freq - minimal possible frequency in KHz as reported by the processor.
  • cpuinfo_max_freq - maximal possible frequency in KHz as reported by the processor.
  • scaling_governor - currently used scaling governor. It can be changed by writing to this file.
  • scaling_driver - currently used scaling driver. It can be changed by writing to this file.
  • scaling_min_freq - minimal processor frequency in KHz to be used by the governor. It can be set by writing to this file.
  • scaling_max_freq - maximum processor frequency in KHz to be used by the governor. It can be set by writing to this file.

Установка

BIOS

Некоторые функции могут быть включены или отключены в BIOS. Убедитесь, что следующие включены:

  • "Processor C1E support"
  • "Enhanced Speedstep (EIST)"

Ядро

Активируйте следующие параметры ядра:

ЯДРО Включение параметров ядра для управления питанием
Power management and ACPI options  --->
     [*] ACPI (Advanced Configuration and Power Interface) Support  --->
         <*>   Processor
     CPU Frequency scaling  --->
         [*] CPU Frequency scaling
             Default CPUFreq governor (ondemand)  --->
                 Select a default governor; see below table
                 Default is ondemand
             *** CPU frequency scaling drivers ***
                 Select a driver; see below table

Необходим регулятор, который отвечает за изменение частоты на основании своего профиля:

Регулятор частоты ЦП
Опция Модуль Поддерживаемые процессоры Примечания
регулятор 'performance' cpufreq_performance Статически устанавливает частоту на самое высокое из доступных значений частоты ЦП. Для процессоров Intel core должно быть выбрано по умолчанию. [3] [4]
регулятор 'powersave' cpufreq_powersave Статически устанавливает частоту на самое низкое из доступных значений частоты ЦП. Нельзя установить по умолчанию.
регулятор 'userspace' для изменения частоты в пользовательском пространстве cpufreq_userspace Для установки частоты ЦП вручную, или когда пользовательская программа должна иметь возможность динамической установки частоты.
регулятор частоты ЦП 'ondemand' cpufreq_ondemand Совершает периодический опрос и изменяет частоту, основываясь на использовании ЦП. Для всех процессоров, за исключением Intel core, должно быть выбрано по умолчанию
регулятор частоты ЦП 'conservative' cpufreq_conservative Похож на ondemand. Частота плавно увеличивается и уменьшается вместо того, что подпрыгивать до 100%, когда нужна скорость.
Заметка
Название активного регулятора CPUFreq доступно в: /sys/devices/system/cpu/cpu[0-9]*/cpufreq/scaling_governor

Behavior of active governor can be further configured via tunables exposed as sysfs interface. For more details see the dedicated documentation. Commonly used sysfs tunables include:

  • schedutil - /sys/devices/system/cpu/cpufreq/schedutil/rate_limit_us sets minimal interval in μs between consecutive governor runs.
  • ondemand - /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate sets the interval in μs between consecutive load sampling runs.
  • conservative - /sys/devices/system/cpu/cpufreq/conservative/freq_step sets the maximal frequency change step as % of scaling_max_freq.


Драйвера изменения частоты ЦП
Опция Модуль Поддерживаемые процессоры Примечания
Intel P state control intel_pstate Новые (SandyBridge+) Intel Core
Processor Clocking Control interface driver pcc-cpufreq
ACPI Processor P-States driver acpi-cpufreq Старые Intel Core, Intel Atom, Intel Pentium M
AMD Opteron/Athlon64 PowerNow! powernow-k8 AMD Opteron, AMD Athlon 64, AMD Turion 64
Intel Enhanced SpeedStep (устаревший) speedstep-centrino Intel Pentium M (Centrino), Intel Xeon Устарел, вместо него используйте ACPI Processor P-States driver
Intel Pentium 4 clock modulation p4-clockmod Intel Pentium 4, Intel XEON Вызывает серьёзные замедления и ощутимые задержки
Заметка
Availability of drivers depend on the processor architecture.
Совет
Name of the active CPUFreq driver is available in: /sys/devices/system/cpu/cpu*/cpufreq/scaling_driver

Specific CPU scaling drivers settings

Intel P-state

This driver implements internal scaling governors (roughly similar to CPUFreq's powersave and performance) and works based on the processor load. It is intended for recent Intel Core series of processors (based on the Sandy Bridge microarchitecture or newer).

This driver works in either active mode (intel_pstate), for processors featuring Hardware P-States (HWP), or passive mode (intel_cpufreq). The passive mode concerns the processors not supporting HWP which are generations prior the Skylake microarchitecture - no hwp CPU flag is present.

In the active mode the processor autonomously sets the frequency based on provided CPUFreq parameters. This passes the control of frequency scaling to the processor itself. On the other hand, in the passive mode the driver behaves similarly to the generic acpi-cpufreq driver - it collaborates with the regular scaling governors. Although, it can use the full range of frequency steps.[5]

In the active mode case, the userspace, ondemand, and conservative scaling governors are unnecessary. The performance governor should be selected as the default. [6]

ЯДРО Setup for Intel Sandy Bridge and newer Intel Core processors
Power management and ACPI options ---> 
  [*] CPU Frequency scaling --->
        Default CPUFreq governor (performance)  --->
    -*- 'performance' governor
    <*> Intel P state control

There is a sysfs interface exposed by the driver. Its root is located at the /sys/devices/system/cpu/intel_pstate/ directory. There are files like:

  • no_turbo - disables the Intel Turbo Boost feature (1 means disabled and 0 means enabled). The state can be changed by writing to this file.
  • status - displays the status of the driver. Values are either - off, passive, or active.


AMD P-State

This driver is available in kernel v5.17 or newer[7]. It aims to provide a more effective alternative to the generic acpi-cpufreq driver. It is based on Collaborative Processor Performance Control (CPPC)[8] to provide fine grained frequency steps. This was motivated by acpi-cpufreq providing only 3 frequency control options, and the lowest frequency is typically higher than what is made available when using amd-pstate thus being less effective than it might otherwise be as a way to maximize battery life.

It is intended for AMD Ryzen/EPYC processors based on the Zen 2 or newer microarchitecture. In case of hardware support and configuration mismatch the scaling driver gets set to the acpi-cpufreq as a fallback.

Совет
To verify the currently used driver did not fall back to acpi-cpufreq read: /sys/devices/system/cpu/cpu0/cpufreq/scaling_driver.
Важно
In order to use this driver, "CPPC", "ACPI CPPC", or similar BIOS setting must be set to enabled or auto.
ЯДРО Kernel setup for amd-pstate (for Zen 2 or newer)
Power management and ACPI options --->
  [*] CPU Frequency scaling --->
         Default CPUFreq governor (performance)  --->
  -*-  'performance' governor
  [*]   AMD Processor P-State driver
  <M>   selftest for AMD Processor P-State driver

There is a sysfs interface exposed by the driver. Its root is located at the /sys/devices/system/cpu/amd_pstate/ directory. There are files like:

  • status - displays the status of the driver. Values are either - active, passive, guided, or disable.


When the currently used driver falls back to the acpi-cpufreq driver the following kernel command-line parameters can fix loading the amd-pstate driver:

  • Zen 2 processors: Add amd_pstate.shared_mem=1 to enable amd-pstate using its shared memory implementation.[9]
  • Zen 3 or newer processors: Add amd-pstate=passive. Zen 3 or newer also supports CPPC.[8]


Kernel 6.3 further developed available AMD P-State options in the form of Energy Preference Performance (EPP) modes.[10] This new driver is referred as amd_pstate_epp. It allows new combinations of drivers and governors such as "amd_pstate_epp powersave performance" or "amd_pstate_epp performance performance". Some benchmarks are available.

For further details on the AMD P-state driver see the documentation available upstream.

Manual governor/driver change

Можно изменять активный регулятор CPU, используя простую команду:

root #for c in $(ls -d /sys/devices/system/cpu/cpu[0-9]*); do echo ondemand >$c/cpufreq/scaling_governor; done

Прочтите /etc/local.d/README, чтобы узнать, как выполнять эту команду во время загрузки.

Set governor at boot time

It is possible to set the default governor via cpufreq.default_governor kernel command-line parameter.

Важно
This parameter requires kernel v5.9+.[11]

Тики

Процессор сохраняет больше всего энергии, когда дольше остаётся в режимах энергосбережения, поэтому уменьшим количество тактов, которые его пробуждают. Подробности о доступных бестактовых режимах могут быть найдены в документации ядра.

Установка

BIOS

Некоторые функции могут быть включены или отключены в BIOS. Убедитесь, что следующие включены:

  • "HPET"
  • "Multimedia timer"

Ядро

Активируйте следующие параметры ядра:

ЯДРО Включение параметров ядра, которые оптимизируют тик
Processor type and features  --->
   [*] Tickless System (Dynamic Ticks)
   [*] High Resolution Timer Support
   [*] HPET Timer Support

CPU Idle

Modern multi-core processors are often not fully loaded which brings an opportunity to suspend the unused parts and save power. The hardware transitions the unused parts to idle states. The kernel then does not schedule regular tasks to the idle parts but only special idle tasks.

The ACPI specification describes those idle states as C-states or Processor Power States. [12] There are usually multiple C-states implemented. Starting from the C0 state for a regularly running processor to C1, C2, and deeper idle states. The deeper the idle state, greater power saving but also a longer transition back to the running state.

The kernel CPUIdle subsystem[13] is responsible for handling the idle state management. Similarly to CPUFreq, this subsystem provides two basic means of idle state management - governor and driver. The governor attempts to predict the optimal C-state and driver to perform the operation on the hardware.

The CPUIdle subsystem exposes a sysfs interface. It is available at /sys/devices/system/cpu/cpuidle/. This directory contains various files, like:

  • current_governor - currently used idle governor. It can be changed by writing to this file.
  • available_governors - list of available idle governors.
  • current_driver - currently used idle driver information.

Installation

BIOS

Check that the following settings are enabled in BIOS:

  • "C-States"
  • "ACPI C states"

Kernel

CPU idle drivers
Name Module / Kernel symbol Supported Processors Note
Intel Idle Time Driver intel_idle (CONFIG_INTEL_IDLE) recent (Nehalem+) Intel Core[14] Asks the processor part to enter the idle state using the MWAIT instruction.
ACPI Idle Driver acpi_idle (CONFIG_ACPI_PROCESSOR_IDLE) AMD processors, old Intel processors Generic idle driver
CPU idle governors
Name Module / Kernel symbol Note
Ladder Governor ladder (CONFIG_CPU_IDLE_GOV_LADDER) Default governor for systems with allowed scheduler ticks in idle - CONFIG_NO_HZ_IDLE=n.
Menu Governor menu (CONFIG_CPU_IDLE_GOV_MENU) Default governor for tickless systems - CONFIG_NO_HZ_IDLE=y.
Timer events oriented (TEO) governor TEO (CONFIG_CPU_IDLE_GOV_TEO) Alternative governor for tickless systems - CONFIG_NO_HZ_IDLE=y.

Tools

PowerTOP

PowerTOP – это утилита, предназначенная для измерения, объяснения и уменьшения электропотребления компьютера.

Когда она запускается, она сортирует запущенные процессы в порядке того, как часто они пробуждают процессор. Для подробностей об установке, настройке и использовании см. отдельную статью PowerTOP.

cpupower

The sys-power/cpupower package provides a set of tools to comfortably manage and monitor processor powersaving features. The tools include cpupower frequency-info, cpupower frequency-set, and cpupower monitor.

Hprofile

Такие приложения как sys-power/cpupower не могут практически ничего, кроме вышеописанного, но зато обладают некоторым интерфейсом. Однако, необходимость выполнения определённых команд от имени суперпользователя в зависимости от использования системы нерациональна для большинства пользователей. Лучше автоматизировать некоторые решения по управлению частотой ЦП. Например, когда отсутствует питание от сети, многие пользователи хотели бы перевести систему в режим энергосбережения.

Здесь вступает в игру Hprofile. Пожалуйста, обратитесь к его статье для получения более подробной информации и сведений о настройках.

Смотрите также

Внешние ресурсы

Ссылки

  1. 8. Processor Configuration and Control — ACPI Specification 6.4 documentation, UEFI Forum, Inc. Retrieved 9 September 2023.
  2. CPU Performance Scaling, The kernel development community. Retrieved 9 September 2023.
  3. Dominik Brodowski. Intel P-State driver, CPU frequency and voltage scaling code in the Linux(TM) kernel. Retrieved 12 June 2016.
  4. Michael Larabel. Linux's "Ondemand" Governor Is No Longer Fit. Retrieved 15 October 2016.
  5. intel_pstate CPU Performance Scaling Driver, The kernel development community. Retrieved 9 September 2023.
  6. Dominik Brodowski. Intel P-State driver, CPU frequency and voltage scaling code in the Linux(TM) kernel. Retrieved 12 June 2016.
  7. AMD P-State Driver To Premiere In Linux 5.17 With Aim To Deliver Better Power Efficiency, Michael Larabel. Retrieved 9 September 2023.
  8. 8.0 8.1 Collaborative Processor Performance Control (CPPC), The kernel development community. Retrieved 9 September 2023.
  9. How to enable amd-pstate?, Manjaro.org. Retrieved 9 September 2023.
  10. Ryzen Mobile Power/Performance With Linux 6.3's New AMD P-State EPP Driver, Michael Larabel. Retrieved 9 September 2023.
  11. The kernel’s command-line parameters, The kernel development community. Retrieved 9 September 2023.
  12. 8.1. Processor Power States — ACPI Specification 6.4 documentation, UEFI Forum, Inc. Retrieved 10 September 2023.
  13. CPU Idle Time Management, The kernel development community. Retrieved 10 September 2023.
  14. intel_idle CPU Idle Time Management Driver, The kernel development community. Retrieved 10 September 2023.