]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - kernel/sched/fair.c
sched/fair: Compute task/cpu utilization at wake-up correctly
[mirror_ubuntu-bionic-kernel.git] / kernel / sched / fair.c
CommitLineData
bf0f6f24
IM
1/*
2 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
3 *
4 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
5 *
6 * Interactivity improvements by Mike Galbraith
7 * (C) 2007 Mike Galbraith <efault@gmx.de>
8 *
9 * Various enhancements by Dmitry Adamushko.
10 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
11 *
12 * Group scheduling enhancements by Srivatsa Vaddagiri
13 * Copyright IBM Corporation, 2007
14 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
15 *
16 * Scaled math optimizations by Thomas Gleixner
17 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
21805085
PZ
18 *
19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
90eec103 20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
bf0f6f24
IM
21 */
22
1983a922 23#include <linux/sched.h>
cb251765 24#include <linux/latencytop.h>
3436ae12 25#include <linux/cpumask.h>
83a0a96a 26#include <linux/cpuidle.h>
029632fb
PZ
27#include <linux/slab.h>
28#include <linux/profile.h>
29#include <linux/interrupt.h>
cbee9f88 30#include <linux/mempolicy.h>
e14808b4 31#include <linux/migrate.h>
cbee9f88 32#include <linux/task_work.h>
029632fb
PZ
33
34#include <trace/events/sched.h>
35
36#include "sched.h"
9745512c 37
bf0f6f24 38/*
21805085 39 * Targeted preemption latency for CPU-bound tasks:
864616ee 40 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
bf0f6f24 41 *
21805085 42 * NOTE: this latency value is not the same as the concept of
d274a4ce
IM
43 * 'timeslice length' - timeslices in CFS are of variable length
44 * and have no persistent notion like in traditional, time-slice
45 * based scheduling concepts.
bf0f6f24 46 *
d274a4ce
IM
47 * (to see the precise effective timeslice length of your workload,
48 * run vmstat and monitor the context-switches (cs) field)
bf0f6f24 49 */
21406928
MG
50unsigned int sysctl_sched_latency = 6000000ULL;
51unsigned int normalized_sysctl_sched_latency = 6000000ULL;
2bd8e6d4 52
1983a922
CE
53/*
54 * The initial- and re-scaling of tunables is configurable
55 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
56 *
57 * Options are:
58 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
59 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
60 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
61 */
62enum sched_tunable_scaling sysctl_sched_tunable_scaling
63 = SCHED_TUNABLESCALING_LOG;
64
2bd8e6d4 65/*
b2be5e96 66 * Minimal preemption granularity for CPU-bound tasks:
864616ee 67 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
2bd8e6d4 68 */
0bf377bb
IM
69unsigned int sysctl_sched_min_granularity = 750000ULL;
70unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
21805085
PZ
71
72/*
b2be5e96
PZ
73 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
74 */
0bf377bb 75static unsigned int sched_nr_latency = 8;
b2be5e96
PZ
76
77/*
2bba22c5 78 * After fork, child runs first. If set to 0 (default) then
b2be5e96 79 * parent will (try to) run first.
21805085 80 */
2bba22c5 81unsigned int sysctl_sched_child_runs_first __read_mostly;
bf0f6f24 82
bf0f6f24
IM
83/*
84 * SCHED_OTHER wake-up granularity.
172e082a 85 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
bf0f6f24
IM
86 *
87 * This option delays the preemption effects of decoupled workloads
88 * and reduces their over-scheduling. Synchronous workloads will still
89 * have immediate wakeup/sleep latencies.
90 */
172e082a 91unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
0bcdcf28 92unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
bf0f6f24 93
da84d961
IM
94const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
95
ec12cb7f
PT
96#ifdef CONFIG_CFS_BANDWIDTH
97/*
98 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
99 * each time a cfs_rq requests quota.
100 *
101 * Note: in the case that the slice exceeds the runtime remaining (either due
102 * to consumption or the quota being specified to be smaller than the slice)
103 * we will always only issue the remaining available time.
104 *
105 * default: 5 msec, units: microseconds
106 */
107unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
108#endif
109
3273163c
MR
110/*
111 * The margin used when comparing utilization with CPU capacity:
112 * util * 1024 < capacity * margin
113 */
114unsigned int capacity_margin = 1280; /* ~20% */
115
8527632d
PG
116static inline void update_load_add(struct load_weight *lw, unsigned long inc)
117{
118 lw->weight += inc;
119 lw->inv_weight = 0;
120}
121
122static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
123{
124 lw->weight -= dec;
125 lw->inv_weight = 0;
126}
127
128static inline void update_load_set(struct load_weight *lw, unsigned long w)
129{
130 lw->weight = w;
131 lw->inv_weight = 0;
132}
133
029632fb
PZ
134/*
135 * Increase the granularity value when there are more CPUs,
136 * because with more CPUs the 'effective latency' as visible
137 * to users decreases. But the relationship is not linear,
138 * so pick a second-best guess by going with the log2 of the
139 * number of CPUs.
140 *
141 * This idea comes from the SD scheduler of Con Kolivas:
142 */
58ac93e4 143static unsigned int get_update_sysctl_factor(void)
029632fb 144{
58ac93e4 145 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
029632fb
PZ
146 unsigned int factor;
147
148 switch (sysctl_sched_tunable_scaling) {
149 case SCHED_TUNABLESCALING_NONE:
150 factor = 1;
151 break;
152 case SCHED_TUNABLESCALING_LINEAR:
153 factor = cpus;
154 break;
155 case SCHED_TUNABLESCALING_LOG:
156 default:
157 factor = 1 + ilog2(cpus);
158 break;
159 }
160
161 return factor;
162}
163
164static void update_sysctl(void)
165{
166 unsigned int factor = get_update_sysctl_factor();
167
168#define SET_SYSCTL(name) \
169 (sysctl_##name = (factor) * normalized_sysctl_##name)
170 SET_SYSCTL(sched_min_granularity);
171 SET_SYSCTL(sched_latency);
172 SET_SYSCTL(sched_wakeup_granularity);
173#undef SET_SYSCTL
174}
175
176void sched_init_granularity(void)
177{
178 update_sysctl();
179}
180
9dbdb155 181#define WMULT_CONST (~0U)
029632fb
PZ
182#define WMULT_SHIFT 32
183
9dbdb155
PZ
184static void __update_inv_weight(struct load_weight *lw)
185{
186 unsigned long w;
187
188 if (likely(lw->inv_weight))
189 return;
190
191 w = scale_load_down(lw->weight);
192
193 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
194 lw->inv_weight = 1;
195 else if (unlikely(!w))
196 lw->inv_weight = WMULT_CONST;
197 else
198 lw->inv_weight = WMULT_CONST / w;
199}
029632fb
PZ
200
201/*
9dbdb155
PZ
202 * delta_exec * weight / lw.weight
203 * OR
204 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
205 *
1c3de5e1 206 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
9dbdb155
PZ
207 * we're guaranteed shift stays positive because inv_weight is guaranteed to
208 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
209 *
210 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
211 * weight/lw.weight <= 1, and therefore our shift will also be positive.
029632fb 212 */
9dbdb155 213static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
029632fb 214{
9dbdb155
PZ
215 u64 fact = scale_load_down(weight);
216 int shift = WMULT_SHIFT;
029632fb 217
9dbdb155 218 __update_inv_weight(lw);
029632fb 219
9dbdb155
PZ
220 if (unlikely(fact >> 32)) {
221 while (fact >> 32) {
222 fact >>= 1;
223 shift--;
224 }
029632fb
PZ
225 }
226
9dbdb155
PZ
227 /* hint to use a 32x32->64 mul */
228 fact = (u64)(u32)fact * lw->inv_weight;
029632fb 229
9dbdb155
PZ
230 while (fact >> 32) {
231 fact >>= 1;
232 shift--;
233 }
029632fb 234
9dbdb155 235 return mul_u64_u32_shr(delta_exec, fact, shift);
029632fb
PZ
236}
237
238
239const struct sched_class fair_sched_class;
a4c2f00f 240
bf0f6f24
IM
241/**************************************************************
242 * CFS operations on generic schedulable entities:
243 */
244
62160e3f 245#ifdef CONFIG_FAIR_GROUP_SCHED
bf0f6f24 246
62160e3f 247/* cpu runqueue to which this cfs_rq is attached */
bf0f6f24
IM
248static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
249{
62160e3f 250 return cfs_rq->rq;
bf0f6f24
IM
251}
252
62160e3f
IM
253/* An entity is a task if it doesn't "own" a runqueue */
254#define entity_is_task(se) (!se->my_q)
bf0f6f24 255
8f48894f
PZ
256static inline struct task_struct *task_of(struct sched_entity *se)
257{
9148a3a1 258 SCHED_WARN_ON(!entity_is_task(se));
8f48894f
PZ
259 return container_of(se, struct task_struct, se);
260}
261
b758149c
PZ
262/* Walk up scheduling entities hierarchy */
263#define for_each_sched_entity(se) \
264 for (; se; se = se->parent)
265
266static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
267{
268 return p->se.cfs_rq;
269}
270
271/* runqueue on which this entity is (to be) queued */
272static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
273{
274 return se->cfs_rq;
275}
276
277/* runqueue "owned" by this group */
278static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
279{
280 return grp->my_q;
281}
282
3d4b47b4
PZ
283static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
284{
285 if (!cfs_rq->on_list) {
67e86250
PT
286 /*
287 * Ensure we either appear before our parent (if already
288 * enqueued) or force our parent to appear after us when it is
289 * enqueued. The fact that we always enqueue bottom-up
290 * reduces this to two cases.
291 */
292 if (cfs_rq->tg->parent &&
293 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
294 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
295 &rq_of(cfs_rq)->leaf_cfs_rq_list);
296 } else {
297 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
3d4b47b4 298 &rq_of(cfs_rq)->leaf_cfs_rq_list);
67e86250 299 }
3d4b47b4
PZ
300
301 cfs_rq->on_list = 1;
302 }
303}
304
305static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
306{
307 if (cfs_rq->on_list) {
308 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
309 cfs_rq->on_list = 0;
310 }
311}
312
b758149c
PZ
313/* Iterate thr' all leaf cfs_rq's on a runqueue */
314#define for_each_leaf_cfs_rq(rq, cfs_rq) \
315 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
316
317/* Do the two (enqueued) entities belong to the same group ? */
fed14d45 318static inline struct cfs_rq *
b758149c
PZ
319is_same_group(struct sched_entity *se, struct sched_entity *pse)
320{
321 if (se->cfs_rq == pse->cfs_rq)
fed14d45 322 return se->cfs_rq;
b758149c 323
fed14d45 324 return NULL;
b758149c
PZ
325}
326
327static inline struct sched_entity *parent_entity(struct sched_entity *se)
328{
329 return se->parent;
330}
331
464b7527
PZ
332static void
333find_matching_se(struct sched_entity **se, struct sched_entity **pse)
334{
335 int se_depth, pse_depth;
336
337 /*
338 * preemption test can be made between sibling entities who are in the
339 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
340 * both tasks until we find their ancestors who are siblings of common
341 * parent.
342 */
343
344 /* First walk up until both entities are at same depth */
fed14d45
PZ
345 se_depth = (*se)->depth;
346 pse_depth = (*pse)->depth;
464b7527
PZ
347
348 while (se_depth > pse_depth) {
349 se_depth--;
350 *se = parent_entity(*se);
351 }
352
353 while (pse_depth > se_depth) {
354 pse_depth--;
355 *pse = parent_entity(*pse);
356 }
357
358 while (!is_same_group(*se, *pse)) {
359 *se = parent_entity(*se);
360 *pse = parent_entity(*pse);
361 }
362}
363
8f48894f
PZ
364#else /* !CONFIG_FAIR_GROUP_SCHED */
365
366static inline struct task_struct *task_of(struct sched_entity *se)
367{
368 return container_of(se, struct task_struct, se);
369}
bf0f6f24 370
62160e3f
IM
371static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
372{
373 return container_of(cfs_rq, struct rq, cfs);
bf0f6f24
IM
374}
375
376#define entity_is_task(se) 1
377
b758149c
PZ
378#define for_each_sched_entity(se) \
379 for (; se; se = NULL)
bf0f6f24 380
b758149c 381static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
bf0f6f24 382{
b758149c 383 return &task_rq(p)->cfs;
bf0f6f24
IM
384}
385
b758149c
PZ
386static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
387{
388 struct task_struct *p = task_of(se);
389 struct rq *rq = task_rq(p);
390
391 return &rq->cfs;
392}
393
394/* runqueue "owned" by this group */
395static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
396{
397 return NULL;
398}
399
3d4b47b4
PZ
400static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
401{
402}
403
404static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
405{
406}
407
b758149c
PZ
408#define for_each_leaf_cfs_rq(rq, cfs_rq) \
409 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
410
b758149c
PZ
411static inline struct sched_entity *parent_entity(struct sched_entity *se)
412{
413 return NULL;
414}
415
464b7527
PZ
416static inline void
417find_matching_se(struct sched_entity **se, struct sched_entity **pse)
418{
419}
420
b758149c
PZ
421#endif /* CONFIG_FAIR_GROUP_SCHED */
422
6c16a6dc 423static __always_inline
9dbdb155 424void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
bf0f6f24
IM
425
426/**************************************************************
427 * Scheduling class tree data structure manipulation methods:
428 */
429
1bf08230 430static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
02e0431a 431{
1bf08230 432 s64 delta = (s64)(vruntime - max_vruntime);
368059a9 433 if (delta > 0)
1bf08230 434 max_vruntime = vruntime;
02e0431a 435
1bf08230 436 return max_vruntime;
02e0431a
PZ
437}
438
0702e3eb 439static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
b0ffd246
PZ
440{
441 s64 delta = (s64)(vruntime - min_vruntime);
442 if (delta < 0)
443 min_vruntime = vruntime;
444
445 return min_vruntime;
446}
447
54fdc581
FC
448static inline int entity_before(struct sched_entity *a,
449 struct sched_entity *b)
450{
451 return (s64)(a->vruntime - b->vruntime) < 0;
452}
453
1af5f730
PZ
454static void update_min_vruntime(struct cfs_rq *cfs_rq)
455{
b60205c7
PZ
456 struct sched_entity *curr = cfs_rq->curr;
457
1af5f730
PZ
458 u64 vruntime = cfs_rq->min_vruntime;
459
b60205c7
PZ
460 if (curr) {
461 if (curr->on_rq)
462 vruntime = curr->vruntime;
463 else
464 curr = NULL;
465 }
1af5f730
PZ
466
467 if (cfs_rq->rb_leftmost) {
468 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
469 struct sched_entity,
470 run_node);
471
b60205c7 472 if (!curr)
1af5f730
PZ
473 vruntime = se->vruntime;
474 else
475 vruntime = min_vruntime(vruntime, se->vruntime);
476 }
477
1bf08230 478 /* ensure we never gain time by being placed backwards. */
1af5f730 479 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
3fe1698b
PZ
480#ifndef CONFIG_64BIT
481 smp_wmb();
482 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
483#endif
1af5f730
PZ
484}
485
bf0f6f24
IM
486/*
487 * Enqueue an entity into the rb-tree:
488 */
0702e3eb 489static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24
IM
490{
491 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
492 struct rb_node *parent = NULL;
493 struct sched_entity *entry;
bf0f6f24
IM
494 int leftmost = 1;
495
496 /*
497 * Find the right place in the rbtree:
498 */
499 while (*link) {
500 parent = *link;
501 entry = rb_entry(parent, struct sched_entity, run_node);
502 /*
503 * We dont care about collisions. Nodes with
504 * the same key stay together.
505 */
2bd2d6f2 506 if (entity_before(se, entry)) {
bf0f6f24
IM
507 link = &parent->rb_left;
508 } else {
509 link = &parent->rb_right;
510 leftmost = 0;
511 }
512 }
513
514 /*
515 * Maintain a cache of leftmost tree entries (it is frequently
516 * used):
517 */
1af5f730 518 if (leftmost)
57cb499d 519 cfs_rq->rb_leftmost = &se->run_node;
bf0f6f24
IM
520
521 rb_link_node(&se->run_node, parent, link);
522 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
bf0f6f24
IM
523}
524
0702e3eb 525static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 526{
3fe69747
PZ
527 if (cfs_rq->rb_leftmost == &se->run_node) {
528 struct rb_node *next_node;
3fe69747
PZ
529
530 next_node = rb_next(&se->run_node);
531 cfs_rq->rb_leftmost = next_node;
3fe69747 532 }
e9acbff6 533
bf0f6f24 534 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
bf0f6f24
IM
535}
536
029632fb 537struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
bf0f6f24 538{
f4b6755f
PZ
539 struct rb_node *left = cfs_rq->rb_leftmost;
540
541 if (!left)
542 return NULL;
543
544 return rb_entry(left, struct sched_entity, run_node);
bf0f6f24
IM
545}
546
ac53db59
RR
547static struct sched_entity *__pick_next_entity(struct sched_entity *se)
548{
549 struct rb_node *next = rb_next(&se->run_node);
550
551 if (!next)
552 return NULL;
553
554 return rb_entry(next, struct sched_entity, run_node);
555}
556
557#ifdef CONFIG_SCHED_DEBUG
029632fb 558struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
aeb73b04 559{
7eee3e67 560 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
aeb73b04 561
70eee74b
BS
562 if (!last)
563 return NULL;
7eee3e67
IM
564
565 return rb_entry(last, struct sched_entity, run_node);
aeb73b04
PZ
566}
567
bf0f6f24
IM
568/**************************************************************
569 * Scheduling class statistics methods:
570 */
571
acb4a848 572int sched_proc_update_handler(struct ctl_table *table, int write,
8d65af78 573 void __user *buffer, size_t *lenp,
b2be5e96
PZ
574 loff_t *ppos)
575{
8d65af78 576 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
58ac93e4 577 unsigned int factor = get_update_sysctl_factor();
b2be5e96
PZ
578
579 if (ret || !write)
580 return ret;
581
582 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
583 sysctl_sched_min_granularity);
584
acb4a848
CE
585#define WRT_SYSCTL(name) \
586 (normalized_sysctl_##name = sysctl_##name / (factor))
587 WRT_SYSCTL(sched_min_granularity);
588 WRT_SYSCTL(sched_latency);
589 WRT_SYSCTL(sched_wakeup_granularity);
acb4a848
CE
590#undef WRT_SYSCTL
591
b2be5e96
PZ
592 return 0;
593}
594#endif
647e7cac 595
a7be37ac 596/*
f9c0b095 597 * delta /= w
a7be37ac 598 */
9dbdb155 599static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
a7be37ac 600{
f9c0b095 601 if (unlikely(se->load.weight != NICE_0_LOAD))
9dbdb155 602 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
a7be37ac
PZ
603
604 return delta;
605}
606
647e7cac
IM
607/*
608 * The idea is to set a period in which each task runs once.
609 *
532b1858 610 * When there are too many tasks (sched_nr_latency) we have to stretch
647e7cac
IM
611 * this period because otherwise the slices get too small.
612 *
613 * p = (nr <= nl) ? l : l*nr/nl
614 */
4d78e7b6
PZ
615static u64 __sched_period(unsigned long nr_running)
616{
8e2b0bf3
BF
617 if (unlikely(nr_running > sched_nr_latency))
618 return nr_running * sysctl_sched_min_granularity;
619 else
620 return sysctl_sched_latency;
4d78e7b6
PZ
621}
622
647e7cac
IM
623/*
624 * We calculate the wall-time slice from the period by taking a part
625 * proportional to the weight.
626 *
f9c0b095 627 * s = p*P[w/rw]
647e7cac 628 */
6d0f0ebd 629static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
21805085 630{
0a582440 631 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
f9c0b095 632
0a582440 633 for_each_sched_entity(se) {
6272d68c 634 struct load_weight *load;
3104bf03 635 struct load_weight lw;
6272d68c
LM
636
637 cfs_rq = cfs_rq_of(se);
638 load = &cfs_rq->load;
f9c0b095 639
0a582440 640 if (unlikely(!se->on_rq)) {
3104bf03 641 lw = cfs_rq->load;
0a582440
MG
642
643 update_load_add(&lw, se->load.weight);
644 load = &lw;
645 }
9dbdb155 646 slice = __calc_delta(slice, se->load.weight, load);
0a582440
MG
647 }
648 return slice;
bf0f6f24
IM
649}
650
647e7cac 651/*
660cc00f 652 * We calculate the vruntime slice of a to-be-inserted task.
647e7cac 653 *
f9c0b095 654 * vs = s/w
647e7cac 655 */
f9c0b095 656static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
67e9fb2a 657{
f9c0b095 658 return calc_delta_fair(sched_slice(cfs_rq, se), se);
a7be37ac
PZ
659}
660
a75cdaa9 661#ifdef CONFIG_SMP
772bd008 662static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
fb13c7ee
MG
663static unsigned long task_h_load(struct task_struct *p);
664
9d89c257
YD
665/*
666 * We choose a half-life close to 1 scheduling period.
84fb5a18
LY
667 * Note: The tables runnable_avg_yN_inv and runnable_avg_yN_sum are
668 * dependent on this value.
9d89c257
YD
669 */
670#define LOAD_AVG_PERIOD 32
671#define LOAD_AVG_MAX 47742 /* maximum possible load avg */
84fb5a18 672#define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_AVG_MAX */
a75cdaa9 673
540247fb
YD
674/* Give new sched_entity start runnable values to heavy its load in infant time */
675void init_entity_runnable_average(struct sched_entity *se)
a75cdaa9 676{
540247fb 677 struct sched_avg *sa = &se->avg;
a75cdaa9 678
9d89c257
YD
679 sa->last_update_time = 0;
680 /*
681 * sched_avg's period_contrib should be strictly less then 1024, so
682 * we give it 1023 to make sure it is almost a period (1024us), and
683 * will definitely be update (after enqueue).
684 */
685 sa->period_contrib = 1023;
b5a9b340
VG
686 /*
687 * Tasks are intialized with full load to be seen as heavy tasks until
688 * they get a chance to stabilize to their real load level.
689 * Group entities are intialized with zero load to reflect the fact that
690 * nothing has been attached to the task group yet.
691 */
692 if (entity_is_task(se))
693 sa->load_avg = scale_load_down(se->load.weight);
9d89c257 694 sa->load_sum = sa->load_avg * LOAD_AVG_MAX;
2b8c41da
YD
695 /*
696 * At this point, util_avg won't be used in select_task_rq_fair anyway
697 */
698 sa->util_avg = 0;
699 sa->util_sum = 0;
9d89c257 700 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
a75cdaa9 701}
7ea241af 702
7dc603c9
PZ
703static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
704static int update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq);
3d30544f 705static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force);
7dc603c9
PZ
706static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se);
707
2b8c41da
YD
708/*
709 * With new tasks being created, their initial util_avgs are extrapolated
710 * based on the cfs_rq's current util_avg:
711 *
712 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
713 *
714 * However, in many cases, the above util_avg does not give a desired
715 * value. Moreover, the sum of the util_avgs may be divergent, such
716 * as when the series is a harmonic series.
717 *
718 * To solve this problem, we also cap the util_avg of successive tasks to
719 * only 1/2 of the left utilization budget:
720 *
721 * util_avg_cap = (1024 - cfs_rq->avg.util_avg) / 2^n
722 *
723 * where n denotes the nth task.
724 *
725 * For example, a simplest series from the beginning would be like:
726 *
727 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
728 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
729 *
730 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
731 * if util_avg > util_avg_cap.
732 */
733void post_init_entity_util_avg(struct sched_entity *se)
734{
735 struct cfs_rq *cfs_rq = cfs_rq_of(se);
736 struct sched_avg *sa = &se->avg;
172895e6 737 long cap = (long)(SCHED_CAPACITY_SCALE - cfs_rq->avg.util_avg) / 2;
7dc603c9 738 u64 now = cfs_rq_clock_task(cfs_rq);
2b8c41da
YD
739
740 if (cap > 0) {
741 if (cfs_rq->avg.util_avg != 0) {
742 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
743 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
744
745 if (sa->util_avg > cap)
746 sa->util_avg = cap;
747 } else {
748 sa->util_avg = cap;
749 }
750 sa->util_sum = sa->util_avg * LOAD_AVG_MAX;
751 }
7dc603c9
PZ
752
753 if (entity_is_task(se)) {
754 struct task_struct *p = task_of(se);
755 if (p->sched_class != &fair_sched_class) {
756 /*
757 * For !fair tasks do:
758 *
759 update_cfs_rq_load_avg(now, cfs_rq, false);
760 attach_entity_load_avg(cfs_rq, se);
761 switched_from_fair(rq, p);
762 *
763 * such that the next switched_to_fair() has the
764 * expected state.
765 */
766 se->avg.last_update_time = now;
767 return;
768 }
769 }
770
7c3edd2c 771 update_cfs_rq_load_avg(now, cfs_rq, false);
7dc603c9 772 attach_entity_load_avg(cfs_rq, se);
7c3edd2c 773 update_tg_load_avg(cfs_rq, false);
2b8c41da
YD
774}
775
7dc603c9 776#else /* !CONFIG_SMP */
540247fb 777void init_entity_runnable_average(struct sched_entity *se)
a75cdaa9
AS
778{
779}
2b8c41da
YD
780void post_init_entity_util_avg(struct sched_entity *se)
781{
782}
3d30544f
PZ
783static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
784{
785}
7dc603c9 786#endif /* CONFIG_SMP */
a75cdaa9 787
bf0f6f24 788/*
9dbdb155 789 * Update the current task's runtime statistics.
bf0f6f24 790 */
b7cc0896 791static void update_curr(struct cfs_rq *cfs_rq)
bf0f6f24 792{
429d43bc 793 struct sched_entity *curr = cfs_rq->curr;
78becc27 794 u64 now = rq_clock_task(rq_of(cfs_rq));
9dbdb155 795 u64 delta_exec;
bf0f6f24
IM
796
797 if (unlikely(!curr))
798 return;
799
9dbdb155
PZ
800 delta_exec = now - curr->exec_start;
801 if (unlikely((s64)delta_exec <= 0))
34f28ecd 802 return;
bf0f6f24 803
8ebc91d9 804 curr->exec_start = now;
d842de87 805
9dbdb155
PZ
806 schedstat_set(curr->statistics.exec_max,
807 max(delta_exec, curr->statistics.exec_max));
808
809 curr->sum_exec_runtime += delta_exec;
ae92882e 810 schedstat_add(cfs_rq->exec_clock, delta_exec);
9dbdb155
PZ
811
812 curr->vruntime += calc_delta_fair(delta_exec, curr);
813 update_min_vruntime(cfs_rq);
814
d842de87
SV
815 if (entity_is_task(curr)) {
816 struct task_struct *curtask = task_of(curr);
817
f977bb49 818 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
d842de87 819 cpuacct_charge(curtask, delta_exec);
f06febc9 820 account_group_exec_runtime(curtask, delta_exec);
d842de87 821 }
ec12cb7f
PT
822
823 account_cfs_rq_runtime(cfs_rq, delta_exec);
bf0f6f24
IM
824}
825
6e998916
SG
826static void update_curr_fair(struct rq *rq)
827{
828 update_curr(cfs_rq_of(&rq->curr->se));
829}
830
bf0f6f24 831static inline void
5870db5b 832update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 833{
4fa8d299
JP
834 u64 wait_start, prev_wait_start;
835
836 if (!schedstat_enabled())
837 return;
838
839 wait_start = rq_clock(rq_of(cfs_rq));
840 prev_wait_start = schedstat_val(se->statistics.wait_start);
3ea94de1
JP
841
842 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)) &&
4fa8d299
JP
843 likely(wait_start > prev_wait_start))
844 wait_start -= prev_wait_start;
3ea94de1 845
4fa8d299 846 schedstat_set(se->statistics.wait_start, wait_start);
bf0f6f24
IM
847}
848
4fa8d299 849static inline void
3ea94de1
JP
850update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
851{
852 struct task_struct *p;
cb251765
MG
853 u64 delta;
854
4fa8d299
JP
855 if (!schedstat_enabled())
856 return;
857
858 delta = rq_clock(rq_of(cfs_rq)) - schedstat_val(se->statistics.wait_start);
3ea94de1
JP
859
860 if (entity_is_task(se)) {
861 p = task_of(se);
862 if (task_on_rq_migrating(p)) {
863 /*
864 * Preserve migrating task's wait time so wait_start
865 * time stamp can be adjusted to accumulate wait time
866 * prior to migration.
867 */
4fa8d299 868 schedstat_set(se->statistics.wait_start, delta);
3ea94de1
JP
869 return;
870 }
871 trace_sched_stat_wait(p, delta);
872 }
873
4fa8d299
JP
874 schedstat_set(se->statistics.wait_max,
875 max(schedstat_val(se->statistics.wait_max), delta));
876 schedstat_inc(se->statistics.wait_count);
877 schedstat_add(se->statistics.wait_sum, delta);
878 schedstat_set(se->statistics.wait_start, 0);
3ea94de1 879}
3ea94de1 880
4fa8d299 881static inline void
1a3d027c
JP
882update_stats_enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
883{
884 struct task_struct *tsk = NULL;
4fa8d299
JP
885 u64 sleep_start, block_start;
886
887 if (!schedstat_enabled())
888 return;
889
890 sleep_start = schedstat_val(se->statistics.sleep_start);
891 block_start = schedstat_val(se->statistics.block_start);
1a3d027c
JP
892
893 if (entity_is_task(se))
894 tsk = task_of(se);
895
4fa8d299
JP
896 if (sleep_start) {
897 u64 delta = rq_clock(rq_of(cfs_rq)) - sleep_start;
1a3d027c
JP
898
899 if ((s64)delta < 0)
900 delta = 0;
901
4fa8d299
JP
902 if (unlikely(delta > schedstat_val(se->statistics.sleep_max)))
903 schedstat_set(se->statistics.sleep_max, delta);
1a3d027c 904
4fa8d299
JP
905 schedstat_set(se->statistics.sleep_start, 0);
906 schedstat_add(se->statistics.sum_sleep_runtime, delta);
1a3d027c
JP
907
908 if (tsk) {
909 account_scheduler_latency(tsk, delta >> 10, 1);
910 trace_sched_stat_sleep(tsk, delta);
911 }
912 }
4fa8d299
JP
913 if (block_start) {
914 u64 delta = rq_clock(rq_of(cfs_rq)) - block_start;
1a3d027c
JP
915
916 if ((s64)delta < 0)
917 delta = 0;
918
4fa8d299
JP
919 if (unlikely(delta > schedstat_val(se->statistics.block_max)))
920 schedstat_set(se->statistics.block_max, delta);
1a3d027c 921
4fa8d299
JP
922 schedstat_set(se->statistics.block_start, 0);
923 schedstat_add(se->statistics.sum_sleep_runtime, delta);
1a3d027c
JP
924
925 if (tsk) {
926 if (tsk->in_iowait) {
4fa8d299
JP
927 schedstat_add(se->statistics.iowait_sum, delta);
928 schedstat_inc(se->statistics.iowait_count);
1a3d027c
JP
929 trace_sched_stat_iowait(tsk, delta);
930 }
931
932 trace_sched_stat_blocked(tsk, delta);
933
934 /*
935 * Blocking time is in units of nanosecs, so shift by
936 * 20 to get a milliseconds-range estimation of the
937 * amount of time that the task spent sleeping:
938 */
939 if (unlikely(prof_on == SLEEP_PROFILING)) {
940 profile_hits(SLEEP_PROFILING,
941 (void *)get_wchan(tsk),
942 delta >> 20);
943 }
944 account_scheduler_latency(tsk, delta >> 10, 0);
945 }
946 }
3ea94de1 947}
3ea94de1 948
bf0f6f24
IM
949/*
950 * Task is being enqueued - update stats:
951 */
cb251765 952static inline void
1a3d027c 953update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 954{
4fa8d299
JP
955 if (!schedstat_enabled())
956 return;
957
bf0f6f24
IM
958 /*
959 * Are we enqueueing a waiting task? (for current tasks
960 * a dequeue/enqueue event is a NOP)
961 */
429d43bc 962 if (se != cfs_rq->curr)
5870db5b 963 update_stats_wait_start(cfs_rq, se);
1a3d027c
JP
964
965 if (flags & ENQUEUE_WAKEUP)
966 update_stats_enqueue_sleeper(cfs_rq, se);
bf0f6f24
IM
967}
968
bf0f6f24 969static inline void
cb251765 970update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 971{
4fa8d299
JP
972
973 if (!schedstat_enabled())
974 return;
975
bf0f6f24
IM
976 /*
977 * Mark the end of the wait period if dequeueing a
978 * waiting task:
979 */
429d43bc 980 if (se != cfs_rq->curr)
9ef0a961 981 update_stats_wait_end(cfs_rq, se);
cb251765 982
4fa8d299
JP
983 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
984 struct task_struct *tsk = task_of(se);
cb251765 985
4fa8d299
JP
986 if (tsk->state & TASK_INTERRUPTIBLE)
987 schedstat_set(se->statistics.sleep_start,
988 rq_clock(rq_of(cfs_rq)));
989 if (tsk->state & TASK_UNINTERRUPTIBLE)
990 schedstat_set(se->statistics.block_start,
991 rq_clock(rq_of(cfs_rq)));
cb251765 992 }
cb251765
MG
993}
994
bf0f6f24
IM
995/*
996 * We are picking a new current task - update its stats:
997 */
998static inline void
79303e9e 999update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24
IM
1000{
1001 /*
1002 * We are starting a new run period:
1003 */
78becc27 1004 se->exec_start = rq_clock_task(rq_of(cfs_rq));
bf0f6f24
IM
1005}
1006
bf0f6f24
IM
1007/**************************************************
1008 * Scheduling class queueing methods:
1009 */
1010
cbee9f88
PZ
1011#ifdef CONFIG_NUMA_BALANCING
1012/*
598f0ec0
MG
1013 * Approximate time to scan a full NUMA task in ms. The task scan period is
1014 * calculated based on the tasks virtual memory size and
1015 * numa_balancing_scan_size.
cbee9f88 1016 */
598f0ec0
MG
1017unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1018unsigned int sysctl_numa_balancing_scan_period_max = 60000;
6e5fb223
PZ
1019
1020/* Portion of address space to scan in MB */
1021unsigned int sysctl_numa_balancing_scan_size = 256;
cbee9f88 1022
4b96a29b
PZ
1023/* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1024unsigned int sysctl_numa_balancing_scan_delay = 1000;
1025
598f0ec0
MG
1026static unsigned int task_nr_scan_windows(struct task_struct *p)
1027{
1028 unsigned long rss = 0;
1029 unsigned long nr_scan_pages;
1030
1031 /*
1032 * Calculations based on RSS as non-present and empty pages are skipped
1033 * by the PTE scanner and NUMA hinting faults should be trapped based
1034 * on resident pages
1035 */
1036 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1037 rss = get_mm_rss(p->mm);
1038 if (!rss)
1039 rss = nr_scan_pages;
1040
1041 rss = round_up(rss, nr_scan_pages);
1042 return rss / nr_scan_pages;
1043}
1044
1045/* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1046#define MAX_SCAN_WINDOW 2560
1047
1048static unsigned int task_scan_min(struct task_struct *p)
1049{
316c1608 1050 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
598f0ec0
MG
1051 unsigned int scan, floor;
1052 unsigned int windows = 1;
1053
64192658
KT
1054 if (scan_size < MAX_SCAN_WINDOW)
1055 windows = MAX_SCAN_WINDOW / scan_size;
598f0ec0
MG
1056 floor = 1000 / windows;
1057
1058 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1059 return max_t(unsigned int, floor, scan);
1060}
1061
1062static unsigned int task_scan_max(struct task_struct *p)
1063{
1064 unsigned int smin = task_scan_min(p);
1065 unsigned int smax;
1066
1067 /* Watch for min being lower than max due to floor calculations */
1068 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1069 return max(smin, smax);
1070}
1071
0ec8aa00
PZ
1072static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1073{
1074 rq->nr_numa_running += (p->numa_preferred_nid != -1);
1075 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1076}
1077
1078static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1079{
1080 rq->nr_numa_running -= (p->numa_preferred_nid != -1);
1081 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1082}
1083
8c8a743c
PZ
1084struct numa_group {
1085 atomic_t refcount;
1086
1087 spinlock_t lock; /* nr_tasks, tasks */
1088 int nr_tasks;
e29cf08b 1089 pid_t gid;
4142c3eb 1090 int active_nodes;
8c8a743c
PZ
1091
1092 struct rcu_head rcu;
989348b5 1093 unsigned long total_faults;
4142c3eb 1094 unsigned long max_faults_cpu;
7e2703e6
RR
1095 /*
1096 * Faults_cpu is used to decide whether memory should move
1097 * towards the CPU. As a consequence, these stats are weighted
1098 * more by CPU use than by memory faults.
1099 */
50ec8a40 1100 unsigned long *faults_cpu;
989348b5 1101 unsigned long faults[0];
8c8a743c
PZ
1102};
1103
be1e4e76
RR
1104/* Shared or private faults. */
1105#define NR_NUMA_HINT_FAULT_TYPES 2
1106
1107/* Memory and CPU locality */
1108#define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1109
1110/* Averaged statistics, and temporary buffers. */
1111#define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1112
e29cf08b
MG
1113pid_t task_numa_group_id(struct task_struct *p)
1114{
1115 return p->numa_group ? p->numa_group->gid : 0;
1116}
1117
44dba3d5
IM
1118/*
1119 * The averaged statistics, shared & private, memory & cpu,
1120 * occupy the first half of the array. The second half of the
1121 * array is for current counters, which are averaged into the
1122 * first set by task_numa_placement.
1123 */
1124static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
ac8e895b 1125{
44dba3d5 1126 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
ac8e895b
MG
1127}
1128
1129static inline unsigned long task_faults(struct task_struct *p, int nid)
1130{
44dba3d5 1131 if (!p->numa_faults)
ac8e895b
MG
1132 return 0;
1133
44dba3d5
IM
1134 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1135 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
ac8e895b
MG
1136}
1137
83e1d2cd
MG
1138static inline unsigned long group_faults(struct task_struct *p, int nid)
1139{
1140 if (!p->numa_group)
1141 return 0;
1142
44dba3d5
IM
1143 return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1144 p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
83e1d2cd
MG
1145}
1146
20e07dea
RR
1147static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1148{
44dba3d5
IM
1149 return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
1150 group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
20e07dea
RR
1151}
1152
4142c3eb
RR
1153/*
1154 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1155 * considered part of a numa group's pseudo-interleaving set. Migrations
1156 * between these nodes are slowed down, to allow things to settle down.
1157 */
1158#define ACTIVE_NODE_FRACTION 3
1159
1160static bool numa_is_active_node(int nid, struct numa_group *ng)
1161{
1162 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1163}
1164
6c6b1193
RR
1165/* Handle placement on systems where not all nodes are directly connected. */
1166static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1167 int maxdist, bool task)
1168{
1169 unsigned long score = 0;
1170 int node;
1171
1172 /*
1173 * All nodes are directly connected, and the same distance
1174 * from each other. No need for fancy placement algorithms.
1175 */
1176 if (sched_numa_topology_type == NUMA_DIRECT)
1177 return 0;
1178
1179 /*
1180 * This code is called for each node, introducing N^2 complexity,
1181 * which should be ok given the number of nodes rarely exceeds 8.
1182 */
1183 for_each_online_node(node) {
1184 unsigned long faults;
1185 int dist = node_distance(nid, node);
1186
1187 /*
1188 * The furthest away nodes in the system are not interesting
1189 * for placement; nid was already counted.
1190 */
1191 if (dist == sched_max_numa_distance || node == nid)
1192 continue;
1193
1194 /*
1195 * On systems with a backplane NUMA topology, compare groups
1196 * of nodes, and move tasks towards the group with the most
1197 * memory accesses. When comparing two nodes at distance
1198 * "hoplimit", only nodes closer by than "hoplimit" are part
1199 * of each group. Skip other nodes.
1200 */
1201 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1202 dist > maxdist)
1203 continue;
1204
1205 /* Add up the faults from nearby nodes. */
1206 if (task)
1207 faults = task_faults(p, node);
1208 else
1209 faults = group_faults(p, node);
1210
1211 /*
1212 * On systems with a glueless mesh NUMA topology, there are
1213 * no fixed "groups of nodes". Instead, nodes that are not
1214 * directly connected bounce traffic through intermediate
1215 * nodes; a numa_group can occupy any set of nodes.
1216 * The further away a node is, the less the faults count.
1217 * This seems to result in good task placement.
1218 */
1219 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1220 faults *= (sched_max_numa_distance - dist);
1221 faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
1222 }
1223
1224 score += faults;
1225 }
1226
1227 return score;
1228}
1229
83e1d2cd
MG
1230/*
1231 * These return the fraction of accesses done by a particular task, or
1232 * task group, on a particular numa node. The group weight is given a
1233 * larger multiplier, in order to group tasks together that are almost
1234 * evenly spread out between numa nodes.
1235 */
7bd95320
RR
1236static inline unsigned long task_weight(struct task_struct *p, int nid,
1237 int dist)
83e1d2cd 1238{
7bd95320 1239 unsigned long faults, total_faults;
83e1d2cd 1240
44dba3d5 1241 if (!p->numa_faults)
83e1d2cd
MG
1242 return 0;
1243
1244 total_faults = p->total_numa_faults;
1245
1246 if (!total_faults)
1247 return 0;
1248
7bd95320 1249 faults = task_faults(p, nid);
6c6b1193
RR
1250 faults += score_nearby_nodes(p, nid, dist, true);
1251
7bd95320 1252 return 1000 * faults / total_faults;
83e1d2cd
MG
1253}
1254
7bd95320
RR
1255static inline unsigned long group_weight(struct task_struct *p, int nid,
1256 int dist)
83e1d2cd 1257{
7bd95320
RR
1258 unsigned long faults, total_faults;
1259
1260 if (!p->numa_group)
1261 return 0;
1262
1263 total_faults = p->numa_group->total_faults;
1264
1265 if (!total_faults)
83e1d2cd
MG
1266 return 0;
1267
7bd95320 1268 faults = group_faults(p, nid);
6c6b1193
RR
1269 faults += score_nearby_nodes(p, nid, dist, false);
1270
7bd95320 1271 return 1000 * faults / total_faults;
83e1d2cd
MG
1272}
1273
10f39042
RR
1274bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1275 int src_nid, int dst_cpu)
1276{
1277 struct numa_group *ng = p->numa_group;
1278 int dst_nid = cpu_to_node(dst_cpu);
1279 int last_cpupid, this_cpupid;
1280
1281 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1282
1283 /*
1284 * Multi-stage node selection is used in conjunction with a periodic
1285 * migration fault to build a temporal task<->page relation. By using
1286 * a two-stage filter we remove short/unlikely relations.
1287 *
1288 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1289 * a task's usage of a particular page (n_p) per total usage of this
1290 * page (n_t) (in a given time-span) to a probability.
1291 *
1292 * Our periodic faults will sample this probability and getting the
1293 * same result twice in a row, given these samples are fully
1294 * independent, is then given by P(n)^2, provided our sample period
1295 * is sufficiently short compared to the usage pattern.
1296 *
1297 * This quadric squishes small probabilities, making it less likely we
1298 * act on an unlikely task<->page relation.
1299 */
1300 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1301 if (!cpupid_pid_unset(last_cpupid) &&
1302 cpupid_to_nid(last_cpupid) != dst_nid)
1303 return false;
1304
1305 /* Always allow migrate on private faults */
1306 if (cpupid_match_pid(p, last_cpupid))
1307 return true;
1308
1309 /* A shared fault, but p->numa_group has not been set up yet. */
1310 if (!ng)
1311 return true;
1312
1313 /*
4142c3eb
RR
1314 * Destination node is much more heavily used than the source
1315 * node? Allow migration.
10f39042 1316 */
4142c3eb
RR
1317 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1318 ACTIVE_NODE_FRACTION)
10f39042
RR
1319 return true;
1320
1321 /*
4142c3eb
RR
1322 * Distribute memory according to CPU & memory use on each node,
1323 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1324 *
1325 * faults_cpu(dst) 3 faults_cpu(src)
1326 * --------------- * - > ---------------
1327 * faults_mem(dst) 4 faults_mem(src)
10f39042 1328 */
4142c3eb
RR
1329 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1330 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
10f39042
RR
1331}
1332
e6628d5b 1333static unsigned long weighted_cpuload(const int cpu);
58d081b5
MG
1334static unsigned long source_load(int cpu, int type);
1335static unsigned long target_load(int cpu, int type);
ced549fa 1336static unsigned long capacity_of(int cpu);
58d081b5
MG
1337static long effective_load(struct task_group *tg, int cpu, long wl, long wg);
1338
fb13c7ee 1339/* Cached statistics for all CPUs within a node */
58d081b5 1340struct numa_stats {
fb13c7ee 1341 unsigned long nr_running;
58d081b5 1342 unsigned long load;
fb13c7ee
MG
1343
1344 /* Total compute capacity of CPUs on a node */
5ef20ca1 1345 unsigned long compute_capacity;
fb13c7ee
MG
1346
1347 /* Approximate capacity in terms of runnable tasks on a node */
5ef20ca1 1348 unsigned long task_capacity;
1b6a7495 1349 int has_free_capacity;
58d081b5 1350};
e6628d5b 1351
fb13c7ee
MG
1352/*
1353 * XXX borrowed from update_sg_lb_stats
1354 */
1355static void update_numa_stats(struct numa_stats *ns, int nid)
1356{
83d7f242
RR
1357 int smt, cpu, cpus = 0;
1358 unsigned long capacity;
fb13c7ee
MG
1359
1360 memset(ns, 0, sizeof(*ns));
1361 for_each_cpu(cpu, cpumask_of_node(nid)) {
1362 struct rq *rq = cpu_rq(cpu);
1363
1364 ns->nr_running += rq->nr_running;
1365 ns->load += weighted_cpuload(cpu);
ced549fa 1366 ns->compute_capacity += capacity_of(cpu);
5eca82a9
PZ
1367
1368 cpus++;
fb13c7ee
MG
1369 }
1370
5eca82a9
PZ
1371 /*
1372 * If we raced with hotplug and there are no CPUs left in our mask
1373 * the @ns structure is NULL'ed and task_numa_compare() will
1374 * not find this node attractive.
1375 *
1b6a7495
NP
1376 * We'll either bail at !has_free_capacity, or we'll detect a huge
1377 * imbalance and bail there.
5eca82a9
PZ
1378 */
1379 if (!cpus)
1380 return;
1381
83d7f242
RR
1382 /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
1383 smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity);
1384 capacity = cpus / smt; /* cores */
1385
1386 ns->task_capacity = min_t(unsigned, capacity,
1387 DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE));
1b6a7495 1388 ns->has_free_capacity = (ns->nr_running < ns->task_capacity);
fb13c7ee
MG
1389}
1390
58d081b5
MG
1391struct task_numa_env {
1392 struct task_struct *p;
e6628d5b 1393
58d081b5
MG
1394 int src_cpu, src_nid;
1395 int dst_cpu, dst_nid;
e6628d5b 1396
58d081b5 1397 struct numa_stats src_stats, dst_stats;
e6628d5b 1398
40ea2b42 1399 int imbalance_pct;
7bd95320 1400 int dist;
fb13c7ee
MG
1401
1402 struct task_struct *best_task;
1403 long best_imp;
58d081b5
MG
1404 int best_cpu;
1405};
1406
fb13c7ee
MG
1407static void task_numa_assign(struct task_numa_env *env,
1408 struct task_struct *p, long imp)
1409{
1410 if (env->best_task)
1411 put_task_struct(env->best_task);
bac78573
ON
1412 if (p)
1413 get_task_struct(p);
fb13c7ee
MG
1414
1415 env->best_task = p;
1416 env->best_imp = imp;
1417 env->best_cpu = env->dst_cpu;
1418}
1419
28a21745 1420static bool load_too_imbalanced(long src_load, long dst_load,
e63da036
RR
1421 struct task_numa_env *env)
1422{
e4991b24
RR
1423 long imb, old_imb;
1424 long orig_src_load, orig_dst_load;
28a21745
RR
1425 long src_capacity, dst_capacity;
1426
1427 /*
1428 * The load is corrected for the CPU capacity available on each node.
1429 *
1430 * src_load dst_load
1431 * ------------ vs ---------
1432 * src_capacity dst_capacity
1433 */
1434 src_capacity = env->src_stats.compute_capacity;
1435 dst_capacity = env->dst_stats.compute_capacity;
e63da036
RR
1436
1437 /* We care about the slope of the imbalance, not the direction. */
e4991b24
RR
1438 if (dst_load < src_load)
1439 swap(dst_load, src_load);
e63da036
RR
1440
1441 /* Is the difference below the threshold? */
e4991b24
RR
1442 imb = dst_load * src_capacity * 100 -
1443 src_load * dst_capacity * env->imbalance_pct;
e63da036
RR
1444 if (imb <= 0)
1445 return false;
1446
1447 /*
1448 * The imbalance is above the allowed threshold.
e4991b24 1449 * Compare it with the old imbalance.
e63da036 1450 */
28a21745 1451 orig_src_load = env->src_stats.load;
e4991b24 1452 orig_dst_load = env->dst_stats.load;
28a21745 1453
e4991b24
RR
1454 if (orig_dst_load < orig_src_load)
1455 swap(orig_dst_load, orig_src_load);
e63da036 1456
e4991b24
RR
1457 old_imb = orig_dst_load * src_capacity * 100 -
1458 orig_src_load * dst_capacity * env->imbalance_pct;
1459
1460 /* Would this change make things worse? */
1461 return (imb > old_imb);
e63da036
RR
1462}
1463
fb13c7ee
MG
1464/*
1465 * This checks if the overall compute and NUMA accesses of the system would
1466 * be improved if the source tasks was migrated to the target dst_cpu taking
1467 * into account that it might be best if task running on the dst_cpu should
1468 * be exchanged with the source task
1469 */
887c290e
RR
1470static void task_numa_compare(struct task_numa_env *env,
1471 long taskimp, long groupimp)
fb13c7ee
MG
1472{
1473 struct rq *src_rq = cpu_rq(env->src_cpu);
1474 struct rq *dst_rq = cpu_rq(env->dst_cpu);
1475 struct task_struct *cur;
28a21745 1476 long src_load, dst_load;
fb13c7ee 1477 long load;
1c5d3eb3 1478 long imp = env->p->numa_group ? groupimp : taskimp;
0132c3e1 1479 long moveimp = imp;
7bd95320 1480 int dist = env->dist;
fb13c7ee
MG
1481
1482 rcu_read_lock();
bac78573
ON
1483 cur = task_rcu_dereference(&dst_rq->curr);
1484 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
fb13c7ee
MG
1485 cur = NULL;
1486
7af68335
PZ
1487 /*
1488 * Because we have preemption enabled we can get migrated around and
1489 * end try selecting ourselves (current == env->p) as a swap candidate.
1490 */
1491 if (cur == env->p)
1492 goto unlock;
1493
fb13c7ee
MG
1494 /*
1495 * "imp" is the fault differential for the source task between the
1496 * source and destination node. Calculate the total differential for
1497 * the source task and potential destination task. The more negative
1498 * the value is, the more rmeote accesses that would be expected to
1499 * be incurred if the tasks were swapped.
1500 */
1501 if (cur) {
1502 /* Skip this swap candidate if cannot move to the source cpu */
1503 if (!cpumask_test_cpu(env->src_cpu, tsk_cpus_allowed(cur)))
1504 goto unlock;
1505
887c290e
RR
1506 /*
1507 * If dst and source tasks are in the same NUMA group, or not
ca28aa53 1508 * in any group then look only at task weights.
887c290e 1509 */
ca28aa53 1510 if (cur->numa_group == env->p->numa_group) {
7bd95320
RR
1511 imp = taskimp + task_weight(cur, env->src_nid, dist) -
1512 task_weight(cur, env->dst_nid, dist);
ca28aa53
RR
1513 /*
1514 * Add some hysteresis to prevent swapping the
1515 * tasks within a group over tiny differences.
1516 */
1517 if (cur->numa_group)
1518 imp -= imp/16;
887c290e 1519 } else {
ca28aa53
RR
1520 /*
1521 * Compare the group weights. If a task is all by
1522 * itself (not part of a group), use the task weight
1523 * instead.
1524 */
ca28aa53 1525 if (cur->numa_group)
7bd95320
RR
1526 imp += group_weight(cur, env->src_nid, dist) -
1527 group_weight(cur, env->dst_nid, dist);
ca28aa53 1528 else
7bd95320
RR
1529 imp += task_weight(cur, env->src_nid, dist) -
1530 task_weight(cur, env->dst_nid, dist);
887c290e 1531 }
fb13c7ee
MG
1532 }
1533
0132c3e1 1534 if (imp <= env->best_imp && moveimp <= env->best_imp)
fb13c7ee
MG
1535 goto unlock;
1536
1537 if (!cur) {
1538 /* Is there capacity at our destination? */
b932c03c 1539 if (env->src_stats.nr_running <= env->src_stats.task_capacity &&
1b6a7495 1540 !env->dst_stats.has_free_capacity)
fb13c7ee
MG
1541 goto unlock;
1542
1543 goto balance;
1544 }
1545
1546 /* Balance doesn't matter much if we're running a task per cpu */
0132c3e1
RR
1547 if (imp > env->best_imp && src_rq->nr_running == 1 &&
1548 dst_rq->nr_running == 1)
fb13c7ee
MG
1549 goto assign;
1550
1551 /*
1552 * In the overloaded case, try and keep the load balanced.
1553 */
1554balance:
e720fff6
PZ
1555 load = task_h_load(env->p);
1556 dst_load = env->dst_stats.load + load;
1557 src_load = env->src_stats.load - load;
fb13c7ee 1558
0132c3e1
RR
1559 if (moveimp > imp && moveimp > env->best_imp) {
1560 /*
1561 * If the improvement from just moving env->p direction is
1562 * better than swapping tasks around, check if a move is
1563 * possible. Store a slightly smaller score than moveimp,
1564 * so an actually idle CPU will win.
1565 */
1566 if (!load_too_imbalanced(src_load, dst_load, env)) {
1567 imp = moveimp - 1;
1568 cur = NULL;
1569 goto assign;
1570 }
1571 }
1572
1573 if (imp <= env->best_imp)
1574 goto unlock;
1575
fb13c7ee 1576 if (cur) {
e720fff6
PZ
1577 load = task_h_load(cur);
1578 dst_load -= load;
1579 src_load += load;
fb13c7ee
MG
1580 }
1581
28a21745 1582 if (load_too_imbalanced(src_load, dst_load, env))
fb13c7ee
MG
1583 goto unlock;
1584
ba7e5a27
RR
1585 /*
1586 * One idle CPU per node is evaluated for a task numa move.
1587 * Call select_idle_sibling to maybe find a better one.
1588 */
10e2f1ac
PZ
1589 if (!cur) {
1590 /*
1591 * select_idle_siblings() uses an per-cpu cpumask that
1592 * can be used from IRQ context.
1593 */
1594 local_irq_disable();
772bd008
MR
1595 env->dst_cpu = select_idle_sibling(env->p, env->src_cpu,
1596 env->dst_cpu);
10e2f1ac
PZ
1597 local_irq_enable();
1598 }
ba7e5a27 1599
fb13c7ee
MG
1600assign:
1601 task_numa_assign(env, cur, imp);
1602unlock:
1603 rcu_read_unlock();
1604}
1605
887c290e
RR
1606static void task_numa_find_cpu(struct task_numa_env *env,
1607 long taskimp, long groupimp)
2c8a50aa
MG
1608{
1609 int cpu;
1610
1611 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
1612 /* Skip this CPU if the source task cannot migrate */
1613 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(env->p)))
1614 continue;
1615
1616 env->dst_cpu = cpu;
887c290e 1617 task_numa_compare(env, taskimp, groupimp);
2c8a50aa
MG
1618 }
1619}
1620
6f9aad0b
RR
1621/* Only move tasks to a NUMA node less busy than the current node. */
1622static bool numa_has_capacity(struct task_numa_env *env)
1623{
1624 struct numa_stats *src = &env->src_stats;
1625 struct numa_stats *dst = &env->dst_stats;
1626
1627 if (src->has_free_capacity && !dst->has_free_capacity)
1628 return false;
1629
1630 /*
1631 * Only consider a task move if the source has a higher load
1632 * than the destination, corrected for CPU capacity on each node.
1633 *
1634 * src->load dst->load
1635 * --------------------- vs ---------------------
1636 * src->compute_capacity dst->compute_capacity
1637 */
44dcb04f
SD
1638 if (src->load * dst->compute_capacity * env->imbalance_pct >
1639
1640 dst->load * src->compute_capacity * 100)
6f9aad0b
RR
1641 return true;
1642
1643 return false;
1644}
1645
58d081b5
MG
1646static int task_numa_migrate(struct task_struct *p)
1647{
58d081b5
MG
1648 struct task_numa_env env = {
1649 .p = p,
fb13c7ee 1650
58d081b5 1651 .src_cpu = task_cpu(p),
b32e86b4 1652 .src_nid = task_node(p),
fb13c7ee
MG
1653
1654 .imbalance_pct = 112,
1655
1656 .best_task = NULL,
1657 .best_imp = 0,
4142c3eb 1658 .best_cpu = -1,
58d081b5
MG
1659 };
1660 struct sched_domain *sd;
887c290e 1661 unsigned long taskweight, groupweight;
7bd95320 1662 int nid, ret, dist;
887c290e 1663 long taskimp, groupimp;
e6628d5b 1664
58d081b5 1665 /*
fb13c7ee
MG
1666 * Pick the lowest SD_NUMA domain, as that would have the smallest
1667 * imbalance and would be the first to start moving tasks about.
1668 *
1669 * And we want to avoid any moving of tasks about, as that would create
1670 * random movement of tasks -- counter the numa conditions we're trying
1671 * to satisfy here.
58d081b5
MG
1672 */
1673 rcu_read_lock();
fb13c7ee 1674 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
46a73e8a
RR
1675 if (sd)
1676 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
e6628d5b
MG
1677 rcu_read_unlock();
1678
46a73e8a
RR
1679 /*
1680 * Cpusets can break the scheduler domain tree into smaller
1681 * balance domains, some of which do not cross NUMA boundaries.
1682 * Tasks that are "trapped" in such domains cannot be migrated
1683 * elsewhere, so there is no point in (re)trying.
1684 */
1685 if (unlikely(!sd)) {
de1b301a 1686 p->numa_preferred_nid = task_node(p);
46a73e8a
RR
1687 return -EINVAL;
1688 }
1689
2c8a50aa 1690 env.dst_nid = p->numa_preferred_nid;
7bd95320
RR
1691 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
1692 taskweight = task_weight(p, env.src_nid, dist);
1693 groupweight = group_weight(p, env.src_nid, dist);
1694 update_numa_stats(&env.src_stats, env.src_nid);
1695 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
1696 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2c8a50aa 1697 update_numa_stats(&env.dst_stats, env.dst_nid);
58d081b5 1698
a43455a1 1699 /* Try to find a spot on the preferred nid. */
6f9aad0b
RR
1700 if (numa_has_capacity(&env))
1701 task_numa_find_cpu(&env, taskimp, groupimp);
e1dda8a7 1702
9de05d48
RR
1703 /*
1704 * Look at other nodes in these cases:
1705 * - there is no space available on the preferred_nid
1706 * - the task is part of a numa_group that is interleaved across
1707 * multiple NUMA nodes; in order to better consolidate the group,
1708 * we need to check other locations.
1709 */
4142c3eb 1710 if (env.best_cpu == -1 || (p->numa_group && p->numa_group->active_nodes > 1)) {
2c8a50aa
MG
1711 for_each_online_node(nid) {
1712 if (nid == env.src_nid || nid == p->numa_preferred_nid)
1713 continue;
58d081b5 1714
7bd95320 1715 dist = node_distance(env.src_nid, env.dst_nid);
6c6b1193
RR
1716 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1717 dist != env.dist) {
1718 taskweight = task_weight(p, env.src_nid, dist);
1719 groupweight = group_weight(p, env.src_nid, dist);
1720 }
7bd95320 1721
83e1d2cd 1722 /* Only consider nodes where both task and groups benefit */
7bd95320
RR
1723 taskimp = task_weight(p, nid, dist) - taskweight;
1724 groupimp = group_weight(p, nid, dist) - groupweight;
887c290e 1725 if (taskimp < 0 && groupimp < 0)
fb13c7ee
MG
1726 continue;
1727
7bd95320 1728 env.dist = dist;
2c8a50aa
MG
1729 env.dst_nid = nid;
1730 update_numa_stats(&env.dst_stats, env.dst_nid);
6f9aad0b
RR
1731 if (numa_has_capacity(&env))
1732 task_numa_find_cpu(&env, taskimp, groupimp);
58d081b5
MG
1733 }
1734 }
1735
68d1b02a
RR
1736 /*
1737 * If the task is part of a workload that spans multiple NUMA nodes,
1738 * and is migrating into one of the workload's active nodes, remember
1739 * this node as the task's preferred numa node, so the workload can
1740 * settle down.
1741 * A task that migrated to a second choice node will be better off
1742 * trying for a better one later. Do not set the preferred node here.
1743 */
db015dae 1744 if (p->numa_group) {
4142c3eb
RR
1745 struct numa_group *ng = p->numa_group;
1746
db015dae
RR
1747 if (env.best_cpu == -1)
1748 nid = env.src_nid;
1749 else
1750 nid = env.dst_nid;
1751
4142c3eb 1752 if (ng->active_nodes > 1 && numa_is_active_node(env.dst_nid, ng))
db015dae
RR
1753 sched_setnuma(p, env.dst_nid);
1754 }
1755
1756 /* No better CPU than the current one was found. */
1757 if (env.best_cpu == -1)
1758 return -EAGAIN;
0ec8aa00 1759
04bb2f94
RR
1760 /*
1761 * Reset the scan period if the task is being rescheduled on an
1762 * alternative node to recheck if the tasks is now properly placed.
1763 */
1764 p->numa_scan_period = task_scan_min(p);
1765
fb13c7ee 1766 if (env.best_task == NULL) {
286549dc
MG
1767 ret = migrate_task_to(p, env.best_cpu);
1768 if (ret != 0)
1769 trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
fb13c7ee
MG
1770 return ret;
1771 }
1772
1773 ret = migrate_swap(p, env.best_task);
286549dc
MG
1774 if (ret != 0)
1775 trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
fb13c7ee
MG
1776 put_task_struct(env.best_task);
1777 return ret;
e6628d5b
MG
1778}
1779
6b9a7460
MG
1780/* Attempt to migrate a task to a CPU on the preferred node. */
1781static void numa_migrate_preferred(struct task_struct *p)
1782{
5085e2a3
RR
1783 unsigned long interval = HZ;
1784
2739d3ee 1785 /* This task has no NUMA fault statistics yet */
44dba3d5 1786 if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
6b9a7460
MG
1787 return;
1788
2739d3ee 1789 /* Periodically retry migrating the task to the preferred node */
5085e2a3
RR
1790 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
1791 p->numa_migrate_retry = jiffies + interval;
2739d3ee
RR
1792
1793 /* Success if task is already running on preferred CPU */
de1b301a 1794 if (task_node(p) == p->numa_preferred_nid)
6b9a7460
MG
1795 return;
1796
1797 /* Otherwise, try migrate to a CPU on the preferred node */
2739d3ee 1798 task_numa_migrate(p);
6b9a7460
MG
1799}
1800
20e07dea 1801/*
4142c3eb 1802 * Find out how many nodes on the workload is actively running on. Do this by
20e07dea
RR
1803 * tracking the nodes from which NUMA hinting faults are triggered. This can
1804 * be different from the set of nodes where the workload's memory is currently
1805 * located.
20e07dea 1806 */
4142c3eb 1807static void numa_group_count_active_nodes(struct numa_group *numa_group)
20e07dea
RR
1808{
1809 unsigned long faults, max_faults = 0;
4142c3eb 1810 int nid, active_nodes = 0;
20e07dea
RR
1811
1812 for_each_online_node(nid) {
1813 faults = group_faults_cpu(numa_group, nid);
1814 if (faults > max_faults)
1815 max_faults = faults;
1816 }
1817
1818 for_each_online_node(nid) {
1819 faults = group_faults_cpu(numa_group, nid);
4142c3eb
RR
1820 if (faults * ACTIVE_NODE_FRACTION > max_faults)
1821 active_nodes++;
20e07dea 1822 }
4142c3eb
RR
1823
1824 numa_group->max_faults_cpu = max_faults;
1825 numa_group->active_nodes = active_nodes;
20e07dea
RR
1826}
1827
04bb2f94
RR
1828/*
1829 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1830 * increments. The more local the fault statistics are, the higher the scan
a22b4b01
RR
1831 * period will be for the next scan window. If local/(local+remote) ratio is
1832 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
1833 * the scan period will decrease. Aim for 70% local accesses.
04bb2f94
RR
1834 */
1835#define NUMA_PERIOD_SLOTS 10
a22b4b01 1836#define NUMA_PERIOD_THRESHOLD 7
04bb2f94
RR
1837
1838/*
1839 * Increase the scan period (slow down scanning) if the majority of
1840 * our memory is already on our local node, or if the majority of
1841 * the page accesses are shared with other processes.
1842 * Otherwise, decrease the scan period.
1843 */
1844static void update_task_scan_period(struct task_struct *p,
1845 unsigned long shared, unsigned long private)
1846{
1847 unsigned int period_slot;
1848 int ratio;
1849 int diff;
1850
1851 unsigned long remote = p->numa_faults_locality[0];
1852 unsigned long local = p->numa_faults_locality[1];
1853
1854 /*
1855 * If there were no record hinting faults then either the task is
1856 * completely idle or all activity is areas that are not of interest
074c2381
MG
1857 * to automatic numa balancing. Related to that, if there were failed
1858 * migration then it implies we are migrating too quickly or the local
1859 * node is overloaded. In either case, scan slower
04bb2f94 1860 */
074c2381 1861 if (local + shared == 0 || p->numa_faults_locality[2]) {
04bb2f94
RR
1862 p->numa_scan_period = min(p->numa_scan_period_max,
1863 p->numa_scan_period << 1);
1864
1865 p->mm->numa_next_scan = jiffies +
1866 msecs_to_jiffies(p->numa_scan_period);
1867
1868 return;
1869 }
1870
1871 /*
1872 * Prepare to scale scan period relative to the current period.
1873 * == NUMA_PERIOD_THRESHOLD scan period stays the same
1874 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1875 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1876 */
1877 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
1878 ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
1879 if (ratio >= NUMA_PERIOD_THRESHOLD) {
1880 int slot = ratio - NUMA_PERIOD_THRESHOLD;
1881 if (!slot)
1882 slot = 1;
1883 diff = slot * period_slot;
1884 } else {
1885 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
1886
1887 /*
1888 * Scale scan rate increases based on sharing. There is an
1889 * inverse relationship between the degree of sharing and
1890 * the adjustment made to the scanning period. Broadly
1891 * speaking the intent is that there is little point
1892 * scanning faster if shared accesses dominate as it may
1893 * simply bounce migrations uselessly
1894 */
2847c90e 1895 ratio = DIV_ROUND_UP(private * NUMA_PERIOD_SLOTS, (private + shared + 1));
04bb2f94
RR
1896 diff = (diff * ratio) / NUMA_PERIOD_SLOTS;
1897 }
1898
1899 p->numa_scan_period = clamp(p->numa_scan_period + diff,
1900 task_scan_min(p), task_scan_max(p));
1901 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
1902}
1903
7e2703e6
RR
1904/*
1905 * Get the fraction of time the task has been running since the last
1906 * NUMA placement cycle. The scheduler keeps similar statistics, but
1907 * decays those on a 32ms period, which is orders of magnitude off
1908 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
1909 * stats only if the task is so new there are no NUMA statistics yet.
1910 */
1911static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
1912{
1913 u64 runtime, delta, now;
1914 /* Use the start of this time slice to avoid calculations. */
1915 now = p->se.exec_start;
1916 runtime = p->se.sum_exec_runtime;
1917
1918 if (p->last_task_numa_placement) {
1919 delta = runtime - p->last_sum_exec_runtime;
1920 *period = now - p->last_task_numa_placement;
1921 } else {
9d89c257
YD
1922 delta = p->se.avg.load_sum / p->se.load.weight;
1923 *period = LOAD_AVG_MAX;
7e2703e6
RR
1924 }
1925
1926 p->last_sum_exec_runtime = runtime;
1927 p->last_task_numa_placement = now;
1928
1929 return delta;
1930}
1931
54009416
RR
1932/*
1933 * Determine the preferred nid for a task in a numa_group. This needs to
1934 * be done in a way that produces consistent results with group_weight,
1935 * otherwise workloads might not converge.
1936 */
1937static int preferred_group_nid(struct task_struct *p, int nid)
1938{
1939 nodemask_t nodes;
1940 int dist;
1941
1942 /* Direct connections between all NUMA nodes. */
1943 if (sched_numa_topology_type == NUMA_DIRECT)
1944 return nid;
1945
1946 /*
1947 * On a system with glueless mesh NUMA topology, group_weight
1948 * scores nodes according to the number of NUMA hinting faults on
1949 * both the node itself, and on nearby nodes.
1950 */
1951 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1952 unsigned long score, max_score = 0;
1953 int node, max_node = nid;
1954
1955 dist = sched_max_numa_distance;
1956
1957 for_each_online_node(node) {
1958 score = group_weight(p, node, dist);
1959 if (score > max_score) {
1960 max_score = score;
1961 max_node = node;
1962 }
1963 }
1964 return max_node;
1965 }
1966
1967 /*
1968 * Finding the preferred nid in a system with NUMA backplane
1969 * interconnect topology is more involved. The goal is to locate
1970 * tasks from numa_groups near each other in the system, and
1971 * untangle workloads from different sides of the system. This requires
1972 * searching down the hierarchy of node groups, recursively searching
1973 * inside the highest scoring group of nodes. The nodemask tricks
1974 * keep the complexity of the search down.
1975 */
1976 nodes = node_online_map;
1977 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
1978 unsigned long max_faults = 0;
81907478 1979 nodemask_t max_group = NODE_MASK_NONE;
54009416
RR
1980 int a, b;
1981
1982 /* Are there nodes at this distance from each other? */
1983 if (!find_numa_distance(dist))
1984 continue;
1985
1986 for_each_node_mask(a, nodes) {
1987 unsigned long faults = 0;
1988 nodemask_t this_group;
1989 nodes_clear(this_group);
1990
1991 /* Sum group's NUMA faults; includes a==b case. */
1992 for_each_node_mask(b, nodes) {
1993 if (node_distance(a, b) < dist) {
1994 faults += group_faults(p, b);
1995 node_set(b, this_group);
1996 node_clear(b, nodes);
1997 }
1998 }
1999
2000 /* Remember the top group. */
2001 if (faults > max_faults) {
2002 max_faults = faults;
2003 max_group = this_group;
2004 /*
2005 * subtle: at the smallest distance there is
2006 * just one node left in each "group", the
2007 * winner is the preferred nid.
2008 */
2009 nid = a;
2010 }
2011 }
2012 /* Next round, evaluate the nodes within max_group. */
890a5409
JB
2013 if (!max_faults)
2014 break;
54009416
RR
2015 nodes = max_group;
2016 }
2017 return nid;
2018}
2019
cbee9f88
PZ
2020static void task_numa_placement(struct task_struct *p)
2021{
83e1d2cd
MG
2022 int seq, nid, max_nid = -1, max_group_nid = -1;
2023 unsigned long max_faults = 0, max_group_faults = 0;
04bb2f94 2024 unsigned long fault_types[2] = { 0, 0 };
7e2703e6
RR
2025 unsigned long total_faults;
2026 u64 runtime, period;
7dbd13ed 2027 spinlock_t *group_lock = NULL;
cbee9f88 2028
7e5a2c17
JL
2029 /*
2030 * The p->mm->numa_scan_seq field gets updated without
2031 * exclusive access. Use READ_ONCE() here to ensure
2032 * that the field is read in a single access:
2033 */
316c1608 2034 seq = READ_ONCE(p->mm->numa_scan_seq);
cbee9f88
PZ
2035 if (p->numa_scan_seq == seq)
2036 return;
2037 p->numa_scan_seq = seq;
598f0ec0 2038 p->numa_scan_period_max = task_scan_max(p);
cbee9f88 2039
7e2703e6
RR
2040 total_faults = p->numa_faults_locality[0] +
2041 p->numa_faults_locality[1];
2042 runtime = numa_get_avg_runtime(p, &period);
2043
7dbd13ed
MG
2044 /* If the task is part of a group prevent parallel updates to group stats */
2045 if (p->numa_group) {
2046 group_lock = &p->numa_group->lock;
60e69eed 2047 spin_lock_irq(group_lock);
7dbd13ed
MG
2048 }
2049
688b7585
MG
2050 /* Find the node with the highest number of faults */
2051 for_each_online_node(nid) {
44dba3d5
IM
2052 /* Keep track of the offsets in numa_faults array */
2053 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
83e1d2cd 2054 unsigned long faults = 0, group_faults = 0;
44dba3d5 2055 int priv;
745d6147 2056
be1e4e76 2057 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
7e2703e6 2058 long diff, f_diff, f_weight;
8c8a743c 2059
44dba3d5
IM
2060 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2061 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2062 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2063 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
745d6147 2064
ac8e895b 2065 /* Decay existing window, copy faults since last scan */
44dba3d5
IM
2066 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2067 fault_types[priv] += p->numa_faults[membuf_idx];
2068 p->numa_faults[membuf_idx] = 0;
fb13c7ee 2069
7e2703e6
RR
2070 /*
2071 * Normalize the faults_from, so all tasks in a group
2072 * count according to CPU use, instead of by the raw
2073 * number of faults. Tasks with little runtime have
2074 * little over-all impact on throughput, and thus their
2075 * faults are less important.
2076 */
2077 f_weight = div64_u64(runtime << 16, period + 1);
44dba3d5 2078 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
7e2703e6 2079 (total_faults + 1);
44dba3d5
IM
2080 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2081 p->numa_faults[cpubuf_idx] = 0;
50ec8a40 2082
44dba3d5
IM
2083 p->numa_faults[mem_idx] += diff;
2084 p->numa_faults[cpu_idx] += f_diff;
2085 faults += p->numa_faults[mem_idx];
83e1d2cd 2086 p->total_numa_faults += diff;
8c8a743c 2087 if (p->numa_group) {
44dba3d5
IM
2088 /*
2089 * safe because we can only change our own group
2090 *
2091 * mem_idx represents the offset for a given
2092 * nid and priv in a specific region because it
2093 * is at the beginning of the numa_faults array.
2094 */
2095 p->numa_group->faults[mem_idx] += diff;
2096 p->numa_group->faults_cpu[mem_idx] += f_diff;
989348b5 2097 p->numa_group->total_faults += diff;
44dba3d5 2098 group_faults += p->numa_group->faults[mem_idx];
8c8a743c 2099 }
ac8e895b
MG
2100 }
2101
688b7585
MG
2102 if (faults > max_faults) {
2103 max_faults = faults;
2104 max_nid = nid;
2105 }
83e1d2cd
MG
2106
2107 if (group_faults > max_group_faults) {
2108 max_group_faults = group_faults;
2109 max_group_nid = nid;
2110 }
2111 }
2112
04bb2f94
RR
2113 update_task_scan_period(p, fault_types[0], fault_types[1]);
2114
7dbd13ed 2115 if (p->numa_group) {
4142c3eb 2116 numa_group_count_active_nodes(p->numa_group);
60e69eed 2117 spin_unlock_irq(group_lock);
54009416 2118 max_nid = preferred_group_nid(p, max_group_nid);
688b7585
MG
2119 }
2120
bb97fc31
RR
2121 if (max_faults) {
2122 /* Set the new preferred node */
2123 if (max_nid != p->numa_preferred_nid)
2124 sched_setnuma(p, max_nid);
2125
2126 if (task_node(p) != p->numa_preferred_nid)
2127 numa_migrate_preferred(p);
3a7053b3 2128 }
cbee9f88
PZ
2129}
2130
8c8a743c
PZ
2131static inline int get_numa_group(struct numa_group *grp)
2132{
2133 return atomic_inc_not_zero(&grp->refcount);
2134}
2135
2136static inline void put_numa_group(struct numa_group *grp)
2137{
2138 if (atomic_dec_and_test(&grp->refcount))
2139 kfree_rcu(grp, rcu);
2140}
2141
3e6a9418
MG
2142static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2143 int *priv)
8c8a743c
PZ
2144{
2145 struct numa_group *grp, *my_grp;
2146 struct task_struct *tsk;
2147 bool join = false;
2148 int cpu = cpupid_to_cpu(cpupid);
2149 int i;
2150
2151 if (unlikely(!p->numa_group)) {
2152 unsigned int size = sizeof(struct numa_group) +
50ec8a40 2153 4*nr_node_ids*sizeof(unsigned long);
8c8a743c
PZ
2154
2155 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2156 if (!grp)
2157 return;
2158
2159 atomic_set(&grp->refcount, 1);
4142c3eb
RR
2160 grp->active_nodes = 1;
2161 grp->max_faults_cpu = 0;
8c8a743c 2162 spin_lock_init(&grp->lock);
e29cf08b 2163 grp->gid = p->pid;
50ec8a40 2164 /* Second half of the array tracks nids where faults happen */
be1e4e76
RR
2165 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
2166 nr_node_ids;
8c8a743c 2167
be1e4e76 2168 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
44dba3d5 2169 grp->faults[i] = p->numa_faults[i];
8c8a743c 2170
989348b5 2171 grp->total_faults = p->total_numa_faults;
83e1d2cd 2172
8c8a743c
PZ
2173 grp->nr_tasks++;
2174 rcu_assign_pointer(p->numa_group, grp);
2175 }
2176
2177 rcu_read_lock();
316c1608 2178 tsk = READ_ONCE(cpu_rq(cpu)->curr);
8c8a743c
PZ
2179
2180 if (!cpupid_match_pid(tsk, cpupid))
3354781a 2181 goto no_join;
8c8a743c
PZ
2182
2183 grp = rcu_dereference(tsk->numa_group);
2184 if (!grp)
3354781a 2185 goto no_join;
8c8a743c
PZ
2186
2187 my_grp = p->numa_group;
2188 if (grp == my_grp)
3354781a 2189 goto no_join;
8c8a743c
PZ
2190
2191 /*
2192 * Only join the other group if its bigger; if we're the bigger group,
2193 * the other task will join us.
2194 */
2195 if (my_grp->nr_tasks > grp->nr_tasks)
3354781a 2196 goto no_join;
8c8a743c
PZ
2197
2198 /*
2199 * Tie-break on the grp address.
2200 */
2201 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3354781a 2202 goto no_join;
8c8a743c 2203
dabe1d99
RR
2204 /* Always join threads in the same process. */
2205 if (tsk->mm == current->mm)
2206 join = true;
2207
2208 /* Simple filter to avoid false positives due to PID collisions */
2209 if (flags & TNF_SHARED)
2210 join = true;
8c8a743c 2211
3e6a9418
MG
2212 /* Update priv based on whether false sharing was detected */
2213 *priv = !join;
2214
dabe1d99 2215 if (join && !get_numa_group(grp))
3354781a 2216 goto no_join;
8c8a743c 2217
8c8a743c
PZ
2218 rcu_read_unlock();
2219
2220 if (!join)
2221 return;
2222
60e69eed
MG
2223 BUG_ON(irqs_disabled());
2224 double_lock_irq(&my_grp->lock, &grp->lock);
989348b5 2225
be1e4e76 2226 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
44dba3d5
IM
2227 my_grp->faults[i] -= p->numa_faults[i];
2228 grp->faults[i] += p->numa_faults[i];
8c8a743c 2229 }
989348b5
MG
2230 my_grp->total_faults -= p->total_numa_faults;
2231 grp->total_faults += p->total_numa_faults;
8c8a743c 2232
8c8a743c
PZ
2233 my_grp->nr_tasks--;
2234 grp->nr_tasks++;
2235
2236 spin_unlock(&my_grp->lock);
60e69eed 2237 spin_unlock_irq(&grp->lock);
8c8a743c
PZ
2238
2239 rcu_assign_pointer(p->numa_group, grp);
2240
2241 put_numa_group(my_grp);
3354781a
PZ
2242 return;
2243
2244no_join:
2245 rcu_read_unlock();
2246 return;
8c8a743c
PZ
2247}
2248
2249void task_numa_free(struct task_struct *p)
2250{
2251 struct numa_group *grp = p->numa_group;
44dba3d5 2252 void *numa_faults = p->numa_faults;
e9dd685c
SR
2253 unsigned long flags;
2254 int i;
8c8a743c
PZ
2255
2256 if (grp) {
e9dd685c 2257 spin_lock_irqsave(&grp->lock, flags);
be1e4e76 2258 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
44dba3d5 2259 grp->faults[i] -= p->numa_faults[i];
989348b5 2260 grp->total_faults -= p->total_numa_faults;
83e1d2cd 2261
8c8a743c 2262 grp->nr_tasks--;
e9dd685c 2263 spin_unlock_irqrestore(&grp->lock, flags);
35b123e2 2264 RCU_INIT_POINTER(p->numa_group, NULL);
8c8a743c
PZ
2265 put_numa_group(grp);
2266 }
2267
44dba3d5 2268 p->numa_faults = NULL;
82727018 2269 kfree(numa_faults);
8c8a743c
PZ
2270}
2271
cbee9f88
PZ
2272/*
2273 * Got a PROT_NONE fault for a page on @node.
2274 */
58b46da3 2275void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
cbee9f88
PZ
2276{
2277 struct task_struct *p = current;
6688cc05 2278 bool migrated = flags & TNF_MIGRATED;
58b46da3 2279 int cpu_node = task_node(current);
792568ec 2280 int local = !!(flags & TNF_FAULT_LOCAL);
4142c3eb 2281 struct numa_group *ng;
ac8e895b 2282 int priv;
cbee9f88 2283
2a595721 2284 if (!static_branch_likely(&sched_numa_balancing))
1a687c2e
MG
2285 return;
2286
9ff1d9ff
MG
2287 /* for example, ksmd faulting in a user's mm */
2288 if (!p->mm)
2289 return;
2290
f809ca9a 2291 /* Allocate buffer to track faults on a per-node basis */
44dba3d5
IM
2292 if (unlikely(!p->numa_faults)) {
2293 int size = sizeof(*p->numa_faults) *
be1e4e76 2294 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
f809ca9a 2295
44dba3d5
IM
2296 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
2297 if (!p->numa_faults)
f809ca9a 2298 return;
745d6147 2299
83e1d2cd 2300 p->total_numa_faults = 0;
04bb2f94 2301 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
f809ca9a 2302 }
cbee9f88 2303
8c8a743c
PZ
2304 /*
2305 * First accesses are treated as private, otherwise consider accesses
2306 * to be private if the accessing pid has not changed
2307 */
2308 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
2309 priv = 1;
2310 } else {
2311 priv = cpupid_match_pid(p, last_cpupid);
6688cc05 2312 if (!priv && !(flags & TNF_NO_GROUP))
3e6a9418 2313 task_numa_group(p, last_cpupid, flags, &priv);
8c8a743c
PZ
2314 }
2315
792568ec
RR
2316 /*
2317 * If a workload spans multiple NUMA nodes, a shared fault that
2318 * occurs wholly within the set of nodes that the workload is
2319 * actively using should be counted as local. This allows the
2320 * scan rate to slow down when a workload has settled down.
2321 */
4142c3eb
RR
2322 ng = p->numa_group;
2323 if (!priv && !local && ng && ng->active_nodes > 1 &&
2324 numa_is_active_node(cpu_node, ng) &&
2325 numa_is_active_node(mem_node, ng))
792568ec
RR
2326 local = 1;
2327
cbee9f88 2328 task_numa_placement(p);
f809ca9a 2329
2739d3ee
RR
2330 /*
2331 * Retry task to preferred node migration periodically, in case it
2332 * case it previously failed, or the scheduler moved us.
2333 */
2334 if (time_after(jiffies, p->numa_migrate_retry))
6b9a7460
MG
2335 numa_migrate_preferred(p);
2336
b32e86b4
IM
2337 if (migrated)
2338 p->numa_pages_migrated += pages;
074c2381
MG
2339 if (flags & TNF_MIGRATE_FAIL)
2340 p->numa_faults_locality[2] += pages;
b32e86b4 2341
44dba3d5
IM
2342 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
2343 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
792568ec 2344 p->numa_faults_locality[local] += pages;
cbee9f88
PZ
2345}
2346
6e5fb223
PZ
2347static void reset_ptenuma_scan(struct task_struct *p)
2348{
7e5a2c17
JL
2349 /*
2350 * We only did a read acquisition of the mmap sem, so
2351 * p->mm->numa_scan_seq is written to without exclusive access
2352 * and the update is not guaranteed to be atomic. That's not
2353 * much of an issue though, since this is just used for
2354 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2355 * expensive, to avoid any form of compiler optimizations:
2356 */
316c1608 2357 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
6e5fb223
PZ
2358 p->mm->numa_scan_offset = 0;
2359}
2360
cbee9f88
PZ
2361/*
2362 * The expensive part of numa migration is done from task_work context.
2363 * Triggered from task_tick_numa().
2364 */
2365void task_numa_work(struct callback_head *work)
2366{
2367 unsigned long migrate, next_scan, now = jiffies;
2368 struct task_struct *p = current;
2369 struct mm_struct *mm = p->mm;
51170840 2370 u64 runtime = p->se.sum_exec_runtime;
6e5fb223 2371 struct vm_area_struct *vma;
9f40604c 2372 unsigned long start, end;
598f0ec0 2373 unsigned long nr_pte_updates = 0;
4620f8c1 2374 long pages, virtpages;
cbee9f88 2375
9148a3a1 2376 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
cbee9f88
PZ
2377
2378 work->next = work; /* protect against double add */
2379 /*
2380 * Who cares about NUMA placement when they're dying.
2381 *
2382 * NOTE: make sure not to dereference p->mm before this check,
2383 * exit_task_work() happens _after_ exit_mm() so we could be called
2384 * without p->mm even though we still had it when we enqueued this
2385 * work.
2386 */
2387 if (p->flags & PF_EXITING)
2388 return;
2389
930aa174 2390 if (!mm->numa_next_scan) {
7e8d16b6
MG
2391 mm->numa_next_scan = now +
2392 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
b8593bfd
MG
2393 }
2394
cbee9f88
PZ
2395 /*
2396 * Enforce maximal scan/migration frequency..
2397 */
2398 migrate = mm->numa_next_scan;
2399 if (time_before(now, migrate))
2400 return;
2401
598f0ec0
MG
2402 if (p->numa_scan_period == 0) {
2403 p->numa_scan_period_max = task_scan_max(p);
2404 p->numa_scan_period = task_scan_min(p);
2405 }
cbee9f88 2406
fb003b80 2407 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
cbee9f88
PZ
2408 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
2409 return;
2410
19a78d11
PZ
2411 /*
2412 * Delay this task enough that another task of this mm will likely win
2413 * the next time around.
2414 */
2415 p->node_stamp += 2 * TICK_NSEC;
2416
9f40604c
MG
2417 start = mm->numa_scan_offset;
2418 pages = sysctl_numa_balancing_scan_size;
2419 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
4620f8c1 2420 virtpages = pages * 8; /* Scan up to this much virtual space */
9f40604c
MG
2421 if (!pages)
2422 return;
cbee9f88 2423
4620f8c1 2424
6e5fb223 2425 down_read(&mm->mmap_sem);
9f40604c 2426 vma = find_vma(mm, start);
6e5fb223
PZ
2427 if (!vma) {
2428 reset_ptenuma_scan(p);
9f40604c 2429 start = 0;
6e5fb223
PZ
2430 vma = mm->mmap;
2431 }
9f40604c 2432 for (; vma; vma = vma->vm_next) {
6b79c57b 2433 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
8e76d4ee 2434 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
6e5fb223 2435 continue;
6b79c57b 2436 }
6e5fb223 2437
4591ce4f
MG
2438 /*
2439 * Shared library pages mapped by multiple processes are not
2440 * migrated as it is expected they are cache replicated. Avoid
2441 * hinting faults in read-only file-backed mappings or the vdso
2442 * as migrating the pages will be of marginal benefit.
2443 */
2444 if (!vma->vm_mm ||
2445 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
2446 continue;
2447
3c67f474
MG
2448 /*
2449 * Skip inaccessible VMAs to avoid any confusion between
2450 * PROT_NONE and NUMA hinting ptes
2451 */
2452 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
2453 continue;
4591ce4f 2454
9f40604c
MG
2455 do {
2456 start = max(start, vma->vm_start);
2457 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
2458 end = min(end, vma->vm_end);
4620f8c1 2459 nr_pte_updates = change_prot_numa(vma, start, end);
598f0ec0
MG
2460
2461 /*
4620f8c1
RR
2462 * Try to scan sysctl_numa_balancing_size worth of
2463 * hpages that have at least one present PTE that
2464 * is not already pte-numa. If the VMA contains
2465 * areas that are unused or already full of prot_numa
2466 * PTEs, scan up to virtpages, to skip through those
2467 * areas faster.
598f0ec0
MG
2468 */
2469 if (nr_pte_updates)
2470 pages -= (end - start) >> PAGE_SHIFT;
4620f8c1 2471 virtpages -= (end - start) >> PAGE_SHIFT;
6e5fb223 2472
9f40604c 2473 start = end;
4620f8c1 2474 if (pages <= 0 || virtpages <= 0)
9f40604c 2475 goto out;
3cf1962c
RR
2476
2477 cond_resched();
9f40604c 2478 } while (end != vma->vm_end);
cbee9f88 2479 }
6e5fb223 2480
9f40604c 2481out:
6e5fb223 2482 /*
c69307d5
PZ
2483 * It is possible to reach the end of the VMA list but the last few
2484 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2485 * would find the !migratable VMA on the next scan but not reset the
2486 * scanner to the start so check it now.
6e5fb223
PZ
2487 */
2488 if (vma)
9f40604c 2489 mm->numa_scan_offset = start;
6e5fb223
PZ
2490 else
2491 reset_ptenuma_scan(p);
2492 up_read(&mm->mmap_sem);
51170840
RR
2493
2494 /*
2495 * Make sure tasks use at least 32x as much time to run other code
2496 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
2497 * Usually update_task_scan_period slows down scanning enough; on an
2498 * overloaded system we need to limit overhead on a per task basis.
2499 */
2500 if (unlikely(p->se.sum_exec_runtime != runtime)) {
2501 u64 diff = p->se.sum_exec_runtime - runtime;
2502 p->node_stamp += 32 * diff;
2503 }
cbee9f88
PZ
2504}
2505
2506/*
2507 * Drive the periodic memory faults..
2508 */
2509void task_tick_numa(struct rq *rq, struct task_struct *curr)
2510{
2511 struct callback_head *work = &curr->numa_work;
2512 u64 period, now;
2513
2514 /*
2515 * We don't care about NUMA placement if we don't have memory.
2516 */
2517 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
2518 return;
2519
2520 /*
2521 * Using runtime rather than walltime has the dual advantage that
2522 * we (mostly) drive the selection from busy threads and that the
2523 * task needs to have done some actual work before we bother with
2524 * NUMA placement.
2525 */
2526 now = curr->se.sum_exec_runtime;
2527 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
2528
25b3e5a3 2529 if (now > curr->node_stamp + period) {
4b96a29b 2530 if (!curr->node_stamp)
598f0ec0 2531 curr->numa_scan_period = task_scan_min(curr);
19a78d11 2532 curr->node_stamp += period;
cbee9f88
PZ
2533
2534 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
2535 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
2536 task_work_add(curr, work, true);
2537 }
2538 }
2539}
2540#else
2541static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2542{
2543}
0ec8aa00
PZ
2544
2545static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2546{
2547}
2548
2549static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2550{
2551}
cbee9f88
PZ
2552#endif /* CONFIG_NUMA_BALANCING */
2553
30cfdcfc
DA
2554static void
2555account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2556{
2557 update_load_add(&cfs_rq->load, se->load.weight);
c09595f6 2558 if (!parent_entity(se))
029632fb 2559 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
367456c7 2560#ifdef CONFIG_SMP
0ec8aa00
PZ
2561 if (entity_is_task(se)) {
2562 struct rq *rq = rq_of(cfs_rq);
2563
2564 account_numa_enqueue(rq, task_of(se));
2565 list_add(&se->group_node, &rq->cfs_tasks);
2566 }
367456c7 2567#endif
30cfdcfc 2568 cfs_rq->nr_running++;
30cfdcfc
DA
2569}
2570
2571static void
2572account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2573{
2574 update_load_sub(&cfs_rq->load, se->load.weight);
c09595f6 2575 if (!parent_entity(se))
029632fb 2576 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
bfdb198c 2577#ifdef CONFIG_SMP
0ec8aa00
PZ
2578 if (entity_is_task(se)) {
2579 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
b87f1724 2580 list_del_init(&se->group_node);
0ec8aa00 2581 }
bfdb198c 2582#endif
30cfdcfc 2583 cfs_rq->nr_running--;
30cfdcfc
DA
2584}
2585
3ff6dcac
YZ
2586#ifdef CONFIG_FAIR_GROUP_SCHED
2587# ifdef CONFIG_SMP
ea1dc6fc 2588static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
cf5f0acf 2589{
ea1dc6fc 2590 long tg_weight, load, shares;
cf5f0acf
PZ
2591
2592 /*
ea1dc6fc
PZ
2593 * This really should be: cfs_rq->avg.load_avg, but instead we use
2594 * cfs_rq->load.weight, which is its upper bound. This helps ramp up
2595 * the shares for small weight interactive tasks.
cf5f0acf 2596 */
ea1dc6fc 2597 load = scale_load_down(cfs_rq->load.weight);
cf5f0acf 2598
ea1dc6fc 2599 tg_weight = atomic_long_read(&tg->load_avg);
3ff6dcac 2600
ea1dc6fc
PZ
2601 /* Ensure tg_weight >= load */
2602 tg_weight -= cfs_rq->tg_load_avg_contrib;
2603 tg_weight += load;
3ff6dcac 2604
3ff6dcac 2605 shares = (tg->shares * load);
cf5f0acf
PZ
2606 if (tg_weight)
2607 shares /= tg_weight;
3ff6dcac
YZ
2608
2609 if (shares < MIN_SHARES)
2610 shares = MIN_SHARES;
2611 if (shares > tg->shares)
2612 shares = tg->shares;
2613
2614 return shares;
2615}
3ff6dcac 2616# else /* CONFIG_SMP */
6d5ab293 2617static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
3ff6dcac
YZ
2618{
2619 return tg->shares;
2620}
3ff6dcac 2621# endif /* CONFIG_SMP */
ea1dc6fc 2622
2069dd75
PZ
2623static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
2624 unsigned long weight)
2625{
19e5eebb
PT
2626 if (se->on_rq) {
2627 /* commit outstanding execution time */
2628 if (cfs_rq->curr == se)
2629 update_curr(cfs_rq);
2069dd75 2630 account_entity_dequeue(cfs_rq, se);
19e5eebb 2631 }
2069dd75
PZ
2632
2633 update_load_set(&se->load, weight);
2634
2635 if (se->on_rq)
2636 account_entity_enqueue(cfs_rq, se);
2637}
2638
82958366
PT
2639static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
2640
6d5ab293 2641static void update_cfs_shares(struct cfs_rq *cfs_rq)
2069dd75
PZ
2642{
2643 struct task_group *tg;
2644 struct sched_entity *se;
3ff6dcac 2645 long shares;
2069dd75 2646
2069dd75
PZ
2647 tg = cfs_rq->tg;
2648 se = tg->se[cpu_of(rq_of(cfs_rq))];
64660c86 2649 if (!se || throttled_hierarchy(cfs_rq))
2069dd75 2650 return;
3ff6dcac
YZ
2651#ifndef CONFIG_SMP
2652 if (likely(se->load.weight == tg->shares))
2653 return;
2654#endif
6d5ab293 2655 shares = calc_cfs_shares(cfs_rq, tg);
2069dd75
PZ
2656
2657 reweight_entity(cfs_rq_of(se), se, shares);
2658}
2659#else /* CONFIG_FAIR_GROUP_SCHED */
6d5ab293 2660static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
2069dd75
PZ
2661{
2662}
2663#endif /* CONFIG_FAIR_GROUP_SCHED */
2664
141965c7 2665#ifdef CONFIG_SMP
5b51f2f8
PT
2666/* Precomputed fixed inverse multiplies for multiplication by y^n */
2667static const u32 runnable_avg_yN_inv[] = {
2668 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
2669 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
2670 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
2671 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
2672 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
2673 0x85aac367, 0x82cd8698,
2674};
2675
2676/*
2677 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
2678 * over-estimates when re-combining.
2679 */
2680static const u32 runnable_avg_yN_sum[] = {
2681 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
2682 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
2683 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
2684};
2685
7b20b916
YD
2686/*
2687 * Precomputed \Sum y^k { 1<=k<=n, where n%32=0). Values are rolled down to
2688 * lower integers. See Documentation/scheduler/sched-avg.txt how these
2689 * were generated:
2690 */
2691static const u32 __accumulated_sum_N32[] = {
2692 0, 23371, 35056, 40899, 43820, 45281,
2693 46011, 46376, 46559, 46650, 46696, 46719,
2694};
2695
9d85f21c
PT
2696/*
2697 * Approximate:
2698 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2699 */
2700static __always_inline u64 decay_load(u64 val, u64 n)
2701{
5b51f2f8
PT
2702 unsigned int local_n;
2703
2704 if (!n)
2705 return val;
2706 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
2707 return 0;
2708
2709 /* after bounds checking we can collapse to 32-bit */
2710 local_n = n;
2711
2712 /*
2713 * As y^PERIOD = 1/2, we can combine
9c58c79a
ZZ
2714 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
2715 * With a look-up table which covers y^n (n<PERIOD)
5b51f2f8
PT
2716 *
2717 * To achieve constant time decay_load.
2718 */
2719 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
2720 val >>= local_n / LOAD_AVG_PERIOD;
2721 local_n %= LOAD_AVG_PERIOD;
9d85f21c
PT
2722 }
2723
9d89c257
YD
2724 val = mul_u64_u32_shr(val, runnable_avg_yN_inv[local_n], 32);
2725 return val;
5b51f2f8
PT
2726}
2727
2728/*
2729 * For updates fully spanning n periods, the contribution to runnable
2730 * average will be: \Sum 1024*y^n
2731 *
2732 * We can compute this reasonably efficiently by combining:
2733 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
2734 */
2735static u32 __compute_runnable_contrib(u64 n)
2736{
2737 u32 contrib = 0;
2738
2739 if (likely(n <= LOAD_AVG_PERIOD))
2740 return runnable_avg_yN_sum[n];
2741 else if (unlikely(n >= LOAD_AVG_MAX_N))
2742 return LOAD_AVG_MAX;
2743
7b20b916
YD
2744 /* Since n < LOAD_AVG_MAX_N, n/LOAD_AVG_PERIOD < 11 */
2745 contrib = __accumulated_sum_N32[n/LOAD_AVG_PERIOD];
2746 n %= LOAD_AVG_PERIOD;
5b51f2f8
PT
2747 contrib = decay_load(contrib, n);
2748 return contrib + runnable_avg_yN_sum[n];
9d85f21c
PT
2749}
2750
54a21385 2751#define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)
e0f5f3af 2752
9d85f21c
PT
2753/*
2754 * We can represent the historical contribution to runnable average as the
2755 * coefficients of a geometric series. To do this we sub-divide our runnable
2756 * history into segments of approximately 1ms (1024us); label the segment that
2757 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2758 *
2759 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2760 * p0 p1 p2
2761 * (now) (~1ms ago) (~2ms ago)
2762 *
2763 * Let u_i denote the fraction of p_i that the entity was runnable.
2764 *
2765 * We then designate the fractions u_i as our co-efficients, yielding the
2766 * following representation of historical load:
2767 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2768 *
2769 * We choose y based on the with of a reasonably scheduling period, fixing:
2770 * y^32 = 0.5
2771 *
2772 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2773 * approximately half as much as the contribution to load within the last ms
2774 * (u_0).
2775 *
2776 * When a period "rolls over" and we have new u_0`, multiplying the previous
2777 * sum again by y is sufficient to update:
2778 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2779 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2780 */
9d89c257
YD
2781static __always_inline int
2782__update_load_avg(u64 now, int cpu, struct sched_avg *sa,
13962234 2783 unsigned long weight, int running, struct cfs_rq *cfs_rq)
9d85f21c 2784{
e0f5f3af 2785 u64 delta, scaled_delta, periods;
9d89c257 2786 u32 contrib;
6115c793 2787 unsigned int delta_w, scaled_delta_w, decayed = 0;
6f2b0452 2788 unsigned long scale_freq, scale_cpu;
9d85f21c 2789
9d89c257 2790 delta = now - sa->last_update_time;
9d85f21c
PT
2791 /*
2792 * This should only happen when time goes backwards, which it
2793 * unfortunately does during sched clock init when we swap over to TSC.
2794 */
2795 if ((s64)delta < 0) {
9d89c257 2796 sa->last_update_time = now;
9d85f21c
PT
2797 return 0;
2798 }
2799
2800 /*
2801 * Use 1024ns as the unit of measurement since it's a reasonable
2802 * approximation of 1us and fast to compute.
2803 */
2804 delta >>= 10;
2805 if (!delta)
2806 return 0;
9d89c257 2807 sa->last_update_time = now;
9d85f21c 2808
6f2b0452
DE
2809 scale_freq = arch_scale_freq_capacity(NULL, cpu);
2810 scale_cpu = arch_scale_cpu_capacity(NULL, cpu);
2811
9d85f21c 2812 /* delta_w is the amount already accumulated against our next period */
9d89c257 2813 delta_w = sa->period_contrib;
9d85f21c 2814 if (delta + delta_w >= 1024) {
9d85f21c
PT
2815 decayed = 1;
2816
9d89c257
YD
2817 /* how much left for next period will start over, we don't know yet */
2818 sa->period_contrib = 0;
2819
9d85f21c
PT
2820 /*
2821 * Now that we know we're crossing a period boundary, figure
2822 * out how much from delta we need to complete the current
2823 * period and accrue it.
2824 */
2825 delta_w = 1024 - delta_w;
54a21385 2826 scaled_delta_w = cap_scale(delta_w, scale_freq);
13962234 2827 if (weight) {
e0f5f3af
DE
2828 sa->load_sum += weight * scaled_delta_w;
2829 if (cfs_rq) {
2830 cfs_rq->runnable_load_sum +=
2831 weight * scaled_delta_w;
2832 }
13962234 2833 }
36ee28e4 2834 if (running)
006cdf02 2835 sa->util_sum += scaled_delta_w * scale_cpu;
5b51f2f8
PT
2836
2837 delta -= delta_w;
2838
2839 /* Figure out how many additional periods this update spans */
2840 periods = delta / 1024;
2841 delta %= 1024;
2842
9d89c257 2843 sa->load_sum = decay_load(sa->load_sum, periods + 1);
13962234
YD
2844 if (cfs_rq) {
2845 cfs_rq->runnable_load_sum =
2846 decay_load(cfs_rq->runnable_load_sum, periods + 1);
2847 }
9d89c257 2848 sa->util_sum = decay_load((u64)(sa->util_sum), periods + 1);
5b51f2f8
PT
2849
2850 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
9d89c257 2851 contrib = __compute_runnable_contrib(periods);
54a21385 2852 contrib = cap_scale(contrib, scale_freq);
13962234 2853 if (weight) {
9d89c257 2854 sa->load_sum += weight * contrib;
13962234
YD
2855 if (cfs_rq)
2856 cfs_rq->runnable_load_sum += weight * contrib;
2857 }
36ee28e4 2858 if (running)
006cdf02 2859 sa->util_sum += contrib * scale_cpu;
9d85f21c
PT
2860 }
2861
2862 /* Remainder of delta accrued against u_0` */
54a21385 2863 scaled_delta = cap_scale(delta, scale_freq);
13962234 2864 if (weight) {
e0f5f3af 2865 sa->load_sum += weight * scaled_delta;
13962234 2866 if (cfs_rq)
e0f5f3af 2867 cfs_rq->runnable_load_sum += weight * scaled_delta;
13962234 2868 }
36ee28e4 2869 if (running)
006cdf02 2870 sa->util_sum += scaled_delta * scale_cpu;
9ee474f5 2871
9d89c257 2872 sa->period_contrib += delta;
9ee474f5 2873
9d89c257
YD
2874 if (decayed) {
2875 sa->load_avg = div_u64(sa->load_sum, LOAD_AVG_MAX);
13962234
YD
2876 if (cfs_rq) {
2877 cfs_rq->runnable_load_avg =
2878 div_u64(cfs_rq->runnable_load_sum, LOAD_AVG_MAX);
2879 }
006cdf02 2880 sa->util_avg = sa->util_sum / LOAD_AVG_MAX;
9d89c257 2881 }
aff3e498 2882
9d89c257 2883 return decayed;
9ee474f5
PT
2884}
2885
c566e8e9 2886#ifdef CONFIG_FAIR_GROUP_SCHED
7c3edd2c
PZ
2887/**
2888 * update_tg_load_avg - update the tg's load avg
2889 * @cfs_rq: the cfs_rq whose avg changed
2890 * @force: update regardless of how small the difference
2891 *
2892 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
2893 * However, because tg->load_avg is a global value there are performance
2894 * considerations.
2895 *
2896 * In order to avoid having to look at the other cfs_rq's, we use a
2897 * differential update where we store the last value we propagated. This in
2898 * turn allows skipping updates if the differential is 'small'.
2899 *
2900 * Updating tg's load_avg is necessary before update_cfs_share() (which is
2901 * done) and effective_load() (which is not done because it is too costly).
bb17f655 2902 */
9d89c257 2903static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
bb17f655 2904{
9d89c257 2905 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
bb17f655 2906
aa0b7ae0
WL
2907 /*
2908 * No need to update load_avg for root_task_group as it is not used.
2909 */
2910 if (cfs_rq->tg == &root_task_group)
2911 return;
2912
9d89c257
YD
2913 if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
2914 atomic_long_add(delta, &cfs_rq->tg->load_avg);
2915 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
bb17f655 2916 }
8165e145 2917}
f5f9739d 2918
ad936d86
BP
2919/*
2920 * Called within set_task_rq() right before setting a task's cpu. The
2921 * caller only guarantees p->pi_lock is held; no other assumptions,
2922 * including the state of rq->lock, should be made.
2923 */
2924void set_task_rq_fair(struct sched_entity *se,
2925 struct cfs_rq *prev, struct cfs_rq *next)
2926{
2927 if (!sched_feat(ATTACH_AGE_LOAD))
2928 return;
2929
2930 /*
2931 * We are supposed to update the task to "current" time, then its up to
2932 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
2933 * getting what current time is, so simply throw away the out-of-date
2934 * time. This will result in the wakee task is less decayed, but giving
2935 * the wakee more load sounds not bad.
2936 */
2937 if (se->avg.last_update_time && prev) {
2938 u64 p_last_update_time;
2939 u64 n_last_update_time;
2940
2941#ifndef CONFIG_64BIT
2942 u64 p_last_update_time_copy;
2943 u64 n_last_update_time_copy;
2944
2945 do {
2946 p_last_update_time_copy = prev->load_last_update_time_copy;
2947 n_last_update_time_copy = next->load_last_update_time_copy;
2948
2949 smp_rmb();
2950
2951 p_last_update_time = prev->avg.last_update_time;
2952 n_last_update_time = next->avg.last_update_time;
2953
2954 } while (p_last_update_time != p_last_update_time_copy ||
2955 n_last_update_time != n_last_update_time_copy);
2956#else
2957 p_last_update_time = prev->avg.last_update_time;
2958 n_last_update_time = next->avg.last_update_time;
2959#endif
2960 __update_load_avg(p_last_update_time, cpu_of(rq_of(prev)),
2961 &se->avg, 0, 0, NULL);
2962 se->avg.last_update_time = n_last_update_time;
2963 }
2964}
6e83125c 2965#else /* CONFIG_FAIR_GROUP_SCHED */
9d89c257 2966static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
6e83125c 2967#endif /* CONFIG_FAIR_GROUP_SCHED */
c566e8e9 2968
a2c6c91f
SM
2969static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq)
2970{
58919e83 2971 if (&this_rq()->cfs == cfs_rq) {
a2c6c91f
SM
2972 /*
2973 * There are a few boundary cases this might miss but it should
2974 * get called often enough that that should (hopefully) not be
2975 * a real problem -- added to that it only calls on the local
2976 * CPU, so if we enqueue remotely we'll miss an update, but
2977 * the next tick/schedule should update.
2978 *
2979 * It will not get called when we go idle, because the idle
2980 * thread is a different class (!fair), nor will the utilization
2981 * number include things like RT tasks.
2982 *
2983 * As is, the util number is not freq-invariant (we'd have to
2984 * implement arch_scale_freq_capacity() for that).
2985 *
2986 * See cpu_util().
2987 */
12bde33d 2988 cpufreq_update_util(rq_of(cfs_rq), 0);
a2c6c91f
SM
2989 }
2990}
2991
89741892
PZ
2992/*
2993 * Unsigned subtract and clamp on underflow.
2994 *
2995 * Explicitly do a load-store to ensure the intermediate value never hits
2996 * memory. This allows lockless observations without ever seeing the negative
2997 * values.
2998 */
2999#define sub_positive(_ptr, _val) do { \
3000 typeof(_ptr) ptr = (_ptr); \
3001 typeof(*ptr) val = (_val); \
3002 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3003 res = var - val; \
3004 if (res > var) \
3005 res = 0; \
3006 WRITE_ONCE(*ptr, res); \
3007} while (0)
3008
3d30544f
PZ
3009/**
3010 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3011 * @now: current time, as per cfs_rq_clock_task()
3012 * @cfs_rq: cfs_rq to update
3013 * @update_freq: should we call cfs_rq_util_change() or will the call do so
3014 *
3015 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3016 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3017 * post_init_entity_util_avg().
3018 *
3019 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3020 *
7c3edd2c
PZ
3021 * Returns true if the load decayed or we removed load.
3022 *
3023 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3024 * call update_tg_load_avg() when this function returns true.
3d30544f 3025 */
a2c6c91f
SM
3026static inline int
3027update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
2dac754e 3028{
9d89c257 3029 struct sched_avg *sa = &cfs_rq->avg;
41e0d37f 3030 int decayed, removed_load = 0, removed_util = 0;
2dac754e 3031
9d89c257 3032 if (atomic_long_read(&cfs_rq->removed_load_avg)) {
9e0e83a1 3033 s64 r = atomic_long_xchg(&cfs_rq->removed_load_avg, 0);
89741892
PZ
3034 sub_positive(&sa->load_avg, r);
3035 sub_positive(&sa->load_sum, r * LOAD_AVG_MAX);
41e0d37f 3036 removed_load = 1;
8165e145 3037 }
2dac754e 3038
9d89c257
YD
3039 if (atomic_long_read(&cfs_rq->removed_util_avg)) {
3040 long r = atomic_long_xchg(&cfs_rq->removed_util_avg, 0);
89741892
PZ
3041 sub_positive(&sa->util_avg, r);
3042 sub_positive(&sa->util_sum, r * LOAD_AVG_MAX);
41e0d37f 3043 removed_util = 1;
9d89c257 3044 }
36ee28e4 3045
a2c6c91f 3046 decayed = __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
13962234 3047 scale_load_down(cfs_rq->load.weight), cfs_rq->curr != NULL, cfs_rq);
36ee28e4 3048
9d89c257
YD
3049#ifndef CONFIG_64BIT
3050 smp_wmb();
3051 cfs_rq->load_last_update_time_copy = sa->last_update_time;
3052#endif
36ee28e4 3053
a2c6c91f
SM
3054 if (update_freq && (decayed || removed_util))
3055 cfs_rq_util_change(cfs_rq);
21e96f88 3056
41e0d37f 3057 return decayed || removed_load;
21e96f88
SM
3058}
3059
3060/* Update task and its cfs_rq load average */
3061static inline void update_load_avg(struct sched_entity *se, int update_tg)
3062{
3063 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3064 u64 now = cfs_rq_clock_task(cfs_rq);
3065 struct rq *rq = rq_of(cfs_rq);
3066 int cpu = cpu_of(rq);
3067
3068 /*
3069 * Track task load average for carrying it to new CPU after migrated, and
3070 * track group sched_entity load average for task_h_load calc in migration
3071 */
3072 __update_load_avg(now, cpu, &se->avg,
3073 se->on_rq * scale_load_down(se->load.weight),
3074 cfs_rq->curr == se, NULL);
3075
a2c6c91f 3076 if (update_cfs_rq_load_avg(now, cfs_rq, true) && update_tg)
21e96f88 3077 update_tg_load_avg(cfs_rq, 0);
9ee474f5
PT
3078}
3079
3d30544f
PZ
3080/**
3081 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3082 * @cfs_rq: cfs_rq to attach to
3083 * @se: sched_entity to attach
3084 *
3085 * Must call update_cfs_rq_load_avg() before this, since we rely on
3086 * cfs_rq->avg.last_update_time being current.
3087 */
a05e8c51
BP
3088static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3089{
a9280514
PZ
3090 if (!sched_feat(ATTACH_AGE_LOAD))
3091 goto skip_aging;
3092
6efdb105
BP
3093 /*
3094 * If we got migrated (either between CPUs or between cgroups) we'll
3095 * have aged the average right before clearing @last_update_time.
7dc603c9
PZ
3096 *
3097 * Or we're fresh through post_init_entity_util_avg().
6efdb105
BP
3098 */
3099 if (se->avg.last_update_time) {
3100 __update_load_avg(cfs_rq->avg.last_update_time, cpu_of(rq_of(cfs_rq)),
3101 &se->avg, 0, 0, NULL);
3102
3103 /*
3104 * XXX: we could have just aged the entire load away if we've been
3105 * absent from the fair class for too long.
3106 */
3107 }
3108
a9280514 3109skip_aging:
a05e8c51
BP
3110 se->avg.last_update_time = cfs_rq->avg.last_update_time;
3111 cfs_rq->avg.load_avg += se->avg.load_avg;
3112 cfs_rq->avg.load_sum += se->avg.load_sum;
3113 cfs_rq->avg.util_avg += se->avg.util_avg;
3114 cfs_rq->avg.util_sum += se->avg.util_sum;
a2c6c91f
SM
3115
3116 cfs_rq_util_change(cfs_rq);
a05e8c51
BP
3117}
3118
3d30544f
PZ
3119/**
3120 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3121 * @cfs_rq: cfs_rq to detach from
3122 * @se: sched_entity to detach
3123 *
3124 * Must call update_cfs_rq_load_avg() before this, since we rely on
3125 * cfs_rq->avg.last_update_time being current.
3126 */
a05e8c51
BP
3127static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3128{
3129 __update_load_avg(cfs_rq->avg.last_update_time, cpu_of(rq_of(cfs_rq)),
3130 &se->avg, se->on_rq * scale_load_down(se->load.weight),
3131 cfs_rq->curr == se, NULL);
3132
89741892
PZ
3133 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3134 sub_positive(&cfs_rq->avg.load_sum, se->avg.load_sum);
3135 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
3136 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
a2c6c91f
SM
3137
3138 cfs_rq_util_change(cfs_rq);
a05e8c51
BP
3139}
3140
9d89c257
YD
3141/* Add the load generated by se into cfs_rq's load average */
3142static inline void
3143enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
9ee474f5 3144{
9d89c257
YD
3145 struct sched_avg *sa = &se->avg;
3146 u64 now = cfs_rq_clock_task(cfs_rq);
a05e8c51 3147 int migrated, decayed;
9ee474f5 3148
a05e8c51
BP
3149 migrated = !sa->last_update_time;
3150 if (!migrated) {
9d89c257 3151 __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
13962234
YD
3152 se->on_rq * scale_load_down(se->load.weight),
3153 cfs_rq->curr == se, NULL);
aff3e498 3154 }
c566e8e9 3155
a2c6c91f 3156 decayed = update_cfs_rq_load_avg(now, cfs_rq, !migrated);
18bf2805 3157
13962234
YD
3158 cfs_rq->runnable_load_avg += sa->load_avg;
3159 cfs_rq->runnable_load_sum += sa->load_sum;
3160
a05e8c51
BP
3161 if (migrated)
3162 attach_entity_load_avg(cfs_rq, se);
9ee474f5 3163
9d89c257
YD
3164 if (decayed || migrated)
3165 update_tg_load_avg(cfs_rq, 0);
2dac754e
PT
3166}
3167
13962234
YD
3168/* Remove the runnable load generated by se from cfs_rq's runnable load average */
3169static inline void
3170dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3171{
3172 update_load_avg(se, 1);
3173
3174 cfs_rq->runnable_load_avg =
3175 max_t(long, cfs_rq->runnable_load_avg - se->avg.load_avg, 0);
3176 cfs_rq->runnable_load_sum =
a05e8c51 3177 max_t(s64, cfs_rq->runnable_load_sum - se->avg.load_sum, 0);
13962234
YD
3178}
3179
9d89c257 3180#ifndef CONFIG_64BIT
0905f04e
YD
3181static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3182{
9d89c257 3183 u64 last_update_time_copy;
0905f04e 3184 u64 last_update_time;
9ee474f5 3185
9d89c257
YD
3186 do {
3187 last_update_time_copy = cfs_rq->load_last_update_time_copy;
3188 smp_rmb();
3189 last_update_time = cfs_rq->avg.last_update_time;
3190 } while (last_update_time != last_update_time_copy);
0905f04e
YD
3191
3192 return last_update_time;
3193}
9d89c257 3194#else
0905f04e
YD
3195static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3196{
3197 return cfs_rq->avg.last_update_time;
3198}
9d89c257
YD
3199#endif
3200
104cb16d
MR
3201/*
3202 * Synchronize entity load avg of dequeued entity without locking
3203 * the previous rq.
3204 */
3205void sync_entity_load_avg(struct sched_entity *se)
3206{
3207 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3208 u64 last_update_time;
3209
3210 last_update_time = cfs_rq_last_update_time(cfs_rq);
3211 __update_load_avg(last_update_time, cpu_of(rq_of(cfs_rq)), &se->avg, 0, 0, NULL);
3212}
3213
0905f04e
YD
3214/*
3215 * Task first catches up with cfs_rq, and then subtract
3216 * itself from the cfs_rq (task must be off the queue now).
3217 */
3218void remove_entity_load_avg(struct sched_entity *se)
3219{
3220 struct cfs_rq *cfs_rq = cfs_rq_of(se);
0905f04e
YD
3221
3222 /*
7dc603c9
PZ
3223 * tasks cannot exit without having gone through wake_up_new_task() ->
3224 * post_init_entity_util_avg() which will have added things to the
3225 * cfs_rq, so we can remove unconditionally.
3226 *
3227 * Similarly for groups, they will have passed through
3228 * post_init_entity_util_avg() before unregister_sched_fair_group()
3229 * calls this.
0905f04e 3230 */
0905f04e 3231
104cb16d 3232 sync_entity_load_avg(se);
9d89c257
YD
3233 atomic_long_add(se->avg.load_avg, &cfs_rq->removed_load_avg);
3234 atomic_long_add(se->avg.util_avg, &cfs_rq->removed_util_avg);
2dac754e 3235}
642dbc39 3236
7ea241af
YD
3237static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
3238{
3239 return cfs_rq->runnable_load_avg;
3240}
3241
3242static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3243{
3244 return cfs_rq->avg.load_avg;
3245}
3246
6e83125c
PZ
3247static int idle_balance(struct rq *this_rq);
3248
38033c37
PZ
3249#else /* CONFIG_SMP */
3250
01011473
PZ
3251static inline int
3252update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
3253{
3254 return 0;
3255}
3256
536bd00c
RW
3257static inline void update_load_avg(struct sched_entity *se, int not_used)
3258{
12bde33d 3259 cpufreq_update_util(rq_of(cfs_rq_of(se)), 0);
536bd00c
RW
3260}
3261
9d89c257
YD
3262static inline void
3263enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
13962234
YD
3264static inline void
3265dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
9d89c257 3266static inline void remove_entity_load_avg(struct sched_entity *se) {}
6e83125c 3267
a05e8c51
BP
3268static inline void
3269attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3270static inline void
3271detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3272
6e83125c
PZ
3273static inline int idle_balance(struct rq *rq)
3274{
3275 return 0;
3276}
3277
38033c37 3278#endif /* CONFIG_SMP */
9d85f21c 3279
ddc97297
PZ
3280static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
3281{
3282#ifdef CONFIG_SCHED_DEBUG
3283 s64 d = se->vruntime - cfs_rq->min_vruntime;
3284
3285 if (d < 0)
3286 d = -d;
3287
3288 if (d > 3*sysctl_sched_latency)
ae92882e 3289 schedstat_inc(cfs_rq->nr_spread_over);
ddc97297
PZ
3290#endif
3291}
3292
aeb73b04
PZ
3293static void
3294place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
3295{
1af5f730 3296 u64 vruntime = cfs_rq->min_vruntime;
94dfb5e7 3297
2cb8600e
PZ
3298 /*
3299 * The 'current' period is already promised to the current tasks,
3300 * however the extra weight of the new task will slow them down a
3301 * little, place the new task so that it fits in the slot that
3302 * stays open at the end.
3303 */
94dfb5e7 3304 if (initial && sched_feat(START_DEBIT))
f9c0b095 3305 vruntime += sched_vslice(cfs_rq, se);
aeb73b04 3306
a2e7a7eb 3307 /* sleeps up to a single latency don't count. */
5ca9880c 3308 if (!initial) {
a2e7a7eb 3309 unsigned long thresh = sysctl_sched_latency;
a7be37ac 3310
a2e7a7eb
MG
3311 /*
3312 * Halve their sleep time's effect, to allow
3313 * for a gentler effect of sleepers:
3314 */
3315 if (sched_feat(GENTLE_FAIR_SLEEPERS))
3316 thresh >>= 1;
51e0304c 3317
a2e7a7eb 3318 vruntime -= thresh;
aeb73b04
PZ
3319 }
3320
b5d9d734 3321 /* ensure we never gain time by being placed backwards. */
16c8f1c7 3322 se->vruntime = max_vruntime(se->vruntime, vruntime);
aeb73b04
PZ
3323}
3324
d3d9dc33
PT
3325static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
3326
cb251765
MG
3327static inline void check_schedstat_required(void)
3328{
3329#ifdef CONFIG_SCHEDSTATS
3330 if (schedstat_enabled())
3331 return;
3332
3333 /* Force schedstat enabled if a dependent tracepoint is active */
3334 if (trace_sched_stat_wait_enabled() ||
3335 trace_sched_stat_sleep_enabled() ||
3336 trace_sched_stat_iowait_enabled() ||
3337 trace_sched_stat_blocked_enabled() ||
3338 trace_sched_stat_runtime_enabled()) {
eda8dca5 3339 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
cb251765
MG
3340 "stat_blocked and stat_runtime require the "
3341 "kernel parameter schedstats=enabled or "
3342 "kernel.sched_schedstats=1\n");
3343 }
3344#endif
3345}
3346
b5179ac7
PZ
3347
3348/*
3349 * MIGRATION
3350 *
3351 * dequeue
3352 * update_curr()
3353 * update_min_vruntime()
3354 * vruntime -= min_vruntime
3355 *
3356 * enqueue
3357 * update_curr()
3358 * update_min_vruntime()
3359 * vruntime += min_vruntime
3360 *
3361 * this way the vruntime transition between RQs is done when both
3362 * min_vruntime are up-to-date.
3363 *
3364 * WAKEUP (remote)
3365 *
59efa0ba 3366 * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
b5179ac7
PZ
3367 * vruntime -= min_vruntime
3368 *
3369 * enqueue
3370 * update_curr()
3371 * update_min_vruntime()
3372 * vruntime += min_vruntime
3373 *
3374 * this way we don't have the most up-to-date min_vruntime on the originating
3375 * CPU and an up-to-date min_vruntime on the destination CPU.
3376 */
3377
bf0f6f24 3378static void
88ec22d3 3379enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 3380{
2f950354
PZ
3381 bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
3382 bool curr = cfs_rq->curr == se;
3383
88ec22d3 3384 /*
2f950354
PZ
3385 * If we're the current task, we must renormalise before calling
3386 * update_curr().
88ec22d3 3387 */
2f950354 3388 if (renorm && curr)
88ec22d3
PZ
3389 se->vruntime += cfs_rq->min_vruntime;
3390
2f950354
PZ
3391 update_curr(cfs_rq);
3392
bf0f6f24 3393 /*
2f950354
PZ
3394 * Otherwise, renormalise after, such that we're placed at the current
3395 * moment in time, instead of some random moment in the past. Being
3396 * placed in the past could significantly boost this task to the
3397 * fairness detriment of existing tasks.
bf0f6f24 3398 */
2f950354
PZ
3399 if (renorm && !curr)
3400 se->vruntime += cfs_rq->min_vruntime;
3401
9d89c257 3402 enqueue_entity_load_avg(cfs_rq, se);
17bc14b7
LT
3403 account_entity_enqueue(cfs_rq, se);
3404 update_cfs_shares(cfs_rq);
bf0f6f24 3405
1a3d027c 3406 if (flags & ENQUEUE_WAKEUP)
aeb73b04 3407 place_entity(cfs_rq, se, 0);
bf0f6f24 3408
cb251765 3409 check_schedstat_required();
4fa8d299
JP
3410 update_stats_enqueue(cfs_rq, se, flags);
3411 check_spread(cfs_rq, se);
2f950354 3412 if (!curr)
83b699ed 3413 __enqueue_entity(cfs_rq, se);
2069dd75 3414 se->on_rq = 1;
3d4b47b4 3415
d3d9dc33 3416 if (cfs_rq->nr_running == 1) {
3d4b47b4 3417 list_add_leaf_cfs_rq(cfs_rq);
d3d9dc33
PT
3418 check_enqueue_throttle(cfs_rq);
3419 }
bf0f6f24
IM
3420}
3421
2c13c919 3422static void __clear_buddies_last(struct sched_entity *se)
2002c695 3423{
2c13c919
RR
3424 for_each_sched_entity(se) {
3425 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 3426 if (cfs_rq->last != se)
2c13c919 3427 break;
f1044799
PZ
3428
3429 cfs_rq->last = NULL;
2c13c919
RR
3430 }
3431}
2002c695 3432
2c13c919
RR
3433static void __clear_buddies_next(struct sched_entity *se)
3434{
3435 for_each_sched_entity(se) {
3436 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 3437 if (cfs_rq->next != se)
2c13c919 3438 break;
f1044799
PZ
3439
3440 cfs_rq->next = NULL;
2c13c919 3441 }
2002c695
PZ
3442}
3443
ac53db59
RR
3444static void __clear_buddies_skip(struct sched_entity *se)
3445{
3446 for_each_sched_entity(se) {
3447 struct cfs_rq *cfs_rq = cfs_rq_of(se);
f1044799 3448 if (cfs_rq->skip != se)
ac53db59 3449 break;
f1044799
PZ
3450
3451 cfs_rq->skip = NULL;
ac53db59
RR
3452 }
3453}
3454
a571bbea
PZ
3455static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
3456{
2c13c919
RR
3457 if (cfs_rq->last == se)
3458 __clear_buddies_last(se);
3459
3460 if (cfs_rq->next == se)
3461 __clear_buddies_next(se);
ac53db59
RR
3462
3463 if (cfs_rq->skip == se)
3464 __clear_buddies_skip(se);
a571bbea
PZ
3465}
3466
6c16a6dc 3467static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
d8b4986d 3468
bf0f6f24 3469static void
371fd7e7 3470dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
bf0f6f24 3471{
a2a2d680
DA
3472 /*
3473 * Update run-time statistics of the 'current'.
3474 */
3475 update_curr(cfs_rq);
13962234 3476 dequeue_entity_load_avg(cfs_rq, se);
a2a2d680 3477
4fa8d299 3478 update_stats_dequeue(cfs_rq, se, flags);
67e9fb2a 3479
2002c695 3480 clear_buddies(cfs_rq, se);
4793241b 3481
83b699ed 3482 if (se != cfs_rq->curr)
30cfdcfc 3483 __dequeue_entity(cfs_rq, se);
17bc14b7 3484 se->on_rq = 0;
30cfdcfc 3485 account_entity_dequeue(cfs_rq, se);
88ec22d3
PZ
3486
3487 /*
b60205c7
PZ
3488 * Normalize after update_curr(); which will also have moved
3489 * min_vruntime if @se is the one holding it back. But before doing
3490 * update_min_vruntime() again, which will discount @se's position and
3491 * can move min_vruntime forward still more.
88ec22d3 3492 */
371fd7e7 3493 if (!(flags & DEQUEUE_SLEEP))
88ec22d3 3494 se->vruntime -= cfs_rq->min_vruntime;
1e876231 3495
d8b4986d
PT
3496 /* return excess runtime on last dequeue */
3497 return_cfs_rq_runtime(cfs_rq);
3498
17bc14b7 3499 update_cfs_shares(cfs_rq);
b60205c7
PZ
3500
3501 /*
3502 * Now advance min_vruntime if @se was the entity holding it back,
3503 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
3504 * put back on, and if we advance min_vruntime, we'll be placed back
3505 * further than we started -- ie. we'll be penalized.
3506 */
3507 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) == DEQUEUE_SAVE)
3508 update_min_vruntime(cfs_rq);
bf0f6f24
IM
3509}
3510
3511/*
3512 * Preempt the current task with a newly woken task if needed:
3513 */
7c92e54f 3514static void
2e09bf55 3515check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
bf0f6f24 3516{
11697830 3517 unsigned long ideal_runtime, delta_exec;
f4cfb33e
WX
3518 struct sched_entity *se;
3519 s64 delta;
11697830 3520
6d0f0ebd 3521 ideal_runtime = sched_slice(cfs_rq, curr);
11697830 3522 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
a9f3e2b5 3523 if (delta_exec > ideal_runtime) {
8875125e 3524 resched_curr(rq_of(cfs_rq));
a9f3e2b5
MG
3525 /*
3526 * The current task ran long enough, ensure it doesn't get
3527 * re-elected due to buddy favours.
3528 */
3529 clear_buddies(cfs_rq, curr);
f685ceac
MG
3530 return;
3531 }
3532
3533 /*
3534 * Ensure that a task that missed wakeup preemption by a
3535 * narrow margin doesn't have to wait for a full slice.
3536 * This also mitigates buddy induced latencies under load.
3537 */
f685ceac
MG
3538 if (delta_exec < sysctl_sched_min_granularity)
3539 return;
3540
f4cfb33e
WX
3541 se = __pick_first_entity(cfs_rq);
3542 delta = curr->vruntime - se->vruntime;
f685ceac 3543
f4cfb33e
WX
3544 if (delta < 0)
3545 return;
d7d82944 3546
f4cfb33e 3547 if (delta > ideal_runtime)
8875125e 3548 resched_curr(rq_of(cfs_rq));
bf0f6f24
IM
3549}
3550
83b699ed 3551static void
8494f412 3552set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
bf0f6f24 3553{
83b699ed
SV
3554 /* 'current' is not kept within the tree. */
3555 if (se->on_rq) {
3556 /*
3557 * Any task has to be enqueued before it get to execute on
3558 * a CPU. So account for the time it spent waiting on the
3559 * runqueue.
3560 */
4fa8d299 3561 update_stats_wait_end(cfs_rq, se);
83b699ed 3562 __dequeue_entity(cfs_rq, se);
9d89c257 3563 update_load_avg(se, 1);
83b699ed
SV
3564 }
3565
79303e9e 3566 update_stats_curr_start(cfs_rq, se);
429d43bc 3567 cfs_rq->curr = se;
4fa8d299 3568
eba1ed4b
IM
3569 /*
3570 * Track our maximum slice length, if the CPU's load is at
3571 * least twice that of our own weight (i.e. dont track it
3572 * when there are only lesser-weight tasks around):
3573 */
cb251765 3574 if (schedstat_enabled() && rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
4fa8d299
JP
3575 schedstat_set(se->statistics.slice_max,
3576 max((u64)schedstat_val(se->statistics.slice_max),
3577 se->sum_exec_runtime - se->prev_sum_exec_runtime));
eba1ed4b 3578 }
4fa8d299 3579
4a55b450 3580 se->prev_sum_exec_runtime = se->sum_exec_runtime;
bf0f6f24
IM
3581}
3582
3f3a4904
PZ
3583static int
3584wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
3585
ac53db59
RR
3586/*
3587 * Pick the next process, keeping these things in mind, in this order:
3588 * 1) keep things fair between processes/task groups
3589 * 2) pick the "next" process, since someone really wants that to run
3590 * 3) pick the "last" process, for cache locality
3591 * 4) do not run the "skip" process, if something else is available
3592 */
678d5718
PZ
3593static struct sched_entity *
3594pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
aa2ac252 3595{
678d5718
PZ
3596 struct sched_entity *left = __pick_first_entity(cfs_rq);
3597 struct sched_entity *se;
3598
3599 /*
3600 * If curr is set we have to see if its left of the leftmost entity
3601 * still in the tree, provided there was anything in the tree at all.
3602 */
3603 if (!left || (curr && entity_before(curr, left)))
3604 left = curr;
3605
3606 se = left; /* ideally we run the leftmost entity */
f4b6755f 3607
ac53db59
RR
3608 /*
3609 * Avoid running the skip buddy, if running something else can
3610 * be done without getting too unfair.
3611 */
3612 if (cfs_rq->skip == se) {
678d5718
PZ
3613 struct sched_entity *second;
3614
3615 if (se == curr) {
3616 second = __pick_first_entity(cfs_rq);
3617 } else {
3618 second = __pick_next_entity(se);
3619 if (!second || (curr && entity_before(curr, second)))
3620 second = curr;
3621 }
3622
ac53db59
RR
3623 if (second && wakeup_preempt_entity(second, left) < 1)
3624 se = second;
3625 }
aa2ac252 3626
f685ceac
MG
3627 /*
3628 * Prefer last buddy, try to return the CPU to a preempted task.
3629 */
3630 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
3631 se = cfs_rq->last;
3632
ac53db59
RR
3633 /*
3634 * Someone really wants this to run. If it's not unfair, run it.
3635 */
3636 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
3637 se = cfs_rq->next;
3638
f685ceac 3639 clear_buddies(cfs_rq, se);
4793241b
PZ
3640
3641 return se;
aa2ac252
PZ
3642}
3643
678d5718 3644static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
d3d9dc33 3645
ab6cde26 3646static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
bf0f6f24
IM
3647{
3648 /*
3649 * If still on the runqueue then deactivate_task()
3650 * was not called and update_curr() has to be done:
3651 */
3652 if (prev->on_rq)
b7cc0896 3653 update_curr(cfs_rq);
bf0f6f24 3654
d3d9dc33
PT
3655 /* throttle cfs_rqs exceeding runtime */
3656 check_cfs_rq_runtime(cfs_rq);
3657
4fa8d299 3658 check_spread(cfs_rq, prev);
cb251765 3659
30cfdcfc 3660 if (prev->on_rq) {
4fa8d299 3661 update_stats_wait_start(cfs_rq, prev);
30cfdcfc
DA
3662 /* Put 'current' back into the tree. */
3663 __enqueue_entity(cfs_rq, prev);
9d85f21c 3664 /* in !on_rq case, update occurred at dequeue */
9d89c257 3665 update_load_avg(prev, 0);
30cfdcfc 3666 }
429d43bc 3667 cfs_rq->curr = NULL;
bf0f6f24
IM
3668}
3669
8f4d37ec
PZ
3670static void
3671entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
bf0f6f24 3672{
bf0f6f24 3673 /*
30cfdcfc 3674 * Update run-time statistics of the 'current'.
bf0f6f24 3675 */
30cfdcfc 3676 update_curr(cfs_rq);
bf0f6f24 3677
9d85f21c
PT
3678 /*
3679 * Ensure that runnable average is periodically updated.
3680 */
9d89c257 3681 update_load_avg(curr, 1);
bf0bd948 3682 update_cfs_shares(cfs_rq);
9d85f21c 3683
8f4d37ec
PZ
3684#ifdef CONFIG_SCHED_HRTICK
3685 /*
3686 * queued ticks are scheduled to match the slice, so don't bother
3687 * validating it and just reschedule.
3688 */
983ed7a6 3689 if (queued) {
8875125e 3690 resched_curr(rq_of(cfs_rq));
983ed7a6
HH
3691 return;
3692 }
8f4d37ec
PZ
3693 /*
3694 * don't let the period tick interfere with the hrtick preemption
3695 */
3696 if (!sched_feat(DOUBLE_TICK) &&
3697 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
3698 return;
3699#endif
3700
2c2efaed 3701 if (cfs_rq->nr_running > 1)
2e09bf55 3702 check_preempt_tick(cfs_rq, curr);
bf0f6f24
IM
3703}
3704
ab84d31e
PT
3705
3706/**************************************************
3707 * CFS bandwidth control machinery
3708 */
3709
3710#ifdef CONFIG_CFS_BANDWIDTH
029632fb
PZ
3711
3712#ifdef HAVE_JUMP_LABEL
c5905afb 3713static struct static_key __cfs_bandwidth_used;
029632fb
PZ
3714
3715static inline bool cfs_bandwidth_used(void)
3716{
c5905afb 3717 return static_key_false(&__cfs_bandwidth_used);
029632fb
PZ
3718}
3719
1ee14e6c 3720void cfs_bandwidth_usage_inc(void)
029632fb 3721{
1ee14e6c
BS
3722 static_key_slow_inc(&__cfs_bandwidth_used);
3723}
3724
3725void cfs_bandwidth_usage_dec(void)
3726{
3727 static_key_slow_dec(&__cfs_bandwidth_used);
029632fb
PZ
3728}
3729#else /* HAVE_JUMP_LABEL */
3730static bool cfs_bandwidth_used(void)
3731{
3732 return true;
3733}
3734
1ee14e6c
BS
3735void cfs_bandwidth_usage_inc(void) {}
3736void cfs_bandwidth_usage_dec(void) {}
029632fb
PZ
3737#endif /* HAVE_JUMP_LABEL */
3738
ab84d31e
PT
3739/*
3740 * default period for cfs group bandwidth.
3741 * default: 0.1s, units: nanoseconds
3742 */
3743static inline u64 default_cfs_period(void)
3744{
3745 return 100000000ULL;
3746}
ec12cb7f
PT
3747
3748static inline u64 sched_cfs_bandwidth_slice(void)
3749{
3750 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
3751}
3752
a9cf55b2
PT
3753/*
3754 * Replenish runtime according to assigned quota and update expiration time.
3755 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
3756 * additional synchronization around rq->lock.
3757 *
3758 * requires cfs_b->lock
3759 */
029632fb 3760void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
a9cf55b2
PT
3761{
3762 u64 now;
3763
3764 if (cfs_b->quota == RUNTIME_INF)
3765 return;
3766
3767 now = sched_clock_cpu(smp_processor_id());
3768 cfs_b->runtime = cfs_b->quota;
3769 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
3770}
3771
029632fb
PZ
3772static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
3773{
3774 return &tg->cfs_bandwidth;
3775}
3776
f1b17280
PT
3777/* rq->task_clock normalized against any time this cfs_rq has spent throttled */
3778static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
3779{
3780 if (unlikely(cfs_rq->throttle_count))
1a99ae3f 3781 return cfs_rq->throttled_clock_task - cfs_rq->throttled_clock_task_time;
f1b17280 3782
78becc27 3783 return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
f1b17280
PT
3784}
3785
85dac906
PT
3786/* returns 0 on failure to allocate runtime */
3787static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
ec12cb7f
PT
3788{
3789 struct task_group *tg = cfs_rq->tg;
3790 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
a9cf55b2 3791 u64 amount = 0, min_amount, expires;
ec12cb7f
PT
3792
3793 /* note: this is a positive sum as runtime_remaining <= 0 */
3794 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
3795
3796 raw_spin_lock(&cfs_b->lock);
3797 if (cfs_b->quota == RUNTIME_INF)
3798 amount = min_amount;
58088ad0 3799 else {
77a4d1a1 3800 start_cfs_bandwidth(cfs_b);
58088ad0
PT
3801
3802 if (cfs_b->runtime > 0) {
3803 amount = min(cfs_b->runtime, min_amount);
3804 cfs_b->runtime -= amount;
3805 cfs_b->idle = 0;
3806 }
ec12cb7f 3807 }
a9cf55b2 3808 expires = cfs_b->runtime_expires;
ec12cb7f
PT
3809 raw_spin_unlock(&cfs_b->lock);
3810
3811 cfs_rq->runtime_remaining += amount;
a9cf55b2
PT
3812 /*
3813 * we may have advanced our local expiration to account for allowed
3814 * spread between our sched_clock and the one on which runtime was
3815 * issued.
3816 */
3817 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
3818 cfs_rq->runtime_expires = expires;
85dac906
PT
3819
3820 return cfs_rq->runtime_remaining > 0;
ec12cb7f
PT
3821}
3822
a9cf55b2
PT
3823/*
3824 * Note: This depends on the synchronization provided by sched_clock and the
3825 * fact that rq->clock snapshots this value.
3826 */
3827static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
ec12cb7f 3828{
a9cf55b2 3829 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
a9cf55b2
PT
3830
3831 /* if the deadline is ahead of our clock, nothing to do */
78becc27 3832 if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
ec12cb7f
PT
3833 return;
3834
a9cf55b2
PT
3835 if (cfs_rq->runtime_remaining < 0)
3836 return;
3837
3838 /*
3839 * If the local deadline has passed we have to consider the
3840 * possibility that our sched_clock is 'fast' and the global deadline
3841 * has not truly expired.
3842 *
3843 * Fortunately we can check determine whether this the case by checking
51f2176d
BS
3844 * whether the global deadline has advanced. It is valid to compare
3845 * cfs_b->runtime_expires without any locks since we only care about
3846 * exact equality, so a partial write will still work.
a9cf55b2
PT
3847 */
3848
51f2176d 3849 if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
a9cf55b2
PT
3850 /* extend local deadline, drift is bounded above by 2 ticks */
3851 cfs_rq->runtime_expires += TICK_NSEC;
3852 } else {
3853 /* global deadline is ahead, expiration has passed */
3854 cfs_rq->runtime_remaining = 0;
3855 }
3856}
3857
9dbdb155 3858static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
a9cf55b2
PT
3859{
3860 /* dock delta_exec before expiring quota (as it could span periods) */
ec12cb7f 3861 cfs_rq->runtime_remaining -= delta_exec;
a9cf55b2
PT
3862 expire_cfs_rq_runtime(cfs_rq);
3863
3864 if (likely(cfs_rq->runtime_remaining > 0))
ec12cb7f
PT
3865 return;
3866
85dac906
PT
3867 /*
3868 * if we're unable to extend our runtime we resched so that the active
3869 * hierarchy can be throttled
3870 */
3871 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
8875125e 3872 resched_curr(rq_of(cfs_rq));
ec12cb7f
PT
3873}
3874
6c16a6dc 3875static __always_inline
9dbdb155 3876void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
ec12cb7f 3877{
56f570e5 3878 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
ec12cb7f
PT
3879 return;
3880
3881 __account_cfs_rq_runtime(cfs_rq, delta_exec);
3882}
3883
85dac906
PT
3884static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
3885{
56f570e5 3886 return cfs_bandwidth_used() && cfs_rq->throttled;
85dac906
PT
3887}
3888
64660c86
PT
3889/* check whether cfs_rq, or any parent, is throttled */
3890static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
3891{
56f570e5 3892 return cfs_bandwidth_used() && cfs_rq->throttle_count;
64660c86
PT
3893}
3894
3895/*
3896 * Ensure that neither of the group entities corresponding to src_cpu or
3897 * dest_cpu are members of a throttled hierarchy when performing group
3898 * load-balance operations.
3899 */
3900static inline int throttled_lb_pair(struct task_group *tg,
3901 int src_cpu, int dest_cpu)
3902{
3903 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
3904
3905 src_cfs_rq = tg->cfs_rq[src_cpu];
3906 dest_cfs_rq = tg->cfs_rq[dest_cpu];
3907
3908 return throttled_hierarchy(src_cfs_rq) ||
3909 throttled_hierarchy(dest_cfs_rq);
3910}
3911
3912/* updated child weight may affect parent so we have to do this bottom up */
3913static int tg_unthrottle_up(struct task_group *tg, void *data)
3914{
3915 struct rq *rq = data;
3916 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3917
3918 cfs_rq->throttle_count--;
64660c86 3919 if (!cfs_rq->throttle_count) {
f1b17280 3920 /* adjust cfs_rq_clock_task() */
78becc27 3921 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
f1b17280 3922 cfs_rq->throttled_clock_task;
64660c86 3923 }
64660c86
PT
3924
3925 return 0;
3926}
3927
3928static int tg_throttle_down(struct task_group *tg, void *data)
3929{
3930 struct rq *rq = data;
3931 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3932
82958366
PT
3933 /* group is entering throttled state, stop time */
3934 if (!cfs_rq->throttle_count)
78becc27 3935 cfs_rq->throttled_clock_task = rq_clock_task(rq);
64660c86
PT
3936 cfs_rq->throttle_count++;
3937
3938 return 0;
3939}
3940
d3d9dc33 3941static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
85dac906
PT
3942{
3943 struct rq *rq = rq_of(cfs_rq);
3944 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3945 struct sched_entity *se;
3946 long task_delta, dequeue = 1;
77a4d1a1 3947 bool empty;
85dac906
PT
3948
3949 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
3950
f1b17280 3951 /* freeze hierarchy runnable averages while throttled */
64660c86
PT
3952 rcu_read_lock();
3953 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
3954 rcu_read_unlock();
85dac906
PT
3955
3956 task_delta = cfs_rq->h_nr_running;
3957 for_each_sched_entity(se) {
3958 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
3959 /* throttled entity or throttle-on-deactivate */
3960 if (!se->on_rq)
3961 break;
3962
3963 if (dequeue)
3964 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
3965 qcfs_rq->h_nr_running -= task_delta;
3966
3967 if (qcfs_rq->load.weight)
3968 dequeue = 0;
3969 }
3970
3971 if (!se)
72465447 3972 sub_nr_running(rq, task_delta);
85dac906
PT
3973
3974 cfs_rq->throttled = 1;
78becc27 3975 cfs_rq->throttled_clock = rq_clock(rq);
85dac906 3976 raw_spin_lock(&cfs_b->lock);
d49db342 3977 empty = list_empty(&cfs_b->throttled_cfs_rq);
77a4d1a1 3978
c06f04c7
BS
3979 /*
3980 * Add to the _head_ of the list, so that an already-started
3981 * distribute_cfs_runtime will not see us
3982 */
3983 list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
77a4d1a1
PZ
3984
3985 /*
3986 * If we're the first throttled task, make sure the bandwidth
3987 * timer is running.
3988 */
3989 if (empty)
3990 start_cfs_bandwidth(cfs_b);
3991
85dac906
PT
3992 raw_spin_unlock(&cfs_b->lock);
3993}
3994
029632fb 3995void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
671fd9da
PT
3996{
3997 struct rq *rq = rq_of(cfs_rq);
3998 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3999 struct sched_entity *se;
4000 int enqueue = 1;
4001 long task_delta;
4002
22b958d8 4003 se = cfs_rq->tg->se[cpu_of(rq)];
671fd9da
PT
4004
4005 cfs_rq->throttled = 0;
1a55af2e
FW
4006
4007 update_rq_clock(rq);
4008
671fd9da 4009 raw_spin_lock(&cfs_b->lock);
78becc27 4010 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
671fd9da
PT
4011 list_del_rcu(&cfs_rq->throttled_list);
4012 raw_spin_unlock(&cfs_b->lock);
4013
64660c86
PT
4014 /* update hierarchical throttle state */
4015 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4016
671fd9da
PT
4017 if (!cfs_rq->load.weight)
4018 return;
4019
4020 task_delta = cfs_rq->h_nr_running;
4021 for_each_sched_entity(se) {
4022 if (se->on_rq)
4023 enqueue = 0;
4024
4025 cfs_rq = cfs_rq_of(se);
4026 if (enqueue)
4027 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4028 cfs_rq->h_nr_running += task_delta;
4029
4030 if (cfs_rq_throttled(cfs_rq))
4031 break;
4032 }
4033
4034 if (!se)
72465447 4035 add_nr_running(rq, task_delta);
671fd9da
PT
4036
4037 /* determine whether we need to wake up potentially idle cpu */
4038 if (rq->curr == rq->idle && rq->cfs.nr_running)
8875125e 4039 resched_curr(rq);
671fd9da
PT
4040}
4041
4042static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
4043 u64 remaining, u64 expires)
4044{
4045 struct cfs_rq *cfs_rq;
c06f04c7
BS
4046 u64 runtime;
4047 u64 starting_runtime = remaining;
671fd9da
PT
4048
4049 rcu_read_lock();
4050 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
4051 throttled_list) {
4052 struct rq *rq = rq_of(cfs_rq);
4053
4054 raw_spin_lock(&rq->lock);
4055 if (!cfs_rq_throttled(cfs_rq))
4056 goto next;
4057
4058 runtime = -cfs_rq->runtime_remaining + 1;
4059 if (runtime > remaining)
4060 runtime = remaining;
4061 remaining -= runtime;
4062
4063 cfs_rq->runtime_remaining += runtime;
4064 cfs_rq->runtime_expires = expires;
4065
4066 /* we check whether we're throttled above */
4067 if (cfs_rq->runtime_remaining > 0)
4068 unthrottle_cfs_rq(cfs_rq);
4069
4070next:
4071 raw_spin_unlock(&rq->lock);
4072
4073 if (!remaining)
4074 break;
4075 }
4076 rcu_read_unlock();
4077
c06f04c7 4078 return starting_runtime - remaining;
671fd9da
PT
4079}
4080
58088ad0
PT
4081/*
4082 * Responsible for refilling a task_group's bandwidth and unthrottling its
4083 * cfs_rqs as appropriate. If there has been no activity within the last
4084 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4085 * used to track this state.
4086 */
4087static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
4088{
671fd9da 4089 u64 runtime, runtime_expires;
51f2176d 4090 int throttled;
58088ad0 4091
58088ad0
PT
4092 /* no need to continue the timer with no bandwidth constraint */
4093 if (cfs_b->quota == RUNTIME_INF)
51f2176d 4094 goto out_deactivate;
58088ad0 4095
671fd9da 4096 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
e8da1b18 4097 cfs_b->nr_periods += overrun;
671fd9da 4098
51f2176d
BS
4099 /*
4100 * idle depends on !throttled (for the case of a large deficit), and if
4101 * we're going inactive then everything else can be deferred
4102 */
4103 if (cfs_b->idle && !throttled)
4104 goto out_deactivate;
a9cf55b2
PT
4105
4106 __refill_cfs_bandwidth_runtime(cfs_b);
4107
671fd9da
PT
4108 if (!throttled) {
4109 /* mark as potentially idle for the upcoming period */
4110 cfs_b->idle = 1;
51f2176d 4111 return 0;
671fd9da
PT
4112 }
4113
e8da1b18
NR
4114 /* account preceding periods in which throttling occurred */
4115 cfs_b->nr_throttled += overrun;
4116
671fd9da 4117 runtime_expires = cfs_b->runtime_expires;
671fd9da
PT
4118
4119 /*
c06f04c7
BS
4120 * This check is repeated as we are holding onto the new bandwidth while
4121 * we unthrottle. This can potentially race with an unthrottled group
4122 * trying to acquire new bandwidth from the global pool. This can result
4123 * in us over-using our runtime if it is all used during this loop, but
4124 * only by limited amounts in that extreme case.
671fd9da 4125 */
c06f04c7
BS
4126 while (throttled && cfs_b->runtime > 0) {
4127 runtime = cfs_b->runtime;
671fd9da
PT
4128 raw_spin_unlock(&cfs_b->lock);
4129 /* we can't nest cfs_b->lock while distributing bandwidth */
4130 runtime = distribute_cfs_runtime(cfs_b, runtime,
4131 runtime_expires);
4132 raw_spin_lock(&cfs_b->lock);
4133
4134 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
c06f04c7
BS
4135
4136 cfs_b->runtime -= min(runtime, cfs_b->runtime);
671fd9da 4137 }
58088ad0 4138
671fd9da
PT
4139 /*
4140 * While we are ensured activity in the period following an
4141 * unthrottle, this also covers the case in which the new bandwidth is
4142 * insufficient to cover the existing bandwidth deficit. (Forcing the
4143 * timer to remain active while there are any throttled entities.)
4144 */
4145 cfs_b->idle = 0;
58088ad0 4146
51f2176d
BS
4147 return 0;
4148
4149out_deactivate:
51f2176d 4150 return 1;
58088ad0 4151}
d3d9dc33 4152
d8b4986d
PT
4153/* a cfs_rq won't donate quota below this amount */
4154static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
4155/* minimum remaining period time to redistribute slack quota */
4156static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
4157/* how long we wait to gather additional slack before distributing */
4158static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
4159
db06e78c
BS
4160/*
4161 * Are we near the end of the current quota period?
4162 *
4163 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4961b6e1 4164 * hrtimer base being cleared by hrtimer_start. In the case of
db06e78c
BS
4165 * migrate_hrtimers, base is never cleared, so we are fine.
4166 */
d8b4986d
PT
4167static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
4168{
4169 struct hrtimer *refresh_timer = &cfs_b->period_timer;
4170 u64 remaining;
4171
4172 /* if the call-back is running a quota refresh is already occurring */
4173 if (hrtimer_callback_running(refresh_timer))
4174 return 1;
4175
4176 /* is a quota refresh about to occur? */
4177 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
4178 if (remaining < min_expire)
4179 return 1;
4180
4181 return 0;
4182}
4183
4184static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
4185{
4186 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
4187
4188 /* if there's a quota refresh soon don't bother with slack */
4189 if (runtime_refresh_within(cfs_b, min_left))
4190 return;
4191
4cfafd30
PZ
4192 hrtimer_start(&cfs_b->slack_timer,
4193 ns_to_ktime(cfs_bandwidth_slack_period),
4194 HRTIMER_MODE_REL);
d8b4986d
PT
4195}
4196
4197/* we know any runtime found here is valid as update_curr() precedes return */
4198static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4199{
4200 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4201 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
4202
4203 if (slack_runtime <= 0)
4204 return;
4205
4206 raw_spin_lock(&cfs_b->lock);
4207 if (cfs_b->quota != RUNTIME_INF &&
4208 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
4209 cfs_b->runtime += slack_runtime;
4210
4211 /* we are under rq->lock, defer unthrottling using a timer */
4212 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
4213 !list_empty(&cfs_b->throttled_cfs_rq))
4214 start_cfs_slack_bandwidth(cfs_b);
4215 }
4216 raw_spin_unlock(&cfs_b->lock);
4217
4218 /* even if it's not valid for return we don't want to try again */
4219 cfs_rq->runtime_remaining -= slack_runtime;
4220}
4221
4222static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4223{
56f570e5
PT
4224 if (!cfs_bandwidth_used())
4225 return;
4226
fccfdc6f 4227 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
d8b4986d
PT
4228 return;
4229
4230 __return_cfs_rq_runtime(cfs_rq);
4231}
4232
4233/*
4234 * This is done with a timer (instead of inline with bandwidth return) since
4235 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
4236 */
4237static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
4238{
4239 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
4240 u64 expires;
4241
4242 /* confirm we're still not at a refresh boundary */
db06e78c
BS
4243 raw_spin_lock(&cfs_b->lock);
4244 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
4245 raw_spin_unlock(&cfs_b->lock);
d8b4986d 4246 return;
db06e78c 4247 }
d8b4986d 4248
c06f04c7 4249 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
d8b4986d 4250 runtime = cfs_b->runtime;
c06f04c7 4251
d8b4986d
PT
4252 expires = cfs_b->runtime_expires;
4253 raw_spin_unlock(&cfs_b->lock);
4254
4255 if (!runtime)
4256 return;
4257
4258 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
4259
4260 raw_spin_lock(&cfs_b->lock);
4261 if (expires == cfs_b->runtime_expires)
c06f04c7 4262 cfs_b->runtime -= min(runtime, cfs_b->runtime);
d8b4986d
PT
4263 raw_spin_unlock(&cfs_b->lock);
4264}
4265
d3d9dc33
PT
4266/*
4267 * When a group wakes up we want to make sure that its quota is not already
4268 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
4269 * runtime as update_curr() throttling can not not trigger until it's on-rq.
4270 */
4271static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
4272{
56f570e5
PT
4273 if (!cfs_bandwidth_used())
4274 return;
4275
d3d9dc33
PT
4276 /* an active group must be handled by the update_curr()->put() path */
4277 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
4278 return;
4279
4280 /* ensure the group is not already throttled */
4281 if (cfs_rq_throttled(cfs_rq))
4282 return;
4283
4284 /* update runtime allocation */
4285 account_cfs_rq_runtime(cfs_rq, 0);
4286 if (cfs_rq->runtime_remaining <= 0)
4287 throttle_cfs_rq(cfs_rq);
4288}
4289
55e16d30
PZ
4290static void sync_throttle(struct task_group *tg, int cpu)
4291{
4292 struct cfs_rq *pcfs_rq, *cfs_rq;
4293
4294 if (!cfs_bandwidth_used())
4295 return;
4296
4297 if (!tg->parent)
4298 return;
4299
4300 cfs_rq = tg->cfs_rq[cpu];
4301 pcfs_rq = tg->parent->cfs_rq[cpu];
4302
4303 cfs_rq->throttle_count = pcfs_rq->throttle_count;
b8922125 4304 cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
55e16d30
PZ
4305}
4306
d3d9dc33 4307/* conditionally throttle active cfs_rq's from put_prev_entity() */
678d5718 4308static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
d3d9dc33 4309{
56f570e5 4310 if (!cfs_bandwidth_used())
678d5718 4311 return false;
56f570e5 4312
d3d9dc33 4313 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
678d5718 4314 return false;
d3d9dc33
PT
4315
4316 /*
4317 * it's possible for a throttled entity to be forced into a running
4318 * state (e.g. set_curr_task), in this case we're finished.
4319 */
4320 if (cfs_rq_throttled(cfs_rq))
678d5718 4321 return true;
d3d9dc33
PT
4322
4323 throttle_cfs_rq(cfs_rq);
678d5718 4324 return true;
d3d9dc33 4325}
029632fb 4326
029632fb
PZ
4327static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
4328{
4329 struct cfs_bandwidth *cfs_b =
4330 container_of(timer, struct cfs_bandwidth, slack_timer);
77a4d1a1 4331
029632fb
PZ
4332 do_sched_cfs_slack_timer(cfs_b);
4333
4334 return HRTIMER_NORESTART;
4335}
4336
4337static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
4338{
4339 struct cfs_bandwidth *cfs_b =
4340 container_of(timer, struct cfs_bandwidth, period_timer);
029632fb
PZ
4341 int overrun;
4342 int idle = 0;
4343
51f2176d 4344 raw_spin_lock(&cfs_b->lock);
029632fb 4345 for (;;) {
77a4d1a1 4346 overrun = hrtimer_forward_now(timer, cfs_b->period);
029632fb
PZ
4347 if (!overrun)
4348 break;
4349
4350 idle = do_sched_cfs_period_timer(cfs_b, overrun);
4351 }
4cfafd30
PZ
4352 if (idle)
4353 cfs_b->period_active = 0;
51f2176d 4354 raw_spin_unlock(&cfs_b->lock);
029632fb
PZ
4355
4356 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
4357}
4358
4359void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4360{
4361 raw_spin_lock_init(&cfs_b->lock);
4362 cfs_b->runtime = 0;
4363 cfs_b->quota = RUNTIME_INF;
4364 cfs_b->period = ns_to_ktime(default_cfs_period());
4365
4366 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
4cfafd30 4367 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
029632fb
PZ
4368 cfs_b->period_timer.function = sched_cfs_period_timer;
4369 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4370 cfs_b->slack_timer.function = sched_cfs_slack_timer;
4371}
4372
4373static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4374{
4375 cfs_rq->runtime_enabled = 0;
4376 INIT_LIST_HEAD(&cfs_rq->throttled_list);
4377}
4378
77a4d1a1 4379void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
029632fb 4380{
4cfafd30 4381 lockdep_assert_held(&cfs_b->lock);
029632fb 4382
4cfafd30
PZ
4383 if (!cfs_b->period_active) {
4384 cfs_b->period_active = 1;
4385 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
4386 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
4387 }
029632fb
PZ
4388}
4389
4390static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4391{
7f1a169b
TH
4392 /* init_cfs_bandwidth() was not called */
4393 if (!cfs_b->throttled_cfs_rq.next)
4394 return;
4395
029632fb
PZ
4396 hrtimer_cancel(&cfs_b->period_timer);
4397 hrtimer_cancel(&cfs_b->slack_timer);
4398}
4399
0e59bdae
KT
4400static void __maybe_unused update_runtime_enabled(struct rq *rq)
4401{
4402 struct cfs_rq *cfs_rq;
4403
4404 for_each_leaf_cfs_rq(rq, cfs_rq) {
4405 struct cfs_bandwidth *cfs_b = &cfs_rq->tg->cfs_bandwidth;
4406
4407 raw_spin_lock(&cfs_b->lock);
4408 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
4409 raw_spin_unlock(&cfs_b->lock);
4410 }
4411}
4412
38dc3348 4413static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
029632fb
PZ
4414{
4415 struct cfs_rq *cfs_rq;
4416
4417 for_each_leaf_cfs_rq(rq, cfs_rq) {
029632fb
PZ
4418 if (!cfs_rq->runtime_enabled)
4419 continue;
4420
4421 /*
4422 * clock_task is not advancing so we just need to make sure
4423 * there's some valid quota amount
4424 */
51f2176d 4425 cfs_rq->runtime_remaining = 1;
0e59bdae
KT
4426 /*
4427 * Offline rq is schedulable till cpu is completely disabled
4428 * in take_cpu_down(), so we prevent new cfs throttling here.
4429 */
4430 cfs_rq->runtime_enabled = 0;
4431
029632fb
PZ
4432 if (cfs_rq_throttled(cfs_rq))
4433 unthrottle_cfs_rq(cfs_rq);
4434 }
4435}
4436
4437#else /* CONFIG_CFS_BANDWIDTH */
f1b17280
PT
4438static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
4439{
78becc27 4440 return rq_clock_task(rq_of(cfs_rq));
f1b17280
PT
4441}
4442
9dbdb155 4443static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
678d5718 4444static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
d3d9dc33 4445static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
55e16d30 4446static inline void sync_throttle(struct task_group *tg, int cpu) {}
6c16a6dc 4447static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
85dac906
PT
4448
4449static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4450{
4451 return 0;
4452}
64660c86
PT
4453
4454static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4455{
4456 return 0;
4457}
4458
4459static inline int throttled_lb_pair(struct task_group *tg,
4460 int src_cpu, int dest_cpu)
4461{
4462 return 0;
4463}
029632fb
PZ
4464
4465void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4466
4467#ifdef CONFIG_FAIR_GROUP_SCHED
4468static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
ab84d31e
PT
4469#endif
4470
029632fb
PZ
4471static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4472{
4473 return NULL;
4474}
4475static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
0e59bdae 4476static inline void update_runtime_enabled(struct rq *rq) {}
a4c96ae3 4477static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
029632fb
PZ
4478
4479#endif /* CONFIG_CFS_BANDWIDTH */
4480
bf0f6f24
IM
4481/**************************************************
4482 * CFS operations on tasks:
4483 */
4484
8f4d37ec
PZ
4485#ifdef CONFIG_SCHED_HRTICK
4486static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
4487{
8f4d37ec
PZ
4488 struct sched_entity *se = &p->se;
4489 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4490
9148a3a1 4491 SCHED_WARN_ON(task_rq(p) != rq);
8f4d37ec 4492
8bf46a39 4493 if (rq->cfs.h_nr_running > 1) {
8f4d37ec
PZ
4494 u64 slice = sched_slice(cfs_rq, se);
4495 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
4496 s64 delta = slice - ran;
4497
4498 if (delta < 0) {
4499 if (rq->curr == p)
8875125e 4500 resched_curr(rq);
8f4d37ec
PZ
4501 return;
4502 }
31656519 4503 hrtick_start(rq, delta);
8f4d37ec
PZ
4504 }
4505}
a4c2f00f
PZ
4506
4507/*
4508 * called from enqueue/dequeue and updates the hrtick when the
4509 * current task is from our class and nr_running is low enough
4510 * to matter.
4511 */
4512static void hrtick_update(struct rq *rq)
4513{
4514 struct task_struct *curr = rq->curr;
4515
b39e66ea 4516 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
a4c2f00f
PZ
4517 return;
4518
4519 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
4520 hrtick_start_fair(rq, curr);
4521}
55e12e5e 4522#else /* !CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
4523static inline void
4524hrtick_start_fair(struct rq *rq, struct task_struct *p)
4525{
4526}
a4c2f00f
PZ
4527
4528static inline void hrtick_update(struct rq *rq)
4529{
4530}
8f4d37ec
PZ
4531#endif
4532
bf0f6f24
IM
4533/*
4534 * The enqueue_task method is called before nr_running is
4535 * increased. Here we update the fair scheduling stats and
4536 * then put the task into the rbtree:
4537 */
ea87bb78 4538static void
371fd7e7 4539enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
4540{
4541 struct cfs_rq *cfs_rq;
62fb1851 4542 struct sched_entity *se = &p->se;
bf0f6f24 4543
8c34ab19
RW
4544 /*
4545 * If in_iowait is set, the code below may not trigger any cpufreq
4546 * utilization updates, so do it here explicitly with the IOWAIT flag
4547 * passed.
4548 */
4549 if (p->in_iowait)
4550 cpufreq_update_this_cpu(rq, SCHED_CPUFREQ_IOWAIT);
4551
bf0f6f24 4552 for_each_sched_entity(se) {
62fb1851 4553 if (se->on_rq)
bf0f6f24
IM
4554 break;
4555 cfs_rq = cfs_rq_of(se);
88ec22d3 4556 enqueue_entity(cfs_rq, se, flags);
85dac906
PT
4557
4558 /*
4559 * end evaluation on encountering a throttled cfs_rq
4560 *
4561 * note: in the case of encountering a throttled cfs_rq we will
4562 * post the final h_nr_running increment below.
e210bffd 4563 */
85dac906
PT
4564 if (cfs_rq_throttled(cfs_rq))
4565 break;
953bfcd1 4566 cfs_rq->h_nr_running++;
85dac906 4567
88ec22d3 4568 flags = ENQUEUE_WAKEUP;
bf0f6f24 4569 }
8f4d37ec 4570
2069dd75 4571 for_each_sched_entity(se) {
0f317143 4572 cfs_rq = cfs_rq_of(se);
953bfcd1 4573 cfs_rq->h_nr_running++;
2069dd75 4574
85dac906
PT
4575 if (cfs_rq_throttled(cfs_rq))
4576 break;
4577
9d89c257 4578 update_load_avg(se, 1);
17bc14b7 4579 update_cfs_shares(cfs_rq);
2069dd75
PZ
4580 }
4581
cd126afe 4582 if (!se)
72465447 4583 add_nr_running(rq, 1);
cd126afe 4584
a4c2f00f 4585 hrtick_update(rq);
bf0f6f24
IM
4586}
4587
2f36825b
VP
4588static void set_next_buddy(struct sched_entity *se);
4589
bf0f6f24
IM
4590/*
4591 * The dequeue_task method is called before nr_running is
4592 * decreased. We remove the task from the rbtree and
4593 * update the fair scheduling stats:
4594 */
371fd7e7 4595static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
bf0f6f24
IM
4596{
4597 struct cfs_rq *cfs_rq;
62fb1851 4598 struct sched_entity *se = &p->se;
2f36825b 4599 int task_sleep = flags & DEQUEUE_SLEEP;
bf0f6f24
IM
4600
4601 for_each_sched_entity(se) {
4602 cfs_rq = cfs_rq_of(se);
371fd7e7 4603 dequeue_entity(cfs_rq, se, flags);
85dac906
PT
4604
4605 /*
4606 * end evaluation on encountering a throttled cfs_rq
4607 *
4608 * note: in the case of encountering a throttled cfs_rq we will
4609 * post the final h_nr_running decrement below.
4610 */
4611 if (cfs_rq_throttled(cfs_rq))
4612 break;
953bfcd1 4613 cfs_rq->h_nr_running--;
2069dd75 4614
bf0f6f24 4615 /* Don't dequeue parent if it has other entities besides us */
2f36825b 4616 if (cfs_rq->load.weight) {
754bd598
KK
4617 /* Avoid re-evaluating load for this entity: */
4618 se = parent_entity(se);
2f36825b
VP
4619 /*
4620 * Bias pick_next to pick a task from this cfs_rq, as
4621 * p is sleeping when it is within its sched_slice.
4622 */
754bd598
KK
4623 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
4624 set_next_buddy(se);
bf0f6f24 4625 break;
2f36825b 4626 }
371fd7e7 4627 flags |= DEQUEUE_SLEEP;
bf0f6f24 4628 }
8f4d37ec 4629
2069dd75 4630 for_each_sched_entity(se) {
0f317143 4631 cfs_rq = cfs_rq_of(se);
953bfcd1 4632 cfs_rq->h_nr_running--;
2069dd75 4633
85dac906
PT
4634 if (cfs_rq_throttled(cfs_rq))
4635 break;
4636
9d89c257 4637 update_load_avg(se, 1);
17bc14b7 4638 update_cfs_shares(cfs_rq);
2069dd75
PZ
4639 }
4640
cd126afe 4641 if (!se)
72465447 4642 sub_nr_running(rq, 1);
cd126afe 4643
a4c2f00f 4644 hrtick_update(rq);
bf0f6f24
IM
4645}
4646
e7693a36 4647#ifdef CONFIG_SMP
10e2f1ac
PZ
4648
4649/* Working cpumask for: load_balance, load_balance_newidle. */
4650DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
4651DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
4652
9fd81dd5 4653#ifdef CONFIG_NO_HZ_COMMON
3289bdb4
PZ
4654/*
4655 * per rq 'load' arrray crap; XXX kill this.
4656 */
4657
4658/*
d937cdc5 4659 * The exact cpuload calculated at every tick would be:
3289bdb4 4660 *
d937cdc5
PZ
4661 * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
4662 *
4663 * If a cpu misses updates for n ticks (as it was idle) and update gets
4664 * called on the n+1-th tick when cpu may be busy, then we have:
4665 *
4666 * load_n = (1 - 1/2^i)^n * load_0
4667 * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
3289bdb4
PZ
4668 *
4669 * decay_load_missed() below does efficient calculation of
3289bdb4 4670 *
d937cdc5
PZ
4671 * load' = (1 - 1/2^i)^n * load
4672 *
4673 * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
4674 * This allows us to precompute the above in said factors, thereby allowing the
4675 * reduction of an arbitrary n in O(log_2 n) steps. (See also
4676 * fixed_power_int())
3289bdb4 4677 *
d937cdc5 4678 * The calculation is approximated on a 128 point scale.
3289bdb4
PZ
4679 */
4680#define DEGRADE_SHIFT 7
d937cdc5
PZ
4681
4682static const u8 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
4683static const u8 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
4684 { 0, 0, 0, 0, 0, 0, 0, 0 },
4685 { 64, 32, 8, 0, 0, 0, 0, 0 },
4686 { 96, 72, 40, 12, 1, 0, 0, 0 },
4687 { 112, 98, 75, 43, 15, 1, 0, 0 },
4688 { 120, 112, 98, 76, 45, 16, 2, 0 }
4689};
3289bdb4
PZ
4690
4691/*
4692 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
4693 * would be when CPU is idle and so we just decay the old load without
4694 * adding any new load.
4695 */
4696static unsigned long
4697decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
4698{
4699 int j = 0;
4700
4701 if (!missed_updates)
4702 return load;
4703
4704 if (missed_updates >= degrade_zero_ticks[idx])
4705 return 0;
4706
4707 if (idx == 1)
4708 return load >> missed_updates;
4709
4710 while (missed_updates) {
4711 if (missed_updates % 2)
4712 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
4713
4714 missed_updates >>= 1;
4715 j++;
4716 }
4717 return load;
4718}
9fd81dd5 4719#endif /* CONFIG_NO_HZ_COMMON */
3289bdb4 4720
59543275 4721/**
cee1afce 4722 * __cpu_load_update - update the rq->cpu_load[] statistics
59543275
BP
4723 * @this_rq: The rq to update statistics for
4724 * @this_load: The current load
4725 * @pending_updates: The number of missed updates
59543275 4726 *
3289bdb4 4727 * Update rq->cpu_load[] statistics. This function is usually called every
59543275
BP
4728 * scheduler tick (TICK_NSEC).
4729 *
4730 * This function computes a decaying average:
4731 *
4732 * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
4733 *
4734 * Because of NOHZ it might not get called on every tick which gives need for
4735 * the @pending_updates argument.
4736 *
4737 * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
4738 * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
4739 * = A * (A * load[i]_n-2 + B) + B
4740 * = A * (A * (A * load[i]_n-3 + B) + B) + B
4741 * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
4742 * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
4743 * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
4744 * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
4745 *
4746 * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
4747 * any change in load would have resulted in the tick being turned back on.
4748 *
4749 * For regular NOHZ, this reduces to:
4750 *
4751 * load[i]_n = (1 - 1/2^i)^n * load[i]_0
4752 *
4753 * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
1f41906a 4754 * term.
3289bdb4 4755 */
1f41906a
FW
4756static void cpu_load_update(struct rq *this_rq, unsigned long this_load,
4757 unsigned long pending_updates)
3289bdb4 4758{
9fd81dd5 4759 unsigned long __maybe_unused tickless_load = this_rq->cpu_load[0];
3289bdb4
PZ
4760 int i, scale;
4761
4762 this_rq->nr_load_updates++;
4763
4764 /* Update our load: */
4765 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
4766 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
4767 unsigned long old_load, new_load;
4768
4769 /* scale is effectively 1 << i now, and >> i divides by scale */
4770
7400d3bb 4771 old_load = this_rq->cpu_load[i];
9fd81dd5 4772#ifdef CONFIG_NO_HZ_COMMON
3289bdb4 4773 old_load = decay_load_missed(old_load, pending_updates - 1, i);
7400d3bb
BP
4774 if (tickless_load) {
4775 old_load -= decay_load_missed(tickless_load, pending_updates - 1, i);
4776 /*
4777 * old_load can never be a negative value because a
4778 * decayed tickless_load cannot be greater than the
4779 * original tickless_load.
4780 */
4781 old_load += tickless_load;
4782 }
9fd81dd5 4783#endif
3289bdb4
PZ
4784 new_load = this_load;
4785 /*
4786 * Round up the averaging division if load is increasing. This
4787 * prevents us from getting stuck on 9 if the load is 10, for
4788 * example.
4789 */
4790 if (new_load > old_load)
4791 new_load += scale - 1;
4792
4793 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
4794 }
4795
4796 sched_avg_update(this_rq);
4797}
4798
7ea241af
YD
4799/* Used instead of source_load when we know the type == 0 */
4800static unsigned long weighted_cpuload(const int cpu)
4801{
4802 return cfs_rq_runnable_load_avg(&cpu_rq(cpu)->cfs);
4803}
4804
3289bdb4 4805#ifdef CONFIG_NO_HZ_COMMON
1f41906a
FW
4806/*
4807 * There is no sane way to deal with nohz on smp when using jiffies because the
4808 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
4809 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
4810 *
4811 * Therefore we need to avoid the delta approach from the regular tick when
4812 * possible since that would seriously skew the load calculation. This is why we
4813 * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
4814 * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
4815 * loop exit, nohz_idle_balance, nohz full exit...)
4816 *
4817 * This means we might still be one tick off for nohz periods.
4818 */
4819
4820static void cpu_load_update_nohz(struct rq *this_rq,
4821 unsigned long curr_jiffies,
4822 unsigned long load)
be68a682
FW
4823{
4824 unsigned long pending_updates;
4825
4826 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
4827 if (pending_updates) {
4828 this_rq->last_load_update_tick = curr_jiffies;
4829 /*
4830 * In the regular NOHZ case, we were idle, this means load 0.
4831 * In the NOHZ_FULL case, we were non-idle, we should consider
4832 * its weighted load.
4833 */
1f41906a 4834 cpu_load_update(this_rq, load, pending_updates);
be68a682
FW
4835 }
4836}
4837
3289bdb4
PZ
4838/*
4839 * Called from nohz_idle_balance() to update the load ratings before doing the
4840 * idle balance.
4841 */
cee1afce 4842static void cpu_load_update_idle(struct rq *this_rq)
3289bdb4 4843{
3289bdb4
PZ
4844 /*
4845 * bail if there's load or we're actually up-to-date.
4846 */
be68a682 4847 if (weighted_cpuload(cpu_of(this_rq)))
3289bdb4
PZ
4848 return;
4849
1f41906a 4850 cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), 0);
3289bdb4
PZ
4851}
4852
4853/*
1f41906a
FW
4854 * Record CPU load on nohz entry so we know the tickless load to account
4855 * on nohz exit. cpu_load[0] happens then to be updated more frequently
4856 * than other cpu_load[idx] but it should be fine as cpu_load readers
4857 * shouldn't rely into synchronized cpu_load[*] updates.
3289bdb4 4858 */
1f41906a 4859void cpu_load_update_nohz_start(void)
3289bdb4
PZ
4860{
4861 struct rq *this_rq = this_rq();
1f41906a
FW
4862
4863 /*
4864 * This is all lockless but should be fine. If weighted_cpuload changes
4865 * concurrently we'll exit nohz. And cpu_load write can race with
4866 * cpu_load_update_idle() but both updater would be writing the same.
4867 */
4868 this_rq->cpu_load[0] = weighted_cpuload(cpu_of(this_rq));
4869}
4870
4871/*
4872 * Account the tickless load in the end of a nohz frame.
4873 */
4874void cpu_load_update_nohz_stop(void)
4875{
316c1608 4876 unsigned long curr_jiffies = READ_ONCE(jiffies);
1f41906a
FW
4877 struct rq *this_rq = this_rq();
4878 unsigned long load;
3289bdb4
PZ
4879
4880 if (curr_jiffies == this_rq->last_load_update_tick)
4881 return;
4882
1f41906a 4883 load = weighted_cpuload(cpu_of(this_rq));
3289bdb4 4884 raw_spin_lock(&this_rq->lock);
b52fad2d 4885 update_rq_clock(this_rq);
1f41906a 4886 cpu_load_update_nohz(this_rq, curr_jiffies, load);
3289bdb4
PZ
4887 raw_spin_unlock(&this_rq->lock);
4888}
1f41906a
FW
4889#else /* !CONFIG_NO_HZ_COMMON */
4890static inline void cpu_load_update_nohz(struct rq *this_rq,
4891 unsigned long curr_jiffies,
4892 unsigned long load) { }
4893#endif /* CONFIG_NO_HZ_COMMON */
4894
4895static void cpu_load_update_periodic(struct rq *this_rq, unsigned long load)
4896{
9fd81dd5 4897#ifdef CONFIG_NO_HZ_COMMON
1f41906a
FW
4898 /* See the mess around cpu_load_update_nohz(). */
4899 this_rq->last_load_update_tick = READ_ONCE(jiffies);
9fd81dd5 4900#endif
1f41906a
FW
4901 cpu_load_update(this_rq, load, 1);
4902}
3289bdb4
PZ
4903
4904/*
4905 * Called from scheduler_tick()
4906 */
cee1afce 4907void cpu_load_update_active(struct rq *this_rq)
3289bdb4 4908{
7ea241af 4909 unsigned long load = weighted_cpuload(cpu_of(this_rq));
1f41906a
FW
4910
4911 if (tick_nohz_tick_stopped())
4912 cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), load);
4913 else
4914 cpu_load_update_periodic(this_rq, load);
3289bdb4
PZ
4915}
4916
029632fb
PZ
4917/*
4918 * Return a low guess at the load of a migration-source cpu weighted
4919 * according to the scheduling class and "nice" value.
4920 *
4921 * We want to under-estimate the load of migration sources, to
4922 * balance conservatively.
4923 */
4924static unsigned long source_load(int cpu, int type)
4925{
4926 struct rq *rq = cpu_rq(cpu);
4927 unsigned long total = weighted_cpuload(cpu);
4928
4929 if (type == 0 || !sched_feat(LB_BIAS))
4930 return total;
4931
4932 return min(rq->cpu_load[type-1], total);
4933}
4934
4935/*
4936 * Return a high guess at the load of a migration-target cpu weighted
4937 * according to the scheduling class and "nice" value.
4938 */
4939static unsigned long target_load(int cpu, int type)
4940{
4941 struct rq *rq = cpu_rq(cpu);
4942 unsigned long total = weighted_cpuload(cpu);
4943
4944 if (type == 0 || !sched_feat(LB_BIAS))
4945 return total;
4946
4947 return max(rq->cpu_load[type-1], total);
4948}
4949
ced549fa 4950static unsigned long capacity_of(int cpu)
029632fb 4951{
ced549fa 4952 return cpu_rq(cpu)->cpu_capacity;
029632fb
PZ
4953}
4954
ca6d75e6
VG
4955static unsigned long capacity_orig_of(int cpu)
4956{
4957 return cpu_rq(cpu)->cpu_capacity_orig;
4958}
4959
029632fb
PZ
4960static unsigned long cpu_avg_load_per_task(int cpu)
4961{
4962 struct rq *rq = cpu_rq(cpu);
316c1608 4963 unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
7ea241af 4964 unsigned long load_avg = weighted_cpuload(cpu);
029632fb
PZ
4965
4966 if (nr_running)
b92486cb 4967 return load_avg / nr_running;
029632fb
PZ
4968
4969 return 0;
4970}
4971
bb3469ac 4972#ifdef CONFIG_FAIR_GROUP_SCHED
f5bfb7d9
PZ
4973/*
4974 * effective_load() calculates the load change as seen from the root_task_group
4975 *
4976 * Adding load to a group doesn't make a group heavier, but can cause movement
4977 * of group shares between cpus. Assuming the shares were perfectly aligned one
4978 * can calculate the shift in shares.
cf5f0acf
PZ
4979 *
4980 * Calculate the effective load difference if @wl is added (subtracted) to @tg
4981 * on this @cpu and results in a total addition (subtraction) of @wg to the
4982 * total group weight.
4983 *
4984 * Given a runqueue weight distribution (rw_i) we can compute a shares
4985 * distribution (s_i) using:
4986 *
4987 * s_i = rw_i / \Sum rw_j (1)
4988 *
4989 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
4990 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
4991 * shares distribution (s_i):
4992 *
4993 * rw_i = { 2, 4, 1, 0 }
4994 * s_i = { 2/7, 4/7, 1/7, 0 }
4995 *
4996 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
4997 * task used to run on and the CPU the waker is running on), we need to
4998 * compute the effect of waking a task on either CPU and, in case of a sync
4999 * wakeup, compute the effect of the current task going to sleep.
5000 *
5001 * So for a change of @wl to the local @cpu with an overall group weight change
5002 * of @wl we can compute the new shares distribution (s'_i) using:
5003 *
5004 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
5005 *
5006 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
5007 * differences in waking a task to CPU 0. The additional task changes the
5008 * weight and shares distributions like:
5009 *
5010 * rw'_i = { 3, 4, 1, 0 }
5011 * s'_i = { 3/8, 4/8, 1/8, 0 }
5012 *
5013 * We can then compute the difference in effective weight by using:
5014 *
5015 * dw_i = S * (s'_i - s_i) (3)
5016 *
5017 * Where 'S' is the group weight as seen by its parent.
5018 *
5019 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
5020 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
5021 * 4/7) times the weight of the group.
f5bfb7d9 5022 */
2069dd75 5023static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
bb3469ac 5024{
4be9daaa 5025 struct sched_entity *se = tg->se[cpu];
f1d239f7 5026
9722c2da 5027 if (!tg->parent) /* the trivial, non-cgroup case */
f1d239f7
PZ
5028 return wl;
5029
4be9daaa 5030 for_each_sched_entity(se) {
7dd49125
PZ
5031 struct cfs_rq *cfs_rq = se->my_q;
5032 long W, w = cfs_rq_load_avg(cfs_rq);
4be9daaa 5033
7dd49125 5034 tg = cfs_rq->tg;
bb3469ac 5035
cf5f0acf
PZ
5036 /*
5037 * W = @wg + \Sum rw_j
5038 */
7dd49125
PZ
5039 W = wg + atomic_long_read(&tg->load_avg);
5040
5041 /* Ensure \Sum rw_j >= rw_i */
5042 W -= cfs_rq->tg_load_avg_contrib;
5043 W += w;
4be9daaa 5044
cf5f0acf
PZ
5045 /*
5046 * w = rw_i + @wl
5047 */
7dd49125 5048 w += wl;
940959e9 5049
cf5f0acf
PZ
5050 /*
5051 * wl = S * s'_i; see (2)
5052 */
5053 if (W > 0 && w < W)
ab522e33 5054 wl = (w * (long)scale_load_down(tg->shares)) / W;
977dda7c 5055 else
ab522e33 5056 wl = scale_load_down(tg->shares);
940959e9 5057
cf5f0acf
PZ
5058 /*
5059 * Per the above, wl is the new se->load.weight value; since
5060 * those are clipped to [MIN_SHARES, ...) do so now. See
5061 * calc_cfs_shares().
5062 */
977dda7c
PT
5063 if (wl < MIN_SHARES)
5064 wl = MIN_SHARES;
cf5f0acf
PZ
5065
5066 /*
5067 * wl = dw_i = S * (s'_i - s_i); see (3)
5068 */
9d89c257 5069 wl -= se->avg.load_avg;
cf5f0acf
PZ
5070
5071 /*
5072 * Recursively apply this logic to all parent groups to compute
5073 * the final effective load change on the root group. Since
5074 * only the @tg group gets extra weight, all parent groups can
5075 * only redistribute existing shares. @wl is the shift in shares
5076 * resulting from this level per the above.
5077 */
4be9daaa 5078 wg = 0;
4be9daaa 5079 }
bb3469ac 5080
4be9daaa 5081 return wl;
bb3469ac
PZ
5082}
5083#else
4be9daaa 5084
58d081b5 5085static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
4be9daaa 5086{
83378269 5087 return wl;
bb3469ac 5088}
4be9daaa 5089
bb3469ac
PZ
5090#endif
5091
c58d25f3
PZ
5092static void record_wakee(struct task_struct *p)
5093{
5094 /*
5095 * Only decay a single time; tasks that have less then 1 wakeup per
5096 * jiffy will not have built up many flips.
5097 */
5098 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5099 current->wakee_flips >>= 1;
5100 current->wakee_flip_decay_ts = jiffies;
5101 }
5102
5103 if (current->last_wakee != p) {
5104 current->last_wakee = p;
5105 current->wakee_flips++;
5106 }
5107}
5108
63b0e9ed
MG
5109/*
5110 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
c58d25f3 5111 *
63b0e9ed 5112 * A waker of many should wake a different task than the one last awakened
c58d25f3
PZ
5113 * at a frequency roughly N times higher than one of its wakees.
5114 *
5115 * In order to determine whether we should let the load spread vs consolidating
5116 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
5117 * partner, and a factor of lls_size higher frequency in the other.
5118 *
5119 * With both conditions met, we can be relatively sure that the relationship is
5120 * non-monogamous, with partner count exceeding socket size.
5121 *
5122 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
5123 * whatever is irrelevant, spread criteria is apparent partner count exceeds
5124 * socket size.
63b0e9ed 5125 */
62470419
MW
5126static int wake_wide(struct task_struct *p)
5127{
63b0e9ed
MG
5128 unsigned int master = current->wakee_flips;
5129 unsigned int slave = p->wakee_flips;
7d9ffa89 5130 int factor = this_cpu_read(sd_llc_size);
62470419 5131
63b0e9ed
MG
5132 if (master < slave)
5133 swap(master, slave);
5134 if (slave < factor || master < slave * factor)
5135 return 0;
5136 return 1;
62470419
MW
5137}
5138
772bd008
MR
5139static int wake_affine(struct sched_domain *sd, struct task_struct *p,
5140 int prev_cpu, int sync)
098fb9db 5141{
e37b6a7b 5142 s64 this_load, load;
bd61c98f 5143 s64 this_eff_load, prev_eff_load;
772bd008 5144 int idx, this_cpu;
c88d5910 5145 struct task_group *tg;
83378269 5146 unsigned long weight;
b3137bc8 5147 int balanced;
098fb9db 5148
c88d5910
PZ
5149 idx = sd->wake_idx;
5150 this_cpu = smp_processor_id();
c88d5910
PZ
5151 load = source_load(prev_cpu, idx);
5152 this_load = target_load(this_cpu, idx);
098fb9db 5153
b3137bc8
MG
5154 /*
5155 * If sync wakeup then subtract the (maximum possible)
5156 * effect of the currently running task from the load
5157 * of the current CPU:
5158 */
83378269
PZ
5159 if (sync) {
5160 tg = task_group(current);
9d89c257 5161 weight = current->se.avg.load_avg;
83378269 5162
c88d5910 5163 this_load += effective_load(tg, this_cpu, -weight, -weight);
83378269
PZ
5164 load += effective_load(tg, prev_cpu, 0, -weight);
5165 }
b3137bc8 5166
83378269 5167 tg = task_group(p);
9d89c257 5168 weight = p->se.avg.load_avg;
b3137bc8 5169
71a29aa7
PZ
5170 /*
5171 * In low-load situations, where prev_cpu is idle and this_cpu is idle
c88d5910
PZ
5172 * due to the sync cause above having dropped this_load to 0, we'll
5173 * always have an imbalance, but there's really nothing you can do
5174 * about that, so that's good too.
71a29aa7
PZ
5175 *
5176 * Otherwise check if either cpus are near enough in load to allow this
5177 * task to be woken on this_cpu.
5178 */
bd61c98f
VG
5179 this_eff_load = 100;
5180 this_eff_load *= capacity_of(prev_cpu);
e51fd5e2 5181
bd61c98f
VG
5182 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
5183 prev_eff_load *= capacity_of(this_cpu);
e51fd5e2 5184
bd61c98f 5185 if (this_load > 0) {
e51fd5e2
PZ
5186 this_eff_load *= this_load +
5187 effective_load(tg, this_cpu, weight, weight);
5188
e51fd5e2 5189 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
bd61c98f 5190 }
e51fd5e2 5191
bd61c98f 5192 balanced = this_eff_load <= prev_eff_load;
098fb9db 5193
ae92882e 5194 schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
098fb9db 5195
05bfb65f
VG
5196 if (!balanced)
5197 return 0;
098fb9db 5198
ae92882e
JP
5199 schedstat_inc(sd->ttwu_move_affine);
5200 schedstat_inc(p->se.statistics.nr_wakeups_affine);
05bfb65f
VG
5201
5202 return 1;
098fb9db
IM
5203}
5204
aaee1203
PZ
5205/*
5206 * find_idlest_group finds and returns the least busy CPU group within the
5207 * domain.
5208 */
5209static struct sched_group *
78e7ed53 5210find_idlest_group(struct sched_domain *sd, struct task_struct *p,
c44f2a02 5211 int this_cpu, int sd_flag)
e7693a36 5212{
b3bd3de6 5213 struct sched_group *idlest = NULL, *group = sd->groups;
aaee1203 5214 unsigned long min_load = ULONG_MAX, this_load = 0;
c44f2a02 5215 int load_idx = sd->forkexec_idx;
aaee1203 5216 int imbalance = 100 + (sd->imbalance_pct-100)/2;
e7693a36 5217
c44f2a02
VG
5218 if (sd_flag & SD_BALANCE_WAKE)
5219 load_idx = sd->wake_idx;
5220
aaee1203
PZ
5221 do {
5222 unsigned long load, avg_load;
5223 int local_group;
5224 int i;
e7693a36 5225
aaee1203
PZ
5226 /* Skip over this group if it has no CPUs allowed */
5227 if (!cpumask_intersects(sched_group_cpus(group),
fa17b507 5228 tsk_cpus_allowed(p)))
aaee1203
PZ
5229 continue;
5230
5231 local_group = cpumask_test_cpu(this_cpu,
5232 sched_group_cpus(group));
5233
5234 /* Tally up the load of all CPUs in the group */
5235 avg_load = 0;
5236
5237 for_each_cpu(i, sched_group_cpus(group)) {
5238 /* Bias balancing toward cpus of our domain */
5239 if (local_group)
5240 load = source_load(i, load_idx);
5241 else
5242 load = target_load(i, load_idx);
5243
5244 avg_load += load;
5245 }
5246
63b2ca30 5247 /* Adjust by relative CPU capacity of the group */
ca8ce3d0 5248 avg_load = (avg_load * SCHED_CAPACITY_SCALE) / group->sgc->capacity;
aaee1203
PZ
5249
5250 if (local_group) {
5251 this_load = avg_load;
aaee1203
PZ
5252 } else if (avg_load < min_load) {
5253 min_load = avg_load;
5254 idlest = group;
5255 }
5256 } while (group = group->next, group != sd->groups);
5257
5258 if (!idlest || 100*this_load < imbalance*min_load)
5259 return NULL;
5260 return idlest;
5261}
5262
5263/*
5264 * find_idlest_cpu - find the idlest cpu among the cpus in group.
5265 */
5266static int
5267find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
5268{
5269 unsigned long load, min_load = ULONG_MAX;
83a0a96a
NP
5270 unsigned int min_exit_latency = UINT_MAX;
5271 u64 latest_idle_timestamp = 0;
5272 int least_loaded_cpu = this_cpu;
5273 int shallowest_idle_cpu = -1;
aaee1203
PZ
5274 int i;
5275
eaecf41f
MR
5276 /* Check if we have any choice: */
5277 if (group->group_weight == 1)
5278 return cpumask_first(sched_group_cpus(group));
5279
aaee1203 5280 /* Traverse only the allowed CPUs */
fa17b507 5281 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
83a0a96a
NP
5282 if (idle_cpu(i)) {
5283 struct rq *rq = cpu_rq(i);
5284 struct cpuidle_state *idle = idle_get_state(rq);
5285 if (idle && idle->exit_latency < min_exit_latency) {
5286 /*
5287 * We give priority to a CPU whose idle state
5288 * has the smallest exit latency irrespective
5289 * of any idle timestamp.
5290 */
5291 min_exit_latency = idle->exit_latency;
5292 latest_idle_timestamp = rq->idle_stamp;
5293 shallowest_idle_cpu = i;
5294 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
5295 rq->idle_stamp > latest_idle_timestamp) {
5296 /*
5297 * If equal or no active idle state, then
5298 * the most recently idled CPU might have
5299 * a warmer cache.
5300 */
5301 latest_idle_timestamp = rq->idle_stamp;
5302 shallowest_idle_cpu = i;
5303 }
9f96742a 5304 } else if (shallowest_idle_cpu == -1) {
83a0a96a
NP
5305 load = weighted_cpuload(i);
5306 if (load < min_load || (load == min_load && i == this_cpu)) {
5307 min_load = load;
5308 least_loaded_cpu = i;
5309 }
e7693a36
GH
5310 }
5311 }
5312
83a0a96a 5313 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
aaee1203 5314}
e7693a36 5315
a50bde51 5316/*
10e2f1ac
PZ
5317 * Implement a for_each_cpu() variant that starts the scan at a given cpu
5318 * (@start), and wraps around.
5319 *
5320 * This is used to scan for idle CPUs; such that not all CPUs looking for an
5321 * idle CPU find the same CPU. The down-side is that tasks tend to cycle
5322 * through the LLC domain.
5323 *
5324 * Especially tbench is found sensitive to this.
5325 */
5326
5327static int cpumask_next_wrap(int n, const struct cpumask *mask, int start, int *wrapped)
5328{
5329 int next;
5330
5331again:
5332 next = find_next_bit(cpumask_bits(mask), nr_cpumask_bits, n+1);
5333
5334 if (*wrapped) {
5335 if (next >= start)
5336 return nr_cpumask_bits;
5337 } else {
5338 if (next >= nr_cpumask_bits) {
5339 *wrapped = 1;
5340 n = -1;
5341 goto again;
5342 }
5343 }
5344
5345 return next;
5346}
5347
5348#define for_each_cpu_wrap(cpu, mask, start, wrap) \
5349 for ((wrap) = 0, (cpu) = (start)-1; \
5350 (cpu) = cpumask_next_wrap((cpu), (mask), (start), &(wrap)), \
5351 (cpu) < nr_cpumask_bits; )
5352
5353#ifdef CONFIG_SCHED_SMT
5354
5355static inline void set_idle_cores(int cpu, int val)
5356{
5357 struct sched_domain_shared *sds;
5358
5359 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
5360 if (sds)
5361 WRITE_ONCE(sds->has_idle_cores, val);
5362}
5363
5364static inline bool test_idle_cores(int cpu, bool def)
5365{
5366 struct sched_domain_shared *sds;
5367
5368 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
5369 if (sds)
5370 return READ_ONCE(sds->has_idle_cores);
5371
5372 return def;
5373}
5374
5375/*
5376 * Scans the local SMT mask to see if the entire core is idle, and records this
5377 * information in sd_llc_shared->has_idle_cores.
5378 *
5379 * Since SMT siblings share all cache levels, inspecting this limited remote
5380 * state should be fairly cheap.
5381 */
1b568f0a 5382void __update_idle_core(struct rq *rq)
10e2f1ac
PZ
5383{
5384 int core = cpu_of(rq);
5385 int cpu;
5386
5387 rcu_read_lock();
5388 if (test_idle_cores(core, true))
5389 goto unlock;
5390
5391 for_each_cpu(cpu, cpu_smt_mask(core)) {
5392 if (cpu == core)
5393 continue;
5394
5395 if (!idle_cpu(cpu))
5396 goto unlock;
5397 }
5398
5399 set_idle_cores(core, 1);
5400unlock:
5401 rcu_read_unlock();
5402}
5403
5404/*
5405 * Scan the entire LLC domain for idle cores; this dynamically switches off if
5406 * there are no idle cores left in the system; tracked through
5407 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
5408 */
5409static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
5410{
5411 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
5412 int core, cpu, wrap;
5413
1b568f0a
PZ
5414 if (!static_branch_likely(&sched_smt_present))
5415 return -1;
5416
10e2f1ac
PZ
5417 if (!test_idle_cores(target, false))
5418 return -1;
5419
5420 cpumask_and(cpus, sched_domain_span(sd), tsk_cpus_allowed(p));
5421
5422 for_each_cpu_wrap(core, cpus, target, wrap) {
5423 bool idle = true;
5424
5425 for_each_cpu(cpu, cpu_smt_mask(core)) {
5426 cpumask_clear_cpu(cpu, cpus);
5427 if (!idle_cpu(cpu))
5428 idle = false;
5429 }
5430
5431 if (idle)
5432 return core;
5433 }
5434
5435 /*
5436 * Failed to find an idle core; stop looking for one.
5437 */
5438 set_idle_cores(target, 0);
5439
5440 return -1;
5441}
5442
5443/*
5444 * Scan the local SMT mask for idle CPUs.
5445 */
5446static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
5447{
5448 int cpu;
5449
1b568f0a
PZ
5450 if (!static_branch_likely(&sched_smt_present))
5451 return -1;
5452
10e2f1ac
PZ
5453 for_each_cpu(cpu, cpu_smt_mask(target)) {
5454 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
5455 continue;
5456 if (idle_cpu(cpu))
5457 return cpu;
5458 }
5459
5460 return -1;
5461}
5462
5463#else /* CONFIG_SCHED_SMT */
5464
5465static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
5466{
5467 return -1;
5468}
5469
5470static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
5471{
5472 return -1;
5473}
5474
5475#endif /* CONFIG_SCHED_SMT */
5476
5477/*
5478 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
5479 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
5480 * average idle time for this rq (as found in rq->avg_idle).
a50bde51 5481 */
10e2f1ac
PZ
5482static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
5483{
9cfb38a7
WL
5484 struct sched_domain *this_sd;
5485 u64 avg_cost, avg_idle = this_rq()->avg_idle;
10e2f1ac
PZ
5486 u64 time, cost;
5487 s64 delta;
5488 int cpu, wrap;
5489
9cfb38a7
WL
5490 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
5491 if (!this_sd)
5492 return -1;
5493
5494 avg_cost = this_sd->avg_scan_cost;
5495
10e2f1ac
PZ
5496 /*
5497 * Due to large variance we need a large fuzz factor; hackbench in
5498 * particularly is sensitive here.
5499 */
5500 if ((avg_idle / 512) < avg_cost)
5501 return -1;
5502
5503 time = local_clock();
5504
5505 for_each_cpu_wrap(cpu, sched_domain_span(sd), target, wrap) {
5506 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
5507 continue;
5508 if (idle_cpu(cpu))
5509 break;
5510 }
5511
5512 time = local_clock() - time;
5513 cost = this_sd->avg_scan_cost;
5514 delta = (s64)(time - cost) / 8;
5515 this_sd->avg_scan_cost += delta;
5516
5517 return cpu;
5518}
5519
5520/*
5521 * Try and locate an idle core/thread in the LLC cache domain.
a50bde51 5522 */
772bd008 5523static int select_idle_sibling(struct task_struct *p, int prev, int target)
a50bde51 5524{
99bd5e2f 5525 struct sched_domain *sd;
10e2f1ac 5526 int i;
a50bde51 5527
e0a79f52
MG
5528 if (idle_cpu(target))
5529 return target;
99bd5e2f
SS
5530
5531 /*
10e2f1ac 5532 * If the previous cpu is cache affine and idle, don't be stupid.
99bd5e2f 5533 */
772bd008
MR
5534 if (prev != target && cpus_share_cache(prev, target) && idle_cpu(prev))
5535 return prev;
a50bde51 5536
518cd623 5537 sd = rcu_dereference(per_cpu(sd_llc, target));
10e2f1ac
PZ
5538 if (!sd)
5539 return target;
772bd008 5540
10e2f1ac
PZ
5541 i = select_idle_core(p, sd, target);
5542 if ((unsigned)i < nr_cpumask_bits)
5543 return i;
37407ea7 5544
10e2f1ac
PZ
5545 i = select_idle_cpu(p, sd, target);
5546 if ((unsigned)i < nr_cpumask_bits)
5547 return i;
5548
5549 i = select_idle_smt(p, sd, target);
5550 if ((unsigned)i < nr_cpumask_bits)
5551 return i;
970e1789 5552
a50bde51
PZ
5553 return target;
5554}
231678b7 5555
8bb5b00c 5556/*
9e91d61d 5557 * cpu_util returns the amount of capacity of a CPU that is used by CFS
8bb5b00c 5558 * tasks. The unit of the return value must be the one of capacity so we can
9e91d61d
DE
5559 * compare the utilization with the capacity of the CPU that is available for
5560 * CFS task (ie cpu_capacity).
231678b7
DE
5561 *
5562 * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
5563 * recent utilization of currently non-runnable tasks on a CPU. It represents
5564 * the amount of utilization of a CPU in the range [0..capacity_orig] where
5565 * capacity_orig is the cpu_capacity available at the highest frequency
5566 * (arch_scale_freq_capacity()).
5567 * The utilization of a CPU converges towards a sum equal to or less than the
5568 * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
5569 * the running time on this CPU scaled by capacity_curr.
5570 *
5571 * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
5572 * higher than capacity_orig because of unfortunate rounding in
5573 * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
5574 * the average stabilizes with the new running time. We need to check that the
5575 * utilization stays within the range of [0..capacity_orig] and cap it if
5576 * necessary. Without utilization capping, a group could be seen as overloaded
5577 * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
5578 * available capacity. We allow utilization to overshoot capacity_curr (but not
5579 * capacity_orig) as it useful for predicting the capacity required after task
5580 * migrations (scheduler-driven DVFS).
8bb5b00c 5581 */
9e91d61d 5582static int cpu_util(int cpu)
8bb5b00c 5583{
9e91d61d 5584 unsigned long util = cpu_rq(cpu)->cfs.avg.util_avg;
8bb5b00c
VG
5585 unsigned long capacity = capacity_orig_of(cpu);
5586
231678b7 5587 return (util >= capacity) ? capacity : util;
8bb5b00c 5588}
a50bde51 5589
3273163c
MR
5590static inline int task_util(struct task_struct *p)
5591{
5592 return p->se.avg.util_avg;
5593}
5594
104cb16d
MR
5595/*
5596 * cpu_util_wake: Compute cpu utilization with any contributions from
5597 * the waking task p removed.
5598 */
5599static int cpu_util_wake(int cpu, struct task_struct *p)
5600{
5601 unsigned long util, capacity;
5602
5603 /* Task has no contribution or is new */
5604 if (cpu != task_cpu(p) || !p->se.avg.last_update_time)
5605 return cpu_util(cpu);
5606
5607 capacity = capacity_orig_of(cpu);
5608 util = max_t(long, cpu_rq(cpu)->cfs.avg.util_avg - task_util(p), 0);
5609
5610 return (util >= capacity) ? capacity : util;
5611}
5612
3273163c
MR
5613/*
5614 * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
5615 * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
5616 *
5617 * In that case WAKE_AFFINE doesn't make sense and we'll let
5618 * BALANCE_WAKE sort things out.
5619 */
5620static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
5621{
5622 long min_cap, max_cap;
5623
5624 min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
5625 max_cap = cpu_rq(cpu)->rd->max_cpu_capacity;
5626
5627 /* Minimum capacity is close to max, no need to abort wake_affine */
5628 if (max_cap - min_cap < max_cap >> 3)
5629 return 0;
5630
104cb16d
MR
5631 /* Bring task utilization in sync with prev_cpu */
5632 sync_entity_load_avg(&p->se);
5633
3273163c
MR
5634 return min_cap * 1024 < task_util(p) * capacity_margin;
5635}
5636
aaee1203 5637/*
de91b9cb
MR
5638 * select_task_rq_fair: Select target runqueue for the waking task in domains
5639 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
5640 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
aaee1203 5641 *
de91b9cb
MR
5642 * Balances load by selecting the idlest cpu in the idlest group, or under
5643 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
aaee1203 5644 *
de91b9cb 5645 * Returns the target cpu number.
aaee1203
PZ
5646 *
5647 * preempt must be disabled.
5648 */
0017d735 5649static int
ac66f547 5650select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
aaee1203 5651{
29cd8bae 5652 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
c88d5910 5653 int cpu = smp_processor_id();
63b0e9ed 5654 int new_cpu = prev_cpu;
99bd5e2f 5655 int want_affine = 0;
5158f4e4 5656 int sync = wake_flags & WF_SYNC;
c88d5910 5657
c58d25f3
PZ
5658 if (sd_flag & SD_BALANCE_WAKE) {
5659 record_wakee(p);
3273163c
MR
5660 want_affine = !wake_wide(p) && !wake_cap(p, cpu, prev_cpu)
5661 && cpumask_test_cpu(cpu, tsk_cpus_allowed(p));
c58d25f3 5662 }
aaee1203 5663
dce840a0 5664 rcu_read_lock();
aaee1203 5665 for_each_domain(cpu, tmp) {
e4f42888 5666 if (!(tmp->flags & SD_LOAD_BALANCE))
63b0e9ed 5667 break;
e4f42888 5668
fe3bcfe1 5669 /*
99bd5e2f
SS
5670 * If both cpu and prev_cpu are part of this domain,
5671 * cpu is a valid SD_WAKE_AFFINE target.
fe3bcfe1 5672 */
99bd5e2f
SS
5673 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
5674 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
5675 affine_sd = tmp;
29cd8bae 5676 break;
f03542a7 5677 }
29cd8bae 5678
f03542a7 5679 if (tmp->flags & sd_flag)
29cd8bae 5680 sd = tmp;
63b0e9ed
MG
5681 else if (!want_affine)
5682 break;
29cd8bae
PZ
5683 }
5684
63b0e9ed
MG
5685 if (affine_sd) {
5686 sd = NULL; /* Prefer wake_affine over balance flags */
772bd008 5687 if (cpu != prev_cpu && wake_affine(affine_sd, p, prev_cpu, sync))
63b0e9ed 5688 new_cpu = cpu;
8b911acd 5689 }
e7693a36 5690
63b0e9ed
MG
5691 if (!sd) {
5692 if (sd_flag & SD_BALANCE_WAKE) /* XXX always ? */
772bd008 5693 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
63b0e9ed
MG
5694
5695 } else while (sd) {
aaee1203 5696 struct sched_group *group;
c88d5910 5697 int weight;
098fb9db 5698
0763a660 5699 if (!(sd->flags & sd_flag)) {
aaee1203
PZ
5700 sd = sd->child;
5701 continue;
5702 }
098fb9db 5703
c44f2a02 5704 group = find_idlest_group(sd, p, cpu, sd_flag);
aaee1203
PZ
5705 if (!group) {
5706 sd = sd->child;
5707 continue;
5708 }
4ae7d5ce 5709
d7c33c49 5710 new_cpu = find_idlest_cpu(group, p, cpu);
aaee1203
PZ
5711 if (new_cpu == -1 || new_cpu == cpu) {
5712 /* Now try balancing at a lower domain level of cpu */
5713 sd = sd->child;
5714 continue;
e7693a36 5715 }
aaee1203
PZ
5716
5717 /* Now try balancing at a lower domain level of new_cpu */
5718 cpu = new_cpu;
669c55e9 5719 weight = sd->span_weight;
aaee1203
PZ
5720 sd = NULL;
5721 for_each_domain(cpu, tmp) {
669c55e9 5722 if (weight <= tmp->span_weight)
aaee1203 5723 break;
0763a660 5724 if (tmp->flags & sd_flag)
aaee1203
PZ
5725 sd = tmp;
5726 }
5727 /* while loop will break here if sd == NULL */
e7693a36 5728 }
dce840a0 5729 rcu_read_unlock();
e7693a36 5730
c88d5910 5731 return new_cpu;
e7693a36 5732}
0a74bef8
PT
5733
5734/*
5735 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
5736 * cfs_rq_of(p) references at time of call are still valid and identify the
525628c7 5737 * previous cpu. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
0a74bef8 5738 */
5a4fd036 5739static void migrate_task_rq_fair(struct task_struct *p)
0a74bef8 5740{
59efa0ba
PZ
5741 /*
5742 * As blocked tasks retain absolute vruntime the migration needs to
5743 * deal with this by subtracting the old and adding the new
5744 * min_vruntime -- the latter is done by enqueue_entity() when placing
5745 * the task on the new runqueue.
5746 */
5747 if (p->state == TASK_WAKING) {
5748 struct sched_entity *se = &p->se;
5749 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5750 u64 min_vruntime;
5751
5752#ifndef CONFIG_64BIT
5753 u64 min_vruntime_copy;
5754
5755 do {
5756 min_vruntime_copy = cfs_rq->min_vruntime_copy;
5757 smp_rmb();
5758 min_vruntime = cfs_rq->min_vruntime;
5759 } while (min_vruntime != min_vruntime_copy);
5760#else
5761 min_vruntime = cfs_rq->min_vruntime;
5762#endif
5763
5764 se->vruntime -= min_vruntime;
5765 }
5766
aff3e498 5767 /*
9d89c257
YD
5768 * We are supposed to update the task to "current" time, then its up to date
5769 * and ready to go to new CPU/cfs_rq. But we have difficulty in getting
5770 * what current time is, so simply throw away the out-of-date time. This
5771 * will result in the wakee task is less decayed, but giving the wakee more
5772 * load sounds not bad.
aff3e498 5773 */
9d89c257
YD
5774 remove_entity_load_avg(&p->se);
5775
5776 /* Tell new CPU we are migrated */
5777 p->se.avg.last_update_time = 0;
3944a927
BS
5778
5779 /* We have migrated, no longer consider this task hot */
9d89c257 5780 p->se.exec_start = 0;
0a74bef8 5781}
12695578
YD
5782
5783static void task_dead_fair(struct task_struct *p)
5784{
5785 remove_entity_load_avg(&p->se);
5786}
e7693a36
GH
5787#endif /* CONFIG_SMP */
5788
e52fb7c0
PZ
5789static unsigned long
5790wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
0bbd3336
PZ
5791{
5792 unsigned long gran = sysctl_sched_wakeup_granularity;
5793
5794 /*
e52fb7c0
PZ
5795 * Since its curr running now, convert the gran from real-time
5796 * to virtual-time in his units.
13814d42
MG
5797 *
5798 * By using 'se' instead of 'curr' we penalize light tasks, so
5799 * they get preempted easier. That is, if 'se' < 'curr' then
5800 * the resulting gran will be larger, therefore penalizing the
5801 * lighter, if otoh 'se' > 'curr' then the resulting gran will
5802 * be smaller, again penalizing the lighter task.
5803 *
5804 * This is especially important for buddies when the leftmost
5805 * task is higher priority than the buddy.
0bbd3336 5806 */
f4ad9bd2 5807 return calc_delta_fair(gran, se);
0bbd3336
PZ
5808}
5809
464b7527
PZ
5810/*
5811 * Should 'se' preempt 'curr'.
5812 *
5813 * |s1
5814 * |s2
5815 * |s3
5816 * g
5817 * |<--->|c
5818 *
5819 * w(c, s1) = -1
5820 * w(c, s2) = 0
5821 * w(c, s3) = 1
5822 *
5823 */
5824static int
5825wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
5826{
5827 s64 gran, vdiff = curr->vruntime - se->vruntime;
5828
5829 if (vdiff <= 0)
5830 return -1;
5831
e52fb7c0 5832 gran = wakeup_gran(curr, se);
464b7527
PZ
5833 if (vdiff > gran)
5834 return 1;
5835
5836 return 0;
5837}
5838
02479099
PZ
5839static void set_last_buddy(struct sched_entity *se)
5840{
69c80f3e
VP
5841 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
5842 return;
5843
5844 for_each_sched_entity(se)
5845 cfs_rq_of(se)->last = se;
02479099
PZ
5846}
5847
5848static void set_next_buddy(struct sched_entity *se)
5849{
69c80f3e
VP
5850 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
5851 return;
5852
5853 for_each_sched_entity(se)
5854 cfs_rq_of(se)->next = se;
02479099
PZ
5855}
5856
ac53db59
RR
5857static void set_skip_buddy(struct sched_entity *se)
5858{
69c80f3e
VP
5859 for_each_sched_entity(se)
5860 cfs_rq_of(se)->skip = se;
ac53db59
RR
5861}
5862
bf0f6f24
IM
5863/*
5864 * Preempt the current task with a newly woken task if needed:
5865 */
5a9b86f6 5866static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
bf0f6f24
IM
5867{
5868 struct task_struct *curr = rq->curr;
8651a86c 5869 struct sched_entity *se = &curr->se, *pse = &p->se;
03e89e45 5870 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
f685ceac 5871 int scale = cfs_rq->nr_running >= sched_nr_latency;
2f36825b 5872 int next_buddy_marked = 0;
bf0f6f24 5873
4ae7d5ce
IM
5874 if (unlikely(se == pse))
5875 return;
5876
5238cdd3 5877 /*
163122b7 5878 * This is possible from callers such as attach_tasks(), in which we
5238cdd3
PT
5879 * unconditionally check_prempt_curr() after an enqueue (which may have
5880 * lead to a throttle). This both saves work and prevents false
5881 * next-buddy nomination below.
5882 */
5883 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
5884 return;
5885
2f36825b 5886 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
3cb63d52 5887 set_next_buddy(pse);
2f36825b
VP
5888 next_buddy_marked = 1;
5889 }
57fdc26d 5890
aec0a514
BR
5891 /*
5892 * We can come here with TIF_NEED_RESCHED already set from new task
5893 * wake up path.
5238cdd3
PT
5894 *
5895 * Note: this also catches the edge-case of curr being in a throttled
5896 * group (e.g. via set_curr_task), since update_curr() (in the
5897 * enqueue of curr) will have resulted in resched being set. This
5898 * prevents us from potentially nominating it as a false LAST_BUDDY
5899 * below.
aec0a514
BR
5900 */
5901 if (test_tsk_need_resched(curr))
5902 return;
5903
a2f5c9ab
DH
5904 /* Idle tasks are by definition preempted by non-idle tasks. */
5905 if (unlikely(curr->policy == SCHED_IDLE) &&
5906 likely(p->policy != SCHED_IDLE))
5907 goto preempt;
5908
91c234b4 5909 /*
a2f5c9ab
DH
5910 * Batch and idle tasks do not preempt non-idle tasks (their preemption
5911 * is driven by the tick):
91c234b4 5912 */
8ed92e51 5913 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
91c234b4 5914 return;
bf0f6f24 5915
464b7527 5916 find_matching_se(&se, &pse);
9bbd7374 5917 update_curr(cfs_rq_of(se));
002f128b 5918 BUG_ON(!pse);
2f36825b
VP
5919 if (wakeup_preempt_entity(se, pse) == 1) {
5920 /*
5921 * Bias pick_next to pick the sched entity that is
5922 * triggering this preemption.
5923 */
5924 if (!next_buddy_marked)
5925 set_next_buddy(pse);
3a7e73a2 5926 goto preempt;
2f36825b 5927 }
464b7527 5928
3a7e73a2 5929 return;
a65ac745 5930
3a7e73a2 5931preempt:
8875125e 5932 resched_curr(rq);
3a7e73a2
PZ
5933 /*
5934 * Only set the backward buddy when the current task is still
5935 * on the rq. This can happen when a wakeup gets interleaved
5936 * with schedule on the ->pre_schedule() or idle_balance()
5937 * point, either of which can * drop the rq lock.
5938 *
5939 * Also, during early boot the idle thread is in the fair class,
5940 * for obvious reasons its a bad idea to schedule back to it.
5941 */
5942 if (unlikely(!se->on_rq || curr == rq->idle))
5943 return;
5944
5945 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
5946 set_last_buddy(se);
bf0f6f24
IM
5947}
5948
606dba2e 5949static struct task_struct *
e7904a28 5950pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
bf0f6f24
IM
5951{
5952 struct cfs_rq *cfs_rq = &rq->cfs;
5953 struct sched_entity *se;
678d5718 5954 struct task_struct *p;
37e117c0 5955 int new_tasks;
678d5718 5956
6e83125c 5957again:
678d5718
PZ
5958#ifdef CONFIG_FAIR_GROUP_SCHED
5959 if (!cfs_rq->nr_running)
38033c37 5960 goto idle;
678d5718 5961
3f1d2a31 5962 if (prev->sched_class != &fair_sched_class)
678d5718
PZ
5963 goto simple;
5964
5965 /*
5966 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
5967 * likely that a next task is from the same cgroup as the current.
5968 *
5969 * Therefore attempt to avoid putting and setting the entire cgroup
5970 * hierarchy, only change the part that actually changes.
5971 */
5972
5973 do {
5974 struct sched_entity *curr = cfs_rq->curr;
5975
5976 /*
5977 * Since we got here without doing put_prev_entity() we also
5978 * have to consider cfs_rq->curr. If it is still a runnable
5979 * entity, update_curr() will update its vruntime, otherwise
5980 * forget we've ever seen it.
5981 */
54d27365
BS
5982 if (curr) {
5983 if (curr->on_rq)
5984 update_curr(cfs_rq);
5985 else
5986 curr = NULL;
678d5718 5987
54d27365
BS
5988 /*
5989 * This call to check_cfs_rq_runtime() will do the
5990 * throttle and dequeue its entity in the parent(s).
5991 * Therefore the 'simple' nr_running test will indeed
5992 * be correct.
5993 */
5994 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
5995 goto simple;
5996 }
678d5718
PZ
5997
5998 se = pick_next_entity(cfs_rq, curr);
5999 cfs_rq = group_cfs_rq(se);
6000 } while (cfs_rq);
6001
6002 p = task_of(se);
6003
6004 /*
6005 * Since we haven't yet done put_prev_entity and if the selected task
6006 * is a different task than we started out with, try and touch the
6007 * least amount of cfs_rqs.
6008 */
6009 if (prev != p) {
6010 struct sched_entity *pse = &prev->se;
6011
6012 while (!(cfs_rq = is_same_group(se, pse))) {
6013 int se_depth = se->depth;
6014 int pse_depth = pse->depth;
6015
6016 if (se_depth <= pse_depth) {
6017 put_prev_entity(cfs_rq_of(pse), pse);
6018 pse = parent_entity(pse);
6019 }
6020 if (se_depth >= pse_depth) {
6021 set_next_entity(cfs_rq_of(se), se);
6022 se = parent_entity(se);
6023 }
6024 }
6025
6026 put_prev_entity(cfs_rq, pse);
6027 set_next_entity(cfs_rq, se);
6028 }
6029
6030 if (hrtick_enabled(rq))
6031 hrtick_start_fair(rq, p);
6032
6033 return p;
6034simple:
6035 cfs_rq = &rq->cfs;
6036#endif
bf0f6f24 6037
36ace27e 6038 if (!cfs_rq->nr_running)
38033c37 6039 goto idle;
bf0f6f24 6040
3f1d2a31 6041 put_prev_task(rq, prev);
606dba2e 6042
bf0f6f24 6043 do {
678d5718 6044 se = pick_next_entity(cfs_rq, NULL);
f4b6755f 6045 set_next_entity(cfs_rq, se);
bf0f6f24
IM
6046 cfs_rq = group_cfs_rq(se);
6047 } while (cfs_rq);
6048
8f4d37ec 6049 p = task_of(se);
678d5718 6050
b39e66ea
MG
6051 if (hrtick_enabled(rq))
6052 hrtick_start_fair(rq, p);
8f4d37ec
PZ
6053
6054 return p;
38033c37
PZ
6055
6056idle:
cbce1a68
PZ
6057 /*
6058 * This is OK, because current is on_cpu, which avoids it being picked
6059 * for load-balance and preemption/IRQs are still disabled avoiding
6060 * further scheduler activity on it and we're being very careful to
6061 * re-start the picking loop.
6062 */
e7904a28 6063 lockdep_unpin_lock(&rq->lock, cookie);
e4aa358b 6064 new_tasks = idle_balance(rq);
e7904a28 6065 lockdep_repin_lock(&rq->lock, cookie);
37e117c0
PZ
6066 /*
6067 * Because idle_balance() releases (and re-acquires) rq->lock, it is
6068 * possible for any higher priority task to appear. In that case we
6069 * must re-start the pick_next_entity() loop.
6070 */
e4aa358b 6071 if (new_tasks < 0)
37e117c0
PZ
6072 return RETRY_TASK;
6073
e4aa358b 6074 if (new_tasks > 0)
38033c37 6075 goto again;
38033c37
PZ
6076
6077 return NULL;
bf0f6f24
IM
6078}
6079
6080/*
6081 * Account for a descheduled task:
6082 */
31ee529c 6083static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
bf0f6f24
IM
6084{
6085 struct sched_entity *se = &prev->se;
6086 struct cfs_rq *cfs_rq;
6087
6088 for_each_sched_entity(se) {
6089 cfs_rq = cfs_rq_of(se);
ab6cde26 6090 put_prev_entity(cfs_rq, se);
bf0f6f24
IM
6091 }
6092}
6093
ac53db59
RR
6094/*
6095 * sched_yield() is very simple
6096 *
6097 * The magic of dealing with the ->skip buddy is in pick_next_entity.
6098 */
6099static void yield_task_fair(struct rq *rq)
6100{
6101 struct task_struct *curr = rq->curr;
6102 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
6103 struct sched_entity *se = &curr->se;
6104
6105 /*
6106 * Are we the only task in the tree?
6107 */
6108 if (unlikely(rq->nr_running == 1))
6109 return;
6110
6111 clear_buddies(cfs_rq, se);
6112
6113 if (curr->policy != SCHED_BATCH) {
6114 update_rq_clock(rq);
6115 /*
6116 * Update run-time statistics of the 'current'.
6117 */
6118 update_curr(cfs_rq);
916671c0
MG
6119 /*
6120 * Tell update_rq_clock() that we've just updated,
6121 * so we don't do microscopic update in schedule()
6122 * and double the fastpath cost.
6123 */
9edfbfed 6124 rq_clock_skip_update(rq, true);
ac53db59
RR
6125 }
6126
6127 set_skip_buddy(se);
6128}
6129
d95f4122
MG
6130static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
6131{
6132 struct sched_entity *se = &p->se;
6133
5238cdd3
PT
6134 /* throttled hierarchies are not runnable */
6135 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
d95f4122
MG
6136 return false;
6137
6138 /* Tell the scheduler that we'd really like pse to run next. */
6139 set_next_buddy(se);
6140
d95f4122
MG
6141 yield_task_fair(rq);
6142
6143 return true;
6144}
6145
681f3e68 6146#ifdef CONFIG_SMP
bf0f6f24 6147/**************************************************
e9c84cb8
PZ
6148 * Fair scheduling class load-balancing methods.
6149 *
6150 * BASICS
6151 *
6152 * The purpose of load-balancing is to achieve the same basic fairness the
6153 * per-cpu scheduler provides, namely provide a proportional amount of compute
6154 * time to each task. This is expressed in the following equation:
6155 *
6156 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
6157 *
6158 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
6159 * W_i,0 is defined as:
6160 *
6161 * W_i,0 = \Sum_j w_i,j (2)
6162 *
6163 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
1c3de5e1 6164 * is derived from the nice value as per sched_prio_to_weight[].
e9c84cb8
PZ
6165 *
6166 * The weight average is an exponential decay average of the instantaneous
6167 * weight:
6168 *
6169 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
6170 *
ced549fa 6171 * C_i is the compute capacity of cpu i, typically it is the
e9c84cb8
PZ
6172 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
6173 * can also include other factors [XXX].
6174 *
6175 * To achieve this balance we define a measure of imbalance which follows
6176 * directly from (1):
6177 *
ced549fa 6178 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
e9c84cb8
PZ
6179 *
6180 * We them move tasks around to minimize the imbalance. In the continuous
6181 * function space it is obvious this converges, in the discrete case we get
6182 * a few fun cases generally called infeasible weight scenarios.
6183 *
6184 * [XXX expand on:
6185 * - infeasible weights;
6186 * - local vs global optima in the discrete case. ]
6187 *
6188 *
6189 * SCHED DOMAINS
6190 *
6191 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
6192 * for all i,j solution, we create a tree of cpus that follows the hardware
6193 * topology where each level pairs two lower groups (or better). This results
6194 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
6195 * tree to only the first of the previous level and we decrease the frequency
6196 * of load-balance at each level inv. proportional to the number of cpus in
6197 * the groups.
6198 *
6199 * This yields:
6200 *
6201 * log_2 n 1 n
6202 * \Sum { --- * --- * 2^i } = O(n) (5)
6203 * i = 0 2^i 2^i
6204 * `- size of each group
6205 * | | `- number of cpus doing load-balance
6206 * | `- freq
6207 * `- sum over all levels
6208 *
6209 * Coupled with a limit on how many tasks we can migrate every balance pass,
6210 * this makes (5) the runtime complexity of the balancer.
6211 *
6212 * An important property here is that each CPU is still (indirectly) connected
6213 * to every other cpu in at most O(log n) steps:
6214 *
6215 * The adjacency matrix of the resulting graph is given by:
6216 *
97a7142f 6217 * log_2 n
e9c84cb8
PZ
6218 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
6219 * k = 0
6220 *
6221 * And you'll find that:
6222 *
6223 * A^(log_2 n)_i,j != 0 for all i,j (7)
6224 *
6225 * Showing there's indeed a path between every cpu in at most O(log n) steps.
6226 * The task movement gives a factor of O(m), giving a convergence complexity
6227 * of:
6228 *
6229 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
6230 *
6231 *
6232 * WORK CONSERVING
6233 *
6234 * In order to avoid CPUs going idle while there's still work to do, new idle
6235 * balancing is more aggressive and has the newly idle cpu iterate up the domain
6236 * tree itself instead of relying on other CPUs to bring it work.
6237 *
6238 * This adds some complexity to both (5) and (8) but it reduces the total idle
6239 * time.
6240 *
6241 * [XXX more?]
6242 *
6243 *
6244 * CGROUPS
6245 *
6246 * Cgroups make a horror show out of (2), instead of a simple sum we get:
6247 *
6248 * s_k,i
6249 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
6250 * S_k
6251 *
6252 * Where
6253 *
6254 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
6255 *
6256 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
6257 *
6258 * The big problem is S_k, its a global sum needed to compute a local (W_i)
6259 * property.
6260 *
6261 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
6262 * rewrite all of this once again.]
97a7142f 6263 */
bf0f6f24 6264
ed387b78
HS
6265static unsigned long __read_mostly max_load_balance_interval = HZ/10;
6266
0ec8aa00
PZ
6267enum fbq_type { regular, remote, all };
6268
ddcdf6e7 6269#define LBF_ALL_PINNED 0x01
367456c7 6270#define LBF_NEED_BREAK 0x02
6263322c
PZ
6271#define LBF_DST_PINNED 0x04
6272#define LBF_SOME_PINNED 0x08
ddcdf6e7
PZ
6273
6274struct lb_env {
6275 struct sched_domain *sd;
6276
ddcdf6e7 6277 struct rq *src_rq;
85c1e7da 6278 int src_cpu;
ddcdf6e7
PZ
6279
6280 int dst_cpu;
6281 struct rq *dst_rq;
6282
88b8dac0
SV
6283 struct cpumask *dst_grpmask;
6284 int new_dst_cpu;
ddcdf6e7 6285 enum cpu_idle_type idle;
bd939f45 6286 long imbalance;
b9403130
MW
6287 /* The set of CPUs under consideration for load-balancing */
6288 struct cpumask *cpus;
6289
ddcdf6e7 6290 unsigned int flags;
367456c7
PZ
6291
6292 unsigned int loop;
6293 unsigned int loop_break;
6294 unsigned int loop_max;
0ec8aa00
PZ
6295
6296 enum fbq_type fbq_type;
163122b7 6297 struct list_head tasks;
ddcdf6e7
PZ
6298};
6299
029632fb
PZ
6300/*
6301 * Is this task likely cache-hot:
6302 */
5d5e2b1b 6303static int task_hot(struct task_struct *p, struct lb_env *env)
029632fb
PZ
6304{
6305 s64 delta;
6306
e5673f28
KT
6307 lockdep_assert_held(&env->src_rq->lock);
6308
029632fb
PZ
6309 if (p->sched_class != &fair_sched_class)
6310 return 0;
6311
6312 if (unlikely(p->policy == SCHED_IDLE))
6313 return 0;
6314
6315 /*
6316 * Buddy candidates are cache hot:
6317 */
5d5e2b1b 6318 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
029632fb
PZ
6319 (&p->se == cfs_rq_of(&p->se)->next ||
6320 &p->se == cfs_rq_of(&p->se)->last))
6321 return 1;
6322
6323 if (sysctl_sched_migration_cost == -1)
6324 return 1;
6325 if (sysctl_sched_migration_cost == 0)
6326 return 0;
6327
5d5e2b1b 6328 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
029632fb
PZ
6329
6330 return delta < (s64)sysctl_sched_migration_cost;
6331}
6332
3a7053b3 6333#ifdef CONFIG_NUMA_BALANCING
c1ceac62 6334/*
2a1ed24c
SD
6335 * Returns 1, if task migration degrades locality
6336 * Returns 0, if task migration improves locality i.e migration preferred.
6337 * Returns -1, if task migration is not affected by locality.
c1ceac62 6338 */
2a1ed24c 6339static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
3a7053b3 6340{
b1ad065e 6341 struct numa_group *numa_group = rcu_dereference(p->numa_group);
c1ceac62 6342 unsigned long src_faults, dst_faults;
3a7053b3
MG
6343 int src_nid, dst_nid;
6344
2a595721 6345 if (!static_branch_likely(&sched_numa_balancing))
2a1ed24c
SD
6346 return -1;
6347
c3b9bc5b 6348 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
2a1ed24c 6349 return -1;
7a0f3083
MG
6350
6351 src_nid = cpu_to_node(env->src_cpu);
6352 dst_nid = cpu_to_node(env->dst_cpu);
6353
83e1d2cd 6354 if (src_nid == dst_nid)
2a1ed24c 6355 return -1;
7a0f3083 6356
2a1ed24c
SD
6357 /* Migrating away from the preferred node is always bad. */
6358 if (src_nid == p->numa_preferred_nid) {
6359 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
6360 return 1;
6361 else
6362 return -1;
6363 }
b1ad065e 6364
c1ceac62
RR
6365 /* Encourage migration to the preferred node. */
6366 if (dst_nid == p->numa_preferred_nid)
2a1ed24c 6367 return 0;
b1ad065e 6368
c1ceac62
RR
6369 if (numa_group) {
6370 src_faults = group_faults(p, src_nid);
6371 dst_faults = group_faults(p, dst_nid);
6372 } else {
6373 src_faults = task_faults(p, src_nid);
6374 dst_faults = task_faults(p, dst_nid);
b1ad065e
RR
6375 }
6376
c1ceac62 6377 return dst_faults < src_faults;
7a0f3083
MG
6378}
6379
3a7053b3 6380#else
2a1ed24c 6381static inline int migrate_degrades_locality(struct task_struct *p,
3a7053b3
MG
6382 struct lb_env *env)
6383{
2a1ed24c 6384 return -1;
7a0f3083 6385}
3a7053b3
MG
6386#endif
6387
1e3c88bd
PZ
6388/*
6389 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
6390 */
6391static
8e45cb54 6392int can_migrate_task(struct task_struct *p, struct lb_env *env)
1e3c88bd 6393{
2a1ed24c 6394 int tsk_cache_hot;
e5673f28
KT
6395
6396 lockdep_assert_held(&env->src_rq->lock);
6397
1e3c88bd
PZ
6398 /*
6399 * We do not migrate tasks that are:
d3198084 6400 * 1) throttled_lb_pair, or
1e3c88bd 6401 * 2) cannot be migrated to this CPU due to cpus_allowed, or
d3198084
JK
6402 * 3) running (obviously), or
6403 * 4) are cache-hot on their current CPU.
1e3c88bd 6404 */
d3198084
JK
6405 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
6406 return 0;
6407
ddcdf6e7 6408 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
e02e60c1 6409 int cpu;
88b8dac0 6410
ae92882e 6411 schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
88b8dac0 6412
6263322c
PZ
6413 env->flags |= LBF_SOME_PINNED;
6414
88b8dac0
SV
6415 /*
6416 * Remember if this task can be migrated to any other cpu in
6417 * our sched_group. We may want to revisit it if we couldn't
6418 * meet load balance goals by pulling other tasks on src_cpu.
6419 *
6420 * Also avoid computing new_dst_cpu if we have already computed
6421 * one in current iteration.
6422 */
6263322c 6423 if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
88b8dac0
SV
6424 return 0;
6425
e02e60c1
JK
6426 /* Prevent to re-select dst_cpu via env's cpus */
6427 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
6428 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
6263322c 6429 env->flags |= LBF_DST_PINNED;
e02e60c1
JK
6430 env->new_dst_cpu = cpu;
6431 break;
6432 }
88b8dac0 6433 }
e02e60c1 6434
1e3c88bd
PZ
6435 return 0;
6436 }
88b8dac0
SV
6437
6438 /* Record that we found atleast one task that could run on dst_cpu */
8e45cb54 6439 env->flags &= ~LBF_ALL_PINNED;
1e3c88bd 6440
ddcdf6e7 6441 if (task_running(env->src_rq, p)) {
ae92882e 6442 schedstat_inc(p->se.statistics.nr_failed_migrations_running);
1e3c88bd
PZ
6443 return 0;
6444 }
6445
6446 /*
6447 * Aggressive migration if:
3a7053b3
MG
6448 * 1) destination numa is preferred
6449 * 2) task is cache cold, or
6450 * 3) too many balance attempts have failed.
1e3c88bd 6451 */
2a1ed24c
SD
6452 tsk_cache_hot = migrate_degrades_locality(p, env);
6453 if (tsk_cache_hot == -1)
6454 tsk_cache_hot = task_hot(p, env);
3a7053b3 6455
2a1ed24c 6456 if (tsk_cache_hot <= 0 ||
7a96c231 6457 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
2a1ed24c 6458 if (tsk_cache_hot == 1) {
ae92882e
JP
6459 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
6460 schedstat_inc(p->se.statistics.nr_forced_migrations);
3a7053b3 6461 }
1e3c88bd
PZ
6462 return 1;
6463 }
6464
ae92882e 6465 schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
4e2dcb73 6466 return 0;
1e3c88bd
PZ
6467}
6468
897c395f 6469/*
163122b7
KT
6470 * detach_task() -- detach the task for the migration specified in env
6471 */
6472static void detach_task(struct task_struct *p, struct lb_env *env)
6473{
6474 lockdep_assert_held(&env->src_rq->lock);
6475
163122b7 6476 p->on_rq = TASK_ON_RQ_MIGRATING;
3ea94de1 6477 deactivate_task(env->src_rq, p, 0);
163122b7
KT
6478 set_task_cpu(p, env->dst_cpu);
6479}
6480
897c395f 6481/*
e5673f28 6482 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
897c395f 6483 * part of active balancing operations within "domain".
897c395f 6484 *
e5673f28 6485 * Returns a task if successful and NULL otherwise.
897c395f 6486 */
e5673f28 6487static struct task_struct *detach_one_task(struct lb_env *env)
897c395f
PZ
6488{
6489 struct task_struct *p, *n;
897c395f 6490
e5673f28
KT
6491 lockdep_assert_held(&env->src_rq->lock);
6492
367456c7 6493 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
367456c7
PZ
6494 if (!can_migrate_task(p, env))
6495 continue;
897c395f 6496
163122b7 6497 detach_task(p, env);
e5673f28 6498
367456c7 6499 /*
e5673f28 6500 * Right now, this is only the second place where
163122b7 6501 * lb_gained[env->idle] is updated (other is detach_tasks)
e5673f28 6502 * so we can safely collect stats here rather than
163122b7 6503 * inside detach_tasks().
367456c7 6504 */
ae92882e 6505 schedstat_inc(env->sd->lb_gained[env->idle]);
e5673f28 6506 return p;
897c395f 6507 }
e5673f28 6508 return NULL;
897c395f
PZ
6509}
6510
eb95308e
PZ
6511static const unsigned int sched_nr_migrate_break = 32;
6512
5d6523eb 6513/*
163122b7
KT
6514 * detach_tasks() -- tries to detach up to imbalance weighted load from
6515 * busiest_rq, as part of a balancing operation within domain "sd".
5d6523eb 6516 *
163122b7 6517 * Returns number of detached tasks if successful and 0 otherwise.
5d6523eb 6518 */
163122b7 6519static int detach_tasks(struct lb_env *env)
1e3c88bd 6520{
5d6523eb
PZ
6521 struct list_head *tasks = &env->src_rq->cfs_tasks;
6522 struct task_struct *p;
367456c7 6523 unsigned long load;
163122b7
KT
6524 int detached = 0;
6525
6526 lockdep_assert_held(&env->src_rq->lock);
1e3c88bd 6527
bd939f45 6528 if (env->imbalance <= 0)
5d6523eb 6529 return 0;
1e3c88bd 6530
5d6523eb 6531 while (!list_empty(tasks)) {
985d3a4c
YD
6532 /*
6533 * We don't want to steal all, otherwise we may be treated likewise,
6534 * which could at worst lead to a livelock crash.
6535 */
6536 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
6537 break;
6538
5d6523eb 6539 p = list_first_entry(tasks, struct task_struct, se.group_node);
1e3c88bd 6540
367456c7
PZ
6541 env->loop++;
6542 /* We've more or less seen every task there is, call it quits */
5d6523eb 6543 if (env->loop > env->loop_max)
367456c7 6544 break;
5d6523eb
PZ
6545
6546 /* take a breather every nr_migrate tasks */
367456c7 6547 if (env->loop > env->loop_break) {
eb95308e 6548 env->loop_break += sched_nr_migrate_break;
8e45cb54 6549 env->flags |= LBF_NEED_BREAK;
ee00e66f 6550 break;
a195f004 6551 }
1e3c88bd 6552
d3198084 6553 if (!can_migrate_task(p, env))
367456c7
PZ
6554 goto next;
6555
6556 load = task_h_load(p);
5d6523eb 6557
eb95308e 6558 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
367456c7
PZ
6559 goto next;
6560
bd939f45 6561 if ((load / 2) > env->imbalance)
367456c7 6562 goto next;
1e3c88bd 6563
163122b7
KT
6564 detach_task(p, env);
6565 list_add(&p->se.group_node, &env->tasks);
6566
6567 detached++;
bd939f45 6568 env->imbalance -= load;
1e3c88bd
PZ
6569
6570#ifdef CONFIG_PREEMPT
ee00e66f
PZ
6571 /*
6572 * NEWIDLE balancing is a source of latency, so preemptible
163122b7 6573 * kernels will stop after the first task is detached to minimize
ee00e66f
PZ
6574 * the critical section.
6575 */
5d6523eb 6576 if (env->idle == CPU_NEWLY_IDLE)
ee00e66f 6577 break;
1e3c88bd
PZ
6578#endif
6579
ee00e66f
PZ
6580 /*
6581 * We only want to steal up to the prescribed amount of
6582 * weighted load.
6583 */
bd939f45 6584 if (env->imbalance <= 0)
ee00e66f 6585 break;
367456c7
PZ
6586
6587 continue;
6588next:
5d6523eb 6589 list_move_tail(&p->se.group_node, tasks);
1e3c88bd 6590 }
5d6523eb 6591
1e3c88bd 6592 /*
163122b7
KT
6593 * Right now, this is one of only two places we collect this stat
6594 * so we can safely collect detach_one_task() stats here rather
6595 * than inside detach_one_task().
1e3c88bd 6596 */
ae92882e 6597 schedstat_add(env->sd->lb_gained[env->idle], detached);
1e3c88bd 6598
163122b7
KT
6599 return detached;
6600}
6601
6602/*
6603 * attach_task() -- attach the task detached by detach_task() to its new rq.
6604 */
6605static void attach_task(struct rq *rq, struct task_struct *p)
6606{
6607 lockdep_assert_held(&rq->lock);
6608
6609 BUG_ON(task_rq(p) != rq);
163122b7 6610 activate_task(rq, p, 0);
3ea94de1 6611 p->on_rq = TASK_ON_RQ_QUEUED;
163122b7
KT
6612 check_preempt_curr(rq, p, 0);
6613}
6614
6615/*
6616 * attach_one_task() -- attaches the task returned from detach_one_task() to
6617 * its new rq.
6618 */
6619static void attach_one_task(struct rq *rq, struct task_struct *p)
6620{
6621 raw_spin_lock(&rq->lock);
6622 attach_task(rq, p);
6623 raw_spin_unlock(&rq->lock);
6624}
6625
6626/*
6627 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
6628 * new rq.
6629 */
6630static void attach_tasks(struct lb_env *env)
6631{
6632 struct list_head *tasks = &env->tasks;
6633 struct task_struct *p;
6634
6635 raw_spin_lock(&env->dst_rq->lock);
6636
6637 while (!list_empty(tasks)) {
6638 p = list_first_entry(tasks, struct task_struct, se.group_node);
6639 list_del_init(&p->se.group_node);
1e3c88bd 6640
163122b7
KT
6641 attach_task(env->dst_rq, p);
6642 }
6643
6644 raw_spin_unlock(&env->dst_rq->lock);
1e3c88bd
PZ
6645}
6646
230059de 6647#ifdef CONFIG_FAIR_GROUP_SCHED
48a16753 6648static void update_blocked_averages(int cpu)
9e3081ca 6649{
9e3081ca 6650 struct rq *rq = cpu_rq(cpu);
48a16753
PT
6651 struct cfs_rq *cfs_rq;
6652 unsigned long flags;
9e3081ca 6653
48a16753
PT
6654 raw_spin_lock_irqsave(&rq->lock, flags);
6655 update_rq_clock(rq);
9d89c257 6656
9763b67f
PZ
6657 /*
6658 * Iterates the task_group tree in a bottom up fashion, see
6659 * list_add_leaf_cfs_rq() for details.
6660 */
64660c86 6661 for_each_leaf_cfs_rq(rq, cfs_rq) {
9d89c257
YD
6662 /* throttled entities do not contribute to load */
6663 if (throttled_hierarchy(cfs_rq))
6664 continue;
48a16753 6665
a2c6c91f 6666 if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true))
9d89c257
YD
6667 update_tg_load_avg(cfs_rq, 0);
6668 }
48a16753 6669 raw_spin_unlock_irqrestore(&rq->lock, flags);
9e3081ca
PZ
6670}
6671
9763b67f 6672/*
68520796 6673 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9763b67f
PZ
6674 * This needs to be done in a top-down fashion because the load of a child
6675 * group is a fraction of its parents load.
6676 */
68520796 6677static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9763b67f 6678{
68520796
VD
6679 struct rq *rq = rq_of(cfs_rq);
6680 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
a35b6466 6681 unsigned long now = jiffies;
68520796 6682 unsigned long load;
a35b6466 6683
68520796 6684 if (cfs_rq->last_h_load_update == now)
a35b6466
PZ
6685 return;
6686
68520796
VD
6687 cfs_rq->h_load_next = NULL;
6688 for_each_sched_entity(se) {
6689 cfs_rq = cfs_rq_of(se);
6690 cfs_rq->h_load_next = se;
6691 if (cfs_rq->last_h_load_update == now)
6692 break;
6693 }
a35b6466 6694
68520796 6695 if (!se) {
7ea241af 6696 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
68520796
VD
6697 cfs_rq->last_h_load_update = now;
6698 }
6699
6700 while ((se = cfs_rq->h_load_next) != NULL) {
6701 load = cfs_rq->h_load;
7ea241af
YD
6702 load = div64_ul(load * se->avg.load_avg,
6703 cfs_rq_load_avg(cfs_rq) + 1);
68520796
VD
6704 cfs_rq = group_cfs_rq(se);
6705 cfs_rq->h_load = load;
6706 cfs_rq->last_h_load_update = now;
6707 }
9763b67f
PZ
6708}
6709
367456c7 6710static unsigned long task_h_load(struct task_struct *p)
230059de 6711{
367456c7 6712 struct cfs_rq *cfs_rq = task_cfs_rq(p);
230059de 6713
68520796 6714 update_cfs_rq_h_load(cfs_rq);
9d89c257 6715 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
7ea241af 6716 cfs_rq_load_avg(cfs_rq) + 1);
230059de
PZ
6717}
6718#else
48a16753 6719static inline void update_blocked_averages(int cpu)
9e3081ca 6720{
6c1d47c0
VG
6721 struct rq *rq = cpu_rq(cpu);
6722 struct cfs_rq *cfs_rq = &rq->cfs;
6723 unsigned long flags;
6724
6725 raw_spin_lock_irqsave(&rq->lock, flags);
6726 update_rq_clock(rq);
a2c6c91f 6727 update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true);
6c1d47c0 6728 raw_spin_unlock_irqrestore(&rq->lock, flags);
9e3081ca
PZ
6729}
6730
367456c7 6731static unsigned long task_h_load(struct task_struct *p)
1e3c88bd 6732{
9d89c257 6733 return p->se.avg.load_avg;
1e3c88bd 6734}
230059de 6735#endif
1e3c88bd 6736
1e3c88bd 6737/********** Helpers for find_busiest_group ************************/
caeb178c
RR
6738
6739enum group_type {
6740 group_other = 0,
6741 group_imbalanced,
6742 group_overloaded,
6743};
6744
1e3c88bd
PZ
6745/*
6746 * sg_lb_stats - stats of a sched_group required for load_balancing
6747 */
6748struct sg_lb_stats {
6749 unsigned long avg_load; /*Avg load across the CPUs of the group */
6750 unsigned long group_load; /* Total load over the CPUs of the group */
1e3c88bd 6751 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
56cf515b 6752 unsigned long load_per_task;
63b2ca30 6753 unsigned long group_capacity;
9e91d61d 6754 unsigned long group_util; /* Total utilization of the group */
147c5fc2 6755 unsigned int sum_nr_running; /* Nr tasks running in the group */
147c5fc2
PZ
6756 unsigned int idle_cpus;
6757 unsigned int group_weight;
caeb178c 6758 enum group_type group_type;
ea67821b 6759 int group_no_capacity;
0ec8aa00
PZ
6760#ifdef CONFIG_NUMA_BALANCING
6761 unsigned int nr_numa_running;
6762 unsigned int nr_preferred_running;
6763#endif
1e3c88bd
PZ
6764};
6765
56cf515b
JK
6766/*
6767 * sd_lb_stats - Structure to store the statistics of a sched_domain
6768 * during load balancing.
6769 */
6770struct sd_lb_stats {
6771 struct sched_group *busiest; /* Busiest group in this sd */
6772 struct sched_group *local; /* Local group in this sd */
6773 unsigned long total_load; /* Total load of all groups in sd */
63b2ca30 6774 unsigned long total_capacity; /* Total capacity of all groups in sd */
56cf515b
JK
6775 unsigned long avg_load; /* Average load across all groups in sd */
6776
56cf515b 6777 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
147c5fc2 6778 struct sg_lb_stats local_stat; /* Statistics of the local group */
56cf515b
JK
6779};
6780
147c5fc2
PZ
6781static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
6782{
6783 /*
6784 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
6785 * local_stat because update_sg_lb_stats() does a full clear/assignment.
6786 * We must however clear busiest_stat::avg_load because
6787 * update_sd_pick_busiest() reads this before assignment.
6788 */
6789 *sds = (struct sd_lb_stats){
6790 .busiest = NULL,
6791 .local = NULL,
6792 .total_load = 0UL,
63b2ca30 6793 .total_capacity = 0UL,
147c5fc2
PZ
6794 .busiest_stat = {
6795 .avg_load = 0UL,
caeb178c
RR
6796 .sum_nr_running = 0,
6797 .group_type = group_other,
147c5fc2
PZ
6798 },
6799 };
6800}
6801
1e3c88bd
PZ
6802/**
6803 * get_sd_load_idx - Obtain the load index for a given sched domain.
6804 * @sd: The sched_domain whose load_idx is to be obtained.
ed1b7732 6805 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
e69f6186
YB
6806 *
6807 * Return: The load index.
1e3c88bd
PZ
6808 */
6809static inline int get_sd_load_idx(struct sched_domain *sd,
6810 enum cpu_idle_type idle)
6811{
6812 int load_idx;
6813
6814 switch (idle) {
6815 case CPU_NOT_IDLE:
6816 load_idx = sd->busy_idx;
6817 break;
6818
6819 case CPU_NEWLY_IDLE:
6820 load_idx = sd->newidle_idx;
6821 break;
6822 default:
6823 load_idx = sd->idle_idx;
6824 break;
6825 }
6826
6827 return load_idx;
6828}
6829
ced549fa 6830static unsigned long scale_rt_capacity(int cpu)
1e3c88bd
PZ
6831{
6832 struct rq *rq = cpu_rq(cpu);
b5b4860d 6833 u64 total, used, age_stamp, avg;
cadefd3d 6834 s64 delta;
1e3c88bd 6835
b654f7de
PZ
6836 /*
6837 * Since we're reading these variables without serialization make sure
6838 * we read them once before doing sanity checks on them.
6839 */
316c1608
JL
6840 age_stamp = READ_ONCE(rq->age_stamp);
6841 avg = READ_ONCE(rq->rt_avg);
cebde6d6 6842 delta = __rq_clock_broken(rq) - age_stamp;
b654f7de 6843
cadefd3d
PZ
6844 if (unlikely(delta < 0))
6845 delta = 0;
6846
6847 total = sched_avg_period() + delta;
aa483808 6848
b5b4860d 6849 used = div_u64(avg, total);
1e3c88bd 6850
b5b4860d
VG
6851 if (likely(used < SCHED_CAPACITY_SCALE))
6852 return SCHED_CAPACITY_SCALE - used;
1e3c88bd 6853
b5b4860d 6854 return 1;
1e3c88bd
PZ
6855}
6856
ced549fa 6857static void update_cpu_capacity(struct sched_domain *sd, int cpu)
1e3c88bd 6858{
8cd5601c 6859 unsigned long capacity = arch_scale_cpu_capacity(sd, cpu);
1e3c88bd
PZ
6860 struct sched_group *sdg = sd->groups;
6861
ca6d75e6 6862 cpu_rq(cpu)->cpu_capacity_orig = capacity;
9d5efe05 6863
ced549fa 6864 capacity *= scale_rt_capacity(cpu);
ca8ce3d0 6865 capacity >>= SCHED_CAPACITY_SHIFT;
1e3c88bd 6866
ced549fa
NP
6867 if (!capacity)
6868 capacity = 1;
1e3c88bd 6869
ced549fa
NP
6870 cpu_rq(cpu)->cpu_capacity = capacity;
6871 sdg->sgc->capacity = capacity;
1e3c88bd
PZ
6872}
6873
63b2ca30 6874void update_group_capacity(struct sched_domain *sd, int cpu)
1e3c88bd
PZ
6875{
6876 struct sched_domain *child = sd->child;
6877 struct sched_group *group, *sdg = sd->groups;
dc7ff76e 6878 unsigned long capacity;
4ec4412e
VG
6879 unsigned long interval;
6880
6881 interval = msecs_to_jiffies(sd->balance_interval);
6882 interval = clamp(interval, 1UL, max_load_balance_interval);
63b2ca30 6883 sdg->sgc->next_update = jiffies + interval;
1e3c88bd
PZ
6884
6885 if (!child) {
ced549fa 6886 update_cpu_capacity(sd, cpu);
1e3c88bd
PZ
6887 return;
6888 }
6889
dc7ff76e 6890 capacity = 0;
1e3c88bd 6891
74a5ce20
PZ
6892 if (child->flags & SD_OVERLAP) {
6893 /*
6894 * SD_OVERLAP domains cannot assume that child groups
6895 * span the current group.
6896 */
6897
863bffc8 6898 for_each_cpu(cpu, sched_group_cpus(sdg)) {
63b2ca30 6899 struct sched_group_capacity *sgc;
9abf24d4 6900 struct rq *rq = cpu_rq(cpu);
863bffc8 6901
9abf24d4 6902 /*
63b2ca30 6903 * build_sched_domains() -> init_sched_groups_capacity()
9abf24d4
SD
6904 * gets here before we've attached the domains to the
6905 * runqueues.
6906 *
ced549fa
NP
6907 * Use capacity_of(), which is set irrespective of domains
6908 * in update_cpu_capacity().
9abf24d4 6909 *
dc7ff76e 6910 * This avoids capacity from being 0 and
9abf24d4 6911 * causing divide-by-zero issues on boot.
9abf24d4
SD
6912 */
6913 if (unlikely(!rq->sd)) {
ced549fa 6914 capacity += capacity_of(cpu);
9abf24d4
SD
6915 continue;
6916 }
863bffc8 6917
63b2ca30 6918 sgc = rq->sd->groups->sgc;
63b2ca30 6919 capacity += sgc->capacity;
863bffc8 6920 }
74a5ce20
PZ
6921 } else {
6922 /*
6923 * !SD_OVERLAP domains can assume that child groups
6924 * span the current group.
97a7142f 6925 */
74a5ce20
PZ
6926
6927 group = child->groups;
6928 do {
63b2ca30 6929 capacity += group->sgc->capacity;
74a5ce20
PZ
6930 group = group->next;
6931 } while (group != child->groups);
6932 }
1e3c88bd 6933
63b2ca30 6934 sdg->sgc->capacity = capacity;
1e3c88bd
PZ
6935}
6936
9d5efe05 6937/*
ea67821b
VG
6938 * Check whether the capacity of the rq has been noticeably reduced by side
6939 * activity. The imbalance_pct is used for the threshold.
6940 * Return true is the capacity is reduced
9d5efe05
SV
6941 */
6942static inline int
ea67821b 6943check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9d5efe05 6944{
ea67821b
VG
6945 return ((rq->cpu_capacity * sd->imbalance_pct) <
6946 (rq->cpu_capacity_orig * 100));
9d5efe05
SV
6947}
6948
30ce5dab
PZ
6949/*
6950 * Group imbalance indicates (and tries to solve) the problem where balancing
6951 * groups is inadequate due to tsk_cpus_allowed() constraints.
6952 *
6953 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
6954 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
6955 * Something like:
6956 *
6957 * { 0 1 2 3 } { 4 5 6 7 }
6958 * * * * *
6959 *
6960 * If we were to balance group-wise we'd place two tasks in the first group and
6961 * two tasks in the second group. Clearly this is undesired as it will overload
6962 * cpu 3 and leave one of the cpus in the second group unused.
6963 *
6964 * The current solution to this issue is detecting the skew in the first group
6263322c
PZ
6965 * by noticing the lower domain failed to reach balance and had difficulty
6966 * moving tasks due to affinity constraints.
30ce5dab
PZ
6967 *
6968 * When this is so detected; this group becomes a candidate for busiest; see
ed1b7732 6969 * update_sd_pick_busiest(). And calculate_imbalance() and
6263322c 6970 * find_busiest_group() avoid some of the usual balance conditions to allow it
30ce5dab
PZ
6971 * to create an effective group imbalance.
6972 *
6973 * This is a somewhat tricky proposition since the next run might not find the
6974 * group imbalance and decide the groups need to be balanced again. A most
6975 * subtle and fragile situation.
6976 */
6977
6263322c 6978static inline int sg_imbalanced(struct sched_group *group)
30ce5dab 6979{
63b2ca30 6980 return group->sgc->imbalance;
30ce5dab
PZ
6981}
6982
b37d9316 6983/*
ea67821b
VG
6984 * group_has_capacity returns true if the group has spare capacity that could
6985 * be used by some tasks.
6986 * We consider that a group has spare capacity if the * number of task is
9e91d61d
DE
6987 * smaller than the number of CPUs or if the utilization is lower than the
6988 * available capacity for CFS tasks.
ea67821b
VG
6989 * For the latter, we use a threshold to stabilize the state, to take into
6990 * account the variance of the tasks' load and to return true if the available
6991 * capacity in meaningful for the load balancer.
6992 * As an example, an available capacity of 1% can appear but it doesn't make
6993 * any benefit for the load balance.
b37d9316 6994 */
ea67821b
VG
6995static inline bool
6996group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
b37d9316 6997{
ea67821b
VG
6998 if (sgs->sum_nr_running < sgs->group_weight)
6999 return true;
c61037e9 7000
ea67821b 7001 if ((sgs->group_capacity * 100) >
9e91d61d 7002 (sgs->group_util * env->sd->imbalance_pct))
ea67821b 7003 return true;
b37d9316 7004
ea67821b
VG
7005 return false;
7006}
7007
7008/*
7009 * group_is_overloaded returns true if the group has more tasks than it can
7010 * handle.
7011 * group_is_overloaded is not equals to !group_has_capacity because a group
7012 * with the exact right number of tasks, has no more spare capacity but is not
7013 * overloaded so both group_has_capacity and group_is_overloaded return
7014 * false.
7015 */
7016static inline bool
7017group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
7018{
7019 if (sgs->sum_nr_running <= sgs->group_weight)
7020 return false;
b37d9316 7021
ea67821b 7022 if ((sgs->group_capacity * 100) <
9e91d61d 7023 (sgs->group_util * env->sd->imbalance_pct))
ea67821b 7024 return true;
b37d9316 7025
ea67821b 7026 return false;
b37d9316
PZ
7027}
7028
79a89f92
LY
7029static inline enum
7030group_type group_classify(struct sched_group *group,
7031 struct sg_lb_stats *sgs)
caeb178c 7032{
ea67821b 7033 if (sgs->group_no_capacity)
caeb178c
RR
7034 return group_overloaded;
7035
7036 if (sg_imbalanced(group))
7037 return group_imbalanced;
7038
7039 return group_other;
7040}
7041
1e3c88bd
PZ
7042/**
7043 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
cd96891d 7044 * @env: The load balancing environment.
1e3c88bd 7045 * @group: sched_group whose statistics are to be updated.
1e3c88bd 7046 * @load_idx: Load index of sched_domain of this_cpu for load calc.
1e3c88bd 7047 * @local_group: Does group contain this_cpu.
1e3c88bd 7048 * @sgs: variable to hold the statistics for this group.
cd3bd4e6 7049 * @overload: Indicate more than one runnable task for any CPU.
1e3c88bd 7050 */
bd939f45
PZ
7051static inline void update_sg_lb_stats(struct lb_env *env,
7052 struct sched_group *group, int load_idx,
4486edd1
TC
7053 int local_group, struct sg_lb_stats *sgs,
7054 bool *overload)
1e3c88bd 7055{
30ce5dab 7056 unsigned long load;
a426f99c 7057 int i, nr_running;
1e3c88bd 7058
b72ff13c
PZ
7059 memset(sgs, 0, sizeof(*sgs));
7060
b9403130 7061 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
1e3c88bd
PZ
7062 struct rq *rq = cpu_rq(i);
7063
1e3c88bd 7064 /* Bias balancing toward cpus of our domain */
6263322c 7065 if (local_group)
04f733b4 7066 load = target_load(i, load_idx);
6263322c 7067 else
1e3c88bd 7068 load = source_load(i, load_idx);
1e3c88bd
PZ
7069
7070 sgs->group_load += load;
9e91d61d 7071 sgs->group_util += cpu_util(i);
65fdac08 7072 sgs->sum_nr_running += rq->cfs.h_nr_running;
4486edd1 7073
a426f99c
WL
7074 nr_running = rq->nr_running;
7075 if (nr_running > 1)
4486edd1
TC
7076 *overload = true;
7077
0ec8aa00
PZ
7078#ifdef CONFIG_NUMA_BALANCING
7079 sgs->nr_numa_running += rq->nr_numa_running;
7080 sgs->nr_preferred_running += rq->nr_preferred_running;
7081#endif
1e3c88bd 7082 sgs->sum_weighted_load += weighted_cpuload(i);
a426f99c
WL
7083 /*
7084 * No need to call idle_cpu() if nr_running is not 0
7085 */
7086 if (!nr_running && idle_cpu(i))
aae6d3dd 7087 sgs->idle_cpus++;
1e3c88bd
PZ
7088 }
7089
63b2ca30
NP
7090 /* Adjust by relative CPU capacity of the group */
7091 sgs->group_capacity = group->sgc->capacity;
ca8ce3d0 7092 sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
1e3c88bd 7093
dd5feea1 7094 if (sgs->sum_nr_running)
38d0f770 7095 sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
1e3c88bd 7096
aae6d3dd 7097 sgs->group_weight = group->group_weight;
b37d9316 7098
ea67821b 7099 sgs->group_no_capacity = group_is_overloaded(env, sgs);
79a89f92 7100 sgs->group_type = group_classify(group, sgs);
1e3c88bd
PZ
7101}
7102
532cb4c4
MN
7103/**
7104 * update_sd_pick_busiest - return 1 on busiest group
cd96891d 7105 * @env: The load balancing environment.
532cb4c4
MN
7106 * @sds: sched_domain statistics
7107 * @sg: sched_group candidate to be checked for being the busiest
b6b12294 7108 * @sgs: sched_group statistics
532cb4c4
MN
7109 *
7110 * Determine if @sg is a busier group than the previously selected
7111 * busiest group.
e69f6186
YB
7112 *
7113 * Return: %true if @sg is a busier group than the previously selected
7114 * busiest group. %false otherwise.
532cb4c4 7115 */
bd939f45 7116static bool update_sd_pick_busiest(struct lb_env *env,
532cb4c4
MN
7117 struct sd_lb_stats *sds,
7118 struct sched_group *sg,
bd939f45 7119 struct sg_lb_stats *sgs)
532cb4c4 7120{
caeb178c 7121 struct sg_lb_stats *busiest = &sds->busiest_stat;
532cb4c4 7122
caeb178c 7123 if (sgs->group_type > busiest->group_type)
532cb4c4
MN
7124 return true;
7125
caeb178c
RR
7126 if (sgs->group_type < busiest->group_type)
7127 return false;
7128
7129 if (sgs->avg_load <= busiest->avg_load)
7130 return false;
7131
7132 /* This is the busiest node in its class. */
7133 if (!(env->sd->flags & SD_ASYM_PACKING))
532cb4c4
MN
7134 return true;
7135
1f621e02
SD
7136 /* No ASYM_PACKING if target cpu is already busy */
7137 if (env->idle == CPU_NOT_IDLE)
7138 return true;
532cb4c4
MN
7139 /*
7140 * ASYM_PACKING needs to move all the work to the lowest
7141 * numbered CPUs in the group, therefore mark all groups
7142 * higher than ourself as busy.
7143 */
caeb178c 7144 if (sgs->sum_nr_running && env->dst_cpu < group_first_cpu(sg)) {
532cb4c4
MN
7145 if (!sds->busiest)
7146 return true;
7147
1f621e02
SD
7148 /* Prefer to move from highest possible cpu's work */
7149 if (group_first_cpu(sds->busiest) < group_first_cpu(sg))
532cb4c4
MN
7150 return true;
7151 }
7152
7153 return false;
7154}
7155
0ec8aa00
PZ
7156#ifdef CONFIG_NUMA_BALANCING
7157static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
7158{
7159 if (sgs->sum_nr_running > sgs->nr_numa_running)
7160 return regular;
7161 if (sgs->sum_nr_running > sgs->nr_preferred_running)
7162 return remote;
7163 return all;
7164}
7165
7166static inline enum fbq_type fbq_classify_rq(struct rq *rq)
7167{
7168 if (rq->nr_running > rq->nr_numa_running)
7169 return regular;
7170 if (rq->nr_running > rq->nr_preferred_running)
7171 return remote;
7172 return all;
7173}
7174#else
7175static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
7176{
7177 return all;
7178}
7179
7180static inline enum fbq_type fbq_classify_rq(struct rq *rq)
7181{
7182 return regular;
7183}
7184#endif /* CONFIG_NUMA_BALANCING */
7185
1e3c88bd 7186/**
461819ac 7187 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
cd96891d 7188 * @env: The load balancing environment.
1e3c88bd
PZ
7189 * @sds: variable to hold the statistics for this sched_domain.
7190 */
0ec8aa00 7191static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 7192{
bd939f45
PZ
7193 struct sched_domain *child = env->sd->child;
7194 struct sched_group *sg = env->sd->groups;
56cf515b 7195 struct sg_lb_stats tmp_sgs;
1e3c88bd 7196 int load_idx, prefer_sibling = 0;
4486edd1 7197 bool overload = false;
1e3c88bd
PZ
7198
7199 if (child && child->flags & SD_PREFER_SIBLING)
7200 prefer_sibling = 1;
7201
bd939f45 7202 load_idx = get_sd_load_idx(env->sd, env->idle);
1e3c88bd
PZ
7203
7204 do {
56cf515b 7205 struct sg_lb_stats *sgs = &tmp_sgs;
1e3c88bd
PZ
7206 int local_group;
7207
bd939f45 7208 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
56cf515b
JK
7209 if (local_group) {
7210 sds->local = sg;
7211 sgs = &sds->local_stat;
b72ff13c
PZ
7212
7213 if (env->idle != CPU_NEWLY_IDLE ||
63b2ca30
NP
7214 time_after_eq(jiffies, sg->sgc->next_update))
7215 update_group_capacity(env->sd, env->dst_cpu);
56cf515b 7216 }
1e3c88bd 7217
4486edd1
TC
7218 update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
7219 &overload);
1e3c88bd 7220
b72ff13c
PZ
7221 if (local_group)
7222 goto next_group;
7223
1e3c88bd
PZ
7224 /*
7225 * In case the child domain prefers tasks go to siblings
ea67821b 7226 * first, lower the sg capacity so that we'll try
75dd321d
NR
7227 * and move all the excess tasks away. We lower the capacity
7228 * of a group only if the local group has the capacity to fit
ea67821b
VG
7229 * these excess tasks. The extra check prevents the case where
7230 * you always pull from the heaviest group when it is already
7231 * under-utilized (possible with a large weight task outweighs
7232 * the tasks on the system).
1e3c88bd 7233 */
b72ff13c 7234 if (prefer_sibling && sds->local &&
ea67821b
VG
7235 group_has_capacity(env, &sds->local_stat) &&
7236 (sgs->sum_nr_running > 1)) {
7237 sgs->group_no_capacity = 1;
79a89f92 7238 sgs->group_type = group_classify(sg, sgs);
cb0b9f24 7239 }
1e3c88bd 7240
b72ff13c 7241 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
532cb4c4 7242 sds->busiest = sg;
56cf515b 7243 sds->busiest_stat = *sgs;
1e3c88bd
PZ
7244 }
7245
b72ff13c
PZ
7246next_group:
7247 /* Now, start updating sd_lb_stats */
7248 sds->total_load += sgs->group_load;
63b2ca30 7249 sds->total_capacity += sgs->group_capacity;
b72ff13c 7250
532cb4c4 7251 sg = sg->next;
bd939f45 7252 } while (sg != env->sd->groups);
0ec8aa00
PZ
7253
7254 if (env->sd->flags & SD_NUMA)
7255 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
4486edd1
TC
7256
7257 if (!env->sd->parent) {
7258 /* update overload indicator if we are at root domain */
7259 if (env->dst_rq->rd->overload != overload)
7260 env->dst_rq->rd->overload = overload;
7261 }
7262
532cb4c4
MN
7263}
7264
532cb4c4
MN
7265/**
7266 * check_asym_packing - Check to see if the group is packed into the
7267 * sched doman.
7268 *
7269 * This is primarily intended to used at the sibling level. Some
7270 * cores like POWER7 prefer to use lower numbered SMT threads. In the
7271 * case of POWER7, it can move to lower SMT modes only when higher
7272 * threads are idle. When in lower SMT modes, the threads will
7273 * perform better since they share less core resources. Hence when we
7274 * have idle threads, we want them to be the higher ones.
7275 *
7276 * This packing function is run on idle threads. It checks to see if
7277 * the busiest CPU in this domain (core in the P7 case) has a higher
7278 * CPU number than the packing function is being run on. Here we are
7279 * assuming lower CPU number will be equivalent to lower a SMT thread
7280 * number.
7281 *
e69f6186 7282 * Return: 1 when packing is required and a task should be moved to
b6b12294
MN
7283 * this CPU. The amount of the imbalance is returned in *imbalance.
7284 *
cd96891d 7285 * @env: The load balancing environment.
532cb4c4 7286 * @sds: Statistics of the sched_domain which is to be packed
532cb4c4 7287 */
bd939f45 7288static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
532cb4c4
MN
7289{
7290 int busiest_cpu;
7291
bd939f45 7292 if (!(env->sd->flags & SD_ASYM_PACKING))
532cb4c4
MN
7293 return 0;
7294
1f621e02
SD
7295 if (env->idle == CPU_NOT_IDLE)
7296 return 0;
7297
532cb4c4
MN
7298 if (!sds->busiest)
7299 return 0;
7300
7301 busiest_cpu = group_first_cpu(sds->busiest);
bd939f45 7302 if (env->dst_cpu > busiest_cpu)
532cb4c4
MN
7303 return 0;
7304
bd939f45 7305 env->imbalance = DIV_ROUND_CLOSEST(
63b2ca30 7306 sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
ca8ce3d0 7307 SCHED_CAPACITY_SCALE);
bd939f45 7308
532cb4c4 7309 return 1;
1e3c88bd
PZ
7310}
7311
7312/**
7313 * fix_small_imbalance - Calculate the minor imbalance that exists
7314 * amongst the groups of a sched_domain, during
7315 * load balancing.
cd96891d 7316 * @env: The load balancing environment.
1e3c88bd 7317 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
1e3c88bd 7318 */
bd939f45
PZ
7319static inline
7320void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 7321{
63b2ca30 7322 unsigned long tmp, capa_now = 0, capa_move = 0;
1e3c88bd 7323 unsigned int imbn = 2;
dd5feea1 7324 unsigned long scaled_busy_load_per_task;
56cf515b 7325 struct sg_lb_stats *local, *busiest;
1e3c88bd 7326
56cf515b
JK
7327 local = &sds->local_stat;
7328 busiest = &sds->busiest_stat;
1e3c88bd 7329
56cf515b
JK
7330 if (!local->sum_nr_running)
7331 local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
7332 else if (busiest->load_per_task > local->load_per_task)
7333 imbn = 1;
dd5feea1 7334
56cf515b 7335 scaled_busy_load_per_task =
ca8ce3d0 7336 (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
63b2ca30 7337 busiest->group_capacity;
56cf515b 7338
3029ede3
VD
7339 if (busiest->avg_load + scaled_busy_load_per_task >=
7340 local->avg_load + (scaled_busy_load_per_task * imbn)) {
56cf515b 7341 env->imbalance = busiest->load_per_task;
1e3c88bd
PZ
7342 return;
7343 }
7344
7345 /*
7346 * OK, we don't have enough imbalance to justify moving tasks,
ced549fa 7347 * however we may be able to increase total CPU capacity used by
1e3c88bd
PZ
7348 * moving them.
7349 */
7350
63b2ca30 7351 capa_now += busiest->group_capacity *
56cf515b 7352 min(busiest->load_per_task, busiest->avg_load);
63b2ca30 7353 capa_now += local->group_capacity *
56cf515b 7354 min(local->load_per_task, local->avg_load);
ca8ce3d0 7355 capa_now /= SCHED_CAPACITY_SCALE;
1e3c88bd
PZ
7356
7357 /* Amount of load we'd subtract */
a2cd4260 7358 if (busiest->avg_load > scaled_busy_load_per_task) {
63b2ca30 7359 capa_move += busiest->group_capacity *
56cf515b 7360 min(busiest->load_per_task,
a2cd4260 7361 busiest->avg_load - scaled_busy_load_per_task);
56cf515b 7362 }
1e3c88bd
PZ
7363
7364 /* Amount of load we'd add */
63b2ca30 7365 if (busiest->avg_load * busiest->group_capacity <
ca8ce3d0 7366 busiest->load_per_task * SCHED_CAPACITY_SCALE) {
63b2ca30
NP
7367 tmp = (busiest->avg_load * busiest->group_capacity) /
7368 local->group_capacity;
56cf515b 7369 } else {
ca8ce3d0 7370 tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
63b2ca30 7371 local->group_capacity;
56cf515b 7372 }
63b2ca30 7373 capa_move += local->group_capacity *
3ae11c90 7374 min(local->load_per_task, local->avg_load + tmp);
ca8ce3d0 7375 capa_move /= SCHED_CAPACITY_SCALE;
1e3c88bd
PZ
7376
7377 /* Move if we gain throughput */
63b2ca30 7378 if (capa_move > capa_now)
56cf515b 7379 env->imbalance = busiest->load_per_task;
1e3c88bd
PZ
7380}
7381
7382/**
7383 * calculate_imbalance - Calculate the amount of imbalance present within the
7384 * groups of a given sched_domain during load balance.
bd939f45 7385 * @env: load balance environment
1e3c88bd 7386 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
1e3c88bd 7387 */
bd939f45 7388static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
1e3c88bd 7389{
dd5feea1 7390 unsigned long max_pull, load_above_capacity = ~0UL;
56cf515b
JK
7391 struct sg_lb_stats *local, *busiest;
7392
7393 local = &sds->local_stat;
56cf515b 7394 busiest = &sds->busiest_stat;
dd5feea1 7395
caeb178c 7396 if (busiest->group_type == group_imbalanced) {
30ce5dab
PZ
7397 /*
7398 * In the group_imb case we cannot rely on group-wide averages
7399 * to ensure cpu-load equilibrium, look at wider averages. XXX
7400 */
56cf515b
JK
7401 busiest->load_per_task =
7402 min(busiest->load_per_task, sds->avg_load);
dd5feea1
SS
7403 }
7404
1e3c88bd 7405 /*
885e542c
DE
7406 * Avg load of busiest sg can be less and avg load of local sg can
7407 * be greater than avg load across all sgs of sd because avg load
7408 * factors in sg capacity and sgs with smaller group_type are
7409 * skipped when updating the busiest sg:
1e3c88bd 7410 */
b1885550
VD
7411 if (busiest->avg_load <= sds->avg_load ||
7412 local->avg_load >= sds->avg_load) {
bd939f45
PZ
7413 env->imbalance = 0;
7414 return fix_small_imbalance(env, sds);
1e3c88bd
PZ
7415 }
7416
9a5d9ba6
PZ
7417 /*
7418 * If there aren't any idle cpus, avoid creating some.
7419 */
7420 if (busiest->group_type == group_overloaded &&
7421 local->group_type == group_overloaded) {
1be0eb2a 7422 load_above_capacity = busiest->sum_nr_running * SCHED_CAPACITY_SCALE;
cfa10334 7423 if (load_above_capacity > busiest->group_capacity) {
ea67821b 7424 load_above_capacity -= busiest->group_capacity;
26656215 7425 load_above_capacity *= scale_load_down(NICE_0_LOAD);
cfa10334
MR
7426 load_above_capacity /= busiest->group_capacity;
7427 } else
ea67821b 7428 load_above_capacity = ~0UL;
dd5feea1
SS
7429 }
7430
7431 /*
7432 * We're trying to get all the cpus to the average_load, so we don't
7433 * want to push ourselves above the average load, nor do we wish to
7434 * reduce the max loaded cpu below the average load. At the same time,
0a9b23ce
DE
7435 * we also don't want to reduce the group load below the group
7436 * capacity. Thus we look for the minimum possible imbalance.
dd5feea1 7437 */
30ce5dab 7438 max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
1e3c88bd
PZ
7439
7440 /* How much load to actually move to equalise the imbalance */
56cf515b 7441 env->imbalance = min(
63b2ca30
NP
7442 max_pull * busiest->group_capacity,
7443 (sds->avg_load - local->avg_load) * local->group_capacity
ca8ce3d0 7444 ) / SCHED_CAPACITY_SCALE;
1e3c88bd
PZ
7445
7446 /*
7447 * if *imbalance is less than the average load per runnable task
25985edc 7448 * there is no guarantee that any tasks will be moved so we'll have
1e3c88bd
PZ
7449 * a think about bumping its value to force at least one task to be
7450 * moved
7451 */
56cf515b 7452 if (env->imbalance < busiest->load_per_task)
bd939f45 7453 return fix_small_imbalance(env, sds);
1e3c88bd 7454}
fab47622 7455
1e3c88bd
PZ
7456/******* find_busiest_group() helpers end here *********************/
7457
7458/**
7459 * find_busiest_group - Returns the busiest group within the sched_domain
0a9b23ce 7460 * if there is an imbalance.
1e3c88bd
PZ
7461 *
7462 * Also calculates the amount of weighted load which should be moved
7463 * to restore balance.
7464 *
cd96891d 7465 * @env: The load balancing environment.
1e3c88bd 7466 *
e69f6186 7467 * Return: - The busiest group if imbalance exists.
1e3c88bd 7468 */
56cf515b 7469static struct sched_group *find_busiest_group(struct lb_env *env)
1e3c88bd 7470{
56cf515b 7471 struct sg_lb_stats *local, *busiest;
1e3c88bd
PZ
7472 struct sd_lb_stats sds;
7473
147c5fc2 7474 init_sd_lb_stats(&sds);
1e3c88bd
PZ
7475
7476 /*
7477 * Compute the various statistics relavent for load balancing at
7478 * this level.
7479 */
23f0d209 7480 update_sd_lb_stats(env, &sds);
56cf515b
JK
7481 local = &sds.local_stat;
7482 busiest = &sds.busiest_stat;
1e3c88bd 7483
ea67821b 7484 /* ASYM feature bypasses nice load balance check */
1f621e02 7485 if (check_asym_packing(env, &sds))
532cb4c4
MN
7486 return sds.busiest;
7487
cc57aa8f 7488 /* There is no busy sibling group to pull tasks from */
56cf515b 7489 if (!sds.busiest || busiest->sum_nr_running == 0)
1e3c88bd
PZ
7490 goto out_balanced;
7491
ca8ce3d0
NP
7492 sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
7493 / sds.total_capacity;
b0432d8f 7494
866ab43e
PZ
7495 /*
7496 * If the busiest group is imbalanced the below checks don't
30ce5dab 7497 * work because they assume all things are equal, which typically
866ab43e
PZ
7498 * isn't true due to cpus_allowed constraints and the like.
7499 */
caeb178c 7500 if (busiest->group_type == group_imbalanced)
866ab43e
PZ
7501 goto force_balance;
7502
cc57aa8f 7503 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
ea67821b
VG
7504 if (env->idle == CPU_NEWLY_IDLE && group_has_capacity(env, local) &&
7505 busiest->group_no_capacity)
fab47622
NR
7506 goto force_balance;
7507
cc57aa8f 7508 /*
9c58c79a 7509 * If the local group is busier than the selected busiest group
cc57aa8f
PZ
7510 * don't try and pull any tasks.
7511 */
56cf515b 7512 if (local->avg_load >= busiest->avg_load)
1e3c88bd
PZ
7513 goto out_balanced;
7514
cc57aa8f
PZ
7515 /*
7516 * Don't pull any tasks if this group is already above the domain
7517 * average load.
7518 */
56cf515b 7519 if (local->avg_load >= sds.avg_load)
1e3c88bd
PZ
7520 goto out_balanced;
7521
bd939f45 7522 if (env->idle == CPU_IDLE) {
aae6d3dd 7523 /*
43f4d666
VG
7524 * This cpu is idle. If the busiest group is not overloaded
7525 * and there is no imbalance between this and busiest group
7526 * wrt idle cpus, it is balanced. The imbalance becomes
7527 * significant if the diff is greater than 1 otherwise we
7528 * might end up to just move the imbalance on another group
aae6d3dd 7529 */
43f4d666
VG
7530 if ((busiest->group_type != group_overloaded) &&
7531 (local->idle_cpus <= (busiest->idle_cpus + 1)))
aae6d3dd 7532 goto out_balanced;
c186fafe
PZ
7533 } else {
7534 /*
7535 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
7536 * imbalance_pct to be conservative.
7537 */
56cf515b
JK
7538 if (100 * busiest->avg_load <=
7539 env->sd->imbalance_pct * local->avg_load)
c186fafe 7540 goto out_balanced;
aae6d3dd 7541 }
1e3c88bd 7542
fab47622 7543force_balance:
1e3c88bd 7544 /* Looks like there is an imbalance. Compute it */
bd939f45 7545 calculate_imbalance(env, &sds);
1e3c88bd
PZ
7546 return sds.busiest;
7547
7548out_balanced:
bd939f45 7549 env->imbalance = 0;
1e3c88bd
PZ
7550 return NULL;
7551}
7552
7553/*
7554 * find_busiest_queue - find the busiest runqueue among the cpus in group.
7555 */
bd939f45 7556static struct rq *find_busiest_queue(struct lb_env *env,
b9403130 7557 struct sched_group *group)
1e3c88bd
PZ
7558{
7559 struct rq *busiest = NULL, *rq;
ced549fa 7560 unsigned long busiest_load = 0, busiest_capacity = 1;
1e3c88bd
PZ
7561 int i;
7562
6906a408 7563 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
ea67821b 7564 unsigned long capacity, wl;
0ec8aa00
PZ
7565 enum fbq_type rt;
7566
7567 rq = cpu_rq(i);
7568 rt = fbq_classify_rq(rq);
1e3c88bd 7569
0ec8aa00
PZ
7570 /*
7571 * We classify groups/runqueues into three groups:
7572 * - regular: there are !numa tasks
7573 * - remote: there are numa tasks that run on the 'wrong' node
7574 * - all: there is no distinction
7575 *
7576 * In order to avoid migrating ideally placed numa tasks,
7577 * ignore those when there's better options.
7578 *
7579 * If we ignore the actual busiest queue to migrate another
7580 * task, the next balance pass can still reduce the busiest
7581 * queue by moving tasks around inside the node.
7582 *
7583 * If we cannot move enough load due to this classification
7584 * the next pass will adjust the group classification and
7585 * allow migration of more tasks.
7586 *
7587 * Both cases only affect the total convergence complexity.
7588 */
7589 if (rt > env->fbq_type)
7590 continue;
7591
ced549fa 7592 capacity = capacity_of(i);
9d5efe05 7593
6e40f5bb 7594 wl = weighted_cpuload(i);
1e3c88bd 7595
6e40f5bb
TG
7596 /*
7597 * When comparing with imbalance, use weighted_cpuload()
ced549fa 7598 * which is not scaled with the cpu capacity.
6e40f5bb 7599 */
ea67821b
VG
7600
7601 if (rq->nr_running == 1 && wl > env->imbalance &&
7602 !check_cpu_capacity(rq, env->sd))
1e3c88bd
PZ
7603 continue;
7604
6e40f5bb
TG
7605 /*
7606 * For the load comparisons with the other cpu's, consider
ced549fa
NP
7607 * the weighted_cpuload() scaled with the cpu capacity, so
7608 * that the load can be moved away from the cpu that is
7609 * potentially running at a lower capacity.
95a79b80 7610 *
ced549fa 7611 * Thus we're looking for max(wl_i / capacity_i), crosswise
95a79b80 7612 * multiplication to rid ourselves of the division works out
ced549fa
NP
7613 * to: wl_i * capacity_j > wl_j * capacity_i; where j is
7614 * our previous maximum.
6e40f5bb 7615 */
ced549fa 7616 if (wl * busiest_capacity > busiest_load * capacity) {
95a79b80 7617 busiest_load = wl;
ced549fa 7618 busiest_capacity = capacity;
1e3c88bd
PZ
7619 busiest = rq;
7620 }
7621 }
7622
7623 return busiest;
7624}
7625
7626/*
7627 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
7628 * so long as it is large enough.
7629 */
7630#define MAX_PINNED_INTERVAL 512
7631
bd939f45 7632static int need_active_balance(struct lb_env *env)
1af3ed3d 7633{
bd939f45
PZ
7634 struct sched_domain *sd = env->sd;
7635
7636 if (env->idle == CPU_NEWLY_IDLE) {
532cb4c4
MN
7637
7638 /*
7639 * ASYM_PACKING needs to force migrate tasks from busy but
7640 * higher numbered CPUs in order to pack all tasks in the
7641 * lowest numbered CPUs.
7642 */
bd939f45 7643 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
532cb4c4 7644 return 1;
1af3ed3d
PZ
7645 }
7646
1aaf90a4
VG
7647 /*
7648 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
7649 * It's worth migrating the task if the src_cpu's capacity is reduced
7650 * because of other sched_class or IRQs if more capacity stays
7651 * available on dst_cpu.
7652 */
7653 if ((env->idle != CPU_NOT_IDLE) &&
7654 (env->src_rq->cfs.h_nr_running == 1)) {
7655 if ((check_cpu_capacity(env->src_rq, sd)) &&
7656 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
7657 return 1;
7658 }
7659
1af3ed3d
PZ
7660 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
7661}
7662
969c7921
TH
7663static int active_load_balance_cpu_stop(void *data);
7664
23f0d209
JK
7665static int should_we_balance(struct lb_env *env)
7666{
7667 struct sched_group *sg = env->sd->groups;
7668 struct cpumask *sg_cpus, *sg_mask;
7669 int cpu, balance_cpu = -1;
7670
7671 /*
7672 * In the newly idle case, we will allow all the cpu's
7673 * to do the newly idle load balance.
7674 */
7675 if (env->idle == CPU_NEWLY_IDLE)
7676 return 1;
7677
7678 sg_cpus = sched_group_cpus(sg);
7679 sg_mask = sched_group_mask(sg);
7680 /* Try to find first idle cpu */
7681 for_each_cpu_and(cpu, sg_cpus, env->cpus) {
7682 if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
7683 continue;
7684
7685 balance_cpu = cpu;
7686 break;
7687 }
7688
7689 if (balance_cpu == -1)
7690 balance_cpu = group_balance_cpu(sg);
7691
7692 /*
7693 * First idle cpu or the first cpu(busiest) in this sched group
7694 * is eligible for doing load balancing at this and above domains.
7695 */
b0cff9d8 7696 return balance_cpu == env->dst_cpu;
23f0d209
JK
7697}
7698
1e3c88bd
PZ
7699/*
7700 * Check this_cpu to ensure it is balanced within domain. Attempt to move
7701 * tasks if there is an imbalance.
7702 */
7703static int load_balance(int this_cpu, struct rq *this_rq,
7704 struct sched_domain *sd, enum cpu_idle_type idle,
23f0d209 7705 int *continue_balancing)
1e3c88bd 7706{
88b8dac0 7707 int ld_moved, cur_ld_moved, active_balance = 0;
6263322c 7708 struct sched_domain *sd_parent = sd->parent;
1e3c88bd 7709 struct sched_group *group;
1e3c88bd
PZ
7710 struct rq *busiest;
7711 unsigned long flags;
4ba29684 7712 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
1e3c88bd 7713
8e45cb54
PZ
7714 struct lb_env env = {
7715 .sd = sd,
ddcdf6e7
PZ
7716 .dst_cpu = this_cpu,
7717 .dst_rq = this_rq,
88b8dac0 7718 .dst_grpmask = sched_group_cpus(sd->groups),
8e45cb54 7719 .idle = idle,
eb95308e 7720 .loop_break = sched_nr_migrate_break,
b9403130 7721 .cpus = cpus,
0ec8aa00 7722 .fbq_type = all,
163122b7 7723 .tasks = LIST_HEAD_INIT(env.tasks),
8e45cb54
PZ
7724 };
7725
cfc03118
JK
7726 /*
7727 * For NEWLY_IDLE load_balancing, we don't need to consider
7728 * other cpus in our group
7729 */
e02e60c1 7730 if (idle == CPU_NEWLY_IDLE)
cfc03118 7731 env.dst_grpmask = NULL;
cfc03118 7732
1e3c88bd
PZ
7733 cpumask_copy(cpus, cpu_active_mask);
7734
ae92882e 7735 schedstat_inc(sd->lb_count[idle]);
1e3c88bd
PZ
7736
7737redo:
23f0d209
JK
7738 if (!should_we_balance(&env)) {
7739 *continue_balancing = 0;
1e3c88bd 7740 goto out_balanced;
23f0d209 7741 }
1e3c88bd 7742
23f0d209 7743 group = find_busiest_group(&env);
1e3c88bd 7744 if (!group) {
ae92882e 7745 schedstat_inc(sd->lb_nobusyg[idle]);
1e3c88bd
PZ
7746 goto out_balanced;
7747 }
7748
b9403130 7749 busiest = find_busiest_queue(&env, group);
1e3c88bd 7750 if (!busiest) {
ae92882e 7751 schedstat_inc(sd->lb_nobusyq[idle]);
1e3c88bd
PZ
7752 goto out_balanced;
7753 }
7754
78feefc5 7755 BUG_ON(busiest == env.dst_rq);
1e3c88bd 7756
ae92882e 7757 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
1e3c88bd 7758
1aaf90a4
VG
7759 env.src_cpu = busiest->cpu;
7760 env.src_rq = busiest;
7761
1e3c88bd
PZ
7762 ld_moved = 0;
7763 if (busiest->nr_running > 1) {
7764 /*
7765 * Attempt to move tasks. If find_busiest_group has found
7766 * an imbalance but busiest->nr_running <= 1, the group is
7767 * still unbalanced. ld_moved simply stays zero, so it is
7768 * correctly treated as an imbalance.
7769 */
8e45cb54 7770 env.flags |= LBF_ALL_PINNED;
c82513e5 7771 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
8e45cb54 7772
5d6523eb 7773more_balance:
163122b7 7774 raw_spin_lock_irqsave(&busiest->lock, flags);
88b8dac0
SV
7775
7776 /*
7777 * cur_ld_moved - load moved in current iteration
7778 * ld_moved - cumulative load moved across iterations
7779 */
163122b7 7780 cur_ld_moved = detach_tasks(&env);
1e3c88bd
PZ
7781
7782 /*
163122b7
KT
7783 * We've detached some tasks from busiest_rq. Every
7784 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
7785 * unlock busiest->lock, and we are able to be sure
7786 * that nobody can manipulate the tasks in parallel.
7787 * See task_rq_lock() family for the details.
1e3c88bd 7788 */
163122b7
KT
7789
7790 raw_spin_unlock(&busiest->lock);
7791
7792 if (cur_ld_moved) {
7793 attach_tasks(&env);
7794 ld_moved += cur_ld_moved;
7795 }
7796
1e3c88bd 7797 local_irq_restore(flags);
88b8dac0 7798
f1cd0858
JK
7799 if (env.flags & LBF_NEED_BREAK) {
7800 env.flags &= ~LBF_NEED_BREAK;
7801 goto more_balance;
7802 }
7803
88b8dac0
SV
7804 /*
7805 * Revisit (affine) tasks on src_cpu that couldn't be moved to
7806 * us and move them to an alternate dst_cpu in our sched_group
7807 * where they can run. The upper limit on how many times we
7808 * iterate on same src_cpu is dependent on number of cpus in our
7809 * sched_group.
7810 *
7811 * This changes load balance semantics a bit on who can move
7812 * load to a given_cpu. In addition to the given_cpu itself
7813 * (or a ilb_cpu acting on its behalf where given_cpu is
7814 * nohz-idle), we now have balance_cpu in a position to move
7815 * load to given_cpu. In rare situations, this may cause
7816 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
7817 * _independently_ and at _same_ time to move some load to
7818 * given_cpu) causing exceess load to be moved to given_cpu.
7819 * This however should not happen so much in practice and
7820 * moreover subsequent load balance cycles should correct the
7821 * excess load moved.
7822 */
6263322c 7823 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
88b8dac0 7824
7aff2e3a
VD
7825 /* Prevent to re-select dst_cpu via env's cpus */
7826 cpumask_clear_cpu(env.dst_cpu, env.cpus);
7827
78feefc5 7828 env.dst_rq = cpu_rq(env.new_dst_cpu);
88b8dac0 7829 env.dst_cpu = env.new_dst_cpu;
6263322c 7830 env.flags &= ~LBF_DST_PINNED;
88b8dac0
SV
7831 env.loop = 0;
7832 env.loop_break = sched_nr_migrate_break;
e02e60c1 7833
88b8dac0
SV
7834 /*
7835 * Go back to "more_balance" rather than "redo" since we
7836 * need to continue with same src_cpu.
7837 */
7838 goto more_balance;
7839 }
1e3c88bd 7840
6263322c
PZ
7841 /*
7842 * We failed to reach balance because of affinity.
7843 */
7844 if (sd_parent) {
63b2ca30 7845 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
6263322c 7846
afdeee05 7847 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
6263322c 7848 *group_imbalance = 1;
6263322c
PZ
7849 }
7850
1e3c88bd 7851 /* All tasks on this runqueue were pinned by CPU affinity */
8e45cb54 7852 if (unlikely(env.flags & LBF_ALL_PINNED)) {
1e3c88bd 7853 cpumask_clear_cpu(cpu_of(busiest), cpus);
bbf18b19
PN
7854 if (!cpumask_empty(cpus)) {
7855 env.loop = 0;
7856 env.loop_break = sched_nr_migrate_break;
1e3c88bd 7857 goto redo;
bbf18b19 7858 }
afdeee05 7859 goto out_all_pinned;
1e3c88bd
PZ
7860 }
7861 }
7862
7863 if (!ld_moved) {
ae92882e 7864 schedstat_inc(sd->lb_failed[idle]);
58b26c4c
VP
7865 /*
7866 * Increment the failure counter only on periodic balance.
7867 * We do not want newidle balance, which can be very
7868 * frequent, pollute the failure counter causing
7869 * excessive cache_hot migrations and active balances.
7870 */
7871 if (idle != CPU_NEWLY_IDLE)
7872 sd->nr_balance_failed++;
1e3c88bd 7873
bd939f45 7874 if (need_active_balance(&env)) {
1e3c88bd
PZ
7875 raw_spin_lock_irqsave(&busiest->lock, flags);
7876
969c7921
TH
7877 /* don't kick the active_load_balance_cpu_stop,
7878 * if the curr task on busiest cpu can't be
7879 * moved to this_cpu
1e3c88bd
PZ
7880 */
7881 if (!cpumask_test_cpu(this_cpu,
fa17b507 7882 tsk_cpus_allowed(busiest->curr))) {
1e3c88bd
PZ
7883 raw_spin_unlock_irqrestore(&busiest->lock,
7884 flags);
8e45cb54 7885 env.flags |= LBF_ALL_PINNED;
1e3c88bd
PZ
7886 goto out_one_pinned;
7887 }
7888
969c7921
TH
7889 /*
7890 * ->active_balance synchronizes accesses to
7891 * ->active_balance_work. Once set, it's cleared
7892 * only after active load balance is finished.
7893 */
1e3c88bd
PZ
7894 if (!busiest->active_balance) {
7895 busiest->active_balance = 1;
7896 busiest->push_cpu = this_cpu;
7897 active_balance = 1;
7898 }
7899 raw_spin_unlock_irqrestore(&busiest->lock, flags);
969c7921 7900
bd939f45 7901 if (active_balance) {
969c7921
TH
7902 stop_one_cpu_nowait(cpu_of(busiest),
7903 active_load_balance_cpu_stop, busiest,
7904 &busiest->active_balance_work);
bd939f45 7905 }
1e3c88bd 7906
d02c0711 7907 /* We've kicked active balancing, force task migration. */
1e3c88bd
PZ
7908 sd->nr_balance_failed = sd->cache_nice_tries+1;
7909 }
7910 } else
7911 sd->nr_balance_failed = 0;
7912
7913 if (likely(!active_balance)) {
7914 /* We were unbalanced, so reset the balancing interval */
7915 sd->balance_interval = sd->min_interval;
7916 } else {
7917 /*
7918 * If we've begun active balancing, start to back off. This
7919 * case may not be covered by the all_pinned logic if there
7920 * is only 1 task on the busy runqueue (because we don't call
163122b7 7921 * detach_tasks).
1e3c88bd
PZ
7922 */
7923 if (sd->balance_interval < sd->max_interval)
7924 sd->balance_interval *= 2;
7925 }
7926
1e3c88bd
PZ
7927 goto out;
7928
7929out_balanced:
afdeee05
VG
7930 /*
7931 * We reach balance although we may have faced some affinity
7932 * constraints. Clear the imbalance flag if it was set.
7933 */
7934 if (sd_parent) {
7935 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
7936
7937 if (*group_imbalance)
7938 *group_imbalance = 0;
7939 }
7940
7941out_all_pinned:
7942 /*
7943 * We reach balance because all tasks are pinned at this level so
7944 * we can't migrate them. Let the imbalance flag set so parent level
7945 * can try to migrate them.
7946 */
ae92882e 7947 schedstat_inc(sd->lb_balanced[idle]);
1e3c88bd
PZ
7948
7949 sd->nr_balance_failed = 0;
7950
7951out_one_pinned:
7952 /* tune up the balancing interval */
8e45cb54 7953 if (((env.flags & LBF_ALL_PINNED) &&
5b54b56b 7954 sd->balance_interval < MAX_PINNED_INTERVAL) ||
1e3c88bd
PZ
7955 (sd->balance_interval < sd->max_interval))
7956 sd->balance_interval *= 2;
7957
46e49b38 7958 ld_moved = 0;
1e3c88bd 7959out:
1e3c88bd
PZ
7960 return ld_moved;
7961}
7962
52a08ef1
JL
7963static inline unsigned long
7964get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
7965{
7966 unsigned long interval = sd->balance_interval;
7967
7968 if (cpu_busy)
7969 interval *= sd->busy_factor;
7970
7971 /* scale ms to jiffies */
7972 interval = msecs_to_jiffies(interval);
7973 interval = clamp(interval, 1UL, max_load_balance_interval);
7974
7975 return interval;
7976}
7977
7978static inline void
31851a98 7979update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
52a08ef1
JL
7980{
7981 unsigned long interval, next;
7982
31851a98
LY
7983 /* used by idle balance, so cpu_busy = 0 */
7984 interval = get_sd_balance_interval(sd, 0);
52a08ef1
JL
7985 next = sd->last_balance + interval;
7986
7987 if (time_after(*next_balance, next))
7988 *next_balance = next;
7989}
7990
1e3c88bd
PZ
7991/*
7992 * idle_balance is called by schedule() if this_cpu is about to become
7993 * idle. Attempts to pull tasks from other CPUs.
7994 */
6e83125c 7995static int idle_balance(struct rq *this_rq)
1e3c88bd 7996{
52a08ef1
JL
7997 unsigned long next_balance = jiffies + HZ;
7998 int this_cpu = this_rq->cpu;
1e3c88bd
PZ
7999 struct sched_domain *sd;
8000 int pulled_task = 0;
9bd721c5 8001 u64 curr_cost = 0;
1e3c88bd 8002
6e83125c
PZ
8003 /*
8004 * We must set idle_stamp _before_ calling idle_balance(), such that we
8005 * measure the duration of idle_balance() as idle time.
8006 */
8007 this_rq->idle_stamp = rq_clock(this_rq);
8008
4486edd1
TC
8009 if (this_rq->avg_idle < sysctl_sched_migration_cost ||
8010 !this_rq->rd->overload) {
52a08ef1
JL
8011 rcu_read_lock();
8012 sd = rcu_dereference_check_sched_domain(this_rq->sd);
8013 if (sd)
31851a98 8014 update_next_balance(sd, &next_balance);
52a08ef1
JL
8015 rcu_read_unlock();
8016
6e83125c 8017 goto out;
52a08ef1 8018 }
1e3c88bd 8019
f492e12e
PZ
8020 raw_spin_unlock(&this_rq->lock);
8021
48a16753 8022 update_blocked_averages(this_cpu);
dce840a0 8023 rcu_read_lock();
1e3c88bd 8024 for_each_domain(this_cpu, sd) {
23f0d209 8025 int continue_balancing = 1;
9bd721c5 8026 u64 t0, domain_cost;
1e3c88bd
PZ
8027
8028 if (!(sd->flags & SD_LOAD_BALANCE))
8029 continue;
8030
52a08ef1 8031 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
31851a98 8032 update_next_balance(sd, &next_balance);
9bd721c5 8033 break;
52a08ef1 8034 }
9bd721c5 8035
f492e12e 8036 if (sd->flags & SD_BALANCE_NEWIDLE) {
9bd721c5
JL
8037 t0 = sched_clock_cpu(this_cpu);
8038
f492e12e 8039 pulled_task = load_balance(this_cpu, this_rq,
23f0d209
JK
8040 sd, CPU_NEWLY_IDLE,
8041 &continue_balancing);
9bd721c5
JL
8042
8043 domain_cost = sched_clock_cpu(this_cpu) - t0;
8044 if (domain_cost > sd->max_newidle_lb_cost)
8045 sd->max_newidle_lb_cost = domain_cost;
8046
8047 curr_cost += domain_cost;
f492e12e 8048 }
1e3c88bd 8049
31851a98 8050 update_next_balance(sd, &next_balance);
39a4d9ca
JL
8051
8052 /*
8053 * Stop searching for tasks to pull if there are
8054 * now runnable tasks on this rq.
8055 */
8056 if (pulled_task || this_rq->nr_running > 0)
1e3c88bd 8057 break;
1e3c88bd 8058 }
dce840a0 8059 rcu_read_unlock();
f492e12e
PZ
8060
8061 raw_spin_lock(&this_rq->lock);
8062
0e5b5337
JL
8063 if (curr_cost > this_rq->max_idle_balance_cost)
8064 this_rq->max_idle_balance_cost = curr_cost;
8065
e5fc6611 8066 /*
0e5b5337
JL
8067 * While browsing the domains, we released the rq lock, a task could
8068 * have been enqueued in the meantime. Since we're not going idle,
8069 * pretend we pulled a task.
e5fc6611 8070 */
0e5b5337 8071 if (this_rq->cfs.h_nr_running && !pulled_task)
6e83125c 8072 pulled_task = 1;
e5fc6611 8073
52a08ef1
JL
8074out:
8075 /* Move the next balance forward */
8076 if (time_after(this_rq->next_balance, next_balance))
1e3c88bd 8077 this_rq->next_balance = next_balance;
9bd721c5 8078
e4aa358b 8079 /* Is there a task of a high priority class? */
46383648 8080 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
e4aa358b
KT
8081 pulled_task = -1;
8082
38c6ade2 8083 if (pulled_task)
6e83125c
PZ
8084 this_rq->idle_stamp = 0;
8085
3c4017c1 8086 return pulled_task;
1e3c88bd
PZ
8087}
8088
8089/*
969c7921
TH
8090 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
8091 * running tasks off the busiest CPU onto idle CPUs. It requires at
8092 * least 1 task to be running on each physical CPU where possible, and
8093 * avoids physical / logical imbalances.
1e3c88bd 8094 */
969c7921 8095static int active_load_balance_cpu_stop(void *data)
1e3c88bd 8096{
969c7921
TH
8097 struct rq *busiest_rq = data;
8098 int busiest_cpu = cpu_of(busiest_rq);
1e3c88bd 8099 int target_cpu = busiest_rq->push_cpu;
969c7921 8100 struct rq *target_rq = cpu_rq(target_cpu);
1e3c88bd 8101 struct sched_domain *sd;
e5673f28 8102 struct task_struct *p = NULL;
969c7921
TH
8103
8104 raw_spin_lock_irq(&busiest_rq->lock);
8105
8106 /* make sure the requested cpu hasn't gone down in the meantime */
8107 if (unlikely(busiest_cpu != smp_processor_id() ||
8108 !busiest_rq->active_balance))
8109 goto out_unlock;
1e3c88bd
PZ
8110
8111 /* Is there any task to move? */
8112 if (busiest_rq->nr_running <= 1)
969c7921 8113 goto out_unlock;
1e3c88bd
PZ
8114
8115 /*
8116 * This condition is "impossible", if it occurs
8117 * we need to fix it. Originally reported by
8118 * Bjorn Helgaas on a 128-cpu setup.
8119 */
8120 BUG_ON(busiest_rq == target_rq);
8121
1e3c88bd 8122 /* Search for an sd spanning us and the target CPU. */
dce840a0 8123 rcu_read_lock();
1e3c88bd
PZ
8124 for_each_domain(target_cpu, sd) {
8125 if ((sd->flags & SD_LOAD_BALANCE) &&
8126 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
8127 break;
8128 }
8129
8130 if (likely(sd)) {
8e45cb54
PZ
8131 struct lb_env env = {
8132 .sd = sd,
ddcdf6e7
PZ
8133 .dst_cpu = target_cpu,
8134 .dst_rq = target_rq,
8135 .src_cpu = busiest_rq->cpu,
8136 .src_rq = busiest_rq,
8e45cb54
PZ
8137 .idle = CPU_IDLE,
8138 };
8139
ae92882e 8140 schedstat_inc(sd->alb_count);
1e3c88bd 8141
e5673f28 8142 p = detach_one_task(&env);
d02c0711 8143 if (p) {
ae92882e 8144 schedstat_inc(sd->alb_pushed);
d02c0711
SD
8145 /* Active balancing done, reset the failure counter. */
8146 sd->nr_balance_failed = 0;
8147 } else {
ae92882e 8148 schedstat_inc(sd->alb_failed);
d02c0711 8149 }
1e3c88bd 8150 }
dce840a0 8151 rcu_read_unlock();
969c7921
TH
8152out_unlock:
8153 busiest_rq->active_balance = 0;
e5673f28
KT
8154 raw_spin_unlock(&busiest_rq->lock);
8155
8156 if (p)
8157 attach_one_task(target_rq, p);
8158
8159 local_irq_enable();
8160
969c7921 8161 return 0;
1e3c88bd
PZ
8162}
8163
d987fc7f
MG
8164static inline int on_null_domain(struct rq *rq)
8165{
8166 return unlikely(!rcu_dereference_sched(rq->sd));
8167}
8168
3451d024 8169#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2
VP
8170/*
8171 * idle load balancing details
83cd4fe2
VP
8172 * - When one of the busy CPUs notice that there may be an idle rebalancing
8173 * needed, they will kick the idle load balancer, which then does idle
8174 * load balancing for all the idle CPUs.
8175 */
1e3c88bd 8176static struct {
83cd4fe2 8177 cpumask_var_t idle_cpus_mask;
0b005cf5 8178 atomic_t nr_cpus;
83cd4fe2
VP
8179 unsigned long next_balance; /* in jiffy units */
8180} nohz ____cacheline_aligned;
1e3c88bd 8181
3dd0337d 8182static inline int find_new_ilb(void)
1e3c88bd 8183{
0b005cf5 8184 int ilb = cpumask_first(nohz.idle_cpus_mask);
1e3c88bd 8185
786d6dc7
SS
8186 if (ilb < nr_cpu_ids && idle_cpu(ilb))
8187 return ilb;
8188
8189 return nr_cpu_ids;
1e3c88bd 8190}
1e3c88bd 8191
83cd4fe2
VP
8192/*
8193 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
8194 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
8195 * CPU (if there is one).
8196 */
0aeeeeba 8197static void nohz_balancer_kick(void)
83cd4fe2
VP
8198{
8199 int ilb_cpu;
8200
8201 nohz.next_balance++;
8202
3dd0337d 8203 ilb_cpu = find_new_ilb();
83cd4fe2 8204
0b005cf5
SS
8205 if (ilb_cpu >= nr_cpu_ids)
8206 return;
83cd4fe2 8207
cd490c5b 8208 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
1c792db7
SS
8209 return;
8210 /*
8211 * Use smp_send_reschedule() instead of resched_cpu().
8212 * This way we generate a sched IPI on the target cpu which
8213 * is idle. And the softirq performing nohz idle load balance
8214 * will be run before returning from the IPI.
8215 */
8216 smp_send_reschedule(ilb_cpu);
83cd4fe2
VP
8217 return;
8218}
8219
20a5c8cc 8220void nohz_balance_exit_idle(unsigned int cpu)
71325960
SS
8221{
8222 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
d987fc7f
MG
8223 /*
8224 * Completely isolated CPUs don't ever set, so we must test.
8225 */
8226 if (likely(cpumask_test_cpu(cpu, nohz.idle_cpus_mask))) {
8227 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
8228 atomic_dec(&nohz.nr_cpus);
8229 }
71325960
SS
8230 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
8231 }
8232}
8233
69e1e811
SS
8234static inline void set_cpu_sd_state_busy(void)
8235{
8236 struct sched_domain *sd;
37dc6b50 8237 int cpu = smp_processor_id();
69e1e811 8238
69e1e811 8239 rcu_read_lock();
0e369d75 8240 sd = rcu_dereference(per_cpu(sd_llc, cpu));
25f55d9d
VG
8241
8242 if (!sd || !sd->nohz_idle)
8243 goto unlock;
8244 sd->nohz_idle = 0;
8245
0e369d75 8246 atomic_inc(&sd->shared->nr_busy_cpus);
25f55d9d 8247unlock:
69e1e811
SS
8248 rcu_read_unlock();
8249}
8250
8251void set_cpu_sd_state_idle(void)
8252{
8253 struct sched_domain *sd;
37dc6b50 8254 int cpu = smp_processor_id();
69e1e811 8255
69e1e811 8256 rcu_read_lock();
0e369d75 8257 sd = rcu_dereference(per_cpu(sd_llc, cpu));
25f55d9d
VG
8258
8259 if (!sd || sd->nohz_idle)
8260 goto unlock;
8261 sd->nohz_idle = 1;
8262
0e369d75 8263 atomic_dec(&sd->shared->nr_busy_cpus);
25f55d9d 8264unlock:
69e1e811
SS
8265 rcu_read_unlock();
8266}
8267
1e3c88bd 8268/*
c1cc017c 8269 * This routine will record that the cpu is going idle with tick stopped.
0b005cf5 8270 * This info will be used in performing idle load balancing in the future.
1e3c88bd 8271 */
c1cc017c 8272void nohz_balance_enter_idle(int cpu)
1e3c88bd 8273{
71325960
SS
8274 /*
8275 * If this cpu is going down, then nothing needs to be done.
8276 */
8277 if (!cpu_active(cpu))
8278 return;
8279
c1cc017c
AS
8280 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
8281 return;
1e3c88bd 8282
d987fc7f
MG
8283 /*
8284 * If we're a completely isolated CPU, we don't play.
8285 */
8286 if (on_null_domain(cpu_rq(cpu)))
8287 return;
8288
c1cc017c
AS
8289 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
8290 atomic_inc(&nohz.nr_cpus);
8291 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
1e3c88bd
PZ
8292}
8293#endif
8294
8295static DEFINE_SPINLOCK(balancing);
8296
49c022e6
PZ
8297/*
8298 * Scale the max load_balance interval with the number of CPUs in the system.
8299 * This trades load-balance latency on larger machines for less cross talk.
8300 */
029632fb 8301void update_max_interval(void)
49c022e6
PZ
8302{
8303 max_load_balance_interval = HZ*num_online_cpus()/10;
8304}
8305
1e3c88bd
PZ
8306/*
8307 * It checks each scheduling domain to see if it is due to be balanced,
8308 * and initiates a balancing operation if so.
8309 *
b9b0853a 8310 * Balancing parameters are set up in init_sched_domains.
1e3c88bd 8311 */
f7ed0a89 8312static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
1e3c88bd 8313{
23f0d209 8314 int continue_balancing = 1;
f7ed0a89 8315 int cpu = rq->cpu;
1e3c88bd 8316 unsigned long interval;
04f733b4 8317 struct sched_domain *sd;
1e3c88bd
PZ
8318 /* Earliest time when we have to do rebalance again */
8319 unsigned long next_balance = jiffies + 60*HZ;
8320 int update_next_balance = 0;
f48627e6
JL
8321 int need_serialize, need_decay = 0;
8322 u64 max_cost = 0;
1e3c88bd 8323
48a16753 8324 update_blocked_averages(cpu);
2069dd75 8325
dce840a0 8326 rcu_read_lock();
1e3c88bd 8327 for_each_domain(cpu, sd) {
f48627e6
JL
8328 /*
8329 * Decay the newidle max times here because this is a regular
8330 * visit to all the domains. Decay ~1% per second.
8331 */
8332 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
8333 sd->max_newidle_lb_cost =
8334 (sd->max_newidle_lb_cost * 253) / 256;
8335 sd->next_decay_max_lb_cost = jiffies + HZ;
8336 need_decay = 1;
8337 }
8338 max_cost += sd->max_newidle_lb_cost;
8339
1e3c88bd
PZ
8340 if (!(sd->flags & SD_LOAD_BALANCE))
8341 continue;
8342
f48627e6
JL
8343 /*
8344 * Stop the load balance at this level. There is another
8345 * CPU in our sched group which is doing load balancing more
8346 * actively.
8347 */
8348 if (!continue_balancing) {
8349 if (need_decay)
8350 continue;
8351 break;
8352 }
8353
52a08ef1 8354 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
1e3c88bd
PZ
8355
8356 need_serialize = sd->flags & SD_SERIALIZE;
1e3c88bd
PZ
8357 if (need_serialize) {
8358 if (!spin_trylock(&balancing))
8359 goto out;
8360 }
8361
8362 if (time_after_eq(jiffies, sd->last_balance + interval)) {
23f0d209 8363 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
1e3c88bd 8364 /*
6263322c 8365 * The LBF_DST_PINNED logic could have changed
de5eb2dd
JK
8366 * env->dst_cpu, so we can't know our idle
8367 * state even if we migrated tasks. Update it.
1e3c88bd 8368 */
de5eb2dd 8369 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
1e3c88bd
PZ
8370 }
8371 sd->last_balance = jiffies;
52a08ef1 8372 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
1e3c88bd
PZ
8373 }
8374 if (need_serialize)
8375 spin_unlock(&balancing);
8376out:
8377 if (time_after(next_balance, sd->last_balance + interval)) {
8378 next_balance = sd->last_balance + interval;
8379 update_next_balance = 1;
8380 }
f48627e6
JL
8381 }
8382 if (need_decay) {
1e3c88bd 8383 /*
f48627e6
JL
8384 * Ensure the rq-wide value also decays but keep it at a
8385 * reasonable floor to avoid funnies with rq->avg_idle.
1e3c88bd 8386 */
f48627e6
JL
8387 rq->max_idle_balance_cost =
8388 max((u64)sysctl_sched_migration_cost, max_cost);
1e3c88bd 8389 }
dce840a0 8390 rcu_read_unlock();
1e3c88bd
PZ
8391
8392 /*
8393 * next_balance will be updated only when there is a need.
8394 * When the cpu is attached to null domain for ex, it will not be
8395 * updated.
8396 */
c5afb6a8 8397 if (likely(update_next_balance)) {
1e3c88bd 8398 rq->next_balance = next_balance;
c5afb6a8
VG
8399
8400#ifdef CONFIG_NO_HZ_COMMON
8401 /*
8402 * If this CPU has been elected to perform the nohz idle
8403 * balance. Other idle CPUs have already rebalanced with
8404 * nohz_idle_balance() and nohz.next_balance has been
8405 * updated accordingly. This CPU is now running the idle load
8406 * balance for itself and we need to update the
8407 * nohz.next_balance accordingly.
8408 */
8409 if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
8410 nohz.next_balance = rq->next_balance;
8411#endif
8412 }
1e3c88bd
PZ
8413}
8414
3451d024 8415#ifdef CONFIG_NO_HZ_COMMON
1e3c88bd 8416/*
3451d024 8417 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
1e3c88bd
PZ
8418 * rebalancing for all the cpus for whom scheduler ticks are stopped.
8419 */
208cb16b 8420static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
83cd4fe2 8421{
208cb16b 8422 int this_cpu = this_rq->cpu;
83cd4fe2
VP
8423 struct rq *rq;
8424 int balance_cpu;
c5afb6a8
VG
8425 /* Earliest time when we have to do rebalance again */
8426 unsigned long next_balance = jiffies + 60*HZ;
8427 int update_next_balance = 0;
83cd4fe2 8428
1c792db7
SS
8429 if (idle != CPU_IDLE ||
8430 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
8431 goto end;
83cd4fe2
VP
8432
8433 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
8a6d42d1 8434 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
83cd4fe2
VP
8435 continue;
8436
8437 /*
8438 * If this cpu gets work to do, stop the load balancing
8439 * work being done for other cpus. Next load
8440 * balancing owner will pick it up.
8441 */
1c792db7 8442 if (need_resched())
83cd4fe2 8443 break;
83cd4fe2 8444
5ed4f1d9
VG
8445 rq = cpu_rq(balance_cpu);
8446
ed61bbc6
TC
8447 /*
8448 * If time for next balance is due,
8449 * do the balance.
8450 */
8451 if (time_after_eq(jiffies, rq->next_balance)) {
8452 raw_spin_lock_irq(&rq->lock);
8453 update_rq_clock(rq);
cee1afce 8454 cpu_load_update_idle(rq);
ed61bbc6
TC
8455 raw_spin_unlock_irq(&rq->lock);
8456 rebalance_domains(rq, CPU_IDLE);
8457 }
83cd4fe2 8458
c5afb6a8
VG
8459 if (time_after(next_balance, rq->next_balance)) {
8460 next_balance = rq->next_balance;
8461 update_next_balance = 1;
8462 }
83cd4fe2 8463 }
c5afb6a8
VG
8464
8465 /*
8466 * next_balance will be updated only when there is a need.
8467 * When the CPU is attached to null domain for ex, it will not be
8468 * updated.
8469 */
8470 if (likely(update_next_balance))
8471 nohz.next_balance = next_balance;
1c792db7
SS
8472end:
8473 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
83cd4fe2
VP
8474}
8475
8476/*
0b005cf5 8477 * Current heuristic for kicking the idle load balancer in the presence
1aaf90a4 8478 * of an idle cpu in the system.
0b005cf5 8479 * - This rq has more than one task.
1aaf90a4
VG
8480 * - This rq has at least one CFS task and the capacity of the CPU is
8481 * significantly reduced because of RT tasks or IRQs.
8482 * - At parent of LLC scheduler domain level, this cpu's scheduler group has
8483 * multiple busy cpu.
0b005cf5
SS
8484 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
8485 * domain span are idle.
83cd4fe2 8486 */
1aaf90a4 8487static inline bool nohz_kick_needed(struct rq *rq)
83cd4fe2
VP
8488{
8489 unsigned long now = jiffies;
0e369d75 8490 struct sched_domain_shared *sds;
0b005cf5 8491 struct sched_domain *sd;
4a725627 8492 int nr_busy, cpu = rq->cpu;
1aaf90a4 8493 bool kick = false;
83cd4fe2 8494
4a725627 8495 if (unlikely(rq->idle_balance))
1aaf90a4 8496 return false;
83cd4fe2 8497
1c792db7
SS
8498 /*
8499 * We may be recently in ticked or tickless idle mode. At the first
8500 * busy tick after returning from idle, we will update the busy stats.
8501 */
69e1e811 8502 set_cpu_sd_state_busy();
c1cc017c 8503 nohz_balance_exit_idle(cpu);
0b005cf5
SS
8504
8505 /*
8506 * None are in tickless mode and hence no need for NOHZ idle load
8507 * balancing.
8508 */
8509 if (likely(!atomic_read(&nohz.nr_cpus)))
1aaf90a4 8510 return false;
1c792db7
SS
8511
8512 if (time_before(now, nohz.next_balance))
1aaf90a4 8513 return false;
83cd4fe2 8514
0b005cf5 8515 if (rq->nr_running >= 2)
1aaf90a4 8516 return true;
83cd4fe2 8517
067491b7 8518 rcu_read_lock();
0e369d75
PZ
8519 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
8520 if (sds) {
8521 /*
8522 * XXX: write a coherent comment on why we do this.
8523 * See also: http://lkml.kernel.org/r/20111202010832.602203411@sbsiddha-desk.sc.intel.com
8524 */
8525 nr_busy = atomic_read(&sds->nr_busy_cpus);
1aaf90a4
VG
8526 if (nr_busy > 1) {
8527 kick = true;
8528 goto unlock;
8529 }
8530
83cd4fe2 8531 }
37dc6b50 8532
1aaf90a4
VG
8533 sd = rcu_dereference(rq->sd);
8534 if (sd) {
8535 if ((rq->cfs.h_nr_running >= 1) &&
8536 check_cpu_capacity(rq, sd)) {
8537 kick = true;
8538 goto unlock;
8539 }
8540 }
37dc6b50 8541
1aaf90a4 8542 sd = rcu_dereference(per_cpu(sd_asym, cpu));
37dc6b50 8543 if (sd && (cpumask_first_and(nohz.idle_cpus_mask,
1aaf90a4
VG
8544 sched_domain_span(sd)) < cpu)) {
8545 kick = true;
8546 goto unlock;
8547 }
067491b7 8548
1aaf90a4 8549unlock:
067491b7 8550 rcu_read_unlock();
1aaf90a4 8551 return kick;
83cd4fe2
VP
8552}
8553#else
208cb16b 8554static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { }
83cd4fe2
VP
8555#endif
8556
8557/*
8558 * run_rebalance_domains is triggered when needed from the scheduler tick.
8559 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
8560 */
0766f788 8561static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
1e3c88bd 8562{
208cb16b 8563 struct rq *this_rq = this_rq();
6eb57e0d 8564 enum cpu_idle_type idle = this_rq->idle_balance ?
1e3c88bd
PZ
8565 CPU_IDLE : CPU_NOT_IDLE;
8566
1e3c88bd 8567 /*
83cd4fe2 8568 * If this cpu has a pending nohz_balance_kick, then do the
1e3c88bd 8569 * balancing on behalf of the other idle cpus whose ticks are
d4573c3e
PM
8570 * stopped. Do nohz_idle_balance *before* rebalance_domains to
8571 * give the idle cpus a chance to load balance. Else we may
8572 * load balance only within the local sched_domain hierarchy
8573 * and abort nohz_idle_balance altogether if we pull some load.
1e3c88bd 8574 */
208cb16b 8575 nohz_idle_balance(this_rq, idle);
d4573c3e 8576 rebalance_domains(this_rq, idle);
1e3c88bd
PZ
8577}
8578
1e3c88bd
PZ
8579/*
8580 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
1e3c88bd 8581 */
7caff66f 8582void trigger_load_balance(struct rq *rq)
1e3c88bd 8583{
1e3c88bd 8584 /* Don't need to rebalance while attached to NULL domain */
c726099e
DL
8585 if (unlikely(on_null_domain(rq)))
8586 return;
8587
8588 if (time_after_eq(jiffies, rq->next_balance))
1e3c88bd 8589 raise_softirq(SCHED_SOFTIRQ);
3451d024 8590#ifdef CONFIG_NO_HZ_COMMON
c726099e 8591 if (nohz_kick_needed(rq))
0aeeeeba 8592 nohz_balancer_kick();
83cd4fe2 8593#endif
1e3c88bd
PZ
8594}
8595
0bcdcf28
CE
8596static void rq_online_fair(struct rq *rq)
8597{
8598 update_sysctl();
0e59bdae
KT
8599
8600 update_runtime_enabled(rq);
0bcdcf28
CE
8601}
8602
8603static void rq_offline_fair(struct rq *rq)
8604{
8605 update_sysctl();
a4c96ae3
PB
8606
8607 /* Ensure any throttled groups are reachable by pick_next_task */
8608 unthrottle_offline_cfs_rqs(rq);
0bcdcf28
CE
8609}
8610
55e12e5e 8611#endif /* CONFIG_SMP */
e1d1484f 8612
bf0f6f24
IM
8613/*
8614 * scheduler tick hitting a task of our scheduling class:
8615 */
8f4d37ec 8616static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
bf0f6f24
IM
8617{
8618 struct cfs_rq *cfs_rq;
8619 struct sched_entity *se = &curr->se;
8620
8621 for_each_sched_entity(se) {
8622 cfs_rq = cfs_rq_of(se);
8f4d37ec 8623 entity_tick(cfs_rq, se, queued);
bf0f6f24 8624 }
18bf2805 8625
b52da86e 8626 if (static_branch_unlikely(&sched_numa_balancing))
cbee9f88 8627 task_tick_numa(rq, curr);
bf0f6f24
IM
8628}
8629
8630/*
cd29fe6f
PZ
8631 * called on fork with the child task as argument from the parent's context
8632 * - child not yet on the tasklist
8633 * - preemption disabled
bf0f6f24 8634 */
cd29fe6f 8635static void task_fork_fair(struct task_struct *p)
bf0f6f24 8636{
4fc420c9
DN
8637 struct cfs_rq *cfs_rq;
8638 struct sched_entity *se = &p->se, *curr;
cd29fe6f 8639 struct rq *rq = this_rq();
bf0f6f24 8640
e210bffd 8641 raw_spin_lock(&rq->lock);
861d034e
PZ
8642 update_rq_clock(rq);
8643
4fc420c9
DN
8644 cfs_rq = task_cfs_rq(current);
8645 curr = cfs_rq->curr;
e210bffd
PZ
8646 if (curr) {
8647 update_curr(cfs_rq);
b5d9d734 8648 se->vruntime = curr->vruntime;
e210bffd 8649 }
aeb73b04 8650 place_entity(cfs_rq, se, 1);
4d78e7b6 8651
cd29fe6f 8652 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
87fefa38 8653 /*
edcb60a3
IM
8654 * Upon rescheduling, sched_class::put_prev_task() will place
8655 * 'current' within the tree based on its new key value.
8656 */
4d78e7b6 8657 swap(curr->vruntime, se->vruntime);
8875125e 8658 resched_curr(rq);
4d78e7b6 8659 }
bf0f6f24 8660
88ec22d3 8661 se->vruntime -= cfs_rq->min_vruntime;
e210bffd 8662 raw_spin_unlock(&rq->lock);
bf0f6f24
IM
8663}
8664
cb469845
SR
8665/*
8666 * Priority of the task has changed. Check to see if we preempt
8667 * the current task.
8668 */
da7a735e
PZ
8669static void
8670prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
cb469845 8671{
da0c1e65 8672 if (!task_on_rq_queued(p))
da7a735e
PZ
8673 return;
8674
cb469845
SR
8675 /*
8676 * Reschedule if we are currently running on this runqueue and
8677 * our priority decreased, or if we are not currently running on
8678 * this runqueue and our priority is higher than the current's
8679 */
da7a735e 8680 if (rq->curr == p) {
cb469845 8681 if (p->prio > oldprio)
8875125e 8682 resched_curr(rq);
cb469845 8683 } else
15afe09b 8684 check_preempt_curr(rq, p, 0);
cb469845
SR
8685}
8686
daa59407 8687static inline bool vruntime_normalized(struct task_struct *p)
da7a735e
PZ
8688{
8689 struct sched_entity *se = &p->se;
da7a735e
PZ
8690
8691 /*
daa59407
BP
8692 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
8693 * the dequeue_entity(.flags=0) will already have normalized the
8694 * vruntime.
8695 */
8696 if (p->on_rq)
8697 return true;
8698
8699 /*
8700 * When !on_rq, vruntime of the task has usually NOT been normalized.
8701 * But there are some cases where it has already been normalized:
da7a735e 8702 *
daa59407
BP
8703 * - A forked child which is waiting for being woken up by
8704 * wake_up_new_task().
8705 * - A task which has been woken up by try_to_wake_up() and
8706 * waiting for actually being woken up by sched_ttwu_pending().
da7a735e 8707 */
daa59407
BP
8708 if (!se->sum_exec_runtime || p->state == TASK_WAKING)
8709 return true;
8710
8711 return false;
8712}
8713
8714static void detach_task_cfs_rq(struct task_struct *p)
8715{
8716 struct sched_entity *se = &p->se;
8717 struct cfs_rq *cfs_rq = cfs_rq_of(se);
01011473 8718 u64 now = cfs_rq_clock_task(cfs_rq);
daa59407
BP
8719
8720 if (!vruntime_normalized(p)) {
da7a735e
PZ
8721 /*
8722 * Fix up our vruntime so that the current sleep doesn't
8723 * cause 'unlimited' sleep bonus.
8724 */
8725 place_entity(cfs_rq, se, 0);
8726 se->vruntime -= cfs_rq->min_vruntime;
8727 }
9ee474f5 8728
9d89c257 8729 /* Catch up with the cfs_rq and remove our load when we leave */
7c3edd2c 8730 update_cfs_rq_load_avg(now, cfs_rq, false);
a05e8c51 8731 detach_entity_load_avg(cfs_rq, se);
7c3edd2c 8732 update_tg_load_avg(cfs_rq, false);
da7a735e
PZ
8733}
8734
daa59407 8735static void attach_task_cfs_rq(struct task_struct *p)
cb469845 8736{
f36c019c 8737 struct sched_entity *se = &p->se;
daa59407 8738 struct cfs_rq *cfs_rq = cfs_rq_of(se);
01011473 8739 u64 now = cfs_rq_clock_task(cfs_rq);
7855a35a
BP
8740
8741#ifdef CONFIG_FAIR_GROUP_SCHED
eb7a59b2
M
8742 /*
8743 * Since the real-depth could have been changed (only FAIR
8744 * class maintain depth value), reset depth properly.
8745 */
8746 se->depth = se->parent ? se->parent->depth + 1 : 0;
8747#endif
7855a35a 8748
6efdb105 8749 /* Synchronize task with its cfs_rq */
7c3edd2c 8750 update_cfs_rq_load_avg(now, cfs_rq, false);
daa59407 8751 attach_entity_load_avg(cfs_rq, se);
7c3edd2c 8752 update_tg_load_avg(cfs_rq, false);
daa59407
BP
8753
8754 if (!vruntime_normalized(p))
8755 se->vruntime += cfs_rq->min_vruntime;
8756}
6efdb105 8757
daa59407
BP
8758static void switched_from_fair(struct rq *rq, struct task_struct *p)
8759{
8760 detach_task_cfs_rq(p);
8761}
8762
8763static void switched_to_fair(struct rq *rq, struct task_struct *p)
8764{
8765 attach_task_cfs_rq(p);
7855a35a 8766
daa59407 8767 if (task_on_rq_queued(p)) {
7855a35a 8768 /*
daa59407
BP
8769 * We were most likely switched from sched_rt, so
8770 * kick off the schedule if running, otherwise just see
8771 * if we can still preempt the current task.
7855a35a 8772 */
daa59407
BP
8773 if (rq->curr == p)
8774 resched_curr(rq);
8775 else
8776 check_preempt_curr(rq, p, 0);
7855a35a 8777 }
cb469845
SR
8778}
8779
83b699ed
SV
8780/* Account for a task changing its policy or group.
8781 *
8782 * This routine is mostly called to set cfs_rq->curr field when a task
8783 * migrates between groups/classes.
8784 */
8785static void set_curr_task_fair(struct rq *rq)
8786{
8787 struct sched_entity *se = &rq->curr->se;
8788
ec12cb7f
PT
8789 for_each_sched_entity(se) {
8790 struct cfs_rq *cfs_rq = cfs_rq_of(se);
8791
8792 set_next_entity(cfs_rq, se);
8793 /* ensure bandwidth has been allocated on our new cfs_rq */
8794 account_cfs_rq_runtime(cfs_rq, 0);
8795 }
83b699ed
SV
8796}
8797
029632fb
PZ
8798void init_cfs_rq(struct cfs_rq *cfs_rq)
8799{
8800 cfs_rq->tasks_timeline = RB_ROOT;
029632fb
PZ
8801 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8802#ifndef CONFIG_64BIT
8803 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
8804#endif
141965c7 8805#ifdef CONFIG_SMP
9d89c257
YD
8806 atomic_long_set(&cfs_rq->removed_load_avg, 0);
8807 atomic_long_set(&cfs_rq->removed_util_avg, 0);
9ee474f5 8808#endif
029632fb
PZ
8809}
8810
810b3817 8811#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b
VG
8812static void task_set_group_fair(struct task_struct *p)
8813{
8814 struct sched_entity *se = &p->se;
8815
8816 set_task_rq(p, task_cpu(p));
8817 se->depth = se->parent ? se->parent->depth + 1 : 0;
8818}
8819
bc54da21 8820static void task_move_group_fair(struct task_struct *p)
810b3817 8821{
daa59407 8822 detach_task_cfs_rq(p);
b2b5ce02 8823 set_task_rq(p, task_cpu(p));
6efdb105
BP
8824
8825#ifdef CONFIG_SMP
8826 /* Tell se's cfs_rq has been changed -- migrated */
8827 p->se.avg.last_update_time = 0;
8828#endif
daa59407 8829 attach_task_cfs_rq(p);
810b3817 8830}
029632fb 8831
ea86cb4b
VG
8832static void task_change_group_fair(struct task_struct *p, int type)
8833{
8834 switch (type) {
8835 case TASK_SET_GROUP:
8836 task_set_group_fair(p);
8837 break;
8838
8839 case TASK_MOVE_GROUP:
8840 task_move_group_fair(p);
8841 break;
8842 }
8843}
8844
029632fb
PZ
8845void free_fair_sched_group(struct task_group *tg)
8846{
8847 int i;
8848
8849 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
8850
8851 for_each_possible_cpu(i) {
8852 if (tg->cfs_rq)
8853 kfree(tg->cfs_rq[i]);
6fe1f348 8854 if (tg->se)
029632fb
PZ
8855 kfree(tg->se[i]);
8856 }
8857
8858 kfree(tg->cfs_rq);
8859 kfree(tg->se);
8860}
8861
8862int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8863{
029632fb 8864 struct sched_entity *se;
b7fa30c9 8865 struct cfs_rq *cfs_rq;
029632fb
PZ
8866 int i;
8867
8868 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8869 if (!tg->cfs_rq)
8870 goto err;
8871 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8872 if (!tg->se)
8873 goto err;
8874
8875 tg->shares = NICE_0_LOAD;
8876
8877 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
8878
8879 for_each_possible_cpu(i) {
8880 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8881 GFP_KERNEL, cpu_to_node(i));
8882 if (!cfs_rq)
8883 goto err;
8884
8885 se = kzalloc_node(sizeof(struct sched_entity),
8886 GFP_KERNEL, cpu_to_node(i));
8887 if (!se)
8888 goto err_free_rq;
8889
8890 init_cfs_rq(cfs_rq);
8891 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
540247fb 8892 init_entity_runnable_average(se);
029632fb
PZ
8893 }
8894
8895 return 1;
8896
8897err_free_rq:
8898 kfree(cfs_rq);
8899err:
8900 return 0;
8901}
8902
8663e24d
PZ
8903void online_fair_sched_group(struct task_group *tg)
8904{
8905 struct sched_entity *se;
8906 struct rq *rq;
8907 int i;
8908
8909 for_each_possible_cpu(i) {
8910 rq = cpu_rq(i);
8911 se = tg->se[i];
8912
8913 raw_spin_lock_irq(&rq->lock);
8914 post_init_entity_util_avg(se);
55e16d30 8915 sync_throttle(tg, i);
8663e24d
PZ
8916 raw_spin_unlock_irq(&rq->lock);
8917 }
8918}
8919
6fe1f348 8920void unregister_fair_sched_group(struct task_group *tg)
029632fb 8921{
029632fb 8922 unsigned long flags;
6fe1f348
PZ
8923 struct rq *rq;
8924 int cpu;
029632fb 8925
6fe1f348
PZ
8926 for_each_possible_cpu(cpu) {
8927 if (tg->se[cpu])
8928 remove_entity_load_avg(tg->se[cpu]);
029632fb 8929
6fe1f348
PZ
8930 /*
8931 * Only empty task groups can be destroyed; so we can speculatively
8932 * check on_list without danger of it being re-added.
8933 */
8934 if (!tg->cfs_rq[cpu]->on_list)
8935 continue;
8936
8937 rq = cpu_rq(cpu);
8938
8939 raw_spin_lock_irqsave(&rq->lock, flags);
8940 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
8941 raw_spin_unlock_irqrestore(&rq->lock, flags);
8942 }
029632fb
PZ
8943}
8944
8945void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8946 struct sched_entity *se, int cpu,
8947 struct sched_entity *parent)
8948{
8949 struct rq *rq = cpu_rq(cpu);
8950
8951 cfs_rq->tg = tg;
8952 cfs_rq->rq = rq;
029632fb
PZ
8953 init_cfs_rq_runtime(cfs_rq);
8954
8955 tg->cfs_rq[cpu] = cfs_rq;
8956 tg->se[cpu] = se;
8957
8958 /* se could be NULL for root_task_group */
8959 if (!se)
8960 return;
8961
fed14d45 8962 if (!parent) {
029632fb 8963 se->cfs_rq = &rq->cfs;
fed14d45
PZ
8964 se->depth = 0;
8965 } else {
029632fb 8966 se->cfs_rq = parent->my_q;
fed14d45
PZ
8967 se->depth = parent->depth + 1;
8968 }
029632fb
PZ
8969
8970 se->my_q = cfs_rq;
0ac9b1c2
PT
8971 /* guarantee group entities always have weight */
8972 update_load_set(&se->load, NICE_0_LOAD);
029632fb
PZ
8973 se->parent = parent;
8974}
8975
8976static DEFINE_MUTEX(shares_mutex);
8977
8978int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8979{
8980 int i;
8981 unsigned long flags;
8982
8983 /*
8984 * We can't change the weight of the root cgroup.
8985 */
8986 if (!tg->se[0])
8987 return -EINVAL;
8988
8989 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
8990
8991 mutex_lock(&shares_mutex);
8992 if (tg->shares == shares)
8993 goto done;
8994
8995 tg->shares = shares;
8996 for_each_possible_cpu(i) {
8997 struct rq *rq = cpu_rq(i);
8998 struct sched_entity *se;
8999
9000 se = tg->se[i];
9001 /* Propagate contribution to hierarchy */
9002 raw_spin_lock_irqsave(&rq->lock, flags);
71b1da46
FW
9003
9004 /* Possible calls to update_curr() need rq clock */
9005 update_rq_clock(rq);
17bc14b7 9006 for_each_sched_entity(se)
029632fb
PZ
9007 update_cfs_shares(group_cfs_rq(se));
9008 raw_spin_unlock_irqrestore(&rq->lock, flags);
9009 }
9010
9011done:
9012 mutex_unlock(&shares_mutex);
9013 return 0;
9014}
9015#else /* CONFIG_FAIR_GROUP_SCHED */
9016
9017void free_fair_sched_group(struct task_group *tg) { }
9018
9019int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9020{
9021 return 1;
9022}
9023
8663e24d
PZ
9024void online_fair_sched_group(struct task_group *tg) { }
9025
6fe1f348 9026void unregister_fair_sched_group(struct task_group *tg) { }
029632fb
PZ
9027
9028#endif /* CONFIG_FAIR_GROUP_SCHED */
9029
810b3817 9030
6d686f45 9031static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
0d721cea
PW
9032{
9033 struct sched_entity *se = &task->se;
0d721cea
PW
9034 unsigned int rr_interval = 0;
9035
9036 /*
9037 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
9038 * idle runqueue:
9039 */
0d721cea 9040 if (rq->cfs.load.weight)
a59f4e07 9041 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
0d721cea
PW
9042
9043 return rr_interval;
9044}
9045
bf0f6f24
IM
9046/*
9047 * All the scheduling class methods:
9048 */
029632fb 9049const struct sched_class fair_sched_class = {
5522d5d5 9050 .next = &idle_sched_class,
bf0f6f24
IM
9051 .enqueue_task = enqueue_task_fair,
9052 .dequeue_task = dequeue_task_fair,
9053 .yield_task = yield_task_fair,
d95f4122 9054 .yield_to_task = yield_to_task_fair,
bf0f6f24 9055
2e09bf55 9056 .check_preempt_curr = check_preempt_wakeup,
bf0f6f24
IM
9057
9058 .pick_next_task = pick_next_task_fair,
9059 .put_prev_task = put_prev_task_fair,
9060
681f3e68 9061#ifdef CONFIG_SMP
4ce72a2c 9062 .select_task_rq = select_task_rq_fair,
0a74bef8 9063 .migrate_task_rq = migrate_task_rq_fair,
141965c7 9064
0bcdcf28
CE
9065 .rq_online = rq_online_fair,
9066 .rq_offline = rq_offline_fair,
88ec22d3 9067
12695578 9068 .task_dead = task_dead_fair,
c5b28038 9069 .set_cpus_allowed = set_cpus_allowed_common,
681f3e68 9070#endif
bf0f6f24 9071
83b699ed 9072 .set_curr_task = set_curr_task_fair,
bf0f6f24 9073 .task_tick = task_tick_fair,
cd29fe6f 9074 .task_fork = task_fork_fair,
cb469845
SR
9075
9076 .prio_changed = prio_changed_fair,
da7a735e 9077 .switched_from = switched_from_fair,
cb469845 9078 .switched_to = switched_to_fair,
810b3817 9079
0d721cea
PW
9080 .get_rr_interval = get_rr_interval_fair,
9081
6e998916
SG
9082 .update_curr = update_curr_fair,
9083
810b3817 9084#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b 9085 .task_change_group = task_change_group_fair,
810b3817 9086#endif
bf0f6f24
IM
9087};
9088
9089#ifdef CONFIG_SCHED_DEBUG
029632fb 9090void print_cfs_stats(struct seq_file *m, int cpu)
bf0f6f24 9091{
bf0f6f24
IM
9092 struct cfs_rq *cfs_rq;
9093
5973e5b9 9094 rcu_read_lock();
c3b64f1e 9095 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
5cef9eca 9096 print_cfs_rq(m, cpu, cfs_rq);
5973e5b9 9097 rcu_read_unlock();
bf0f6f24 9098}
397f2378
SD
9099
9100#ifdef CONFIG_NUMA_BALANCING
9101void show_numa_stats(struct task_struct *p, struct seq_file *m)
9102{
9103 int node;
9104 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
9105
9106 for_each_online_node(node) {
9107 if (p->numa_faults) {
9108 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
9109 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
9110 }
9111 if (p->numa_group) {
9112 gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
9113 gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
9114 }
9115 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
9116 }
9117}
9118#endif /* CONFIG_NUMA_BALANCING */
9119#endif /* CONFIG_SCHED_DEBUG */
029632fb
PZ
9120
9121__init void init_sched_fair_class(void)
9122{
9123#ifdef CONFIG_SMP
9124 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9125
3451d024 9126#ifdef CONFIG_NO_HZ_COMMON
554cecaf 9127 nohz.next_balance = jiffies;
029632fb 9128 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
029632fb
PZ
9129#endif
9130#endif /* SMP */
9131
9132}