// SPDX-License-Identifier: GPL-2.0/* * Pressure stall information for CPU, memory and IO * * Copyright (c) 2018 Facebook, Inc. * Author: Johannes Weiner <hannes@cmpxchg.org> * * Polling support by Suren Baghdasaryan <surenb@google.com> * Copyright (c) 2018 Google, Inc. * * When CPU, memory and IO are contended, tasks experience delays that * reduce throughput and introduce latencies into the workload. Memory * and IO contention, in addition, can cause a full loss of forward * progress in which the CPU goes idle. * * This code aggregates individual task delays into resource pressure * metrics that indicate problems with both workload health and * resource utilization. * * Model * * The time in which a task can execute on a CPU is our baseline for * productivity. Pressure expresses the amount of time in which this * potential cannot be realized due to resource contention. * * This concept of productivity has two components: the workload and * the CPU. To measure the impact of pressure on both, we define two * contention states for a resource: SOME and FULL. * * In the SOME state of a given resource, one or more tasks are * delayed on that resource. This affects the workload's ability to * perform work, but the CPU may still be executing other tasks. * * In the FULL state of a given resource, all non-idle tasks are * delayed on that resource such that nobody is advancing and the CPU * goes idle. This leaves both workload and CPU unproductive. * * SOME = nr_delayed_tasks != 0 * FULL = nr_delayed_tasks != 0 && nr_productive_tasks == 0 * * What it means for a task to be productive is defined differently * for each resource. For IO, productive means a running task. For * memory, productive means a running task that isn't a reclaimer. For * CPU, productive means an on-CPU task. * * Naturally, the FULL state doesn't exist for the CPU resource at the * system level, but exist at the cgroup level. At the cgroup level, * FULL means all non-idle tasks in the cgroup are delayed on the CPU * resource which is being used by others outside of the cgroup or * throttled by the cgroup cpu.max configuration. * * The percentage of wall clock time spent in those compound stall * states gives pressure numbers between 0 and 100 for each resource, * where the SOME percentage indicates workload slowdowns and the FULL * percentage indicates reduced CPU utilization: * * %SOME = time(SOME) / period * %FULL = time(FULL) / period * * Multiple CPUs * * The more tasks and available CPUs there are, the more work can be * performed concurrently. This means that the potential that can go * unrealized due to resource contention *also* scales with non-idle * tasks and CPUs. * * Consider a scenario where 257 number crunching tasks are trying to * run concurrently on 256 CPUs. If we simply aggregated the task * states, we would have to conclude a CPU SOME pressure number of * 100%, since *somebody* is waiting on a runqueue at all * times. However, that is clearly not the amount of contention the * workload is experiencing: only one out of 256 possible execution * threads will be contended at any given time, or about 0.4%. * * Conversely, consider a scenario of 4 tasks and 4 CPUs where at any * given time *one* of the tasks is delayed due to a lack of memory. * Again, looking purely at the task state would yield a memory FULL * pressure number of 0%, since *somebody* is always making forward * progress. But again this wouldn't capture the amount of execution * potential lost, which is 1 out of 4 CPUs, or 25%. * * To calculate wasted potential (pressure) with multiple processors, * we have to base our calculation on the number of non-idle tasks in * conjunction with the number of available CPUs, which is the number * of potential execution threads. SOME becomes then the proportion of * delayed tasks to possible threads, and FULL is the share of possible * threads that are unproductive due to delays: * * threads = min(nr_nonidle_tasks, nr_cpus) * SOME = min(nr_delayed_tasks / threads, 1) * FULL = (threads - min(nr_productive_tasks, threads)) / threads * * For the 257 number crunchers on 256 CPUs, this yields: * * threads = min(257, 256) * SOME = min(1 / 256, 1) = 0.4% * FULL = (256 - min(256, 256)) / 256 = 0% * * For the 1 out of 4 memory-delayed tasks, this yields: * * threads = min(4, 4) * SOME = min(1 / 4, 1) = 25% * FULL = (4 - min(3, 4)) / 4 = 25% * * [ Substitute nr_cpus with 1, and you can see that it's a natural * extension of the single-CPU model. ] * * Implementation * * To assess the precise time spent in each such state, we would have * to freeze the system on task changes and start/stop the state * clocks accordingly. Obviously that doesn't scale in practice. * * Because the scheduler aims to distribute the compute load evenly * among the available CPUs, we can track task state locally to each * CPU and, at much lower frequency, extrapolate the global state for * the cumulative stall times and the running averages. * * For each runqueue, we track: * * tSOME[cpu] = time(nr_delayed_tasks[cpu] != 0) * tFULL[cpu] = time(nr_delayed_tasks[cpu] && !nr_productive_tasks[cpu]) * tNONIDLE[cpu] = time(nr_nonidle_tasks[cpu] != 0) * * and then periodically aggregate: * * tNONIDLE = sum(tNONIDLE[i]) * * tSOME = sum(tSOME[i] * tNONIDLE[i]) / tNONIDLE * tFULL = sum(tFULL[i] * tNONIDLE[i]) / tNONIDLE * * %SOME = tSOME / period * %FULL = tFULL / period * * This gives us an approximation of pressure that is practical * cost-wise, yet way more sensitive and accurate than periodic * sampling of the aggregate task states would be. */#include <linux/sched/clock.h>#include <linux/workqueue.h>#include <linux/psi.h>#include "sched.h" static int psi_bug __read_mostly; DEFINE_STATIC_KEY_FALSE(psi_disabled);static DEFINE_STATIC_KEY_TRUE(psi_cgroups_enabled); #ifdef CONFIG_PSI_DEFAULT_DISABLEDstatic bool psi_enable;#elsestatic bool psi_enable = true;#endifstatic int __init setup_psi(char *str){ return kstrtobool(str, &psi_enable) == 0;}__setup("psi=", setup_psi); /* Running averages - we need to be higher-res than loadavg */#define PSI_FREQ (2*HZ+1) /* 2 sec intervals */#define EXP_10s 1677 /* 1/exp(2s/10s) as fixed-point */#define EXP_60s 1981 /* 1/exp(2s/60s) */#define EXP_300s 2034 /* 1/exp(2s/300s) */ /* PSI trigger definitions */#define WINDOW_MAX_US 10000000 /* Max window size is 10s */#define UPDATES_PER_WINDOW 10 /* 10 updates per window */ /* Sampling frequency in nanoseconds */static u64 psi_period __read_mostly; /* System-level pressure and stall tracking */static DEFINE_PER_CPU(struct psi_group_cpu, system_group_pcpu);struct psi_group psi_system = { .pcpu = &system_group_pcpu,}; static DEFINE_PER_CPU(seqcount_t, psi_seq) = SEQCNT_ZERO(psi_seq); static inline void psi_write_begin(int cpu){ write_seqcount_begin(per_cpu_ptr(&psi_seq, cpu));} static inline void psi_write_end(int cpu){ write_seqcount_end(per_cpu_ptr(&psi_seq, cpu));} static inline u32 psi_read_begin(int cpu){ return read_seqcount_begin(per_cpu_ptr(&psi_seq, cpu));} static inline bool psi_read_retry(int cpu, u32 seq){ return read_seqcount_retry(per_cpu_ptr(&psi_seq, cpu), seq);} static void psi_avgs_work(struct work_struct *work); static void poll_timer_fn(struct timer_list *t); static void group_init(struct psi_group *group){ group->enabled = true; group->avg_last_update = sched_clock(); group->avg_next_update = group->avg_last_update + psi_period; mutex_init(&group->avgs_lock); /* Init avg trigger-related members */ INIT_LIST_HEAD(&group->avg_triggers); memset(group->avg_nr_triggers, 0, sizeof(group->avg_nr_triggers)); INIT_DELAYED_WORK(&group->avgs_work, psi_avgs_work); /* Init rtpoll trigger-related members */ atomic_set(&group->rtpoll_scheduled, 0); mutex_init(&group->rtpoll_trigger_lock); INIT_LIST_HEAD(&group->rtpoll_triggers); group->rtpoll_min_period = U32_MAX; group->rtpoll_next_update = ULLONG_MAX; init_waitqueue_head(&group->rtpoll_wait); timer_setup(&group->rtpoll_timer, poll_timer_fn, 0); rcu_assign_pointer(group->rtpoll_task, NULL);} void __init psi_init(void){ if (!psi_enable) { static_branch_enable(&psi_disabled); static_branch_disable(&psi_cgroups_enabled); return; } if (!cgroup_psi_enabled()) static_branch_disable(&psi_cgroups_enabled); psi_period = jiffies_to_nsecs(PSI_FREQ); group_init(&psi_system);} static u32 test_states(unsigned int *tasks, u32 state_mask){ const bool oncpu = state_mask & PSI_ONCPU; if (tasks[NR_IOWAIT]) { state_mask |= BIT(PSI_IO_SOME); if (!tasks[NR_RUNNING]) state_mask |= BIT(PSI_IO_FULL); } if (tasks[NR_MEMSTALL]) { state_mask |= BIT(PSI_MEM_SOME); if (tasks[NR_RUNNING] == tasks[NR_MEMSTALL_RUNNING]) state_mask |= BIT(PSI_MEM_FULL); } if (tasks[NR_RUNNING] > oncpu) state_mask |= BIT(PSI_CPU_SOME); if (tasks[NR_RUNNING] && !oncpu) state_mask |= BIT(PSI_CPU_FULL); if (tasks[NR_IOWAIT] || tasks[NR_MEMSTALL] || tasks[NR_RUNNING]) state_mask |= BIT(PSI_NONIDLE); return state_mask;} static void get_recent_times(struct psi_group *group, int cpu, enum psi_aggregators aggregator, u32 *times, u32 *pchanged_states){ struct psi_group_cpu *groupc = per_cpu_ptr(group->pcpu, cpu); int current_cpu = raw_smp_processor_id(); unsigned int tasks[NR_PSI_TASK_COUNTS]; u64 now, state_start; enum psi_states s; unsigned int seq; u32 state_mask; *pchanged_states = 0; /* Snapshot a coherent view of the CPU state */ do { seq = psi_read_begin(cpu); now = cpu_clock(cpu); memcpy(times, groupc->times, sizeof(groupc->times)); state_mask = groupc->state_mask; state_start = groupc->state_start; if (cpu == current_cpu) memcpy(tasks, groupc->tasks, sizeof(groupc->tasks)); } while (psi_read_retry(cpu, seq)); /* Calculate state time deltas against the previous snapshot */ for (s = 0; s < NR_PSI_STATES; s++) { u32 delta; /* * In addition to already concluded states, we also * incorporate currently active states on the CPU, * since states may last for many sampling periods. * * This way we keep our delta sampling buckets small * (u32) and our reported pressure close to what's * actually happening. */ if (state_mask & (1 << s)) times[s] += now - state_start; delta = times[s] - groupc->times_prev[aggregator][s]; groupc->times_prev[aggregator][s] = times[s]; times[s] = delta; if (delta) *pchanged_states |= (1 << s); } /* * When collect_percpu_times() from the avgs_work, we don't want to * re-arm avgs_work when all CPUs are IDLE. But the current CPU running * this avgs_work is never IDLE, cause avgs_work can't be shut off. * So for the current CPU, we need to re-arm avgs_work only when * (NR_RUNNING > 1 || NR_IOWAIT > 0 || NR_MEMSTALL > 0), for other CPUs * we can just check PSI_NONIDLE delta. */ if (current_work() == &group->avgs_work.work) { bool reschedule; if (cpu == current_cpu) reschedule = tasks[NR_RUNNING] + tasks[NR_IOWAIT] + tasks[NR_MEMSTALL] > 1; else reschedule = *pchanged_states & (1 << PSI_NONIDLE); if (reschedule) *pchanged_states |= PSI_STATE_RESCHEDULE; }} static void calc_avgs(unsigned long avg[3], int missed_periods, u64 time, u64 period){ unsigned long pct; /* Fill in zeroes for periods of no activity */ if (missed_periods) { avg[0] = calc_load_n(avg[0], EXP_10s, 0, missed_periods); avg[1] = calc_load_n(avg[1], EXP_60s, 0, missed_periods); avg[2] = calc_load_n(avg[2], EXP_300s, 0, missed_periods); } /* Sample the most recent active period */ pct = div_u64(time * 100, period); pct *= FIXED_1; avg[0] = calc_load(avg[0], EXP_10s, pct); avg[1] = calc_load(avg[1], EXP_60s, pct); avg[2] = calc_load(avg[2], EXP_300s, pct);} static void collect_percpu_times(struct psi_group *group, enum psi_aggregators aggregator, u32 *pchanged_states){ u64 deltas[NR_PSI_STATES - 1] = { 0, }; unsigned long nonidle_total = 0; u32 changed_states = 0; int cpu; int s; /* * Collect the per-cpu time buckets and average them into a * single time sample that is normalized to wall clock time. * * For averaging, each CPU is weighted by its non-idle time in * the sampling period. This eliminates artifacts from uneven * loading, or even entirely idle CPUs. */ for_each_possible_cpu(cpu) { u32 times[NR_PSI_STATES]; u32 nonidle; u32 cpu_changed_states; get_recent_times(group, cpu, aggregator, times, &cpu_changed_states); changed_states |= cpu_changed_states; nonidle = nsecs_to_jiffies(times[PSI_NONIDLE]); nonidle_total += nonidle; for (s = 0; s < PSI_NONIDLE; s++) deltas[s] += (u64)times[s] * nonidle; } /* * Integrate the sample into the running statistics that are * reported to userspace: the cumulative stall times and the * decaying averages. * * Pressure percentages are sampled at PSI_FREQ. We might be * called more often when the user polls more frequently than * that; we might be called less often when there is no task * activity, thus no data, and clock ticks are sporadic. The * below handles both. */ /* total= */ for (s = 0; s < NR_PSI_STATES - 1; s++) group->total[aggregator][s] += div_u64(deltas[s], max(nonidle_total, 1UL)); if (pchanged_states) *pchanged_states = changed_states;} /* Trigger tracking window manipulations */static void window_reset(struct psi_window *win, u64 now, u64 value, u64 prev_growth){ win->start_time = now; win->start_value = value; win->prev_growth = prev_growth;} /* * PSI growth tracking window update and growth calculation routine. * * This approximates a sliding tracking window by interpolating * partially elapsed windows using historical growth data from the * previous intervals. This minimizes memory requirements (by not storing * all the intermediate values in the previous window) and simplifies * the calculations. It works well because PSI signal changes only in * positive direction and over relatively small window sizes the growth * is close to linear. */static u64 window_update(struct psi_window *win, u64 now, u64 value){ u64 elapsed; u64 growth; elapsed = now - win->start_time; growth = value - win->start_value; /* * After each tracking window passes win->start_value and * win->start_time get reset and win->prev_growth stores * the average per-window growth of the previous window. * win->prev_growth is then used to interpolate additional * growth from the previous window assuming it was linear. */ if (elapsed > win->size) window_reset(win, now, value, growth); else { u32 remaining; remaining = win->size - elapsed; growth += div64_u64(win->prev_growth * remaining, win->size); } return growth;} static void update_triggers(struct psi_group *group, u64 now, enum psi_aggregators aggregator){ struct psi_trigger *t; u64 *total = group->total[aggregator]; struct list_head *triggers; u64 *aggregator_total; if (aggregator == PSI_AVGS) { triggers = &group->avg_triggers; aggregator_total = group->avg_total; } else { triggers = &group->rtpoll_triggers; aggregator_total = group->rtpoll_total; } /* * On subsequent updates, calculate growth deltas and let * watchers know when their specified thresholds are exceeded. */ list_for_each_entry(t, triggers, node) { u64 growth; bool new_stall; new_stall = aggregator_total[t->state] != total[t->state]; /* Check for stall activity or a previous threshold breach */ if (!new_stall && !t->pending_event) continue; /* * Check for new stall activity, as well as deferred * events that occurred in the last window after the * trigger had already fired (we want to ratelimit * events without dropping any). */ if (new_stall) { /* Calculate growth since last update */ growth = window_update(&t->win, now, total[t->state]);Lines 1–500 of 1725. Load more
// SPDX-License-Identifier: GPL-2.0 /* * Pressure stall information for CPU, memory and IO * * Copyright (c) 2018 Facebook, Inc. * Author: Johannes Weiner <hannes@cmpxchg.org> * * Polling support by Suren Baghdasaryan <surenb@google.com> * Copyright (c) 2018 Google, Inc. * * When CPU, memory and IO are contended, tasks experience delays that * reduce throughput and introduce latencies into the workload. Memory * and IO contention, in addition, can cause a full loss of forward * progress in which the CPU goes idle. * * This code aggregates individual task delays into resource pressure * metrics that indicate problems with both workload health and * resource utilization. * * Model * * The time in which a task can execute on a CPU is our baseline for * productivity. Pressure expresses the amount of time in which this * potential cannot be realized due to resource contention. * * This concept of productivity has two components: the workload and * the CPU. To measure the impact of pressure on both, we define two * contention states for a resource: SOME and FULL. * * In the SOME state of a given resource, one or more tasks are * delayed on that resource. This affects the workload's ability to * perform work, but the CPU may still be executing other tasks. * * In the FULL state of a given resource, all non-idle tasks are * delayed on that resource such that nobody is advancing and the CPU * goes idle. This leaves both workload and CPU unproductive. * * SOME = nr_delayed_tasks != 0 * FULL = nr_delayed_tasks != 0 && nr_productive_tasks == 0 * * What it means for a task to be productive is defined differently * for each resource. For IO, productive means a running task. For * memory, productive means a running task that isn't a reclaimer. For * CPU, productive means an on-CPU task. * * Naturally, the FULL state doesn't exist for the CPU resource at the * system level, but exist at the cgroup level. At the cgroup level, * FULL means all non-idle tasks in the cgroup are delayed on the CPU * resource which is being used by others outside of the cgroup or * throttled by the cgroup cpu.max configuration. * * The percentage of wall clock time spent in those compound stall * states gives pressure numbers between 0 and 100 for each resource, * where the SOME percentage indicates workload slowdowns and the FULL * percentage indicates reduced CPU utilization: * * %SOME = time(SOME) / period * %FULL = time(FULL) / period * * Multiple CPUs * * The more tasks and available CPUs there are, the more work can be * performed concurrently. This means that the potential that can go * unrealized due to resource contention *also* scales with non-idle * tasks and CPUs. * * Consider a scenario where 257 number crunching tasks are trying to * run concurrently on 256 CPUs. If we simply aggregated the task * states, we would have to conclude a CPU SOME pressure number of * 100%, since *somebody* is waiting on a runqueue at all * times. However, that is clearly not the amount of contention the * workload is experiencing: only one out of 256 possible execution * threads will be contended at any given time, or about 0.4%. * * Conversely, consider a scenario of 4 tasks and 4 CPUs where at any * given time *one* of the tasks is delayed due to a lack of memory. * Again, looking purely at the task state would yield a memory FULL * pressure number of 0%, since *somebody* is always making forward * progress. But again this wouldn't capture the amount of execution * potential lost, which is 1 out of 4 CPUs, or 25%. * * To calculate wasted potential (pressure) with multiple processors, * we have to base our calculation on the number of non-idle tasks in * conjunction with the number of available CPUs, which is the number * of potential execution threads. SOME becomes then the proportion of * delayed tasks to possible threads, and FULL is the share of possible * threads that are unproductive due to delays: * * threads = min(nr_nonidle_tasks, nr_cpus) * SOME = min(nr_delayed_tasks / threads, 1) * FULL = (threads - min(nr_productive_tasks, threads)) / threads * * For the 257 number crunchers on 256 CPUs, this yields: * * threads = min(257, 256) * SOME = min(1 / 256, 1) = 0.4% * FULL = (256 - min(256, 256)) / 256 = 0% * * For the 1 out of 4 memory-delayed tasks, this yields: * * threads = min(4, 4) * SOME = min(1 / 4, 1) = 25% * FULL = (4 - min(3, 4)) / 4 = 25% * * [ Substitute nr_cpus with 1, and you can see that it's a natural * extension of the single-CPU model. ] * * Implementation * * To assess the precise time spent in each such state, we would have * to freeze the system on task changes and start/stop the state * clocks accordingly. Obviously that doesn't scale in practice. * * Because the scheduler aims to distribute the compute load evenly * among the available CPUs, we can track task state locally to each * CPU and, at much lower frequency, extrapolate the global state for * the cumulative stall times and the running averages. * * For each runqueue, we track: * * tSOME[cpu] = time(nr_delayed_tasks[cpu] != 0) * tFULL[cpu] = time(nr_delayed_tasks[cpu] && !nr_productive_tasks[cpu]) * tNONIDLE[cpu] = time(nr_nonidle_tasks[cpu] != 0) * * and then periodically aggregate: * * tNONIDLE = sum(tNONIDLE[i]) * * tSOME = sum(tSOME[i] * tNONIDLE[i]) / tNONIDLE * tFULL = sum(tFULL[i] * tNONIDLE[i]) / tNONIDLE * * %SOME = tSOME / period * %FULL = tFULL / period * * This gives us an approximation of pressure that is practical * cost-wise, yet way more sensitive and accurate than periodic * sampling of the aggregate task states would be. */ #include <linux/sched/clock.h> #include <linux/workqueue.h> #include <linux/psi.h> #include "sched.h" static int psi_bug __read_mostly; DEFINE_STATIC_KEY_FALSE(psi_disabled); static DEFINE_STATIC_KEY_TRUE(psi_cgroups_enabled); #ifdef CONFIG_PSI_DEFAULT_DISABLED static bool psi_enable; #else static bool psi_enable = true; #endif static int __init setup_psi(char *str) { return kstrtobool(str, &psi_enable) == 0; } __setup("psi=", setup_psi); /* Running averages - we need to be higher-res than loadavg */ #define PSI_FREQ (2*HZ+1) /* 2 sec intervals */ #define EXP_10s 1677 /* 1/exp(2s/10s) as fixed-point */ #define EXP_60s 1981 /* 1/exp(2s/60s) */ #define EXP_300s 2034 /* 1/exp(2s/300s) */ /* PSI trigger definitions */ #define WINDOW_MAX_US 10000000 /* Max window size is 10s */ #define UPDATES_PER_WINDOW 10 /* 10 updates per window */ /* Sampling frequency in nanoseconds */ static u64 psi_period __read_mostly; /* System-level pressure and stall tracking */ static DEFINE_PER_CPU(struct psi_group_cpu, system_group_pcpu); struct psi_group psi_system = { .pcpu = &system_group_pcpu, }; static DEFINE_PER_CPU(seqcount_t, psi_seq) = SEQCNT_ZERO(psi_seq); static inline void psi_write_begin(int cpu) { write_seqcount_begin(per_cpu_ptr(&psi_seq, cpu)); } static inline void psi_write_end(int cpu) { write_seqcount_end(per_cpu_ptr(&psi_seq, cpu)); } static inline u32 psi_read_begin(int cpu) { return read_seqcount_begin(per_cpu_ptr(&psi_seq, cpu)); } static inline bool psi_read_retry(int cpu, u32 seq) { return read_seqcount_retry(per_cpu_ptr(&psi_seq, cpu), seq); } static void psi_avgs_work(struct work_struct *work); static void poll_timer_fn(struct timer_list *t); static void group_init(struct psi_group *group) { group->enabled = true; group->avg_last_update = sched_clock(); group->avg_next_update = group->avg_last_update + psi_period; mutex_init(&group->avgs_lock); /* Init avg trigger-related members */ INIT_LIST_HEAD(&group->avg_triggers); memset(group->avg_nr_triggers, 0, sizeof(group->avg_nr_triggers)); INIT_DELAYED_WORK(&group->avgs_work, psi_avgs_work); /* Init rtpoll trigger-related members */ atomic_set(&group->rtpoll_scheduled, 0); mutex_init(&group->rtpoll_trigger_lock); INIT_LIST_HEAD(&group->rtpoll_triggers); group->rtpoll_min_period = U32_MAX; group->rtpoll_next_update = ULLONG_MAX; init_waitqueue_head(&group->rtpoll_wait); timer_setup(&group->rtpoll_timer, poll_timer_fn, 0); rcu_assign_pointer(group->rtpoll_task, NULL); } void __init psi_init(void) { if (!psi_enable) { static_branch_enable(&psi_disabled); static_branch_disable(&psi_cgroups_enabled); return; } if (!cgroup_psi_enabled()) static_branch_disable(&psi_cgroups_enabled); psi_period = jiffies_to_nsecs(PSI_FREQ); group_init(&psi_system); } static u32 test_states(unsigned int *tasks, u32 state_mask) { const bool oncpu = state_mask & PSI_ONCPU; if (tasks[NR_IOWAIT]) { state_mask |= BIT(PSI_IO_SOME); if (!tasks[NR_RUNNING]) state_mask |= BIT(PSI_IO_FULL); } if (tasks[NR_MEMSTALL]) { state_mask |= BIT(PSI_MEM_SOME); if (tasks[NR_RUNNING] == tasks[NR_MEMSTALL_RUNNING]) state_mask |= BIT(PSI_MEM_FULL); } if (tasks[NR_RUNNING] > oncpu) state_mask |= BIT(PSI_CPU_SOME); if (tasks[NR_RUNNING] && !oncpu) state_mask |= BIT(PSI_CPU_FULL); if (tasks[NR_IOWAIT] || tasks[NR_MEMSTALL] || tasks[NR_RUNNING]) state_mask |= BIT(PSI_NONIDLE); return state_mask; } static void get_recent_times(struct psi_group *group, int cpu, enum psi_aggregators aggregator, u32 *times, u32 *pchanged_states) { struct psi_group_cpu *groupc = per_cpu_ptr(group->pcpu, cpu); int current_cpu = raw_smp_processor_id(); unsigned int tasks[NR_PSI_TASK_COUNTS]; u64 now, state_start; enum psi_states s; unsigned int seq; u32 state_mask; *pchanged_states = 0; /* Snapshot a coherent view of the CPU state */ do { seq = psi_read_begin(cpu); now = cpu_clock(cpu); memcpy(times, groupc->times, sizeof(groupc->times)); state_mask = groupc->state_mask; state_start = groupc->state_start; if (cpu == current_cpu) memcpy(tasks, groupc->tasks, sizeof(groupc->tasks)); } while (psi_read_retry(cpu, seq)); /* Calculate state time deltas against the previous snapshot */ for (s = 0; s < NR_PSI_STATES; s++) { u32 delta; /* * In addition to already concluded states, we also * incorporate currently active states on the CPU, * since states may last for many sampling periods. * * This way we keep our delta sampling buckets small * (u32) and our reported pressure close to what's * actually happening. */ if (state_mask & (1 << s)) times[s] += now - state_start; delta = times[s] - groupc->times_prev[aggregator][s]; groupc->times_prev[aggregator][s] = times[s]; times[s] = delta; if (delta) *pchanged_states |= (1 << s); } /* * When collect_percpu_times() from the avgs_work, we don't want to * re-arm avgs_work when all CPUs are IDLE. But the current CPU running * this avgs_work is never IDLE, cause avgs_work can't be shut off. * So for the current CPU, we need to re-arm avgs_work only when * (NR_RUNNING > 1 || NR_IOWAIT > 0 || NR_MEMSTALL > 0), for other CPUs * we can just check PSI_NONIDLE delta. */ if (current_work() == &group->avgs_work.work) { bool reschedule; if (cpu == current_cpu) reschedule = tasks[NR_RUNNING] + tasks[NR_IOWAIT] + tasks[NR_MEMSTALL] > 1; else reschedule = *pchanged_states & (1 << PSI_NONIDLE); if (reschedule) *pchanged_states |= PSI_STATE_RESCHEDULE; } } static void calc_avgs(unsigned long avg[3], int missed_periods, u64 time, u64 period) { unsigned long pct; /* Fill in zeroes for periods of no activity */ if (missed_periods) { avg[0] = calc_load_n(avg[0], EXP_10s, 0, missed_periods); avg[1] = calc_load_n(avg[1], EXP_60s, 0, missed_periods); avg[2] = calc_load_n(avg[2], EXP_300s, 0, missed_periods); } /* Sample the most recent active period */ pct = div_u64(time * 100, period); pct *= FIXED_1; avg[0] = calc_load(avg[0], EXP_10s, pct); avg[1] = calc_load(avg[1], EXP_60s, pct); avg[2] = calc_load(avg[2], EXP_300s, pct); } static void collect_percpu_times(struct psi_group *group, enum psi_aggregators aggregator, u32 *pchanged_states) { u64 deltas[NR_PSI_STATES - 1] = { 0, }; unsigned long nonidle_total = 0; u32 changed_states = 0; int cpu; int s; /* * Collect the per-cpu time buckets and average them into a * single time sample that is normalized to wall clock time. * * For averaging, each CPU is weighted by its non-idle time in * the sampling period. This eliminates artifacts from uneven * loading, or even entirely idle CPUs. */ for_each_possible_cpu(cpu) { u32 times[NR_PSI_STATES]; u32 nonidle; u32 cpu_changed_states; get_recent_times(group, cpu, aggregator, times, &cpu_changed_states); changed_states |= cpu_changed_states; nonidle = nsecs_to_jiffies(times[PSI_NONIDLE]); nonidle_total += nonidle; for (s = 0; s < PSI_NONIDLE; s++) deltas[s] += (u64)times[s] * nonidle; } /* * Integrate the sample into the running statistics that are * reported to userspace: the cumulative stall times and the * decaying averages. * * Pressure percentages are sampled at PSI_FREQ. We might be * called more often when the user polls more frequently than * that; we might be called less often when there is no task * activity, thus no data, and clock ticks are sporadic. The * below handles both. */ /* total= */ for (s = 0; s < NR_PSI_STATES - 1; s++) group->total[aggregator][s] += div_u64(deltas[s], max(nonidle_total, 1UL)); if (pchanged_states) *pchanged_states = changed_states; } /* Trigger tracking window manipulations */ static void window_reset(struct psi_window *win, u64 now, u64 value, u64 prev_growth) { win->start_time = now; win->start_value = value; win->prev_growth = prev_growth; } /* * PSI growth tracking window update and growth calculation routine. * * This approximates a sliding tracking window by interpolating * partially elapsed windows using historical growth data from the * previous intervals. This minimizes memory requirements (by not storing * all the intermediate values in the previous window) and simplifies * the calculations. It works well because PSI signal changes only in * positive direction and over relatively small window sizes the growth * is close to linear. */ static u64 window_update(struct psi_window *win, u64 now, u64 value) { u64 elapsed; u64 growth; elapsed = now - win->start_time; growth = value - win->start_value; /* * After each tracking window passes win->start_value and * win->start_time get reset and win->prev_growth stores * the average per-window growth of the previous window. * win->prev_growth is then used to interpolate additional * growth from the previous window assuming it was linear. */ if (elapsed > win->size) window_reset(win, now, value, growth); else { u32 remaining; remaining = win->size - elapsed; growth += div64_u64(win->prev_growth * remaining, win->size); } return growth; } static void update_triggers(struct psi_group *group, u64 now, enum psi_aggregators aggregator) { struct psi_trigger *t; u64 *total = group->total[aggregator]; struct list_head *triggers; u64 *aggregator_total; if (aggregator == PSI_AVGS) { triggers = &group->avg_triggers; aggregator_total = group->avg_total; } else { triggers = &group->rtpoll_triggers; aggregator_total = group->rtpoll_total; } /* * On subsequent updates, calculate growth deltas and let * watchers know when their specified thresholds are exceeded. */ list_for_each_entry(t, triggers, node) { u64 growth; bool new_stall; new_stall = aggregator_total[t->state] != total[t->state]; /* Check for stall activity or a previous threshold breach */ if (!new_stall && !t->pending_event) continue; /* * Check for new stall activity, as well as deferred * events that occurred in the last window after the * trigger had already fired (we want to ratelimit * events without dropping any). */ if (new_stall) { /* Calculate growth since last update */ growth = window_update(&t->win, now, total[t->state]);