2 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
4 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6 * Interactivity improvements by Mike Galbraith
7 * (C) 2007 Mike Galbraith <efault@gmx.de>
9 * Various enhancements by Dmitry Adamushko.
10 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12 * Group scheduling enhancements by Srivatsa Vaddagiri
13 * Copyright IBM Corporation, 2007
14 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16 * Scaled math optimizations by Thomas Gleixner
17 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
23 #include <linux/latencytop.h>
24 #include <linux/sched.h>
25 #include <linux/cpumask.h>
26 #include <linux/slab.h>
27 #include <linux/profile.h>
28 #include <linux/interrupt.h>
29 #include <linux/random.h>
30 #include <linux/mempolicy.h>
31 #include <linux/task_work.h>
33 #include <trace/events/sched.h>
38 * Targeted preemption latency for CPU-bound tasks:
39 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
41 * NOTE: this latency value is not the same as the concept of
42 * 'timeslice length' - timeslices in CFS are of variable length
43 * and have no persistent notion like in traditional, time-slice
44 * based scheduling concepts.
46 * (to see the precise effective timeslice length of your workload,
47 * run vmstat and monitor the context-switches (cs) field)
49 unsigned int sysctl_sched_latency = 6000000ULL;
50 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
53 * The initial- and re-scaling of tunables is configurable
54 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
57 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
58 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
59 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
61 enum sched_tunable_scaling sysctl_sched_tunable_scaling
62 = SCHED_TUNABLESCALING_LOG;
65 * Minimal preemption granularity for CPU-bound tasks:
66 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
68 unsigned int sysctl_sched_min_granularity = 750000ULL;
69 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
72 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
74 static unsigned int sched_nr_latency = 8;
77 * After fork, child runs first. If set to 0 (default) then
78 * parent will (try to) run first.
80 unsigned int sysctl_sched_child_runs_first __read_mostly;
83 * SCHED_OTHER wake-up granularity.
84 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
86 * This option delays the preemption effects of decoupled workloads
87 * and reduces their over-scheduling. Synchronous workloads will still
88 * have immediate wakeup/sleep latencies.
90 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
91 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
93 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
96 * The exponential sliding window over which load is averaged for shares
100 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
102 #ifdef CONFIG_CFS_BANDWIDTH
104 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
105 * each time a cfs_rq requests quota.
107 * Note: in the case that the slice exceeds the runtime remaining (either due
108 * to consumption or the quota being specified to be smaller than the slice)
109 * we will always only issue the remaining available time.
111 * default: 5 msec, units: microseconds
113 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
117 * Increase the granularity value when there are more CPUs,
118 * because with more CPUs the 'effective latency' as visible
119 * to users decreases. But the relationship is not linear,
120 * so pick a second-best guess by going with the log2 of the
123 * This idea comes from the SD scheduler of Con Kolivas:
125 static int get_update_sysctl_factor(void)
127 unsigned int cpus = min_t(int, num_online_cpus(), 8);
130 switch (sysctl_sched_tunable_scaling) {
131 case SCHED_TUNABLESCALING_NONE:
134 case SCHED_TUNABLESCALING_LINEAR:
137 case SCHED_TUNABLESCALING_LOG:
139 factor = 1 + ilog2(cpus);
146 static void update_sysctl(void)
148 unsigned int factor = get_update_sysctl_factor();
150 #define SET_SYSCTL(name) \
151 (sysctl_##name = (factor) * normalized_sysctl_##name)
152 SET_SYSCTL(sched_min_granularity);
153 SET_SYSCTL(sched_latency);
154 SET_SYSCTL(sched_wakeup_granularity);
158 void sched_init_granularity(void)
163 #if BITS_PER_LONG == 32
164 # define WMULT_CONST (~0UL)
166 # define WMULT_CONST (1UL << 32)
169 #define WMULT_SHIFT 32
172 * Shift right and round:
174 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
177 * delta *= weight / lw
180 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
181 struct load_weight *lw)
186 * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
187 * entities since MIN_SHARES = 2. Treat weight as 1 if less than
188 * 2^SCHED_LOAD_RESOLUTION.
190 if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
191 tmp = (u64)delta_exec * scale_load_down(weight);
193 tmp = (u64)delta_exec;
195 if (!lw->inv_weight) {
196 unsigned long w = scale_load_down(lw->weight);
198 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
200 else if (unlikely(!w))
201 lw->inv_weight = WMULT_CONST;
203 lw->inv_weight = WMULT_CONST / w;
207 * Check whether we'd overflow the 64-bit multiplication:
209 if (unlikely(tmp > WMULT_CONST))
210 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
213 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
215 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
219 const struct sched_class fair_sched_class;
221 /**************************************************************
222 * CFS operations on generic schedulable entities:
225 #ifdef CONFIG_FAIR_GROUP_SCHED
227 /* cpu runqueue to which this cfs_rq is attached */
228 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
233 /* An entity is a task if it doesn't "own" a runqueue */
234 #define entity_is_task(se) (!se->my_q)
236 static inline struct task_struct *task_of(struct sched_entity *se)
238 #ifdef CONFIG_SCHED_DEBUG
239 WARN_ON_ONCE(!entity_is_task(se));
241 return container_of(se, struct task_struct, se);
244 /* Walk up scheduling entities hierarchy */
245 #define for_each_sched_entity(se) \
246 for (; se; se = se->parent)
248 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
253 /* runqueue on which this entity is (to be) queued */
254 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
259 /* runqueue "owned" by this group */
260 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
265 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
267 if (!cfs_rq->on_list) {
269 * Ensure we either appear before our parent (if already
270 * enqueued) or force our parent to appear after us when it is
271 * enqueued. The fact that we always enqueue bottom-up
272 * reduces this to two cases.
274 if (cfs_rq->tg->parent &&
275 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
276 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
277 &rq_of(cfs_rq)->leaf_cfs_rq_list);
279 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
280 &rq_of(cfs_rq)->leaf_cfs_rq_list);
287 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
289 if (cfs_rq->on_list) {
290 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
295 /* Iterate thr' all leaf cfs_rq's on a runqueue */
296 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
297 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
299 /* Do the two (enqueued) entities belong to the same group ? */
301 is_same_group(struct sched_entity *se, struct sched_entity *pse)
303 if (se->cfs_rq == pse->cfs_rq)
309 static inline struct sched_entity *parent_entity(struct sched_entity *se)
314 /* return depth at which a sched entity is present in the hierarchy */
315 static inline int depth_se(struct sched_entity *se)
319 for_each_sched_entity(se)
326 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
328 int se_depth, pse_depth;
331 * preemption test can be made between sibling entities who are in the
332 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
333 * both tasks until we find their ancestors who are siblings of common
337 /* First walk up until both entities are at same depth */
338 se_depth = depth_se(*se);
339 pse_depth = depth_se(*pse);
341 while (se_depth > pse_depth) {
343 *se = parent_entity(*se);
346 while (pse_depth > se_depth) {
348 *pse = parent_entity(*pse);
351 while (!is_same_group(*se, *pse)) {
352 *se = parent_entity(*se);
353 *pse = parent_entity(*pse);
357 #else /* !CONFIG_FAIR_GROUP_SCHED */
359 static inline struct task_struct *task_of(struct sched_entity *se)
361 return container_of(se, struct task_struct, se);
364 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
366 return container_of(cfs_rq, struct rq, cfs);
369 #define entity_is_task(se) 1
371 #define for_each_sched_entity(se) \
372 for (; se; se = NULL)
374 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
376 return &task_rq(p)->cfs;
379 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
381 struct task_struct *p = task_of(se);
382 struct rq *rq = task_rq(p);
387 /* runqueue "owned" by this group */
388 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
393 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
397 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
401 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
402 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
405 is_same_group(struct sched_entity *se, struct sched_entity *pse)
410 static inline struct sched_entity *parent_entity(struct sched_entity *se)
416 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
420 #endif /* CONFIG_FAIR_GROUP_SCHED */
422 static __always_inline
423 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
425 /**************************************************************
426 * Scheduling class tree data structure manipulation methods:
429 static inline u64 max_vruntime(u64 min_vruntime, u64 vruntime)
431 s64 delta = (s64)(vruntime - min_vruntime);
433 min_vruntime = vruntime;
438 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
440 s64 delta = (s64)(vruntime - min_vruntime);
442 min_vruntime = vruntime;
447 static inline int entity_before(struct sched_entity *a,
448 struct sched_entity *b)
450 return (s64)(a->vruntime - b->vruntime) < 0;
453 static void update_min_vruntime(struct cfs_rq *cfs_rq)
455 u64 vruntime = cfs_rq->min_vruntime;
458 vruntime = cfs_rq->curr->vruntime;
460 if (cfs_rq->rb_leftmost) {
461 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
466 vruntime = se->vruntime;
468 vruntime = min_vruntime(vruntime, se->vruntime);
471 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
474 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
479 * Enqueue an entity into the rb-tree:
481 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
483 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
484 struct rb_node *parent = NULL;
485 struct sched_entity *entry;
489 * Find the right place in the rbtree:
493 entry = rb_entry(parent, struct sched_entity, run_node);
495 * We dont care about collisions. Nodes with
496 * the same key stay together.
498 if (entity_before(se, entry)) {
499 link = &parent->rb_left;
501 link = &parent->rb_right;
507 * Maintain a cache of leftmost tree entries (it is frequently
511 cfs_rq->rb_leftmost = &se->run_node;
513 rb_link_node(&se->run_node, parent, link);
514 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
517 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
519 if (cfs_rq->rb_leftmost == &se->run_node) {
520 struct rb_node *next_node;
522 next_node = rb_next(&se->run_node);
523 cfs_rq->rb_leftmost = next_node;
526 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
529 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
531 struct rb_node *left = cfs_rq->rb_leftmost;
536 return rb_entry(left, struct sched_entity, run_node);
539 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
541 struct rb_node *next = rb_next(&se->run_node);
546 return rb_entry(next, struct sched_entity, run_node);
549 #ifdef CONFIG_SCHED_DEBUG
550 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
552 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
557 return rb_entry(last, struct sched_entity, run_node);
560 /**************************************************************
561 * Scheduling class statistics methods:
564 int sched_proc_update_handler(struct ctl_table *table, int write,
565 void __user *buffer, size_t *lenp,
568 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
569 int factor = get_update_sysctl_factor();
574 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
575 sysctl_sched_min_granularity);
577 #define WRT_SYSCTL(name) \
578 (normalized_sysctl_##name = sysctl_##name / (factor))
579 WRT_SYSCTL(sched_min_granularity);
580 WRT_SYSCTL(sched_latency);
581 WRT_SYSCTL(sched_wakeup_granularity);
591 static inline unsigned long
592 calc_delta_fair(unsigned long delta, struct sched_entity *se)
594 if (unlikely(se->load.weight != NICE_0_LOAD))
595 delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
601 * The idea is to set a period in which each task runs once.
603 * When there are too many tasks (sched_nr_latency) we have to stretch
604 * this period because otherwise the slices get too small.
606 * p = (nr <= nl) ? l : l*nr/nl
608 static u64 __sched_period(unsigned long nr_running)
610 u64 period = sysctl_sched_latency;
611 unsigned long nr_latency = sched_nr_latency;
613 if (unlikely(nr_running > nr_latency)) {
614 period = sysctl_sched_min_granularity;
615 period *= nr_running;
622 * We calculate the wall-time slice from the period by taking a part
623 * proportional to the weight.
627 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
629 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
631 for_each_sched_entity(se) {
632 struct load_weight *load;
633 struct load_weight lw;
635 cfs_rq = cfs_rq_of(se);
636 load = &cfs_rq->load;
638 if (unlikely(!se->on_rq)) {
641 update_load_add(&lw, se->load.weight);
644 slice = calc_delta_mine(slice, se->load.weight, load);
650 * We calculate the vruntime slice of a to be inserted task
654 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
656 return calc_delta_fair(sched_slice(cfs_rq, se), se);
659 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update);
660 static void update_cfs_shares(struct cfs_rq *cfs_rq);
663 * Update the current task's runtime statistics. Skip current tasks that
664 * are not in our scheduling class.
667 __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
668 unsigned long delta_exec)
670 unsigned long delta_exec_weighted;
672 schedstat_set(curr->statistics.exec_max,
673 max((u64)delta_exec, curr->statistics.exec_max));
675 curr->sum_exec_runtime += delta_exec;
676 schedstat_add(cfs_rq, exec_clock, delta_exec);
677 delta_exec_weighted = calc_delta_fair(delta_exec, curr);
679 curr->vruntime += delta_exec_weighted;
680 update_min_vruntime(cfs_rq);
682 #if defined CONFIG_SMP && defined CONFIG_FAIR_GROUP_SCHED
683 cfs_rq->load_unacc_exec_time += delta_exec;
687 static void update_curr(struct cfs_rq *cfs_rq)
689 struct sched_entity *curr = cfs_rq->curr;
690 u64 now = rq_of(cfs_rq)->clock_task;
691 unsigned long delta_exec;
697 * Get the amount of time the current task was running
698 * since the last time we changed load (this cannot
699 * overflow on 32 bits):
701 delta_exec = (unsigned long)(now - curr->exec_start);
705 __update_curr(cfs_rq, curr, delta_exec);
706 curr->exec_start = now;
708 if (entity_is_task(curr)) {
709 struct task_struct *curtask = task_of(curr);
711 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
712 cpuacct_charge(curtask, delta_exec);
713 account_group_exec_runtime(curtask, delta_exec);
716 account_cfs_rq_runtime(cfs_rq, delta_exec);
720 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
722 schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
726 * Task is being enqueued - update stats:
728 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
731 * Are we enqueueing a waiting task? (for current tasks
732 * a dequeue/enqueue event is a NOP)
734 if (se != cfs_rq->curr)
735 update_stats_wait_start(cfs_rq, se);
739 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
741 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
742 rq_of(cfs_rq)->clock - se->statistics.wait_start));
743 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
744 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
745 rq_of(cfs_rq)->clock - se->statistics.wait_start);
746 #ifdef CONFIG_SCHEDSTATS
747 if (entity_is_task(se)) {
748 trace_sched_stat_wait(task_of(se),
749 rq_of(cfs_rq)->clock - se->statistics.wait_start);
752 schedstat_set(se->statistics.wait_start, 0);
756 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
759 * Mark the end of the wait period if dequeueing a
762 if (se != cfs_rq->curr)
763 update_stats_wait_end(cfs_rq, se);
767 * We are picking a new current task - update its stats:
770 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
773 * We are starting a new run period:
775 se->exec_start = rq_of(cfs_rq)->clock_task;
778 /**************************************************
779 * Scheduling class numa methods.
781 * The purpose of the NUMA bits are to maintain compute (task) and data
782 * (memory) locality. We try and achieve this by making tasks stick to
783 * a particular node (their home node) but if fairness mandates they run
784 * elsewhere for long enough, we let the memory follow them.
786 * Tasks start out with their home-node unset (-1) this effectively means
787 * they act !NUMA until we've established the task is busy enough to bother
790 * We keep a home-node per task and use periodic fault scans to try and
791 * estalish a task<->page relation. This assumes the task<->page relation is a
792 * compute<->data relation, this is false for things like virt. and n:m
793 * threading solutions but its the best we can do given the information we
797 static unsigned long task_h_load(struct task_struct *p);
799 #ifdef CONFIG_SCHED_NUMA
800 static void account_offnode_enqueue(struct rq *rq, struct task_struct *p)
802 p->numa_contrib = task_h_load(p);
803 rq->offnode_weight += p->numa_contrib;
804 rq->offnode_running++;
807 static void account_offnode_dequeue(struct rq *rq, struct task_struct *p)
809 rq->offnode_weight -= p->numa_contrib;
810 rq->offnode_running--;
814 * numa task sample period in ms: 5s
816 unsigned int sysctl_sched_numa_task_period_min = 5000;
817 unsigned int sysctl_sched_numa_task_period_max = 5000*16;
820 * Wait for the 2-sample stuff to settle before migrating again
822 unsigned int sysctl_sched_numa_settle_count = 2;
825 * Got a PROT_NONE fault for a page on @node.
827 void task_numa_fault(int node)
829 struct task_struct *p = current;
831 if (unlikely(!p->numa_faults)) {
832 p->numa_faults = kzalloc(sizeof(unsigned long) * nr_node_ids,
838 p->numa_faults[node]++;
841 void task_numa_placement(void)
843 unsigned long faults, max_faults = 0;
844 struct task_struct *p = current;
845 int node, max_node = -1;
846 int seq = ACCESS_ONCE(p->mm->numa_scan_seq);
848 if (p->numa_scan_seq == seq)
851 p->numa_scan_seq = seq;
853 if (unlikely(!p->numa_faults))
856 for (node = 0; node < nr_node_ids; node++) {
857 faults = p->numa_faults[node];
859 if (faults > max_faults) {
864 p->numa_faults[node] /= 2;
870 if (p->node != max_node) {
871 p->numa_task_period = sysctl_sched_numa_task_period_min;
872 if (sched_feat(NUMA_SETTLE) &&
873 (seq - p->numa_migrate_seq) <= (int)sysctl_sched_numa_settle_count)
875 p->numa_migrate_seq = seq;
876 sched_setnode(p, max_node);
878 p->numa_task_period = min(sysctl_sched_numa_task_period_max,
879 p->numa_task_period * 2);
884 * The expensive part of numa migration is done from task_work context.
885 * Triggered from task_tick_numa().
887 void task_numa_work(struct callback_head *work)
889 unsigned long migrate, next_scan, now = jiffies;
890 struct task_struct *p = current;
891 struct mm_struct *mm = p->mm;
893 WARN_ON_ONCE(p != container_of(work, struct task_struct, rcu));
896 * Who cares about NUMA placement when they're dying.
898 * NOTE: make sure not to dereference p->mm before this check,
899 * exit_task_work() happens _after_ exit_mm() so we could be called
900 * without p->mm even though we still had it when we enqueued this
903 if (p->flags & PF_EXITING)
907 * Enforce maximal scan/migration frequency..
909 migrate = mm->numa_next_scan;
910 if (time_before(now, migrate))
913 next_scan = now + 2*msecs_to_jiffies(sysctl_sched_numa_task_period_min);
914 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
917 ACCESS_ONCE(mm->numa_scan_seq)++;
918 lazy_migrate_process(mm);
922 * Drive the periodic memory faults..
924 void task_tick_numa(struct rq *rq, struct task_struct *curr)
929 * We don't care about NUMA placement if we don't have memory.
935 * Using runtime rather than walltime has the dual advantage that
936 * we (mostly) drive the selection from busy threads and that the
937 * task needs to have done some actual work before we bother with
940 now = curr->se.sum_exec_runtime;
941 period = (u64)curr->numa_task_period * NSEC_PER_MSEC;
943 if (now - curr->node_stamp > period) {
944 curr->node_stamp = now;
946 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
948 * We can re-use curr->rcu because we checked curr->mm
949 * != NULL so release_task()->call_rcu() was not called
950 * yet and exit_task_work() is called before
953 init_task_work(&curr->rcu, task_numa_work);
954 task_work_add(curr, &curr->rcu, true);
959 static void account_offnode_enqueue(struct rq *rq, struct task_struct *p)
963 static void account_offnode_dequeue(struct rq *rq, struct task_struct *p)
967 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
970 #endif /* CONFIG_SCHED_NUMA */
972 /**************************************************
973 * Scheduling class queueing methods:
977 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
979 update_load_add(&cfs_rq->load, se->load.weight);
980 if (!parent_entity(se))
981 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
983 if (entity_is_task(se)) {
984 struct rq *rq = rq_of(cfs_rq);
985 struct task_struct *p = task_of(se);
986 struct list_head *tasks = &rq->cfs_tasks;
988 if (offnode_task(p)) {
989 account_offnode_enqueue(rq, p);
990 tasks = offnode_tasks(rq);
993 list_add(&se->group_node, tasks);
995 #endif /* CONFIG_SMP */
996 cfs_rq->nr_running++;
1000 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1002 update_load_sub(&cfs_rq->load, se->load.weight);
1003 if (!parent_entity(se))
1004 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
1005 if (entity_is_task(se)) {
1006 struct task_struct *p = task_of(se);
1008 list_del_init(&se->group_node);
1010 if (offnode_task(p))
1011 account_offnode_dequeue(rq_of(cfs_rq), p);
1013 cfs_rq->nr_running--;
1016 #ifdef CONFIG_FAIR_GROUP_SCHED
1017 /* we need this in update_cfs_load and load-balance functions below */
1018 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
1020 static void update_cfs_rq_load_contribution(struct cfs_rq *cfs_rq,
1023 struct task_group *tg = cfs_rq->tg;
1026 load_avg = div64_u64(cfs_rq->load_avg, cfs_rq->load_period+1);
1027 load_avg -= cfs_rq->load_contribution;
1029 if (global_update || abs(load_avg) > cfs_rq->load_contribution / 8) {
1030 atomic_add(load_avg, &tg->load_weight);
1031 cfs_rq->load_contribution += load_avg;
1035 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1037 u64 period = sysctl_sched_shares_window;
1039 unsigned long load = cfs_rq->load.weight;
1041 if (cfs_rq->tg == &root_task_group || throttled_hierarchy(cfs_rq))
1044 now = rq_of(cfs_rq)->clock_task;
1045 delta = now - cfs_rq->load_stamp;
1047 /* truncate load history at 4 idle periods */
1048 if (cfs_rq->load_stamp > cfs_rq->load_last &&
1049 now - cfs_rq->load_last > 4 * period) {
1050 cfs_rq->load_period = 0;
1051 cfs_rq->load_avg = 0;
1055 cfs_rq->load_stamp = now;
1056 cfs_rq->load_unacc_exec_time = 0;
1057 cfs_rq->load_period += delta;
1059 cfs_rq->load_last = now;
1060 cfs_rq->load_avg += delta * load;
1063 /* consider updating load contribution on each fold or truncate */
1064 if (global_update || cfs_rq->load_period > period
1065 || !cfs_rq->load_period)
1066 update_cfs_rq_load_contribution(cfs_rq, global_update);
1068 while (cfs_rq->load_period > period) {
1070 * Inline assembly required to prevent the compiler
1071 * optimising this loop into a divmod call.
1072 * See __iter_div_u64_rem() for another example of this.
1074 asm("" : "+rm" (cfs_rq->load_period));
1075 cfs_rq->load_period /= 2;
1076 cfs_rq->load_avg /= 2;
1079 if (!cfs_rq->curr && !cfs_rq->nr_running && !cfs_rq->load_avg)
1080 list_del_leaf_cfs_rq(cfs_rq);
1083 static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
1088 * Use this CPU's actual weight instead of the last load_contribution
1089 * to gain a more accurate current total weight. See
1090 * update_cfs_rq_load_contribution().
1092 tg_weight = atomic_read(&tg->load_weight);
1093 tg_weight -= cfs_rq->load_contribution;
1094 tg_weight += cfs_rq->load.weight;
1099 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1101 long tg_weight, load, shares;
1103 tg_weight = calc_tg_weight(tg, cfs_rq);
1104 load = cfs_rq->load.weight;
1106 shares = (tg->shares * load);
1108 shares /= tg_weight;
1110 if (shares < MIN_SHARES)
1111 shares = MIN_SHARES;
1112 if (shares > tg->shares)
1113 shares = tg->shares;
1118 static void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1120 if (cfs_rq->load_unacc_exec_time > sysctl_sched_shares_window) {
1121 update_cfs_load(cfs_rq, 0);
1122 update_cfs_shares(cfs_rq);
1125 # else /* CONFIG_SMP */
1126 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1130 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1135 static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1138 # endif /* CONFIG_SMP */
1139 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
1140 unsigned long weight)
1143 /* commit outstanding execution time */
1144 if (cfs_rq->curr == se)
1145 update_curr(cfs_rq);
1146 account_entity_dequeue(cfs_rq, se);
1149 update_load_set(&se->load, weight);
1152 account_entity_enqueue(cfs_rq, se);
1155 static void update_cfs_shares(struct cfs_rq *cfs_rq)
1157 struct task_group *tg;
1158 struct sched_entity *se;
1162 se = tg->se[cpu_of(rq_of(cfs_rq))];
1163 if (!se || throttled_hierarchy(cfs_rq))
1166 if (likely(se->load.weight == tg->shares))
1169 shares = calc_cfs_shares(cfs_rq, tg);
1171 reweight_entity(cfs_rq_of(se), se, shares);
1173 #else /* CONFIG_FAIR_GROUP_SCHED */
1174 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1178 static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
1182 static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1185 #endif /* CONFIG_FAIR_GROUP_SCHED */
1187 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
1189 #ifdef CONFIG_SCHEDSTATS
1190 struct task_struct *tsk = NULL;
1192 if (entity_is_task(se))
1195 if (se->statistics.sleep_start) {
1196 u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
1201 if (unlikely(delta > se->statistics.sleep_max))
1202 se->statistics.sleep_max = delta;
1204 se->statistics.sleep_start = 0;
1205 se->statistics.sum_sleep_runtime += delta;
1208 account_scheduler_latency(tsk, delta >> 10, 1);
1209 trace_sched_stat_sleep(tsk, delta);
1212 if (se->statistics.block_start) {
1213 u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
1218 if (unlikely(delta > se->statistics.block_max))
1219 se->statistics.block_max = delta;
1221 se->statistics.block_start = 0;
1222 se->statistics.sum_sleep_runtime += delta;
1225 if (tsk->in_iowait) {
1226 se->statistics.iowait_sum += delta;
1227 se->statistics.iowait_count++;
1228 trace_sched_stat_iowait(tsk, delta);
1231 trace_sched_stat_blocked(tsk, delta);
1234 * Blocking time is in units of nanosecs, so shift by
1235 * 20 to get a milliseconds-range estimation of the
1236 * amount of time that the task spent sleeping:
1238 if (unlikely(prof_on == SLEEP_PROFILING)) {
1239 profile_hits(SLEEP_PROFILING,
1240 (void *)get_wchan(tsk),
1243 account_scheduler_latency(tsk, delta >> 10, 0);
1249 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
1251 #ifdef CONFIG_SCHED_DEBUG
1252 s64 d = se->vruntime - cfs_rq->min_vruntime;
1257 if (d > 3*sysctl_sched_latency)
1258 schedstat_inc(cfs_rq, nr_spread_over);
1263 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
1265 u64 vruntime = cfs_rq->min_vruntime;
1268 * The 'current' period is already promised to the current tasks,
1269 * however the extra weight of the new task will slow them down a
1270 * little, place the new task so that it fits in the slot that
1271 * stays open at the end.
1273 if (initial && sched_feat(START_DEBIT))
1274 vruntime += sched_vslice(cfs_rq, se);
1276 /* sleeps up to a single latency don't count. */
1278 unsigned long thresh = sysctl_sched_latency;
1281 * Halve their sleep time's effect, to allow
1282 * for a gentler effect of sleepers:
1284 if (sched_feat(GENTLE_FAIR_SLEEPERS))
1290 /* ensure we never gain time by being placed backwards. */
1291 vruntime = max_vruntime(se->vruntime, vruntime);
1293 se->vruntime = vruntime;
1296 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
1299 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1302 * Update the normalized vruntime before updating min_vruntime
1303 * through callig update_curr().
1305 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
1306 se->vruntime += cfs_rq->min_vruntime;
1309 * Update run-time statistics of the 'current'.
1311 update_curr(cfs_rq);
1312 update_cfs_load(cfs_rq, 0);
1313 account_entity_enqueue(cfs_rq, se);
1314 update_cfs_shares(cfs_rq);
1316 if (flags & ENQUEUE_WAKEUP) {
1317 place_entity(cfs_rq, se, 0);
1318 enqueue_sleeper(cfs_rq, se);
1321 update_stats_enqueue(cfs_rq, se);
1322 check_spread(cfs_rq, se);
1323 if (se != cfs_rq->curr)
1324 __enqueue_entity(cfs_rq, se);
1327 if (cfs_rq->nr_running == 1) {
1328 list_add_leaf_cfs_rq(cfs_rq);
1329 check_enqueue_throttle(cfs_rq);
1333 static void __clear_buddies_last(struct sched_entity *se)
1335 for_each_sched_entity(se) {
1336 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1337 if (cfs_rq->last == se)
1338 cfs_rq->last = NULL;
1344 static void __clear_buddies_next(struct sched_entity *se)
1346 for_each_sched_entity(se) {
1347 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1348 if (cfs_rq->next == se)
1349 cfs_rq->next = NULL;
1355 static void __clear_buddies_skip(struct sched_entity *se)
1357 for_each_sched_entity(se) {
1358 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1359 if (cfs_rq->skip == se)
1360 cfs_rq->skip = NULL;
1366 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
1368 if (cfs_rq->last == se)
1369 __clear_buddies_last(se);
1371 if (cfs_rq->next == se)
1372 __clear_buddies_next(se);
1374 if (cfs_rq->skip == se)
1375 __clear_buddies_skip(se);
1378 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1381 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1384 * Update run-time statistics of the 'current'.
1386 update_curr(cfs_rq);
1388 update_stats_dequeue(cfs_rq, se);
1389 if (flags & DEQUEUE_SLEEP) {
1390 #ifdef CONFIG_SCHEDSTATS
1391 if (entity_is_task(se)) {
1392 struct task_struct *tsk = task_of(se);
1394 if (tsk->state & TASK_INTERRUPTIBLE)
1395 se->statistics.sleep_start = rq_of(cfs_rq)->clock;
1396 if (tsk->state & TASK_UNINTERRUPTIBLE)
1397 se->statistics.block_start = rq_of(cfs_rq)->clock;
1402 clear_buddies(cfs_rq, se);
1404 if (se != cfs_rq->curr)
1405 __dequeue_entity(cfs_rq, se);
1407 update_cfs_load(cfs_rq, 0);
1408 account_entity_dequeue(cfs_rq, se);
1411 * Normalize the entity after updating the min_vruntime because the
1412 * update can refer to the ->curr item and we need to reflect this
1413 * movement in our normalized position.
1415 if (!(flags & DEQUEUE_SLEEP))
1416 se->vruntime -= cfs_rq->min_vruntime;
1418 /* return excess runtime on last dequeue */
1419 return_cfs_rq_runtime(cfs_rq);
1421 update_min_vruntime(cfs_rq);
1422 update_cfs_shares(cfs_rq);
1426 * Preempt the current task with a newly woken task if needed:
1429 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
1431 unsigned long ideal_runtime, delta_exec;
1432 struct sched_entity *se;
1435 ideal_runtime = sched_slice(cfs_rq, curr);
1436 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
1437 if (delta_exec > ideal_runtime) {
1438 resched_task(rq_of(cfs_rq)->curr);
1440 * The current task ran long enough, ensure it doesn't get
1441 * re-elected due to buddy favours.
1443 clear_buddies(cfs_rq, curr);
1448 * Ensure that a task that missed wakeup preemption by a
1449 * narrow margin doesn't have to wait for a full slice.
1450 * This also mitigates buddy induced latencies under load.
1452 if (delta_exec < sysctl_sched_min_granularity)
1455 se = __pick_first_entity(cfs_rq);
1456 delta = curr->vruntime - se->vruntime;
1461 if (delta > ideal_runtime)
1462 resched_task(rq_of(cfs_rq)->curr);
1466 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1468 /* 'current' is not kept within the tree. */
1471 * Any task has to be enqueued before it get to execute on
1472 * a CPU. So account for the time it spent waiting on the
1475 update_stats_wait_end(cfs_rq, se);
1476 __dequeue_entity(cfs_rq, se);
1479 update_stats_curr_start(cfs_rq, se);
1481 #ifdef CONFIG_SCHEDSTATS
1483 * Track our maximum slice length, if the CPU's load is at
1484 * least twice that of our own weight (i.e. dont track it
1485 * when there are only lesser-weight tasks around):
1487 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
1488 se->statistics.slice_max = max(se->statistics.slice_max,
1489 se->sum_exec_runtime - se->prev_sum_exec_runtime);
1492 se->prev_sum_exec_runtime = se->sum_exec_runtime;
1496 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
1499 * Pick the next process, keeping these things in mind, in this order:
1500 * 1) keep things fair between processes/task groups
1501 * 2) pick the "next" process, since someone really wants that to run
1502 * 3) pick the "last" process, for cache locality
1503 * 4) do not run the "skip" process, if something else is available
1505 static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
1507 struct sched_entity *se = __pick_first_entity(cfs_rq);
1508 struct sched_entity *left = se;
1511 * Avoid running the skip buddy, if running something else can
1512 * be done without getting too unfair.
1514 if (cfs_rq->skip == se) {
1515 struct sched_entity *second = __pick_next_entity(se);
1516 if (second && wakeup_preempt_entity(second, left) < 1)
1521 * Prefer last buddy, try to return the CPU to a preempted task.
1523 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
1527 * Someone really wants this to run. If it's not unfair, run it.
1529 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
1532 clear_buddies(cfs_rq, se);
1537 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1539 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
1542 * If still on the runqueue then deactivate_task()
1543 * was not called and update_curr() has to be done:
1546 update_curr(cfs_rq);
1548 /* throttle cfs_rqs exceeding runtime */
1549 check_cfs_rq_runtime(cfs_rq);
1551 check_spread(cfs_rq, prev);
1553 update_stats_wait_start(cfs_rq, prev);
1554 /* Put 'current' back into the tree. */
1555 __enqueue_entity(cfs_rq, prev);
1557 cfs_rq->curr = NULL;
1561 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
1564 * Update run-time statistics of the 'current'.
1566 update_curr(cfs_rq);
1569 * Update share accounting for long-running entities.
1571 update_entity_shares_tick(cfs_rq);
1573 #ifdef CONFIG_SCHED_HRTICK
1575 * queued ticks are scheduled to match the slice, so don't bother
1576 * validating it and just reschedule.
1579 resched_task(rq_of(cfs_rq)->curr);
1583 * don't let the period tick interfere with the hrtick preemption
1585 if (!sched_feat(DOUBLE_TICK) &&
1586 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
1590 if (cfs_rq->nr_running > 1)
1591 check_preempt_tick(cfs_rq, curr);
1595 /**************************************************
1596 * CFS bandwidth control machinery
1599 #ifdef CONFIG_CFS_BANDWIDTH
1601 #ifdef HAVE_JUMP_LABEL
1602 static struct static_key __cfs_bandwidth_used;
1604 static inline bool cfs_bandwidth_used(void)
1606 return static_key_false(&__cfs_bandwidth_used);
1609 void account_cfs_bandwidth_used(int enabled, int was_enabled)
1611 /* only need to count groups transitioning between enabled/!enabled */
1612 if (enabled && !was_enabled)
1613 static_key_slow_inc(&__cfs_bandwidth_used);
1614 else if (!enabled && was_enabled)
1615 static_key_slow_dec(&__cfs_bandwidth_used);
1617 #else /* HAVE_JUMP_LABEL */
1618 static bool cfs_bandwidth_used(void)
1623 void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
1624 #endif /* HAVE_JUMP_LABEL */
1627 * default period for cfs group bandwidth.
1628 * default: 0.1s, units: nanoseconds
1630 static inline u64 default_cfs_period(void)
1632 return 100000000ULL;
1635 static inline u64 sched_cfs_bandwidth_slice(void)
1637 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
1641 * Replenish runtime according to assigned quota and update expiration time.
1642 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
1643 * additional synchronization around rq->lock.
1645 * requires cfs_b->lock
1647 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
1651 if (cfs_b->quota == RUNTIME_INF)
1654 now = sched_clock_cpu(smp_processor_id());
1655 cfs_b->runtime = cfs_b->quota;
1656 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
1659 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
1661 return &tg->cfs_bandwidth;
1664 /* returns 0 on failure to allocate runtime */
1665 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
1667 struct task_group *tg = cfs_rq->tg;
1668 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
1669 u64 amount = 0, min_amount, expires;
1671 /* note: this is a positive sum as runtime_remaining <= 0 */
1672 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
1674 raw_spin_lock(&cfs_b->lock);
1675 if (cfs_b->quota == RUNTIME_INF)
1676 amount = min_amount;
1679 * If the bandwidth pool has become inactive, then at least one
1680 * period must have elapsed since the last consumption.
1681 * Refresh the global state and ensure bandwidth timer becomes
1684 if (!cfs_b->timer_active) {
1685 __refill_cfs_bandwidth_runtime(cfs_b);
1686 __start_cfs_bandwidth(cfs_b);
1689 if (cfs_b->runtime > 0) {
1690 amount = min(cfs_b->runtime, min_amount);
1691 cfs_b->runtime -= amount;
1695 expires = cfs_b->runtime_expires;
1696 raw_spin_unlock(&cfs_b->lock);
1698 cfs_rq->runtime_remaining += amount;
1700 * we may have advanced our local expiration to account for allowed
1701 * spread between our sched_clock and the one on which runtime was
1704 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
1705 cfs_rq->runtime_expires = expires;
1707 return cfs_rq->runtime_remaining > 0;
1711 * Note: This depends on the synchronization provided by sched_clock and the
1712 * fact that rq->clock snapshots this value.
1714 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
1716 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1717 struct rq *rq = rq_of(cfs_rq);
1719 /* if the deadline is ahead of our clock, nothing to do */
1720 if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
1723 if (cfs_rq->runtime_remaining < 0)
1727 * If the local deadline has passed we have to consider the
1728 * possibility that our sched_clock is 'fast' and the global deadline
1729 * has not truly expired.
1731 * Fortunately we can check determine whether this the case by checking
1732 * whether the global deadline has advanced.
1735 if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
1736 /* extend local deadline, drift is bounded above by 2 ticks */
1737 cfs_rq->runtime_expires += TICK_NSEC;
1739 /* global deadline is ahead, expiration has passed */
1740 cfs_rq->runtime_remaining = 0;
1744 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
1745 unsigned long delta_exec)
1747 /* dock delta_exec before expiring quota (as it could span periods) */
1748 cfs_rq->runtime_remaining -= delta_exec;
1749 expire_cfs_rq_runtime(cfs_rq);
1751 if (likely(cfs_rq->runtime_remaining > 0))
1755 * if we're unable to extend our runtime we resched so that the active
1756 * hierarchy can be throttled
1758 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
1759 resched_task(rq_of(cfs_rq)->curr);
1762 static __always_inline
1763 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
1765 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
1768 __account_cfs_rq_runtime(cfs_rq, delta_exec);
1771 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
1773 return cfs_bandwidth_used() && cfs_rq->throttled;
1776 /* check whether cfs_rq, or any parent, is throttled */
1777 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
1779 return cfs_bandwidth_used() && cfs_rq->throttle_count;
1783 * Ensure that neither of the group entities corresponding to src_cpu or
1784 * dest_cpu are members of a throttled hierarchy when performing group
1785 * load-balance operations.
1787 static inline int throttled_lb_pair(struct task_group *tg,
1788 int src_cpu, int dest_cpu)
1790 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
1792 src_cfs_rq = tg->cfs_rq[src_cpu];
1793 dest_cfs_rq = tg->cfs_rq[dest_cpu];
1795 return throttled_hierarchy(src_cfs_rq) ||
1796 throttled_hierarchy(dest_cfs_rq);
1799 /* updated child weight may affect parent so we have to do this bottom up */
1800 static int tg_unthrottle_up(struct task_group *tg, void *data)
1802 struct rq *rq = data;
1803 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1805 cfs_rq->throttle_count--;
1807 if (!cfs_rq->throttle_count) {
1808 u64 delta = rq->clock_task - cfs_rq->load_stamp;
1810 /* leaving throttled state, advance shares averaging windows */
1811 cfs_rq->load_stamp += delta;
1812 cfs_rq->load_last += delta;
1814 /* update entity weight now that we are on_rq again */
1815 update_cfs_shares(cfs_rq);
1822 static int tg_throttle_down(struct task_group *tg, void *data)
1824 struct rq *rq = data;
1825 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1827 /* group is entering throttled state, record last load */
1828 if (!cfs_rq->throttle_count)
1829 update_cfs_load(cfs_rq, 0);
1830 cfs_rq->throttle_count++;
1835 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
1837 struct rq *rq = rq_of(cfs_rq);
1838 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1839 struct sched_entity *se;
1840 long task_delta, dequeue = 1;
1842 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
1844 /* account load preceding throttle */
1846 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
1849 task_delta = cfs_rq->h_nr_running;
1850 for_each_sched_entity(se) {
1851 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
1852 /* throttled entity or throttle-on-deactivate */
1857 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
1858 qcfs_rq->h_nr_running -= task_delta;
1860 if (qcfs_rq->load.weight)
1865 rq->nr_running -= task_delta;
1867 cfs_rq->throttled = 1;
1868 cfs_rq->throttled_timestamp = rq->clock;
1869 raw_spin_lock(&cfs_b->lock);
1870 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
1871 raw_spin_unlock(&cfs_b->lock);
1874 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
1876 struct rq *rq = rq_of(cfs_rq);
1877 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1878 struct sched_entity *se;
1882 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
1884 cfs_rq->throttled = 0;
1885 raw_spin_lock(&cfs_b->lock);
1886 cfs_b->throttled_time += rq->clock - cfs_rq->throttled_timestamp;
1887 list_del_rcu(&cfs_rq->throttled_list);
1888 raw_spin_unlock(&cfs_b->lock);
1889 cfs_rq->throttled_timestamp = 0;
1891 update_rq_clock(rq);
1892 /* update hierarchical throttle state */
1893 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
1895 if (!cfs_rq->load.weight)
1898 task_delta = cfs_rq->h_nr_running;
1899 for_each_sched_entity(se) {
1903 cfs_rq = cfs_rq_of(se);
1905 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
1906 cfs_rq->h_nr_running += task_delta;
1908 if (cfs_rq_throttled(cfs_rq))
1913 rq->nr_running += task_delta;
1915 /* determine whether we need to wake up potentially idle cpu */
1916 if (rq->curr == rq->idle && rq->cfs.nr_running)
1917 resched_task(rq->curr);
1920 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
1921 u64 remaining, u64 expires)
1923 struct cfs_rq *cfs_rq;
1924 u64 runtime = remaining;
1927 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
1929 struct rq *rq = rq_of(cfs_rq);
1931 raw_spin_lock(&rq->lock);
1932 if (!cfs_rq_throttled(cfs_rq))
1935 runtime = -cfs_rq->runtime_remaining + 1;
1936 if (runtime > remaining)
1937 runtime = remaining;
1938 remaining -= runtime;
1940 cfs_rq->runtime_remaining += runtime;
1941 cfs_rq->runtime_expires = expires;
1943 /* we check whether we're throttled above */
1944 if (cfs_rq->runtime_remaining > 0)
1945 unthrottle_cfs_rq(cfs_rq);
1948 raw_spin_unlock(&rq->lock);
1959 * Responsible for refilling a task_group's bandwidth and unthrottling its
1960 * cfs_rqs as appropriate. If there has been no activity within the last
1961 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
1962 * used to track this state.
1964 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
1966 u64 runtime, runtime_expires;
1967 int idle = 1, throttled;
1969 raw_spin_lock(&cfs_b->lock);
1970 /* no need to continue the timer with no bandwidth constraint */
1971 if (cfs_b->quota == RUNTIME_INF)
1974 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
1975 /* idle depends on !throttled (for the case of a large deficit) */
1976 idle = cfs_b->idle && !throttled;
1977 cfs_b->nr_periods += overrun;
1979 /* if we're going inactive then everything else can be deferred */
1983 __refill_cfs_bandwidth_runtime(cfs_b);
1986 /* mark as potentially idle for the upcoming period */
1991 /* account preceding periods in which throttling occurred */
1992 cfs_b->nr_throttled += overrun;
1995 * There are throttled entities so we must first use the new bandwidth
1996 * to unthrottle them before making it generally available. This
1997 * ensures that all existing debts will be paid before a new cfs_rq is
2000 runtime = cfs_b->runtime;
2001 runtime_expires = cfs_b->runtime_expires;
2005 * This check is repeated as we are holding onto the new bandwidth
2006 * while we unthrottle. This can potentially race with an unthrottled
2007 * group trying to acquire new bandwidth from the global pool.
2009 while (throttled && runtime > 0) {
2010 raw_spin_unlock(&cfs_b->lock);
2011 /* we can't nest cfs_b->lock while distributing bandwidth */
2012 runtime = distribute_cfs_runtime(cfs_b, runtime,
2014 raw_spin_lock(&cfs_b->lock);
2016 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2019 /* return (any) remaining runtime */
2020 cfs_b->runtime = runtime;
2022 * While we are ensured activity in the period following an
2023 * unthrottle, this also covers the case in which the new bandwidth is
2024 * insufficient to cover the existing bandwidth deficit. (Forcing the
2025 * timer to remain active while there are any throttled entities.)
2030 cfs_b->timer_active = 0;
2031 raw_spin_unlock(&cfs_b->lock);
2036 /* a cfs_rq won't donate quota below this amount */
2037 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
2038 /* minimum remaining period time to redistribute slack quota */
2039 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
2040 /* how long we wait to gather additional slack before distributing */
2041 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
2043 /* are we near the end of the current quota period? */
2044 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
2046 struct hrtimer *refresh_timer = &cfs_b->period_timer;
2049 /* if the call-back is running a quota refresh is already occurring */
2050 if (hrtimer_callback_running(refresh_timer))
2053 /* is a quota refresh about to occur? */
2054 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
2055 if (remaining < min_expire)
2061 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
2063 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
2065 /* if there's a quota refresh soon don't bother with slack */
2066 if (runtime_refresh_within(cfs_b, min_left))
2069 start_bandwidth_timer(&cfs_b->slack_timer,
2070 ns_to_ktime(cfs_bandwidth_slack_period));
2073 /* we know any runtime found here is valid as update_curr() precedes return */
2074 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2076 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2077 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
2079 if (slack_runtime <= 0)
2082 raw_spin_lock(&cfs_b->lock);
2083 if (cfs_b->quota != RUNTIME_INF &&
2084 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
2085 cfs_b->runtime += slack_runtime;
2087 /* we are under rq->lock, defer unthrottling using a timer */
2088 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
2089 !list_empty(&cfs_b->throttled_cfs_rq))
2090 start_cfs_slack_bandwidth(cfs_b);
2092 raw_spin_unlock(&cfs_b->lock);
2094 /* even if it's not valid for return we don't want to try again */
2095 cfs_rq->runtime_remaining -= slack_runtime;
2098 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2100 if (!cfs_bandwidth_used())
2103 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
2106 __return_cfs_rq_runtime(cfs_rq);
2110 * This is done with a timer (instead of inline with bandwidth return) since
2111 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
2113 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
2115 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
2118 /* confirm we're still not at a refresh boundary */
2119 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
2122 raw_spin_lock(&cfs_b->lock);
2123 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
2124 runtime = cfs_b->runtime;
2127 expires = cfs_b->runtime_expires;
2128 raw_spin_unlock(&cfs_b->lock);
2133 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
2135 raw_spin_lock(&cfs_b->lock);
2136 if (expires == cfs_b->runtime_expires)
2137 cfs_b->runtime = runtime;
2138 raw_spin_unlock(&cfs_b->lock);
2142 * When a group wakes up we want to make sure that its quota is not already
2143 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
2144 * runtime as update_curr() throttling can not not trigger until it's on-rq.
2146 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
2148 if (!cfs_bandwidth_used())
2151 /* an active group must be handled by the update_curr()->put() path */
2152 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
2155 /* ensure the group is not already throttled */
2156 if (cfs_rq_throttled(cfs_rq))
2159 /* update runtime allocation */
2160 account_cfs_rq_runtime(cfs_rq, 0);
2161 if (cfs_rq->runtime_remaining <= 0)
2162 throttle_cfs_rq(cfs_rq);
2165 /* conditionally throttle active cfs_rq's from put_prev_entity() */
2166 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2168 if (!cfs_bandwidth_used())
2171 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
2175 * it's possible for a throttled entity to be forced into a running
2176 * state (e.g. set_curr_task), in this case we're finished.
2178 if (cfs_rq_throttled(cfs_rq))
2181 throttle_cfs_rq(cfs_rq);
2184 static inline u64 default_cfs_period(void);
2185 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
2186 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
2188 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
2190 struct cfs_bandwidth *cfs_b =
2191 container_of(timer, struct cfs_bandwidth, slack_timer);
2192 do_sched_cfs_slack_timer(cfs_b);
2194 return HRTIMER_NORESTART;
2197 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
2199 struct cfs_bandwidth *cfs_b =
2200 container_of(timer, struct cfs_bandwidth, period_timer);
2206 now = hrtimer_cb_get_time(timer);
2207 overrun = hrtimer_forward(timer, now, cfs_b->period);
2212 idle = do_sched_cfs_period_timer(cfs_b, overrun);
2215 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
2218 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2220 raw_spin_lock_init(&cfs_b->lock);
2222 cfs_b->quota = RUNTIME_INF;
2223 cfs_b->period = ns_to_ktime(default_cfs_period());
2225 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
2226 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2227 cfs_b->period_timer.function = sched_cfs_period_timer;
2228 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2229 cfs_b->slack_timer.function = sched_cfs_slack_timer;
2232 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2234 cfs_rq->runtime_enabled = 0;
2235 INIT_LIST_HEAD(&cfs_rq->throttled_list);
2238 /* requires cfs_b->lock, may release to reprogram timer */
2239 void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2242 * The timer may be active because we're trying to set a new bandwidth
2243 * period or because we're racing with the tear-down path
2244 * (timer_active==0 becomes visible before the hrtimer call-back
2245 * terminates). In either case we ensure that it's re-programmed
2247 while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
2248 raw_spin_unlock(&cfs_b->lock);
2249 /* ensure cfs_b->lock is available while we wait */
2250 hrtimer_cancel(&cfs_b->period_timer);
2252 raw_spin_lock(&cfs_b->lock);
2253 /* if someone else restarted the timer then we're done */
2254 if (cfs_b->timer_active)
2258 cfs_b->timer_active = 1;
2259 start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
2262 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2264 hrtimer_cancel(&cfs_b->period_timer);
2265 hrtimer_cancel(&cfs_b->slack_timer);
2268 static void unthrottle_offline_cfs_rqs(struct rq *rq)
2270 struct cfs_rq *cfs_rq;
2272 for_each_leaf_cfs_rq(rq, cfs_rq) {
2273 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2275 if (!cfs_rq->runtime_enabled)
2279 * clock_task is not advancing so we just need to make sure
2280 * there's some valid quota amount
2282 cfs_rq->runtime_remaining = cfs_b->quota;
2283 if (cfs_rq_throttled(cfs_rq))
2284 unthrottle_cfs_rq(cfs_rq);
2288 #else /* CONFIG_CFS_BANDWIDTH */
2289 static __always_inline
2290 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec) {}
2291 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2292 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
2293 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2295 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2300 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2305 static inline int throttled_lb_pair(struct task_group *tg,
2306 int src_cpu, int dest_cpu)
2311 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2313 #ifdef CONFIG_FAIR_GROUP_SCHED
2314 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2317 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2321 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2322 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
2324 #endif /* CONFIG_CFS_BANDWIDTH */
2326 /**************************************************
2327 * CFS operations on tasks:
2330 #ifdef CONFIG_SCHED_HRTICK
2331 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
2333 struct sched_entity *se = &p->se;
2334 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2336 WARN_ON(task_rq(p) != rq);
2338 if (cfs_rq->nr_running > 1) {
2339 u64 slice = sched_slice(cfs_rq, se);
2340 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
2341 s64 delta = slice - ran;
2350 * Don't schedule slices shorter than 10000ns, that just
2351 * doesn't make sense. Rely on vruntime for fairness.
2354 delta = max_t(s64, 10000LL, delta);
2356 hrtick_start(rq, delta);
2361 * called from enqueue/dequeue and updates the hrtick when the
2362 * current task is from our class and nr_running is low enough
2365 static void hrtick_update(struct rq *rq)
2367 struct task_struct *curr = rq->curr;
2369 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
2372 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
2373 hrtick_start_fair(rq, curr);
2375 #else /* !CONFIG_SCHED_HRTICK */
2377 hrtick_start_fair(struct rq *rq, struct task_struct *p)
2381 static inline void hrtick_update(struct rq *rq)
2387 * The enqueue_task method is called before nr_running is
2388 * increased. Here we update the fair scheduling stats and
2389 * then put the task into the rbtree:
2392 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
2394 struct cfs_rq *cfs_rq;
2395 struct sched_entity *se = &p->se;
2397 for_each_sched_entity(se) {
2400 cfs_rq = cfs_rq_of(se);
2401 enqueue_entity(cfs_rq, se, flags);
2404 * end evaluation on encountering a throttled cfs_rq
2406 * note: in the case of encountering a throttled cfs_rq we will
2407 * post the final h_nr_running increment below.
2409 if (cfs_rq_throttled(cfs_rq))
2411 cfs_rq->h_nr_running++;
2413 flags = ENQUEUE_WAKEUP;
2416 for_each_sched_entity(se) {
2417 cfs_rq = cfs_rq_of(se);
2418 cfs_rq->h_nr_running++;
2420 if (cfs_rq_throttled(cfs_rq))
2423 update_cfs_load(cfs_rq, 0);
2424 update_cfs_shares(cfs_rq);
2432 static void set_next_buddy(struct sched_entity *se);
2435 * The dequeue_task method is called before nr_running is
2436 * decreased. We remove the task from the rbtree and
2437 * update the fair scheduling stats:
2439 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
2441 struct cfs_rq *cfs_rq;
2442 struct sched_entity *se = &p->se;
2443 int task_sleep = flags & DEQUEUE_SLEEP;
2445 for_each_sched_entity(se) {
2446 cfs_rq = cfs_rq_of(se);
2447 dequeue_entity(cfs_rq, se, flags);
2450 * end evaluation on encountering a throttled cfs_rq
2452 * note: in the case of encountering a throttled cfs_rq we will
2453 * post the final h_nr_running decrement below.
2455 if (cfs_rq_throttled(cfs_rq))
2457 cfs_rq->h_nr_running--;
2459 /* Don't dequeue parent if it has other entities besides us */
2460 if (cfs_rq->load.weight) {
2462 * Bias pick_next to pick a task from this cfs_rq, as
2463 * p is sleeping when it is within its sched_slice.
2465 if (task_sleep && parent_entity(se))
2466 set_next_buddy(parent_entity(se));
2468 /* avoid re-evaluating load for this entity */
2469 se = parent_entity(se);
2472 flags |= DEQUEUE_SLEEP;
2475 for_each_sched_entity(se) {
2476 cfs_rq = cfs_rq_of(se);
2477 cfs_rq->h_nr_running--;
2479 if (cfs_rq_throttled(cfs_rq))
2482 update_cfs_load(cfs_rq, 0);
2483 update_cfs_shares(cfs_rq);
2492 /* Used instead of source_load when we know the type == 0 */
2493 static unsigned long weighted_cpuload(const int cpu)
2495 return cpu_rq(cpu)->load.weight;
2499 * Return a low guess at the load of a migration-source cpu weighted
2500 * according to the scheduling class and "nice" value.
2502 * We want to under-estimate the load of migration sources, to
2503 * balance conservatively.
2505 static unsigned long source_load(int cpu, int type)
2507 struct rq *rq = cpu_rq(cpu);
2508 unsigned long total = weighted_cpuload(cpu);
2510 if (type == 0 || !sched_feat(LB_BIAS))
2513 return min(rq->cpu_load[type-1], total);
2517 * Return a high guess at the load of a migration-target cpu weighted
2518 * according to the scheduling class and "nice" value.
2520 static unsigned long target_load(int cpu, int type)
2522 struct rq *rq = cpu_rq(cpu);
2523 unsigned long total = weighted_cpuload(cpu);
2525 if (type == 0 || !sched_feat(LB_BIAS))
2528 return max(rq->cpu_load[type-1], total);
2531 static unsigned long power_of(int cpu)
2533 return cpu_rq(cpu)->cpu_power;
2536 static unsigned long cpu_avg_load_per_task(int cpu)
2538 struct rq *rq = cpu_rq(cpu);
2539 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
2542 return rq->load.weight / nr_running;
2548 static void task_waking_fair(struct task_struct *p)
2550 struct sched_entity *se = &p->se;
2551 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2554 #ifndef CONFIG_64BIT
2555 u64 min_vruntime_copy;
2558 min_vruntime_copy = cfs_rq->min_vruntime_copy;
2560 min_vruntime = cfs_rq->min_vruntime;
2561 } while (min_vruntime != min_vruntime_copy);
2563 min_vruntime = cfs_rq->min_vruntime;
2566 se->vruntime -= min_vruntime;
2569 #ifdef CONFIG_FAIR_GROUP_SCHED
2571 * effective_load() calculates the load change as seen from the root_task_group
2573 * Adding load to a group doesn't make a group heavier, but can cause movement
2574 * of group shares between cpus. Assuming the shares were perfectly aligned one
2575 * can calculate the shift in shares.
2577 * Calculate the effective load difference if @wl is added (subtracted) to @tg
2578 * on this @cpu and results in a total addition (subtraction) of @wg to the
2579 * total group weight.
2581 * Given a runqueue weight distribution (rw_i) we can compute a shares
2582 * distribution (s_i) using:
2584 * s_i = rw_i / \Sum rw_j (1)
2586 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
2587 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
2588 * shares distribution (s_i):
2590 * rw_i = { 2, 4, 1, 0 }
2591 * s_i = { 2/7, 4/7, 1/7, 0 }
2593 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
2594 * task used to run on and the CPU the waker is running on), we need to
2595 * compute the effect of waking a task on either CPU and, in case of a sync
2596 * wakeup, compute the effect of the current task going to sleep.
2598 * So for a change of @wl to the local @cpu with an overall group weight change
2599 * of @wl we can compute the new shares distribution (s'_i) using:
2601 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
2603 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
2604 * differences in waking a task to CPU 0. The additional task changes the
2605 * weight and shares distributions like:
2607 * rw'_i = { 3, 4, 1, 0 }
2608 * s'_i = { 3/8, 4/8, 1/8, 0 }
2610 * We can then compute the difference in effective weight by using:
2612 * dw_i = S * (s'_i - s_i) (3)
2614 * Where 'S' is the group weight as seen by its parent.
2616 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
2617 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
2618 * 4/7) times the weight of the group.
2620 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
2622 struct sched_entity *se = tg->se[cpu];
2624 if (!tg->parent) /* the trivial, non-cgroup case */
2627 for_each_sched_entity(se) {
2633 * W = @wg + \Sum rw_j
2635 W = wg + calc_tg_weight(tg, se->my_q);
2640 w = se->my_q->load.weight + wl;
2643 * wl = S * s'_i; see (2)
2646 wl = (w * tg->shares) / W;
2651 * Per the above, wl is the new se->load.weight value; since
2652 * those are clipped to [MIN_SHARES, ...) do so now. See
2653 * calc_cfs_shares().
2655 if (wl < MIN_SHARES)
2659 * wl = dw_i = S * (s'_i - s_i); see (3)
2661 wl -= se->load.weight;
2664 * Recursively apply this logic to all parent groups to compute
2665 * the final effective load change on the root group. Since
2666 * only the @tg group gets extra weight, all parent groups can
2667 * only redistribute existing shares. @wl is the shift in shares
2668 * resulting from this level per the above.
2677 static inline unsigned long effective_load(struct task_group *tg, int cpu,
2678 unsigned long wl, unsigned long wg)
2685 static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
2687 s64 this_load, load;
2688 int idx, this_cpu, prev_cpu;
2689 unsigned long tl_per_task;
2690 struct task_group *tg;
2691 unsigned long weight;
2695 this_cpu = smp_processor_id();
2696 prev_cpu = task_cpu(p);
2697 load = source_load(prev_cpu, idx);
2698 this_load = target_load(this_cpu, idx);
2701 * If sync wakeup then subtract the (maximum possible)
2702 * effect of the currently running task from the load
2703 * of the current CPU:
2706 tg = task_group(current);
2707 weight = current->se.load.weight;
2709 this_load += effective_load(tg, this_cpu, -weight, -weight);
2710 load += effective_load(tg, prev_cpu, 0, -weight);
2714 weight = p->se.load.weight;
2717 * In low-load situations, where prev_cpu is idle and this_cpu is idle
2718 * due to the sync cause above having dropped this_load to 0, we'll
2719 * always have an imbalance, but there's really nothing you can do
2720 * about that, so that's good too.
2722 * Otherwise check if either cpus are near enough in load to allow this
2723 * task to be woken on this_cpu.
2725 if (this_load > 0) {
2726 s64 this_eff_load, prev_eff_load;
2728 this_eff_load = 100;
2729 this_eff_load *= power_of(prev_cpu);
2730 this_eff_load *= this_load +
2731 effective_load(tg, this_cpu, weight, weight);
2733 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
2734 prev_eff_load *= power_of(this_cpu);
2735 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
2737 balanced = this_eff_load <= prev_eff_load;
2742 * If the currently running task will sleep within
2743 * a reasonable amount of time then attract this newly
2746 if (sync && balanced)
2749 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
2750 tl_per_task = cpu_avg_load_per_task(this_cpu);
2753 (this_load <= load &&
2754 this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
2756 * This domain has SD_WAKE_AFFINE and
2757 * p is cache cold in this domain, and
2758 * there is no bad imbalance.
2760 schedstat_inc(sd, ttwu_move_affine);
2761 schedstat_inc(p, se.statistics.nr_wakeups_affine);
2769 * find_idlest_group finds and returns the least busy CPU group within the
2772 static struct sched_group *
2773 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
2774 int this_cpu, int load_idx)
2776 struct sched_group *idlest = NULL, *group = sd->groups;
2777 unsigned long min_load = ULONG_MAX, this_load = 0;
2778 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2781 unsigned long load, avg_load;
2785 /* Skip over this group if it has no CPUs allowed */
2786 if (!cpumask_intersects(sched_group_cpus(group),
2787 tsk_cpus_allowed(p)))
2790 local_group = cpumask_test_cpu(this_cpu,
2791 sched_group_cpus(group));
2793 /* Tally up the load of all CPUs in the group */
2796 for_each_cpu(i, sched_group_cpus(group)) {
2797 /* Bias balancing toward cpus of our domain */
2799 load = source_load(i, load_idx);
2801 load = target_load(i, load_idx);
2806 /* Adjust by relative CPU power of the group */
2807 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
2810 this_load = avg_load;
2811 } else if (avg_load < min_load) {
2812 min_load = avg_load;
2815 } while (group = group->next, group != sd->groups);
2817 if (!idlest || 100*this_load < imbalance*min_load)
2823 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2826 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2828 unsigned long load, min_load = ULONG_MAX;
2832 /* Traverse only the allowed CPUs */
2833 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
2834 load = weighted_cpuload(i);
2836 if (load < min_load || (load == min_load && i == this_cpu)) {
2846 * Try and locate an idle CPU in the sched_domain.
2848 static int select_idle_sibling(struct task_struct *p, int target)
2850 int cpu = smp_processor_id();
2851 int prev_cpu = task_cpu(p);
2852 struct sched_domain *sd;
2853 struct sched_group *sg;
2857 * If the task is going to be woken-up on this cpu and if it is
2858 * already idle, then it is the right target.
2860 if (target == cpu && idle_cpu(cpu))
2864 * If the task is going to be woken-up on the cpu where it previously
2865 * ran and if it is currently idle, then it the right target.
2867 if (target == prev_cpu && idle_cpu(prev_cpu))
2871 * Otherwise, iterate the domains and find an elegible idle cpu.
2873 sd = rcu_dereference(per_cpu(sd_llc, target));
2874 for_each_lower_domain(sd) {
2877 if (!cpumask_intersects(sched_group_cpus(sg),
2878 tsk_cpus_allowed(p)))
2881 for_each_cpu(i, sched_group_cpus(sg)) {
2886 target = cpumask_first_and(sched_group_cpus(sg),
2887 tsk_cpus_allowed(p));
2891 } while (sg != sd->groups);
2897 #ifdef CONFIG_SCHED_NUMA
2898 static inline bool pick_numa_rand(int n)
2900 return !(get_random_int() % n);
2904 * Pick a random elegible CPU in the target node, hopefully faster
2905 * than doing a least-loaded scan.
2907 static int numa_select_node_cpu(struct task_struct *p, int node)
2909 int weight = cpumask_weight(cpumask_of_node(node));
2912 for_each_cpu_and(i, cpumask_of_node(node), tsk_cpus_allowed(p)) {
2913 if (cpu < 0 || pick_numa_rand(weight))
2920 static int numa_select_node_cpu(struct task_struct *p, int node)
2924 #endif /* CONFIG_SCHED_NUMA */
2927 * sched_balance_self: balance the current task (running on cpu) in domains
2928 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2931 * Balance, ie. select the least loaded group.
2933 * Returns the target CPU number, or the same CPU if no balancing is needed.
2935 * preempt must be disabled.
2938 select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
2940 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
2941 int cpu = smp_processor_id();
2942 int prev_cpu = task_cpu(p);
2944 int want_affine = 0;
2945 int sync = wake_flags & WF_SYNC;
2946 int node = tsk_home_node(p);
2948 if (p->nr_cpus_allowed == 1)
2951 if (sd_flag & SD_BALANCE_WAKE) {
2952 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
2958 if (sched_feat_numa(NUMA_TTWU_BIAS) && node != -1) {
2960 * For fork,exec find the idlest cpu in the home-node.
2962 if (sd_flag & (SD_BALANCE_FORK|SD_BALANCE_EXEC)) {
2963 int node_cpu = numa_select_node_cpu(p, node);
2967 new_cpu = cpu = node_cpu;
2968 sd = per_cpu(sd_node, cpu);
2973 * For wake, pretend we were running in the home-node.
2975 if (cpu_to_node(prev_cpu) != node) {
2976 int node_cpu = numa_select_node_cpu(p, node);
2980 if (sched_feat_numa(NUMA_TTWU_TO))
2983 prev_cpu = node_cpu;
2988 for_each_domain(cpu, tmp) {
2989 if (!(tmp->flags & SD_LOAD_BALANCE))
2993 * If both cpu and prev_cpu are part of this domain,
2994 * cpu is a valid SD_WAKE_AFFINE target.
2996 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
2997 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
3002 if (tmp->flags & sd_flag)
3007 if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
3010 new_cpu = select_idle_sibling(p, prev_cpu);
3016 int load_idx = sd->forkexec_idx;
3017 struct sched_group *group;
3020 if (!(sd->flags & sd_flag)) {
3025 if (sd_flag & SD_BALANCE_WAKE)
3026 load_idx = sd->wake_idx;
3028 group = find_idlest_group(sd, p, cpu, load_idx);
3034 new_cpu = find_idlest_cpu(group, p, cpu);
3035 if (new_cpu == -1 || new_cpu == cpu) {
3036 /* Now try balancing at a lower domain level of cpu */
3041 /* Now try balancing at a lower domain level of new_cpu */
3043 weight = sd->span_weight;
3045 for_each_domain(cpu, tmp) {
3046 if (weight <= tmp->span_weight)
3048 if (tmp->flags & sd_flag)
3051 /* while loop will break here if sd == NULL */
3058 #endif /* CONFIG_SMP */
3060 static unsigned long
3061 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
3063 unsigned long gran = sysctl_sched_wakeup_granularity;
3066 * Since its curr running now, convert the gran from real-time
3067 * to virtual-time in his units.
3069 * By using 'se' instead of 'curr' we penalize light tasks, so
3070 * they get preempted easier. That is, if 'se' < 'curr' then
3071 * the resulting gran will be larger, therefore penalizing the
3072 * lighter, if otoh 'se' > 'curr' then the resulting gran will
3073 * be smaller, again penalizing the lighter task.
3075 * This is especially important for buddies when the leftmost
3076 * task is higher priority than the buddy.
3078 return calc_delta_fair(gran, se);
3082 * Should 'se' preempt 'curr'.
3096 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
3098 s64 gran, vdiff = curr->vruntime - se->vruntime;
3103 gran = wakeup_gran(curr, se);
3110 static void set_last_buddy(struct sched_entity *se)
3112 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3115 for_each_sched_entity(se)
3116 cfs_rq_of(se)->last = se;
3119 static void set_next_buddy(struct sched_entity *se)
3121 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3124 for_each_sched_entity(se)
3125 cfs_rq_of(se)->next = se;
3128 static void set_skip_buddy(struct sched_entity *se)
3130 for_each_sched_entity(se)
3131 cfs_rq_of(se)->skip = se;
3135 * Preempt the current task with a newly woken task if needed:
3137 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
3139 struct task_struct *curr = rq->curr;
3140 struct sched_entity *se = &curr->se, *pse = &p->se;
3141 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
3142 int scale = cfs_rq->nr_running >= sched_nr_latency;
3143 int next_buddy_marked = 0;
3145 if (unlikely(se == pse))
3149 * This is possible from callers such as move_task(), in which we
3150 * unconditionally check_prempt_curr() after an enqueue (which may have
3151 * lead to a throttle). This both saves work and prevents false
3152 * next-buddy nomination below.
3154 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
3157 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
3158 set_next_buddy(pse);
3159 next_buddy_marked = 1;
3163 * We can come here with TIF_NEED_RESCHED already set from new task
3166 * Note: this also catches the edge-case of curr being in a throttled
3167 * group (e.g. via set_curr_task), since update_curr() (in the
3168 * enqueue of curr) will have resulted in resched being set. This
3169 * prevents us from potentially nominating it as a false LAST_BUDDY
3172 if (test_tsk_need_resched(curr))
3175 /* Idle tasks are by definition preempted by non-idle tasks. */
3176 if (unlikely(curr->policy == SCHED_IDLE) &&
3177 likely(p->policy != SCHED_IDLE))
3181 * Batch and idle tasks do not preempt non-idle tasks (their preemption
3182 * is driven by the tick):
3184 if (unlikely(p->policy != SCHED_NORMAL))
3187 find_matching_se(&se, &pse);
3188 update_curr(cfs_rq_of(se));
3190 if (wakeup_preempt_entity(se, pse) == 1) {
3192 * Bias pick_next to pick the sched entity that is
3193 * triggering this preemption.
3195 if (!next_buddy_marked)
3196 set_next_buddy(pse);
3205 * Only set the backward buddy when the current task is still
3206 * on the rq. This can happen when a wakeup gets interleaved
3207 * with schedule on the ->pre_schedule() or idle_balance()
3208 * point, either of which can * drop the rq lock.
3210 * Also, during early boot the idle thread is in the fair class,
3211 * for obvious reasons its a bad idea to schedule back to it.
3213 if (unlikely(!se->on_rq || curr == rq->idle))
3216 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
3220 static struct task_struct *pick_next_task_fair(struct rq *rq)
3222 struct task_struct *p;
3223 struct cfs_rq *cfs_rq = &rq->cfs;
3224 struct sched_entity *se;
3226 if (!cfs_rq->nr_running)
3230 se = pick_next_entity(cfs_rq);
3231 set_next_entity(cfs_rq, se);
3232 cfs_rq = group_cfs_rq(se);
3236 if (hrtick_enabled(rq))
3237 hrtick_start_fair(rq, p);
3243 * Account for a descheduled task:
3245 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
3247 struct sched_entity *se = &prev->se;
3248 struct cfs_rq *cfs_rq;
3250 for_each_sched_entity(se) {
3251 cfs_rq = cfs_rq_of(se);
3252 put_prev_entity(cfs_rq, se);
3257 * sched_yield() is very simple
3259 * The magic of dealing with the ->skip buddy is in pick_next_entity.
3261 static void yield_task_fair(struct rq *rq)
3263 struct task_struct *curr = rq->curr;
3264 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
3265 struct sched_entity *se = &curr->se;
3268 * Are we the only task in the tree?
3270 if (unlikely(rq->nr_running == 1))
3273 clear_buddies(cfs_rq, se);
3275 if (curr->policy != SCHED_BATCH) {
3276 update_rq_clock(rq);
3278 * Update run-time statistics of the 'current'.
3280 update_curr(cfs_rq);
3282 * Tell update_rq_clock() that we've just updated,
3283 * so we don't do microscopic update in schedule()
3284 * and double the fastpath cost.
3286 rq->skip_clock_update = 1;
3292 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
3294 struct sched_entity *se = &p->se;
3296 /* throttled hierarchies are not runnable */
3297 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
3300 /* Tell the scheduler that we'd really like pse to run next. */
3303 yield_task_fair(rq);
3309 /**************************************************
3310 * Fair scheduling class load-balancing methods:
3313 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
3315 #define LBF_ALL_PINNED 0x01
3316 #define LBF_NEED_BREAK 0x02
3317 #define LBF_SOME_PINNED 0x04
3320 struct sched_domain *sd;
3328 struct cpumask *dst_grpmask;
3330 enum cpu_idle_type idle;
3332 /* The set of CPUs under consideration for load-balancing */
3333 struct cpumask *cpus;
3337 struct list_head *tasks;
3340 unsigned int loop_break;
3341 unsigned int loop_max;
3343 struct rq * (*find_busiest_queue)(struct lb_env *,
3344 struct sched_group *);
3348 * move_task - move a task from one runqueue to another runqueue.
3349 * Both runqueues must be locked.
3351 static void move_task(struct task_struct *p, struct lb_env *env)
3353 deactivate_task(env->src_rq, p, 0);
3354 set_task_cpu(p, env->dst_cpu);
3355 activate_task(env->dst_rq, p, 0);
3356 check_preempt_curr(env->dst_rq, p, 0);
3359 static int task_numa_hot(struct task_struct *p, struct lb_env *env)
3361 int from_dist, to_dist;
3362 int node = tsk_home_node(p);
3364 if (!sched_feat_numa(NUMA_HOT) || node == -1)
3365 return 0; /* no node preference */
3367 from_dist = node_distance(cpu_to_node(env->src_cpu), node);
3368 to_dist = node_distance(cpu_to_node(env->dst_cpu), node);
3370 if (to_dist < from_dist)
3371 return 0; /* getting closer is ok */
3373 return 1; /* stick to where we are */
3377 * Is this task likely cache-hot:
3380 task_hot(struct task_struct *p, struct lb_env *env)
3384 if (p->sched_class != &fair_sched_class)
3387 if (unlikely(p->policy == SCHED_IDLE))
3391 * Buddy candidates are cache hot:
3393 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
3394 (&p->se == cfs_rq_of(&p->se)->next ||
3395 &p->se == cfs_rq_of(&p->se)->last))
3398 if (sysctl_sched_migration_cost == -1)
3400 if (sysctl_sched_migration_cost == 0)
3403 delta = env->src_rq->clock_task - p->se.exec_start;
3405 return delta < (s64)sysctl_sched_migration_cost;
3409 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3412 int can_migrate_task(struct task_struct *p, struct lb_env *env)
3414 int tsk_cache_hot = 0;
3416 * We do not migrate tasks that are:
3417 * 1) running (obviously), or
3418 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3419 * 3) are cache-hot on their current CPU.
3421 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
3424 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
3427 * Remember if this task can be migrated to any other cpu in
3428 * our sched_group. We may want to revisit it if we couldn't
3429 * meet load balance goals by pulling other tasks on src_cpu.
3431 * Also avoid computing new_dst_cpu if we have already computed
3432 * one in current iteration.
3434 if (!env->dst_grpmask || (env->flags & LBF_SOME_PINNED))
3437 new_dst_cpu = cpumask_first_and(env->dst_grpmask,
3438 tsk_cpus_allowed(p));
3439 if (new_dst_cpu < nr_cpu_ids) {
3440 env->flags |= LBF_SOME_PINNED;
3441 env->new_dst_cpu = new_dst_cpu;
3446 /* Record that we found atleast one task that could run on dst_cpu */
3447 env->flags &= ~LBF_ALL_PINNED;
3449 if (task_running(env->src_rq, p)) {
3450 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
3455 * Aggressive migration if:
3456 * 1) task is cache cold, or
3457 * 2) too many balance attempts have failed.
3460 tsk_cache_hot = task_hot(p, env);
3461 if (env->idle == CPU_NOT_IDLE)
3462 tsk_cache_hot |= task_numa_hot(p, env);
3463 if (!tsk_cache_hot ||
3464 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
3465 #ifdef CONFIG_SCHEDSTATS
3466 if (tsk_cache_hot) {
3467 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
3468 schedstat_inc(p, se.statistics.nr_forced_migrations);
3474 if (tsk_cache_hot) {
3475 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
3482 * move_one_task tries to move exactly one task from busiest to this_rq, as
3483 * part of active balancing operations within "domain".
3484 * Returns 1 if successful and 0 otherwise.
3486 * Called with both runqueues locked.
3488 static int __move_one_task(struct lb_env *env)
3490 struct task_struct *p, *n;
3492 list_for_each_entry_safe(p, n, env->tasks, se.group_node) {
3493 if (throttled_lb_pair(task_group(p), env->src_rq->cpu, env->dst_cpu))
3496 if (!can_migrate_task(p, env))
3501 * Right now, this is only the second place move_task()
3502 * is called, so we can safely collect move_task()
3503 * stats here rather than inside move_task().
3505 schedstat_inc(env->sd, lb_gained[env->idle]);
3511 static int move_one_task(struct lb_env *env)
3513 if (sched_feat_numa(NUMA_PULL)) {
3514 env->tasks = offnode_tasks(env->src_rq);
3515 if (__move_one_task(env))
3519 env->tasks = &env->src_rq->cfs_tasks;
3520 if (__move_one_task(env))
3526 static const unsigned int sched_nr_migrate_break = 32;
3529 * move_tasks tries to move up to imbalance weighted load from busiest to
3530 * this_rq, as part of a balancing operation within domain "sd".
3531 * Returns 1 if successful and 0 otherwise.
3533 * Called with both runqueues locked.
3535 static int move_tasks(struct lb_env *env)
3537 struct task_struct *p;
3541 if (env->imbalance <= 0)
3545 while (!list_empty(env->tasks)) {
3546 p = list_first_entry(env->tasks, struct task_struct, se.group_node);
3549 /* We've more or less seen every task there is, call it quits */
3550 if (env->loop > env->loop_max)
3553 /* take a breather every nr_migrate tasks */
3554 if (env->loop > env->loop_break) {
3555 env->loop_break += sched_nr_migrate_break;
3556 env->flags |= LBF_NEED_BREAK;
3560 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
3563 load = task_h_load(p);
3565 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
3568 if ((load / 2) > env->imbalance)
3571 if (!can_migrate_task(p, env))
3576 env->imbalance -= load;
3578 #ifdef CONFIG_PREEMPT
3580 * NEWIDLE balancing is a source of latency, so preemptible
3581 * kernels will stop after the first task is pulled to minimize
3582 * the critical section.
3584 if (env->idle == CPU_NEWLY_IDLE)
3589 * We only want to steal up to the prescribed amount of
3592 if (env->imbalance <= 0)
3597 list_move_tail(&p->se.group_node, env->tasks);
3600 if (env->tasks == offnode_tasks(env->src_rq)) {
3601 env->tasks = &env->src_rq->cfs_tasks;
3608 * Right now, this is one of only two places move_task() is called,
3609 * so we can safely collect move_task() stats here rather than
3610 * inside move_task().
3612 schedstat_add(env->sd, lb_gained[env->idle], pulled);
3617 #ifdef CONFIG_FAIR_GROUP_SCHED
3619 * update tg->load_weight by folding this cpu's load_avg
3621 static int update_shares_cpu(struct task_group *tg, int cpu)
3623 struct cfs_rq *cfs_rq;
3624 unsigned long flags;
3631 cfs_rq = tg->cfs_rq[cpu];
3633 raw_spin_lock_irqsave(&rq->lock, flags);
3635 update_rq_clock(rq);
3636 update_cfs_load(cfs_rq, 1);
3639 * We need to update shares after updating tg->load_weight in
3640 * order to adjust the weight of groups with long running tasks.
3642 update_cfs_shares(cfs_rq);
3644 raw_spin_unlock_irqrestore(&rq->lock, flags);
3649 static void update_shares(int cpu)
3651 struct cfs_rq *cfs_rq;
3652 struct rq *rq = cpu_rq(cpu);
3656 * Iterates the task_group tree in a bottom up fashion, see
3657 * list_add_leaf_cfs_rq() for details.
3659 for_each_leaf_cfs_rq(rq, cfs_rq) {
3660 /* throttled entities do not contribute to load */
3661 if (throttled_hierarchy(cfs_rq))
3664 update_shares_cpu(cfs_rq->tg, cpu);
3670 * Compute the cpu's hierarchical load factor for each task group.
3671 * This needs to be done in a top-down fashion because the load of a child
3672 * group is a fraction of its parents load.
3674 static int tg_load_down(struct task_group *tg, void *data)
3677 long cpu = (long)data;
3680 load = cpu_rq(cpu)->load.weight;
3682 load = tg->parent->cfs_rq[cpu]->h_load;
3683 load *= tg->se[cpu]->load.weight;
3684 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
3687 tg->cfs_rq[cpu]->h_load = load;
3692 static void update_h_load(long cpu)
3694 struct rq *rq = cpu_rq(cpu);
3695 unsigned long now = jiffies;
3697 if (rq->h_load_throttle == now)
3700 rq->h_load_throttle = now;
3703 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
3707 static unsigned long task_h_load(struct task_struct *p)
3709 struct cfs_rq *cfs_rq = task_cfs_rq(p);
3712 load = p->se.load.weight;
3713 load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
3718 static inline void update_shares(int cpu)
3722 static inline void update_h_load(long cpu)
3726 static unsigned long task_h_load(struct task_struct *p)
3728 return p->se.load.weight;
3732 /********** Helpers for find_busiest_group ************************/
3734 * sd_lb_stats - Structure to store the statistics of a sched_domain
3735 * during load balancing.
3737 struct sd_lb_stats {
3738 struct sched_group *busiest; /* Busiest group in this sd */
3739 struct sched_group *this; /* Local group in this sd */
3740 unsigned long total_load; /* Total load of all groups in sd */
3741 unsigned long total_pwr; /* Total power of all groups in sd */
3742 unsigned long avg_load; /* Average load across all groups in sd */
3744 /** Statistics of this group */
3745 unsigned long this_load;
3746 unsigned long this_load_per_task;
3747 unsigned long this_nr_running;
3748 unsigned long this_has_capacity;
3749 unsigned int this_idle_cpus;
3751 /* Statistics of the busiest group */
3752 unsigned int busiest_idle_cpus;
3753 unsigned long max_load;
3754 unsigned long busiest_load_per_task;
3755 unsigned long busiest_nr_running;
3756 unsigned long busiest_group_capacity;
3757 unsigned long busiest_has_capacity;
3758 unsigned int busiest_group_weight;
3760 int group_imb; /* Is there imbalance in this sd */
3761 #ifdef CONFIG_SCHED_NUMA
3762 struct sched_group *numa_group; /* group which has offnode_tasks */
3763 unsigned long numa_group_weight;
3764 unsigned long numa_group_running;
3769 * sg_lb_stats - stats of a sched_group required for load_balancing
3771 struct sg_lb_stats {
3772 unsigned long avg_load; /*Avg load across the CPUs of the group */
3773 unsigned long group_load; /* Total load over the CPUs of the group */
3774 unsigned long sum_nr_running; /* Nr tasks running in the group */
3775 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3776 unsigned long group_capacity;
3777 unsigned long idle_cpus;
3778 unsigned long group_weight;
3779 int group_imb; /* Is there an imbalance in the group ? */
3780 int group_has_capacity; /* Is there extra capacity in the group? */
3781 #ifdef CONFIG_SCHED_NUMA
3782 unsigned long numa_weight;
3783 unsigned long numa_running;
3788 * get_sd_load_idx - Obtain the load index for a given sched domain.
3789 * @sd: The sched_domain whose load_idx is to be obtained.
3790 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3792 static inline int get_sd_load_idx(struct sched_domain *sd,
3793 enum cpu_idle_type idle)
3799 load_idx = sd->busy_idx;
3802 case CPU_NEWLY_IDLE:
3803 load_idx = sd->newidle_idx;
3806 load_idx = sd->idle_idx;
3813 #ifdef CONFIG_SCHED_NUMA
3814 static inline void update_sg_numa_stats(struct sg_lb_stats *sgs, struct rq *rq)
3816 sgs->numa_weight += rq->offnode_weight;
3817 sgs->numa_running += rq->offnode_running;
3821 * Since the offnode lists are indiscriminate (they contain tasks for all other
3822 * nodes) it is impossible to say if there's any task on there that wants to
3823 * move towards the pulling cpu. Therefore select a random offnode list to pull
3824 * from such that eventually we'll try them all.
3826 * Select a random group that has offnode tasks as sds->numa_group
3828 static inline void update_sd_numa_stats(struct sched_domain *sd,
3829 struct sched_group *group, struct sd_lb_stats *sds,
3830 int local_group, struct sg_lb_stats *sgs)
3832 if (!(sd->flags & SD_NUMA))
3838 if (!sgs->numa_running)
3841 if (!sds->numa_group || pick_numa_rand(sd->span_weight / group->group_weight)) {
3842 sds->numa_group = group;
3843 sds->numa_group_weight = sgs->numa_weight;
3844 sds->numa_group_running = sgs->numa_running;
3849 * Pick a random queue from the group that has offnode tasks.
3851 static struct rq *find_busiest_numa_queue(struct lb_env *env,
3852 struct sched_group *group)
3854 struct rq *busiest = NULL, *rq;
3857 for_each_cpu_and(cpu, sched_group_cpus(group), env->cpus) {
3859 if (!rq->offnode_running)
3861 if (!busiest || pick_numa_rand(group->group_weight))
3869 * Called in case of no other imbalance, if there is a queue running offnode
3870 * tasksk we'll say we're imbalanced anyway to nudge these tasks towards their
3873 static inline int check_numa_busiest_group(struct lb_env *env, struct sd_lb_stats *sds)
3875 if (!sched_feat(NUMA_PULL_BIAS))
3878 if (!sds->numa_group)
3881 env->imbalance = sds->numa_group_weight / sds->numa_group_running;
3882 sds->busiest = sds->numa_group;
3883 env->find_busiest_queue = find_busiest_numa_queue;
3887 static inline bool need_active_numa_balance(struct lb_env *env)
3889 return env->find_busiest_queue == find_busiest_numa_queue &&
3890 env->src_rq->offnode_running == 1 &&
3891 env->src_rq->nr_running == 1;
3894 #else /* CONFIG_SCHED_NUMA */
3896 static inline void update_sg_numa_stats(struct sg_lb_stats *sgs, struct rq *rq)
3900 static inline void update_sd_numa_stats(struct sched_domain *sd,
3901 struct sched_group *group, struct sd_lb_stats *sds,
3902 int local_group, struct sg_lb_stats *sgs)
3906 static inline int check_numa_busiest_group(struct lb_env *env, struct sd_lb_stats *sds)
3911 static inline bool need_active_numa_balance(struct lb_env *env)
3915 #endif /* CONFIG_SCHED_NUMA */
3917 unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
3919 return SCHED_POWER_SCALE;
3922 unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
3924 return default_scale_freq_power(sd, cpu);
3927 unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
3929 unsigned long weight = sd->span_weight;
3930 unsigned long smt_gain = sd->smt_gain;
3937 unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
3939 return default_scale_smt_power(sd, cpu);
3942 unsigned long scale_rt_power(int cpu)
3944 struct rq *rq = cpu_rq(cpu);
3945 u64 total, available, age_stamp, avg;
3948 * Since we're reading these variables without serialization make sure
3949 * we read them once before doing sanity checks on them.
3951 age_stamp = ACCESS_ONCE(rq->age_stamp);
3952 avg = ACCESS_ONCE(rq->rt_avg);
3954 total = sched_avg_period() + (rq->clock - age_stamp);
3956 if (unlikely(total < avg)) {
3957 /* Ensures that power won't end up being negative */
3960 available = total - avg;
3963 if (unlikely((s64)total < SCHED_POWER_SCALE))
3964 total = SCHED_POWER_SCALE;
3966 total >>= SCHED_POWER_SHIFT;
3968 return div_u64(available, total);
3971 static void update_cpu_power(struct sched_domain *sd, int cpu)
3973 unsigned long weight = sd->span_weight;
3974 unsigned long power = SCHED_POWER_SCALE;
3975 struct sched_group *sdg = sd->groups;
3977 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
3978 if (sched_feat(ARCH_POWER))
3979 power *= arch_scale_smt_power(sd, cpu);
3981 power *= default_scale_smt_power(sd, cpu);
3983 power >>= SCHED_POWER_SHIFT;
3986 sdg->sgp->power_orig = power;
3988 if (sched_feat(ARCH_POWER))
3989 power *= arch_scale_freq_power(sd, cpu);
3991 power *= default_scale_freq_power(sd, cpu);
3993 power >>= SCHED_POWER_SHIFT;
3995 power *= scale_rt_power(cpu);
3996 power >>= SCHED_POWER_SHIFT;
4001 cpu_rq(cpu)->cpu_power = power;
4002 sdg->sgp->power = power;
4005 void update_group_power(struct sched_domain *sd, int cpu)
4007 struct sched_domain *child = sd->child;
4008 struct sched_group *group, *sdg = sd->groups;
4009 unsigned long power;
4010 unsigned long interval;
4012 interval = msecs_to_jiffies(sd->balance_interval);
4013 interval = clamp(interval, 1UL, max_load_balance_interval);
4014 sdg->sgp->next_update = jiffies + interval;
4017 update_cpu_power(sd, cpu);
4023 if (child->flags & SD_OVERLAP) {
4025 * SD_OVERLAP domains cannot assume that child groups
4026 * span the current group.
4029 for_each_cpu(cpu, sched_group_cpus(sdg))
4030 power += power_of(cpu);
4033 * !SD_OVERLAP domains can assume that child groups
4034 * span the current group.
4037 group = child->groups;
4039 power += group->sgp->power;
4040 group = group->next;
4041 } while (group != child->groups);
4044 sdg->sgp->power_orig = sdg->sgp->power = power;
4048 * Try and fix up capacity for tiny siblings, this is needed when
4049 * things like SD_ASYM_PACKING need f_b_g to select another sibling
4050 * which on its own isn't powerful enough.
4052 * See update_sd_pick_busiest() and check_asym_packing().
4055 fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
4058 * Only siblings can have significantly less than SCHED_POWER_SCALE
4060 if (!(sd->flags & SD_SHARE_CPUPOWER))
4064 * If ~90% of the cpu_power is still there, we're good.
4066 if (group->sgp->power * 32 > group->sgp->power_orig * 29)
4073 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
4074 * @env: The load balancing environment.
4075 * @group: sched_group whose statistics are to be updated.
4076 * @load_idx: Load index of sched_domain of this_cpu for load calc.
4077 * @local_group: Does group contain this_cpu.
4078 * @balance: Should we balance.
4079 * @sgs: variable to hold the statistics for this group.
4081 static inline void update_sg_lb_stats(struct lb_env *env,
4082 struct sched_group *group, int load_idx,
4083 int local_group, int *balance, struct sg_lb_stats *sgs)
4085 unsigned long nr_running, max_nr_running, min_nr_running;
4086 unsigned long load, max_cpu_load, min_cpu_load;
4087 unsigned int balance_cpu = -1, first_idle_cpu = 0;
4088 unsigned long avg_load_per_task = 0;
4092 balance_cpu = group_balance_cpu(group);
4094 /* Tally up the load of all CPUs in the group */
4096 min_cpu_load = ~0UL;
4098 min_nr_running = ~0UL;
4100 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
4101 struct rq *rq = cpu_rq(i);
4103 nr_running = rq->nr_running;
4105 /* Bias balancing toward cpus of our domain */
4107 if (idle_cpu(i) && !first_idle_cpu &&
4108 cpumask_test_cpu(i, sched_group_mask(group))) {
4113 load = target_load(i, load_idx);
4115 load = source_load(i, load_idx);
4116 if (load > max_cpu_load)
4117 max_cpu_load = load;
4118 if (min_cpu_load > load)
4119 min_cpu_load = load;
4121 if (nr_running > max_nr_running)
4122 max_nr_running = nr_running;
4123 if (min_nr_running > nr_running)
4124 min_nr_running = nr_running;
4127 sgs->group_load += load;
4128 sgs->sum_nr_running += nr_running;
4129 sgs->sum_weighted_load += weighted_cpuload(i);
4133 update_sg_numa_stats(sgs, rq);
4137 * First idle cpu or the first cpu(busiest) in this sched group
4138 * is eligible for doing load balancing at this and above
4139 * domains. In the newly idle case, we will allow all the cpu's
4140 * to do the newly idle load balance.
4143 if (env->idle != CPU_NEWLY_IDLE) {
4144 if (balance_cpu != env->dst_cpu) {
4148 update_group_power(env->sd, env->dst_cpu);
4149 } else if (time_after_eq(jiffies, group->sgp->next_update))
4150 update_group_power(env->sd, env->dst_cpu);
4153 /* Adjust by relative CPU power of the group */
4154 sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
4157 * Consider the group unbalanced when the imbalance is larger
4158 * than the average weight of a task.
4160 * APZ: with cgroup the avg task weight can vary wildly and
4161 * might not be a suitable number - should we keep a
4162 * normalized nr_running number somewhere that negates
4165 if (sgs->sum_nr_running)
4166 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
4168 if ((max_cpu_load - min_cpu_load) >= avg_load_per_task &&
4169 (max_nr_running - min_nr_running) > 1)
4172 sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
4174 if (!sgs->group_capacity)
4175 sgs->group_capacity = fix_small_capacity(env->sd, group);
4176 sgs->group_weight = group->group_weight;
4178 if (sgs->group_capacity > sgs->sum_nr_running)
4179 sgs->group_has_capacity = 1;
4183 * update_sd_pick_busiest - return 1 on busiest group
4184 * @env: The load balancing environment.
4185 * @sds: sched_domain statistics
4186 * @sg: sched_group candidate to be checked for being the busiest
4187 * @sgs: sched_group statistics
4189 * Determine if @sg is a busier group than the previously selected
4192 static bool update_sd_pick_busiest(struct lb_env *env,
4193 struct sd_lb_stats *sds,
4194 struct sched_group *sg,
4195 struct sg_lb_stats *sgs)
4197 if (sgs->avg_load <= sds->max_load)
4200 if (sgs->sum_nr_running > sgs->group_capacity)
4207 * ASYM_PACKING needs to move all the work to the lowest
4208 * numbered CPUs in the group, therefore mark all groups
4209 * higher than ourself as busy.
4211 if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
4212 env->dst_cpu < group_first_cpu(sg)) {
4216 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
4224 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
4225 * @env: The load balancing environment.
4226 * @balance: Should we balance.
4227 * @sds: variable to hold the statistics for this sched_domain.
4229 static inline void update_sd_lb_stats(struct lb_env *env,
4230 int *balance, struct sd_lb_stats *sds)
4232 struct sched_domain *child = env->sd->child;
4233 struct sched_group *sg = env->sd->groups;
4234 struct sg_lb_stats sgs;
4235 int load_idx, prefer_sibling = 0;
4237 if (child && child->flags & SD_PREFER_SIBLING)
4240 load_idx = get_sd_load_idx(env->sd, env->idle);
4245 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
4246 memset(&sgs, 0, sizeof(sgs));
4247 update_sg_lb_stats(env, sg, load_idx, local_group, balance, &sgs);
4249 if (local_group && !(*balance))
4252 sds->total_load += sgs.group_load;
4253 sds->total_pwr += sg->sgp->power;
4256 * In case the child domain prefers tasks go to siblings
4257 * first, lower the sg capacity to one so that we'll try
4258 * and move all the excess tasks away. We lower the capacity
4259 * of a group only if the local group has the capacity to fit
4260 * these excess tasks, i.e. nr_running < group_capacity. The
4261 * extra check prevents the case where you always pull from the
4262 * heaviest group when it is already under-utilized (possible
4263 * with a large weight task outweighs the tasks on the system).
4265 if (prefer_sibling && !local_group && sds->this_has_capacity)
4266 sgs.group_capacity = min(sgs.group_capacity, 1UL);
4269 sds->this_load = sgs.avg_load;
4271 sds->this_nr_running = sgs.sum_nr_running;
4272 sds->this_load_per_task = sgs.sum_weighted_load;
4273 sds->this_has_capacity = sgs.group_has_capacity;
4274 sds->this_idle_cpus = sgs.idle_cpus;
4275 } else if (update_sd_pick_busiest(env, sds, sg, &sgs)) {
4276 sds->max_load = sgs.avg_load;
4278 sds->busiest_nr_running = sgs.sum_nr_running;
4279 sds->busiest_idle_cpus = sgs.idle_cpus;
4280 sds->busiest_group_capacity = sgs.group_capacity;
4281 sds->busiest_load_per_task = sgs.sum_weighted_load;
4282 sds->busiest_has_capacity = sgs.group_has_capacity;
4283 sds->busiest_group_weight = sgs.group_weight;
4284 sds->group_imb = sgs.group_imb;
4287 update_sd_numa_stats(env->sd, sg, sds, local_group, &sgs);
4290 } while (sg != env->sd->groups);
4294 * check_asym_packing - Check to see if the group is packed into the
4297 * This is primarily intended to used at the sibling level. Some
4298 * cores like POWER7 prefer to use lower numbered SMT threads. In the
4299 * case of POWER7, it can move to lower SMT modes only when higher
4300 * threads are idle. When in lower SMT modes, the threads will
4301 * perform better since they share less core resources. Hence when we
4302 * have idle threads, we want them to be the higher ones.
4304 * This packing function is run on idle threads. It checks to see if
4305 * the busiest CPU in this domain (core in the P7 case) has a higher
4306 * CPU number than the packing function is being run on. Here we are
4307 * assuming lower CPU number will be equivalent to lower a SMT thread
4310 * Returns 1 when packing is required and a task should be moved to
4311 * this CPU. The amount of the imbalance is returned in *imbalance.
4313 * @env: The load balancing environment.
4314 * @sds: Statistics of the sched_domain which is to be packed
4316 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
4320 if (!(env->sd->flags & SD_ASYM_PACKING))
4326 busiest_cpu = group_first_cpu(sds->busiest);
4327 if (env->dst_cpu > busiest_cpu)
4330 env->imbalance = DIV_ROUND_CLOSEST(
4331 sds->max_load * sds->busiest->sgp->power, SCHED_POWER_SCALE);
4337 * fix_small_imbalance - Calculate the minor imbalance that exists
4338 * amongst the groups of a sched_domain, during
4340 * @env: The load balancing environment.
4341 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
4344 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
4346 unsigned long tmp, pwr_now = 0, pwr_move = 0;
4347 unsigned int imbn = 2;
4348 unsigned long scaled_busy_load_per_task;
4350 if (sds->this_nr_running) {
4351 sds->this_load_per_task /= sds->this_nr_running;
4352 if (sds->busiest_load_per_task >
4353 sds->this_load_per_task)
4356 sds->this_load_per_task =
4357 cpu_avg_load_per_task(env->dst_cpu);
4360 scaled_busy_load_per_task = sds->busiest_load_per_task
4361 * SCHED_POWER_SCALE;
4362 scaled_busy_load_per_task /= sds->busiest->sgp->power;
4364 if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
4365 (scaled_busy_load_per_task * imbn)) {
4366 env->imbalance = sds->busiest_load_per_task;
4371 * OK, we don't have enough imbalance to justify moving tasks,
4372 * however we may be able to increase total CPU power used by
4376 pwr_now += sds->busiest->sgp->power *
4377 min(sds->busiest_load_per_task, sds->max_load);
4378 pwr_now += sds->this->sgp->power *
4379 min(sds->this_load_per_task, sds->this_load);
4380 pwr_now /= SCHED_POWER_SCALE;
4382 /* Amount of load we'd subtract */
4383 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
4384 sds->busiest->sgp->power;
4385 if (sds->max_load > tmp)
4386 pwr_move += sds->busiest->sgp->power *
4387 min(sds->busiest_load_per_task, sds->max_load - tmp);
4389 /* Amount of load we'd add */
4390 if (sds->max_load * sds->busiest->sgp->power <
4391 sds->busiest_load_per_task * SCHED_POWER_SCALE)
4392 tmp = (sds->max_load * sds->busiest->sgp->power) /
4393 sds->this->sgp->power;
4395 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
4396 sds->this->sgp->power;
4397 pwr_move += sds->this->sgp->power *
4398 min(sds->this_load_per_task, sds->this_load + tmp);
4399 pwr_move /= SCHED_POWER_SCALE;
4401 /* Move if we gain throughput */
4402 if (pwr_move > pwr_now)
4403 env->imbalance = sds->busiest_load_per_task;
4407 * calculate_imbalance - Calculate the amount of imbalance present within the
4408 * groups of a given sched_domain during load balance.
4409 * @env: load balance environment
4410 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
4412 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
4414 unsigned long max_pull, load_above_capacity = ~0UL;
4416 sds->busiest_load_per_task /= sds->busiest_nr_running;
4417 if (sds->group_imb) {
4418 sds->busiest_load_per_task =
4419 min(sds->busiest_load_per_task, sds->avg_load);
4423 * In the presence of smp nice balancing, certain scenarios can have
4424 * max load less than avg load(as we skip the groups at or below
4425 * its cpu_power, while calculating max_load..)
4427 if (sds->max_load < sds->avg_load) {
4429 return fix_small_imbalance(env, sds);
4432 if (!sds->group_imb) {
4434 * Don't want to pull so many tasks that a group would go idle.
4436 load_above_capacity = (sds->busiest_nr_running -
4437 sds->busiest_group_capacity);
4439 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
4441 load_above_capacity /= sds->busiest->sgp->power;
4445 * We're trying to get all the cpus to the average_load, so we don't
4446 * want to push ourselves above the average load, nor do we wish to
4447 * reduce the max loaded cpu below the average load. At the same time,
4448 * we also don't want to reduce the group load below the group capacity
4449 * (so that we can implement power-savings policies etc). Thus we look
4450 * for the minimum possible imbalance.
4451 * Be careful of negative numbers as they'll appear as very large values
4452 * with unsigned longs.
4454 max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
4456 /* How much load to actually move to equalise the imbalance */
4457 env->imbalance = min(max_pull * sds->busiest->sgp->power,
4458 (sds->avg_load - sds->this_load) * sds->this->sgp->power)
4459 / SCHED_POWER_SCALE;
4462 * if *imbalance is less than the average load per runnable task
4463 * there is no guarantee that any tasks will be moved so we'll have
4464 * a think about bumping its value to force at least one task to be
4467 if (env->imbalance < sds->busiest_load_per_task)
4468 return fix_small_imbalance(env, sds);
4472 /******* find_busiest_group() helpers end here *********************/
4475 * find_busiest_group - Returns the busiest group within the sched_domain
4476 * if there is an imbalance. If there isn't an imbalance, and
4477 * the user has opted for power-savings, it returns a group whose
4478 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
4479 * such a group exists.
4481 * Also calculates the amount of weighted load which should be moved
4482 * to restore balance.
4484 * @env: The load balancing environment.
4485 * @balance: Pointer to a variable indicating if this_cpu
4486 * is the appropriate cpu to perform load balancing at this_level.
4488 * Returns: - the busiest group if imbalance exists.
4489 * - If no imbalance and user has opted for power-savings balance,
4490 * return the least loaded group whose CPUs can be
4491 * put to idle by rebalancing its tasks onto our group.
4493 static struct sched_group *
4494 find_busiest_group(struct lb_env *env, int *balance)
4496 struct sd_lb_stats sds;
4498 memset(&sds, 0, sizeof(sds));
4501 * Compute the various statistics relavent for load balancing at
4504 update_sd_lb_stats(env, balance, &sds);
4507 * this_cpu is not the appropriate cpu to perform load balancing at
4513 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
4514 check_asym_packing(env, &sds))
4517 /* There is no busy sibling group to pull tasks from */
4518 if (!sds.busiest || sds.busiest_nr_running == 0)
4521 sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
4524 * If the busiest group is imbalanced the below checks don't
4525 * work because they assumes all things are equal, which typically
4526 * isn't true due to cpus_allowed constraints and the like.
4531 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
4532 if (env->idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
4533 !sds.busiest_has_capacity)
4537 * If the local group is more busy than the selected busiest group
4538 * don't try and pull any tasks.
4540 if (sds.this_load >= sds.max_load)
4544 * Don't pull any tasks if this group is already above the domain
4547 if (sds.this_load >= sds.avg_load)
4550 if (env->idle == CPU_IDLE) {
4552 * This cpu is idle. If the busiest group load doesn't
4553 * have more tasks than the number of available cpu's and
4554 * there is no imbalance between this and busiest group
4555 * wrt to idle cpu's, it is balanced.
4557 if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
4558 sds.busiest_nr_running <= sds.busiest_group_weight)
4562 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
4563 * imbalance_pct to be conservative.
4565 if (100 * sds.max_load <= env->sd->imbalance_pct * sds.this_load)
4570 /* Looks like there is an imbalance. Compute it */
4571 calculate_imbalance(env, &sds);
4575 if (check_numa_busiest_group(env, &sds))
4584 * find_busiest_queue - find the busiest runqueue among the cpus in group.
4586 static struct rq *find_busiest_queue(struct lb_env *env,
4587 struct sched_group *group)
4589 struct rq *busiest = NULL, *rq;
4590 unsigned long max_load = 0;
4593 for_each_cpu(i, sched_group_cpus(group)) {
4594 unsigned long power = power_of(i);
4595 unsigned long capacity = DIV_ROUND_CLOSEST(power,
4600 capacity = fix_small_capacity(env->sd, group);
4602 if (!cpumask_test_cpu(i, env->cpus))
4606 wl = weighted_cpuload(i);
4609 * When comparing with imbalance, use weighted_cpuload()
4610 * which is not scaled with the cpu power.
4612 if (capacity && rq->nr_running == 1 && wl > env->imbalance)
4616 * For the load comparisons with the other cpu's, consider
4617 * the weighted_cpuload() scaled with the cpu power, so that
4618 * the load can be moved away from the cpu that is potentially
4619 * running at a lower capacity.
4621 wl = (wl * SCHED_POWER_SCALE) / power;
4623 if (wl > max_load) {
4633 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4634 * so long as it is large enough.
4636 #define MAX_PINNED_INTERVAL 512
4638 /* Working cpumask for load_balance and load_balance_newidle. */
4639 DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
4641 static int need_active_balance(struct lb_env *env)
4643 struct sched_domain *sd = env->sd;
4645 if (env->idle == CPU_NEWLY_IDLE) {
4648 * ASYM_PACKING needs to force migrate tasks from busy but
4649 * higher numbered CPUs in order to pack all tasks in the
4650 * lowest numbered CPUs.
4652 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
4656 if (need_active_numa_balance(env))
4659 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
4662 static int active_load_balance_cpu_stop(void *data);
4665 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4666 * tasks if there is an imbalance.
4668 static int load_balance(int this_cpu, struct rq *this_rq,
4669 struct sched_domain *sd, enum cpu_idle_type idle,
4672 int ld_moved, cur_ld_moved, active_balance = 0;
4673 int lb_iterations, max_lb_iterations;
4674 struct sched_group *group;
4676 unsigned long flags;
4677 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4679 struct lb_env env = {
4681 .dst_cpu = this_cpu,
4683 .dst_grpmask = sched_group_cpus(sd->groups),
4685 .loop_break = sched_nr_migrate_break,
4687 .find_busiest_queue = find_busiest_queue,
4690 cpumask_copy(cpus, cpu_active_mask);
4691 max_lb_iterations = cpumask_weight(env.dst_grpmask);
4693 schedstat_inc(sd, lb_count[idle]);
4696 group = find_busiest_group(&env, balance);
4702 schedstat_inc(sd, lb_nobusyg[idle]);
4706 busiest = env.find_busiest_queue(&env, group);
4708 schedstat_inc(sd, lb_nobusyq[idle]);
4711 env.src_rq = busiest;
4712 env.src_cpu = busiest->cpu;
4714 BUG_ON(busiest == env.dst_rq);
4716 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
4720 if (busiest->nr_running > 1) {
4722 * Attempt to move tasks. If find_busiest_group has found
4723 * an imbalance but busiest->nr_running <= 1, the group is
4724 * still unbalanced. ld_moved simply stays zero, so it is
4725 * correctly treated as an imbalance.
4727 env.flags |= LBF_ALL_PINNED;
4728 env.src_cpu = busiest->cpu;
4729 env.src_rq = busiest;
4730 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
4731 if (sched_feat_numa(NUMA_PULL))
4732 env.tasks = offnode_tasks(busiest);
4734 env.tasks = &busiest->cfs_tasks;
4736 update_h_load(env.src_cpu);
4738 local_irq_save(flags);
4739 double_rq_lock(env.dst_rq, busiest);
4742 * cur_ld_moved - load moved in current iteration
4743 * ld_moved - cumulative load moved across iterations
4745 cur_ld_moved = move_tasks(&env);
4746 ld_moved += cur_ld_moved;
4747 double_rq_unlock(env.dst_rq, busiest);
4748 local_irq_restore(flags);
4750 if (env.flags & LBF_NEED_BREAK) {
4751 env.flags &= ~LBF_NEED_BREAK;
4756 * some other cpu did the load balance for us.
4758 if (cur_ld_moved && env.dst_cpu != smp_processor_id())
4759 resched_cpu(env.dst_cpu);
4762 * Revisit (affine) tasks on src_cpu that couldn't be moved to
4763 * us and move them to an alternate dst_cpu in our sched_group
4764 * where they can run. The upper limit on how many times we
4765 * iterate on same src_cpu is dependent on number of cpus in our
4768 * This changes load balance semantics a bit on who can move
4769 * load to a given_cpu. In addition to the given_cpu itself
4770 * (or a ilb_cpu acting on its behalf where given_cpu is
4771 * nohz-idle), we now have balance_cpu in a position to move
4772 * load to given_cpu. In rare situations, this may cause
4773 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
4774 * _independently_ and at _same_ time to move some load to
4775 * given_cpu) causing exceess load to be moved to given_cpu.
4776 * This however should not happen so much in practice and
4777 * moreover subsequent load balance cycles should correct the
4778 * excess load moved.
4780 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0 &&
4781 lb_iterations++ < max_lb_iterations) {
4783 env.dst_rq = cpu_rq(env.new_dst_cpu);
4784 env.dst_cpu = env.new_dst_cpu;
4785 env.flags &= ~LBF_SOME_PINNED;
4787 env.loop_break = sched_nr_migrate_break;
4789 * Go back to "more_balance" rather than "redo" since we
4790 * need to continue with same src_cpu.
4795 /* All tasks on this runqueue were pinned by CPU affinity */
4796 if (unlikely(env.flags & LBF_ALL_PINNED)) {
4797 cpumask_clear_cpu(cpu_of(busiest), cpus);
4798 if (!cpumask_empty(cpus)) {
4800 env.loop_break = sched_nr_migrate_break;
4808 schedstat_inc(sd, lb_failed[idle]);
4810 * Increment the failure counter only on periodic balance.
4811 * We do not want newidle balance, which can be very
4812 * frequent, pollute the failure counter causing
4813 * excessive cache_hot migrations and active balances.
4815 if (idle != CPU_NEWLY_IDLE)
4816 sd->nr_balance_failed++;
4818 if (need_active_balance(&env)) {
4819 raw_spin_lock_irqsave(&busiest->lock, flags);
4821 /* don't kick the active_load_balance_cpu_stop,
4822 * if the curr task on busiest cpu can't be
4825 if (!cpumask_test_cpu(this_cpu,
4826 tsk_cpus_allowed(busiest->curr))) {
4827 raw_spin_unlock_irqrestore(&busiest->lock,
4829 env.flags |= LBF_ALL_PINNED;
4830 goto out_one_pinned;
4834 * ->active_balance synchronizes accesses to
4835 * ->active_balance_work. Once set, it's cleared
4836 * only after active load balance is finished.
4838 if (!busiest->active_balance) {
4839 busiest->active_balance = 1;
4840 busiest->push_cpu = this_cpu;
4843 raw_spin_unlock_irqrestore(&busiest->lock, flags);
4845 if (active_balance) {
4846 stop_one_cpu_nowait(cpu_of(busiest),
4847 active_load_balance_cpu_stop, busiest,
4848 &busiest->active_balance_work);
4852 * We've kicked active balancing, reset the failure
4855 sd->nr_balance_failed = sd->cache_nice_tries+1;
4858 sd->nr_balance_failed = 0;
4860 if (likely(!active_balance)) {
4861 /* We were unbalanced, so reset the balancing interval */
4862 sd->balance_interval = sd->min_interval;
4865 * If we've begun active balancing, start to back off. This
4866 * case may not be covered by the all_pinned logic if there
4867 * is only 1 task on the busy runqueue (because we don't call
4870 if (sd->balance_interval < sd->max_interval)
4871 sd->balance_interval *= 2;
4877 schedstat_inc(sd, lb_balanced[idle]);
4879 sd->nr_balance_failed = 0;
4882 /* tune up the balancing interval */
4883 if (((env.flags & LBF_ALL_PINNED) &&
4884 sd->balance_interval < MAX_PINNED_INTERVAL) ||
4885 (sd->balance_interval < sd->max_interval))
4886 sd->balance_interval *= 2;
4894 * idle_balance is called by schedule() if this_cpu is about to become
4895 * idle. Attempts to pull tasks from other CPUs.
4897 void idle_balance(int this_cpu, struct rq *this_rq)
4899 struct sched_domain *sd;
4900 int pulled_task = 0;
4901 unsigned long next_balance = jiffies + HZ;
4903 this_rq->idle_stamp = this_rq->clock;
4905 if (this_rq->avg_idle < sysctl_sched_migration_cost)
4909 * Drop the rq->lock, but keep IRQ/preempt disabled.
4911 raw_spin_unlock(&this_rq->lock);
4913 update_shares(this_cpu);
4915 for_each_domain(this_cpu, sd) {
4916 unsigned long interval;
4919 if (!(sd->flags & SD_LOAD_BALANCE))
4922 if (sd->flags & SD_BALANCE_NEWIDLE) {
4923 /* If we've pulled tasks over stop searching: */
4924 pulled_task = load_balance(this_cpu, this_rq,
4925 sd, CPU_NEWLY_IDLE, &balance);
4928 interval = msecs_to_jiffies(sd->balance_interval);
4929 if (time_after(next_balance, sd->last_balance + interval))
4930 next_balance = sd->last_balance + interval;
4932 this_rq->idle_stamp = 0;
4938 raw_spin_lock(&this_rq->lock);
4940 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4942 * We are going idle. next_balance may be set based on
4943 * a busy processor. So reset next_balance.
4945 this_rq->next_balance = next_balance;
4950 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
4951 * running tasks off the busiest CPU onto idle CPUs. It requires at
4952 * least 1 task to be running on each physical CPU where possible, and
4953 * avoids physical / logical imbalances.
4955 static int active_load_balance_cpu_stop(void *data)
4957 struct rq *busiest_rq = data;
4958 int busiest_cpu = cpu_of(busiest_rq);
4959 int target_cpu = busiest_rq->push_cpu;
4960 struct rq *target_rq = cpu_rq(target_cpu);
4961 struct sched_domain *sd;
4963 raw_spin_lock_irq(&busiest_rq->lock);
4965 /* make sure the requested cpu hasn't gone down in the meantime */
4966 if (unlikely(busiest_cpu != smp_processor_id() ||
4967 !busiest_rq->active_balance))
4970 /* Is there any task to move? */
4971 if (busiest_rq->nr_running <= 1)
4975 * This condition is "impossible", if it occurs
4976 * we need to fix it. Originally reported by
4977 * Bjorn Helgaas on a 128-cpu setup.
4979 BUG_ON(busiest_rq == target_rq);
4981 /* move a task from busiest_rq to target_rq */
4982 double_lock_balance(busiest_rq, target_rq);
4984 /* Search for an sd spanning us and the target CPU. */
4986 for_each_domain(target_cpu, sd) {
4987 if ((sd->flags & SD_LOAD_BALANCE) &&
4988 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4993 struct lb_env env = {
4995 .dst_cpu = target_cpu,
4996 .dst_rq = target_rq,
4997 .src_cpu = busiest_rq->cpu,
4998 .src_rq = busiest_rq,
5002 schedstat_inc(sd, alb_count);
5004 if (move_one_task(&env))
5005 schedstat_inc(sd, alb_pushed);
5007 schedstat_inc(sd, alb_failed);
5010 double_unlock_balance(busiest_rq, target_rq);
5012 busiest_rq->active_balance = 0;
5013 raw_spin_unlock_irq(&busiest_rq->lock);
5019 * idle load balancing details
5020 * - When one of the busy CPUs notice that there may be an idle rebalancing
5021 * needed, they will kick the idle load balancer, which then does idle
5022 * load balancing for all the idle CPUs.
5025 cpumask_var_t idle_cpus_mask;
5027 unsigned long next_balance; /* in jiffy units */
5028 } nohz ____cacheline_aligned;
5030 static inline int find_new_ilb(int call_cpu)
5032 int ilb = cpumask_first(nohz.idle_cpus_mask);
5034 if (ilb < nr_cpu_ids && idle_cpu(ilb))
5041 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
5042 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
5043 * CPU (if there is one).
5045 static void nohz_balancer_kick(int cpu)
5049 nohz.next_balance++;
5051 ilb_cpu = find_new_ilb(cpu);
5053 if (ilb_cpu >= nr_cpu_ids)
5056 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
5059 * Use smp_send_reschedule() instead of resched_cpu().
5060 * This way we generate a sched IPI on the target cpu which
5061 * is idle. And the softirq performing nohz idle load balance
5062 * will be run before returning from the IPI.
5064 smp_send_reschedule(ilb_cpu);
5068 static inline void nohz_balance_exit_idle(int cpu)
5070 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
5071 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
5072 atomic_dec(&nohz.nr_cpus);
5073 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
5077 static inline void set_cpu_sd_state_busy(void)
5079 struct sched_domain *sd;
5080 int cpu = smp_processor_id();
5082 if (!test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5084 clear_bit(NOHZ_IDLE, nohz_flags(cpu));
5087 for_each_domain(cpu, sd)
5088 atomic_inc(&sd->groups->sgp->nr_busy_cpus);
5092 void set_cpu_sd_state_idle(void)
5094 struct sched_domain *sd;
5095 int cpu = smp_processor_id();
5097 if (test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5099 set_bit(NOHZ_IDLE, nohz_flags(cpu));
5102 for_each_domain(cpu, sd)
5103 atomic_dec(&sd->groups->sgp->nr_busy_cpus);
5108 * This routine will record that the cpu is going idle with tick stopped.
5109 * This info will be used in performing idle load balancing in the future.
5111 void nohz_balance_enter_idle(int cpu)
5114 * If this cpu is going down, then nothing needs to be done.
5116 if (!cpu_active(cpu))
5119 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
5122 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
5123 atomic_inc(&nohz.nr_cpus);
5124 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
5127 static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
5128 unsigned long action, void *hcpu)
5130 switch (action & ~CPU_TASKS_FROZEN) {
5132 nohz_balance_exit_idle(smp_processor_id());
5140 static DEFINE_SPINLOCK(balancing);
5143 * Scale the max load_balance interval with the number of CPUs in the system.
5144 * This trades load-balance latency on larger machines for less cross talk.
5146 void update_max_interval(void)
5148 max_load_balance_interval = HZ*num_online_cpus()/10;
5152 * It checks each scheduling domain to see if it is due to be balanced,
5153 * and initiates a balancing operation if so.
5155 * Balancing parameters are set up in arch_init_sched_domains.
5157 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
5160 struct rq *rq = cpu_rq(cpu);
5161 unsigned long interval;
5162 struct sched_domain *sd;
5163 /* Earliest time when we have to do rebalance again */
5164 unsigned long next_balance = jiffies + 60*HZ;
5165 int update_next_balance = 0;
5171 for_each_domain(cpu, sd) {
5172 if (!(sd->flags & SD_LOAD_BALANCE))
5175 interval = sd->balance_interval;
5176 if (idle != CPU_IDLE)
5177 interval *= sd->busy_factor;
5179 /* scale ms to jiffies */
5180 interval = msecs_to_jiffies(interval);
5181 interval = clamp(interval, 1UL, max_load_balance_interval);
5183 need_serialize = sd->flags & SD_SERIALIZE;
5185 if (need_serialize) {
5186 if (!spin_trylock(&balancing))
5190 if (time_after_eq(jiffies, sd->last_balance + interval)) {
5191 if (load_balance(cpu, rq, sd, idle, &balance)) {
5193 * We've pulled tasks over so either we're no
5196 idle = CPU_NOT_IDLE;
5198 sd->last_balance = jiffies;
5201 spin_unlock(&balancing);
5203 if (time_after(next_balance, sd->last_balance + interval)) {
5204 next_balance = sd->last_balance + interval;
5205 update_next_balance = 1;
5209 * Stop the load balance at this level. There is another
5210 * CPU in our sched group which is doing load balancing more
5219 * next_balance will be updated only when there is a need.
5220 * When the cpu is attached to null domain for ex, it will not be
5223 if (likely(update_next_balance))
5224 rq->next_balance = next_balance;
5229 * In CONFIG_NO_HZ case, the idle balance kickee will do the
5230 * rebalancing for all the cpus for whom scheduler ticks are stopped.
5232 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
5234 struct rq *this_rq = cpu_rq(this_cpu);
5238 if (idle != CPU_IDLE ||
5239 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
5242 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
5243 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
5247 * If this cpu gets work to do, stop the load balancing
5248 * work being done for other cpus. Next load
5249 * balancing owner will pick it up.
5254 rq = cpu_rq(balance_cpu);
5256 raw_spin_lock_irq(&rq->lock);
5257 update_rq_clock(rq);
5258 update_idle_cpu_load(rq);
5259 raw_spin_unlock_irq(&rq->lock);
5261 rebalance_domains(balance_cpu, CPU_IDLE);
5263 if (time_after(this_rq->next_balance, rq->next_balance))
5264 this_rq->next_balance = rq->next_balance;
5266 nohz.next_balance = this_rq->next_balance;
5268 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
5272 * Current heuristic for kicking the idle load balancer in the presence
5273 * of an idle cpu is the system.
5274 * - This rq has more than one task.
5275 * - At any scheduler domain level, this cpu's scheduler group has multiple
5276 * busy cpu's exceeding the group's power.
5277 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
5278 * domain span are idle.
5280 static inline int nohz_kick_needed(struct rq *rq, int cpu)
5282 unsigned long now = jiffies;
5283 struct sched_domain *sd;
5285 if (unlikely(idle_cpu(cpu)))
5289 * We may be recently in ticked or tickless idle mode. At the first
5290 * busy tick after returning from idle, we will update the busy stats.
5292 set_cpu_sd_state_busy();
5293 nohz_balance_exit_idle(cpu);
5296 * None are in tickless mode and hence no need for NOHZ idle load
5299 if (likely(!atomic_read(&nohz.nr_cpus)))
5302 if (time_before(now, nohz.next_balance))
5305 if (rq->nr_running >= 2)
5309 for_each_domain(cpu, sd) {
5310 struct sched_group *sg = sd->groups;
5311 struct sched_group_power *sgp = sg->sgp;
5312 int nr_busy = atomic_read(&sgp->nr_busy_cpus);
5314 if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
5315 goto need_kick_unlock;
5317 if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
5318 && (cpumask_first_and(nohz.idle_cpus_mask,
5319 sched_domain_span(sd)) < cpu))
5320 goto need_kick_unlock;
5322 if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
5334 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
5338 * run_rebalance_domains is triggered when needed from the scheduler tick.
5339 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
5341 static void run_rebalance_domains(struct softirq_action *h)
5343 int this_cpu = smp_processor_id();
5344 struct rq *this_rq = cpu_rq(this_cpu);
5345 enum cpu_idle_type idle = this_rq->idle_balance ?
5346 CPU_IDLE : CPU_NOT_IDLE;
5348 rebalance_domains(this_cpu, idle);
5351 * If this cpu has a pending nohz_balance_kick, then do the
5352 * balancing on behalf of the other idle cpus whose ticks are
5355 nohz_idle_balance(this_cpu, idle);
5358 static inline int on_null_domain(int cpu)
5360 return !rcu_dereference_sched(cpu_rq(cpu)->sd);
5364 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
5366 void trigger_load_balance(struct rq *rq, int cpu)
5368 /* Don't need to rebalance while attached to NULL domain */
5369 if (time_after_eq(jiffies, rq->next_balance) &&
5370 likely(!on_null_domain(cpu)))
5371 raise_softirq(SCHED_SOFTIRQ);
5373 if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
5374 nohz_balancer_kick(cpu);
5378 static void rq_online_fair(struct rq *rq)
5383 static void rq_offline_fair(struct rq *rq)
5387 /* Ensure any throttled groups are reachable by pick_next_task */
5388 unthrottle_offline_cfs_rqs(rq);
5391 #endif /* CONFIG_SMP */
5394 * scheduler tick hitting a task of our scheduling class:
5396 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
5398 struct cfs_rq *cfs_rq;
5399 struct sched_entity *se = &curr->se;
5401 for_each_sched_entity(se) {
5402 cfs_rq = cfs_rq_of(se);
5403 entity_tick(cfs_rq, se, queued);
5406 if (sched_feat_numa(NUMA))
5407 task_tick_numa(rq, curr);
5411 * called on fork with the child task as argument from the parent's context
5412 * - child not yet on the tasklist
5413 * - preemption disabled
5415 static void task_fork_fair(struct task_struct *p)
5417 struct cfs_rq *cfs_rq;
5418 struct sched_entity *se = &p->se, *curr;
5419 int this_cpu = smp_processor_id();
5420 struct rq *rq = this_rq();
5421 unsigned long flags;
5423 raw_spin_lock_irqsave(&rq->lock, flags);
5425 update_rq_clock(rq);
5427 cfs_rq = task_cfs_rq(current);
5428 curr = cfs_rq->curr;
5430 if (unlikely(task_cpu(p) != this_cpu)) {
5432 __set_task_cpu(p, this_cpu);
5436 update_curr(cfs_rq);
5439 se->vruntime = curr->vruntime;
5440 place_entity(cfs_rq, se, 1);
5442 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
5444 * Upon rescheduling, sched_class::put_prev_task() will place
5445 * 'current' within the tree based on its new key value.
5447 swap(curr->vruntime, se->vruntime);
5448 resched_task(rq->curr);
5451 se->vruntime -= cfs_rq->min_vruntime;
5453 raw_spin_unlock_irqrestore(&rq->lock, flags);
5457 * Priority of the task has changed. Check to see if we preempt
5461 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
5467 * Reschedule if we are currently running on this runqueue and
5468 * our priority decreased, or if we are not currently running on
5469 * this runqueue and our priority is higher than the current's
5471 if (rq->curr == p) {
5472 if (p->prio > oldprio)
5473 resched_task(rq->curr);
5475 check_preempt_curr(rq, p, 0);
5478 static void switched_from_fair(struct rq *rq, struct task_struct *p)
5480 struct sched_entity *se = &p->se;
5481 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5484 * Ensure the task's vruntime is normalized, so that when its
5485 * switched back to the fair class the enqueue_entity(.flags=0) will
5486 * do the right thing.
5488 * If it was on_rq, then the dequeue_entity(.flags=0) will already
5489 * have normalized the vruntime, if it was !on_rq, then only when
5490 * the task is sleeping will it still have non-normalized vruntime.
5492 if (!se->on_rq && p->state != TASK_RUNNING) {
5494 * Fix up our vruntime so that the current sleep doesn't
5495 * cause 'unlimited' sleep bonus.
5497 place_entity(cfs_rq, se, 0);
5498 se->vruntime -= cfs_rq->min_vruntime;
5503 * We switched to the sched_fair class.
5505 static void switched_to_fair(struct rq *rq, struct task_struct *p)
5511 * We were most likely switched from sched_rt, so
5512 * kick off the schedule if running, otherwise just see
5513 * if we can still preempt the current task.
5516 resched_task(rq->curr);
5518 check_preempt_curr(rq, p, 0);
5521 /* Account for a task changing its policy or group.
5523 * This routine is mostly called to set cfs_rq->curr field when a task
5524 * migrates between groups/classes.
5526 static void set_curr_task_fair(struct rq *rq)
5528 struct sched_entity *se = &rq->curr->se;
5530 for_each_sched_entity(se) {
5531 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5533 set_next_entity(cfs_rq, se);
5534 /* ensure bandwidth has been allocated on our new cfs_rq */
5535 account_cfs_rq_runtime(cfs_rq, 0);
5539 void init_cfs_rq(struct cfs_rq *cfs_rq)
5541 cfs_rq->tasks_timeline = RB_ROOT;
5542 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
5543 #ifndef CONFIG_64BIT
5544 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
5548 #ifdef CONFIG_FAIR_GROUP_SCHED
5549 static void task_move_group_fair(struct task_struct *p, int on_rq)
5552 * If the task was not on the rq at the time of this cgroup movement
5553 * it must have been asleep, sleeping tasks keep their ->vruntime
5554 * absolute on their old rq until wakeup (needed for the fair sleeper
5555 * bonus in place_entity()).
5557 * If it was on the rq, we've just 'preempted' it, which does convert
5558 * ->vruntime to a relative base.
5560 * Make sure both cases convert their relative position when migrating
5561 * to another cgroup's rq. This does somewhat interfere with the
5562 * fair sleeper stuff for the first placement, but who cares.
5565 * When !on_rq, vruntime of the task has usually NOT been normalized.
5566 * But there are some cases where it has already been normalized:
5568 * - Moving a forked child which is waiting for being woken up by
5569 * wake_up_new_task().
5570 * - Moving a task which has been woken up by try_to_wake_up() and
5571 * waiting for actually being woken up by sched_ttwu_pending().
5573 * To prevent boost or penalty in the new cfs_rq caused by delta
5574 * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
5576 if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
5580 p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
5581 set_task_rq(p, task_cpu(p));
5583 p->se.vruntime += cfs_rq_of(&p->se)->min_vruntime;
5586 void free_fair_sched_group(struct task_group *tg)
5590 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
5592 for_each_possible_cpu(i) {
5594 kfree(tg->cfs_rq[i]);
5603 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5605 struct cfs_rq *cfs_rq;
5606 struct sched_entity *se;
5609 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
5612 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
5616 tg->shares = NICE_0_LOAD;
5618 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
5620 for_each_possible_cpu(i) {
5621 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
5622 GFP_KERNEL, cpu_to_node(i));
5626 se = kzalloc_node(sizeof(struct sched_entity),
5627 GFP_KERNEL, cpu_to_node(i));
5631 init_cfs_rq(cfs_rq);
5632 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
5643 void unregister_fair_sched_group(struct task_group *tg, int cpu)
5645 struct rq *rq = cpu_rq(cpu);
5646 unsigned long flags;
5649 * Only empty task groups can be destroyed; so we can speculatively
5650 * check on_list without danger of it being re-added.
5652 if (!tg->cfs_rq[cpu]->on_list)
5655 raw_spin_lock_irqsave(&rq->lock, flags);
5656 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
5657 raw_spin_unlock_irqrestore(&rq->lock, flags);
5660 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
5661 struct sched_entity *se, int cpu,
5662 struct sched_entity *parent)
5664 struct rq *rq = cpu_rq(cpu);
5669 /* allow initial update_cfs_load() to truncate */
5670 cfs_rq->load_stamp = 1;
5672 init_cfs_rq_runtime(cfs_rq);
5674 tg->cfs_rq[cpu] = cfs_rq;
5677 /* se could be NULL for root_task_group */
5682 se->cfs_rq = &rq->cfs;
5684 se->cfs_rq = parent->my_q;
5687 update_load_set(&se->load, 0);
5688 se->parent = parent;
5691 static DEFINE_MUTEX(shares_mutex);
5693 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
5696 unsigned long flags;
5699 * We can't change the weight of the root cgroup.
5704 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
5706 mutex_lock(&shares_mutex);
5707 if (tg->shares == shares)
5710 tg->shares = shares;
5711 for_each_possible_cpu(i) {
5712 struct rq *rq = cpu_rq(i);
5713 struct sched_entity *se;
5716 /* Propagate contribution to hierarchy */
5717 raw_spin_lock_irqsave(&rq->lock, flags);
5718 for_each_sched_entity(se)
5719 update_cfs_shares(group_cfs_rq(se));
5720 raw_spin_unlock_irqrestore(&rq->lock, flags);
5724 mutex_unlock(&shares_mutex);
5727 #else /* CONFIG_FAIR_GROUP_SCHED */
5729 void free_fair_sched_group(struct task_group *tg) { }
5731 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5736 void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
5738 #endif /* CONFIG_FAIR_GROUP_SCHED */
5741 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
5743 struct sched_entity *se = &task->se;
5744 unsigned int rr_interval = 0;
5747 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
5750 if (rq->cfs.load.weight)
5751 rr_interval = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5757 * All the scheduling class methods:
5759 const struct sched_class fair_sched_class = {
5760 .next = &idle_sched_class,
5761 .enqueue_task = enqueue_task_fair,
5762 .dequeue_task = dequeue_task_fair,
5763 .yield_task = yield_task_fair,
5764 .yield_to_task = yield_to_task_fair,
5766 .check_preempt_curr = check_preempt_wakeup,
5768 .pick_next_task = pick_next_task_fair,
5769 .put_prev_task = put_prev_task_fair,
5772 .select_task_rq = select_task_rq_fair,
5774 .rq_online = rq_online_fair,
5775 .rq_offline = rq_offline_fair,
5777 .task_waking = task_waking_fair,
5780 .set_curr_task = set_curr_task_fair,
5781 .task_tick = task_tick_fair,
5782 .task_fork = task_fork_fair,
5784 .prio_changed = prio_changed_fair,
5785 .switched_from = switched_from_fair,
5786 .switched_to = switched_to_fair,
5788 .get_rr_interval = get_rr_interval_fair,
5790 #ifdef CONFIG_FAIR_GROUP_SCHED
5791 .task_move_group = task_move_group_fair,
5795 #ifdef CONFIG_SCHED_DEBUG
5796 void print_cfs_stats(struct seq_file *m, int cpu)
5798 struct cfs_rq *cfs_rq;
5801 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
5802 print_cfs_rq(m, cpu, cfs_rq);
5807 __init void init_sched_fair_class(void)
5810 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
5813 nohz.next_balance = jiffies;
5814 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
5815 cpu_notifier(sched_ilb_notifier, 0);