1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Pressure stall information for CPU, memory and IO
4 *
5 * Copyright (c) 2018 Facebook, Inc.
6 * Author: Johannes Weiner <hannes@cmpxchg.org>
7 *
8 * Polling support by Suren Baghdasaryan <surenb@google.com>
9 * Copyright (c) 2018 Google, Inc.
10 *
11 * When CPU, memory and IO are contended, tasks experience delays that
12 * reduce throughput and introduce latencies into the workload. Memory
13 * and IO contention, in addition, can cause a full loss of forward
14 * progress in which the CPU goes idle.
15 *
16 * This code aggregates individual task delays into resource pressure
17 * metrics that indicate problems with both workload health and
18 * resource utilization.
19 *
20 * Model
21 *
22 * The time in which a task can execute on a CPU is our baseline for
23 * productivity. Pressure expresses the amount of time in which this
24 * potential cannot be realized due to resource contention.
25 *
26 * This concept of productivity has two components: the workload and
27 * the CPU. To measure the impact of pressure on both, we define two
28 * contention states for a resource: SOME and FULL.
29 *
30 * In the SOME state of a given resource, one or more tasks are
31 * delayed on that resource. This affects the workload's ability to
32 * perform work, but the CPU may still be executing other tasks.
33 *
34 * In the FULL state of a given resource, all non-idle tasks are
35 * delayed on that resource such that nobody is advancing and the CPU
36 * goes idle. This leaves both workload and CPU unproductive.
37 *
38 * SOME = nr_delayed_tasks != 0
39 * FULL = nr_delayed_tasks != 0 && nr_productive_tasks == 0
40 *
41 * What it means for a task to be productive is defined differently
42 * for each resource. For IO, productive means a running task. For
43 * memory, productive means a running task that isn't a reclaimer. For
44 * CPU, productive means an on-CPU task.
45 *
46 * Naturally, the FULL state doesn't exist for the CPU resource at the
47 * system level, but exist at the cgroup level. At the cgroup level,
48 * FULL means all non-idle tasks in the cgroup are delayed on the CPU
49 * resource which is being used by others outside of the cgroup or
50 * throttled by the cgroup cpu.max configuration.
51 *
52 * The percentage of wall clock time spent in those compound stall
53 * states gives pressure numbers between 0 and 100 for each resource,
54 * where the SOME percentage indicates workload slowdowns and the FULL
55 * percentage indicates reduced CPU utilization:
56 *
57 * %SOME = time(SOME) / period
58 * %FULL = time(FULL) / period
59 *
60 * Multiple CPUs
61 *
62 * The more tasks and available CPUs there are, the more work can be
63 * performed concurrently. This means that the potential that can go
64 * unrealized due to resource contention *also* scales with non-idle
65 * tasks and CPUs.
66 *
67 * Consider a scenario where 257 number crunching tasks are trying to
68 * run concurrently on 256 CPUs. If we simply aggregated the task
69 * states, we would have to conclude a CPU SOME pressure number of
70 * 100%, since *somebody* is waiting on a runqueue at all
71 * times. However, that is clearly not the amount of contention the
72 * workload is experiencing: only one out of 256 possible execution
73 * threads will be contended at any given time, or about 0.4%.
74 *
75 * Conversely, consider a scenario of 4 tasks and 4 CPUs where at any
76 * given time *one* of the tasks is delayed due to a lack of memory.
77 * Again, looking purely at the task state would yield a memory FULL
78 * pressure number of 0%, since *somebody* is always making forward
79 * progress. But again this wouldn't capture the amount of execution
80 * potential lost, which is 1 out of 4 CPUs, or 25%.
81 *
82 * To calculate wasted potential (pressure) with multiple processors,
83 * we have to base our calculation on the number of non-idle tasks in
84 * conjunction with the number of available CPUs, which is the number
85 * of potential execution threads. SOME becomes then the proportion of
86 * delayed tasks to possible threads, and FULL is the share of possible
87 * threads that are unproductive due to delays:
88 *
89 * threads = min(nr_nonidle_tasks, nr_cpus)
90 * SOME = min(nr_delayed_tasks / threads, 1)
91 * FULL = (threads - min(nr_productive_tasks, threads)) / threads
92 *
93 * For the 257 number crunchers on 256 CPUs, this yields:
94 *
95 * threads = min(257, 256)
96 * SOME = min(1 / 256, 1) = 0.4%
97 * FULL = (256 - min(256, 256)) / 256 = 0%
98 *
99 * For the 1 out of 4 memory-delayed tasks, this yields:
100 *
101 * threads = min(4, 4)
102 * SOME = min(1 / 4, 1) = 25%
103 * FULL = (4 - min(3, 4)) / 4 = 25%
104 *
105 * [ Substitute nr_cpus with 1, and you can see that it's a natural
106 * extension of the single-CPU model. ]
107 *
108 * Implementation
109 *
110 * To assess the precise time spent in each such state, we would have
111 * to freeze the system on task changes and start/stop the state
112 * clocks accordingly. Obviously that doesn't scale in practice.
113 *
114 * Because the scheduler aims to distribute the compute load evenly
115 * among the available CPUs, we can track task state locally to each
116 * CPU and, at much lower frequency, extrapolate the global state for
117 * the cumulative stall times and the running averages.
118 *
119 * For each runqueue, we track:
120 *
121 * tSOME[cpu] = time(nr_delayed_tasks[cpu] != 0)
122 * tFULL[cpu] = time(nr_delayed_tasks[cpu] && !nr_productive_tasks[cpu])
123 * tNONIDLE[cpu] = time(nr_nonidle_tasks[cpu] != 0)
124 *
125 * and then periodically aggregate:
126 *
127 * tNONIDLE = sum(tNONIDLE[i])
128 *
129 * tSOME = sum(tSOME[i] * tNONIDLE[i]) / tNONIDLE
130 * tFULL = sum(tFULL[i] * tNONIDLE[i]) / tNONIDLE
131 *
132 * %SOME = tSOME / period
133 * %FULL = tFULL / period
134 *
135 * This gives us an approximation of pressure that is practical
136 * cost-wise, yet way more sensitive and accurate than periodic
137 * sampling of the aggregate task states would be.
138 */
139 #include <trace/hooks/psi.h>
140
141 static int psi_bug __read_mostly;
142
143 DEFINE_STATIC_KEY_FALSE(psi_disabled);
144 static DEFINE_STATIC_KEY_TRUE(psi_cgroups_enabled);
145
146 #ifdef CONFIG_PSI_DEFAULT_DISABLED
147 static bool psi_enable;
148 #else
149 static bool psi_enable = true;
150 #endif
setup_psi(char * str)151 static int __init setup_psi(char *str)
152 {
153 return kstrtobool(str, &psi_enable) == 0;
154 }
155 __setup("psi=", setup_psi);
156
157 /* Running averages - we need to be higher-res than loadavg */
158 #define PSI_FREQ (2*HZ+1) /* 2 sec intervals */
159 #define EXP_10s 1677 /* 1/exp(2s/10s) as fixed-point */
160 #define EXP_60s 1981 /* 1/exp(2s/60s) */
161 #define EXP_300s 2034 /* 1/exp(2s/300s) */
162
163 /* PSI trigger definitions */
164 #define WINDOW_MAX_US 10000000 /* Max window size is 10s */
165 #define UPDATES_PER_WINDOW 10 /* 10 updates per window */
166
167 /* Sampling frequency in nanoseconds */
168 static u64 psi_period __read_mostly;
169
170 /* System-level pressure and stall tracking */
171 static DEFINE_PER_CPU(struct psi_group_cpu, system_group_pcpu);
172 struct psi_group psi_system = {
173 .pcpu = &system_group_pcpu,
174 };
175
176 static void psi_avgs_work(struct work_struct *work);
177
178 static void poll_timer_fn(struct timer_list *t);
179
group_init(struct psi_group * group)180 static void group_init(struct psi_group *group)
181 {
182 int cpu;
183
184 group->enabled = true;
185 for_each_possible_cpu(cpu)
186 seqcount_init(&per_cpu_ptr(group->pcpu, cpu)->seq);
187 group->avg_last_update = sched_clock();
188 group->avg_next_update = group->avg_last_update + psi_period;
189 mutex_init(&group->avgs_lock);
190
191 /* Init avg trigger-related members */
192 INIT_LIST_HEAD(&group->avg_triggers);
193 memset(group->avg_nr_triggers, 0, sizeof(group->avg_nr_triggers));
194 INIT_DELAYED_WORK(&group->avgs_work, psi_avgs_work);
195
196 /* Init rtpoll trigger-related members */
197 atomic_set(&group->rtpoll_scheduled, 0);
198 mutex_init(&group->rtpoll_trigger_lock);
199 INIT_LIST_HEAD(&group->rtpoll_triggers);
200 group->rtpoll_min_period = U32_MAX;
201 group->rtpoll_next_update = ULLONG_MAX;
202 init_waitqueue_head(&group->rtpoll_wait);
203 timer_setup(&group->rtpoll_timer, poll_timer_fn, 0);
204 rcu_assign_pointer(group->rtpoll_task, NULL);
205 }
206
psi_init(void)207 void __init psi_init(void)
208 {
209 if (!psi_enable) {
210 static_branch_enable(&psi_disabled);
211 static_branch_disable(&psi_cgroups_enabled);
212 return;
213 }
214
215 if (!cgroup_psi_enabled())
216 static_branch_disable(&psi_cgroups_enabled);
217
218 psi_period = jiffies_to_nsecs(PSI_FREQ);
219 group_init(&psi_system);
220 }
221
test_states(unsigned int * tasks,u32 state_mask)222 static u32 test_states(unsigned int *tasks, u32 state_mask)
223 {
224 const bool oncpu = state_mask & PSI_ONCPU;
225
226 if (tasks[NR_IOWAIT]) {
227 state_mask |= BIT(PSI_IO_SOME);
228 if (!tasks[NR_RUNNING])
229 state_mask |= BIT(PSI_IO_FULL);
230 }
231
232 if (tasks[NR_MEMSTALL]) {
233 state_mask |= BIT(PSI_MEM_SOME);
234 if (tasks[NR_RUNNING] == tasks[NR_MEMSTALL_RUNNING])
235 state_mask |= BIT(PSI_MEM_FULL);
236 }
237
238 if (tasks[NR_RUNNING] > oncpu)
239 state_mask |= BIT(PSI_CPU_SOME);
240
241 if (tasks[NR_RUNNING] && !oncpu)
242 state_mask |= BIT(PSI_CPU_FULL);
243
244 if (tasks[NR_IOWAIT] || tasks[NR_MEMSTALL] || tasks[NR_RUNNING])
245 state_mask |= BIT(PSI_NONIDLE);
246
247 return state_mask;
248 }
249
get_recent_times(struct psi_group * group,int cpu,enum psi_aggregators aggregator,u32 * times,u32 * pchanged_states)250 static void get_recent_times(struct psi_group *group, int cpu,
251 enum psi_aggregators aggregator, u32 *times,
252 u32 *pchanged_states)
253 {
254 struct psi_group_cpu *groupc = per_cpu_ptr(group->pcpu, cpu);
255 int current_cpu = raw_smp_processor_id();
256 unsigned int tasks[NR_PSI_TASK_COUNTS];
257 u64 now, state_start;
258 enum psi_states s;
259 unsigned int seq;
260 u32 state_mask;
261
262 *pchanged_states = 0;
263
264 /* Snapshot a coherent view of the CPU state */
265 do {
266 seq = read_seqcount_begin(&groupc->seq);
267 now = cpu_clock(cpu);
268 memcpy(times, groupc->times, sizeof(groupc->times));
269 state_mask = groupc->state_mask;
270 state_start = groupc->state_start;
271 if (cpu == current_cpu)
272 memcpy(tasks, groupc->tasks, sizeof(groupc->tasks));
273 } while (read_seqcount_retry(&groupc->seq, seq));
274
275 /* Calculate state time deltas against the previous snapshot */
276 for (s = 0; s < NR_PSI_STATES; s++) {
277 u32 delta;
278 /*
279 * In addition to already concluded states, we also
280 * incorporate currently active states on the CPU,
281 * since states may last for many sampling periods.
282 *
283 * This way we keep our delta sampling buckets small
284 * (u32) and our reported pressure close to what's
285 * actually happening.
286 */
287 if (state_mask & (1 << s))
288 times[s] += now - state_start;
289
290 delta = times[s] - groupc->times_prev[aggregator][s];
291 groupc->times_prev[aggregator][s] = times[s];
292
293 times[s] = delta;
294 if (delta)
295 *pchanged_states |= (1 << s);
296 }
297
298 /*
299 * When collect_percpu_times() from the avgs_work, we don't want to
300 * re-arm avgs_work when all CPUs are IDLE. But the current CPU running
301 * this avgs_work is never IDLE, cause avgs_work can't be shut off.
302 * So for the current CPU, we need to re-arm avgs_work only when
303 * (NR_RUNNING > 1 || NR_IOWAIT > 0 || NR_MEMSTALL > 0), for other CPUs
304 * we can just check PSI_NONIDLE delta.
305 */
306 if (current_work() == &group->avgs_work.work) {
307 bool reschedule;
308
309 if (cpu == current_cpu)
310 reschedule = tasks[NR_RUNNING] +
311 tasks[NR_IOWAIT] +
312 tasks[NR_MEMSTALL] > 1;
313 else
314 reschedule = *pchanged_states & (1 << PSI_NONIDLE);
315
316 if (reschedule)
317 *pchanged_states |= PSI_STATE_RESCHEDULE;
318 }
319 }
320
calc_avgs(unsigned long avg[3],int missed_periods,u64 time,u64 period)321 static void calc_avgs(unsigned long avg[3], int missed_periods,
322 u64 time, u64 period)
323 {
324 unsigned long pct;
325
326 /* Fill in zeroes for periods of no activity */
327 if (missed_periods) {
328 avg[0] = calc_load_n(avg[0], EXP_10s, 0, missed_periods);
329 avg[1] = calc_load_n(avg[1], EXP_60s, 0, missed_periods);
330 avg[2] = calc_load_n(avg[2], EXP_300s, 0, missed_periods);
331 }
332
333 /* Sample the most recent active period */
334 pct = div_u64(time * 100, period);
335 pct *= FIXED_1;
336 avg[0] = calc_load(avg[0], EXP_10s, pct);
337 avg[1] = calc_load(avg[1], EXP_60s, pct);
338 avg[2] = calc_load(avg[2], EXP_300s, pct);
339 }
340
collect_percpu_times(struct psi_group * group,enum psi_aggregators aggregator,u32 * pchanged_states)341 static void collect_percpu_times(struct psi_group *group,
342 enum psi_aggregators aggregator,
343 u32 *pchanged_states)
344 {
345 u64 deltas[NR_PSI_STATES - 1] = { 0, };
346 unsigned long nonidle_total = 0;
347 u32 changed_states = 0;
348 int cpu;
349 int s;
350
351 /*
352 * Collect the per-cpu time buckets and average them into a
353 * single time sample that is normalized to wall clock time.
354 *
355 * For averaging, each CPU is weighted by its non-idle time in
356 * the sampling period. This eliminates artifacts from uneven
357 * loading, or even entirely idle CPUs.
358 */
359 for_each_possible_cpu(cpu) {
360 u32 times[NR_PSI_STATES];
361 u32 nonidle;
362 u32 cpu_changed_states;
363
364 get_recent_times(group, cpu, aggregator, times,
365 &cpu_changed_states);
366 changed_states |= cpu_changed_states;
367
368 nonidle = nsecs_to_jiffies(times[PSI_NONIDLE]);
369 nonidle_total += nonidle;
370
371 for (s = 0; s < PSI_NONIDLE; s++)
372 deltas[s] += (u64)times[s] * nonidle;
373 }
374
375 /*
376 * Integrate the sample into the running statistics that are
377 * reported to userspace: the cumulative stall times and the
378 * decaying averages.
379 *
380 * Pressure percentages are sampled at PSI_FREQ. We might be
381 * called more often when the user polls more frequently than
382 * that; we might be called less often when there is no task
383 * activity, thus no data, and clock ticks are sporadic. The
384 * below handles both.
385 */
386
387 /* total= */
388 for (s = 0; s < NR_PSI_STATES - 1; s++)
389 group->total[aggregator][s] +=
390 div_u64(deltas[s], max(nonidle_total, 1UL));
391
392 if (pchanged_states)
393 *pchanged_states = changed_states;
394 }
395
396 /* Trigger tracking window manipulations */
window_reset(struct psi_window * win,u64 now,u64 value,u64 prev_growth)397 static void window_reset(struct psi_window *win, u64 now, u64 value,
398 u64 prev_growth)
399 {
400 win->start_time = now;
401 win->start_value = value;
402 win->prev_growth = prev_growth;
403 }
404
405 /*
406 * PSI growth tracking window update and growth calculation routine.
407 *
408 * This approximates a sliding tracking window by interpolating
409 * partially elapsed windows using historical growth data from the
410 * previous intervals. This minimizes memory requirements (by not storing
411 * all the intermediate values in the previous window) and simplifies
412 * the calculations. It works well because PSI signal changes only in
413 * positive direction and over relatively small window sizes the growth
414 * is close to linear.
415 */
window_update(struct psi_window * win,u64 now,u64 value)416 static u64 window_update(struct psi_window *win, u64 now, u64 value)
417 {
418 u64 elapsed;
419 u64 growth;
420
421 elapsed = now - win->start_time;
422 growth = value - win->start_value;
423 /*
424 * After each tracking window passes win->start_value and
425 * win->start_time get reset and win->prev_growth stores
426 * the average per-window growth of the previous window.
427 * win->prev_growth is then used to interpolate additional
428 * growth from the previous window assuming it was linear.
429 */
430 if (elapsed > win->size)
431 window_reset(win, now, value, growth);
432 else {
433 u32 remaining;
434
435 remaining = win->size - elapsed;
436 growth += div64_u64(win->prev_growth * remaining, win->size);
437 }
438
439 return growth;
440 }
441
update_triggers(struct psi_group * group,u64 now,enum psi_aggregators aggregator)442 static void update_triggers(struct psi_group *group, u64 now,
443 enum psi_aggregators aggregator)
444 {
445 struct psi_trigger *t;
446 u64 *total = group->total[aggregator];
447 struct list_head *triggers;
448 u64 *aggregator_total;
449
450 if (aggregator == PSI_AVGS) {
451 triggers = &group->avg_triggers;
452 aggregator_total = group->avg_total;
453 } else {
454 triggers = &group->rtpoll_triggers;
455 aggregator_total = group->rtpoll_total;
456 }
457
458 /*
459 * On subsequent updates, calculate growth deltas and let
460 * watchers know when their specified thresholds are exceeded.
461 */
462 list_for_each_entry(t, triggers, node) {
463 u64 growth;
464 bool new_stall;
465
466 new_stall = aggregator_total[t->state] != total[t->state];
467
468 /* Check for stall activity or a previous threshold breach */
469 if (!new_stall && !t->pending_event)
470 continue;
471 /*
472 * Check for new stall activity, as well as deferred
473 * events that occurred in the last window after the
474 * trigger had already fired (we want to ratelimit
475 * events without dropping any).
476 */
477 if (new_stall) {
478 /* Calculate growth since last update */
479 growth = window_update(&t->win, now, total[t->state]);
480 if (!t->pending_event) {
481 if (growth < t->threshold)
482 continue;
483
484 t->pending_event = true;
485 }
486 }
487 /* Limit event signaling to once per window */
488 if (now < t->last_event_time + t->win.size)
489 continue;
490
491 trace_android_vh_psi_event(t);
492
493 /* Generate an event */
494 if (cmpxchg(&t->event, 0, 1) == 0) {
495 if (t->of)
496 kernfs_notify(t->of->kn);
497 else
498 wake_up_interruptible(&t->event_wait);
499 }
500 t->last_event_time = now;
501 /* Reset threshold breach flag once event got generated */
502 t->pending_event = false;
503 }
504
505 trace_android_vh_psi_group(group);
506 }
507
update_averages(struct psi_group * group,u64 now)508 static u64 update_averages(struct psi_group *group, u64 now)
509 {
510 unsigned long missed_periods = 0;
511 u64 expires, period;
512 u64 avg_next_update;
513 int s;
514
515 /* avgX= */
516 expires = group->avg_next_update;
517 if (now - expires >= psi_period)
518 missed_periods = div_u64(now - expires, psi_period);
519
520 /*
521 * The periodic clock tick can get delayed for various
522 * reasons, especially on loaded systems. To avoid clock
523 * drift, we schedule the clock in fixed psi_period intervals.
524 * But the deltas we sample out of the per-cpu buckets above
525 * are based on the actual time elapsing between clock ticks.
526 */
527 avg_next_update = expires + ((1 + missed_periods) * psi_period);
528 period = now - (group->avg_last_update + (missed_periods * psi_period));
529 group->avg_last_update = now;
530
531 for (s = 0; s < NR_PSI_STATES - 1; s++) {
532 u32 sample;
533
534 sample = group->total[PSI_AVGS][s] - group->avg_total[s];
535 /*
536 * Due to the lockless sampling of the time buckets,
537 * recorded time deltas can slip into the next period,
538 * which under full pressure can result in samples in
539 * excess of the period length.
540 *
541 * We don't want to report non-sensical pressures in
542 * excess of 100%, nor do we want to drop such events
543 * on the floor. Instead we punt any overage into the
544 * future until pressure subsides. By doing this we
545 * don't underreport the occurring pressure curve, we
546 * just report it delayed by one period length.
547 *
548 * The error isn't cumulative. As soon as another
549 * delta slips from a period P to P+1, by definition
550 * it frees up its time T in P.
551 */
552 if (sample > period)
553 sample = period;
554 group->avg_total[s] += sample;
555 calc_avgs(group->avg[s], missed_periods, sample, period);
556 }
557
558 return avg_next_update;
559 }
560
psi_avgs_work(struct work_struct * work)561 static void psi_avgs_work(struct work_struct *work)
562 {
563 struct delayed_work *dwork;
564 struct psi_group *group;
565 u32 changed_states;
566 u64 now;
567
568 dwork = to_delayed_work(work);
569 group = container_of(dwork, struct psi_group, avgs_work);
570
571 mutex_lock(&group->avgs_lock);
572
573 now = sched_clock();
574
575 collect_percpu_times(group, PSI_AVGS, &changed_states);
576 /*
577 * If there is task activity, periodically fold the per-cpu
578 * times and feed samples into the running averages. If things
579 * are idle and there is no data to process, stop the clock.
580 * Once restarted, we'll catch up the running averages in one
581 * go - see calc_avgs() and missed_periods.
582 */
583 if (now >= group->avg_next_update) {
584 update_triggers(group, now, PSI_AVGS);
585 group->avg_next_update = update_averages(group, now);
586 }
587
588 if (changed_states & PSI_STATE_RESCHEDULE) {
589 schedule_delayed_work(dwork, nsecs_to_jiffies(
590 group->avg_next_update - now) + 1);
591 }
592
593 mutex_unlock(&group->avgs_lock);
594 }
595
init_rtpoll_triggers(struct psi_group * group,u64 now)596 static void init_rtpoll_triggers(struct psi_group *group, u64 now)
597 {
598 struct psi_trigger *t;
599
600 list_for_each_entry(t, &group->rtpoll_triggers, node)
601 window_reset(&t->win, now,
602 group->total[PSI_POLL][t->state], 0);
603 memcpy(group->rtpoll_total, group->total[PSI_POLL],
604 sizeof(group->rtpoll_total));
605 group->rtpoll_next_update = now + group->rtpoll_min_period;
606 }
607
608 /* Schedule rtpolling if it's not already scheduled or forced. */
psi_schedule_rtpoll_work(struct psi_group * group,unsigned long delay,bool force)609 static void psi_schedule_rtpoll_work(struct psi_group *group, unsigned long delay,
610 bool force)
611 {
612 struct task_struct *task;
613
614 /*
615 * atomic_xchg should be called even when !force to provide a
616 * full memory barrier (see the comment inside psi_rtpoll_work).
617 */
618 if (atomic_xchg(&group->rtpoll_scheduled, 1) && !force)
619 return;
620
621 rcu_read_lock();
622
623 task = rcu_dereference(group->rtpoll_task);
624 /*
625 * kworker might be NULL in case psi_trigger_destroy races with
626 * psi_task_change (hotpath) which can't use locks
627 */
628 if (likely(task))
629 mod_timer(&group->rtpoll_timer, jiffies + delay);
630 else
631 atomic_set(&group->rtpoll_scheduled, 0);
632
633 rcu_read_unlock();
634 }
635
psi_rtpoll_work(struct psi_group * group)636 static void psi_rtpoll_work(struct psi_group *group)
637 {
638 bool force_reschedule = false;
639 u32 changed_states;
640 u64 now;
641
642 mutex_lock(&group->rtpoll_trigger_lock);
643
644 now = sched_clock();
645
646 if (now > group->rtpoll_until) {
647 /*
648 * We are either about to start or might stop rtpolling if no
649 * state change was recorded. Resetting rtpoll_scheduled leaves
650 * a small window for psi_group_change to sneak in and schedule
651 * an immediate rtpoll_work before we get to rescheduling. One
652 * potential extra wakeup at the end of the rtpolling window
653 * should be negligible and rtpoll_next_update still keeps
654 * updates correctly on schedule.
655 */
656 atomic_set(&group->rtpoll_scheduled, 0);
657 /*
658 * A task change can race with the rtpoll worker that is supposed to
659 * report on it. To avoid missing events, ensure ordering between
660 * rtpoll_scheduled and the task state accesses, such that if the
661 * rtpoll worker misses the state update, the task change is
662 * guaranteed to reschedule the rtpoll worker:
663 *
664 * rtpoll worker:
665 * atomic_set(rtpoll_scheduled, 0)
666 * smp_mb()
667 * LOAD states
668 *
669 * task change:
670 * STORE states
671 * if atomic_xchg(rtpoll_scheduled, 1) == 0:
672 * schedule rtpoll worker
673 *
674 * The atomic_xchg() implies a full barrier.
675 */
676 smp_mb();
677 } else {
678 /* The rtpolling window is not over, keep rescheduling */
679 force_reschedule = true;
680 }
681
682
683 collect_percpu_times(group, PSI_POLL, &changed_states);
684
685 if (changed_states & group->rtpoll_states) {
686 /* Initialize trigger windows when entering rtpolling mode */
687 if (now > group->rtpoll_until)
688 init_rtpoll_triggers(group, now);
689
690 /*
691 * Keep the monitor active for at least the duration of the
692 * minimum tracking window as long as monitor states are
693 * changing.
694 */
695 group->rtpoll_until = now +
696 group->rtpoll_min_period * UPDATES_PER_WINDOW;
697 }
698
699 if (now > group->rtpoll_until) {
700 group->rtpoll_next_update = ULLONG_MAX;
701 goto out;
702 }
703
704 if (now >= group->rtpoll_next_update) {
705 if (changed_states & group->rtpoll_states) {
706 update_triggers(group, now, PSI_POLL);
707 memcpy(group->rtpoll_total, group->total[PSI_POLL],
708 sizeof(group->rtpoll_total));
709 }
710 group->rtpoll_next_update = now + group->rtpoll_min_period;
711 }
712
713 psi_schedule_rtpoll_work(group,
714 nsecs_to_jiffies(group->rtpoll_next_update - now) + 1,
715 force_reschedule);
716
717 out:
718 mutex_unlock(&group->rtpoll_trigger_lock);
719 }
720
psi_rtpoll_worker(void * data)721 static int psi_rtpoll_worker(void *data)
722 {
723 struct psi_group *group = (struct psi_group *)data;
724
725 sched_set_fifo_low(current);
726
727 while (true) {
728 wait_event_interruptible(group->rtpoll_wait,
729 atomic_cmpxchg(&group->rtpoll_wakeup, 1, 0) ||
730 kthread_should_stop());
731 if (kthread_should_stop())
732 break;
733
734 psi_rtpoll_work(group);
735 }
736 return 0;
737 }
738
poll_timer_fn(struct timer_list * t)739 static void poll_timer_fn(struct timer_list *t)
740 {
741 struct psi_group *group = from_timer(group, t, rtpoll_timer);
742
743 atomic_set(&group->rtpoll_wakeup, 1);
744 wake_up_interruptible(&group->rtpoll_wait);
745 }
746
record_times(struct psi_group_cpu * groupc,u64 now)747 static void record_times(struct psi_group_cpu *groupc, u64 now)
748 {
749 u32 delta;
750
751 delta = now - groupc->state_start;
752 groupc->state_start = now;
753
754 if (groupc->state_mask & (1 << PSI_IO_SOME)) {
755 groupc->times[PSI_IO_SOME] += delta;
756 if (groupc->state_mask & (1 << PSI_IO_FULL))
757 groupc->times[PSI_IO_FULL] += delta;
758 }
759
760 if (groupc->state_mask & (1 << PSI_MEM_SOME)) {
761 groupc->times[PSI_MEM_SOME] += delta;
762 if (groupc->state_mask & (1 << PSI_MEM_FULL))
763 groupc->times[PSI_MEM_FULL] += delta;
764 }
765
766 if (groupc->state_mask & (1 << PSI_CPU_SOME)) {
767 groupc->times[PSI_CPU_SOME] += delta;
768 if (groupc->state_mask & (1 << PSI_CPU_FULL))
769 groupc->times[PSI_CPU_FULL] += delta;
770 }
771
772 if (groupc->state_mask & (1 << PSI_NONIDLE))
773 groupc->times[PSI_NONIDLE] += delta;
774 }
775
psi_group_change(struct psi_group * group,int cpu,unsigned int clear,unsigned int set,bool wake_clock)776 static void psi_group_change(struct psi_group *group, int cpu,
777 unsigned int clear, unsigned int set,
778 bool wake_clock)
779 {
780 struct psi_group_cpu *groupc;
781 unsigned int t, m;
782 u32 state_mask;
783 u64 now;
784
785 lockdep_assert_rq_held(cpu_rq(cpu));
786 groupc = per_cpu_ptr(group->pcpu, cpu);
787
788 /*
789 * First we update the task counts according to the state
790 * change requested through the @clear and @set bits.
791 *
792 * Then if the cgroup PSI stats accounting enabled, we
793 * assess the aggregate resource states this CPU's tasks
794 * have been in since the last change, and account any
795 * SOME and FULL time these may have resulted in.
796 */
797 write_seqcount_begin(&groupc->seq);
798 now = cpu_clock(cpu);
799
800 /*
801 * Start with TSK_ONCPU, which doesn't have a corresponding
802 * task count - it's just a boolean flag directly encoded in
803 * the state mask. Clear, set, or carry the current state if
804 * no changes are requested.
805 */
806 if (unlikely(clear & TSK_ONCPU)) {
807 state_mask = 0;
808 clear &= ~TSK_ONCPU;
809 } else if (unlikely(set & TSK_ONCPU)) {
810 state_mask = PSI_ONCPU;
811 set &= ~TSK_ONCPU;
812 } else {
813 state_mask = groupc->state_mask & PSI_ONCPU;
814 }
815
816 /*
817 * The rest of the state mask is calculated based on the task
818 * counts. Update those first, then construct the mask.
819 */
820 for (t = 0, m = clear; m; m &= ~(1 << t), t++) {
821 if (!(m & (1 << t)))
822 continue;
823 if (groupc->tasks[t]) {
824 groupc->tasks[t]--;
825 } else if (!psi_bug) {
826 printk_deferred(KERN_ERR "psi: task underflow! cpu=%d t=%d tasks=[%u %u %u %u] clear=%x set=%x\n",
827 cpu, t, groupc->tasks[0],
828 groupc->tasks[1], groupc->tasks[2],
829 groupc->tasks[3], clear, set);
830 psi_bug = 1;
831 }
832 }
833
834 for (t = 0; set; set &= ~(1 << t), t++)
835 if (set & (1 << t))
836 groupc->tasks[t]++;
837
838 if (!group->enabled) {
839 /*
840 * On the first group change after disabling PSI, conclude
841 * the current state and flush its time. This is unlikely
842 * to matter to the user, but aggregation (get_recent_times)
843 * may have already incorporated the live state into times_prev;
844 * avoid a delta sample underflow when PSI is later re-enabled.
845 */
846 if (unlikely(groupc->state_mask & (1 << PSI_NONIDLE)))
847 record_times(groupc, now);
848
849 groupc->state_mask = state_mask;
850
851 write_seqcount_end(&groupc->seq);
852 return;
853 }
854
855 state_mask = test_states(groupc->tasks, state_mask);
856
857 /*
858 * Since we care about lost potential, a memstall is FULL
859 * when there are no other working tasks, but also when
860 * the CPU is actively reclaiming and nothing productive
861 * could run even if it were runnable. So when the current
862 * task in a cgroup is in_memstall, the corresponding groupc
863 * on that cpu is in PSI_MEM_FULL state.
864 */
865 if (unlikely((state_mask & PSI_ONCPU) && cpu_curr(cpu)->in_memstall))
866 state_mask |= (1 << PSI_MEM_FULL);
867
868 record_times(groupc, now);
869
870 groupc->state_mask = state_mask;
871
872 write_seqcount_end(&groupc->seq);
873
874 if (state_mask & group->rtpoll_states)
875 psi_schedule_rtpoll_work(group, 1, false);
876
877 if (wake_clock && !delayed_work_pending(&group->avgs_work))
878 schedule_delayed_work(&group->avgs_work, PSI_FREQ);
879 }
880
task_psi_group(struct task_struct * task)881 static inline struct psi_group *task_psi_group(struct task_struct *task)
882 {
883 #ifdef CONFIG_CGROUPS
884 if (static_branch_likely(&psi_cgroups_enabled))
885 return cgroup_psi(task_dfl_cgroup(task));
886 #endif
887 return &psi_system;
888 }
889
psi_flags_change(struct task_struct * task,int clear,int set)890 static void psi_flags_change(struct task_struct *task, int clear, int set)
891 {
892 if (((task->psi_flags & set) ||
893 (task->psi_flags & clear) != clear) &&
894 !psi_bug) {
895 printk_deferred(KERN_ERR "psi: inconsistent task state! task=%d:%s cpu=%d psi_flags=%x clear=%x set=%x\n",
896 task->pid, task->comm, task_cpu(task),
897 task->psi_flags, clear, set);
898 psi_bug = 1;
899 }
900
901 task->psi_flags &= ~clear;
902 task->psi_flags |= set;
903 }
904
psi_task_change(struct task_struct * task,int clear,int set)905 void psi_task_change(struct task_struct *task, int clear, int set)
906 {
907 int cpu = task_cpu(task);
908 struct psi_group *group;
909
910 if (!task->pid)
911 return;
912
913 psi_flags_change(task, clear, set);
914
915 group = task_psi_group(task);
916 do {
917 psi_group_change(group, cpu, clear, set, true);
918 } while ((group = group->parent));
919 }
920
psi_task_switch(struct task_struct * prev,struct task_struct * next,bool sleep)921 void psi_task_switch(struct task_struct *prev, struct task_struct *next,
922 bool sleep)
923 {
924 struct psi_group *group, *common = NULL;
925 int cpu = task_cpu(prev);
926
927 if (next->pid) {
928 psi_flags_change(next, 0, TSK_ONCPU);
929 /*
930 * Set TSK_ONCPU on @next's cgroups. If @next shares any
931 * ancestors with @prev, those will already have @prev's
932 * TSK_ONCPU bit set, and we can stop the iteration there.
933 */
934 group = task_psi_group(next);
935 do {
936 if (per_cpu_ptr(group->pcpu, cpu)->state_mask &
937 PSI_ONCPU) {
938 common = group;
939 break;
940 }
941
942 psi_group_change(group, cpu, 0, TSK_ONCPU, true);
943 } while ((group = group->parent));
944 }
945
946 if (prev->pid) {
947 int clear = TSK_ONCPU, set = 0;
948 bool wake_clock = true;
949
950 /*
951 * When we're going to sleep, psi_dequeue() lets us
952 * handle TSK_RUNNING, TSK_MEMSTALL_RUNNING and
953 * TSK_IOWAIT here, where we can combine it with
954 * TSK_ONCPU and save walking common ancestors twice.
955 */
956 if (sleep) {
957 clear |= TSK_RUNNING;
958 if (prev->in_memstall)
959 clear |= TSK_MEMSTALL_RUNNING;
960 if (prev->in_iowait)
961 set |= TSK_IOWAIT;
962
963 /*
964 * Periodic aggregation shuts off if there is a period of no
965 * task changes, so we wake it back up if necessary. However,
966 * don't do this if the task change is the aggregation worker
967 * itself going to sleep, or we'll ping-pong forever.
968 */
969 if (unlikely((prev->flags & PF_WQ_WORKER) &&
970 wq_worker_last_func(prev) == psi_avgs_work))
971 wake_clock = false;
972 }
973
974 psi_flags_change(prev, clear, set);
975
976 group = task_psi_group(prev);
977 do {
978 if (group == common)
979 break;
980 psi_group_change(group, cpu, clear, set, wake_clock);
981 } while ((group = group->parent));
982
983 /*
984 * TSK_ONCPU is handled up to the common ancestor. If there are
985 * any other differences between the two tasks (e.g. prev goes
986 * to sleep, or only one task is memstall), finish propagating
987 * those differences all the way up to the root.
988 */
989 if ((prev->psi_flags ^ next->psi_flags) & ~TSK_ONCPU) {
990 clear &= ~TSK_ONCPU;
991 for (; group; group = group->parent)
992 psi_group_change(group, cpu, clear, set, wake_clock);
993 }
994 }
995 }
996
997 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
psi_account_irqtime(struct rq * rq,struct task_struct * curr,struct task_struct * prev)998 void psi_account_irqtime(struct rq *rq, struct task_struct *curr, struct task_struct *prev)
999 {
1000 int cpu = task_cpu(curr);
1001 struct psi_group *group;
1002 struct psi_group_cpu *groupc;
1003 s64 delta;
1004 u64 irq;
1005
1006 if (static_branch_likely(&psi_disabled))
1007 return;
1008
1009 if (!curr->pid)
1010 return;
1011
1012 lockdep_assert_rq_held(rq);
1013 group = task_psi_group(curr);
1014 if (prev && task_psi_group(prev) == group)
1015 return;
1016
1017 irq = irq_time_read(cpu);
1018 delta = (s64)(irq - rq->psi_irq_time);
1019 if (delta < 0)
1020 return;
1021 rq->psi_irq_time = irq;
1022
1023 do {
1024 u64 now;
1025
1026 if (!group->enabled)
1027 continue;
1028
1029 groupc = per_cpu_ptr(group->pcpu, cpu);
1030
1031 write_seqcount_begin(&groupc->seq);
1032 now = cpu_clock(cpu);
1033
1034 record_times(groupc, now);
1035 groupc->times[PSI_IRQ_FULL] += delta;
1036
1037 write_seqcount_end(&groupc->seq);
1038
1039 if (group->rtpoll_states & (1 << PSI_IRQ_FULL))
1040 psi_schedule_rtpoll_work(group, 1, false);
1041 } while ((group = group->parent));
1042 }
1043 #endif
1044
1045 /**
1046 * psi_memstall_enter - mark the beginning of a memory stall section
1047 * @flags: flags to handle nested sections
1048 *
1049 * Marks the calling task as being stalled due to a lack of memory,
1050 * such as waiting for a refault or performing reclaim.
1051 */
psi_memstall_enter(unsigned long * flags)1052 void psi_memstall_enter(unsigned long *flags)
1053 {
1054 struct rq_flags rf;
1055 struct rq *rq;
1056
1057 if (static_branch_likely(&psi_disabled))
1058 return;
1059
1060 *flags = current->in_memstall;
1061 if (*flags)
1062 return;
1063 /*
1064 * in_memstall setting & accounting needs to be atomic wrt
1065 * changes to the task's scheduling state, otherwise we can
1066 * race with CPU migration.
1067 */
1068 rq = this_rq_lock_irq(&rf);
1069
1070 current->in_memstall = 1;
1071 psi_task_change(current, 0, TSK_MEMSTALL | TSK_MEMSTALL_RUNNING);
1072
1073 rq_unlock_irq(rq, &rf);
1074 }
1075 EXPORT_SYMBOL_GPL(psi_memstall_enter);
1076
1077 /**
1078 * psi_memstall_leave - mark the end of an memory stall section
1079 * @flags: flags to handle nested memdelay sections
1080 *
1081 * Marks the calling task as no longer stalled due to lack of memory.
1082 */
psi_memstall_leave(unsigned long * flags)1083 void psi_memstall_leave(unsigned long *flags)
1084 {
1085 struct rq_flags rf;
1086 struct rq *rq;
1087
1088 if (static_branch_likely(&psi_disabled))
1089 return;
1090
1091 if (*flags)
1092 return;
1093 /*
1094 * in_memstall clearing & accounting needs to be atomic wrt
1095 * changes to the task's scheduling state, otherwise we could
1096 * race with CPU migration.
1097 */
1098 rq = this_rq_lock_irq(&rf);
1099
1100 current->in_memstall = 0;
1101 psi_task_change(current, TSK_MEMSTALL | TSK_MEMSTALL_RUNNING, 0);
1102
1103 rq_unlock_irq(rq, &rf);
1104 }
1105 EXPORT_SYMBOL_GPL(psi_memstall_leave);
1106
1107 #ifdef CONFIG_CGROUPS
psi_cgroup_alloc(struct cgroup * cgroup)1108 int psi_cgroup_alloc(struct cgroup *cgroup)
1109 {
1110 if (!static_branch_likely(&psi_cgroups_enabled))
1111 return 0;
1112
1113 cgroup->psi = kzalloc(sizeof(struct psi_group), GFP_KERNEL);
1114 if (!cgroup->psi)
1115 return -ENOMEM;
1116
1117 cgroup->psi->pcpu = alloc_percpu(struct psi_group_cpu);
1118 if (!cgroup->psi->pcpu) {
1119 kfree(cgroup->psi);
1120 return -ENOMEM;
1121 }
1122 group_init(cgroup->psi);
1123 cgroup->psi->parent = cgroup_psi(cgroup_parent(cgroup));
1124 return 0;
1125 }
1126
psi_cgroup_free(struct cgroup * cgroup)1127 void psi_cgroup_free(struct cgroup *cgroup)
1128 {
1129 if (!static_branch_likely(&psi_cgroups_enabled))
1130 return;
1131
1132 cancel_delayed_work_sync(&cgroup->psi->avgs_work);
1133 free_percpu(cgroup->psi->pcpu);
1134 /* All triggers must be removed by now */
1135 WARN_ONCE(cgroup->psi->rtpoll_states, "psi: trigger leak\n");
1136 kfree(cgroup->psi);
1137 }
1138
1139 /**
1140 * cgroup_move_task - move task to a different cgroup
1141 * @task: the task
1142 * @to: the target css_set
1143 *
1144 * Move task to a new cgroup and safely migrate its associated stall
1145 * state between the different groups.
1146 *
1147 * This function acquires the task's rq lock to lock out concurrent
1148 * changes to the task's scheduling state and - in case the task is
1149 * running - concurrent changes to its stall state.
1150 */
cgroup_move_task(struct task_struct * task,struct css_set * to)1151 void cgroup_move_task(struct task_struct *task, struct css_set *to)
1152 {
1153 unsigned int task_flags;
1154 struct rq_flags rf;
1155 struct rq *rq;
1156
1157 if (!static_branch_likely(&psi_cgroups_enabled)) {
1158 /*
1159 * Lame to do this here, but the scheduler cannot be locked
1160 * from the outside, so we move cgroups from inside sched/.
1161 */
1162 rcu_assign_pointer(task->cgroups, to);
1163 return;
1164 }
1165
1166 rq = task_rq_lock(task, &rf);
1167
1168 /*
1169 * We may race with schedule() dropping the rq lock between
1170 * deactivating prev and switching to next. Because the psi
1171 * updates from the deactivation are deferred to the switch
1172 * callback to save cgroup tree updates, the task's scheduling
1173 * state here is not coherent with its psi state:
1174 *
1175 * schedule() cgroup_move_task()
1176 * rq_lock()
1177 * deactivate_task()
1178 * p->on_rq = 0
1179 * psi_dequeue() // defers TSK_RUNNING & TSK_IOWAIT updates
1180 * pick_next_task()
1181 * rq_unlock()
1182 * rq_lock()
1183 * psi_task_change() // old cgroup
1184 * task->cgroups = to
1185 * psi_task_change() // new cgroup
1186 * rq_unlock()
1187 * rq_lock()
1188 * psi_sched_switch() // does deferred updates in new cgroup
1189 *
1190 * Don't rely on the scheduling state. Use psi_flags instead.
1191 */
1192 task_flags = task->psi_flags;
1193
1194 if (task_flags)
1195 psi_task_change(task, task_flags, 0);
1196
1197 /* See comment above */
1198 rcu_assign_pointer(task->cgroups, to);
1199
1200 if (task_flags)
1201 psi_task_change(task, 0, task_flags);
1202
1203 task_rq_unlock(rq, task, &rf);
1204 }
1205
psi_cgroup_restart(struct psi_group * group)1206 void psi_cgroup_restart(struct psi_group *group)
1207 {
1208 int cpu;
1209
1210 /*
1211 * After we disable psi_group->enabled, we don't actually
1212 * stop percpu tasks accounting in each psi_group_cpu,
1213 * instead only stop test_states() loop, record_times()
1214 * and averaging worker, see psi_group_change() for details.
1215 *
1216 * When disable cgroup PSI, this function has nothing to sync
1217 * since cgroup pressure files are hidden and percpu psi_group_cpu
1218 * would see !psi_group->enabled and only do task accounting.
1219 *
1220 * When re-enable cgroup PSI, this function use psi_group_change()
1221 * to get correct state mask from test_states() loop on tasks[],
1222 * and restart groupc->state_start from now, use .clear = .set = 0
1223 * here since no task status really changed.
1224 */
1225 if (!group->enabled)
1226 return;
1227
1228 for_each_possible_cpu(cpu) {
1229 struct rq *rq = cpu_rq(cpu);
1230 struct rq_flags rf;
1231
1232 rq_lock_irq(rq, &rf);
1233 psi_group_change(group, cpu, 0, 0, true);
1234 rq_unlock_irq(rq, &rf);
1235 }
1236 }
1237 #endif /* CONFIG_CGROUPS */
1238
psi_show(struct seq_file * m,struct psi_group * group,enum psi_res res)1239 int psi_show(struct seq_file *m, struct psi_group *group, enum psi_res res)
1240 {
1241 bool only_full = false;
1242 int full;
1243 u64 now;
1244
1245 if (static_branch_likely(&psi_disabled))
1246 return -EOPNOTSUPP;
1247
1248 /* Update averages before reporting them */
1249 mutex_lock(&group->avgs_lock);
1250 now = sched_clock();
1251 collect_percpu_times(group, PSI_AVGS, NULL);
1252 if (now >= group->avg_next_update)
1253 group->avg_next_update = update_averages(group, now);
1254 mutex_unlock(&group->avgs_lock);
1255
1256 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1257 only_full = res == PSI_IRQ;
1258 #endif
1259
1260 for (full = 0; full < 2 - only_full; full++) {
1261 unsigned long avg[3] = { 0, };
1262 u64 total = 0;
1263 int w;
1264
1265 /* CPU FULL is undefined at the system level */
1266 if (!(group == &psi_system && res == PSI_CPU && full)) {
1267 for (w = 0; w < 3; w++)
1268 avg[w] = group->avg[res * 2 + full][w];
1269 total = div_u64(group->total[PSI_AVGS][res * 2 + full],
1270 NSEC_PER_USEC);
1271 }
1272
1273 seq_printf(m, "%s avg10=%lu.%02lu avg60=%lu.%02lu avg300=%lu.%02lu total=%llu\n",
1274 full || only_full ? "full" : "some",
1275 LOAD_INT(avg[0]), LOAD_FRAC(avg[0]),
1276 LOAD_INT(avg[1]), LOAD_FRAC(avg[1]),
1277 LOAD_INT(avg[2]), LOAD_FRAC(avg[2]),
1278 total);
1279 }
1280
1281 return 0;
1282 }
1283
psi_trigger_create(struct psi_group * group,char * buf,enum psi_res res,struct file * file,struct kernfs_open_file * of)1284 struct psi_trigger *psi_trigger_create(struct psi_group *group, char *buf,
1285 enum psi_res res, struct file *file,
1286 struct kernfs_open_file *of)
1287 {
1288 struct psi_trigger *t;
1289 enum psi_states state;
1290 u32 threshold_us;
1291 bool privileged;
1292 u32 window_us;
1293
1294 if (static_branch_likely(&psi_disabled))
1295 return ERR_PTR(-EOPNOTSUPP);
1296
1297 /*
1298 * Checking the privilege on file->f_cred or selinux enabled here imply
1299 * that a privileged user could open the file and delegate the write
1300 * to an unprivileged one.
1301 */
1302 privileged = cap_raised(file->f_cred->cap_effective, CAP_SYS_RESOURCE) ||
1303 IS_ENABLED(CONFIG_DEFAULT_SECURITY_SELINUX);
1304
1305 if (sscanf(buf, "some %u %u", &threshold_us, &window_us) == 2)
1306 state = PSI_IO_SOME + res * 2;
1307 else if (sscanf(buf, "full %u %u", &threshold_us, &window_us) == 2)
1308 state = PSI_IO_FULL + res * 2;
1309 else
1310 return ERR_PTR(-EINVAL);
1311
1312 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1313 if (res == PSI_IRQ && --state != PSI_IRQ_FULL)
1314 return ERR_PTR(-EINVAL);
1315 #endif
1316
1317 if (state >= PSI_NONIDLE)
1318 return ERR_PTR(-EINVAL);
1319
1320 if (window_us == 0 || window_us > WINDOW_MAX_US)
1321 return ERR_PTR(-EINVAL);
1322
1323 /*
1324 * Unprivileged users can only use 2s windows so that averages aggregation
1325 * work is used, and no RT threads need to be spawned.
1326 */
1327 if (!privileged && window_us % 2000000)
1328 return ERR_PTR(-EINVAL);
1329
1330 /* Check threshold */
1331 if (threshold_us == 0 || threshold_us > window_us)
1332 return ERR_PTR(-EINVAL);
1333
1334 t = kmalloc(sizeof(*t), GFP_KERNEL);
1335 if (!t)
1336 return ERR_PTR(-ENOMEM);
1337
1338 t->group = group;
1339 t->state = state;
1340 t->threshold = threshold_us * NSEC_PER_USEC;
1341 t->win.size = window_us * NSEC_PER_USEC;
1342 window_reset(&t->win, sched_clock(),
1343 group->total[PSI_POLL][t->state], 0);
1344
1345 t->event = 0;
1346 t->last_event_time = 0;
1347 t->of = of;
1348 if (!of)
1349 init_waitqueue_head(&t->event_wait);
1350 t->pending_event = false;
1351 t->aggregator = privileged ? PSI_POLL : PSI_AVGS;
1352
1353 if (privileged) {
1354 mutex_lock(&group->rtpoll_trigger_lock);
1355
1356 if (!rcu_access_pointer(group->rtpoll_task)) {
1357 struct task_struct *task;
1358
1359 task = kthread_create(psi_rtpoll_worker, group, "psimon");
1360 if (IS_ERR(task)) {
1361 kfree(t);
1362 mutex_unlock(&group->rtpoll_trigger_lock);
1363 return ERR_CAST(task);
1364 }
1365 atomic_set(&group->rtpoll_wakeup, 0);
1366 wake_up_process(task);
1367 rcu_assign_pointer(group->rtpoll_task, task);
1368 }
1369
1370 list_add(&t->node, &group->rtpoll_triggers);
1371 group->rtpoll_min_period = min(group->rtpoll_min_period,
1372 div_u64(t->win.size, UPDATES_PER_WINDOW));
1373 group->rtpoll_nr_triggers[t->state]++;
1374 group->rtpoll_states |= (1 << t->state);
1375
1376 mutex_unlock(&group->rtpoll_trigger_lock);
1377 } else {
1378 mutex_lock(&group->avgs_lock);
1379
1380 list_add(&t->node, &group->avg_triggers);
1381 group->avg_nr_triggers[t->state]++;
1382
1383 mutex_unlock(&group->avgs_lock);
1384 }
1385 return t;
1386 }
1387
psi_trigger_destroy(struct psi_trigger * t)1388 void psi_trigger_destroy(struct psi_trigger *t)
1389 {
1390 struct psi_group *group;
1391 struct task_struct *task_to_destroy = NULL;
1392
1393 /*
1394 * We do not check psi_disabled since it might have been disabled after
1395 * the trigger got created.
1396 */
1397 if (!t)
1398 return;
1399
1400 group = t->group;
1401 /*
1402 * Wakeup waiters to stop polling and clear the queue to prevent it from
1403 * being accessed later. Can happen if cgroup is deleted from under a
1404 * polling process.
1405 */
1406 if (t->of)
1407 kernfs_notify(t->of->kn);
1408 else
1409 wake_up_interruptible(&t->event_wait);
1410
1411 if (t->aggregator == PSI_AVGS) {
1412 mutex_lock(&group->avgs_lock);
1413 if (!list_empty(&t->node)) {
1414 list_del(&t->node);
1415 group->avg_nr_triggers[t->state]--;
1416 }
1417 mutex_unlock(&group->avgs_lock);
1418 } else {
1419 mutex_lock(&group->rtpoll_trigger_lock);
1420 if (!list_empty(&t->node)) {
1421 struct psi_trigger *tmp;
1422 u64 period = ULLONG_MAX;
1423
1424 list_del(&t->node);
1425 group->rtpoll_nr_triggers[t->state]--;
1426 if (!group->rtpoll_nr_triggers[t->state])
1427 group->rtpoll_states &= ~(1 << t->state);
1428 /*
1429 * Reset min update period for the remaining triggers
1430 * iff the destroying trigger had the min window size.
1431 */
1432 if (group->rtpoll_min_period == div_u64(t->win.size, UPDATES_PER_WINDOW)) {
1433 list_for_each_entry(tmp, &group->rtpoll_triggers, node)
1434 period = min(period, div_u64(tmp->win.size,
1435 UPDATES_PER_WINDOW));
1436 group->rtpoll_min_period = period;
1437 }
1438 /* Destroy rtpoll_task when the last trigger is destroyed */
1439 if (group->rtpoll_states == 0) {
1440 group->rtpoll_until = 0;
1441 task_to_destroy = rcu_dereference_protected(
1442 group->rtpoll_task,
1443 lockdep_is_held(&group->rtpoll_trigger_lock));
1444 rcu_assign_pointer(group->rtpoll_task, NULL);
1445 del_timer(&group->rtpoll_timer);
1446 }
1447 }
1448 mutex_unlock(&group->rtpoll_trigger_lock);
1449 }
1450
1451 /*
1452 * Wait for psi_schedule_rtpoll_work RCU to complete its read-side
1453 * critical section before destroying the trigger and optionally the
1454 * rtpoll_task.
1455 */
1456 synchronize_rcu();
1457 /*
1458 * Stop kthread 'psimon' after releasing rtpoll_trigger_lock to prevent
1459 * a deadlock while waiting for psi_rtpoll_work to acquire
1460 * rtpoll_trigger_lock
1461 */
1462 if (task_to_destroy) {
1463 /*
1464 * After the RCU grace period has expired, the worker
1465 * can no longer be found through group->rtpoll_task.
1466 */
1467 kthread_stop(task_to_destroy);
1468 atomic_set(&group->rtpoll_scheduled, 0);
1469 }
1470 kfree(t);
1471 }
1472
psi_trigger_poll(void ** trigger_ptr,struct file * file,poll_table * wait)1473 __poll_t psi_trigger_poll(void **trigger_ptr,
1474 struct file *file, poll_table *wait)
1475 {
1476 __poll_t ret = DEFAULT_POLLMASK;
1477 struct psi_trigger *t;
1478
1479 if (static_branch_likely(&psi_disabled))
1480 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1481
1482 t = smp_load_acquire(trigger_ptr);
1483 if (!t)
1484 return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
1485
1486 if (t->of)
1487 kernfs_generic_poll(t->of, wait);
1488 else
1489 poll_wait(file, &t->event_wait, wait);
1490
1491 if (cmpxchg(&t->event, 1, 0) == 1)
1492 ret |= EPOLLPRI;
1493
1494 return ret;
1495 }
1496
1497 #ifdef CONFIG_PROC_FS
psi_io_show(struct seq_file * m,void * v)1498 static int psi_io_show(struct seq_file *m, void *v)
1499 {
1500 return psi_show(m, &psi_system, PSI_IO);
1501 }
1502
psi_memory_show(struct seq_file * m,void * v)1503 static int psi_memory_show(struct seq_file *m, void *v)
1504 {
1505 return psi_show(m, &psi_system, PSI_MEM);
1506 }
1507
psi_cpu_show(struct seq_file * m,void * v)1508 static int psi_cpu_show(struct seq_file *m, void *v)
1509 {
1510 return psi_show(m, &psi_system, PSI_CPU);
1511 }
1512
psi_io_open(struct inode * inode,struct file * file)1513 static int psi_io_open(struct inode *inode, struct file *file)
1514 {
1515 return single_open(file, psi_io_show, NULL);
1516 }
1517
psi_memory_open(struct inode * inode,struct file * file)1518 static int psi_memory_open(struct inode *inode, struct file *file)
1519 {
1520 return single_open(file, psi_memory_show, NULL);
1521 }
1522
psi_cpu_open(struct inode * inode,struct file * file)1523 static int psi_cpu_open(struct inode *inode, struct file *file)
1524 {
1525 return single_open(file, psi_cpu_show, NULL);
1526 }
1527
psi_write(struct file * file,const char __user * user_buf,size_t nbytes,enum psi_res res)1528 static ssize_t psi_write(struct file *file, const char __user *user_buf,
1529 size_t nbytes, enum psi_res res)
1530 {
1531 char buf[32];
1532 size_t buf_size;
1533 struct seq_file *seq;
1534 struct psi_trigger *new;
1535
1536 if (static_branch_likely(&psi_disabled))
1537 return -EOPNOTSUPP;
1538
1539 if (!nbytes)
1540 return -EINVAL;
1541
1542 buf_size = min(nbytes, sizeof(buf));
1543 if (copy_from_user(buf, user_buf, buf_size))
1544 return -EFAULT;
1545
1546 buf[buf_size - 1] = '\0';
1547
1548 seq = file->private_data;
1549
1550 /* Take seq->lock to protect seq->private from concurrent writes */
1551 mutex_lock(&seq->lock);
1552
1553 /* Allow only one trigger per file descriptor */
1554 if (seq->private) {
1555 mutex_unlock(&seq->lock);
1556 return -EBUSY;
1557 }
1558
1559 new = psi_trigger_create(&psi_system, buf, res, file, NULL);
1560 if (IS_ERR(new)) {
1561 mutex_unlock(&seq->lock);
1562 return PTR_ERR(new);
1563 }
1564
1565 smp_store_release(&seq->private, new);
1566 mutex_unlock(&seq->lock);
1567
1568 return nbytes;
1569 }
1570
psi_io_write(struct file * file,const char __user * user_buf,size_t nbytes,loff_t * ppos)1571 static ssize_t psi_io_write(struct file *file, const char __user *user_buf,
1572 size_t nbytes, loff_t *ppos)
1573 {
1574 return psi_write(file, user_buf, nbytes, PSI_IO);
1575 }
1576
psi_memory_write(struct file * file,const char __user * user_buf,size_t nbytes,loff_t * ppos)1577 static ssize_t psi_memory_write(struct file *file, const char __user *user_buf,
1578 size_t nbytes, loff_t *ppos)
1579 {
1580 return psi_write(file, user_buf, nbytes, PSI_MEM);
1581 }
1582
psi_cpu_write(struct file * file,const char __user * user_buf,size_t nbytes,loff_t * ppos)1583 static ssize_t psi_cpu_write(struct file *file, const char __user *user_buf,
1584 size_t nbytes, loff_t *ppos)
1585 {
1586 return psi_write(file, user_buf, nbytes, PSI_CPU);
1587 }
1588
psi_fop_poll(struct file * file,poll_table * wait)1589 static __poll_t psi_fop_poll(struct file *file, poll_table *wait)
1590 {
1591 struct seq_file *seq = file->private_data;
1592
1593 return psi_trigger_poll(&seq->private, file, wait);
1594 }
1595
psi_fop_release(struct inode * inode,struct file * file)1596 static int psi_fop_release(struct inode *inode, struct file *file)
1597 {
1598 struct seq_file *seq = file->private_data;
1599
1600 psi_trigger_destroy(seq->private);
1601 return single_release(inode, file);
1602 }
1603
1604 static const struct proc_ops psi_io_proc_ops = {
1605 .proc_open = psi_io_open,
1606 .proc_read = seq_read,
1607 .proc_lseek = seq_lseek,
1608 .proc_write = psi_io_write,
1609 .proc_poll = psi_fop_poll,
1610 .proc_release = psi_fop_release,
1611 };
1612
1613 static const struct proc_ops psi_memory_proc_ops = {
1614 .proc_open = psi_memory_open,
1615 .proc_read = seq_read,
1616 .proc_lseek = seq_lseek,
1617 .proc_write = psi_memory_write,
1618 .proc_poll = psi_fop_poll,
1619 .proc_release = psi_fop_release,
1620 };
1621
1622 static const struct proc_ops psi_cpu_proc_ops = {
1623 .proc_open = psi_cpu_open,
1624 .proc_read = seq_read,
1625 .proc_lseek = seq_lseek,
1626 .proc_write = psi_cpu_write,
1627 .proc_poll = psi_fop_poll,
1628 .proc_release = psi_fop_release,
1629 };
1630
1631 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
psi_irq_show(struct seq_file * m,void * v)1632 static int psi_irq_show(struct seq_file *m, void *v)
1633 {
1634 return psi_show(m, &psi_system, PSI_IRQ);
1635 }
1636
psi_irq_open(struct inode * inode,struct file * file)1637 static int psi_irq_open(struct inode *inode, struct file *file)
1638 {
1639 return single_open(file, psi_irq_show, NULL);
1640 }
1641
psi_irq_write(struct file * file,const char __user * user_buf,size_t nbytes,loff_t * ppos)1642 static ssize_t psi_irq_write(struct file *file, const char __user *user_buf,
1643 size_t nbytes, loff_t *ppos)
1644 {
1645 return psi_write(file, user_buf, nbytes, PSI_IRQ);
1646 }
1647
1648 static const struct proc_ops psi_irq_proc_ops = {
1649 .proc_open = psi_irq_open,
1650 .proc_read = seq_read,
1651 .proc_lseek = seq_lseek,
1652 .proc_write = psi_irq_write,
1653 .proc_poll = psi_fop_poll,
1654 .proc_release = psi_fop_release,
1655 };
1656 #endif
1657
psi_proc_init(void)1658 static int __init psi_proc_init(void)
1659 {
1660 if (psi_enable) {
1661 proc_mkdir("pressure", NULL);
1662 proc_create("pressure/io", 0, NULL, &psi_io_proc_ops);
1663 proc_create("pressure/memory", 0, NULL, &psi_memory_proc_ops);
1664 proc_create("pressure/cpu", 0, NULL, &psi_cpu_proc_ops);
1665 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1666 proc_create("pressure/irq", 0, NULL, &psi_irq_proc_ops);
1667 #endif
1668 }
1669 return 0;
1670 }
1671 module_init(psi_proc_init);
1672
1673 #endif /* CONFIG_PROC_FS */
1674