• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Per Entity Load Tracking (PELT)
4  *
5  *  Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6  *
7  *  Interactivity improvements by Mike Galbraith
8  *  (C) 2007 Mike Galbraith <efault@gmx.de>
9  *
10  *  Various enhancements by Dmitry Adamushko.
11  *  (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12  *
13  *  Group scheduling enhancements by Srivatsa Vaddagiri
14  *  Copyright IBM Corporation, 2007
15  *  Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16  *
17  *  Scaled math optimizations by Thomas Gleixner
18  *  Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
19  *
20  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
22  *
23  *  Move PELT related code from fair.c into this pelt.c file
24  *  Author: Vincent Guittot <vincent.guittot@linaro.org>
25  */
26 
27 /*
28  * Approximate:
29  *   val * y^n,    where y^32 ~= 0.5 (~1 scheduling period)
30  */
decay_load(u64 val,u64 n)31 static u64 decay_load(u64 val, u64 n)
32 {
33 	unsigned int local_n;
34 
35 	if (unlikely(n > LOAD_AVG_PERIOD * 63))
36 		return 0;
37 
38 	/* after bounds checking we can collapse to 32-bit */
39 	local_n = n;
40 
41 	/*
42 	 * As y^PERIOD = 1/2, we can combine
43 	 *    y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
44 	 * With a look-up table which covers y^n (n<PERIOD)
45 	 *
46 	 * To achieve constant time decay_load.
47 	 */
48 	if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
49 		val >>= local_n / LOAD_AVG_PERIOD;
50 		local_n %= LOAD_AVG_PERIOD;
51 	}
52 
53 	val = mul_u64_u32_shr(val, runnable_avg_yN_inv[local_n], 32);
54 	return val;
55 }
56 
__accumulate_pelt_segments(u64 periods,u32 d1,u32 d3)57 static u32 __accumulate_pelt_segments(u64 periods, u32 d1, u32 d3)
58 {
59 	u32 c1, c2, c3 = d3; /* y^0 == 1 */
60 
61 	/*
62 	 * c1 = d1 y^p
63 	 */
64 	c1 = decay_load((u64)d1, periods);
65 
66 	/*
67 	 *            p-1
68 	 * c2 = 1024 \Sum y^n
69 	 *            n=1
70 	 *
71 	 *              inf        inf
72 	 *    = 1024 ( \Sum y^n - \Sum y^n - y^0 )
73 	 *              n=0        n=p
74 	 */
75 	c2 = LOAD_AVG_MAX - decay_load(LOAD_AVG_MAX, periods) - 1024;
76 
77 	return c1 + c2 + c3;
78 }
79 
80 /*
81  * Accumulate the three separate parts of the sum; d1 the remainder
82  * of the last (incomplete) period, d2 the span of full periods and d3
83  * the remainder of the (incomplete) current period.
84  *
85  *           d1          d2           d3
86  *           ^           ^            ^
87  *           |           |            |
88  *         |<->|<----------------->|<--->|
89  * ... |---x---|------| ... |------|-----x (now)
90  *
91  *                           p-1
92  * u' = (u + d1) y^p + 1024 \Sum y^n + d3 y^0
93  *                           n=1
94  *
95  *    = u y^p +					(Step 1)
96  *
97  *                     p-1
98  *      d1 y^p + 1024 \Sum y^n + d3 y^0		(Step 2)
99  *                     n=1
100  */
101 static __always_inline u32
accumulate_sum(u64 delta,struct sched_avg * sa,unsigned long load,unsigned long runnable,int running)102 accumulate_sum(u64 delta, struct sched_avg *sa,
103 	       unsigned long load, unsigned long runnable, int running)
104 {
105 	u32 contrib = (u32)delta; /* p == 0 -> delta < 1024 */
106 	u64 periods;
107 
108 	delta += sa->period_contrib;
109 	periods = delta / 1024; /* A period is 1024us (~1ms) */
110 
111 	/*
112 	 * Step 1: decay old *_sum if we crossed period boundaries.
113 	 */
114 	if (periods) {
115 		sa->load_sum = decay_load(sa->load_sum, periods);
116 		sa->runnable_sum =
117 			decay_load(sa->runnable_sum, periods);
118 		sa->util_sum = decay_load((u64)(sa->util_sum), periods);
119 
120 		/*
121 		 * Step 2
122 		 */
123 		delta %= 1024;
124 		if (load) {
125 			/*
126 			 * This relies on the:
127 			 *
128 			 * if (!load)
129 			 *	runnable = running = 0;
130 			 *
131 			 * clause from ___update_load_sum(); this results in
132 			 * the below usage of @contrib to disappear entirely,
133 			 * so no point in calculating it.
134 			 */
135 			contrib = __accumulate_pelt_segments(periods,
136 					1024 - sa->period_contrib, delta);
137 		}
138 	}
139 	sa->period_contrib = delta;
140 
141 	if (load)
142 		sa->load_sum += load * contrib;
143 	if (runnable)
144 		sa->runnable_sum += runnable * contrib << SCHED_CAPACITY_SHIFT;
145 	if (running)
146 		sa->util_sum += contrib << SCHED_CAPACITY_SHIFT;
147 
148 	return periods;
149 }
150 
151 /*
152  * We can represent the historical contribution to runnable average as the
153  * coefficients of a geometric series.  To do this we sub-divide our runnable
154  * history into segments of approximately 1ms (1024us); label the segment that
155  * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
156  *
157  * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
158  *      p0            p1           p2
159  *     (now)       (~1ms ago)  (~2ms ago)
160  *
161  * Let u_i denote the fraction of p_i that the entity was runnable.
162  *
163  * We then designate the fractions u_i as our co-efficients, yielding the
164  * following representation of historical load:
165  *   u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
166  *
167  * We choose y based on the with of a reasonably scheduling period, fixing:
168  *   y^32 = 0.5
169  *
170  * This means that the contribution to load ~32ms ago (u_32) will be weighted
171  * approximately half as much as the contribution to load within the last ms
172  * (u_0).
173  *
174  * When a period "rolls over" and we have new u_0`, multiplying the previous
175  * sum again by y is sufficient to update:
176  *   load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
177  *            = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
178  */
179 __always_inline int
___update_load_sum(u64 now,struct sched_avg * sa,unsigned long load,unsigned long runnable,int running)180 ___update_load_sum(u64 now, struct sched_avg *sa,
181 		  unsigned long load, unsigned long runnable, int running)
182 {
183 	u64 delta;
184 
185 	delta = now - sa->last_update_time;
186 	/*
187 	 * This should only happen when time goes backwards, which it
188 	 * unfortunately does during sched clock init when we swap over to TSC.
189 	 */
190 	if ((s64)delta < 0) {
191 		sa->last_update_time = now;
192 		return 0;
193 	}
194 
195 	/*
196 	 * Use 1024ns as the unit of measurement since it's a reasonable
197 	 * approximation of 1us and fast to compute.
198 	 */
199 	delta >>= 10;
200 	if (!delta)
201 		return 0;
202 
203 	sa->last_update_time += delta << 10;
204 
205 	/*
206 	 * running is a subset of runnable (weight) so running can't be set if
207 	 * runnable is clear. But there are some corner cases where the current
208 	 * se has been already dequeued but cfs_rq->curr still points to it.
209 	 * This means that weight will be 0 but not running for a sched_entity
210 	 * but also for a cfs_rq if the latter becomes idle. As an example,
211 	 * this happens during sched_balance_newidle() which calls
212 	 * sched_balance_update_blocked_averages().
213 	 *
214 	 * Also see the comment in accumulate_sum().
215 	 */
216 	if (!load)
217 		runnable = running = 0;
218 
219 	/*
220 	 * Now we know we crossed measurement unit boundaries. The *_avg
221 	 * accrues by two steps:
222 	 *
223 	 * Step 1: accumulate *_sum since last_update_time. If we haven't
224 	 * crossed period boundaries, finish.
225 	 */
226 	if (!accumulate_sum(delta, sa, load, runnable, running))
227 		return 0;
228 
229 	return 1;
230 }
231 EXPORT_SYMBOL_GPL(___update_load_sum);
232 
233 /*
234  * When syncing *_avg with *_sum, we must take into account the current
235  * position in the PELT segment otherwise the remaining part of the segment
236  * will be considered as idle time whereas it's not yet elapsed and this will
237  * generate unwanted oscillation in the range [1002..1024[.
238  *
239  * The max value of *_sum varies with the position in the time segment and is
240  * equals to :
241  *
242  *   LOAD_AVG_MAX*y + sa->period_contrib
243  *
244  * which can be simplified into:
245  *
246  *   LOAD_AVG_MAX - 1024 + sa->period_contrib
247  *
248  * because LOAD_AVG_MAX*y == LOAD_AVG_MAX-1024
249  *
250  * The same care must be taken when a sched entity is added, updated or
251  * removed from a cfs_rq and we need to update sched_avg. Scheduler entities
252  * and the cfs rq, to which they are attached, have the same position in the
253  * time segment because they use the same clock. This means that we can use
254  * the period_contrib of cfs_rq when updating the sched_avg of a sched_entity
255  * if it's more convenient.
256  */
257 static __always_inline void
___update_load_avg(struct sched_avg * sa,unsigned long load)258 ___update_load_avg(struct sched_avg *sa, unsigned long load)
259 {
260 	u32 divider = get_pelt_divider(sa);
261 
262 	/*
263 	 * Step 2: update *_avg.
264 	 */
265 	sa->load_avg = div_u64(load * sa->load_sum, divider);
266 	sa->runnable_avg = div_u64(sa->runnable_sum, divider);
267 	WRITE_ONCE(sa->util_avg, sa->util_sum / divider);
268 }
269 
270 /*
271  * sched_entity:
272  *
273  *   task:
274  *     se_weight()   = se->load.weight
275  *     se_runnable() = !!on_rq
276  *
277  *   group: [ see update_cfs_group() ]
278  *     se_weight()   = tg->weight * grq->load_avg / tg->load_avg
279  *     se_runnable() = grq->h_nr_running
280  *
281  *   runnable_sum = se_runnable() * runnable = grq->runnable_sum
282  *   runnable_avg = runnable_sum
283  *
284  *   load_sum := runnable
285  *   load_avg = se_weight(se) * load_sum
286  *
287  * cfq_rq:
288  *
289  *   runnable_sum = \Sum se->avg.runnable_sum
290  *   runnable_avg = \Sum se->avg.runnable_avg
291  *
292  *   load_sum = \Sum se_weight(se) * se->avg.load_sum
293  *   load_avg = \Sum se->avg.load_avg
294  */
295 
__update_load_avg_blocked_se(u64 now,struct sched_entity * se)296 int __update_load_avg_blocked_se(u64 now, struct sched_entity *se)
297 {
298 	int ret = -1;
299 
300 	trace_android_rvh_update_load_avg_blocked_se(now, se, &ret);
301 	if (ret != -1)
302 		return ret;
303 
304 	if (___update_load_sum(now, &se->avg, 0, 0, 0)) {
305 		___update_load_avg(&se->avg, se_weight(se));
306 		trace_pelt_se_tp(se);
307 		return 1;
308 	}
309 
310 	return 0;
311 }
312 EXPORT_SYMBOL_GPL(__update_load_avg_blocked_se);
313 
__update_load_avg_se(u64 now,struct cfs_rq * cfs_rq,struct sched_entity * se)314 int __update_load_avg_se(u64 now, struct cfs_rq *cfs_rq, struct sched_entity *se)
315 {
316 	int ret = -1;
317 
318 	trace_android_rvh_update_load_avg_se(now, cfs_rq, se, &ret);
319 	if (ret != -1)
320 		return ret;
321 
322 	if (___update_load_sum(now, &se->avg, !!se->on_rq, se_runnable(se),
323 				cfs_rq->curr == se)) {
324 
325 		___update_load_avg(&se->avg, se_weight(se));
326 		cfs_se_util_change(&se->avg);
327 		trace_pelt_se_tp(se);
328 		return 1;
329 	}
330 
331 	return 0;
332 }
333 
__update_load_avg_cfs_rq(u64 now,struct cfs_rq * cfs_rq)334 int __update_load_avg_cfs_rq(u64 now, struct cfs_rq *cfs_rq)
335 {
336 	int ret = -1;
337 
338 	trace_android_rvh_update_load_avg_cfs_rq(now, cfs_rq, &ret);
339 	if (ret != -1)
340 		return ret;
341 
342 	if (___update_load_sum(now, &cfs_rq->avg,
343 				scale_load_down(cfs_rq->load.weight),
344 				cfs_rq->h_nr_running - cfs_rq->h_nr_delayed,
345 				cfs_rq->curr != NULL)) {
346 
347 		___update_load_avg(&cfs_rq->avg, 1);
348 		trace_pelt_cfs_tp(cfs_rq);
349 		return 1;
350 	}
351 
352 	return 0;
353 }
354 
355 /*
356  * rt_rq:
357  *
358  *   util_sum = \Sum se->avg.util_sum but se->avg.util_sum is not tracked
359  *   util_sum = cpu_scale * load_sum
360  *   runnable_sum = util_sum
361  *
362  *   load_avg and runnable_avg are not supported and meaningless.
363  *
364  */
365 
update_rt_rq_load_avg(u64 now,struct rq * rq,int running)366 int update_rt_rq_load_avg(u64 now, struct rq *rq, int running)
367 {
368 	int ret = -1;
369 
370 	trace_android_rvh_update_rt_rq_load_avg_internal(now, rq, running, &ret);
371 	if (ret != -1)
372 		return ret;
373 
374 	if (___update_load_sum(now, &rq->avg_rt,
375 				running,
376 				running,
377 				running)) {
378 
379 		___update_load_avg(&rq->avg_rt, 1);
380 		trace_pelt_rt_tp(rq);
381 		return 1;
382 	}
383 
384 	return 0;
385 }
386 
387 /*
388  * dl_rq:
389  *
390  *   util_sum = \Sum se->avg.util_sum but se->avg.util_sum is not tracked
391  *   util_sum = cpu_scale * load_sum
392  *   runnable_sum = util_sum
393  *
394  *   load_avg and runnable_avg are not supported and meaningless.
395  *
396  */
397 
update_dl_rq_load_avg(u64 now,struct rq * rq,int running)398 int update_dl_rq_load_avg(u64 now, struct rq *rq, int running)
399 {
400 	if (___update_load_sum(now, &rq->avg_dl,
401 				running,
402 				running,
403 				running)) {
404 
405 		___update_load_avg(&rq->avg_dl, 1);
406 		trace_pelt_dl_tp(rq);
407 		return 1;
408 	}
409 
410 	return 0;
411 }
412 
413 #ifdef CONFIG_SCHED_HW_PRESSURE
414 /*
415  * hardware:
416  *
417  *   load_sum = \Sum se->avg.load_sum but se->avg.load_sum is not tracked
418  *
419  *   util_avg and runnable_load_avg are not supported and meaningless.
420  *
421  * Unlike rt/dl utilization tracking that track time spent by a cpu
422  * running a rt/dl task through util_avg, the average HW pressure is
423  * tracked through load_avg. This is because HW pressure signal is
424  * time weighted "delta" capacity unlike util_avg which is binary.
425  * "delta capacity" =  actual capacity  -
426  *			capped capacity a cpu due to a HW event.
427  */
428 
update_hw_load_avg(u64 now,struct rq * rq,u64 capacity)429 int update_hw_load_avg(u64 now, struct rq *rq, u64 capacity)
430 {
431 	if (___update_load_sum(now, &rq->avg_hw,
432 			       capacity,
433 			       capacity,
434 			       capacity)) {
435 		___update_load_avg(&rq->avg_hw, 1);
436 		trace_pelt_hw_tp(rq);
437 		return 1;
438 	}
439 
440 	return 0;
441 }
442 #endif
443 
444 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
445 /*
446  * IRQ:
447  *
448  *   util_sum = \Sum se->avg.util_sum but se->avg.util_sum is not tracked
449  *   util_sum = cpu_scale * load_sum
450  *   runnable_sum = util_sum
451  *
452  *   load_avg and runnable_avg are not supported and meaningless.
453  *
454  */
455 
update_irq_load_avg(struct rq * rq,u64 running)456 int update_irq_load_avg(struct rq *rq, u64 running)
457 {
458 	int ret = 0;
459 
460 	/*
461 	 * We can't use clock_pelt because IRQ time is not accounted in
462 	 * clock_task. Instead we directly scale the running time to
463 	 * reflect the real amount of computation
464 	 */
465 	running = cap_scale(running, arch_scale_freq_capacity(cpu_of(rq)));
466 	running = cap_scale(running, arch_scale_cpu_capacity(cpu_of(rq)));
467 
468 	/*
469 	 * We know the time that has been used by interrupt since last update
470 	 * but we don't when. Let be pessimistic and assume that interrupt has
471 	 * happened just before the update. This is not so far from reality
472 	 * because interrupt will most probably wake up task and trig an update
473 	 * of rq clock during which the metric is updated.
474 	 * We start to decay with normal context time and then we add the
475 	 * interrupt context time.
476 	 * We can safely remove running from rq->clock because
477 	 * rq->clock += delta with delta >= running
478 	 */
479 	ret = ___update_load_sum(rq->clock - running, &rq->avg_irq,
480 				0,
481 				0,
482 				0);
483 	ret += ___update_load_sum(rq->clock, &rq->avg_irq,
484 				1,
485 				1,
486 				1);
487 
488 	if (ret) {
489 		___update_load_avg(&rq->avg_irq, 1);
490 		trace_pelt_irq_tp(rq);
491 	}
492 
493 	return ret;
494 }
495 #endif
496 
497 /*
498  * Load avg and utiliztion metrics need to be updated periodically and before
499  * consumption. This function updates the metrics for all subsystems except for
500  * the fair class. @rq must be locked and have its clock updated.
501  */
update_other_load_avgs(struct rq * rq)502 bool update_other_load_avgs(struct rq *rq)
503 {
504 	u64 now = rq_clock_pelt(rq);
505 	const struct sched_class *curr_class = rq->donor->sched_class;
506 	unsigned long hw_pressure = arch_scale_hw_pressure(cpu_of(rq));
507 
508 	lockdep_assert_rq_held(rq);
509 
510 	/* hw_pressure doesn't care about invariance */
511 	return update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
512 		update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
513 		update_hw_load_avg(rq_clock_task(rq), rq, hw_pressure) |
514 		update_irq_load_avg(rq, 0);
515 }
516 
517 __read_mostly unsigned int sched_pelt_lshift;
518 
519 #ifdef CONFIG_SYSCTL
520 #include <trace/hooks/sched.h>
521 static unsigned int sysctl_sched_pelt_multiplier = 1;
522 
sched_pelt_multiplier(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)523 int sched_pelt_multiplier(const struct ctl_table *table, int write, void *buffer,
524 			  size_t *lenp, loff_t *ppos)
525 {
526 	static DEFINE_MUTEX(mutex);
527 	unsigned int old;
528 	int ret;
529 
530 	mutex_lock(&mutex);
531 	old = sysctl_sched_pelt_multiplier;
532 	ret = proc_dointvec(table, write, buffer, lenp, ppos);
533 	if (ret)
534 		goto undo;
535 	if (!write)
536 		goto done;
537 
538 	trace_android_vh_sched_pelt_multiplier(old, sysctl_sched_pelt_multiplier, &ret);
539 	if (ret)
540 		goto undo;
541 
542 	switch (sysctl_sched_pelt_multiplier)  {
543 	case 1:
544 		fallthrough;
545 	case 2:
546 		fallthrough;
547 	case 4:
548 		WRITE_ONCE(sched_pelt_lshift,
549 			   sysctl_sched_pelt_multiplier >> 1);
550 		goto done;
551 	default:
552 		ret = -EINVAL;
553 	}
554 
555 undo:
556 	sysctl_sched_pelt_multiplier = old;
557 done:
558 	mutex_unlock(&mutex);
559 
560 	return ret;
561 }
562 
563 static struct ctl_table sched_pelt_sysctls[] = {
564 	{
565 		.procname       = "sched_pelt_multiplier",
566 		.data           = &sysctl_sched_pelt_multiplier,
567 		.maxlen         = sizeof(unsigned int),
568 		.mode           = 0644,
569 		.proc_handler   = sched_pelt_multiplier,
570 	},
571 };
572 
sched_pelt_sysctl_init(void)573 static int __init sched_pelt_sysctl_init(void)
574 {
575 	register_sysctl_init("kernel", sched_pelt_sysctls);
576 	return 0;
577 }
578 late_initcall(sched_pelt_sysctl_init);
579 #endif
580