blob: e53b711bd643120f66aa6cdf3f3e5c1add123830 [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 *
37 * (Naturally, the FULL state doesn't exist for the CPU resource.)
38 *
39 * SOME = nr_delayed_tasks != 0
40 * FULL = nr_delayed_tasks != 0 && nr_running_tasks == 0
41 *
42 * The percentage of wallclock time spent in those compound stall
43 * states gives pressure numbers between 0 and 100 for each resource,
44 * where the SOME percentage indicates workload slowdowns and the FULL
45 * percentage indicates reduced CPU utilization:
46 *
47 * %SOME = time(SOME) / period
48 * %FULL = time(FULL) / period
49 *
50 * Multiple CPUs
51 *
52 * The more tasks and available CPUs there are, the more work can be
53 * performed concurrently. This means that the potential that can go
54 * unrealized due to resource contention *also* scales with non-idle
55 * tasks and CPUs.
56 *
57 * Consider a scenario where 257 number crunching tasks are trying to
58 * run concurrently on 256 CPUs. If we simply aggregated the task
59 * states, we would have to conclude a CPU SOME pressure number of
60 * 100%, since *somebody* is waiting on a runqueue at all
61 * times. However, that is clearly not the amount of contention the
62 * workload is experiencing: only one out of 256 possible exceution
63 * threads will be contended at any given time, or about 0.4%.
64 *
65 * Conversely, consider a scenario of 4 tasks and 4 CPUs where at any
66 * given time *one* of the tasks is delayed due to a lack of memory.
67 * Again, looking purely at the task state would yield a memory FULL
68 * pressure number of 0%, since *somebody* is always making forward
69 * progress. But again this wouldn't capture the amount of execution
70 * potential lost, which is 1 out of 4 CPUs, or 25%.
71 *
72 * To calculate wasted potential (pressure) with multiple processors,
73 * we have to base our calculation on the number of non-idle tasks in
74 * conjunction with the number of available CPUs, which is the number
75 * of potential execution threads. SOME becomes then the proportion of
76 * delayed tasks to possibe threads, and FULL is the share of possible
77 * threads that are unproductive due to delays:
78 *
79 * threads = min(nr_nonidle_tasks, nr_cpus)
80 * SOME = min(nr_delayed_tasks / threads, 1)
81 * FULL = (threads - min(nr_running_tasks, threads)) / threads
82 *
83 * For the 257 number crunchers on 256 CPUs, this yields:
84 *
85 * threads = min(257, 256)
86 * SOME = min(1 / 256, 1) = 0.4%
87 * FULL = (256 - min(257, 256)) / 256 = 0%
88 *
89 * For the 1 out of 4 memory-delayed tasks, this yields:
90 *
91 * threads = min(4, 4)
92 * SOME = min(1 / 4, 1) = 25%
93 * FULL = (4 - min(3, 4)) / 4 = 25%
94 *
95 * [ Substitute nr_cpus with 1, and you can see that it's a natural
96 * extension of the single-CPU model. ]
97 *
98 * Implementation
99 *
100 * To assess the precise time spent in each such state, we would have
101 * to freeze the system on task changes and start/stop the state
102 * clocks accordingly. Obviously that doesn't scale in practice.
103 *
104 * Because the scheduler aims to distribute the compute load evenly
105 * among the available CPUs, we can track task state locally to each
106 * CPU and, at much lower frequency, extrapolate the global state for
107 * the cumulative stall times and the running averages.
108 *
109 * For each runqueue, we track:
110 *
111 * tSOME[cpu] = time(nr_delayed_tasks[cpu] != 0)
112 * tFULL[cpu] = time(nr_delayed_tasks[cpu] && !nr_running_tasks[cpu])
113 * tNONIDLE[cpu] = time(nr_nonidle_tasks[cpu] != 0)
114 *
115 * and then periodically aggregate:
116 *
117 * tNONIDLE = sum(tNONIDLE[i])
118 *
119 * tSOME = sum(tSOME[i] * tNONIDLE[i]) / tNONIDLE
120 * tFULL = sum(tFULL[i] * tNONIDLE[i]) / tNONIDLE
121 *
122 * %SOME = tSOME / period
123 * %FULL = tFULL / period
124 *
125 * This gives us an approximation of pressure that is practical
126 * cost-wise, yet way more sensitive and accurate than periodic
127 * sampling of the aggregate task states would be.
128 */
129
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800130#include "../workqueue_internal.h"
Johannes Weinereb414682018-10-26 15:06:27 -0700131#include <linux/sched/loadavg.h>
132#include <linux/seq_file.h>
133#include <linux/proc_fs.h>
134#include <linux/seqlock.h>
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700135#include <linux/uaccess.h>
Johannes Weinereb414682018-10-26 15:06:27 -0700136#include <linux/cgroup.h>
137#include <linux/module.h>
138#include <linux/sched.h>
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700139#include <linux/ctype.h>
140#include <linux/file.h>
141#include <linux/poll.h>
Johannes Weinereb414682018-10-26 15:06:27 -0700142#include <linux/psi.h>
143#include "sched.h"
144
145static int psi_bug __read_mostly;
146
Johannes Weinere0c27442018-11-30 14:09:58 -0800147DEFINE_STATIC_KEY_FALSE(psi_disabled);
148
149#ifdef CONFIG_PSI_DEFAULT_DISABLED
Suren Baghdasaryan9289c5e2019-05-14 15:40:59 -0700150static bool psi_enable;
Johannes Weinere0c27442018-11-30 14:09:58 -0800151#else
Suren Baghdasaryan9289c5e2019-05-14 15:40:59 -0700152static bool psi_enable = true;
Johannes Weinere0c27442018-11-30 14:09:58 -0800153#endif
154static int __init setup_psi(char *str)
155{
156 return kstrtobool(str, &psi_enable) == 0;
157}
158__setup("psi=", setup_psi);
Johannes Weinereb414682018-10-26 15:06:27 -0700159
160/* Running averages - we need to be higher-res than loadavg */
161#define PSI_FREQ (2*HZ+1) /* 2 sec intervals */
162#define EXP_10s 1677 /* 1/exp(2s/10s) as fixed-point */
163#define EXP_60s 1981 /* 1/exp(2s/60s) */
164#define EXP_300s 2034 /* 1/exp(2s/300s) */
165
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700166/* PSI trigger definitions */
167#define WINDOW_MIN_US 500000 /* Min window size is 500ms */
168#define WINDOW_MAX_US 10000000 /* Max window size is 10s */
169#define UPDATES_PER_WINDOW 10 /* 10 updates per window */
170
Johannes Weinereb414682018-10-26 15:06:27 -0700171/* Sampling frequency in nanoseconds */
172static u64 psi_period __read_mostly;
173
174/* System-level pressure and stall tracking */
175static DEFINE_PER_CPU(struct psi_group_cpu, system_group_pcpu);
Dan Schatzbergdf5ba5b2019-05-14 15:41:18 -0700176struct psi_group psi_system = {
Johannes Weinereb414682018-10-26 15:06:27 -0700177 .pcpu = &system_group_pcpu,
178};
179
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700180static void psi_avgs_work(struct work_struct *work);
Johannes Weinereb414682018-10-26 15:06:27 -0700181
182static void group_init(struct psi_group *group)
183{
184 int cpu;
185
186 for_each_possible_cpu(cpu)
187 seqcount_init(&per_cpu_ptr(group->pcpu, cpu)->seq);
Johannes Weiner3dfbe252019-12-03 13:35:23 -0500188 group->avg_last_update = sched_clock();
189 group->avg_next_update = group->avg_last_update + psi_period;
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700190 INIT_DELAYED_WORK(&group->avgs_work, psi_avgs_work);
191 mutex_init(&group->avgs_lock);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700192 /* Init trigger-related members */
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700193 mutex_init(&group->trigger_lock);
194 INIT_LIST_HEAD(&group->triggers);
195 memset(group->nr_triggers, 0, sizeof(group->nr_triggers));
196 group->poll_states = 0;
197 group->poll_min_period = U32_MAX;
198 memset(group->polling_total, 0, sizeof(group->polling_total));
199 group->polling_next_update = ULLONG_MAX;
200 group->polling_until = 0;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700201 rcu_assign_pointer(group->poll_task, NULL);
Johannes Weinereb414682018-10-26 15:06:27 -0700202}
203
204void __init psi_init(void)
205{
Johannes Weinere0c27442018-11-30 14:09:58 -0800206 if (!psi_enable) {
207 static_branch_enable(&psi_disabled);
Johannes Weinereb414682018-10-26 15:06:27 -0700208 return;
Johannes Weinere0c27442018-11-30 14:09:58 -0800209 }
Johannes Weinereb414682018-10-26 15:06:27 -0700210
211 psi_period = jiffies_to_nsecs(PSI_FREQ);
212 group_init(&psi_system);
213}
214
215static bool test_state(unsigned int *tasks, enum psi_states state)
216{
217 switch (state) {
218 case PSI_IO_SOME:
219 return tasks[NR_IOWAIT];
220 case PSI_IO_FULL:
221 return tasks[NR_IOWAIT] && !tasks[NR_RUNNING];
222 case PSI_MEM_SOME:
223 return tasks[NR_MEMSTALL];
224 case PSI_MEM_FULL:
225 return tasks[NR_MEMSTALL] && !tasks[NR_RUNNING];
226 case PSI_CPU_SOME:
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400227 return tasks[NR_RUNNING] > tasks[NR_ONCPU];
Johannes Weinereb414682018-10-26 15:06:27 -0700228 case PSI_NONIDLE:
229 return tasks[NR_IOWAIT] || tasks[NR_MEMSTALL] ||
230 tasks[NR_RUNNING];
231 default:
232 return false;
233 }
234}
235
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700236static void get_recent_times(struct psi_group *group, int cpu,
237 enum psi_aggregators aggregator, u32 *times,
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700238 u32 *pchanged_states)
Johannes Weinereb414682018-10-26 15:06:27 -0700239{
240 struct psi_group_cpu *groupc = per_cpu_ptr(group->pcpu, cpu);
Johannes Weinereb414682018-10-26 15:06:27 -0700241 u64 now, state_start;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700242 enum psi_states s;
Johannes Weinereb414682018-10-26 15:06:27 -0700243 unsigned int seq;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700244 u32 state_mask;
Johannes Weinereb414682018-10-26 15:06:27 -0700245
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700246 *pchanged_states = 0;
247
Johannes Weinereb414682018-10-26 15:06:27 -0700248 /* Snapshot a coherent view of the CPU state */
249 do {
250 seq = read_seqcount_begin(&groupc->seq);
251 now = cpu_clock(cpu);
252 memcpy(times, groupc->times, sizeof(groupc->times));
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700253 state_mask = groupc->state_mask;
Johannes Weinereb414682018-10-26 15:06:27 -0700254 state_start = groupc->state_start;
255 } while (read_seqcount_retry(&groupc->seq, seq));
256
257 /* Calculate state time deltas against the previous snapshot */
258 for (s = 0; s < NR_PSI_STATES; s++) {
259 u32 delta;
260 /*
261 * In addition to already concluded states, we also
262 * incorporate currently active states on the CPU,
263 * since states may last for many sampling periods.
264 *
265 * This way we keep our delta sampling buckets small
266 * (u32) and our reported pressure close to what's
267 * actually happening.
268 */
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700269 if (state_mask & (1 << s))
Johannes Weinereb414682018-10-26 15:06:27 -0700270 times[s] += now - state_start;
271
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700272 delta = times[s] - groupc->times_prev[aggregator][s];
273 groupc->times_prev[aggregator][s] = times[s];
Johannes Weinereb414682018-10-26 15:06:27 -0700274
275 times[s] = delta;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700276 if (delta)
277 *pchanged_states |= (1 << s);
Johannes Weinereb414682018-10-26 15:06:27 -0700278 }
279}
280
281static void calc_avgs(unsigned long avg[3], int missed_periods,
282 u64 time, u64 period)
283{
284 unsigned long pct;
285
286 /* Fill in zeroes for periods of no activity */
287 if (missed_periods) {
288 avg[0] = calc_load_n(avg[0], EXP_10s, 0, missed_periods);
289 avg[1] = calc_load_n(avg[1], EXP_60s, 0, missed_periods);
290 avg[2] = calc_load_n(avg[2], EXP_300s, 0, missed_periods);
291 }
292
293 /* Sample the most recent active period */
294 pct = div_u64(time * 100, period);
295 pct *= FIXED_1;
296 avg[0] = calc_load(avg[0], EXP_10s, pct);
297 avg[1] = calc_load(avg[1], EXP_60s, pct);
298 avg[2] = calc_load(avg[2], EXP_300s, pct);
299}
300
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700301static void collect_percpu_times(struct psi_group *group,
302 enum psi_aggregators aggregator,
303 u32 *pchanged_states)
Johannes Weinereb414682018-10-26 15:06:27 -0700304{
305 u64 deltas[NR_PSI_STATES - 1] = { 0, };
Johannes Weinereb414682018-10-26 15:06:27 -0700306 unsigned long nonidle_total = 0;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700307 u32 changed_states = 0;
Johannes Weinereb414682018-10-26 15:06:27 -0700308 int cpu;
309 int s;
310
Johannes Weinereb414682018-10-26 15:06:27 -0700311 /*
312 * Collect the per-cpu time buckets and average them into a
313 * single time sample that is normalized to wallclock time.
314 *
315 * For averaging, each CPU is weighted by its non-idle time in
316 * the sampling period. This eliminates artifacts from uneven
317 * loading, or even entirely idle CPUs.
318 */
319 for_each_possible_cpu(cpu) {
320 u32 times[NR_PSI_STATES];
321 u32 nonidle;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700322 u32 cpu_changed_states;
Johannes Weinereb414682018-10-26 15:06:27 -0700323
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700324 get_recent_times(group, cpu, aggregator, times,
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700325 &cpu_changed_states);
326 changed_states |= cpu_changed_states;
Johannes Weinereb414682018-10-26 15:06:27 -0700327
328 nonidle = nsecs_to_jiffies(times[PSI_NONIDLE]);
329 nonidle_total += nonidle;
330
331 for (s = 0; s < PSI_NONIDLE; s++)
332 deltas[s] += (u64)times[s] * nonidle;
333 }
334
335 /*
336 * Integrate the sample into the running statistics that are
337 * reported to userspace: the cumulative stall times and the
338 * decaying averages.
339 *
340 * Pressure percentages are sampled at PSI_FREQ. We might be
341 * called more often when the user polls more frequently than
342 * that; we might be called less often when there is no task
343 * activity, thus no data, and clock ticks are sporadic. The
344 * below handles both.
345 */
346
347 /* total= */
348 for (s = 0; s < NR_PSI_STATES - 1; s++)
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700349 group->total[aggregator][s] +=
350 div_u64(deltas[s], max(nonidle_total, 1UL));
Johannes Weinereb414682018-10-26 15:06:27 -0700351
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700352 if (pchanged_states)
353 *pchanged_states = changed_states;
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700354}
355
356static u64 update_averages(struct psi_group *group, u64 now)
357{
358 unsigned long missed_periods = 0;
359 u64 expires, period;
360 u64 avg_next_update;
361 int s;
362
Johannes Weinereb414682018-10-26 15:06:27 -0700363 /* avgX= */
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700364 expires = group->avg_next_update;
Johannes Weiner4e375042019-02-20 22:19:59 -0800365 if (now - expires >= psi_period)
Johannes Weinereb414682018-10-26 15:06:27 -0700366 missed_periods = div_u64(now - expires, psi_period);
367
368 /*
369 * The periodic clock tick can get delayed for various
370 * reasons, especially on loaded systems. To avoid clock
371 * drift, we schedule the clock in fixed psi_period intervals.
372 * But the deltas we sample out of the per-cpu buckets above
373 * are based on the actual time elapsing between clock ticks.
374 */
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700375 avg_next_update = expires + ((1 + missed_periods) * psi_period);
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700376 period = now - (group->avg_last_update + (missed_periods * psi_period));
377 group->avg_last_update = now;
Johannes Weinereb414682018-10-26 15:06:27 -0700378
379 for (s = 0; s < NR_PSI_STATES - 1; s++) {
380 u32 sample;
381
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700382 sample = group->total[PSI_AVGS][s] - group->avg_total[s];
Johannes Weinereb414682018-10-26 15:06:27 -0700383 /*
384 * Due to the lockless sampling of the time buckets,
385 * recorded time deltas can slip into the next period,
386 * which under full pressure can result in samples in
387 * excess of the period length.
388 *
389 * We don't want to report non-sensical pressures in
390 * excess of 100%, nor do we want to drop such events
391 * on the floor. Instead we punt any overage into the
392 * future until pressure subsides. By doing this we
393 * don't underreport the occurring pressure curve, we
394 * just report it delayed by one period length.
395 *
396 * The error isn't cumulative. As soon as another
397 * delta slips from a period P to P+1, by definition
398 * it frees up its time T in P.
399 */
400 if (sample > period)
401 sample = period;
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700402 group->avg_total[s] += sample;
Johannes Weinereb414682018-10-26 15:06:27 -0700403 calc_avgs(group->avg[s], missed_periods, sample, period);
404 }
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700405
406 return avg_next_update;
Johannes Weinereb414682018-10-26 15:06:27 -0700407}
408
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700409static void psi_avgs_work(struct work_struct *work)
Johannes Weinereb414682018-10-26 15:06:27 -0700410{
411 struct delayed_work *dwork;
412 struct psi_group *group;
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700413 u32 changed_states;
Johannes Weinereb414682018-10-26 15:06:27 -0700414 bool nonidle;
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700415 u64 now;
Johannes Weinereb414682018-10-26 15:06:27 -0700416
417 dwork = to_delayed_work(work);
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700418 group = container_of(dwork, struct psi_group, avgs_work);
Johannes Weinereb414682018-10-26 15:06:27 -0700419
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700420 mutex_lock(&group->avgs_lock);
421
422 now = sched_clock();
423
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700424 collect_percpu_times(group, PSI_AVGS, &changed_states);
Suren Baghdasaryan333f3017c2019-05-14 15:41:09 -0700425 nonidle = changed_states & (1 << PSI_NONIDLE);
Johannes Weinereb414682018-10-26 15:06:27 -0700426 /*
427 * If there is task activity, periodically fold the per-cpu
428 * times and feed samples into the running averages. If things
429 * are idle and there is no data to process, stop the clock.
430 * Once restarted, we'll catch up the running averages in one
431 * go - see calc_avgs() and missed_periods.
432 */
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700433 if (now >= group->avg_next_update)
434 group->avg_next_update = update_averages(group, now);
Johannes Weinereb414682018-10-26 15:06:27 -0700435
436 if (nonidle) {
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700437 schedule_delayed_work(dwork, nsecs_to_jiffies(
438 group->avg_next_update - now) + 1);
Johannes Weinereb414682018-10-26 15:06:27 -0700439 }
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -0700440
441 mutex_unlock(&group->avgs_lock);
Johannes Weinereb414682018-10-26 15:06:27 -0700442}
443
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700444/* Trigger tracking window manupulations */
445static void window_reset(struct psi_window *win, u64 now, u64 value,
446 u64 prev_growth)
447{
448 win->start_time = now;
449 win->start_value = value;
450 win->prev_growth = prev_growth;
451}
452
453/*
454 * PSI growth tracking window update and growth calculation routine.
455 *
456 * This approximates a sliding tracking window by interpolating
457 * partially elapsed windows using historical growth data from the
458 * previous intervals. This minimizes memory requirements (by not storing
459 * all the intermediate values in the previous window) and simplifies
460 * the calculations. It works well because PSI signal changes only in
461 * positive direction and over relatively small window sizes the growth
462 * is close to linear.
463 */
464static u64 window_update(struct psi_window *win, u64 now, u64 value)
465{
466 u64 elapsed;
467 u64 growth;
468
469 elapsed = now - win->start_time;
470 growth = value - win->start_value;
471 /*
472 * After each tracking window passes win->start_value and
473 * win->start_time get reset and win->prev_growth stores
474 * the average per-window growth of the previous window.
475 * win->prev_growth is then used to interpolate additional
476 * growth from the previous window assuming it was linear.
477 */
478 if (elapsed > win->size)
479 window_reset(win, now, value, growth);
480 else {
481 u32 remaining;
482
483 remaining = win->size - elapsed;
Johannes Weinerc3466952019-12-03 13:35:24 -0500484 growth += div64_u64(win->prev_growth * remaining, win->size);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700485 }
486
487 return growth;
488}
489
490static void init_triggers(struct psi_group *group, u64 now)
491{
492 struct psi_trigger *t;
493
494 list_for_each_entry(t, &group->triggers, node)
495 window_reset(&t->win, now,
496 group->total[PSI_POLL][t->state], 0);
497 memcpy(group->polling_total, group->total[PSI_POLL],
498 sizeof(group->polling_total));
499 group->polling_next_update = now + group->poll_min_period;
500}
501
502static u64 update_triggers(struct psi_group *group, u64 now)
503{
504 struct psi_trigger *t;
505 bool new_stall = false;
506 u64 *total = group->total[PSI_POLL];
507
508 /*
509 * On subsequent updates, calculate growth deltas and let
510 * watchers know when their specified thresholds are exceeded.
511 */
512 list_for_each_entry(t, &group->triggers, node) {
513 u64 growth;
514
515 /* Check for stall activity */
516 if (group->polling_total[t->state] == total[t->state])
517 continue;
518
519 /*
520 * Multiple triggers might be looking at the same state,
521 * remember to update group->polling_total[] once we've
522 * been through all of them. Also remember to extend the
523 * polling time if we see new stall activity.
524 */
525 new_stall = true;
526
527 /* Calculate growth since last update */
528 growth = window_update(&t->win, now, total[t->state]);
529 if (growth < t->threshold)
530 continue;
531
532 /* Limit event signaling to once per window */
533 if (now < t->last_event_time + t->win.size)
534 continue;
535
536 /* Generate an event */
537 if (cmpxchg(&t->event, 0, 1) == 0)
538 wake_up_interruptible(&t->event_wait);
539 t->last_event_time = now;
540 }
541
542 if (new_stall)
543 memcpy(group->polling_total, total,
544 sizeof(group->polling_total));
545
546 return now + group->poll_min_period;
547}
548
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700549/* Schedule polling if it's not already scheduled. */
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700550static void psi_schedule_poll_work(struct psi_group *group, unsigned long delay)
551{
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700552 struct task_struct *task;
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700553
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700554 /*
555 * Do not reschedule if already scheduled.
556 * Possible race with a timer scheduled after this check but before
557 * mod_timer below can be tolerated because group->polling_next_update
558 * will keep updates on schedule.
559 */
560 if (timer_pending(&group->poll_timer))
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700561 return;
562
563 rcu_read_lock();
564
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700565 task = rcu_dereference(group->poll_task);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700566 /*
567 * kworker might be NULL in case psi_trigger_destroy races with
568 * psi_task_change (hotpath) which can't use locks
569 */
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700570 if (likely(task))
571 mod_timer(&group->poll_timer, jiffies + delay);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700572
573 rcu_read_unlock();
574}
575
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700576static void psi_poll_work(struct psi_group *group)
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700577{
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700578 u32 changed_states;
579 u64 now;
580
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700581 mutex_lock(&group->trigger_lock);
582
583 now = sched_clock();
584
585 collect_percpu_times(group, PSI_POLL, &changed_states);
586
587 if (changed_states & group->poll_states) {
588 /* Initialize trigger windows when entering polling mode */
589 if (now > group->polling_until)
590 init_triggers(group, now);
591
592 /*
593 * Keep the monitor active for at least the duration of the
594 * minimum tracking window as long as monitor states are
595 * changing.
596 */
597 group->polling_until = now +
598 group->poll_min_period * UPDATES_PER_WINDOW;
599 }
600
601 if (now > group->polling_until) {
602 group->polling_next_update = ULLONG_MAX;
603 goto out;
604 }
605
606 if (now >= group->polling_next_update)
607 group->polling_next_update = update_triggers(group, now);
608
609 psi_schedule_poll_work(group,
610 nsecs_to_jiffies(group->polling_next_update - now) + 1);
611
612out:
613 mutex_unlock(&group->trigger_lock);
614}
615
Suren Baghdasaryan461daba2020-05-28 12:54:42 -0700616static int psi_poll_worker(void *data)
617{
618 struct psi_group *group = (struct psi_group *)data;
619 struct sched_param param = {
620 .sched_priority = 1,
621 };
622
623 sched_setscheduler_nocheck(current, SCHED_FIFO, &param);
624
625 while (true) {
626 wait_event_interruptible(group->poll_wait,
627 atomic_cmpxchg(&group->poll_wakeup, 1, 0) ||
628 kthread_should_stop());
629 if (kthread_should_stop())
630 break;
631
632 psi_poll_work(group);
633 }
634 return 0;
635}
636
637static void poll_timer_fn(struct timer_list *t)
638{
639 struct psi_group *group = from_timer(group, t, poll_timer);
640
641 atomic_set(&group->poll_wakeup, 1);
642 wake_up_interruptible(&group->poll_wait);
643}
644
Johannes Weinereb414682018-10-26 15:06:27 -0700645static void record_times(struct psi_group_cpu *groupc, int cpu,
646 bool memstall_tick)
647{
648 u32 delta;
649 u64 now;
650
651 now = cpu_clock(cpu);
652 delta = now - groupc->state_start;
653 groupc->state_start = now;
654
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700655 if (groupc->state_mask & (1 << PSI_IO_SOME)) {
Johannes Weinereb414682018-10-26 15:06:27 -0700656 groupc->times[PSI_IO_SOME] += delta;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700657 if (groupc->state_mask & (1 << PSI_IO_FULL))
Johannes Weinereb414682018-10-26 15:06:27 -0700658 groupc->times[PSI_IO_FULL] += delta;
659 }
660
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700661 if (groupc->state_mask & (1 << PSI_MEM_SOME)) {
Johannes Weinereb414682018-10-26 15:06:27 -0700662 groupc->times[PSI_MEM_SOME] += delta;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700663 if (groupc->state_mask & (1 << PSI_MEM_FULL))
Johannes Weinereb414682018-10-26 15:06:27 -0700664 groupc->times[PSI_MEM_FULL] += delta;
665 else if (memstall_tick) {
666 u32 sample;
667 /*
668 * Since we care about lost potential, a
669 * memstall is FULL when there are no other
670 * working tasks, but also when the CPU is
671 * actively reclaiming and nothing productive
672 * could run even if it were runnable.
673 *
674 * When the timer tick sees a reclaiming CPU,
675 * regardless of runnable tasks, sample a FULL
676 * tick (or less if it hasn't been a full tick
677 * since the last state change).
678 */
679 sample = min(delta, (u32)jiffies_to_nsecs(1));
680 groupc->times[PSI_MEM_FULL] += sample;
681 }
682 }
683
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700684 if (groupc->state_mask & (1 << PSI_CPU_SOME))
Johannes Weinereb414682018-10-26 15:06:27 -0700685 groupc->times[PSI_CPU_SOME] += delta;
686
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700687 if (groupc->state_mask & (1 << PSI_NONIDLE))
Johannes Weinereb414682018-10-26 15:06:27 -0700688 groupc->times[PSI_NONIDLE] += delta;
689}
690
Johannes Weiner36b238d2020-03-16 15:13:32 -0400691static void psi_group_change(struct psi_group *group, int cpu,
692 unsigned int clear, unsigned int set,
693 bool wake_clock)
Johannes Weinereb414682018-10-26 15:06:27 -0700694{
695 struct psi_group_cpu *groupc;
Johannes Weiner36b238d2020-03-16 15:13:32 -0400696 u32 state_mask = 0;
Johannes Weinereb414682018-10-26 15:06:27 -0700697 unsigned int t, m;
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700698 enum psi_states s;
Johannes Weinereb414682018-10-26 15:06:27 -0700699
700 groupc = per_cpu_ptr(group->pcpu, cpu);
701
702 /*
703 * First we assess the aggregate resource states this CPU's
704 * tasks have been in since the last change, and account any
705 * SOME and FULL time these may have resulted in.
706 *
707 * Then we update the task counts according to the state
708 * change requested through the @clear and @set bits.
709 */
710 write_seqcount_begin(&groupc->seq);
711
712 record_times(groupc, cpu, false);
713
714 for (t = 0, m = clear; m; m &= ~(1 << t), t++) {
715 if (!(m & (1 << t)))
716 continue;
717 if (groupc->tasks[t] == 0 && !psi_bug) {
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400718 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 -0700719 cpu, t, groupc->tasks[0],
720 groupc->tasks[1], groupc->tasks[2],
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400721 groupc->tasks[3], clear, set);
Johannes Weinereb414682018-10-26 15:06:27 -0700722 psi_bug = 1;
723 }
724 groupc->tasks[t]--;
725 }
726
727 for (t = 0; set; set &= ~(1 << t), t++)
728 if (set & (1 << t))
729 groupc->tasks[t]++;
730
Suren Baghdasaryan33b2d632019-05-14 15:40:56 -0700731 /* Calculate state mask representing active states */
732 for (s = 0; s < NR_PSI_STATES; s++) {
733 if (test_state(groupc->tasks, s))
734 state_mask |= (1 << s);
735 }
736 groupc->state_mask = state_mask;
737
Johannes Weinereb414682018-10-26 15:06:27 -0700738 write_seqcount_end(&groupc->seq);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700739
Johannes Weiner36b238d2020-03-16 15:13:32 -0400740 if (state_mask & group->poll_states)
741 psi_schedule_poll_work(group, 1);
742
743 if (wake_clock && !delayed_work_pending(&group->avgs_work))
744 schedule_delayed_work(&group->avgs_work, PSI_FREQ);
Johannes Weinereb414682018-10-26 15:06:27 -0700745}
746
Johannes Weiner2ce71352018-10-26 15:06:31 -0700747static struct psi_group *iterate_groups(struct task_struct *task, void **iter)
748{
749#ifdef CONFIG_CGROUPS
750 struct cgroup *cgroup = NULL;
751
752 if (!*iter)
753 cgroup = task->cgroups->dfl_cgrp;
754 else if (*iter == &psi_system)
755 return NULL;
756 else
757 cgroup = cgroup_parent(*iter);
758
759 if (cgroup && cgroup_parent(cgroup)) {
760 *iter = cgroup;
761 return cgroup_psi(cgroup);
762 }
763#else
764 if (*iter)
765 return NULL;
766#endif
767 *iter = &psi_system;
768 return &psi_system;
769}
770
Johannes Weiner36b238d2020-03-16 15:13:32 -0400771static void psi_flags_change(struct task_struct *task, int clear, int set)
772{
773 if (((task->psi_flags & set) ||
774 (task->psi_flags & clear) != clear) &&
775 !psi_bug) {
776 printk_deferred(KERN_ERR "psi: inconsistent task state! task=%d:%s cpu=%d psi_flags=%x clear=%x set=%x\n",
777 task->pid, task->comm, task_cpu(task),
778 task->psi_flags, clear, set);
779 psi_bug = 1;
780 }
781
782 task->psi_flags &= ~clear;
783 task->psi_flags |= set;
784}
785
Johannes Weinereb414682018-10-26 15:06:27 -0700786void psi_task_change(struct task_struct *task, int clear, int set)
787{
788 int cpu = task_cpu(task);
Johannes Weiner2ce71352018-10-26 15:06:31 -0700789 struct psi_group *group;
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800790 bool wake_clock = true;
Johannes Weiner2ce71352018-10-26 15:06:31 -0700791 void *iter = NULL;
Johannes Weinereb414682018-10-26 15:06:27 -0700792
793 if (!task->pid)
794 return;
795
Johannes Weiner36b238d2020-03-16 15:13:32 -0400796 psi_flags_change(task, clear, set);
Johannes Weinereb414682018-10-26 15:06:27 -0700797
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)))
810 psi_group_change(group, cpu, clear, set, wake_clock);
811}
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;
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700819
Johannes Weiner36b238d2020-03-16 15:13:32 -0400820 if (next->pid) {
821 psi_flags_change(next, 0, TSK_ONCPU);
822 /*
823 * When moving state between tasks, the group that
824 * contains them both does not change: we can stop
825 * updating the tree once we reach the first common
826 * ancestor. Iterate @next's ancestors until we
827 * encounter @prev's state.
828 */
829 iter = NULL;
830 while ((group = iterate_groups(next, &iter))) {
831 if (per_cpu_ptr(group->pcpu, cpu)->tasks[NR_ONCPU]) {
832 common = group;
833 break;
834 }
835
836 psi_group_change(group, cpu, 0, TSK_ONCPU, true);
837 }
838 }
839
840 /*
841 * If this is a voluntary sleep, dequeue will have taken care
842 * of the outgoing TSK_ONCPU alongside TSK_RUNNING already. We
843 * only need to deal with it during preemption.
844 */
845 if (sleep)
846 return;
847
848 if (prev->pid) {
849 psi_flags_change(prev, TSK_ONCPU, 0);
850
851 iter = NULL;
852 while ((group = iterate_groups(prev, &iter)) && group != common)
853 psi_group_change(group, cpu, TSK_ONCPU, 0, true);
Johannes Weiner1b69ac62019-02-01 14:20:42 -0800854 }
Johannes Weinereb414682018-10-26 15:06:27 -0700855}
856
857void psi_memstall_tick(struct task_struct *task, int cpu)
858{
Johannes Weiner2ce71352018-10-26 15:06:31 -0700859 struct psi_group *group;
860 void *iter = NULL;
Johannes Weinereb414682018-10-26 15:06:27 -0700861
Johannes Weiner2ce71352018-10-26 15:06:31 -0700862 while ((group = iterate_groups(task, &iter))) {
863 struct psi_group_cpu *groupc;
864
865 groupc = per_cpu_ptr(group->pcpu, cpu);
866 write_seqcount_begin(&groupc->seq);
867 record_times(groupc, cpu, true);
868 write_seqcount_end(&groupc->seq);
869 }
Johannes Weinereb414682018-10-26 15:06:27 -0700870}
871
872/**
873 * psi_memstall_enter - mark the beginning of a memory stall section
874 * @flags: flags to handle nested sections
875 *
876 * Marks the calling task as being stalled due to a lack of memory,
877 * such as waiting for a refault or performing reclaim.
878 */
879void psi_memstall_enter(unsigned long *flags)
880{
881 struct rq_flags rf;
882 struct rq *rq;
883
Johannes Weinere0c27442018-11-30 14:09:58 -0800884 if (static_branch_likely(&psi_disabled))
Johannes Weinereb414682018-10-26 15:06:27 -0700885 return;
886
Yafang Shao1066d1b2020-03-16 21:28:05 -0400887 *flags = current->in_memstall;
Johannes Weinereb414682018-10-26 15:06:27 -0700888 if (*flags)
889 return;
890 /*
Yafang Shao1066d1b2020-03-16 21:28:05 -0400891 * in_memstall setting & accounting needs to be atomic wrt
Johannes Weinereb414682018-10-26 15:06:27 -0700892 * changes to the task's scheduling state, otherwise we can
893 * race with CPU migration.
894 */
895 rq = this_rq_lock_irq(&rf);
896
Yafang Shao1066d1b2020-03-16 21:28:05 -0400897 current->in_memstall = 1;
Johannes Weinereb414682018-10-26 15:06:27 -0700898 psi_task_change(current, 0, TSK_MEMSTALL);
899
900 rq_unlock_irq(rq, &rf);
901}
902
903/**
904 * psi_memstall_leave - mark the end of an memory stall section
905 * @flags: flags to handle nested memdelay sections
906 *
907 * Marks the calling task as no longer stalled due to lack of memory.
908 */
909void psi_memstall_leave(unsigned long *flags)
910{
911 struct rq_flags rf;
912 struct rq *rq;
913
Johannes Weinere0c27442018-11-30 14:09:58 -0800914 if (static_branch_likely(&psi_disabled))
Johannes Weinereb414682018-10-26 15:06:27 -0700915 return;
916
917 if (*flags)
918 return;
919 /*
Yafang Shao1066d1b2020-03-16 21:28:05 -0400920 * in_memstall clearing & accounting needs to be atomic wrt
Johannes Weinereb414682018-10-26 15:06:27 -0700921 * changes to the task's scheduling state, otherwise we could
922 * race with CPU migration.
923 */
924 rq = this_rq_lock_irq(&rf);
925
Yafang Shao1066d1b2020-03-16 21:28:05 -0400926 current->in_memstall = 0;
Johannes Weinereb414682018-10-26 15:06:27 -0700927 psi_task_change(current, TSK_MEMSTALL, 0);
928
929 rq_unlock_irq(rq, &rf);
930}
931
Johannes Weiner2ce71352018-10-26 15:06:31 -0700932#ifdef CONFIG_CGROUPS
933int psi_cgroup_alloc(struct cgroup *cgroup)
934{
Johannes Weinere0c27442018-11-30 14:09:58 -0800935 if (static_branch_likely(&psi_disabled))
Johannes Weiner2ce71352018-10-26 15:06:31 -0700936 return 0;
937
938 cgroup->psi.pcpu = alloc_percpu(struct psi_group_cpu);
939 if (!cgroup->psi.pcpu)
940 return -ENOMEM;
941 group_init(&cgroup->psi);
942 return 0;
943}
944
945void psi_cgroup_free(struct cgroup *cgroup)
946{
Johannes Weinere0c27442018-11-30 14:09:58 -0800947 if (static_branch_likely(&psi_disabled))
Johannes Weiner2ce71352018-10-26 15:06:31 -0700948 return;
949
Suren Baghdasaryanbcc78db2019-05-14 15:41:02 -0700950 cancel_delayed_work_sync(&cgroup->psi.avgs_work);
Johannes Weiner2ce71352018-10-26 15:06:31 -0700951 free_percpu(cgroup->psi.pcpu);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -0700952 /* All triggers must be removed by now */
953 WARN_ONCE(cgroup->psi.poll_states, "psi: trigger leak\n");
Johannes Weiner2ce71352018-10-26 15:06:31 -0700954}
955
956/**
957 * cgroup_move_task - move task to a different cgroup
958 * @task: the task
959 * @to: the target css_set
960 *
961 * Move task to a new cgroup and safely migrate its associated stall
962 * state between the different groups.
963 *
964 * This function acquires the task's rq lock to lock out concurrent
965 * changes to the task's scheduling state and - in case the task is
966 * running - concurrent changes to its stall state.
967 */
968void cgroup_move_task(struct task_struct *task, struct css_set *to)
969{
Johannes Weiner2ce71352018-10-26 15:06:31 -0700970 unsigned int task_flags = 0;
971 struct rq_flags rf;
972 struct rq *rq;
973
Johannes Weinere0c27442018-11-30 14:09:58 -0800974 if (static_branch_likely(&psi_disabled)) {
Olof Johansson8fcb2312018-11-16 15:08:00 -0800975 /*
976 * Lame to do this here, but the scheduler cannot be locked
977 * from the outside, so we move cgroups from inside sched/.
978 */
979 rcu_assign_pointer(task->cgroups, to);
980 return;
Johannes Weiner2ce71352018-10-26 15:06:31 -0700981 }
982
Olof Johansson8fcb2312018-11-16 15:08:00 -0800983 rq = task_rq_lock(task, &rf);
984
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400985 if (task_on_rq_queued(task)) {
Olof Johansson8fcb2312018-11-16 15:08:00 -0800986 task_flags = TSK_RUNNING;
Johannes Weinerb05e75d2020-03-16 15:13:31 -0400987 if (task_current(rq, task))
988 task_flags |= TSK_ONCPU;
989 } else if (task->in_iowait)
Olof Johansson8fcb2312018-11-16 15:08:00 -0800990 task_flags = TSK_IOWAIT;
991
Yafang Shao1066d1b2020-03-16 21:28:05 -0400992 if (task->in_memstall)
Olof Johansson8fcb2312018-11-16 15:08:00 -0800993 task_flags |= TSK_MEMSTALL;
994
995 if (task_flags)
996 psi_task_change(task, task_flags, 0);
997
998 /* See comment above */
Johannes Weiner2ce71352018-10-26 15:06:31 -0700999 rcu_assign_pointer(task->cgroups, to);
1000
Olof Johansson8fcb2312018-11-16 15:08:00 -08001001 if (task_flags)
1002 psi_task_change(task, 0, task_flags);
Johannes Weiner2ce71352018-10-26 15:06:31 -07001003
Olof Johansson8fcb2312018-11-16 15:08:00 -08001004 task_rq_unlock(rq, task, &rf);
Johannes Weiner2ce71352018-10-26 15:06:31 -07001005}
1006#endif /* CONFIG_CGROUPS */
1007
1008int psi_show(struct seq_file *m, struct psi_group *group, enum psi_res res)
Johannes Weinereb414682018-10-26 15:06:27 -07001009{
1010 int full;
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -07001011 u64 now;
Johannes Weinereb414682018-10-26 15:06:27 -07001012
Johannes Weinere0c27442018-11-30 14:09:58 -08001013 if (static_branch_likely(&psi_disabled))
Johannes Weinereb414682018-10-26 15:06:27 -07001014 return -EOPNOTSUPP;
1015
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -07001016 /* Update averages before reporting them */
1017 mutex_lock(&group->avgs_lock);
1018 now = sched_clock();
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001019 collect_percpu_times(group, PSI_AVGS, NULL);
Suren Baghdasaryan7fc70a32019-05-14 15:41:06 -07001020 if (now >= group->avg_next_update)
1021 group->avg_next_update = update_averages(group, now);
1022 mutex_unlock(&group->avgs_lock);
Johannes Weinereb414682018-10-26 15:06:27 -07001023
1024 for (full = 0; full < 2 - (res == PSI_CPU); full++) {
1025 unsigned long avg[3];
1026 u64 total;
1027 int w;
1028
1029 for (w = 0; w < 3; w++)
1030 avg[w] = group->avg[res * 2 + full][w];
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001031 total = div_u64(group->total[PSI_AVGS][res * 2 + full],
1032 NSEC_PER_USEC);
Johannes Weinereb414682018-10-26 15:06:27 -07001033
1034 seq_printf(m, "%s avg10=%lu.%02lu avg60=%lu.%02lu avg300=%lu.%02lu total=%llu\n",
1035 full ? "full" : "some",
1036 LOAD_INT(avg[0]), LOAD_FRAC(avg[0]),
1037 LOAD_INT(avg[1]), LOAD_FRAC(avg[1]),
1038 LOAD_INT(avg[2]), LOAD_FRAC(avg[2]),
1039 total);
1040 }
1041
1042 return 0;
1043}
1044
1045static int psi_io_show(struct seq_file *m, void *v)
1046{
1047 return psi_show(m, &psi_system, PSI_IO);
1048}
1049
1050static int psi_memory_show(struct seq_file *m, void *v)
1051{
1052 return psi_show(m, &psi_system, PSI_MEM);
1053}
1054
1055static int psi_cpu_show(struct seq_file *m, void *v)
1056{
1057 return psi_show(m, &psi_system, PSI_CPU);
1058}
1059
1060static int psi_io_open(struct inode *inode, struct file *file)
1061{
1062 return single_open(file, psi_io_show, NULL);
1063}
1064
1065static int psi_memory_open(struct inode *inode, struct file *file)
1066{
1067 return single_open(file, psi_memory_show, NULL);
1068}
1069
1070static int psi_cpu_open(struct inode *inode, struct file *file)
1071{
1072 return single_open(file, psi_cpu_show, NULL);
1073}
1074
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001075struct psi_trigger *psi_trigger_create(struct psi_group *group,
1076 char *buf, size_t nbytes, enum psi_res res)
1077{
1078 struct psi_trigger *t;
1079 enum psi_states state;
1080 u32 threshold_us;
1081 u32 window_us;
1082
1083 if (static_branch_likely(&psi_disabled))
1084 return ERR_PTR(-EOPNOTSUPP);
1085
1086 if (sscanf(buf, "some %u %u", &threshold_us, &window_us) == 2)
1087 state = PSI_IO_SOME + res * 2;
1088 else if (sscanf(buf, "full %u %u", &threshold_us, &window_us) == 2)
1089 state = PSI_IO_FULL + res * 2;
1090 else
1091 return ERR_PTR(-EINVAL);
1092
1093 if (state >= PSI_NONIDLE)
1094 return ERR_PTR(-EINVAL);
1095
1096 if (window_us < WINDOW_MIN_US ||
1097 window_us > WINDOW_MAX_US)
1098 return ERR_PTR(-EINVAL);
1099
1100 /* Check threshold */
1101 if (threshold_us == 0 || threshold_us > window_us)
1102 return ERR_PTR(-EINVAL);
1103
1104 t = kmalloc(sizeof(*t), GFP_KERNEL);
1105 if (!t)
1106 return ERR_PTR(-ENOMEM);
1107
1108 t->group = group;
1109 t->state = state;
1110 t->threshold = threshold_us * NSEC_PER_USEC;
1111 t->win.size = window_us * NSEC_PER_USEC;
1112 window_reset(&t->win, 0, 0, 0);
1113
1114 t->event = 0;
1115 t->last_event_time = 0;
1116 init_waitqueue_head(&t->event_wait);
1117 kref_init(&t->refcount);
1118
1119 mutex_lock(&group->trigger_lock);
1120
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001121 if (!rcu_access_pointer(group->poll_task)) {
1122 struct task_struct *task;
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001123
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001124 task = kthread_create(psi_poll_worker, group, "psimon");
1125 if (IS_ERR(task)) {
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001126 kfree(t);
1127 mutex_unlock(&group->trigger_lock);
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001128 return ERR_CAST(task);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001129 }
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001130 atomic_set(&group->poll_wakeup, 0);
1131 init_waitqueue_head(&group->poll_wait);
1132 wake_up_process(task);
1133 timer_setup(&group->poll_timer, poll_timer_fn, 0);
1134 rcu_assign_pointer(group->poll_task, task);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001135 }
1136
1137 list_add(&t->node, &group->triggers);
1138 group->poll_min_period = min(group->poll_min_period,
1139 div_u64(t->win.size, UPDATES_PER_WINDOW));
1140 group->nr_triggers[t->state]++;
1141 group->poll_states |= (1 << t->state);
1142
1143 mutex_unlock(&group->trigger_lock);
1144
1145 return t;
1146}
1147
1148static void psi_trigger_destroy(struct kref *ref)
1149{
1150 struct psi_trigger *t = container_of(ref, struct psi_trigger, refcount);
1151 struct psi_group *group = t->group;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001152 struct task_struct *task_to_destroy = NULL;
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001153
1154 if (static_branch_likely(&psi_disabled))
1155 return;
1156
1157 /*
1158 * Wakeup waiters to stop polling. Can happen if cgroup is deleted
1159 * from under a polling process.
1160 */
1161 wake_up_interruptible(&t->event_wait);
1162
1163 mutex_lock(&group->trigger_lock);
1164
1165 if (!list_empty(&t->node)) {
1166 struct psi_trigger *tmp;
1167 u64 period = ULLONG_MAX;
1168
1169 list_del(&t->node);
1170 group->nr_triggers[t->state]--;
1171 if (!group->nr_triggers[t->state])
1172 group->poll_states &= ~(1 << t->state);
1173 /* reset min update period for the remaining triggers */
1174 list_for_each_entry(tmp, &group->triggers, node)
1175 period = min(period, div_u64(tmp->win.size,
1176 UPDATES_PER_WINDOW));
1177 group->poll_min_period = period;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001178 /* Destroy poll_task when the last trigger is destroyed */
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001179 if (group->poll_states == 0) {
1180 group->polling_until = 0;
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001181 task_to_destroy = rcu_dereference_protected(
1182 group->poll_task,
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001183 lockdep_is_held(&group->trigger_lock));
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001184 rcu_assign_pointer(group->poll_task, NULL);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001185 }
1186 }
1187
1188 mutex_unlock(&group->trigger_lock);
1189
1190 /*
1191 * Wait for both *trigger_ptr from psi_trigger_replace and
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001192 * poll_task RCUs to complete their read-side critical sections
1193 * before destroying the trigger and optionally the poll_task
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001194 */
1195 synchronize_rcu();
1196 /*
1197 * Destroy the kworker after releasing trigger_lock to prevent a
1198 * deadlock while waiting for psi_poll_work to acquire trigger_lock
1199 */
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001200 if (task_to_destroy) {
Jason Xing7b2b55d2019-08-24 17:54:53 -07001201 /*
1202 * After the RCU grace period has expired, the worker
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001203 * can no longer be found through group->poll_task.
Jason Xing7b2b55d2019-08-24 17:54:53 -07001204 * But it might have been already scheduled before
1205 * that - deschedule it cleanly before destroying it.
1206 */
Suren Baghdasaryan461daba2020-05-28 12:54:42 -07001207 del_timer_sync(&group->poll_timer);
1208 kthread_stop(task_to_destroy);
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001209 }
1210 kfree(t);
1211}
1212
1213void psi_trigger_replace(void **trigger_ptr, struct psi_trigger *new)
1214{
1215 struct psi_trigger *old = *trigger_ptr;
1216
1217 if (static_branch_likely(&psi_disabled))
1218 return;
1219
1220 rcu_assign_pointer(*trigger_ptr, new);
1221 if (old)
1222 kref_put(&old->refcount, psi_trigger_destroy);
1223}
1224
1225__poll_t psi_trigger_poll(void **trigger_ptr,
1226 struct file *file, poll_table *wait)
1227{
1228 __poll_t ret = DEFAULT_POLLMASK;
1229 struct psi_trigger *t;
1230
1231 if (static_branch_likely(&psi_disabled))
1232 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1233
1234 rcu_read_lock();
1235
1236 t = rcu_dereference(*(void __rcu __force **)trigger_ptr);
1237 if (!t) {
1238 rcu_read_unlock();
1239 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1240 }
1241 kref_get(&t->refcount);
1242
1243 rcu_read_unlock();
1244
1245 poll_wait(file, &t->event_wait, wait);
1246
1247 if (cmpxchg(&t->event, 1, 0) == 1)
1248 ret |= EPOLLPRI;
1249
1250 kref_put(&t->refcount, psi_trigger_destroy);
1251
1252 return ret;
1253}
1254
1255static ssize_t psi_write(struct file *file, const char __user *user_buf,
1256 size_t nbytes, enum psi_res res)
1257{
1258 char buf[32];
1259 size_t buf_size;
1260 struct seq_file *seq;
1261 struct psi_trigger *new;
1262
1263 if (static_branch_likely(&psi_disabled))
1264 return -EOPNOTSUPP;
1265
Suren Baghdasaryan6fcca0f2020-02-03 13:22:16 -08001266 if (!nbytes)
1267 return -EINVAL;
1268
Miles Chen4adcdce2019-09-12 18:34:52 +08001269 buf_size = min(nbytes, sizeof(buf));
Suren Baghdasaryan0e946822019-05-14 15:41:15 -07001270 if (copy_from_user(buf, user_buf, buf_size))
1271 return -EFAULT;
1272
1273 buf[buf_size - 1] = '\0';
1274
1275 new = psi_trigger_create(&psi_system, buf, nbytes, res);
1276 if (IS_ERR(new))
1277 return PTR_ERR(new);
1278
1279 seq = file->private_data;
1280 /* Take seq->lock to protect seq->private from concurrent writes */
1281 mutex_lock(&seq->lock);
1282 psi_trigger_replace(&seq->private, new);
1283 mutex_unlock(&seq->lock);
1284
1285 return nbytes;
1286}
1287
1288static ssize_t psi_io_write(struct file *file, const char __user *user_buf,
1289 size_t nbytes, loff_t *ppos)
1290{
1291 return psi_write(file, user_buf, nbytes, PSI_IO);
1292}
1293
1294static ssize_t psi_memory_write(struct file *file, const char __user *user_buf,
1295 size_t nbytes, loff_t *ppos)
1296{
1297 return psi_write(file, user_buf, nbytes, PSI_MEM);
1298}
1299
1300static ssize_t psi_cpu_write(struct file *file, const char __user *user_buf,
1301 size_t nbytes, loff_t *ppos)
1302{
1303 return psi_write(file, user_buf, nbytes, PSI_CPU);
1304}
1305
1306static __poll_t psi_fop_poll(struct file *file, poll_table *wait)
1307{
1308 struct seq_file *seq = file->private_data;
1309
1310 return psi_trigger_poll(&seq->private, file, wait);
1311}
1312
1313static int psi_fop_release(struct inode *inode, struct file *file)
1314{
1315 struct seq_file *seq = file->private_data;
1316
1317 psi_trigger_replace(&seq->private, NULL);
1318 return single_release(inode, file);
1319}
1320
Alexey Dobriyan97a32532020-02-03 17:37:17 -08001321static const struct proc_ops psi_io_proc_ops = {
1322 .proc_open = psi_io_open,
1323 .proc_read = seq_read,
1324 .proc_lseek = seq_lseek,
1325 .proc_write = psi_io_write,
1326 .proc_poll = psi_fop_poll,
1327 .proc_release = psi_fop_release,
Johannes Weinereb414682018-10-26 15:06:27 -07001328};
1329
Alexey Dobriyan97a32532020-02-03 17:37:17 -08001330static const struct proc_ops psi_memory_proc_ops = {
1331 .proc_open = psi_memory_open,
1332 .proc_read = seq_read,
1333 .proc_lseek = seq_lseek,
1334 .proc_write = psi_memory_write,
1335 .proc_poll = psi_fop_poll,
1336 .proc_release = psi_fop_release,
Johannes Weinereb414682018-10-26 15:06:27 -07001337};
1338
Alexey Dobriyan97a32532020-02-03 17:37:17 -08001339static const struct proc_ops psi_cpu_proc_ops = {
1340 .proc_open = psi_cpu_open,
1341 .proc_read = seq_read,
1342 .proc_lseek = seq_lseek,
1343 .proc_write = psi_cpu_write,
1344 .proc_poll = psi_fop_poll,
1345 .proc_release = psi_fop_release,
Johannes Weinereb414682018-10-26 15:06:27 -07001346};
1347
1348static int __init psi_proc_init(void)
1349{
Wang Long3d817682019-12-18 20:38:18 +08001350 if (psi_enable) {
1351 proc_mkdir("pressure", NULL);
Alexey Dobriyan97a32532020-02-03 17:37:17 -08001352 proc_create("pressure/io", 0, NULL, &psi_io_proc_ops);
1353 proc_create("pressure/memory", 0, NULL, &psi_memory_proc_ops);
1354 proc_create("pressure/cpu", 0, NULL, &psi_cpu_proc_ops);
Wang Long3d817682019-12-18 20:38:18 +08001355 }
Johannes Weinereb414682018-10-26 15:06:27 -07001356 return 0;
1357}
1358module_init(psi_proc_init);