blob: db27b69fa92a0756a0fe06d9b98f1f09573f66f7 [file] [log] [blame]
Johannes Weinereb414682018-10-26 15:06:27 -07001/*
2 * Pressure stall information for CPU, memory and IO
3 *
4 * Copyright (c) 2018 Facebook, Inc.
5 * Author: Johannes Weiner <hannes@cmpxchg.org>
6 *
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07007 * Polling support by Suren Baghdasaryan <surenb@google.com>
8 * Copyright (c) 2018 Google, Inc.
9 *
Johannes Weinereb414682018-10-26 15:06:27 -070010 * When CPU, memory and IO are contended, tasks experience delays that
11 * reduce throughput and introduce latencies into the workload. Memory
12 * and IO contention, in addition, can cause a full loss of forward
13 * progress in which the CPU goes idle.
14 *
15 * This code aggregates individual task delays into resource pressure
16 * metrics that indicate problems with both workload health and
17 * resource utilization.
18 *
19 * Model
20 *
21 * The time in which a task can execute on a CPU is our baseline for
22 * productivity. Pressure expresses the amount of time in which this
23 * potential cannot be realized due to resource contention.
24 *
25 * This concept of productivity has two components: the workload and
26 * the CPU. To measure the impact of pressure on both, we define two
27 * contention states for a resource: SOME and FULL.
28 *
29 * In the SOME state of a given resource, one or more tasks are
30 * delayed on that resource. This affects the workload's ability to
31 * perform work, but the CPU may still be executing other tasks.
32 *
33 * In the FULL state of a given resource, all non-idle tasks are
34 * delayed on that resource such that nobody is advancing and the CPU
35 * goes idle. This leaves both workload and CPU unproductive.
36 *
Chengming Zhoue7fcd762021-03-03 11:46:56 +080037 * Naturally, the FULL state doesn't exist for the CPU resource at the
38 * system level, but exist at the cgroup level, means all non-idle tasks
39 * in a cgroup are delayed on the CPU resource which used by others outside
40 * of the cgroup or throttled by the cgroup cpu.max configuration.
Johannes Weinereb414682018-10-26 15:06:27 -070041 *
42 * SOME = nr_delayed_tasks != 0
43 * FULL = nr_delayed_tasks != 0 && nr_running_tasks == 0
44 *
45 * The percentage of wallclock time spent in those compound stall
46 * states gives pressure numbers between 0 and 100 for each resource,
47 * where the SOME percentage indicates workload slowdowns and the FULL
48 * percentage indicates reduced CPU utilization:
49 *
50 * %SOME = time(SOME) / period
51 * %FULL = time(FULL) / period
52 *
53 * Multiple CPUs
54 *
55 * The more tasks and available CPUs there are, the more work can be
56 * performed concurrently. This means that the potential that can go
57 * unrealized due to resource contention *also* scales with non-idle
58 * tasks and CPUs.
59 *
60 * Consider a scenario where 257 number crunching tasks are trying to
61 * run concurrently on 256 CPUs. If we simply aggregated the task
62 * states, we would have to conclude a CPU SOME pressure number of
63 * 100%, since *somebody* is waiting on a runqueue at all
64 * times. However, that is clearly not the amount of contention the
Ingo Molnar3b037062021-03-18 13:38:50 +010065 * workload is experiencing: only one out of 256 possible execution
Johannes Weinereb414682018-10-26 15:06:27 -070066 * threads will be contended at any given time, or about 0.4%.
67 *
68 * Conversely, consider a scenario of 4 tasks and 4 CPUs where at any
69 * given time *one* of the tasks is delayed due to a lack of memory.
70 * Again, looking purely at the task state would yield a memory FULL
71 * pressure number of 0%, since *somebody* is always making forward
72 * progress. But again this wouldn't capture the amount of execution
73 * potential lost, which is 1 out of 4 CPUs, or 25%.
74 *
75 * To calculate wasted potential (pressure) with multiple processors,
76 * we have to base our calculation on the number of non-idle tasks in
77 * conjunction with the number of available CPUs, which is the number
78 * of potential execution threads. SOME becomes then the proportion of
Ingo Molnar3b037062021-03-18 13:38:50 +010079 * delayed tasks to possible threads, and FULL is the share of possible
Johannes Weinereb414682018-10-26 15:06:27 -070080 * threads that are unproductive due to delays:
81 *
82 * threads = min(nr_nonidle_tasks, nr_cpus)
83 * SOME = min(nr_delayed_tasks / threads, 1)
84 * FULL = (threads - min(nr_running_tasks, threads)) / threads
85 *
86 * For the 257 number crunchers on 256 CPUs, this yields:
87 *
88 * threads = min(257, 256)
89 * SOME = min(1 / 256, 1) = 0.4%
90 * FULL = (256 - min(257, 256)) / 256 = 0%
91 *
92 * For the 1 out of 4 memory-delayed tasks, this yields:
93 *
94 * threads = min(4, 4)
95 * SOME = min(1 / 4, 1) = 25%
96 * FULL = (4 - min(3, 4)) / 4 = 25%
97 *
98 * [ Substitute nr_cpus with 1, and you can see that it's a natural
99 * extension of the single-CPU model. ]
100 *
101 * Implementation
102 *
103 * To assess the precise time spent in each such state, we would have
104 * to freeze the system on task changes and start/stop the state
105 * clocks accordingly. Obviously that doesn't scale in practice.
106 *
107 * Because the scheduler aims to distribute the compute load evenly
108 * among the available CPUs, we can track task state locally to each
109 * CPU and, at much lower frequency, extrapolate the global state for
110 * the cumulative stall times and the running averages.
111 *
112 * For each runqueue, we track:
113 *
114 * tSOME[cpu] = time(nr_delayed_tasks[cpu] != 0)
115 * tFULL[cpu] = time(nr_delayed_tasks[cpu] && !nr_running_tasks[cpu])
116 * tNONIDLE[cpu] = time(nr_nonidle_tasks[cpu] != 0)
117 *
118 * and then periodically aggregate:
119 *
120 * tNONIDLE = sum(tNONIDLE[i])
121 *
122 * tSOME = sum(tSOME[i] * tNONIDLE[i]) / tNONIDLE
123 * tFULL = sum(tFULL[i] * tNONIDLE[i]) / tNONIDLE
124 *
125 * %SOME = tSOME / period
126 * %FULL = tFULL / period
127 *
128 * This gives us an approximation of pressure that is practical
129 * cost-wise, yet way more sensitive and accurate than periodic
130 * sampling of the aggregate task states would be.
131 */
132
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800133#include "../workqueue_internal.h"
Johannes Weinereb414682018-10-26 15:06:27 -0700134#include <linux/sched/loadavg.h>
135#include <linux/seq_file.h>
136#include <linux/proc_fs.h>
137#include <linux/seqlock.h>
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700138#include <linux/uaccess.h>
Johannes Weinereb414682018-10-26 15:06:27 -0700139#include <linux/cgroup.h>
140#include <linux/module.h>
141#include <linux/sched.h>
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700142#include <linux/ctype.h>
143#include <linux/file.h>
144#include <linux/poll.h>
Johannes Weinereb414682018-10-26 15:06:27 -0700145#include <linux/psi.h>
146#include "sched.h"
147
148static int psi_bug __read_mostly;
149
Johannes Weinere0c27442018-11-30 14:09:58 -0800150DEFINE_STATIC_KEY_FALSE(psi_disabled);
151
152#ifdef CONFIG_PSI_DEFAULT_DISABLED
Suren Baghdasaryan9289c5e2019-05-14 15:40:59 -0700153static bool psi_enable;
Johannes Weinere0c27442018-11-30 14:09:58 -0800154#else
Suren Baghdasaryan9289c5e2019-05-14 15:40:59 -0700155static bool psi_enable = true;
Johannes Weinere0c27442018-11-30 14:09:58 -0800156#endif
157static int __init setup_psi(char *str)
158{
159 return kstrtobool(str, &psi_enable) == 0;
160}
161__setup("psi=", setup_psi);
Johannes Weinereb414682018-10-26 15:06:27 -0700162
163/* Running averages - we need to be higher-res than loadavg */
164#define PSI_FREQ (2*HZ+1) /* 2 sec intervals */
165#define EXP_10s 1677 /* 1/exp(2s/10s) as fixed-point */
166#define EXP_60s 1981 /* 1/exp(2s/60s) */
167#define EXP_300s 2034 /* 1/exp(2s/300s) */
168
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700169/* PSI trigger definitions */
170#define WINDOW_MIN_US 500000 /* Min window size is 500ms */
171#define WINDOW_MAX_US 10000000 /* Max window size is 10s */
172#define UPDATES_PER_WINDOW 10 /* 10 updates per window */
173
Johannes Weinereb414682018-10-26 15:06:27 -0700174/* Sampling frequency in nanoseconds */
175static u64 psi_period __read_mostly;
176
177/* System-level pressure and stall tracking */
178static DEFINE_PER_CPU(struct psi_group_cpu, system_group_pcpu);
Dan Schatzbergdf5ba5b2019-05-14 15:41:18 -0700179struct psi_group psi_system = {
Johannes Weinereb414682018-10-26 15:06:27 -0700180 .pcpu = &system_group_pcpu,
181};
182
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700183static void psi_avgs_work(struct work_struct *work);
Johannes Weinereb414682018-10-26 15:06:27 -0700184
185static void group_init(struct psi_group *group)
186{
187 int cpu;
188
189 for_each_possible_cpu(cpu)
190 seqcount_init(&per_cpu_ptr(group->pcpu, cpu)->seq);
Johannes Weiner3dfbe252019-12-03 13:35:23 -0500191 group->avg_last_update = sched_clock();
192 group->avg_next_update = group->avg_last_update + psi_period;
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700193 INIT_DELAYED_WORK(&group->avgs_work, psi_avgs_work);
194 mutex_init(&group->avgs_lock);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700195 /* Init trigger-related members */
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700196 mutex_init(&group->trigger_lock);
197 INIT_LIST_HEAD(&group->triggers);
198 memset(group->nr_triggers, 0, sizeof(group->nr_triggers));
199 group->poll_states = 0;
200 group->poll_min_period = U32_MAX;
201 memset(group->polling_total, 0, sizeof(group->polling_total));
202 group->polling_next_update = ULLONG_MAX;
203 group->polling_until = 0;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700204 rcu_assign_pointer(group->poll_task, NULL);
Johannes Weinereb414682018-10-26 15:06:27 -0700205}
206
207void __init psi_init(void)
208{
Johannes Weinere0c27442018-11-30 14:09:58 -0800209 if (!psi_enable) {
210 static_branch_enable(&psi_disabled);
Johannes Weinereb414682018-10-26 15:06:27 -0700211 return;
Johannes Weinere0c27442018-11-30 14:09:58 -0800212 }
Johannes Weinereb414682018-10-26 15:06:27 -0700213
214 psi_period = jiffies_to_nsecs(PSI_FREQ);
215 group_init(&psi_system);
216}
217
218static bool test_state(unsigned int *tasks, enum psi_states state)
219{
220 switch (state) {
221 case PSI_IO_SOME:
Johannes Weinerfddc8ba2021-03-03 11:46:58 +0800222 return unlikely(tasks[NR_IOWAIT]);
Johannes Weinereb414682018-10-26 15:06:27 -0700223 case PSI_IO_FULL:
Johannes Weinerfddc8ba2021-03-03 11:46:58 +0800224 return unlikely(tasks[NR_IOWAIT] && !tasks[NR_RUNNING]);
Johannes Weinereb414682018-10-26 15:06:27 -0700225 case PSI_MEM_SOME:
Johannes Weinerfddc8ba2021-03-03 11:46:58 +0800226 return unlikely(tasks[NR_MEMSTALL]);
Johannes Weinereb414682018-10-26 15:06:27 -0700227 case PSI_MEM_FULL:
Johannes Weinerfddc8ba2021-03-03 11:46:58 +0800228 return unlikely(tasks[NR_MEMSTALL] && !tasks[NR_RUNNING]);
Johannes Weinereb414682018-10-26 15:06:27 -0700229 case PSI_CPU_SOME:
Johannes Weinerfddc8ba2021-03-03 11:46:58 +0800230 return unlikely(tasks[NR_RUNNING] > tasks[NR_ONCPU]);
Chengming Zhoue7fcd762021-03-03 11:46:56 +0800231 case PSI_CPU_FULL:
Johannes Weinerfddc8ba2021-03-03 11:46:58 +0800232 return unlikely(tasks[NR_RUNNING] && !tasks[NR_ONCPU]);
Johannes Weinereb414682018-10-26 15:06:27 -0700233 case PSI_NONIDLE:
234 return tasks[NR_IOWAIT] || tasks[NR_MEMSTALL] ||
235 tasks[NR_RUNNING];
236 default:
237 return false;
238 }
239}
240
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700241static void get_recent_times(struct psi_group *group, int cpu,
242 enum psi_aggregators aggregator, u32 *times,
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700243 u32 *pchanged_states)
Johannes Weinereb414682018-10-26 15:06:27 -0700244{
245 struct psi_group_cpu *groupc = per_cpu_ptr(group->pcpu, cpu);
Johannes Weinereb414682018-10-26 15:06:27 -0700246 u64 now, state_start;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700247 enum psi_states s;
Johannes Weinereb414682018-10-26 15:06:27 -0700248 unsigned int seq;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700249 u32 state_mask;
Johannes Weinereb414682018-10-26 15:06:27 -0700250
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700251 *pchanged_states = 0;
252
Johannes Weinereb414682018-10-26 15:06:27 -0700253 /* Snapshot a coherent view of the CPU state */
254 do {
255 seq = read_seqcount_begin(&groupc->seq);
256 now = cpu_clock(cpu);
257 memcpy(times, groupc->times, sizeof(groupc->times));
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700258 state_mask = groupc->state_mask;
Johannes Weinereb414682018-10-26 15:06:27 -0700259 state_start = groupc->state_start;
260 } while (read_seqcount_retry(&groupc->seq, seq));
261
262 /* Calculate state time deltas against the previous snapshot */
263 for (s = 0; s < NR_PSI_STATES; s++) {
264 u32 delta;
265 /*
266 * In addition to already concluded states, we also
267 * incorporate currently active states on the CPU,
268 * since states may last for many sampling periods.
269 *
270 * This way we keep our delta sampling buckets small
271 * (u32) and our reported pressure close to what's
272 * actually happening.
273 */
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700274 if (state_mask & (1 << s))
Johannes Weinereb414682018-10-26 15:06:27 -0700275 times[s] += now - state_start;
276
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700277 delta = times[s] - groupc->times_prev[aggregator][s];
278 groupc->times_prev[aggregator][s] = times[s];
Johannes Weinereb414682018-10-26 15:06:27 -0700279
280 times[s] = delta;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700281 if (delta)
282 *pchanged_states |= (1 << s);
Johannes Weinereb414682018-10-26 15:06:27 -0700283 }
284}
285
286static void calc_avgs(unsigned long avg[3], int missed_periods,
287 u64 time, u64 period)
288{
289 unsigned long pct;
290
291 /* Fill in zeroes for periods of no activity */
292 if (missed_periods) {
293 avg[0] = calc_load_n(avg[0], EXP_10s, 0, missed_periods);
294 avg[1] = calc_load_n(avg[1], EXP_60s, 0, missed_periods);
295 avg[2] = calc_load_n(avg[2], EXP_300s, 0, missed_periods);
296 }
297
298 /* Sample the most recent active period */
299 pct = div_u64(time * 100, period);
300 pct *= FIXED_1;
301 avg[0] = calc_load(avg[0], EXP_10s, pct);
302 avg[1] = calc_load(avg[1], EXP_60s, pct);
303 avg[2] = calc_load(avg[2], EXP_300s, pct);
304}
305
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700306static void collect_percpu_times(struct psi_group *group,
307 enum psi_aggregators aggregator,
308 u32 *pchanged_states)
Johannes Weinereb414682018-10-26 15:06:27 -0700309{
310 u64 deltas[NR_PSI_STATES - 1] = { 0, };
Johannes Weinereb414682018-10-26 15:06:27 -0700311 unsigned long nonidle_total = 0;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700312 u32 changed_states = 0;
Johannes Weinereb414682018-10-26 15:06:27 -0700313 int cpu;
314 int s;
315
Johannes Weinereb414682018-10-26 15:06:27 -0700316 /*
317 * Collect the per-cpu time buckets and average them into a
318 * single time sample that is normalized to wallclock time.
319 *
320 * For averaging, each CPU is weighted by its non-idle time in
321 * the sampling period. This eliminates artifacts from uneven
322 * loading, or even entirely idle CPUs.
323 */
324 for_each_possible_cpu(cpu) {
325 u32 times[NR_PSI_STATES];
326 u32 nonidle;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700327 u32 cpu_changed_states;
Johannes Weinereb414682018-10-26 15:06:27 -0700328
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700329 get_recent_times(group, cpu, aggregator, times,
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700330 &cpu_changed_states);
331 changed_states |= cpu_changed_states;
Johannes Weinereb414682018-10-26 15:06:27 -0700332
333 nonidle = nsecs_to_jiffies(times[PSI_NONIDLE]);
334 nonidle_total += nonidle;
335
336 for (s = 0; s < PSI_NONIDLE; s++)
337 deltas[s] += (u64)times[s] * nonidle;
338 }
339
340 /*
341 * Integrate the sample into the running statistics that are
342 * reported to userspace: the cumulative stall times and the
343 * decaying averages.
344 *
345 * Pressure percentages are sampled at PSI_FREQ. We might be
346 * called more often when the user polls more frequently than
347 * that; we might be called less often when there is no task
348 * activity, thus no data, and clock ticks are sporadic. The
349 * below handles both.
350 */
351
352 /* total= */
353 for (s = 0; s < NR_PSI_STATES - 1; s++)
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700354 group->total[aggregator][s] +=
355 div_u64(deltas[s], max(nonidle_total, 1UL));
Johannes Weinereb414682018-10-26 15:06:27 -0700356
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700357 if (pchanged_states)
358 *pchanged_states = changed_states;
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700359}
360
361static u64 update_averages(struct psi_group *group, u64 now)
362{
363 unsigned long missed_periods = 0;
364 u64 expires, period;
365 u64 avg_next_update;
366 int s;
367
Johannes Weinereb414682018-10-26 15:06:27 -0700368 /* avgX= */
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700369 expires = group->avg_next_update;
Johannes Weiner4e375042019-02-20 22:19:59 -0800370 if (now - expires >= psi_period)
Johannes Weinereb414682018-10-26 15:06:27 -0700371 missed_periods = div_u64(now - expires, psi_period);
372
373 /*
374 * The periodic clock tick can get delayed for various
375 * reasons, especially on loaded systems. To avoid clock
376 * drift, we schedule the clock in fixed psi_period intervals.
377 * But the deltas we sample out of the per-cpu buckets above
378 * are based on the actual time elapsing between clock ticks.
379 */
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700380 avg_next_update = expires + ((1 + missed_periods) * psi_period);
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700381 period = now - (group->avg_last_update + (missed_periods * psi_period));
382 group->avg_last_update = now;
Johannes Weinereb414682018-10-26 15:06:27 -0700383
384 for (s = 0; s < NR_PSI_STATES - 1; s++) {
385 u32 sample;
386
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700387 sample = group->total[PSI_AVGS][s] - group->avg_total[s];
Johannes Weinereb414682018-10-26 15:06:27 -0700388 /*
389 * Due to the lockless sampling of the time buckets,
390 * recorded time deltas can slip into the next period,
391 * which under full pressure can result in samples in
392 * excess of the period length.
393 *
394 * We don't want to report non-sensical pressures in
395 * excess of 100%, nor do we want to drop such events
396 * on the floor. Instead we punt any overage into the
397 * future until pressure subsides. By doing this we
398 * don't underreport the occurring pressure curve, we
399 * just report it delayed by one period length.
400 *
401 * The error isn't cumulative. As soon as another
402 * delta slips from a period P to P+1, by definition
403 * it frees up its time T in P.
404 */
405 if (sample > period)
406 sample = period;
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700407 group->avg_total[s] += sample;
Johannes Weinereb414682018-10-26 15:06:27 -0700408 calc_avgs(group->avg[s], missed_periods, sample, period);
409 }
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700410
411 return avg_next_update;
Johannes Weinereb414682018-10-26 15:06:27 -0700412}
413
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700414static void psi_avgs_work(struct work_struct *work)
Johannes Weinereb414682018-10-26 15:06:27 -0700415{
416 struct delayed_work *dwork;
417 struct psi_group *group;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700418 u32 changed_states;
Johannes Weinereb414682018-10-26 15:06:27 -0700419 bool nonidle;
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700420 u64 now;
Johannes Weinereb414682018-10-26 15:06:27 -0700421
422 dwork = to_delayed_work(work);
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700423 group = container_of(dwork, struct psi_group, avgs_work);
Johannes Weinereb414682018-10-26 15:06:27 -0700424
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700425 mutex_lock(&group->avgs_lock);
426
427 now = sched_clock();
428
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700429 collect_percpu_times(group, PSI_AVGS, &changed_states);
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700430 nonidle = changed_states & (1 << PSI_NONIDLE);
Johannes Weinereb414682018-10-26 15:06:27 -0700431 /*
432 * If there is task activity, periodically fold the per-cpu
433 * times and feed samples into the running averages. If things
434 * are idle and there is no data to process, stop the clock.
435 * Once restarted, we'll catch up the running averages in one
436 * go - see calc_avgs() and missed_periods.
437 */
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700438 if (now >= group->avg_next_update)
439 group->avg_next_update = update_averages(group, now);
Johannes Weinereb414682018-10-26 15:06:27 -0700440
441 if (nonidle) {
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700442 schedule_delayed_work(dwork, nsecs_to_jiffies(
443 group->avg_next_update - now) + 1);
Johannes Weinereb414682018-10-26 15:06:27 -0700444 }
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700445
446 mutex_unlock(&group->avgs_lock);
Johannes Weinereb414682018-10-26 15:06:27 -0700447}
448
Ingo Molnar3b037062021-03-18 13:38:50 +0100449/* Trigger tracking window manipulations */
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700450static void window_reset(struct psi_window *win, u64 now, u64 value,
451 u64 prev_growth)
452{
453 win->start_time = now;
454 win->start_value = value;
455 win->prev_growth = prev_growth;
456}
457
458/*
459 * PSI growth tracking window update and growth calculation routine.
460 *
461 * This approximates a sliding tracking window by interpolating
462 * partially elapsed windows using historical growth data from the
463 * previous intervals. This minimizes memory requirements (by not storing
464 * all the intermediate values in the previous window) and simplifies
465 * the calculations. It works well because PSI signal changes only in
466 * positive direction and over relatively small window sizes the growth
467 * is close to linear.
468 */
469static u64 window_update(struct psi_window *win, u64 now, u64 value)
470{
471 u64 elapsed;
472 u64 growth;
473
474 elapsed = now - win->start_time;
475 growth = value - win->start_value;
476 /*
477 * After each tracking window passes win->start_value and
478 * win->start_time get reset and win->prev_growth stores
479 * the average per-window growth of the previous window.
480 * win->prev_growth is then used to interpolate additional
481 * growth from the previous window assuming it was linear.
482 */
483 if (elapsed > win->size)
484 window_reset(win, now, value, growth);
485 else {
486 u32 remaining;
487
488 remaining = win->size - elapsed;
Johannes Weinerc3466952019-12-03 13:35:24 -0500489 growth += div64_u64(win->prev_growth * remaining, win->size);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700490 }
491
492 return growth;
493}
494
495static void init_triggers(struct psi_group *group, u64 now)
496{
497 struct psi_trigger *t;
498
499 list_for_each_entry(t, &group->triggers, node)
500 window_reset(&t->win, now,
501 group->total[PSI_POLL][t->state], 0);
502 memcpy(group->polling_total, group->total[PSI_POLL],
503 sizeof(group->polling_total));
504 group->polling_next_update = now + group->poll_min_period;
505}
506
507static u64 update_triggers(struct psi_group *group, u64 now)
508{
509 struct psi_trigger *t;
510 bool new_stall = false;
511 u64 *total = group->total[PSI_POLL];
512
513 /*
514 * On subsequent updates, calculate growth deltas and let
515 * watchers know when their specified thresholds are exceeded.
516 */
517 list_for_each_entry(t, &group->triggers, node) {
518 u64 growth;
519
520 /* Check for stall activity */
521 if (group->polling_total[t->state] == total[t->state])
522 continue;
523
524 /*
525 * Multiple triggers might be looking at the same state,
526 * remember to update group->polling_total[] once we've
527 * been through all of them. Also remember to extend the
528 * polling time if we see new stall activity.
529 */
530 new_stall = true;
531
532 /* Calculate growth since last update */
533 growth = window_update(&t->win, now, total[t->state]);
534 if (growth < t->threshold)
535 continue;
536
537 /* Limit event signaling to once per window */
538 if (now < t->last_event_time + t->win.size)
539 continue;
540
541 /* Generate an event */
542 if (cmpxchg(&t->event, 0, 1) == 0)
543 wake_up_interruptible(&t->event_wait);
544 t->last_event_time = now;
545 }
546
547 if (new_stall)
548 memcpy(group->polling_total, total,
549 sizeof(group->polling_total));
550
551 return now + group->poll_min_period;
552}
553
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700554/* Schedule polling if it's not already scheduled. */
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700555static void psi_schedule_poll_work(struct psi_group *group, unsigned long delay)
556{
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700557 struct task_struct *task;
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700558
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700559 /*
560 * Do not reschedule if already scheduled.
561 * Possible race with a timer scheduled after this check but before
562 * mod_timer below can be tolerated because group->polling_next_update
563 * will keep updates on schedule.
564 */
565 if (timer_pending(&group->poll_timer))
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700566 return;
567
568 rcu_read_lock();
569
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700570 task = rcu_dereference(group->poll_task);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700571 /*
572 * kworker might be NULL in case psi_trigger_destroy races with
573 * psi_task_change (hotpath) which can't use locks
574 */
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700575 if (likely(task))
576 mod_timer(&group->poll_timer, jiffies + delay);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700577
578 rcu_read_unlock();
579}
580
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700581static void psi_poll_work(struct psi_group *group)
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700582{
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700583 u32 changed_states;
584 u64 now;
585
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700586 mutex_lock(&group->trigger_lock);
587
588 now = sched_clock();
589
590 collect_percpu_times(group, PSI_POLL, &changed_states);
591
592 if (changed_states & group->poll_states) {
593 /* Initialize trigger windows when entering polling mode */
594 if (now > group->polling_until)
595 init_triggers(group, now);
596
597 /*
598 * Keep the monitor active for at least the duration of the
599 * minimum tracking window as long as monitor states are
600 * changing.
601 */
602 group->polling_until = now +
603 group->poll_min_period * UPDATES_PER_WINDOW;
604 }
605
606 if (now > group->polling_until) {
607 group->polling_next_update = ULLONG_MAX;
608 goto out;
609 }
610
611 if (now >= group->polling_next_update)
612 group->polling_next_update = update_triggers(group, now);
613
614 psi_schedule_poll_work(group,
615 nsecs_to_jiffies(group->polling_next_update - now) + 1);
616
617out:
618 mutex_unlock(&group->trigger_lock);
619}
620
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700621static int psi_poll_worker(void *data)
622{
623 struct psi_group *group = (struct psi_group *)data;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700624
Peter Zijlstra2cca5422020-04-21 12:09:13 +0200625 sched_set_fifo_low(current);
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700626
627 while (true) {
628 wait_event_interruptible(group->poll_wait,
629 atomic_cmpxchg(&group->poll_wakeup, 1, 0) ||
630 kthread_should_stop());
631 if (kthread_should_stop())
632 break;
633
634 psi_poll_work(group);
635 }
636 return 0;
637}
638
639static void poll_timer_fn(struct timer_list *t)
640{
641 struct psi_group *group = from_timer(group, t, poll_timer);
642
643 atomic_set(&group->poll_wakeup, 1);
644 wake_up_interruptible(&group->poll_wait);
645}
646
Shakeel Buttdf774302021-03-21 13:51:56 -0700647static void record_times(struct psi_group_cpu *groupc, u64 now)
Johannes Weinereb414682018-10-26 15:06:27 -0700648{
649 u32 delta;
Johannes Weinereb414682018-10-26 15:06:27 -0700650
Johannes Weinereb414682018-10-26 15:06:27 -0700651 delta = now - groupc->state_start;
652 groupc->state_start = now;
653
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700654 if (groupc->state_mask & (1 << PSI_IO_SOME)) {
Johannes Weinereb414682018-10-26 15:06:27 -0700655 groupc->times[PSI_IO_SOME] += delta;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700656 if (groupc->state_mask & (1 << PSI_IO_FULL))
Johannes Weinereb414682018-10-26 15:06:27 -0700657 groupc->times[PSI_IO_FULL] += delta;
658 }
659
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700660 if (groupc->state_mask & (1 << PSI_MEM_SOME)) {
Johannes Weinereb414682018-10-26 15:06:27 -0700661 groupc->times[PSI_MEM_SOME] += delta;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700662 if (groupc->state_mask & (1 << PSI_MEM_FULL))
Johannes Weinereb414682018-10-26 15:06:27 -0700663 groupc->times[PSI_MEM_FULL] += delta;
Johannes Weinereb414682018-10-26 15:06:27 -0700664 }
665
Chengming Zhoue7fcd762021-03-03 11:46:56 +0800666 if (groupc->state_mask & (1 << PSI_CPU_SOME)) {
Johannes Weinereb414682018-10-26 15:06:27 -0700667 groupc->times[PSI_CPU_SOME] += delta;
Chengming Zhoue7fcd762021-03-03 11:46:56 +0800668 if (groupc->state_mask & (1 << PSI_CPU_FULL))
669 groupc->times[PSI_CPU_FULL] += delta;
670 }
Johannes Weinereb414682018-10-26 15:06:27 -0700671
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700672 if (groupc->state_mask & (1 << PSI_NONIDLE))
Johannes Weinereb414682018-10-26 15:06:27 -0700673 groupc->times[PSI_NONIDLE] += delta;
674}
675
Johannes Weiner36b238d2020-03-16 15:13:32 -0400676static void psi_group_change(struct psi_group *group, int cpu,
Shakeel Buttdf774302021-03-21 13:51:56 -0700677 unsigned int clear, unsigned int set, u64 now,
Johannes Weiner36b238d2020-03-16 15:13:32 -0400678 bool wake_clock)
Johannes Weinereb414682018-10-26 15:06:27 -0700679{
680 struct psi_group_cpu *groupc;
Johannes Weiner36b238d2020-03-16 15:13:32 -0400681 u32 state_mask = 0;
Johannes Weinereb414682018-10-26 15:06:27 -0700682 unsigned int t, m;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700683 enum psi_states s;
Johannes Weinereb414682018-10-26 15:06:27 -0700684
685 groupc = per_cpu_ptr(group->pcpu, cpu);
686
687 /*
688 * First we assess the aggregate resource states this CPU's
689 * tasks have been in since the last change, and account any
690 * SOME and FULL time these may have resulted in.
691 *
692 * Then we update the task counts according to the state
693 * change requested through the @clear and @set bits.
694 */
695 write_seqcount_begin(&groupc->seq);
696
Shakeel Buttdf774302021-03-21 13:51:56 -0700697 record_times(groupc, now);
Johannes Weinereb414682018-10-26 15:06:27 -0700698
699 for (t = 0, m = clear; m; m &= ~(1 << t), t++) {
700 if (!(m & (1 << t)))
701 continue;
Charan Teja Reddy9d10a132021-04-16 20:32:16 +0530702 if (groupc->tasks[t]) {
703 groupc->tasks[t]--;
704 } else if (!psi_bug) {
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400705 printk_deferred(KERN_ERR "psi: task underflow! cpu=%d t=%d tasks=[%u %u %u %u] clear=%x set=%x\n",
Johannes Weinereb414682018-10-26 15:06:27 -0700706 cpu, t, groupc->tasks[0],
707 groupc->tasks[1], groupc->tasks[2],
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400708 groupc->tasks[3], clear, set);
Johannes Weinereb414682018-10-26 15:06:27 -0700709 psi_bug = 1;
710 }
Johannes Weinereb414682018-10-26 15:06:27 -0700711 }
712
713 for (t = 0; set; set &= ~(1 << t), t++)
714 if (set & (1 << t))
715 groupc->tasks[t]++;
716
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700717 /* Calculate state mask representing active states */
718 for (s = 0; s < NR_PSI_STATES; s++) {
719 if (test_state(groupc->tasks, s))
720 state_mask |= (1 << s);
721 }
Chengming Zhou7fae6c82021-03-03 11:46:57 +0800722
723 /*
724 * Since we care about lost potential, a memstall is FULL
725 * when there are no other working tasks, but also when
726 * the CPU is actively reclaiming and nothing productive
727 * could run even if it were runnable. So when the current
728 * task in a cgroup is in_memstall, the corresponding groupc
729 * on that cpu is in PSI_MEM_FULL state.
730 */
Johannes Weinerfddc8ba2021-03-03 11:46:58 +0800731 if (unlikely(groupc->tasks[NR_ONCPU] && cpu_curr(cpu)->in_memstall))
Chengming Zhou7fae6c82021-03-03 11:46:57 +0800732 state_mask |= (1 << PSI_MEM_FULL);
733
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700734 groupc->state_mask = state_mask;
735
Johannes Weinereb414682018-10-26 15:06:27 -0700736 write_seqcount_end(&groupc->seq);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700737
Johannes Weiner36b238d2020-03-16 15:13:32 -0400738 if (state_mask & group->poll_states)
739 psi_schedule_poll_work(group, 1);
740
741 if (wake_clock && !delayed_work_pending(&group->avgs_work))
742 schedule_delayed_work(&group->avgs_work, PSI_FREQ);
Johannes Weinereb414682018-10-26 15:06:27 -0700743}
744
Johannes Weiner2ce71352018-10-26 15:06:31 -0700745static struct psi_group *iterate_groups(struct task_struct *task, void **iter)
746{
747#ifdef CONFIG_CGROUPS
748 struct cgroup *cgroup = NULL;
749
750 if (!*iter)
751 cgroup = task->cgroups->dfl_cgrp;
752 else if (*iter == &psi_system)
753 return NULL;
754 else
755 cgroup = cgroup_parent(*iter);
756
757 if (cgroup && cgroup_parent(cgroup)) {
758 *iter = cgroup;
759 return cgroup_psi(cgroup);
760 }
761#else
762 if (*iter)
763 return NULL;
764#endif
765 *iter = &psi_system;
766 return &psi_system;
767}
768
Johannes Weiner36b238d2020-03-16 15:13:32 -0400769static void psi_flags_change(struct task_struct *task, int clear, int set)
770{
771 if (((task->psi_flags & set) ||
772 (task->psi_flags & clear) != clear) &&
773 !psi_bug) {
774 printk_deferred(KERN_ERR "psi: inconsistent task state! task=%d:%s cpu=%d psi_flags=%x clear=%x set=%x\n",
775 task->pid, task->comm, task_cpu(task),
776 task->psi_flags, clear, set);
777 psi_bug = 1;
778 }
779
780 task->psi_flags &= ~clear;
781 task->psi_flags |= set;
782}
783
Johannes Weinereb414682018-10-26 15:06:27 -0700784void psi_task_change(struct task_struct *task, int clear, int set)
785{
786 int cpu = task_cpu(task);
Johannes Weiner2ce71352018-10-26 15:06:31 -0700787 struct psi_group *group;
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800788 bool wake_clock = true;
Johannes Weiner2ce71352018-10-26 15:06:31 -0700789 void *iter = NULL;
Shakeel Buttdf774302021-03-21 13:51:56 -0700790 u64 now;
Johannes Weinereb414682018-10-26 15:06:27 -0700791
792 if (!task->pid)
793 return;
794
Johannes Weiner36b238d2020-03-16 15:13:32 -0400795 psi_flags_change(task, clear, set);
Johannes Weinereb414682018-10-26 15:06:27 -0700796
Shakeel Buttdf774302021-03-21 13:51:56 -0700797 now = cpu_clock(cpu);
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800798 /*
799 * Periodic aggregation shuts off if there is a period of no
800 * task changes, so we wake it back up if necessary. However,
801 * don't do this if the task change is the aggregation worker
802 * itself going to sleep, or we'll ping-pong forever.
803 */
804 if (unlikely((clear & TSK_RUNNING) &&
805 (task->flags & PF_WQ_WORKER) &&
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700806 wq_worker_last_func(task) == psi_avgs_work))
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800807 wake_clock = false;
808
Johannes Weiner36b238d2020-03-16 15:13:32 -0400809 while ((group = iterate_groups(task, &iter)))
Shakeel Buttdf774302021-03-21 13:51:56 -0700810 psi_group_change(group, cpu, clear, set, now, wake_clock);
Johannes Weiner36b238d2020-03-16 15:13:32 -0400811}
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700812
Johannes Weiner36b238d2020-03-16 15:13:32 -0400813void psi_task_switch(struct task_struct *prev, struct task_struct *next,
814 bool sleep)
815{
816 struct psi_group *group, *common = NULL;
817 int cpu = task_cpu(prev);
818 void *iter;
Shakeel Buttdf774302021-03-21 13:51:56 -0700819 u64 now = cpu_clock(cpu);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700820
Johannes Weiner36b238d2020-03-16 15:13:32 -0400821 if (next->pid) {
Chengming Zhou7fae6c82021-03-03 11:46:57 +0800822 bool identical_state;
823
Johannes Weiner36b238d2020-03-16 15:13:32 -0400824 psi_flags_change(next, 0, TSK_ONCPU);
825 /*
Chengming Zhou7fae6c82021-03-03 11:46:57 +0800826 * When switching between tasks that have an identical
827 * runtime state, the cgroup that contains both tasks
828 * runtime state, the cgroup that contains both tasks
829 * we reach the first common ancestor. Iterate @next's
830 * ancestors only until we encounter @prev's ONCPU.
Johannes Weiner36b238d2020-03-16 15:13:32 -0400831 */
Chengming Zhou7fae6c82021-03-03 11:46:57 +0800832 identical_state = prev->psi_flags == next->psi_flags;
Johannes Weiner36b238d2020-03-16 15:13:32 -0400833 iter = NULL;
834 while ((group = iterate_groups(next, &iter))) {
Chengming Zhou7fae6c82021-03-03 11:46:57 +0800835 if (identical_state &&
836 per_cpu_ptr(group->pcpu, cpu)->tasks[NR_ONCPU]) {
Johannes Weiner36b238d2020-03-16 15:13:32 -0400837 common = group;
838 break;
839 }
840
Shakeel Buttdf774302021-03-21 13:51:56 -0700841 psi_group_change(group, cpu, 0, TSK_ONCPU, now, true);
Johannes Weiner36b238d2020-03-16 15:13:32 -0400842 }
843 }
844
Johannes Weiner36b238d2020-03-16 15:13:32 -0400845 if (prev->pid) {
Chengming Zhou4117ceb2021-03-03 11:46:59 +0800846 int clear = TSK_ONCPU, set = 0;
847
848 /*
849 * When we're going to sleep, psi_dequeue() lets us handle
850 * TSK_RUNNING and TSK_IOWAIT here, where we can combine it
851 * with TSK_ONCPU and save walking common ancestors twice.
852 */
853 if (sleep) {
854 clear |= TSK_RUNNING;
855 if (prev->in_iowait)
856 set |= TSK_IOWAIT;
857 }
858
859 psi_flags_change(prev, clear, set);
Johannes Weiner36b238d2020-03-16 15:13:32 -0400860
861 iter = NULL;
862 while ((group = iterate_groups(prev, &iter)) && group != common)
Shakeel Buttdf774302021-03-21 13:51:56 -0700863 psi_group_change(group, cpu, clear, set, now, true);
Chengming Zhou4117ceb2021-03-03 11:46:59 +0800864
865 /*
866 * TSK_ONCPU is handled up to the common ancestor. If we're tasked
867 * with dequeuing too, finish that for the rest of the hierarchy.
868 */
869 if (sleep) {
870 clear &= ~TSK_ONCPU;
871 for (; group; group = iterate_groups(prev, &iter))
Shakeel Buttdf774302021-03-21 13:51:56 -0700872 psi_group_change(group, cpu, clear, set, now, true);
Chengming Zhou4117ceb2021-03-03 11:46:59 +0800873 }
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800874 }
Johannes Weinereb414682018-10-26 15:06:27 -0700875}
876
Johannes Weinereb414682018-10-26 15:06:27 -0700877/**
878 * psi_memstall_enter - mark the beginning of a memory stall section
879 * @flags: flags to handle nested sections
880 *
881 * Marks the calling task as being stalled due to a lack of memory,
882 * such as waiting for a refault or performing reclaim.
883 */
884void psi_memstall_enter(unsigned long *flags)
885{
886 struct rq_flags rf;
887 struct rq *rq;
888
Johannes Weinere0c27442018-11-30 14:09:58 -0800889 if (static_branch_likely(&psi_disabled))
Johannes Weinereb414682018-10-26 15:06:27 -0700890 return;
891
Yafang Shao1066d1b2020-03-16 21:28:05 -0400892 *flags = current->in_memstall;
Johannes Weinereb414682018-10-26 15:06:27 -0700893 if (*flags)
894 return;
895 /*
Yafang Shao1066d1b2020-03-16 21:28:05 -0400896 * in_memstall setting & accounting needs to be atomic wrt
Johannes Weinereb414682018-10-26 15:06:27 -0700897 * changes to the task's scheduling state, otherwise we can
898 * race with CPU migration.
899 */
900 rq = this_rq_lock_irq(&rf);
901
Yafang Shao1066d1b2020-03-16 21:28:05 -0400902 current->in_memstall = 1;
Johannes Weinereb414682018-10-26 15:06:27 -0700903 psi_task_change(current, 0, TSK_MEMSTALL);
904
905 rq_unlock_irq(rq, &rf);
906}
907
908/**
909 * psi_memstall_leave - mark the end of an memory stall section
910 * @flags: flags to handle nested memdelay sections
911 *
912 * Marks the calling task as no longer stalled due to lack of memory.
913 */
914void psi_memstall_leave(unsigned long *flags)
915{
916 struct rq_flags rf;
917 struct rq *rq;
918
Johannes Weinere0c27442018-11-30 14:09:58 -0800919 if (static_branch_likely(&psi_disabled))
Johannes Weinereb414682018-10-26 15:06:27 -0700920 return;
921
922 if (*flags)
923 return;
924 /*
Yafang Shao1066d1b2020-03-16 21:28:05 -0400925 * in_memstall clearing & accounting needs to be atomic wrt
Johannes Weinereb414682018-10-26 15:06:27 -0700926 * changes to the task's scheduling state, otherwise we could
927 * race with CPU migration.
928 */
929 rq = this_rq_lock_irq(&rf);
930
Yafang Shao1066d1b2020-03-16 21:28:05 -0400931 current->in_memstall = 0;
Johannes Weinereb414682018-10-26 15:06:27 -0700932 psi_task_change(current, TSK_MEMSTALL, 0);
933
934 rq_unlock_irq(rq, &rf);
935}
936
Johannes Weiner2ce71352018-10-26 15:06:31 -0700937#ifdef CONFIG_CGROUPS
938int psi_cgroup_alloc(struct cgroup *cgroup)
939{
Johannes Weinere0c27442018-11-30 14:09:58 -0800940 if (static_branch_likely(&psi_disabled))
Johannes Weiner2ce71352018-10-26 15:06:31 -0700941 return 0;
942
943 cgroup->psi.pcpu = alloc_percpu(struct psi_group_cpu);
944 if (!cgroup->psi.pcpu)
945 return -ENOMEM;
946 group_init(&cgroup->psi);
947 return 0;
948}
949
950void psi_cgroup_free(struct cgroup *cgroup)
951{
Johannes Weinere0c27442018-11-30 14:09:58 -0800952 if (static_branch_likely(&psi_disabled))
Johannes Weiner2ce71352018-10-26 15:06:31 -0700953 return;
954
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700955 cancel_delayed_work_sync(&cgroup->psi.avgs_work);
Johannes Weiner2ce71352018-10-26 15:06:31 -0700956 free_percpu(cgroup->psi.pcpu);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700957 /* All triggers must be removed by now */
958 WARN_ONCE(cgroup->psi.poll_states, "psi: trigger leak\n");
Johannes Weiner2ce71352018-10-26 15:06:31 -0700959}
960
961/**
962 * cgroup_move_task - move task to a different cgroup
963 * @task: the task
964 * @to: the target css_set
965 *
966 * Move task to a new cgroup and safely migrate its associated stall
967 * state between the different groups.
968 *
969 * This function acquires the task's rq lock to lock out concurrent
970 * changes to the task's scheduling state and - in case the task is
971 * running - concurrent changes to its stall state.
972 */
973void cgroup_move_task(struct task_struct *task, struct css_set *to)
974{
Johannes Weiner2ce71352018-10-26 15:06:31 -0700975 unsigned int task_flags = 0;
976 struct rq_flags rf;
977 struct rq *rq;
978
Johannes Weinere0c27442018-11-30 14:09:58 -0800979 if (static_branch_likely(&psi_disabled)) {
Olof Johansson8fcb2312018-11-16 15:08:00 -0800980 /*
981 * Lame to do this here, but the scheduler cannot be locked
982 * from the outside, so we move cgroups from inside sched/.
983 */
984 rcu_assign_pointer(task->cgroups, to);
985 return;
Johannes Weiner2ce71352018-10-26 15:06:31 -0700986 }
987
Olof Johansson8fcb2312018-11-16 15:08:00 -0800988 rq = task_rq_lock(task, &rf);
989
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400990 if (task_on_rq_queued(task)) {
Olof Johansson8fcb2312018-11-16 15:08:00 -0800991 task_flags = TSK_RUNNING;
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400992 if (task_current(rq, task))
993 task_flags |= TSK_ONCPU;
994 } else if (task->in_iowait)
Olof Johansson8fcb2312018-11-16 15:08:00 -0800995 task_flags = TSK_IOWAIT;
996
Yafang Shao1066d1b2020-03-16 21:28:05 -0400997 if (task->in_memstall)
Olof Johansson8fcb2312018-11-16 15:08:00 -0800998 task_flags |= TSK_MEMSTALL;
999
1000 if (task_flags)
1001 psi_task_change(task, task_flags, 0);
1002
1003 /* See comment above */
Johannes Weiner2ce71352018-10-26 15:06:31 -07001004 rcu_assign_pointer(task->cgroups, to);
1005
Olof Johansson8fcb2312018-11-16 15:08:00 -08001006 if (task_flags)
1007 psi_task_change(task, 0, task_flags);
Johannes Weiner2ce71352018-10-26 15:06:31 -07001008
Olof Johansson8fcb2312018-11-16 15:08:00 -08001009 task_rq_unlock(rq, task, &rf);
Johannes Weiner2ce71352018-10-26 15:06:31 -07001010}
1011#endif /* CONFIG_CGROUPS */
1012
1013int psi_show(struct seq_file *m, struct psi_group *group, enum psi_res res)
Johannes Weinereb414682018-10-26 15:06:27 -07001014{
1015 int full;
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -07001016 u64 now;
Johannes Weinereb414682018-10-26 15:06:27 -07001017
Johannes Weinere0c27442018-11-30 14:09:58 -08001018 if (static_branch_likely(&psi_disabled))
Johannes Weinereb414682018-10-26 15:06:27 -07001019 return -EOPNOTSUPP;
1020
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -07001021 /* Update averages before reporting them */
1022 mutex_lock(&group->avgs_lock);
1023 now = sched_clock();
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001024 collect_percpu_times(group, PSI_AVGS, NULL);
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -07001025 if (now >= group->avg_next_update)
1026 group->avg_next_update = update_averages(group, now);
1027 mutex_unlock(&group->avgs_lock);
Johannes Weinereb414682018-10-26 15:06:27 -07001028
Chengming Zhoue7fcd762021-03-03 11:46:56 +08001029 for (full = 0; full < 2; full++) {
Johannes Weinereb414682018-10-26 15:06:27 -07001030 unsigned long avg[3];
1031 u64 total;
1032 int w;
1033
1034 for (w = 0; w < 3; w++)
1035 avg[w] = group->avg[res * 2 + full][w];
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001036 total = div_u64(group->total[PSI_AVGS][res * 2 + full],
1037 NSEC_PER_USEC);
Johannes Weinereb414682018-10-26 15:06:27 -07001038
1039 seq_printf(m, "%s avg10=%lu.%02lu avg60=%lu.%02lu avg300=%lu.%02lu total=%llu\n",
1040 full ? "full" : "some",
1041 LOAD_INT(avg[0]), LOAD_FRAC(avg[0]),
1042 LOAD_INT(avg[1]), LOAD_FRAC(avg[1]),
1043 LOAD_INT(avg[2]), LOAD_FRAC(avg[2]),
1044 total);
1045 }
1046
1047 return 0;
1048}
1049
1050static int psi_io_show(struct seq_file *m, void *v)
1051{
1052 return psi_show(m, &psi_system, PSI_IO);
1053}
1054
1055static int psi_memory_show(struct seq_file *m, void *v)
1056{
1057 return psi_show(m, &psi_system, PSI_MEM);
1058}
1059
1060static int psi_cpu_show(struct seq_file *m, void *v)
1061{
1062 return psi_show(m, &psi_system, PSI_CPU);
1063}
1064
Josh Hunt6db12ee2021-04-01 22:58:33 -04001065static int psi_open(struct file *file, int (*psi_show)(struct seq_file *, void *))
1066{
1067 if (file->f_mode & FMODE_WRITE && !capable(CAP_SYS_RESOURCE))
1068 return -EPERM;
1069
1070 return single_open(file, psi_show, NULL);
1071}
1072
Johannes Weinereb414682018-10-26 15:06:27 -07001073static int psi_io_open(struct inode *inode, struct file *file)
1074{
Josh Hunt6db12ee2021-04-01 22:58:33 -04001075 return psi_open(file, psi_io_show);
Johannes Weinereb414682018-10-26 15:06:27 -07001076}
1077
1078static int psi_memory_open(struct inode *inode, struct file *file)
1079{
Josh Hunt6db12ee2021-04-01 22:58:33 -04001080 return psi_open(file, psi_memory_show);
Johannes Weinereb414682018-10-26 15:06:27 -07001081}
1082
1083static int psi_cpu_open(struct inode *inode, struct file *file)
1084{
Josh Hunt6db12ee2021-04-01 22:58:33 -04001085 return psi_open(file, psi_cpu_show);
Johannes Weinereb414682018-10-26 15:06:27 -07001086}
1087
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001088struct psi_trigger *psi_trigger_create(struct psi_group *group,
1089 char *buf, size_t nbytes, enum psi_res res)
1090{
1091 struct psi_trigger *t;
1092 enum psi_states state;
1093 u32 threshold_us;
1094 u32 window_us;
1095
1096 if (static_branch_likely(&psi_disabled))
1097 return ERR_PTR(-EOPNOTSUPP);
1098
1099 if (sscanf(buf, "some %u %u", &threshold_us, &window_us) == 2)
1100 state = PSI_IO_SOME + res * 2;
1101 else if (sscanf(buf, "full %u %u", &threshold_us, &window_us) == 2)
1102 state = PSI_IO_FULL + res * 2;
1103 else
1104 return ERR_PTR(-EINVAL);
1105
1106 if (state >= PSI_NONIDLE)
1107 return ERR_PTR(-EINVAL);
1108
1109 if (window_us < WINDOW_MIN_US ||
1110 window_us > WINDOW_MAX_US)
1111 return ERR_PTR(-EINVAL);
1112
1113 /* Check threshold */
1114 if (threshold_us == 0 || threshold_us > window_us)
1115 return ERR_PTR(-EINVAL);
1116
1117 t = kmalloc(sizeof(*t), GFP_KERNEL);
1118 if (!t)
1119 return ERR_PTR(-ENOMEM);
1120
1121 t->group = group;
1122 t->state = state;
1123 t->threshold = threshold_us * NSEC_PER_USEC;
1124 t->win.size = window_us * NSEC_PER_USEC;
1125 window_reset(&t->win, 0, 0, 0);
1126
1127 t->event = 0;
1128 t->last_event_time = 0;
1129 init_waitqueue_head(&t->event_wait);
1130 kref_init(&t->refcount);
1131
1132 mutex_lock(&group->trigger_lock);
1133
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001134 if (!rcu_access_pointer(group->poll_task)) {
1135 struct task_struct *task;
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001136
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001137 task = kthread_create(psi_poll_worker, group, "psimon");
1138 if (IS_ERR(task)) {
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001139 kfree(t);
1140 mutex_unlock(&group->trigger_lock);
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001141 return ERR_CAST(task);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001142 }
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001143 atomic_set(&group->poll_wakeup, 0);
1144 init_waitqueue_head(&group->poll_wait);
1145 wake_up_process(task);
1146 timer_setup(&group->poll_timer, poll_timer_fn, 0);
1147 rcu_assign_pointer(group->poll_task, task);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001148 }
1149
1150 list_add(&t->node, &group->triggers);
1151 group->poll_min_period = min(group->poll_min_period,
1152 div_u64(t->win.size, UPDATES_PER_WINDOW));
1153 group->nr_triggers[t->state]++;
1154 group->poll_states |= (1 << t->state);
1155
1156 mutex_unlock(&group->trigger_lock);
1157
1158 return t;
1159}
1160
1161static void psi_trigger_destroy(struct kref *ref)
1162{
1163 struct psi_trigger *t = container_of(ref, struct psi_trigger, refcount);
1164 struct psi_group *group = t->group;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001165 struct task_struct *task_to_destroy = NULL;
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001166
1167 if (static_branch_likely(&psi_disabled))
1168 return;
1169
1170 /*
1171 * Wakeup waiters to stop polling. Can happen if cgroup is deleted
1172 * from under a polling process.
1173 */
1174 wake_up_interruptible(&t->event_wait);
1175
1176 mutex_lock(&group->trigger_lock);
1177
1178 if (!list_empty(&t->node)) {
1179 struct psi_trigger *tmp;
1180 u64 period = ULLONG_MAX;
1181
1182 list_del(&t->node);
1183 group->nr_triggers[t->state]--;
1184 if (!group->nr_triggers[t->state])
1185 group->poll_states &= ~(1 << t->state);
1186 /* reset min update period for the remaining triggers */
1187 list_for_each_entry(tmp, &group->triggers, node)
1188 period = min(period, div_u64(tmp->win.size,
1189 UPDATES_PER_WINDOW));
1190 group->poll_min_period = period;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001191 /* Destroy poll_task when the last trigger is destroyed */
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001192 if (group->poll_states == 0) {
1193 group->polling_until = 0;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001194 task_to_destroy = rcu_dereference_protected(
1195 group->poll_task,
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001196 lockdep_is_held(&group->trigger_lock));
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001197 rcu_assign_pointer(group->poll_task, NULL);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001198 }
1199 }
1200
1201 mutex_unlock(&group->trigger_lock);
1202
1203 /*
1204 * Wait for both *trigger_ptr from psi_trigger_replace and
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001205 * poll_task RCUs to complete their read-side critical sections
1206 * before destroying the trigger and optionally the poll_task
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001207 */
1208 synchronize_rcu();
1209 /*
1210 * Destroy the kworker after releasing trigger_lock to prevent a
1211 * deadlock while waiting for psi_poll_work to acquire trigger_lock
1212 */
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001213 if (task_to_destroy) {
Jason Xing7b2b55d2019-08-24 17:54:53 -07001214 /*
1215 * After the RCU grace period has expired, the worker
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001216 * can no longer be found through group->poll_task.
Jason Xing7b2b55d2019-08-24 17:54:53 -07001217 * But it might have been already scheduled before
1218 * that - deschedule it cleanly before destroying it.
1219 */
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001220 del_timer_sync(&group->poll_timer);
1221 kthread_stop(task_to_destroy);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001222 }
1223 kfree(t);
1224}
1225
1226void psi_trigger_replace(void **trigger_ptr, struct psi_trigger *new)
1227{
1228 struct psi_trigger *old = *trigger_ptr;
1229
1230 if (static_branch_likely(&psi_disabled))
1231 return;
1232
1233 rcu_assign_pointer(*trigger_ptr, new);
1234 if (old)
1235 kref_put(&old->refcount, psi_trigger_destroy);
1236}
1237
1238__poll_t psi_trigger_poll(void **trigger_ptr,
1239 struct file *file, poll_table *wait)
1240{
1241 __poll_t ret = DEFAULT_POLLMASK;
1242 struct psi_trigger *t;
1243
1244 if (static_branch_likely(&psi_disabled))
1245 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1246
1247 rcu_read_lock();
1248
1249 t = rcu_dereference(*(void __rcu __force **)trigger_ptr);
1250 if (!t) {
1251 rcu_read_unlock();
1252 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1253 }
1254 kref_get(&t->refcount);
1255
1256 rcu_read_unlock();
1257
1258 poll_wait(file, &t->event_wait, wait);
1259
1260 if (cmpxchg(&t->event, 1, 0) == 1)
1261 ret |= EPOLLPRI;
1262
1263 kref_put(&t->refcount, psi_trigger_destroy);
1264
1265 return ret;
1266}
1267
1268static ssize_t psi_write(struct file *file, const char __user *user_buf,
1269 size_t nbytes, enum psi_res res)
1270{
1271 char buf[32];
1272 size_t buf_size;
1273 struct seq_file *seq;
1274 struct psi_trigger *new;
1275
1276 if (static_branch_likely(&psi_disabled))
1277 return -EOPNOTSUPP;
1278
Suren Baghdasaryan6fcca0f2020-02-03 13:22:16 -08001279 if (!nbytes)
1280 return -EINVAL;
1281
Miles Chen4adcdce2019-09-12 18:34:52 +08001282 buf_size = min(nbytes, sizeof(buf));
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001283 if (copy_from_user(buf, user_buf, buf_size))
1284 return -EFAULT;
1285
1286 buf[buf_size - 1] = '\0';
1287
1288 new = psi_trigger_create(&psi_system, buf, nbytes, res);
1289 if (IS_ERR(new))
1290 return PTR_ERR(new);
1291
1292 seq = file->private_data;
1293 /* Take seq->lock to protect seq->private from concurrent writes */
1294 mutex_lock(&seq->lock);
1295 psi_trigger_replace(&seq->private, new);
1296 mutex_unlock(&seq->lock);
1297
1298 return nbytes;
1299}
1300
1301static ssize_t psi_io_write(struct file *file, const char __user *user_buf,
1302 size_t nbytes, loff_t *ppos)
1303{
1304 return psi_write(file, user_buf, nbytes, PSI_IO);
1305}
1306
1307static ssize_t psi_memory_write(struct file *file, const char __user *user_buf,
1308 size_t nbytes, loff_t *ppos)
1309{
1310 return psi_write(file, user_buf, nbytes, PSI_MEM);
1311}
1312
1313static ssize_t psi_cpu_write(struct file *file, const char __user *user_buf,
1314 size_t nbytes, loff_t *ppos)
1315{
1316 return psi_write(file, user_buf, nbytes, PSI_CPU);
1317}
1318
1319static __poll_t psi_fop_poll(struct file *file, poll_table *wait)
1320{
1321 struct seq_file *seq = file->private_data;
1322
1323 return psi_trigger_poll(&seq->private, file, wait);
1324}
1325
1326static int psi_fop_release(struct inode *inode, struct file *file)
1327{
1328 struct seq_file *seq = file->private_data;
1329
1330 psi_trigger_replace(&seq->private, NULL);
1331 return single_release(inode, file);
1332}
1333
Alexey Dobriyan97a32532020-02-03 17:37:17 -08001334static const struct proc_ops psi_io_proc_ops = {
1335 .proc_open = psi_io_open,
1336 .proc_read = seq_read,
1337 .proc_lseek = seq_lseek,
1338 .proc_write = psi_io_write,
1339 .proc_poll = psi_fop_poll,
1340 .proc_release = psi_fop_release,
Johannes Weinereb414682018-10-26 15:06:27 -07001341};
1342
Alexey Dobriyan97a32532020-02-03 17:37:17 -08001343static const struct proc_ops psi_memory_proc_ops = {
1344 .proc_open = psi_memory_open,
1345 .proc_read = seq_read,
1346 .proc_lseek = seq_lseek,
1347 .proc_write = psi_memory_write,
1348 .proc_poll = psi_fop_poll,
1349 .proc_release = psi_fop_release,
Johannes Weinereb414682018-10-26 15:06:27 -07001350};
1351
Alexey Dobriyan97a32532020-02-03 17:37:17 -08001352static const struct proc_ops psi_cpu_proc_ops = {
1353 .proc_open = psi_cpu_open,
1354 .proc_read = seq_read,
1355 .proc_lseek = seq_lseek,
1356 .proc_write = psi_cpu_write,
1357 .proc_poll = psi_fop_poll,
1358 .proc_release = psi_fop_release,
Johannes Weinereb414682018-10-26 15:06:27 -07001359};
1360
1361static int __init psi_proc_init(void)
1362{
Wang Long3d817682019-12-18 20:38:18 +08001363 if (psi_enable) {
1364 proc_mkdir("pressure", NULL);
Josh Hunt6db12ee2021-04-01 22:58:33 -04001365 proc_create("pressure/io", 0666, NULL, &psi_io_proc_ops);
1366 proc_create("pressure/memory", 0666, NULL, &psi_memory_proc_ops);
1367 proc_create("pressure/cpu", 0666, NULL, &psi_cpu_proc_ops);
Wang Long3d817682019-12-18 20:38:18 +08001368 }
Johannes Weinereb414682018-10-26 15:06:27 -07001369 return 0;
1370}
1371module_init(psi_proc_init);