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>
22 * NUMA placement, statistics and algorithm by Andrea Arcangeli,
23 * CFS balancing changes by Peter Zijlstra. Copyright (C) 2012 Red Hat, Inc.
26 #include <linux/latencytop.h>
27 #include <linux/sched.h>
28 #include <linux/cpumask.h>
29 #include <linux/slab.h>
30 #include <linux/profile.h>
31 #include <linux/interrupt.h>
32 #include <linux/random.h>
33 #include <linux/mempolicy.h>
34 #include <linux/task_work.h>
36 #include <trace/events/sched.h>
41 * Targeted preemption latency for CPU-bound tasks:
42 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
44 * NOTE: this latency value is not the same as the concept of
45 * 'timeslice length' - timeslices in CFS are of variable length
46 * and have no persistent notion like in traditional, time-slice
47 * based scheduling concepts.
49 * (to see the precise effective timeslice length of your workload,
50 * run vmstat and monitor the context-switches (cs) field)
52 unsigned int sysctl_sched_latency = 6000000ULL;
53 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
56 * The initial- and re-scaling of tunables is configurable
57 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
60 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
61 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
62 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
64 enum sched_tunable_scaling sysctl_sched_tunable_scaling
65 = SCHED_TUNABLESCALING_LOG;
68 * Minimal preemption granularity for CPU-bound tasks:
69 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
71 unsigned int sysctl_sched_min_granularity = 750000ULL;
72 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
75 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
77 static unsigned int sched_nr_latency = 8;
80 * After fork, child runs first. If set to 0 (default) then
81 * parent will (try to) run first.
83 unsigned int sysctl_sched_child_runs_first __read_mostly;
86 * SCHED_OTHER wake-up granularity.
87 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
89 * This option delays the preemption effects of decoupled workloads
90 * and reduces their over-scheduling. Synchronous workloads will still
91 * have immediate wakeup/sleep latencies.
93 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
94 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
96 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
99 * The exponential sliding window over which load is averaged for shares
103 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
105 #ifdef CONFIG_CFS_BANDWIDTH
107 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
108 * each time a cfs_rq requests quota.
110 * Note: in the case that the slice exceeds the runtime remaining (either due
111 * to consumption or the quota being specified to be smaller than the slice)
112 * we will always only issue the remaining available time.
114 * default: 5 msec, units: microseconds
116 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
120 * Increase the granularity value when there are more CPUs,
121 * because with more CPUs the 'effective latency' as visible
122 * to users decreases. But the relationship is not linear,
123 * so pick a second-best guess by going with the log2 of the
126 * This idea comes from the SD scheduler of Con Kolivas:
128 static int get_update_sysctl_factor(void)
130 unsigned int cpus = min_t(int, num_online_cpus(), 8);
133 switch (sysctl_sched_tunable_scaling) {
134 case SCHED_TUNABLESCALING_NONE:
137 case SCHED_TUNABLESCALING_LINEAR:
140 case SCHED_TUNABLESCALING_LOG:
142 factor = 1 + ilog2(cpus);
149 static void update_sysctl(void)
151 unsigned int factor = get_update_sysctl_factor();
153 #define SET_SYSCTL(name) \
154 (sysctl_##name = (factor) * normalized_sysctl_##name)
155 SET_SYSCTL(sched_min_granularity);
156 SET_SYSCTL(sched_latency);
157 SET_SYSCTL(sched_wakeup_granularity);
161 void sched_init_granularity(void)
166 #if BITS_PER_LONG == 32
167 # define WMULT_CONST (~0UL)
169 # define WMULT_CONST (1UL << 32)
172 #define WMULT_SHIFT 32
175 * Shift right and round:
177 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
180 * delta *= weight / lw
183 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
184 struct load_weight *lw)
189 * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
190 * entities since MIN_SHARES = 2. Treat weight as 1 if less than
191 * 2^SCHED_LOAD_RESOLUTION.
193 if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
194 tmp = (u64)delta_exec * scale_load_down(weight);
196 tmp = (u64)delta_exec;
198 if (!lw->inv_weight) {
199 unsigned long w = scale_load_down(lw->weight);
201 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
203 else if (unlikely(!w))
204 lw->inv_weight = WMULT_CONST;
206 lw->inv_weight = WMULT_CONST / w;
210 * Check whether we'd overflow the 64-bit multiplication:
212 if (unlikely(tmp > WMULT_CONST))
213 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
216 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
218 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
222 const struct sched_class fair_sched_class;
224 /**************************************************************
225 * CFS operations on generic schedulable entities:
228 #ifdef CONFIG_FAIR_GROUP_SCHED
230 /* cpu runqueue to which this cfs_rq is attached */
231 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
236 /* An entity is a task if it doesn't "own" a runqueue */
237 #define entity_is_task(se) (!se->my_q)
239 static inline struct task_struct *task_of(struct sched_entity *se)
241 #ifdef CONFIG_SCHED_DEBUG
242 WARN_ON_ONCE(!entity_is_task(se));
244 return container_of(se, struct task_struct, se);
247 /* Walk up scheduling entities hierarchy */
248 #define for_each_sched_entity(se) \
249 for (; se; se = se->parent)
251 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
256 /* runqueue on which this entity is (to be) queued */
257 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
262 /* runqueue "owned" by this group */
263 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
268 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
270 if (!cfs_rq->on_list) {
272 * Ensure we either appear before our parent (if already
273 * enqueued) or force our parent to appear after us when it is
274 * enqueued. The fact that we always enqueue bottom-up
275 * reduces this to two cases.
277 if (cfs_rq->tg->parent &&
278 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
279 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
280 &rq_of(cfs_rq)->leaf_cfs_rq_list);
282 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
283 &rq_of(cfs_rq)->leaf_cfs_rq_list);
290 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
292 if (cfs_rq->on_list) {
293 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
298 /* Iterate thr' all leaf cfs_rq's on a runqueue */
299 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
300 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
302 /* Do the two (enqueued) entities belong to the same group ? */
304 is_same_group(struct sched_entity *se, struct sched_entity *pse)
306 if (se->cfs_rq == pse->cfs_rq)
312 static inline struct sched_entity *parent_entity(struct sched_entity *se)
317 /* return depth at which a sched entity is present in the hierarchy */
318 static inline int depth_se(struct sched_entity *se)
322 for_each_sched_entity(se)
329 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
331 int se_depth, pse_depth;
334 * preemption test can be made between sibling entities who are in the
335 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
336 * both tasks until we find their ancestors who are siblings of common
340 /* First walk up until both entities are at same depth */
341 se_depth = depth_se(*se);
342 pse_depth = depth_se(*pse);
344 while (se_depth > pse_depth) {
346 *se = parent_entity(*se);
349 while (pse_depth > se_depth) {
351 *pse = parent_entity(*pse);
354 while (!is_same_group(*se, *pse)) {
355 *se = parent_entity(*se);
356 *pse = parent_entity(*pse);
360 #else /* !CONFIG_FAIR_GROUP_SCHED */
362 static inline struct task_struct *task_of(struct sched_entity *se)
364 return container_of(se, struct task_struct, se);
367 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
369 return container_of(cfs_rq, struct rq, cfs);
372 #define entity_is_task(se) 1
374 #define for_each_sched_entity(se) \
375 for (; se; se = NULL)
377 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
379 return &task_rq(p)->cfs;
382 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
384 struct task_struct *p = task_of(se);
385 struct rq *rq = task_rq(p);
390 /* runqueue "owned" by this group */
391 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
396 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
400 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
404 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
405 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
408 is_same_group(struct sched_entity *se, struct sched_entity *pse)
413 static inline struct sched_entity *parent_entity(struct sched_entity *se)
419 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
423 #endif /* CONFIG_FAIR_GROUP_SCHED */
425 static __always_inline
426 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
428 /**************************************************************
429 * Scheduling class tree data structure manipulation methods:
432 static inline u64 max_vruntime(u64 min_vruntime, u64 vruntime)
434 s64 delta = (s64)(vruntime - min_vruntime);
436 min_vruntime = vruntime;
441 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
443 s64 delta = (s64)(vruntime - min_vruntime);
445 min_vruntime = vruntime;
450 static inline int entity_before(struct sched_entity *a,
451 struct sched_entity *b)
453 return (s64)(a->vruntime - b->vruntime) < 0;
456 static void update_min_vruntime(struct cfs_rq *cfs_rq)
458 u64 vruntime = cfs_rq->min_vruntime;
461 vruntime = cfs_rq->curr->vruntime;
463 if (cfs_rq->rb_leftmost) {
464 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
469 vruntime = se->vruntime;
471 vruntime = min_vruntime(vruntime, se->vruntime);
474 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
477 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
482 * Enqueue an entity into the rb-tree:
484 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
486 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
487 struct rb_node *parent = NULL;
488 struct sched_entity *entry;
492 * Find the right place in the rbtree:
496 entry = rb_entry(parent, struct sched_entity, run_node);
498 * We dont care about collisions. Nodes with
499 * the same key stay together.
501 if (entity_before(se, entry)) {
502 link = &parent->rb_left;
504 link = &parent->rb_right;
510 * Maintain a cache of leftmost tree entries (it is frequently
514 cfs_rq->rb_leftmost = &se->run_node;
516 rb_link_node(&se->run_node, parent, link);
517 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
520 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
522 if (cfs_rq->rb_leftmost == &se->run_node) {
523 struct rb_node *next_node;
525 next_node = rb_next(&se->run_node);
526 cfs_rq->rb_leftmost = next_node;
529 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
532 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
534 struct rb_node *left = cfs_rq->rb_leftmost;
539 return rb_entry(left, struct sched_entity, run_node);
542 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
544 struct rb_node *next = rb_next(&se->run_node);
549 return rb_entry(next, struct sched_entity, run_node);
552 #ifdef CONFIG_SCHED_DEBUG
553 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
555 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
560 return rb_entry(last, struct sched_entity, run_node);
563 /**************************************************************
564 * Scheduling class statistics methods:
567 int sched_proc_update_handler(struct ctl_table *table, int write,
568 void __user *buffer, size_t *lenp,
571 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
572 int factor = get_update_sysctl_factor();
577 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
578 sysctl_sched_min_granularity);
580 #define WRT_SYSCTL(name) \
581 (normalized_sysctl_##name = sysctl_##name / (factor))
582 WRT_SYSCTL(sched_min_granularity);
583 WRT_SYSCTL(sched_latency);
584 WRT_SYSCTL(sched_wakeup_granularity);
594 static inline unsigned long
595 calc_delta_fair(unsigned long delta, struct sched_entity *se)
597 if (unlikely(se->load.weight != NICE_0_LOAD))
598 delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
604 * The idea is to set a period in which each task runs once.
606 * When there are too many tasks (sched_nr_latency) we have to stretch
607 * this period because otherwise the slices get too small.
609 * p = (nr <= nl) ? l : l*nr/nl
611 static u64 __sched_period(unsigned long nr_running)
613 u64 period = sysctl_sched_latency;
614 unsigned long nr_latency = sched_nr_latency;
616 if (unlikely(nr_running > nr_latency)) {
617 period = sysctl_sched_min_granularity;
618 period *= nr_running;
625 * We calculate the wall-time slice from the period by taking a part
626 * proportional to the weight.
630 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
632 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
634 for_each_sched_entity(se) {
635 struct load_weight *load;
636 struct load_weight lw;
638 cfs_rq = cfs_rq_of(se);
639 load = &cfs_rq->load;
641 if (unlikely(!se->on_rq)) {
644 update_load_add(&lw, se->load.weight);
647 slice = calc_delta_mine(slice, se->load.weight, load);
653 * We calculate the vruntime slice of a to be inserted task
657 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
659 return calc_delta_fair(sched_slice(cfs_rq, se), se);
662 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update);
663 static void update_cfs_shares(struct cfs_rq *cfs_rq);
666 * Update the current task's runtime statistics. Skip current tasks that
667 * are not in our scheduling class.
670 __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
671 unsigned long delta_exec)
673 unsigned long delta_exec_weighted;
675 schedstat_set(curr->statistics.exec_max,
676 max((u64)delta_exec, curr->statistics.exec_max));
678 curr->sum_exec_runtime += delta_exec;
679 schedstat_add(cfs_rq, exec_clock, delta_exec);
680 delta_exec_weighted = calc_delta_fair(delta_exec, curr);
682 curr->vruntime += delta_exec_weighted;
683 update_min_vruntime(cfs_rq);
685 #if defined CONFIG_SMP && defined CONFIG_FAIR_GROUP_SCHED
686 cfs_rq->load_unacc_exec_time += delta_exec;
690 static void update_curr(struct cfs_rq *cfs_rq)
692 struct sched_entity *curr = cfs_rq->curr;
693 u64 now = rq_of(cfs_rq)->clock_task;
694 unsigned long delta_exec;
700 * Get the amount of time the current task was running
701 * since the last time we changed load (this cannot
702 * overflow on 32 bits):
704 delta_exec = (unsigned long)(now - curr->exec_start);
708 __update_curr(cfs_rq, curr, delta_exec);
709 curr->exec_start = now;
711 if (entity_is_task(curr)) {
712 struct task_struct *curtask = task_of(curr);
714 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
715 cpuacct_charge(curtask, delta_exec);
716 account_group_exec_runtime(curtask, delta_exec);
719 account_cfs_rq_runtime(cfs_rq, delta_exec);
723 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
725 schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
729 * Task is being enqueued - update stats:
731 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
734 * Are we enqueueing a waiting task? (for current tasks
735 * a dequeue/enqueue event is a NOP)
737 if (se != cfs_rq->curr)
738 update_stats_wait_start(cfs_rq, se);
742 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
744 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
745 rq_of(cfs_rq)->clock - se->statistics.wait_start));
746 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
747 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
748 rq_of(cfs_rq)->clock - se->statistics.wait_start);
749 #ifdef CONFIG_SCHEDSTATS
750 if (entity_is_task(se)) {
751 trace_sched_stat_wait(task_of(se),
752 rq_of(cfs_rq)->clock - se->statistics.wait_start);
755 schedstat_set(se->statistics.wait_start, 0);
759 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
762 * Mark the end of the wait period if dequeueing a
765 if (se != cfs_rq->curr)
766 update_stats_wait_end(cfs_rq, se);
770 * We are picking a new current task - update its stats:
773 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
776 * We are starting a new run period:
778 se->exec_start = rq_of(cfs_rq)->clock_task;
781 /**************************************************
782 * Scheduling class numa methods.
784 * The purpose of the NUMA bits are to maintain compute (task) and data
785 * (memory) locality. We try and achieve this by making tasks stick to
786 * a particular node (their home node) but if fairness mandates they run
787 * elsewhere for long enough, we let the memory follow them.
789 * Tasks start out with their home-node unset (-1) this effectively means
790 * they act !NUMA until we've established the task is busy enough to bother
793 * We keep a home-node per task and use periodic fault scans to try and
794 * estalish a task<->page relation. This assumes the task<->page relation is a
795 * compute<->data relation, this is false for things like virt. and n:m
796 * threading solutions but its the best we can do given the information we
800 static unsigned long task_h_load(struct task_struct *p);
802 #ifdef CONFIG_SCHED_NUMA
803 static struct list_head *account_numa_enqueue(struct rq *rq, struct task_struct *p)
805 struct list_head *tasks = &rq->cfs_tasks;
807 if (tsk_home_node(p) != cpu_to_node(task_cpu(p))) {
808 p->numa_contrib = task_h_load(p);
809 rq->offnode_weight += p->numa_contrib;
810 rq->offnode_running++;
811 tasks = &rq->offnode_tasks;
813 rq->onnode_running++;
818 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
820 if (tsk_home_node(p) != cpu_to_node(task_cpu(p))) {
821 rq->offnode_weight -= p->numa_contrib;
822 rq->offnode_running--;
824 rq->onnode_running--;
828 * numa task sample period in ms: 5s
830 unsigned int sysctl_sched_numa_task_period_min = 5000;
831 unsigned int sysctl_sched_numa_task_period_max = 5000*16;
834 * Wait for the 2-sample stuff to settle before migrating again
836 unsigned int sysctl_sched_numa_settle_count = 2;
838 static void task_numa_placement(struct task_struct *p)
840 unsigned long faults, max_faults = 0;
841 int node, max_node = -1;
842 int seq = ACCESS_ONCE(p->mm->numa_scan_seq);
844 if (p->numa_scan_seq == seq)
847 p->numa_scan_seq = seq;
849 for (node = 0; node < nr_node_ids; node++) {
850 faults = p->numa_faults[node];
852 if (faults > max_faults) {
857 p->numa_faults[node] /= 2;
863 if (p->node != max_node) {
864 p->numa_task_period = sysctl_sched_numa_task_period_min;
865 if (sched_feat(NUMA_SETTLE) &&
866 (seq - p->numa_migrate_seq) <= (int)sysctl_sched_numa_settle_count)
868 p->numa_migrate_seq = seq;
869 sched_setnode(p, max_node);
871 p->numa_task_period = min(sysctl_sched_numa_task_period_max,
872 p->numa_task_period * 2);
877 * Got a PROT_NONE fault for a page on @node.
879 void task_numa_fault(int node, int pages)
881 struct task_struct *p = current;
883 if (unlikely(!p->numa_faults)) {
884 int size = sizeof(unsigned long) * nr_node_ids;
886 p->numa_faults = kzalloc(size, GFP_KERNEL);
891 task_numa_placement(p);
893 p->numa_faults[node] += pages;
897 * The expensive part of numa migration is done from task_work context.
898 * Triggered from task_tick_numa().
900 void task_numa_work(struct callback_head *work)
902 unsigned long migrate, next_scan, now = jiffies;
903 struct task_struct *p = current;
904 struct mm_struct *mm = p->mm;
906 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
908 work->next = work; /* protect against double add */
910 * Who cares about NUMA placement when they're dying.
912 * NOTE: make sure not to dereference p->mm before this check,
913 * exit_task_work() happens _after_ exit_mm() so we could be called
914 * without p->mm even though we still had it when we enqueued this
917 if (p->flags & PF_EXITING)
921 * Enforce maximal scan/migration frequency..
923 migrate = mm->numa_next_scan;
924 if (time_before(now, migrate))
927 next_scan = now + 2*msecs_to_jiffies(sysctl_sched_numa_task_period_min);
928 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
931 ACCESS_ONCE(mm->numa_scan_seq)++;
932 lazy_migrate_process(mm);
936 * Drive the periodic memory faults..
938 void task_tick_numa(struct rq *rq, struct task_struct *curr)
940 struct callback_head *work = &curr->numa_work;
944 * We don't care about NUMA placement if we don't have memory.
946 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
950 * Using runtime rather than walltime has the dual advantage that
951 * we (mostly) drive the selection from busy threads and that the
952 * task needs to have done some actual work before we bother with
955 now = curr->se.sum_exec_runtime;
956 period = (u64)curr->numa_task_period * NSEC_PER_MSEC;
958 if (now - curr->node_stamp > period) {
959 curr->node_stamp = now;
961 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
962 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
963 task_work_add(curr, work, true);
968 static struct list_head *account_numa_enqueue(struct rq *rq, struct task_struct *p)
973 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
977 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
980 #endif /* CONFIG_SCHED_NUMA */
982 /**************************************************
983 * Scheduling class queueing methods:
987 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
989 update_load_add(&cfs_rq->load, se->load.weight);
990 if (!parent_entity(se))
991 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
993 if (entity_is_task(se)) {
994 struct rq *rq = rq_of(cfs_rq);
995 struct task_struct *p = task_of(se);
996 struct list_head *tasks = &rq->cfs_tasks;
998 if (tsk_home_node(p) != -1)
999 tasks = account_numa_enqueue(rq, p);
1001 list_add(&se->group_node, tasks);
1003 #endif /* CONFIG_SMP */
1004 cfs_rq->nr_running++;
1008 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1010 update_load_sub(&cfs_rq->load, se->load.weight);
1011 if (!parent_entity(se))
1012 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
1013 if (entity_is_task(se)) {
1014 struct task_struct *p = task_of(se);
1016 list_del_init(&se->group_node);
1018 if (tsk_home_node(p) != -1)
1019 account_numa_dequeue(rq_of(cfs_rq), p);
1021 cfs_rq->nr_running--;
1024 #ifdef CONFIG_FAIR_GROUP_SCHED
1025 /* we need this in update_cfs_load and load-balance functions below */
1026 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
1028 static void update_cfs_rq_load_contribution(struct cfs_rq *cfs_rq,
1031 struct task_group *tg = cfs_rq->tg;
1034 load_avg = div64_u64(cfs_rq->load_avg, cfs_rq->load_period+1);
1035 load_avg -= cfs_rq->load_contribution;
1037 if (global_update || abs(load_avg) > cfs_rq->load_contribution / 8) {
1038 atomic_add(load_avg, &tg->load_weight);
1039 cfs_rq->load_contribution += load_avg;
1043 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1045 u64 period = sysctl_sched_shares_window;
1047 unsigned long load = cfs_rq->load.weight;
1049 if (cfs_rq->tg == &root_task_group || throttled_hierarchy(cfs_rq))
1052 now = rq_of(cfs_rq)->clock_task;
1053 delta = now - cfs_rq->load_stamp;
1055 /* truncate load history at 4 idle periods */
1056 if (cfs_rq->load_stamp > cfs_rq->load_last &&
1057 now - cfs_rq->load_last > 4 * period) {
1058 cfs_rq->load_period = 0;
1059 cfs_rq->load_avg = 0;
1063 cfs_rq->load_stamp = now;
1064 cfs_rq->load_unacc_exec_time = 0;
1065 cfs_rq->load_period += delta;
1067 cfs_rq->load_last = now;
1068 cfs_rq->load_avg += delta * load;
1071 /* consider updating load contribution on each fold or truncate */
1072 if (global_update || cfs_rq->load_period > period
1073 || !cfs_rq->load_period)
1074 update_cfs_rq_load_contribution(cfs_rq, global_update);
1076 while (cfs_rq->load_period > period) {
1078 * Inline assembly required to prevent the compiler
1079 * optimising this loop into a divmod call.
1080 * See __iter_div_u64_rem() for another example of this.
1082 asm("" : "+rm" (cfs_rq->load_period));
1083 cfs_rq->load_period /= 2;
1084 cfs_rq->load_avg /= 2;
1087 if (!cfs_rq->curr && !cfs_rq->nr_running && !cfs_rq->load_avg)
1088 list_del_leaf_cfs_rq(cfs_rq);
1091 static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
1096 * Use this CPU's actual weight instead of the last load_contribution
1097 * to gain a more accurate current total weight. See
1098 * update_cfs_rq_load_contribution().
1100 tg_weight = atomic_read(&tg->load_weight);
1101 tg_weight -= cfs_rq->load_contribution;
1102 tg_weight += cfs_rq->load.weight;
1107 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1109 long tg_weight, load, shares;
1111 tg_weight = calc_tg_weight(tg, cfs_rq);
1112 load = cfs_rq->load.weight;
1114 shares = (tg->shares * load);
1116 shares /= tg_weight;
1118 if (shares < MIN_SHARES)
1119 shares = MIN_SHARES;
1120 if (shares > tg->shares)
1121 shares = tg->shares;
1126 static void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1128 if (cfs_rq->load_unacc_exec_time > sysctl_sched_shares_window) {
1129 update_cfs_load(cfs_rq, 0);
1130 update_cfs_shares(cfs_rq);
1133 # else /* CONFIG_SMP */
1134 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1138 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1143 static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1146 # endif /* CONFIG_SMP */
1147 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
1148 unsigned long weight)
1151 /* commit outstanding execution time */
1152 if (cfs_rq->curr == se)
1153 update_curr(cfs_rq);
1154 account_entity_dequeue(cfs_rq, se);
1157 update_load_set(&se->load, weight);
1160 account_entity_enqueue(cfs_rq, se);
1163 static void update_cfs_shares(struct cfs_rq *cfs_rq)
1165 struct task_group *tg;
1166 struct sched_entity *se;
1170 se = tg->se[cpu_of(rq_of(cfs_rq))];
1171 if (!se || throttled_hierarchy(cfs_rq))
1174 if (likely(se->load.weight == tg->shares))
1177 shares = calc_cfs_shares(cfs_rq, tg);
1179 reweight_entity(cfs_rq_of(se), se, shares);
1181 #else /* CONFIG_FAIR_GROUP_SCHED */
1182 static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
1186 static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
1190 static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
1193 #endif /* CONFIG_FAIR_GROUP_SCHED */
1195 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
1197 #ifdef CONFIG_SCHEDSTATS
1198 struct task_struct *tsk = NULL;
1200 if (entity_is_task(se))
1203 if (se->statistics.sleep_start) {
1204 u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
1209 if (unlikely(delta > se->statistics.sleep_max))
1210 se->statistics.sleep_max = delta;
1212 se->statistics.sleep_start = 0;
1213 se->statistics.sum_sleep_runtime += delta;
1216 account_scheduler_latency(tsk, delta >> 10, 1);
1217 trace_sched_stat_sleep(tsk, delta);
1220 if (se->statistics.block_start) {
1221 u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
1226 if (unlikely(delta > se->statistics.block_max))
1227 se->statistics.block_max = delta;
1229 se->statistics.block_start = 0;
1230 se->statistics.sum_sleep_runtime += delta;
1233 if (tsk->in_iowait) {
1234 se->statistics.iowait_sum += delta;
1235 se->statistics.iowait_count++;
1236 trace_sched_stat_iowait(tsk, delta);
1239 trace_sched_stat_blocked(tsk, delta);
1242 * Blocking time is in units of nanosecs, so shift by
1243 * 20 to get a milliseconds-range estimation of the
1244 * amount of time that the task spent sleeping:
1246 if (unlikely(prof_on == SLEEP_PROFILING)) {
1247 profile_hits(SLEEP_PROFILING,
1248 (void *)get_wchan(tsk),
1251 account_scheduler_latency(tsk, delta >> 10, 0);
1257 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
1259 #ifdef CONFIG_SCHED_DEBUG
1260 s64 d = se->vruntime - cfs_rq->min_vruntime;
1265 if (d > 3*sysctl_sched_latency)
1266 schedstat_inc(cfs_rq, nr_spread_over);
1271 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
1273 u64 vruntime = cfs_rq->min_vruntime;
1276 * The 'current' period is already promised to the current tasks,
1277 * however the extra weight of the new task will slow them down a
1278 * little, place the new task so that it fits in the slot that
1279 * stays open at the end.
1281 if (initial && sched_feat(START_DEBIT))
1282 vruntime += sched_vslice(cfs_rq, se);
1284 /* sleeps up to a single latency don't count. */
1286 unsigned long thresh = sysctl_sched_latency;
1289 * Halve their sleep time's effect, to allow
1290 * for a gentler effect of sleepers:
1292 if (sched_feat(GENTLE_FAIR_SLEEPERS))
1298 /* ensure we never gain time by being placed backwards. */
1299 vruntime = max_vruntime(se->vruntime, vruntime);
1301 se->vruntime = vruntime;
1304 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
1307 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1310 * Update the normalized vruntime before updating min_vruntime
1311 * through callig update_curr().
1313 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
1314 se->vruntime += cfs_rq->min_vruntime;
1317 * Update run-time statistics of the 'current'.
1319 update_curr(cfs_rq);
1320 update_cfs_load(cfs_rq, 0);
1321 account_entity_enqueue(cfs_rq, se);
1322 update_cfs_shares(cfs_rq);
1324 if (flags & ENQUEUE_WAKEUP) {
1325 place_entity(cfs_rq, se, 0);
1326 enqueue_sleeper(cfs_rq, se);
1329 update_stats_enqueue(cfs_rq, se);
1330 check_spread(cfs_rq, se);
1331 if (se != cfs_rq->curr)
1332 __enqueue_entity(cfs_rq, se);
1335 if (cfs_rq->nr_running == 1) {
1336 list_add_leaf_cfs_rq(cfs_rq);
1337 check_enqueue_throttle(cfs_rq);
1341 static void __clear_buddies_last(struct sched_entity *se)
1343 for_each_sched_entity(se) {
1344 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1345 if (cfs_rq->last == se)
1346 cfs_rq->last = NULL;
1352 static void __clear_buddies_next(struct sched_entity *se)
1354 for_each_sched_entity(se) {
1355 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1356 if (cfs_rq->next == se)
1357 cfs_rq->next = NULL;
1363 static void __clear_buddies_skip(struct sched_entity *se)
1365 for_each_sched_entity(se) {
1366 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1367 if (cfs_rq->skip == se)
1368 cfs_rq->skip = NULL;
1374 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
1376 if (cfs_rq->last == se)
1377 __clear_buddies_last(se);
1379 if (cfs_rq->next == se)
1380 __clear_buddies_next(se);
1382 if (cfs_rq->skip == se)
1383 __clear_buddies_skip(se);
1386 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1389 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1392 * Update run-time statistics of the 'current'.
1394 update_curr(cfs_rq);
1396 update_stats_dequeue(cfs_rq, se);
1397 if (flags & DEQUEUE_SLEEP) {
1398 #ifdef CONFIG_SCHEDSTATS
1399 if (entity_is_task(se)) {
1400 struct task_struct *tsk = task_of(se);
1402 if (tsk->state & TASK_INTERRUPTIBLE)
1403 se->statistics.sleep_start = rq_of(cfs_rq)->clock;
1404 if (tsk->state & TASK_UNINTERRUPTIBLE)
1405 se->statistics.block_start = rq_of(cfs_rq)->clock;
1410 clear_buddies(cfs_rq, se);
1412 if (se != cfs_rq->curr)
1413 __dequeue_entity(cfs_rq, se);
1415 update_cfs_load(cfs_rq, 0);
1416 account_entity_dequeue(cfs_rq, se);
1419 * Normalize the entity after updating the min_vruntime because the
1420 * update can refer to the ->curr item and we need to reflect this
1421 * movement in our normalized position.
1423 if (!(flags & DEQUEUE_SLEEP))
1424 se->vruntime -= cfs_rq->min_vruntime;
1426 /* return excess runtime on last dequeue */
1427 return_cfs_rq_runtime(cfs_rq);
1429 update_min_vruntime(cfs_rq);
1430 update_cfs_shares(cfs_rq);
1434 * Preempt the current task with a newly woken task if needed:
1437 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
1439 unsigned long ideal_runtime, delta_exec;
1440 struct sched_entity *se;
1443 ideal_runtime = sched_slice(cfs_rq, curr);
1444 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
1445 if (delta_exec > ideal_runtime) {
1446 resched_task(rq_of(cfs_rq)->curr);
1448 * The current task ran long enough, ensure it doesn't get
1449 * re-elected due to buddy favours.
1451 clear_buddies(cfs_rq, curr);
1456 * Ensure that a task that missed wakeup preemption by a
1457 * narrow margin doesn't have to wait for a full slice.
1458 * This also mitigates buddy induced latencies under load.
1460 if (delta_exec < sysctl_sched_min_granularity)
1463 se = __pick_first_entity(cfs_rq);
1464 delta = curr->vruntime - se->vruntime;
1469 if (delta > ideal_runtime)
1470 resched_task(rq_of(cfs_rq)->curr);
1474 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1476 /* 'current' is not kept within the tree. */
1479 * Any task has to be enqueued before it get to execute on
1480 * a CPU. So account for the time it spent waiting on the
1483 update_stats_wait_end(cfs_rq, se);
1484 __dequeue_entity(cfs_rq, se);
1487 update_stats_curr_start(cfs_rq, se);
1489 #ifdef CONFIG_SCHEDSTATS
1491 * Track our maximum slice length, if the CPU's load is at
1492 * least twice that of our own weight (i.e. dont track it
1493 * when there are only lesser-weight tasks around):
1495 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
1496 se->statistics.slice_max = max(se->statistics.slice_max,
1497 se->sum_exec_runtime - se->prev_sum_exec_runtime);
1500 se->prev_sum_exec_runtime = se->sum_exec_runtime;
1504 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
1507 * Pick the next process, keeping these things in mind, in this order:
1508 * 1) keep things fair between processes/task groups
1509 * 2) pick the "next" process, since someone really wants that to run
1510 * 3) pick the "last" process, for cache locality
1511 * 4) do not run the "skip" process, if something else is available
1513 static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
1515 struct sched_entity *se = __pick_first_entity(cfs_rq);
1516 struct sched_entity *left = se;
1519 * Avoid running the skip buddy, if running something else can
1520 * be done without getting too unfair.
1522 if (cfs_rq->skip == se) {
1523 struct sched_entity *second = __pick_next_entity(se);
1524 if (second && wakeup_preempt_entity(second, left) < 1)
1529 * Prefer last buddy, try to return the CPU to a preempted task.
1531 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
1535 * Someone really wants this to run. If it's not unfair, run it.
1537 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
1540 clear_buddies(cfs_rq, se);
1545 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1547 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
1550 * If still on the runqueue then deactivate_task()
1551 * was not called and update_curr() has to be done:
1554 update_curr(cfs_rq);
1556 /* throttle cfs_rqs exceeding runtime */
1557 check_cfs_rq_runtime(cfs_rq);
1559 check_spread(cfs_rq, prev);
1561 update_stats_wait_start(cfs_rq, prev);
1562 /* Put 'current' back into the tree. */
1563 __enqueue_entity(cfs_rq, prev);
1565 cfs_rq->curr = NULL;
1569 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
1572 * Update run-time statistics of the 'current'.
1574 update_curr(cfs_rq);
1577 * Update share accounting for long-running entities.
1579 update_entity_shares_tick(cfs_rq);
1581 #ifdef CONFIG_SCHED_HRTICK
1583 * queued ticks are scheduled to match the slice, so don't bother
1584 * validating it and just reschedule.
1587 resched_task(rq_of(cfs_rq)->curr);
1591 * don't let the period tick interfere with the hrtick preemption
1593 if (!sched_feat(DOUBLE_TICK) &&
1594 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
1598 if (cfs_rq->nr_running > 1)
1599 check_preempt_tick(cfs_rq, curr);
1603 /**************************************************
1604 * CFS bandwidth control machinery
1607 #ifdef CONFIG_CFS_BANDWIDTH
1609 #ifdef HAVE_JUMP_LABEL
1610 static struct static_key __cfs_bandwidth_used;
1612 static inline bool cfs_bandwidth_used(void)
1614 return static_key_false(&__cfs_bandwidth_used);
1617 void account_cfs_bandwidth_used(int enabled, int was_enabled)
1619 /* only need to count groups transitioning between enabled/!enabled */
1620 if (enabled && !was_enabled)
1621 static_key_slow_inc(&__cfs_bandwidth_used);
1622 else if (!enabled && was_enabled)
1623 static_key_slow_dec(&__cfs_bandwidth_used);
1625 #else /* HAVE_JUMP_LABEL */
1626 static bool cfs_bandwidth_used(void)
1631 void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
1632 #endif /* HAVE_JUMP_LABEL */
1635 * default period for cfs group bandwidth.
1636 * default: 0.1s, units: nanoseconds
1638 static inline u64 default_cfs_period(void)
1640 return 100000000ULL;
1643 static inline u64 sched_cfs_bandwidth_slice(void)
1645 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
1649 * Replenish runtime according to assigned quota and update expiration time.
1650 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
1651 * additional synchronization around rq->lock.
1653 * requires cfs_b->lock
1655 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
1659 if (cfs_b->quota == RUNTIME_INF)
1662 now = sched_clock_cpu(smp_processor_id());
1663 cfs_b->runtime = cfs_b->quota;
1664 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
1667 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
1669 return &tg->cfs_bandwidth;
1672 /* returns 0 on failure to allocate runtime */
1673 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
1675 struct task_group *tg = cfs_rq->tg;
1676 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
1677 u64 amount = 0, min_amount, expires;
1679 /* note: this is a positive sum as runtime_remaining <= 0 */
1680 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
1682 raw_spin_lock(&cfs_b->lock);
1683 if (cfs_b->quota == RUNTIME_INF)
1684 amount = min_amount;
1687 * If the bandwidth pool has become inactive, then at least one
1688 * period must have elapsed since the last consumption.
1689 * Refresh the global state and ensure bandwidth timer becomes
1692 if (!cfs_b->timer_active) {
1693 __refill_cfs_bandwidth_runtime(cfs_b);
1694 __start_cfs_bandwidth(cfs_b);
1697 if (cfs_b->runtime > 0) {
1698 amount = min(cfs_b->runtime, min_amount);
1699 cfs_b->runtime -= amount;
1703 expires = cfs_b->runtime_expires;
1704 raw_spin_unlock(&cfs_b->lock);
1706 cfs_rq->runtime_remaining += amount;
1708 * we may have advanced our local expiration to account for allowed
1709 * spread between our sched_clock and the one on which runtime was
1712 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
1713 cfs_rq->runtime_expires = expires;
1715 return cfs_rq->runtime_remaining > 0;
1719 * Note: This depends on the synchronization provided by sched_clock and the
1720 * fact that rq->clock snapshots this value.
1722 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
1724 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1725 struct rq *rq = rq_of(cfs_rq);
1727 /* if the deadline is ahead of our clock, nothing to do */
1728 if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
1731 if (cfs_rq->runtime_remaining < 0)
1735 * If the local deadline has passed we have to consider the
1736 * possibility that our sched_clock is 'fast' and the global deadline
1737 * has not truly expired.
1739 * Fortunately we can check determine whether this the case by checking
1740 * whether the global deadline has advanced.
1743 if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
1744 /* extend local deadline, drift is bounded above by 2 ticks */
1745 cfs_rq->runtime_expires += TICK_NSEC;
1747 /* global deadline is ahead, expiration has passed */
1748 cfs_rq->runtime_remaining = 0;
1752 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
1753 unsigned long delta_exec)
1755 /* dock delta_exec before expiring quota (as it could span periods) */
1756 cfs_rq->runtime_remaining -= delta_exec;
1757 expire_cfs_rq_runtime(cfs_rq);
1759 if (likely(cfs_rq->runtime_remaining > 0))
1763 * if we're unable to extend our runtime we resched so that the active
1764 * hierarchy can be throttled
1766 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
1767 resched_task(rq_of(cfs_rq)->curr);
1770 static __always_inline
1771 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
1773 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
1776 __account_cfs_rq_runtime(cfs_rq, delta_exec);
1779 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
1781 return cfs_bandwidth_used() && cfs_rq->throttled;
1784 /* check whether cfs_rq, or any parent, is throttled */
1785 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
1787 return cfs_bandwidth_used() && cfs_rq->throttle_count;
1791 * Ensure that neither of the group entities corresponding to src_cpu or
1792 * dest_cpu are members of a throttled hierarchy when performing group
1793 * load-balance operations.
1795 static inline int throttled_lb_pair(struct task_group *tg,
1796 int src_cpu, int dest_cpu)
1798 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
1800 src_cfs_rq = tg->cfs_rq[src_cpu];
1801 dest_cfs_rq = tg->cfs_rq[dest_cpu];
1803 return throttled_hierarchy(src_cfs_rq) ||
1804 throttled_hierarchy(dest_cfs_rq);
1807 /* updated child weight may affect parent so we have to do this bottom up */
1808 static int tg_unthrottle_up(struct task_group *tg, void *data)
1810 struct rq *rq = data;
1811 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1813 cfs_rq->throttle_count--;
1815 if (!cfs_rq->throttle_count) {
1816 u64 delta = rq->clock_task - cfs_rq->load_stamp;
1818 /* leaving throttled state, advance shares averaging windows */
1819 cfs_rq->load_stamp += delta;
1820 cfs_rq->load_last += delta;
1822 /* update entity weight now that we are on_rq again */
1823 update_cfs_shares(cfs_rq);
1830 static int tg_throttle_down(struct task_group *tg, void *data)
1832 struct rq *rq = data;
1833 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
1835 /* group is entering throttled state, record last load */
1836 if (!cfs_rq->throttle_count)
1837 update_cfs_load(cfs_rq, 0);
1838 cfs_rq->throttle_count++;
1843 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
1845 struct rq *rq = rq_of(cfs_rq);
1846 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1847 struct sched_entity *se;
1848 long task_delta, dequeue = 1;
1850 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
1852 /* account load preceding throttle */
1854 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
1857 task_delta = cfs_rq->h_nr_running;
1858 for_each_sched_entity(se) {
1859 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
1860 /* throttled entity or throttle-on-deactivate */
1865 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
1866 qcfs_rq->h_nr_running -= task_delta;
1868 if (qcfs_rq->load.weight)
1873 rq->nr_running -= task_delta;
1875 cfs_rq->throttled = 1;
1876 cfs_rq->throttled_timestamp = rq->clock;
1877 raw_spin_lock(&cfs_b->lock);
1878 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
1879 raw_spin_unlock(&cfs_b->lock);
1882 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
1884 struct rq *rq = rq_of(cfs_rq);
1885 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
1886 struct sched_entity *se;
1890 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
1892 cfs_rq->throttled = 0;
1893 raw_spin_lock(&cfs_b->lock);
1894 cfs_b->throttled_time += rq->clock - cfs_rq->throttled_timestamp;
1895 list_del_rcu(&cfs_rq->throttled_list);
1896 raw_spin_unlock(&cfs_b->lock);
1897 cfs_rq->throttled_timestamp = 0;
1899 update_rq_clock(rq);
1900 /* update hierarchical throttle state */
1901 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
1903 if (!cfs_rq->load.weight)
1906 task_delta = cfs_rq->h_nr_running;
1907 for_each_sched_entity(se) {
1911 cfs_rq = cfs_rq_of(se);
1913 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
1914 cfs_rq->h_nr_running += task_delta;
1916 if (cfs_rq_throttled(cfs_rq))
1921 rq->nr_running += task_delta;
1923 /* determine whether we need to wake up potentially idle cpu */
1924 if (rq->curr == rq->idle && rq->cfs.nr_running)
1925 resched_task(rq->curr);
1928 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
1929 u64 remaining, u64 expires)
1931 struct cfs_rq *cfs_rq;
1932 u64 runtime = remaining;
1935 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
1937 struct rq *rq = rq_of(cfs_rq);
1939 raw_spin_lock(&rq->lock);
1940 if (!cfs_rq_throttled(cfs_rq))
1943 runtime = -cfs_rq->runtime_remaining + 1;
1944 if (runtime > remaining)
1945 runtime = remaining;
1946 remaining -= runtime;
1948 cfs_rq->runtime_remaining += runtime;
1949 cfs_rq->runtime_expires = expires;
1951 /* we check whether we're throttled above */
1952 if (cfs_rq->runtime_remaining > 0)
1953 unthrottle_cfs_rq(cfs_rq);
1956 raw_spin_unlock(&rq->lock);
1967 * Responsible for refilling a task_group's bandwidth and unthrottling its
1968 * cfs_rqs as appropriate. If there has been no activity within the last
1969 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
1970 * used to track this state.
1972 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
1974 u64 runtime, runtime_expires;
1975 int idle = 1, throttled;
1977 raw_spin_lock(&cfs_b->lock);
1978 /* no need to continue the timer with no bandwidth constraint */
1979 if (cfs_b->quota == RUNTIME_INF)
1982 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
1983 /* idle depends on !throttled (for the case of a large deficit) */
1984 idle = cfs_b->idle && !throttled;
1985 cfs_b->nr_periods += overrun;
1987 /* if we're going inactive then everything else can be deferred */
1991 __refill_cfs_bandwidth_runtime(cfs_b);
1994 /* mark as potentially idle for the upcoming period */
1999 /* account preceding periods in which throttling occurred */
2000 cfs_b->nr_throttled += overrun;
2003 * There are throttled entities so we must first use the new bandwidth
2004 * to unthrottle them before making it generally available. This
2005 * ensures that all existing debts will be paid before a new cfs_rq is
2008 runtime = cfs_b->runtime;
2009 runtime_expires = cfs_b->runtime_expires;
2013 * This check is repeated as we are holding onto the new bandwidth
2014 * while we unthrottle. This can potentially race with an unthrottled
2015 * group trying to acquire new bandwidth from the global pool.
2017 while (throttled && runtime > 0) {
2018 raw_spin_unlock(&cfs_b->lock);
2019 /* we can't nest cfs_b->lock while distributing bandwidth */
2020 runtime = distribute_cfs_runtime(cfs_b, runtime,
2022 raw_spin_lock(&cfs_b->lock);
2024 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2027 /* return (any) remaining runtime */
2028 cfs_b->runtime = runtime;
2030 * While we are ensured activity in the period following an
2031 * unthrottle, this also covers the case in which the new bandwidth is
2032 * insufficient to cover the existing bandwidth deficit. (Forcing the
2033 * timer to remain active while there are any throttled entities.)
2038 cfs_b->timer_active = 0;
2039 raw_spin_unlock(&cfs_b->lock);
2044 /* a cfs_rq won't donate quota below this amount */
2045 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
2046 /* minimum remaining period time to redistribute slack quota */
2047 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
2048 /* how long we wait to gather additional slack before distributing */
2049 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
2051 /* are we near the end of the current quota period? */
2052 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
2054 struct hrtimer *refresh_timer = &cfs_b->period_timer;
2057 /* if the call-back is running a quota refresh is already occurring */
2058 if (hrtimer_callback_running(refresh_timer))
2061 /* is a quota refresh about to occur? */
2062 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
2063 if (remaining < min_expire)
2069 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
2071 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
2073 /* if there's a quota refresh soon don't bother with slack */
2074 if (runtime_refresh_within(cfs_b, min_left))
2077 start_bandwidth_timer(&cfs_b->slack_timer,
2078 ns_to_ktime(cfs_bandwidth_slack_period));
2081 /* we know any runtime found here is valid as update_curr() precedes return */
2082 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2084 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2085 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
2087 if (slack_runtime <= 0)
2090 raw_spin_lock(&cfs_b->lock);
2091 if (cfs_b->quota != RUNTIME_INF &&
2092 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
2093 cfs_b->runtime += slack_runtime;
2095 /* we are under rq->lock, defer unthrottling using a timer */
2096 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
2097 !list_empty(&cfs_b->throttled_cfs_rq))
2098 start_cfs_slack_bandwidth(cfs_b);
2100 raw_spin_unlock(&cfs_b->lock);
2102 /* even if it's not valid for return we don't want to try again */
2103 cfs_rq->runtime_remaining -= slack_runtime;
2106 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2108 if (!cfs_bandwidth_used())
2111 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
2114 __return_cfs_rq_runtime(cfs_rq);
2118 * This is done with a timer (instead of inline with bandwidth return) since
2119 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
2121 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
2123 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
2126 /* confirm we're still not at a refresh boundary */
2127 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
2130 raw_spin_lock(&cfs_b->lock);
2131 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
2132 runtime = cfs_b->runtime;
2135 expires = cfs_b->runtime_expires;
2136 raw_spin_unlock(&cfs_b->lock);
2141 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
2143 raw_spin_lock(&cfs_b->lock);
2144 if (expires == cfs_b->runtime_expires)
2145 cfs_b->runtime = runtime;
2146 raw_spin_unlock(&cfs_b->lock);
2150 * When a group wakes up we want to make sure that its quota is not already
2151 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
2152 * runtime as update_curr() throttling can not not trigger until it's on-rq.
2154 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
2156 if (!cfs_bandwidth_used())
2159 /* an active group must be handled by the update_curr()->put() path */
2160 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
2163 /* ensure the group is not already throttled */
2164 if (cfs_rq_throttled(cfs_rq))
2167 /* update runtime allocation */
2168 account_cfs_rq_runtime(cfs_rq, 0);
2169 if (cfs_rq->runtime_remaining <= 0)
2170 throttle_cfs_rq(cfs_rq);
2173 /* conditionally throttle active cfs_rq's from put_prev_entity() */
2174 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2176 if (!cfs_bandwidth_used())
2179 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
2183 * it's possible for a throttled entity to be forced into a running
2184 * state (e.g. set_curr_task), in this case we're finished.
2186 if (cfs_rq_throttled(cfs_rq))
2189 throttle_cfs_rq(cfs_rq);
2192 static inline u64 default_cfs_period(void);
2193 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
2194 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
2196 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
2198 struct cfs_bandwidth *cfs_b =
2199 container_of(timer, struct cfs_bandwidth, slack_timer);
2200 do_sched_cfs_slack_timer(cfs_b);
2202 return HRTIMER_NORESTART;
2205 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
2207 struct cfs_bandwidth *cfs_b =
2208 container_of(timer, struct cfs_bandwidth, period_timer);
2214 now = hrtimer_cb_get_time(timer);
2215 overrun = hrtimer_forward(timer, now, cfs_b->period);
2220 idle = do_sched_cfs_period_timer(cfs_b, overrun);
2223 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
2226 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2228 raw_spin_lock_init(&cfs_b->lock);
2230 cfs_b->quota = RUNTIME_INF;
2231 cfs_b->period = ns_to_ktime(default_cfs_period());
2233 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
2234 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2235 cfs_b->period_timer.function = sched_cfs_period_timer;
2236 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2237 cfs_b->slack_timer.function = sched_cfs_slack_timer;
2240 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2242 cfs_rq->runtime_enabled = 0;
2243 INIT_LIST_HEAD(&cfs_rq->throttled_list);
2246 /* requires cfs_b->lock, may release to reprogram timer */
2247 void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2250 * The timer may be active because we're trying to set a new bandwidth
2251 * period or because we're racing with the tear-down path
2252 * (timer_active==0 becomes visible before the hrtimer call-back
2253 * terminates). In either case we ensure that it's re-programmed
2255 while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
2256 raw_spin_unlock(&cfs_b->lock);
2257 /* ensure cfs_b->lock is available while we wait */
2258 hrtimer_cancel(&cfs_b->period_timer);
2260 raw_spin_lock(&cfs_b->lock);
2261 /* if someone else restarted the timer then we're done */
2262 if (cfs_b->timer_active)
2266 cfs_b->timer_active = 1;
2267 start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
2270 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2272 hrtimer_cancel(&cfs_b->period_timer);
2273 hrtimer_cancel(&cfs_b->slack_timer);
2276 static void unthrottle_offline_cfs_rqs(struct rq *rq)
2278 struct cfs_rq *cfs_rq;
2280 for_each_leaf_cfs_rq(rq, cfs_rq) {
2281 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2283 if (!cfs_rq->runtime_enabled)
2287 * clock_task is not advancing so we just need to make sure
2288 * there's some valid quota amount
2290 cfs_rq->runtime_remaining = cfs_b->quota;
2291 if (cfs_rq_throttled(cfs_rq))
2292 unthrottle_cfs_rq(cfs_rq);
2296 #else /* CONFIG_CFS_BANDWIDTH */
2297 static __always_inline
2298 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec) {}
2299 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2300 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
2301 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2303 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2308 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2313 static inline int throttled_lb_pair(struct task_group *tg,
2314 int src_cpu, int dest_cpu)
2319 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2321 #ifdef CONFIG_FAIR_GROUP_SCHED
2322 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2325 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2329 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2330 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
2332 #endif /* CONFIG_CFS_BANDWIDTH */
2334 /**************************************************
2335 * CFS operations on tasks:
2338 #ifdef CONFIG_SCHED_HRTICK
2339 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
2341 struct sched_entity *se = &p->se;
2342 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2344 WARN_ON(task_rq(p) != rq);
2346 if (cfs_rq->nr_running > 1) {
2347 u64 slice = sched_slice(cfs_rq, se);
2348 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
2349 s64 delta = slice - ran;
2358 * Don't schedule slices shorter than 10000ns, that just
2359 * doesn't make sense. Rely on vruntime for fairness.
2362 delta = max_t(s64, 10000LL, delta);
2364 hrtick_start(rq, delta);
2369 * called from enqueue/dequeue and updates the hrtick when the
2370 * current task is from our class and nr_running is low enough
2373 static void hrtick_update(struct rq *rq)
2375 struct task_struct *curr = rq->curr;
2377 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
2380 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
2381 hrtick_start_fair(rq, curr);
2383 #else /* !CONFIG_SCHED_HRTICK */
2385 hrtick_start_fair(struct rq *rq, struct task_struct *p)
2389 static inline void hrtick_update(struct rq *rq)
2395 * The enqueue_task method is called before nr_running is
2396 * increased. Here we update the fair scheduling stats and
2397 * then put the task into the rbtree:
2400 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
2402 struct cfs_rq *cfs_rq;
2403 struct sched_entity *se = &p->se;
2405 for_each_sched_entity(se) {
2408 cfs_rq = cfs_rq_of(se);
2409 enqueue_entity(cfs_rq, se, flags);
2412 * end evaluation on encountering a throttled cfs_rq
2414 * note: in the case of encountering a throttled cfs_rq we will
2415 * post the final h_nr_running increment below.
2417 if (cfs_rq_throttled(cfs_rq))
2419 cfs_rq->h_nr_running++;
2421 flags = ENQUEUE_WAKEUP;
2424 for_each_sched_entity(se) {
2425 cfs_rq = cfs_rq_of(se);
2426 cfs_rq->h_nr_running++;
2428 if (cfs_rq_throttled(cfs_rq))
2431 update_cfs_load(cfs_rq, 0);
2432 update_cfs_shares(cfs_rq);
2440 static void set_next_buddy(struct sched_entity *se);
2443 * The dequeue_task method is called before nr_running is
2444 * decreased. We remove the task from the rbtree and
2445 * update the fair scheduling stats:
2447 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
2449 struct cfs_rq *cfs_rq;
2450 struct sched_entity *se = &p->se;
2451 int task_sleep = flags & DEQUEUE_SLEEP;
2453 for_each_sched_entity(se) {
2454 cfs_rq = cfs_rq_of(se);
2455 dequeue_entity(cfs_rq, se, flags);
2458 * end evaluation on encountering a throttled cfs_rq
2460 * note: in the case of encountering a throttled cfs_rq we will
2461 * post the final h_nr_running decrement below.
2463 if (cfs_rq_throttled(cfs_rq))
2465 cfs_rq->h_nr_running--;
2467 /* Don't dequeue parent if it has other entities besides us */
2468 if (cfs_rq->load.weight) {
2470 * Bias pick_next to pick a task from this cfs_rq, as
2471 * p is sleeping when it is within its sched_slice.
2473 if (task_sleep && parent_entity(se))
2474 set_next_buddy(parent_entity(se));
2476 /* avoid re-evaluating load for this entity */
2477 se = parent_entity(se);
2480 flags |= DEQUEUE_SLEEP;
2483 for_each_sched_entity(se) {
2484 cfs_rq = cfs_rq_of(se);
2485 cfs_rq->h_nr_running--;
2487 if (cfs_rq_throttled(cfs_rq))
2490 update_cfs_load(cfs_rq, 0);
2491 update_cfs_shares(cfs_rq);
2500 /* Used instead of source_load when we know the type == 0 */
2501 static unsigned long weighted_cpuload(const int cpu)
2503 return cpu_rq(cpu)->load.weight;
2507 * Return a low guess at the load of a migration-source cpu weighted
2508 * according to the scheduling class and "nice" value.
2510 * We want to under-estimate the load of migration sources, to
2511 * balance conservatively.
2513 static unsigned long source_load(int cpu, int type)
2515 struct rq *rq = cpu_rq(cpu);
2516 unsigned long total = weighted_cpuload(cpu);
2518 if (type == 0 || !sched_feat(LB_BIAS))
2521 return min(rq->cpu_load[type-1], total);
2525 * Return a high guess at the load of a migration-target cpu weighted
2526 * according to the scheduling class and "nice" value.
2528 static unsigned long target_load(int cpu, int type)
2530 struct rq *rq = cpu_rq(cpu);
2531 unsigned long total = weighted_cpuload(cpu);
2533 if (type == 0 || !sched_feat(LB_BIAS))
2536 return max(rq->cpu_load[type-1], total);
2539 static unsigned long power_of(int cpu)
2541 return cpu_rq(cpu)->cpu_power;
2544 static unsigned long cpu_avg_load_per_task(int cpu)
2546 struct rq *rq = cpu_rq(cpu);
2547 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
2550 return rq->load.weight / nr_running;
2556 static void task_waking_fair(struct task_struct *p)
2558 struct sched_entity *se = &p->se;
2559 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2562 #ifndef CONFIG_64BIT
2563 u64 min_vruntime_copy;
2566 min_vruntime_copy = cfs_rq->min_vruntime_copy;
2568 min_vruntime = cfs_rq->min_vruntime;
2569 } while (min_vruntime != min_vruntime_copy);
2571 min_vruntime = cfs_rq->min_vruntime;
2574 se->vruntime -= min_vruntime;
2577 #ifdef CONFIG_FAIR_GROUP_SCHED
2579 * effective_load() calculates the load change as seen from the root_task_group
2581 * Adding load to a group doesn't make a group heavier, but can cause movement
2582 * of group shares between cpus. Assuming the shares were perfectly aligned one
2583 * can calculate the shift in shares.
2585 * Calculate the effective load difference if @wl is added (subtracted) to @tg
2586 * on this @cpu and results in a total addition (subtraction) of @wg to the
2587 * total group weight.
2589 * Given a runqueue weight distribution (rw_i) we can compute a shares
2590 * distribution (s_i) using:
2592 * s_i = rw_i / \Sum rw_j (1)
2594 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
2595 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
2596 * shares distribution (s_i):
2598 * rw_i = { 2, 4, 1, 0 }
2599 * s_i = { 2/7, 4/7, 1/7, 0 }
2601 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
2602 * task used to run on and the CPU the waker is running on), we need to
2603 * compute the effect of waking a task on either CPU and, in case of a sync
2604 * wakeup, compute the effect of the current task going to sleep.
2606 * So for a change of @wl to the local @cpu with an overall group weight change
2607 * of @wl we can compute the new shares distribution (s'_i) using:
2609 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
2611 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
2612 * differences in waking a task to CPU 0. The additional task changes the
2613 * weight and shares distributions like:
2615 * rw'_i = { 3, 4, 1, 0 }
2616 * s'_i = { 3/8, 4/8, 1/8, 0 }
2618 * We can then compute the difference in effective weight by using:
2620 * dw_i = S * (s'_i - s_i) (3)
2622 * Where 'S' is the group weight as seen by its parent.
2624 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
2625 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
2626 * 4/7) times the weight of the group.
2628 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
2630 struct sched_entity *se = tg->se[cpu];
2632 if (!tg->parent) /* the trivial, non-cgroup case */
2635 for_each_sched_entity(se) {
2641 * W = @wg + \Sum rw_j
2643 W = wg + calc_tg_weight(tg, se->my_q);
2648 w = se->my_q->load.weight + wl;
2651 * wl = S * s'_i; see (2)
2654 wl = (w * tg->shares) / W;
2659 * Per the above, wl is the new se->load.weight value; since
2660 * those are clipped to [MIN_SHARES, ...) do so now. See
2661 * calc_cfs_shares().
2663 if (wl < MIN_SHARES)
2667 * wl = dw_i = S * (s'_i - s_i); see (3)
2669 wl -= se->load.weight;
2672 * Recursively apply this logic to all parent groups to compute
2673 * the final effective load change on the root group. Since
2674 * only the @tg group gets extra weight, all parent groups can
2675 * only redistribute existing shares. @wl is the shift in shares
2676 * resulting from this level per the above.
2685 static inline unsigned long effective_load(struct task_group *tg, int cpu,
2686 unsigned long wl, unsigned long wg)
2693 static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
2695 s64 this_load, load;
2696 int idx, this_cpu, prev_cpu;
2697 unsigned long tl_per_task;
2698 struct task_group *tg;
2699 unsigned long weight;
2703 this_cpu = smp_processor_id();
2704 prev_cpu = task_cpu(p);
2705 load = source_load(prev_cpu, idx);
2706 this_load = target_load(this_cpu, idx);
2709 * If sync wakeup then subtract the (maximum possible)
2710 * effect of the currently running task from the load
2711 * of the current CPU:
2714 tg = task_group(current);
2715 weight = current->se.load.weight;
2717 this_load += effective_load(tg, this_cpu, -weight, -weight);
2718 load += effective_load(tg, prev_cpu, 0, -weight);
2722 weight = p->se.load.weight;
2725 * In low-load situations, where prev_cpu is idle and this_cpu is idle
2726 * due to the sync cause above having dropped this_load to 0, we'll
2727 * always have an imbalance, but there's really nothing you can do
2728 * about that, so that's good too.
2730 * Otherwise check if either cpus are near enough in load to allow this
2731 * task to be woken on this_cpu.
2733 if (this_load > 0) {
2734 s64 this_eff_load, prev_eff_load;
2736 this_eff_load = 100;
2737 this_eff_load *= power_of(prev_cpu);
2738 this_eff_load *= this_load +
2739 effective_load(tg, this_cpu, weight, weight);
2741 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
2742 prev_eff_load *= power_of(this_cpu);
2743 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
2745 balanced = this_eff_load <= prev_eff_load;
2750 * If the currently running task will sleep within
2751 * a reasonable amount of time then attract this newly
2754 if (sync && balanced)
2757 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
2758 tl_per_task = cpu_avg_load_per_task(this_cpu);
2761 (this_load <= load &&
2762 this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
2764 * This domain has SD_WAKE_AFFINE and
2765 * p is cache cold in this domain, and
2766 * there is no bad imbalance.
2768 schedstat_inc(sd, ttwu_move_affine);
2769 schedstat_inc(p, se.statistics.nr_wakeups_affine);
2777 * find_idlest_group finds and returns the least busy CPU group within the
2780 static struct sched_group *
2781 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
2782 int this_cpu, int load_idx)
2784 struct sched_group *idlest = NULL, *group = sd->groups;
2785 unsigned long min_load = ULONG_MAX, this_load = 0;
2786 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2789 unsigned long load, avg_load;
2793 /* Skip over this group if it has no CPUs allowed */
2794 if (!cpumask_intersects(sched_group_cpus(group),
2795 tsk_cpus_allowed(p)))
2798 local_group = cpumask_test_cpu(this_cpu,
2799 sched_group_cpus(group));
2801 /* Tally up the load of all CPUs in the group */
2804 for_each_cpu(i, sched_group_cpus(group)) {
2805 /* Bias balancing toward cpus of our domain */
2807 load = source_load(i, load_idx);
2809 load = target_load(i, load_idx);
2814 /* Adjust by relative CPU power of the group */
2815 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
2818 this_load = avg_load;
2819 } else if (avg_load < min_load) {
2820 min_load = avg_load;
2823 } while (group = group->next, group != sd->groups);
2825 if (!idlest || 100*this_load < imbalance*min_load)
2831 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2834 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2836 unsigned long load, min_load = ULONG_MAX;
2840 /* Traverse only the allowed CPUs */
2841 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
2842 load = weighted_cpuload(i);
2844 if (load < min_load || (load == min_load && i == this_cpu)) {
2854 * Try and locate an idle CPU in the sched_domain.
2856 static int select_idle_sibling(struct task_struct *p, int target)
2858 int cpu = smp_processor_id();
2859 int prev_cpu = task_cpu(p);
2860 struct sched_domain *sd;
2861 struct sched_group *sg;
2865 * If the task is going to be woken-up on this cpu and if it is
2866 * already idle, then it is the right target.
2868 if (target == cpu && idle_cpu(cpu))
2872 * If the task is going to be woken-up on the cpu where it previously
2873 * ran and if it is currently idle, then it the right target.
2875 if (target == prev_cpu && idle_cpu(prev_cpu))
2879 * Otherwise, iterate the domains and find an elegible idle cpu.
2881 sd = rcu_dereference(per_cpu(sd_llc, target));
2882 for_each_lower_domain(sd) {
2885 if (!cpumask_intersects(sched_group_cpus(sg),
2886 tsk_cpus_allowed(p)))
2889 for_each_cpu(i, sched_group_cpus(sg)) {
2894 target = cpumask_first_and(sched_group_cpus(sg),
2895 tsk_cpus_allowed(p));
2899 } while (sg != sd->groups);
2905 #ifdef CONFIG_SCHED_NUMA
2906 static inline bool pick_numa_rand(int n)
2908 return !(get_random_int() % n);
2912 * Pick a random elegible CPU in the target node, hopefully faster
2913 * than doing a least-loaded scan.
2915 static int numa_select_node_cpu(struct task_struct *p, int node)
2917 int weight = cpumask_weight(cpumask_of_node(node));
2920 for_each_cpu_and(i, cpumask_of_node(node), tsk_cpus_allowed(p)) {
2921 if (cpu < 0 || pick_numa_rand(weight))
2928 static int numa_select_node_cpu(struct task_struct *p, int node)
2932 #endif /* CONFIG_SCHED_NUMA */
2935 * sched_balance_self: balance the current task (running on cpu) in domains
2936 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2939 * Balance, ie. select the least loaded group.
2941 * Returns the target CPU number, or the same CPU if no balancing is needed.
2943 * preempt must be disabled.
2946 select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
2948 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
2949 int cpu = smp_processor_id();
2950 int prev_cpu = task_cpu(p);
2952 int want_affine = 0;
2953 int sync = wake_flags & WF_SYNC;
2954 int node = tsk_home_node(p);
2956 if (p->nr_cpus_allowed == 1)
2959 if (sd_flag & SD_BALANCE_WAKE) {
2960 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
2966 if (sched_feat_numa(NUMA_TTWU_BIAS) && node != -1) {
2968 * For fork,exec find the idlest cpu in the home-node.
2970 if (sd_flag & (SD_BALANCE_FORK|SD_BALANCE_EXEC)) {
2971 int node_cpu = numa_select_node_cpu(p, node);
2975 new_cpu = cpu = node_cpu;
2976 sd = per_cpu(sd_node, cpu);
2981 * For wake, pretend we were running in the home-node.
2983 if (cpu_to_node(prev_cpu) != node) {
2984 int node_cpu = numa_select_node_cpu(p, node);
2988 if (sched_feat_numa(NUMA_TTWU_TO))
2991 prev_cpu = node_cpu;
2996 for_each_domain(cpu, tmp) {
2997 if (!(tmp->flags & SD_LOAD_BALANCE))
3001 * If both cpu and prev_cpu are part of this domain,
3002 * cpu is a valid SD_WAKE_AFFINE target.
3004 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
3005 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
3010 if (tmp->flags & sd_flag)
3015 if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
3018 new_cpu = select_idle_sibling(p, prev_cpu);
3024 int load_idx = sd->forkexec_idx;
3025 struct sched_group *group;
3028 if (!(sd->flags & sd_flag)) {
3033 if (sd_flag & SD_BALANCE_WAKE)
3034 load_idx = sd->wake_idx;
3036 group = find_idlest_group(sd, p, cpu, load_idx);
3042 new_cpu = find_idlest_cpu(group, p, cpu);
3043 if (new_cpu == -1 || new_cpu == cpu) {
3044 /* Now try balancing at a lower domain level of cpu */
3049 /* Now try balancing at a lower domain level of new_cpu */
3051 weight = sd->span_weight;
3053 for_each_domain(cpu, tmp) {
3054 if (weight <= tmp->span_weight)
3056 if (tmp->flags & sd_flag)
3059 /* while loop will break here if sd == NULL */
3066 #endif /* CONFIG_SMP */
3068 static unsigned long
3069 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
3071 unsigned long gran = sysctl_sched_wakeup_granularity;
3074 * Since its curr running now, convert the gran from real-time
3075 * to virtual-time in his units.
3077 * By using 'se' instead of 'curr' we penalize light tasks, so
3078 * they get preempted easier. That is, if 'se' < 'curr' then
3079 * the resulting gran will be larger, therefore penalizing the
3080 * lighter, if otoh 'se' > 'curr' then the resulting gran will
3081 * be smaller, again penalizing the lighter task.
3083 * This is especially important for buddies when the leftmost
3084 * task is higher priority than the buddy.
3086 return calc_delta_fair(gran, se);
3090 * Should 'se' preempt 'curr'.
3104 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
3106 s64 gran, vdiff = curr->vruntime - se->vruntime;
3111 gran = wakeup_gran(curr, se);
3118 static void set_last_buddy(struct sched_entity *se)
3120 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3123 for_each_sched_entity(se)
3124 cfs_rq_of(se)->last = se;
3127 static void set_next_buddy(struct sched_entity *se)
3129 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
3132 for_each_sched_entity(se)
3133 cfs_rq_of(se)->next = se;
3136 static void set_skip_buddy(struct sched_entity *se)
3138 for_each_sched_entity(se)
3139 cfs_rq_of(se)->skip = se;
3143 * Preempt the current task with a newly woken task if needed:
3145 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
3147 struct task_struct *curr = rq->curr;
3148 struct sched_entity *se = &curr->se, *pse = &p->se;
3149 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
3150 int scale = cfs_rq->nr_running >= sched_nr_latency;
3151 int next_buddy_marked = 0;
3153 if (unlikely(se == pse))
3157 * This is possible from callers such as move_task(), in which we
3158 * unconditionally check_prempt_curr() after an enqueue (which may have
3159 * lead to a throttle). This both saves work and prevents false
3160 * next-buddy nomination below.
3162 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
3165 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
3166 set_next_buddy(pse);
3167 next_buddy_marked = 1;
3171 * We can come here with TIF_NEED_RESCHED already set from new task
3174 * Note: this also catches the edge-case of curr being in a throttled
3175 * group (e.g. via set_curr_task), since update_curr() (in the
3176 * enqueue of curr) will have resulted in resched being set. This
3177 * prevents us from potentially nominating it as a false LAST_BUDDY
3180 if (test_tsk_need_resched(curr))
3183 /* Idle tasks are by definition preempted by non-idle tasks. */
3184 if (unlikely(curr->policy == SCHED_IDLE) &&
3185 likely(p->policy != SCHED_IDLE))
3189 * Batch and idle tasks do not preempt non-idle tasks (their preemption
3190 * is driven by the tick):
3192 if (unlikely(p->policy != SCHED_NORMAL))
3195 find_matching_se(&se, &pse);
3196 update_curr(cfs_rq_of(se));
3198 if (wakeup_preempt_entity(se, pse) == 1) {
3200 * Bias pick_next to pick the sched entity that is
3201 * triggering this preemption.
3203 if (!next_buddy_marked)
3204 set_next_buddy(pse);
3213 * Only set the backward buddy when the current task is still
3214 * on the rq. This can happen when a wakeup gets interleaved
3215 * with schedule on the ->pre_schedule() or idle_balance()
3216 * point, either of which can * drop the rq lock.
3218 * Also, during early boot the idle thread is in the fair class,
3219 * for obvious reasons its a bad idea to schedule back to it.
3221 if (unlikely(!se->on_rq || curr == rq->idle))
3224 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
3228 static struct task_struct *pick_next_task_fair(struct rq *rq)
3230 struct task_struct *p;
3231 struct cfs_rq *cfs_rq = &rq->cfs;
3232 struct sched_entity *se;
3234 if (!cfs_rq->nr_running)
3238 se = pick_next_entity(cfs_rq);
3239 set_next_entity(cfs_rq, se);
3240 cfs_rq = group_cfs_rq(se);
3244 if (hrtick_enabled(rq))
3245 hrtick_start_fair(rq, p);
3251 * Account for a descheduled task:
3253 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
3255 struct sched_entity *se = &prev->se;
3256 struct cfs_rq *cfs_rq;
3258 for_each_sched_entity(se) {
3259 cfs_rq = cfs_rq_of(se);
3260 put_prev_entity(cfs_rq, se);
3265 * sched_yield() is very simple
3267 * The magic of dealing with the ->skip buddy is in pick_next_entity.
3269 static void yield_task_fair(struct rq *rq)
3271 struct task_struct *curr = rq->curr;
3272 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
3273 struct sched_entity *se = &curr->se;
3276 * Are we the only task in the tree?
3278 if (unlikely(rq->nr_running == 1))
3281 clear_buddies(cfs_rq, se);
3283 if (curr->policy != SCHED_BATCH) {
3284 update_rq_clock(rq);
3286 * Update run-time statistics of the 'current'.
3288 update_curr(cfs_rq);
3290 * Tell update_rq_clock() that we've just updated,
3291 * so we don't do microscopic update in schedule()
3292 * and double the fastpath cost.
3294 rq->skip_clock_update = 1;
3300 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
3302 struct sched_entity *se = &p->se;
3304 /* throttled hierarchies are not runnable */
3305 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
3308 /* Tell the scheduler that we'd really like pse to run next. */
3311 yield_task_fair(rq);
3317 /**************************************************
3318 * Fair scheduling class load-balancing methods:
3321 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
3323 #define LBF_ALL_PINNED 0x01
3324 #define LBF_NEED_BREAK 0x02
3325 #define LBF_SOME_PINNED 0x04
3328 struct sched_domain *sd;
3336 struct cpumask *dst_grpmask;
3338 enum cpu_idle_type idle;
3340 /* The set of CPUs under consideration for load-balancing */
3341 struct cpumask *cpus;
3345 struct list_head *tasks;
3348 unsigned int loop_break;
3349 unsigned int loop_max;
3351 struct rq * (*find_busiest_queue)(struct lb_env *,
3352 struct sched_group *);
3356 * move_task - move a task from one runqueue to another runqueue.
3357 * Both runqueues must be locked.
3359 static void move_task(struct task_struct *p, struct lb_env *env)
3361 deactivate_task(env->src_rq, p, 0);
3362 set_task_cpu(p, env->dst_cpu);
3363 activate_task(env->dst_rq, p, 0);
3364 check_preempt_curr(env->dst_rq, p, 0);
3367 static int task_numa_hot(struct task_struct *p, struct lb_env *env)
3369 int from_dist, to_dist;
3370 int node = tsk_home_node(p);
3372 if (!sched_feat_numa(NUMA_HOT) || node == -1)
3373 return 0; /* no node preference */
3375 from_dist = node_distance(cpu_to_node(env->src_cpu), node);
3376 to_dist = node_distance(cpu_to_node(env->dst_cpu), node);
3378 if (to_dist < from_dist)
3379 return 0; /* getting closer is ok */
3381 return 1; /* stick to where we are */
3385 * Is this task likely cache-hot:
3388 task_hot(struct task_struct *p, struct lb_env *env)
3392 if (p->sched_class != &fair_sched_class)
3395 if (unlikely(p->policy == SCHED_IDLE))
3399 * Buddy candidates are cache hot:
3401 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
3402 (&p->se == cfs_rq_of(&p->se)->next ||
3403 &p->se == cfs_rq_of(&p->se)->last))
3406 if (sysctl_sched_migration_cost == -1)
3408 if (sysctl_sched_migration_cost == 0)
3411 delta = env->src_rq->clock_task - p->se.exec_start;
3413 return delta < (s64)sysctl_sched_migration_cost;
3417 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3420 int can_migrate_task(struct task_struct *p, struct lb_env *env)
3422 int tsk_cache_hot = 0;
3424 * We do not migrate tasks that are:
3425 * 1) running (obviously), or
3426 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3427 * 3) are cache-hot on their current CPU.
3429 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
3432 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
3435 * Remember if this task can be migrated to any other cpu in
3436 * our sched_group. We may want to revisit it if we couldn't
3437 * meet load balance goals by pulling other tasks on src_cpu.
3439 * Also avoid computing new_dst_cpu if we have already computed
3440 * one in current iteration.
3442 if (!env->dst_grpmask || (env->flags & LBF_SOME_PINNED))
3445 new_dst_cpu = cpumask_first_and(env->dst_grpmask,
3446 tsk_cpus_allowed(p));
3447 if (new_dst_cpu < nr_cpu_ids) {
3448 env->flags |= LBF_SOME_PINNED;
3449 env->new_dst_cpu = new_dst_cpu;
3454 /* Record that we found atleast one task that could run on dst_cpu */
3455 env->flags &= ~LBF_ALL_PINNED;
3457 if (task_running(env->src_rq, p)) {
3458 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
3463 * Aggressive migration if:
3464 * 1) task is cache cold, or
3465 * 2) too many balance attempts have failed.
3468 tsk_cache_hot = task_hot(p, env);
3469 if (env->idle == CPU_NOT_IDLE)
3470 tsk_cache_hot |= task_numa_hot(p, env);
3471 if (!tsk_cache_hot ||
3472 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
3473 #ifdef CONFIG_SCHEDSTATS
3474 if (tsk_cache_hot) {
3475 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
3476 schedstat_inc(p, se.statistics.nr_forced_migrations);
3482 if (tsk_cache_hot) {
3483 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
3490 * move_one_task tries to move exactly one task from busiest to this_rq, as
3491 * part of active balancing operations within "domain".
3492 * Returns 1 if successful and 0 otherwise.
3494 * Called with both runqueues locked.
3496 static int __move_one_task(struct lb_env *env)
3498 struct task_struct *p, *n;
3500 list_for_each_entry_safe(p, n, env->tasks, se.group_node) {
3501 if (throttled_lb_pair(task_group(p), env->src_rq->cpu, env->dst_cpu))
3504 if (!can_migrate_task(p, env))
3509 * Right now, this is only the second place move_task()
3510 * is called, so we can safely collect move_task()
3511 * stats here rather than inside move_task().
3513 schedstat_inc(env->sd, lb_gained[env->idle]);
3519 static int move_one_task(struct lb_env *env)
3521 if (sched_feat_numa(NUMA_PULL)) {
3522 env->tasks = offnode_tasks(env->src_rq);
3523 if (__move_one_task(env))
3527 env->tasks = &env->src_rq->cfs_tasks;
3528 if (__move_one_task(env))
3534 static const unsigned int sched_nr_migrate_break = 32;
3537 * move_tasks tries to move up to imbalance weighted load from busiest to
3538 * this_rq, as part of a balancing operation within domain "sd".
3539 * Returns 1 if successful and 0 otherwise.
3541 * Called with both runqueues locked.
3543 static int move_tasks(struct lb_env *env)
3545 struct task_struct *p;
3549 if (env->imbalance <= 0)
3553 while (!list_empty(env->tasks)) {
3554 p = list_first_entry(env->tasks, struct task_struct, se.group_node);
3557 /* We've more or less seen every task there is, call it quits */
3558 if (env->loop > env->loop_max)
3561 /* take a breather every nr_migrate tasks */
3562 if (env->loop > env->loop_break) {
3563 env->loop_break += sched_nr_migrate_break;
3564 env->flags |= LBF_NEED_BREAK;
3568 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
3571 load = task_h_load(p);
3573 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
3576 if ((load / 2) > env->imbalance)
3579 if (!can_migrate_task(p, env))
3584 env->imbalance -= load;
3586 #ifdef CONFIG_PREEMPT
3588 * NEWIDLE balancing is a source of latency, so preemptible
3589 * kernels will stop after the first task is pulled to minimize
3590 * the critical section.
3592 if (env->idle == CPU_NEWLY_IDLE)
3597 * We only want to steal up to the prescribed amount of
3600 if (env->imbalance <= 0)
3605 list_move_tail(&p->se.group_node, env->tasks);
3608 if (env->tasks == offnode_tasks(env->src_rq)) {
3609 env->tasks = &env->src_rq->cfs_tasks;
3616 * Right now, this is one of only two places move_task() is called,
3617 * so we can safely collect move_task() stats here rather than
3618 * inside move_task().
3620 schedstat_add(env->sd, lb_gained[env->idle], pulled);
3625 #ifdef CONFIG_FAIR_GROUP_SCHED
3627 * update tg->load_weight by folding this cpu's load_avg
3629 static int update_shares_cpu(struct task_group *tg, int cpu)
3631 struct cfs_rq *cfs_rq;
3632 unsigned long flags;
3639 cfs_rq = tg->cfs_rq[cpu];
3641 raw_spin_lock_irqsave(&rq->lock, flags);
3643 update_rq_clock(rq);
3644 update_cfs_load(cfs_rq, 1);
3647 * We need to update shares after updating tg->load_weight in
3648 * order to adjust the weight of groups with long running tasks.
3650 update_cfs_shares(cfs_rq);
3652 raw_spin_unlock_irqrestore(&rq->lock, flags);
3657 static void update_shares(int cpu)
3659 struct cfs_rq *cfs_rq;
3660 struct rq *rq = cpu_rq(cpu);
3664 * Iterates the task_group tree in a bottom up fashion, see
3665 * list_add_leaf_cfs_rq() for details.
3667 for_each_leaf_cfs_rq(rq, cfs_rq) {
3668 /* throttled entities do not contribute to load */
3669 if (throttled_hierarchy(cfs_rq))
3672 update_shares_cpu(cfs_rq->tg, cpu);
3678 * Compute the cpu's hierarchical load factor for each task group.
3679 * This needs to be done in a top-down fashion because the load of a child
3680 * group is a fraction of its parents load.
3682 static int tg_load_down(struct task_group *tg, void *data)
3685 long cpu = (long)data;
3688 load = cpu_rq(cpu)->load.weight;
3690 load = tg->parent->cfs_rq[cpu]->h_load;
3691 load *= tg->se[cpu]->load.weight;
3692 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
3695 tg->cfs_rq[cpu]->h_load = load;
3700 static void update_h_load(long cpu)
3702 struct rq *rq = cpu_rq(cpu);
3703 unsigned long now = jiffies;
3705 if (rq->h_load_throttle == now)
3708 rq->h_load_throttle = now;
3711 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
3715 static unsigned long task_h_load(struct task_struct *p)
3717 struct cfs_rq *cfs_rq = task_cfs_rq(p);
3720 load = p->se.load.weight;
3721 load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
3726 static inline void update_shares(int cpu)
3730 static inline void update_h_load(long cpu)
3734 static unsigned long task_h_load(struct task_struct *p)
3736 return p->se.load.weight;
3740 /********** Helpers for find_busiest_group ************************/
3742 * sd_lb_stats - Structure to store the statistics of a sched_domain
3743 * during load balancing.
3745 struct sd_lb_stats {
3746 struct sched_group *busiest; /* Busiest group in this sd */
3747 struct sched_group *this; /* Local group in this sd */
3748 unsigned long total_load; /* Total load of all groups in sd */
3749 unsigned long total_pwr; /* Total power of all groups in sd */
3750 unsigned long avg_load; /* Average load across all groups in sd */
3752 /** Statistics of this group */
3753 unsigned long this_load;
3754 unsigned long this_load_per_task;
3755 unsigned long this_nr_running;
3756 unsigned long this_has_capacity;
3757 unsigned int this_idle_cpus;
3759 /* Statistics of the busiest group */
3760 unsigned int busiest_idle_cpus;
3761 unsigned long max_load;
3762 unsigned long busiest_load_per_task;
3763 unsigned long busiest_nr_running;
3764 unsigned long busiest_group_capacity;
3765 unsigned long busiest_has_capacity;
3766 unsigned int busiest_group_weight;
3768 int group_imb; /* Is there imbalance in this sd */
3769 #ifdef CONFIG_SCHED_NUMA
3770 struct sched_group *numa_group; /* group which has offnode_tasks */
3771 unsigned long numa_group_weight;
3772 unsigned long numa_group_running;
3774 unsigned long this_offnode_running;
3775 unsigned long this_onnode_running;
3780 * sg_lb_stats - stats of a sched_group required for load_balancing
3782 struct sg_lb_stats {
3783 unsigned long avg_load; /*Avg load across the CPUs of the group */
3784 unsigned long group_load; /* Total load over the CPUs of the group */
3785 unsigned long sum_nr_running; /* Nr tasks running in the group */
3786 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3787 unsigned long group_capacity;
3788 unsigned long idle_cpus;
3789 unsigned long group_weight;
3790 int group_imb; /* Is there an imbalance in the group ? */
3791 int group_has_capacity; /* Is there extra capacity in the group? */
3792 #ifdef CONFIG_SCHED_NUMA
3793 unsigned long numa_offnode_weight;
3794 unsigned long numa_offnode_running;
3795 unsigned long numa_onnode_running;
3800 * get_sd_load_idx - Obtain the load index for a given sched domain.
3801 * @sd: The sched_domain whose load_idx is to be obtained.
3802 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3804 static inline int get_sd_load_idx(struct sched_domain *sd,
3805 enum cpu_idle_type idle)
3811 load_idx = sd->busy_idx;
3814 case CPU_NEWLY_IDLE:
3815 load_idx = sd->newidle_idx;
3818 load_idx = sd->idle_idx;
3825 #ifdef CONFIG_SCHED_NUMA
3826 static inline void update_sg_numa_stats(struct sg_lb_stats *sgs, struct rq *rq)
3828 sgs->numa_offnode_weight += rq->offnode_weight;
3829 sgs->numa_offnode_running += rq->offnode_running;
3830 sgs->numa_onnode_running += rq->onnode_running;
3834 * Since the offnode lists are indiscriminate (they contain tasks for all other
3835 * nodes) it is impossible to say if there's any task on there that wants to
3836 * move towards the pulling cpu. Therefore select a random offnode list to pull
3837 * from such that eventually we'll try them all.
3839 * Select a random group that has offnode tasks as sds->numa_group
3841 static inline void update_sd_numa_stats(struct sched_domain *sd,
3842 struct sched_group *group, struct sd_lb_stats *sds,
3843 int local_group, struct sg_lb_stats *sgs)
3845 if (!(sd->flags & SD_NUMA))
3849 sds->this_offnode_running = sgs->numa_offnode_running;
3850 sds->this_onnode_running = sgs->numa_onnode_running;
3854 if (!sgs->numa_offnode_running)
3857 if (!sds->numa_group || pick_numa_rand(sd->span_weight / group->group_weight)) {
3858 sds->numa_group = group;
3859 sds->numa_group_weight = sgs->numa_offnode_weight;
3860 sds->numa_group_running = sgs->numa_offnode_running;
3865 * Pick a random queue from the group that has offnode tasks.
3867 static struct rq *find_busiest_numa_queue(struct lb_env *env,
3868 struct sched_group *group)
3870 struct rq *busiest = NULL, *rq;
3873 for_each_cpu_and(cpu, sched_group_cpus(group), env->cpus) {
3875 if (!rq->offnode_running)
3877 if (!busiest || pick_numa_rand(group->group_weight))
3885 * Called in case of no other imbalance, if there is a queue running offnode
3886 * tasksk we'll say we're imbalanced anyway to nudge these tasks towards their
3889 static inline int check_numa_busiest_group(struct lb_env *env, struct sd_lb_stats *sds)
3891 if (!sched_feat(NUMA_PULL_BIAS))
3894 if (!sds->numa_group)
3898 * Only pull an offnode task home if we've got offnode or !numa tasks to trade for it.
3900 if (!sds->this_offnode_running &&
3901 !(sds->this_nr_running - sds->this_onnode_running - sds->this_offnode_running))
3904 env->imbalance = sds->numa_group_weight / sds->numa_group_running;
3905 sds->busiest = sds->numa_group;
3906 env->find_busiest_queue = find_busiest_numa_queue;
3910 static inline bool need_active_numa_balance(struct lb_env *env)
3912 return env->find_busiest_queue == find_busiest_numa_queue &&
3913 env->src_rq->offnode_running == 1 &&
3914 env->src_rq->nr_running == 1;
3917 #else /* CONFIG_SCHED_NUMA */
3919 static inline void update_sg_numa_stats(struct sg_lb_stats *sgs, struct rq *rq)
3923 static inline void update_sd_numa_stats(struct sched_domain *sd,
3924 struct sched_group *group, struct sd_lb_stats *sds,
3925 int local_group, struct sg_lb_stats *sgs)
3929 static inline int check_numa_busiest_group(struct lb_env *env, struct sd_lb_stats *sds)
3934 static inline bool need_active_numa_balance(struct lb_env *env)
3938 #endif /* CONFIG_SCHED_NUMA */
3940 unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
3942 return SCHED_POWER_SCALE;
3945 unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
3947 return default_scale_freq_power(sd, cpu);
3950 unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
3952 unsigned long weight = sd->span_weight;
3953 unsigned long smt_gain = sd->smt_gain;
3960 unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
3962 return default_scale_smt_power(sd, cpu);
3965 unsigned long scale_rt_power(int cpu)
3967 struct rq *rq = cpu_rq(cpu);
3968 u64 total, available, age_stamp, avg;
3971 * Since we're reading these variables without serialization make sure
3972 * we read them once before doing sanity checks on them.
3974 age_stamp = ACCESS_ONCE(rq->age_stamp);
3975 avg = ACCESS_ONCE(rq->rt_avg);
3977 total = sched_avg_period() + (rq->clock - age_stamp);
3979 if (unlikely(total < avg)) {
3980 /* Ensures that power won't end up being negative */
3983 available = total - avg;
3986 if (unlikely((s64)total < SCHED_POWER_SCALE))
3987 total = SCHED_POWER_SCALE;
3989 total >>= SCHED_POWER_SHIFT;
3991 return div_u64(available, total);
3994 static void update_cpu_power(struct sched_domain *sd, int cpu)
3996 unsigned long weight = sd->span_weight;
3997 unsigned long power = SCHED_POWER_SCALE;
3998 struct sched_group *sdg = sd->groups;
4000 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
4001 if (sched_feat(ARCH_POWER))
4002 power *= arch_scale_smt_power(sd, cpu);
4004 power *= default_scale_smt_power(sd, cpu);
4006 power >>= SCHED_POWER_SHIFT;
4009 sdg->sgp->power_orig = power;
4011 if (sched_feat(ARCH_POWER))
4012 power *= arch_scale_freq_power(sd, cpu);
4014 power *= default_scale_freq_power(sd, cpu);
4016 power >>= SCHED_POWER_SHIFT;
4018 power *= scale_rt_power(cpu);
4019 power >>= SCHED_POWER_SHIFT;
4024 cpu_rq(cpu)->cpu_power = power;
4025 sdg->sgp->power = power;
4028 void update_group_power(struct sched_domain *sd, int cpu)
4030 struct sched_domain *child = sd->child;
4031 struct sched_group *group, *sdg = sd->groups;
4032 unsigned long power;
4033 unsigned long interval;
4035 interval = msecs_to_jiffies(sd->balance_interval);
4036 interval = clamp(interval, 1UL, max_load_balance_interval);
4037 sdg->sgp->next_update = jiffies + interval;
4040 update_cpu_power(sd, cpu);
4046 if (child->flags & SD_OVERLAP) {
4048 * SD_OVERLAP domains cannot assume that child groups
4049 * span the current group.
4052 for_each_cpu(cpu, sched_group_cpus(sdg))
4053 power += power_of(cpu);
4056 * !SD_OVERLAP domains can assume that child groups
4057 * span the current group.
4060 group = child->groups;
4062 power += group->sgp->power;
4063 group = group->next;
4064 } while (group != child->groups);
4067 sdg->sgp->power_orig = sdg->sgp->power = power;
4071 * Try and fix up capacity for tiny siblings, this is needed when
4072 * things like SD_ASYM_PACKING need f_b_g to select another sibling
4073 * which on its own isn't powerful enough.
4075 * See update_sd_pick_busiest() and check_asym_packing().
4078 fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
4081 * Only siblings can have significantly less than SCHED_POWER_SCALE
4083 if (!(sd->flags & SD_SHARE_CPUPOWER))
4087 * If ~90% of the cpu_power is still there, we're good.
4089 if (group->sgp->power * 32 > group->sgp->power_orig * 29)
4096 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
4097 * @env: The load balancing environment.
4098 * @group: sched_group whose statistics are to be updated.
4099 * @load_idx: Load index of sched_domain of this_cpu for load calc.
4100 * @local_group: Does group contain this_cpu.
4101 * @balance: Should we balance.
4102 * @sgs: variable to hold the statistics for this group.
4104 static inline void update_sg_lb_stats(struct lb_env *env,
4105 struct sched_group *group, int load_idx,
4106 int local_group, int *balance, struct sg_lb_stats *sgs)
4108 unsigned long nr_running, max_nr_running, min_nr_running;
4109 unsigned long load, max_cpu_load, min_cpu_load;
4110 unsigned int balance_cpu = -1, first_idle_cpu = 0;
4111 unsigned long avg_load_per_task = 0;
4115 balance_cpu = group_balance_cpu(group);
4117 /* Tally up the load of all CPUs in the group */
4119 min_cpu_load = ~0UL;
4121 min_nr_running = ~0UL;
4123 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
4124 struct rq *rq = cpu_rq(i);
4126 nr_running = rq->nr_running;
4128 /* Bias balancing toward cpus of our domain */
4130 if (idle_cpu(i) && !first_idle_cpu &&
4131 cpumask_test_cpu(i, sched_group_mask(group))) {
4136 load = target_load(i, load_idx);
4138 load = source_load(i, load_idx);
4139 if (load > max_cpu_load)
4140 max_cpu_load = load;
4141 if (min_cpu_load > load)
4142 min_cpu_load = load;
4144 if (nr_running > max_nr_running)
4145 max_nr_running = nr_running;
4146 if (min_nr_running > nr_running)
4147 min_nr_running = nr_running;
4150 sgs->group_load += load;
4151 sgs->sum_nr_running += nr_running;
4152 sgs->sum_weighted_load += weighted_cpuload(i);
4156 update_sg_numa_stats(sgs, rq);
4160 * First idle cpu or the first cpu(busiest) in this sched group
4161 * is eligible for doing load balancing at this and above
4162 * domains. In the newly idle case, we will allow all the cpu's
4163 * to do the newly idle load balance.
4166 if (env->idle != CPU_NEWLY_IDLE) {
4167 if (balance_cpu != env->dst_cpu) {
4171 update_group_power(env->sd, env->dst_cpu);
4172 } else if (time_after_eq(jiffies, group->sgp->next_update))
4173 update_group_power(env->sd, env->dst_cpu);
4176 /* Adjust by relative CPU power of the group */
4177 sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
4180 * Consider the group unbalanced when the imbalance is larger
4181 * than the average weight of a task.
4183 * APZ: with cgroup the avg task weight can vary wildly and
4184 * might not be a suitable number - should we keep a
4185 * normalized nr_running number somewhere that negates
4188 if (sgs->sum_nr_running)
4189 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
4191 if ((max_cpu_load - min_cpu_load) >= avg_load_per_task &&
4192 (max_nr_running - min_nr_running) > 1)
4195 sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
4197 if (!sgs->group_capacity)
4198 sgs->group_capacity = fix_small_capacity(env->sd, group);
4199 sgs->group_weight = group->group_weight;
4201 if (sgs->group_capacity > sgs->sum_nr_running)
4202 sgs->group_has_capacity = 1;
4206 * update_sd_pick_busiest - return 1 on busiest group
4207 * @env: The load balancing environment.
4208 * @sds: sched_domain statistics
4209 * @sg: sched_group candidate to be checked for being the busiest
4210 * @sgs: sched_group statistics
4212 * Determine if @sg is a busier group than the previously selected
4215 static bool update_sd_pick_busiest(struct lb_env *env,
4216 struct sd_lb_stats *sds,
4217 struct sched_group *sg,
4218 struct sg_lb_stats *sgs)
4220 if (sgs->avg_load <= sds->max_load)
4223 if (sgs->sum_nr_running > sgs->group_capacity)
4230 * ASYM_PACKING needs to move all the work to the lowest
4231 * numbered CPUs in the group, therefore mark all groups
4232 * higher than ourself as busy.
4234 if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
4235 env->dst_cpu < group_first_cpu(sg)) {
4239 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
4247 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
4248 * @env: The load balancing environment.
4249 * @balance: Should we balance.
4250 * @sds: variable to hold the statistics for this sched_domain.
4252 static inline void update_sd_lb_stats(struct lb_env *env,
4253 int *balance, struct sd_lb_stats *sds)
4255 struct sched_domain *child = env->sd->child;
4256 struct sched_group *sg = env->sd->groups;
4257 struct sg_lb_stats sgs;
4258 int load_idx, prefer_sibling = 0;
4260 if (child && child->flags & SD_PREFER_SIBLING)
4263 load_idx = get_sd_load_idx(env->sd, env->idle);
4268 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
4269 memset(&sgs, 0, sizeof(sgs));
4270 update_sg_lb_stats(env, sg, load_idx, local_group, balance, &sgs);
4272 if (local_group && !(*balance))
4275 sds->total_load += sgs.group_load;
4276 sds->total_pwr += sg->sgp->power;
4279 * In case the child domain prefers tasks go to siblings
4280 * first, lower the sg capacity to one so that we'll try
4281 * and move all the excess tasks away. We lower the capacity
4282 * of a group only if the local group has the capacity to fit
4283 * these excess tasks, i.e. nr_running < group_capacity. The
4284 * extra check prevents the case where you always pull from the
4285 * heaviest group when it is already under-utilized (possible
4286 * with a large weight task outweighs the tasks on the system).
4288 if (prefer_sibling && !local_group && sds->this_has_capacity)
4289 sgs.group_capacity = min(sgs.group_capacity, 1UL);
4292 sds->this_load = sgs.avg_load;
4294 sds->this_nr_running = sgs.sum_nr_running;
4295 sds->this_load_per_task = sgs.sum_weighted_load;
4296 sds->this_has_capacity = sgs.group_has_capacity;
4297 sds->this_idle_cpus = sgs.idle_cpus;
4298 } else if (update_sd_pick_busiest(env, sds, sg, &sgs)) {
4299 sds->max_load = sgs.avg_load;
4301 sds->busiest_nr_running = sgs.sum_nr_running;
4302 sds->busiest_idle_cpus = sgs.idle_cpus;
4303 sds->busiest_group_capacity = sgs.group_capacity;
4304 sds->busiest_load_per_task = sgs.sum_weighted_load;
4305 sds->busiest_has_capacity = sgs.group_has_capacity;
4306 sds->busiest_group_weight = sgs.group_weight;
4307 sds->group_imb = sgs.group_imb;
4310 update_sd_numa_stats(env->sd, sg, sds, local_group, &sgs);
4313 } while (sg != env->sd->groups);
4317 * check_asym_packing - Check to see if the group is packed into the
4320 * This is primarily intended to used at the sibling level. Some
4321 * cores like POWER7 prefer to use lower numbered SMT threads. In the
4322 * case of POWER7, it can move to lower SMT modes only when higher
4323 * threads are idle. When in lower SMT modes, the threads will
4324 * perform better since they share less core resources. Hence when we
4325 * have idle threads, we want them to be the higher ones.
4327 * This packing function is run on idle threads. It checks to see if
4328 * the busiest CPU in this domain (core in the P7 case) has a higher
4329 * CPU number than the packing function is being run on. Here we are
4330 * assuming lower CPU number will be equivalent to lower a SMT thread
4333 * Returns 1 when packing is required and a task should be moved to
4334 * this CPU. The amount of the imbalance is returned in *imbalance.
4336 * @env: The load balancing environment.
4337 * @sds: Statistics of the sched_domain which is to be packed
4339 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
4343 if (!(env->sd->flags & SD_ASYM_PACKING))
4349 busiest_cpu = group_first_cpu(sds->busiest);
4350 if (env->dst_cpu > busiest_cpu)
4353 env->imbalance = DIV_ROUND_CLOSEST(
4354 sds->max_load * sds->busiest->sgp->power, SCHED_POWER_SCALE);
4360 * fix_small_imbalance - Calculate the minor imbalance that exists
4361 * amongst the groups of a sched_domain, during
4363 * @env: The load balancing environment.
4364 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
4367 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
4369 unsigned long tmp, pwr_now = 0, pwr_move = 0;
4370 unsigned int imbn = 2;
4371 unsigned long scaled_busy_load_per_task;
4373 if (sds->this_nr_running) {
4374 sds->this_load_per_task /= sds->this_nr_running;
4375 if (sds->busiest_load_per_task >
4376 sds->this_load_per_task)
4379 sds->this_load_per_task =
4380 cpu_avg_load_per_task(env->dst_cpu);
4383 scaled_busy_load_per_task = sds->busiest_load_per_task
4384 * SCHED_POWER_SCALE;
4385 scaled_busy_load_per_task /= sds->busiest->sgp->power;
4387 if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
4388 (scaled_busy_load_per_task * imbn)) {
4389 env->imbalance = sds->busiest_load_per_task;
4394 * OK, we don't have enough imbalance to justify moving tasks,
4395 * however we may be able to increase total CPU power used by
4399 pwr_now += sds->busiest->sgp->power *
4400 min(sds->busiest_load_per_task, sds->max_load);
4401 pwr_now += sds->this->sgp->power *
4402 min(sds->this_load_per_task, sds->this_load);
4403 pwr_now /= SCHED_POWER_SCALE;
4405 /* Amount of load we'd subtract */
4406 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
4407 sds->busiest->sgp->power;
4408 if (sds->max_load > tmp)
4409 pwr_move += sds->busiest->sgp->power *
4410 min(sds->busiest_load_per_task, sds->max_load - tmp);
4412 /* Amount of load we'd add */
4413 if (sds->max_load * sds->busiest->sgp->power <
4414 sds->busiest_load_per_task * SCHED_POWER_SCALE)
4415 tmp = (sds->max_load * sds->busiest->sgp->power) /
4416 sds->this->sgp->power;
4418 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
4419 sds->this->sgp->power;
4420 pwr_move += sds->this->sgp->power *
4421 min(sds->this_load_per_task, sds->this_load + tmp);
4422 pwr_move /= SCHED_POWER_SCALE;
4424 /* Move if we gain throughput */
4425 if (pwr_move > pwr_now)
4426 env->imbalance = sds->busiest_load_per_task;
4430 * calculate_imbalance - Calculate the amount of imbalance present within the
4431 * groups of a given sched_domain during load balance.
4432 * @env: load balance environment
4433 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
4435 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
4437 unsigned long max_pull, load_above_capacity = ~0UL;
4439 sds->busiest_load_per_task /= sds->busiest_nr_running;
4440 if (sds->group_imb) {
4441 sds->busiest_load_per_task =
4442 min(sds->busiest_load_per_task, sds->avg_load);
4446 * In the presence of smp nice balancing, certain scenarios can have
4447 * max load less than avg load(as we skip the groups at or below
4448 * its cpu_power, while calculating max_load..)
4450 if (sds->max_load < sds->avg_load) {
4452 return fix_small_imbalance(env, sds);
4455 if (!sds->group_imb) {
4457 * Don't want to pull so many tasks that a group would go idle.
4459 load_above_capacity = (sds->busiest_nr_running -
4460 sds->busiest_group_capacity);
4462 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
4464 load_above_capacity /= sds->busiest->sgp->power;
4468 * We're trying to get all the cpus to the average_load, so we don't
4469 * want to push ourselves above the average load, nor do we wish to
4470 * reduce the max loaded cpu below the average load. At the same time,
4471 * we also don't want to reduce the group load below the group capacity
4472 * (so that we can implement power-savings policies etc). Thus we look
4473 * for the minimum possible imbalance.
4474 * Be careful of negative numbers as they'll appear as very large values
4475 * with unsigned longs.
4477 max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
4479 /* How much load to actually move to equalise the imbalance */
4480 env->imbalance = min(max_pull * sds->busiest->sgp->power,
4481 (sds->avg_load - sds->this_load) * sds->this->sgp->power)
4482 / SCHED_POWER_SCALE;
4485 * if *imbalance is less than the average load per runnable task
4486 * there is no guarantee that any tasks will be moved so we'll have
4487 * a think about bumping its value to force at least one task to be
4490 if (env->imbalance < sds->busiest_load_per_task)
4491 return fix_small_imbalance(env, sds);
4495 /******* find_busiest_group() helpers end here *********************/
4498 * find_busiest_group - Returns the busiest group within the sched_domain
4499 * if there is an imbalance. If there isn't an imbalance, and
4500 * the user has opted for power-savings, it returns a group whose
4501 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
4502 * such a group exists.
4504 * Also calculates the amount of weighted load which should be moved
4505 * to restore balance.
4507 * @env: The load balancing environment.
4508 * @balance: Pointer to a variable indicating if this_cpu
4509 * is the appropriate cpu to perform load balancing at this_level.
4511 * Returns: - the busiest group if imbalance exists.
4512 * - If no imbalance and user has opted for power-savings balance,
4513 * return the least loaded group whose CPUs can be
4514 * put to idle by rebalancing its tasks onto our group.
4516 static struct sched_group *
4517 find_busiest_group(struct lb_env *env, int *balance)
4519 struct sd_lb_stats sds;
4521 memset(&sds, 0, sizeof(sds));
4524 * Compute the various statistics relavent for load balancing at
4527 update_sd_lb_stats(env, balance, &sds);
4530 * this_cpu is not the appropriate cpu to perform load balancing at
4536 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
4537 check_asym_packing(env, &sds))
4540 /* There is no busy sibling group to pull tasks from */
4541 if (!sds.busiest || sds.busiest_nr_running == 0)
4544 sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
4547 * If the busiest group is imbalanced the below checks don't
4548 * work because they assumes all things are equal, which typically
4549 * isn't true due to cpus_allowed constraints and the like.
4554 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
4555 if (env->idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
4556 !sds.busiest_has_capacity)
4560 * If the local group is more busy than the selected busiest group
4561 * don't try and pull any tasks.
4563 if (sds.this_load >= sds.max_load)
4567 * Don't pull any tasks if this group is already above the domain
4570 if (sds.this_load >= sds.avg_load)
4573 if (env->idle == CPU_IDLE) {
4575 * This cpu is idle. If the busiest group load doesn't
4576 * have more tasks than the number of available cpu's and
4577 * there is no imbalance between this and busiest group
4578 * wrt to idle cpu's, it is balanced.
4580 if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
4581 sds.busiest_nr_running <= sds.busiest_group_weight)
4585 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
4586 * imbalance_pct to be conservative.
4588 if (100 * sds.max_load <= env->sd->imbalance_pct * sds.this_load)
4593 /* Looks like there is an imbalance. Compute it */
4594 calculate_imbalance(env, &sds);
4598 if (check_numa_busiest_group(env, &sds))
4607 * find_busiest_queue - find the busiest runqueue among the cpus in group.
4609 static struct rq *find_busiest_queue(struct lb_env *env,
4610 struct sched_group *group)
4612 struct rq *busiest = NULL, *rq;
4613 unsigned long max_load = 0;
4616 for_each_cpu(i, sched_group_cpus(group)) {
4617 unsigned long power = power_of(i);
4618 unsigned long capacity = DIV_ROUND_CLOSEST(power,
4623 capacity = fix_small_capacity(env->sd, group);
4625 if (!cpumask_test_cpu(i, env->cpus))
4629 wl = weighted_cpuload(i);
4632 * When comparing with imbalance, use weighted_cpuload()
4633 * which is not scaled with the cpu power.
4635 if (capacity && rq->nr_running == 1 && wl > env->imbalance)
4639 * For the load comparisons with the other cpu's, consider
4640 * the weighted_cpuload() scaled with the cpu power, so that
4641 * the load can be moved away from the cpu that is potentially
4642 * running at a lower capacity.
4644 wl = (wl * SCHED_POWER_SCALE) / power;
4646 if (wl > max_load) {
4656 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4657 * so long as it is large enough.
4659 #define MAX_PINNED_INTERVAL 512
4661 /* Working cpumask for load_balance and load_balance_newidle. */
4662 DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
4664 static int need_active_balance(struct lb_env *env)
4666 struct sched_domain *sd = env->sd;
4668 if (env->idle == CPU_NEWLY_IDLE) {
4671 * ASYM_PACKING needs to force migrate tasks from busy but
4672 * higher numbered CPUs in order to pack all tasks in the
4673 * lowest numbered CPUs.
4675 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
4679 if (need_active_numa_balance(env))
4682 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
4685 static int active_load_balance_cpu_stop(void *data);
4688 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4689 * tasks if there is an imbalance.
4691 static int load_balance(int this_cpu, struct rq *this_rq,
4692 struct sched_domain *sd, enum cpu_idle_type idle,
4695 int ld_moved, cur_ld_moved, active_balance = 0;
4696 int lb_iterations, max_lb_iterations;
4697 struct sched_group *group;
4699 unsigned long flags;
4700 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4702 struct lb_env env = {
4704 .dst_cpu = this_cpu,
4706 .dst_grpmask = sched_group_cpus(sd->groups),
4708 .loop_break = sched_nr_migrate_break,
4710 .find_busiest_queue = find_busiest_queue,
4713 cpumask_copy(cpus, cpu_active_mask);
4714 max_lb_iterations = cpumask_weight(env.dst_grpmask);
4716 schedstat_inc(sd, lb_count[idle]);
4719 group = find_busiest_group(&env, balance);
4725 schedstat_inc(sd, lb_nobusyg[idle]);
4729 busiest = env.find_busiest_queue(&env, group);
4731 schedstat_inc(sd, lb_nobusyq[idle]);
4734 env.src_rq = busiest;
4735 env.src_cpu = busiest->cpu;
4737 BUG_ON(busiest == env.dst_rq);
4739 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
4743 if (busiest->nr_running > 1) {
4745 * Attempt to move tasks. If find_busiest_group has found
4746 * an imbalance but busiest->nr_running <= 1, the group is
4747 * still unbalanced. ld_moved simply stays zero, so it is
4748 * correctly treated as an imbalance.
4750 env.flags |= LBF_ALL_PINNED;
4751 env.src_cpu = busiest->cpu;
4752 env.src_rq = busiest;
4753 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
4754 if (sched_feat_numa(NUMA_PULL))
4755 env.tasks = offnode_tasks(busiest);
4757 env.tasks = &busiest->cfs_tasks;
4759 update_h_load(env.src_cpu);
4761 local_irq_save(flags);
4762 double_rq_lock(env.dst_rq, busiest);
4765 * cur_ld_moved - load moved in current iteration
4766 * ld_moved - cumulative load moved across iterations
4768 cur_ld_moved = move_tasks(&env);
4769 ld_moved += cur_ld_moved;
4770 double_rq_unlock(env.dst_rq, busiest);
4771 local_irq_restore(flags);
4773 if (env.flags & LBF_NEED_BREAK) {
4774 env.flags &= ~LBF_NEED_BREAK;
4779 * some other cpu did the load balance for us.
4781 if (cur_ld_moved && env.dst_cpu != smp_processor_id())
4782 resched_cpu(env.dst_cpu);
4785 * Revisit (affine) tasks on src_cpu that couldn't be moved to
4786 * us and move them to an alternate dst_cpu in our sched_group
4787 * where they can run. The upper limit on how many times we
4788 * iterate on same src_cpu is dependent on number of cpus in our
4791 * This changes load balance semantics a bit on who can move
4792 * load to a given_cpu. In addition to the given_cpu itself
4793 * (or a ilb_cpu acting on its behalf where given_cpu is
4794 * nohz-idle), we now have balance_cpu in a position to move
4795 * load to given_cpu. In rare situations, this may cause
4796 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
4797 * _independently_ and at _same_ time to move some load to
4798 * given_cpu) causing exceess load to be moved to given_cpu.
4799 * This however should not happen so much in practice and
4800 * moreover subsequent load balance cycles should correct the
4801 * excess load moved.
4803 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0 &&
4804 lb_iterations++ < max_lb_iterations) {
4806 env.dst_rq = cpu_rq(env.new_dst_cpu);
4807 env.dst_cpu = env.new_dst_cpu;
4808 env.flags &= ~LBF_SOME_PINNED;
4810 env.loop_break = sched_nr_migrate_break;
4812 * Go back to "more_balance" rather than "redo" since we
4813 * need to continue with same src_cpu.
4818 /* All tasks on this runqueue were pinned by CPU affinity */
4819 if (unlikely(env.flags & LBF_ALL_PINNED)) {
4820 cpumask_clear_cpu(cpu_of(busiest), cpus);
4821 if (!cpumask_empty(cpus)) {
4823 env.loop_break = sched_nr_migrate_break;
4831 schedstat_inc(sd, lb_failed[idle]);
4833 * Increment the failure counter only on periodic balance.
4834 * We do not want newidle balance, which can be very
4835 * frequent, pollute the failure counter causing
4836 * excessive cache_hot migrations and active balances.
4838 if (idle != CPU_NEWLY_IDLE)
4839 sd->nr_balance_failed++;
4841 if (need_active_balance(&env)) {
4842 raw_spin_lock_irqsave(&busiest->lock, flags);
4844 /* don't kick the active_load_balance_cpu_stop,
4845 * if the curr task on busiest cpu can't be
4848 if (!cpumask_test_cpu(this_cpu,
4849 tsk_cpus_allowed(busiest->curr))) {
4850 raw_spin_unlock_irqrestore(&busiest->lock,
4852 env.flags |= LBF_ALL_PINNED;
4853 goto out_one_pinned;
4857 * ->active_balance synchronizes accesses to
4858 * ->active_balance_work. Once set, it's cleared
4859 * only after active load balance is finished.
4861 if (!busiest->active_balance) {
4862 busiest->active_balance = 1;
4863 busiest->push_cpu = this_cpu;
4866 raw_spin_unlock_irqrestore(&busiest->lock, flags);
4868 if (active_balance) {
4869 stop_one_cpu_nowait(cpu_of(busiest),
4870 active_load_balance_cpu_stop, busiest,
4871 &busiest->active_balance_work);
4875 * We've kicked active balancing, reset the failure
4878 sd->nr_balance_failed = sd->cache_nice_tries+1;
4881 sd->nr_balance_failed = 0;
4883 if (likely(!active_balance)) {
4884 /* We were unbalanced, so reset the balancing interval */
4885 sd->balance_interval = sd->min_interval;
4888 * If we've begun active balancing, start to back off. This
4889 * case may not be covered by the all_pinned logic if there
4890 * is only 1 task on the busy runqueue (because we don't call
4893 if (sd->balance_interval < sd->max_interval)
4894 sd->balance_interval *= 2;
4900 schedstat_inc(sd, lb_balanced[idle]);
4902 sd->nr_balance_failed = 0;
4905 /* tune up the balancing interval */
4906 if (((env.flags & LBF_ALL_PINNED) &&
4907 sd->balance_interval < MAX_PINNED_INTERVAL) ||
4908 (sd->balance_interval < sd->max_interval))
4909 sd->balance_interval *= 2;
4917 * idle_balance is called by schedule() if this_cpu is about to become
4918 * idle. Attempts to pull tasks from other CPUs.
4920 void idle_balance(int this_cpu, struct rq *this_rq)
4922 struct sched_domain *sd;
4923 int pulled_task = 0;
4924 unsigned long next_balance = jiffies + HZ;
4926 this_rq->idle_stamp = this_rq->clock;
4928 if (this_rq->avg_idle < sysctl_sched_migration_cost)
4932 * Drop the rq->lock, but keep IRQ/preempt disabled.
4934 raw_spin_unlock(&this_rq->lock);
4936 update_shares(this_cpu);
4938 for_each_domain(this_cpu, sd) {
4939 unsigned long interval;
4942 if (!(sd->flags & SD_LOAD_BALANCE))
4945 if (sd->flags & SD_BALANCE_NEWIDLE) {
4946 /* If we've pulled tasks over stop searching: */
4947 pulled_task = load_balance(this_cpu, this_rq,
4948 sd, CPU_NEWLY_IDLE, &balance);
4951 interval = msecs_to_jiffies(sd->balance_interval);
4952 if (time_after(next_balance, sd->last_balance + interval))
4953 next_balance = sd->last_balance + interval;
4955 this_rq->idle_stamp = 0;
4961 raw_spin_lock(&this_rq->lock);
4963 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4965 * We are going idle. next_balance may be set based on
4966 * a busy processor. So reset next_balance.
4968 this_rq->next_balance = next_balance;
4973 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
4974 * running tasks off the busiest CPU onto idle CPUs. It requires at
4975 * least 1 task to be running on each physical CPU where possible, and
4976 * avoids physical / logical imbalances.
4978 static int active_load_balance_cpu_stop(void *data)
4980 struct rq *busiest_rq = data;
4981 int busiest_cpu = cpu_of(busiest_rq);
4982 int target_cpu = busiest_rq->push_cpu;
4983 struct rq *target_rq = cpu_rq(target_cpu);
4984 struct sched_domain *sd;
4986 raw_spin_lock_irq(&busiest_rq->lock);
4988 /* make sure the requested cpu hasn't gone down in the meantime */
4989 if (unlikely(busiest_cpu != smp_processor_id() ||
4990 !busiest_rq->active_balance))
4993 /* Is there any task to move? */
4994 if (busiest_rq->nr_running <= 1)
4998 * This condition is "impossible", if it occurs
4999 * we need to fix it. Originally reported by
5000 * Bjorn Helgaas on a 128-cpu setup.
5002 BUG_ON(busiest_rq == target_rq);
5004 /* move a task from busiest_rq to target_rq */
5005 double_lock_balance(busiest_rq, target_rq);
5007 /* Search for an sd spanning us and the target CPU. */
5009 for_each_domain(target_cpu, sd) {
5010 if ((sd->flags & SD_LOAD_BALANCE) &&
5011 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
5016 struct lb_env env = {
5018 .dst_cpu = target_cpu,
5019 .dst_rq = target_rq,
5020 .src_cpu = busiest_rq->cpu,
5021 .src_rq = busiest_rq,
5025 schedstat_inc(sd, alb_count);
5027 if (move_one_task(&env))
5028 schedstat_inc(sd, alb_pushed);
5030 schedstat_inc(sd, alb_failed);
5033 double_unlock_balance(busiest_rq, target_rq);
5035 busiest_rq->active_balance = 0;
5036 raw_spin_unlock_irq(&busiest_rq->lock);
5042 * idle load balancing details
5043 * - When one of the busy CPUs notice that there may be an idle rebalancing
5044 * needed, they will kick the idle load balancer, which then does idle
5045 * load balancing for all the idle CPUs.
5048 cpumask_var_t idle_cpus_mask;
5050 unsigned long next_balance; /* in jiffy units */
5051 } nohz ____cacheline_aligned;
5053 static inline int find_new_ilb(int call_cpu)
5055 int ilb = cpumask_first(nohz.idle_cpus_mask);
5057 if (ilb < nr_cpu_ids && idle_cpu(ilb))
5064 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
5065 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
5066 * CPU (if there is one).
5068 static void nohz_balancer_kick(int cpu)
5072 nohz.next_balance++;
5074 ilb_cpu = find_new_ilb(cpu);
5076 if (ilb_cpu >= nr_cpu_ids)
5079 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
5082 * Use smp_send_reschedule() instead of resched_cpu().
5083 * This way we generate a sched IPI on the target cpu which
5084 * is idle. And the softirq performing nohz idle load balance
5085 * will be run before returning from the IPI.
5087 smp_send_reschedule(ilb_cpu);
5091 static inline void nohz_balance_exit_idle(int cpu)
5093 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
5094 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
5095 atomic_dec(&nohz.nr_cpus);
5096 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
5100 static inline void set_cpu_sd_state_busy(void)
5102 struct sched_domain *sd;
5103 int cpu = smp_processor_id();
5105 if (!test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5107 clear_bit(NOHZ_IDLE, nohz_flags(cpu));
5110 for_each_domain(cpu, sd)
5111 atomic_inc(&sd->groups->sgp->nr_busy_cpus);
5115 void set_cpu_sd_state_idle(void)
5117 struct sched_domain *sd;
5118 int cpu = smp_processor_id();
5120 if (test_bit(NOHZ_IDLE, nohz_flags(cpu)))
5122 set_bit(NOHZ_IDLE, nohz_flags(cpu));
5125 for_each_domain(cpu, sd)
5126 atomic_dec(&sd->groups->sgp->nr_busy_cpus);
5131 * This routine will record that the cpu is going idle with tick stopped.
5132 * This info will be used in performing idle load balancing in the future.
5134 void nohz_balance_enter_idle(int cpu)
5137 * If this cpu is going down, then nothing needs to be done.
5139 if (!cpu_active(cpu))
5142 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
5145 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
5146 atomic_inc(&nohz.nr_cpus);
5147 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
5150 static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
5151 unsigned long action, void *hcpu)
5153 switch (action & ~CPU_TASKS_FROZEN) {
5155 nohz_balance_exit_idle(smp_processor_id());
5163 static DEFINE_SPINLOCK(balancing);
5166 * Scale the max load_balance interval with the number of CPUs in the system.
5167 * This trades load-balance latency on larger machines for less cross talk.
5169 void update_max_interval(void)
5171 max_load_balance_interval = HZ*num_online_cpus()/10;
5175 * It checks each scheduling domain to see if it is due to be balanced,
5176 * and initiates a balancing operation if so.
5178 * Balancing parameters are set up in arch_init_sched_domains.
5180 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
5183 struct rq *rq = cpu_rq(cpu);
5184 unsigned long interval;
5185 struct sched_domain *sd;
5186 /* Earliest time when we have to do rebalance again */
5187 unsigned long next_balance = jiffies + 60*HZ;
5188 int update_next_balance = 0;
5194 for_each_domain(cpu, sd) {
5195 if (!(sd->flags & SD_LOAD_BALANCE))
5198 interval = sd->balance_interval;
5199 if (idle != CPU_IDLE)
5200 interval *= sd->busy_factor;
5202 /* scale ms to jiffies */
5203 interval = msecs_to_jiffies(interval);
5204 interval = clamp(interval, 1UL, max_load_balance_interval);
5206 need_serialize = sd->flags & SD_SERIALIZE;
5208 if (need_serialize) {
5209 if (!spin_trylock(&balancing))
5213 if (time_after_eq(jiffies, sd->last_balance + interval)) {
5214 if (load_balance(cpu, rq, sd, idle, &balance)) {
5216 * We've pulled tasks over so either we're no
5219 idle = CPU_NOT_IDLE;
5221 sd->last_balance = jiffies;
5224 spin_unlock(&balancing);
5226 if (time_after(next_balance, sd->last_balance + interval)) {
5227 next_balance = sd->last_balance + interval;
5228 update_next_balance = 1;
5232 * Stop the load balance at this level. There is another
5233 * CPU in our sched group which is doing load balancing more
5242 * next_balance will be updated only when there is a need.
5243 * When the cpu is attached to null domain for ex, it will not be
5246 if (likely(update_next_balance))
5247 rq->next_balance = next_balance;
5252 * In CONFIG_NO_HZ case, the idle balance kickee will do the
5253 * rebalancing for all the cpus for whom scheduler ticks are stopped.
5255 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
5257 struct rq *this_rq = cpu_rq(this_cpu);
5261 if (idle != CPU_IDLE ||
5262 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
5265 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
5266 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
5270 * If this cpu gets work to do, stop the load balancing
5271 * work being done for other cpus. Next load
5272 * balancing owner will pick it up.
5277 rq = cpu_rq(balance_cpu);
5279 raw_spin_lock_irq(&rq->lock);
5280 update_rq_clock(rq);
5281 update_idle_cpu_load(rq);
5282 raw_spin_unlock_irq(&rq->lock);
5284 rebalance_domains(balance_cpu, CPU_IDLE);
5286 if (time_after(this_rq->next_balance, rq->next_balance))
5287 this_rq->next_balance = rq->next_balance;
5289 nohz.next_balance = this_rq->next_balance;
5291 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
5295 * Current heuristic for kicking the idle load balancer in the presence
5296 * of an idle cpu is the system.
5297 * - This rq has more than one task.
5298 * - At any scheduler domain level, this cpu's scheduler group has multiple
5299 * busy cpu's exceeding the group's power.
5300 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
5301 * domain span are idle.
5303 static inline int nohz_kick_needed(struct rq *rq, int cpu)
5305 unsigned long now = jiffies;
5306 struct sched_domain *sd;
5308 if (unlikely(idle_cpu(cpu)))
5312 * We may be recently in ticked or tickless idle mode. At the first
5313 * busy tick after returning from idle, we will update the busy stats.
5315 set_cpu_sd_state_busy();
5316 nohz_balance_exit_idle(cpu);
5319 * None are in tickless mode and hence no need for NOHZ idle load
5322 if (likely(!atomic_read(&nohz.nr_cpus)))
5325 if (time_before(now, nohz.next_balance))
5328 if (rq->nr_running >= 2)
5332 for_each_domain(cpu, sd) {
5333 struct sched_group *sg = sd->groups;
5334 struct sched_group_power *sgp = sg->sgp;
5335 int nr_busy = atomic_read(&sgp->nr_busy_cpus);
5337 if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
5338 goto need_kick_unlock;
5340 if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
5341 && (cpumask_first_and(nohz.idle_cpus_mask,
5342 sched_domain_span(sd)) < cpu))
5343 goto need_kick_unlock;
5345 if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
5357 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
5361 * run_rebalance_domains is triggered when needed from the scheduler tick.
5362 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
5364 static void run_rebalance_domains(struct softirq_action *h)
5366 int this_cpu = smp_processor_id();
5367 struct rq *this_rq = cpu_rq(this_cpu);
5368 enum cpu_idle_type idle = this_rq->idle_balance ?
5369 CPU_IDLE : CPU_NOT_IDLE;
5371 rebalance_domains(this_cpu, idle);
5374 * If this cpu has a pending nohz_balance_kick, then do the
5375 * balancing on behalf of the other idle cpus whose ticks are
5378 nohz_idle_balance(this_cpu, idle);
5381 static inline int on_null_domain(int cpu)
5383 return !rcu_dereference_sched(cpu_rq(cpu)->sd);
5387 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
5389 void trigger_load_balance(struct rq *rq, int cpu)
5391 /* Don't need to rebalance while attached to NULL domain */
5392 if (time_after_eq(jiffies, rq->next_balance) &&
5393 likely(!on_null_domain(cpu)))
5394 raise_softirq(SCHED_SOFTIRQ);
5396 if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
5397 nohz_balancer_kick(cpu);
5401 static void rq_online_fair(struct rq *rq)
5406 static void rq_offline_fair(struct rq *rq)
5410 /* Ensure any throttled groups are reachable by pick_next_task */
5411 unthrottle_offline_cfs_rqs(rq);
5414 #endif /* CONFIG_SMP */
5417 * scheduler tick hitting a task of our scheduling class:
5419 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
5421 struct cfs_rq *cfs_rq;
5422 struct sched_entity *se = &curr->se;
5424 for_each_sched_entity(se) {
5425 cfs_rq = cfs_rq_of(se);
5426 entity_tick(cfs_rq, se, queued);
5429 if (sched_feat_numa(NUMA))
5430 task_tick_numa(rq, curr);
5434 * called on fork with the child task as argument from the parent's context
5435 * - child not yet on the tasklist
5436 * - preemption disabled
5438 static void task_fork_fair(struct task_struct *p)
5440 struct cfs_rq *cfs_rq;
5441 struct sched_entity *se = &p->se, *curr;
5442 int this_cpu = smp_processor_id();
5443 struct rq *rq = this_rq();
5444 unsigned long flags;
5446 raw_spin_lock_irqsave(&rq->lock, flags);
5448 update_rq_clock(rq);
5450 cfs_rq = task_cfs_rq(current);
5451 curr = cfs_rq->curr;
5453 if (unlikely(task_cpu(p) != this_cpu)) {
5455 __set_task_cpu(p, this_cpu);
5459 update_curr(cfs_rq);
5462 se->vruntime = curr->vruntime;
5463 place_entity(cfs_rq, se, 1);
5465 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
5467 * Upon rescheduling, sched_class::put_prev_task() will place
5468 * 'current' within the tree based on its new key value.
5470 swap(curr->vruntime, se->vruntime);
5471 resched_task(rq->curr);
5474 se->vruntime -= cfs_rq->min_vruntime;
5476 raw_spin_unlock_irqrestore(&rq->lock, flags);
5480 * Priority of the task has changed. Check to see if we preempt
5484 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
5490 * Reschedule if we are currently running on this runqueue and
5491 * our priority decreased, or if we are not currently running on
5492 * this runqueue and our priority is higher than the current's
5494 if (rq->curr == p) {
5495 if (p->prio > oldprio)
5496 resched_task(rq->curr);
5498 check_preempt_curr(rq, p, 0);
5501 static void switched_from_fair(struct rq *rq, struct task_struct *p)
5503 struct sched_entity *se = &p->se;
5504 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5507 * Ensure the task's vruntime is normalized, so that when its
5508 * switched back to the fair class the enqueue_entity(.flags=0) will
5509 * do the right thing.
5511 * If it was on_rq, then the dequeue_entity(.flags=0) will already
5512 * have normalized the vruntime, if it was !on_rq, then only when
5513 * the task is sleeping will it still have non-normalized vruntime.
5515 if (!se->on_rq && p->state != TASK_RUNNING) {
5517 * Fix up our vruntime so that the current sleep doesn't
5518 * cause 'unlimited' sleep bonus.
5520 place_entity(cfs_rq, se, 0);
5521 se->vruntime -= cfs_rq->min_vruntime;
5526 * We switched to the sched_fair class.
5528 static void switched_to_fair(struct rq *rq, struct task_struct *p)
5534 * We were most likely switched from sched_rt, so
5535 * kick off the schedule if running, otherwise just see
5536 * if we can still preempt the current task.
5539 resched_task(rq->curr);
5541 check_preempt_curr(rq, p, 0);
5544 /* Account for a task changing its policy or group.
5546 * This routine is mostly called to set cfs_rq->curr field when a task
5547 * migrates between groups/classes.
5549 static void set_curr_task_fair(struct rq *rq)
5551 struct sched_entity *se = &rq->curr->se;
5553 for_each_sched_entity(se) {
5554 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5556 set_next_entity(cfs_rq, se);
5557 /* ensure bandwidth has been allocated on our new cfs_rq */
5558 account_cfs_rq_runtime(cfs_rq, 0);
5562 void init_cfs_rq(struct cfs_rq *cfs_rq)
5564 cfs_rq->tasks_timeline = RB_ROOT;
5565 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
5566 #ifndef CONFIG_64BIT
5567 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
5571 #ifdef CONFIG_FAIR_GROUP_SCHED
5572 static void task_move_group_fair(struct task_struct *p, int on_rq)
5575 * If the task was not on the rq at the time of this cgroup movement
5576 * it must have been asleep, sleeping tasks keep their ->vruntime
5577 * absolute on their old rq until wakeup (needed for the fair sleeper
5578 * bonus in place_entity()).
5580 * If it was on the rq, we've just 'preempted' it, which does convert
5581 * ->vruntime to a relative base.
5583 * Make sure both cases convert their relative position when migrating
5584 * to another cgroup's rq. This does somewhat interfere with the
5585 * fair sleeper stuff for the first placement, but who cares.
5588 * When !on_rq, vruntime of the task has usually NOT been normalized.
5589 * But there are some cases where it has already been normalized:
5591 * - Moving a forked child which is waiting for being woken up by
5592 * wake_up_new_task().
5593 * - Moving a task which has been woken up by try_to_wake_up() and
5594 * waiting for actually being woken up by sched_ttwu_pending().
5596 * To prevent boost or penalty in the new cfs_rq caused by delta
5597 * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
5599 if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
5603 p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
5604 set_task_rq(p, task_cpu(p));
5606 p->se.vruntime += cfs_rq_of(&p->se)->min_vruntime;
5609 void free_fair_sched_group(struct task_group *tg)
5613 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
5615 for_each_possible_cpu(i) {
5617 kfree(tg->cfs_rq[i]);
5626 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5628 struct cfs_rq *cfs_rq;
5629 struct sched_entity *se;
5632 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
5635 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
5639 tg->shares = NICE_0_LOAD;
5641 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
5643 for_each_possible_cpu(i) {
5644 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
5645 GFP_KERNEL, cpu_to_node(i));
5649 se = kzalloc_node(sizeof(struct sched_entity),
5650 GFP_KERNEL, cpu_to_node(i));
5654 init_cfs_rq(cfs_rq);
5655 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
5666 void unregister_fair_sched_group(struct task_group *tg, int cpu)
5668 struct rq *rq = cpu_rq(cpu);
5669 unsigned long flags;
5672 * Only empty task groups can be destroyed; so we can speculatively
5673 * check on_list without danger of it being re-added.
5675 if (!tg->cfs_rq[cpu]->on_list)
5678 raw_spin_lock_irqsave(&rq->lock, flags);
5679 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
5680 raw_spin_unlock_irqrestore(&rq->lock, flags);
5683 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
5684 struct sched_entity *se, int cpu,
5685 struct sched_entity *parent)
5687 struct rq *rq = cpu_rq(cpu);
5692 /* allow initial update_cfs_load() to truncate */
5693 cfs_rq->load_stamp = 1;
5695 init_cfs_rq_runtime(cfs_rq);
5697 tg->cfs_rq[cpu] = cfs_rq;
5700 /* se could be NULL for root_task_group */
5705 se->cfs_rq = &rq->cfs;
5707 se->cfs_rq = parent->my_q;
5710 update_load_set(&se->load, 0);
5711 se->parent = parent;
5714 static DEFINE_MUTEX(shares_mutex);
5716 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
5719 unsigned long flags;
5722 * We can't change the weight of the root cgroup.
5727 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
5729 mutex_lock(&shares_mutex);
5730 if (tg->shares == shares)
5733 tg->shares = shares;
5734 for_each_possible_cpu(i) {
5735 struct rq *rq = cpu_rq(i);
5736 struct sched_entity *se;
5739 /* Propagate contribution to hierarchy */
5740 raw_spin_lock_irqsave(&rq->lock, flags);
5741 for_each_sched_entity(se)
5742 update_cfs_shares(group_cfs_rq(se));
5743 raw_spin_unlock_irqrestore(&rq->lock, flags);
5747 mutex_unlock(&shares_mutex);
5750 #else /* CONFIG_FAIR_GROUP_SCHED */
5752 void free_fair_sched_group(struct task_group *tg) { }
5754 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
5759 void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
5761 #endif /* CONFIG_FAIR_GROUP_SCHED */
5764 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
5766 struct sched_entity *se = &task->se;
5767 unsigned int rr_interval = 0;
5770 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
5773 if (rq->cfs.load.weight)
5774 rr_interval = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5780 * All the scheduling class methods:
5782 const struct sched_class fair_sched_class = {
5783 .next = &idle_sched_class,
5784 .enqueue_task = enqueue_task_fair,
5785 .dequeue_task = dequeue_task_fair,
5786 .yield_task = yield_task_fair,
5787 .yield_to_task = yield_to_task_fair,
5789 .check_preempt_curr = check_preempt_wakeup,
5791 .pick_next_task = pick_next_task_fair,
5792 .put_prev_task = put_prev_task_fair,
5795 .select_task_rq = select_task_rq_fair,
5797 .rq_online = rq_online_fair,
5798 .rq_offline = rq_offline_fair,
5800 .task_waking = task_waking_fair,
5803 .set_curr_task = set_curr_task_fair,
5804 .task_tick = task_tick_fair,
5805 .task_fork = task_fork_fair,
5807 .prio_changed = prio_changed_fair,
5808 .switched_from = switched_from_fair,
5809 .switched_to = switched_to_fair,
5811 .get_rr_interval = get_rr_interval_fair,
5813 #ifdef CONFIG_FAIR_GROUP_SCHED
5814 .task_move_group = task_move_group_fair,
5818 #ifdef CONFIG_SCHED_DEBUG
5819 void print_cfs_stats(struct seq_file *m, int cpu)
5821 struct cfs_rq *cfs_rq;
5824 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
5825 print_cfs_rq(m, cpu, cfs_rq);
5830 __init void init_sched_fair_class(void)
5833 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
5836 nohz.next_balance = jiffies;
5837 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
5838 cpu_notifier(sched_ilb_notifier, 0);