1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * kernel/sched/loadavg.c
4 *
5 * This file contains the magic bits required to compute the global loadavg
6 * figure. Its a silly number but people think its important. We go through
7 * great pains to make it work on big machines and tickless kernels.
8 */
9
10 #include <linux/export.h>
11 #include <linux/sched/loadavg.h>
12
13 #include "sched.h"
14
15 /*
16 * Global load-average calculations
17 *
18 * We take a distributed and async approach to calculating the global load-avg
19 * in order to minimize overhead.
20 *
21 * The global load average is an exponentially decaying average of nr_running +
22 * nr_uninterruptible.
23 *
24 * Once every LOAD_FREQ:
25 *
26 * nr_active = 0;
27 * for_each_possible_cpu(cpu)
28 * nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
29 *
30 * avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
31 *
32 * Due to a number of reasons the above turns in the mess below:
33 *
34 * - for_each_possible_cpu() is prohibitively expensive on machines with
35 * serious number of cpus, therefore we need to take a distributed approach
36 * to calculating nr_active.
37 *
38 * \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
39 * = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
40 *
41 * So assuming nr_active := 0 when we start out -- true per definition, we
42 * can simply take per-cpu deltas and fold those into a global accumulate
43 * to obtain the same result. See calc_load_fold_active().
44 *
45 * Furthermore, in order to avoid synchronizing all per-cpu delta folding
46 * across the machine, we assume 10 ticks is sufficient time for every
47 * cpu to have completed this task.
48 *
49 * This places an upper-bound on the IRQ-off latency of the machine. Then
50 * again, being late doesn't loose the delta, just wrecks the sample.
51 *
52 * - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because
53 * this would add another cross-cpu cacheline miss and atomic operation
54 * to the wakeup path. Instead we increment on whatever cpu the task ran
55 * when it went into uninterruptible state and decrement on whatever cpu
56 * did the wakeup. This means that only the sum of nr_uninterruptible over
57 * all cpus yields the correct result.
58 *
59 * This covers the NO_HZ=n code, for extra head-aches, see the comment below.
60 */
61
62 /* Variables and functions for calc_load */
63 atomic_long_t calc_load_tasks;
64 unsigned long calc_load_update;
65 unsigned long avenrun[3];
66 EXPORT_SYMBOL(avenrun); /* should be removed */
67
68 /**
69 * get_avenrun - get the load average array
70 * @loads: pointer to dest load array
71 * @offset: offset to add
72 * @shift: shift count to shift the result left
73 *
74 * These values are estimates at best, so no need for locking.
75 */
get_avenrun(unsigned long * loads,unsigned long offset,int shift)76 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
77 {
78 loads[0] = (avenrun[0] + offset) << shift;
79 loads[1] = (avenrun[1] + offset) << shift;
80 loads[2] = (avenrun[2] + offset) << shift;
81 }
82
calc_load_fold_active(struct rq * this_rq,long adjust)83 long calc_load_fold_active(struct rq *this_rq, long adjust)
84 {
85 long nr_active, delta = 0;
86
87 nr_active = this_rq->nr_running - adjust;
88 nr_active += (long)this_rq->nr_uninterruptible;
89
90 if (nr_active != this_rq->calc_load_active) {
91 delta = nr_active - this_rq->calc_load_active;
92 this_rq->calc_load_active = nr_active;
93 }
94
95 return delta;
96 }
97
98 /**
99 * fixed_power_int - compute: x^n, in O(log n) time
100 *
101 * @x: base of the power
102 * @frac_bits: fractional bits of @x
103 * @n: power to raise @x to.
104 *
105 * By exploiting the relation between the definition of the natural power
106 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
107 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
108 * (where: n_i \elem {0, 1}, the binary vector representing n),
109 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
110 * of course trivially computable in O(log_2 n), the length of our binary
111 * vector.
112 */
113 static unsigned long
fixed_power_int(unsigned long x,unsigned int frac_bits,unsigned int n)114 fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
115 {
116 unsigned long result = 1UL << frac_bits;
117
118 if (n) {
119 for (;;) {
120 if (n & 1) {
121 result *= x;
122 result += 1UL << (frac_bits - 1);
123 result >>= frac_bits;
124 }
125 n >>= 1;
126 if (!n)
127 break;
128 x *= x;
129 x += 1UL << (frac_bits - 1);
130 x >>= frac_bits;
131 }
132 }
133
134 return result;
135 }
136
137 /*
138 * a1 = a0 * e + a * (1 - e)
139 *
140 * a2 = a1 * e + a * (1 - e)
141 * = (a0 * e + a * (1 - e)) * e + a * (1 - e)
142 * = a0 * e^2 + a * (1 - e) * (1 + e)
143 *
144 * a3 = a2 * e + a * (1 - e)
145 * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
146 * = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
147 *
148 * ...
149 *
150 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
151 * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
152 * = a0 * e^n + a * (1 - e^n)
153 *
154 * [1] application of the geometric series:
155 *
156 * n 1 - x^(n+1)
157 * S_n := \Sum x^i = -------------
158 * i=0 1 - x
159 */
160 unsigned long
calc_load_n(unsigned long load,unsigned long exp,unsigned long active,unsigned int n)161 calc_load_n(unsigned long load, unsigned long exp,
162 unsigned long active, unsigned int n)
163 {
164 return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
165 }
166
167 #ifdef CONFIG_NO_HZ_COMMON
168 /*
169 * Handle NO_HZ for the global load-average.
170 *
171 * Since the above described distributed algorithm to compute the global
172 * load-average relies on per-cpu sampling from the tick, it is affected by
173 * NO_HZ.
174 *
175 * The basic idea is to fold the nr_active delta into a global NO_HZ-delta upon
176 * entering NO_HZ state such that we can include this as an 'extra' cpu delta
177 * when we read the global state.
178 *
179 * Obviously reality has to ruin such a delightfully simple scheme:
180 *
181 * - When we go NO_HZ idle during the window, we can negate our sample
182 * contribution, causing under-accounting.
183 *
184 * We avoid this by keeping two NO_HZ-delta counters and flipping them
185 * when the window starts, thus separating old and new NO_HZ load.
186 *
187 * The only trick is the slight shift in index flip for read vs write.
188 *
189 * 0s 5s 10s 15s
190 * +10 +10 +10 +10
191 * |-|-----------|-|-----------|-|-----------|-|
192 * r:0 0 1 1 0 0 1 1 0
193 * w:0 1 1 0 0 1 1 0 0
194 *
195 * This ensures we'll fold the old NO_HZ contribution in this window while
196 * accumlating the new one.
197 *
198 * - When we wake up from NO_HZ during the window, we push up our
199 * contribution, since we effectively move our sample point to a known
200 * busy state.
201 *
202 * This is solved by pushing the window forward, and thus skipping the
203 * sample, for this cpu (effectively using the NO_HZ-delta for this cpu which
204 * was in effect at the time the window opened). This also solves the issue
205 * of having to deal with a cpu having been in NO_HZ for multiple LOAD_FREQ
206 * intervals.
207 *
208 * When making the ILB scale, we should try to pull this in as well.
209 */
210 static atomic_long_t calc_load_nohz[2];
211 static int calc_load_idx;
212
calc_load_write_idx(void)213 static inline int calc_load_write_idx(void)
214 {
215 int idx = calc_load_idx;
216
217 /*
218 * See calc_global_nohz(), if we observe the new index, we also
219 * need to observe the new update time.
220 */
221 smp_rmb();
222
223 /*
224 * If the folding window started, make sure we start writing in the
225 * next NO_HZ-delta.
226 */
227 if (!time_before(jiffies, READ_ONCE(calc_load_update)))
228 idx++;
229
230 return idx & 1;
231 }
232
calc_load_read_idx(void)233 static inline int calc_load_read_idx(void)
234 {
235 return calc_load_idx & 1;
236 }
237
calc_load_nohz_start(void)238 void calc_load_nohz_start(void)
239 {
240 struct rq *this_rq = this_rq();
241 long delta;
242
243 /*
244 * We're going into NO_HZ mode, if there's any pending delta, fold it
245 * into the pending NO_HZ delta.
246 */
247 delta = calc_load_fold_active(this_rq, 0);
248 if (delta) {
249 int idx = calc_load_write_idx();
250
251 atomic_long_add(delta, &calc_load_nohz[idx]);
252 }
253 }
254
calc_load_nohz_stop(void)255 void calc_load_nohz_stop(void)
256 {
257 struct rq *this_rq = this_rq();
258
259 /*
260 * If we're still before the pending sample window, we're done.
261 */
262 this_rq->calc_load_update = READ_ONCE(calc_load_update);
263 if (time_before(jiffies, this_rq->calc_load_update))
264 return;
265
266 /*
267 * We woke inside or after the sample window, this means we're already
268 * accounted through the nohz accounting, so skip the entire deal and
269 * sync up for the next window.
270 */
271 if (time_before(jiffies, this_rq->calc_load_update + 10))
272 this_rq->calc_load_update += LOAD_FREQ;
273 }
274
calc_load_nohz_fold(void)275 static long calc_load_nohz_fold(void)
276 {
277 int idx = calc_load_read_idx();
278 long delta = 0;
279
280 if (atomic_long_read(&calc_load_nohz[idx]))
281 delta = atomic_long_xchg(&calc_load_nohz[idx], 0);
282
283 return delta;
284 }
285
286 /*
287 * NO_HZ can leave us missing all per-cpu ticks calling
288 * calc_load_fold_active(), but since a NO_HZ CPU folds its delta into
289 * calc_load_nohz per calc_load_nohz_start(), all we need to do is fold
290 * in the pending NO_HZ delta if our NO_HZ period crossed a load cycle boundary.
291 *
292 * Once we've updated the global active value, we need to apply the exponential
293 * weights adjusted to the number of cycles missed.
294 */
calc_global_nohz(void)295 static void calc_global_nohz(void)
296 {
297 unsigned long sample_window;
298 long delta, active, n;
299
300 sample_window = READ_ONCE(calc_load_update);
301 if (!time_before(jiffies, sample_window + 10)) {
302 /*
303 * Catch-up, fold however many we are behind still
304 */
305 delta = jiffies - sample_window - 10;
306 n = 1 + (delta / LOAD_FREQ);
307
308 active = atomic_long_read(&calc_load_tasks);
309 active = active > 0 ? active * FIXED_1 : 0;
310
311 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
312 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
313 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
314
315 WRITE_ONCE(calc_load_update, sample_window + n * LOAD_FREQ);
316 }
317
318 /*
319 * Flip the NO_HZ index...
320 *
321 * Make sure we first write the new time then flip the index, so that
322 * calc_load_write_idx() will see the new time when it reads the new
323 * index, this avoids a double flip messing things up.
324 */
325 smp_wmb();
326 calc_load_idx++;
327 }
328 #else /* !CONFIG_NO_HZ_COMMON */
329
calc_load_nohz_fold(void)330 static inline long calc_load_nohz_fold(void) { return 0; }
calc_global_nohz(void)331 static inline void calc_global_nohz(void) { }
332
333 #endif /* CONFIG_NO_HZ_COMMON */
334
335 /*
336 * calc_load - update the avenrun load estimates 10 ticks after the
337 * CPUs have updated calc_load_tasks.
338 *
339 * Called from the global timer code.
340 */
calc_global_load(unsigned long ticks)341 void calc_global_load(unsigned long ticks)
342 {
343 unsigned long sample_window;
344 long active, delta;
345
346 sample_window = READ_ONCE(calc_load_update);
347 if (time_before(jiffies, sample_window + 10))
348 return;
349
350 /*
351 * Fold the 'old' NO_HZ-delta to include all NO_HZ cpus.
352 */
353 delta = calc_load_nohz_fold();
354 if (delta)
355 atomic_long_add(delta, &calc_load_tasks);
356
357 active = atomic_long_read(&calc_load_tasks);
358 active = active > 0 ? active * FIXED_1 : 0;
359
360 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
361 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
362 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
363
364 WRITE_ONCE(calc_load_update, sample_window + LOAD_FREQ);
365
366 /*
367 * In case we went to NO_HZ for multiple LOAD_FREQ intervals
368 * catch up in bulk.
369 */
370 calc_global_nohz();
371 }
372
373 /*
374 * Called from scheduler_tick() to periodically update this CPU's
375 * active count.
376 */
calc_global_load_tick(struct rq * this_rq)377 void calc_global_load_tick(struct rq *this_rq)
378 {
379 long delta;
380
381 if (time_before(jiffies, this_rq->calc_load_update))
382 return;
383
384 delta = calc_load_fold_active(this_rq, 0);
385 if (delta)
386 atomic_long_add(delta, &calc_load_tasks);
387
388 this_rq->calc_load_update += LOAD_FREQ;
389 }
390