← Documents Documentation/accounting/psi.rst GitHub 원문 ↗

Linux 6.18.37 · Accounting

PSI - Pressure Stall Information

CPU·memory·I/O contention의 some/full stall 비율과 누적 시간을 제공하고 threshold trigger·poll·cgroup2 monitoring을 정의합니다.

Source pathDocumentation/accounting/psi.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

Pressure signals

psi.rst:1-66

Resource scarcity가 workload productivity에 미치는 영향을 10/60/300초 trend와 absolute stall time으로 수치화합니다.

Threshold monitors

psi.rst:67-177

Descriptor별 some/full threshold를 등록하고 select/poll/epoll로 rate-limited wakeup을 받습니다.

Cgroup2 scope

psi.rst:178-188

Cgroup마다 cpu.pressure, memory.pressure, io.pressure를 같은 format으로 제공합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. _psi:
2
3 ================================
4 PSI - Pressure Stall Information
5 ================================
6
7 :Date: April, 2018
8 :Author: Johannes Weiner <hannes@cmpxchg.org>
9
10 When CPU, memory or IO devices are contended, workloads experience
11 latency spikes, throughput losses, and run the risk of OOM kills.
12
13 Without an accurate measure of such contention, users are forced to
14 either play it safe and under-utilize their hardware resources, or
15 roll the dice and frequently suffer the disruptions resulting from
16 excessive overcommit.
17
18 The psi feature identifies and quantifies the disruptions caused by
19 such resource crunches and the time impact it has on complex workloads
20 or even entire systems.
21
22 Having an accurate measure of productivity losses caused by resource
23 scarcity aids users in sizing workloads to hardware--or provisioning
24 hardware according to workload demand.
25
26 As psi aggregates this information in realtime, systems can be managed
27 dynamically using techniques such as load shedding, migrating jobs to
28 other systems or data centers, or strategically pausing or killing low
29 priority or restartable batch jobs.
30
31 This allows maximizing hardware utilization without sacrificing
32 workload health or risking major disruptions such as OOM kills.
33
34 Pressure interface
35 ==================
36
37 Pressure information for each resource is exported through the
38 respective file in /proc/pressure/ -- cpu, memory, and io.
39
40 The format is as such::
41
42 some avg10=0.00 avg60=0.00 avg300=0.00 total=0
43 full avg10=0.00 avg60=0.00 avg300=0.00 total=0
44
45 The "some" line indicates the share of time in which at least some
46 tasks are stalled on a given resource.
47
48 The "full" line indicates the share of time in which all non-idle
49 tasks are stalled on a given resource simultaneously. In this state
50 actual CPU cycles are going to waste, and a workload that spends
51 extended time in this state is considered to be thrashing. This has
52 severe impact on performance, and it's useful to distinguish this
53 situation from a state where some tasks are stalled but the CPU is
54 still doing productive work. As such, time spent in this subset of the
55 stall state is tracked separately and exported in the "full" averages.
56
57 CPU full is undefined at the system level, but has been reported
58 since 5.13, so it is set to zero for backward compatibility.
59
60 The ratios (in %) are tracked as recent trends over ten, sixty, and
61 three hundred second windows, which gives insight into short term events
62 as well as medium and long term trends. The total absolute stall time
63 (in us) is tracked and exported as well, to allow detection of latency
64 spikes which wouldn't necessarily make a dent in the time averages,
65 or to average trends over custom time frames.
66
67 Monitoring for pressure thresholds
68 ==================================
69
70 Users can register triggers and use poll() to be woken up when resource
71 pressure exceeds certain thresholds.
72
73 A trigger describes the maximum cumulative stall time over a specific
74 time window, e.g. 100ms of total stall time within any 500ms window to
75 generate a wakeup event.
76
77 To register a trigger user has to open psi interface file under
78 /proc/pressure/ representing the resource to be monitored and write the
79 desired threshold and time window. The open file descriptor should be
80 used to wait for trigger events using select(), poll() or epoll().
81 The following format is used::
82
83 <some|full> <stall amount in us> <time window in us>
84
85 For example writing "some 150000 1000000" into /proc/pressure/memory
86 would add 150ms threshold for partial memory stall measured within
87 1sec time window. Writing "full 50000 1000000" into /proc/pressure/io
88 would add 50ms threshold for full io stall measured within 1sec time window.
89
90 Triggers can be set on more than one psi metric and more than one trigger
91 for the same psi metric can be specified. However for each trigger a separate
92 file descriptor is required to be able to poll it separately from others,
93 therefore for each trigger a separate open() syscall should be made even
94 when opening the same psi interface file. Write operations to a file descriptor
95 with an already existing psi trigger will fail with EBUSY.
96
97 Monitors activate only when system enters stall state for the monitored
98 psi metric and deactivates upon exit from the stall state. While system is
99 in the stall state psi signal growth is monitored at a rate of 10 times per
100 tracking window.
101
102 The kernel accepts window sizes ranging from 500ms to 10s, therefore min
103 monitoring update interval is 50ms and max is 1s. Min limit is set to
104 prevent overly frequent polling. Max limit is chosen as a high enough number
105 after which monitors are most likely not needed and psi averages can be used
106 instead.
107
108 Unprivileged users can also create monitors, with the only limitation that the
109 window size must be a multiple of 2s, in order to prevent excessive resource
110 usage.
111
112 When activated, psi monitor stays active for at least the duration of one
113 tracking window to avoid repeated activations/deactivations when system is
114 bouncing in and out of the stall state.
115
116 Notifications to the userspace are rate-limited to one per tracking window.
117
118 The trigger will de-register when the file descriptor used to define the
119 trigger is closed.
120
121 Userspace monitor usage example
122 ===============================
123
124 ::
125
126 #include <errno.h>
127 #include <fcntl.h>
128 #include <stdio.h>
129 #include <poll.h>
130 #include <string.h>
131 #include <unistd.h>
132
133 /*
134 * Monitor memory partial stall with 1s tracking window size
135 * and 150ms threshold.
136 */
137 int main() {
138 const char trig[] = "some 150000 1000000";
139 struct pollfd fds;
140 int n;
141
142 fds.fd = open("/proc/pressure/memory", O_RDWR | O_NONBLOCK);
143 if (fds.fd < 0) {
144 printf("/proc/pressure/memory open error: %s\n",
145 strerror(errno));
146 return 1;
147 }
148 fds.events = POLLPRI;
149
150 if (write(fds.fd, trig, strlen(trig) + 1) < 0) {
151 printf("/proc/pressure/memory write error: %s\n",
152 strerror(errno));
153 return 1;
154 }
155
156 printf("waiting for events...\n");
157 while (1) {
158 n = poll(&fds, 1, -1);
159 if (n < 0) {
160 printf("poll error: %s\n", strerror(errno));
161 return 1;
162 }
163 if (fds.revents & POLLERR) {
164 printf("got POLLERR, event source is gone\n");
165 return 0;
166 }
167 if (fds.revents & POLLPRI) {
168 printf("event triggered!\n");
169 } else {
170 printf("unknown event received: 0x%x\n", fds.revents);
171 return 1;
172 }
173 }
174
175 return 0;
176 }
177
178 Cgroup2 interface
179 =================
180
181 In a system with a CONFIG_CGROUPS=y kernel and the cgroup2 filesystem
182 mounted, pressure stall information is also tracked for tasks grouped
183 into cgroups. Each subdirectory in the cgroupfs mountpoint contains
184 cpu.pressure, memory.pressure, and io.pressure files; the format is
185 the same as the /proc/pressure/ files.
186
187 Per-cgroup psi monitors can be specified and used the same way as
188 system-wide ones.
189

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

PSI가 측정하는 resource pressure

1-33

PSI(Pressure Stall Information)는 2018년 4월 Johannes Weiner가 작성했습니다. CPU, memory 또는 I/O device가 contention 상태가 되면 workload는 latency spike와 throughput loss를 겪고 OOM kill 위험도 커집니다.

Contention을 정확히 측정하지 못하면 사용자는 안전을 위해 hardware resource를 충분히 활용하지 못하거나, 과도한 overcommit으로 인한 disruption을 자주 감수해야 합니다. PSI는 resource crunch가 일으키는 disruption과 complex workload 또는 system 전체에 미치는 시간 영향을 식별하고 수치화합니다.

Resource scarcity로 인한 productivity loss를 정확히 알면 workload를 hardware에 맞게 sizing하거나 workload demand에 맞춰 hardware를 provision할 수 있습니다. PSI는 정보를 realtime으로 aggregate하므로 load shedding, job을 다른 system/data center로 migration, 낮은 priority 또는 restart 가능한 batch job을 선택적으로 pause/kill하는 방식으로 system을 동적으로 관리할 수 있습니다. 따라서 workload health를 해치거나 OOM kill 같은 큰 disruption 위험을 높이지 않고 hardware utilization을 극대화할 수 있습니다.

Pressure feedback loop
CPU / memory / I/O contentionPSI quantifies stall timeEstimate productivity lossResize workload or provision hardware
Realtime pressure trendLoad shedding / migration / pause / killProtect workload health and utilization

Resource contention을 측정 가능한 signal로 바꿔 dynamic capacity action에 연결합니다.

Pressure interface와 some/full

34-66

Resource별 pressure information은 `/proc/pressure/` 아래 `cpu`, `memory`, `io` file로 내보냅니다. 각 file은 다음 형식의 `some`과 `full` line을 제공합니다.

some avg10=0.00 avg60=0.00 avg300=0.00 total=0
full avg10=0.00 avg60=0.00 avg300=0.00 total=0

`some`은 주어진 resource에서 task 일부 이상이 stall된 시간 비율입니다. `full`은 non-idle task 전부가 같은 resource에서 동시에 stall된 시간 비율입니다. Full 상태에서는 실제 CPU cycle이 낭비되고 이 상태가 오래 지속되는 workload는 thrashing 중이라고 봅니다. 일부 task는 stall돼도 CPU가 productive work를 하는 상태와 성능 영향이 큰 full 상태를 구분하기 위해 full average를 별도로 추적합니다.

System level의 CPU `full`은 정의되지 않았지만 Linux 5.13부터 보고됐기 때문에 backward compatibility를 위해 `0`으로 설정합니다.

PSI output fields
Line/fieldMeaning
someAt least some tasks stalled
fullAll non-idle tasks stalled simultaneously
avg10Recent 10-second percentage trend
avg60Recent 60-second percentage trend
avg300Recent 300-second percentage trend
totalAbsolute cumulative stall time in microseconds

Resource별 두 stall scope와 time metrics입니다.

Ratio는 percent 단위로 10초, 60초, 300초 window의 recent trend를 추적해 short-, medium-, long-term event를 보여 줍니다. Absolute total stall time은 microseconds(`us`)로도 내보냅니다. Average에 눈에 띄는 변화를 만들지 못하는 latency spike를 감지하거나 custom time frame의 trend를 계산할 때 사용합니다.

Pressure threshold monitoring

67-120

사용자는 trigger를 register하고 resource pressure가 threshold를 넘을 때 `poll()` wakeup을 받을 수 있습니다. Trigger는 특정 time window 안의 maximum cumulative stall time을 기술합니다. 예를 들어 어떤 500ms window에서든 total stall이 100ms이면 wakeup event를 만들 수 있습니다.

Monitor할 resource의 `/proc/pressure/` file을 open하고 threshold와 time window를 씁니다. Open file descriptor로 `select()`, `poll()`, `epoll()` event를 기다립니다. 형식은 `<some|full> <stall amount in us> <time window in us>`입니다.

PSI trigger examples
Write targetTriggerMeaning
/proc/pressure/memorysome 150000 1000000150ms partial memory stall within 1s
/proc/pressure/iofull 50000 100000050ms full I/O stall within 1s

Partial memory stall과 full I/O stall의 입력을 해석합니다.

Metric 여러 개와 같은 metric의 trigger 여러 개를 설정할 수 있습니다. Trigger마다 별도로 poll하려면 각자 file descriptor가 필요하므로 같은 PSI file이라도 trigger마다 `open()`해야 합니다. 이미 trigger가 있는 descriptor에 다시 write하면 `EBUSY`로 실패합니다.

Monitor는 system이 대상 PSI metric의 stall state에 들어갈 때만 activate되고 빠져나오면 deactivate됩니다. Stall 중 PSI signal growth는 tracking window마다 10회 rate로 monitor합니다. Kernel은 500ms~10s window를 허용하므로 update interval은 최소 50ms, 최대 1s입니다. 최소치는 지나친 polling을 막고 최대치는 그보다 긴 구간에는 monitor 대신 PSI average를 쓰는 편이 적합하기 때문에 정했습니다.

Unprivileged user도 monitor를 만들 수 있지만 excessive resource usage를 막기 위해 window size는 2s의 배수여야 합니다. Activate된 monitor는 system이 stall 경계를 오갈 때 반복 activate/deactivate하지 않도록 적어도 tracking window 하나 동안 active 상태를 유지합니다. Userspace notification은 tracking window마다 한 번으로 rate-limit됩니다. Trigger를 정의한 file descriptor를 close하면 de-register됩니다.

PSI monitor constraints
ConstraintValue
Kernel window range500ms to 10s
Monitoring rate in stall10 updates per tracking window
Update interval range50ms to 1s
Unprivileged windowMultiple of 2s
Minimum active durationOne tracking window
Notification rateAt most one per tracking window
LifetimeClose defining fd to deregister

Window, sampling, notification과 descriptor lifetime 규칙입니다.

Userspace poll monitor 예제

121-177

다음 C program은 1초 tracking window에서 150ms의 partial memory stall을 monitor합니다. `/proc/pressure/memory`를 `O_RDWR | O_NONBLOCK`으로 열고 `some 150000 1000000` trigger를 쓴 뒤 `POLLPRI` event를 무기한 기다립니다.

`POLLERR`이면 event source가 사라진 것이므로 종료하고, `POLLPRI`이면 trigger event를 보고합니다. 그 밖의 event는 unknown으로 처리합니다. Header, function call, string과 error path를 보존하기 위해 원문 code를 그대로 제공합니다.

::

  #include <errno.h>
  #include <fcntl.h>
  #include <stdio.h>
  #include <poll.h>
  #include <string.h>
  #include <unistd.h>

  /*
   * Monitor memory partial stall with 1s tracking window size
   * and 150ms threshold.
   */
  int main() {
	const char trig[] = "some 150000 1000000";
	struct pollfd fds;
	int n;

	fds.fd = open("/proc/pressure/memory", O_RDWR | O_NONBLOCK);
	if (fds.fd < 0) {
		printf("/proc/pressure/memory open error: %s\n",
			strerror(errno));
		return 1;
	}
	fds.events = POLLPRI;

	if (write(fds.fd, trig, strlen(trig) + 1) < 0) {
		printf("/proc/pressure/memory write error: %s\n",
			strerror(errno));
		return 1;
	}

	printf("waiting for events...\n");
	while (1) {
		n = poll(&fds, 1, -1);
		if (n < 0) {
			printf("poll error: %s\n", strerror(errno));
			return 1;
		}
		if (fds.revents & POLLERR) {
			printf("got POLLERR, event source is gone\n");
			return 0;
		}
		if (fds.revents & POLLPRI) {
			printf("event triggered!\n");
		} else {
			printf("unknown event received: 0x%x\n", fds.revents);
			return 1;
		}
	}

	return 0;
  }

Cgroup2 pressure interface

178-188

`CONFIG_CGROUPS=y` kernel에서 cgroup2 filesystem을 mount하면 cgroup에 묶인 task의 PSI도 추적합니다. Cgroupfs mountpoint의 각 subdirectory에는 `cpu.pressure`, `memory.pressure`, `io.pressure` file이 있고 format은 `/proc/pressure/` file과 같습니다.

Per-cgroup PSI monitor도 system-wide monitor와 같은 방식으로 지정하고 사용할 수 있습니다.

System-wide와 cgroup2 PSI paths
ScopeCPUMemoryI/O
System/proc/pressure/cpu/proc/pressure/memory/proc/pressure/io
Cgroup2 directorycpu.pressurememory.pressureio.pressure

같은 some/full format을 서로 다른 accounting scope에 제공합니다.