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