1 // SPDX-License-Identifier: GPL-2.0-only
5 * Core kernel scheduler code and related syscalls
7 * Copyright (C) 1991-2002 Linus Torvalds
9 #include <linux/highmem.h>
10 #include <linux/hrtimer_api.h>
11 #include <linux/ktime_api.h>
12 #include <linux/sched/signal.h>
13 #include <linux/syscalls_api.h>
14 #include <linux/debug_locks.h>
15 #include <linux/prefetch.h>
16 #include <linux/capability.h>
17 #include <linux/pgtable_api.h>
18 #include <linux/wait_bit.h>
19 #include <linux/jiffies.h>
20 #include <linux/spinlock_api.h>
21 #include <linux/cpumask_api.h>
22 #include <linux/lockdep_api.h>
23 #include <linux/hardirq.h>
24 #include <linux/softirq.h>
25 #include <linux/refcount_api.h>
26 #include <linux/topology.h>
27 #include <linux/sched/clock.h>
28 #include <linux/sched/cond_resched.h>
29 #include <linux/sched/debug.h>
30 #include <linux/sched/isolation.h>
31 #include <linux/sched/loadavg.h>
32 #include <linux/sched/mm.h>
33 #include <linux/sched/nohz.h>
34 #include <linux/sched/rseq_api.h>
35 #include <linux/sched/rt.h>
37 #include <linux/blkdev.h>
38 #include <linux/context_tracking.h>
39 #include <linux/cpuset.h>
40 #include <linux/delayacct.h>
41 #include <linux/init_task.h>
42 #include <linux/interrupt.h>
43 #include <linux/ioprio.h>
44 #include <linux/kallsyms.h>
45 #include <linux/kcov.h>
46 #include <linux/kprobes.h>
47 #include <linux/llist_api.h>
48 #include <linux/mmu_context.h>
49 #include <linux/mmzone.h>
50 #include <linux/mutex_api.h>
51 #include <linux/nmi.h>
52 #include <linux/nospec.h>
53 #include <linux/perf_event_api.h>
54 #include <linux/profile.h>
55 #include <linux/psi.h>
56 #include <linux/rcuwait_api.h>
57 #include <linux/sched/wake_q.h>
58 #include <linux/scs.h>
59 #include <linux/slab.h>
60 #include <linux/syscalls.h>
61 #include <linux/vtime.h>
62 #include <linux/wait_api.h>
63 #include <linux/workqueue_api.h>
65 #ifdef CONFIG_PREEMPT_DYNAMIC
66 # ifdef CONFIG_GENERIC_ENTRY
67 # include <linux/entry-common.h>
71 #include <uapi/linux/sched/types.h>
73 #include <asm/switch_to.h>
76 #define CREATE_TRACE_POINTS
77 #include <linux/sched/rseq_api.h>
78 #include <trace/events/sched.h>
79 #undef CREATE_TRACE_POINTS
83 #include "autogroup.h"
85 #include "autogroup.h"
90 #include "../workqueue_internal.h"
91 #include "../../fs/io-wq.h"
92 #include "../smpboot.h"
95 * Export tracepoints that act as a bare tracehook (ie: have no trace event
96 * associated with them) to allow external modules to probe them.
98 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
99 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
100 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
101 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
102 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
103 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_thermal_tp);
104 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
105 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
106 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
107 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
108 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
110 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
112 #ifdef CONFIG_SCHED_DEBUG
114 * Debugging: various feature bits
116 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
117 * sysctl_sched_features, defined in sched.h, to allow constants propagation
118 * at compile time and compiler optimization based on features default.
120 #define SCHED_FEAT(name, enabled) \
121 (1UL << __SCHED_FEAT_##name) * enabled |
122 const_debug unsigned int sysctl_sched_features =
123 #include "features.h"
128 * Print a warning if need_resched is set for the given duration (if
129 * LATENCY_WARN is enabled).
131 * If sysctl_resched_latency_warn_once is set, only one warning will be shown
134 __read_mostly int sysctl_resched_latency_warn_ms = 100;
135 __read_mostly int sysctl_resched_latency_warn_once = 1;
136 #endif /* CONFIG_SCHED_DEBUG */
139 * Number of tasks to iterate in a single balance run.
140 * Limited because this is done with IRQs disabled.
142 #ifdef CONFIG_PREEMPT_RT
143 const_debug unsigned int sysctl_sched_nr_migrate = 8;
145 const_debug unsigned int sysctl_sched_nr_migrate = 32;
149 * period over which we measure -rt task CPU usage in us.
152 unsigned int sysctl_sched_rt_period = 1000000;
154 __read_mostly int scheduler_running;
156 #ifdef CONFIG_SCHED_CORE
158 DEFINE_STATIC_KEY_FALSE(__sched_core_enabled);
160 /* kernel prio, less is more */
161 static inline int __task_prio(struct task_struct *p)
163 if (p->sched_class == &stop_sched_class) /* trumps deadline */
166 if (rt_prio(p->prio)) /* includes deadline */
167 return p->prio; /* [-1, 99] */
169 if (p->sched_class == &idle_sched_class)
170 return MAX_RT_PRIO + NICE_WIDTH; /* 140 */
172 return MAX_RT_PRIO + MAX_NICE; /* 120, squash fair */
182 /* real prio, less is less */
183 static inline bool prio_less(struct task_struct *a, struct task_struct *b, bool in_fi)
186 int pa = __task_prio(a), pb = __task_prio(b);
194 if (pa == -1) /* dl_prio() doesn't work because of stop_class above */
195 return !dl_time_before(a->dl.deadline, b->dl.deadline);
197 if (pa == MAX_RT_PRIO + MAX_NICE) /* fair */
198 return cfs_prio_less(a, b, in_fi);
203 static inline bool __sched_core_less(struct task_struct *a, struct task_struct *b)
205 if (a->core_cookie < b->core_cookie)
208 if (a->core_cookie > b->core_cookie)
211 /* flip prio, so high prio is leftmost */
212 if (prio_less(b, a, !!task_rq(a)->core->core_forceidle_count))
218 #define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
220 static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b)
222 return __sched_core_less(__node_2_sc(a), __node_2_sc(b));
225 static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node)
227 const struct task_struct *p = __node_2_sc(node);
228 unsigned long cookie = (unsigned long)key;
230 if (cookie < p->core_cookie)
233 if (cookie > p->core_cookie)
239 void sched_core_enqueue(struct rq *rq, struct task_struct *p)
241 rq->core->core_task_seq++;
246 rb_add(&p->core_node, &rq->core_tree, rb_sched_core_less);
249 void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags)
251 rq->core->core_task_seq++;
253 if (sched_core_enqueued(p)) {
254 rb_erase(&p->core_node, &rq->core_tree);
255 RB_CLEAR_NODE(&p->core_node);
259 * Migrating the last task off the cpu, with the cpu in forced idle
260 * state. Reschedule to create an accounting edge for forced idle,
261 * and re-examine whether the core is still in forced idle state.
263 if (!(flags & DEQUEUE_SAVE) && rq->nr_running == 1 &&
264 rq->core->core_forceidle_count && rq->curr == rq->idle)
269 * Find left-most (aka, highest priority) task matching @cookie.
271 static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie)
273 struct rb_node *node;
275 node = rb_find_first((void *)cookie, &rq->core_tree, rb_sched_core_cmp);
277 * The idle task always matches any cookie!
280 return idle_sched_class.pick_task(rq);
282 return __node_2_sc(node);
285 static struct task_struct *sched_core_next(struct task_struct *p, unsigned long cookie)
287 struct rb_node *node = &p->core_node;
289 node = rb_next(node);
293 p = container_of(node, struct task_struct, core_node);
294 if (p->core_cookie != cookie)
301 * Magic required such that:
303 * raw_spin_rq_lock(rq);
305 * raw_spin_rq_unlock(rq);
307 * ends up locking and unlocking the _same_ lock, and all CPUs
308 * always agree on what rq has what lock.
310 * XXX entirely possible to selectively enable cores, don't bother for now.
313 static DEFINE_MUTEX(sched_core_mutex);
314 static atomic_t sched_core_count;
315 static struct cpumask sched_core_mask;
317 static void sched_core_lock(int cpu, unsigned long *flags)
319 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
322 local_irq_save(*flags);
323 for_each_cpu(t, smt_mask)
324 raw_spin_lock_nested(&cpu_rq(t)->__lock, i++);
327 static void sched_core_unlock(int cpu, unsigned long *flags)
329 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
332 for_each_cpu(t, smt_mask)
333 raw_spin_unlock(&cpu_rq(t)->__lock);
334 local_irq_restore(*flags);
337 static void __sched_core_flip(bool enabled)
345 * Toggle the online cores, one by one.
347 cpumask_copy(&sched_core_mask, cpu_online_mask);
348 for_each_cpu(cpu, &sched_core_mask) {
349 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
351 sched_core_lock(cpu, &flags);
353 for_each_cpu(t, smt_mask)
354 cpu_rq(t)->core_enabled = enabled;
356 cpu_rq(cpu)->core->core_forceidle_start = 0;
358 sched_core_unlock(cpu, &flags);
360 cpumask_andnot(&sched_core_mask, &sched_core_mask, smt_mask);
364 * Toggle the offline CPUs.
366 cpumask_copy(&sched_core_mask, cpu_possible_mask);
367 cpumask_andnot(&sched_core_mask, &sched_core_mask, cpu_online_mask);
369 for_each_cpu(cpu, &sched_core_mask)
370 cpu_rq(cpu)->core_enabled = enabled;
375 static void sched_core_assert_empty(void)
379 for_each_possible_cpu(cpu)
380 WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu)->core_tree));
383 static void __sched_core_enable(void)
385 static_branch_enable(&__sched_core_enabled);
387 * Ensure all previous instances of raw_spin_rq_*lock() have finished
388 * and future ones will observe !sched_core_disabled().
391 __sched_core_flip(true);
392 sched_core_assert_empty();
395 static void __sched_core_disable(void)
397 sched_core_assert_empty();
398 __sched_core_flip(false);
399 static_branch_disable(&__sched_core_enabled);
402 void sched_core_get(void)
404 if (atomic_inc_not_zero(&sched_core_count))
407 mutex_lock(&sched_core_mutex);
408 if (!atomic_read(&sched_core_count))
409 __sched_core_enable();
411 smp_mb__before_atomic();
412 atomic_inc(&sched_core_count);
413 mutex_unlock(&sched_core_mutex);
416 static void __sched_core_put(struct work_struct *work)
418 if (atomic_dec_and_mutex_lock(&sched_core_count, &sched_core_mutex)) {
419 __sched_core_disable();
420 mutex_unlock(&sched_core_mutex);
424 void sched_core_put(void)
426 static DECLARE_WORK(_work, __sched_core_put);
429 * "There can be only one"
431 * Either this is the last one, or we don't actually need to do any
432 * 'work'. If it is the last *again*, we rely on
433 * WORK_STRUCT_PENDING_BIT.
435 if (!atomic_add_unless(&sched_core_count, -1, 1))
436 schedule_work(&_work);
439 #else /* !CONFIG_SCHED_CORE */
441 static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { }
443 sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { }
445 #endif /* CONFIG_SCHED_CORE */
448 * part of the period that we allow rt tasks to run in us.
451 int sysctl_sched_rt_runtime = 950000;
455 * Serialization rules:
461 * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
464 * rq2->lock where: rq1 < rq2
468 * Normal scheduling state is serialized by rq->lock. __schedule() takes the
469 * local CPU's rq->lock, it optionally removes the task from the runqueue and
470 * always looks at the local rq data structures to find the most eligible task
473 * Task enqueue is also under rq->lock, possibly taken from another CPU.
474 * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
475 * the local CPU to avoid bouncing the runqueue state around [ see
476 * ttwu_queue_wakelist() ]
478 * Task wakeup, specifically wakeups that involve migration, are horribly
479 * complicated to avoid having to take two rq->locks.
483 * System-calls and anything external will use task_rq_lock() which acquires
484 * both p->pi_lock and rq->lock. As a consequence the state they change is
485 * stable while holding either lock:
487 * - sched_setaffinity()/
488 * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
489 * - set_user_nice(): p->se.load, p->*prio
490 * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
491 * p->se.load, p->rt_priority,
492 * p->dl.dl_{runtime, deadline, period, flags, bw, density}
493 * - sched_setnuma(): p->numa_preferred_nid
494 * - sched_move_task()/
495 * cpu_cgroup_fork(): p->sched_task_group
496 * - uclamp_update_active() p->uclamp*
498 * p->state <- TASK_*:
500 * is changed locklessly using set_current_state(), __set_current_state() or
501 * set_special_state(), see their respective comments, or by
502 * try_to_wake_up(). This latter uses p->pi_lock to serialize against
505 * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
507 * is set by activate_task() and cleared by deactivate_task(), under
508 * rq->lock. Non-zero indicates the task is runnable, the special
509 * ON_RQ_MIGRATING state is used for migration without holding both
510 * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
512 * p->on_cpu <- { 0, 1 }:
514 * is set by prepare_task() and cleared by finish_task() such that it will be
515 * set before p is scheduled-in and cleared after p is scheduled-out, both
516 * under rq->lock. Non-zero indicates the task is running on its CPU.
518 * [ The astute reader will observe that it is possible for two tasks on one
519 * CPU to have ->on_cpu = 1 at the same time. ]
521 * task_cpu(p): is changed by set_task_cpu(), the rules are:
523 * - Don't call set_task_cpu() on a blocked task:
525 * We don't care what CPU we're not running on, this simplifies hotplug,
526 * the CPU assignment of blocked tasks isn't required to be valid.
528 * - for try_to_wake_up(), called under p->pi_lock:
530 * This allows try_to_wake_up() to only take one rq->lock, see its comment.
532 * - for migration called under rq->lock:
533 * [ see task_on_rq_migrating() in task_rq_lock() ]
535 * o move_queued_task()
538 * - for migration called under double_rq_lock():
540 * o __migrate_swap_task()
541 * o push_rt_task() / pull_rt_task()
542 * o push_dl_task() / pull_dl_task()
543 * o dl_task_offline_migration()
547 void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
549 raw_spinlock_t *lock;
551 /* Matches synchronize_rcu() in __sched_core_enable() */
553 if (sched_core_disabled()) {
554 raw_spin_lock_nested(&rq->__lock, subclass);
555 /* preempt_count *MUST* be > 1 */
556 preempt_enable_no_resched();
561 lock = __rq_lockp(rq);
562 raw_spin_lock_nested(lock, subclass);
563 if (likely(lock == __rq_lockp(rq))) {
564 /* preempt_count *MUST* be > 1 */
565 preempt_enable_no_resched();
568 raw_spin_unlock(lock);
572 bool raw_spin_rq_trylock(struct rq *rq)
574 raw_spinlock_t *lock;
577 /* Matches synchronize_rcu() in __sched_core_enable() */
579 if (sched_core_disabled()) {
580 ret = raw_spin_trylock(&rq->__lock);
586 lock = __rq_lockp(rq);
587 ret = raw_spin_trylock(lock);
588 if (!ret || (likely(lock == __rq_lockp(rq)))) {
592 raw_spin_unlock(lock);
596 void raw_spin_rq_unlock(struct rq *rq)
598 raw_spin_unlock(rq_lockp(rq));
603 * double_rq_lock - safely lock two runqueues
605 void double_rq_lock(struct rq *rq1, struct rq *rq2)
607 lockdep_assert_irqs_disabled();
609 if (rq_order_less(rq2, rq1))
612 raw_spin_rq_lock(rq1);
613 if (__rq_lockp(rq1) == __rq_lockp(rq2))
616 raw_spin_rq_lock_nested(rq2, SINGLE_DEPTH_NESTING);
621 * __task_rq_lock - lock the rq @p resides on.
623 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
628 lockdep_assert_held(&p->pi_lock);
632 raw_spin_rq_lock(rq);
633 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
637 raw_spin_rq_unlock(rq);
639 while (unlikely(task_on_rq_migrating(p)))
645 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
647 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
648 __acquires(p->pi_lock)
654 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
656 raw_spin_rq_lock(rq);
658 * move_queued_task() task_rq_lock()
661 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
662 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
663 * [S] ->cpu = new_cpu [L] task_rq()
667 * If we observe the old CPU in task_rq_lock(), the acquire of
668 * the old rq->lock will fully serialize against the stores.
670 * If we observe the new CPU in task_rq_lock(), the address
671 * dependency headed by '[L] rq = task_rq()' and the acquire
672 * will pair with the WMB to ensure we then also see migrating.
674 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
678 raw_spin_rq_unlock(rq);
679 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
681 while (unlikely(task_on_rq_migrating(p)))
687 * RQ-clock updating methods:
690 static void update_rq_clock_task(struct rq *rq, s64 delta)
693 * In theory, the compile should just see 0 here, and optimize out the call
694 * to sched_rt_avg_update. But I don't trust it...
696 s64 __maybe_unused steal = 0, irq_delta = 0;
698 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
699 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
702 * Since irq_time is only updated on {soft,}irq_exit, we might run into
703 * this case when a previous update_rq_clock() happened inside a
706 * When this happens, we stop ->clock_task and only update the
707 * prev_irq_time stamp to account for the part that fit, so that a next
708 * update will consume the rest. This ensures ->clock_task is
711 * It does however cause some slight miss-attribution of {soft,}irq
712 * time, a more accurate solution would be to update the irq_time using
713 * the current rq->clock timestamp, except that would require using
716 if (irq_delta > delta)
719 rq->prev_irq_time += irq_delta;
722 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
723 if (static_key_false((¶virt_steal_rq_enabled))) {
724 steal = paravirt_steal_clock(cpu_of(rq));
725 steal -= rq->prev_steal_time_rq;
727 if (unlikely(steal > delta))
730 rq->prev_steal_time_rq += steal;
735 rq->clock_task += delta;
737 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
738 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
739 update_irq_load_avg(rq, irq_delta + steal);
741 update_rq_clock_pelt(rq, delta);
744 void update_rq_clock(struct rq *rq)
748 lockdep_assert_rq_held(rq);
750 if (rq->clock_update_flags & RQCF_ACT_SKIP)
753 #ifdef CONFIG_SCHED_DEBUG
754 if (sched_feat(WARN_DOUBLE_CLOCK))
755 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
756 rq->clock_update_flags |= RQCF_UPDATED;
759 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
763 update_rq_clock_task(rq, delta);
766 #ifdef CONFIG_SCHED_HRTICK
768 * Use HR-timers to deliver accurate preemption points.
771 static void hrtick_clear(struct rq *rq)
773 if (hrtimer_active(&rq->hrtick_timer))
774 hrtimer_cancel(&rq->hrtick_timer);
778 * High-resolution timer tick.
779 * Runs from hardirq context with interrupts disabled.
781 static enum hrtimer_restart hrtick(struct hrtimer *timer)
783 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
786 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
790 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
793 return HRTIMER_NORESTART;
798 static void __hrtick_restart(struct rq *rq)
800 struct hrtimer *timer = &rq->hrtick_timer;
801 ktime_t time = rq->hrtick_time;
803 hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
807 * called from hardirq (IPI) context
809 static void __hrtick_start(void *arg)
815 __hrtick_restart(rq);
820 * Called to set the hrtick timer state.
822 * called with rq->lock held and irqs disabled
824 void hrtick_start(struct rq *rq, u64 delay)
826 struct hrtimer *timer = &rq->hrtick_timer;
830 * Don't schedule slices shorter than 10000ns, that just
831 * doesn't make sense and can cause timer DoS.
833 delta = max_t(s64, delay, 10000LL);
834 rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
837 __hrtick_restart(rq);
839 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
844 * Called to set the hrtick timer state.
846 * called with rq->lock held and irqs disabled
848 void hrtick_start(struct rq *rq, u64 delay)
851 * Don't schedule slices shorter than 10000ns, that just
852 * doesn't make sense. Rely on vruntime for fairness.
854 delay = max_t(u64, delay, 10000LL);
855 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
856 HRTIMER_MODE_REL_PINNED_HARD);
859 #endif /* CONFIG_SMP */
861 static void hrtick_rq_init(struct rq *rq)
864 INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq);
866 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
867 rq->hrtick_timer.function = hrtick;
869 #else /* CONFIG_SCHED_HRTICK */
870 static inline void hrtick_clear(struct rq *rq)
874 static inline void hrtick_rq_init(struct rq *rq)
877 #endif /* CONFIG_SCHED_HRTICK */
880 * cmpxchg based fetch_or, macro so it works for different integer types
882 #define fetch_or(ptr, mask) \
884 typeof(ptr) _ptr = (ptr); \
885 typeof(mask) _mask = (mask); \
886 typeof(*_ptr) _old, _val = *_ptr; \
889 _old = cmpxchg(_ptr, _val, _val | _mask); \
897 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
899 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
900 * this avoids any races wrt polling state changes and thereby avoids
903 static bool set_nr_and_not_polling(struct task_struct *p)
905 struct thread_info *ti = task_thread_info(p);
906 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
910 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
912 * If this returns true, then the idle task promises to call
913 * sched_ttwu_pending() and reschedule soon.
915 static bool set_nr_if_polling(struct task_struct *p)
917 struct thread_info *ti = task_thread_info(p);
918 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
921 if (!(val & _TIF_POLLING_NRFLAG))
923 if (val & _TIF_NEED_RESCHED)
925 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
934 static bool set_nr_and_not_polling(struct task_struct *p)
936 set_tsk_need_resched(p);
941 static bool set_nr_if_polling(struct task_struct *p)
948 static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
950 struct wake_q_node *node = &task->wake_q;
953 * Atomically grab the task, if ->wake_q is !nil already it means
954 * it's already queued (either by us or someone else) and will get the
955 * wakeup due to that.
957 * In order to ensure that a pending wakeup will observe our pending
958 * state, even in the failed case, an explicit smp_mb() must be used.
960 smp_mb__before_atomic();
961 if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
965 * The head is context local, there can be no concurrency.
968 head->lastp = &node->next;
973 * wake_q_add() - queue a wakeup for 'later' waking.
974 * @head: the wake_q_head to add @task to
975 * @task: the task to queue for 'later' wakeup
977 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
978 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
981 * This function must be used as-if it were wake_up_process(); IOW the task
982 * must be ready to be woken at this location.
984 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
986 if (__wake_q_add(head, task))
987 get_task_struct(task);
991 * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
992 * @head: the wake_q_head to add @task to
993 * @task: the task to queue for 'later' wakeup
995 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
996 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
999 * This function must be used as-if it were wake_up_process(); IOW the task
1000 * must be ready to be woken at this location.
1002 * This function is essentially a task-safe equivalent to wake_q_add(). Callers
1003 * that already hold reference to @task can call the 'safe' version and trust
1004 * wake_q to do the right thing depending whether or not the @task is already
1005 * queued for wakeup.
1007 void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
1009 if (!__wake_q_add(head, task))
1010 put_task_struct(task);
1013 void wake_up_q(struct wake_q_head *head)
1015 struct wake_q_node *node = head->first;
1017 while (node != WAKE_Q_TAIL) {
1018 struct task_struct *task;
1020 task = container_of(node, struct task_struct, wake_q);
1021 /* Task can safely be re-inserted now: */
1023 task->wake_q.next = NULL;
1026 * wake_up_process() executes a full barrier, which pairs with
1027 * the queueing in wake_q_add() so as not to miss wakeups.
1029 wake_up_process(task);
1030 put_task_struct(task);
1035 * resched_curr - mark rq's current task 'to be rescheduled now'.
1037 * On UP this means the setting of the need_resched flag, on SMP it
1038 * might also involve a cross-CPU call to trigger the scheduler on
1041 void resched_curr(struct rq *rq)
1043 struct task_struct *curr = rq->curr;
1046 lockdep_assert_rq_held(rq);
1048 if (test_tsk_need_resched(curr))
1053 if (cpu == smp_processor_id()) {
1054 set_tsk_need_resched(curr);
1055 set_preempt_need_resched();
1059 if (set_nr_and_not_polling(curr))
1060 smp_send_reschedule(cpu);
1062 trace_sched_wake_idle_without_ipi(cpu);
1065 void resched_cpu(int cpu)
1067 struct rq *rq = cpu_rq(cpu);
1068 unsigned long flags;
1070 raw_spin_rq_lock_irqsave(rq, flags);
1071 if (cpu_online(cpu) || cpu == smp_processor_id())
1073 raw_spin_rq_unlock_irqrestore(rq, flags);
1077 #ifdef CONFIG_NO_HZ_COMMON
1079 * In the semi idle case, use the nearest busy CPU for migrating timers
1080 * from an idle CPU. This is good for power-savings.
1082 * We don't do similar optimization for completely idle system, as
1083 * selecting an idle CPU will add more delays to the timers than intended
1084 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
1086 int get_nohz_timer_target(void)
1088 int i, cpu = smp_processor_id(), default_cpu = -1;
1089 struct sched_domain *sd;
1090 const struct cpumask *hk_mask;
1092 if (housekeeping_cpu(cpu, HK_TYPE_TIMER)) {
1098 hk_mask = housekeeping_cpumask(HK_TYPE_TIMER);
1101 for_each_domain(cpu, sd) {
1102 for_each_cpu_and(i, sched_domain_span(sd), hk_mask) {
1113 if (default_cpu == -1)
1114 default_cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
1122 * When add_timer_on() enqueues a timer into the timer wheel of an
1123 * idle CPU then this timer might expire before the next timer event
1124 * which is scheduled to wake up that CPU. In case of a completely
1125 * idle system the next event might even be infinite time into the
1126 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1127 * leaves the inner idle loop so the newly added timer is taken into
1128 * account when the CPU goes back to idle and evaluates the timer
1129 * wheel for the next timer event.
1131 static void wake_up_idle_cpu(int cpu)
1133 struct rq *rq = cpu_rq(cpu);
1135 if (cpu == smp_processor_id())
1138 if (set_nr_and_not_polling(rq->idle))
1139 smp_send_reschedule(cpu);
1141 trace_sched_wake_idle_without_ipi(cpu);
1144 static bool wake_up_full_nohz_cpu(int cpu)
1147 * We just need the target to call irq_exit() and re-evaluate
1148 * the next tick. The nohz full kick at least implies that.
1149 * If needed we can still optimize that later with an
1152 if (cpu_is_offline(cpu))
1153 return true; /* Don't try to wake offline CPUs. */
1154 if (tick_nohz_full_cpu(cpu)) {
1155 if (cpu != smp_processor_id() ||
1156 tick_nohz_tick_stopped())
1157 tick_nohz_full_kick_cpu(cpu);
1165 * Wake up the specified CPU. If the CPU is going offline, it is the
1166 * caller's responsibility to deal with the lost wakeup, for example,
1167 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
1169 void wake_up_nohz_cpu(int cpu)
1171 if (!wake_up_full_nohz_cpu(cpu))
1172 wake_up_idle_cpu(cpu);
1175 static void nohz_csd_func(void *info)
1177 struct rq *rq = info;
1178 int cpu = cpu_of(rq);
1182 * Release the rq::nohz_csd.
1184 flags = atomic_fetch_andnot(NOHZ_KICK_MASK | NOHZ_NEWILB_KICK, nohz_flags(cpu));
1185 WARN_ON(!(flags & NOHZ_KICK_MASK));
1187 rq->idle_balance = idle_cpu(cpu);
1188 if (rq->idle_balance && !need_resched()) {
1189 rq->nohz_idle_balance = flags;
1190 raise_softirq_irqoff(SCHED_SOFTIRQ);
1194 #endif /* CONFIG_NO_HZ_COMMON */
1196 #ifdef CONFIG_NO_HZ_FULL
1197 bool sched_can_stop_tick(struct rq *rq)
1199 int fifo_nr_running;
1201 /* Deadline tasks, even if single, need the tick */
1202 if (rq->dl.dl_nr_running)
1206 * If there are more than one RR tasks, we need the tick to affect the
1207 * actual RR behaviour.
1209 if (rq->rt.rr_nr_running) {
1210 if (rq->rt.rr_nr_running == 1)
1217 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
1218 * forced preemption between FIFO tasks.
1220 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
1221 if (fifo_nr_running)
1225 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
1226 * if there's more than one we need the tick for involuntary
1229 if (rq->nr_running > 1)
1234 #endif /* CONFIG_NO_HZ_FULL */
1235 #endif /* CONFIG_SMP */
1237 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
1238 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
1240 * Iterate task_group tree rooted at *from, calling @down when first entering a
1241 * node and @up when leaving it for the final time.
1243 * Caller must hold rcu_lock or sufficient equivalent.
1245 int walk_tg_tree_from(struct task_group *from,
1246 tg_visitor down, tg_visitor up, void *data)
1248 struct task_group *parent, *child;
1254 ret = (*down)(parent, data);
1257 list_for_each_entry_rcu(child, &parent->children, siblings) {
1264 ret = (*up)(parent, data);
1265 if (ret || parent == from)
1269 parent = parent->parent;
1276 int tg_nop(struct task_group *tg, void *data)
1282 static void set_load_weight(struct task_struct *p, bool update_load)
1284 int prio = p->static_prio - MAX_RT_PRIO;
1285 struct load_weight *load = &p->se.load;
1288 * SCHED_IDLE tasks get minimal weight:
1290 if (task_has_idle_policy(p)) {
1291 load->weight = scale_load(WEIGHT_IDLEPRIO);
1292 load->inv_weight = WMULT_IDLEPRIO;
1297 * SCHED_OTHER tasks have to update their load when changing their
1300 if (update_load && p->sched_class == &fair_sched_class) {
1301 reweight_task(p, prio);
1303 load->weight = scale_load(sched_prio_to_weight[prio]);
1304 load->inv_weight = sched_prio_to_wmult[prio];
1308 #ifdef CONFIG_UCLAMP_TASK
1310 * Serializes updates of utilization clamp values
1312 * The (slow-path) user-space triggers utilization clamp value updates which
1313 * can require updates on (fast-path) scheduler's data structures used to
1314 * support enqueue/dequeue operations.
1315 * While the per-CPU rq lock protects fast-path update operations, user-space
1316 * requests are serialized using a mutex to reduce the risk of conflicting
1317 * updates or API abuses.
1319 static DEFINE_MUTEX(uclamp_mutex);
1321 /* Max allowed minimum utilization */
1322 unsigned int sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
1324 /* Max allowed maximum utilization */
1325 unsigned int sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
1328 * By default RT tasks run at the maximum performance point/capacity of the
1329 * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
1330 * SCHED_CAPACITY_SCALE.
1332 * This knob allows admins to change the default behavior when uclamp is being
1333 * used. In battery powered devices, particularly, running at the maximum
1334 * capacity and frequency will increase energy consumption and shorten the
1337 * This knob only affects RT tasks that their uclamp_se->user_defined == false.
1339 * This knob will not override the system default sched_util_clamp_min defined
1342 unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
1344 /* All clamps are required to be less or equal than these values */
1345 static struct uclamp_se uclamp_default[UCLAMP_CNT];
1348 * This static key is used to reduce the uclamp overhead in the fast path. It
1349 * primarily disables the call to uclamp_rq_{inc, dec}() in
1350 * enqueue/dequeue_task().
1352 * This allows users to continue to enable uclamp in their kernel config with
1353 * minimum uclamp overhead in the fast path.
1355 * As soon as userspace modifies any of the uclamp knobs, the static key is
1356 * enabled, since we have an actual users that make use of uclamp
1359 * The knobs that would enable this static key are:
1361 * * A task modifying its uclamp value with sched_setattr().
1362 * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
1363 * * An admin modifying the cgroup cpu.uclamp.{min, max}
1365 DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
1367 /* Integer rounded range for each bucket */
1368 #define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
1370 #define for_each_clamp_id(clamp_id) \
1371 for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
1373 static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
1375 return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
1378 static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
1380 if (clamp_id == UCLAMP_MIN)
1382 return SCHED_CAPACITY_SCALE;
1385 static inline void uclamp_se_set(struct uclamp_se *uc_se,
1386 unsigned int value, bool user_defined)
1388 uc_se->value = value;
1389 uc_se->bucket_id = uclamp_bucket_id(value);
1390 uc_se->user_defined = user_defined;
1393 static inline unsigned int
1394 uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
1395 unsigned int clamp_value)
1398 * Avoid blocked utilization pushing up the frequency when we go
1399 * idle (which drops the max-clamp) by retaining the last known
1402 if (clamp_id == UCLAMP_MAX) {
1403 rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
1407 return uclamp_none(UCLAMP_MIN);
1410 static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
1411 unsigned int clamp_value)
1413 /* Reset max-clamp retention only on idle exit */
1414 if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1417 WRITE_ONCE(rq->uclamp[clamp_id].value, clamp_value);
1421 unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
1422 unsigned int clamp_value)
1424 struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
1425 int bucket_id = UCLAMP_BUCKETS - 1;
1428 * Since both min and max clamps are max aggregated, find the
1429 * top most bucket with tasks in.
1431 for ( ; bucket_id >= 0; bucket_id--) {
1432 if (!bucket[bucket_id].tasks)
1434 return bucket[bucket_id].value;
1437 /* No tasks -- default clamp values */
1438 return uclamp_idle_value(rq, clamp_id, clamp_value);
1441 static void __uclamp_update_util_min_rt_default(struct task_struct *p)
1443 unsigned int default_util_min;
1444 struct uclamp_se *uc_se;
1446 lockdep_assert_held(&p->pi_lock);
1448 uc_se = &p->uclamp_req[UCLAMP_MIN];
1450 /* Only sync if user didn't override the default */
1451 if (uc_se->user_defined)
1454 default_util_min = sysctl_sched_uclamp_util_min_rt_default;
1455 uclamp_se_set(uc_se, default_util_min, false);
1458 static void uclamp_update_util_min_rt_default(struct task_struct *p)
1466 /* Protect updates to p->uclamp_* */
1467 rq = task_rq_lock(p, &rf);
1468 __uclamp_update_util_min_rt_default(p);
1469 task_rq_unlock(rq, p, &rf);
1472 static void uclamp_sync_util_min_rt_default(void)
1474 struct task_struct *g, *p;
1477 * copy_process() sysctl_uclamp
1478 * uclamp_min_rt = X;
1479 * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
1480 * // link thread smp_mb__after_spinlock()
1481 * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
1482 * sched_post_fork() for_each_process_thread()
1483 * __uclamp_sync_rt() __uclamp_sync_rt()
1485 * Ensures that either sched_post_fork() will observe the new
1486 * uclamp_min_rt or for_each_process_thread() will observe the new
1489 read_lock(&tasklist_lock);
1490 smp_mb__after_spinlock();
1491 read_unlock(&tasklist_lock);
1494 for_each_process_thread(g, p)
1495 uclamp_update_util_min_rt_default(p);
1499 static inline struct uclamp_se
1500 uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
1502 /* Copy by value as we could modify it */
1503 struct uclamp_se uc_req = p->uclamp_req[clamp_id];
1504 #ifdef CONFIG_UCLAMP_TASK_GROUP
1505 unsigned int tg_min, tg_max, value;
1508 * Tasks in autogroups or root task group will be
1509 * restricted by system defaults.
1511 if (task_group_is_autogroup(task_group(p)))
1513 if (task_group(p) == &root_task_group)
1516 tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
1517 tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
1518 value = uc_req.value;
1519 value = clamp(value, tg_min, tg_max);
1520 uclamp_se_set(&uc_req, value, false);
1527 * The effective clamp bucket index of a task depends on, by increasing
1529 * - the task specific clamp value, when explicitly requested from userspace
1530 * - the task group effective clamp value, for tasks not either in the root
1531 * group or in an autogroup
1532 * - the system default clamp value, defined by the sysadmin
1534 static inline struct uclamp_se
1535 uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
1537 struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
1538 struct uclamp_se uc_max = uclamp_default[clamp_id];
1540 /* System default restrictions always apply */
1541 if (unlikely(uc_req.value > uc_max.value))
1547 unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
1549 struct uclamp_se uc_eff;
1551 /* Task currently refcounted: use back-annotated (effective) value */
1552 if (p->uclamp[clamp_id].active)
1553 return (unsigned long)p->uclamp[clamp_id].value;
1555 uc_eff = uclamp_eff_get(p, clamp_id);
1557 return (unsigned long)uc_eff.value;
1561 * When a task is enqueued on a rq, the clamp bucket currently defined by the
1562 * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1563 * updates the rq's clamp value if required.
1565 * Tasks can have a task-specific value requested from user-space, track
1566 * within each bucket the maximum value for tasks refcounted in it.
1567 * This "local max aggregation" allows to track the exact "requested" value
1568 * for each bucket when all its RUNNABLE tasks require the same clamp.
1570 static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
1571 enum uclamp_id clamp_id)
1573 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1574 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1575 struct uclamp_bucket *bucket;
1577 lockdep_assert_rq_held(rq);
1579 /* Update task effective clamp */
1580 p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
1582 bucket = &uc_rq->bucket[uc_se->bucket_id];
1584 uc_se->active = true;
1586 uclamp_idle_reset(rq, clamp_id, uc_se->value);
1589 * Local max aggregation: rq buckets always track the max
1590 * "requested" clamp value of its RUNNABLE tasks.
1592 if (bucket->tasks == 1 || uc_se->value > bucket->value)
1593 bucket->value = uc_se->value;
1595 if (uc_se->value > READ_ONCE(uc_rq->value))
1596 WRITE_ONCE(uc_rq->value, uc_se->value);
1600 * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1601 * is released. If this is the last task reference counting the rq's max
1602 * active clamp value, then the rq's clamp value is updated.
1604 * Both refcounted tasks and rq's cached clamp values are expected to be
1605 * always valid. If it's detected they are not, as defensive programming,
1606 * enforce the expected state and warn.
1608 static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
1609 enum uclamp_id clamp_id)
1611 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1612 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1613 struct uclamp_bucket *bucket;
1614 unsigned int bkt_clamp;
1615 unsigned int rq_clamp;
1617 lockdep_assert_rq_held(rq);
1620 * If sched_uclamp_used was enabled after task @p was enqueued,
1621 * we could end up with unbalanced call to uclamp_rq_dec_id().
1623 * In this case the uc_se->active flag should be false since no uclamp
1624 * accounting was performed at enqueue time and we can just return
1627 * Need to be careful of the following enqueue/dequeue ordering
1631 * // sched_uclamp_used gets enabled
1634 * // Must not decrement bucket->tasks here
1637 * where we could end up with stale data in uc_se and
1638 * bucket[uc_se->bucket_id].
1640 * The following check here eliminates the possibility of such race.
1642 if (unlikely(!uc_se->active))
1645 bucket = &uc_rq->bucket[uc_se->bucket_id];
1647 SCHED_WARN_ON(!bucket->tasks);
1648 if (likely(bucket->tasks))
1651 uc_se->active = false;
1654 * Keep "local max aggregation" simple and accept to (possibly)
1655 * overboost some RUNNABLE tasks in the same bucket.
1656 * The rq clamp bucket value is reset to its base value whenever
1657 * there are no more RUNNABLE tasks refcounting it.
1659 if (likely(bucket->tasks))
1662 rq_clamp = READ_ONCE(uc_rq->value);
1664 * Defensive programming: this should never happen. If it happens,
1665 * e.g. due to future modification, warn and fixup the expected value.
1667 SCHED_WARN_ON(bucket->value > rq_clamp);
1668 if (bucket->value >= rq_clamp) {
1669 bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
1670 WRITE_ONCE(uc_rq->value, bkt_clamp);
1674 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
1676 enum uclamp_id clamp_id;
1679 * Avoid any overhead until uclamp is actually used by the userspace.
1681 * The condition is constructed such that a NOP is generated when
1682 * sched_uclamp_used is disabled.
1684 if (!static_branch_unlikely(&sched_uclamp_used))
1687 if (unlikely(!p->sched_class->uclamp_enabled))
1690 for_each_clamp_id(clamp_id)
1691 uclamp_rq_inc_id(rq, p, clamp_id);
1693 /* Reset clamp idle holding when there is one RUNNABLE task */
1694 if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
1695 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1698 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
1700 enum uclamp_id clamp_id;
1703 * Avoid any overhead until uclamp is actually used by the userspace.
1705 * The condition is constructed such that a NOP is generated when
1706 * sched_uclamp_used is disabled.
1708 if (!static_branch_unlikely(&sched_uclamp_used))
1711 if (unlikely(!p->sched_class->uclamp_enabled))
1714 for_each_clamp_id(clamp_id)
1715 uclamp_rq_dec_id(rq, p, clamp_id);
1718 static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
1719 enum uclamp_id clamp_id)
1721 if (!p->uclamp[clamp_id].active)
1724 uclamp_rq_dec_id(rq, p, clamp_id);
1725 uclamp_rq_inc_id(rq, p, clamp_id);
1728 * Make sure to clear the idle flag if we've transiently reached 0
1729 * active tasks on rq.
1731 if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1732 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1736 uclamp_update_active(struct task_struct *p)
1738 enum uclamp_id clamp_id;
1743 * Lock the task and the rq where the task is (or was) queued.
1745 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1746 * price to pay to safely serialize util_{min,max} updates with
1747 * enqueues, dequeues and migration operations.
1748 * This is the same locking schema used by __set_cpus_allowed_ptr().
1750 rq = task_rq_lock(p, &rf);
1753 * Setting the clamp bucket is serialized by task_rq_lock().
1754 * If the task is not yet RUNNABLE and its task_struct is not
1755 * affecting a valid clamp bucket, the next time it's enqueued,
1756 * it will already see the updated clamp bucket value.
1758 for_each_clamp_id(clamp_id)
1759 uclamp_rq_reinc_id(rq, p, clamp_id);
1761 task_rq_unlock(rq, p, &rf);
1764 #ifdef CONFIG_UCLAMP_TASK_GROUP
1766 uclamp_update_active_tasks(struct cgroup_subsys_state *css)
1768 struct css_task_iter it;
1769 struct task_struct *p;
1771 css_task_iter_start(css, 0, &it);
1772 while ((p = css_task_iter_next(&it)))
1773 uclamp_update_active(p);
1774 css_task_iter_end(&it);
1777 static void cpu_util_update_eff(struct cgroup_subsys_state *css);
1778 static void uclamp_update_root_tg(void)
1780 struct task_group *tg = &root_task_group;
1782 uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
1783 sysctl_sched_uclamp_util_min, false);
1784 uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
1785 sysctl_sched_uclamp_util_max, false);
1788 cpu_util_update_eff(&root_task_group.css);
1792 static void uclamp_update_root_tg(void) { }
1795 int sysctl_sched_uclamp_handler(struct ctl_table *table, int write,
1796 void *buffer, size_t *lenp, loff_t *ppos)
1798 bool update_root_tg = false;
1799 int old_min, old_max, old_min_rt;
1802 mutex_lock(&uclamp_mutex);
1803 old_min = sysctl_sched_uclamp_util_min;
1804 old_max = sysctl_sched_uclamp_util_max;
1805 old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
1807 result = proc_dointvec(table, write, buffer, lenp, ppos);
1813 if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
1814 sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE ||
1815 sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
1821 if (old_min != sysctl_sched_uclamp_util_min) {
1822 uclamp_se_set(&uclamp_default[UCLAMP_MIN],
1823 sysctl_sched_uclamp_util_min, false);
1824 update_root_tg = true;
1826 if (old_max != sysctl_sched_uclamp_util_max) {
1827 uclamp_se_set(&uclamp_default[UCLAMP_MAX],
1828 sysctl_sched_uclamp_util_max, false);
1829 update_root_tg = true;
1832 if (update_root_tg) {
1833 static_branch_enable(&sched_uclamp_used);
1834 uclamp_update_root_tg();
1837 if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
1838 static_branch_enable(&sched_uclamp_used);
1839 uclamp_sync_util_min_rt_default();
1843 * We update all RUNNABLE tasks only when task groups are in use.
1844 * Otherwise, keep it simple and do just a lazy update at each next
1845 * task enqueue time.
1851 sysctl_sched_uclamp_util_min = old_min;
1852 sysctl_sched_uclamp_util_max = old_max;
1853 sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
1855 mutex_unlock(&uclamp_mutex);
1860 static int uclamp_validate(struct task_struct *p,
1861 const struct sched_attr *attr)
1863 int util_min = p->uclamp_req[UCLAMP_MIN].value;
1864 int util_max = p->uclamp_req[UCLAMP_MAX].value;
1866 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
1867 util_min = attr->sched_util_min;
1869 if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
1873 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
1874 util_max = attr->sched_util_max;
1876 if (util_max + 1 > SCHED_CAPACITY_SCALE + 1)
1880 if (util_min != -1 && util_max != -1 && util_min > util_max)
1884 * We have valid uclamp attributes; make sure uclamp is enabled.
1886 * We need to do that here, because enabling static branches is a
1887 * blocking operation which obviously cannot be done while holding
1890 static_branch_enable(&sched_uclamp_used);
1895 static bool uclamp_reset(const struct sched_attr *attr,
1896 enum uclamp_id clamp_id,
1897 struct uclamp_se *uc_se)
1899 /* Reset on sched class change for a non user-defined clamp value. */
1900 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)) &&
1901 !uc_se->user_defined)
1904 /* Reset on sched_util_{min,max} == -1. */
1905 if (clamp_id == UCLAMP_MIN &&
1906 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1907 attr->sched_util_min == -1) {
1911 if (clamp_id == UCLAMP_MAX &&
1912 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1913 attr->sched_util_max == -1) {
1920 static void __setscheduler_uclamp(struct task_struct *p,
1921 const struct sched_attr *attr)
1923 enum uclamp_id clamp_id;
1925 for_each_clamp_id(clamp_id) {
1926 struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
1929 if (!uclamp_reset(attr, clamp_id, uc_se))
1933 * RT by default have a 100% boost value that could be modified
1936 if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
1937 value = sysctl_sched_uclamp_util_min_rt_default;
1939 value = uclamp_none(clamp_id);
1941 uclamp_se_set(uc_se, value, false);
1945 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
1948 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1949 attr->sched_util_min != -1) {
1950 uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
1951 attr->sched_util_min, true);
1954 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1955 attr->sched_util_max != -1) {
1956 uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
1957 attr->sched_util_max, true);
1961 static void uclamp_fork(struct task_struct *p)
1963 enum uclamp_id clamp_id;
1966 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
1967 * as the task is still at its early fork stages.
1969 for_each_clamp_id(clamp_id)
1970 p->uclamp[clamp_id].active = false;
1972 if (likely(!p->sched_reset_on_fork))
1975 for_each_clamp_id(clamp_id) {
1976 uclamp_se_set(&p->uclamp_req[clamp_id],
1977 uclamp_none(clamp_id), false);
1981 static void uclamp_post_fork(struct task_struct *p)
1983 uclamp_update_util_min_rt_default(p);
1986 static void __init init_uclamp_rq(struct rq *rq)
1988 enum uclamp_id clamp_id;
1989 struct uclamp_rq *uc_rq = rq->uclamp;
1991 for_each_clamp_id(clamp_id) {
1992 uc_rq[clamp_id] = (struct uclamp_rq) {
1993 .value = uclamp_none(clamp_id)
1997 rq->uclamp_flags = UCLAMP_FLAG_IDLE;
2000 static void __init init_uclamp(void)
2002 struct uclamp_se uc_max = {};
2003 enum uclamp_id clamp_id;
2006 for_each_possible_cpu(cpu)
2007 init_uclamp_rq(cpu_rq(cpu));
2009 for_each_clamp_id(clamp_id) {
2010 uclamp_se_set(&init_task.uclamp_req[clamp_id],
2011 uclamp_none(clamp_id), false);
2014 /* System defaults allow max clamp values for both indexes */
2015 uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
2016 for_each_clamp_id(clamp_id) {
2017 uclamp_default[clamp_id] = uc_max;
2018 #ifdef CONFIG_UCLAMP_TASK_GROUP
2019 root_task_group.uclamp_req[clamp_id] = uc_max;
2020 root_task_group.uclamp[clamp_id] = uc_max;
2025 #else /* CONFIG_UCLAMP_TASK */
2026 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
2027 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
2028 static inline int uclamp_validate(struct task_struct *p,
2029 const struct sched_attr *attr)
2033 static void __setscheduler_uclamp(struct task_struct *p,
2034 const struct sched_attr *attr) { }
2035 static inline void uclamp_fork(struct task_struct *p) { }
2036 static inline void uclamp_post_fork(struct task_struct *p) { }
2037 static inline void init_uclamp(void) { }
2038 #endif /* CONFIG_UCLAMP_TASK */
2040 bool sched_task_on_rq(struct task_struct *p)
2042 return task_on_rq_queued(p);
2045 unsigned long get_wchan(struct task_struct *p)
2047 unsigned long ip = 0;
2050 if (!p || p == current)
2053 /* Only get wchan if task is blocked and we can keep it that way. */
2054 raw_spin_lock_irq(&p->pi_lock);
2055 state = READ_ONCE(p->__state);
2056 smp_rmb(); /* see try_to_wake_up() */
2057 if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq)
2058 ip = __get_wchan(p);
2059 raw_spin_unlock_irq(&p->pi_lock);
2064 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2066 if (!(flags & ENQUEUE_NOCLOCK))
2067 update_rq_clock(rq);
2069 if (!(flags & ENQUEUE_RESTORE)) {
2070 sched_info_enqueue(rq, p);
2071 psi_enqueue(p, flags & ENQUEUE_WAKEUP);
2074 uclamp_rq_inc(rq, p);
2075 p->sched_class->enqueue_task(rq, p, flags);
2077 if (sched_core_enabled(rq))
2078 sched_core_enqueue(rq, p);
2081 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
2083 if (sched_core_enabled(rq))
2084 sched_core_dequeue(rq, p, flags);
2086 if (!(flags & DEQUEUE_NOCLOCK))
2087 update_rq_clock(rq);
2089 if (!(flags & DEQUEUE_SAVE)) {
2090 sched_info_dequeue(rq, p);
2091 psi_dequeue(p, flags & DEQUEUE_SLEEP);
2094 uclamp_rq_dec(rq, p);
2095 p->sched_class->dequeue_task(rq, p, flags);
2098 void activate_task(struct rq *rq, struct task_struct *p, int flags)
2100 enqueue_task(rq, p, flags);
2102 p->on_rq = TASK_ON_RQ_QUEUED;
2105 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
2107 p->on_rq = (flags & DEQUEUE_SLEEP) ? 0 : TASK_ON_RQ_MIGRATING;
2109 dequeue_task(rq, p, flags);
2112 static inline int __normal_prio(int policy, int rt_prio, int nice)
2116 if (dl_policy(policy))
2117 prio = MAX_DL_PRIO - 1;
2118 else if (rt_policy(policy))
2119 prio = MAX_RT_PRIO - 1 - rt_prio;
2121 prio = NICE_TO_PRIO(nice);
2127 * Calculate the expected normal priority: i.e. priority
2128 * without taking RT-inheritance into account. Might be
2129 * boosted by interactivity modifiers. Changes upon fork,
2130 * setprio syscalls, and whenever the interactivity
2131 * estimator recalculates.
2133 static inline int normal_prio(struct task_struct *p)
2135 return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio));
2139 * Calculate the current priority, i.e. the priority
2140 * taken into account by the scheduler. This value might
2141 * be boosted by RT tasks, or might be boosted by
2142 * interactivity modifiers. Will be RT if the task got
2143 * RT-boosted. If not then it returns p->normal_prio.
2145 static int effective_prio(struct task_struct *p)
2147 p->normal_prio = normal_prio(p);
2149 * If we are RT tasks or we were boosted to RT priority,
2150 * keep the priority unchanged. Otherwise, update priority
2151 * to the normal priority:
2153 if (!rt_prio(p->prio))
2154 return p->normal_prio;
2159 * task_curr - is this task currently executing on a CPU?
2160 * @p: the task in question.
2162 * Return: 1 if the task is currently executing. 0 otherwise.
2164 inline int task_curr(const struct task_struct *p)
2166 return cpu_curr(task_cpu(p)) == p;
2170 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
2171 * use the balance_callback list if you want balancing.
2173 * this means any call to check_class_changed() must be followed by a call to
2174 * balance_callback().
2176 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2177 const struct sched_class *prev_class,
2180 if (prev_class != p->sched_class) {
2181 if (prev_class->switched_from)
2182 prev_class->switched_from(rq, p);
2184 p->sched_class->switched_to(rq, p);
2185 } else if (oldprio != p->prio || dl_task(p))
2186 p->sched_class->prio_changed(rq, p, oldprio);
2189 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
2191 if (p->sched_class == rq->curr->sched_class)
2192 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
2193 else if (p->sched_class > rq->curr->sched_class)
2197 * A queue event has occurred, and we're going to schedule. In
2198 * this case, we can save a useless back to back clock update.
2200 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
2201 rq_clock_skip_update(rq);
2207 __do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask, u32 flags);
2209 static int __set_cpus_allowed_ptr(struct task_struct *p,
2210 const struct cpumask *new_mask,
2213 static void migrate_disable_switch(struct rq *rq, struct task_struct *p)
2215 if (likely(!p->migration_disabled))
2218 if (p->cpus_ptr != &p->cpus_mask)
2222 * Violates locking rules! see comment in __do_set_cpus_allowed().
2224 __do_set_cpus_allowed(p, cpumask_of(rq->cpu), SCA_MIGRATE_DISABLE);
2227 void migrate_disable(void)
2229 struct task_struct *p = current;
2231 if (p->migration_disabled) {
2232 p->migration_disabled++;
2237 this_rq()->nr_pinned++;
2238 p->migration_disabled = 1;
2241 EXPORT_SYMBOL_GPL(migrate_disable);
2243 void migrate_enable(void)
2245 struct task_struct *p = current;
2247 if (p->migration_disabled > 1) {
2248 p->migration_disabled--;
2252 if (WARN_ON_ONCE(!p->migration_disabled))
2256 * Ensure stop_task runs either before or after this, and that
2257 * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
2260 if (p->cpus_ptr != &p->cpus_mask)
2261 __set_cpus_allowed_ptr(p, &p->cpus_mask, SCA_MIGRATE_ENABLE);
2263 * Mustn't clear migration_disabled() until cpus_ptr points back at the
2264 * regular cpus_mask, otherwise things that race (eg.
2265 * select_fallback_rq) get confused.
2268 p->migration_disabled = 0;
2269 this_rq()->nr_pinned--;
2272 EXPORT_SYMBOL_GPL(migrate_enable);
2274 static inline bool rq_has_pinned_tasks(struct rq *rq)
2276 return rq->nr_pinned;
2280 * Per-CPU kthreads are allowed to run on !active && online CPUs, see
2281 * __set_cpus_allowed_ptr() and select_fallback_rq().
2283 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
2285 /* When not in the task's cpumask, no point in looking further. */
2286 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
2289 /* migrate_disabled() must be allowed to finish. */
2290 if (is_migration_disabled(p))
2291 return cpu_online(cpu);
2293 /* Non kernel threads are not allowed during either online or offline. */
2294 if (!(p->flags & PF_KTHREAD))
2295 return cpu_active(cpu) && task_cpu_possible(cpu, p);
2297 /* KTHREAD_IS_PER_CPU is always allowed. */
2298 if (kthread_is_per_cpu(p))
2299 return cpu_online(cpu);
2301 /* Regular kernel threads don't get to stay during offline. */
2305 /* But are allowed during online. */
2306 return cpu_online(cpu);
2310 * This is how migration works:
2312 * 1) we invoke migration_cpu_stop() on the target CPU using
2314 * 2) stopper starts to run (implicitly forcing the migrated thread
2316 * 3) it checks whether the migrated task is still in the wrong runqueue.
2317 * 4) if it's in the wrong runqueue then the migration thread removes
2318 * it and puts it into the right queue.
2319 * 5) stopper completes and stop_one_cpu() returns and the migration
2324 * move_queued_task - move a queued task to new rq.
2326 * Returns (locked) new rq. Old rq's lock is released.
2328 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
2329 struct task_struct *p, int new_cpu)
2331 lockdep_assert_rq_held(rq);
2333 deactivate_task(rq, p, DEQUEUE_NOCLOCK);
2334 set_task_cpu(p, new_cpu);
2337 rq = cpu_rq(new_cpu);
2340 BUG_ON(task_cpu(p) != new_cpu);
2341 activate_task(rq, p, 0);
2342 check_preempt_curr(rq, p, 0);
2347 struct migration_arg {
2348 struct task_struct *task;
2350 struct set_affinity_pending *pending;
2354 * @refs: number of wait_for_completion()
2355 * @stop_pending: is @stop_work in use
2357 struct set_affinity_pending {
2359 unsigned int stop_pending;
2360 struct completion done;
2361 struct cpu_stop_work stop_work;
2362 struct migration_arg arg;
2366 * Move (not current) task off this CPU, onto the destination CPU. We're doing
2367 * this because either it can't run here any more (set_cpus_allowed()
2368 * away from this CPU, or CPU going down), or because we're
2369 * attempting to rebalance this task on exec (sched_exec).
2371 * So we race with normal scheduler movements, but that's OK, as long
2372 * as the task is no longer on this CPU.
2374 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
2375 struct task_struct *p, int dest_cpu)
2377 /* Affinity changed (again). */
2378 if (!is_cpu_allowed(p, dest_cpu))
2381 update_rq_clock(rq);
2382 rq = move_queued_task(rq, rf, p, dest_cpu);
2388 * migration_cpu_stop - this will be executed by a highprio stopper thread
2389 * and performs thread migration by bumping thread off CPU then
2390 * 'pushing' onto another runqueue.
2392 static int migration_cpu_stop(void *data)
2394 struct migration_arg *arg = data;
2395 struct set_affinity_pending *pending = arg->pending;
2396 struct task_struct *p = arg->task;
2397 struct rq *rq = this_rq();
2398 bool complete = false;
2402 * The original target CPU might have gone down and we might
2403 * be on another CPU but it doesn't matter.
2405 local_irq_save(rf.flags);
2407 * We need to explicitly wake pending tasks before running
2408 * __migrate_task() such that we will not miss enforcing cpus_ptr
2409 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
2411 flush_smp_call_function_from_idle();
2413 raw_spin_lock(&p->pi_lock);
2417 * If we were passed a pending, then ->stop_pending was set, thus
2418 * p->migration_pending must have remained stable.
2420 WARN_ON_ONCE(pending && pending != p->migration_pending);
2423 * If task_rq(p) != rq, it cannot be migrated here, because we're
2424 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
2425 * we're holding p->pi_lock.
2427 if (task_rq(p) == rq) {
2428 if (is_migration_disabled(p))
2432 p->migration_pending = NULL;
2435 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask))
2439 if (task_on_rq_queued(p))
2440 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
2442 p->wake_cpu = arg->dest_cpu;
2445 * XXX __migrate_task() can fail, at which point we might end
2446 * up running on a dodgy CPU, AFAICT this can only happen
2447 * during CPU hotplug, at which point we'll get pushed out
2448 * anyway, so it's probably not a big deal.
2451 } else if (pending) {
2453 * This happens when we get migrated between migrate_enable()'s
2454 * preempt_enable() and scheduling the stopper task. At that
2455 * point we're a regular task again and not current anymore.
2457 * A !PREEMPT kernel has a giant hole here, which makes it far
2462 * The task moved before the stopper got to run. We're holding
2463 * ->pi_lock, so the allowed mask is stable - if it got
2464 * somewhere allowed, we're done.
2466 if (cpumask_test_cpu(task_cpu(p), p->cpus_ptr)) {
2467 p->migration_pending = NULL;
2473 * When migrate_enable() hits a rq mis-match we can't reliably
2474 * determine is_migration_disabled() and so have to chase after
2477 WARN_ON_ONCE(!pending->stop_pending);
2478 task_rq_unlock(rq, p, &rf);
2479 stop_one_cpu_nowait(task_cpu(p), migration_cpu_stop,
2480 &pending->arg, &pending->stop_work);
2485 pending->stop_pending = false;
2486 task_rq_unlock(rq, p, &rf);
2489 complete_all(&pending->done);
2494 int push_cpu_stop(void *arg)
2496 struct rq *lowest_rq = NULL, *rq = this_rq();
2497 struct task_struct *p = arg;
2499 raw_spin_lock_irq(&p->pi_lock);
2500 raw_spin_rq_lock(rq);
2502 if (task_rq(p) != rq)
2505 if (is_migration_disabled(p)) {
2506 p->migration_flags |= MDF_PUSH;
2510 p->migration_flags &= ~MDF_PUSH;
2512 if (p->sched_class->find_lock_rq)
2513 lowest_rq = p->sched_class->find_lock_rq(p, rq);
2518 // XXX validate p is still the highest prio task
2519 if (task_rq(p) == rq) {
2520 deactivate_task(rq, p, 0);
2521 set_task_cpu(p, lowest_rq->cpu);
2522 activate_task(lowest_rq, p, 0);
2523 resched_curr(lowest_rq);
2526 double_unlock_balance(rq, lowest_rq);
2529 rq->push_busy = false;
2530 raw_spin_rq_unlock(rq);
2531 raw_spin_unlock_irq(&p->pi_lock);
2538 * sched_class::set_cpus_allowed must do the below, but is not required to
2539 * actually call this function.
2541 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask, u32 flags)
2543 if (flags & (SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) {
2544 p->cpus_ptr = new_mask;
2548 cpumask_copy(&p->cpus_mask, new_mask);
2549 p->nr_cpus_allowed = cpumask_weight(new_mask);
2553 __do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask, u32 flags)
2555 struct rq *rq = task_rq(p);
2556 bool queued, running;
2559 * This here violates the locking rules for affinity, since we're only
2560 * supposed to change these variables while holding both rq->lock and
2563 * HOWEVER, it magically works, because ttwu() is the only code that
2564 * accesses these variables under p->pi_lock and only does so after
2565 * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
2566 * before finish_task().
2568 * XXX do further audits, this smells like something putrid.
2570 if (flags & SCA_MIGRATE_DISABLE)
2571 SCHED_WARN_ON(!p->on_cpu);
2573 lockdep_assert_held(&p->pi_lock);
2575 queued = task_on_rq_queued(p);
2576 running = task_current(rq, p);
2580 * Because __kthread_bind() calls this on blocked tasks without
2583 lockdep_assert_rq_held(rq);
2584 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
2587 put_prev_task(rq, p);
2589 p->sched_class->set_cpus_allowed(p, new_mask, flags);
2592 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
2594 set_next_task(rq, p);
2597 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
2599 __do_set_cpus_allowed(p, new_mask, 0);
2602 int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src,
2605 if (!src->user_cpus_ptr)
2608 dst->user_cpus_ptr = kmalloc_node(cpumask_size(), GFP_KERNEL, node);
2609 if (!dst->user_cpus_ptr)
2612 cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr);
2616 static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p)
2618 struct cpumask *user_mask = NULL;
2620 swap(p->user_cpus_ptr, user_mask);
2625 void release_user_cpus_ptr(struct task_struct *p)
2627 kfree(clear_user_cpus_ptr(p));
2631 * This function is wildly self concurrent; here be dragons.
2634 * When given a valid mask, __set_cpus_allowed_ptr() must block until the
2635 * designated task is enqueued on an allowed CPU. If that task is currently
2636 * running, we have to kick it out using the CPU stopper.
2638 * Migrate-Disable comes along and tramples all over our nice sandcastle.
2641 * Initial conditions: P0->cpus_mask = [0, 1]
2645 * migrate_disable();
2647 * set_cpus_allowed_ptr(P0, [1]);
2649 * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
2650 * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
2651 * This means we need the following scheme:
2655 * migrate_disable();
2657 * set_cpus_allowed_ptr(P0, [1]);
2661 * __set_cpus_allowed_ptr();
2662 * <wakes local stopper>
2663 * `--> <woken on migration completion>
2665 * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
2666 * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
2667 * task p are serialized by p->pi_lock, which we can leverage: the one that
2668 * should come into effect at the end of the Migrate-Disable region is the last
2669 * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
2670 * but we still need to properly signal those waiting tasks at the appropriate
2673 * This is implemented using struct set_affinity_pending. The first
2674 * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
2675 * setup an instance of that struct and install it on the targeted task_struct.
2676 * Any and all further callers will reuse that instance. Those then wait for
2677 * a completion signaled at the tail of the CPU stopper callback (1), triggered
2678 * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
2681 * (1) In the cases covered above. There is one more where the completion is
2682 * signaled within affine_move_task() itself: when a subsequent affinity request
2683 * occurs after the stopper bailed out due to the targeted task still being
2684 * Migrate-Disable. Consider:
2686 * Initial conditions: P0->cpus_mask = [0, 1]
2690 * migrate_disable();
2692 * set_cpus_allowed_ptr(P0, [1]);
2695 * migration_cpu_stop()
2696 * is_migration_disabled()
2698 * set_cpus_allowed_ptr(P0, [0, 1]);
2699 * <signal completion>
2702 * Note that the above is safe vs a concurrent migrate_enable(), as any
2703 * pending affinity completion is preceded by an uninstallation of
2704 * p->migration_pending done with p->pi_lock held.
2706 static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf,
2707 int dest_cpu, unsigned int flags)
2709 struct set_affinity_pending my_pending = { }, *pending = NULL;
2710 bool stop_pending, complete = false;
2712 /* Can the task run on the task's current CPU? If so, we're done */
2713 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) {
2714 struct task_struct *push_task = NULL;
2716 if ((flags & SCA_MIGRATE_ENABLE) &&
2717 (p->migration_flags & MDF_PUSH) && !rq->push_busy) {
2718 rq->push_busy = true;
2719 push_task = get_task_struct(p);
2723 * If there are pending waiters, but no pending stop_work,
2724 * then complete now.
2726 pending = p->migration_pending;
2727 if (pending && !pending->stop_pending) {
2728 p->migration_pending = NULL;
2732 task_rq_unlock(rq, p, rf);
2735 stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
2740 complete_all(&pending->done);
2745 if (!(flags & SCA_MIGRATE_ENABLE)) {
2746 /* serialized by p->pi_lock */
2747 if (!p->migration_pending) {
2748 /* Install the request */
2749 refcount_set(&my_pending.refs, 1);
2750 init_completion(&my_pending.done);
2751 my_pending.arg = (struct migration_arg) {
2753 .dest_cpu = dest_cpu,
2754 .pending = &my_pending,
2757 p->migration_pending = &my_pending;
2759 pending = p->migration_pending;
2760 refcount_inc(&pending->refs);
2762 * Affinity has changed, but we've already installed a
2763 * pending. migration_cpu_stop() *must* see this, else
2764 * we risk a completion of the pending despite having a
2765 * task on a disallowed CPU.
2767 * Serialized by p->pi_lock, so this is safe.
2769 pending->arg.dest_cpu = dest_cpu;
2772 pending = p->migration_pending;
2774 * - !MIGRATE_ENABLE:
2775 * we'll have installed a pending if there wasn't one already.
2778 * we're here because the current CPU isn't matching anymore,
2779 * the only way that can happen is because of a concurrent
2780 * set_cpus_allowed_ptr() call, which should then still be
2781 * pending completion.
2783 * Either way, we really should have a @pending here.
2785 if (WARN_ON_ONCE(!pending)) {
2786 task_rq_unlock(rq, p, rf);
2790 if (task_running(rq, p) || READ_ONCE(p->__state) == TASK_WAKING) {
2792 * MIGRATE_ENABLE gets here because 'p == current', but for
2793 * anything else we cannot do is_migration_disabled(), punt
2794 * and have the stopper function handle it all race-free.
2796 stop_pending = pending->stop_pending;
2798 pending->stop_pending = true;
2800 if (flags & SCA_MIGRATE_ENABLE)
2801 p->migration_flags &= ~MDF_PUSH;
2803 task_rq_unlock(rq, p, rf);
2805 if (!stop_pending) {
2806 stop_one_cpu_nowait(cpu_of(rq), migration_cpu_stop,
2807 &pending->arg, &pending->stop_work);
2810 if (flags & SCA_MIGRATE_ENABLE)
2814 if (!is_migration_disabled(p)) {
2815 if (task_on_rq_queued(p))
2816 rq = move_queued_task(rq, rf, p, dest_cpu);
2818 if (!pending->stop_pending) {
2819 p->migration_pending = NULL;
2823 task_rq_unlock(rq, p, rf);
2826 complete_all(&pending->done);
2829 wait_for_completion(&pending->done);
2831 if (refcount_dec_and_test(&pending->refs))
2832 wake_up_var(&pending->refs); /* No UaF, just an address */
2835 * Block the original owner of &pending until all subsequent callers
2836 * have seen the completion and decremented the refcount
2838 wait_var_event(&my_pending.refs, !refcount_read(&my_pending.refs));
2841 WARN_ON_ONCE(my_pending.stop_pending);
2847 * Called with both p->pi_lock and rq->lock held; drops both before returning.
2849 static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
2850 const struct cpumask *new_mask,
2853 struct rq_flags *rf)
2854 __releases(rq->lock)
2855 __releases(p->pi_lock)
2857 const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p);
2858 const struct cpumask *cpu_valid_mask = cpu_active_mask;
2859 bool kthread = p->flags & PF_KTHREAD;
2860 struct cpumask *user_mask = NULL;
2861 unsigned int dest_cpu;
2864 update_rq_clock(rq);
2866 if (kthread || is_migration_disabled(p)) {
2868 * Kernel threads are allowed on online && !active CPUs,
2869 * however, during cpu-hot-unplug, even these might get pushed
2870 * away if not KTHREAD_IS_PER_CPU.
2872 * Specifically, migration_disabled() tasks must not fail the
2873 * cpumask_any_and_distribute() pick below, esp. so on
2874 * SCA_MIGRATE_ENABLE, otherwise we'll not call
2875 * set_cpus_allowed_common() and actually reset p->cpus_ptr.
2877 cpu_valid_mask = cpu_online_mask;
2880 if (!kthread && !cpumask_subset(new_mask, cpu_allowed_mask)) {
2886 * Must re-check here, to close a race against __kthread_bind(),
2887 * sched_setaffinity() is not guaranteed to observe the flag.
2889 if ((flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) {
2894 if (!(flags & SCA_MIGRATE_ENABLE)) {
2895 if (cpumask_equal(&p->cpus_mask, new_mask))
2898 if (WARN_ON_ONCE(p == current &&
2899 is_migration_disabled(p) &&
2900 !cpumask_test_cpu(task_cpu(p), new_mask))) {
2907 * Picking a ~random cpu helps in cases where we are changing affinity
2908 * for groups of tasks (ie. cpuset), so that load balancing is not
2909 * immediately required to distribute the tasks within their new mask.
2911 dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, new_mask);
2912 if (dest_cpu >= nr_cpu_ids) {
2917 __do_set_cpus_allowed(p, new_mask, flags);
2919 if (flags & SCA_USER)
2920 user_mask = clear_user_cpus_ptr(p);
2922 ret = affine_move_task(rq, p, rf, dest_cpu, flags);
2929 task_rq_unlock(rq, p, rf);
2935 * Change a given task's CPU affinity. Migrate the thread to a
2936 * proper CPU and schedule it away if the CPU it's executing on
2937 * is removed from the allowed bitmask.
2939 * NOTE: the caller must have a valid reference to the task, the
2940 * task must not exit() & deallocate itself prematurely. The
2941 * call is not atomic; no spinlocks may be held.
2943 static int __set_cpus_allowed_ptr(struct task_struct *p,
2944 const struct cpumask *new_mask, u32 flags)
2949 rq = task_rq_lock(p, &rf);
2950 return __set_cpus_allowed_ptr_locked(p, new_mask, flags, rq, &rf);
2953 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
2955 return __set_cpus_allowed_ptr(p, new_mask, 0);
2957 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
2960 * Change a given task's CPU affinity to the intersection of its current
2961 * affinity mask and @subset_mask, writing the resulting mask to @new_mask
2962 * and pointing @p->user_cpus_ptr to a copy of the old mask.
2963 * If the resulting mask is empty, leave the affinity unchanged and return
2966 static int restrict_cpus_allowed_ptr(struct task_struct *p,
2967 struct cpumask *new_mask,
2968 const struct cpumask *subset_mask)
2970 struct cpumask *user_mask = NULL;
2975 if (!p->user_cpus_ptr) {
2976 user_mask = kmalloc(cpumask_size(), GFP_KERNEL);
2981 rq = task_rq_lock(p, &rf);
2984 * Forcefully restricting the affinity of a deadline task is
2985 * likely to cause problems, so fail and noisily override the
2988 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
2993 if (!cpumask_and(new_mask, &p->cpus_mask, subset_mask)) {
2999 * We're about to butcher the task affinity, so keep track of what
3000 * the user asked for in case we're able to restore it later on.
3003 cpumask_copy(user_mask, p->cpus_ptr);
3004 p->user_cpus_ptr = user_mask;
3007 return __set_cpus_allowed_ptr_locked(p, new_mask, 0, rq, &rf);
3010 task_rq_unlock(rq, p, &rf);
3016 * Restrict the CPU affinity of task @p so that it is a subset of
3017 * task_cpu_possible_mask() and point @p->user_cpu_ptr to a copy of the
3018 * old affinity mask. If the resulting mask is empty, we warn and walk
3019 * up the cpuset hierarchy until we find a suitable mask.
3021 void force_compatible_cpus_allowed_ptr(struct task_struct *p)
3023 cpumask_var_t new_mask;
3024 const struct cpumask *override_mask = task_cpu_possible_mask(p);
3026 alloc_cpumask_var(&new_mask, GFP_KERNEL);
3029 * __migrate_task() can fail silently in the face of concurrent
3030 * offlining of the chosen destination CPU, so take the hotplug
3031 * lock to ensure that the migration succeeds.
3034 if (!cpumask_available(new_mask))
3037 if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask))
3041 * We failed to find a valid subset of the affinity mask for the
3042 * task, so override it based on its cpuset hierarchy.
3044 cpuset_cpus_allowed(p, new_mask);
3045 override_mask = new_mask;
3048 if (printk_ratelimit()) {
3049 printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n",
3050 task_pid_nr(p), p->comm,
3051 cpumask_pr_args(override_mask));
3054 WARN_ON(set_cpus_allowed_ptr(p, override_mask));
3057 free_cpumask_var(new_mask);
3061 __sched_setaffinity(struct task_struct *p, const struct cpumask *mask);
3064 * Restore the affinity of a task @p which was previously restricted by a
3065 * call to force_compatible_cpus_allowed_ptr(). This will clear (and free)
3066 * @p->user_cpus_ptr.
3068 * It is the caller's responsibility to serialise this with any calls to
3069 * force_compatible_cpus_allowed_ptr(@p).
3071 void relax_compatible_cpus_allowed_ptr(struct task_struct *p)
3073 struct cpumask *user_mask = p->user_cpus_ptr;
3074 unsigned long flags;
3077 * Try to restore the old affinity mask. If this fails, then
3078 * we free the mask explicitly to avoid it being inherited across
3079 * a subsequent fork().
3081 if (!user_mask || !__sched_setaffinity(p, user_mask))
3084 raw_spin_lock_irqsave(&p->pi_lock, flags);
3085 user_mask = clear_user_cpus_ptr(p);
3086 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3091 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
3093 #ifdef CONFIG_SCHED_DEBUG
3094 unsigned int state = READ_ONCE(p->__state);
3097 * We should never call set_task_cpu() on a blocked task,
3098 * ttwu() will sort out the placement.
3100 WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq);
3103 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
3104 * because schedstat_wait_{start,end} rebase migrating task's wait_start
3105 * time relying on p->on_rq.
3107 WARN_ON_ONCE(state == TASK_RUNNING &&
3108 p->sched_class == &fair_sched_class &&
3109 (p->on_rq && !task_on_rq_migrating(p)));
3111 #ifdef CONFIG_LOCKDEP
3113 * The caller should hold either p->pi_lock or rq->lock, when changing
3114 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
3116 * sched_move_task() holds both and thus holding either pins the cgroup,
3119 * Furthermore, all task_rq users should acquire both locks, see
3122 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
3123 lockdep_is_held(__rq_lockp(task_rq(p)))));
3126 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
3128 WARN_ON_ONCE(!cpu_online(new_cpu));
3130 WARN_ON_ONCE(is_migration_disabled(p));
3133 trace_sched_migrate_task(p, new_cpu);
3135 if (task_cpu(p) != new_cpu) {
3136 if (p->sched_class->migrate_task_rq)
3137 p->sched_class->migrate_task_rq(p, new_cpu);
3138 p->se.nr_migrations++;
3140 perf_event_task_migrate(p);
3143 __set_task_cpu(p, new_cpu);
3146 #ifdef CONFIG_NUMA_BALANCING
3147 static void __migrate_swap_task(struct task_struct *p, int cpu)
3149 if (task_on_rq_queued(p)) {
3150 struct rq *src_rq, *dst_rq;
3151 struct rq_flags srf, drf;
3153 src_rq = task_rq(p);
3154 dst_rq = cpu_rq(cpu);
3156 rq_pin_lock(src_rq, &srf);
3157 rq_pin_lock(dst_rq, &drf);
3159 deactivate_task(src_rq, p, 0);
3160 set_task_cpu(p, cpu);
3161 activate_task(dst_rq, p, 0);
3162 check_preempt_curr(dst_rq, p, 0);
3164 rq_unpin_lock(dst_rq, &drf);
3165 rq_unpin_lock(src_rq, &srf);
3169 * Task isn't running anymore; make it appear like we migrated
3170 * it before it went to sleep. This means on wakeup we make the
3171 * previous CPU our target instead of where it really is.
3177 struct migration_swap_arg {
3178 struct task_struct *src_task, *dst_task;
3179 int src_cpu, dst_cpu;
3182 static int migrate_swap_stop(void *data)
3184 struct migration_swap_arg *arg = data;
3185 struct rq *src_rq, *dst_rq;
3188 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
3191 src_rq = cpu_rq(arg->src_cpu);
3192 dst_rq = cpu_rq(arg->dst_cpu);
3194 double_raw_lock(&arg->src_task->pi_lock,
3195 &arg->dst_task->pi_lock);
3196 double_rq_lock(src_rq, dst_rq);
3198 if (task_cpu(arg->dst_task) != arg->dst_cpu)
3201 if (task_cpu(arg->src_task) != arg->src_cpu)
3204 if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
3207 if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
3210 __migrate_swap_task(arg->src_task, arg->dst_cpu);
3211 __migrate_swap_task(arg->dst_task, arg->src_cpu);
3216 double_rq_unlock(src_rq, dst_rq);
3217 raw_spin_unlock(&arg->dst_task->pi_lock);
3218 raw_spin_unlock(&arg->src_task->pi_lock);
3224 * Cross migrate two tasks
3226 int migrate_swap(struct task_struct *cur, struct task_struct *p,
3227 int target_cpu, int curr_cpu)
3229 struct migration_swap_arg arg;
3232 arg = (struct migration_swap_arg){
3234 .src_cpu = curr_cpu,
3236 .dst_cpu = target_cpu,
3239 if (arg.src_cpu == arg.dst_cpu)
3243 * These three tests are all lockless; this is OK since all of them
3244 * will be re-checked with proper locks held further down the line.
3246 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
3249 if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
3252 if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
3255 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
3256 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
3261 #endif /* CONFIG_NUMA_BALANCING */
3264 * wait_task_inactive - wait for a thread to unschedule.
3266 * If @match_state is nonzero, it's the @p->state value just checked and
3267 * not expected to change. If it changes, i.e. @p might have woken up,
3268 * then return zero. When we succeed in waiting for @p to be off its CPU,
3269 * we return a positive number (its total switch count). If a second call
3270 * a short while later returns the same number, the caller can be sure that
3271 * @p has remained unscheduled the whole time.
3273 * The caller must ensure that the task *will* unschedule sometime soon,
3274 * else this function might spin for a *long* time. This function can't
3275 * be called with interrupts off, or it may introduce deadlock with
3276 * smp_call_function() if an IPI is sent by the same process we are
3277 * waiting to become inactive.
3279 unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state)
3281 int running, queued;
3288 * We do the initial early heuristics without holding
3289 * any task-queue locks at all. We'll only try to get
3290 * the runqueue lock when things look like they will
3296 * If the task is actively running on another CPU
3297 * still, just relax and busy-wait without holding
3300 * NOTE! Since we don't hold any locks, it's not
3301 * even sure that "rq" stays as the right runqueue!
3302 * But we don't care, since "task_running()" will
3303 * return false if the runqueue has changed and p
3304 * is actually now running somewhere else!
3306 while (task_running(rq, p)) {
3307 if (match_state && unlikely(READ_ONCE(p->__state) != match_state))
3313 * Ok, time to look more closely! We need the rq
3314 * lock now, to be *sure*. If we're wrong, we'll
3315 * just go back and repeat.
3317 rq = task_rq_lock(p, &rf);
3318 trace_sched_wait_task(p);
3319 running = task_running(rq, p);
3320 queued = task_on_rq_queued(p);
3322 if (!match_state || READ_ONCE(p->__state) == match_state)
3323 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
3324 task_rq_unlock(rq, p, &rf);
3327 * If it changed from the expected state, bail out now.
3329 if (unlikely(!ncsw))
3333 * Was it really running after all now that we
3334 * checked with the proper locks actually held?
3336 * Oops. Go back and try again..
3338 if (unlikely(running)) {
3344 * It's not enough that it's not actively running,
3345 * it must be off the runqueue _entirely_, and not
3348 * So if it was still runnable (but just not actively
3349 * running right now), it's preempted, and we should
3350 * yield - it could be a while.
3352 if (unlikely(queued)) {
3353 ktime_t to = NSEC_PER_SEC / HZ;
3355 set_current_state(TASK_UNINTERRUPTIBLE);
3356 schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD);
3361 * Ahh, all good. It wasn't running, and it wasn't
3362 * runnable, which means that it will never become
3363 * running in the future either. We're all done!
3372 * kick_process - kick a running thread to enter/exit the kernel
3373 * @p: the to-be-kicked thread
3375 * Cause a process which is running on another CPU to enter
3376 * kernel-mode, without any delay. (to get signals handled.)
3378 * NOTE: this function doesn't have to take the runqueue lock,
3379 * because all it wants to ensure is that the remote task enters
3380 * the kernel. If the IPI races and the task has been migrated
3381 * to another CPU then no harm is done and the purpose has been
3384 void kick_process(struct task_struct *p)
3390 if ((cpu != smp_processor_id()) && task_curr(p))
3391 smp_send_reschedule(cpu);
3394 EXPORT_SYMBOL_GPL(kick_process);
3397 * ->cpus_ptr is protected by both rq->lock and p->pi_lock
3399 * A few notes on cpu_active vs cpu_online:
3401 * - cpu_active must be a subset of cpu_online
3403 * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
3404 * see __set_cpus_allowed_ptr(). At this point the newly online
3405 * CPU isn't yet part of the sched domains, and balancing will not
3408 * - on CPU-down we clear cpu_active() to mask the sched domains and
3409 * avoid the load balancer to place new tasks on the to be removed
3410 * CPU. Existing tasks will remain running there and will be taken
3413 * This means that fallback selection must not select !active CPUs.
3414 * And can assume that any active CPU must be online. Conversely
3415 * select_task_rq() below may allow selection of !active CPUs in order
3416 * to satisfy the above rules.
3418 static int select_fallback_rq(int cpu, struct task_struct *p)
3420 int nid = cpu_to_node(cpu);
3421 const struct cpumask *nodemask = NULL;
3422 enum { cpuset, possible, fail } state = cpuset;
3426 * If the node that the CPU is on has been offlined, cpu_to_node()
3427 * will return -1. There is no CPU on the node, and we should
3428 * select the CPU on the other node.
3431 nodemask = cpumask_of_node(nid);
3433 /* Look for allowed, online CPU in same node. */
3434 for_each_cpu(dest_cpu, nodemask) {
3435 if (is_cpu_allowed(p, dest_cpu))
3441 /* Any allowed, online CPU? */
3442 for_each_cpu(dest_cpu, p->cpus_ptr) {
3443 if (!is_cpu_allowed(p, dest_cpu))
3449 /* No more Mr. Nice Guy. */
3452 if (cpuset_cpus_allowed_fallback(p)) {
3459 * XXX When called from select_task_rq() we only
3460 * hold p->pi_lock and again violate locking order.
3462 * More yuck to audit.
3464 do_set_cpus_allowed(p, task_cpu_possible_mask(p));
3474 if (state != cpuset) {
3476 * Don't tell them about moving exiting tasks or
3477 * kernel threads (both mm NULL), since they never
3480 if (p->mm && printk_ratelimit()) {
3481 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
3482 task_pid_nr(p), p->comm, cpu);
3490 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
3493 int select_task_rq(struct task_struct *p, int cpu, int wake_flags)
3495 lockdep_assert_held(&p->pi_lock);
3497 if (p->nr_cpus_allowed > 1 && !is_migration_disabled(p))
3498 cpu = p->sched_class->select_task_rq(p, cpu, wake_flags);
3500 cpu = cpumask_any(p->cpus_ptr);
3503 * In order not to call set_task_cpu() on a blocking task we need
3504 * to rely on ttwu() to place the task on a valid ->cpus_ptr
3507 * Since this is common to all placement strategies, this lives here.
3509 * [ this allows ->select_task() to simply return task_cpu(p) and
3510 * not worry about this generic constraint ]
3512 if (unlikely(!is_cpu_allowed(p, cpu)))
3513 cpu = select_fallback_rq(task_cpu(p), p);
3518 void sched_set_stop_task(int cpu, struct task_struct *stop)
3520 static struct lock_class_key stop_pi_lock;
3521 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
3522 struct task_struct *old_stop = cpu_rq(cpu)->stop;
3526 * Make it appear like a SCHED_FIFO task, its something
3527 * userspace knows about and won't get confused about.
3529 * Also, it will make PI more or less work without too
3530 * much confusion -- but then, stop work should not
3531 * rely on PI working anyway.
3533 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
3535 stop->sched_class = &stop_sched_class;
3538 * The PI code calls rt_mutex_setprio() with ->pi_lock held to
3539 * adjust the effective priority of a task. As a result,
3540 * rt_mutex_setprio() can trigger (RT) balancing operations,
3541 * which can then trigger wakeups of the stop thread to push
3542 * around the current task.
3544 * The stop task itself will never be part of the PI-chain, it
3545 * never blocks, therefore that ->pi_lock recursion is safe.
3546 * Tell lockdep about this by placing the stop->pi_lock in its
3549 lockdep_set_class(&stop->pi_lock, &stop_pi_lock);
3552 cpu_rq(cpu)->stop = stop;
3556 * Reset it back to a normal scheduling class so that
3557 * it can die in pieces.
3559 old_stop->sched_class = &rt_sched_class;
3563 #else /* CONFIG_SMP */
3565 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
3566 const struct cpumask *new_mask,
3569 return set_cpus_allowed_ptr(p, new_mask);
3572 static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { }
3574 static inline bool rq_has_pinned_tasks(struct rq *rq)
3579 #endif /* !CONFIG_SMP */
3582 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
3586 if (!schedstat_enabled())
3592 if (cpu == rq->cpu) {
3593 __schedstat_inc(rq->ttwu_local);
3594 __schedstat_inc(p->stats.nr_wakeups_local);
3596 struct sched_domain *sd;
3598 __schedstat_inc(p->stats.nr_wakeups_remote);
3600 for_each_domain(rq->cpu, sd) {
3601 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
3602 __schedstat_inc(sd->ttwu_wake_remote);
3609 if (wake_flags & WF_MIGRATED)
3610 __schedstat_inc(p->stats.nr_wakeups_migrate);
3611 #endif /* CONFIG_SMP */
3613 __schedstat_inc(rq->ttwu_count);
3614 __schedstat_inc(p->stats.nr_wakeups);
3616 if (wake_flags & WF_SYNC)
3617 __schedstat_inc(p->stats.nr_wakeups_sync);
3621 * Mark the task runnable and perform wakeup-preemption.
3623 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
3624 struct rq_flags *rf)
3626 check_preempt_curr(rq, p, wake_flags);
3627 WRITE_ONCE(p->__state, TASK_RUNNING);
3628 trace_sched_wakeup(p);
3631 if (p->sched_class->task_woken) {
3633 * Our task @p is fully woken up and running; so it's safe to
3634 * drop the rq->lock, hereafter rq is only used for statistics.
3636 rq_unpin_lock(rq, rf);
3637 p->sched_class->task_woken(rq, p);
3638 rq_repin_lock(rq, rf);
3641 if (rq->idle_stamp) {
3642 u64 delta = rq_clock(rq) - rq->idle_stamp;
3643 u64 max = 2*rq->max_idle_balance_cost;
3645 update_avg(&rq->avg_idle, delta);
3647 if (rq->avg_idle > max)
3650 rq->wake_stamp = jiffies;
3651 rq->wake_avg_idle = rq->avg_idle / 2;
3659 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
3660 struct rq_flags *rf)
3662 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
3664 lockdep_assert_rq_held(rq);
3666 if (p->sched_contributes_to_load)
3667 rq->nr_uninterruptible--;
3670 if (wake_flags & WF_MIGRATED)
3671 en_flags |= ENQUEUE_MIGRATED;
3675 delayacct_blkio_end(p);
3676 atomic_dec(&task_rq(p)->nr_iowait);
3679 activate_task(rq, p, en_flags);
3680 ttwu_do_wakeup(rq, p, wake_flags, rf);
3684 * Consider @p being inside a wait loop:
3687 * set_current_state(TASK_UNINTERRUPTIBLE);
3694 * __set_current_state(TASK_RUNNING);
3696 * between set_current_state() and schedule(). In this case @p is still
3697 * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
3700 * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
3701 * then schedule() must still happen and p->state can be changed to
3702 * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
3703 * need to do a full wakeup with enqueue.
3705 * Returns: %true when the wakeup is done,
3708 static int ttwu_runnable(struct task_struct *p, int wake_flags)
3714 rq = __task_rq_lock(p, &rf);
3715 if (task_on_rq_queued(p)) {
3716 /* check_preempt_curr() may use rq clock */
3717 update_rq_clock(rq);
3718 ttwu_do_wakeup(rq, p, wake_flags, &rf);
3721 __task_rq_unlock(rq, &rf);
3727 void sched_ttwu_pending(void *arg)
3729 struct llist_node *llist = arg;
3730 struct rq *rq = this_rq();
3731 struct task_struct *p, *t;
3738 * rq::ttwu_pending racy indication of out-standing wakeups.
3739 * Races such that false-negatives are possible, since they
3740 * are shorter lived that false-positives would be.
3742 WRITE_ONCE(rq->ttwu_pending, 0);
3744 rq_lock_irqsave(rq, &rf);
3745 update_rq_clock(rq);
3747 llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
3748 if (WARN_ON_ONCE(p->on_cpu))
3749 smp_cond_load_acquire(&p->on_cpu, !VAL);
3751 if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
3752 set_task_cpu(p, cpu_of(rq));
3754 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
3757 rq_unlock_irqrestore(rq, &rf);
3760 void send_call_function_single_ipi(int cpu)
3762 struct rq *rq = cpu_rq(cpu);
3764 if (!set_nr_if_polling(rq->idle))
3765 arch_send_call_function_single_ipi(cpu);
3767 trace_sched_wake_idle_without_ipi(cpu);
3771 * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
3772 * necessary. The wakee CPU on receipt of the IPI will queue the task
3773 * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
3774 * of the wakeup instead of the waker.
3776 static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3778 struct rq *rq = cpu_rq(cpu);
3780 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
3782 WRITE_ONCE(rq->ttwu_pending, 1);
3783 __smp_call_single_queue(cpu, &p->wake_entry.llist);
3786 void wake_up_if_idle(int cpu)
3788 struct rq *rq = cpu_rq(cpu);
3793 if (!is_idle_task(rcu_dereference(rq->curr)))
3796 rq_lock_irqsave(rq, &rf);
3797 if (is_idle_task(rq->curr))
3799 /* Else CPU is not idle, do nothing here: */
3800 rq_unlock_irqrestore(rq, &rf);
3806 bool cpus_share_cache(int this_cpu, int that_cpu)
3808 if (this_cpu == that_cpu)
3811 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
3814 static inline bool ttwu_queue_cond(int cpu, int wake_flags)
3817 * Do not complicate things with the async wake_list while the CPU is
3820 if (!cpu_active(cpu))
3824 * If the CPU does not share cache, then queue the task on the
3825 * remote rqs wakelist to avoid accessing remote data.
3827 if (!cpus_share_cache(smp_processor_id(), cpu))
3831 * If the task is descheduling and the only running task on the
3832 * CPU then use the wakelist to offload the task activation to
3833 * the soon-to-be-idle CPU as the current CPU is likely busy.
3834 * nr_running is checked to avoid unnecessary task stacking.
3836 if ((wake_flags & WF_ON_CPU) && cpu_rq(cpu)->nr_running <= 1)
3842 static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3844 if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(cpu, wake_flags)) {
3845 if (WARN_ON_ONCE(cpu == smp_processor_id()))
3848 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
3849 __ttwu_queue_wakelist(p, cpu, wake_flags);
3856 #else /* !CONFIG_SMP */
3858 static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3863 #endif /* CONFIG_SMP */
3865 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
3867 struct rq *rq = cpu_rq(cpu);
3870 if (ttwu_queue_wakelist(p, cpu, wake_flags))
3874 update_rq_clock(rq);
3875 ttwu_do_activate(rq, p, wake_flags, &rf);
3880 * Invoked from try_to_wake_up() to check whether the task can be woken up.
3882 * The caller holds p::pi_lock if p != current or has preemption
3883 * disabled when p == current.
3885 * The rules of PREEMPT_RT saved_state:
3887 * The related locking code always holds p::pi_lock when updating
3888 * p::saved_state, which means the code is fully serialized in both cases.
3890 * The lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. No other
3891 * bits set. This allows to distinguish all wakeup scenarios.
3893 static __always_inline
3894 bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success)
3896 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
3897 WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) &&
3898 state != TASK_RTLOCK_WAIT);
3901 if (READ_ONCE(p->__state) & state) {
3906 #ifdef CONFIG_PREEMPT_RT
3908 * Saved state preserves the task state across blocking on
3909 * an RT lock. If the state matches, set p::saved_state to
3910 * TASK_RUNNING, but do not wake the task because it waits
3911 * for a lock wakeup. Also indicate success because from
3912 * the regular waker's point of view this has succeeded.
3914 * After acquiring the lock the task will restore p::__state
3915 * from p::saved_state which ensures that the regular
3916 * wakeup is not lost. The restore will also set
3917 * p::saved_state to TASK_RUNNING so any further tests will
3918 * not result in false positives vs. @success
3920 if (p->saved_state & state) {
3921 p->saved_state = TASK_RUNNING;
3929 * Notes on Program-Order guarantees on SMP systems.
3933 * The basic program-order guarantee on SMP systems is that when a task [t]
3934 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
3935 * execution on its new CPU [c1].
3937 * For migration (of runnable tasks) this is provided by the following means:
3939 * A) UNLOCK of the rq(c0)->lock scheduling out task t
3940 * B) migration for t is required to synchronize *both* rq(c0)->lock and
3941 * rq(c1)->lock (if not at the same time, then in that order).
3942 * C) LOCK of the rq(c1)->lock scheduling in task
3944 * Release/acquire chaining guarantees that B happens after A and C after B.
3945 * Note: the CPU doing B need not be c0 or c1
3954 * UNLOCK rq(0)->lock
3956 * LOCK rq(0)->lock // orders against CPU0
3958 * UNLOCK rq(0)->lock
3962 * UNLOCK rq(1)->lock
3964 * LOCK rq(1)->lock // orders against CPU2
3967 * UNLOCK rq(1)->lock
3970 * BLOCKING -- aka. SLEEP + WAKEUP
3972 * For blocking we (obviously) need to provide the same guarantee as for
3973 * migration. However the means are completely different as there is no lock
3974 * chain to provide order. Instead we do:
3976 * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
3977 * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
3981 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
3983 * LOCK rq(0)->lock LOCK X->pi_lock
3986 * smp_store_release(X->on_cpu, 0);
3988 * smp_cond_load_acquire(&X->on_cpu, !VAL);
3994 * X->state = RUNNING
3995 * UNLOCK rq(2)->lock
3997 * LOCK rq(2)->lock // orders against CPU1
4000 * UNLOCK rq(2)->lock
4003 * UNLOCK rq(0)->lock
4006 * However, for wakeups there is a second guarantee we must provide, namely we
4007 * must ensure that CONDITION=1 done by the caller can not be reordered with
4008 * accesses to the task state; see try_to_wake_up() and set_current_state().
4012 * try_to_wake_up - wake up a thread
4013 * @p: the thread to be awakened
4014 * @state: the mask of task states that can be woken
4015 * @wake_flags: wake modifier flags (WF_*)
4017 * Conceptually does:
4019 * If (@state & @p->state) @p->state = TASK_RUNNING.
4021 * If the task was not queued/runnable, also place it back on a runqueue.
4023 * This function is atomic against schedule() which would dequeue the task.
4025 * It issues a full memory barrier before accessing @p->state, see the comment
4026 * with set_current_state().
4028 * Uses p->pi_lock to serialize against concurrent wake-ups.
4030 * Relies on p->pi_lock stabilizing:
4033 * - p->sched_task_group
4034 * in order to do migration, see its use of select_task_rq()/set_task_cpu().
4036 * Tries really hard to only take one task_rq(p)->lock for performance.
4037 * Takes rq->lock in:
4038 * - ttwu_runnable() -- old rq, unavoidable, see comment there;
4039 * - ttwu_queue() -- new rq, for enqueue of the task;
4040 * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
4042 * As a consequence we race really badly with just about everything. See the
4043 * many memory barriers and their comments for details.
4045 * Return: %true if @p->state changes (an actual wakeup was done),
4049 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
4051 unsigned long flags;
4052 int cpu, success = 0;
4057 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
4058 * == smp_processor_id()'. Together this means we can special
4059 * case the whole 'p->on_rq && ttwu_runnable()' case below
4060 * without taking any locks.
4063 * - we rely on Program-Order guarantees for all the ordering,
4064 * - we're serialized against set_special_state() by virtue of
4065 * it disabling IRQs (this allows not taking ->pi_lock).
4067 if (!ttwu_state_match(p, state, &success))
4070 trace_sched_waking(p);
4071 WRITE_ONCE(p->__state, TASK_RUNNING);
4072 trace_sched_wakeup(p);
4077 * If we are going to wake up a thread waiting for CONDITION we
4078 * need to ensure that CONDITION=1 done by the caller can not be
4079 * reordered with p->state check below. This pairs with smp_store_mb()
4080 * in set_current_state() that the waiting thread does.
4082 raw_spin_lock_irqsave(&p->pi_lock, flags);
4083 smp_mb__after_spinlock();
4084 if (!ttwu_state_match(p, state, &success))
4087 trace_sched_waking(p);
4090 * Ensure we load p->on_rq _after_ p->state, otherwise it would
4091 * be possible to, falsely, observe p->on_rq == 0 and get stuck
4092 * in smp_cond_load_acquire() below.
4094 * sched_ttwu_pending() try_to_wake_up()
4095 * STORE p->on_rq = 1 LOAD p->state
4098 * __schedule() (switch to task 'p')
4099 * LOCK rq->lock smp_rmb();
4100 * smp_mb__after_spinlock();
4104 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
4106 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4107 * __schedule(). See the comment for smp_mb__after_spinlock().
4109 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
4112 if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
4117 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
4118 * possible to, falsely, observe p->on_cpu == 0.
4120 * One must be running (->on_cpu == 1) in order to remove oneself
4121 * from the runqueue.
4123 * __schedule() (switch to task 'p') try_to_wake_up()
4124 * STORE p->on_cpu = 1 LOAD p->on_rq
4127 * __schedule() (put 'p' to sleep)
4128 * LOCK rq->lock smp_rmb();
4129 * smp_mb__after_spinlock();
4130 * STORE p->on_rq = 0 LOAD p->on_cpu
4132 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4133 * __schedule(). See the comment for smp_mb__after_spinlock().
4135 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
4136 * schedule()'s deactivate_task() has 'happened' and p will no longer
4137 * care about it's own p->state. See the comment in __schedule().
4139 smp_acquire__after_ctrl_dep();
4142 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
4143 * == 0), which means we need to do an enqueue, change p->state to
4144 * TASK_WAKING such that we can unlock p->pi_lock before doing the
4145 * enqueue, such as ttwu_queue_wakelist().
4147 WRITE_ONCE(p->__state, TASK_WAKING);
4150 * If the owning (remote) CPU is still in the middle of schedule() with
4151 * this task as prev, considering queueing p on the remote CPUs wake_list
4152 * which potentially sends an IPI instead of spinning on p->on_cpu to
4153 * let the waker make forward progress. This is safe because IRQs are
4154 * disabled and the IPI will deliver after on_cpu is cleared.
4156 * Ensure we load task_cpu(p) after p->on_cpu:
4158 * set_task_cpu(p, cpu);
4159 * STORE p->cpu = @cpu
4160 * __schedule() (switch to task 'p')
4162 * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
4163 * STORE p->on_cpu = 1 LOAD p->cpu
4165 * to ensure we observe the correct CPU on which the task is currently
4168 if (smp_load_acquire(&p->on_cpu) &&
4169 ttwu_queue_wakelist(p, task_cpu(p), wake_flags | WF_ON_CPU))
4173 * If the owning (remote) CPU is still in the middle of schedule() with
4174 * this task as prev, wait until it's done referencing the task.
4176 * Pairs with the smp_store_release() in finish_task().
4178 * This ensures that tasks getting woken will be fully ordered against
4179 * their previous state and preserve Program Order.
4181 smp_cond_load_acquire(&p->on_cpu, !VAL);
4183 cpu = select_task_rq(p, p->wake_cpu, wake_flags | WF_TTWU);
4184 if (task_cpu(p) != cpu) {
4186 delayacct_blkio_end(p);
4187 atomic_dec(&task_rq(p)->nr_iowait);
4190 wake_flags |= WF_MIGRATED;
4191 psi_ttwu_dequeue(p);
4192 set_task_cpu(p, cpu);
4196 #endif /* CONFIG_SMP */
4198 ttwu_queue(p, cpu, wake_flags);
4200 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4203 ttwu_stat(p, task_cpu(p), wake_flags);
4210 * task_call_func - Invoke a function on task in fixed state
4211 * @p: Process for which the function is to be invoked, can be @current.
4212 * @func: Function to invoke.
4213 * @arg: Argument to function.
4215 * Fix the task in it's current state by avoiding wakeups and or rq operations
4216 * and call @func(@arg) on it. This function can use ->on_rq and task_curr()
4217 * to work out what the state is, if required. Given that @func can be invoked
4218 * with a runqueue lock held, it had better be quite lightweight.
4221 * Whatever @func returns
4223 int task_call_func(struct task_struct *p, task_call_f func, void *arg)
4225 struct rq *rq = NULL;
4230 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
4232 state = READ_ONCE(p->__state);
4235 * Ensure we load p->on_rq after p->__state, otherwise it would be
4236 * possible to, falsely, observe p->on_rq == 0.
4238 * See try_to_wake_up() for a longer comment.
4243 * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when
4244 * the task is blocked. Make sure to check @state since ttwu() can drop
4245 * locks at the end, see ttwu_queue_wakelist().
4247 if (state == TASK_RUNNING || state == TASK_WAKING || p->on_rq)
4248 rq = __task_rq_lock(p, &rf);
4251 * At this point the task is pinned; either:
4252 * - blocked and we're holding off wakeups (pi->lock)
4253 * - woken, and we're holding off enqueue (rq->lock)
4254 * - queued, and we're holding off schedule (rq->lock)
4255 * - running, and we're holding off de-schedule (rq->lock)
4257 * The called function (@func) can use: task_curr(), p->on_rq and
4258 * p->__state to differentiate between these states.
4265 raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
4270 * wake_up_process - Wake up a specific process
4271 * @p: The process to be woken up.
4273 * Attempt to wake up the nominated process and move it to the set of runnable
4276 * Return: 1 if the process was woken up, 0 if it was already running.
4278 * This function executes a full memory barrier before accessing the task state.
4280 int wake_up_process(struct task_struct *p)
4282 return try_to_wake_up(p, TASK_NORMAL, 0);
4284 EXPORT_SYMBOL(wake_up_process);
4286 int wake_up_state(struct task_struct *p, unsigned int state)
4288 return try_to_wake_up(p, state, 0);
4292 * Perform scheduler related setup for a newly forked process p.
4293 * p is forked by current.
4295 * __sched_fork() is basic setup used by init_idle() too:
4297 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
4302 p->se.exec_start = 0;
4303 p->se.sum_exec_runtime = 0;
4304 p->se.prev_sum_exec_runtime = 0;
4305 p->se.nr_migrations = 0;
4307 INIT_LIST_HEAD(&p->se.group_node);
4309 #ifdef CONFIG_FAIR_GROUP_SCHED
4310 p->se.cfs_rq = NULL;
4313 #ifdef CONFIG_SCHEDSTATS
4314 /* Even if schedstat is disabled, there should not be garbage */
4315 memset(&p->stats, 0, sizeof(p->stats));
4318 RB_CLEAR_NODE(&p->dl.rb_node);
4319 init_dl_task_timer(&p->dl);
4320 init_dl_inactive_task_timer(&p->dl);
4321 __dl_clear_params(p);
4323 INIT_LIST_HEAD(&p->rt.run_list);
4325 p->rt.time_slice = sched_rr_timeslice;
4329 #ifdef CONFIG_PREEMPT_NOTIFIERS
4330 INIT_HLIST_HEAD(&p->preempt_notifiers);
4333 #ifdef CONFIG_COMPACTION
4334 p->capture_control = NULL;
4336 init_numa_balancing(clone_flags, p);
4338 p->wake_entry.u_flags = CSD_TYPE_TTWU;
4339 p->migration_pending = NULL;
4343 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
4345 #ifdef CONFIG_NUMA_BALANCING
4347 int sysctl_numa_balancing_mode;
4349 static void __set_numabalancing_state(bool enabled)
4352 static_branch_enable(&sched_numa_balancing);
4354 static_branch_disable(&sched_numa_balancing);
4357 void set_numabalancing_state(bool enabled)
4360 sysctl_numa_balancing_mode = NUMA_BALANCING_NORMAL;
4362 sysctl_numa_balancing_mode = NUMA_BALANCING_DISABLED;
4363 __set_numabalancing_state(enabled);
4366 #ifdef CONFIG_PROC_SYSCTL
4367 int sysctl_numa_balancing(struct ctl_table *table, int write,
4368 void *buffer, size_t *lenp, loff_t *ppos)
4372 int state = sysctl_numa_balancing_mode;
4374 if (write && !capable(CAP_SYS_ADMIN))
4379 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4383 sysctl_numa_balancing_mode = state;
4384 __set_numabalancing_state(state);
4391 #ifdef CONFIG_SCHEDSTATS
4393 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
4395 static void set_schedstats(bool enabled)
4398 static_branch_enable(&sched_schedstats);
4400 static_branch_disable(&sched_schedstats);
4403 void force_schedstat_enabled(void)
4405 if (!schedstat_enabled()) {
4406 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
4407 static_branch_enable(&sched_schedstats);
4411 static int __init setup_schedstats(char *str)
4417 if (!strcmp(str, "enable")) {
4418 set_schedstats(true);
4420 } else if (!strcmp(str, "disable")) {
4421 set_schedstats(false);
4426 pr_warn("Unable to parse schedstats=\n");
4430 __setup("schedstats=", setup_schedstats);
4432 #ifdef CONFIG_PROC_SYSCTL
4433 int sysctl_schedstats(struct ctl_table *table, int write, void *buffer,
4434 size_t *lenp, loff_t *ppos)
4438 int state = static_branch_likely(&sched_schedstats);
4440 if (write && !capable(CAP_SYS_ADMIN))
4445 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4449 set_schedstats(state);
4452 #endif /* CONFIG_PROC_SYSCTL */
4453 #endif /* CONFIG_SCHEDSTATS */
4456 * fork()/clone()-time setup:
4458 int sched_fork(unsigned long clone_flags, struct task_struct *p)
4460 __sched_fork(clone_flags, p);
4462 * We mark the process as NEW here. This guarantees that
4463 * nobody will actually run it, and a signal or other external
4464 * event cannot wake it up and insert it on the runqueue either.
4466 p->__state = TASK_NEW;
4469 * Make sure we do not leak PI boosting priority to the child.
4471 p->prio = current->normal_prio;
4476 * Revert to default priority/policy on fork if requested.
4478 if (unlikely(p->sched_reset_on_fork)) {
4479 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
4480 p->policy = SCHED_NORMAL;
4481 p->static_prio = NICE_TO_PRIO(0);
4483 } else if (PRIO_TO_NICE(p->static_prio) < 0)
4484 p->static_prio = NICE_TO_PRIO(0);
4486 p->prio = p->normal_prio = p->static_prio;
4487 set_load_weight(p, false);
4490 * We don't need the reset flag anymore after the fork. It has
4491 * fulfilled its duty:
4493 p->sched_reset_on_fork = 0;
4496 if (dl_prio(p->prio))
4498 else if (rt_prio(p->prio))
4499 p->sched_class = &rt_sched_class;
4501 p->sched_class = &fair_sched_class;
4503 init_entity_runnable_average(&p->se);
4506 #ifdef CONFIG_SCHED_INFO
4507 if (likely(sched_info_on()))
4508 memset(&p->sched_info, 0, sizeof(p->sched_info));
4510 #if defined(CONFIG_SMP)
4513 init_task_preempt_count(p);
4515 plist_node_init(&p->pushable_tasks, MAX_PRIO);
4516 RB_CLEAR_NODE(&p->pushable_dl_tasks);
4521 void sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs)
4523 unsigned long flags;
4526 * Because we're not yet on the pid-hash, p->pi_lock isn't strictly
4527 * required yet, but lockdep gets upset if rules are violated.
4529 raw_spin_lock_irqsave(&p->pi_lock, flags);
4530 #ifdef CONFIG_CGROUP_SCHED
4532 struct task_group *tg;
4533 tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
4534 struct task_group, css);
4535 tg = autogroup_task_group(p, tg);
4536 p->sched_task_group = tg;
4541 * We're setting the CPU for the first time, we don't migrate,
4542 * so use __set_task_cpu().
4544 __set_task_cpu(p, smp_processor_id());
4545 if (p->sched_class->task_fork)
4546 p->sched_class->task_fork(p);
4547 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4550 void sched_post_fork(struct task_struct *p)
4552 uclamp_post_fork(p);
4555 unsigned long to_ratio(u64 period, u64 runtime)
4557 if (runtime == RUNTIME_INF)
4561 * Doing this here saves a lot of checks in all
4562 * the calling paths, and returning zero seems
4563 * safe for them anyway.
4568 return div64_u64(runtime << BW_SHIFT, period);
4572 * wake_up_new_task - wake up a newly created task for the first time.
4574 * This function will do some initial scheduler statistics housekeeping
4575 * that must be done for every newly created context, then puts the task
4576 * on the runqueue and wakes it.
4578 void wake_up_new_task(struct task_struct *p)
4583 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
4584 WRITE_ONCE(p->__state, TASK_RUNNING);
4587 * Fork balancing, do it here and not earlier because:
4588 * - cpus_ptr can change in the fork path
4589 * - any previously selected CPU might disappear through hotplug
4591 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
4592 * as we're not fully set-up yet.
4594 p->recent_used_cpu = task_cpu(p);
4596 __set_task_cpu(p, select_task_rq(p, task_cpu(p), WF_FORK));
4598 rq = __task_rq_lock(p, &rf);
4599 update_rq_clock(rq);
4600 post_init_entity_util_avg(p);
4602 activate_task(rq, p, ENQUEUE_NOCLOCK);
4603 trace_sched_wakeup_new(p);
4604 check_preempt_curr(rq, p, WF_FORK);
4606 if (p->sched_class->task_woken) {
4608 * Nothing relies on rq->lock after this, so it's fine to
4611 rq_unpin_lock(rq, &rf);
4612 p->sched_class->task_woken(rq, p);
4613 rq_repin_lock(rq, &rf);
4616 task_rq_unlock(rq, p, &rf);
4619 #ifdef CONFIG_PREEMPT_NOTIFIERS
4621 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
4623 void preempt_notifier_inc(void)
4625 static_branch_inc(&preempt_notifier_key);
4627 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
4629 void preempt_notifier_dec(void)
4631 static_branch_dec(&preempt_notifier_key);
4633 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
4636 * preempt_notifier_register - tell me when current is being preempted & rescheduled
4637 * @notifier: notifier struct to register
4639 void preempt_notifier_register(struct preempt_notifier *notifier)
4641 if (!static_branch_unlikely(&preempt_notifier_key))
4642 WARN(1, "registering preempt_notifier while notifiers disabled\n");
4644 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
4646 EXPORT_SYMBOL_GPL(preempt_notifier_register);
4649 * preempt_notifier_unregister - no longer interested in preemption notifications
4650 * @notifier: notifier struct to unregister
4652 * This is *not* safe to call from within a preemption notifier.
4654 void preempt_notifier_unregister(struct preempt_notifier *notifier)
4656 hlist_del(¬ifier->link);
4658 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
4660 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
4662 struct preempt_notifier *notifier;
4664 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
4665 notifier->ops->sched_in(notifier, raw_smp_processor_id());
4668 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
4670 if (static_branch_unlikely(&preempt_notifier_key))
4671 __fire_sched_in_preempt_notifiers(curr);
4675 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
4676 struct task_struct *next)
4678 struct preempt_notifier *notifier;
4680 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
4681 notifier->ops->sched_out(notifier, next);
4684 static __always_inline void
4685 fire_sched_out_preempt_notifiers(struct task_struct *curr,
4686 struct task_struct *next)
4688 if (static_branch_unlikely(&preempt_notifier_key))
4689 __fire_sched_out_preempt_notifiers(curr, next);
4692 #else /* !CONFIG_PREEMPT_NOTIFIERS */
4694 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
4699 fire_sched_out_preempt_notifiers(struct task_struct *curr,
4700 struct task_struct *next)
4704 #endif /* CONFIG_PREEMPT_NOTIFIERS */
4706 static inline void prepare_task(struct task_struct *next)
4710 * Claim the task as running, we do this before switching to it
4711 * such that any running task will have this set.
4713 * See the ttwu() WF_ON_CPU case and its ordering comment.
4715 WRITE_ONCE(next->on_cpu, 1);
4719 static inline void finish_task(struct task_struct *prev)
4723 * This must be the very last reference to @prev from this CPU. After
4724 * p->on_cpu is cleared, the task can be moved to a different CPU. We
4725 * must ensure this doesn't happen until the switch is completely
4728 * In particular, the load of prev->state in finish_task_switch() must
4729 * happen before this.
4731 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
4733 smp_store_release(&prev->on_cpu, 0);
4739 static void do_balance_callbacks(struct rq *rq, struct callback_head *head)
4741 void (*func)(struct rq *rq);
4742 struct callback_head *next;
4744 lockdep_assert_rq_held(rq);
4747 func = (void (*)(struct rq *))head->func;
4756 static void balance_push(struct rq *rq);
4758 struct callback_head balance_push_callback = {
4760 .func = (void (*)(struct callback_head *))balance_push,
4763 static inline struct callback_head *splice_balance_callbacks(struct rq *rq)
4765 struct callback_head *head = rq->balance_callback;
4767 lockdep_assert_rq_held(rq);
4769 rq->balance_callback = NULL;
4774 static void __balance_callbacks(struct rq *rq)
4776 do_balance_callbacks(rq, splice_balance_callbacks(rq));
4779 static inline void balance_callbacks(struct rq *rq, struct callback_head *head)
4781 unsigned long flags;
4783 if (unlikely(head)) {
4784 raw_spin_rq_lock_irqsave(rq, flags);
4785 do_balance_callbacks(rq, head);
4786 raw_spin_rq_unlock_irqrestore(rq, flags);
4792 static inline void __balance_callbacks(struct rq *rq)
4796 static inline struct callback_head *splice_balance_callbacks(struct rq *rq)
4801 static inline void balance_callbacks(struct rq *rq, struct callback_head *head)
4808 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
4811 * Since the runqueue lock will be released by the next
4812 * task (which is an invalid locking op but in the case
4813 * of the scheduler it's an obvious special-case), so we
4814 * do an early lockdep release here:
4816 rq_unpin_lock(rq, rf);
4817 spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_);
4818 #ifdef CONFIG_DEBUG_SPINLOCK
4819 /* this is a valid case when another task releases the spinlock */
4820 rq_lockp(rq)->owner = next;
4824 static inline void finish_lock_switch(struct rq *rq)
4827 * If we are tracking spinlock dependencies then we have to
4828 * fix up the runqueue lock - which gets 'carried over' from
4829 * prev into current:
4831 spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_);
4832 __balance_callbacks(rq);
4833 raw_spin_rq_unlock_irq(rq);
4837 * NOP if the arch has not defined these:
4840 #ifndef prepare_arch_switch
4841 # define prepare_arch_switch(next) do { } while (0)
4844 #ifndef finish_arch_post_lock_switch
4845 # define finish_arch_post_lock_switch() do { } while (0)
4848 static inline void kmap_local_sched_out(void)
4850 #ifdef CONFIG_KMAP_LOCAL
4851 if (unlikely(current->kmap_ctrl.idx))
4852 __kmap_local_sched_out();
4856 static inline void kmap_local_sched_in(void)
4858 #ifdef CONFIG_KMAP_LOCAL
4859 if (unlikely(current->kmap_ctrl.idx))
4860 __kmap_local_sched_in();
4865 * prepare_task_switch - prepare to switch tasks
4866 * @rq: the runqueue preparing to switch
4867 * @prev: the current task that is being switched out
4868 * @next: the task we are going to switch to.
4870 * This is called with the rq lock held and interrupts off. It must
4871 * be paired with a subsequent finish_task_switch after the context
4874 * prepare_task_switch sets up locking and calls architecture specific
4878 prepare_task_switch(struct rq *rq, struct task_struct *prev,
4879 struct task_struct *next)
4881 kcov_prepare_switch(prev);
4882 sched_info_switch(rq, prev, next);
4883 perf_event_task_sched_out(prev, next);
4885 fire_sched_out_preempt_notifiers(prev, next);
4886 kmap_local_sched_out();
4888 prepare_arch_switch(next);
4892 * finish_task_switch - clean up after a task-switch
4893 * @prev: the thread we just switched away from.
4895 * finish_task_switch must be called after the context switch, paired
4896 * with a prepare_task_switch call before the context switch.
4897 * finish_task_switch will reconcile locking set up by prepare_task_switch,
4898 * and do any other architecture-specific cleanup actions.
4900 * Note that we may have delayed dropping an mm in context_switch(). If
4901 * so, we finish that here outside of the runqueue lock. (Doing it
4902 * with the lock held can cause deadlocks; see schedule() for
4905 * The context switch have flipped the stack from under us and restored the
4906 * local variables which were saved when this task called schedule() in the
4907 * past. prev == current is still correct but we need to recalculate this_rq
4908 * because prev may have moved to another CPU.
4910 static struct rq *finish_task_switch(struct task_struct *prev)
4911 __releases(rq->lock)
4913 struct rq *rq = this_rq();
4914 struct mm_struct *mm = rq->prev_mm;
4915 unsigned int prev_state;
4918 * The previous task will have left us with a preempt_count of 2
4919 * because it left us after:
4922 * preempt_disable(); // 1
4924 * raw_spin_lock_irq(&rq->lock) // 2
4926 * Also, see FORK_PREEMPT_COUNT.
4928 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
4929 "corrupted preempt_count: %s/%d/0x%x\n",
4930 current->comm, current->pid, preempt_count()))
4931 preempt_count_set(FORK_PREEMPT_COUNT);
4936 * A task struct has one reference for the use as "current".
4937 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
4938 * schedule one last time. The schedule call will never return, and
4939 * the scheduled task must drop that reference.
4941 * We must observe prev->state before clearing prev->on_cpu (in
4942 * finish_task), otherwise a concurrent wakeup can get prev
4943 * running on another CPU and we could rave with its RUNNING -> DEAD
4944 * transition, resulting in a double drop.
4946 prev_state = READ_ONCE(prev->__state);
4947 vtime_task_switch(prev);
4948 perf_event_task_sched_in(prev, current);
4950 tick_nohz_task_switch();
4951 finish_lock_switch(rq);
4952 finish_arch_post_lock_switch();
4953 kcov_finish_switch(current);
4955 * kmap_local_sched_out() is invoked with rq::lock held and
4956 * interrupts disabled. There is no requirement for that, but the
4957 * sched out code does not have an interrupt enabled section.
4958 * Restoring the maps on sched in does not require interrupts being
4961 kmap_local_sched_in();
4963 fire_sched_in_preempt_notifiers(current);
4965 * When switching through a kernel thread, the loop in
4966 * membarrier_{private,global}_expedited() may have observed that
4967 * kernel thread and not issued an IPI. It is therefore possible to
4968 * schedule between user->kernel->user threads without passing though
4969 * switch_mm(). Membarrier requires a barrier after storing to
4970 * rq->curr, before returning to userspace, so provide them here:
4972 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
4973 * provided by mmdrop(),
4974 * - a sync_core for SYNC_CORE.
4977 membarrier_mm_sync_core_before_usermode(mm);
4980 if (unlikely(prev_state == TASK_DEAD)) {
4981 if (prev->sched_class->task_dead)
4982 prev->sched_class->task_dead(prev);
4984 /* Task is done with its stack. */
4985 put_task_stack(prev);
4987 put_task_struct_rcu_user(prev);
4994 * schedule_tail - first thing a freshly forked thread must call.
4995 * @prev: the thread we just switched away from.
4997 asmlinkage __visible void schedule_tail(struct task_struct *prev)
4998 __releases(rq->lock)
5001 * New tasks start with FORK_PREEMPT_COUNT, see there and
5002 * finish_task_switch() for details.
5004 * finish_task_switch() will drop rq->lock() and lower preempt_count
5005 * and the preempt_enable() will end up enabling preemption (on
5006 * PREEMPT_COUNT kernels).
5009 finish_task_switch(prev);
5012 if (current->set_child_tid)
5013 put_user(task_pid_vnr(current), current->set_child_tid);
5015 calculate_sigpending();
5019 * context_switch - switch to the new MM and the new thread's register state.
5021 static __always_inline struct rq *
5022 context_switch(struct rq *rq, struct task_struct *prev,
5023 struct task_struct *next, struct rq_flags *rf)
5025 prepare_task_switch(rq, prev, next);
5028 * For paravirt, this is coupled with an exit in switch_to to
5029 * combine the page table reload and the switch backend into
5032 arch_start_context_switch(prev);
5035 * kernel -> kernel lazy + transfer active
5036 * user -> kernel lazy + mmgrab() active
5038 * kernel -> user switch + mmdrop() active
5039 * user -> user switch
5041 if (!next->mm) { // to kernel
5042 enter_lazy_tlb(prev->active_mm, next);
5044 next->active_mm = prev->active_mm;
5045 if (prev->mm) // from user
5046 mmgrab(prev->active_mm);
5048 prev->active_mm = NULL;
5050 membarrier_switch_mm(rq, prev->active_mm, next->mm);
5052 * sys_membarrier() requires an smp_mb() between setting
5053 * rq->curr / membarrier_switch_mm() and returning to userspace.
5055 * The below provides this either through switch_mm(), or in
5056 * case 'prev->active_mm == next->mm' through
5057 * finish_task_switch()'s mmdrop().
5059 switch_mm_irqs_off(prev->active_mm, next->mm, next);
5061 if (!prev->mm) { // from kernel
5062 /* will mmdrop() in finish_task_switch(). */
5063 rq->prev_mm = prev->active_mm;
5064 prev->active_mm = NULL;
5068 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
5070 prepare_lock_switch(rq, next, rf);
5072 /* Here we just switch the register state and the stack. */
5073 switch_to(prev, next, prev);
5076 return finish_task_switch(prev);
5080 * nr_running and nr_context_switches:
5082 * externally visible scheduler statistics: current number of runnable
5083 * threads, total number of context switches performed since bootup.
5085 unsigned int nr_running(void)
5087 unsigned int i, sum = 0;
5089 for_each_online_cpu(i)
5090 sum += cpu_rq(i)->nr_running;
5096 * Check if only the current task is running on the CPU.
5098 * Caution: this function does not check that the caller has disabled
5099 * preemption, thus the result might have a time-of-check-to-time-of-use
5100 * race. The caller is responsible to use it correctly, for example:
5102 * - from a non-preemptible section (of course)
5104 * - from a thread that is bound to a single CPU
5106 * - in a loop with very short iterations (e.g. a polling loop)
5108 bool single_task_running(void)
5110 return raw_rq()->nr_running == 1;
5112 EXPORT_SYMBOL(single_task_running);
5114 unsigned long long nr_context_switches(void)
5117 unsigned long long sum = 0;
5119 for_each_possible_cpu(i)
5120 sum += cpu_rq(i)->nr_switches;
5126 * Consumers of these two interfaces, like for example the cpuidle menu
5127 * governor, are using nonsensical data. Preferring shallow idle state selection
5128 * for a CPU that has IO-wait which might not even end up running the task when
5129 * it does become runnable.
5132 unsigned int nr_iowait_cpu(int cpu)
5134 return atomic_read(&cpu_rq(cpu)->nr_iowait);
5138 * IO-wait accounting, and how it's mostly bollocks (on SMP).
5140 * The idea behind IO-wait account is to account the idle time that we could
5141 * have spend running if it were not for IO. That is, if we were to improve the
5142 * storage performance, we'd have a proportional reduction in IO-wait time.
5144 * This all works nicely on UP, where, when a task blocks on IO, we account
5145 * idle time as IO-wait, because if the storage were faster, it could've been
5146 * running and we'd not be idle.
5148 * This has been extended to SMP, by doing the same for each CPU. This however
5151 * Imagine for instance the case where two tasks block on one CPU, only the one
5152 * CPU will have IO-wait accounted, while the other has regular idle. Even
5153 * though, if the storage were faster, both could've ran at the same time,
5154 * utilising both CPUs.
5156 * This means, that when looking globally, the current IO-wait accounting on
5157 * SMP is a lower bound, by reason of under accounting.
5159 * Worse, since the numbers are provided per CPU, they are sometimes
5160 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
5161 * associated with any one particular CPU, it can wake to another CPU than it
5162 * blocked on. This means the per CPU IO-wait number is meaningless.
5164 * Task CPU affinities can make all that even more 'interesting'.
5167 unsigned int nr_iowait(void)
5169 unsigned int i, sum = 0;
5171 for_each_possible_cpu(i)
5172 sum += nr_iowait_cpu(i);
5180 * sched_exec - execve() is a valuable balancing opportunity, because at
5181 * this point the task has the smallest effective memory and cache footprint.
5183 void sched_exec(void)
5185 struct task_struct *p = current;
5186 unsigned long flags;
5189 raw_spin_lock_irqsave(&p->pi_lock, flags);
5190 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC);
5191 if (dest_cpu == smp_processor_id())
5194 if (likely(cpu_active(dest_cpu))) {
5195 struct migration_arg arg = { p, dest_cpu };
5197 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5198 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
5202 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5207 DEFINE_PER_CPU(struct kernel_stat, kstat);
5208 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
5210 EXPORT_PER_CPU_SYMBOL(kstat);
5211 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
5214 * The function fair_sched_class.update_curr accesses the struct curr
5215 * and its field curr->exec_start; when called from task_sched_runtime(),
5216 * we observe a high rate of cache misses in practice.
5217 * Prefetching this data results in improved performance.
5219 static inline void prefetch_curr_exec_start(struct task_struct *p)
5221 #ifdef CONFIG_FAIR_GROUP_SCHED
5222 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
5224 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
5227 prefetch(&curr->exec_start);
5231 * Return accounted runtime for the task.
5232 * In case the task is currently running, return the runtime plus current's
5233 * pending runtime that have not been accounted yet.
5235 unsigned long long task_sched_runtime(struct task_struct *p)
5241 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
5243 * 64-bit doesn't need locks to atomically read a 64-bit value.
5244 * So we have a optimization chance when the task's delta_exec is 0.
5245 * Reading ->on_cpu is racy, but this is ok.
5247 * If we race with it leaving CPU, we'll take a lock. So we're correct.
5248 * If we race with it entering CPU, unaccounted time is 0. This is
5249 * indistinguishable from the read occurring a few cycles earlier.
5250 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
5251 * been accounted, so we're correct here as well.
5253 if (!p->on_cpu || !task_on_rq_queued(p))
5254 return p->se.sum_exec_runtime;
5257 rq = task_rq_lock(p, &rf);
5259 * Must be ->curr _and_ ->on_rq. If dequeued, we would
5260 * project cycles that may never be accounted to this
5261 * thread, breaking clock_gettime().
5263 if (task_current(rq, p) && task_on_rq_queued(p)) {
5264 prefetch_curr_exec_start(p);
5265 update_rq_clock(rq);
5266 p->sched_class->update_curr(rq);
5268 ns = p->se.sum_exec_runtime;
5269 task_rq_unlock(rq, p, &rf);
5274 #ifdef CONFIG_SCHED_DEBUG
5275 static u64 cpu_resched_latency(struct rq *rq)
5277 int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms);
5278 u64 resched_latency, now = rq_clock(rq);
5279 static bool warned_once;
5281 if (sysctl_resched_latency_warn_once && warned_once)
5284 if (!need_resched() || !latency_warn_ms)
5287 if (system_state == SYSTEM_BOOTING)
5290 if (!rq->last_seen_need_resched_ns) {
5291 rq->last_seen_need_resched_ns = now;
5292 rq->ticks_without_resched = 0;
5296 rq->ticks_without_resched++;
5297 resched_latency = now - rq->last_seen_need_resched_ns;
5298 if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC)
5303 return resched_latency;
5306 static int __init setup_resched_latency_warn_ms(char *str)
5310 if ((kstrtol(str, 0, &val))) {
5311 pr_warn("Unable to set resched_latency_warn_ms\n");
5315 sysctl_resched_latency_warn_ms = val;
5318 __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms);
5320 static inline u64 cpu_resched_latency(struct rq *rq) { return 0; }
5321 #endif /* CONFIG_SCHED_DEBUG */
5324 * This function gets called by the timer code, with HZ frequency.
5325 * We call it with interrupts disabled.
5327 void scheduler_tick(void)
5329 int cpu = smp_processor_id();
5330 struct rq *rq = cpu_rq(cpu);
5331 struct task_struct *curr = rq->curr;
5333 unsigned long thermal_pressure;
5334 u64 resched_latency;
5336 arch_scale_freq_tick();
5341 update_rq_clock(rq);
5342 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
5343 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure);
5344 curr->sched_class->task_tick(rq, curr, 0);
5345 if (sched_feat(LATENCY_WARN))
5346 resched_latency = cpu_resched_latency(rq);
5347 calc_global_load_tick(rq);
5348 sched_core_tick(rq);
5352 if (sched_feat(LATENCY_WARN) && resched_latency)
5353 resched_latency_warn(cpu, resched_latency);
5355 perf_event_task_tick();
5358 rq->idle_balance = idle_cpu(cpu);
5359 trigger_load_balance(rq);
5363 #ifdef CONFIG_NO_HZ_FULL
5368 struct delayed_work work;
5370 /* Values for ->state, see diagram below. */
5371 #define TICK_SCHED_REMOTE_OFFLINE 0
5372 #define TICK_SCHED_REMOTE_OFFLINING 1
5373 #define TICK_SCHED_REMOTE_RUNNING 2
5376 * State diagram for ->state:
5379 * TICK_SCHED_REMOTE_OFFLINE
5382 * | | sched_tick_remote()
5385 * +--TICK_SCHED_REMOTE_OFFLINING
5388 * sched_tick_start() | | sched_tick_stop()
5391 * TICK_SCHED_REMOTE_RUNNING
5394 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
5395 * and sched_tick_start() are happy to leave the state in RUNNING.
5398 static struct tick_work __percpu *tick_work_cpu;
5400 static void sched_tick_remote(struct work_struct *work)
5402 struct delayed_work *dwork = to_delayed_work(work);
5403 struct tick_work *twork = container_of(dwork, struct tick_work, work);
5404 int cpu = twork->cpu;
5405 struct rq *rq = cpu_rq(cpu);
5406 struct task_struct *curr;
5412 * Handle the tick only if it appears the remote CPU is running in full
5413 * dynticks mode. The check is racy by nature, but missing a tick or
5414 * having one too much is no big deal because the scheduler tick updates
5415 * statistics and checks timeslices in a time-independent way, regardless
5416 * of when exactly it is running.
5418 if (!tick_nohz_tick_stopped_cpu(cpu))
5421 rq_lock_irq(rq, &rf);
5423 if (cpu_is_offline(cpu))
5426 update_rq_clock(rq);
5428 if (!is_idle_task(curr)) {
5430 * Make sure the next tick runs within a reasonable
5433 delta = rq_clock_task(rq) - curr->se.exec_start;
5434 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
5436 curr->sched_class->task_tick(rq, curr, 0);
5438 calc_load_nohz_remote(rq);
5440 rq_unlock_irq(rq, &rf);
5444 * Run the remote tick once per second (1Hz). This arbitrary
5445 * frequency is large enough to avoid overload but short enough
5446 * to keep scheduler internal stats reasonably up to date. But
5447 * first update state to reflect hotplug activity if required.
5449 os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
5450 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
5451 if (os == TICK_SCHED_REMOTE_RUNNING)
5452 queue_delayed_work(system_unbound_wq, dwork, HZ);
5455 static void sched_tick_start(int cpu)
5458 struct tick_work *twork;
5460 if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5463 WARN_ON_ONCE(!tick_work_cpu);
5465 twork = per_cpu_ptr(tick_work_cpu, cpu);
5466 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
5467 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
5468 if (os == TICK_SCHED_REMOTE_OFFLINE) {
5470 INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
5471 queue_delayed_work(system_unbound_wq, &twork->work, HZ);
5475 #ifdef CONFIG_HOTPLUG_CPU
5476 static void sched_tick_stop(int cpu)
5478 struct tick_work *twork;
5481 if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5484 WARN_ON_ONCE(!tick_work_cpu);
5486 twork = per_cpu_ptr(tick_work_cpu, cpu);
5487 /* There cannot be competing actions, but don't rely on stop-machine. */
5488 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
5489 WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
5490 /* Don't cancel, as this would mess up the state machine. */
5492 #endif /* CONFIG_HOTPLUG_CPU */
5494 int __init sched_tick_offload_init(void)
5496 tick_work_cpu = alloc_percpu(struct tick_work);
5497 BUG_ON(!tick_work_cpu);
5501 #else /* !CONFIG_NO_HZ_FULL */
5502 static inline void sched_tick_start(int cpu) { }
5503 static inline void sched_tick_stop(int cpu) { }
5506 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
5507 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
5509 * If the value passed in is equal to the current preempt count
5510 * then we just disabled preemption. Start timing the latency.
5512 static inline void preempt_latency_start(int val)
5514 if (preempt_count() == val) {
5515 unsigned long ip = get_lock_parent_ip();
5516 #ifdef CONFIG_DEBUG_PREEMPT
5517 current->preempt_disable_ip = ip;
5519 trace_preempt_off(CALLER_ADDR0, ip);
5523 void preempt_count_add(int val)
5525 #ifdef CONFIG_DEBUG_PREEMPT
5529 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5532 __preempt_count_add(val);
5533 #ifdef CONFIG_DEBUG_PREEMPT
5535 * Spinlock count overflowing soon?
5537 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5540 preempt_latency_start(val);
5542 EXPORT_SYMBOL(preempt_count_add);
5543 NOKPROBE_SYMBOL(preempt_count_add);
5546 * If the value passed in equals to the current preempt count
5547 * then we just enabled preemption. Stop timing the latency.
5549 static inline void preempt_latency_stop(int val)
5551 if (preempt_count() == val)
5552 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
5555 void preempt_count_sub(int val)
5557 #ifdef CONFIG_DEBUG_PREEMPT
5561 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
5564 * Is the spinlock portion underflowing?
5566 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5567 !(preempt_count() & PREEMPT_MASK)))
5571 preempt_latency_stop(val);
5572 __preempt_count_sub(val);
5574 EXPORT_SYMBOL(preempt_count_sub);
5575 NOKPROBE_SYMBOL(preempt_count_sub);
5578 static inline void preempt_latency_start(int val) { }
5579 static inline void preempt_latency_stop(int val) { }
5582 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
5584 #ifdef CONFIG_DEBUG_PREEMPT
5585 return p->preempt_disable_ip;
5592 * Print scheduling while atomic bug:
5594 static noinline void __schedule_bug(struct task_struct *prev)
5596 /* Save this before calling printk(), since that will clobber it */
5597 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
5599 if (oops_in_progress)
5602 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
5603 prev->comm, prev->pid, preempt_count());
5605 debug_show_held_locks(prev);
5607 if (irqs_disabled())
5608 print_irqtrace_events(prev);
5609 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
5610 && in_atomic_preempt_off()) {
5611 pr_err("Preemption disabled at:");
5612 print_ip_sym(KERN_ERR, preempt_disable_ip);
5615 panic("scheduling while atomic\n");
5618 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5622 * Various schedule()-time debugging checks and statistics:
5624 static inline void schedule_debug(struct task_struct *prev, bool preempt)
5626 #ifdef CONFIG_SCHED_STACK_END_CHECK
5627 if (task_stack_end_corrupted(prev))
5628 panic("corrupted stack end detected inside scheduler\n");
5630 if (task_scs_end_corrupted(prev))
5631 panic("corrupted shadow stack detected inside scheduler\n");
5634 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
5635 if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) {
5636 printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
5637 prev->comm, prev->pid, prev->non_block_count);
5639 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5643 if (unlikely(in_atomic_preempt_off())) {
5644 __schedule_bug(prev);
5645 preempt_count_set(PREEMPT_DISABLED);
5648 SCHED_WARN_ON(ct_state() == CONTEXT_USER);
5650 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5652 schedstat_inc(this_rq()->sched_count);
5655 static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
5656 struct rq_flags *rf)
5659 const struct sched_class *class;
5661 * We must do the balancing pass before put_prev_task(), such
5662 * that when we release the rq->lock the task is in the same
5663 * state as before we took rq->lock.
5665 * We can terminate the balance pass as soon as we know there is
5666 * a runnable task of @class priority or higher.
5668 for_class_range(class, prev->sched_class, &idle_sched_class) {
5669 if (class->balance(rq, prev, rf))
5674 put_prev_task(rq, prev);
5678 * Pick up the highest-prio task:
5680 static inline struct task_struct *
5681 __pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5683 const struct sched_class *class;
5684 struct task_struct *p;
5687 * Optimization: we know that if all tasks are in the fair class we can
5688 * call that function directly, but only if the @prev task wasn't of a
5689 * higher scheduling class, because otherwise those lose the
5690 * opportunity to pull in more work from other CPUs.
5692 if (likely(prev->sched_class <= &fair_sched_class &&
5693 rq->nr_running == rq->cfs.h_nr_running)) {
5695 p = pick_next_task_fair(rq, prev, rf);
5696 if (unlikely(p == RETRY_TASK))
5699 /* Assume the next prioritized class is idle_sched_class */
5701 put_prev_task(rq, prev);
5702 p = pick_next_task_idle(rq);
5709 put_prev_task_balance(rq, prev, rf);
5711 for_each_class(class) {
5712 p = class->pick_next_task(rq);
5717 BUG(); /* The idle class should always have a runnable task. */
5720 #ifdef CONFIG_SCHED_CORE
5721 static inline bool is_task_rq_idle(struct task_struct *t)
5723 return (task_rq(t)->idle == t);
5726 static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
5728 return is_task_rq_idle(a) || (a->core_cookie == cookie);
5731 static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
5733 if (is_task_rq_idle(a) || is_task_rq_idle(b))
5736 return a->core_cookie == b->core_cookie;
5739 static inline struct task_struct *pick_task(struct rq *rq)
5741 const struct sched_class *class;
5742 struct task_struct *p;
5744 for_each_class(class) {
5745 p = class->pick_task(rq);
5750 BUG(); /* The idle class should always have a runnable task. */
5753 extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
5755 static void queue_core_balance(struct rq *rq);
5757 static struct task_struct *
5758 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5760 struct task_struct *next, *p, *max = NULL;
5761 const struct cpumask *smt_mask;
5762 bool fi_before = false;
5763 bool core_clock_updated = (rq == rq->core);
5764 unsigned long cookie;
5765 int i, cpu, occ = 0;
5769 if (!sched_core_enabled(rq))
5770 return __pick_next_task(rq, prev, rf);
5774 /* Stopper task is switching into idle, no need core-wide selection. */
5775 if (cpu_is_offline(cpu)) {
5777 * Reset core_pick so that we don't enter the fastpath when
5778 * coming online. core_pick would already be migrated to
5779 * another cpu during offline.
5781 rq->core_pick = NULL;
5782 return __pick_next_task(rq, prev, rf);
5786 * If there were no {en,de}queues since we picked (IOW, the task
5787 * pointers are all still valid), and we haven't scheduled the last
5788 * pick yet, do so now.
5790 * rq->core_pick can be NULL if no selection was made for a CPU because
5791 * it was either offline or went offline during a sibling's core-wide
5792 * selection. In this case, do a core-wide selection.
5794 if (rq->core->core_pick_seq == rq->core->core_task_seq &&
5795 rq->core->core_pick_seq != rq->core_sched_seq &&
5797 WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
5799 next = rq->core_pick;
5801 put_prev_task(rq, prev);
5802 set_next_task(rq, next);
5805 rq->core_pick = NULL;
5809 put_prev_task_balance(rq, prev, rf);
5811 smt_mask = cpu_smt_mask(cpu);
5812 need_sync = !!rq->core->core_cookie;
5815 rq->core->core_cookie = 0UL;
5816 if (rq->core->core_forceidle_count) {
5817 if (!core_clock_updated) {
5818 update_rq_clock(rq->core);
5819 core_clock_updated = true;
5821 sched_core_account_forceidle(rq);
5822 /* reset after accounting force idle */
5823 rq->core->core_forceidle_start = 0;
5824 rq->core->core_forceidle_count = 0;
5825 rq->core->core_forceidle_occupation = 0;
5831 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
5833 * @task_seq guards the task state ({en,de}queues)
5834 * @pick_seq is the @task_seq we did a selection on
5835 * @sched_seq is the @pick_seq we scheduled
5837 * However, preemptions can cause multiple picks on the same task set.
5838 * 'Fix' this by also increasing @task_seq for every pick.
5840 rq->core->core_task_seq++;
5843 * Optimize for common case where this CPU has no cookies
5844 * and there are no cookied tasks running on siblings.
5847 next = pick_task(rq);
5848 if (!next->core_cookie) {
5849 rq->core_pick = NULL;
5851 * For robustness, update the min_vruntime_fi for
5852 * unconstrained picks as well.
5854 WARN_ON_ONCE(fi_before);
5855 task_vruntime_update(rq, next, false);
5861 * For each thread: do the regular task pick and find the max prio task
5864 * Tie-break prio towards the current CPU
5866 for_each_cpu_wrap(i, smt_mask, cpu) {
5870 * Current cpu always has its clock updated on entrance to
5871 * pick_next_task(). If the current cpu is not the core,
5872 * the core may also have been updated above.
5874 if (i != cpu && (rq_i != rq->core || !core_clock_updated))
5875 update_rq_clock(rq_i);
5877 p = rq_i->core_pick = pick_task(rq_i);
5878 if (!max || prio_less(max, p, fi_before))
5882 cookie = rq->core->core_cookie = max->core_cookie;
5885 * For each thread: try and find a runnable task that matches @max or
5888 for_each_cpu(i, smt_mask) {
5890 p = rq_i->core_pick;
5892 if (!cookie_equals(p, cookie)) {
5895 p = sched_core_find(rq_i, cookie);
5897 p = idle_sched_class.pick_task(rq_i);
5900 rq_i->core_pick = p;
5902 if (p == rq_i->idle) {
5903 if (rq_i->nr_running) {
5904 rq->core->core_forceidle_count++;
5906 rq->core->core_forceidle_seq++;
5913 if (schedstat_enabled() && rq->core->core_forceidle_count) {
5914 rq->core->core_forceidle_start = rq_clock(rq->core);
5915 rq->core->core_forceidle_occupation = occ;
5918 rq->core->core_pick_seq = rq->core->core_task_seq;
5919 next = rq->core_pick;
5920 rq->core_sched_seq = rq->core->core_pick_seq;
5922 /* Something should have been selected for current CPU */
5923 WARN_ON_ONCE(!next);
5926 * Reschedule siblings
5928 * NOTE: L1TF -- at this point we're no longer running the old task and
5929 * sending an IPI (below) ensures the sibling will no longer be running
5930 * their task. This ensures there is no inter-sibling overlap between
5931 * non-matching user state.
5933 for_each_cpu(i, smt_mask) {
5937 * An online sibling might have gone offline before a task
5938 * could be picked for it, or it might be offline but later
5939 * happen to come online, but its too late and nothing was
5940 * picked for it. That's Ok - it will pick tasks for itself,
5943 if (!rq_i->core_pick)
5947 * Update for new !FI->FI transitions, or if continuing to be in !FI:
5948 * fi_before fi update?
5954 if (!(fi_before && rq->core->core_forceidle_count))
5955 task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count);
5957 rq_i->core_pick->core_occupation = occ;
5960 rq_i->core_pick = NULL;
5964 /* Did we break L1TF mitigation requirements? */
5965 WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
5967 if (rq_i->curr == rq_i->core_pick) {
5968 rq_i->core_pick = NULL;
5976 set_next_task(rq, next);
5978 if (rq->core->core_forceidle_count && next == rq->idle)
5979 queue_core_balance(rq);
5984 static bool try_steal_cookie(int this, int that)
5986 struct rq *dst = cpu_rq(this), *src = cpu_rq(that);
5987 struct task_struct *p;
5988 unsigned long cookie;
5989 bool success = false;
5991 local_irq_disable();
5992 double_rq_lock(dst, src);
5994 cookie = dst->core->core_cookie;
5998 if (dst->curr != dst->idle)
6001 p = sched_core_find(src, cookie);
6006 if (p == src->core_pick || p == src->curr)
6009 if (!is_cpu_allowed(p, this))
6012 if (p->core_occupation > dst->idle->core_occupation)
6015 deactivate_task(src, p, 0);
6016 set_task_cpu(p, this);
6017 activate_task(dst, p, 0);
6025 p = sched_core_next(p, cookie);
6029 double_rq_unlock(dst, src);
6035 static bool steal_cookie_task(int cpu, struct sched_domain *sd)
6039 for_each_cpu_wrap(i, sched_domain_span(sd), cpu) {
6046 if (try_steal_cookie(cpu, i))
6053 static void sched_core_balance(struct rq *rq)
6055 struct sched_domain *sd;
6056 int cpu = cpu_of(rq);
6060 raw_spin_rq_unlock_irq(rq);
6061 for_each_domain(cpu, sd) {
6065 if (steal_cookie_task(cpu, sd))
6068 raw_spin_rq_lock_irq(rq);
6073 static DEFINE_PER_CPU(struct callback_head, core_balance_head);
6075 static void queue_core_balance(struct rq *rq)
6077 if (!sched_core_enabled(rq))
6080 if (!rq->core->core_cookie)
6083 if (!rq->nr_running) /* not forced idle */
6086 queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance);
6089 static void sched_core_cpu_starting(unsigned int cpu)
6091 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6092 struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6093 unsigned long flags;
6096 sched_core_lock(cpu, &flags);
6098 WARN_ON_ONCE(rq->core != rq);
6100 /* if we're the first, we'll be our own leader */
6101 if (cpumask_weight(smt_mask) == 1)
6104 /* find the leader */
6105 for_each_cpu(t, smt_mask) {
6109 if (rq->core == rq) {
6115 if (WARN_ON_ONCE(!core_rq)) /* whoopsie */
6118 /* install and validate core_rq */
6119 for_each_cpu(t, smt_mask) {
6125 WARN_ON_ONCE(rq->core != core_rq);
6129 sched_core_unlock(cpu, &flags);
6132 static void sched_core_cpu_deactivate(unsigned int cpu)
6134 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6135 struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6136 unsigned long flags;
6139 sched_core_lock(cpu, &flags);
6141 /* if we're the last man standing, nothing to do */
6142 if (cpumask_weight(smt_mask) == 1) {
6143 WARN_ON_ONCE(rq->core != rq);
6147 /* if we're not the leader, nothing to do */
6151 /* find a new leader */
6152 for_each_cpu(t, smt_mask) {
6155 core_rq = cpu_rq(t);
6159 if (WARN_ON_ONCE(!core_rq)) /* impossible */
6162 /* copy the shared state to the new leader */
6163 core_rq->core_task_seq = rq->core_task_seq;
6164 core_rq->core_pick_seq = rq->core_pick_seq;
6165 core_rq->core_cookie = rq->core_cookie;
6166 core_rq->core_forceidle_count = rq->core_forceidle_count;
6167 core_rq->core_forceidle_seq = rq->core_forceidle_seq;
6168 core_rq->core_forceidle_occupation = rq->core_forceidle_occupation;
6171 * Accounting edge for forced idle is handled in pick_next_task().
6172 * Don't need another one here, since the hotplug thread shouldn't
6175 core_rq->core_forceidle_start = 0;
6177 /* install new leader */
6178 for_each_cpu(t, smt_mask) {
6184 sched_core_unlock(cpu, &flags);
6187 static inline void sched_core_cpu_dying(unsigned int cpu)
6189 struct rq *rq = cpu_rq(cpu);
6195 #else /* !CONFIG_SCHED_CORE */
6197 static inline void sched_core_cpu_starting(unsigned int cpu) {}
6198 static inline void sched_core_cpu_deactivate(unsigned int cpu) {}
6199 static inline void sched_core_cpu_dying(unsigned int cpu) {}
6201 static struct task_struct *
6202 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6204 return __pick_next_task(rq, prev, rf);
6207 #endif /* CONFIG_SCHED_CORE */
6210 * Constants for the sched_mode argument of __schedule().
6212 * The mode argument allows RT enabled kernels to differentiate a
6213 * preemption from blocking on an 'sleeping' spin/rwlock. Note that
6214 * SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to
6215 * optimize the AND operation out and just check for zero.
6218 #define SM_PREEMPT 0x1
6219 #define SM_RTLOCK_WAIT 0x2
6221 #ifndef CONFIG_PREEMPT_RT
6222 # define SM_MASK_PREEMPT (~0U)
6224 # define SM_MASK_PREEMPT SM_PREEMPT
6228 * __schedule() is the main scheduler function.
6230 * The main means of driving the scheduler and thus entering this function are:
6232 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
6234 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
6235 * paths. For example, see arch/x86/entry_64.S.
6237 * To drive preemption between tasks, the scheduler sets the flag in timer
6238 * interrupt handler scheduler_tick().
6240 * 3. Wakeups don't really cause entry into schedule(). They add a
6241 * task to the run-queue and that's it.
6243 * Now, if the new task added to the run-queue preempts the current
6244 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
6245 * called on the nearest possible occasion:
6247 * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
6249 * - in syscall or exception context, at the next outmost
6250 * preempt_enable(). (this might be as soon as the wake_up()'s
6253 * - in IRQ context, return from interrupt-handler to
6254 * preemptible context
6256 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
6259 * - cond_resched() call
6260 * - explicit schedule() call
6261 * - return from syscall or exception to user-space
6262 * - return from interrupt-handler to user-space
6264 * WARNING: must be called with preemption disabled!
6266 static void __sched notrace __schedule(unsigned int sched_mode)
6268 struct task_struct *prev, *next;
6269 unsigned long *switch_count;
6270 unsigned long prev_state;
6275 cpu = smp_processor_id();
6279 schedule_debug(prev, !!sched_mode);
6281 if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
6284 local_irq_disable();
6285 rcu_note_context_switch(!!sched_mode);
6288 * Make sure that signal_pending_state()->signal_pending() below
6289 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
6290 * done by the caller to avoid the race with signal_wake_up():
6292 * __set_current_state(@state) signal_wake_up()
6293 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
6294 * wake_up_state(p, state)
6295 * LOCK rq->lock LOCK p->pi_state
6296 * smp_mb__after_spinlock() smp_mb__after_spinlock()
6297 * if (signal_pending_state()) if (p->state & @state)
6299 * Also, the membarrier system call requires a full memory barrier
6300 * after coming from user-space, before storing to rq->curr.
6303 smp_mb__after_spinlock();
6305 /* Promote REQ to ACT */
6306 rq->clock_update_flags <<= 1;
6307 update_rq_clock(rq);
6309 switch_count = &prev->nivcsw;
6312 * We must load prev->state once (task_struct::state is volatile), such
6315 * - we form a control dependency vs deactivate_task() below.
6316 * - ptrace_{,un}freeze_traced() can change ->state underneath us.
6318 prev_state = READ_ONCE(prev->__state);
6319 if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {
6320 if (signal_pending_state(prev_state, prev)) {
6321 WRITE_ONCE(prev->__state, TASK_RUNNING);
6323 prev->sched_contributes_to_load =
6324 (prev_state & TASK_UNINTERRUPTIBLE) &&
6325 !(prev_state & TASK_NOLOAD) &&
6326 !(prev->flags & PF_FROZEN);
6328 if (prev->sched_contributes_to_load)
6329 rq->nr_uninterruptible++;
6332 * __schedule() ttwu()
6333 * prev_state = prev->state; if (p->on_rq && ...)
6334 * if (prev_state) goto out;
6335 * p->on_rq = 0; smp_acquire__after_ctrl_dep();
6336 * p->state = TASK_WAKING
6338 * Where __schedule() and ttwu() have matching control dependencies.
6340 * After this, schedule() must not care about p->state any more.
6342 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
6344 if (prev->in_iowait) {
6345 atomic_inc(&rq->nr_iowait);
6346 delayacct_blkio_start();
6349 switch_count = &prev->nvcsw;
6352 next = pick_next_task(rq, prev, &rf);
6353 clear_tsk_need_resched(prev);
6354 clear_preempt_need_resched();
6355 #ifdef CONFIG_SCHED_DEBUG
6356 rq->last_seen_need_resched_ns = 0;
6359 if (likely(prev != next)) {
6362 * RCU users of rcu_dereference(rq->curr) may not see
6363 * changes to task_struct made by pick_next_task().
6365 RCU_INIT_POINTER(rq->curr, next);
6367 * The membarrier system call requires each architecture
6368 * to have a full memory barrier after updating
6369 * rq->curr, before returning to user-space.
6371 * Here are the schemes providing that barrier on the
6372 * various architectures:
6373 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
6374 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
6375 * - finish_lock_switch() for weakly-ordered
6376 * architectures where spin_unlock is a full barrier,
6377 * - switch_to() for arm64 (weakly-ordered, spin_unlock
6378 * is a RELEASE barrier),
6382 migrate_disable_switch(rq, prev);
6383 psi_sched_switch(prev, next, !task_on_rq_queued(prev));
6385 trace_sched_switch(sched_mode & SM_MASK_PREEMPT, prev, next, prev_state);
6387 /* Also unlocks the rq: */
6388 rq = context_switch(rq, prev, next, &rf);
6390 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
6392 rq_unpin_lock(rq, &rf);
6393 __balance_callbacks(rq);
6394 raw_spin_rq_unlock_irq(rq);
6398 void __noreturn do_task_dead(void)
6400 /* Causes final put_task_struct in finish_task_switch(): */
6401 set_special_state(TASK_DEAD);
6403 /* Tell freezer to ignore us: */
6404 current->flags |= PF_NOFREEZE;
6406 __schedule(SM_NONE);
6409 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
6414 static inline void sched_submit_work(struct task_struct *tsk)
6416 unsigned int task_flags;
6418 if (task_is_running(tsk))
6421 task_flags = tsk->flags;
6423 * If a worker goes to sleep, notify and ask workqueue whether it
6424 * wants to wake up a task to maintain concurrency.
6426 if (task_flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6427 if (task_flags & PF_WQ_WORKER)
6428 wq_worker_sleeping(tsk);
6430 io_wq_worker_sleeping(tsk);
6433 if (tsk_is_pi_blocked(tsk))
6437 * If we are going to sleep and we have plugged IO queued,
6438 * make sure to submit it to avoid deadlocks.
6440 blk_flush_plug(tsk->plug, true);
6443 static void sched_update_worker(struct task_struct *tsk)
6445 if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6446 if (tsk->flags & PF_WQ_WORKER)
6447 wq_worker_running(tsk);
6449 io_wq_worker_running(tsk);
6453 asmlinkage __visible void __sched schedule(void)
6455 struct task_struct *tsk = current;
6457 sched_submit_work(tsk);
6460 __schedule(SM_NONE);
6461 sched_preempt_enable_no_resched();
6462 } while (need_resched());
6463 sched_update_worker(tsk);
6465 EXPORT_SYMBOL(schedule);
6468 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
6469 * state (have scheduled out non-voluntarily) by making sure that all
6470 * tasks have either left the run queue or have gone into user space.
6471 * As idle tasks do not do either, they must not ever be preempted
6472 * (schedule out non-voluntarily).
6474 * schedule_idle() is similar to schedule_preempt_disable() except that it
6475 * never enables preemption because it does not call sched_submit_work().
6477 void __sched schedule_idle(void)
6480 * As this skips calling sched_submit_work(), which the idle task does
6481 * regardless because that function is a nop when the task is in a
6482 * TASK_RUNNING state, make sure this isn't used someplace that the
6483 * current task can be in any other state. Note, idle is always in the
6484 * TASK_RUNNING state.
6486 WARN_ON_ONCE(current->__state);
6488 __schedule(SM_NONE);
6489 } while (need_resched());
6492 #if defined(CONFIG_CONTEXT_TRACKING) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_OFFSTACK)
6493 asmlinkage __visible void __sched schedule_user(void)
6496 * If we come here after a random call to set_need_resched(),
6497 * or we have been woken up remotely but the IPI has not yet arrived,
6498 * we haven't yet exited the RCU idle mode. Do it here manually until
6499 * we find a better solution.
6501 * NB: There are buggy callers of this function. Ideally we
6502 * should warn if prev_state != CONTEXT_USER, but that will trigger
6503 * too frequently to make sense yet.
6505 enum ctx_state prev_state = exception_enter();
6507 exception_exit(prev_state);
6512 * schedule_preempt_disabled - called with preemption disabled
6514 * Returns with preemption disabled. Note: preempt_count must be 1
6516 void __sched schedule_preempt_disabled(void)
6518 sched_preempt_enable_no_resched();
6523 #ifdef CONFIG_PREEMPT_RT
6524 void __sched notrace schedule_rtlock(void)
6528 __schedule(SM_RTLOCK_WAIT);
6529 sched_preempt_enable_no_resched();
6530 } while (need_resched());
6532 NOKPROBE_SYMBOL(schedule_rtlock);
6535 static void __sched notrace preempt_schedule_common(void)
6539 * Because the function tracer can trace preempt_count_sub()
6540 * and it also uses preempt_enable/disable_notrace(), if
6541 * NEED_RESCHED is set, the preempt_enable_notrace() called
6542 * by the function tracer will call this function again and
6543 * cause infinite recursion.
6545 * Preemption must be disabled here before the function
6546 * tracer can trace. Break up preempt_disable() into two
6547 * calls. One to disable preemption without fear of being
6548 * traced. The other to still record the preemption latency,
6549 * which can also be traced by the function tracer.
6551 preempt_disable_notrace();
6552 preempt_latency_start(1);
6553 __schedule(SM_PREEMPT);
6554 preempt_latency_stop(1);
6555 preempt_enable_no_resched_notrace();
6558 * Check again in case we missed a preemption opportunity
6559 * between schedule and now.
6561 } while (need_resched());
6564 #ifdef CONFIG_PREEMPTION
6566 * This is the entry point to schedule() from in-kernel preemption
6567 * off of preempt_enable.
6569 asmlinkage __visible void __sched notrace preempt_schedule(void)
6572 * If there is a non-zero preempt_count or interrupts are disabled,
6573 * we do not want to preempt the current task. Just return..
6575 if (likely(!preemptible()))
6577 preempt_schedule_common();
6579 NOKPROBE_SYMBOL(preempt_schedule);
6580 EXPORT_SYMBOL(preempt_schedule);
6582 #ifdef CONFIG_PREEMPT_DYNAMIC
6583 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
6584 #ifndef preempt_schedule_dynamic_enabled
6585 #define preempt_schedule_dynamic_enabled preempt_schedule
6586 #define preempt_schedule_dynamic_disabled NULL
6588 DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled);
6589 EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
6590 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6591 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule);
6592 void __sched notrace dynamic_preempt_schedule(void)
6594 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule))
6598 NOKPROBE_SYMBOL(dynamic_preempt_schedule);
6599 EXPORT_SYMBOL(dynamic_preempt_schedule);
6604 * preempt_schedule_notrace - preempt_schedule called by tracing
6606 * The tracing infrastructure uses preempt_enable_notrace to prevent
6607 * recursion and tracing preempt enabling caused by the tracing
6608 * infrastructure itself. But as tracing can happen in areas coming
6609 * from userspace or just about to enter userspace, a preempt enable
6610 * can occur before user_exit() is called. This will cause the scheduler
6611 * to be called when the system is still in usermode.
6613 * To prevent this, the preempt_enable_notrace will use this function
6614 * instead of preempt_schedule() to exit user context if needed before
6615 * calling the scheduler.
6617 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
6619 enum ctx_state prev_ctx;
6621 if (likely(!preemptible()))
6626 * Because the function tracer can trace preempt_count_sub()
6627 * and it also uses preempt_enable/disable_notrace(), if
6628 * NEED_RESCHED is set, the preempt_enable_notrace() called
6629 * by the function tracer will call this function again and
6630 * cause infinite recursion.
6632 * Preemption must be disabled here before the function
6633 * tracer can trace. Break up preempt_disable() into two
6634 * calls. One to disable preemption without fear of being
6635 * traced. The other to still record the preemption latency,
6636 * which can also be traced by the function tracer.
6638 preempt_disable_notrace();
6639 preempt_latency_start(1);
6641 * Needs preempt disabled in case user_exit() is traced
6642 * and the tracer calls preempt_enable_notrace() causing
6643 * an infinite recursion.
6645 prev_ctx = exception_enter();
6646 __schedule(SM_PREEMPT);
6647 exception_exit(prev_ctx);
6649 preempt_latency_stop(1);
6650 preempt_enable_no_resched_notrace();
6651 } while (need_resched());
6653 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
6655 #ifdef CONFIG_PREEMPT_DYNAMIC
6656 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
6657 #ifndef preempt_schedule_notrace_dynamic_enabled
6658 #define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace
6659 #define preempt_schedule_notrace_dynamic_disabled NULL
6661 DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled);
6662 EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
6663 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6664 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace);
6665 void __sched notrace dynamic_preempt_schedule_notrace(void)
6667 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace))
6669 preempt_schedule_notrace();
6671 NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace);
6672 EXPORT_SYMBOL(dynamic_preempt_schedule_notrace);
6676 #endif /* CONFIG_PREEMPTION */
6679 * This is the entry point to schedule() from kernel preemption
6680 * off of irq context.
6681 * Note, that this is called and return with irqs disabled. This will
6682 * protect us against recursive calling from irq.
6684 asmlinkage __visible void __sched preempt_schedule_irq(void)
6686 enum ctx_state prev_state;
6688 /* Catch callers which need to be fixed */
6689 BUG_ON(preempt_count() || !irqs_disabled());
6691 prev_state = exception_enter();
6696 __schedule(SM_PREEMPT);
6697 local_irq_disable();
6698 sched_preempt_enable_no_resched();
6699 } while (need_resched());
6701 exception_exit(prev_state);
6704 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
6707 WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~WF_SYNC);
6708 return try_to_wake_up(curr->private, mode, wake_flags);
6710 EXPORT_SYMBOL(default_wake_function);
6712 static void __setscheduler_prio(struct task_struct *p, int prio)
6715 p->sched_class = &dl_sched_class;
6716 else if (rt_prio(prio))
6717 p->sched_class = &rt_sched_class;
6719 p->sched_class = &fair_sched_class;
6724 #ifdef CONFIG_RT_MUTEXES
6726 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
6729 prio = min(prio, pi_task->prio);
6734 static inline int rt_effective_prio(struct task_struct *p, int prio)
6736 struct task_struct *pi_task = rt_mutex_get_top_task(p);
6738 return __rt_effective_prio(pi_task, prio);
6742 * rt_mutex_setprio - set the current priority of a task
6744 * @pi_task: donor task
6746 * This function changes the 'effective' priority of a task. It does
6747 * not touch ->normal_prio like __setscheduler().
6749 * Used by the rt_mutex code to implement priority inheritance
6750 * logic. Call site only calls if the priority of the task changed.
6752 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
6754 int prio, oldprio, queued, running, queue_flag =
6755 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6756 const struct sched_class *prev_class;
6760 /* XXX used to be waiter->prio, not waiter->task->prio */
6761 prio = __rt_effective_prio(pi_task, p->normal_prio);
6764 * If nothing changed; bail early.
6766 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
6769 rq = __task_rq_lock(p, &rf);
6770 update_rq_clock(rq);
6772 * Set under pi_lock && rq->lock, such that the value can be used under
6775 * Note that there is loads of tricky to make this pointer cache work
6776 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
6777 * ensure a task is de-boosted (pi_task is set to NULL) before the
6778 * task is allowed to run again (and can exit). This ensures the pointer
6779 * points to a blocked task -- which guarantees the task is present.
6781 p->pi_top_task = pi_task;
6784 * For FIFO/RR we only need to set prio, if that matches we're done.
6786 if (prio == p->prio && !dl_prio(prio))
6790 * Idle task boosting is a nono in general. There is one
6791 * exception, when PREEMPT_RT and NOHZ is active:
6793 * The idle task calls get_next_timer_interrupt() and holds
6794 * the timer wheel base->lock on the CPU and another CPU wants
6795 * to access the timer (probably to cancel it). We can safely
6796 * ignore the boosting request, as the idle CPU runs this code
6797 * with interrupts disabled and will complete the lock
6798 * protected section without being interrupted. So there is no
6799 * real need to boost.
6801 if (unlikely(p == rq->idle)) {
6802 WARN_ON(p != rq->curr);
6803 WARN_ON(p->pi_blocked_on);
6807 trace_sched_pi_setprio(p, pi_task);
6810 if (oldprio == prio)
6811 queue_flag &= ~DEQUEUE_MOVE;
6813 prev_class = p->sched_class;
6814 queued = task_on_rq_queued(p);
6815 running = task_current(rq, p);
6817 dequeue_task(rq, p, queue_flag);
6819 put_prev_task(rq, p);
6822 * Boosting condition are:
6823 * 1. -rt task is running and holds mutex A
6824 * --> -dl task blocks on mutex A
6826 * 2. -dl task is running and holds mutex A
6827 * --> -dl task blocks on mutex A and could preempt the
6830 if (dl_prio(prio)) {
6831 if (!dl_prio(p->normal_prio) ||
6832 (pi_task && dl_prio(pi_task->prio) &&
6833 dl_entity_preempt(&pi_task->dl, &p->dl))) {
6834 p->dl.pi_se = pi_task->dl.pi_se;
6835 queue_flag |= ENQUEUE_REPLENISH;
6837 p->dl.pi_se = &p->dl;
6839 } else if (rt_prio(prio)) {
6840 if (dl_prio(oldprio))
6841 p->dl.pi_se = &p->dl;
6843 queue_flag |= ENQUEUE_HEAD;
6845 if (dl_prio(oldprio))
6846 p->dl.pi_se = &p->dl;
6847 if (rt_prio(oldprio))
6851 __setscheduler_prio(p, prio);
6854 enqueue_task(rq, p, queue_flag);
6856 set_next_task(rq, p);
6858 check_class_changed(rq, p, prev_class, oldprio);
6860 /* Avoid rq from going away on us: */
6863 rq_unpin_lock(rq, &rf);
6864 __balance_callbacks(rq);
6865 raw_spin_rq_unlock(rq);
6870 static inline int rt_effective_prio(struct task_struct *p, int prio)
6876 void set_user_nice(struct task_struct *p, long nice)
6878 bool queued, running;
6883 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
6886 * We have to be careful, if called from sys_setpriority(),
6887 * the task might be in the middle of scheduling on another CPU.
6889 rq = task_rq_lock(p, &rf);
6890 update_rq_clock(rq);
6893 * The RT priorities are set via sched_setscheduler(), but we still
6894 * allow the 'normal' nice value to be set - but as expected
6895 * it won't have any effect on scheduling until the task is
6896 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
6898 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
6899 p->static_prio = NICE_TO_PRIO(nice);
6902 queued = task_on_rq_queued(p);
6903 running = task_current(rq, p);
6905 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
6907 put_prev_task(rq, p);
6909 p->static_prio = NICE_TO_PRIO(nice);
6910 set_load_weight(p, true);
6912 p->prio = effective_prio(p);
6915 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
6917 set_next_task(rq, p);
6920 * If the task increased its priority or is running and
6921 * lowered its priority, then reschedule its CPU:
6923 p->sched_class->prio_changed(rq, p, old_prio);
6926 task_rq_unlock(rq, p, &rf);
6928 EXPORT_SYMBOL(set_user_nice);
6931 * can_nice - check if a task can reduce its nice value
6935 int can_nice(const struct task_struct *p, const int nice)
6937 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
6938 int nice_rlim = nice_to_rlimit(nice);
6940 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
6941 capable(CAP_SYS_NICE));
6944 #ifdef __ARCH_WANT_SYS_NICE
6947 * sys_nice - change the priority of the current process.
6948 * @increment: priority increment
6950 * sys_setpriority is a more generic, but much slower function that
6951 * does similar things.
6953 SYSCALL_DEFINE1(nice, int, increment)
6958 * Setpriority might change our priority at the same moment.
6959 * We don't have to worry. Conceptually one call occurs first
6960 * and we have a single winner.
6962 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
6963 nice = task_nice(current) + increment;
6965 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
6966 if (increment < 0 && !can_nice(current, nice))
6969 retval = security_task_setnice(current, nice);
6973 set_user_nice(current, nice);
6980 * task_prio - return the priority value of a given task.
6981 * @p: the task in question.
6983 * Return: The priority value as seen by users in /proc.
6985 * sched policy return value kernel prio user prio/nice
6987 * normal, batch, idle [0 ... 39] [100 ... 139] 0/[-20 ... 19]
6988 * fifo, rr [-2 ... -100] [98 ... 0] [1 ... 99]
6989 * deadline -101 -1 0
6991 int task_prio(const struct task_struct *p)
6993 return p->prio - MAX_RT_PRIO;
6997 * idle_cpu - is a given CPU idle currently?
6998 * @cpu: the processor in question.
7000 * Return: 1 if the CPU is currently idle. 0 otherwise.
7002 int idle_cpu(int cpu)
7004 struct rq *rq = cpu_rq(cpu);
7006 if (rq->curr != rq->idle)
7013 if (rq->ttwu_pending)
7021 * available_idle_cpu - is a given CPU idle for enqueuing work.
7022 * @cpu: the CPU in question.
7024 * Return: 1 if the CPU is currently idle. 0 otherwise.
7026 int available_idle_cpu(int cpu)
7031 if (vcpu_is_preempted(cpu))
7038 * idle_task - return the idle task for a given CPU.
7039 * @cpu: the processor in question.
7041 * Return: The idle task for the CPU @cpu.
7043 struct task_struct *idle_task(int cpu)
7045 return cpu_rq(cpu)->idle;
7050 * This function computes an effective utilization for the given CPU, to be
7051 * used for frequency selection given the linear relation: f = u * f_max.
7053 * The scheduler tracks the following metrics:
7055 * cpu_util_{cfs,rt,dl,irq}()
7058 * Where the cfs,rt and dl util numbers are tracked with the same metric and
7059 * synchronized windows and are thus directly comparable.
7061 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
7062 * which excludes things like IRQ and steal-time. These latter are then accrued
7063 * in the irq utilization.
7065 * The DL bandwidth number otoh is not a measured metric but a value computed
7066 * based on the task model parameters and gives the minimal utilization
7067 * required to meet deadlines.
7069 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
7070 unsigned long max, enum cpu_util_type type,
7071 struct task_struct *p)
7073 unsigned long dl_util, util, irq;
7074 struct rq *rq = cpu_rq(cpu);
7076 if (!uclamp_is_used() &&
7077 type == FREQUENCY_UTIL && rt_rq_is_runnable(&rq->rt)) {
7082 * Early check to see if IRQ/steal time saturates the CPU, can be
7083 * because of inaccuracies in how we track these -- see
7084 * update_irq_load_avg().
7086 irq = cpu_util_irq(rq);
7087 if (unlikely(irq >= max))
7091 * Because the time spend on RT/DL tasks is visible as 'lost' time to
7092 * CFS tasks and we use the same metric to track the effective
7093 * utilization (PELT windows are synchronized) we can directly add them
7094 * to obtain the CPU's actual utilization.
7096 * CFS and RT utilization can be boosted or capped, depending on
7097 * utilization clamp constraints requested by currently RUNNABLE
7099 * When there are no CFS RUNNABLE tasks, clamps are released and
7100 * frequency will be gracefully reduced with the utilization decay.
7102 util = util_cfs + cpu_util_rt(rq);
7103 if (type == FREQUENCY_UTIL)
7104 util = uclamp_rq_util_with(rq, util, p);
7106 dl_util = cpu_util_dl(rq);
7109 * For frequency selection we do not make cpu_util_dl() a permanent part
7110 * of this sum because we want to use cpu_bw_dl() later on, but we need
7111 * to check if the CFS+RT+DL sum is saturated (ie. no idle time) such
7112 * that we select f_max when there is no idle time.
7114 * NOTE: numerical errors or stop class might cause us to not quite hit
7115 * saturation when we should -- something for later.
7117 if (util + dl_util >= max)
7121 * OTOH, for energy computation we need the estimated running time, so
7122 * include util_dl and ignore dl_bw.
7124 if (type == ENERGY_UTIL)
7128 * There is still idle time; further improve the number by using the
7129 * irq metric. Because IRQ/steal time is hidden from the task clock we
7130 * need to scale the task numbers:
7133 * U' = irq + --------- * U
7136 util = scale_irq_capacity(util, irq, max);
7140 * Bandwidth required by DEADLINE must always be granted while, for
7141 * FAIR and RT, we use blocked utilization of IDLE CPUs as a mechanism
7142 * to gracefully reduce the frequency when no tasks show up for longer
7145 * Ideally we would like to set bw_dl as min/guaranteed freq and util +
7146 * bw_dl as requested freq. However, cpufreq is not yet ready for such
7147 * an interface. So, we only do the latter for now.
7149 if (type == FREQUENCY_UTIL)
7150 util += cpu_bw_dl(rq);
7152 return min(max, util);
7155 unsigned long sched_cpu_util(int cpu, unsigned long max)
7157 return effective_cpu_util(cpu, cpu_util_cfs(cpu), max,
7160 #endif /* CONFIG_SMP */
7163 * find_process_by_pid - find a process with a matching PID value.
7164 * @pid: the pid in question.
7166 * The task of @pid, if found. %NULL otherwise.
7168 static struct task_struct *find_process_by_pid(pid_t pid)
7170 return pid ? find_task_by_vpid(pid) : current;
7174 * sched_setparam() passes in -1 for its policy, to let the functions
7175 * it calls know not to change it.
7177 #define SETPARAM_POLICY -1
7179 static void __setscheduler_params(struct task_struct *p,
7180 const struct sched_attr *attr)
7182 int policy = attr->sched_policy;
7184 if (policy == SETPARAM_POLICY)
7189 if (dl_policy(policy))
7190 __setparam_dl(p, attr);
7191 else if (fair_policy(policy))
7192 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
7195 * __sched_setscheduler() ensures attr->sched_priority == 0 when
7196 * !rt_policy. Always setting this ensures that things like
7197 * getparam()/getattr() don't report silly values for !rt tasks.
7199 p->rt_priority = attr->sched_priority;
7200 p->normal_prio = normal_prio(p);
7201 set_load_weight(p, true);
7205 * Check the target process has a UID that matches the current process's:
7207 static bool check_same_owner(struct task_struct *p)
7209 const struct cred *cred = current_cred(), *pcred;
7213 pcred = __task_cred(p);
7214 match = (uid_eq(cred->euid, pcred->euid) ||
7215 uid_eq(cred->euid, pcred->uid));
7220 static int __sched_setscheduler(struct task_struct *p,
7221 const struct sched_attr *attr,
7224 int oldpolicy = -1, policy = attr->sched_policy;
7225 int retval, oldprio, newprio, queued, running;
7226 const struct sched_class *prev_class;
7227 struct callback_head *head;
7230 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
7233 /* The pi code expects interrupts enabled */
7234 BUG_ON(pi && in_interrupt());
7236 /* Double check policy once rq lock held: */
7238 reset_on_fork = p->sched_reset_on_fork;
7239 policy = oldpolicy = p->policy;
7241 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
7243 if (!valid_policy(policy))
7247 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
7251 * Valid priorities for SCHED_FIFO and SCHED_RR are
7252 * 1..MAX_RT_PRIO-1, valid priority for SCHED_NORMAL,
7253 * SCHED_BATCH and SCHED_IDLE is 0.
7255 if (attr->sched_priority > MAX_RT_PRIO-1)
7257 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
7258 (rt_policy(policy) != (attr->sched_priority != 0)))
7262 * Allow unprivileged RT tasks to decrease priority:
7264 if (user && !capable(CAP_SYS_NICE)) {
7265 if (fair_policy(policy)) {
7266 if (attr->sched_nice < task_nice(p) &&
7267 !can_nice(p, attr->sched_nice))
7271 if (rt_policy(policy)) {
7272 unsigned long rlim_rtprio =
7273 task_rlimit(p, RLIMIT_RTPRIO);
7275 /* Can't set/change the rt policy: */
7276 if (policy != p->policy && !rlim_rtprio)
7279 /* Can't increase priority: */
7280 if (attr->sched_priority > p->rt_priority &&
7281 attr->sched_priority > rlim_rtprio)
7286 * Can't set/change SCHED_DEADLINE policy at all for now
7287 * (safest behavior); in the future we would like to allow
7288 * unprivileged DL tasks to increase their relative deadline
7289 * or reduce their runtime (both ways reducing utilization)
7291 if (dl_policy(policy))
7295 * Treat SCHED_IDLE as nice 20. Only allow a switch to
7296 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
7298 if (task_has_idle_policy(p) && !idle_policy(policy)) {
7299 if (!can_nice(p, task_nice(p)))
7303 /* Can't change other user's priorities: */
7304 if (!check_same_owner(p))
7307 /* Normal users shall not reset the sched_reset_on_fork flag: */
7308 if (p->sched_reset_on_fork && !reset_on_fork)
7313 if (attr->sched_flags & SCHED_FLAG_SUGOV)
7316 retval = security_task_setscheduler(p);
7321 /* Update task specific "requested" clamps */
7322 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
7323 retval = uclamp_validate(p, attr);
7332 * Make sure no PI-waiters arrive (or leave) while we are
7333 * changing the priority of the task:
7335 * To be able to change p->policy safely, the appropriate
7336 * runqueue lock must be held.
7338 rq = task_rq_lock(p, &rf);
7339 update_rq_clock(rq);
7342 * Changing the policy of the stop threads its a very bad idea:
7344 if (p == rq->stop) {
7350 * If not changing anything there's no need to proceed further,
7351 * but store a possible modification of reset_on_fork.
7353 if (unlikely(policy == p->policy)) {
7354 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
7356 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
7358 if (dl_policy(policy) && dl_param_changed(p, attr))
7360 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
7363 p->sched_reset_on_fork = reset_on_fork;
7370 #ifdef CONFIG_RT_GROUP_SCHED
7372 * Do not allow realtime tasks into groups that have no runtime
7375 if (rt_bandwidth_enabled() && rt_policy(policy) &&
7376 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
7377 !task_group_is_autogroup(task_group(p))) {
7383 if (dl_bandwidth_enabled() && dl_policy(policy) &&
7384 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
7385 cpumask_t *span = rq->rd->span;
7388 * Don't allow tasks with an affinity mask smaller than
7389 * the entire root_domain to become SCHED_DEADLINE. We
7390 * will also fail if there's no bandwidth available.
7392 if (!cpumask_subset(span, p->cpus_ptr) ||
7393 rq->rd->dl_bw.bw == 0) {
7401 /* Re-check policy now with rq lock held: */
7402 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
7403 policy = oldpolicy = -1;
7404 task_rq_unlock(rq, p, &rf);
7406 cpuset_read_unlock();
7411 * If setscheduling to SCHED_DEADLINE (or changing the parameters
7412 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
7415 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
7420 p->sched_reset_on_fork = reset_on_fork;
7423 newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
7426 * Take priority boosted tasks into account. If the new
7427 * effective priority is unchanged, we just store the new
7428 * normal parameters and do not touch the scheduler class and
7429 * the runqueue. This will be done when the task deboost
7432 newprio = rt_effective_prio(p, newprio);
7433 if (newprio == oldprio)
7434 queue_flags &= ~DEQUEUE_MOVE;
7437 queued = task_on_rq_queued(p);
7438 running = task_current(rq, p);
7440 dequeue_task(rq, p, queue_flags);
7442 put_prev_task(rq, p);
7444 prev_class = p->sched_class;
7446 if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
7447 __setscheduler_params(p, attr);
7448 __setscheduler_prio(p, newprio);
7450 __setscheduler_uclamp(p, attr);
7454 * We enqueue to tail when the priority of a task is
7455 * increased (user space view).
7457 if (oldprio < p->prio)
7458 queue_flags |= ENQUEUE_HEAD;
7460 enqueue_task(rq, p, queue_flags);
7463 set_next_task(rq, p);
7465 check_class_changed(rq, p, prev_class, oldprio);
7467 /* Avoid rq from going away on us: */
7469 head = splice_balance_callbacks(rq);
7470 task_rq_unlock(rq, p, &rf);
7473 cpuset_read_unlock();
7474 rt_mutex_adjust_pi(p);
7477 /* Run balance callbacks after we've adjusted the PI chain: */
7478 balance_callbacks(rq, head);
7484 task_rq_unlock(rq, p, &rf);
7486 cpuset_read_unlock();
7490 static int _sched_setscheduler(struct task_struct *p, int policy,
7491 const struct sched_param *param, bool check)
7493 struct sched_attr attr = {
7494 .sched_policy = policy,
7495 .sched_priority = param->sched_priority,
7496 .sched_nice = PRIO_TO_NICE(p->static_prio),
7499 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
7500 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
7501 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
7502 policy &= ~SCHED_RESET_ON_FORK;
7503 attr.sched_policy = policy;
7506 return __sched_setscheduler(p, &attr, check, true);
7509 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
7510 * @p: the task in question.
7511 * @policy: new policy.
7512 * @param: structure containing the new RT priority.
7514 * Use sched_set_fifo(), read its comment.
7516 * Return: 0 on success. An error code otherwise.
7518 * NOTE that the task may be already dead.
7520 int sched_setscheduler(struct task_struct *p, int policy,
7521 const struct sched_param *param)
7523 return _sched_setscheduler(p, policy, param, true);
7526 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
7528 return __sched_setscheduler(p, attr, true, true);
7531 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
7533 return __sched_setscheduler(p, attr, false, true);
7535 EXPORT_SYMBOL_GPL(sched_setattr_nocheck);
7538 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
7539 * @p: the task in question.
7540 * @policy: new policy.
7541 * @param: structure containing the new RT priority.
7543 * Just like sched_setscheduler, only don't bother checking if the
7544 * current context has permission. For example, this is needed in
7545 * stop_machine(): we create temporary high priority worker threads,
7546 * but our caller might not have that capability.
7548 * Return: 0 on success. An error code otherwise.
7550 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
7551 const struct sched_param *param)
7553 return _sched_setscheduler(p, policy, param, false);
7557 * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
7558 * incapable of resource management, which is the one thing an OS really should
7561 * This is of course the reason it is limited to privileged users only.
7563 * Worse still; it is fundamentally impossible to compose static priority
7564 * workloads. You cannot take two correctly working static prio workloads
7565 * and smash them together and still expect them to work.
7567 * For this reason 'all' FIFO tasks the kernel creates are basically at:
7571 * The administrator _MUST_ configure the system, the kernel simply doesn't
7572 * know enough information to make a sensible choice.
7574 void sched_set_fifo(struct task_struct *p)
7576 struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
7577 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7579 EXPORT_SYMBOL_GPL(sched_set_fifo);
7582 * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
7584 void sched_set_fifo_low(struct task_struct *p)
7586 struct sched_param sp = { .sched_priority = 1 };
7587 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7589 EXPORT_SYMBOL_GPL(sched_set_fifo_low);
7591 void sched_set_normal(struct task_struct *p, int nice)
7593 struct sched_attr attr = {
7594 .sched_policy = SCHED_NORMAL,
7597 WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
7599 EXPORT_SYMBOL_GPL(sched_set_normal);
7602 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
7604 struct sched_param lparam;
7605 struct task_struct *p;
7608 if (!param || pid < 0)
7610 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
7615 p = find_process_by_pid(pid);
7621 retval = sched_setscheduler(p, policy, &lparam);
7629 * Mimics kernel/events/core.c perf_copy_attr().
7631 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
7636 /* Zero the full structure, so that a short copy will be nice: */
7637 memset(attr, 0, sizeof(*attr));
7639 ret = get_user(size, &uattr->size);
7643 /* ABI compatibility quirk: */
7645 size = SCHED_ATTR_SIZE_VER0;
7646 if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
7649 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
7656 if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
7657 size < SCHED_ATTR_SIZE_VER1)
7661 * XXX: Do we want to be lenient like existing syscalls; or do we want
7662 * to be strict and return an error on out-of-bounds values?
7664 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
7669 put_user(sizeof(*attr), &uattr->size);
7673 static void get_params(struct task_struct *p, struct sched_attr *attr)
7675 if (task_has_dl_policy(p))
7676 __getparam_dl(p, attr);
7677 else if (task_has_rt_policy(p))
7678 attr->sched_priority = p->rt_priority;
7680 attr->sched_nice = task_nice(p);
7684 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
7685 * @pid: the pid in question.
7686 * @policy: new policy.
7687 * @param: structure containing the new RT priority.
7689 * Return: 0 on success. An error code otherwise.
7691 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
7696 return do_sched_setscheduler(pid, policy, param);
7700 * sys_sched_setparam - set/change the RT priority of a thread
7701 * @pid: the pid in question.
7702 * @param: structure containing the new RT priority.
7704 * Return: 0 on success. An error code otherwise.
7706 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
7708 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
7712 * sys_sched_setattr - same as above, but with extended sched_attr
7713 * @pid: the pid in question.
7714 * @uattr: structure containing the extended parameters.
7715 * @flags: for future extension.
7717 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
7718 unsigned int, flags)
7720 struct sched_attr attr;
7721 struct task_struct *p;
7724 if (!uattr || pid < 0 || flags)
7727 retval = sched_copy_attr(uattr, &attr);
7731 if ((int)attr.sched_policy < 0)
7733 if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
7734 attr.sched_policy = SETPARAM_POLICY;
7738 p = find_process_by_pid(pid);
7744 if (attr.sched_flags & SCHED_FLAG_KEEP_PARAMS)
7745 get_params(p, &attr);
7746 retval = sched_setattr(p, &attr);
7754 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
7755 * @pid: the pid in question.
7757 * Return: On success, the policy of the thread. Otherwise, a negative error
7760 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
7762 struct task_struct *p;
7770 p = find_process_by_pid(pid);
7772 retval = security_task_getscheduler(p);
7775 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
7782 * sys_sched_getparam - get the RT priority of a thread
7783 * @pid: the pid in question.
7784 * @param: structure containing the RT priority.
7786 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
7789 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
7791 struct sched_param lp = { .sched_priority = 0 };
7792 struct task_struct *p;
7795 if (!param || pid < 0)
7799 p = find_process_by_pid(pid);
7804 retval = security_task_getscheduler(p);
7808 if (task_has_rt_policy(p))
7809 lp.sched_priority = p->rt_priority;
7813 * This one might sleep, we cannot do it with a spinlock held ...
7815 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
7825 * Copy the kernel size attribute structure (which might be larger
7826 * than what user-space knows about) to user-space.
7828 * Note that all cases are valid: user-space buffer can be larger or
7829 * smaller than the kernel-space buffer. The usual case is that both
7830 * have the same size.
7833 sched_attr_copy_to_user(struct sched_attr __user *uattr,
7834 struct sched_attr *kattr,
7837 unsigned int ksize = sizeof(*kattr);
7839 if (!access_ok(uattr, usize))
7843 * sched_getattr() ABI forwards and backwards compatibility:
7845 * If usize == ksize then we just copy everything to user-space and all is good.
7847 * If usize < ksize then we only copy as much as user-space has space for,
7848 * this keeps ABI compatibility as well. We skip the rest.
7850 * If usize > ksize then user-space is using a newer version of the ABI,
7851 * which part the kernel doesn't know about. Just ignore it - tooling can
7852 * detect the kernel's knowledge of attributes from the attr->size value
7853 * which is set to ksize in this case.
7855 kattr->size = min(usize, ksize);
7857 if (copy_to_user(uattr, kattr, kattr->size))
7864 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
7865 * @pid: the pid in question.
7866 * @uattr: structure containing the extended parameters.
7867 * @usize: sizeof(attr) for fwd/bwd comp.
7868 * @flags: for future extension.
7870 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
7871 unsigned int, usize, unsigned int, flags)
7873 struct sched_attr kattr = { };
7874 struct task_struct *p;
7877 if (!uattr || pid < 0 || usize > PAGE_SIZE ||
7878 usize < SCHED_ATTR_SIZE_VER0 || flags)
7882 p = find_process_by_pid(pid);
7887 retval = security_task_getscheduler(p);
7891 kattr.sched_policy = p->policy;
7892 if (p->sched_reset_on_fork)
7893 kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
7894 get_params(p, &kattr);
7895 kattr.sched_flags &= SCHED_FLAG_ALL;
7897 #ifdef CONFIG_UCLAMP_TASK
7899 * This could race with another potential updater, but this is fine
7900 * because it'll correctly read the old or the new value. We don't need
7901 * to guarantee who wins the race as long as it doesn't return garbage.
7903 kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
7904 kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
7909 return sched_attr_copy_to_user(uattr, &kattr, usize);
7917 int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
7922 * If the task isn't a deadline task or admission control is
7923 * disabled then we don't care about affinity changes.
7925 if (!task_has_dl_policy(p) || !dl_bandwidth_enabled())
7929 * Since bandwidth control happens on root_domain basis,
7930 * if admission test is enabled, we only admit -deadline
7931 * tasks allowed to run on all the CPUs in the task's
7935 if (!cpumask_subset(task_rq(p)->rd->span, mask))
7943 __sched_setaffinity(struct task_struct *p, const struct cpumask *mask)
7946 cpumask_var_t cpus_allowed, new_mask;
7948 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL))
7951 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
7953 goto out_free_cpus_allowed;
7956 cpuset_cpus_allowed(p, cpus_allowed);
7957 cpumask_and(new_mask, mask, cpus_allowed);
7959 retval = dl_task_check_affinity(p, new_mask);
7961 goto out_free_new_mask;
7963 retval = __set_cpus_allowed_ptr(p, new_mask, SCA_CHECK | SCA_USER);
7965 goto out_free_new_mask;
7967 cpuset_cpus_allowed(p, cpus_allowed);
7968 if (!cpumask_subset(new_mask, cpus_allowed)) {
7970 * We must have raced with a concurrent cpuset update.
7971 * Just reset the cpumask to the cpuset's cpus_allowed.
7973 cpumask_copy(new_mask, cpus_allowed);
7978 free_cpumask_var(new_mask);
7979 out_free_cpus_allowed:
7980 free_cpumask_var(cpus_allowed);
7984 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
7986 struct task_struct *p;
7991 p = find_process_by_pid(pid);
7997 /* Prevent p going away */
8001 if (p->flags & PF_NO_SETAFFINITY) {
8006 if (!check_same_owner(p)) {
8008 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
8016 retval = security_task_setscheduler(p);
8020 retval = __sched_setaffinity(p, in_mask);
8026 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
8027 struct cpumask *new_mask)
8029 if (len < cpumask_size())
8030 cpumask_clear(new_mask);
8031 else if (len > cpumask_size())
8032 len = cpumask_size();
8034 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
8038 * sys_sched_setaffinity - set the CPU affinity of a process
8039 * @pid: pid of the process
8040 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8041 * @user_mask_ptr: user-space pointer to the new CPU mask
8043 * Return: 0 on success. An error code otherwise.
8045 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
8046 unsigned long __user *, user_mask_ptr)
8048 cpumask_var_t new_mask;
8051 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
8054 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
8056 retval = sched_setaffinity(pid, new_mask);
8057 free_cpumask_var(new_mask);
8061 long sched_getaffinity(pid_t pid, struct cpumask *mask)
8063 struct task_struct *p;
8064 unsigned long flags;
8070 p = find_process_by_pid(pid);
8074 retval = security_task_getscheduler(p);
8078 raw_spin_lock_irqsave(&p->pi_lock, flags);
8079 cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
8080 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
8089 * sys_sched_getaffinity - get the CPU affinity of a process
8090 * @pid: pid of the process
8091 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8092 * @user_mask_ptr: user-space pointer to hold the current CPU mask
8094 * Return: size of CPU mask copied to user_mask_ptr on success. An
8095 * error code otherwise.
8097 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
8098 unsigned long __user *, user_mask_ptr)
8103 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
8105 if (len & (sizeof(unsigned long)-1))
8108 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
8111 ret = sched_getaffinity(pid, mask);
8113 unsigned int retlen = min(len, cpumask_size());
8115 if (copy_to_user(user_mask_ptr, mask, retlen))
8120 free_cpumask_var(mask);
8125 static void do_sched_yield(void)
8130 rq = this_rq_lock_irq(&rf);
8132 schedstat_inc(rq->yld_count);
8133 current->sched_class->yield_task(rq);
8136 rq_unlock_irq(rq, &rf);
8137 sched_preempt_enable_no_resched();
8143 * sys_sched_yield - yield the current processor to other threads.
8145 * This function yields the current CPU to other tasks. If there are no
8146 * other threads running on this CPU then this function will return.
8150 SYSCALL_DEFINE0(sched_yield)
8156 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
8157 int __sched __cond_resched(void)
8159 if (should_resched(0)) {
8160 preempt_schedule_common();
8164 * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
8165 * whether the current CPU is in an RCU read-side critical section,
8166 * so the tick can report quiescent states even for CPUs looping
8167 * in kernel context. In contrast, in non-preemptible kernels,
8168 * RCU readers leave no in-memory hints, which means that CPU-bound
8169 * processes executing in kernel context might never report an
8170 * RCU quiescent state. Therefore, the following code causes
8171 * cond_resched() to report a quiescent state, but only when RCU
8172 * is in urgent need of one.
8174 #ifndef CONFIG_PREEMPT_RCU
8179 EXPORT_SYMBOL(__cond_resched);
8182 #ifdef CONFIG_PREEMPT_DYNAMIC
8183 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8184 #define cond_resched_dynamic_enabled __cond_resched
8185 #define cond_resched_dynamic_disabled ((void *)&__static_call_return0)
8186 DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
8187 EXPORT_STATIC_CALL_TRAMP(cond_resched);
8189 #define might_resched_dynamic_enabled __cond_resched
8190 #define might_resched_dynamic_disabled ((void *)&__static_call_return0)
8191 DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
8192 EXPORT_STATIC_CALL_TRAMP(might_resched);
8193 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8194 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched);
8195 int __sched dynamic_cond_resched(void)
8197 if (!static_branch_unlikely(&sk_dynamic_cond_resched))
8199 return __cond_resched();
8201 EXPORT_SYMBOL(dynamic_cond_resched);
8203 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched);
8204 int __sched dynamic_might_resched(void)
8206 if (!static_branch_unlikely(&sk_dynamic_might_resched))
8208 return __cond_resched();
8210 EXPORT_SYMBOL(dynamic_might_resched);
8215 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
8216 * call schedule, and on return reacquire the lock.
8218 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
8219 * operations here to prevent schedule() from being called twice (once via
8220 * spin_unlock(), once by hand).
8222 int __cond_resched_lock(spinlock_t *lock)
8224 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8227 lockdep_assert_held(lock);
8229 if (spin_needbreak(lock) || resched) {
8231 if (!_cond_resched())
8238 EXPORT_SYMBOL(__cond_resched_lock);
8240 int __cond_resched_rwlock_read(rwlock_t *lock)
8242 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8245 lockdep_assert_held_read(lock);
8247 if (rwlock_needbreak(lock) || resched) {
8249 if (!_cond_resched())
8256 EXPORT_SYMBOL(__cond_resched_rwlock_read);
8258 int __cond_resched_rwlock_write(rwlock_t *lock)
8260 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8263 lockdep_assert_held_write(lock);
8265 if (rwlock_needbreak(lock) || resched) {
8267 if (!_cond_resched())
8274 EXPORT_SYMBOL(__cond_resched_rwlock_write);
8276 #ifdef CONFIG_PREEMPT_DYNAMIC
8278 #ifdef CONFIG_GENERIC_ENTRY
8279 #include <linux/entry-common.h>
8285 * SC:preempt_schedule
8286 * SC:preempt_schedule_notrace
8287 * SC:irqentry_exit_cond_resched
8291 * cond_resched <- __cond_resched
8292 * might_resched <- RET0
8293 * preempt_schedule <- NOP
8294 * preempt_schedule_notrace <- NOP
8295 * irqentry_exit_cond_resched <- NOP
8298 * cond_resched <- __cond_resched
8299 * might_resched <- __cond_resched
8300 * preempt_schedule <- NOP
8301 * preempt_schedule_notrace <- NOP
8302 * irqentry_exit_cond_resched <- NOP
8305 * cond_resched <- RET0
8306 * might_resched <- RET0
8307 * preempt_schedule <- preempt_schedule
8308 * preempt_schedule_notrace <- preempt_schedule_notrace
8309 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched
8313 preempt_dynamic_undefined = -1,
8314 preempt_dynamic_none,
8315 preempt_dynamic_voluntary,
8316 preempt_dynamic_full,
8319 int preempt_dynamic_mode = preempt_dynamic_undefined;
8321 int sched_dynamic_mode(const char *str)
8323 if (!strcmp(str, "none"))
8324 return preempt_dynamic_none;
8326 if (!strcmp(str, "voluntary"))
8327 return preempt_dynamic_voluntary;
8329 if (!strcmp(str, "full"))
8330 return preempt_dynamic_full;
8335 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8336 #define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled)
8337 #define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled)
8338 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8339 #define preempt_dynamic_enable(f) static_key_enable(&sk_dynamic_##f.key)
8340 #define preempt_dynamic_disable(f) static_key_disable(&sk_dynamic_##f.key)
8342 #error "Unsupported PREEMPT_DYNAMIC mechanism"
8345 void sched_dynamic_update(int mode)
8348 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
8349 * the ZERO state, which is invalid.
8351 preempt_dynamic_enable(cond_resched);
8352 preempt_dynamic_enable(might_resched);
8353 preempt_dynamic_enable(preempt_schedule);
8354 preempt_dynamic_enable(preempt_schedule_notrace);
8355 preempt_dynamic_enable(irqentry_exit_cond_resched);
8358 case preempt_dynamic_none:
8359 preempt_dynamic_enable(cond_resched);
8360 preempt_dynamic_disable(might_resched);
8361 preempt_dynamic_disable(preempt_schedule);
8362 preempt_dynamic_disable(preempt_schedule_notrace);
8363 preempt_dynamic_disable(irqentry_exit_cond_resched);
8364 pr_info("Dynamic Preempt: none\n");
8367 case preempt_dynamic_voluntary:
8368 preempt_dynamic_enable(cond_resched);
8369 preempt_dynamic_enable(might_resched);
8370 preempt_dynamic_disable(preempt_schedule);
8371 preempt_dynamic_disable(preempt_schedule_notrace);
8372 preempt_dynamic_disable(irqentry_exit_cond_resched);
8373 pr_info("Dynamic Preempt: voluntary\n");
8376 case preempt_dynamic_full:
8377 preempt_dynamic_disable(cond_resched);
8378 preempt_dynamic_disable(might_resched);
8379 preempt_dynamic_enable(preempt_schedule);
8380 preempt_dynamic_enable(preempt_schedule_notrace);
8381 preempt_dynamic_enable(irqentry_exit_cond_resched);
8382 pr_info("Dynamic Preempt: full\n");
8386 preempt_dynamic_mode = mode;
8389 static int __init setup_preempt_mode(char *str)
8391 int mode = sched_dynamic_mode(str);
8393 pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
8397 sched_dynamic_update(mode);
8400 __setup("preempt=", setup_preempt_mode);
8402 static void __init preempt_dynamic_init(void)
8404 if (preempt_dynamic_mode == preempt_dynamic_undefined) {
8405 if (IS_ENABLED(CONFIG_PREEMPT_NONE)) {
8406 sched_dynamic_update(preempt_dynamic_none);
8407 } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) {
8408 sched_dynamic_update(preempt_dynamic_voluntary);
8410 /* Default static call setting, nothing to do */
8411 WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT));
8412 preempt_dynamic_mode = preempt_dynamic_full;
8413 pr_info("Dynamic Preempt: full\n");
8418 #define PREEMPT_MODEL_ACCESSOR(mode) \
8419 bool preempt_model_##mode(void) \
8421 WARN_ON_ONCE(preempt_dynamic_mode == preempt_dynamic_undefined); \
8422 return preempt_dynamic_mode == preempt_dynamic_##mode; \
8424 EXPORT_SYMBOL_GPL(preempt_model_##mode)
8426 PREEMPT_MODEL_ACCESSOR(none);
8427 PREEMPT_MODEL_ACCESSOR(voluntary);
8428 PREEMPT_MODEL_ACCESSOR(full);
8430 #else /* !CONFIG_PREEMPT_DYNAMIC */
8432 static inline void preempt_dynamic_init(void) { }
8434 #endif /* #ifdef CONFIG_PREEMPT_DYNAMIC */
8437 * yield - yield the current processor to other threads.
8439 * Do not ever use this function, there's a 99% chance you're doing it wrong.
8441 * The scheduler is at all times free to pick the calling task as the most
8442 * eligible task to run, if removing the yield() call from your code breaks
8443 * it, it's already broken.
8445 * Typical broken usage is:
8450 * where one assumes that yield() will let 'the other' process run that will
8451 * make event true. If the current task is a SCHED_FIFO task that will never
8452 * happen. Never use yield() as a progress guarantee!!
8454 * If you want to use yield() to wait for something, use wait_event().
8455 * If you want to use yield() to be 'nice' for others, use cond_resched().
8456 * If you still want to use yield(), do not!
8458 void __sched yield(void)
8460 set_current_state(TASK_RUNNING);
8463 EXPORT_SYMBOL(yield);
8466 * yield_to - yield the current processor to another thread in
8467 * your thread group, or accelerate that thread toward the
8468 * processor it's on.
8470 * @preempt: whether task preemption is allowed or not
8472 * It's the caller's job to ensure that the target task struct
8473 * can't go away on us before we can do any checks.
8476 * true (>0) if we indeed boosted the target task.
8477 * false (0) if we failed to boost the target.
8478 * -ESRCH if there's no task to yield to.
8480 int __sched yield_to(struct task_struct *p, bool preempt)
8482 struct task_struct *curr = current;
8483 struct rq *rq, *p_rq;
8484 unsigned long flags;
8487 local_irq_save(flags);
8493 * If we're the only runnable task on the rq and target rq also
8494 * has only one task, there's absolutely no point in yielding.
8496 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
8501 double_rq_lock(rq, p_rq);
8502 if (task_rq(p) != p_rq) {
8503 double_rq_unlock(rq, p_rq);
8507 if (!curr->sched_class->yield_to_task)
8510 if (curr->sched_class != p->sched_class)
8513 if (task_running(p_rq, p) || !task_is_running(p))
8516 yielded = curr->sched_class->yield_to_task(rq, p);
8518 schedstat_inc(rq->yld_count);
8520 * Make p's CPU reschedule; pick_next_entity takes care of
8523 if (preempt && rq != p_rq)
8528 double_rq_unlock(rq, p_rq);
8530 local_irq_restore(flags);
8537 EXPORT_SYMBOL_GPL(yield_to);
8539 int io_schedule_prepare(void)
8541 int old_iowait = current->in_iowait;
8543 current->in_iowait = 1;
8544 blk_flush_plug(current->plug, true);
8548 void io_schedule_finish(int token)
8550 current->in_iowait = token;
8554 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
8555 * that process accounting knows that this is a task in IO wait state.
8557 long __sched io_schedule_timeout(long timeout)
8562 token = io_schedule_prepare();
8563 ret = schedule_timeout(timeout);
8564 io_schedule_finish(token);
8568 EXPORT_SYMBOL(io_schedule_timeout);
8570 void __sched io_schedule(void)
8574 token = io_schedule_prepare();
8576 io_schedule_finish(token);
8578 EXPORT_SYMBOL(io_schedule);
8581 * sys_sched_get_priority_max - return maximum RT priority.
8582 * @policy: scheduling class.
8584 * Return: On success, this syscall returns the maximum
8585 * rt_priority that can be used by a given scheduling class.
8586 * On failure, a negative error code is returned.
8588 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
8595 ret = MAX_RT_PRIO-1;
8597 case SCHED_DEADLINE:
8608 * sys_sched_get_priority_min - return minimum RT priority.
8609 * @policy: scheduling class.
8611 * Return: On success, this syscall returns the minimum
8612 * rt_priority that can be used by a given scheduling class.
8613 * On failure, a negative error code is returned.
8615 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
8624 case SCHED_DEADLINE:
8633 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
8635 struct task_struct *p;
8636 unsigned int time_slice;
8646 p = find_process_by_pid(pid);
8650 retval = security_task_getscheduler(p);
8654 rq = task_rq_lock(p, &rf);
8656 if (p->sched_class->get_rr_interval)
8657 time_slice = p->sched_class->get_rr_interval(rq, p);
8658 task_rq_unlock(rq, p, &rf);
8661 jiffies_to_timespec64(time_slice, t);
8670 * sys_sched_rr_get_interval - return the default timeslice of a process.
8671 * @pid: pid of the process.
8672 * @interval: userspace pointer to the timeslice value.
8674 * this syscall writes the default timeslice value of a given process
8675 * into the user-space timespec buffer. A value of '0' means infinity.
8677 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
8680 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
8681 struct __kernel_timespec __user *, interval)
8683 struct timespec64 t;
8684 int retval = sched_rr_get_interval(pid, &t);
8687 retval = put_timespec64(&t, interval);
8692 #ifdef CONFIG_COMPAT_32BIT_TIME
8693 SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
8694 struct old_timespec32 __user *, interval)
8696 struct timespec64 t;
8697 int retval = sched_rr_get_interval(pid, &t);
8700 retval = put_old_timespec32(&t, interval);
8705 void sched_show_task(struct task_struct *p)
8707 unsigned long free = 0;
8710 if (!try_get_task_stack(p))
8713 pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
8715 if (task_is_running(p))
8716 pr_cont(" running task ");
8717 #ifdef CONFIG_DEBUG_STACK_USAGE
8718 free = stack_not_used(p);
8723 ppid = task_pid_nr(rcu_dereference(p->real_parent));
8725 pr_cont(" stack:%5lu pid:%5d ppid:%6d flags:0x%08lx\n",
8726 free, task_pid_nr(p), ppid,
8727 read_task_thread_flags(p));
8729 print_worker_info(KERN_INFO, p);
8730 print_stop_info(KERN_INFO, p);
8731 show_stack(p, NULL, KERN_INFO);
8734 EXPORT_SYMBOL_GPL(sched_show_task);
8737 state_filter_match(unsigned long state_filter, struct task_struct *p)
8739 unsigned int state = READ_ONCE(p->__state);
8741 /* no filter, everything matches */
8745 /* filter, but doesn't match */
8746 if (!(state & state_filter))
8750 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
8753 if (state_filter == TASK_UNINTERRUPTIBLE && state == TASK_IDLE)
8760 void show_state_filter(unsigned int state_filter)
8762 struct task_struct *g, *p;
8765 for_each_process_thread(g, p) {
8767 * reset the NMI-timeout, listing all files on a slow
8768 * console might take a lot of time:
8769 * Also, reset softlockup watchdogs on all CPUs, because
8770 * another CPU might be blocked waiting for us to process
8773 touch_nmi_watchdog();
8774 touch_all_softlockup_watchdogs();
8775 if (state_filter_match(state_filter, p))
8779 #ifdef CONFIG_SCHED_DEBUG
8781 sysrq_sched_debug_show();
8785 * Only show locks if all tasks are dumped:
8788 debug_show_all_locks();
8792 * init_idle - set up an idle thread for a given CPU
8793 * @idle: task in question
8794 * @cpu: CPU the idle task belongs to
8796 * NOTE: this function does not set the idle thread's NEED_RESCHED
8797 * flag, to make booting more robust.
8799 void __init init_idle(struct task_struct *idle, int cpu)
8801 struct rq *rq = cpu_rq(cpu);
8802 unsigned long flags;
8804 __sched_fork(0, idle);
8806 raw_spin_lock_irqsave(&idle->pi_lock, flags);
8807 raw_spin_rq_lock(rq);
8809 idle->__state = TASK_RUNNING;
8810 idle->se.exec_start = sched_clock();
8812 * PF_KTHREAD should already be set at this point; regardless, make it
8813 * look like a proper per-CPU kthread.
8815 idle->flags |= PF_IDLE | PF_KTHREAD | PF_NO_SETAFFINITY;
8816 kthread_set_per_cpu(idle, cpu);
8820 * It's possible that init_idle() gets called multiple times on a task,
8821 * in that case do_set_cpus_allowed() will not do the right thing.
8823 * And since this is boot we can forgo the serialization.
8825 set_cpus_allowed_common(idle, cpumask_of(cpu), 0);
8828 * We're having a chicken and egg problem, even though we are
8829 * holding rq->lock, the CPU isn't yet set to this CPU so the
8830 * lockdep check in task_group() will fail.
8832 * Similar case to sched_fork(). / Alternatively we could
8833 * use task_rq_lock() here and obtain the other rq->lock.
8838 __set_task_cpu(idle, cpu);
8842 rcu_assign_pointer(rq->curr, idle);
8843 idle->on_rq = TASK_ON_RQ_QUEUED;
8847 raw_spin_rq_unlock(rq);
8848 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
8850 /* Set the preempt count _outside_ the spinlocks! */
8851 init_idle_preempt_count(idle, cpu);
8854 * The idle tasks have their own, simple scheduling class:
8856 idle->sched_class = &idle_sched_class;
8857 ftrace_graph_init_idle_task(idle, cpu);
8858 vtime_init_idle(idle, cpu);
8860 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
8866 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
8867 const struct cpumask *trial)
8871 if (cpumask_empty(cur))
8874 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
8879 int task_can_attach(struct task_struct *p,
8880 const struct cpumask *cs_cpus_allowed)
8885 * Kthreads which disallow setaffinity shouldn't be moved
8886 * to a new cpuset; we don't want to change their CPU
8887 * affinity and isolating such threads by their set of
8888 * allowed nodes is unnecessary. Thus, cpusets are not
8889 * applicable for such threads. This prevents checking for
8890 * success of set_cpus_allowed_ptr() on all attached tasks
8891 * before cpus_mask may be changed.
8893 if (p->flags & PF_NO_SETAFFINITY) {
8898 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
8900 int cpu = cpumask_any_and(cpu_active_mask, cs_cpus_allowed);
8902 ret = dl_cpu_busy(cpu, p);
8909 bool sched_smp_initialized __read_mostly;
8911 #ifdef CONFIG_NUMA_BALANCING
8912 /* Migrate current task p to target_cpu */
8913 int migrate_task_to(struct task_struct *p, int target_cpu)
8915 struct migration_arg arg = { p, target_cpu };
8916 int curr_cpu = task_cpu(p);
8918 if (curr_cpu == target_cpu)
8921 if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
8924 /* TODO: This is not properly updating schedstats */
8926 trace_sched_move_numa(p, curr_cpu, target_cpu);
8927 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
8931 * Requeue a task on a given node and accurately track the number of NUMA
8932 * tasks on the runqueues
8934 void sched_setnuma(struct task_struct *p, int nid)
8936 bool queued, running;
8940 rq = task_rq_lock(p, &rf);
8941 queued = task_on_rq_queued(p);
8942 running = task_current(rq, p);
8945 dequeue_task(rq, p, DEQUEUE_SAVE);
8947 put_prev_task(rq, p);
8949 p->numa_preferred_nid = nid;
8952 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
8954 set_next_task(rq, p);
8955 task_rq_unlock(rq, p, &rf);
8957 #endif /* CONFIG_NUMA_BALANCING */
8959 #ifdef CONFIG_HOTPLUG_CPU
8961 * Ensure that the idle task is using init_mm right before its CPU goes
8964 void idle_task_exit(void)
8966 struct mm_struct *mm = current->active_mm;
8968 BUG_ON(cpu_online(smp_processor_id()));
8969 BUG_ON(current != this_rq()->idle);
8971 if (mm != &init_mm) {
8972 switch_mm(mm, &init_mm, current);
8973 finish_arch_post_lock_switch();
8976 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
8979 static int __balance_push_cpu_stop(void *arg)
8981 struct task_struct *p = arg;
8982 struct rq *rq = this_rq();
8986 raw_spin_lock_irq(&p->pi_lock);
8989 update_rq_clock(rq);
8991 if (task_rq(p) == rq && task_on_rq_queued(p)) {
8992 cpu = select_fallback_rq(rq->cpu, p);
8993 rq = __migrate_task(rq, &rf, p, cpu);
8997 raw_spin_unlock_irq(&p->pi_lock);
9004 static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
9007 * Ensure we only run per-cpu kthreads once the CPU goes !active.
9009 * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
9010 * effective when the hotplug motion is down.
9012 static void balance_push(struct rq *rq)
9014 struct task_struct *push_task = rq->curr;
9016 lockdep_assert_rq_held(rq);
9019 * Ensure the thing is persistent until balance_push_set(.on = false);
9021 rq->balance_callback = &balance_push_callback;
9024 * Only active while going offline and when invoked on the outgoing
9027 if (!cpu_dying(rq->cpu) || rq != this_rq())
9031 * Both the cpu-hotplug and stop task are in this case and are
9032 * required to complete the hotplug process.
9034 if (kthread_is_per_cpu(push_task) ||
9035 is_migration_disabled(push_task)) {
9038 * If this is the idle task on the outgoing CPU try to wake
9039 * up the hotplug control thread which might wait for the
9040 * last task to vanish. The rcuwait_active() check is
9041 * accurate here because the waiter is pinned on this CPU
9042 * and can't obviously be running in parallel.
9044 * On RT kernels this also has to check whether there are
9045 * pinned and scheduled out tasks on the runqueue. They
9046 * need to leave the migrate disabled section first.
9048 if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
9049 rcuwait_active(&rq->hotplug_wait)) {
9050 raw_spin_rq_unlock(rq);
9051 rcuwait_wake_up(&rq->hotplug_wait);
9052 raw_spin_rq_lock(rq);
9057 get_task_struct(push_task);
9059 * Temporarily drop rq->lock such that we can wake-up the stop task.
9060 * Both preemption and IRQs are still disabled.
9062 raw_spin_rq_unlock(rq);
9063 stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
9064 this_cpu_ptr(&push_work));
9066 * At this point need_resched() is true and we'll take the loop in
9067 * schedule(). The next pick is obviously going to be the stop task
9068 * which kthread_is_per_cpu() and will push this task away.
9070 raw_spin_rq_lock(rq);
9073 static void balance_push_set(int cpu, bool on)
9075 struct rq *rq = cpu_rq(cpu);
9078 rq_lock_irqsave(rq, &rf);
9080 WARN_ON_ONCE(rq->balance_callback);
9081 rq->balance_callback = &balance_push_callback;
9082 } else if (rq->balance_callback == &balance_push_callback) {
9083 rq->balance_callback = NULL;
9085 rq_unlock_irqrestore(rq, &rf);
9089 * Invoked from a CPUs hotplug control thread after the CPU has been marked
9090 * inactive. All tasks which are not per CPU kernel threads are either
9091 * pushed off this CPU now via balance_push() or placed on a different CPU
9092 * during wakeup. Wait until the CPU is quiescent.
9094 static void balance_hotplug_wait(void)
9096 struct rq *rq = this_rq();
9098 rcuwait_wait_event(&rq->hotplug_wait,
9099 rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
9100 TASK_UNINTERRUPTIBLE);
9105 static inline void balance_push(struct rq *rq)
9109 static inline void balance_push_set(int cpu, bool on)
9113 static inline void balance_hotplug_wait(void)
9117 #endif /* CONFIG_HOTPLUG_CPU */
9119 void set_rq_online(struct rq *rq)
9122 const struct sched_class *class;
9124 cpumask_set_cpu(rq->cpu, rq->rd->online);
9127 for_each_class(class) {
9128 if (class->rq_online)
9129 class->rq_online(rq);
9134 void set_rq_offline(struct rq *rq)
9137 const struct sched_class *class;
9139 for_each_class(class) {
9140 if (class->rq_offline)
9141 class->rq_offline(rq);
9144 cpumask_clear_cpu(rq->cpu, rq->rd->online);
9150 * used to mark begin/end of suspend/resume:
9152 static int num_cpus_frozen;
9155 * Update cpusets according to cpu_active mask. If cpusets are
9156 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
9157 * around partition_sched_domains().
9159 * If we come here as part of a suspend/resume, don't touch cpusets because we
9160 * want to restore it back to its original state upon resume anyway.
9162 static void cpuset_cpu_active(void)
9164 if (cpuhp_tasks_frozen) {
9166 * num_cpus_frozen tracks how many CPUs are involved in suspend
9167 * resume sequence. As long as this is not the last online
9168 * operation in the resume sequence, just build a single sched
9169 * domain, ignoring cpusets.
9171 partition_sched_domains(1, NULL, NULL);
9172 if (--num_cpus_frozen)
9175 * This is the last CPU online operation. So fall through and
9176 * restore the original sched domains by considering the
9177 * cpuset configurations.
9179 cpuset_force_rebuild();
9181 cpuset_update_active_cpus();
9184 static int cpuset_cpu_inactive(unsigned int cpu)
9186 if (!cpuhp_tasks_frozen) {
9187 int ret = dl_cpu_busy(cpu, NULL);
9191 cpuset_update_active_cpus();
9194 partition_sched_domains(1, NULL, NULL);
9199 int sched_cpu_activate(unsigned int cpu)
9201 struct rq *rq = cpu_rq(cpu);
9205 * Clear the balance_push callback and prepare to schedule
9208 balance_push_set(cpu, false);
9210 #ifdef CONFIG_SCHED_SMT
9212 * When going up, increment the number of cores with SMT present.
9214 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9215 static_branch_inc_cpuslocked(&sched_smt_present);
9217 set_cpu_active(cpu, true);
9219 if (sched_smp_initialized) {
9220 sched_update_numa(cpu, true);
9221 sched_domains_numa_masks_set(cpu);
9222 cpuset_cpu_active();
9226 * Put the rq online, if not already. This happens:
9228 * 1) In the early boot process, because we build the real domains
9229 * after all CPUs have been brought up.
9231 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
9234 rq_lock_irqsave(rq, &rf);
9236 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9239 rq_unlock_irqrestore(rq, &rf);
9244 int sched_cpu_deactivate(unsigned int cpu)
9246 struct rq *rq = cpu_rq(cpu);
9251 * Remove CPU from nohz.idle_cpus_mask to prevent participating in
9252 * load balancing when not active
9254 nohz_balance_exit_idle(rq);
9256 set_cpu_active(cpu, false);
9259 * From this point forward, this CPU will refuse to run any task that
9260 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
9261 * push those tasks away until this gets cleared, see
9262 * sched_cpu_dying().
9264 balance_push_set(cpu, true);
9267 * We've cleared cpu_active_mask / set balance_push, wait for all
9268 * preempt-disabled and RCU users of this state to go away such that
9269 * all new such users will observe it.
9271 * Specifically, we rely on ttwu to no longer target this CPU, see
9272 * ttwu_queue_cond() and is_cpu_allowed().
9274 * Do sync before park smpboot threads to take care the rcu boost case.
9278 rq_lock_irqsave(rq, &rf);
9280 update_rq_clock(rq);
9281 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9284 rq_unlock_irqrestore(rq, &rf);
9286 #ifdef CONFIG_SCHED_SMT
9288 * When going down, decrement the number of cores with SMT present.
9290 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9291 static_branch_dec_cpuslocked(&sched_smt_present);
9293 sched_core_cpu_deactivate(cpu);
9296 if (!sched_smp_initialized)
9299 sched_update_numa(cpu, false);
9300 ret = cpuset_cpu_inactive(cpu);
9302 balance_push_set(cpu, false);
9303 set_cpu_active(cpu, true);
9304 sched_update_numa(cpu, true);
9307 sched_domains_numa_masks_clear(cpu);
9311 static void sched_rq_cpu_starting(unsigned int cpu)
9313 struct rq *rq = cpu_rq(cpu);
9315 rq->calc_load_update = calc_load_update;
9316 update_max_interval();
9319 int sched_cpu_starting(unsigned int cpu)
9321 sched_core_cpu_starting(cpu);
9322 sched_rq_cpu_starting(cpu);
9323 sched_tick_start(cpu);
9327 #ifdef CONFIG_HOTPLUG_CPU
9330 * Invoked immediately before the stopper thread is invoked to bring the
9331 * CPU down completely. At this point all per CPU kthreads except the
9332 * hotplug thread (current) and the stopper thread (inactive) have been
9333 * either parked or have been unbound from the outgoing CPU. Ensure that
9334 * any of those which might be on the way out are gone.
9336 * If after this point a bound task is being woken on this CPU then the
9337 * responsible hotplug callback has failed to do it's job.
9338 * sched_cpu_dying() will catch it with the appropriate fireworks.
9340 int sched_cpu_wait_empty(unsigned int cpu)
9342 balance_hotplug_wait();
9347 * Since this CPU is going 'away' for a while, fold any nr_active delta we
9348 * might have. Called from the CPU stopper task after ensuring that the
9349 * stopper is the last running task on the CPU, so nr_active count is
9350 * stable. We need to take the teardown thread which is calling this into
9351 * account, so we hand in adjust = 1 to the load calculation.
9353 * Also see the comment "Global load-average calculations".
9355 static void calc_load_migrate(struct rq *rq)
9357 long delta = calc_load_fold_active(rq, 1);
9360 atomic_long_add(delta, &calc_load_tasks);
9363 static void dump_rq_tasks(struct rq *rq, const char *loglvl)
9365 struct task_struct *g, *p;
9366 int cpu = cpu_of(rq);
9368 lockdep_assert_rq_held(rq);
9370 printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
9371 for_each_process_thread(g, p) {
9372 if (task_cpu(p) != cpu)
9375 if (!task_on_rq_queued(p))
9378 printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
9382 int sched_cpu_dying(unsigned int cpu)
9384 struct rq *rq = cpu_rq(cpu);
9387 /* Handle pending wakeups and then migrate everything off */
9388 sched_tick_stop(cpu);
9390 rq_lock_irqsave(rq, &rf);
9391 if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
9392 WARN(true, "Dying CPU not properly vacated!");
9393 dump_rq_tasks(rq, KERN_WARNING);
9395 rq_unlock_irqrestore(rq, &rf);
9397 calc_load_migrate(rq);
9398 update_max_interval();
9400 sched_core_cpu_dying(cpu);
9405 void __init sched_init_smp(void)
9407 sched_init_numa(NUMA_NO_NODE);
9410 * There's no userspace yet to cause hotplug operations; hence all the
9411 * CPU masks are stable and all blatant races in the below code cannot
9414 mutex_lock(&sched_domains_mutex);
9415 sched_init_domains(cpu_active_mask);
9416 mutex_unlock(&sched_domains_mutex);
9418 /* Move init over to a non-isolated CPU */
9419 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0)
9421 current->flags &= ~PF_NO_SETAFFINITY;
9422 sched_init_granularity();
9424 init_sched_rt_class();
9425 init_sched_dl_class();
9427 sched_smp_initialized = true;
9430 static int __init migration_init(void)
9432 sched_cpu_starting(smp_processor_id());
9435 early_initcall(migration_init);
9438 void __init sched_init_smp(void)
9440 sched_init_granularity();
9442 #endif /* CONFIG_SMP */
9444 int in_sched_functions(unsigned long addr)
9446 return in_lock_functions(addr) ||
9447 (addr >= (unsigned long)__sched_text_start
9448 && addr < (unsigned long)__sched_text_end);
9451 #ifdef CONFIG_CGROUP_SCHED
9453 * Default task group.
9454 * Every task in system belongs to this group at bootup.
9456 struct task_group root_task_group;
9457 LIST_HEAD(task_groups);
9459 /* Cacheline aligned slab cache for task_group */
9460 static struct kmem_cache *task_group_cache __read_mostly;
9463 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
9464 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
9466 void __init sched_init(void)
9468 unsigned long ptr = 0;
9471 /* Make sure the linker didn't screw up */
9472 BUG_ON(&idle_sched_class + 1 != &fair_sched_class ||
9473 &fair_sched_class + 1 != &rt_sched_class ||
9474 &rt_sched_class + 1 != &dl_sched_class);
9476 BUG_ON(&dl_sched_class + 1 != &stop_sched_class);
9481 #ifdef CONFIG_FAIR_GROUP_SCHED
9482 ptr += 2 * nr_cpu_ids * sizeof(void **);
9484 #ifdef CONFIG_RT_GROUP_SCHED
9485 ptr += 2 * nr_cpu_ids * sizeof(void **);
9488 ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
9490 #ifdef CONFIG_FAIR_GROUP_SCHED
9491 root_task_group.se = (struct sched_entity **)ptr;
9492 ptr += nr_cpu_ids * sizeof(void **);
9494 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
9495 ptr += nr_cpu_ids * sizeof(void **);
9497 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
9498 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
9499 #endif /* CONFIG_FAIR_GROUP_SCHED */
9500 #ifdef CONFIG_RT_GROUP_SCHED
9501 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
9502 ptr += nr_cpu_ids * sizeof(void **);
9504 root_task_group.rt_rq = (struct rt_rq **)ptr;
9505 ptr += nr_cpu_ids * sizeof(void **);
9507 #endif /* CONFIG_RT_GROUP_SCHED */
9509 #ifdef CONFIG_CPUMASK_OFFSTACK
9510 for_each_possible_cpu(i) {
9511 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
9512 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
9513 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
9514 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
9516 #endif /* CONFIG_CPUMASK_OFFSTACK */
9518 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
9521 init_defrootdomain();
9524 #ifdef CONFIG_RT_GROUP_SCHED
9525 init_rt_bandwidth(&root_task_group.rt_bandwidth,
9526 global_rt_period(), global_rt_runtime());
9527 #endif /* CONFIG_RT_GROUP_SCHED */
9529 #ifdef CONFIG_CGROUP_SCHED
9530 task_group_cache = KMEM_CACHE(task_group, 0);
9532 list_add(&root_task_group.list, &task_groups);
9533 INIT_LIST_HEAD(&root_task_group.children);
9534 INIT_LIST_HEAD(&root_task_group.siblings);
9535 autogroup_init(&init_task);
9536 #endif /* CONFIG_CGROUP_SCHED */
9538 for_each_possible_cpu(i) {
9542 raw_spin_lock_init(&rq->__lock);
9544 rq->calc_load_active = 0;
9545 rq->calc_load_update = jiffies + LOAD_FREQ;
9546 init_cfs_rq(&rq->cfs);
9547 init_rt_rq(&rq->rt);
9548 init_dl_rq(&rq->dl);
9549 #ifdef CONFIG_FAIR_GROUP_SCHED
9550 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9551 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
9553 * How much CPU bandwidth does root_task_group get?
9555 * In case of task-groups formed thr' the cgroup filesystem, it
9556 * gets 100% of the CPU resources in the system. This overall
9557 * system CPU resource is divided among the tasks of
9558 * root_task_group and its child task-groups in a fair manner,
9559 * based on each entity's (task or task-group's) weight
9560 * (se->load.weight).
9562 * In other words, if root_task_group has 10 tasks of weight
9563 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9564 * then A0's share of the CPU resource is:
9566 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9568 * We achieve this by letting root_task_group's tasks sit
9569 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
9571 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
9572 #endif /* CONFIG_FAIR_GROUP_SCHED */
9574 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
9575 #ifdef CONFIG_RT_GROUP_SCHED
9576 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
9581 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
9582 rq->balance_callback = &balance_push_callback;
9583 rq->active_balance = 0;
9584 rq->next_balance = jiffies;
9589 rq->avg_idle = 2*sysctl_sched_migration_cost;
9590 rq->wake_stamp = jiffies;
9591 rq->wake_avg_idle = rq->avg_idle;
9592 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
9594 INIT_LIST_HEAD(&rq->cfs_tasks);
9596 rq_attach_root(rq, &def_root_domain);
9597 #ifdef CONFIG_NO_HZ_COMMON
9598 rq->last_blocked_load_update_tick = jiffies;
9599 atomic_set(&rq->nohz_flags, 0);
9601 INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
9603 #ifdef CONFIG_HOTPLUG_CPU
9604 rcuwait_init(&rq->hotplug_wait);
9606 #endif /* CONFIG_SMP */
9608 atomic_set(&rq->nr_iowait, 0);
9610 #ifdef CONFIG_SCHED_CORE
9612 rq->core_pick = NULL;
9613 rq->core_enabled = 0;
9614 rq->core_tree = RB_ROOT;
9615 rq->core_forceidle_count = 0;
9616 rq->core_forceidle_occupation = 0;
9617 rq->core_forceidle_start = 0;
9619 rq->core_cookie = 0UL;
9623 set_load_weight(&init_task, false);
9626 * The boot idle thread does lazy MMU switching as well:
9629 enter_lazy_tlb(&init_mm, current);
9632 * The idle task doesn't need the kthread struct to function, but it
9633 * is dressed up as a per-CPU kthread and thus needs to play the part
9634 * if we want to avoid special-casing it in code that deals with per-CPU
9637 WARN_ON(!set_kthread_struct(current));
9640 * Make us the idle thread. Technically, schedule() should not be
9641 * called from this thread, however somewhere below it might be,
9642 * but because we are the idle thread, we just pick up running again
9643 * when this runqueue becomes "idle".
9645 init_idle(current, smp_processor_id());
9647 calc_load_update = jiffies + LOAD_FREQ;
9650 idle_thread_set_boot_cpu();
9651 balance_push_set(smp_processor_id(), false);
9653 init_sched_fair_class();
9659 preempt_dynamic_init();
9661 scheduler_running = 1;
9664 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
9666 void __might_sleep(const char *file, int line)
9668 unsigned int state = get_current_state();
9670 * Blocking primitives will set (and therefore destroy) current->state,
9671 * since we will exit with TASK_RUNNING make sure we enter with it,
9672 * otherwise we will destroy state.
9674 WARN_ONCE(state != TASK_RUNNING && current->task_state_change,
9675 "do not call blocking ops when !TASK_RUNNING; "
9676 "state=%x set at [<%p>] %pS\n", state,
9677 (void *)current->task_state_change,
9678 (void *)current->task_state_change);
9680 __might_resched(file, line, 0);
9682 EXPORT_SYMBOL(__might_sleep);
9684 static void print_preempt_disable_ip(int preempt_offset, unsigned long ip)
9686 if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT))
9689 if (preempt_count() == preempt_offset)
9692 pr_err("Preemption disabled at:");
9693 print_ip_sym(KERN_ERR, ip);
9696 static inline bool resched_offsets_ok(unsigned int offsets)
9698 unsigned int nested = preempt_count();
9700 nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT;
9702 return nested == offsets;
9705 void __might_resched(const char *file, int line, unsigned int offsets)
9707 /* Ratelimiting timestamp: */
9708 static unsigned long prev_jiffy;
9710 unsigned long preempt_disable_ip;
9712 /* WARN_ON_ONCE() by default, no rate limit required: */
9715 if ((resched_offsets_ok(offsets) && !irqs_disabled() &&
9716 !is_idle_task(current) && !current->non_block_count) ||
9717 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
9721 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9723 prev_jiffy = jiffies;
9725 /* Save this before calling printk(), since that will clobber it: */
9726 preempt_disable_ip = get_preempt_disable_ip(current);
9728 pr_err("BUG: sleeping function called from invalid context at %s:%d\n",
9730 pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
9731 in_atomic(), irqs_disabled(), current->non_block_count,
9732 current->pid, current->comm);
9733 pr_err("preempt_count: %x, expected: %x\n", preempt_count(),
9734 offsets & MIGHT_RESCHED_PREEMPT_MASK);
9736 if (IS_ENABLED(CONFIG_PREEMPT_RCU)) {
9737 pr_err("RCU nest depth: %d, expected: %u\n",
9738 rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT);
9741 if (task_stack_end_corrupted(current))
9742 pr_emerg("Thread overran stack, or stack corrupted\n");
9744 debug_show_held_locks(current);
9745 if (irqs_disabled())
9746 print_irqtrace_events(current);
9748 print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK,
9749 preempt_disable_ip);
9752 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
9754 EXPORT_SYMBOL(__might_resched);
9756 void __cant_sleep(const char *file, int line, int preempt_offset)
9758 static unsigned long prev_jiffy;
9760 if (irqs_disabled())
9763 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
9766 if (preempt_count() > preempt_offset)
9769 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9771 prev_jiffy = jiffies;
9773 printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
9774 printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9775 in_atomic(), irqs_disabled(),
9776 current->pid, current->comm);
9778 debug_show_held_locks(current);
9780 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
9782 EXPORT_SYMBOL_GPL(__cant_sleep);
9785 void __cant_migrate(const char *file, int line)
9787 static unsigned long prev_jiffy;
9789 if (irqs_disabled())
9792 if (is_migration_disabled(current))
9795 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
9798 if (preempt_count() > 0)
9801 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9803 prev_jiffy = jiffies;
9805 pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
9806 pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
9807 in_atomic(), irqs_disabled(), is_migration_disabled(current),
9808 current->pid, current->comm);
9810 debug_show_held_locks(current);
9812 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
9814 EXPORT_SYMBOL_GPL(__cant_migrate);
9818 #ifdef CONFIG_MAGIC_SYSRQ
9819 void normalize_rt_tasks(void)
9821 struct task_struct *g, *p;
9822 struct sched_attr attr = {
9823 .sched_policy = SCHED_NORMAL,
9826 read_lock(&tasklist_lock);
9827 for_each_process_thread(g, p) {
9829 * Only normalize user tasks:
9831 if (p->flags & PF_KTHREAD)
9834 p->se.exec_start = 0;
9835 schedstat_set(p->stats.wait_start, 0);
9836 schedstat_set(p->stats.sleep_start, 0);
9837 schedstat_set(p->stats.block_start, 0);
9839 if (!dl_task(p) && !rt_task(p)) {
9841 * Renice negative nice level userspace
9844 if (task_nice(p) < 0)
9845 set_user_nice(p, 0);
9849 __sched_setscheduler(p, &attr, false, false);
9851 read_unlock(&tasklist_lock);
9854 #endif /* CONFIG_MAGIC_SYSRQ */
9856 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
9858 * These functions are only useful for the IA64 MCA handling, or kdb.
9860 * They can only be called when the whole system has been
9861 * stopped - every CPU needs to be quiescent, and no scheduling
9862 * activity can take place. Using them for anything else would
9863 * be a serious bug, and as a result, they aren't even visible
9864 * under any other configuration.
9868 * curr_task - return the current task for a given CPU.
9869 * @cpu: the processor in question.
9871 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9873 * Return: The current task for @cpu.
9875 struct task_struct *curr_task(int cpu)
9877 return cpu_curr(cpu);
9880 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
9884 * ia64_set_curr_task - set the current task for a given CPU.
9885 * @cpu: the processor in question.
9886 * @p: the task pointer to set.
9888 * Description: This function must only be used when non-maskable interrupts
9889 * are serviced on a separate stack. It allows the architecture to switch the
9890 * notion of the current task on a CPU in a non-blocking manner. This function
9891 * must be called with all CPU's synchronized, and interrupts disabled, the
9892 * and caller must save the original value of the current task (see
9893 * curr_task() above) and restore that value before reenabling interrupts and
9894 * re-starting the system.
9896 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9898 void ia64_set_curr_task(int cpu, struct task_struct *p)
9905 #ifdef CONFIG_CGROUP_SCHED
9906 /* task_group_lock serializes the addition/removal of task groups */
9907 static DEFINE_SPINLOCK(task_group_lock);
9909 static inline void alloc_uclamp_sched_group(struct task_group *tg,
9910 struct task_group *parent)
9912 #ifdef CONFIG_UCLAMP_TASK_GROUP
9913 enum uclamp_id clamp_id;
9915 for_each_clamp_id(clamp_id) {
9916 uclamp_se_set(&tg->uclamp_req[clamp_id],
9917 uclamp_none(clamp_id), false);
9918 tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
9923 static void sched_free_group(struct task_group *tg)
9925 free_fair_sched_group(tg);
9926 free_rt_sched_group(tg);
9928 kmem_cache_free(task_group_cache, tg);
9931 static void sched_free_group_rcu(struct rcu_head *rcu)
9933 sched_free_group(container_of(rcu, struct task_group, rcu));
9936 static void sched_unregister_group(struct task_group *tg)
9938 unregister_fair_sched_group(tg);
9939 unregister_rt_sched_group(tg);
9941 * We have to wait for yet another RCU grace period to expire, as
9942 * print_cfs_stats() might run concurrently.
9944 call_rcu(&tg->rcu, sched_free_group_rcu);
9947 /* allocate runqueue etc for a new task group */
9948 struct task_group *sched_create_group(struct task_group *parent)
9950 struct task_group *tg;
9952 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
9954 return ERR_PTR(-ENOMEM);
9956 if (!alloc_fair_sched_group(tg, parent))
9959 if (!alloc_rt_sched_group(tg, parent))
9962 alloc_uclamp_sched_group(tg, parent);
9967 sched_free_group(tg);
9968 return ERR_PTR(-ENOMEM);
9971 void sched_online_group(struct task_group *tg, struct task_group *parent)
9973 unsigned long flags;
9975 spin_lock_irqsave(&task_group_lock, flags);
9976 list_add_rcu(&tg->list, &task_groups);
9978 /* Root should already exist: */
9981 tg->parent = parent;
9982 INIT_LIST_HEAD(&tg->children);
9983 list_add_rcu(&tg->siblings, &parent->children);
9984 spin_unlock_irqrestore(&task_group_lock, flags);
9986 online_fair_sched_group(tg);
9989 /* rcu callback to free various structures associated with a task group */
9990 static void sched_unregister_group_rcu(struct rcu_head *rhp)
9992 /* Now it should be safe to free those cfs_rqs: */
9993 sched_unregister_group(container_of(rhp, struct task_group, rcu));
9996 void sched_destroy_group(struct task_group *tg)
9998 /* Wait for possible concurrent references to cfs_rqs complete: */
9999 call_rcu(&tg->rcu, sched_unregister_group_rcu);
10002 void sched_release_group(struct task_group *tg)
10004 unsigned long flags;
10007 * Unlink first, to avoid walk_tg_tree_from() from finding us (via
10008 * sched_cfs_period_timer()).
10010 * For this to be effective, we have to wait for all pending users of
10011 * this task group to leave their RCU critical section to ensure no new
10012 * user will see our dying task group any more. Specifically ensure
10013 * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
10015 * We therefore defer calling unregister_fair_sched_group() to
10016 * sched_unregister_group() which is guarantied to get called only after the
10017 * current RCU grace period has expired.
10019 spin_lock_irqsave(&task_group_lock, flags);
10020 list_del_rcu(&tg->list);
10021 list_del_rcu(&tg->siblings);
10022 spin_unlock_irqrestore(&task_group_lock, flags);
10025 static void sched_change_group(struct task_struct *tsk, int type)
10027 struct task_group *tg;
10030 * All callers are synchronized by task_rq_lock(); we do not use RCU
10031 * which is pointless here. Thus, we pass "true" to task_css_check()
10032 * to prevent lockdep warnings.
10034 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
10035 struct task_group, css);
10036 tg = autogroup_task_group(tsk, tg);
10037 tsk->sched_task_group = tg;
10039 #ifdef CONFIG_FAIR_GROUP_SCHED
10040 if (tsk->sched_class->task_change_group)
10041 tsk->sched_class->task_change_group(tsk, type);
10044 set_task_rq(tsk, task_cpu(tsk));
10048 * Change task's runqueue when it moves between groups.
10050 * The caller of this function should have put the task in its new group by
10051 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
10054 void sched_move_task(struct task_struct *tsk)
10056 int queued, running, queue_flags =
10057 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
10058 struct rq_flags rf;
10061 rq = task_rq_lock(tsk, &rf);
10062 update_rq_clock(rq);
10064 running = task_current(rq, tsk);
10065 queued = task_on_rq_queued(tsk);
10068 dequeue_task(rq, tsk, queue_flags);
10070 put_prev_task(rq, tsk);
10072 sched_change_group(tsk, TASK_MOVE_GROUP);
10075 enqueue_task(rq, tsk, queue_flags);
10077 set_next_task(rq, tsk);
10079 * After changing group, the running task may have joined a
10080 * throttled one but it's still the running task. Trigger a
10081 * resched to make sure that task can still run.
10086 task_rq_unlock(rq, tsk, &rf);
10089 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
10091 return css ? container_of(css, struct task_group, css) : NULL;
10094 static struct cgroup_subsys_state *
10095 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10097 struct task_group *parent = css_tg(parent_css);
10098 struct task_group *tg;
10101 /* This is early initialization for the top cgroup */
10102 return &root_task_group.css;
10105 tg = sched_create_group(parent);
10107 return ERR_PTR(-ENOMEM);
10112 /* Expose task group only after completing cgroup initialization */
10113 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
10115 struct task_group *tg = css_tg(css);
10116 struct task_group *parent = css_tg(css->parent);
10119 sched_online_group(tg, parent);
10121 #ifdef CONFIG_UCLAMP_TASK_GROUP
10122 /* Propagate the effective uclamp value for the new group */
10123 mutex_lock(&uclamp_mutex);
10125 cpu_util_update_eff(css);
10127 mutex_unlock(&uclamp_mutex);
10133 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
10135 struct task_group *tg = css_tg(css);
10137 sched_release_group(tg);
10140 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
10142 struct task_group *tg = css_tg(css);
10145 * Relies on the RCU grace period between css_released() and this.
10147 sched_unregister_group(tg);
10151 * This is called before wake_up_new_task(), therefore we really only
10152 * have to set its group bits, all the other stuff does not apply.
10154 static void cpu_cgroup_fork(struct task_struct *task)
10156 struct rq_flags rf;
10159 rq = task_rq_lock(task, &rf);
10161 update_rq_clock(rq);
10162 sched_change_group(task, TASK_SET_GROUP);
10164 task_rq_unlock(rq, task, &rf);
10167 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
10169 struct task_struct *task;
10170 struct cgroup_subsys_state *css;
10173 cgroup_taskset_for_each(task, css, tset) {
10174 #ifdef CONFIG_RT_GROUP_SCHED
10175 if (!sched_rt_can_attach(css_tg(css), task))
10179 * Serialize against wake_up_new_task() such that if it's
10180 * running, we're sure to observe its full state.
10182 raw_spin_lock_irq(&task->pi_lock);
10184 * Avoid calling sched_move_task() before wake_up_new_task()
10185 * has happened. This would lead to problems with PELT, due to
10186 * move wanting to detach+attach while we're not attached yet.
10188 if (READ_ONCE(task->__state) == TASK_NEW)
10190 raw_spin_unlock_irq(&task->pi_lock);
10198 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
10200 struct task_struct *task;
10201 struct cgroup_subsys_state *css;
10203 cgroup_taskset_for_each(task, css, tset)
10204 sched_move_task(task);
10207 #ifdef CONFIG_UCLAMP_TASK_GROUP
10208 static void cpu_util_update_eff(struct cgroup_subsys_state *css)
10210 struct cgroup_subsys_state *top_css = css;
10211 struct uclamp_se *uc_parent = NULL;
10212 struct uclamp_se *uc_se = NULL;
10213 unsigned int eff[UCLAMP_CNT];
10214 enum uclamp_id clamp_id;
10215 unsigned int clamps;
10217 lockdep_assert_held(&uclamp_mutex);
10218 SCHED_WARN_ON(!rcu_read_lock_held());
10220 css_for_each_descendant_pre(css, top_css) {
10221 uc_parent = css_tg(css)->parent
10222 ? css_tg(css)->parent->uclamp : NULL;
10224 for_each_clamp_id(clamp_id) {
10225 /* Assume effective clamps matches requested clamps */
10226 eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
10227 /* Cap effective clamps with parent's effective clamps */
10229 eff[clamp_id] > uc_parent[clamp_id].value) {
10230 eff[clamp_id] = uc_parent[clamp_id].value;
10233 /* Ensure protection is always capped by limit */
10234 eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
10236 /* Propagate most restrictive effective clamps */
10238 uc_se = css_tg(css)->uclamp;
10239 for_each_clamp_id(clamp_id) {
10240 if (eff[clamp_id] == uc_se[clamp_id].value)
10242 uc_se[clamp_id].value = eff[clamp_id];
10243 uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
10244 clamps |= (0x1 << clamp_id);
10247 css = css_rightmost_descendant(css);
10251 /* Immediately update descendants RUNNABLE tasks */
10252 uclamp_update_active_tasks(css);
10257 * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
10258 * C expression. Since there is no way to convert a macro argument (N) into a
10259 * character constant, use two levels of macros.
10261 #define _POW10(exp) ((unsigned int)1e##exp)
10262 #define POW10(exp) _POW10(exp)
10264 struct uclamp_request {
10265 #define UCLAMP_PERCENT_SHIFT 2
10266 #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
10272 static inline struct uclamp_request
10273 capacity_from_percent(char *buf)
10275 struct uclamp_request req = {
10276 .percent = UCLAMP_PERCENT_SCALE,
10277 .util = SCHED_CAPACITY_SCALE,
10282 if (strcmp(buf, "max")) {
10283 req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
10287 if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
10292 req.util = req.percent << SCHED_CAPACITY_SHIFT;
10293 req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
10299 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
10300 size_t nbytes, loff_t off,
10301 enum uclamp_id clamp_id)
10303 struct uclamp_request req;
10304 struct task_group *tg;
10306 req = capacity_from_percent(buf);
10310 static_branch_enable(&sched_uclamp_used);
10312 mutex_lock(&uclamp_mutex);
10315 tg = css_tg(of_css(of));
10316 if (tg->uclamp_req[clamp_id].value != req.util)
10317 uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
10320 * Because of not recoverable conversion rounding we keep track of the
10321 * exact requested value
10323 tg->uclamp_pct[clamp_id] = req.percent;
10325 /* Update effective clamps to track the most restrictive value */
10326 cpu_util_update_eff(of_css(of));
10329 mutex_unlock(&uclamp_mutex);
10334 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
10335 char *buf, size_t nbytes,
10338 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
10341 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
10342 char *buf, size_t nbytes,
10345 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
10348 static inline void cpu_uclamp_print(struct seq_file *sf,
10349 enum uclamp_id clamp_id)
10351 struct task_group *tg;
10357 tg = css_tg(seq_css(sf));
10358 util_clamp = tg->uclamp_req[clamp_id].value;
10361 if (util_clamp == SCHED_CAPACITY_SCALE) {
10362 seq_puts(sf, "max\n");
10366 percent = tg->uclamp_pct[clamp_id];
10367 percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
10368 seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
10371 static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
10373 cpu_uclamp_print(sf, UCLAMP_MIN);
10377 static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
10379 cpu_uclamp_print(sf, UCLAMP_MAX);
10382 #endif /* CONFIG_UCLAMP_TASK_GROUP */
10384 #ifdef CONFIG_FAIR_GROUP_SCHED
10385 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
10386 struct cftype *cftype, u64 shareval)
10388 if (shareval > scale_load_down(ULONG_MAX))
10389 shareval = MAX_SHARES;
10390 return sched_group_set_shares(css_tg(css), scale_load(shareval));
10393 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
10394 struct cftype *cft)
10396 struct task_group *tg = css_tg(css);
10398 return (u64) scale_load_down(tg->shares);
10401 #ifdef CONFIG_CFS_BANDWIDTH
10402 static DEFINE_MUTEX(cfs_constraints_mutex);
10404 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
10405 static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
10406 /* More than 203 days if BW_SHIFT equals 20. */
10407 static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
10409 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
10411 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota,
10414 int i, ret = 0, runtime_enabled, runtime_was_enabled;
10415 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
10417 if (tg == &root_task_group)
10421 * Ensure we have at some amount of bandwidth every period. This is
10422 * to prevent reaching a state of large arrears when throttled via
10423 * entity_tick() resulting in prolonged exit starvation.
10425 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
10429 * Likewise, bound things on the other side by preventing insane quota
10430 * periods. This also allows us to normalize in computing quota
10433 if (period > max_cfs_quota_period)
10437 * Bound quota to defend quota against overflow during bandwidth shift.
10439 if (quota != RUNTIME_INF && quota > max_cfs_runtime)
10442 if (quota != RUNTIME_INF && (burst > quota ||
10443 burst + quota > max_cfs_runtime))
10447 * Prevent race between setting of cfs_rq->runtime_enabled and
10448 * unthrottle_offline_cfs_rqs().
10451 mutex_lock(&cfs_constraints_mutex);
10452 ret = __cfs_schedulable(tg, period, quota);
10456 runtime_enabled = quota != RUNTIME_INF;
10457 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
10459 * If we need to toggle cfs_bandwidth_used, off->on must occur
10460 * before making related changes, and on->off must occur afterwards
10462 if (runtime_enabled && !runtime_was_enabled)
10463 cfs_bandwidth_usage_inc();
10464 raw_spin_lock_irq(&cfs_b->lock);
10465 cfs_b->period = ns_to_ktime(period);
10466 cfs_b->quota = quota;
10467 cfs_b->burst = burst;
10469 __refill_cfs_bandwidth_runtime(cfs_b);
10471 /* Restart the period timer (if active) to handle new period expiry: */
10472 if (runtime_enabled)
10473 start_cfs_bandwidth(cfs_b);
10475 raw_spin_unlock_irq(&cfs_b->lock);
10477 for_each_online_cpu(i) {
10478 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
10479 struct rq *rq = cfs_rq->rq;
10480 struct rq_flags rf;
10482 rq_lock_irq(rq, &rf);
10483 cfs_rq->runtime_enabled = runtime_enabled;
10484 cfs_rq->runtime_remaining = 0;
10486 if (cfs_rq->throttled)
10487 unthrottle_cfs_rq(cfs_rq);
10488 rq_unlock_irq(rq, &rf);
10490 if (runtime_was_enabled && !runtime_enabled)
10491 cfs_bandwidth_usage_dec();
10493 mutex_unlock(&cfs_constraints_mutex);
10494 cpus_read_unlock();
10499 static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
10501 u64 quota, period, burst;
10503 period = ktime_to_ns(tg->cfs_bandwidth.period);
10504 burst = tg->cfs_bandwidth.burst;
10505 if (cfs_quota_us < 0)
10506 quota = RUNTIME_INF;
10507 else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
10508 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
10512 return tg_set_cfs_bandwidth(tg, period, quota, burst);
10515 static long tg_get_cfs_quota(struct task_group *tg)
10519 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
10522 quota_us = tg->cfs_bandwidth.quota;
10523 do_div(quota_us, NSEC_PER_USEC);
10528 static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
10530 u64 quota, period, burst;
10532 if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
10535 period = (u64)cfs_period_us * NSEC_PER_USEC;
10536 quota = tg->cfs_bandwidth.quota;
10537 burst = tg->cfs_bandwidth.burst;
10539 return tg_set_cfs_bandwidth(tg, period, quota, burst);
10542 static long tg_get_cfs_period(struct task_group *tg)
10546 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
10547 do_div(cfs_period_us, NSEC_PER_USEC);
10549 return cfs_period_us;
10552 static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us)
10554 u64 quota, period, burst;
10556 if ((u64)cfs_burst_us > U64_MAX / NSEC_PER_USEC)
10559 burst = (u64)cfs_burst_us * NSEC_PER_USEC;
10560 period = ktime_to_ns(tg->cfs_bandwidth.period);
10561 quota = tg->cfs_bandwidth.quota;
10563 return tg_set_cfs_bandwidth(tg, period, quota, burst);
10566 static long tg_get_cfs_burst(struct task_group *tg)
10570 burst_us = tg->cfs_bandwidth.burst;
10571 do_div(burst_us, NSEC_PER_USEC);
10576 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
10577 struct cftype *cft)
10579 return tg_get_cfs_quota(css_tg(css));
10582 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
10583 struct cftype *cftype, s64 cfs_quota_us)
10585 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
10588 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
10589 struct cftype *cft)
10591 return tg_get_cfs_period(css_tg(css));
10594 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
10595 struct cftype *cftype, u64 cfs_period_us)
10597 return tg_set_cfs_period(css_tg(css), cfs_period_us);
10600 static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css,
10601 struct cftype *cft)
10603 return tg_get_cfs_burst(css_tg(css));
10606 static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css,
10607 struct cftype *cftype, u64 cfs_burst_us)
10609 return tg_set_cfs_burst(css_tg(css), cfs_burst_us);
10612 struct cfs_schedulable_data {
10613 struct task_group *tg;
10618 * normalize group quota/period to be quota/max_period
10619 * note: units are usecs
10621 static u64 normalize_cfs_quota(struct task_group *tg,
10622 struct cfs_schedulable_data *d)
10627 period = d->period;
10630 period = tg_get_cfs_period(tg);
10631 quota = tg_get_cfs_quota(tg);
10634 /* note: these should typically be equivalent */
10635 if (quota == RUNTIME_INF || quota == -1)
10636 return RUNTIME_INF;
10638 return to_ratio(period, quota);
10641 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
10643 struct cfs_schedulable_data *d = data;
10644 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
10645 s64 quota = 0, parent_quota = -1;
10648 quota = RUNTIME_INF;
10650 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
10652 quota = normalize_cfs_quota(tg, d);
10653 parent_quota = parent_b->hierarchical_quota;
10656 * Ensure max(child_quota) <= parent_quota. On cgroup2,
10657 * always take the min. On cgroup1, only inherit when no
10660 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
10661 quota = min(quota, parent_quota);
10663 if (quota == RUNTIME_INF)
10664 quota = parent_quota;
10665 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
10669 cfs_b->hierarchical_quota = quota;
10674 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
10677 struct cfs_schedulable_data data = {
10683 if (quota != RUNTIME_INF) {
10684 do_div(data.period, NSEC_PER_USEC);
10685 do_div(data.quota, NSEC_PER_USEC);
10689 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
10695 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
10697 struct task_group *tg = css_tg(seq_css(sf));
10698 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
10700 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
10701 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
10702 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
10704 if (schedstat_enabled() && tg != &root_task_group) {
10705 struct sched_statistics *stats;
10709 for_each_possible_cpu(i) {
10710 stats = __schedstats_from_se(tg->se[i]);
10711 ws += schedstat_val(stats->wait_sum);
10714 seq_printf(sf, "wait_sum %llu\n", ws);
10717 seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst);
10718 seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time);
10722 #endif /* CONFIG_CFS_BANDWIDTH */
10723 #endif /* CONFIG_FAIR_GROUP_SCHED */
10725 #ifdef CONFIG_RT_GROUP_SCHED
10726 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
10727 struct cftype *cft, s64 val)
10729 return sched_group_set_rt_runtime(css_tg(css), val);
10732 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
10733 struct cftype *cft)
10735 return sched_group_rt_runtime(css_tg(css));
10738 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
10739 struct cftype *cftype, u64 rt_period_us)
10741 return sched_group_set_rt_period(css_tg(css), rt_period_us);
10744 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
10745 struct cftype *cft)
10747 return sched_group_rt_period(css_tg(css));
10749 #endif /* CONFIG_RT_GROUP_SCHED */
10751 #ifdef CONFIG_FAIR_GROUP_SCHED
10752 static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css,
10753 struct cftype *cft)
10755 return css_tg(css)->idle;
10758 static int cpu_idle_write_s64(struct cgroup_subsys_state *css,
10759 struct cftype *cft, s64 idle)
10761 return sched_group_set_idle(css_tg(css), idle);
10765 static struct cftype cpu_legacy_files[] = {
10766 #ifdef CONFIG_FAIR_GROUP_SCHED
10769 .read_u64 = cpu_shares_read_u64,
10770 .write_u64 = cpu_shares_write_u64,
10774 .read_s64 = cpu_idle_read_s64,
10775 .write_s64 = cpu_idle_write_s64,
10778 #ifdef CONFIG_CFS_BANDWIDTH
10780 .name = "cfs_quota_us",
10781 .read_s64 = cpu_cfs_quota_read_s64,
10782 .write_s64 = cpu_cfs_quota_write_s64,
10785 .name = "cfs_period_us",
10786 .read_u64 = cpu_cfs_period_read_u64,
10787 .write_u64 = cpu_cfs_period_write_u64,
10790 .name = "cfs_burst_us",
10791 .read_u64 = cpu_cfs_burst_read_u64,
10792 .write_u64 = cpu_cfs_burst_write_u64,
10796 .seq_show = cpu_cfs_stat_show,
10799 #ifdef CONFIG_RT_GROUP_SCHED
10801 .name = "rt_runtime_us",
10802 .read_s64 = cpu_rt_runtime_read,
10803 .write_s64 = cpu_rt_runtime_write,
10806 .name = "rt_period_us",
10807 .read_u64 = cpu_rt_period_read_uint,
10808 .write_u64 = cpu_rt_period_write_uint,
10811 #ifdef CONFIG_UCLAMP_TASK_GROUP
10813 .name = "uclamp.min",
10814 .flags = CFTYPE_NOT_ON_ROOT,
10815 .seq_show = cpu_uclamp_min_show,
10816 .write = cpu_uclamp_min_write,
10819 .name = "uclamp.max",
10820 .flags = CFTYPE_NOT_ON_ROOT,
10821 .seq_show = cpu_uclamp_max_show,
10822 .write = cpu_uclamp_max_write,
10825 { } /* Terminate */
10828 static int cpu_extra_stat_show(struct seq_file *sf,
10829 struct cgroup_subsys_state *css)
10831 #ifdef CONFIG_CFS_BANDWIDTH
10833 struct task_group *tg = css_tg(css);
10834 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
10835 u64 throttled_usec, burst_usec;
10837 throttled_usec = cfs_b->throttled_time;
10838 do_div(throttled_usec, NSEC_PER_USEC);
10839 burst_usec = cfs_b->burst_time;
10840 do_div(burst_usec, NSEC_PER_USEC);
10842 seq_printf(sf, "nr_periods %d\n"
10843 "nr_throttled %d\n"
10844 "throttled_usec %llu\n"
10846 "burst_usec %llu\n",
10847 cfs_b->nr_periods, cfs_b->nr_throttled,
10848 throttled_usec, cfs_b->nr_burst, burst_usec);
10854 #ifdef CONFIG_FAIR_GROUP_SCHED
10855 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
10856 struct cftype *cft)
10858 struct task_group *tg = css_tg(css);
10859 u64 weight = scale_load_down(tg->shares);
10861 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
10864 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
10865 struct cftype *cft, u64 weight)
10868 * cgroup weight knobs should use the common MIN, DFL and MAX
10869 * values which are 1, 100 and 10000 respectively. While it loses
10870 * a bit of range on both ends, it maps pretty well onto the shares
10871 * value used by scheduler and the round-trip conversions preserve
10872 * the original value over the entire range.
10874 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
10877 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
10879 return sched_group_set_shares(css_tg(css), scale_load(weight));
10882 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
10883 struct cftype *cft)
10885 unsigned long weight = scale_load_down(css_tg(css)->shares);
10886 int last_delta = INT_MAX;
10889 /* find the closest nice value to the current weight */
10890 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
10891 delta = abs(sched_prio_to_weight[prio] - weight);
10892 if (delta >= last_delta)
10894 last_delta = delta;
10897 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
10900 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
10901 struct cftype *cft, s64 nice)
10903 unsigned long weight;
10906 if (nice < MIN_NICE || nice > MAX_NICE)
10909 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
10910 idx = array_index_nospec(idx, 40);
10911 weight = sched_prio_to_weight[idx];
10913 return sched_group_set_shares(css_tg(css), scale_load(weight));
10917 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
10918 long period, long quota)
10921 seq_puts(sf, "max");
10923 seq_printf(sf, "%ld", quota);
10925 seq_printf(sf, " %ld\n", period);
10928 /* caller should put the current value in *@periodp before calling */
10929 static int __maybe_unused cpu_period_quota_parse(char *buf,
10930 u64 *periodp, u64 *quotap)
10932 char tok[21]; /* U64_MAX */
10934 if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
10937 *periodp *= NSEC_PER_USEC;
10939 if (sscanf(tok, "%llu", quotap))
10940 *quotap *= NSEC_PER_USEC;
10941 else if (!strcmp(tok, "max"))
10942 *quotap = RUNTIME_INF;
10949 #ifdef CONFIG_CFS_BANDWIDTH
10950 static int cpu_max_show(struct seq_file *sf, void *v)
10952 struct task_group *tg = css_tg(seq_css(sf));
10954 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
10958 static ssize_t cpu_max_write(struct kernfs_open_file *of,
10959 char *buf, size_t nbytes, loff_t off)
10961 struct task_group *tg = css_tg(of_css(of));
10962 u64 period = tg_get_cfs_period(tg);
10963 u64 burst = tg_get_cfs_burst(tg);
10967 ret = cpu_period_quota_parse(buf, &period, "a);
10969 ret = tg_set_cfs_bandwidth(tg, period, quota, burst);
10970 return ret ?: nbytes;
10974 static struct cftype cpu_files[] = {
10975 #ifdef CONFIG_FAIR_GROUP_SCHED
10978 .flags = CFTYPE_NOT_ON_ROOT,
10979 .read_u64 = cpu_weight_read_u64,
10980 .write_u64 = cpu_weight_write_u64,
10983 .name = "weight.nice",
10984 .flags = CFTYPE_NOT_ON_ROOT,
10985 .read_s64 = cpu_weight_nice_read_s64,
10986 .write_s64 = cpu_weight_nice_write_s64,
10990 .flags = CFTYPE_NOT_ON_ROOT,
10991 .read_s64 = cpu_idle_read_s64,
10992 .write_s64 = cpu_idle_write_s64,
10995 #ifdef CONFIG_CFS_BANDWIDTH
10998 .flags = CFTYPE_NOT_ON_ROOT,
10999 .seq_show = cpu_max_show,
11000 .write = cpu_max_write,
11003 .name = "max.burst",
11004 .flags = CFTYPE_NOT_ON_ROOT,
11005 .read_u64 = cpu_cfs_burst_read_u64,
11006 .write_u64 = cpu_cfs_burst_write_u64,
11009 #ifdef CONFIG_UCLAMP_TASK_GROUP
11011 .name = "uclamp.min",
11012 .flags = CFTYPE_NOT_ON_ROOT,
11013 .seq_show = cpu_uclamp_min_show,
11014 .write = cpu_uclamp_min_write,
11017 .name = "uclamp.max",
11018 .flags = CFTYPE_NOT_ON_ROOT,
11019 .seq_show = cpu_uclamp_max_show,
11020 .write = cpu_uclamp_max_write,
11023 { } /* terminate */
11026 struct cgroup_subsys cpu_cgrp_subsys = {
11027 .css_alloc = cpu_cgroup_css_alloc,
11028 .css_online = cpu_cgroup_css_online,
11029 .css_released = cpu_cgroup_css_released,
11030 .css_free = cpu_cgroup_css_free,
11031 .css_extra_stat_show = cpu_extra_stat_show,
11032 .fork = cpu_cgroup_fork,
11033 .can_attach = cpu_cgroup_can_attach,
11034 .attach = cpu_cgroup_attach,
11035 .legacy_cftypes = cpu_legacy_files,
11036 .dfl_cftypes = cpu_files,
11037 .early_init = true,
11041 #endif /* CONFIG_CGROUP_SCHED */
11043 void dump_cpu_task(int cpu)
11045 pr_info("Task dump for CPU %d:\n", cpu);
11046 sched_show_task(cpu_curr(cpu));
11050 * Nice levels are multiplicative, with a gentle 10% change for every
11051 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
11052 * nice 1, it will get ~10% less CPU time than another CPU-bound task
11053 * that remained on nice 0.
11055 * The "10% effect" is relative and cumulative: from _any_ nice level,
11056 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
11057 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
11058 * If a task goes up by ~10% and another task goes down by ~10% then
11059 * the relative distance between them is ~25%.)
11061 const int sched_prio_to_weight[40] = {
11062 /* -20 */ 88761, 71755, 56483, 46273, 36291,
11063 /* -15 */ 29154, 23254, 18705, 14949, 11916,
11064 /* -10 */ 9548, 7620, 6100, 4904, 3906,
11065 /* -5 */ 3121, 2501, 1991, 1586, 1277,
11066 /* 0 */ 1024, 820, 655, 526, 423,
11067 /* 5 */ 335, 272, 215, 172, 137,
11068 /* 10 */ 110, 87, 70, 56, 45,
11069 /* 15 */ 36, 29, 23, 18, 15,
11073 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
11075 * In cases where the weight does not change often, we can use the
11076 * precalculated inverse to speed up arithmetics by turning divisions
11077 * into multiplications:
11079 const u32 sched_prio_to_wmult[40] = {
11080 /* -20 */ 48388, 59856, 76040, 92818, 118348,
11081 /* -15 */ 147320, 184698, 229616, 287308, 360437,
11082 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
11083 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
11084 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
11085 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
11086 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
11087 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
11090 void call_trace_sched_update_nr_running(struct rq *rq, int count)
11092 trace_sched_update_nr_running_tp(rq, count);