blob: ddf449fcd7cf5e2573f4494e3d67e2e4fd6ae702 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001/*
2 * Pressure stall information for CPU, memory and IO
3 *
4 * Copyright (c) 2018 Facebook, Inc.
5 * Author: Johannes Weiner <hannes@cmpxchg.org>
6 *
7 * Polling support by Suren Baghdasaryan <surenb@google.com>
8 * Copyright (c) 2018 Google, Inc.
9 *
10 * 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
130#include "../workqueue_internal.h"
131#include <linux/sched/loadavg.h>
132#include <linux/seq_file.h>
133#include <linux/proc_fs.h>
134#include <linux/seqlock.h>
135#include <linux/uaccess.h>
136#include <linux/cgroup.h>
137#include <linux/module.h>
138#include <linux/sched.h>
139#include <linux/ctype.h>
140#include <linux/file.h>
141#include <linux/poll.h>
142#include <linux/psi.h>
143#include "sched.h"
144
145static int psi_bug __read_mostly;
146
147DEFINE_STATIC_KEY_FALSE(psi_disabled);
148DEFINE_STATIC_KEY_TRUE(psi_cgroups_enabled);
149
150#ifdef CONFIG_PSI_DEFAULT_DISABLED
151static bool psi_enable;
152#else
153static bool psi_enable = true;
154#endif
155static int __init setup_psi(char *str)
156{
157 return kstrtobool(str, &psi_enable) == 0;
158}
159__setup("psi=", setup_psi);
160
161/* Running averages - we need to be higher-res than loadavg */
162#define PSI_FREQ (2*HZ+1) /* 2 sec intervals */
163#define EXP_10s 1677 /* 1/exp(2s/10s) as fixed-point */
164#define EXP_60s 1981 /* 1/exp(2s/60s) */
165#define EXP_300s 2034 /* 1/exp(2s/300s) */
166
167/* PSI trigger definitions */
168#define WINDOW_MIN_US 500000 /* Min window size is 500ms */
169#define WINDOW_MAX_US 10000000 /* Max window size is 10s */
170#define UPDATES_PER_WINDOW 10 /* 10 updates per window */
171
172/* Sampling frequency in nanoseconds */
173static u64 psi_period __read_mostly;
174
175/* System-level pressure and stall tracking */
176static DEFINE_PER_CPU(struct psi_group_cpu, system_group_pcpu);
177struct psi_group psi_system = {
178 .pcpu = &system_group_pcpu,
179};
180
181static void psi_avgs_work(struct work_struct *work);
182
183static void poll_timer_fn(struct timer_list *t);
184
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);
191 group->avg_last_update = sched_clock();
192 group->avg_next_update = group->avg_last_update + psi_period;
193 INIT_DELAYED_WORK(&group->avgs_work, psi_avgs_work);
194 mutex_init(&group->avgs_lock);
195 /* Init trigger-related members */
196 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;
204 init_waitqueue_head(&group->poll_wait);
205 timer_setup(&group->poll_timer, poll_timer_fn, 0);
206 rcu_assign_pointer(group->poll_task, NULL);
207}
208
209void __init psi_init(void)
210{
211 if (!psi_enable) {
212 static_branch_enable(&psi_disabled);
213 return;
214 }
215
216 if (!cgroup_psi_enabled())
217 static_branch_disable(&psi_cgroups_enabled);
218
219 psi_period = jiffies_to_nsecs(PSI_FREQ);
220 group_init(&psi_system);
221}
222
223static bool test_state(unsigned int *tasks, enum psi_states state)
224{
225 switch (state) {
226 case PSI_IO_SOME:
227 return tasks[NR_IOWAIT];
228 case PSI_IO_FULL:
229 return tasks[NR_IOWAIT] && !tasks[NR_RUNNING];
230 case PSI_MEM_SOME:
231 return tasks[NR_MEMSTALL];
232 case PSI_MEM_FULL:
233 return tasks[NR_MEMSTALL] && !tasks[NR_RUNNING];
234 case PSI_CPU_SOME:
235 return tasks[NR_RUNNING] > 1;
236 case PSI_NONIDLE:
237 return tasks[NR_IOWAIT] || tasks[NR_MEMSTALL] ||
238 tasks[NR_RUNNING];
239 default:
240 return false;
241 }
242}
243
244static void get_recent_times(struct psi_group *group, int cpu,
245 enum psi_aggregators aggregator, u32 *times,
246 u32 *pchanged_states)
247{
248 struct psi_group_cpu *groupc = per_cpu_ptr(group->pcpu, cpu);
249 u64 now, state_start;
250 enum psi_states s;
251 unsigned int seq;
252 u32 state_mask;
253
254 *pchanged_states = 0;
255
256 /* Snapshot a coherent view of the CPU state */
257 do {
258 seq = read_seqcount_begin(&groupc->seq);
259 now = cpu_clock(cpu);
260 memcpy(times, groupc->times, sizeof(groupc->times));
261 state_mask = groupc->state_mask;
262 state_start = groupc->state_start;
263 } while (read_seqcount_retry(&groupc->seq, seq));
264
265 /* Calculate state time deltas against the previous snapshot */
266 for (s = 0; s < NR_PSI_STATES; s++) {
267 u32 delta;
268 /*
269 * In addition to already concluded states, we also
270 * incorporate currently active states on the CPU,
271 * since states may last for many sampling periods.
272 *
273 * This way we keep our delta sampling buckets small
274 * (u32) and our reported pressure close to what's
275 * actually happening.
276 */
277 if (state_mask & (1 << s))
278 times[s] += now - state_start;
279
280 delta = times[s] - groupc->times_prev[aggregator][s];
281 groupc->times_prev[aggregator][s] = times[s];
282
283 times[s] = delta;
284 if (delta)
285 *pchanged_states |= (1 << s);
286 }
287}
288
289static void calc_avgs(unsigned long avg[3], int missed_periods,
290 u64 time, u64 period)
291{
292 unsigned long pct;
293
294 /* Fill in zeroes for periods of no activity */
295 if (missed_periods) {
296 avg[0] = calc_load_n(avg[0], EXP_10s, 0, missed_periods);
297 avg[1] = calc_load_n(avg[1], EXP_60s, 0, missed_periods);
298 avg[2] = calc_load_n(avg[2], EXP_300s, 0, missed_periods);
299 }
300
301 /* Sample the most recent active period */
302 pct = div_u64(time * 100, period);
303 pct *= FIXED_1;
304 avg[0] = calc_load(avg[0], EXP_10s, pct);
305 avg[1] = calc_load(avg[1], EXP_60s, pct);
306 avg[2] = calc_load(avg[2], EXP_300s, pct);
307}
308
309static void collect_percpu_times(struct psi_group *group,
310 enum psi_aggregators aggregator,
311 u32 *pchanged_states)
312{
313 u64 deltas[NR_PSI_STATES - 1] = { 0, };
314 unsigned long nonidle_total = 0;
315 u32 changed_states = 0;
316 int cpu;
317 int s;
318
319 /*
320 * Collect the per-cpu time buckets and average them into a
321 * single time sample that is normalized to wallclock time.
322 *
323 * For averaging, each CPU is weighted by its non-idle time in
324 * the sampling period. This eliminates artifacts from uneven
325 * loading, or even entirely idle CPUs.
326 */
327 for_each_possible_cpu(cpu) {
328 u32 times[NR_PSI_STATES];
329 u32 nonidle;
330 u32 cpu_changed_states;
331
332 get_recent_times(group, cpu, aggregator, times,
333 &cpu_changed_states);
334 changed_states |= cpu_changed_states;
335
336 nonidle = nsecs_to_jiffies(times[PSI_NONIDLE]);
337 nonidle_total += nonidle;
338
339 for (s = 0; s < PSI_NONIDLE; s++)
340 deltas[s] += (u64)times[s] * nonidle;
341 }
342
343 /*
344 * Integrate the sample into the running statistics that are
345 * reported to userspace: the cumulative stall times and the
346 * decaying averages.
347 *
348 * Pressure percentages are sampled at PSI_FREQ. We might be
349 * called more often when the user polls more frequently than
350 * that; we might be called less often when there is no task
351 * activity, thus no data, and clock ticks are sporadic. The
352 * below handles both.
353 */
354
355 /* total= */
356 for (s = 0; s < NR_PSI_STATES - 1; s++)
357 group->total[aggregator][s] +=
358 div_u64(deltas[s], max(nonidle_total, 1UL));
359
360 if (pchanged_states)
361 *pchanged_states = changed_states;
362}
363
364static u64 update_averages(struct psi_group *group, u64 now)
365{
366 unsigned long missed_periods = 0;
367 u64 expires, period;
368 u64 avg_next_update;
369 int s;
370
371 /* avgX= */
372 expires = group->avg_next_update;
373 if (now - expires >= psi_period)
374 missed_periods = div_u64(now - expires, psi_period);
375
376 /*
377 * The periodic clock tick can get delayed for various
378 * reasons, especially on loaded systems. To avoid clock
379 * drift, we schedule the clock in fixed psi_period intervals.
380 * But the deltas we sample out of the per-cpu buckets above
381 * are based on the actual time elapsing between clock ticks.
382 */
383 avg_next_update = expires + ((1 + missed_periods) * psi_period);
384 period = now - (group->avg_last_update + (missed_periods * psi_period));
385 group->avg_last_update = now;
386
387 for (s = 0; s < NR_PSI_STATES - 1; s++) {
388 u32 sample;
389
390 sample = group->total[PSI_AVGS][s] - group->avg_total[s];
391 /*
392 * Due to the lockless sampling of the time buckets,
393 * recorded time deltas can slip into the next period,
394 * which under full pressure can result in samples in
395 * excess of the period length.
396 *
397 * We don't want to report non-sensical pressures in
398 * excess of 100%, nor do we want to drop such events
399 * on the floor. Instead we punt any overage into the
400 * future until pressure subsides. By doing this we
401 * don't underreport the occurring pressure curve, we
402 * just report it delayed by one period length.
403 *
404 * The error isn't cumulative. As soon as another
405 * delta slips from a period P to P+1, by definition
406 * it frees up its time T in P.
407 */
408 if (sample > period)
409 sample = period;
410 group->avg_total[s] += sample;
411 calc_avgs(group->avg[s], missed_periods, sample, period);
412 }
413
414 return avg_next_update;
415}
416
417static void psi_avgs_work(struct work_struct *work)
418{
419 struct delayed_work *dwork;
420 struct psi_group *group;
421 u32 changed_states;
422 bool nonidle;
423 u64 now;
424
425 dwork = to_delayed_work(work);
426 group = container_of(dwork, struct psi_group, avgs_work);
427
428 mutex_lock(&group->avgs_lock);
429
430 now = sched_clock();
431
432 collect_percpu_times(group, PSI_AVGS, &changed_states);
433 nonidle = changed_states & (1 << PSI_NONIDLE);
434 /*
435 * If there is task activity, periodically fold the per-cpu
436 * times and feed samples into the running averages. If things
437 * are idle and there is no data to process, stop the clock.
438 * Once restarted, we'll catch up the running averages in one
439 * go - see calc_avgs() and missed_periods.
440 */
441 if (now >= group->avg_next_update)
442 group->avg_next_update = update_averages(group, now);
443
444 if (nonidle) {
445 schedule_delayed_work(dwork, nsecs_to_jiffies(
446 group->avg_next_update - now) + 1);
447 }
448
449 mutex_unlock(&group->avgs_lock);
450}
451
452/* Trigger tracking window manupulations */
453static void window_reset(struct psi_window *win, u64 now, u64 value,
454 u64 prev_growth)
455{
456 win->start_time = now;
457 win->start_value = value;
458 win->prev_growth = prev_growth;
459}
460
461/*
462 * PSI growth tracking window update and growth calculation routine.
463 *
464 * This approximates a sliding tracking window by interpolating
465 * partially elapsed windows using historical growth data from the
466 * previous intervals. This minimizes memory requirements (by not storing
467 * all the intermediate values in the previous window) and simplifies
468 * the calculations. It works well because PSI signal changes only in
469 * positive direction and over relatively small window sizes the growth
470 * is close to linear.
471 */
472static u64 window_update(struct psi_window *win, u64 now, u64 value)
473{
474 u64 elapsed;
475 u64 growth;
476
477 elapsed = now - win->start_time;
478 growth = value - win->start_value;
479 /*
480 * After each tracking window passes win->start_value and
481 * win->start_time get reset and win->prev_growth stores
482 * the average per-window growth of the previous window.
483 * win->prev_growth is then used to interpolate additional
484 * growth from the previous window assuming it was linear.
485 */
486 if (elapsed > win->size)
487 window_reset(win, now, value, growth);
488 else {
489 u32 remaining;
490
491 remaining = win->size - elapsed;
492 growth += div64_u64(win->prev_growth * remaining, win->size);
493 }
494
495 return growth;
496}
497
498static void init_triggers(struct psi_group *group, u64 now)
499{
500 struct psi_trigger *t;
501
502 list_for_each_entry(t, &group->triggers, node)
503 window_reset(&t->win, now,
504 group->total[PSI_POLL][t->state], 0);
505 memcpy(group->polling_total, group->total[PSI_POLL],
506 sizeof(group->polling_total));
507 group->polling_next_update = now + group->poll_min_period;
508}
509
510static u64 update_triggers(struct psi_group *group, u64 now)
511{
512 struct psi_trigger *t;
513 bool new_stall = false;
514 u64 *total = group->total[PSI_POLL];
515
516 /*
517 * On subsequent updates, calculate growth deltas and let
518 * watchers know when their specified thresholds are exceeded.
519 */
520 list_for_each_entry(t, &group->triggers, node) {
521 u64 growth;
522
523 /* Check for stall activity */
524 if (group->polling_total[t->state] == total[t->state])
525 continue;
526
527 /*
528 * Multiple triggers might be looking at the same state,
529 * remember to update group->polling_total[] once we've
530 * been through all of them. Also remember to extend the
531 * polling time if we see new stall activity.
532 */
533 new_stall = true;
534
535 /* Calculate growth since last update */
536 growth = window_update(&t->win, now, total[t->state]);
537 if (growth < t->threshold)
538 continue;
539
540 /* Limit event signaling to once per window */
541 if (now < t->last_event_time + t->win.size)
542 continue;
543
544 /* Generate an event */
545 if (cmpxchg(&t->event, 0, 1) == 0)
546 wake_up_interruptible(&t->event_wait);
547 t->last_event_time = now;
548 }
549
550 if (new_stall)
551 memcpy(group->polling_total, total,
552 sizeof(group->polling_total));
553
554 return now + group->poll_min_period;
555}
556
557/* Schedule polling if it's not already scheduled. */
558static void psi_schedule_poll_work(struct psi_group *group, unsigned long delay)
559{
560 struct task_struct *task;
561
562 /*
563 * Do not reschedule if already scheduled.
564 * Possible race with a timer scheduled after this check but before
565 * mod_timer below can be tolerated because group->polling_next_update
566 * will keep updates on schedule.
567 */
568 if (timer_pending(&group->poll_timer))
569 return;
570
571 rcu_read_lock();
572
573 task = rcu_dereference(group->poll_task);
574 /*
575 * kworker might be NULL in case psi_trigger_destroy races with
576 * psi_task_change (hotpath) which can't use locks
577 */
578 if (likely(task))
579 mod_timer(&group->poll_timer, jiffies + delay);
580
581 rcu_read_unlock();
582}
583
584static void psi_poll_work(struct psi_group *group)
585{
586 u32 changed_states;
587 u64 now;
588
589 mutex_lock(&group->trigger_lock);
590
591 now = sched_clock();
592
593 collect_percpu_times(group, PSI_POLL, &changed_states);
594
595 if (changed_states & group->poll_states) {
596 /* Initialize trigger windows when entering polling mode */
597 if (now > group->polling_until)
598 init_triggers(group, now);
599
600 /*
601 * Keep the monitor active for at least the duration of the
602 * minimum tracking window as long as monitor states are
603 * changing.
604 */
605 group->polling_until = now +
606 group->poll_min_period * UPDATES_PER_WINDOW;
607 }
608
609 if (now > group->polling_until) {
610 group->polling_next_update = ULLONG_MAX;
611 goto out;
612 }
613
614 if (now >= group->polling_next_update)
615 group->polling_next_update = update_triggers(group, now);
616
617 psi_schedule_poll_work(group,
618 nsecs_to_jiffies(group->polling_next_update - now) + 1);
619
620out:
621 mutex_unlock(&group->trigger_lock);
622}
623
624static int psi_poll_worker(void *data)
625{
626 struct psi_group *group = (struct psi_group *)data;
627 struct sched_param param = {
628 .sched_priority = 1,
629 };
630
631 sched_setscheduler_nocheck(current, SCHED_FIFO, &param);
632
633 while (true) {
634 wait_event_interruptible(group->poll_wait,
635 atomic_cmpxchg(&group->poll_wakeup, 1, 0) ||
636 kthread_should_stop());
637 if (kthread_should_stop())
638 break;
639
640 psi_poll_work(group);
641 }
642 return 0;
643}
644
645static void poll_timer_fn(struct timer_list *t)
646{
647 struct psi_group *group = from_timer(group, t, poll_timer);
648
649 atomic_set(&group->poll_wakeup, 1);
650 wake_up_interruptible(&group->poll_wait);
651}
652
653static void record_times(struct psi_group_cpu *groupc, int cpu,
654 bool memstall_tick)
655{
656 u32 delta;
657 u64 now;
658
659 now = cpu_clock(cpu);
660 delta = now - groupc->state_start;
661 groupc->state_start = now;
662
663 if (groupc->state_mask & (1 << PSI_IO_SOME)) {
664 groupc->times[PSI_IO_SOME] += delta;
665 if (groupc->state_mask & (1 << PSI_IO_FULL))
666 groupc->times[PSI_IO_FULL] += delta;
667 }
668
669 if (groupc->state_mask & (1 << PSI_MEM_SOME)) {
670 groupc->times[PSI_MEM_SOME] += delta;
671 if (groupc->state_mask & (1 << PSI_MEM_FULL))
672 groupc->times[PSI_MEM_FULL] += delta;
673 else if (memstall_tick) {
674 u32 sample;
675 /*
676 * Since we care about lost potential, a
677 * memstall is FULL when there are no other
678 * working tasks, but also when the CPU is
679 * actively reclaiming and nothing productive
680 * could run even if it were runnable.
681 *
682 * When the timer tick sees a reclaiming CPU,
683 * regardless of runnable tasks, sample a FULL
684 * tick (or less if it hasn't been a full tick
685 * since the last state change).
686 */
687 sample = min(delta, (u32)jiffies_to_nsecs(1));
688 groupc->times[PSI_MEM_FULL] += sample;
689 }
690 }
691
692 if (groupc->state_mask & (1 << PSI_CPU_SOME))
693 groupc->times[PSI_CPU_SOME] += delta;
694
695 if (groupc->state_mask & (1 << PSI_NONIDLE))
696 groupc->times[PSI_NONIDLE] += delta;
697}
698
699static u32 psi_group_change(struct psi_group *group, int cpu,
700 unsigned int clear, unsigned int set)
701{
702 struct psi_group_cpu *groupc;
703 unsigned int t, m;
704 enum psi_states s;
705 u32 state_mask = 0;
706
707 groupc = per_cpu_ptr(group->pcpu, cpu);
708
709 /*
710 * First we assess the aggregate resource states this CPU's
711 * tasks have been in since the last change, and account any
712 * SOME and FULL time these may have resulted in.
713 *
714 * Then we update the task counts according to the state
715 * change requested through the @clear and @set bits.
716 */
717 write_seqcount_begin(&groupc->seq);
718
719 record_times(groupc, cpu, false);
720
721 for (t = 0, m = clear; m; m &= ~(1 << t), t++) {
722 if (!(m & (1 << t)))
723 continue;
724 if (groupc->tasks[t] == 0 && !psi_bug) {
725 printk_deferred(KERN_ERR "psi: task underflow! cpu=%d t=%d tasks=[%u %u %u] clear=%x set=%x\n",
726 cpu, t, groupc->tasks[0],
727 groupc->tasks[1], groupc->tasks[2],
728 clear, set);
729 psi_bug = 1;
730 }
731 groupc->tasks[t]--;
732 }
733
734 for (t = 0; set; set &= ~(1 << t), t++)
735 if (set & (1 << t))
736 groupc->tasks[t]++;
737
738 /* Calculate state mask representing active states */
739 for (s = 0; s < NR_PSI_STATES; s++) {
740 if (test_state(groupc->tasks, s))
741 state_mask |= (1 << s);
742 }
743 groupc->state_mask = state_mask;
744
745 write_seqcount_end(&groupc->seq);
746
747 return state_mask;
748}
749
750static struct psi_group *iterate_groups(struct task_struct *task, void **iter)
751{
752 if (*iter == &psi_system)
753 return NULL;
754
755#ifdef CONFIG_CGROUPS
756 if (static_branch_likely(&psi_cgroups_enabled)) {
757 struct cgroup *cgroup = NULL;
758
759 if (!*iter)
760 cgroup = task->cgroups->dfl_cgrp;
761 else
762 cgroup = cgroup_parent(*iter);
763
764 if (cgroup && cgroup_parent(cgroup)) {
765 *iter = cgroup;
766 return cgroup_psi(cgroup);
767 }
768 }
769#endif
770 *iter = &psi_system;
771 return &psi_system;
772}
773
774void psi_task_change(struct task_struct *task, int clear, int set)
775{
776 int cpu = task_cpu(task);
777 struct psi_group *group;
778 bool wake_clock = true;
779 void *iter = NULL;
780
781 if (!task->pid)
782 return;
783
784 if (((task->psi_flags & set) ||
785 (task->psi_flags & clear) != clear) &&
786 !psi_bug) {
787 printk_deferred(KERN_ERR "psi: inconsistent task state! task=%d:%s cpu=%d psi_flags=%x clear=%x set=%x\n",
788 task->pid, task->comm, cpu,
789 task->psi_flags, clear, set);
790 psi_bug = 1;
791 }
792
793 task->psi_flags &= ~clear;
794 task->psi_flags |= set;
795
796 /*
797 * Periodic aggregation shuts off if there is a period of no
798 * task changes, so we wake it back up if necessary. However,
799 * don't do this if the task change is the aggregation worker
800 * itself going to sleep, or we'll ping-pong forever.
801 */
802 if (unlikely((clear & TSK_RUNNING) &&
803 (task->flags & PF_WQ_WORKER) &&
804 wq_worker_last_func(task) == psi_avgs_work))
805 wake_clock = false;
806
807 while ((group = iterate_groups(task, &iter))) {
808 u32 state_mask = psi_group_change(group, cpu, clear, set);
809
810 if (state_mask & group->poll_states)
811 psi_schedule_poll_work(group, 1);
812
813 if (wake_clock && !delayed_work_pending(&group->avgs_work))
814 schedule_delayed_work(&group->avgs_work, PSI_FREQ);
815 }
816}
817
818void psi_memstall_tick(struct task_struct *task, int cpu)
819{
820 struct psi_group *group;
821 void *iter = NULL;
822
823 while ((group = iterate_groups(task, &iter))) {
824 struct psi_group_cpu *groupc;
825
826 groupc = per_cpu_ptr(group->pcpu, cpu);
827 write_seqcount_begin(&groupc->seq);
828 record_times(groupc, cpu, true);
829 write_seqcount_end(&groupc->seq);
830 }
831}
832
833/**
834 * psi_memstall_enter - mark the beginning of a memory stall section
835 * @flags: flags to handle nested sections
836 *
837 * Marks the calling task as being stalled due to a lack of memory,
838 * such as waiting for a refault or performing reclaim.
839 */
840void psi_memstall_enter(unsigned long *flags)
841{
842 struct rq_flags rf;
843 struct rq *rq;
844
845 if (static_branch_likely(&psi_disabled))
846 return;
847
848 *flags = current->flags & PF_MEMSTALL;
849 if (*flags)
850 return;
851 /*
852 * PF_MEMSTALL setting & accounting needs to be atomic wrt
853 * changes to the task's scheduling state, otherwise we can
854 * race with CPU migration.
855 */
856 rq = this_rq_lock_irq(&rf);
857
858 current->flags |= PF_MEMSTALL;
859 psi_task_change(current, 0, TSK_MEMSTALL);
860
861 rq_unlock_irq(rq, &rf);
862}
863
864/**
865 * psi_memstall_leave - mark the end of an memory stall section
866 * @flags: flags to handle nested memdelay sections
867 *
868 * Marks the calling task as no longer stalled due to lack of memory.
869 */
870void psi_memstall_leave(unsigned long *flags)
871{
872 struct rq_flags rf;
873 struct rq *rq;
874
875 if (static_branch_likely(&psi_disabled))
876 return;
877
878 if (*flags)
879 return;
880 /*
881 * PF_MEMSTALL clearing & accounting needs to be atomic wrt
882 * changes to the task's scheduling state, otherwise we could
883 * race with CPU migration.
884 */
885 rq = this_rq_lock_irq(&rf);
886
887 current->flags &= ~PF_MEMSTALL;
888 psi_task_change(current, TSK_MEMSTALL, 0);
889
890 rq_unlock_irq(rq, &rf);
891}
892
893#ifdef CONFIG_CGROUPS
894int psi_cgroup_alloc(struct cgroup *cgroup)
895{
896 if (static_branch_likely(&psi_disabled))
897 return 0;
898
899 cgroup->psi.pcpu = alloc_percpu(struct psi_group_cpu);
900 if (!cgroup->psi.pcpu)
901 return -ENOMEM;
902 group_init(&cgroup->psi);
903 return 0;
904}
905
906void psi_cgroup_free(struct cgroup *cgroup)
907{
908 if (static_branch_likely(&psi_disabled))
909 return;
910
911 cancel_delayed_work_sync(&cgroup->psi.avgs_work);
912 free_percpu(cgroup->psi.pcpu);
913 /* All triggers must be removed by now */
914 WARN_ONCE(cgroup->psi.poll_states, "psi: trigger leak\n");
915}
916
917/**
918 * cgroup_move_task - move task to a different cgroup
919 * @task: the task
920 * @to: the target css_set
921 *
922 * Move task to a new cgroup and safely migrate its associated stall
923 * state between the different groups.
924 *
925 * This function acquires the task's rq lock to lock out concurrent
926 * changes to the task's scheduling state and - in case the task is
927 * running - concurrent changes to its stall state.
928 */
929void cgroup_move_task(struct task_struct *task, struct css_set *to)
930{
931 unsigned int task_flags = 0;
932 struct rq_flags rf;
933 struct rq *rq;
934
935 if (static_branch_likely(&psi_disabled)) {
936 /*
937 * Lame to do this here, but the scheduler cannot be locked
938 * from the outside, so we move cgroups from inside sched/.
939 */
940 rcu_assign_pointer(task->cgroups, to);
941 return;
942 }
943
944 rq = task_rq_lock(task, &rf);
945
946 if (task_on_rq_queued(task))
947 task_flags = TSK_RUNNING;
948 else if (task->in_iowait)
949 task_flags = TSK_IOWAIT;
950
951 if (task->flags & PF_MEMSTALL)
952 task_flags |= TSK_MEMSTALL;
953
954 if (task_flags)
955 psi_task_change(task, task_flags, 0);
956
957 /* See comment above */
958 rcu_assign_pointer(task->cgroups, to);
959
960 if (task_flags)
961 psi_task_change(task, 0, task_flags);
962
963 task_rq_unlock(rq, task, &rf);
964}
965#endif /* CONFIG_CGROUPS */
966
967int psi_show(struct seq_file *m, struct psi_group *group, enum psi_res res)
968{
969 int full;
970 u64 now;
971
972 if (static_branch_likely(&psi_disabled))
973 return -EOPNOTSUPP;
974
975 /* Update averages before reporting them */
976 mutex_lock(&group->avgs_lock);
977 now = sched_clock();
978 collect_percpu_times(group, PSI_AVGS, NULL);
979 if (now >= group->avg_next_update)
980 group->avg_next_update = update_averages(group, now);
981 mutex_unlock(&group->avgs_lock);
982
983 for (full = 0; full < 2 - (res == PSI_CPU); full++) {
984 unsigned long avg[3];
985 u64 total;
986 int w;
987
988 for (w = 0; w < 3; w++)
989 avg[w] = group->avg[res * 2 + full][w];
990 total = div_u64(group->total[PSI_AVGS][res * 2 + full],
991 NSEC_PER_USEC);
992
993 seq_printf(m, "%s avg10=%lu.%02lu avg60=%lu.%02lu avg300=%lu.%02lu total=%llu\n",
994 full ? "full" : "some",
995 LOAD_INT(avg[0]), LOAD_FRAC(avg[0]),
996 LOAD_INT(avg[1]), LOAD_FRAC(avg[1]),
997 LOAD_INT(avg[2]), LOAD_FRAC(avg[2]),
998 total);
999 }
1000
1001 return 0;
1002}
1003
1004static int psi_io_show(struct seq_file *m, void *v)
1005{
1006 return psi_show(m, &psi_system, PSI_IO);
1007}
1008
1009static int psi_memory_show(struct seq_file *m, void *v)
1010{
1011 return psi_show(m, &psi_system, PSI_MEM);
1012}
1013
1014static int psi_cpu_show(struct seq_file *m, void *v)
1015{
1016 return psi_show(m, &psi_system, PSI_CPU);
1017}
1018
1019static int psi_io_open(struct inode *inode, struct file *file)
1020{
1021 return single_open(file, psi_io_show, NULL);
1022}
1023
1024static int psi_memory_open(struct inode *inode, struct file *file)
1025{
1026 return single_open(file, psi_memory_show, NULL);
1027}
1028
1029static int psi_cpu_open(struct inode *inode, struct file *file)
1030{
1031 return single_open(file, psi_cpu_show, NULL);
1032}
1033
1034struct psi_trigger *psi_trigger_create(struct psi_group *group,
1035 char *buf, size_t nbytes, enum psi_res res)
1036{
1037 struct psi_trigger *t;
1038 enum psi_states state;
1039 u32 threshold_us;
1040 u32 window_us;
1041
1042 if (static_branch_likely(&psi_disabled))
1043 return ERR_PTR(-EOPNOTSUPP);
1044
1045 if (sscanf(buf, "some %u %u", &threshold_us, &window_us) == 2)
1046 state = PSI_IO_SOME + res * 2;
1047 else if (sscanf(buf, "full %u %u", &threshold_us, &window_us) == 2)
1048 state = PSI_IO_FULL + res * 2;
1049 else
1050 return ERR_PTR(-EINVAL);
1051
1052 if (state >= PSI_NONIDLE)
1053 return ERR_PTR(-EINVAL);
1054
1055 if (window_us < WINDOW_MIN_US ||
1056 window_us > WINDOW_MAX_US)
1057 return ERR_PTR(-EINVAL);
1058
1059 /* Check threshold */
1060 if (threshold_us == 0 || threshold_us > window_us)
1061 return ERR_PTR(-EINVAL);
1062
1063 t = kmalloc(sizeof(*t), GFP_KERNEL);
1064 if (!t)
1065 return ERR_PTR(-ENOMEM);
1066
1067 t->group = group;
1068 t->state = state;
1069 t->threshold = threshold_us * NSEC_PER_USEC;
1070 t->win.size = window_us * NSEC_PER_USEC;
1071 window_reset(&t->win, 0, 0, 0);
1072
1073 t->event = 0;
1074 t->last_event_time = 0;
1075 init_waitqueue_head(&t->event_wait);
1076
1077 mutex_lock(&group->trigger_lock);
1078
1079 if (!rcu_access_pointer(group->poll_task)) {
1080 struct task_struct *task;
1081
1082 task = kthread_create(psi_poll_worker, group, "psimon");
1083 if (IS_ERR(task)) {
1084 kfree(t);
1085 mutex_unlock(&group->trigger_lock);
1086 return ERR_CAST(task);
1087 }
1088 atomic_set(&group->poll_wakeup, 0);
1089 wake_up_process(task);
1090 rcu_assign_pointer(group->poll_task, task);
1091 }
1092
1093 list_add(&t->node, &group->triggers);
1094 group->poll_min_period = min(group->poll_min_period,
1095 div_u64(t->win.size, UPDATES_PER_WINDOW));
1096 group->nr_triggers[t->state]++;
1097 group->poll_states |= (1 << t->state);
1098
1099 mutex_unlock(&group->trigger_lock);
1100
1101 return t;
1102}
1103
1104void psi_trigger_destroy(struct psi_trigger *t)
1105{
1106 struct psi_group *group;
1107 struct task_struct *task_to_destroy = NULL;
1108
1109 /*
1110 * We do not check psi_disabled since it might have been disabled after
1111 * the trigger got created.
1112 */
1113 if (!t)
1114 return;
1115
1116 group = t->group;
1117 /*
1118 * Wakeup waiters to stop polling and clear the queue to prevent it from
1119 * being accessed later. Can happen if cgroup is deleted from under a
1120 * polling process.
1121 */
1122 wake_up_pollfree(&t->event_wait);
1123
1124 mutex_lock(&group->trigger_lock);
1125
1126 if (!list_empty(&t->node)) {
1127 struct psi_trigger *tmp;
1128 u64 period = ULLONG_MAX;
1129
1130 list_del(&t->node);
1131 group->nr_triggers[t->state]--;
1132 if (!group->nr_triggers[t->state])
1133 group->poll_states &= ~(1 << t->state);
1134 /* reset min update period for the remaining triggers */
1135 list_for_each_entry(tmp, &group->triggers, node)
1136 period = min(period, div_u64(tmp->win.size,
1137 UPDATES_PER_WINDOW));
1138 group->poll_min_period = period;
1139 /* Destroy poll_task when the last trigger is destroyed */
1140 if (group->poll_states == 0) {
1141 group->polling_until = 0;
1142 task_to_destroy = rcu_dereference_protected(
1143 group->poll_task,
1144 lockdep_is_held(&group->trigger_lock));
1145 rcu_assign_pointer(group->poll_task, NULL);
1146 del_timer(&group->poll_timer);
1147 }
1148 }
1149
1150 mutex_unlock(&group->trigger_lock);
1151
1152 /*
1153 * Wait for psi_schedule_poll_work RCU to complete its read-side
1154 * critical section before destroying the trigger and optionally the
1155 * poll_task.
1156 */
1157 synchronize_rcu();
1158 /*
1159 * Stop kthread 'psimon' after releasing trigger_lock to prevent a
1160 * deadlock while waiting for psi_poll_work to acquire trigger_lock
1161 */
1162 if (task_to_destroy) {
1163 /*
1164 * After the RCU grace period has expired, the worker
1165 * can no longer be found through group->poll_task.
1166 */
1167 kthread_stop(task_to_destroy);
1168 }
1169 kfree(t);
1170}
1171
1172__poll_t psi_trigger_poll(void **trigger_ptr,
1173 struct file *file, poll_table *wait)
1174{
1175 __poll_t ret = DEFAULT_POLLMASK;
1176 struct psi_trigger *t;
1177
1178 if (static_branch_likely(&psi_disabled))
1179 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1180 t = smp_load_acquire(trigger_ptr);
1181 if (!t)
1182 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1183
1184 poll_wait(file, &t->event_wait, wait);
1185
1186 if (cmpxchg(&t->event, 1, 0) == 1)
1187 ret |= EPOLLPRI;
1188
1189 return ret;
1190}
1191
1192static ssize_t psi_write(struct file *file, const char __user *user_buf,
1193 size_t nbytes, enum psi_res res)
1194{
1195 char buf[32];
1196 size_t buf_size;
1197 struct seq_file *seq;
1198 struct psi_trigger *new;
1199
1200 if (static_branch_likely(&psi_disabled))
1201 return -EOPNOTSUPP;
1202
1203 if (!nbytes)
1204 return -EINVAL;
1205
1206 buf_size = min(nbytes, sizeof(buf));
1207 if (copy_from_user(buf, user_buf, buf_size))
1208 return -EFAULT;
1209
1210 buf[buf_size - 1] = '\0';
1211
1212 seq = file->private_data;
1213
1214 /* Take seq->lock to protect seq->private from concurrent writes */
1215 mutex_lock(&seq->lock);
1216
1217 /* Allow only one trigger per file descriptor */
1218 if (seq->private) {
1219 mutex_unlock(&seq->lock);
1220 return -EBUSY;
1221 }
1222
1223 new = psi_trigger_create(&psi_system, buf, nbytes, res);
1224 if (IS_ERR(new)) {
1225 mutex_unlock(&seq->lock);
1226 return PTR_ERR(new);
1227 }
1228
1229 smp_store_release(&seq->private, new);
1230 mutex_unlock(&seq->lock);
1231
1232 return nbytes;
1233}
1234
1235static ssize_t psi_io_write(struct file *file, const char __user *user_buf,
1236 size_t nbytes, loff_t *ppos)
1237{
1238 return psi_write(file, user_buf, nbytes, PSI_IO);
1239}
1240
1241static ssize_t psi_memory_write(struct file *file, const char __user *user_buf,
1242 size_t nbytes, loff_t *ppos)
1243{
1244 return psi_write(file, user_buf, nbytes, PSI_MEM);
1245}
1246
1247static ssize_t psi_cpu_write(struct file *file, const char __user *user_buf,
1248 size_t nbytes, loff_t *ppos)
1249{
1250 return psi_write(file, user_buf, nbytes, PSI_CPU);
1251}
1252
1253static __poll_t psi_fop_poll(struct file *file, poll_table *wait)
1254{
1255 struct seq_file *seq = file->private_data;
1256
1257 return psi_trigger_poll(&seq->private, file, wait);
1258}
1259
1260static int psi_fop_release(struct inode *inode, struct file *file)
1261{
1262 struct seq_file *seq = file->private_data;
1263
1264 psi_trigger_destroy(seq->private);
1265 return single_release(inode, file);
1266}
1267
1268static const struct file_operations psi_io_fops = {
1269 .open = psi_io_open,
1270 .read = seq_read,
1271 .llseek = seq_lseek,
1272 .write = psi_io_write,
1273 .poll = psi_fop_poll,
1274 .release = psi_fop_release,
1275};
1276
1277static const struct file_operations psi_memory_fops = {
1278 .open = psi_memory_open,
1279 .read = seq_read,
1280 .llseek = seq_lseek,
1281 .write = psi_memory_write,
1282 .poll = psi_fop_poll,
1283 .release = psi_fop_release,
1284};
1285
1286static const struct file_operations psi_cpu_fops = {
1287 .open = psi_cpu_open,
1288 .read = seq_read,
1289 .llseek = seq_lseek,
1290 .write = psi_cpu_write,
1291 .poll = psi_fop_poll,
1292 .release = psi_fop_release,
1293};
1294
1295static int __init psi_proc_init(void)
1296{
1297 proc_mkdir("pressure", NULL);
1298 proc_create("pressure/io", 0, NULL, &psi_io_fops);
1299 proc_create("pressure/memory", 0, NULL, &psi_memory_fops);
1300 proc_create("pressure/cpu", 0, NULL, &psi_cpu_fops);
1301 return 0;
1302}
1303module_init(psi_proc_init);