2 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
4 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6 * Interactivity improvements by Mike Galbraith
7 * (C) 2007 Mike Galbraith <efault@gmx.de>
9 * Various enhancements by Dmitry Adamushko.
10 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12 * Group scheduling enhancements by Srivatsa Vaddagiri
13 * Copyright IBM Corporation, 2007
14 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16 * Scaled math optimizations by Thomas Gleixner
17 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
23 #include <linux/latencytop.h>
24 #include <linux/sched.h>
25 #include <linux/cpumask.h>
26 #include <linux/slab.h>
27 #include <linux/profile.h>
28 #include <linux/interrupt.h>
29 #include <linux/mempolicy.h>
30 #include <linux/migrate.h>
31 #include <linux/task_work.h>
33 #include <trace/events/sched.h>
34 #ifdef CONFIG_HMP_VARIABLE_SCALE
35 #include <linux/sysfs.h>
36 #include <linux/vmalloc.h>
37 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
38 /* Include cpufreq header to add a notifier so that cpu frequency
39 * scaling can track the current CPU frequency
41 #include <linux/cpufreq.h>
42 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
43 #endif /* CONFIG_HMP_VARIABLE_SCALE */
49 * Targeted preemption latency for CPU-bound tasks:
50 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
52 * NOTE: this latency value is not the same as the concept of
53 * 'timeslice length' - timeslices in CFS are of variable length
54 * and have no persistent notion like in traditional, time-slice
55 * based scheduling concepts.
57 * (to see the precise effective timeslice length of your workload,
58 * run vmstat and monitor the context-switches (cs) field)
60 unsigned int sysctl_sched_latency = 6000000ULL;
61 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
64 * The initial- and re-scaling of tunables is configurable
65 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
68 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
69 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
70 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
72 enum sched_tunable_scaling sysctl_sched_tunable_scaling
73 = SCHED_TUNABLESCALING_LOG;
76 * Minimal preemption granularity for CPU-bound tasks:
77 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
79 unsigned int sysctl_sched_min_granularity = 750000ULL;
80 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
83 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
85 static unsigned int sched_nr_latency = 8;
88 * After fork, child runs first. If set to 0 (default) then
89 * parent will (try to) run first.
91 unsigned int sysctl_sched_child_runs_first __read_mostly;
94 * SCHED_OTHER wake-up granularity.
95 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
97 * This option delays the preemption effects of decoupled workloads
98 * and reduces their over-scheduling. Synchronous workloads will still
99 * have immediate wakeup/sleep latencies.
101 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
102 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
104 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
107 * The exponential sliding window over which load is averaged for shares
111 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
113 #ifdef CONFIG_CFS_BANDWIDTH
115 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
116 * each time a cfs_rq requests quota.
118 * Note: in the case that the slice exceeds the runtime remaining (either due
119 * to consumption or the quota being specified to be smaller than the slice)
120 * we will always only issue the remaining available time.
122 * default: 5 msec, units: microseconds
124 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
128 * Increase the granularity value when there are more CPUs,
129 * because with more CPUs the 'effective latency' as visible
130 * to users decreases. But the relationship is not linear,
131 * so pick a second-best guess by going with the log2 of the
134 * This idea comes from the SD scheduler of Con Kolivas:
136 static int get_update_sysctl_factor(void)
138 unsigned int cpus = min_t(int, num_online_cpus(), 8);
141 switch (sysctl_sched_tunable_scaling) {
142 case SCHED_TUNABLESCALING_NONE:
145 case SCHED_TUNABLESCALING_LINEAR:
148 case SCHED_TUNABLESCALING_LOG:
150 factor = 1 + ilog2(cpus);
157 static void update_sysctl(void)
159 unsigned int factor = get_update_sysctl_factor();
161 #define SET_SYSCTL(name) \
162 (sysctl_##name = (factor) * normalized_sysctl_##name)
163 SET_SYSCTL(sched_min_granularity);
164 SET_SYSCTL(sched_latency);
165 SET_SYSCTL(sched_wakeup_granularity);
169 void sched_init_granularity(void)
174 #if BITS_PER_LONG == 32
175 # define WMULT_CONST (~0UL)
177 # define WMULT_CONST (1UL << 32)
180 #define WMULT_SHIFT 32
183 * Shift right and round:
185 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
188 * delta *= weight / lw
191 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
192 struct load_weight *lw)
197 * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
198 * entities since MIN_SHARES = 2. Treat weight as 1 if less than
199 * 2^SCHED_LOAD_RESOLUTION.
201 if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
202 tmp = (u64)delta_exec * scale_load_down(weight);
204 tmp = (u64)delta_exec;
206 if (!lw->inv_weight) {
207 unsigned long w = scale_load_down(lw->weight);
209 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
211 else if (unlikely(!w))
212 lw->inv_weight = WMULT_CONST;
214 lw->inv_weight = WMULT_CONST / w;
218 * Check whether we'd overflow the 64-bit multiplication:
220 if (unlikely(tmp > WMULT_CONST))
221 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
224 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
226 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
230 const struct sched_class fair_sched_class;
232 /**************************************************************
233 * CFS operations on generic schedulable entities:
236 #ifdef CONFIG_FAIR_GROUP_SCHED
238 /* cpu runqueue to which this cfs_rq is attached */
239 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
244 /* An entity is a task if it doesn't "own" a runqueue */
245 #define entity_is_task(se) (!se->my_q)
247 static inline struct task_struct *task_of(struct sched_entity *se)
249 #ifdef CONFIG_SCHED_DEBUG
250 WARN_ON_ONCE(!entity_is_task(se));
252 return container_of(se, struct task_struct, se);
255 /* Walk up scheduling entities hierarchy */
256 #define for_each_sched_entity(se) \
257 for (; se; se = se->parent)
259 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
264 /* runqueue on which this entity is (to be) queued */
265 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
270 /* runqueue "owned" by this group */
271 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
276 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
279 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
281 if (!cfs_rq->on_list) {
283 * Ensure we either appear before our parent (if already
284 * enqueued) or force our parent to appear after us when it is
285 * enqueued. The fact that we always enqueue bottom-up
286 * reduces this to two cases.
288 if (cfs_rq->tg->parent &&
289 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
290 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
291 &rq_of(cfs_rq)->leaf_cfs_rq_list);
293 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
294 &rq_of(cfs_rq)->leaf_cfs_rq_list);
298 /* We should have no load, but we need to update last_decay. */
299 update_cfs_rq_blocked_load(cfs_rq, 0);
303 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
305 if (cfs_rq->on_list) {
306 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
311 /* Iterate thr' all leaf cfs_rq's on a runqueue */
312 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
313 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
315 /* Do the two (enqueued) entities belong to the same group ? */
317 is_same_group(struct sched_entity *se, struct sched_entity *pse)
319 if (se->cfs_rq == pse->cfs_rq)
325 static inline struct sched_entity *parent_entity(struct sched_entity *se)
330 /* return depth at which a sched entity is present in the hierarchy */
331 static inline int depth_se(struct sched_entity *se)
335 for_each_sched_entity(se)
342 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
344 int se_depth, pse_depth;
347 * preemption test can be made between sibling entities who are in the
348 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
349 * both tasks until we find their ancestors who are siblings of common
353 /* First walk up until both entities are at same depth */
354 se_depth = depth_se(*se);
355 pse_depth = depth_se(*pse);
357 while (se_depth > pse_depth) {
359 *se = parent_entity(*se);
362 while (pse_depth > se_depth) {
364 *pse = parent_entity(*pse);
367 while (!is_same_group(*se, *pse)) {
368 *se = parent_entity(*se);
369 *pse = parent_entity(*pse);
373 #else /* !CONFIG_FAIR_GROUP_SCHED */
375 static inline struct task_struct *task_of(struct sched_entity *se)
377 return container_of(se, struct task_struct, se);
380 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
382 return container_of(cfs_rq, struct rq, cfs);
385 #define entity_is_task(se) 1
387 #define for_each_sched_entity(se) \
388 for (; se; se = NULL)
390 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
392 return &task_rq(p)->cfs;
395 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
397 struct task_struct *p = task_of(se);
398 struct rq *rq = task_rq(p);
403 /* runqueue "owned" by this group */
404 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
409 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
413 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
417 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
418 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
421 is_same_group(struct sched_entity *se, struct sched_entity *pse)
426 static inline struct sched_entity *parent_entity(struct sched_entity *se)
432 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
436 #endif /* CONFIG_FAIR_GROUP_SCHED */
438 static __always_inline
439 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
441 /**************************************************************
442 * Scheduling class tree data structure manipulation methods:
445 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
447 s64 delta = (s64)(vruntime - max_vruntime);
449 max_vruntime = vruntime;
454 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
456 s64 delta = (s64)(vruntime - min_vruntime);
458 min_vruntime = vruntime;
463 static inline int entity_before(struct sched_entity *a,
464 struct sched_entity *b)
466 return (s64)(a->vruntime - b->vruntime) < 0;
469 static void update_min_vruntime(struct cfs_rq *cfs_rq)
471 u64 vruntime = cfs_rq->min_vruntime;
474 vruntime = cfs_rq->curr->vruntime;
476 if (cfs_rq->rb_leftmost) {
477 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
482 vruntime = se->vruntime;
484 vruntime = min_vruntime(vruntime, se->vruntime);
487 /* ensure we never gain time by being placed backwards. */
488 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
491 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
496 * Enqueue an entity into the rb-tree:
498 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
500 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
501 struct rb_node *parent = NULL;
502 struct sched_entity *entry;
506 * Find the right place in the rbtree:
510 entry = rb_entry(parent, struct sched_entity, run_node);
512 * We dont care about collisions. Nodes with
513 * the same key stay together.
515 if (entity_before(se, entry)) {
516 link = &parent->rb_left;
518 link = &parent->rb_right;
524 * Maintain a cache of leftmost tree entries (it is frequently
528 cfs_rq->rb_leftmost = &se->run_node;
530 rb_link_node(&se->run_node, parent, link);
531 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
534 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
536 if (cfs_rq->rb_leftmost == &se->run_node) {
537 struct rb_node *next_node;
539 next_node = rb_next(&se->run_node);
540 cfs_rq->rb_leftmost = next_node;
543 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
546 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
548 struct rb_node *left = cfs_rq->rb_leftmost;
553 return rb_entry(left, struct sched_entity, run_node);
556 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
558 struct rb_node *next = rb_next(&se->run_node);
563 return rb_entry(next, struct sched_entity, run_node);
566 #ifdef CONFIG_SCHED_DEBUG
567 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
569 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
574 return rb_entry(last, struct sched_entity, run_node);
577 /**************************************************************
578 * Scheduling class statistics methods:
581 int sched_proc_update_handler(struct ctl_table *table, int write,
582 void __user *buffer, size_t *lenp,
585 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
586 int factor = get_update_sysctl_factor();
591 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
592 sysctl_sched_min_granularity);
594 #define WRT_SYSCTL(name) \
595 (normalized_sysctl_##name = sysctl_##name / (factor))
596 WRT_SYSCTL(sched_min_granularity);
597 WRT_SYSCTL(sched_latency);
598 WRT_SYSCTL(sched_wakeup_granularity);
608 static inline unsigned long
609 calc_delta_fair(unsigned long delta, struct sched_entity *se)
611 if (unlikely(se->load.weight != NICE_0_LOAD))
612 delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
618 * The idea is to set a period in which each task runs once.
620 * When there are too many tasks (sched_nr_latency) we have to stretch
621 * this period because otherwise the slices get too small.
623 * p = (nr <= nl) ? l : l*nr/nl
625 static u64 __sched_period(unsigned long nr_running)
627 u64 period = sysctl_sched_latency;
628 unsigned long nr_latency = sched_nr_latency;
630 if (unlikely(nr_running > nr_latency)) {
631 period = sysctl_sched_min_granularity;
632 period *= nr_running;
639 * We calculate the wall-time slice from the period by taking a part
640 * proportional to the weight.
644 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
646 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
648 for_each_sched_entity(se) {
649 struct load_weight *load;
650 struct load_weight lw;
652 cfs_rq = cfs_rq_of(se);
653 load = &cfs_rq->load;
655 if (unlikely(!se->on_rq)) {
658 update_load_add(&lw, se->load.weight);
661 slice = calc_delta_mine(slice, se->load.weight, load);
667 * We calculate the vruntime slice of a to-be-inserted task.
671 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
673 return calc_delta_fair(sched_slice(cfs_rq, se), se);
677 * Update the current task's runtime statistics. Skip current tasks that
678 * are not in our scheduling class.
681 __update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
682 unsigned long delta_exec)
684 unsigned long delta_exec_weighted;
686 schedstat_set(curr->statistics.exec_max,
687 max((u64)delta_exec, curr->statistics.exec_max));
689 curr->sum_exec_runtime += delta_exec;
690 schedstat_add(cfs_rq, exec_clock, delta_exec);
691 delta_exec_weighted = calc_delta_fair(delta_exec, curr);
693 curr->vruntime += delta_exec_weighted;
694 update_min_vruntime(cfs_rq);
697 static void update_curr(struct cfs_rq *cfs_rq)
699 struct sched_entity *curr = cfs_rq->curr;
700 u64 now = rq_of(cfs_rq)->clock_task;
701 unsigned long delta_exec;
707 * Get the amount of time the current task was running
708 * since the last time we changed load (this cannot
709 * overflow on 32 bits):
711 delta_exec = (unsigned long)(now - curr->exec_start);
715 __update_curr(cfs_rq, curr, delta_exec);
716 curr->exec_start = now;
718 if (entity_is_task(curr)) {
719 struct task_struct *curtask = task_of(curr);
721 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
722 cpuacct_charge(curtask, delta_exec);
723 account_group_exec_runtime(curtask, delta_exec);
726 account_cfs_rq_runtime(cfs_rq, delta_exec);
730 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
732 schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
736 * Task is being enqueued - update stats:
738 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
741 * Are we enqueueing a waiting task? (for current tasks
742 * a dequeue/enqueue event is a NOP)
744 if (se != cfs_rq->curr)
745 update_stats_wait_start(cfs_rq, se);
749 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
751 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
752 rq_of(cfs_rq)->clock - se->statistics.wait_start));
753 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
754 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
755 rq_of(cfs_rq)->clock - se->statistics.wait_start);
756 #ifdef CONFIG_SCHEDSTATS
757 if (entity_is_task(se)) {
758 trace_sched_stat_wait(task_of(se),
759 rq_of(cfs_rq)->clock - se->statistics.wait_start);
762 schedstat_set(se->statistics.wait_start, 0);
766 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
769 * Mark the end of the wait period if dequeueing a
772 if (se != cfs_rq->curr)
773 update_stats_wait_end(cfs_rq, se);
777 * We are picking a new current task - update its stats:
780 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
783 * We are starting a new run period:
785 se->exec_start = rq_of(cfs_rq)->clock_task;
788 /**************************************************
789 * Scheduling class queueing methods:
792 #ifdef CONFIG_NUMA_BALANCING
794 * numa task sample period in ms
796 unsigned int sysctl_numa_balancing_scan_period_min = 100;
797 unsigned int sysctl_numa_balancing_scan_period_max = 100*50;
798 unsigned int sysctl_numa_balancing_scan_period_reset = 100*600;
800 /* Portion of address space to scan in MB */
801 unsigned int sysctl_numa_balancing_scan_size = 256;
803 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
804 unsigned int sysctl_numa_balancing_scan_delay = 1000;
806 static void task_numa_placement(struct task_struct *p)
810 if (!p->mm) /* for example, ksmd faulting in a user's mm */
812 seq = ACCESS_ONCE(p->mm->numa_scan_seq);
813 if (p->numa_scan_seq == seq)
815 p->numa_scan_seq = seq;
817 /* FIXME: Scheduling placement policy hints go here */
821 * Got a PROT_NONE fault for a page on @node.
823 void task_numa_fault(int node, int pages, bool migrated)
825 struct task_struct *p = current;
827 if (!sched_feat_numa(NUMA))
830 /* FIXME: Allocate task-specific structure for placement policy here */
833 * If pages are properly placed (did not migrate) then scan slower.
834 * This is reset periodically in case of phase changes
837 p->numa_scan_period = min(sysctl_numa_balancing_scan_period_max,
838 p->numa_scan_period + jiffies_to_msecs(10));
840 task_numa_placement(p);
843 static void reset_ptenuma_scan(struct task_struct *p)
845 ACCESS_ONCE(p->mm->numa_scan_seq)++;
846 p->mm->numa_scan_offset = 0;
850 * The expensive part of numa migration is done from task_work context.
851 * Triggered from task_tick_numa().
853 void task_numa_work(struct callback_head *work)
855 unsigned long migrate, next_scan, now = jiffies;
856 struct task_struct *p = current;
857 struct mm_struct *mm = p->mm;
858 struct vm_area_struct *vma;
859 unsigned long start, end;
862 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
864 work->next = work; /* protect against double add */
866 * Who cares about NUMA placement when they're dying.
868 * NOTE: make sure not to dereference p->mm before this check,
869 * exit_task_work() happens _after_ exit_mm() so we could be called
870 * without p->mm even though we still had it when we enqueued this
873 if (p->flags & PF_EXITING)
877 * We do not care about task placement until a task runs on a node
878 * other than the first one used by the address space. This is
879 * largely because migrations are driven by what CPU the task
880 * is running on. If it's never scheduled on another node, it'll
881 * not migrate so why bother trapping the fault.
883 if (mm->first_nid == NUMA_PTE_SCAN_INIT)
884 mm->first_nid = numa_node_id();
885 if (mm->first_nid != NUMA_PTE_SCAN_ACTIVE) {
886 /* Are we running on a new node yet? */
887 if (numa_node_id() == mm->first_nid &&
888 !sched_feat_numa(NUMA_FORCE))
891 mm->first_nid = NUMA_PTE_SCAN_ACTIVE;
895 * Reset the scan period if enough time has gone by. Objective is that
896 * scanning will be reduced if pages are properly placed. As tasks
897 * can enter different phases this needs to be re-examined. Lacking
898 * proper tracking of reference behaviour, this blunt hammer is used.
900 migrate = mm->numa_next_reset;
901 if (time_after(now, migrate)) {
902 p->numa_scan_period = sysctl_numa_balancing_scan_period_min;
903 next_scan = now + msecs_to_jiffies(sysctl_numa_balancing_scan_period_reset);
904 xchg(&mm->numa_next_reset, next_scan);
908 * Enforce maximal scan/migration frequency..
910 migrate = mm->numa_next_scan;
911 if (time_before(now, migrate))
914 if (p->numa_scan_period == 0)
915 p->numa_scan_period = sysctl_numa_balancing_scan_period_min;
917 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
918 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
922 * Do not set pte_numa if the current running node is rate-limited.
923 * This loses statistics on the fault but if we are unwilling to
924 * migrate to this node, it is less likely we can do useful work
926 if (migrate_ratelimited(numa_node_id()))
929 start = mm->numa_scan_offset;
930 pages = sysctl_numa_balancing_scan_size;
931 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
935 down_read(&mm->mmap_sem);
936 vma = find_vma(mm, start);
938 reset_ptenuma_scan(p);
942 for (; vma; vma = vma->vm_next) {
943 if (!vma_migratable(vma))
946 /* Skip small VMAs. They are not likely to be of relevance */
947 if (vma->vm_end - vma->vm_start < HPAGE_SIZE)
951 start = max(start, vma->vm_start);
952 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
953 end = min(end, vma->vm_end);
954 pages -= change_prot_numa(vma, start, end);
959 } while (end != vma->vm_end);
964 * It is possible to reach the end of the VMA list but the last few VMAs are
965 * not guaranteed to the vma_migratable. If they are not, we would find the
966 * !migratable VMA on the next scan but not reset the scanner to the start
970 mm->numa_scan_offset = start;
972 reset_ptenuma_scan(p);
973 up_read(&mm->mmap_sem);
977 * Drive the periodic memory faults..
979 void task_tick_numa(struct rq *rq, struct task_struct *curr)
981 struct callback_head *work = &curr->numa_work;
985 * We don't care about NUMA placement if we don't have memory.
987 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
991 * Using runtime rather than walltime has the dual advantage that
992 * we (mostly) drive the selection from busy threads and that the
993 * task needs to have done some actual work before we bother with
996 now = curr->se.sum_exec_runtime;
997 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
999 if (now - curr->node_stamp > period) {
1000 if (!curr->node_stamp)
1001 curr->numa_scan_period = sysctl_numa_balancing_scan_period_min;
1002 curr->node_stamp = now;
1004 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
1005 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
1006 task_work_add(curr, work, true);
1011 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
1014 #endif /* CONFIG_NUMA_BALANCING */
1017 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1019 update_load_add(&cfs_rq->load, se->load.weight);
1020 if (!parent_entity(se))
1021 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
1023 if (entity_is_task(se))
1024 list_add(&se->group_node, &rq_of(cfs_rq)->cfs_tasks);
1026 cfs_rq->nr_running++;
1030 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
1032 update_load_sub(&cfs_rq->load, se->load.weight);
1033 if (!parent_entity(se))
1034 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
1035 if (entity_is_task(se))
1036 list_del_init(&se->group_node);
1037 cfs_rq->nr_running--;
1040 #ifdef CONFIG_FAIR_GROUP_SCHED
1042 static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
1047 * Use this CPU's actual weight instead of the last load_contribution
1048 * to gain a more accurate current total weight. See
1049 * update_cfs_rq_load_contribution().
1051 tg_weight = atomic64_read(&tg->load_avg);
1052 tg_weight -= cfs_rq->tg_load_contrib;
1053 tg_weight += cfs_rq->load.weight;
1058 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1060 long tg_weight, load, shares;
1062 tg_weight = calc_tg_weight(tg, cfs_rq);
1063 load = cfs_rq->load.weight;
1065 shares = (tg->shares * load);
1067 shares /= tg_weight;
1069 if (shares < MIN_SHARES)
1070 shares = MIN_SHARES;
1071 if (shares > tg->shares)
1072 shares = tg->shares;
1076 # else /* CONFIG_SMP */
1077 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
1081 # endif /* CONFIG_SMP */
1082 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
1083 unsigned long weight)
1086 /* commit outstanding execution time */
1087 if (cfs_rq->curr == se)
1088 update_curr(cfs_rq);
1089 account_entity_dequeue(cfs_rq, se);
1092 update_load_set(&se->load, weight);
1095 account_entity_enqueue(cfs_rq, se);
1098 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
1100 static void update_cfs_shares(struct cfs_rq *cfs_rq)
1102 struct task_group *tg;
1103 struct sched_entity *se;
1107 se = tg->se[cpu_of(rq_of(cfs_rq))];
1108 if (!se || throttled_hierarchy(cfs_rq))
1111 if (likely(se->load.weight == tg->shares))
1114 shares = calc_cfs_shares(cfs_rq, tg);
1116 reweight_entity(cfs_rq_of(se), se, shares);
1118 #else /* CONFIG_FAIR_GROUP_SCHED */
1119 static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
1122 #endif /* CONFIG_FAIR_GROUP_SCHED */
1124 /* Only depends on SMP, FAIR_GROUP_SCHED may be removed when useful in lb */
1125 #if defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)
1127 * We choose a half-life close to 1 scheduling period.
1128 * Note: The tables below are dependent on this value.
1130 #define LOAD_AVG_PERIOD 32
1131 #define LOAD_AVG_MAX 47742 /* maximum possible load avg */
1132 #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */
1134 /* Precomputed fixed inverse multiplies for multiplication by y^n */
1135 static const u32 runnable_avg_yN_inv[] = {
1136 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
1137 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
1138 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
1139 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
1140 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
1141 0x85aac367, 0x82cd8698,
1145 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
1146 * over-estimates when re-combining.
1148 static const u32 runnable_avg_yN_sum[] = {
1149 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
1150 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
1151 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
1156 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
1158 static __always_inline u64 decay_load(u64 val, u64 n)
1160 unsigned int local_n;
1164 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
1167 /* after bounds checking we can collapse to 32-bit */
1171 * As y^PERIOD = 1/2, we can combine
1172 * y^n = 1/2^(n/PERIOD) * k^(n%PERIOD)
1173 * With a look-up table which covers k^n (n<PERIOD)
1175 * To achieve constant time decay_load.
1177 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
1178 val >>= local_n / LOAD_AVG_PERIOD;
1179 local_n %= LOAD_AVG_PERIOD;
1182 val *= runnable_avg_yN_inv[local_n];
1183 /* We don't use SRR here since we always want to round down. */
1188 * For updates fully spanning n periods, the contribution to runnable
1189 * average will be: \Sum 1024*y^n
1191 * We can compute this reasonably efficiently by combining:
1192 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
1194 static u32 __compute_runnable_contrib(u64 n)
1198 if (likely(n <= LOAD_AVG_PERIOD))
1199 return runnable_avg_yN_sum[n];
1200 else if (unlikely(n >= LOAD_AVG_MAX_N))
1201 return LOAD_AVG_MAX;
1203 /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
1205 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
1206 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
1208 n -= LOAD_AVG_PERIOD;
1209 } while (n > LOAD_AVG_PERIOD);
1211 contrib = decay_load(contrib, n);
1212 return contrib + runnable_avg_yN_sum[n];
1215 #ifdef CONFIG_HMP_VARIABLE_SCALE
1217 #define HMP_VARIABLE_SCALE_SHIFT 16ULL
1218 struct hmp_global_attr {
1219 struct attribute attr;
1220 ssize_t (*show)(struct kobject *kobj,
1221 struct attribute *attr, char *buf);
1222 ssize_t (*store)(struct kobject *a, struct attribute *b,
1223 const char *c, size_t count);
1225 int (*to_sysfs)(int);
1226 int (*from_sysfs)(int);
1229 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1230 #define HMP_DATA_SYSFS_MAX 4
1232 #define HMP_DATA_SYSFS_MAX 3
1235 struct hmp_data_struct {
1236 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1237 int freqinvar_load_scale_enabled;
1239 int multiplier; /* used to scale the time delta */
1240 struct attribute_group attr_group;
1241 struct attribute *attributes[HMP_DATA_SYSFS_MAX + 1];
1242 struct hmp_global_attr attr[HMP_DATA_SYSFS_MAX];
1245 static u64 hmp_variable_scale_convert(u64 delta);
1246 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1247 /* Frequency-Invariant Load Modification:
1248 * Loads are calculated as in PJT's patch however we also scale the current
1249 * contribution in line with the frequency of the CPU that the task was
1251 * In this version, we use a simple linear scale derived from the maximum
1252 * frequency reported by CPUFreq. As an example:
1254 * Consider that we ran a task for 100% of the previous interval.
1256 * Our CPU was under asynchronous frequency control through one of the
1257 * CPUFreq governors.
1259 * The CPUFreq governor reports that it is able to scale the CPU between
1262 * During the period, the CPU was running at 1GHz.
1264 * In this case, our load contribution for that period is calculated as
1265 * 1 * (number_of_active_microseconds)
1267 * This results in our task being able to accumulate maximum load as normal.
1270 * Consider now that our CPU was executing at 500MHz.
1272 * We now scale the load contribution such that it is calculated as
1273 * 0.5 * (number_of_active_microseconds)
1275 * Our task can only record 50% maximum load during this period.
1277 * This represents the task consuming 50% of the CPU's *possible* compute
1278 * capacity. However the task did consume 100% of the CPU's *available*
1279 * compute capacity which is the value seen by the CPUFreq governor and
1280 * user-side CPU Utilization tools.
1282 * Restricting tracked load to be scaled by the CPU's frequency accurately
1283 * represents the consumption of possible compute capacity and allows the
1284 * HMP migration's simple threshold migration strategy to interact more
1285 * predictably with CPUFreq's asynchronous compute capacity changes.
1287 #define SCHED_FREQSCALE_SHIFT 10
1288 struct cpufreq_extents {
1294 /* Flag set when the governor in use only allows one frequency.
1297 #define SCHED_LOAD_FREQINVAR_SINGLEFREQ 0x01
1299 static struct cpufreq_extents freq_scale[CONFIG_NR_CPUS];
1300 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1301 #endif /* CONFIG_HMP_VARIABLE_SCALE */
1303 /* We can represent the historical contribution to runnable average as the
1304 * coefficients of a geometric series. To do this we sub-divide our runnable
1305 * history into segments of approximately 1ms (1024us); label the segment that
1306 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
1308 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
1310 * (now) (~1ms ago) (~2ms ago)
1312 * Let u_i denote the fraction of p_i that the entity was runnable.
1314 * We then designate the fractions u_i as our co-efficients, yielding the
1315 * following representation of historical load:
1316 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
1318 * We choose y based on the with of a reasonably scheduling period, fixing:
1321 * This means that the contribution to load ~32ms ago (u_32) will be weighted
1322 * approximately half as much as the contribution to load within the last ms
1325 * When a period "rolls over" and we have new u_0`, multiplying the previous
1326 * sum again by y is sufficient to update:
1327 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
1328 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
1330 static __always_inline int __update_entity_runnable_avg(u64 now,
1331 struct sched_avg *sa,
1337 u32 runnable_contrib;
1338 int delta_w, decayed = 0;
1339 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1341 u32 scaled_runnable_contrib;
1343 u32 curr_scale = 1024;
1344 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1346 delta = now - sa->last_runnable_update;
1347 #ifdef CONFIG_HMP_VARIABLE_SCALE
1348 delta = hmp_variable_scale_convert(delta);
1351 * This should only happen when time goes backwards, which it
1352 * unfortunately does during sched clock init when we swap over to TSC.
1354 if ((s64)delta < 0) {
1355 sa->last_runnable_update = now;
1360 * Use 1024ns as the unit of measurement since it's a reasonable
1361 * approximation of 1us and fast to compute.
1366 sa->last_runnable_update = now;
1368 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1369 /* retrieve scale factor for load */
1370 if (hmp_data.freqinvar_load_scale_enabled)
1371 curr_scale = freq_scale[cpu].curr_scale;
1372 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1374 /* delta_w is the amount already accumulated against our next period */
1375 delta_w = sa->runnable_avg_period % 1024;
1376 if (delta + delta_w >= 1024) {
1377 /* period roll-over */
1381 * Now that we know we're crossing a period boundary, figure
1382 * out how much from delta we need to complete the current
1383 * period and accrue it.
1385 delta_w = 1024 - delta_w;
1386 /* scale runnable time if necessary */
1387 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1388 scaled_delta_w = (delta_w * curr_scale)
1389 >> SCHED_FREQSCALE_SHIFT;
1391 sa->runnable_avg_sum += scaled_delta_w;
1393 sa->usage_avg_sum += scaled_delta_w;
1396 sa->runnable_avg_sum += delta_w;
1398 sa->usage_avg_sum += delta_w;
1399 #endif /* #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1400 sa->runnable_avg_period += delta_w;
1404 /* Figure out how many additional periods this update spans */
1405 periods = delta / 1024;
1407 /* decay the load we have accumulated so far */
1408 sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum,
1410 sa->runnable_avg_period = decay_load(sa->runnable_avg_period,
1412 sa->usage_avg_sum = decay_load(sa->usage_avg_sum, periods + 1);
1413 /* add the contribution from this period */
1414 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
1415 runnable_contrib = __compute_runnable_contrib(periods);
1416 /* Apply load scaling if necessary.
1417 * Note that multiplying the whole series is same as
1418 * multiplying all terms
1420 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1421 scaled_runnable_contrib = (runnable_contrib * curr_scale)
1422 >> SCHED_FREQSCALE_SHIFT;
1424 sa->runnable_avg_sum += scaled_runnable_contrib;
1426 sa->usage_avg_sum += scaled_runnable_contrib;
1429 sa->runnable_avg_sum += runnable_contrib;
1431 sa->usage_avg_sum += runnable_contrib;
1432 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1433 sa->runnable_avg_period += runnable_contrib;
1436 /* Remainder of delta accrued against u_0` */
1437 /* scale if necessary */
1438 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1439 scaled_delta = ((delta * curr_scale) >> SCHED_FREQSCALE_SHIFT);
1441 sa->runnable_avg_sum += scaled_delta;
1443 sa->usage_avg_sum += scaled_delta;
1446 sa->runnable_avg_sum += delta;
1448 sa->usage_avg_sum += delta;
1449 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */
1450 sa->runnable_avg_period += delta;
1455 /* Synchronize an entity's decay with its parenting cfs_rq.*/
1456 static inline u64 __synchronize_entity_decay(struct sched_entity *se)
1458 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1459 u64 decays = atomic64_read(&cfs_rq->decay_counter);
1461 decays -= se->avg.decay_count;
1465 se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays);
1466 se->avg.decay_count = 0;
1471 #ifdef CONFIG_FAIR_GROUP_SCHED
1472 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
1475 struct task_group *tg = cfs_rq->tg;
1478 tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg;
1479 tg_contrib -= cfs_rq->tg_load_contrib;
1481 if (force_update || abs64(tg_contrib) > cfs_rq->tg_load_contrib / 8) {
1482 atomic64_add(tg_contrib, &tg->load_avg);
1483 cfs_rq->tg_load_contrib += tg_contrib;
1488 * Aggregate cfs_rq runnable averages into an equivalent task_group
1489 * representation for computing load contributions.
1491 static inline void __update_tg_runnable_avg(struct sched_avg *sa,
1492 struct cfs_rq *cfs_rq)
1494 struct task_group *tg = cfs_rq->tg;
1495 long contrib, usage_contrib;
1497 /* The fraction of a cpu used by this cfs_rq */
1498 contrib = div_u64(sa->runnable_avg_sum << NICE_0_SHIFT,
1499 sa->runnable_avg_period + 1);
1500 contrib -= cfs_rq->tg_runnable_contrib;
1502 usage_contrib = div_u64(sa->usage_avg_sum << NICE_0_SHIFT,
1503 sa->runnable_avg_period + 1);
1504 usage_contrib -= cfs_rq->tg_usage_contrib;
1507 * contrib/usage at this point represent deltas, only update if they
1510 if ((abs(contrib) > cfs_rq->tg_runnable_contrib / 64) ||
1511 (abs(usage_contrib) > cfs_rq->tg_usage_contrib / 64)) {
1512 atomic_add(contrib, &tg->runnable_avg);
1513 cfs_rq->tg_runnable_contrib += contrib;
1515 atomic_add(usage_contrib, &tg->usage_avg);
1516 cfs_rq->tg_usage_contrib += usage_contrib;
1520 static inline void __update_group_entity_contrib(struct sched_entity *se)
1522 struct cfs_rq *cfs_rq = group_cfs_rq(se);
1523 struct task_group *tg = cfs_rq->tg;
1528 contrib = cfs_rq->tg_load_contrib * tg->shares;
1529 se->avg.load_avg_contrib = div64_u64(contrib,
1530 atomic64_read(&tg->load_avg) + 1);
1533 * For group entities we need to compute a correction term in the case
1534 * that they are consuming <1 cpu so that we would contribute the same
1535 * load as a task of equal weight.
1537 * Explicitly co-ordinating this measurement would be expensive, but
1538 * fortunately the sum of each cpus contribution forms a usable
1539 * lower-bound on the true value.
1541 * Consider the aggregate of 2 contributions. Either they are disjoint
1542 * (and the sum represents true value) or they are disjoint and we are
1543 * understating by the aggregate of their overlap.
1545 * Extending this to N cpus, for a given overlap, the maximum amount we
1546 * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of
1547 * cpus that overlap for this interval and w_i is the interval width.
1549 * On a small machine; the first term is well-bounded which bounds the
1550 * total error since w_i is a subset of the period. Whereas on a
1551 * larger machine, while this first term can be larger, if w_i is the
1552 * of consequential size guaranteed to see n_i*w_i quickly converge to
1553 * our upper bound of 1-cpu.
1555 runnable_avg = atomic_read(&tg->runnable_avg);
1556 if (runnable_avg < NICE_0_LOAD) {
1557 se->avg.load_avg_contrib *= runnable_avg;
1558 se->avg.load_avg_contrib >>= NICE_0_SHIFT;
1562 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
1563 int force_update) {}
1564 static inline void __update_tg_runnable_avg(struct sched_avg *sa,
1565 struct cfs_rq *cfs_rq) {}
1566 static inline void __update_group_entity_contrib(struct sched_entity *se) {}
1569 static inline void __update_task_entity_contrib(struct sched_entity *se)
1573 /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */
1574 contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);
1575 contrib /= (se->avg.runnable_avg_period + 1);
1576 se->avg.load_avg_contrib = scale_load(contrib);
1577 trace_sched_task_load_contrib(task_of(se), se->avg.load_avg_contrib);
1578 contrib = se->avg.runnable_avg_sum * scale_load_down(NICE_0_LOAD);
1579 contrib /= (se->avg.runnable_avg_period + 1);
1580 se->avg.load_avg_ratio = scale_load(contrib);
1581 trace_sched_task_runnable_ratio(task_of(se), se->avg.load_avg_ratio);
1584 /* Compute the current contribution to load_avg by se, return any delta */
1585 static long __update_entity_load_avg_contrib(struct sched_entity *se, long *ratio)
1587 long old_contrib = se->avg.load_avg_contrib;
1588 long old_ratio = se->avg.load_avg_ratio;
1590 if (entity_is_task(se)) {
1591 __update_task_entity_contrib(se);
1593 __update_tg_runnable_avg(&se->avg, group_cfs_rq(se));
1594 __update_group_entity_contrib(se);
1598 *ratio = se->avg.load_avg_ratio - old_ratio;
1599 return se->avg.load_avg_contrib - old_contrib;
1602 static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq,
1605 if (likely(load_contrib < cfs_rq->blocked_load_avg))
1606 cfs_rq->blocked_load_avg -= load_contrib;
1608 cfs_rq->blocked_load_avg = 0;
1611 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
1613 /* Update a sched_entity's runnable average */
1614 static inline void update_entity_load_avg(struct sched_entity *se,
1617 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1618 long contrib_delta, ratio_delta;
1620 int cpu = -1; /* not used in normal case */
1622 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1623 cpu = cfs_rq->rq->cpu;
1626 * For a group entity we need to use their owned cfs_rq_clock_task() in
1627 * case they are the parent of a throttled hierarchy.
1629 if (entity_is_task(se))
1630 now = cfs_rq_clock_task(cfs_rq);
1632 now = cfs_rq_clock_task(group_cfs_rq(se));
1634 if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq,
1635 cfs_rq->curr == se, cpu))
1638 contrib_delta = __update_entity_load_avg_contrib(se, &ratio_delta);
1644 cfs_rq->runnable_load_avg += contrib_delta;
1645 rq_of(cfs_rq)->avg.load_avg_ratio += ratio_delta;
1647 subtract_blocked_load_contrib(cfs_rq, -contrib_delta);
1652 * Decay the load contributed by all blocked children and account this so that
1653 * their contribution may appropriately discounted when they wake up.
1655 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update)
1657 u64 now = cfs_rq_clock_task(cfs_rq) >> 20;
1660 decays = now - cfs_rq->last_decay;
1661 if (!decays && !force_update)
1664 if (atomic64_read(&cfs_rq->removed_load)) {
1665 u64 removed_load = atomic64_xchg(&cfs_rq->removed_load, 0);
1666 subtract_blocked_load_contrib(cfs_rq, removed_load);
1670 cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg,
1672 atomic64_add(decays, &cfs_rq->decay_counter);
1673 cfs_rq->last_decay = now;
1676 __update_cfs_rq_tg_load_contrib(cfs_rq, force_update);
1679 static inline void update_rq_runnable_avg(struct rq *rq, int runnable)
1681 int cpu = -1; /* not used in normal case */
1683 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
1686 __update_entity_runnable_avg(rq->clock_task, &rq->avg, runnable,
1688 __update_tg_runnable_avg(&rq->avg, &rq->cfs);
1689 trace_sched_rq_runnable_ratio(cpu_of(rq), rq->avg.load_avg_ratio);
1690 trace_sched_rq_runnable_load(cpu_of(rq), rq->cfs.runnable_load_avg);
1693 /* Add the load generated by se into cfs_rq's child load-average */
1694 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
1695 struct sched_entity *se,
1699 * We track migrations using entity decay_count <= 0, on a wake-up
1700 * migration we use a negative decay count to track the remote decays
1701 * accumulated while sleeping.
1703 if (unlikely(se->avg.decay_count <= 0)) {
1704 se->avg.last_runnable_update = rq_of(cfs_rq)->clock_task;
1705 if (se->avg.decay_count) {
1707 * In a wake-up migration we have to approximate the
1708 * time sleeping. This is because we can't synchronize
1709 * clock_task between the two cpus, and it is not
1710 * guaranteed to be read-safe. Instead, we can
1711 * approximate this using our carried decays, which are
1712 * explicitly atomically readable.
1714 se->avg.last_runnable_update -= (-se->avg.decay_count)
1716 update_entity_load_avg(se, 0);
1717 /* Indicate that we're now synchronized and on-rq */
1718 se->avg.decay_count = 0;
1722 __synchronize_entity_decay(se);
1725 /* migrated tasks did not contribute to our blocked load */
1727 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
1728 update_entity_load_avg(se, 0);
1731 cfs_rq->runnable_load_avg += se->avg.load_avg_contrib;
1732 rq_of(cfs_rq)->avg.load_avg_ratio += se->avg.load_avg_ratio;
1734 /* we force update consideration on load-balancer moves */
1735 update_cfs_rq_blocked_load(cfs_rq, !wakeup);
1739 * Remove se's load from this cfs_rq child load-average, if the entity is
1740 * transitioning to a blocked state we track its projected decay using
1743 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
1744 struct sched_entity *se,
1747 update_entity_load_avg(se, 1);
1748 /* we force update consideration on load-balancer moves */
1749 update_cfs_rq_blocked_load(cfs_rq, !sleep);
1751 cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib;
1752 rq_of(cfs_rq)->avg.load_avg_ratio -= se->avg.load_avg_ratio;
1755 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
1756 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
1757 } /* migrations, e.g. sleep=0 leave decay_count == 0 */
1761 * Update the rq's load with the elapsed running time before entering
1762 * idle. if the last scheduled task is not a CFS task, idle_enter will
1763 * be the only way to update the runnable statistic.
1765 void idle_enter_fair(struct rq *this_rq)
1767 update_rq_runnable_avg(this_rq, 1);
1771 * Update the rq's load with the elapsed idle time before a task is
1772 * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
1773 * be the only way to update the runnable statistic.
1775 void idle_exit_fair(struct rq *this_rq)
1777 update_rq_runnable_avg(this_rq, 0);
1781 static inline void update_entity_load_avg(struct sched_entity *se,
1782 int update_cfs_rq) {}
1783 static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
1784 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
1785 struct sched_entity *se,
1787 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
1788 struct sched_entity *se,
1790 static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
1791 int force_update) {}
1794 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
1796 #ifdef CONFIG_SCHEDSTATS
1797 struct task_struct *tsk = NULL;
1799 if (entity_is_task(se))
1802 if (se->statistics.sleep_start) {
1803 u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
1808 if (unlikely(delta > se->statistics.sleep_max))
1809 se->statistics.sleep_max = delta;
1811 se->statistics.sleep_start = 0;
1812 se->statistics.sum_sleep_runtime += delta;
1815 account_scheduler_latency(tsk, delta >> 10, 1);
1816 trace_sched_stat_sleep(tsk, delta);
1819 if (se->statistics.block_start) {
1820 u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
1825 if (unlikely(delta > se->statistics.block_max))
1826 se->statistics.block_max = delta;
1828 se->statistics.block_start = 0;
1829 se->statistics.sum_sleep_runtime += delta;
1832 if (tsk->in_iowait) {
1833 se->statistics.iowait_sum += delta;
1834 se->statistics.iowait_count++;
1835 trace_sched_stat_iowait(tsk, delta);
1838 trace_sched_stat_blocked(tsk, delta);
1841 * Blocking time is in units of nanosecs, so shift by
1842 * 20 to get a milliseconds-range estimation of the
1843 * amount of time that the task spent sleeping:
1845 if (unlikely(prof_on == SLEEP_PROFILING)) {
1846 profile_hits(SLEEP_PROFILING,
1847 (void *)get_wchan(tsk),
1850 account_scheduler_latency(tsk, delta >> 10, 0);
1856 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
1858 #ifdef CONFIG_SCHED_DEBUG
1859 s64 d = se->vruntime - cfs_rq->min_vruntime;
1864 if (d > 3*sysctl_sched_latency)
1865 schedstat_inc(cfs_rq, nr_spread_over);
1870 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
1872 u64 vruntime = cfs_rq->min_vruntime;
1875 * The 'current' period is already promised to the current tasks,
1876 * however the extra weight of the new task will slow them down a
1877 * little, place the new task so that it fits in the slot that
1878 * stays open at the end.
1880 if (initial && sched_feat(START_DEBIT))
1881 vruntime += sched_vslice(cfs_rq, se);
1883 /* sleeps up to a single latency don't count. */
1885 unsigned long thresh = sysctl_sched_latency;
1888 * Halve their sleep time's effect, to allow
1889 * for a gentler effect of sleepers:
1891 if (sched_feat(GENTLE_FAIR_SLEEPERS))
1897 /* ensure we never gain time by being placed backwards. */
1898 se->vruntime = max_vruntime(se->vruntime, vruntime);
1901 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
1904 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1907 * Update the normalized vruntime before updating min_vruntime
1908 * through callig update_curr().
1910 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
1911 se->vruntime += cfs_rq->min_vruntime;
1914 * Update run-time statistics of the 'current'.
1916 update_curr(cfs_rq);
1917 enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP);
1918 account_entity_enqueue(cfs_rq, se);
1919 update_cfs_shares(cfs_rq);
1921 if (flags & ENQUEUE_WAKEUP) {
1922 place_entity(cfs_rq, se, 0);
1923 enqueue_sleeper(cfs_rq, se);
1926 update_stats_enqueue(cfs_rq, se);
1927 check_spread(cfs_rq, se);
1928 if (se != cfs_rq->curr)
1929 __enqueue_entity(cfs_rq, se);
1932 if (cfs_rq->nr_running == 1) {
1933 list_add_leaf_cfs_rq(cfs_rq);
1934 check_enqueue_throttle(cfs_rq);
1938 static void __clear_buddies_last(struct sched_entity *se)
1940 for_each_sched_entity(se) {
1941 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1942 if (cfs_rq->last == se)
1943 cfs_rq->last = NULL;
1949 static void __clear_buddies_next(struct sched_entity *se)
1951 for_each_sched_entity(se) {
1952 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1953 if (cfs_rq->next == se)
1954 cfs_rq->next = NULL;
1960 static void __clear_buddies_skip(struct sched_entity *se)
1962 for_each_sched_entity(se) {
1963 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1964 if (cfs_rq->skip == se)
1965 cfs_rq->skip = NULL;
1971 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
1973 if (cfs_rq->last == se)
1974 __clear_buddies_last(se);
1976 if (cfs_rq->next == se)
1977 __clear_buddies_next(se);
1979 if (cfs_rq->skip == se)
1980 __clear_buddies_skip(se);
1983 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
1986 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1989 * Update run-time statistics of the 'current'.
1991 update_curr(cfs_rq);
1992 dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP);
1994 update_stats_dequeue(cfs_rq, se);
1995 if (flags & DEQUEUE_SLEEP) {
1996 #ifdef CONFIG_SCHEDSTATS
1997 if (entity_is_task(se)) {
1998 struct task_struct *tsk = task_of(se);
2000 if (tsk->state & TASK_INTERRUPTIBLE)
2001 se->statistics.sleep_start = rq_of(cfs_rq)->clock;
2002 if (tsk->state & TASK_UNINTERRUPTIBLE)
2003 se->statistics.block_start = rq_of(cfs_rq)->clock;
2008 clear_buddies(cfs_rq, se);
2010 if (se != cfs_rq->curr)
2011 __dequeue_entity(cfs_rq, se);
2013 account_entity_dequeue(cfs_rq, se);
2016 * Normalize the entity after updating the min_vruntime because the
2017 * update can refer to the ->curr item and we need to reflect this
2018 * movement in our normalized position.
2020 if (!(flags & DEQUEUE_SLEEP))
2021 se->vruntime -= cfs_rq->min_vruntime;
2023 /* return excess runtime on last dequeue */
2024 return_cfs_rq_runtime(cfs_rq);
2026 update_min_vruntime(cfs_rq);
2027 update_cfs_shares(cfs_rq);
2031 * Preempt the current task with a newly woken task if needed:
2034 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
2036 unsigned long ideal_runtime, delta_exec;
2037 struct sched_entity *se;
2040 ideal_runtime = sched_slice(cfs_rq, curr);
2041 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
2042 if (delta_exec > ideal_runtime) {
2043 resched_task(rq_of(cfs_rq)->curr);
2045 * The current task ran long enough, ensure it doesn't get
2046 * re-elected due to buddy favours.
2048 clear_buddies(cfs_rq, curr);
2053 * Ensure that a task that missed wakeup preemption by a
2054 * narrow margin doesn't have to wait for a full slice.
2055 * This also mitigates buddy induced latencies under load.
2057 if (delta_exec < sysctl_sched_min_granularity)
2060 se = __pick_first_entity(cfs_rq);
2061 delta = curr->vruntime - se->vruntime;
2066 if (delta > ideal_runtime)
2067 resched_task(rq_of(cfs_rq)->curr);
2071 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
2073 /* 'current' is not kept within the tree. */
2076 * Any task has to be enqueued before it get to execute on
2077 * a CPU. So account for the time it spent waiting on the
2080 update_stats_wait_end(cfs_rq, se);
2081 __dequeue_entity(cfs_rq, se);
2082 update_entity_load_avg(se, 1);
2085 update_stats_curr_start(cfs_rq, se);
2087 #ifdef CONFIG_SCHEDSTATS
2089 * Track our maximum slice length, if the CPU's load is at
2090 * least twice that of our own weight (i.e. dont track it
2091 * when there are only lesser-weight tasks around):
2093 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
2094 se->statistics.slice_max = max(se->statistics.slice_max,
2095 se->sum_exec_runtime - se->prev_sum_exec_runtime);
2098 se->prev_sum_exec_runtime = se->sum_exec_runtime;
2102 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
2105 * Pick the next process, keeping these things in mind, in this order:
2106 * 1) keep things fair between processes/task groups
2107 * 2) pick the "next" process, since someone really wants that to run
2108 * 3) pick the "last" process, for cache locality
2109 * 4) do not run the "skip" process, if something else is available
2111 static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
2113 struct sched_entity *se = __pick_first_entity(cfs_rq);
2114 struct sched_entity *left = se;
2117 * Avoid running the skip buddy, if running something else can
2118 * be done without getting too unfair.
2120 if (cfs_rq->skip == se) {
2121 struct sched_entity *second = __pick_next_entity(se);
2122 if (second && wakeup_preempt_entity(second, left) < 1)
2127 * Prefer last buddy, try to return the CPU to a preempted task.
2129 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
2133 * Someone really wants this to run. If it's not unfair, run it.
2135 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
2138 clear_buddies(cfs_rq, se);
2143 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
2145 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
2148 * If still on the runqueue then deactivate_task()
2149 * was not called and update_curr() has to be done:
2152 update_curr(cfs_rq);
2154 /* throttle cfs_rqs exceeding runtime */
2155 check_cfs_rq_runtime(cfs_rq);
2157 check_spread(cfs_rq, prev);
2159 update_stats_wait_start(cfs_rq, prev);
2160 /* Put 'current' back into the tree. */
2161 __enqueue_entity(cfs_rq, prev);
2162 /* in !on_rq case, update occurred at dequeue */
2163 update_entity_load_avg(prev, 1);
2165 cfs_rq->curr = NULL;
2169 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
2172 * Update run-time statistics of the 'current'.
2174 update_curr(cfs_rq);
2177 * Ensure that runnable average is periodically updated.
2179 update_entity_load_avg(curr, 1);
2180 update_cfs_rq_blocked_load(cfs_rq, 1);
2182 #ifdef CONFIG_SCHED_HRTICK
2184 * queued ticks are scheduled to match the slice, so don't bother
2185 * validating it and just reschedule.
2188 resched_task(rq_of(cfs_rq)->curr);
2192 * don't let the period tick interfere with the hrtick preemption
2194 if (!sched_feat(DOUBLE_TICK) &&
2195 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
2199 if (cfs_rq->nr_running > 1)
2200 check_preempt_tick(cfs_rq, curr);
2204 /**************************************************
2205 * CFS bandwidth control machinery
2208 #ifdef CONFIG_CFS_BANDWIDTH
2210 #ifdef HAVE_JUMP_LABEL
2211 static struct static_key __cfs_bandwidth_used;
2213 static inline bool cfs_bandwidth_used(void)
2215 return static_key_false(&__cfs_bandwidth_used);
2218 void account_cfs_bandwidth_used(int enabled, int was_enabled)
2220 /* only need to count groups transitioning between enabled/!enabled */
2221 if (enabled && !was_enabled)
2222 static_key_slow_inc(&__cfs_bandwidth_used);
2223 else if (!enabled && was_enabled)
2224 static_key_slow_dec(&__cfs_bandwidth_used);
2226 #else /* HAVE_JUMP_LABEL */
2227 static bool cfs_bandwidth_used(void)
2232 void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
2233 #endif /* HAVE_JUMP_LABEL */
2236 * default period for cfs group bandwidth.
2237 * default: 0.1s, units: nanoseconds
2239 static inline u64 default_cfs_period(void)
2241 return 100000000ULL;
2244 static inline u64 sched_cfs_bandwidth_slice(void)
2246 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
2250 * Replenish runtime according to assigned quota and update expiration time.
2251 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
2252 * additional synchronization around rq->lock.
2254 * requires cfs_b->lock
2256 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
2260 if (cfs_b->quota == RUNTIME_INF)
2263 now = sched_clock_cpu(smp_processor_id());
2264 cfs_b->runtime = cfs_b->quota;
2265 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
2268 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2270 return &tg->cfs_bandwidth;
2273 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
2274 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
2276 if (unlikely(cfs_rq->throttle_count))
2277 return cfs_rq->throttled_clock_task;
2279 return rq_of(cfs_rq)->clock_task - cfs_rq->throttled_clock_task_time;
2282 /* returns 0 on failure to allocate runtime */
2283 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2285 struct task_group *tg = cfs_rq->tg;
2286 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
2287 u64 amount = 0, min_amount, expires;
2289 /* note: this is a positive sum as runtime_remaining <= 0 */
2290 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
2292 raw_spin_lock(&cfs_b->lock);
2293 if (cfs_b->quota == RUNTIME_INF)
2294 amount = min_amount;
2297 * If the bandwidth pool has become inactive, then at least one
2298 * period must have elapsed since the last consumption.
2299 * Refresh the global state and ensure bandwidth timer becomes
2302 if (!cfs_b->timer_active) {
2303 __refill_cfs_bandwidth_runtime(cfs_b);
2304 __start_cfs_bandwidth(cfs_b);
2307 if (cfs_b->runtime > 0) {
2308 amount = min(cfs_b->runtime, min_amount);
2309 cfs_b->runtime -= amount;
2313 expires = cfs_b->runtime_expires;
2314 raw_spin_unlock(&cfs_b->lock);
2316 cfs_rq->runtime_remaining += amount;
2318 * we may have advanced our local expiration to account for allowed
2319 * spread between our sched_clock and the one on which runtime was
2322 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
2323 cfs_rq->runtime_expires = expires;
2325 return cfs_rq->runtime_remaining > 0;
2329 * Note: This depends on the synchronization provided by sched_clock and the
2330 * fact that rq->clock snapshots this value.
2332 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2334 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2335 struct rq *rq = rq_of(cfs_rq);
2337 /* if the deadline is ahead of our clock, nothing to do */
2338 if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
2341 if (cfs_rq->runtime_remaining < 0)
2345 * If the local deadline has passed we have to consider the
2346 * possibility that our sched_clock is 'fast' and the global deadline
2347 * has not truly expired.
2349 * Fortunately we can check determine whether this the case by checking
2350 * whether the global deadline has advanced.
2353 if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
2354 /* extend local deadline, drift is bounded above by 2 ticks */
2355 cfs_rq->runtime_expires += TICK_NSEC;
2357 /* global deadline is ahead, expiration has passed */
2358 cfs_rq->runtime_remaining = 0;
2362 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
2363 unsigned long delta_exec)
2365 /* dock delta_exec before expiring quota (as it could span periods) */
2366 cfs_rq->runtime_remaining -= delta_exec;
2367 expire_cfs_rq_runtime(cfs_rq);
2369 if (likely(cfs_rq->runtime_remaining > 0))
2373 * if we're unable to extend our runtime we resched so that the active
2374 * hierarchy can be throttled
2376 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
2377 resched_task(rq_of(cfs_rq)->curr);
2380 static __always_inline
2381 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
2383 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
2386 __account_cfs_rq_runtime(cfs_rq, delta_exec);
2389 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2391 return cfs_bandwidth_used() && cfs_rq->throttled;
2394 /* check whether cfs_rq, or any parent, is throttled */
2395 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2397 return cfs_bandwidth_used() && cfs_rq->throttle_count;
2401 * Ensure that neither of the group entities corresponding to src_cpu or
2402 * dest_cpu are members of a throttled hierarchy when performing group
2403 * load-balance operations.
2405 static inline int throttled_lb_pair(struct task_group *tg,
2406 int src_cpu, int dest_cpu)
2408 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
2410 src_cfs_rq = tg->cfs_rq[src_cpu];
2411 dest_cfs_rq = tg->cfs_rq[dest_cpu];
2413 return throttled_hierarchy(src_cfs_rq) ||
2414 throttled_hierarchy(dest_cfs_rq);
2417 /* updated child weight may affect parent so we have to do this bottom up */
2418 static int tg_unthrottle_up(struct task_group *tg, void *data)
2420 struct rq *rq = data;
2421 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
2423 cfs_rq->throttle_count--;
2425 if (!cfs_rq->throttle_count) {
2426 /* adjust cfs_rq_clock_task() */
2427 cfs_rq->throttled_clock_task_time += rq->clock_task -
2428 cfs_rq->throttled_clock_task;
2435 static int tg_throttle_down(struct task_group *tg, void *data)
2437 struct rq *rq = data;
2438 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
2440 /* group is entering throttled state, stop time */
2441 if (!cfs_rq->throttle_count)
2442 cfs_rq->throttled_clock_task = rq->clock_task;
2443 cfs_rq->throttle_count++;
2448 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
2450 struct rq *rq = rq_of(cfs_rq);
2451 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2452 struct sched_entity *se;
2453 long task_delta, dequeue = 1;
2455 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
2457 /* freeze hierarchy runnable averages while throttled */
2459 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
2462 task_delta = cfs_rq->h_nr_running;
2463 for_each_sched_entity(se) {
2464 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
2465 /* throttled entity or throttle-on-deactivate */
2470 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
2471 qcfs_rq->h_nr_running -= task_delta;
2473 if (qcfs_rq->load.weight)
2478 rq->nr_running -= task_delta;
2480 cfs_rq->throttled = 1;
2481 cfs_rq->throttled_clock = rq->clock;
2482 raw_spin_lock(&cfs_b->lock);
2483 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
2484 raw_spin_unlock(&cfs_b->lock);
2487 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
2489 struct rq *rq = rq_of(cfs_rq);
2490 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2491 struct sched_entity *se;
2495 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
2497 cfs_rq->throttled = 0;
2498 raw_spin_lock(&cfs_b->lock);
2499 cfs_b->throttled_time += rq->clock - cfs_rq->throttled_clock;
2500 list_del_rcu(&cfs_rq->throttled_list);
2501 raw_spin_unlock(&cfs_b->lock);
2503 update_rq_clock(rq);
2504 /* update hierarchical throttle state */
2505 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
2507 if (!cfs_rq->load.weight)
2510 task_delta = cfs_rq->h_nr_running;
2511 for_each_sched_entity(se) {
2515 cfs_rq = cfs_rq_of(se);
2517 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
2518 cfs_rq->h_nr_running += task_delta;
2520 if (cfs_rq_throttled(cfs_rq))
2525 rq->nr_running += task_delta;
2527 /* determine whether we need to wake up potentially idle cpu */
2528 if (rq->curr == rq->idle && rq->cfs.nr_running)
2529 resched_task(rq->curr);
2532 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
2533 u64 remaining, u64 expires)
2535 struct cfs_rq *cfs_rq;
2536 u64 runtime = remaining;
2539 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
2541 struct rq *rq = rq_of(cfs_rq);
2543 raw_spin_lock(&rq->lock);
2544 if (!cfs_rq_throttled(cfs_rq))
2547 runtime = -cfs_rq->runtime_remaining + 1;
2548 if (runtime > remaining)
2549 runtime = remaining;
2550 remaining -= runtime;
2552 cfs_rq->runtime_remaining += runtime;
2553 cfs_rq->runtime_expires = expires;
2555 /* we check whether we're throttled above */
2556 if (cfs_rq->runtime_remaining > 0)
2557 unthrottle_cfs_rq(cfs_rq);
2560 raw_spin_unlock(&rq->lock);
2571 * Responsible for refilling a task_group's bandwidth and unthrottling its
2572 * cfs_rqs as appropriate. If there has been no activity within the last
2573 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
2574 * used to track this state.
2576 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
2578 u64 runtime, runtime_expires;
2579 int idle = 1, throttled;
2581 raw_spin_lock(&cfs_b->lock);
2582 /* no need to continue the timer with no bandwidth constraint */
2583 if (cfs_b->quota == RUNTIME_INF)
2586 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2587 /* idle depends on !throttled (for the case of a large deficit) */
2588 idle = cfs_b->idle && !throttled;
2589 cfs_b->nr_periods += overrun;
2591 /* if we're going inactive then everything else can be deferred */
2595 __refill_cfs_bandwidth_runtime(cfs_b);
2598 /* mark as potentially idle for the upcoming period */
2603 /* account preceding periods in which throttling occurred */
2604 cfs_b->nr_throttled += overrun;
2607 * There are throttled entities so we must first use the new bandwidth
2608 * to unthrottle them before making it generally available. This
2609 * ensures that all existing debts will be paid before a new cfs_rq is
2612 runtime = cfs_b->runtime;
2613 runtime_expires = cfs_b->runtime_expires;
2617 * This check is repeated as we are holding onto the new bandwidth
2618 * while we unthrottle. This can potentially race with an unthrottled
2619 * group trying to acquire new bandwidth from the global pool.
2621 while (throttled && runtime > 0) {
2622 raw_spin_unlock(&cfs_b->lock);
2623 /* we can't nest cfs_b->lock while distributing bandwidth */
2624 runtime = distribute_cfs_runtime(cfs_b, runtime,
2626 raw_spin_lock(&cfs_b->lock);
2628 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
2631 /* return (any) remaining runtime */
2632 cfs_b->runtime = runtime;
2634 * While we are ensured activity in the period following an
2635 * unthrottle, this also covers the case in which the new bandwidth is
2636 * insufficient to cover the existing bandwidth deficit. (Forcing the
2637 * timer to remain active while there are any throttled entities.)
2642 cfs_b->timer_active = 0;
2643 raw_spin_unlock(&cfs_b->lock);
2648 /* a cfs_rq won't donate quota below this amount */
2649 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
2650 /* minimum remaining period time to redistribute slack quota */
2651 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
2652 /* how long we wait to gather additional slack before distributing */
2653 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
2655 /* are we near the end of the current quota period? */
2656 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
2658 struct hrtimer *refresh_timer = &cfs_b->period_timer;
2661 /* if the call-back is running a quota refresh is already occurring */
2662 if (hrtimer_callback_running(refresh_timer))
2665 /* is a quota refresh about to occur? */
2666 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
2667 if (remaining < min_expire)
2673 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
2675 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
2677 /* if there's a quota refresh soon don't bother with slack */
2678 if (runtime_refresh_within(cfs_b, min_left))
2681 start_bandwidth_timer(&cfs_b->slack_timer,
2682 ns_to_ktime(cfs_bandwidth_slack_period));
2685 /* we know any runtime found here is valid as update_curr() precedes return */
2686 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2688 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2689 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
2691 if (slack_runtime <= 0)
2694 raw_spin_lock(&cfs_b->lock);
2695 if (cfs_b->quota != RUNTIME_INF &&
2696 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
2697 cfs_b->runtime += slack_runtime;
2699 /* we are under rq->lock, defer unthrottling using a timer */
2700 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
2701 !list_empty(&cfs_b->throttled_cfs_rq))
2702 start_cfs_slack_bandwidth(cfs_b);
2704 raw_spin_unlock(&cfs_b->lock);
2706 /* even if it's not valid for return we don't want to try again */
2707 cfs_rq->runtime_remaining -= slack_runtime;
2710 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2712 if (!cfs_bandwidth_used())
2715 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
2718 __return_cfs_rq_runtime(cfs_rq);
2722 * This is done with a timer (instead of inline with bandwidth return) since
2723 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
2725 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
2727 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
2730 /* confirm we're still not at a refresh boundary */
2731 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
2734 raw_spin_lock(&cfs_b->lock);
2735 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
2736 runtime = cfs_b->runtime;
2739 expires = cfs_b->runtime_expires;
2740 raw_spin_unlock(&cfs_b->lock);
2745 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
2747 raw_spin_lock(&cfs_b->lock);
2748 if (expires == cfs_b->runtime_expires)
2749 cfs_b->runtime = runtime;
2750 raw_spin_unlock(&cfs_b->lock);
2754 * When a group wakes up we want to make sure that its quota is not already
2755 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
2756 * runtime as update_curr() throttling can not not trigger until it's on-rq.
2758 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
2760 if (!cfs_bandwidth_used())
2763 /* an active group must be handled by the update_curr()->put() path */
2764 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
2767 /* ensure the group is not already throttled */
2768 if (cfs_rq_throttled(cfs_rq))
2771 /* update runtime allocation */
2772 account_cfs_rq_runtime(cfs_rq, 0);
2773 if (cfs_rq->runtime_remaining <= 0)
2774 throttle_cfs_rq(cfs_rq);
2777 /* conditionally throttle active cfs_rq's from put_prev_entity() */
2778 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2780 if (!cfs_bandwidth_used())
2783 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
2787 * it's possible for a throttled entity to be forced into a running
2788 * state (e.g. set_curr_task), in this case we're finished.
2790 if (cfs_rq_throttled(cfs_rq))
2793 throttle_cfs_rq(cfs_rq);
2796 static inline u64 default_cfs_period(void);
2797 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
2798 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
2800 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
2802 struct cfs_bandwidth *cfs_b =
2803 container_of(timer, struct cfs_bandwidth, slack_timer);
2804 do_sched_cfs_slack_timer(cfs_b);
2806 return HRTIMER_NORESTART;
2809 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
2811 struct cfs_bandwidth *cfs_b =
2812 container_of(timer, struct cfs_bandwidth, period_timer);
2818 now = hrtimer_cb_get_time(timer);
2819 overrun = hrtimer_forward(timer, now, cfs_b->period);
2824 idle = do_sched_cfs_period_timer(cfs_b, overrun);
2827 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
2830 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2832 raw_spin_lock_init(&cfs_b->lock);
2834 cfs_b->quota = RUNTIME_INF;
2835 cfs_b->period = ns_to_ktime(default_cfs_period());
2837 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
2838 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2839 cfs_b->period_timer.function = sched_cfs_period_timer;
2840 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2841 cfs_b->slack_timer.function = sched_cfs_slack_timer;
2844 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
2846 cfs_rq->runtime_enabled = 0;
2847 INIT_LIST_HEAD(&cfs_rq->throttled_list);
2850 /* requires cfs_b->lock, may release to reprogram timer */
2851 void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2854 * The timer may be active because we're trying to set a new bandwidth
2855 * period or because we're racing with the tear-down path
2856 * (timer_active==0 becomes visible before the hrtimer call-back
2857 * terminates). In either case we ensure that it's re-programmed
2859 while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
2860 raw_spin_unlock(&cfs_b->lock);
2861 /* ensure cfs_b->lock is available while we wait */
2862 hrtimer_cancel(&cfs_b->period_timer);
2864 raw_spin_lock(&cfs_b->lock);
2865 /* if someone else restarted the timer then we're done */
2866 if (cfs_b->timer_active)
2870 cfs_b->timer_active = 1;
2871 start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
2874 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
2876 hrtimer_cancel(&cfs_b->period_timer);
2877 hrtimer_cancel(&cfs_b->slack_timer);
2880 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
2882 struct cfs_rq *cfs_rq;
2884 for_each_leaf_cfs_rq(rq, cfs_rq) {
2885 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
2887 if (!cfs_rq->runtime_enabled)
2891 * clock_task is not advancing so we just need to make sure
2892 * there's some valid quota amount
2894 cfs_rq->runtime_remaining = cfs_b->quota;
2895 if (cfs_rq_throttled(cfs_rq))
2896 unthrottle_cfs_rq(cfs_rq);
2900 #else /* CONFIG_CFS_BANDWIDTH */
2901 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
2903 return rq_of(cfs_rq)->clock_task;
2906 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
2907 unsigned long delta_exec) {}
2908 static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2909 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
2910 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2912 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
2917 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
2922 static inline int throttled_lb_pair(struct task_group *tg,
2923 int src_cpu, int dest_cpu)
2928 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2930 #ifdef CONFIG_FAIR_GROUP_SCHED
2931 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
2934 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
2938 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
2939 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
2941 #endif /* CONFIG_CFS_BANDWIDTH */
2943 /**************************************************
2944 * CFS operations on tasks:
2947 #ifdef CONFIG_SCHED_HRTICK
2948 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
2950 struct sched_entity *se = &p->se;
2951 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2953 WARN_ON(task_rq(p) != rq);
2955 if (cfs_rq->nr_running > 1) {
2956 u64 slice = sched_slice(cfs_rq, se);
2957 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
2958 s64 delta = slice - ran;
2967 * Don't schedule slices shorter than 10000ns, that just
2968 * doesn't make sense. Rely on vruntime for fairness.
2971 delta = max_t(s64, 10000LL, delta);
2973 hrtick_start(rq, delta);
2978 * called from enqueue/dequeue and updates the hrtick when the
2979 * current task is from our class and nr_running is low enough
2982 static void hrtick_update(struct rq *rq)
2984 struct task_struct *curr = rq->curr;
2986 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
2989 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
2990 hrtick_start_fair(rq, curr);
2992 #else /* !CONFIG_SCHED_HRTICK */
2994 hrtick_start_fair(struct rq *rq, struct task_struct *p)
2998 static inline void hrtick_update(struct rq *rq)
3004 * The enqueue_task method is called before nr_running is
3005 * increased. Here we update the fair scheduling stats and
3006 * then put the task into the rbtree:
3009 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
3011 struct cfs_rq *cfs_rq;
3012 struct sched_entity *se = &p->se;
3014 for_each_sched_entity(se) {
3017 cfs_rq = cfs_rq_of(se);
3018 enqueue_entity(cfs_rq, se, flags);
3021 * end evaluation on encountering a throttled cfs_rq
3023 * note: in the case of encountering a throttled cfs_rq we will
3024 * post the final h_nr_running increment below.
3026 if (cfs_rq_throttled(cfs_rq))
3028 cfs_rq->h_nr_running++;
3030 flags = ENQUEUE_WAKEUP;
3033 for_each_sched_entity(se) {
3034 cfs_rq = cfs_rq_of(se);
3035 cfs_rq->h_nr_running++;
3037 if (cfs_rq_throttled(cfs_rq))
3040 update_cfs_shares(cfs_rq);
3041 update_entity_load_avg(se, 1);
3045 update_rq_runnable_avg(rq, rq->nr_running);
3051 static void set_next_buddy(struct sched_entity *se);
3054 * The dequeue_task method is called before nr_running is
3055 * decreased. We remove the task from the rbtree and
3056 * update the fair scheduling stats:
3058 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
3060 struct cfs_rq *cfs_rq;
3061 struct sched_entity *se = &p->se;
3062 int task_sleep = flags & DEQUEUE_SLEEP;
3064 for_each_sched_entity(se) {
3065 cfs_rq = cfs_rq_of(se);
3066 dequeue_entity(cfs_rq, se, flags);
3069 * end evaluation on encountering a throttled cfs_rq
3071 * note: in the case of encountering a throttled cfs_rq we will
3072 * post the final h_nr_running decrement below.
3074 if (cfs_rq_throttled(cfs_rq))
3076 cfs_rq->h_nr_running--;
3078 /* Don't dequeue parent if it has other entities besides us */
3079 if (cfs_rq->load.weight) {
3081 * Bias pick_next to pick a task from this cfs_rq, as
3082 * p is sleeping when it is within its sched_slice.
3084 if (task_sleep && parent_entity(se))
3085 set_next_buddy(parent_entity(se));
3087 /* avoid re-evaluating load for this entity */
3088 se = parent_entity(se);
3091 flags |= DEQUEUE_SLEEP;
3094 for_each_sched_entity(se) {
3095 cfs_rq = cfs_rq_of(se);
3096 cfs_rq->h_nr_running--;
3098 if (cfs_rq_throttled(cfs_rq))
3101 update_cfs_shares(cfs_rq);
3102 update_entity_load_avg(se, 1);
3107 update_rq_runnable_avg(rq, 1);
3113 /* Used instead of source_load when we know the type == 0 */
3114 static unsigned long weighted_cpuload(const int cpu)
3116 return cpu_rq(cpu)->load.weight;
3120 * Return a low guess at the load of a migration-source cpu weighted
3121 * according to the scheduling class and "nice" value.
3123 * We want to under-estimate the load of migration sources, to
3124 * balance conservatively.
3126 static unsigned long source_load(int cpu, int type)
3128 struct rq *rq = cpu_rq(cpu);
3129 unsigned long total = weighted_cpuload(cpu);
3131 if (type == 0 || !sched_feat(LB_BIAS))
3134 return min(rq->cpu_load[type-1], total);
3138 * Return a high guess at the load of a migration-target cpu weighted
3139 * according to the scheduling class and "nice" value.
3141 static unsigned long target_load(int cpu, int type)
3143 struct rq *rq = cpu_rq(cpu);
3144 unsigned long total = weighted_cpuload(cpu);
3146 if (type == 0 || !sched_feat(LB_BIAS))
3149 return max(rq->cpu_load[type-1], total);
3152 static unsigned long power_of(int cpu)
3154 return cpu_rq(cpu)->cpu_power;
3157 static unsigned long cpu_avg_load_per_task(int cpu)
3159 struct rq *rq = cpu_rq(cpu);
3160 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
3163 return rq->load.weight / nr_running;
3169 static void task_waking_fair(struct task_struct *p)
3171 struct sched_entity *se = &p->se;
3172 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3175 #ifndef CONFIG_64BIT
3176 u64 min_vruntime_copy;
3179 min_vruntime_copy = cfs_rq->min_vruntime_copy;
3181 min_vruntime = cfs_rq->min_vruntime;
3182 } while (min_vruntime != min_vruntime_copy);
3184 min_vruntime = cfs_rq->min_vruntime;
3187 se->vruntime -= min_vruntime;
3190 #ifdef CONFIG_FAIR_GROUP_SCHED
3192 * effective_load() calculates the load change as seen from the root_task_group
3194 * Adding load to a group doesn't make a group heavier, but can cause movement
3195 * of group shares between cpus. Assuming the shares were perfectly aligned one
3196 * can calculate the shift in shares.
3198 * Calculate the effective load difference if @wl is added (subtracted) to @tg
3199 * on this @cpu and results in a total addition (subtraction) of @wg to the
3200 * total group weight.
3202 * Given a runqueue weight distribution (rw_i) we can compute a shares
3203 * distribution (s_i) using:
3205 * s_i = rw_i / \Sum rw_j (1)
3207 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
3208 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
3209 * shares distribution (s_i):
3211 * rw_i = { 2, 4, 1, 0 }
3212 * s_i = { 2/7, 4/7, 1/7, 0 }
3214 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
3215 * task used to run on and the CPU the waker is running on), we need to
3216 * compute the effect of waking a task on either CPU and, in case of a sync
3217 * wakeup, compute the effect of the current task going to sleep.
3219 * So for a change of @wl to the local @cpu with an overall group weight change
3220 * of @wl we can compute the new shares distribution (s'_i) using:
3222 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
3224 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
3225 * differences in waking a task to CPU 0. The additional task changes the
3226 * weight and shares distributions like:
3228 * rw'_i = { 3, 4, 1, 0 }
3229 * s'_i = { 3/8, 4/8, 1/8, 0 }
3231 * We can then compute the difference in effective weight by using:
3233 * dw_i = S * (s'_i - s_i) (3)
3235 * Where 'S' is the group weight as seen by its parent.
3237 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
3238 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
3239 * 4/7) times the weight of the group.
3241 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
3243 struct sched_entity *se = tg->se[cpu];
3245 if (!tg->parent) /* the trivial, non-cgroup case */
3248 for_each_sched_entity(se) {
3254 * W = @wg + \Sum rw_j
3256 W = wg + calc_tg_weight(tg, se->my_q);
3261 w = se->my_q->load.weight + wl;
3264 * wl = S * s'_i; see (2)
3267 wl = (w * tg->shares) / W;
3272 * Per the above, wl is the new se->load.weight value; since
3273 * those are clipped to [MIN_SHARES, ...) do so now. See
3274 * calc_cfs_shares().
3276 if (wl < MIN_SHARES)
3280 * wl = dw_i = S * (s'_i - s_i); see (3)
3282 wl -= se->load.weight;
3285 * Recursively apply this logic to all parent groups to compute
3286 * the final effective load change on the root group. Since
3287 * only the @tg group gets extra weight, all parent groups can
3288 * only redistribute existing shares. @wl is the shift in shares
3289 * resulting from this level per the above.
3298 static inline unsigned long effective_load(struct task_group *tg, int cpu,
3299 unsigned long wl, unsigned long wg)
3306 static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
3308 s64 this_load, load;
3309 int idx, this_cpu, prev_cpu;
3310 unsigned long tl_per_task;
3311 struct task_group *tg;
3312 unsigned long weight;
3316 this_cpu = smp_processor_id();
3317 prev_cpu = task_cpu(p);
3318 load = source_load(prev_cpu, idx);
3319 this_load = target_load(this_cpu, idx);
3322 * If sync wakeup then subtract the (maximum possible)
3323 * effect of the currently running task from the load
3324 * of the current CPU:
3327 tg = task_group(current);
3328 weight = current->se.load.weight;
3330 this_load += effective_load(tg, this_cpu, -weight, -weight);
3331 load += effective_load(tg, prev_cpu, 0, -weight);
3335 weight = p->se.load.weight;
3338 * In low-load situations, where prev_cpu is idle and this_cpu is idle
3339 * due to the sync cause above having dropped this_load to 0, we'll
3340 * always have an imbalance, but there's really nothing you can do
3341 * about that, so that's good too.
3343 * Otherwise check if either cpus are near enough in load to allow this
3344 * task to be woken on this_cpu.
3346 if (this_load > 0) {
3347 s64 this_eff_load, prev_eff_load;
3349 this_eff_load = 100;
3350 this_eff_load *= power_of(prev_cpu);
3351 this_eff_load *= this_load +
3352 effective_load(tg, this_cpu, weight, weight);
3354 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
3355 prev_eff_load *= power_of(this_cpu);
3356 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
3358 balanced = this_eff_load <= prev_eff_load;
3363 * If the currently running task will sleep within
3364 * a reasonable amount of time then attract this newly
3367 if (sync && balanced)
3370 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
3371 tl_per_task = cpu_avg_load_per_task(this_cpu);
3374 (this_load <= load &&
3375 this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
3377 * This domain has SD_WAKE_AFFINE and
3378 * p is cache cold in this domain, and
3379 * there is no bad imbalance.
3381 schedstat_inc(sd, ttwu_move_affine);
3382 schedstat_inc(p, se.statistics.nr_wakeups_affine);
3390 * find_idlest_group finds and returns the least busy CPU group within the
3393 static struct sched_group *
3394 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
3395 int this_cpu, int load_idx)
3397 struct sched_group *idlest = NULL, *group = sd->groups;
3398 unsigned long min_load = ULONG_MAX, this_load = 0;
3399 int imbalance = 100 + (sd->imbalance_pct-100)/2;
3402 unsigned long load, avg_load;
3406 /* Skip over this group if it has no CPUs allowed */
3407 if (!cpumask_intersects(sched_group_cpus(group),
3408 tsk_cpus_allowed(p)))
3411 local_group = cpumask_test_cpu(this_cpu,
3412 sched_group_cpus(group));
3414 /* Tally up the load of all CPUs in the group */
3417 for_each_cpu(i, sched_group_cpus(group)) {
3418 /* Bias balancing toward cpus of our domain */
3420 load = source_load(i, load_idx);
3422 load = target_load(i, load_idx);
3427 /* Adjust by relative CPU power of the group */
3428 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
3431 this_load = avg_load;
3432 } else if (avg_load < min_load) {
3433 min_load = avg_load;
3436 } while (group = group->next, group != sd->groups);
3438 if (!idlest || 100*this_load < imbalance*min_load)
3444 * find_idlest_cpu - find the idlest cpu among the cpus in group.
3447 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
3449 unsigned long load, min_load = ULONG_MAX;
3453 /* Traverse only the allowed CPUs */
3454 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
3455 load = weighted_cpuload(i);
3457 if (load < min_load || (load == min_load && i == this_cpu)) {
3467 * Try and locate an idle CPU in the sched_domain.
3469 static int select_idle_sibling(struct task_struct *p, int target)
3471 struct sched_domain *sd;
3472 struct sched_group *sg;
3473 int i = task_cpu(p);
3475 if (idle_cpu(target))
3479 * If the prevous cpu is cache affine and idle, don't be stupid.
3481 if (i != target && cpus_share_cache(i, target) && idle_cpu(i))
3485 * Otherwise, iterate the domains and find an elegible idle cpu.
3487 sd = rcu_dereference(per_cpu(sd_llc, target));
3488 for_each_lower_domain(sd) {
3491 if (!cpumask_intersects(sched_group_cpus(sg),
3492 tsk_cpus_allowed(p)))
3495 for_each_cpu(i, sched_group_cpus(sg)) {
3496 if (i == target || !idle_cpu(i))
3500 target = cpumask_first_and(sched_group_cpus(sg),
3501 tsk_cpus_allowed(p));
3505 } while (sg != sd->groups);
3511 #ifdef CONFIG_SCHED_HMP
3513 * Heterogenous multiprocessor (HMP) optimizations
3515 * The cpu types are distinguished using a list of hmp_domains
3516 * which each represent one cpu type using a cpumask.
3517 * The list is assumed ordered by compute capacity with the
3518 * fastest domain first.
3520 DEFINE_PER_CPU(struct hmp_domain *, hmp_cpu_domain);
3521 static const int hmp_max_tasks = 5;
3523 extern void __init arch_get_hmp_domains(struct list_head *hmp_domains_list);
3525 /* Setup hmp_domains */
3526 static int __init hmp_cpu_mask_setup(void)
3529 struct hmp_domain *domain;
3530 struct list_head *pos;
3533 pr_debug("Initializing HMP scheduler:\n");
3535 /* Initialize hmp_domains using platform code */
3536 arch_get_hmp_domains(&hmp_domains);
3537 if (list_empty(&hmp_domains)) {
3538 pr_debug("HMP domain list is empty!\n");
3542 /* Print hmp_domains */
3544 list_for_each(pos, &hmp_domains) {
3545 domain = list_entry(pos, struct hmp_domain, hmp_domains);
3546 cpulist_scnprintf(buf, 64, &domain->possible_cpus);
3547 pr_debug(" HMP domain %d: %s\n", dc, buf);
3549 for_each_cpu_mask(cpu, domain->possible_cpus) {
3550 per_cpu(hmp_cpu_domain, cpu) = domain;
3558 static struct hmp_domain *hmp_get_hmp_domain_for_cpu(int cpu)
3560 struct hmp_domain *domain;
3561 struct list_head *pos;
3563 list_for_each(pos, &hmp_domains) {
3564 domain = list_entry(pos, struct hmp_domain, hmp_domains);
3565 if(cpumask_test_cpu(cpu, &domain->possible_cpus))
3571 static void hmp_online_cpu(int cpu)
3573 struct hmp_domain *domain = hmp_get_hmp_domain_for_cpu(cpu);
3576 cpumask_set_cpu(cpu, &domain->cpus);
3579 static void hmp_offline_cpu(int cpu)
3581 struct hmp_domain *domain = hmp_get_hmp_domain_for_cpu(cpu);
3584 cpumask_clear_cpu(cpu, &domain->cpus);
3587 * Needed to determine heaviest tasks etc.
3589 static inline unsigned int hmp_cpu_is_fastest(int cpu);
3590 static inline unsigned int hmp_cpu_is_slowest(int cpu);
3591 static inline struct hmp_domain *hmp_slower_domain(int cpu);
3592 static inline struct hmp_domain *hmp_faster_domain(int cpu);
3594 /* must hold runqueue lock for queue se is currently on */
3595 static struct sched_entity *hmp_get_heaviest_task(
3596 struct sched_entity *se, int migrate_up)
3598 int num_tasks = hmp_max_tasks;
3599 struct sched_entity *max_se = se;
3600 unsigned long int max_ratio = se->avg.load_avg_ratio;
3601 const struct cpumask *hmp_target_mask = NULL;
3604 struct hmp_domain *hmp;
3605 if (hmp_cpu_is_fastest(cpu_of(se->cfs_rq->rq)))
3608 hmp = hmp_faster_domain(cpu_of(se->cfs_rq->rq));
3609 hmp_target_mask = &hmp->cpus;
3611 /* The currently running task is not on the runqueue */
3612 se = __pick_first_entity(cfs_rq_of(se));
3614 while (num_tasks && se) {
3615 if (entity_is_task(se) &&
3616 (se->avg.load_avg_ratio > max_ratio &&
3618 cpumask_intersects(hmp_target_mask,
3619 tsk_cpus_allowed(task_of(se))))) {
3621 max_ratio = se->avg.load_avg_ratio;
3623 se = __pick_next_entity(se);
3629 static struct sched_entity *hmp_get_lightest_task(
3630 struct sched_entity *se, int migrate_down)
3632 int num_tasks = hmp_max_tasks;
3633 struct sched_entity *min_se = se;
3634 unsigned long int min_ratio = se->avg.load_avg_ratio;
3635 const struct cpumask *hmp_target_mask = NULL;
3638 struct hmp_domain *hmp;
3639 if (hmp_cpu_is_slowest(cpu_of(se->cfs_rq->rq)))
3641 hmp = hmp_slower_domain(cpu_of(se->cfs_rq->rq));
3642 hmp_target_mask = &hmp->cpus;
3644 /* The currently running task is not on the runqueue */
3645 se = __pick_first_entity(cfs_rq_of(se));
3647 while (num_tasks && se) {
3648 if (entity_is_task(se) &&
3649 (se->avg.load_avg_ratio < min_ratio &&
3651 cpumask_intersects(hmp_target_mask,
3652 tsk_cpus_allowed(task_of(se))))) {
3654 min_ratio = se->avg.load_avg_ratio;
3656 se = __pick_next_entity(se);
3663 * Migration thresholds should be in the range [0..1023]
3664 * hmp_up_threshold: min. load required for migrating tasks to a faster cpu
3665 * hmp_down_threshold: max. load allowed for tasks migrating to a slower cpu
3666 * The default values (512, 256) offer good responsiveness, but may need
3667 * tweaking suit particular needs.
3669 * hmp_up_prio: Only up migrate task with high priority (<hmp_up_prio)
3670 * hmp_next_up_threshold: Delay before next up migration (1024 ~= 1 ms)
3671 * hmp_next_down_threshold: Delay before next down migration (1024 ~= 1 ms)
3673 unsigned int hmp_up_threshold = 512;
3674 unsigned int hmp_down_threshold = 256;
3675 #ifdef CONFIG_SCHED_HMP_PRIO_FILTER
3676 unsigned int hmp_up_prio = NICE_TO_PRIO(CONFIG_SCHED_HMP_PRIO_FILTER_VAL);
3678 unsigned int hmp_next_up_threshold = 4096;
3679 unsigned int hmp_next_down_threshold = 4096;
3681 static unsigned int hmp_up_migration(int cpu, int *target_cpu, struct sched_entity *se);
3682 static unsigned int hmp_down_migration(int cpu, struct sched_entity *se);
3683 static inline unsigned int hmp_domain_min_load(struct hmp_domain *hmpd,
3686 /* Check if cpu is in fastest hmp_domain */
3687 static inline unsigned int hmp_cpu_is_fastest(int cpu)
3689 struct list_head *pos;
3691 pos = &hmp_cpu_domain(cpu)->hmp_domains;
3692 return pos == hmp_domains.next;
3695 /* Check if cpu is in slowest hmp_domain */
3696 static inline unsigned int hmp_cpu_is_slowest(int cpu)
3698 struct list_head *pos;
3700 pos = &hmp_cpu_domain(cpu)->hmp_domains;
3701 return list_is_last(pos, &hmp_domains);
3704 /* Next (slower) hmp_domain relative to cpu */
3705 static inline struct hmp_domain *hmp_slower_domain(int cpu)
3707 struct list_head *pos;
3709 pos = &hmp_cpu_domain(cpu)->hmp_domains;
3710 return list_entry(pos->next, struct hmp_domain, hmp_domains);
3713 /* Previous (faster) hmp_domain relative to cpu */
3714 static inline struct hmp_domain *hmp_faster_domain(int cpu)
3716 struct list_head *pos;
3718 pos = &hmp_cpu_domain(cpu)->hmp_domains;
3719 return list_entry(pos->prev, struct hmp_domain, hmp_domains);
3723 * Selects a cpu in previous (faster) hmp_domain
3724 * Note that cpumask_any_and() returns the first cpu in the cpumask
3726 static inline unsigned int hmp_select_faster_cpu(struct task_struct *tsk,
3729 int lowest_cpu=NR_CPUS;
3730 __always_unused int lowest_ratio = hmp_domain_min_load(hmp_faster_domain(cpu), &lowest_cpu);
3732 * If the lowest-loaded CPU in the domain is allowed by the task affinity
3733 * select that one, otherwise select one which is allowed
3735 if(lowest_cpu != NR_CPUS && cpumask_test_cpu(lowest_cpu,tsk_cpus_allowed(tsk)))
3738 return cpumask_any_and(&hmp_faster_domain(cpu)->cpus,
3739 tsk_cpus_allowed(tsk));
3743 * Selects a cpu in next (slower) hmp_domain
3744 * Note that cpumask_any_and() returns the first cpu in the cpumask
3746 static inline unsigned int hmp_select_slower_cpu(struct task_struct *tsk,
3749 int lowest_cpu=NR_CPUS;
3750 struct hmp_domain *hmp;
3751 __always_unused int lowest_ratio;
3753 if (hmp_cpu_is_slowest(cpu))
3754 hmp = hmp_cpu_domain(cpu);
3756 hmp = hmp_slower_domain(cpu);
3758 lowest_ratio = hmp_domain_min_load(hmp, &lowest_cpu);
3760 * If the lowest-loaded CPU in the domain is allowed by the task affinity
3761 * select that one, otherwise select one which is allowed
3763 if(lowest_cpu != NR_CPUS && cpumask_test_cpu(lowest_cpu,tsk_cpus_allowed(tsk)))
3766 return cpumask_any_and(&hmp_slower_domain(cpu)->cpus,
3767 tsk_cpus_allowed(tsk));
3770 static inline void hmp_next_up_delay(struct sched_entity *se, int cpu)
3772 /* hack - always use clock from first online CPU */
3773 u64 now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
3774 se->avg.hmp_last_up_migration = now;
3775 se->avg.hmp_last_down_migration = 0;
3776 cpu_rq(cpu)->avg.hmp_last_up_migration = now;
3777 cpu_rq(cpu)->avg.hmp_last_down_migration = 0;
3780 static inline void hmp_next_down_delay(struct sched_entity *se, int cpu)
3782 /* hack - always use clock from first online CPU */
3783 u64 now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
3784 se->avg.hmp_last_down_migration = now;
3785 se->avg.hmp_last_up_migration = 0;
3786 cpu_rq(cpu)->avg.hmp_last_down_migration = now;
3787 cpu_rq(cpu)->avg.hmp_last_up_migration = 0;
3790 #ifdef CONFIG_HMP_VARIABLE_SCALE
3792 * Heterogenous multiprocessor (HMP) optimizations
3794 * These functions allow to change the growing speed of the load_avg_ratio
3795 * by default it goes from 0 to 0.5 in LOAD_AVG_PERIOD = 32ms
3796 * This can now be changed with /sys/kernel/hmp/load_avg_period_ms.
3798 * These functions also allow to change the up and down threshold of HMP
3799 * using /sys/kernel/hmp/{up,down}_threshold.
3800 * Both must be between 0 and 1023. The threshold that is compared
3801 * to the load_avg_ratio is up_threshold/1024 and down_threshold/1024.
3803 * For instance, if load_avg_period = 64 and up_threshold = 512, an idle
3804 * task with a load of 0 will reach the threshold after 64ms of busy loop.
3806 * Changing load_avg_periods_ms has the same effect than changing the
3807 * default scaling factor Y=1002/1024 in the load_avg_ratio computation to
3808 * (1002/1024.0)^(LOAD_AVG_PERIOD/load_avg_period_ms), but the last one
3809 * could trigger overflows.
3810 * For instance, with Y = 1023/1024 in __update_task_entity_contrib()
3811 * "contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);"
3812 * could be overflowed for a weight > 2^12 even is the load_avg_contrib
3813 * should still be a 32bits result. This would not happen by multiplicating
3814 * delta time by 1/22 and setting load_avg_period_ms = 706.
3818 * By scaling the delta time it end-up increasing or decrease the
3819 * growing speed of the per entity load_avg_ratio
3820 * The scale factor hmp_data.multiplier is a fixed point
3821 * number: (32-HMP_VARIABLE_SCALE_SHIFT).HMP_VARIABLE_SCALE_SHIFT
3823 static u64 hmp_variable_scale_convert(u64 delta)
3825 u64 high = delta >> 32ULL;
3826 u64 low = delta & 0xffffffffULL;
3827 low *= hmp_data.multiplier;
3828 high *= hmp_data.multiplier;
3829 return (low >> HMP_VARIABLE_SCALE_SHIFT)
3830 + (high << (32ULL - HMP_VARIABLE_SCALE_SHIFT));
3833 static ssize_t hmp_show(struct kobject *kobj,
3834 struct attribute *attr, char *buf)
3837 struct hmp_global_attr *hmp_attr =
3838 container_of(attr, struct hmp_global_attr, attr);
3839 int temp = *(hmp_attr->value);
3840 if (hmp_attr->to_sysfs != NULL)
3841 temp = hmp_attr->to_sysfs(temp);
3842 ret = sprintf(buf, "%d\n", temp);
3846 static ssize_t hmp_store(struct kobject *a, struct attribute *attr,
3847 const char *buf, size_t count)
3850 ssize_t ret = count;
3851 struct hmp_global_attr *hmp_attr =
3852 container_of(attr, struct hmp_global_attr, attr);
3853 char *str = vmalloc(count + 1);
3856 memcpy(str, buf, count);
3858 if (sscanf(str, "%d", &temp) < 1)
3861 if (hmp_attr->from_sysfs != NULL)
3862 temp = hmp_attr->from_sysfs(temp);
3866 *(hmp_attr->value) = temp;
3872 static int hmp_period_tofrom_sysfs(int value)
3874 return (LOAD_AVG_PERIOD << HMP_VARIABLE_SCALE_SHIFT) / value;
3877 /* max value for threshold is 1024 */
3878 static int hmp_theshold_from_sysfs(int value)
3884 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
3885 /* freqinvar control is only 0,1 off/on */
3886 static int hmp_freqinvar_from_sysfs(int value)
3888 if (value < 0 || value > 1)
3893 static void hmp_attr_add(
3896 int (*to_sysfs)(int),
3897 int (*from_sysfs)(int))
3900 while (hmp_data.attributes[i] != NULL) {
3902 if (i >= HMP_DATA_SYSFS_MAX)
3905 hmp_data.attr[i].attr.mode = 0644;
3906 hmp_data.attr[i].show = hmp_show;
3907 hmp_data.attr[i].store = hmp_store;
3908 hmp_data.attr[i].attr.name = name;
3909 hmp_data.attr[i].value = value;
3910 hmp_data.attr[i].to_sysfs = to_sysfs;
3911 hmp_data.attr[i].from_sysfs = from_sysfs;
3912 hmp_data.attributes[i] = &hmp_data.attr[i].attr;
3913 hmp_data.attributes[i + 1] = NULL;
3916 static int hmp_attr_init(void)
3919 memset(&hmp_data, sizeof(hmp_data), 0);
3920 /* by default load_avg_period_ms == LOAD_AVG_PERIOD
3923 hmp_data.multiplier = hmp_period_tofrom_sysfs(LOAD_AVG_PERIOD);
3925 hmp_attr_add("load_avg_period_ms",
3926 &hmp_data.multiplier,
3927 hmp_period_tofrom_sysfs,
3928 hmp_period_tofrom_sysfs);
3929 hmp_attr_add("up_threshold",
3932 hmp_theshold_from_sysfs);
3933 hmp_attr_add("down_threshold",
3934 &hmp_down_threshold,
3936 hmp_theshold_from_sysfs);
3937 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
3938 /* default frequency-invariant scaling ON */
3939 hmp_data.freqinvar_load_scale_enabled = 1;
3940 hmp_attr_add("frequency_invariant_load_scale",
3941 &hmp_data.freqinvar_load_scale_enabled,
3943 hmp_freqinvar_from_sysfs);
3945 hmp_data.attr_group.name = "hmp";
3946 hmp_data.attr_group.attrs = hmp_data.attributes;
3947 ret = sysfs_create_group(kernel_kobj,
3948 &hmp_data.attr_group);
3951 late_initcall(hmp_attr_init);
3952 #endif /* CONFIG_HMP_VARIABLE_SCALE */
3954 static inline unsigned int hmp_domain_min_load(struct hmp_domain *hmpd,
3958 int min_cpu_runnable_temp = NR_CPUS;
3959 u64 min_target_last_migration = ULLONG_MAX;
3960 u64 curr_last_migration;
3961 unsigned long min_runnable_load = INT_MAX;
3962 unsigned long contrib;
3963 struct sched_avg *avg;
3965 for_each_cpu_mask(cpu, hmpd->cpus) {
3966 avg = &cpu_rq(cpu)->avg;
3967 /* used for both up and down migration */
3968 curr_last_migration = avg->hmp_last_up_migration ?
3969 avg->hmp_last_up_migration : avg->hmp_last_down_migration;
3971 contrib = avg->load_avg_ratio;
3973 * Consider a runqueue completely busy if there is any load
3974 * on it. Definitely not the best for overall fairness, but
3975 * does well in typical Android use cases.
3980 if ((contrib < min_runnable_load) ||
3981 (contrib == min_runnable_load &&
3982 curr_last_migration < min_target_last_migration)) {
3984 * if the load is the same target the CPU with
3985 * the longest time since a migration.
3986 * This is to spread migration load between
3987 * members of a domain more evenly when the
3988 * domain is fully loaded
3990 min_runnable_load = contrib;
3991 min_cpu_runnable_temp = cpu;
3992 min_target_last_migration = curr_last_migration;
3997 *min_cpu = min_cpu_runnable_temp;
3999 return min_runnable_load;
4003 * Calculate the task starvation
4004 * This is the ratio of actually running time vs. runnable time.
4005 * If the two are equal the task is getting the cpu time it needs or
4006 * it is alone on the cpu and the cpu is fully utilized.
4008 static inline unsigned int hmp_task_starvation(struct sched_entity *se)
4012 starvation = se->avg.usage_avg_sum * scale_load_down(NICE_0_LOAD);
4013 starvation /= (se->avg.runnable_avg_sum + 1);
4015 return scale_load(starvation);
4018 static inline unsigned int hmp_offload_down(int cpu, struct sched_entity *se)
4021 int dest_cpu = NR_CPUS;
4023 if (hmp_cpu_is_slowest(cpu))
4026 /* Is there an idle CPU in the current domain */
4027 min_usage = hmp_domain_min_load(hmp_cpu_domain(cpu), NULL);
4031 /* Is the task alone on the cpu? */
4032 if (cpu_rq(cpu)->cfs.h_nr_running < 2)
4035 /* Is the task actually starving? */
4036 /* >=25% ratio running/runnable = starving */
4037 if (hmp_task_starvation(se) > 768)
4040 /* Does the slower domain have any idle CPUs? */
4041 min_usage = hmp_domain_min_load(hmp_slower_domain(cpu), &dest_cpu);
4045 if (cpumask_test_cpu(dest_cpu, &hmp_slower_domain(cpu)->cpus))
4050 #endif /* CONFIG_SCHED_HMP */
4053 * sched_balance_self: balance the current task (running on cpu) in domains
4054 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
4057 * Balance, ie. select the least loaded group.
4059 * Returns the target CPU number, or the same CPU if no balancing is needed.
4061 * preempt must be disabled.
4064 select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
4066 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
4067 int cpu = smp_processor_id();
4068 int prev_cpu = task_cpu(p);
4070 int want_affine = 0;
4071 int sync = wake_flags & WF_SYNC;
4073 if (p->nr_cpus_allowed == 1)
4076 #ifdef CONFIG_SCHED_HMP
4077 /* always put non-kernel forking tasks on a big domain */
4078 if (p->mm && (sd_flag & SD_BALANCE_FORK)) {
4079 if(hmp_cpu_is_fastest(prev_cpu)) {
4080 struct hmp_domain *hmpdom = list_entry(&hmp_cpu_domain(prev_cpu)->hmp_domains, struct hmp_domain, hmp_domains);
4081 __always_unused int lowest_ratio = hmp_domain_min_load(hmpdom, &new_cpu);
4082 if(new_cpu != NR_CPUS && cpumask_test_cpu(new_cpu,tsk_cpus_allowed(p)))
4085 new_cpu = cpumask_any_and(&hmp_faster_domain(cpu)->cpus,
4086 tsk_cpus_allowed(p));
4087 if(new_cpu < nr_cpu_ids)
4091 new_cpu = hmp_select_faster_cpu(p, prev_cpu);
4092 if (new_cpu != NR_CPUS)
4098 if (sd_flag & SD_BALANCE_WAKE) {
4099 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
4105 for_each_domain(cpu, tmp) {
4106 if (!(tmp->flags & SD_LOAD_BALANCE))
4110 * If both cpu and prev_cpu are part of this domain,
4111 * cpu is a valid SD_WAKE_AFFINE target.
4113 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
4114 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
4119 if (tmp->flags & sd_flag)
4124 if (cpu != prev_cpu && wake_affine(affine_sd, p, sync))
4127 new_cpu = select_idle_sibling(p, prev_cpu);
4132 int load_idx = sd->forkexec_idx;
4133 struct sched_group *group;
4136 if (!(sd->flags & sd_flag)) {
4141 if (sd_flag & SD_BALANCE_WAKE)
4142 load_idx = sd->wake_idx;
4144 group = find_idlest_group(sd, p, cpu, load_idx);
4150 new_cpu = find_idlest_cpu(group, p, cpu);
4151 if (new_cpu == -1 || new_cpu == cpu) {
4152 /* Now try balancing at a lower domain level of cpu */
4157 /* Now try balancing at a lower domain level of new_cpu */
4159 weight = sd->span_weight;
4161 for_each_domain(cpu, tmp) {
4162 if (weight <= tmp->span_weight)
4164 if (tmp->flags & sd_flag)
4167 /* while loop will break here if sd == NULL */
4172 #ifdef CONFIG_SCHED_HMP
4173 if (hmp_up_migration(prev_cpu, &new_cpu, &p->se)) {
4174 hmp_next_up_delay(&p->se, new_cpu);
4175 trace_sched_hmp_migrate(p, new_cpu, 0);
4178 if (hmp_down_migration(prev_cpu, &p->se)) {
4179 new_cpu = hmp_select_slower_cpu(p, prev_cpu);
4180 hmp_next_down_delay(&p->se, new_cpu);
4181 trace_sched_hmp_migrate(p, new_cpu, 0);
4184 /* Make sure that the task stays in its previous hmp domain */
4185 if (!cpumask_test_cpu(new_cpu, &hmp_cpu_domain(prev_cpu)->cpus))
4193 * Load-tracking only depends on SMP, FAIR_GROUP_SCHED dependency below may be
4194 * removed when useful for applications beyond shares distribution (e.g.
4197 #ifdef CONFIG_FAIR_GROUP_SCHED
4199 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
4200 * cfs_rq_of(p) references at time of call are still valid and identify the
4201 * previous cpu. However, the caller only guarantees p->pi_lock is held; no
4202 * other assumptions, including the state of rq->lock, should be made.
4205 migrate_task_rq_fair(struct task_struct *p, int next_cpu)
4207 struct sched_entity *se = &p->se;
4208 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4211 * Load tracking: accumulate removed load so that it can be processed
4212 * when we next update owning cfs_rq under rq->lock. Tasks contribute
4213 * to blocked load iff they have a positive decay-count. It can never
4214 * be negative here since on-rq tasks have decay-count == 0.
4216 if (se->avg.decay_count) {
4217 se->avg.decay_count = -__synchronize_entity_decay(se);
4218 atomic64_add(se->avg.load_avg_contrib, &cfs_rq->removed_load);
4222 #endif /* CONFIG_SMP */
4224 static unsigned long
4225 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
4227 unsigned long gran = sysctl_sched_wakeup_granularity;
4230 * Since its curr running now, convert the gran from real-time
4231 * to virtual-time in his units.
4233 * By using 'se' instead of 'curr' we penalize light tasks, so
4234 * they get preempted easier. That is, if 'se' < 'curr' then
4235 * the resulting gran will be larger, therefore penalizing the
4236 * lighter, if otoh 'se' > 'curr' then the resulting gran will
4237 * be smaller, again penalizing the lighter task.
4239 * This is especially important for buddies when the leftmost
4240 * task is higher priority than the buddy.
4242 return calc_delta_fair(gran, se);
4246 * Should 'se' preempt 'curr'.
4260 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
4262 s64 gran, vdiff = curr->vruntime - se->vruntime;
4267 gran = wakeup_gran(curr, se);
4274 static void set_last_buddy(struct sched_entity *se)
4276 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4279 for_each_sched_entity(se)
4280 cfs_rq_of(se)->last = se;
4283 static void set_next_buddy(struct sched_entity *se)
4285 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4288 for_each_sched_entity(se)
4289 cfs_rq_of(se)->next = se;
4292 static void set_skip_buddy(struct sched_entity *se)
4294 for_each_sched_entity(se)
4295 cfs_rq_of(se)->skip = se;
4299 * Preempt the current task with a newly woken task if needed:
4301 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
4303 struct task_struct *curr = rq->curr;
4304 struct sched_entity *se = &curr->se, *pse = &p->se;
4305 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
4306 int scale = cfs_rq->nr_running >= sched_nr_latency;
4307 int next_buddy_marked = 0;
4309 if (unlikely(se == pse))
4313 * This is possible from callers such as move_task(), in which we
4314 * unconditionally check_prempt_curr() after an enqueue (which may have
4315 * lead to a throttle). This both saves work and prevents false
4316 * next-buddy nomination below.
4318 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
4321 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
4322 set_next_buddy(pse);
4323 next_buddy_marked = 1;
4327 * We can come here with TIF_NEED_RESCHED already set from new task
4330 * Note: this also catches the edge-case of curr being in a throttled
4331 * group (e.g. via set_curr_task), since update_curr() (in the
4332 * enqueue of curr) will have resulted in resched being set. This
4333 * prevents us from potentially nominating it as a false LAST_BUDDY
4336 if (test_tsk_need_resched(curr))
4339 /* Idle tasks are by definition preempted by non-idle tasks. */
4340 if (unlikely(curr->policy == SCHED_IDLE) &&
4341 likely(p->policy != SCHED_IDLE))
4345 * Batch and idle tasks do not preempt non-idle tasks (their preemption
4346 * is driven by the tick):
4348 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
4351 find_matching_se(&se, &pse);
4352 update_curr(cfs_rq_of(se));
4354 if (wakeup_preempt_entity(se, pse) == 1) {
4356 * Bias pick_next to pick the sched entity that is
4357 * triggering this preemption.
4359 if (!next_buddy_marked)
4360 set_next_buddy(pse);
4369 * Only set the backward buddy when the current task is still
4370 * on the rq. This can happen when a wakeup gets interleaved
4371 * with schedule on the ->pre_schedule() or idle_balance()
4372 * point, either of which can * drop the rq lock.
4374 * Also, during early boot the idle thread is in the fair class,
4375 * for obvious reasons its a bad idea to schedule back to it.
4377 if (unlikely(!se->on_rq || curr == rq->idle))
4380 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
4384 static struct task_struct *pick_next_task_fair(struct rq *rq)
4386 struct task_struct *p;
4387 struct cfs_rq *cfs_rq = &rq->cfs;
4388 struct sched_entity *se;
4390 if (!cfs_rq->nr_running)
4394 se = pick_next_entity(cfs_rq);
4395 set_next_entity(cfs_rq, se);
4396 cfs_rq = group_cfs_rq(se);
4400 if (hrtick_enabled(rq))
4401 hrtick_start_fair(rq, p);
4407 * Account for a descheduled task:
4409 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
4411 struct sched_entity *se = &prev->se;
4412 struct cfs_rq *cfs_rq;
4414 for_each_sched_entity(se) {
4415 cfs_rq = cfs_rq_of(se);
4416 put_prev_entity(cfs_rq, se);
4421 * sched_yield() is very simple
4423 * The magic of dealing with the ->skip buddy is in pick_next_entity.
4425 static void yield_task_fair(struct rq *rq)
4427 struct task_struct *curr = rq->curr;
4428 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
4429 struct sched_entity *se = &curr->se;
4432 * Are we the only task in the tree?
4434 if (unlikely(rq->nr_running == 1))
4437 clear_buddies(cfs_rq, se);
4439 if (curr->policy != SCHED_BATCH) {
4440 update_rq_clock(rq);
4442 * Update run-time statistics of the 'current'.
4444 update_curr(cfs_rq);
4446 * Tell update_rq_clock() that we've just updated,
4447 * so we don't do microscopic update in schedule()
4448 * and double the fastpath cost.
4450 rq->skip_clock_update = 1;
4456 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
4458 struct sched_entity *se = &p->se;
4460 /* throttled hierarchies are not runnable */
4461 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
4464 /* Tell the scheduler that we'd really like pse to run next. */
4467 yield_task_fair(rq);
4473 /**************************************************
4474 * Fair scheduling class load-balancing methods.
4478 * The purpose of load-balancing is to achieve the same basic fairness the
4479 * per-cpu scheduler provides, namely provide a proportional amount of compute
4480 * time to each task. This is expressed in the following equation:
4482 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
4484 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
4485 * W_i,0 is defined as:
4487 * W_i,0 = \Sum_j w_i,j (2)
4489 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
4490 * is derived from the nice value as per prio_to_weight[].
4492 * The weight average is an exponential decay average of the instantaneous
4495 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
4497 * P_i is the cpu power (or compute capacity) of cpu i, typically it is the
4498 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
4499 * can also include other factors [XXX].
4501 * To achieve this balance we define a measure of imbalance which follows
4502 * directly from (1):
4504 * imb_i,j = max{ avg(W/P), W_i/P_i } - min{ avg(W/P), W_j/P_j } (4)
4506 * We them move tasks around to minimize the imbalance. In the continuous
4507 * function space it is obvious this converges, in the discrete case we get
4508 * a few fun cases generally called infeasible weight scenarios.
4511 * - infeasible weights;
4512 * - local vs global optima in the discrete case. ]
4517 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
4518 * for all i,j solution, we create a tree of cpus that follows the hardware
4519 * topology where each level pairs two lower groups (or better). This results
4520 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
4521 * tree to only the first of the previous level and we decrease the frequency
4522 * of load-balance at each level inv. proportional to the number of cpus in
4528 * \Sum { --- * --- * 2^i } = O(n) (5)
4530 * `- size of each group
4531 * | | `- number of cpus doing load-balance
4533 * `- sum over all levels
4535 * Coupled with a limit on how many tasks we can migrate every balance pass,
4536 * this makes (5) the runtime complexity of the balancer.
4538 * An important property here is that each CPU is still (indirectly) connected
4539 * to every other cpu in at most O(log n) steps:
4541 * The adjacency matrix of the resulting graph is given by:
4544 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
4547 * And you'll find that:
4549 * A^(log_2 n)_i,j != 0 for all i,j (7)
4551 * Showing there's indeed a path between every cpu in at most O(log n) steps.
4552 * The task movement gives a factor of O(m), giving a convergence complexity
4555 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
4560 * In order to avoid CPUs going idle while there's still work to do, new idle
4561 * balancing is more aggressive and has the newly idle cpu iterate up the domain
4562 * tree itself instead of relying on other CPUs to bring it work.
4564 * This adds some complexity to both (5) and (8) but it reduces the total idle
4572 * Cgroups make a horror show out of (2), instead of a simple sum we get:
4575 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
4580 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
4582 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
4584 * The big problem is S_k, its a global sum needed to compute a local (W_i)
4587 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
4588 * rewrite all of this once again.]
4591 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
4593 #define LBF_ALL_PINNED 0x01
4594 #define LBF_NEED_BREAK 0x02
4595 #define LBF_SOME_PINNED 0x04
4598 struct sched_domain *sd;
4606 struct cpumask *dst_grpmask;
4608 enum cpu_idle_type idle;
4610 /* The set of CPUs under consideration for load-balancing */
4611 struct cpumask *cpus;
4616 unsigned int loop_break;
4617 unsigned int loop_max;
4621 * move_task - move a task from one runqueue to another runqueue.
4622 * Both runqueues must be locked.
4624 static void move_task(struct task_struct *p, struct lb_env *env)
4626 deactivate_task(env->src_rq, p, 0);
4627 set_task_cpu(p, env->dst_cpu);
4628 activate_task(env->dst_rq, p, 0);
4629 check_preempt_curr(env->dst_rq, p, 0);
4633 * Is this task likely cache-hot:
4636 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
4640 if (p->sched_class != &fair_sched_class)
4643 if (unlikely(p->policy == SCHED_IDLE))
4647 * Buddy candidates are cache hot:
4649 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
4650 (&p->se == cfs_rq_of(&p->se)->next ||
4651 &p->se == cfs_rq_of(&p->se)->last))
4654 if (sysctl_sched_migration_cost == -1)
4656 if (sysctl_sched_migration_cost == 0)
4659 delta = now - p->se.exec_start;
4661 return delta < (s64)sysctl_sched_migration_cost;
4665 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
4668 int can_migrate_task(struct task_struct *p, struct lb_env *env)
4670 int tsk_cache_hot = 0;
4672 * We do not migrate tasks that are:
4673 * 1) throttled_lb_pair, or
4674 * 2) cannot be migrated to this CPU due to cpus_allowed, or
4675 * 3) running (obviously), or
4676 * 4) are cache-hot on their current CPU.
4678 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
4681 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
4684 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
4687 * Remember if this task can be migrated to any other cpu in
4688 * our sched_group. We may want to revisit it if we couldn't
4689 * meet load balance goals by pulling other tasks on src_cpu.
4691 * Also avoid computing new_dst_cpu if we have already computed
4692 * one in current iteration.
4694 if (!env->dst_grpmask || (env->flags & LBF_SOME_PINNED))
4697 /* Prevent to re-select dst_cpu via env's cpus */
4698 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
4699 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
4700 env->flags |= LBF_SOME_PINNED;
4701 env->new_dst_cpu = cpu;
4709 /* Record that we found atleast one task that could run on dst_cpu */
4710 env->flags &= ~LBF_ALL_PINNED;
4712 if (task_running(env->src_rq, p)) {
4713 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
4718 * Aggressive migration if:
4719 * 1) task is cache cold, or
4720 * 2) too many balance attempts have failed.
4722 tsk_cache_hot = task_hot(p, env->src_rq->clock_task, env->sd);
4723 if (!tsk_cache_hot ||
4724 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
4726 if (tsk_cache_hot) {
4727 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
4728 schedstat_inc(p, se.statistics.nr_forced_migrations);
4734 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
4739 * move_one_task tries to move exactly one task from busiest to this_rq, as
4740 * part of active balancing operations within "domain".
4741 * Returns 1 if successful and 0 otherwise.
4743 * Called with both runqueues locked.
4745 static int move_one_task(struct lb_env *env)
4747 struct task_struct *p, *n;
4749 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
4750 if (!can_migrate_task(p, env))
4755 * Right now, this is only the second place move_task()
4756 * is called, so we can safely collect move_task()
4757 * stats here rather than inside move_task().
4759 schedstat_inc(env->sd, lb_gained[env->idle]);
4765 static unsigned long task_h_load(struct task_struct *p);
4767 static const unsigned int sched_nr_migrate_break = 32;
4770 * move_tasks tries to move up to imbalance weighted load from busiest to
4771 * this_rq, as part of a balancing operation within domain "sd".
4772 * Returns 1 if successful and 0 otherwise.
4774 * Called with both runqueues locked.
4776 static int move_tasks(struct lb_env *env)
4778 struct list_head *tasks = &env->src_rq->cfs_tasks;
4779 struct task_struct *p;
4783 if (env->imbalance <= 0)
4786 while (!list_empty(tasks)) {
4787 p = list_first_entry(tasks, struct task_struct, se.group_node);
4790 /* We've more or less seen every task there is, call it quits */
4791 if (env->loop > env->loop_max)
4794 /* take a breather every nr_migrate tasks */
4795 if (env->loop > env->loop_break) {
4796 env->loop_break += sched_nr_migrate_break;
4797 env->flags |= LBF_NEED_BREAK;
4801 if (!can_migrate_task(p, env))
4804 load = task_h_load(p);
4806 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
4809 if ((load / 2) > env->imbalance)
4814 env->imbalance -= load;
4816 #ifdef CONFIG_PREEMPT
4818 * NEWIDLE balancing is a source of latency, so preemptible
4819 * kernels will stop after the first task is pulled to minimize
4820 * the critical section.
4822 if (env->idle == CPU_NEWLY_IDLE)
4827 * We only want to steal up to the prescribed amount of
4830 if (env->imbalance <= 0)
4835 list_move_tail(&p->se.group_node, tasks);
4839 * Right now, this is one of only two places move_task() is called,
4840 * so we can safely collect move_task() stats here rather than
4841 * inside move_task().
4843 schedstat_add(env->sd, lb_gained[env->idle], pulled);
4848 #ifdef CONFIG_FAIR_GROUP_SCHED
4850 * update tg->load_weight by folding this cpu's load_avg
4852 static void __update_blocked_averages_cpu(struct task_group *tg, int cpu)
4854 struct sched_entity *se = tg->se[cpu];
4855 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
4857 /* throttled entities do not contribute to load */
4858 if (throttled_hierarchy(cfs_rq))
4861 update_cfs_rq_blocked_load(cfs_rq, 1);
4864 update_entity_load_avg(se, 1);
4866 * We pivot on our runnable average having decayed to zero for
4867 * list removal. This generally implies that all our children
4868 * have also been removed (modulo rounding error or bandwidth
4869 * control); however, such cases are rare and we can fix these
4872 * TODO: fix up out-of-order children on enqueue.
4874 if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running)
4875 list_del_leaf_cfs_rq(cfs_rq);
4877 struct rq *rq = rq_of(cfs_rq);
4878 update_rq_runnable_avg(rq, rq->nr_running);
4882 static void update_blocked_averages(int cpu)
4884 struct rq *rq = cpu_rq(cpu);
4885 struct cfs_rq *cfs_rq;
4886 unsigned long flags;
4888 raw_spin_lock_irqsave(&rq->lock, flags);
4889 update_rq_clock(rq);
4891 * Iterates the task_group tree in a bottom up fashion, see
4892 * list_add_leaf_cfs_rq() for details.
4894 for_each_leaf_cfs_rq(rq, cfs_rq) {
4896 * Note: We may want to consider periodically releasing
4897 * rq->lock about these updates so that creating many task
4898 * groups does not result in continually extending hold time.
4900 __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu);
4903 raw_spin_unlock_irqrestore(&rq->lock, flags);
4907 * Compute the cpu's hierarchical load factor for each task group.
4908 * This needs to be done in a top-down fashion because the load of a child
4909 * group is a fraction of its parents load.
4911 static int tg_load_down(struct task_group *tg, void *data)
4914 long cpu = (long)data;
4917 load = cpu_rq(cpu)->load.weight;
4919 load = tg->parent->cfs_rq[cpu]->h_load;
4920 load *= tg->se[cpu]->load.weight;
4921 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
4924 tg->cfs_rq[cpu]->h_load = load;
4929 static void update_h_load(long cpu)
4931 struct rq *rq = cpu_rq(cpu);
4932 unsigned long now = jiffies;
4934 if (rq->h_load_throttle == now)
4937 rq->h_load_throttle = now;
4940 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
4944 static unsigned long task_h_load(struct task_struct *p)
4946 struct cfs_rq *cfs_rq = task_cfs_rq(p);
4949 load = p->se.load.weight;
4950 load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
4955 static inline void update_blocked_averages(int cpu)
4959 static inline void update_h_load(long cpu)
4963 static unsigned long task_h_load(struct task_struct *p)
4965 return p->se.load.weight;
4969 /********** Helpers for find_busiest_group ************************/
4971 * sd_lb_stats - Structure to store the statistics of a sched_domain
4972 * during load balancing.
4974 struct sd_lb_stats {
4975 struct sched_group *busiest; /* Busiest group in this sd */
4976 struct sched_group *this; /* Local group in this sd */
4977 unsigned long total_load; /* Total load of all groups in sd */
4978 unsigned long total_pwr; /* Total power of all groups in sd */
4979 unsigned long avg_load; /* Average load across all groups in sd */
4981 /** Statistics of this group */
4982 unsigned long this_load;
4983 unsigned long this_load_per_task;
4984 unsigned long this_nr_running;
4985 unsigned long this_has_capacity;
4986 unsigned int this_idle_cpus;
4988 /* Statistics of the busiest group */
4989 unsigned int busiest_idle_cpus;
4990 unsigned long max_load;
4991 unsigned long busiest_load_per_task;
4992 unsigned long busiest_nr_running;
4993 unsigned long busiest_group_capacity;
4994 unsigned long busiest_has_capacity;
4995 unsigned int busiest_group_weight;
4997 int group_imb; /* Is there imbalance in this sd */
5001 * sg_lb_stats - stats of a sched_group required for load_balancing
5003 struct sg_lb_stats {
5004 unsigned long avg_load; /*Avg load across the CPUs of the group */
5005 unsigned long group_load; /* Total load over the CPUs of the group */
5006 unsigned long sum_nr_running; /* Nr tasks running in the group */
5007 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
5008 unsigned long group_capacity;
5009 unsigned long idle_cpus;
5010 unsigned long group_weight;
5011 int group_imb; /* Is there an imbalance in the group ? */
5012 int group_has_capacity; /* Is there extra capacity in the group? */
5016 * get_sd_load_idx - Obtain the load index for a given sched domain.
5017 * @sd: The sched_domain whose load_idx is to be obtained.
5018 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
5020 static inline int get_sd_load_idx(struct sched_domain *sd,
5021 enum cpu_idle_type idle)
5027 load_idx = sd->busy_idx;
5030 case CPU_NEWLY_IDLE:
5031 load_idx = sd->newidle_idx;
5034 load_idx = sd->idle_idx;
5041 static unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
5043 return SCHED_POWER_SCALE;
5046 unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
5048 return default_scale_freq_power(sd, cpu);
5051 static unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
5053 unsigned long weight = sd->span_weight;
5054 unsigned long smt_gain = sd->smt_gain;
5061 unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
5063 return default_scale_smt_power(sd, cpu);
5066 static unsigned long scale_rt_power(int cpu)
5068 struct rq *rq = cpu_rq(cpu);
5069 u64 total, available, age_stamp, avg;
5072 * Since we're reading these variables without serialization make sure
5073 * we read them once before doing sanity checks on them.
5075 age_stamp = ACCESS_ONCE(rq->age_stamp);
5076 avg = ACCESS_ONCE(rq->rt_avg);
5078 total = sched_avg_period() + (rq->clock - age_stamp);
5080 if (unlikely(total < avg)) {
5081 /* Ensures that power won't end up being negative */
5084 available = total - avg;
5087 if (unlikely((s64)total < SCHED_POWER_SCALE))
5088 total = SCHED_POWER_SCALE;
5090 total >>= SCHED_POWER_SHIFT;
5092 return div_u64(available, total);
5095 static void update_cpu_power(struct sched_domain *sd, int cpu)
5097 unsigned long weight = sd->span_weight;
5098 unsigned long power = SCHED_POWER_SCALE;
5099 struct sched_group *sdg = sd->groups;
5101 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
5102 if (sched_feat(ARCH_POWER))
5103 power *= arch_scale_smt_power(sd, cpu);
5105 power *= default_scale_smt_power(sd, cpu);
5107 power >>= SCHED_POWER_SHIFT;
5110 sdg->sgp->power_orig = power;
5112 if (sched_feat(ARCH_POWER))
5113 power *= arch_scale_freq_power(sd, cpu);
5115 power *= default_scale_freq_power(sd, cpu);
5117 power >>= SCHED_POWER_SHIFT;
5119 power *= scale_rt_power(cpu);
5120 power >>= SCHED_POWER_SHIFT;
5125 cpu_rq(cpu)->cpu_power = power;
5126 sdg->sgp->power = power;
5129 void update_group_power(struct sched_domain *sd, int cpu)
5131 struct sched_domain *child = sd->child;
5132 struct sched_group *group, *sdg = sd->groups;
5133 unsigned long power;
5134 unsigned long interval;
5136 interval = msecs_to_jiffies(sd->balance_interval);
5137 interval = clamp(interval, 1UL, max_load_balance_interval);
5138 sdg->sgp->next_update = jiffies + interval;
5141 update_cpu_power(sd, cpu);
5147 if (child->flags & SD_OVERLAP) {
5149 * SD_OVERLAP domains cannot assume that child groups
5150 * span the current group.
5153 for_each_cpu(cpu, sched_group_cpus(sdg))
5154 power += power_of(cpu);
5157 * !SD_OVERLAP domains can assume that child groups
5158 * span the current group.
5161 group = child->groups;
5163 power += group->sgp->power;
5164 group = group->next;
5165 } while (group != child->groups);
5168 sdg->sgp->power_orig = sdg->sgp->power = power;
5172 * Try and fix up capacity for tiny siblings, this is needed when
5173 * things like SD_ASYM_PACKING need f_b_g to select another sibling
5174 * which on its own isn't powerful enough.
5176 * See update_sd_pick_busiest() and check_asym_packing().
5179 fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
5182 * Only siblings can have significantly less than SCHED_POWER_SCALE
5184 if (!(sd->flags & SD_SHARE_CPUPOWER))
5188 * If ~90% of the cpu_power is still there, we're good.
5190 if (group->sgp->power * 32 > group->sgp->power_orig * 29)
5197 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
5198 * @env: The load balancing environment.
5199 * @group: sched_group whose statistics are to be updated.
5200 * @load_idx: Load index of sched_domain of this_cpu for load calc.
5201 * @local_group: Does group contain this_cpu.
5202 * @balance: Should we balance.
5203 * @sgs: variable to hold the statistics for this group.
5205 static inline void update_sg_lb_stats(struct lb_env *env,
5206 struct sched_group *group, int load_idx,
5207 int local_group, int *balance, struct sg_lb_stats *sgs)
5209 unsigned long nr_running, max_nr_running, min_nr_running;
5210 unsigned long load, max_cpu_load, min_cpu_load;
5211 unsigned int balance_cpu = -1, first_idle_cpu = 0;
5212 unsigned long avg_load_per_task = 0;
5216 balance_cpu = group_balance_cpu(group);
5218 /* Tally up the load of all CPUs in the group */
5220 min_cpu_load = ~0UL;
5222 min_nr_running = ~0UL;
5224 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
5225 struct rq *rq = cpu_rq(i);
5227 nr_running = rq->nr_running;
5229 /* Bias balancing toward cpus of our domain */
5231 if (idle_cpu(i) && !first_idle_cpu &&
5232 cpumask_test_cpu(i, sched_group_mask(group))) {
5237 load = target_load(i, load_idx);
5239 load = source_load(i, load_idx);
5240 if (load > max_cpu_load)
5241 max_cpu_load = load;
5242 if (min_cpu_load > load)
5243 min_cpu_load = load;
5245 if (nr_running > max_nr_running)
5246 max_nr_running = nr_running;
5247 if (min_nr_running > nr_running)
5248 min_nr_running = nr_running;
5251 sgs->group_load += load;
5252 sgs->sum_nr_running += nr_running;
5253 sgs->sum_weighted_load += weighted_cpuload(i);
5259 * First idle cpu or the first cpu(busiest) in this sched group
5260 * is eligible for doing load balancing at this and above
5261 * domains. In the newly idle case, we will allow all the cpu's
5262 * to do the newly idle load balance.
5265 if (env->idle != CPU_NEWLY_IDLE) {
5266 if (balance_cpu != env->dst_cpu) {
5270 update_group_power(env->sd, env->dst_cpu);
5271 } else if (time_after_eq(jiffies, group->sgp->next_update))
5272 update_group_power(env->sd, env->dst_cpu);
5275 /* Adjust by relative CPU power of the group */
5276 sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
5279 * Consider the group unbalanced when the imbalance is larger
5280 * than the average weight of a task.
5282 * APZ: with cgroup the avg task weight can vary wildly and
5283 * might not be a suitable number - should we keep a
5284 * normalized nr_running number somewhere that negates
5287 if (sgs->sum_nr_running)
5288 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
5290 if ((max_cpu_load - min_cpu_load) >= avg_load_per_task &&
5291 (max_nr_running - min_nr_running) > 1)
5294 sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
5296 if (!sgs->group_capacity)
5297 sgs->group_capacity = fix_small_capacity(env->sd, group);
5298 sgs->group_weight = group->group_weight;
5300 if (sgs->group_capacity > sgs->sum_nr_running)
5301 sgs->group_has_capacity = 1;
5305 * update_sd_pick_busiest - return 1 on busiest group
5306 * @env: The load balancing environment.
5307 * @sds: sched_domain statistics
5308 * @sg: sched_group candidate to be checked for being the busiest
5309 * @sgs: sched_group statistics
5311 * Determine if @sg is a busier group than the previously selected
5314 static bool update_sd_pick_busiest(struct lb_env *env,
5315 struct sd_lb_stats *sds,
5316 struct sched_group *sg,
5317 struct sg_lb_stats *sgs)
5319 if (sgs->avg_load <= sds->max_load)
5322 if (sgs->sum_nr_running > sgs->group_capacity)
5329 * ASYM_PACKING needs to move all the work to the lowest
5330 * numbered CPUs in the group, therefore mark all groups
5331 * higher than ourself as busy.
5333 if ((env->sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
5334 env->dst_cpu < group_first_cpu(sg)) {
5338 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
5346 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
5347 * @env: The load balancing environment.
5348 * @balance: Should we balance.
5349 * @sds: variable to hold the statistics for this sched_domain.
5351 static inline void update_sd_lb_stats(struct lb_env *env,
5352 int *balance, struct sd_lb_stats *sds)
5354 struct sched_domain *child = env->sd->child;
5355 struct sched_group *sg = env->sd->groups;
5356 struct sg_lb_stats sgs;
5357 int load_idx, prefer_sibling = 0;
5359 if (child && child->flags & SD_PREFER_SIBLING)
5362 load_idx = get_sd_load_idx(env->sd, env->idle);
5367 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
5368 memset(&sgs, 0, sizeof(sgs));
5369 update_sg_lb_stats(env, sg, load_idx, local_group, balance, &sgs);
5371 if (local_group && !(*balance))
5374 sds->total_load += sgs.group_load;
5375 sds->total_pwr += sg->sgp->power;
5378 * In case the child domain prefers tasks go to siblings
5379 * first, lower the sg capacity to one so that we'll try
5380 * and move all the excess tasks away. We lower the capacity
5381 * of a group only if the local group has the capacity to fit
5382 * these excess tasks, i.e. nr_running < group_capacity. The
5383 * extra check prevents the case where you always pull from the
5384 * heaviest group when it is already under-utilized (possible
5385 * with a large weight task outweighs the tasks on the system).
5387 if (prefer_sibling && !local_group && sds->this_has_capacity)
5388 sgs.group_capacity = min(sgs.group_capacity, 1UL);
5391 sds->this_load = sgs.avg_load;
5393 sds->this_nr_running = sgs.sum_nr_running;
5394 sds->this_load_per_task = sgs.sum_weighted_load;
5395 sds->this_has_capacity = sgs.group_has_capacity;
5396 sds->this_idle_cpus = sgs.idle_cpus;
5397 } else if (update_sd_pick_busiest(env, sds, sg, &sgs)) {
5398 sds->max_load = sgs.avg_load;
5400 sds->busiest_nr_running = sgs.sum_nr_running;
5401 sds->busiest_idle_cpus = sgs.idle_cpus;
5402 sds->busiest_group_capacity = sgs.group_capacity;
5403 sds->busiest_load_per_task = sgs.sum_weighted_load;
5404 sds->busiest_has_capacity = sgs.group_has_capacity;
5405 sds->busiest_group_weight = sgs.group_weight;
5406 sds->group_imb = sgs.group_imb;
5410 } while (sg != env->sd->groups);
5414 * check_asym_packing - Check to see if the group is packed into the
5417 * This is primarily intended to used at the sibling level. Some
5418 * cores like POWER7 prefer to use lower numbered SMT threads. In the
5419 * case of POWER7, it can move to lower SMT modes only when higher
5420 * threads are idle. When in lower SMT modes, the threads will
5421 * perform better since they share less core resources. Hence when we
5422 * have idle threads, we want them to be the higher ones.
5424 * This packing function is run on idle threads. It checks to see if
5425 * the busiest CPU in this domain (core in the P7 case) has a higher
5426 * CPU number than the packing function is being run on. Here we are
5427 * assuming lower CPU number will be equivalent to lower a SMT thread
5430 * Returns 1 when packing is required and a task should be moved to
5431 * this CPU. The amount of the imbalance is returned in *imbalance.
5433 * @env: The load balancing environment.
5434 * @sds: Statistics of the sched_domain which is to be packed
5436 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
5440 if (!(env->sd->flags & SD_ASYM_PACKING))
5446 busiest_cpu = group_first_cpu(sds->busiest);
5447 if (env->dst_cpu > busiest_cpu)
5450 env->imbalance = DIV_ROUND_CLOSEST(
5451 sds->max_load * sds->busiest->sgp->power, SCHED_POWER_SCALE);
5457 * fix_small_imbalance - Calculate the minor imbalance that exists
5458 * amongst the groups of a sched_domain, during
5460 * @env: The load balancing environment.
5461 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
5464 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
5466 unsigned long tmp, pwr_now = 0, pwr_move = 0;
5467 unsigned int imbn = 2;
5468 unsigned long scaled_busy_load_per_task;
5470 if (sds->this_nr_running) {
5471 sds->this_load_per_task /= sds->this_nr_running;
5472 if (sds->busiest_load_per_task >
5473 sds->this_load_per_task)
5476 sds->this_load_per_task =
5477 cpu_avg_load_per_task(env->dst_cpu);
5480 scaled_busy_load_per_task = sds->busiest_load_per_task
5481 * SCHED_POWER_SCALE;
5482 scaled_busy_load_per_task /= sds->busiest->sgp->power;
5484 if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
5485 (scaled_busy_load_per_task * imbn)) {
5486 env->imbalance = sds->busiest_load_per_task;
5491 * OK, we don't have enough imbalance to justify moving tasks,
5492 * however we may be able to increase total CPU power used by
5496 pwr_now += sds->busiest->sgp->power *
5497 min(sds->busiest_load_per_task, sds->max_load);
5498 pwr_now += sds->this->sgp->power *
5499 min(sds->this_load_per_task, sds->this_load);
5500 pwr_now /= SCHED_POWER_SCALE;
5502 /* Amount of load we'd subtract */
5503 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
5504 sds->busiest->sgp->power;
5505 if (sds->max_load > tmp)
5506 pwr_move += sds->busiest->sgp->power *
5507 min(sds->busiest_load_per_task, sds->max_load - tmp);
5509 /* Amount of load we'd add */
5510 if (sds->max_load * sds->busiest->sgp->power <
5511 sds->busiest_load_per_task * SCHED_POWER_SCALE)
5512 tmp = (sds->max_load * sds->busiest->sgp->power) /
5513 sds->this->sgp->power;
5515 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
5516 sds->this->sgp->power;
5517 pwr_move += sds->this->sgp->power *
5518 min(sds->this_load_per_task, sds->this_load + tmp);
5519 pwr_move /= SCHED_POWER_SCALE;
5521 /* Move if we gain throughput */
5522 if (pwr_move > pwr_now)
5523 env->imbalance = sds->busiest_load_per_task;
5527 * calculate_imbalance - Calculate the amount of imbalance present within the
5528 * groups of a given sched_domain during load balance.
5529 * @env: load balance environment
5530 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
5532 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
5534 unsigned long max_pull, load_above_capacity = ~0UL;
5536 sds->busiest_load_per_task /= sds->busiest_nr_running;
5537 if (sds->group_imb) {
5538 sds->busiest_load_per_task =
5539 min(sds->busiest_load_per_task, sds->avg_load);
5543 * In the presence of smp nice balancing, certain scenarios can have
5544 * max load less than avg load(as we skip the groups at or below
5545 * its cpu_power, while calculating max_load..)
5547 if (sds->max_load < sds->avg_load) {
5549 return fix_small_imbalance(env, sds);
5552 if (!sds->group_imb) {
5554 * Don't want to pull so many tasks that a group would go idle.
5556 load_above_capacity = (sds->busiest_nr_running -
5557 sds->busiest_group_capacity);
5559 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
5561 load_above_capacity /= sds->busiest->sgp->power;
5565 * We're trying to get all the cpus to the average_load, so we don't
5566 * want to push ourselves above the average load, nor do we wish to
5567 * reduce the max loaded cpu below the average load. At the same time,
5568 * we also don't want to reduce the group load below the group capacity
5569 * (so that we can implement power-savings policies etc). Thus we look
5570 * for the minimum possible imbalance.
5571 * Be careful of negative numbers as they'll appear as very large values
5572 * with unsigned longs.
5574 max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
5576 /* How much load to actually move to equalise the imbalance */
5577 env->imbalance = min(max_pull * sds->busiest->sgp->power,
5578 (sds->avg_load - sds->this_load) * sds->this->sgp->power)
5579 / SCHED_POWER_SCALE;
5582 * if *imbalance is less than the average load per runnable task
5583 * there is no guarantee that any tasks will be moved so we'll have
5584 * a think about bumping its value to force at least one task to be
5587 if (env->imbalance < sds->busiest_load_per_task)
5588 return fix_small_imbalance(env, sds);
5592 /******* find_busiest_group() helpers end here *********************/
5595 * find_busiest_group - Returns the busiest group within the sched_domain
5596 * if there is an imbalance. If there isn't an imbalance, and
5597 * the user has opted for power-savings, it returns a group whose
5598 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
5599 * such a group exists.
5601 * Also calculates the amount of weighted load which should be moved
5602 * to restore balance.
5604 * @env: The load balancing environment.
5605 * @balance: Pointer to a variable indicating if this_cpu
5606 * is the appropriate cpu to perform load balancing at this_level.
5608 * Returns: - the busiest group if imbalance exists.
5609 * - If no imbalance and user has opted for power-savings balance,
5610 * return the least loaded group whose CPUs can be
5611 * put to idle by rebalancing its tasks onto our group.
5613 static struct sched_group *
5614 find_busiest_group(struct lb_env *env, int *balance)
5616 struct sd_lb_stats sds;
5618 memset(&sds, 0, sizeof(sds));
5621 * Compute the various statistics relavent for load balancing at
5624 update_sd_lb_stats(env, balance, &sds);
5627 * this_cpu is not the appropriate cpu to perform load balancing at
5633 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
5634 check_asym_packing(env, &sds))
5637 /* There is no busy sibling group to pull tasks from */
5638 if (!sds.busiest || sds.busiest_nr_running == 0)
5641 sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
5644 * If the busiest group is imbalanced the below checks don't
5645 * work because they assumes all things are equal, which typically
5646 * isn't true due to cpus_allowed constraints and the like.
5651 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
5652 if (env->idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
5653 !sds.busiest_has_capacity)
5657 * If the local group is more busy than the selected busiest group
5658 * don't try and pull any tasks.
5660 if (sds.this_load >= sds.max_load)
5664 * Don't pull any tasks if this group is already above the domain
5667 if (sds.this_load >= sds.avg_load)
5670 if (env->idle == CPU_IDLE) {
5672 * This cpu is idle. If the busiest group load doesn't
5673 * have more tasks than the number of available cpu's and
5674 * there is no imbalance between this and busiest group
5675 * wrt to idle cpu's, it is balanced.
5677 if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
5678 sds.busiest_nr_running <= sds.busiest_group_weight)
5682 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
5683 * imbalance_pct to be conservative.
5685 if (100 * sds.max_load <= env->sd->imbalance_pct * sds.this_load)
5690 /* Looks like there is an imbalance. Compute it */
5691 calculate_imbalance(env, &sds);
5701 * find_busiest_queue - find the busiest runqueue among the cpus in group.
5703 static struct rq *find_busiest_queue(struct lb_env *env,
5704 struct sched_group *group)
5706 struct rq *busiest = NULL, *rq;
5707 unsigned long max_load = 0;
5710 for_each_cpu(i, sched_group_cpus(group)) {
5711 unsigned long power = power_of(i);
5712 unsigned long capacity = DIV_ROUND_CLOSEST(power,
5717 capacity = fix_small_capacity(env->sd, group);
5719 if (!cpumask_test_cpu(i, env->cpus))
5723 wl = weighted_cpuload(i);
5726 * When comparing with imbalance, use weighted_cpuload()
5727 * which is not scaled with the cpu power.
5729 if (capacity && rq->nr_running == 1 && wl > env->imbalance)
5733 * For the load comparisons with the other cpu's, consider
5734 * the weighted_cpuload() scaled with the cpu power, so that
5735 * the load can be moved away from the cpu that is potentially
5736 * running at a lower capacity.
5738 wl = (wl * SCHED_POWER_SCALE) / power;
5740 if (wl > max_load) {
5750 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
5751 * so long as it is large enough.
5753 #define MAX_PINNED_INTERVAL 512
5755 /* Working cpumask for load_balance and load_balance_newidle. */
5756 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
5758 static int need_active_balance(struct lb_env *env)
5760 struct sched_domain *sd = env->sd;
5762 if (env->idle == CPU_NEWLY_IDLE) {
5765 * ASYM_PACKING needs to force migrate tasks from busy but
5766 * higher numbered CPUs in order to pack all tasks in the
5767 * lowest numbered CPUs.
5769 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
5773 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
5776 static int active_load_balance_cpu_stop(void *data);
5779 * Check this_cpu to ensure it is balanced within domain. Attempt to move
5780 * tasks if there is an imbalance.
5782 static int load_balance(int this_cpu, struct rq *this_rq,
5783 struct sched_domain *sd, enum cpu_idle_type idle,
5786 int ld_moved, cur_ld_moved, active_balance = 0;
5787 struct sched_group *group;
5789 unsigned long flags;
5790 struct cpumask *cpus = __get_cpu_var(load_balance_mask);
5792 struct lb_env env = {
5794 .dst_cpu = this_cpu,
5796 .dst_grpmask = sched_group_cpus(sd->groups),
5798 .loop_break = sched_nr_migrate_break,
5803 * For NEWLY_IDLE load_balancing, we don't need to consider
5804 * other cpus in our group
5806 if (idle == CPU_NEWLY_IDLE)
5807 env.dst_grpmask = NULL;
5809 cpumask_copy(cpus, cpu_active_mask);
5811 schedstat_inc(sd, lb_count[idle]);
5814 group = find_busiest_group(&env, balance);
5820 schedstat_inc(sd, lb_nobusyg[idle]);
5824 busiest = find_busiest_queue(&env, group);
5826 schedstat_inc(sd, lb_nobusyq[idle]);
5830 BUG_ON(busiest == env.dst_rq);
5832 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
5835 if (busiest->nr_running > 1) {
5837 * Attempt to move tasks. If find_busiest_group has found
5838 * an imbalance but busiest->nr_running <= 1, the group is
5839 * still unbalanced. ld_moved simply stays zero, so it is
5840 * correctly treated as an imbalance.
5842 env.flags |= LBF_ALL_PINNED;
5843 env.src_cpu = busiest->cpu;
5844 env.src_rq = busiest;
5845 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
5847 update_h_load(env.src_cpu);
5849 local_irq_save(flags);
5850 double_rq_lock(env.dst_rq, busiest);
5853 * cur_ld_moved - load moved in current iteration
5854 * ld_moved - cumulative load moved across iterations
5856 cur_ld_moved = move_tasks(&env);
5857 ld_moved += cur_ld_moved;
5858 double_rq_unlock(env.dst_rq, busiest);
5859 local_irq_restore(flags);
5862 * some other cpu did the load balance for us.
5864 if (cur_ld_moved && env.dst_cpu != smp_processor_id())
5865 resched_cpu(env.dst_cpu);
5867 if (env.flags & LBF_NEED_BREAK) {
5868 env.flags &= ~LBF_NEED_BREAK;
5873 * Revisit (affine) tasks on src_cpu that couldn't be moved to
5874 * us and move them to an alternate dst_cpu in our sched_group
5875 * where they can run. The upper limit on how many times we
5876 * iterate on same src_cpu is dependent on number of cpus in our
5879 * This changes load balance semantics a bit on who can move
5880 * load to a given_cpu. In addition to the given_cpu itself
5881 * (or a ilb_cpu acting on its behalf where given_cpu is
5882 * nohz-idle), we now have balance_cpu in a position to move
5883 * load to given_cpu. In rare situations, this may cause
5884 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
5885 * _independently_ and at _same_ time to move some load to
5886 * given_cpu) causing exceess load to be moved to given_cpu.
5887 * This however should not happen so much in practice and
5888 * moreover subsequent load balance cycles should correct the
5889 * excess load moved.
5891 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) {
5893 env.dst_rq = cpu_rq(env.new_dst_cpu);
5894 env.dst_cpu = env.new_dst_cpu;
5895 env.flags &= ~LBF_SOME_PINNED;
5897 env.loop_break = sched_nr_migrate_break;
5899 /* Prevent to re-select dst_cpu via env's cpus */
5900 cpumask_clear_cpu(env.dst_cpu, env.cpus);
5903 * Go back to "more_balance" rather than "redo" since we
5904 * need to continue with same src_cpu.
5909 /* All tasks on this runqueue were pinned by CPU affinity */
5910 if (unlikely(env.flags & LBF_ALL_PINNED)) {
5911 cpumask_clear_cpu(cpu_of(busiest), cpus);
5912 if (!cpumask_empty(cpus)) {
5914 env.loop_break = sched_nr_migrate_break;
5922 schedstat_inc(sd, lb_failed[idle]);
5924 * Increment the failure counter only on periodic balance.
5925 * We do not want newidle balance, which can be very
5926 * frequent, pollute the failure counter causing
5927 * excessive cache_hot migrations and active balances.
5929 if (idle != CPU_NEWLY_IDLE)
5930 sd->nr_balance_failed++;
5932 if (need_active_balance(&env)) {
5933 raw_spin_lock_irqsave(&busiest->lock, flags);
5935 /* don't kick the active_load_balance_cpu_stop,
5936 * if the curr task on busiest cpu can't be
5939 if (!cpumask_test_cpu(this_cpu,
5940 tsk_cpus_allowed(busiest->curr))) {
5941 raw_spin_unlock_irqrestore(&busiest->lock,
5943 env.flags |= LBF_ALL_PINNED;
5944 goto out_one_pinned;
5948 * ->active_balance synchronizes accesses to
5949 * ->active_balance_work. Once set, it's cleared
5950 * only after active load balance is finished.
5952 if (!busiest->active_balance) {
5953 busiest->active_balance = 1;
5954 busiest->push_cpu = this_cpu;
5957 raw_spin_unlock_irqrestore(&busiest->lock, flags);
5959 if (active_balance) {
5960 stop_one_cpu_nowait(cpu_of(busiest),
5961 active_load_balance_cpu_stop, busiest,
5962 &busiest->active_balance_work);
5966 * We've kicked active balancing, reset the failure
5969 sd->nr_balance_failed = sd->cache_nice_tries+1;
5972 sd->nr_balance_failed = 0;
5974 if (likely(!active_balance)) {
5975 /* We were unbalanced, so reset the balancing interval */
5976 sd->balance_interval = sd->min_interval;
5979 * If we've begun active balancing, start to back off. This
5980 * case may not be covered by the all_pinned logic if there
5981 * is only 1 task on the busy runqueue (because we don't call
5984 if (sd->balance_interval < sd->max_interval)
5985 sd->balance_interval *= 2;
5991 schedstat_inc(sd, lb_balanced[idle]);
5993 sd->nr_balance_failed = 0;
5996 /* tune up the balancing interval */
5997 if (((env.flags & LBF_ALL_PINNED) &&
5998 sd->balance_interval < MAX_PINNED_INTERVAL) ||
5999 (sd->balance_interval < sd->max_interval))
6000 sd->balance_interval *= 2;
6006 #ifdef CONFIG_SCHED_HMP
6007 static unsigned int hmp_idle_pull(int this_cpu);
6010 * idle_balance is called by schedule() if this_cpu is about to become
6011 * idle. Attempts to pull tasks from other CPUs.
6013 void idle_balance(int this_cpu, struct rq *this_rq)
6015 struct sched_domain *sd;
6016 int pulled_task = 0;
6017 unsigned long next_balance = jiffies + HZ;
6019 this_rq->idle_stamp = this_rq->clock;
6021 if (this_rq->avg_idle < sysctl_sched_migration_cost)
6025 * Drop the rq->lock, but keep IRQ/preempt disabled.
6027 raw_spin_unlock(&this_rq->lock);
6029 update_blocked_averages(this_cpu);
6031 for_each_domain(this_cpu, sd) {
6032 unsigned long interval;
6035 if (!(sd->flags & SD_LOAD_BALANCE))
6038 if (sd->flags & SD_BALANCE_NEWIDLE) {
6039 /* If we've pulled tasks over stop searching: */
6040 pulled_task = load_balance(this_cpu, this_rq,
6041 sd, CPU_NEWLY_IDLE, &balance);
6044 interval = msecs_to_jiffies(sd->balance_interval);
6045 if (time_after(next_balance, sd->last_balance + interval))
6046 next_balance = sd->last_balance + interval;
6048 this_rq->idle_stamp = 0;
6053 #ifdef CONFIG_SCHED_HMP
6055 pulled_task = hmp_idle_pull(this_cpu);
6057 raw_spin_lock(&this_rq->lock);
6059 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
6061 * We are going idle. next_balance may be set based on
6062 * a busy processor. So reset next_balance.
6064 this_rq->next_balance = next_balance;
6069 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
6070 * running tasks off the busiest CPU onto idle CPUs. It requires at
6071 * least 1 task to be running on each physical CPU where possible, and
6072 * avoids physical / logical imbalances.
6074 static int active_load_balance_cpu_stop(void *data)
6076 struct rq *busiest_rq = data;
6077 int busiest_cpu = cpu_of(busiest_rq);
6078 int target_cpu = busiest_rq->push_cpu;
6079 struct rq *target_rq = cpu_rq(target_cpu);
6080 struct sched_domain *sd;
6082 raw_spin_lock_irq(&busiest_rq->lock);
6084 /* make sure the requested cpu hasn't gone down in the meantime */
6085 if (unlikely(busiest_cpu != smp_processor_id() ||
6086 !busiest_rq->active_balance))
6089 /* Is there any task to move? */
6090 if (busiest_rq->nr_running <= 1)
6094 * This condition is "impossible", if it occurs
6095 * we need to fix it. Originally reported by
6096 * Bjorn Helgaas on a 128-cpu setup.
6098 BUG_ON(busiest_rq == target_rq);
6100 /* move a task from busiest_rq to target_rq */
6101 double_lock_balance(busiest_rq, target_rq);
6103 /* Search for an sd spanning us and the target CPU. */
6105 for_each_domain(target_cpu, sd) {
6106 if ((sd->flags & SD_LOAD_BALANCE) &&
6107 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
6112 struct lb_env env = {
6114 .dst_cpu = target_cpu,
6115 .dst_rq = target_rq,
6116 .src_cpu = busiest_rq->cpu,
6117 .src_rq = busiest_rq,
6121 schedstat_inc(sd, alb_count);
6123 if (move_one_task(&env))
6124 schedstat_inc(sd, alb_pushed);
6126 schedstat_inc(sd, alb_failed);
6129 double_unlock_balance(busiest_rq, target_rq);
6131 busiest_rq->active_balance = 0;
6132 raw_spin_unlock_irq(&busiest_rq->lock);
6136 #ifdef CONFIG_NO_HZ_COMMON
6138 * idle load balancing details
6139 * - When one of the busy CPUs notice that there may be an idle rebalancing
6140 * needed, they will kick the idle load balancer, which then does idle
6141 * load balancing for all the idle CPUs.
6144 cpumask_var_t idle_cpus_mask;
6146 unsigned long next_balance; /* in jiffy units */
6147 } nohz ____cacheline_aligned;
6149 static inline int find_new_ilb(int call_cpu)
6151 int ilb = cpumask_first(nohz.idle_cpus_mask);
6152 #ifdef CONFIG_SCHED_HMP
6153 /* restrict nohz balancing to occur in the same hmp domain */
6154 ilb = cpumask_first_and(nohz.idle_cpus_mask,
6155 &((struct hmp_domain *)hmp_cpu_domain(call_cpu))->cpus);
6157 if (ilb < nr_cpu_ids && idle_cpu(ilb))
6164 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
6165 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
6166 * CPU (if there is one).
6168 static void nohz_balancer_kick(int cpu)
6172 nohz.next_balance++;
6174 ilb_cpu = find_new_ilb(cpu);
6176 if (ilb_cpu >= nr_cpu_ids)
6179 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
6182 * Use smp_send_reschedule() instead of resched_cpu().
6183 * This way we generate a sched IPI on the target cpu which
6184 * is idle. And the softirq performing nohz idle load balance
6185 * will be run before returning from the IPI.
6187 smp_send_reschedule(ilb_cpu);
6191 static inline void nohz_balance_exit_idle(int cpu)
6193 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
6194 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
6195 atomic_dec(&nohz.nr_cpus);
6196 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
6200 static inline void set_cpu_sd_state_busy(void)
6202 struct sched_domain *sd;
6203 int cpu = smp_processor_id();
6206 sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd);
6208 if (!sd || !sd->nohz_idle)
6212 for (; sd; sd = sd->parent)
6213 atomic_inc(&sd->groups->sgp->nr_busy_cpus);
6218 void set_cpu_sd_state_idle(void)
6220 struct sched_domain *sd;
6221 int cpu = smp_processor_id();
6224 sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd);
6226 if (!sd || sd->nohz_idle)
6230 for (; sd; sd = sd->parent)
6231 atomic_dec(&sd->groups->sgp->nr_busy_cpus);
6237 * This routine will record that the cpu is going idle with tick stopped.
6238 * This info will be used in performing idle load balancing in the future.
6240 void nohz_balance_enter_idle(int cpu)
6243 * If this cpu is going down, then nothing needs to be done.
6245 if (!cpu_active(cpu))
6248 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
6251 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
6252 atomic_inc(&nohz.nr_cpus);
6253 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
6256 static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
6257 unsigned long action, void *hcpu)
6259 switch (action & ~CPU_TASKS_FROZEN) {
6261 nohz_balance_exit_idle(smp_processor_id());
6269 static DEFINE_SPINLOCK(balancing);
6272 * Scale the max load_balance interval with the number of CPUs in the system.
6273 * This trades load-balance latency on larger machines for less cross talk.
6275 void update_max_interval(void)
6277 max_load_balance_interval = HZ*num_online_cpus()/10;
6281 * It checks each scheduling domain to see if it is due to be balanced,
6282 * and initiates a balancing operation if so.
6284 * Balancing parameters are set up in init_sched_domains.
6286 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
6289 struct rq *rq = cpu_rq(cpu);
6290 unsigned long interval;
6291 struct sched_domain *sd;
6292 /* Earliest time when we have to do rebalance again */
6293 unsigned long next_balance = jiffies + 60*HZ;
6294 int update_next_balance = 0;
6297 update_blocked_averages(cpu);
6300 for_each_domain(cpu, sd) {
6301 if (!(sd->flags & SD_LOAD_BALANCE))
6304 interval = sd->balance_interval;
6305 if (idle != CPU_IDLE)
6306 interval *= sd->busy_factor;
6308 /* scale ms to jiffies */
6309 interval = msecs_to_jiffies(interval);
6310 interval = clamp(interval, 1UL, max_load_balance_interval);
6312 need_serialize = sd->flags & SD_SERIALIZE;
6314 if (need_serialize) {
6315 if (!spin_trylock(&balancing))
6319 if (time_after_eq(jiffies, sd->last_balance + interval)) {
6320 if (load_balance(cpu, rq, sd, idle, &balance)) {
6322 * The LBF_SOME_PINNED logic could have changed
6323 * env->dst_cpu, so we can't know our idle
6324 * state even if we migrated tasks. Update it.
6326 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
6328 sd->last_balance = jiffies;
6331 spin_unlock(&balancing);
6333 if (time_after(next_balance, sd->last_balance + interval)) {
6334 next_balance = sd->last_balance + interval;
6335 update_next_balance = 1;
6339 * Stop the load balance at this level. There is another
6340 * CPU in our sched group which is doing load balancing more
6349 * next_balance will be updated only when there is a need.
6350 * When the cpu is attached to null domain for ex, it will not be
6353 if (likely(update_next_balance))
6354 rq->next_balance = next_balance;
6357 #ifdef CONFIG_NO_HZ_COMMON
6359 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
6360 * rebalancing for all the cpus for whom scheduler ticks are stopped.
6362 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
6364 struct rq *this_rq = cpu_rq(this_cpu);
6368 if (idle != CPU_IDLE ||
6369 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
6372 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
6373 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
6377 * If this cpu gets work to do, stop the load balancing
6378 * work being done for other cpus. Next load
6379 * balancing owner will pick it up.
6384 rq = cpu_rq(balance_cpu);
6386 raw_spin_lock_irq(&rq->lock);
6387 update_rq_clock(rq);
6388 update_idle_cpu_load(rq);
6389 raw_spin_unlock_irq(&rq->lock);
6391 rebalance_domains(balance_cpu, CPU_IDLE);
6393 if (time_after(this_rq->next_balance, rq->next_balance))
6394 this_rq->next_balance = rq->next_balance;
6396 nohz.next_balance = this_rq->next_balance;
6398 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
6402 * Current heuristic for kicking the idle load balancer in the presence
6403 * of an idle cpu is the system.
6404 * - This rq has more than one task.
6405 * - At any scheduler domain level, this cpu's scheduler group has multiple
6406 * busy cpu's exceeding the group's power.
6407 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
6408 * domain span are idle.
6410 static inline int nohz_kick_needed(struct rq *rq, int cpu)
6412 unsigned long now = jiffies;
6413 struct sched_domain *sd;
6415 if (unlikely(idle_cpu(cpu)))
6419 * We may be recently in ticked or tickless idle mode. At the first
6420 * busy tick after returning from idle, we will update the busy stats.
6422 set_cpu_sd_state_busy();
6423 nohz_balance_exit_idle(cpu);
6426 * None are in tickless mode and hence no need for NOHZ idle load
6429 if (likely(!atomic_read(&nohz.nr_cpus)))
6432 if (time_before(now, nohz.next_balance))
6435 #ifdef CONFIG_SCHED_HMP
6437 * Bail out if there are no nohz CPUs in our
6438 * HMP domain, since we will move tasks between
6439 * domains through wakeup and force balancing
6440 * as necessary based upon task load.
6442 if (cpumask_first_and(nohz.idle_cpus_mask,
6443 &((struct hmp_domain *)hmp_cpu_domain(cpu))->cpus) >= nr_cpu_ids)
6447 if (rq->nr_running >= 2)
6451 for_each_domain(cpu, sd) {
6452 struct sched_group *sg = sd->groups;
6453 struct sched_group_power *sgp = sg->sgp;
6454 int nr_busy = atomic_read(&sgp->nr_busy_cpus);
6456 if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
6457 goto need_kick_unlock;
6459 if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
6460 && (cpumask_first_and(nohz.idle_cpus_mask,
6461 sched_domain_span(sd)) < cpu))
6462 goto need_kick_unlock;
6464 if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
6476 static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
6479 #ifdef CONFIG_SCHED_HMP
6480 /* Check if task should migrate to a faster cpu */
6481 static unsigned int hmp_up_migration(int cpu, int *target_cpu, struct sched_entity *se)
6483 struct task_struct *p = task_of(se);
6487 *target_cpu = NR_CPUS;
6489 if (hmp_cpu_is_fastest(cpu))
6492 #ifdef CONFIG_SCHED_HMP_PRIO_FILTER
6493 /* Filter by task priority */
6494 if (p->prio >= hmp_up_prio)
6497 if (se->avg.load_avg_ratio < hmp_up_threshold)
6500 /* Let the task load settle before doing another up migration */
6501 /* hack - always use clock from first online CPU */
6502 now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
6503 if (((now - se->avg.hmp_last_up_migration) >> 10)
6504 < hmp_next_up_threshold)
6507 /* hmp_domain_min_load only returns 0 for an
6508 * idle CPU or 1023 for any partly-busy one.
6509 * Be explicit about requirement for an idle CPU.
6511 if (hmp_domain_min_load(hmp_faster_domain(cpu), target_cpu) != 0)
6514 if (cpumask_intersects(&hmp_faster_domain(cpu)->cpus,
6515 tsk_cpus_allowed(p)))
6521 /* Check if task should migrate to a slower cpu */
6522 static unsigned int hmp_down_migration(int cpu, struct sched_entity *se)
6524 struct task_struct *p = task_of(se);
6527 if (hmp_cpu_is_slowest(cpu))
6530 #ifdef CONFIG_SCHED_HMP_PRIO_FILTER
6531 /* Filter by task priority */
6532 if ((p->prio >= hmp_up_prio) &&
6533 cpumask_intersects(&hmp_slower_domain(cpu)->cpus,
6534 tsk_cpus_allowed(p))) {
6539 /* Let the task load settle before doing another down migration */
6540 /* hack - always use clock from first online CPU */
6541 now = cpu_rq(cpumask_first(cpu_online_mask))->clock_task;
6542 if (((now - se->avg.hmp_last_down_migration) >> 10)
6543 < hmp_next_down_threshold)
6546 if (cpumask_intersects(&hmp_slower_domain(cpu)->cpus,
6547 tsk_cpus_allowed(p))
6548 && se->avg.load_avg_ratio < hmp_down_threshold) {
6555 * hmp_can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
6556 * Ideally this function should be merged with can_migrate_task() to avoid
6559 static int hmp_can_migrate_task(struct task_struct *p, struct lb_env *env)
6561 int tsk_cache_hot = 0;
6564 * We do not migrate tasks that are:
6565 * 1) running (obviously), or
6566 * 2) cannot be migrated to this CPU due to cpus_allowed
6568 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
6569 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
6572 env->flags &= ~LBF_ALL_PINNED;
6574 if (task_running(env->src_rq, p)) {
6575 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
6580 * Aggressive migration if:
6581 * 1) task is cache cold, or
6582 * 2) too many balance attempts have failed.
6585 tsk_cache_hot = task_hot(p, env->src_rq->clock_task, env->sd);
6586 if (!tsk_cache_hot ||
6587 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
6588 #ifdef CONFIG_SCHEDSTATS
6589 if (tsk_cache_hot) {
6590 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
6591 schedstat_inc(p, se.statistics.nr_forced_migrations);
6601 * move_specific_task tries to move a specific task.
6602 * Returns 1 if successful and 0 otherwise.
6603 * Called with both runqueues locked.
6605 static int move_specific_task(struct lb_env *env, struct task_struct *pm)
6607 struct task_struct *p, *n;
6609 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
6610 if (throttled_lb_pair(task_group(p), env->src_rq->cpu,
6614 if (!hmp_can_migrate_task(p, env))
6616 /* Check if we found the right task */
6622 * Right now, this is only the third place move_task()
6623 * is called, so we can safely collect move_task()
6624 * stats here rather than inside move_task().
6626 schedstat_inc(env->sd, lb_gained[env->idle]);
6633 * hmp_active_task_migration_cpu_stop is run by cpu stopper and used to
6634 * migrate a specific task from one runqueue to another.
6635 * hmp_force_up_migration uses this to push a currently running task
6637 * Based on active_load_balance_stop_cpu and can potentially be merged.
6639 static int hmp_active_task_migration_cpu_stop(void *data)
6641 struct rq *busiest_rq = data;
6642 struct task_struct *p = busiest_rq->migrate_task;
6643 int busiest_cpu = cpu_of(busiest_rq);
6644 int target_cpu = busiest_rq->push_cpu;
6645 struct rq *target_rq = cpu_rq(target_cpu);
6646 struct sched_domain *sd;
6648 raw_spin_lock_irq(&busiest_rq->lock);
6649 /* make sure the requested cpu hasn't gone down in the meantime */
6650 if (unlikely(busiest_cpu != smp_processor_id() ||
6651 !busiest_rq->active_balance)) {
6654 /* Is there any task to move? */
6655 if (busiest_rq->nr_running <= 1)
6657 /* Task has migrated meanwhile, abort forced migration */
6658 if (task_rq(p) != busiest_rq)
6661 * This condition is "impossible", if it occurs
6662 * we need to fix it. Originally reported by
6663 * Bjorn Helgaas on a 128-cpu setup.
6665 BUG_ON(busiest_rq == target_rq);
6667 /* move a task from busiest_rq to target_rq */
6668 double_lock_balance(busiest_rq, target_rq);
6670 /* Search for an sd spanning us and the target CPU. */
6672 for_each_domain(target_cpu, sd) {
6673 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
6678 struct lb_env env = {
6680 .dst_cpu = target_cpu,
6681 .dst_rq = target_rq,
6682 .src_cpu = busiest_rq->cpu,
6683 .src_rq = busiest_rq,
6687 schedstat_inc(sd, alb_count);
6689 if (move_specific_task(&env, p))
6690 schedstat_inc(sd, alb_pushed);
6692 schedstat_inc(sd, alb_failed);
6695 double_unlock_balance(busiest_rq, target_rq);
6697 busiest_rq->active_balance = 0;
6698 raw_spin_unlock_irq(&busiest_rq->lock);
6703 * hmp_idle_pull_cpu_stop is run by cpu stopper and used to
6704 * migrate a specific task from one runqueue to another.
6705 * hmp_idle_pull uses this to push a currently running task
6706 * off a runqueue to a faster CPU.
6707 * Locking is slightly different than usual.
6708 * Based on active_load_balance_stop_cpu and can potentially be merged.
6710 static int hmp_idle_pull_cpu_stop(void *data)
6712 struct rq *busiest_rq = data;
6713 struct task_struct *p = busiest_rq->migrate_task;
6714 int busiest_cpu = cpu_of(busiest_rq);
6715 int target_cpu = busiest_rq->push_cpu;
6716 struct rq *target_rq = cpu_rq(target_cpu);
6717 struct sched_domain *sd;
6719 raw_spin_lock_irq(&busiest_rq->lock);
6721 /* make sure the requested cpu hasn't gone down in the meantime */
6722 if (unlikely(busiest_cpu != smp_processor_id() ||
6723 !busiest_rq->active_balance))
6726 /* Is there any task to move? */
6727 if (busiest_rq->nr_running <= 1)
6730 /* Task has migrated meanwhile, abort forced migration */
6731 if (task_rq(p) != busiest_rq)
6735 * This condition is "impossible", if it occurs
6736 * we need to fix it. Originally reported by
6737 * Bjorn Helgaas on a 128-cpu setup.
6739 BUG_ON(busiest_rq == target_rq);
6741 /* move a task from busiest_rq to target_rq */
6742 double_lock_balance(busiest_rq, target_rq);
6744 /* Search for an sd spanning us and the target CPU. */
6746 for_each_domain(target_cpu, sd) {
6747 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
6751 struct lb_env env = {
6753 .dst_cpu = target_cpu,
6754 .dst_rq = target_rq,
6755 .src_cpu = busiest_rq->cpu,
6756 .src_rq = busiest_rq,
6760 schedstat_inc(sd, alb_count);
6762 if (move_specific_task(&env, p))
6763 schedstat_inc(sd, alb_pushed);
6765 schedstat_inc(sd, alb_failed);
6768 double_unlock_balance(busiest_rq, target_rq);
6770 busiest_rq->active_balance = 0;
6771 raw_spin_unlock_irq(&busiest_rq->lock);
6775 static DEFINE_SPINLOCK(hmp_force_migration);
6778 * hmp_force_up_migration checks runqueues for tasks that need to
6779 * be actively migrated to a faster cpu.
6781 static void hmp_force_up_migration(int this_cpu)
6783 int cpu, target_cpu;
6784 struct sched_entity *curr, *orig;
6786 unsigned long flags;
6788 struct task_struct *p;
6790 if (!spin_trylock(&hmp_force_migration))
6792 for_each_online_cpu(cpu) {
6794 target = cpu_rq(cpu);
6795 raw_spin_lock_irqsave(&target->lock, flags);
6796 curr = target->cfs.curr;
6798 raw_spin_unlock_irqrestore(&target->lock, flags);
6801 if (!entity_is_task(curr)) {
6802 struct cfs_rq *cfs_rq;
6804 cfs_rq = group_cfs_rq(curr);
6806 curr = cfs_rq->curr;
6807 cfs_rq = group_cfs_rq(curr);
6811 curr = hmp_get_heaviest_task(curr, 1);
6813 if (hmp_up_migration(cpu, &target_cpu, curr)) {
6814 if (!target->active_balance) {
6815 target->active_balance = 1;
6816 target->push_cpu = target_cpu;
6817 target->migrate_task = p;
6819 trace_sched_hmp_migrate(p, target->push_cpu, 1);
6820 hmp_next_up_delay(&p->se, target->push_cpu);
6823 if (!force && !target->active_balance) {
6825 * For now we just check the currently running task.
6826 * Selecting the lightest task for offloading will
6827 * require extensive book keeping.
6829 curr = hmp_get_lightest_task(orig, 1);
6830 target->push_cpu = hmp_offload_down(cpu, curr);
6831 if (target->push_cpu < NR_CPUS) {
6832 target->active_balance = 1;
6833 target->migrate_task = p;
6835 trace_sched_hmp_migrate(p, target->push_cpu, 2);
6836 hmp_next_down_delay(&p->se, target->push_cpu);
6839 raw_spin_unlock_irqrestore(&target->lock, flags);
6841 stop_one_cpu_nowait(cpu_of(target),
6842 hmp_active_task_migration_cpu_stop,
6843 target, &target->active_balance_work);
6845 spin_unlock(&hmp_force_migration);
6848 * hmp_idle_pull looks at little domain runqueues to see
6849 * if a task should be pulled.
6851 * Reuses hmp_force_migration spinlock.
6854 static unsigned int hmp_idle_pull(int this_cpu)
6857 struct sched_entity *curr, *orig;
6858 struct hmp_domain *hmp_domain = NULL;
6859 struct rq *target, *rq;
6860 unsigned long flags, ratio = 0;
6861 unsigned int force = 0;
6862 struct task_struct *p = NULL;
6864 if (!hmp_cpu_is_slowest(this_cpu))
6865 hmp_domain = hmp_slower_domain(this_cpu);
6869 if (!spin_trylock(&hmp_force_migration))
6872 /* first select a task */
6873 for_each_cpu(cpu, &hmp_domain->cpus) {
6875 raw_spin_lock_irqsave(&rq->lock, flags);
6876 curr = rq->cfs.curr;
6878 raw_spin_unlock_irqrestore(&rq->lock, flags);
6881 if (!entity_is_task(curr)) {
6882 struct cfs_rq *cfs_rq;
6884 cfs_rq = group_cfs_rq(curr);
6886 curr = cfs_rq->curr;
6887 if (!entity_is_task(curr))
6888 cfs_rq = group_cfs_rq(curr);
6894 curr = hmp_get_heaviest_task(curr, 1);
6895 if (curr->avg.load_avg_ratio > hmp_up_threshold &&
6896 curr->avg.load_avg_ratio > ratio) {
6899 ratio = curr->avg.load_avg_ratio;
6901 raw_spin_unlock_irqrestore(&rq->lock, flags);
6907 /* now we have a candidate */
6908 raw_spin_lock_irqsave(&target->lock, flags);
6909 if (!target->active_balance && task_rq(p) == target) {
6910 target->active_balance = 1;
6911 target->push_cpu = this_cpu;
6912 target->migrate_task = p;
6914 trace_sched_hmp_migrate(p, target->push_cpu, 3);
6915 hmp_next_up_delay(&p->se, target->push_cpu);
6917 raw_spin_unlock_irqrestore(&target->lock, flags);
6919 stop_one_cpu_nowait(cpu_of(target),
6920 hmp_idle_pull_cpu_stop,
6921 target, &target->active_balance_work);
6924 spin_unlock(&hmp_force_migration);
6928 static void hmp_force_up_migration(int this_cpu) { }
6929 #endif /* CONFIG_SCHED_HMP */
6932 * run_rebalance_domains is triggered when needed from the scheduler tick.
6933 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
6935 static void run_rebalance_domains(struct softirq_action *h)
6937 int this_cpu = smp_processor_id();
6938 struct rq *this_rq = cpu_rq(this_cpu);
6939 enum cpu_idle_type idle = this_rq->idle_balance ?
6940 CPU_IDLE : CPU_NOT_IDLE;
6942 hmp_force_up_migration(this_cpu);
6944 rebalance_domains(this_cpu, idle);
6947 * If this cpu has a pending nohz_balance_kick, then do the
6948 * balancing on behalf of the other idle cpus whose ticks are
6951 nohz_idle_balance(this_cpu, idle);
6954 static inline int on_null_domain(int cpu)
6956 return !rcu_dereference_sched(cpu_rq(cpu)->sd);
6960 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
6962 void trigger_load_balance(struct rq *rq, int cpu)
6964 /* Don't need to rebalance while attached to NULL domain */
6965 if (time_after_eq(jiffies, rq->next_balance) &&
6966 likely(!on_null_domain(cpu)))
6967 raise_softirq(SCHED_SOFTIRQ);
6968 #ifdef CONFIG_NO_HZ_COMMON
6969 if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
6970 nohz_balancer_kick(cpu);
6974 static void rq_online_fair(struct rq *rq)
6976 #ifdef CONFIG_SCHED_HMP
6977 hmp_online_cpu(rq->cpu);
6982 static void rq_offline_fair(struct rq *rq)
6984 #ifdef CONFIG_SCHED_HMP
6985 hmp_offline_cpu(rq->cpu);
6989 /* Ensure any throttled groups are reachable by pick_next_task */
6990 unthrottle_offline_cfs_rqs(rq);
6993 #endif /* CONFIG_SMP */
6996 * scheduler tick hitting a task of our scheduling class:
6998 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
7000 struct cfs_rq *cfs_rq;
7001 struct sched_entity *se = &curr->se;
7003 for_each_sched_entity(se) {
7004 cfs_rq = cfs_rq_of(se);
7005 entity_tick(cfs_rq, se, queued);
7008 if (sched_feat_numa(NUMA))
7009 task_tick_numa(rq, curr);
7011 update_rq_runnable_avg(rq, 1);
7015 * called on fork with the child task as argument from the parent's context
7016 * - child not yet on the tasklist
7017 * - preemption disabled
7019 static void task_fork_fair(struct task_struct *p)
7021 struct cfs_rq *cfs_rq;
7022 struct sched_entity *se = &p->se, *curr;
7023 int this_cpu = smp_processor_id();
7024 struct rq *rq = this_rq();
7025 unsigned long flags;
7027 raw_spin_lock_irqsave(&rq->lock, flags);
7029 update_rq_clock(rq);
7031 cfs_rq = task_cfs_rq(current);
7032 curr = cfs_rq->curr;
7034 if (unlikely(task_cpu(p) != this_cpu)) {
7036 __set_task_cpu(p, this_cpu);
7040 update_curr(cfs_rq);
7043 se->vruntime = curr->vruntime;
7044 place_entity(cfs_rq, se, 1);
7046 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
7048 * Upon rescheduling, sched_class::put_prev_task() will place
7049 * 'current' within the tree based on its new key value.
7051 swap(curr->vruntime, se->vruntime);
7052 resched_task(rq->curr);
7055 se->vruntime -= cfs_rq->min_vruntime;
7057 raw_spin_unlock_irqrestore(&rq->lock, flags);
7061 * Priority of the task has changed. Check to see if we preempt
7065 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
7071 * Reschedule if we are currently running on this runqueue and
7072 * our priority decreased, or if we are not currently running on
7073 * this runqueue and our priority is higher than the current's
7075 if (rq->curr == p) {
7076 if (p->prio > oldprio)
7077 resched_task(rq->curr);
7079 check_preempt_curr(rq, p, 0);
7082 static void switched_from_fair(struct rq *rq, struct task_struct *p)
7084 struct sched_entity *se = &p->se;
7085 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7088 * Ensure the task's vruntime is normalized, so that when its
7089 * switched back to the fair class the enqueue_entity(.flags=0) will
7090 * do the right thing.
7092 * If it was on_rq, then the dequeue_entity(.flags=0) will already
7093 * have normalized the vruntime, if it was !on_rq, then only when
7094 * the task is sleeping will it still have non-normalized vruntime.
7096 if (!se->on_rq && p->state != TASK_RUNNING) {
7098 * Fix up our vruntime so that the current sleep doesn't
7099 * cause 'unlimited' sleep bonus.
7101 place_entity(cfs_rq, se, 0);
7102 se->vruntime -= cfs_rq->min_vruntime;
7105 #if defined(CONFIG_FAIR_GROUP_SCHED) && defined(CONFIG_SMP)
7107 * Remove our load from contribution when we leave sched_fair
7108 * and ensure we don't carry in an old decay_count if we
7111 if (p->se.avg.decay_count) {
7112 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
7113 __synchronize_entity_decay(&p->se);
7114 subtract_blocked_load_contrib(cfs_rq,
7115 p->se.avg.load_avg_contrib);
7121 * We switched to the sched_fair class.
7123 static void switched_to_fair(struct rq *rq, struct task_struct *p)
7129 * We were most likely switched from sched_rt, so
7130 * kick off the schedule if running, otherwise just see
7131 * if we can still preempt the current task.
7134 resched_task(rq->curr);
7136 check_preempt_curr(rq, p, 0);
7139 /* Account for a task changing its policy or group.
7141 * This routine is mostly called to set cfs_rq->curr field when a task
7142 * migrates between groups/classes.
7144 static void set_curr_task_fair(struct rq *rq)
7146 struct sched_entity *se = &rq->curr->se;
7148 for_each_sched_entity(se) {
7149 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7151 set_next_entity(cfs_rq, se);
7152 /* ensure bandwidth has been allocated on our new cfs_rq */
7153 account_cfs_rq_runtime(cfs_rq, 0);
7157 void init_cfs_rq(struct cfs_rq *cfs_rq)
7159 cfs_rq->tasks_timeline = RB_ROOT;
7160 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7161 #ifndef CONFIG_64BIT
7162 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
7164 #if defined(CONFIG_FAIR_GROUP_SCHED) && defined(CONFIG_SMP)
7165 atomic64_set(&cfs_rq->decay_counter, 1);
7166 atomic64_set(&cfs_rq->removed_load, 0);
7170 #ifdef CONFIG_FAIR_GROUP_SCHED
7171 static void task_move_group_fair(struct task_struct *p, int on_rq)
7173 struct cfs_rq *cfs_rq;
7175 * If the task was not on the rq at the time of this cgroup movement
7176 * it must have been asleep, sleeping tasks keep their ->vruntime
7177 * absolute on their old rq until wakeup (needed for the fair sleeper
7178 * bonus in place_entity()).
7180 * If it was on the rq, we've just 'preempted' it, which does convert
7181 * ->vruntime to a relative base.
7183 * Make sure both cases convert their relative position when migrating
7184 * to another cgroup's rq. This does somewhat interfere with the
7185 * fair sleeper stuff for the first placement, but who cares.
7188 * When !on_rq, vruntime of the task has usually NOT been normalized.
7189 * But there are some cases where it has already been normalized:
7191 * - Moving a forked child which is waiting for being woken up by
7192 * wake_up_new_task().
7193 * - Moving a task which has been woken up by try_to_wake_up() and
7194 * waiting for actually being woken up by sched_ttwu_pending().
7196 * To prevent boost or penalty in the new cfs_rq caused by delta
7197 * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
7199 if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
7203 p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
7204 set_task_rq(p, task_cpu(p));
7206 cfs_rq = cfs_rq_of(&p->se);
7207 p->se.vruntime += cfs_rq->min_vruntime;
7210 * migrate_task_rq_fair() will have removed our previous
7211 * contribution, but we must synchronize for ongoing future
7214 p->se.avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
7215 cfs_rq->blocked_load_avg += p->se.avg.load_avg_contrib;
7220 void free_fair_sched_group(struct task_group *tg)
7224 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
7226 for_each_possible_cpu(i) {
7228 kfree(tg->cfs_rq[i]);
7237 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7239 struct cfs_rq *cfs_rq;
7240 struct sched_entity *se;
7243 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
7246 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
7250 tg->shares = NICE_0_LOAD;
7252 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
7254 for_each_possible_cpu(i) {
7255 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
7256 GFP_KERNEL, cpu_to_node(i));
7260 se = kzalloc_node(sizeof(struct sched_entity),
7261 GFP_KERNEL, cpu_to_node(i));
7265 init_cfs_rq(cfs_rq);
7266 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
7277 void unregister_fair_sched_group(struct task_group *tg, int cpu)
7279 struct rq *rq = cpu_rq(cpu);
7280 unsigned long flags;
7283 * Only empty task groups can be destroyed; so we can speculatively
7284 * check on_list without danger of it being re-added.
7286 if (!tg->cfs_rq[cpu]->on_list)
7289 raw_spin_lock_irqsave(&rq->lock, flags);
7290 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
7291 raw_spin_unlock_irqrestore(&rq->lock, flags);
7294 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7295 struct sched_entity *se, int cpu,
7296 struct sched_entity *parent)
7298 struct rq *rq = cpu_rq(cpu);
7302 init_cfs_rq_runtime(cfs_rq);
7304 tg->cfs_rq[cpu] = cfs_rq;
7307 /* se could be NULL for root_task_group */
7312 se->cfs_rq = &rq->cfs;
7314 se->cfs_rq = parent->my_q;
7317 update_load_set(&se->load, 0);
7318 se->parent = parent;
7321 static DEFINE_MUTEX(shares_mutex);
7323 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7326 unsigned long flags;
7329 * We can't change the weight of the root cgroup.
7334 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
7336 mutex_lock(&shares_mutex);
7337 if (tg->shares == shares)
7340 tg->shares = shares;
7341 for_each_possible_cpu(i) {
7342 struct rq *rq = cpu_rq(i);
7343 struct sched_entity *se;
7346 /* Propagate contribution to hierarchy */
7347 raw_spin_lock_irqsave(&rq->lock, flags);
7348 for_each_sched_entity(se)
7349 update_cfs_shares(group_cfs_rq(se));
7350 raw_spin_unlock_irqrestore(&rq->lock, flags);
7354 mutex_unlock(&shares_mutex);
7357 #else /* CONFIG_FAIR_GROUP_SCHED */
7359 void free_fair_sched_group(struct task_group *tg) { }
7361 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7366 void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
7368 #endif /* CONFIG_FAIR_GROUP_SCHED */
7371 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
7373 struct sched_entity *se = &task->se;
7374 unsigned int rr_interval = 0;
7377 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
7380 if (rq->cfs.load.weight)
7381 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
7387 * All the scheduling class methods:
7389 const struct sched_class fair_sched_class = {
7390 .next = &idle_sched_class,
7391 .enqueue_task = enqueue_task_fair,
7392 .dequeue_task = dequeue_task_fair,
7393 .yield_task = yield_task_fair,
7394 .yield_to_task = yield_to_task_fair,
7396 .check_preempt_curr = check_preempt_wakeup,
7398 .pick_next_task = pick_next_task_fair,
7399 .put_prev_task = put_prev_task_fair,
7402 .select_task_rq = select_task_rq_fair,
7403 #ifdef CONFIG_FAIR_GROUP_SCHED
7404 .migrate_task_rq = migrate_task_rq_fair,
7406 .rq_online = rq_online_fair,
7407 .rq_offline = rq_offline_fair,
7409 .task_waking = task_waking_fair,
7412 .set_curr_task = set_curr_task_fair,
7413 .task_tick = task_tick_fair,
7414 .task_fork = task_fork_fair,
7416 .prio_changed = prio_changed_fair,
7417 .switched_from = switched_from_fair,
7418 .switched_to = switched_to_fair,
7420 .get_rr_interval = get_rr_interval_fair,
7422 #ifdef CONFIG_FAIR_GROUP_SCHED
7423 .task_move_group = task_move_group_fair,
7427 #ifdef CONFIG_SCHED_DEBUG
7428 void print_cfs_stats(struct seq_file *m, int cpu)
7430 struct cfs_rq *cfs_rq;
7433 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
7434 print_cfs_rq(m, cpu, cfs_rq);
7439 __init void init_sched_fair_class(void)
7442 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
7444 #ifdef CONFIG_NO_HZ_COMMON
7445 nohz.next_balance = jiffies;
7446 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
7447 cpu_notifier(sched_ilb_notifier, 0);
7450 #ifdef CONFIG_SCHED_HMP
7451 hmp_cpu_mask_setup();
7457 #ifdef CONFIG_HMP_FREQUENCY_INVARIANT_SCALE
7458 static u32 cpufreq_calc_scale(u32 min, u32 max, u32 curr)
7460 u32 result = curr / max;
7464 /* Called when the CPU Frequency is changed.
7465 * Once for each CPU.
7467 static int cpufreq_callback(struct notifier_block *nb,
7468 unsigned long val, void *data)
7470 struct cpufreq_freqs *freq = data;
7471 int cpu = freq->cpu;
7472 struct cpufreq_extents *extents;
7474 if (freq->flags & CPUFREQ_CONST_LOOPS)
7477 if (val != CPUFREQ_POSTCHANGE)
7480 /* if dynamic load scale is disabled, set the load scale to 1.0 */
7481 if (!hmp_data.freqinvar_load_scale_enabled) {
7482 freq_scale[cpu].curr_scale = 1024;
7486 extents = &freq_scale[cpu];
7487 if (extents->flags & SCHED_LOAD_FREQINVAR_SINGLEFREQ) {
7488 /* If our governor was recognised as a single-freq governor,
7491 extents->curr_scale = 1024;
7493 extents->curr_scale = cpufreq_calc_scale(extents->min,
7494 extents->max, freq->new);
7500 /* Called when the CPUFreq governor is changed.
7501 * Only called for the CPUs which are actually changed by the
7504 static int cpufreq_policy_callback(struct notifier_block *nb,
7505 unsigned long event, void *data)
7507 struct cpufreq_policy *policy = data;
7508 struct cpufreq_extents *extents;
7509 int cpu, singleFreq = 0;
7510 static const char performance_governor[] = "performance";
7511 static const char powersave_governor[] = "powersave";
7513 if (event == CPUFREQ_START)
7516 if (event != CPUFREQ_INCOMPATIBLE)
7519 /* CPUFreq governors do not accurately report the range of
7520 * CPU Frequencies they will choose from.
7521 * We recognise performance and powersave governors as
7522 * single-frequency only.
7524 if (!strncmp(policy->governor->name, performance_governor,
7525 strlen(performance_governor)) ||
7526 !strncmp(policy->governor->name, powersave_governor,
7527 strlen(powersave_governor)))
7530 /* Make sure that all CPUs impacted by this policy are
7531 * updated since we will only get a notification when the
7532 * user explicitly changes the policy on a CPU.
7534 for_each_cpu(cpu, policy->cpus) {
7535 extents = &freq_scale[cpu];
7536 extents->max = policy->max >> SCHED_FREQSCALE_SHIFT;
7537 extents->min = policy->min >> SCHED_FREQSCALE_SHIFT;
7538 if (!hmp_data.freqinvar_load_scale_enabled) {
7539 extents->curr_scale = 1024;
7540 } else if (singleFreq) {
7541 extents->flags |= SCHED_LOAD_FREQINVAR_SINGLEFREQ;
7542 extents->curr_scale = 1024;
7544 extents->flags &= ~SCHED_LOAD_FREQINVAR_SINGLEFREQ;
7545 extents->curr_scale = cpufreq_calc_scale(extents->min,
7546 extents->max, policy->cur);
7553 static struct notifier_block cpufreq_notifier = {
7554 .notifier_call = cpufreq_callback,
7556 static struct notifier_block cpufreq_policy_notifier = {
7557 .notifier_call = cpufreq_policy_callback,
7560 static int __init register_sched_cpufreq_notifier(void)
7564 /* init safe defaults since there are no policies at registration */
7565 for (ret = 0; ret < CONFIG_NR_CPUS; ret++) {
7567 freq_scale[ret].max = 1024;
7568 freq_scale[ret].min = 1024;
7569 freq_scale[ret].curr_scale = 1024;
7572 pr_info("sched: registering cpufreq notifiers for scale-invariant loads\n");
7573 ret = cpufreq_register_notifier(&cpufreq_policy_notifier,
7574 CPUFREQ_POLICY_NOTIFIER);
7577 ret = cpufreq_register_notifier(&cpufreq_notifier,
7578 CPUFREQ_TRANSITION_NOTIFIER);
7583 core_initcall(register_sched_cpufreq_notifier);
7584 #endif /* CONFIG_HMP_FREQUENCY_INVARIANT_SCALE */