When possible, choose a preferred CPUs to pick. This is essential to maintain user affinities when preferred CPUs change. A task pinned on non-preferred CPU should continue to run there, since this is non-user triggered.
If CPU is non-preferred and task can run on other CPUs which are currently preferred, then choose those other CPUs instead. This is decided by checking cpus_ptr and cpu_preferred_mask intersect or not. If yes, task has other preferred CPUs, it can run there instead. Overhead is minimal when CPU is preferred. Push task mechanism uses stopper thread which going to call select_fallback_rq and use this mechanism to pick only a preferred CPU. This takes care of wakeup path for FAIR tasks too. is_cpu_allowed is called to ensure wakeup happens on preferred CPUs. With that, additional checks in available_idle_cpu is not necessary. For majority of the cases this would still keep select_fallback_rq as O(N). task_has_preferred_cpus which is O(N) is called only if !cpu_preferred. Then task running there is expected to move out. So subsequent it should run on preferred CPU. This becomes O(N**2) only for tasks pinned only non preferred CPUs. That is rare case. Signed-off-by: Shrikanth Hegde <[email protected]> --- kernel/sched/core.c | 12 ++++++++++-- kernel/sched/sched.h | 12 ++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/kernel/sched/core.c b/kernel/sched/core.c index a45f7c308329..9e8eec4451b6 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -2509,8 +2509,12 @@ static inline bool is_cpu_allowed(struct task_struct *p, int cpu) return cpu_online(cpu); /* Non kernel threads are not allowed during either online or offline. */ - if (!(p->flags & PF_KTHREAD)) + if (!(p->flags & PF_KTHREAD)) { + /* Try to use preferred CPU if task's affinity allows */ + if (task_can_sched_on_preferred(cpu, p)) + return false; return cpu_active(cpu); + } /* KTHREAD_IS_PER_CPU is always allowed. */ if (kthread_is_per_cpu(p)) @@ -2520,7 +2524,11 @@ static inline bool is_cpu_allowed(struct task_struct *p, int cpu) if (cpu_dying(cpu)) return false; - /* But are allowed during online. */ + /* Try to keep unbound kthreads on a preferred CPU if possible. */ + if (task_can_sched_on_preferred(cpu, p)) + return false; + + /* Otherwise, they are allowed to run on online CPU. */ return cpu_online(cpu); } diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 26ae13c86b69..6de6366f2faa 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -4230,4 +4230,16 @@ DEFINE_CLASS_IS_UNCONDITIONAL(sched_change) #include "ext/ext.h" +static inline bool task_can_sched_on_preferred(int cpu, struct task_struct *p) +{ + if (cpu_preferred(cpu)) + return false; + + /* Only FAIR tasks honor preferred CPU state */ + if (unlikely(p->sched_class != &fair_sched_class)) + return false; + + return cpumask_intersects(p->cpus_ptr, cpu_preferred_mask); +} + #endif /* _KERNEL_SCHED_SCHED_H */ -- 2.47.3

