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