1 // SPDX-License-Identifier: GPL-2.0-only
5 * Core kernel scheduler code and related syscalls
7 * Copyright (C) 1991-2002 Linus Torvalds
9 #define CREATE_TRACE_POINTS
10 #include <trace/events/sched.h>
11 #undef CREATE_TRACE_POINTS
15 #include <linux/nospec.h>
17 #include <linux/kcov.h>
18 #include <linux/scs.h>
20 #include <asm/switch_to.h>
23 #include "../workqueue_internal.h"
24 #include "../../fs/io-wq.h"
25 #include "../smpboot.h"
31 * Export tracepoints that act as a bare tracehook (ie: have no trace event
32 * associated with them) to allow external modules to probe them.
34 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp
);
35 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp
);
36 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp
);
37 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp
);
38 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp
);
39 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_thermal_tp
);
40 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp
);
41 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp
);
42 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp
);
43 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp
);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp
);
46 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
48 #ifdef CONFIG_SCHED_DEBUG
50 * Debugging: various feature bits
52 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
53 * sysctl_sched_features, defined in sched.h, to allow constants propagation
54 * at compile time and compiler optimization based on features default.
56 #define SCHED_FEAT(name, enabled) \
57 (1UL << __SCHED_FEAT_##name) * enabled |
58 const_debug
unsigned int sysctl_sched_features
=
64 * Print a warning if need_resched is set for the given duration (if
65 * LATENCY_WARN is enabled).
67 * If sysctl_resched_latency_warn_once is set, only one warning will be shown
70 __read_mostly
int sysctl_resched_latency_warn_ms
= 100;
71 __read_mostly
int sysctl_resched_latency_warn_once
= 1;
72 #endif /* CONFIG_SCHED_DEBUG */
75 * Number of tasks to iterate in a single balance run.
76 * Limited because this is done with IRQs disabled.
78 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
81 * period over which we measure -rt task CPU usage in us.
84 unsigned int sysctl_sched_rt_period
= 1000000;
86 __read_mostly
int scheduler_running
;
88 #ifdef CONFIG_SCHED_CORE
90 DEFINE_STATIC_KEY_FALSE(__sched_core_enabled
);
92 /* kernel prio, less is more */
93 static inline int __task_prio(struct task_struct
*p
)
95 if (p
->sched_class
== &stop_sched_class
) /* trumps deadline */
98 if (rt_prio(p
->prio
)) /* includes deadline */
99 return p
->prio
; /* [-1, 99] */
101 if (p
->sched_class
== &idle_sched_class
)
102 return MAX_RT_PRIO
+ NICE_WIDTH
; /* 140 */
104 return MAX_RT_PRIO
+ MAX_NICE
; /* 120, squash fair */
114 /* real prio, less is less */
115 static inline bool prio_less(struct task_struct
*a
, struct task_struct
*b
, bool in_fi
)
118 int pa
= __task_prio(a
), pb
= __task_prio(b
);
126 if (pa
== -1) /* dl_prio() doesn't work because of stop_class above */
127 return !dl_time_before(a
->dl
.deadline
, b
->dl
.deadline
);
129 if (pa
== MAX_RT_PRIO
+ MAX_NICE
) /* fair */
130 return cfs_prio_less(a
, b
, in_fi
);
135 static inline bool __sched_core_less(struct task_struct
*a
, struct task_struct
*b
)
137 if (a
->core_cookie
< b
->core_cookie
)
140 if (a
->core_cookie
> b
->core_cookie
)
143 /* flip prio, so high prio is leftmost */
144 if (prio_less(b
, a
, task_rq(a
)->core
->core_forceidle
))
150 #define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
152 static inline bool rb_sched_core_less(struct rb_node
*a
, const struct rb_node
*b
)
154 return __sched_core_less(__node_2_sc(a
), __node_2_sc(b
));
157 static inline int rb_sched_core_cmp(const void *key
, const struct rb_node
*node
)
159 const struct task_struct
*p
= __node_2_sc(node
);
160 unsigned long cookie
= (unsigned long)key
;
162 if (cookie
< p
->core_cookie
)
165 if (cookie
> p
->core_cookie
)
171 void sched_core_enqueue(struct rq
*rq
, struct task_struct
*p
)
173 rq
->core
->core_task_seq
++;
178 rb_add(&p
->core_node
, &rq
->core_tree
, rb_sched_core_less
);
181 void sched_core_dequeue(struct rq
*rq
, struct task_struct
*p
)
183 rq
->core
->core_task_seq
++;
185 if (!sched_core_enqueued(p
))
188 rb_erase(&p
->core_node
, &rq
->core_tree
);
189 RB_CLEAR_NODE(&p
->core_node
);
193 * Find left-most (aka, highest priority) task matching @cookie.
195 static struct task_struct
*sched_core_find(struct rq
*rq
, unsigned long cookie
)
197 struct rb_node
*node
;
199 node
= rb_find_first((void *)cookie
, &rq
->core_tree
, rb_sched_core_cmp
);
201 * The idle task always matches any cookie!
204 return idle_sched_class
.pick_task(rq
);
206 return __node_2_sc(node
);
209 static struct task_struct
*sched_core_next(struct task_struct
*p
, unsigned long cookie
)
211 struct rb_node
*node
= &p
->core_node
;
213 node
= rb_next(node
);
217 p
= container_of(node
, struct task_struct
, core_node
);
218 if (p
->core_cookie
!= cookie
)
225 * Magic required such that:
227 * raw_spin_rq_lock(rq);
229 * raw_spin_rq_unlock(rq);
231 * ends up locking and unlocking the _same_ lock, and all CPUs
232 * always agree on what rq has what lock.
234 * XXX entirely possible to selectively enable cores, don't bother for now.
237 static DEFINE_MUTEX(sched_core_mutex
);
238 static atomic_t sched_core_count
;
239 static struct cpumask sched_core_mask
;
241 static void sched_core_lock(int cpu
, unsigned long *flags
)
243 const struct cpumask
*smt_mask
= cpu_smt_mask(cpu
);
246 local_irq_save(*flags
);
247 for_each_cpu(t
, smt_mask
)
248 raw_spin_lock_nested(&cpu_rq(t
)->__lock
, i
++);
251 static void sched_core_unlock(int cpu
, unsigned long *flags
)
253 const struct cpumask
*smt_mask
= cpu_smt_mask(cpu
);
256 for_each_cpu(t
, smt_mask
)
257 raw_spin_unlock(&cpu_rq(t
)->__lock
);
258 local_irq_restore(*flags
);
261 static void __sched_core_flip(bool enabled
)
269 * Toggle the online cores, one by one.
271 cpumask_copy(&sched_core_mask
, cpu_online_mask
);
272 for_each_cpu(cpu
, &sched_core_mask
) {
273 const struct cpumask
*smt_mask
= cpu_smt_mask(cpu
);
275 sched_core_lock(cpu
, &flags
);
277 for_each_cpu(t
, smt_mask
)
278 cpu_rq(t
)->core_enabled
= enabled
;
280 sched_core_unlock(cpu
, &flags
);
282 cpumask_andnot(&sched_core_mask
, &sched_core_mask
, smt_mask
);
286 * Toggle the offline CPUs.
288 cpumask_copy(&sched_core_mask
, cpu_possible_mask
);
289 cpumask_andnot(&sched_core_mask
, &sched_core_mask
, cpu_online_mask
);
291 for_each_cpu(cpu
, &sched_core_mask
)
292 cpu_rq(cpu
)->core_enabled
= enabled
;
297 static void sched_core_assert_empty(void)
301 for_each_possible_cpu(cpu
)
302 WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu
)->core_tree
));
305 static void __sched_core_enable(void)
307 static_branch_enable(&__sched_core_enabled
);
309 * Ensure all previous instances of raw_spin_rq_*lock() have finished
310 * and future ones will observe !sched_core_disabled().
313 __sched_core_flip(true);
314 sched_core_assert_empty();
317 static void __sched_core_disable(void)
319 sched_core_assert_empty();
320 __sched_core_flip(false);
321 static_branch_disable(&__sched_core_enabled
);
324 void sched_core_get(void)
326 if (atomic_inc_not_zero(&sched_core_count
))
329 mutex_lock(&sched_core_mutex
);
330 if (!atomic_read(&sched_core_count
))
331 __sched_core_enable();
333 smp_mb__before_atomic();
334 atomic_inc(&sched_core_count
);
335 mutex_unlock(&sched_core_mutex
);
338 static void __sched_core_put(struct work_struct
*work
)
340 if (atomic_dec_and_mutex_lock(&sched_core_count
, &sched_core_mutex
)) {
341 __sched_core_disable();
342 mutex_unlock(&sched_core_mutex
);
346 void sched_core_put(void)
348 static DECLARE_WORK(_work
, __sched_core_put
);
351 * "There can be only one"
353 * Either this is the last one, or we don't actually need to do any
354 * 'work'. If it is the last *again*, we rely on
355 * WORK_STRUCT_PENDING_BIT.
357 if (!atomic_add_unless(&sched_core_count
, -1, 1))
358 schedule_work(&_work
);
361 #else /* !CONFIG_SCHED_CORE */
363 static inline void sched_core_enqueue(struct rq
*rq
, struct task_struct
*p
) { }
364 static inline void sched_core_dequeue(struct rq
*rq
, struct task_struct
*p
) { }
366 #endif /* CONFIG_SCHED_CORE */
369 * part of the period that we allow rt tasks to run in us.
372 int sysctl_sched_rt_runtime
= 950000;
376 * Serialization rules:
382 * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
385 * rq2->lock where: rq1 < rq2
389 * Normal scheduling state is serialized by rq->lock. __schedule() takes the
390 * local CPU's rq->lock, it optionally removes the task from the runqueue and
391 * always looks at the local rq data structures to find the most eligible task
394 * Task enqueue is also under rq->lock, possibly taken from another CPU.
395 * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
396 * the local CPU to avoid bouncing the runqueue state around [ see
397 * ttwu_queue_wakelist() ]
399 * Task wakeup, specifically wakeups that involve migration, are horribly
400 * complicated to avoid having to take two rq->locks.
404 * System-calls and anything external will use task_rq_lock() which acquires
405 * both p->pi_lock and rq->lock. As a consequence the state they change is
406 * stable while holding either lock:
408 * - sched_setaffinity()/
409 * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
410 * - set_user_nice(): p->se.load, p->*prio
411 * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
412 * p->se.load, p->rt_priority,
413 * p->dl.dl_{runtime, deadline, period, flags, bw, density}
414 * - sched_setnuma(): p->numa_preferred_nid
415 * - sched_move_task()/
416 * cpu_cgroup_fork(): p->sched_task_group
417 * - uclamp_update_active() p->uclamp*
419 * p->state <- TASK_*:
421 * is changed locklessly using set_current_state(), __set_current_state() or
422 * set_special_state(), see their respective comments, or by
423 * try_to_wake_up(). This latter uses p->pi_lock to serialize against
426 * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
428 * is set by activate_task() and cleared by deactivate_task(), under
429 * rq->lock. Non-zero indicates the task is runnable, the special
430 * ON_RQ_MIGRATING state is used for migration without holding both
431 * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
433 * p->on_cpu <- { 0, 1 }:
435 * is set by prepare_task() and cleared by finish_task() such that it will be
436 * set before p is scheduled-in and cleared after p is scheduled-out, both
437 * under rq->lock. Non-zero indicates the task is running on its CPU.
439 * [ The astute reader will observe that it is possible for two tasks on one
440 * CPU to have ->on_cpu = 1 at the same time. ]
442 * task_cpu(p): is changed by set_task_cpu(), the rules are:
444 * - Don't call set_task_cpu() on a blocked task:
446 * We don't care what CPU we're not running on, this simplifies hotplug,
447 * the CPU assignment of blocked tasks isn't required to be valid.
449 * - for try_to_wake_up(), called under p->pi_lock:
451 * This allows try_to_wake_up() to only take one rq->lock, see its comment.
453 * - for migration called under rq->lock:
454 * [ see task_on_rq_migrating() in task_rq_lock() ]
456 * o move_queued_task()
459 * - for migration called under double_rq_lock():
461 * o __migrate_swap_task()
462 * o push_rt_task() / pull_rt_task()
463 * o push_dl_task() / pull_dl_task()
464 * o dl_task_offline_migration()
468 void raw_spin_rq_lock_nested(struct rq
*rq
, int subclass
)
470 raw_spinlock_t
*lock
;
472 /* Matches synchronize_rcu() in __sched_core_enable() */
474 if (sched_core_disabled()) {
475 raw_spin_lock_nested(&rq
->__lock
, subclass
);
476 /* preempt_count *MUST* be > 1 */
477 preempt_enable_no_resched();
482 lock
= __rq_lockp(rq
);
483 raw_spin_lock_nested(lock
, subclass
);
484 if (likely(lock
== __rq_lockp(rq
))) {
485 /* preempt_count *MUST* be > 1 */
486 preempt_enable_no_resched();
489 raw_spin_unlock(lock
);
493 bool raw_spin_rq_trylock(struct rq
*rq
)
495 raw_spinlock_t
*lock
;
498 /* Matches synchronize_rcu() in __sched_core_enable() */
500 if (sched_core_disabled()) {
501 ret
= raw_spin_trylock(&rq
->__lock
);
507 lock
= __rq_lockp(rq
);
508 ret
= raw_spin_trylock(lock
);
509 if (!ret
|| (likely(lock
== __rq_lockp(rq
)))) {
513 raw_spin_unlock(lock
);
517 void raw_spin_rq_unlock(struct rq
*rq
)
519 raw_spin_unlock(rq_lockp(rq
));
524 * double_rq_lock - safely lock two runqueues
526 void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
528 lockdep_assert_irqs_disabled();
530 if (rq_order_less(rq2
, rq1
))
533 raw_spin_rq_lock(rq1
);
534 if (__rq_lockp(rq1
) == __rq_lockp(rq2
))
537 raw_spin_rq_lock_nested(rq2
, SINGLE_DEPTH_NESTING
);
542 * __task_rq_lock - lock the rq @p resides on.
544 struct rq
*__task_rq_lock(struct task_struct
*p
, struct rq_flags
*rf
)
549 lockdep_assert_held(&p
->pi_lock
);
553 raw_spin_rq_lock(rq
);
554 if (likely(rq
== task_rq(p
) && !task_on_rq_migrating(p
))) {
558 raw_spin_rq_unlock(rq
);
560 while (unlikely(task_on_rq_migrating(p
)))
566 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
568 struct rq
*task_rq_lock(struct task_struct
*p
, struct rq_flags
*rf
)
569 __acquires(p
->pi_lock
)
575 raw_spin_lock_irqsave(&p
->pi_lock
, rf
->flags
);
577 raw_spin_rq_lock(rq
);
579 * move_queued_task() task_rq_lock()
582 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
583 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
584 * [S] ->cpu = new_cpu [L] task_rq()
588 * If we observe the old CPU in task_rq_lock(), the acquire of
589 * the old rq->lock will fully serialize against the stores.
591 * If we observe the new CPU in task_rq_lock(), the address
592 * dependency headed by '[L] rq = task_rq()' and the acquire
593 * will pair with the WMB to ensure we then also see migrating.
595 if (likely(rq
== task_rq(p
) && !task_on_rq_migrating(p
))) {
599 raw_spin_rq_unlock(rq
);
600 raw_spin_unlock_irqrestore(&p
->pi_lock
, rf
->flags
);
602 while (unlikely(task_on_rq_migrating(p
)))
608 * RQ-clock updating methods:
611 static void update_rq_clock_task(struct rq
*rq
, s64 delta
)
614 * In theory, the compile should just see 0 here, and optimize out the call
615 * to sched_rt_avg_update. But I don't trust it...
617 s64 __maybe_unused steal
= 0, irq_delta
= 0;
619 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
620 irq_delta
= irq_time_read(cpu_of(rq
)) - rq
->prev_irq_time
;
623 * Since irq_time is only updated on {soft,}irq_exit, we might run into
624 * this case when a previous update_rq_clock() happened inside a
627 * When this happens, we stop ->clock_task and only update the
628 * prev_irq_time stamp to account for the part that fit, so that a next
629 * update will consume the rest. This ensures ->clock_task is
632 * It does however cause some slight miss-attribution of {soft,}irq
633 * time, a more accurate solution would be to update the irq_time using
634 * the current rq->clock timestamp, except that would require using
637 if (irq_delta
> delta
)
640 rq
->prev_irq_time
+= irq_delta
;
643 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
644 if (static_key_false((¶virt_steal_rq_enabled
))) {
645 steal
= paravirt_steal_clock(cpu_of(rq
));
646 steal
-= rq
->prev_steal_time_rq
;
648 if (unlikely(steal
> delta
))
651 rq
->prev_steal_time_rq
+= steal
;
656 rq
->clock_task
+= delta
;
658 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
659 if ((irq_delta
+ steal
) && sched_feat(NONTASK_CAPACITY
))
660 update_irq_load_avg(rq
, irq_delta
+ steal
);
662 update_rq_clock_pelt(rq
, delta
);
665 void update_rq_clock(struct rq
*rq
)
669 lockdep_assert_rq_held(rq
);
671 if (rq
->clock_update_flags
& RQCF_ACT_SKIP
)
674 #ifdef CONFIG_SCHED_DEBUG
675 if (sched_feat(WARN_DOUBLE_CLOCK
))
676 SCHED_WARN_ON(rq
->clock_update_flags
& RQCF_UPDATED
);
677 rq
->clock_update_flags
|= RQCF_UPDATED
;
680 delta
= sched_clock_cpu(cpu_of(rq
)) - rq
->clock
;
684 update_rq_clock_task(rq
, delta
);
687 #ifdef CONFIG_SCHED_HRTICK
689 * Use HR-timers to deliver accurate preemption points.
692 static void hrtick_clear(struct rq
*rq
)
694 if (hrtimer_active(&rq
->hrtick_timer
))
695 hrtimer_cancel(&rq
->hrtick_timer
);
699 * High-resolution timer tick.
700 * Runs from hardirq context with interrupts disabled.
702 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
704 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
707 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
711 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
714 return HRTIMER_NORESTART
;
719 static void __hrtick_restart(struct rq
*rq
)
721 struct hrtimer
*timer
= &rq
->hrtick_timer
;
722 ktime_t time
= rq
->hrtick_time
;
724 hrtimer_start(timer
, time
, HRTIMER_MODE_ABS_PINNED_HARD
);
728 * called from hardirq (IPI) context
730 static void __hrtick_start(void *arg
)
736 __hrtick_restart(rq
);
741 * Called to set the hrtick timer state.
743 * called with rq->lock held and irqs disabled
745 void hrtick_start(struct rq
*rq
, u64 delay
)
747 struct hrtimer
*timer
= &rq
->hrtick_timer
;
751 * Don't schedule slices shorter than 10000ns, that just
752 * doesn't make sense and can cause timer DoS.
754 delta
= max_t(s64
, delay
, 10000LL);
755 rq
->hrtick_time
= ktime_add_ns(timer
->base
->get_time(), delta
);
758 __hrtick_restart(rq
);
760 smp_call_function_single_async(cpu_of(rq
), &rq
->hrtick_csd
);
765 * Called to set the hrtick timer state.
767 * called with rq->lock held and irqs disabled
769 void hrtick_start(struct rq
*rq
, u64 delay
)
772 * Don't schedule slices shorter than 10000ns, that just
773 * doesn't make sense. Rely on vruntime for fairness.
775 delay
= max_t(u64
, delay
, 10000LL);
776 hrtimer_start(&rq
->hrtick_timer
, ns_to_ktime(delay
),
777 HRTIMER_MODE_REL_PINNED_HARD
);
780 #endif /* CONFIG_SMP */
782 static void hrtick_rq_init(struct rq
*rq
)
785 INIT_CSD(&rq
->hrtick_csd
, __hrtick_start
, rq
);
787 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL_HARD
);
788 rq
->hrtick_timer
.function
= hrtick
;
790 #else /* CONFIG_SCHED_HRTICK */
791 static inline void hrtick_clear(struct rq
*rq
)
795 static inline void hrtick_rq_init(struct rq
*rq
)
798 #endif /* CONFIG_SCHED_HRTICK */
801 * cmpxchg based fetch_or, macro so it works for different integer types
803 #define fetch_or(ptr, mask) \
805 typeof(ptr) _ptr = (ptr); \
806 typeof(mask) _mask = (mask); \
807 typeof(*_ptr) _old, _val = *_ptr; \
810 _old = cmpxchg(_ptr, _val, _val | _mask); \
818 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
820 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
821 * this avoids any races wrt polling state changes and thereby avoids
824 static bool set_nr_and_not_polling(struct task_struct
*p
)
826 struct thread_info
*ti
= task_thread_info(p
);
827 return !(fetch_or(&ti
->flags
, _TIF_NEED_RESCHED
) & _TIF_POLLING_NRFLAG
);
831 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
833 * If this returns true, then the idle task promises to call
834 * sched_ttwu_pending() and reschedule soon.
836 static bool set_nr_if_polling(struct task_struct
*p
)
838 struct thread_info
*ti
= task_thread_info(p
);
839 typeof(ti
->flags
) old
, val
= READ_ONCE(ti
->flags
);
842 if (!(val
& _TIF_POLLING_NRFLAG
))
844 if (val
& _TIF_NEED_RESCHED
)
846 old
= cmpxchg(&ti
->flags
, val
, val
| _TIF_NEED_RESCHED
);
855 static bool set_nr_and_not_polling(struct task_struct
*p
)
857 set_tsk_need_resched(p
);
862 static bool set_nr_if_polling(struct task_struct
*p
)
869 static bool __wake_q_add(struct wake_q_head
*head
, struct task_struct
*task
)
871 struct wake_q_node
*node
= &task
->wake_q
;
874 * Atomically grab the task, if ->wake_q is !nil already it means
875 * it's already queued (either by us or someone else) and will get the
876 * wakeup due to that.
878 * In order to ensure that a pending wakeup will observe our pending
879 * state, even in the failed case, an explicit smp_mb() must be used.
881 smp_mb__before_atomic();
882 if (unlikely(cmpxchg_relaxed(&node
->next
, NULL
, WAKE_Q_TAIL
)))
886 * The head is context local, there can be no concurrency.
889 head
->lastp
= &node
->next
;
894 * wake_q_add() - queue a wakeup for 'later' waking.
895 * @head: the wake_q_head to add @task to
896 * @task: the task to queue for 'later' wakeup
898 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
899 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
902 * This function must be used as-if it were wake_up_process(); IOW the task
903 * must be ready to be woken at this location.
905 void wake_q_add(struct wake_q_head
*head
, struct task_struct
*task
)
907 if (__wake_q_add(head
, task
))
908 get_task_struct(task
);
912 * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
913 * @head: the wake_q_head to add @task to
914 * @task: the task to queue for 'later' wakeup
916 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
917 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
920 * This function must be used as-if it were wake_up_process(); IOW the task
921 * must be ready to be woken at this location.
923 * This function is essentially a task-safe equivalent to wake_q_add(). Callers
924 * that already hold reference to @task can call the 'safe' version and trust
925 * wake_q to do the right thing depending whether or not the @task is already
928 void wake_q_add_safe(struct wake_q_head
*head
, struct task_struct
*task
)
930 if (!__wake_q_add(head
, task
))
931 put_task_struct(task
);
934 void wake_up_q(struct wake_q_head
*head
)
936 struct wake_q_node
*node
= head
->first
;
938 while (node
!= WAKE_Q_TAIL
) {
939 struct task_struct
*task
;
941 task
= container_of(node
, struct task_struct
, wake_q
);
942 /* Task can safely be re-inserted now: */
944 task
->wake_q
.next
= NULL
;
947 * wake_up_process() executes a full barrier, which pairs with
948 * the queueing in wake_q_add() so as not to miss wakeups.
950 wake_up_process(task
);
951 put_task_struct(task
);
956 * resched_curr - mark rq's current task 'to be rescheduled now'.
958 * On UP this means the setting of the need_resched flag, on SMP it
959 * might also involve a cross-CPU call to trigger the scheduler on
962 void resched_curr(struct rq
*rq
)
964 struct task_struct
*curr
= rq
->curr
;
967 lockdep_assert_rq_held(rq
);
969 if (test_tsk_need_resched(curr
))
974 if (cpu
== smp_processor_id()) {
975 set_tsk_need_resched(curr
);
976 set_preempt_need_resched();
980 if (set_nr_and_not_polling(curr
))
981 smp_send_reschedule(cpu
);
983 trace_sched_wake_idle_without_ipi(cpu
);
986 void resched_cpu(int cpu
)
988 struct rq
*rq
= cpu_rq(cpu
);
991 raw_spin_rq_lock_irqsave(rq
, flags
);
992 if (cpu_online(cpu
) || cpu
== smp_processor_id())
994 raw_spin_rq_unlock_irqrestore(rq
, flags
);
998 #ifdef CONFIG_NO_HZ_COMMON
1000 * In the semi idle case, use the nearest busy CPU for migrating timers
1001 * from an idle CPU. This is good for power-savings.
1003 * We don't do similar optimization for completely idle system, as
1004 * selecting an idle CPU will add more delays to the timers than intended
1005 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
1007 int get_nohz_timer_target(void)
1009 int i
, cpu
= smp_processor_id(), default_cpu
= -1;
1010 struct sched_domain
*sd
;
1011 const struct cpumask
*hk_mask
;
1013 if (housekeeping_cpu(cpu
, HK_FLAG_TIMER
)) {
1019 hk_mask
= housekeeping_cpumask(HK_FLAG_TIMER
);
1022 for_each_domain(cpu
, sd
) {
1023 for_each_cpu_and(i
, sched_domain_span(sd
), hk_mask
) {
1034 if (default_cpu
== -1)
1035 default_cpu
= housekeeping_any_cpu(HK_FLAG_TIMER
);
1043 * When add_timer_on() enqueues a timer into the timer wheel of an
1044 * idle CPU then this timer might expire before the next timer event
1045 * which is scheduled to wake up that CPU. In case of a completely
1046 * idle system the next event might even be infinite time into the
1047 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1048 * leaves the inner idle loop so the newly added timer is taken into
1049 * account when the CPU goes back to idle and evaluates the timer
1050 * wheel for the next timer event.
1052 static void wake_up_idle_cpu(int cpu
)
1054 struct rq
*rq
= cpu_rq(cpu
);
1056 if (cpu
== smp_processor_id())
1059 if (set_nr_and_not_polling(rq
->idle
))
1060 smp_send_reschedule(cpu
);
1062 trace_sched_wake_idle_without_ipi(cpu
);
1065 static bool wake_up_full_nohz_cpu(int cpu
)
1068 * We just need the target to call irq_exit() and re-evaluate
1069 * the next tick. The nohz full kick at least implies that.
1070 * If needed we can still optimize that later with an
1073 if (cpu_is_offline(cpu
))
1074 return true; /* Don't try to wake offline CPUs. */
1075 if (tick_nohz_full_cpu(cpu
)) {
1076 if (cpu
!= smp_processor_id() ||
1077 tick_nohz_tick_stopped())
1078 tick_nohz_full_kick_cpu(cpu
);
1086 * Wake up the specified CPU. If the CPU is going offline, it is the
1087 * caller's responsibility to deal with the lost wakeup, for example,
1088 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
1090 void wake_up_nohz_cpu(int cpu
)
1092 if (!wake_up_full_nohz_cpu(cpu
))
1093 wake_up_idle_cpu(cpu
);
1096 static void nohz_csd_func(void *info
)
1098 struct rq
*rq
= info
;
1099 int cpu
= cpu_of(rq
);
1103 * Release the rq::nohz_csd.
1105 flags
= atomic_fetch_andnot(NOHZ_KICK_MASK
| NOHZ_NEWILB_KICK
, nohz_flags(cpu
));
1106 WARN_ON(!(flags
& NOHZ_KICK_MASK
));
1108 rq
->idle_balance
= idle_cpu(cpu
);
1109 if (rq
->idle_balance
&& !need_resched()) {
1110 rq
->nohz_idle_balance
= flags
;
1111 raise_softirq_irqoff(SCHED_SOFTIRQ
);
1115 #endif /* CONFIG_NO_HZ_COMMON */
1117 #ifdef CONFIG_NO_HZ_FULL
1118 bool sched_can_stop_tick(struct rq
*rq
)
1120 int fifo_nr_running
;
1122 /* Deadline tasks, even if single, need the tick */
1123 if (rq
->dl
.dl_nr_running
)
1127 * If there are more than one RR tasks, we need the tick to affect the
1128 * actual RR behaviour.
1130 if (rq
->rt
.rr_nr_running
) {
1131 if (rq
->rt
.rr_nr_running
== 1)
1138 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
1139 * forced preemption between FIFO tasks.
1141 fifo_nr_running
= rq
->rt
.rt_nr_running
- rq
->rt
.rr_nr_running
;
1142 if (fifo_nr_running
)
1146 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
1147 * if there's more than one we need the tick for involuntary
1150 if (rq
->nr_running
> 1)
1155 #endif /* CONFIG_NO_HZ_FULL */
1156 #endif /* CONFIG_SMP */
1158 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
1159 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
1161 * Iterate task_group tree rooted at *from, calling @down when first entering a
1162 * node and @up when leaving it for the final time.
1164 * Caller must hold rcu_lock or sufficient equivalent.
1166 int walk_tg_tree_from(struct task_group
*from
,
1167 tg_visitor down
, tg_visitor up
, void *data
)
1169 struct task_group
*parent
, *child
;
1175 ret
= (*down
)(parent
, data
);
1178 list_for_each_entry_rcu(child
, &parent
->children
, siblings
) {
1185 ret
= (*up
)(parent
, data
);
1186 if (ret
|| parent
== from
)
1190 parent
= parent
->parent
;
1197 int tg_nop(struct task_group
*tg
, void *data
)
1203 static void set_load_weight(struct task_struct
*p
, bool update_load
)
1205 int prio
= p
->static_prio
- MAX_RT_PRIO
;
1206 struct load_weight
*load
= &p
->se
.load
;
1209 * SCHED_IDLE tasks get minimal weight:
1211 if (task_has_idle_policy(p
)) {
1212 load
->weight
= scale_load(WEIGHT_IDLEPRIO
);
1213 load
->inv_weight
= WMULT_IDLEPRIO
;
1218 * SCHED_OTHER tasks have to update their load when changing their
1221 if (update_load
&& p
->sched_class
== &fair_sched_class
) {
1222 reweight_task(p
, prio
);
1224 load
->weight
= scale_load(sched_prio_to_weight
[prio
]);
1225 load
->inv_weight
= sched_prio_to_wmult
[prio
];
1229 #ifdef CONFIG_UCLAMP_TASK
1231 * Serializes updates of utilization clamp values
1233 * The (slow-path) user-space triggers utilization clamp value updates which
1234 * can require updates on (fast-path) scheduler's data structures used to
1235 * support enqueue/dequeue operations.
1236 * While the per-CPU rq lock protects fast-path update operations, user-space
1237 * requests are serialized using a mutex to reduce the risk of conflicting
1238 * updates or API abuses.
1240 static DEFINE_MUTEX(uclamp_mutex
);
1242 /* Max allowed minimum utilization */
1243 unsigned int sysctl_sched_uclamp_util_min
= SCHED_CAPACITY_SCALE
;
1245 /* Max allowed maximum utilization */
1246 unsigned int sysctl_sched_uclamp_util_max
= SCHED_CAPACITY_SCALE
;
1249 * By default RT tasks run at the maximum performance point/capacity of the
1250 * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
1251 * SCHED_CAPACITY_SCALE.
1253 * This knob allows admins to change the default behavior when uclamp is being
1254 * used. In battery powered devices, particularly, running at the maximum
1255 * capacity and frequency will increase energy consumption and shorten the
1258 * This knob only affects RT tasks that their uclamp_se->user_defined == false.
1260 * This knob will not override the system default sched_util_clamp_min defined
1263 unsigned int sysctl_sched_uclamp_util_min_rt_default
= SCHED_CAPACITY_SCALE
;
1265 /* All clamps are required to be less or equal than these values */
1266 static struct uclamp_se uclamp_default
[UCLAMP_CNT
];
1269 * This static key is used to reduce the uclamp overhead in the fast path. It
1270 * primarily disables the call to uclamp_rq_{inc, dec}() in
1271 * enqueue/dequeue_task().
1273 * This allows users to continue to enable uclamp in their kernel config with
1274 * minimum uclamp overhead in the fast path.
1276 * As soon as userspace modifies any of the uclamp knobs, the static key is
1277 * enabled, since we have an actual users that make use of uclamp
1280 * The knobs that would enable this static key are:
1282 * * A task modifying its uclamp value with sched_setattr().
1283 * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
1284 * * An admin modifying the cgroup cpu.uclamp.{min, max}
1286 DEFINE_STATIC_KEY_FALSE(sched_uclamp_used
);
1288 /* Integer rounded range for each bucket */
1289 #define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
1291 #define for_each_clamp_id(clamp_id) \
1292 for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
1294 static inline unsigned int uclamp_bucket_id(unsigned int clamp_value
)
1296 return min_t(unsigned int, clamp_value
/ UCLAMP_BUCKET_DELTA
, UCLAMP_BUCKETS
- 1);
1299 static inline unsigned int uclamp_none(enum uclamp_id clamp_id
)
1301 if (clamp_id
== UCLAMP_MIN
)
1303 return SCHED_CAPACITY_SCALE
;
1306 static inline void uclamp_se_set(struct uclamp_se
*uc_se
,
1307 unsigned int value
, bool user_defined
)
1309 uc_se
->value
= value
;
1310 uc_se
->bucket_id
= uclamp_bucket_id(value
);
1311 uc_se
->user_defined
= user_defined
;
1314 static inline unsigned int
1315 uclamp_idle_value(struct rq
*rq
, enum uclamp_id clamp_id
,
1316 unsigned int clamp_value
)
1319 * Avoid blocked utilization pushing up the frequency when we go
1320 * idle (which drops the max-clamp) by retaining the last known
1323 if (clamp_id
== UCLAMP_MAX
) {
1324 rq
->uclamp_flags
|= UCLAMP_FLAG_IDLE
;
1328 return uclamp_none(UCLAMP_MIN
);
1331 static inline void uclamp_idle_reset(struct rq
*rq
, enum uclamp_id clamp_id
,
1332 unsigned int clamp_value
)
1334 /* Reset max-clamp retention only on idle exit */
1335 if (!(rq
->uclamp_flags
& UCLAMP_FLAG_IDLE
))
1338 WRITE_ONCE(rq
->uclamp
[clamp_id
].value
, clamp_value
);
1342 unsigned int uclamp_rq_max_value(struct rq
*rq
, enum uclamp_id clamp_id
,
1343 unsigned int clamp_value
)
1345 struct uclamp_bucket
*bucket
= rq
->uclamp
[clamp_id
].bucket
;
1346 int bucket_id
= UCLAMP_BUCKETS
- 1;
1349 * Since both min and max clamps are max aggregated, find the
1350 * top most bucket with tasks in.
1352 for ( ; bucket_id
>= 0; bucket_id
--) {
1353 if (!bucket
[bucket_id
].tasks
)
1355 return bucket
[bucket_id
].value
;
1358 /* No tasks -- default clamp values */
1359 return uclamp_idle_value(rq
, clamp_id
, clamp_value
);
1362 static void __uclamp_update_util_min_rt_default(struct task_struct
*p
)
1364 unsigned int default_util_min
;
1365 struct uclamp_se
*uc_se
;
1367 lockdep_assert_held(&p
->pi_lock
);
1369 uc_se
= &p
->uclamp_req
[UCLAMP_MIN
];
1371 /* Only sync if user didn't override the default */
1372 if (uc_se
->user_defined
)
1375 default_util_min
= sysctl_sched_uclamp_util_min_rt_default
;
1376 uclamp_se_set(uc_se
, default_util_min
, false);
1379 static void uclamp_update_util_min_rt_default(struct task_struct
*p
)
1387 /* Protect updates to p->uclamp_* */
1388 rq
= task_rq_lock(p
, &rf
);
1389 __uclamp_update_util_min_rt_default(p
);
1390 task_rq_unlock(rq
, p
, &rf
);
1393 static void uclamp_sync_util_min_rt_default(void)
1395 struct task_struct
*g
, *p
;
1398 * copy_process() sysctl_uclamp
1399 * uclamp_min_rt = X;
1400 * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
1401 * // link thread smp_mb__after_spinlock()
1402 * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
1403 * sched_post_fork() for_each_process_thread()
1404 * __uclamp_sync_rt() __uclamp_sync_rt()
1406 * Ensures that either sched_post_fork() will observe the new
1407 * uclamp_min_rt or for_each_process_thread() will observe the new
1410 read_lock(&tasklist_lock
);
1411 smp_mb__after_spinlock();
1412 read_unlock(&tasklist_lock
);
1415 for_each_process_thread(g
, p
)
1416 uclamp_update_util_min_rt_default(p
);
1420 static inline struct uclamp_se
1421 uclamp_tg_restrict(struct task_struct
*p
, enum uclamp_id clamp_id
)
1423 /* Copy by value as we could modify it */
1424 struct uclamp_se uc_req
= p
->uclamp_req
[clamp_id
];
1425 #ifdef CONFIG_UCLAMP_TASK_GROUP
1426 unsigned int tg_min
, tg_max
, value
;
1429 * Tasks in autogroups or root task group will be
1430 * restricted by system defaults.
1432 if (task_group_is_autogroup(task_group(p
)))
1434 if (task_group(p
) == &root_task_group
)
1437 tg_min
= task_group(p
)->uclamp
[UCLAMP_MIN
].value
;
1438 tg_max
= task_group(p
)->uclamp
[UCLAMP_MAX
].value
;
1439 value
= uc_req
.value
;
1440 value
= clamp(value
, tg_min
, tg_max
);
1441 uclamp_se_set(&uc_req
, value
, false);
1448 * The effective clamp bucket index of a task depends on, by increasing
1450 * - the task specific clamp value, when explicitly requested from userspace
1451 * - the task group effective clamp value, for tasks not either in the root
1452 * group or in an autogroup
1453 * - the system default clamp value, defined by the sysadmin
1455 static inline struct uclamp_se
1456 uclamp_eff_get(struct task_struct
*p
, enum uclamp_id clamp_id
)
1458 struct uclamp_se uc_req
= uclamp_tg_restrict(p
, clamp_id
);
1459 struct uclamp_se uc_max
= uclamp_default
[clamp_id
];
1461 /* System default restrictions always apply */
1462 if (unlikely(uc_req
.value
> uc_max
.value
))
1468 unsigned long uclamp_eff_value(struct task_struct
*p
, enum uclamp_id clamp_id
)
1470 struct uclamp_se uc_eff
;
1472 /* Task currently refcounted: use back-annotated (effective) value */
1473 if (p
->uclamp
[clamp_id
].active
)
1474 return (unsigned long)p
->uclamp
[clamp_id
].value
;
1476 uc_eff
= uclamp_eff_get(p
, clamp_id
);
1478 return (unsigned long)uc_eff
.value
;
1482 * When a task is enqueued on a rq, the clamp bucket currently defined by the
1483 * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1484 * updates the rq's clamp value if required.
1486 * Tasks can have a task-specific value requested from user-space, track
1487 * within each bucket the maximum value for tasks refcounted in it.
1488 * This "local max aggregation" allows to track the exact "requested" value
1489 * for each bucket when all its RUNNABLE tasks require the same clamp.
1491 static inline void uclamp_rq_inc_id(struct rq
*rq
, struct task_struct
*p
,
1492 enum uclamp_id clamp_id
)
1494 struct uclamp_rq
*uc_rq
= &rq
->uclamp
[clamp_id
];
1495 struct uclamp_se
*uc_se
= &p
->uclamp
[clamp_id
];
1496 struct uclamp_bucket
*bucket
;
1498 lockdep_assert_rq_held(rq
);
1500 /* Update task effective clamp */
1501 p
->uclamp
[clamp_id
] = uclamp_eff_get(p
, clamp_id
);
1503 bucket
= &uc_rq
->bucket
[uc_se
->bucket_id
];
1505 uc_se
->active
= true;
1507 uclamp_idle_reset(rq
, clamp_id
, uc_se
->value
);
1510 * Local max aggregation: rq buckets always track the max
1511 * "requested" clamp value of its RUNNABLE tasks.
1513 if (bucket
->tasks
== 1 || uc_se
->value
> bucket
->value
)
1514 bucket
->value
= uc_se
->value
;
1516 if (uc_se
->value
> READ_ONCE(uc_rq
->value
))
1517 WRITE_ONCE(uc_rq
->value
, uc_se
->value
);
1521 * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1522 * is released. If this is the last task reference counting the rq's max
1523 * active clamp value, then the rq's clamp value is updated.
1525 * Both refcounted tasks and rq's cached clamp values are expected to be
1526 * always valid. If it's detected they are not, as defensive programming,
1527 * enforce the expected state and warn.
1529 static inline void uclamp_rq_dec_id(struct rq
*rq
, struct task_struct
*p
,
1530 enum uclamp_id clamp_id
)
1532 struct uclamp_rq
*uc_rq
= &rq
->uclamp
[clamp_id
];
1533 struct uclamp_se
*uc_se
= &p
->uclamp
[clamp_id
];
1534 struct uclamp_bucket
*bucket
;
1535 unsigned int bkt_clamp
;
1536 unsigned int rq_clamp
;
1538 lockdep_assert_rq_held(rq
);
1541 * If sched_uclamp_used was enabled after task @p was enqueued,
1542 * we could end up with unbalanced call to uclamp_rq_dec_id().
1544 * In this case the uc_se->active flag should be false since no uclamp
1545 * accounting was performed at enqueue time and we can just return
1548 * Need to be careful of the following enqueue/dequeue ordering
1552 * // sched_uclamp_used gets enabled
1555 * // Must not decrement bucket->tasks here
1558 * where we could end up with stale data in uc_se and
1559 * bucket[uc_se->bucket_id].
1561 * The following check here eliminates the possibility of such race.
1563 if (unlikely(!uc_se
->active
))
1566 bucket
= &uc_rq
->bucket
[uc_se
->bucket_id
];
1568 SCHED_WARN_ON(!bucket
->tasks
);
1569 if (likely(bucket
->tasks
))
1572 uc_se
->active
= false;
1575 * Keep "local max aggregation" simple and accept to (possibly)
1576 * overboost some RUNNABLE tasks in the same bucket.
1577 * The rq clamp bucket value is reset to its base value whenever
1578 * there are no more RUNNABLE tasks refcounting it.
1580 if (likely(bucket
->tasks
))
1583 rq_clamp
= READ_ONCE(uc_rq
->value
);
1585 * Defensive programming: this should never happen. If it happens,
1586 * e.g. due to future modification, warn and fixup the expected value.
1588 SCHED_WARN_ON(bucket
->value
> rq_clamp
);
1589 if (bucket
->value
>= rq_clamp
) {
1590 bkt_clamp
= uclamp_rq_max_value(rq
, clamp_id
, uc_se
->value
);
1591 WRITE_ONCE(uc_rq
->value
, bkt_clamp
);
1595 static inline void uclamp_rq_inc(struct rq
*rq
, struct task_struct
*p
)
1597 enum uclamp_id clamp_id
;
1600 * Avoid any overhead until uclamp is actually used by the userspace.
1602 * The condition is constructed such that a NOP is generated when
1603 * sched_uclamp_used is disabled.
1605 if (!static_branch_unlikely(&sched_uclamp_used
))
1608 if (unlikely(!p
->sched_class
->uclamp_enabled
))
1611 for_each_clamp_id(clamp_id
)
1612 uclamp_rq_inc_id(rq
, p
, clamp_id
);
1614 /* Reset clamp idle holding when there is one RUNNABLE task */
1615 if (rq
->uclamp_flags
& UCLAMP_FLAG_IDLE
)
1616 rq
->uclamp_flags
&= ~UCLAMP_FLAG_IDLE
;
1619 static inline void uclamp_rq_dec(struct rq
*rq
, struct task_struct
*p
)
1621 enum uclamp_id clamp_id
;
1624 * Avoid any overhead until uclamp is actually used by the userspace.
1626 * The condition is constructed such that a NOP is generated when
1627 * sched_uclamp_used is disabled.
1629 if (!static_branch_unlikely(&sched_uclamp_used
))
1632 if (unlikely(!p
->sched_class
->uclamp_enabled
))
1635 for_each_clamp_id(clamp_id
)
1636 uclamp_rq_dec_id(rq
, p
, clamp_id
);
1639 static inline void uclamp_rq_reinc_id(struct rq
*rq
, struct task_struct
*p
,
1640 enum uclamp_id clamp_id
)
1642 if (!p
->uclamp
[clamp_id
].active
)
1645 uclamp_rq_dec_id(rq
, p
, clamp_id
);
1646 uclamp_rq_inc_id(rq
, p
, clamp_id
);
1649 * Make sure to clear the idle flag if we've transiently reached 0
1650 * active tasks on rq.
1652 if (clamp_id
== UCLAMP_MAX
&& (rq
->uclamp_flags
& UCLAMP_FLAG_IDLE
))
1653 rq
->uclamp_flags
&= ~UCLAMP_FLAG_IDLE
;
1657 uclamp_update_active(struct task_struct
*p
)
1659 enum uclamp_id clamp_id
;
1664 * Lock the task and the rq where the task is (or was) queued.
1666 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1667 * price to pay to safely serialize util_{min,max} updates with
1668 * enqueues, dequeues and migration operations.
1669 * This is the same locking schema used by __set_cpus_allowed_ptr().
1671 rq
= task_rq_lock(p
, &rf
);
1674 * Setting the clamp bucket is serialized by task_rq_lock().
1675 * If the task is not yet RUNNABLE and its task_struct is not
1676 * affecting a valid clamp bucket, the next time it's enqueued,
1677 * it will already see the updated clamp bucket value.
1679 for_each_clamp_id(clamp_id
)
1680 uclamp_rq_reinc_id(rq
, p
, clamp_id
);
1682 task_rq_unlock(rq
, p
, &rf
);
1685 #ifdef CONFIG_UCLAMP_TASK_GROUP
1687 uclamp_update_active_tasks(struct cgroup_subsys_state
*css
)
1689 struct css_task_iter it
;
1690 struct task_struct
*p
;
1692 css_task_iter_start(css
, 0, &it
);
1693 while ((p
= css_task_iter_next(&it
)))
1694 uclamp_update_active(p
);
1695 css_task_iter_end(&it
);
1698 static void cpu_util_update_eff(struct cgroup_subsys_state
*css
);
1699 static void uclamp_update_root_tg(void)
1701 struct task_group
*tg
= &root_task_group
;
1703 uclamp_se_set(&tg
->uclamp_req
[UCLAMP_MIN
],
1704 sysctl_sched_uclamp_util_min
, false);
1705 uclamp_se_set(&tg
->uclamp_req
[UCLAMP_MAX
],
1706 sysctl_sched_uclamp_util_max
, false);
1709 cpu_util_update_eff(&root_task_group
.css
);
1713 static void uclamp_update_root_tg(void) { }
1716 int sysctl_sched_uclamp_handler(struct ctl_table
*table
, int write
,
1717 void *buffer
, size_t *lenp
, loff_t
*ppos
)
1719 bool update_root_tg
= false;
1720 int old_min
, old_max
, old_min_rt
;
1723 mutex_lock(&uclamp_mutex
);
1724 old_min
= sysctl_sched_uclamp_util_min
;
1725 old_max
= sysctl_sched_uclamp_util_max
;
1726 old_min_rt
= sysctl_sched_uclamp_util_min_rt_default
;
1728 result
= proc_dointvec(table
, write
, buffer
, lenp
, ppos
);
1734 if (sysctl_sched_uclamp_util_min
> sysctl_sched_uclamp_util_max
||
1735 sysctl_sched_uclamp_util_max
> SCHED_CAPACITY_SCALE
||
1736 sysctl_sched_uclamp_util_min_rt_default
> SCHED_CAPACITY_SCALE
) {
1742 if (old_min
!= sysctl_sched_uclamp_util_min
) {
1743 uclamp_se_set(&uclamp_default
[UCLAMP_MIN
],
1744 sysctl_sched_uclamp_util_min
, false);
1745 update_root_tg
= true;
1747 if (old_max
!= sysctl_sched_uclamp_util_max
) {
1748 uclamp_se_set(&uclamp_default
[UCLAMP_MAX
],
1749 sysctl_sched_uclamp_util_max
, false);
1750 update_root_tg
= true;
1753 if (update_root_tg
) {
1754 static_branch_enable(&sched_uclamp_used
);
1755 uclamp_update_root_tg();
1758 if (old_min_rt
!= sysctl_sched_uclamp_util_min_rt_default
) {
1759 static_branch_enable(&sched_uclamp_used
);
1760 uclamp_sync_util_min_rt_default();
1764 * We update all RUNNABLE tasks only when task groups are in use.
1765 * Otherwise, keep it simple and do just a lazy update at each next
1766 * task enqueue time.
1772 sysctl_sched_uclamp_util_min
= old_min
;
1773 sysctl_sched_uclamp_util_max
= old_max
;
1774 sysctl_sched_uclamp_util_min_rt_default
= old_min_rt
;
1776 mutex_unlock(&uclamp_mutex
);
1781 static int uclamp_validate(struct task_struct
*p
,
1782 const struct sched_attr
*attr
)
1784 int util_min
= p
->uclamp_req
[UCLAMP_MIN
].value
;
1785 int util_max
= p
->uclamp_req
[UCLAMP_MAX
].value
;
1787 if (attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP_MIN
) {
1788 util_min
= attr
->sched_util_min
;
1790 if (util_min
+ 1 > SCHED_CAPACITY_SCALE
+ 1)
1794 if (attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP_MAX
) {
1795 util_max
= attr
->sched_util_max
;
1797 if (util_max
+ 1 > SCHED_CAPACITY_SCALE
+ 1)
1801 if (util_min
!= -1 && util_max
!= -1 && util_min
> util_max
)
1805 * We have valid uclamp attributes; make sure uclamp is enabled.
1807 * We need to do that here, because enabling static branches is a
1808 * blocking operation which obviously cannot be done while holding
1811 static_branch_enable(&sched_uclamp_used
);
1816 static bool uclamp_reset(const struct sched_attr
*attr
,
1817 enum uclamp_id clamp_id
,
1818 struct uclamp_se
*uc_se
)
1820 /* Reset on sched class change for a non user-defined clamp value. */
1821 if (likely(!(attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP
)) &&
1822 !uc_se
->user_defined
)
1825 /* Reset on sched_util_{min,max} == -1. */
1826 if (clamp_id
== UCLAMP_MIN
&&
1827 attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP_MIN
&&
1828 attr
->sched_util_min
== -1) {
1832 if (clamp_id
== UCLAMP_MAX
&&
1833 attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP_MAX
&&
1834 attr
->sched_util_max
== -1) {
1841 static void __setscheduler_uclamp(struct task_struct
*p
,
1842 const struct sched_attr
*attr
)
1844 enum uclamp_id clamp_id
;
1846 for_each_clamp_id(clamp_id
) {
1847 struct uclamp_se
*uc_se
= &p
->uclamp_req
[clamp_id
];
1850 if (!uclamp_reset(attr
, clamp_id
, uc_se
))
1854 * RT by default have a 100% boost value that could be modified
1857 if (unlikely(rt_task(p
) && clamp_id
== UCLAMP_MIN
))
1858 value
= sysctl_sched_uclamp_util_min_rt_default
;
1860 value
= uclamp_none(clamp_id
);
1862 uclamp_se_set(uc_se
, value
, false);
1866 if (likely(!(attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP
)))
1869 if (attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP_MIN
&&
1870 attr
->sched_util_min
!= -1) {
1871 uclamp_se_set(&p
->uclamp_req
[UCLAMP_MIN
],
1872 attr
->sched_util_min
, true);
1875 if (attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP_MAX
&&
1876 attr
->sched_util_max
!= -1) {
1877 uclamp_se_set(&p
->uclamp_req
[UCLAMP_MAX
],
1878 attr
->sched_util_max
, true);
1882 static void uclamp_fork(struct task_struct
*p
)
1884 enum uclamp_id clamp_id
;
1887 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
1888 * as the task is still at its early fork stages.
1890 for_each_clamp_id(clamp_id
)
1891 p
->uclamp
[clamp_id
].active
= false;
1893 if (likely(!p
->sched_reset_on_fork
))
1896 for_each_clamp_id(clamp_id
) {
1897 uclamp_se_set(&p
->uclamp_req
[clamp_id
],
1898 uclamp_none(clamp_id
), false);
1902 static void uclamp_post_fork(struct task_struct
*p
)
1904 uclamp_update_util_min_rt_default(p
);
1907 static void __init
init_uclamp_rq(struct rq
*rq
)
1909 enum uclamp_id clamp_id
;
1910 struct uclamp_rq
*uc_rq
= rq
->uclamp
;
1912 for_each_clamp_id(clamp_id
) {
1913 uc_rq
[clamp_id
] = (struct uclamp_rq
) {
1914 .value
= uclamp_none(clamp_id
)
1918 rq
->uclamp_flags
= UCLAMP_FLAG_IDLE
;
1921 static void __init
init_uclamp(void)
1923 struct uclamp_se uc_max
= {};
1924 enum uclamp_id clamp_id
;
1927 for_each_possible_cpu(cpu
)
1928 init_uclamp_rq(cpu_rq(cpu
));
1930 for_each_clamp_id(clamp_id
) {
1931 uclamp_se_set(&init_task
.uclamp_req
[clamp_id
],
1932 uclamp_none(clamp_id
), false);
1935 /* System defaults allow max clamp values for both indexes */
1936 uclamp_se_set(&uc_max
, uclamp_none(UCLAMP_MAX
), false);
1937 for_each_clamp_id(clamp_id
) {
1938 uclamp_default
[clamp_id
] = uc_max
;
1939 #ifdef CONFIG_UCLAMP_TASK_GROUP
1940 root_task_group
.uclamp_req
[clamp_id
] = uc_max
;
1941 root_task_group
.uclamp
[clamp_id
] = uc_max
;
1946 #else /* CONFIG_UCLAMP_TASK */
1947 static inline void uclamp_rq_inc(struct rq
*rq
, struct task_struct
*p
) { }
1948 static inline void uclamp_rq_dec(struct rq
*rq
, struct task_struct
*p
) { }
1949 static inline int uclamp_validate(struct task_struct
*p
,
1950 const struct sched_attr
*attr
)
1954 static void __setscheduler_uclamp(struct task_struct
*p
,
1955 const struct sched_attr
*attr
) { }
1956 static inline void uclamp_fork(struct task_struct
*p
) { }
1957 static inline void uclamp_post_fork(struct task_struct
*p
) { }
1958 static inline void init_uclamp(void) { }
1959 #endif /* CONFIG_UCLAMP_TASK */
1961 bool sched_task_on_rq(struct task_struct
*p
)
1963 return task_on_rq_queued(p
);
1966 static inline void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
1968 if (!(flags
& ENQUEUE_NOCLOCK
))
1969 update_rq_clock(rq
);
1971 if (!(flags
& ENQUEUE_RESTORE
)) {
1972 sched_info_enqueue(rq
, p
);
1973 psi_enqueue(p
, flags
& ENQUEUE_WAKEUP
);
1976 uclamp_rq_inc(rq
, p
);
1977 p
->sched_class
->enqueue_task(rq
, p
, flags
);
1979 if (sched_core_enabled(rq
))
1980 sched_core_enqueue(rq
, p
);
1983 static inline void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
1985 if (sched_core_enabled(rq
))
1986 sched_core_dequeue(rq
, p
);
1988 if (!(flags
& DEQUEUE_NOCLOCK
))
1989 update_rq_clock(rq
);
1991 if (!(flags
& DEQUEUE_SAVE
)) {
1992 sched_info_dequeue(rq
, p
);
1993 psi_dequeue(p
, flags
& DEQUEUE_SLEEP
);
1996 uclamp_rq_dec(rq
, p
);
1997 p
->sched_class
->dequeue_task(rq
, p
, flags
);
2000 void activate_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
2002 enqueue_task(rq
, p
, flags
);
2004 p
->on_rq
= TASK_ON_RQ_QUEUED
;
2007 void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
2009 p
->on_rq
= (flags
& DEQUEUE_SLEEP
) ? 0 : TASK_ON_RQ_MIGRATING
;
2011 dequeue_task(rq
, p
, flags
);
2014 static inline int __normal_prio(int policy
, int rt_prio
, int nice
)
2018 if (dl_policy(policy
))
2019 prio
= MAX_DL_PRIO
- 1;
2020 else if (rt_policy(policy
))
2021 prio
= MAX_RT_PRIO
- 1 - rt_prio
;
2023 prio
= NICE_TO_PRIO(nice
);
2029 * Calculate the expected normal priority: i.e. priority
2030 * without taking RT-inheritance into account. Might be
2031 * boosted by interactivity modifiers. Changes upon fork,
2032 * setprio syscalls, and whenever the interactivity
2033 * estimator recalculates.
2035 static inline int normal_prio(struct task_struct
*p
)
2037 return __normal_prio(p
->policy
, p
->rt_priority
, PRIO_TO_NICE(p
->static_prio
));
2041 * Calculate the current priority, i.e. the priority
2042 * taken into account by the scheduler. This value might
2043 * be boosted by RT tasks, or might be boosted by
2044 * interactivity modifiers. Will be RT if the task got
2045 * RT-boosted. If not then it returns p->normal_prio.
2047 static int effective_prio(struct task_struct
*p
)
2049 p
->normal_prio
= normal_prio(p
);
2051 * If we are RT tasks or we were boosted to RT priority,
2052 * keep the priority unchanged. Otherwise, update priority
2053 * to the normal priority:
2055 if (!rt_prio(p
->prio
))
2056 return p
->normal_prio
;
2061 * task_curr - is this task currently executing on a CPU?
2062 * @p: the task in question.
2064 * Return: 1 if the task is currently executing. 0 otherwise.
2066 inline int task_curr(const struct task_struct
*p
)
2068 return cpu_curr(task_cpu(p
)) == p
;
2072 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
2073 * use the balance_callback list if you want balancing.
2075 * this means any call to check_class_changed() must be followed by a call to
2076 * balance_callback().
2078 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
2079 const struct sched_class
*prev_class
,
2082 if (prev_class
!= p
->sched_class
) {
2083 if (prev_class
->switched_from
)
2084 prev_class
->switched_from(rq
, p
);
2086 p
->sched_class
->switched_to(rq
, p
);
2087 } else if (oldprio
!= p
->prio
|| dl_task(p
))
2088 p
->sched_class
->prio_changed(rq
, p
, oldprio
);
2091 void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
, int flags
)
2093 if (p
->sched_class
== rq
->curr
->sched_class
)
2094 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
, flags
);
2095 else if (p
->sched_class
> rq
->curr
->sched_class
)
2099 * A queue event has occurred, and we're going to schedule. In
2100 * this case, we can save a useless back to back clock update.
2102 if (task_on_rq_queued(rq
->curr
) && test_tsk_need_resched(rq
->curr
))
2103 rq_clock_skip_update(rq
);
2109 __do_set_cpus_allowed(struct task_struct
*p
, const struct cpumask
*new_mask
, u32 flags
);
2111 static int __set_cpus_allowed_ptr(struct task_struct
*p
,
2112 const struct cpumask
*new_mask
,
2115 static void migrate_disable_switch(struct rq
*rq
, struct task_struct
*p
)
2117 if (likely(!p
->migration_disabled
))
2120 if (p
->cpus_ptr
!= &p
->cpus_mask
)
2124 * Violates locking rules! see comment in __do_set_cpus_allowed().
2126 __do_set_cpus_allowed(p
, cpumask_of(rq
->cpu
), SCA_MIGRATE_DISABLE
);
2129 void migrate_disable(void)
2131 struct task_struct
*p
= current
;
2133 if (p
->migration_disabled
) {
2134 p
->migration_disabled
++;
2139 this_rq()->nr_pinned
++;
2140 p
->migration_disabled
= 1;
2143 EXPORT_SYMBOL_GPL(migrate_disable
);
2145 void migrate_enable(void)
2147 struct task_struct
*p
= current
;
2149 if (p
->migration_disabled
> 1) {
2150 p
->migration_disabled
--;
2155 * Ensure stop_task runs either before or after this, and that
2156 * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
2159 if (p
->cpus_ptr
!= &p
->cpus_mask
)
2160 __set_cpus_allowed_ptr(p
, &p
->cpus_mask
, SCA_MIGRATE_ENABLE
);
2162 * Mustn't clear migration_disabled() until cpus_ptr points back at the
2163 * regular cpus_mask, otherwise things that race (eg.
2164 * select_fallback_rq) get confused.
2167 p
->migration_disabled
= 0;
2168 this_rq()->nr_pinned
--;
2171 EXPORT_SYMBOL_GPL(migrate_enable
);
2173 static inline bool rq_has_pinned_tasks(struct rq
*rq
)
2175 return rq
->nr_pinned
;
2179 * Per-CPU kthreads are allowed to run on !active && online CPUs, see
2180 * __set_cpus_allowed_ptr() and select_fallback_rq().
2182 static inline bool is_cpu_allowed(struct task_struct
*p
, int cpu
)
2184 /* When not in the task's cpumask, no point in looking further. */
2185 if (!cpumask_test_cpu(cpu
, p
->cpus_ptr
))
2188 /* migrate_disabled() must be allowed to finish. */
2189 if (is_migration_disabled(p
))
2190 return cpu_online(cpu
);
2192 /* Non kernel threads are not allowed during either online or offline. */
2193 if (!(p
->flags
& PF_KTHREAD
))
2194 return cpu_active(cpu
) && task_cpu_possible(cpu
, p
);
2196 /* KTHREAD_IS_PER_CPU is always allowed. */
2197 if (kthread_is_per_cpu(p
))
2198 return cpu_online(cpu
);
2200 /* Regular kernel threads don't get to stay during offline. */
2204 /* But are allowed during online. */
2205 return cpu_online(cpu
);
2209 * This is how migration works:
2211 * 1) we invoke migration_cpu_stop() on the target CPU using
2213 * 2) stopper starts to run (implicitly forcing the migrated thread
2215 * 3) it checks whether the migrated task is still in the wrong runqueue.
2216 * 4) if it's in the wrong runqueue then the migration thread removes
2217 * it and puts it into the right queue.
2218 * 5) stopper completes and stop_one_cpu() returns and the migration
2223 * move_queued_task - move a queued task to new rq.
2225 * Returns (locked) new rq. Old rq's lock is released.
2227 static struct rq
*move_queued_task(struct rq
*rq
, struct rq_flags
*rf
,
2228 struct task_struct
*p
, int new_cpu
)
2230 lockdep_assert_rq_held(rq
);
2232 deactivate_task(rq
, p
, DEQUEUE_NOCLOCK
);
2233 set_task_cpu(p
, new_cpu
);
2236 rq
= cpu_rq(new_cpu
);
2239 BUG_ON(task_cpu(p
) != new_cpu
);
2240 activate_task(rq
, p
, 0);
2241 check_preempt_curr(rq
, p
, 0);
2246 struct migration_arg
{
2247 struct task_struct
*task
;
2249 struct set_affinity_pending
*pending
;
2253 * @refs: number of wait_for_completion()
2254 * @stop_pending: is @stop_work in use
2256 struct set_affinity_pending
{
2258 unsigned int stop_pending
;
2259 struct completion done
;
2260 struct cpu_stop_work stop_work
;
2261 struct migration_arg arg
;
2265 * Move (not current) task off this CPU, onto the destination CPU. We're doing
2266 * this because either it can't run here any more (set_cpus_allowed()
2267 * away from this CPU, or CPU going down), or because we're
2268 * attempting to rebalance this task on exec (sched_exec).
2270 * So we race with normal scheduler movements, but that's OK, as long
2271 * as the task is no longer on this CPU.
2273 static struct rq
*__migrate_task(struct rq
*rq
, struct rq_flags
*rf
,
2274 struct task_struct
*p
, int dest_cpu
)
2276 /* Affinity changed (again). */
2277 if (!is_cpu_allowed(p
, dest_cpu
))
2280 update_rq_clock(rq
);
2281 rq
= move_queued_task(rq
, rf
, p
, dest_cpu
);
2287 * migration_cpu_stop - this will be executed by a highprio stopper thread
2288 * and performs thread migration by bumping thread off CPU then
2289 * 'pushing' onto another runqueue.
2291 static int migration_cpu_stop(void *data
)
2293 struct migration_arg
*arg
= data
;
2294 struct set_affinity_pending
*pending
= arg
->pending
;
2295 struct task_struct
*p
= arg
->task
;
2296 struct rq
*rq
= this_rq();
2297 bool complete
= false;
2301 * The original target CPU might have gone down and we might
2302 * be on another CPU but it doesn't matter.
2304 local_irq_save(rf
.flags
);
2306 * We need to explicitly wake pending tasks before running
2307 * __migrate_task() such that we will not miss enforcing cpus_ptr
2308 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
2310 flush_smp_call_function_from_idle();
2312 raw_spin_lock(&p
->pi_lock
);
2316 * If we were passed a pending, then ->stop_pending was set, thus
2317 * p->migration_pending must have remained stable.
2319 WARN_ON_ONCE(pending
&& pending
!= p
->migration_pending
);
2322 * If task_rq(p) != rq, it cannot be migrated here, because we're
2323 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
2324 * we're holding p->pi_lock.
2326 if (task_rq(p
) == rq
) {
2327 if (is_migration_disabled(p
))
2331 p
->migration_pending
= NULL
;
2334 if (cpumask_test_cpu(task_cpu(p
), &p
->cpus_mask
))
2338 if (task_on_rq_queued(p
))
2339 rq
= __migrate_task(rq
, &rf
, p
, arg
->dest_cpu
);
2341 p
->wake_cpu
= arg
->dest_cpu
;
2344 * XXX __migrate_task() can fail, at which point we might end
2345 * up running on a dodgy CPU, AFAICT this can only happen
2346 * during CPU hotplug, at which point we'll get pushed out
2347 * anyway, so it's probably not a big deal.
2350 } else if (pending
) {
2352 * This happens when we get migrated between migrate_enable()'s
2353 * preempt_enable() and scheduling the stopper task. At that
2354 * point we're a regular task again and not current anymore.
2356 * A !PREEMPT kernel has a giant hole here, which makes it far
2361 * The task moved before the stopper got to run. We're holding
2362 * ->pi_lock, so the allowed mask is stable - if it got
2363 * somewhere allowed, we're done.
2365 if (cpumask_test_cpu(task_cpu(p
), p
->cpus_ptr
)) {
2366 p
->migration_pending
= NULL
;
2372 * When migrate_enable() hits a rq mis-match we can't reliably
2373 * determine is_migration_disabled() and so have to chase after
2376 WARN_ON_ONCE(!pending
->stop_pending
);
2377 task_rq_unlock(rq
, p
, &rf
);
2378 stop_one_cpu_nowait(task_cpu(p
), migration_cpu_stop
,
2379 &pending
->arg
, &pending
->stop_work
);
2384 pending
->stop_pending
= false;
2385 task_rq_unlock(rq
, p
, &rf
);
2388 complete_all(&pending
->done
);
2393 int push_cpu_stop(void *arg
)
2395 struct rq
*lowest_rq
= NULL
, *rq
= this_rq();
2396 struct task_struct
*p
= arg
;
2398 raw_spin_lock_irq(&p
->pi_lock
);
2399 raw_spin_rq_lock(rq
);
2401 if (task_rq(p
) != rq
)
2404 if (is_migration_disabled(p
)) {
2405 p
->migration_flags
|= MDF_PUSH
;
2409 p
->migration_flags
&= ~MDF_PUSH
;
2411 if (p
->sched_class
->find_lock_rq
)
2412 lowest_rq
= p
->sched_class
->find_lock_rq(p
, rq
);
2417 // XXX validate p is still the highest prio task
2418 if (task_rq(p
) == rq
) {
2419 deactivate_task(rq
, p
, 0);
2420 set_task_cpu(p
, lowest_rq
->cpu
);
2421 activate_task(lowest_rq
, p
, 0);
2422 resched_curr(lowest_rq
);
2425 double_unlock_balance(rq
, lowest_rq
);
2428 rq
->push_busy
= false;
2429 raw_spin_rq_unlock(rq
);
2430 raw_spin_unlock_irq(&p
->pi_lock
);
2437 * sched_class::set_cpus_allowed must do the below, but is not required to
2438 * actually call this function.
2440 void set_cpus_allowed_common(struct task_struct
*p
, const struct cpumask
*new_mask
, u32 flags
)
2442 if (flags
& (SCA_MIGRATE_ENABLE
| SCA_MIGRATE_DISABLE
)) {
2443 p
->cpus_ptr
= new_mask
;
2447 cpumask_copy(&p
->cpus_mask
, new_mask
);
2448 p
->nr_cpus_allowed
= cpumask_weight(new_mask
);
2452 __do_set_cpus_allowed(struct task_struct
*p
, const struct cpumask
*new_mask
, u32 flags
)
2454 struct rq
*rq
= task_rq(p
);
2455 bool queued
, running
;
2458 * This here violates the locking rules for affinity, since we're only
2459 * supposed to change these variables while holding both rq->lock and
2462 * HOWEVER, it magically works, because ttwu() is the only code that
2463 * accesses these variables under p->pi_lock and only does so after
2464 * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
2465 * before finish_task().
2467 * XXX do further audits, this smells like something putrid.
2469 if (flags
& SCA_MIGRATE_DISABLE
)
2470 SCHED_WARN_ON(!p
->on_cpu
);
2472 lockdep_assert_held(&p
->pi_lock
);
2474 queued
= task_on_rq_queued(p
);
2475 running
= task_current(rq
, p
);
2479 * Because __kthread_bind() calls this on blocked tasks without
2482 lockdep_assert_rq_held(rq
);
2483 dequeue_task(rq
, p
, DEQUEUE_SAVE
| DEQUEUE_NOCLOCK
);
2486 put_prev_task(rq
, p
);
2488 p
->sched_class
->set_cpus_allowed(p
, new_mask
, flags
);
2491 enqueue_task(rq
, p
, ENQUEUE_RESTORE
| ENQUEUE_NOCLOCK
);
2493 set_next_task(rq
, p
);
2496 void do_set_cpus_allowed(struct task_struct
*p
, const struct cpumask
*new_mask
)
2498 __do_set_cpus_allowed(p
, new_mask
, 0);
2501 int dup_user_cpus_ptr(struct task_struct
*dst
, struct task_struct
*src
,
2504 if (!src
->user_cpus_ptr
)
2507 dst
->user_cpus_ptr
= kmalloc_node(cpumask_size(), GFP_KERNEL
, node
);
2508 if (!dst
->user_cpus_ptr
)
2511 cpumask_copy(dst
->user_cpus_ptr
, src
->user_cpus_ptr
);
2515 static inline struct cpumask
*clear_user_cpus_ptr(struct task_struct
*p
)
2517 struct cpumask
*user_mask
= NULL
;
2519 swap(p
->user_cpus_ptr
, user_mask
);
2524 void release_user_cpus_ptr(struct task_struct
*p
)
2526 kfree(clear_user_cpus_ptr(p
));
2530 * This function is wildly self concurrent; here be dragons.
2533 * When given a valid mask, __set_cpus_allowed_ptr() must block until the
2534 * designated task is enqueued on an allowed CPU. If that task is currently
2535 * running, we have to kick it out using the CPU stopper.
2537 * Migrate-Disable comes along and tramples all over our nice sandcastle.
2540 * Initial conditions: P0->cpus_mask = [0, 1]
2544 * migrate_disable();
2546 * set_cpus_allowed_ptr(P0, [1]);
2548 * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
2549 * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
2550 * This means we need the following scheme:
2554 * migrate_disable();
2556 * set_cpus_allowed_ptr(P0, [1]);
2560 * __set_cpus_allowed_ptr();
2561 * <wakes local stopper>
2562 * `--> <woken on migration completion>
2564 * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
2565 * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
2566 * task p are serialized by p->pi_lock, which we can leverage: the one that
2567 * should come into effect at the end of the Migrate-Disable region is the last
2568 * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
2569 * but we still need to properly signal those waiting tasks at the appropriate
2572 * This is implemented using struct set_affinity_pending. The first
2573 * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
2574 * setup an instance of that struct and install it on the targeted task_struct.
2575 * Any and all further callers will reuse that instance. Those then wait for
2576 * a completion signaled at the tail of the CPU stopper callback (1), triggered
2577 * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
2580 * (1) In the cases covered above. There is one more where the completion is
2581 * signaled within affine_move_task() itself: when a subsequent affinity request
2582 * occurs after the stopper bailed out due to the targeted task still being
2583 * Migrate-Disable. Consider:
2585 * Initial conditions: P0->cpus_mask = [0, 1]
2589 * migrate_disable();
2591 * set_cpus_allowed_ptr(P0, [1]);
2594 * migration_cpu_stop()
2595 * is_migration_disabled()
2597 * set_cpus_allowed_ptr(P0, [0, 1]);
2598 * <signal completion>
2601 * Note that the above is safe vs a concurrent migrate_enable(), as any
2602 * pending affinity completion is preceded by an uninstallation of
2603 * p->migration_pending done with p->pi_lock held.
2605 static int affine_move_task(struct rq
*rq
, struct task_struct
*p
, struct rq_flags
*rf
,
2606 int dest_cpu
, unsigned int flags
)
2608 struct set_affinity_pending my_pending
= { }, *pending
= NULL
;
2609 bool stop_pending
, complete
= false;
2611 /* Can the task run on the task's current CPU? If so, we're done */
2612 if (cpumask_test_cpu(task_cpu(p
), &p
->cpus_mask
)) {
2613 struct task_struct
*push_task
= NULL
;
2615 if ((flags
& SCA_MIGRATE_ENABLE
) &&
2616 (p
->migration_flags
& MDF_PUSH
) && !rq
->push_busy
) {
2617 rq
->push_busy
= true;
2618 push_task
= get_task_struct(p
);
2622 * If there are pending waiters, but no pending stop_work,
2623 * then complete now.
2625 pending
= p
->migration_pending
;
2626 if (pending
&& !pending
->stop_pending
) {
2627 p
->migration_pending
= NULL
;
2631 task_rq_unlock(rq
, p
, rf
);
2634 stop_one_cpu_nowait(rq
->cpu
, push_cpu_stop
,
2639 complete_all(&pending
->done
);
2644 if (!(flags
& SCA_MIGRATE_ENABLE
)) {
2645 /* serialized by p->pi_lock */
2646 if (!p
->migration_pending
) {
2647 /* Install the request */
2648 refcount_set(&my_pending
.refs
, 1);
2649 init_completion(&my_pending
.done
);
2650 my_pending
.arg
= (struct migration_arg
) {
2652 .dest_cpu
= dest_cpu
,
2653 .pending
= &my_pending
,
2656 p
->migration_pending
= &my_pending
;
2658 pending
= p
->migration_pending
;
2659 refcount_inc(&pending
->refs
);
2661 * Affinity has changed, but we've already installed a
2662 * pending. migration_cpu_stop() *must* see this, else
2663 * we risk a completion of the pending despite having a
2664 * task on a disallowed CPU.
2666 * Serialized by p->pi_lock, so this is safe.
2668 pending
->arg
.dest_cpu
= dest_cpu
;
2671 pending
= p
->migration_pending
;
2673 * - !MIGRATE_ENABLE:
2674 * we'll have installed a pending if there wasn't one already.
2677 * we're here because the current CPU isn't matching anymore,
2678 * the only way that can happen is because of a concurrent
2679 * set_cpus_allowed_ptr() call, which should then still be
2680 * pending completion.
2682 * Either way, we really should have a @pending here.
2684 if (WARN_ON_ONCE(!pending
)) {
2685 task_rq_unlock(rq
, p
, rf
);
2689 if (task_running(rq
, p
) || READ_ONCE(p
->__state
) == TASK_WAKING
) {
2691 * MIGRATE_ENABLE gets here because 'p == current', but for
2692 * anything else we cannot do is_migration_disabled(), punt
2693 * and have the stopper function handle it all race-free.
2695 stop_pending
= pending
->stop_pending
;
2697 pending
->stop_pending
= true;
2699 if (flags
& SCA_MIGRATE_ENABLE
)
2700 p
->migration_flags
&= ~MDF_PUSH
;
2702 task_rq_unlock(rq
, p
, rf
);
2704 if (!stop_pending
) {
2705 stop_one_cpu_nowait(cpu_of(rq
), migration_cpu_stop
,
2706 &pending
->arg
, &pending
->stop_work
);
2709 if (flags
& SCA_MIGRATE_ENABLE
)
2713 if (!is_migration_disabled(p
)) {
2714 if (task_on_rq_queued(p
))
2715 rq
= move_queued_task(rq
, rf
, p
, dest_cpu
);
2717 if (!pending
->stop_pending
) {
2718 p
->migration_pending
= NULL
;
2722 task_rq_unlock(rq
, p
, rf
);
2725 complete_all(&pending
->done
);
2728 wait_for_completion(&pending
->done
);
2730 if (refcount_dec_and_test(&pending
->refs
))
2731 wake_up_var(&pending
->refs
); /* No UaF, just an address */
2734 * Block the original owner of &pending until all subsequent callers
2735 * have seen the completion and decremented the refcount
2737 wait_var_event(&my_pending
.refs
, !refcount_read(&my_pending
.refs
));
2740 WARN_ON_ONCE(my_pending
.stop_pending
);
2746 * Called with both p->pi_lock and rq->lock held; drops both before returning.
2748 static int __set_cpus_allowed_ptr_locked(struct task_struct
*p
,
2749 const struct cpumask
*new_mask
,
2752 struct rq_flags
*rf
)
2753 __releases(rq
->lock
)
2754 __releases(p
->pi_lock
)
2756 const struct cpumask
*cpu_allowed_mask
= task_cpu_possible_mask(p
);
2757 const struct cpumask
*cpu_valid_mask
= cpu_active_mask
;
2758 bool kthread
= p
->flags
& PF_KTHREAD
;
2759 struct cpumask
*user_mask
= NULL
;
2760 unsigned int dest_cpu
;
2763 update_rq_clock(rq
);
2765 if (kthread
|| is_migration_disabled(p
)) {
2767 * Kernel threads are allowed on online && !active CPUs,
2768 * however, during cpu-hot-unplug, even these might get pushed
2769 * away if not KTHREAD_IS_PER_CPU.
2771 * Specifically, migration_disabled() tasks must not fail the
2772 * cpumask_any_and_distribute() pick below, esp. so on
2773 * SCA_MIGRATE_ENABLE, otherwise we'll not call
2774 * set_cpus_allowed_common() and actually reset p->cpus_ptr.
2776 cpu_valid_mask
= cpu_online_mask
;
2779 if (!kthread
&& !cpumask_subset(new_mask
, cpu_allowed_mask
)) {
2785 * Must re-check here, to close a race against __kthread_bind(),
2786 * sched_setaffinity() is not guaranteed to observe the flag.
2788 if ((flags
& SCA_CHECK
) && (p
->flags
& PF_NO_SETAFFINITY
)) {
2793 if (!(flags
& SCA_MIGRATE_ENABLE
)) {
2794 if (cpumask_equal(&p
->cpus_mask
, new_mask
))
2797 if (WARN_ON_ONCE(p
== current
&&
2798 is_migration_disabled(p
) &&
2799 !cpumask_test_cpu(task_cpu(p
), new_mask
))) {
2806 * Picking a ~random cpu helps in cases where we are changing affinity
2807 * for groups of tasks (ie. cpuset), so that load balancing is not
2808 * immediately required to distribute the tasks within their new mask.
2810 dest_cpu
= cpumask_any_and_distribute(cpu_valid_mask
, new_mask
);
2811 if (dest_cpu
>= nr_cpu_ids
) {
2816 __do_set_cpus_allowed(p
, new_mask
, flags
);
2818 if (flags
& SCA_USER
)
2819 user_mask
= clear_user_cpus_ptr(p
);
2821 ret
= affine_move_task(rq
, p
, rf
, dest_cpu
, flags
);
2828 task_rq_unlock(rq
, p
, rf
);
2834 * Change a given task's CPU affinity. Migrate the thread to a
2835 * proper CPU and schedule it away if the CPU it's executing on
2836 * is removed from the allowed bitmask.
2838 * NOTE: the caller must have a valid reference to the task, the
2839 * task must not exit() & deallocate itself prematurely. The
2840 * call is not atomic; no spinlocks may be held.
2842 static int __set_cpus_allowed_ptr(struct task_struct
*p
,
2843 const struct cpumask
*new_mask
, u32 flags
)
2848 rq
= task_rq_lock(p
, &rf
);
2849 return __set_cpus_allowed_ptr_locked(p
, new_mask
, flags
, rq
, &rf
);
2852 int set_cpus_allowed_ptr(struct task_struct
*p
, const struct cpumask
*new_mask
)
2854 return __set_cpus_allowed_ptr(p
, new_mask
, 0);
2856 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr
);
2859 * Change a given task's CPU affinity to the intersection of its current
2860 * affinity mask and @subset_mask, writing the resulting mask to @new_mask
2861 * and pointing @p->user_cpus_ptr to a copy of the old mask.
2862 * If the resulting mask is empty, leave the affinity unchanged and return
2865 static int restrict_cpus_allowed_ptr(struct task_struct
*p
,
2866 struct cpumask
*new_mask
,
2867 const struct cpumask
*subset_mask
)
2869 struct cpumask
*user_mask
= NULL
;
2874 if (!p
->user_cpus_ptr
) {
2875 user_mask
= kmalloc(cpumask_size(), GFP_KERNEL
);
2880 rq
= task_rq_lock(p
, &rf
);
2883 * Forcefully restricting the affinity of a deadline task is
2884 * likely to cause problems, so fail and noisily override the
2887 if (task_has_dl_policy(p
) && dl_bandwidth_enabled()) {
2892 if (!cpumask_and(new_mask
, &p
->cpus_mask
, subset_mask
)) {
2898 * We're about to butcher the task affinity, so keep track of what
2899 * the user asked for in case we're able to restore it later on.
2902 cpumask_copy(user_mask
, p
->cpus_ptr
);
2903 p
->user_cpus_ptr
= user_mask
;
2906 return __set_cpus_allowed_ptr_locked(p
, new_mask
, 0, rq
, &rf
);
2909 task_rq_unlock(rq
, p
, &rf
);
2915 * Restrict the CPU affinity of task @p so that it is a subset of
2916 * task_cpu_possible_mask() and point @p->user_cpu_ptr to a copy of the
2917 * old affinity mask. If the resulting mask is empty, we warn and walk
2918 * up the cpuset hierarchy until we find a suitable mask.
2920 void force_compatible_cpus_allowed_ptr(struct task_struct
*p
)
2922 cpumask_var_t new_mask
;
2923 const struct cpumask
*override_mask
= task_cpu_possible_mask(p
);
2925 alloc_cpumask_var(&new_mask
, GFP_KERNEL
);
2928 * __migrate_task() can fail silently in the face of concurrent
2929 * offlining of the chosen destination CPU, so take the hotplug
2930 * lock to ensure that the migration succeeds.
2933 if (!cpumask_available(new_mask
))
2936 if (!restrict_cpus_allowed_ptr(p
, new_mask
, override_mask
))
2940 * We failed to find a valid subset of the affinity mask for the
2941 * task, so override it based on its cpuset hierarchy.
2943 cpuset_cpus_allowed(p
, new_mask
);
2944 override_mask
= new_mask
;
2947 if (printk_ratelimit()) {
2948 printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n",
2949 task_pid_nr(p
), p
->comm
,
2950 cpumask_pr_args(override_mask
));
2953 WARN_ON(set_cpus_allowed_ptr(p
, override_mask
));
2956 free_cpumask_var(new_mask
);
2960 __sched_setaffinity(struct task_struct
*p
, const struct cpumask
*mask
);
2963 * Restore the affinity of a task @p which was previously restricted by a
2964 * call to force_compatible_cpus_allowed_ptr(). This will clear (and free)
2965 * @p->user_cpus_ptr.
2967 * It is the caller's responsibility to serialise this with any calls to
2968 * force_compatible_cpus_allowed_ptr(@p).
2970 void relax_compatible_cpus_allowed_ptr(struct task_struct
*p
)
2972 struct cpumask
*user_mask
= p
->user_cpus_ptr
;
2973 unsigned long flags
;
2976 * Try to restore the old affinity mask. If this fails, then
2977 * we free the mask explicitly to avoid it being inherited across
2978 * a subsequent fork().
2980 if (!user_mask
|| !__sched_setaffinity(p
, user_mask
))
2983 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
2984 user_mask
= clear_user_cpus_ptr(p
);
2985 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2990 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
2992 #ifdef CONFIG_SCHED_DEBUG
2993 unsigned int state
= READ_ONCE(p
->__state
);
2996 * We should never call set_task_cpu() on a blocked task,
2997 * ttwu() will sort out the placement.
2999 WARN_ON_ONCE(state
!= TASK_RUNNING
&& state
!= TASK_WAKING
&& !p
->on_rq
);
3002 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
3003 * because schedstat_wait_{start,end} rebase migrating task's wait_start
3004 * time relying on p->on_rq.
3006 WARN_ON_ONCE(state
== TASK_RUNNING
&&
3007 p
->sched_class
== &fair_sched_class
&&
3008 (p
->on_rq
&& !task_on_rq_migrating(p
)));
3010 #ifdef CONFIG_LOCKDEP
3012 * The caller should hold either p->pi_lock or rq->lock, when changing
3013 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
3015 * sched_move_task() holds both and thus holding either pins the cgroup,
3018 * Furthermore, all task_rq users should acquire both locks, see
3021 WARN_ON_ONCE(debug_locks
&& !(lockdep_is_held(&p
->pi_lock
) ||
3022 lockdep_is_held(__rq_lockp(task_rq(p
)))));
3025 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
3027 WARN_ON_ONCE(!cpu_online(new_cpu
));
3029 WARN_ON_ONCE(is_migration_disabled(p
));
3032 trace_sched_migrate_task(p
, new_cpu
);
3034 if (task_cpu(p
) != new_cpu
) {
3035 if (p
->sched_class
->migrate_task_rq
)
3036 p
->sched_class
->migrate_task_rq(p
, new_cpu
);
3037 p
->se
.nr_migrations
++;
3039 perf_event_task_migrate(p
);
3042 __set_task_cpu(p
, new_cpu
);
3045 #ifdef CONFIG_NUMA_BALANCING
3046 static void __migrate_swap_task(struct task_struct
*p
, int cpu
)
3048 if (task_on_rq_queued(p
)) {
3049 struct rq
*src_rq
, *dst_rq
;
3050 struct rq_flags srf
, drf
;
3052 src_rq
= task_rq(p
);
3053 dst_rq
= cpu_rq(cpu
);
3055 rq_pin_lock(src_rq
, &srf
);
3056 rq_pin_lock(dst_rq
, &drf
);
3058 deactivate_task(src_rq
, p
, 0);
3059 set_task_cpu(p
, cpu
);
3060 activate_task(dst_rq
, p
, 0);
3061 check_preempt_curr(dst_rq
, p
, 0);
3063 rq_unpin_lock(dst_rq
, &drf
);
3064 rq_unpin_lock(src_rq
, &srf
);
3068 * Task isn't running anymore; make it appear like we migrated
3069 * it before it went to sleep. This means on wakeup we make the
3070 * previous CPU our target instead of where it really is.
3076 struct migration_swap_arg
{
3077 struct task_struct
*src_task
, *dst_task
;
3078 int src_cpu
, dst_cpu
;
3081 static int migrate_swap_stop(void *data
)
3083 struct migration_swap_arg
*arg
= data
;
3084 struct rq
*src_rq
, *dst_rq
;
3087 if (!cpu_active(arg
->src_cpu
) || !cpu_active(arg
->dst_cpu
))
3090 src_rq
= cpu_rq(arg
->src_cpu
);
3091 dst_rq
= cpu_rq(arg
->dst_cpu
);
3093 double_raw_lock(&arg
->src_task
->pi_lock
,
3094 &arg
->dst_task
->pi_lock
);
3095 double_rq_lock(src_rq
, dst_rq
);
3097 if (task_cpu(arg
->dst_task
) != arg
->dst_cpu
)
3100 if (task_cpu(arg
->src_task
) != arg
->src_cpu
)
3103 if (!cpumask_test_cpu(arg
->dst_cpu
, arg
->src_task
->cpus_ptr
))
3106 if (!cpumask_test_cpu(arg
->src_cpu
, arg
->dst_task
->cpus_ptr
))
3109 __migrate_swap_task(arg
->src_task
, arg
->dst_cpu
);
3110 __migrate_swap_task(arg
->dst_task
, arg
->src_cpu
);
3115 double_rq_unlock(src_rq
, dst_rq
);
3116 raw_spin_unlock(&arg
->dst_task
->pi_lock
);
3117 raw_spin_unlock(&arg
->src_task
->pi_lock
);
3123 * Cross migrate two tasks
3125 int migrate_swap(struct task_struct
*cur
, struct task_struct
*p
,
3126 int target_cpu
, int curr_cpu
)
3128 struct migration_swap_arg arg
;
3131 arg
= (struct migration_swap_arg
){
3133 .src_cpu
= curr_cpu
,
3135 .dst_cpu
= target_cpu
,
3138 if (arg
.src_cpu
== arg
.dst_cpu
)
3142 * These three tests are all lockless; this is OK since all of them
3143 * will be re-checked with proper locks held further down the line.
3145 if (!cpu_active(arg
.src_cpu
) || !cpu_active(arg
.dst_cpu
))
3148 if (!cpumask_test_cpu(arg
.dst_cpu
, arg
.src_task
->cpus_ptr
))
3151 if (!cpumask_test_cpu(arg
.src_cpu
, arg
.dst_task
->cpus_ptr
))
3154 trace_sched_swap_numa(cur
, arg
.src_cpu
, p
, arg
.dst_cpu
);
3155 ret
= stop_two_cpus(arg
.dst_cpu
, arg
.src_cpu
, migrate_swap_stop
, &arg
);
3160 #endif /* CONFIG_NUMA_BALANCING */
3163 * wait_task_inactive - wait for a thread to unschedule.
3165 * If @match_state is nonzero, it's the @p->state value just checked and
3166 * not expected to change. If it changes, i.e. @p might have woken up,
3167 * then return zero. When we succeed in waiting for @p to be off its CPU,
3168 * we return a positive number (its total switch count). If a second call
3169 * a short while later returns the same number, the caller can be sure that
3170 * @p has remained unscheduled the whole time.
3172 * The caller must ensure that the task *will* unschedule sometime soon,
3173 * else this function might spin for a *long* time. This function can't
3174 * be called with interrupts off, or it may introduce deadlock with
3175 * smp_call_function() if an IPI is sent by the same process we are
3176 * waiting to become inactive.
3178 unsigned long wait_task_inactive(struct task_struct
*p
, unsigned int match_state
)
3180 int running
, queued
;
3187 * We do the initial early heuristics without holding
3188 * any task-queue locks at all. We'll only try to get
3189 * the runqueue lock when things look like they will
3195 * If the task is actively running on another CPU
3196 * still, just relax and busy-wait without holding
3199 * NOTE! Since we don't hold any locks, it's not
3200 * even sure that "rq" stays as the right runqueue!
3201 * But we don't care, since "task_running()" will
3202 * return false if the runqueue has changed and p
3203 * is actually now running somewhere else!
3205 while (task_running(rq
, p
)) {
3206 if (match_state
&& unlikely(READ_ONCE(p
->__state
) != match_state
))
3212 * Ok, time to look more closely! We need the rq
3213 * lock now, to be *sure*. If we're wrong, we'll
3214 * just go back and repeat.
3216 rq
= task_rq_lock(p
, &rf
);
3217 trace_sched_wait_task(p
);
3218 running
= task_running(rq
, p
);
3219 queued
= task_on_rq_queued(p
);
3221 if (!match_state
|| READ_ONCE(p
->__state
) == match_state
)
3222 ncsw
= p
->nvcsw
| LONG_MIN
; /* sets MSB */
3223 task_rq_unlock(rq
, p
, &rf
);
3226 * If it changed from the expected state, bail out now.
3228 if (unlikely(!ncsw
))
3232 * Was it really running after all now that we
3233 * checked with the proper locks actually held?
3235 * Oops. Go back and try again..
3237 if (unlikely(running
)) {
3243 * It's not enough that it's not actively running,
3244 * it must be off the runqueue _entirely_, and not
3247 * So if it was still runnable (but just not actively
3248 * running right now), it's preempted, and we should
3249 * yield - it could be a while.
3251 if (unlikely(queued
)) {
3252 ktime_t to
= NSEC_PER_SEC
/ HZ
;
3254 set_current_state(TASK_UNINTERRUPTIBLE
);
3255 schedule_hrtimeout(&to
, HRTIMER_MODE_REL
);
3260 * Ahh, all good. It wasn't running, and it wasn't
3261 * runnable, which means that it will never become
3262 * running in the future either. We're all done!
3271 * kick_process - kick a running thread to enter/exit the kernel
3272 * @p: the to-be-kicked thread
3274 * Cause a process which is running on another CPU to enter
3275 * kernel-mode, without any delay. (to get signals handled.)
3277 * NOTE: this function doesn't have to take the runqueue lock,
3278 * because all it wants to ensure is that the remote task enters
3279 * the kernel. If the IPI races and the task has been migrated
3280 * to another CPU then no harm is done and the purpose has been
3283 void kick_process(struct task_struct
*p
)
3289 if ((cpu
!= smp_processor_id()) && task_curr(p
))
3290 smp_send_reschedule(cpu
);
3293 EXPORT_SYMBOL_GPL(kick_process
);
3296 * ->cpus_ptr is protected by both rq->lock and p->pi_lock
3298 * A few notes on cpu_active vs cpu_online:
3300 * - cpu_active must be a subset of cpu_online
3302 * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
3303 * see __set_cpus_allowed_ptr(). At this point the newly online
3304 * CPU isn't yet part of the sched domains, and balancing will not
3307 * - on CPU-down we clear cpu_active() to mask the sched domains and
3308 * avoid the load balancer to place new tasks on the to be removed
3309 * CPU. Existing tasks will remain running there and will be taken
3312 * This means that fallback selection must not select !active CPUs.
3313 * And can assume that any active CPU must be online. Conversely
3314 * select_task_rq() below may allow selection of !active CPUs in order
3315 * to satisfy the above rules.
3317 static int select_fallback_rq(int cpu
, struct task_struct
*p
)
3319 int nid
= cpu_to_node(cpu
);
3320 const struct cpumask
*nodemask
= NULL
;
3321 enum { cpuset
, possible
, fail
} state
= cpuset
;
3325 * If the node that the CPU is on has been offlined, cpu_to_node()
3326 * will return -1. There is no CPU on the node, and we should
3327 * select the CPU on the other node.
3330 nodemask
= cpumask_of_node(nid
);
3332 /* Look for allowed, online CPU in same node. */
3333 for_each_cpu(dest_cpu
, nodemask
) {
3334 if (is_cpu_allowed(p
, dest_cpu
))
3340 /* Any allowed, online CPU? */
3341 for_each_cpu(dest_cpu
, p
->cpus_ptr
) {
3342 if (!is_cpu_allowed(p
, dest_cpu
))
3348 /* No more Mr. Nice Guy. */
3351 if (cpuset_cpus_allowed_fallback(p
)) {
3358 * XXX When called from select_task_rq() we only
3359 * hold p->pi_lock and again violate locking order.
3361 * More yuck to audit.
3363 do_set_cpus_allowed(p
, task_cpu_possible_mask(p
));
3373 if (state
!= cpuset
) {
3375 * Don't tell them about moving exiting tasks or
3376 * kernel threads (both mm NULL), since they never
3379 if (p
->mm
&& printk_ratelimit()) {
3380 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
3381 task_pid_nr(p
), p
->comm
, cpu
);
3389 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
3392 int select_task_rq(struct task_struct
*p
, int cpu
, int wake_flags
)
3394 lockdep_assert_held(&p
->pi_lock
);
3396 if (p
->nr_cpus_allowed
> 1 && !is_migration_disabled(p
))
3397 cpu
= p
->sched_class
->select_task_rq(p
, cpu
, wake_flags
);
3399 cpu
= cpumask_any(p
->cpus_ptr
);
3402 * In order not to call set_task_cpu() on a blocking task we need
3403 * to rely on ttwu() to place the task on a valid ->cpus_ptr
3406 * Since this is common to all placement strategies, this lives here.
3408 * [ this allows ->select_task() to simply return task_cpu(p) and
3409 * not worry about this generic constraint ]
3411 if (unlikely(!is_cpu_allowed(p
, cpu
)))
3412 cpu
= select_fallback_rq(task_cpu(p
), p
);
3417 void sched_set_stop_task(int cpu
, struct task_struct
*stop
)
3419 static struct lock_class_key stop_pi_lock
;
3420 struct sched_param param
= { .sched_priority
= MAX_RT_PRIO
- 1 };
3421 struct task_struct
*old_stop
= cpu_rq(cpu
)->stop
;
3425 * Make it appear like a SCHED_FIFO task, its something
3426 * userspace knows about and won't get confused about.
3428 * Also, it will make PI more or less work without too
3429 * much confusion -- but then, stop work should not
3430 * rely on PI working anyway.
3432 sched_setscheduler_nocheck(stop
, SCHED_FIFO
, ¶m
);
3434 stop
->sched_class
= &stop_sched_class
;
3437 * The PI code calls rt_mutex_setprio() with ->pi_lock held to
3438 * adjust the effective priority of a task. As a result,
3439 * rt_mutex_setprio() can trigger (RT) balancing operations,
3440 * which can then trigger wakeups of the stop thread to push
3441 * around the current task.
3443 * The stop task itself will never be part of the PI-chain, it
3444 * never blocks, therefore that ->pi_lock recursion is safe.
3445 * Tell lockdep about this by placing the stop->pi_lock in its
3448 lockdep_set_class(&stop
->pi_lock
, &stop_pi_lock
);
3451 cpu_rq(cpu
)->stop
= stop
;
3455 * Reset it back to a normal scheduling class so that
3456 * it can die in pieces.
3458 old_stop
->sched_class
= &rt_sched_class
;
3462 #else /* CONFIG_SMP */
3464 static inline int __set_cpus_allowed_ptr(struct task_struct
*p
,
3465 const struct cpumask
*new_mask
,
3468 return set_cpus_allowed_ptr(p
, new_mask
);
3471 static inline void migrate_disable_switch(struct rq
*rq
, struct task_struct
*p
) { }
3473 static inline bool rq_has_pinned_tasks(struct rq
*rq
)
3478 #endif /* !CONFIG_SMP */
3481 ttwu_stat(struct task_struct
*p
, int cpu
, int wake_flags
)
3485 if (!schedstat_enabled())
3491 if (cpu
== rq
->cpu
) {
3492 __schedstat_inc(rq
->ttwu_local
);
3493 __schedstat_inc(p
->se
.statistics
.nr_wakeups_local
);
3495 struct sched_domain
*sd
;
3497 __schedstat_inc(p
->se
.statistics
.nr_wakeups_remote
);
3499 for_each_domain(rq
->cpu
, sd
) {
3500 if (cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
3501 __schedstat_inc(sd
->ttwu_wake_remote
);
3508 if (wake_flags
& WF_MIGRATED
)
3509 __schedstat_inc(p
->se
.statistics
.nr_wakeups_migrate
);
3510 #endif /* CONFIG_SMP */
3512 __schedstat_inc(rq
->ttwu_count
);
3513 __schedstat_inc(p
->se
.statistics
.nr_wakeups
);
3515 if (wake_flags
& WF_SYNC
)
3516 __schedstat_inc(p
->se
.statistics
.nr_wakeups_sync
);
3520 * Mark the task runnable and perform wakeup-preemption.
3522 static void ttwu_do_wakeup(struct rq
*rq
, struct task_struct
*p
, int wake_flags
,
3523 struct rq_flags
*rf
)
3525 check_preempt_curr(rq
, p
, wake_flags
);
3526 WRITE_ONCE(p
->__state
, TASK_RUNNING
);
3527 trace_sched_wakeup(p
);
3530 if (p
->sched_class
->task_woken
) {
3532 * Our task @p is fully woken up and running; so it's safe to
3533 * drop the rq->lock, hereafter rq is only used for statistics.
3535 rq_unpin_lock(rq
, rf
);
3536 p
->sched_class
->task_woken(rq
, p
);
3537 rq_repin_lock(rq
, rf
);
3540 if (rq
->idle_stamp
) {
3541 u64 delta
= rq_clock(rq
) - rq
->idle_stamp
;
3542 u64 max
= 2*rq
->max_idle_balance_cost
;
3544 update_avg(&rq
->avg_idle
, delta
);
3546 if (rq
->avg_idle
> max
)
3549 rq
->wake_stamp
= jiffies
;
3550 rq
->wake_avg_idle
= rq
->avg_idle
/ 2;
3558 ttwu_do_activate(struct rq
*rq
, struct task_struct
*p
, int wake_flags
,
3559 struct rq_flags
*rf
)
3561 int en_flags
= ENQUEUE_WAKEUP
| ENQUEUE_NOCLOCK
;
3563 lockdep_assert_rq_held(rq
);
3565 if (p
->sched_contributes_to_load
)
3566 rq
->nr_uninterruptible
--;
3569 if (wake_flags
& WF_MIGRATED
)
3570 en_flags
|= ENQUEUE_MIGRATED
;
3574 delayacct_blkio_end(p
);
3575 atomic_dec(&task_rq(p
)->nr_iowait
);
3578 activate_task(rq
, p
, en_flags
);
3579 ttwu_do_wakeup(rq
, p
, wake_flags
, rf
);
3583 * Consider @p being inside a wait loop:
3586 * set_current_state(TASK_UNINTERRUPTIBLE);
3593 * __set_current_state(TASK_RUNNING);
3595 * between set_current_state() and schedule(). In this case @p is still
3596 * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
3599 * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
3600 * then schedule() must still happen and p->state can be changed to
3601 * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
3602 * need to do a full wakeup with enqueue.
3604 * Returns: %true when the wakeup is done,
3607 static int ttwu_runnable(struct task_struct
*p
, int wake_flags
)
3613 rq
= __task_rq_lock(p
, &rf
);
3614 if (task_on_rq_queued(p
)) {
3615 /* check_preempt_curr() may use rq clock */
3616 update_rq_clock(rq
);
3617 ttwu_do_wakeup(rq
, p
, wake_flags
, &rf
);
3620 __task_rq_unlock(rq
, &rf
);
3626 void sched_ttwu_pending(void *arg
)
3628 struct llist_node
*llist
= arg
;
3629 struct rq
*rq
= this_rq();
3630 struct task_struct
*p
, *t
;
3637 * rq::ttwu_pending racy indication of out-standing wakeups.
3638 * Races such that false-negatives are possible, since they
3639 * are shorter lived that false-positives would be.
3641 WRITE_ONCE(rq
->ttwu_pending
, 0);
3643 rq_lock_irqsave(rq
, &rf
);
3644 update_rq_clock(rq
);
3646 llist_for_each_entry_safe(p
, t
, llist
, wake_entry
.llist
) {
3647 if (WARN_ON_ONCE(p
->on_cpu
))
3648 smp_cond_load_acquire(&p
->on_cpu
, !VAL
);
3650 if (WARN_ON_ONCE(task_cpu(p
) != cpu_of(rq
)))
3651 set_task_cpu(p
, cpu_of(rq
));
3653 ttwu_do_activate(rq
, p
, p
->sched_remote_wakeup
? WF_MIGRATED
: 0, &rf
);
3656 rq_unlock_irqrestore(rq
, &rf
);
3659 void send_call_function_single_ipi(int cpu
)
3661 struct rq
*rq
= cpu_rq(cpu
);
3663 if (!set_nr_if_polling(rq
->idle
))
3664 arch_send_call_function_single_ipi(cpu
);
3666 trace_sched_wake_idle_without_ipi(cpu
);
3670 * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
3671 * necessary. The wakee CPU on receipt of the IPI will queue the task
3672 * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
3673 * of the wakeup instead of the waker.
3675 static void __ttwu_queue_wakelist(struct task_struct
*p
, int cpu
, int wake_flags
)
3677 struct rq
*rq
= cpu_rq(cpu
);
3679 p
->sched_remote_wakeup
= !!(wake_flags
& WF_MIGRATED
);
3681 WRITE_ONCE(rq
->ttwu_pending
, 1);
3682 __smp_call_single_queue(cpu
, &p
->wake_entry
.llist
);
3685 void wake_up_if_idle(int cpu
)
3687 struct rq
*rq
= cpu_rq(cpu
);
3692 if (!is_idle_task(rcu_dereference(rq
->curr
)))
3695 if (set_nr_if_polling(rq
->idle
)) {
3696 trace_sched_wake_idle_without_ipi(cpu
);
3698 rq_lock_irqsave(rq
, &rf
);
3699 if (is_idle_task(rq
->curr
))
3700 smp_send_reschedule(cpu
);
3701 /* Else CPU is not idle, do nothing here: */
3702 rq_unlock_irqrestore(rq
, &rf
);
3709 bool cpus_share_cache(int this_cpu
, int that_cpu
)
3711 if (this_cpu
== that_cpu
)
3714 return per_cpu(sd_llc_id
, this_cpu
) == per_cpu(sd_llc_id
, that_cpu
);
3717 static inline bool ttwu_queue_cond(int cpu
, int wake_flags
)
3720 * Do not complicate things with the async wake_list while the CPU is
3723 if (!cpu_active(cpu
))
3727 * If the CPU does not share cache, then queue the task on the
3728 * remote rqs wakelist to avoid accessing remote data.
3730 if (!cpus_share_cache(smp_processor_id(), cpu
))
3734 * If the task is descheduling and the only running task on the
3735 * CPU then use the wakelist to offload the task activation to
3736 * the soon-to-be-idle CPU as the current CPU is likely busy.
3737 * nr_running is checked to avoid unnecessary task stacking.
3739 if ((wake_flags
& WF_ON_CPU
) && cpu_rq(cpu
)->nr_running
<= 1)
3745 static bool ttwu_queue_wakelist(struct task_struct
*p
, int cpu
, int wake_flags
)
3747 if (sched_feat(TTWU_QUEUE
) && ttwu_queue_cond(cpu
, wake_flags
)) {
3748 if (WARN_ON_ONCE(cpu
== smp_processor_id()))
3751 sched_clock_cpu(cpu
); /* Sync clocks across CPUs */
3752 __ttwu_queue_wakelist(p
, cpu
, wake_flags
);
3759 #else /* !CONFIG_SMP */
3761 static inline bool ttwu_queue_wakelist(struct task_struct
*p
, int cpu
, int wake_flags
)
3766 #endif /* CONFIG_SMP */
3768 static void ttwu_queue(struct task_struct
*p
, int cpu
, int wake_flags
)
3770 struct rq
*rq
= cpu_rq(cpu
);
3773 if (ttwu_queue_wakelist(p
, cpu
, wake_flags
))
3777 update_rq_clock(rq
);
3778 ttwu_do_activate(rq
, p
, wake_flags
, &rf
);
3783 * Invoked from try_to_wake_up() to check whether the task can be woken up.
3785 * The caller holds p::pi_lock if p != current or has preemption
3786 * disabled when p == current.
3788 * The rules of PREEMPT_RT saved_state:
3790 * The related locking code always holds p::pi_lock when updating
3791 * p::saved_state, which means the code is fully serialized in both cases.
3793 * The lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. No other
3794 * bits set. This allows to distinguish all wakeup scenarios.
3796 static __always_inline
3797 bool ttwu_state_match(struct task_struct
*p
, unsigned int state
, int *success
)
3799 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT
)) {
3800 WARN_ON_ONCE((state
& TASK_RTLOCK_WAIT
) &&
3801 state
!= TASK_RTLOCK_WAIT
);
3804 if (READ_ONCE(p
->__state
) & state
) {
3809 #ifdef CONFIG_PREEMPT_RT
3811 * Saved state preserves the task state across blocking on
3812 * an RT lock. If the state matches, set p::saved_state to
3813 * TASK_RUNNING, but do not wake the task because it waits
3814 * for a lock wakeup. Also indicate success because from
3815 * the regular waker's point of view this has succeeded.
3817 * After acquiring the lock the task will restore p::__state
3818 * from p::saved_state which ensures that the regular
3819 * wakeup is not lost. The restore will also set
3820 * p::saved_state to TASK_RUNNING so any further tests will
3821 * not result in false positives vs. @success
3823 if (p
->saved_state
& state
) {
3824 p
->saved_state
= TASK_RUNNING
;
3832 * Notes on Program-Order guarantees on SMP systems.
3836 * The basic program-order guarantee on SMP systems is that when a task [t]
3837 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
3838 * execution on its new CPU [c1].
3840 * For migration (of runnable tasks) this is provided by the following means:
3842 * A) UNLOCK of the rq(c0)->lock scheduling out task t
3843 * B) migration for t is required to synchronize *both* rq(c0)->lock and
3844 * rq(c1)->lock (if not at the same time, then in that order).
3845 * C) LOCK of the rq(c1)->lock scheduling in task
3847 * Release/acquire chaining guarantees that B happens after A and C after B.
3848 * Note: the CPU doing B need not be c0 or c1
3857 * UNLOCK rq(0)->lock
3859 * LOCK rq(0)->lock // orders against CPU0
3861 * UNLOCK rq(0)->lock
3865 * UNLOCK rq(1)->lock
3867 * LOCK rq(1)->lock // orders against CPU2
3870 * UNLOCK rq(1)->lock
3873 * BLOCKING -- aka. SLEEP + WAKEUP
3875 * For blocking we (obviously) need to provide the same guarantee as for
3876 * migration. However the means are completely different as there is no lock
3877 * chain to provide order. Instead we do:
3879 * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
3880 * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
3884 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
3886 * LOCK rq(0)->lock LOCK X->pi_lock
3889 * smp_store_release(X->on_cpu, 0);
3891 * smp_cond_load_acquire(&X->on_cpu, !VAL);
3897 * X->state = RUNNING
3898 * UNLOCK rq(2)->lock
3900 * LOCK rq(2)->lock // orders against CPU1
3903 * UNLOCK rq(2)->lock
3906 * UNLOCK rq(0)->lock
3909 * However, for wakeups there is a second guarantee we must provide, namely we
3910 * must ensure that CONDITION=1 done by the caller can not be reordered with
3911 * accesses to the task state; see try_to_wake_up() and set_current_state().
3915 * try_to_wake_up - wake up a thread
3916 * @p: the thread to be awakened
3917 * @state: the mask of task states that can be woken
3918 * @wake_flags: wake modifier flags (WF_*)
3920 * Conceptually does:
3922 * If (@state & @p->state) @p->state = TASK_RUNNING.
3924 * If the task was not queued/runnable, also place it back on a runqueue.
3926 * This function is atomic against schedule() which would dequeue the task.
3928 * It issues a full memory barrier before accessing @p->state, see the comment
3929 * with set_current_state().
3931 * Uses p->pi_lock to serialize against concurrent wake-ups.
3933 * Relies on p->pi_lock stabilizing:
3936 * - p->sched_task_group
3937 * in order to do migration, see its use of select_task_rq()/set_task_cpu().
3939 * Tries really hard to only take one task_rq(p)->lock for performance.
3940 * Takes rq->lock in:
3941 * - ttwu_runnable() -- old rq, unavoidable, see comment there;
3942 * - ttwu_queue() -- new rq, for enqueue of the task;
3943 * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
3945 * As a consequence we race really badly with just about everything. See the
3946 * many memory barriers and their comments for details.
3948 * Return: %true if @p->state changes (an actual wakeup was done),
3952 try_to_wake_up(struct task_struct
*p
, unsigned int state
, int wake_flags
)
3954 unsigned long flags
;
3955 int cpu
, success
= 0;
3960 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
3961 * == smp_processor_id()'. Together this means we can special
3962 * case the whole 'p->on_rq && ttwu_runnable()' case below
3963 * without taking any locks.
3966 * - we rely on Program-Order guarantees for all the ordering,
3967 * - we're serialized against set_special_state() by virtue of
3968 * it disabling IRQs (this allows not taking ->pi_lock).
3970 if (!ttwu_state_match(p
, state
, &success
))
3973 trace_sched_waking(p
);
3974 WRITE_ONCE(p
->__state
, TASK_RUNNING
);
3975 trace_sched_wakeup(p
);
3980 * If we are going to wake up a thread waiting for CONDITION we
3981 * need to ensure that CONDITION=1 done by the caller can not be
3982 * reordered with p->state check below. This pairs with smp_store_mb()
3983 * in set_current_state() that the waiting thread does.
3985 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
3986 smp_mb__after_spinlock();
3987 if (!ttwu_state_match(p
, state
, &success
))
3990 trace_sched_waking(p
);
3993 * Ensure we load p->on_rq _after_ p->state, otherwise it would
3994 * be possible to, falsely, observe p->on_rq == 0 and get stuck
3995 * in smp_cond_load_acquire() below.
3997 * sched_ttwu_pending() try_to_wake_up()
3998 * STORE p->on_rq = 1 LOAD p->state
4001 * __schedule() (switch to task 'p')
4002 * LOCK rq->lock smp_rmb();
4003 * smp_mb__after_spinlock();
4007 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
4009 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4010 * __schedule(). See the comment for smp_mb__after_spinlock().
4012 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
4015 if (READ_ONCE(p
->on_rq
) && ttwu_runnable(p
, wake_flags
))
4020 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
4021 * possible to, falsely, observe p->on_cpu == 0.
4023 * One must be running (->on_cpu == 1) in order to remove oneself
4024 * from the runqueue.
4026 * __schedule() (switch to task 'p') try_to_wake_up()
4027 * STORE p->on_cpu = 1 LOAD p->on_rq
4030 * __schedule() (put 'p' to sleep)
4031 * LOCK rq->lock smp_rmb();
4032 * smp_mb__after_spinlock();
4033 * STORE p->on_rq = 0 LOAD p->on_cpu
4035 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4036 * __schedule(). See the comment for smp_mb__after_spinlock().
4038 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
4039 * schedule()'s deactivate_task() has 'happened' and p will no longer
4040 * care about it's own p->state. See the comment in __schedule().
4042 smp_acquire__after_ctrl_dep();
4045 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
4046 * == 0), which means we need to do an enqueue, change p->state to
4047 * TASK_WAKING such that we can unlock p->pi_lock before doing the
4048 * enqueue, such as ttwu_queue_wakelist().
4050 WRITE_ONCE(p
->__state
, TASK_WAKING
);
4053 * If the owning (remote) CPU is still in the middle of schedule() with
4054 * this task as prev, considering queueing p on the remote CPUs wake_list
4055 * which potentially sends an IPI instead of spinning on p->on_cpu to
4056 * let the waker make forward progress. This is safe because IRQs are
4057 * disabled and the IPI will deliver after on_cpu is cleared.
4059 * Ensure we load task_cpu(p) after p->on_cpu:
4061 * set_task_cpu(p, cpu);
4062 * STORE p->cpu = @cpu
4063 * __schedule() (switch to task 'p')
4065 * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
4066 * STORE p->on_cpu = 1 LOAD p->cpu
4068 * to ensure we observe the correct CPU on which the task is currently
4071 if (smp_load_acquire(&p
->on_cpu
) &&
4072 ttwu_queue_wakelist(p
, task_cpu(p
), wake_flags
| WF_ON_CPU
))
4076 * If the owning (remote) CPU is still in the middle of schedule() with
4077 * this task as prev, wait until it's done referencing the task.
4079 * Pairs with the smp_store_release() in finish_task().
4081 * This ensures that tasks getting woken will be fully ordered against
4082 * their previous state and preserve Program Order.
4084 smp_cond_load_acquire(&p
->on_cpu
, !VAL
);
4086 cpu
= select_task_rq(p
, p
->wake_cpu
, wake_flags
| WF_TTWU
);
4087 if (task_cpu(p
) != cpu
) {
4089 delayacct_blkio_end(p
);
4090 atomic_dec(&task_rq(p
)->nr_iowait
);
4093 wake_flags
|= WF_MIGRATED
;
4094 psi_ttwu_dequeue(p
);
4095 set_task_cpu(p
, cpu
);
4099 #endif /* CONFIG_SMP */
4101 ttwu_queue(p
, cpu
, wake_flags
);
4103 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4106 ttwu_stat(p
, task_cpu(p
), wake_flags
);
4113 * try_invoke_on_locked_down_task - Invoke a function on task in fixed state
4114 * @p: Process for which the function is to be invoked, can be @current.
4115 * @func: Function to invoke.
4116 * @arg: Argument to function.
4118 * If the specified task can be quickly locked into a definite state
4119 * (either sleeping or on a given runqueue), arrange to keep it in that
4120 * state while invoking @func(@arg). This function can use ->on_rq and
4121 * task_curr() to work out what the state is, if required. Given that
4122 * @func can be invoked with a runqueue lock held, it had better be quite
4126 * @false if the task slipped out from under the locks.
4127 * @true if the task was locked onto a runqueue or is sleeping.
4128 * However, @func can override this by returning @false.
4130 bool try_invoke_on_locked_down_task(struct task_struct
*p
, bool (*func
)(struct task_struct
*t
, void *arg
), void *arg
)
4136 raw_spin_lock_irqsave(&p
->pi_lock
, rf
.flags
);
4138 rq
= __task_rq_lock(p
, &rf
);
4139 if (task_rq(p
) == rq
)
4143 switch (READ_ONCE(p
->__state
)) {
4148 smp_rmb(); // See smp_rmb() comment in try_to_wake_up().
4153 raw_spin_unlock_irqrestore(&p
->pi_lock
, rf
.flags
);
4158 * wake_up_process - Wake up a specific process
4159 * @p: The process to be woken up.
4161 * Attempt to wake up the nominated process and move it to the set of runnable
4164 * Return: 1 if the process was woken up, 0 if it was already running.
4166 * This function executes a full memory barrier before accessing the task state.
4168 int wake_up_process(struct task_struct
*p
)
4170 return try_to_wake_up(p
, TASK_NORMAL
, 0);
4172 EXPORT_SYMBOL(wake_up_process
);
4174 int wake_up_state(struct task_struct
*p
, unsigned int state
)
4176 return try_to_wake_up(p
, state
, 0);
4180 * Perform scheduler related setup for a newly forked process p.
4181 * p is forked by current.
4183 * __sched_fork() is basic setup used by init_idle() too:
4185 static void __sched_fork(unsigned long clone_flags
, struct task_struct
*p
)
4190 p
->se
.exec_start
= 0;
4191 p
->se
.sum_exec_runtime
= 0;
4192 p
->se
.prev_sum_exec_runtime
= 0;
4193 p
->se
.nr_migrations
= 0;
4195 INIT_LIST_HEAD(&p
->se
.group_node
);
4197 #ifdef CONFIG_FAIR_GROUP_SCHED
4198 p
->se
.cfs_rq
= NULL
;
4201 #ifdef CONFIG_SCHEDSTATS
4202 /* Even if schedstat is disabled, there should not be garbage */
4203 memset(&p
->se
.statistics
, 0, sizeof(p
->se
.statistics
));
4206 RB_CLEAR_NODE(&p
->dl
.rb_node
);
4207 init_dl_task_timer(&p
->dl
);
4208 init_dl_inactive_task_timer(&p
->dl
);
4209 __dl_clear_params(p
);
4211 INIT_LIST_HEAD(&p
->rt
.run_list
);
4213 p
->rt
.time_slice
= sched_rr_timeslice
;
4217 #ifdef CONFIG_PREEMPT_NOTIFIERS
4218 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
4221 #ifdef CONFIG_COMPACTION
4222 p
->capture_control
= NULL
;
4224 init_numa_balancing(clone_flags
, p
);
4226 p
->wake_entry
.u_flags
= CSD_TYPE_TTWU
;
4227 p
->migration_pending
= NULL
;
4231 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing
);
4233 #ifdef CONFIG_NUMA_BALANCING
4235 void set_numabalancing_state(bool enabled
)
4238 static_branch_enable(&sched_numa_balancing
);
4240 static_branch_disable(&sched_numa_balancing
);
4243 #ifdef CONFIG_PROC_SYSCTL
4244 int sysctl_numa_balancing(struct ctl_table
*table
, int write
,
4245 void *buffer
, size_t *lenp
, loff_t
*ppos
)
4249 int state
= static_branch_likely(&sched_numa_balancing
);
4251 if (write
&& !capable(CAP_SYS_ADMIN
))
4256 err
= proc_dointvec_minmax(&t
, write
, buffer
, lenp
, ppos
);
4260 set_numabalancing_state(state
);
4266 #ifdef CONFIG_SCHEDSTATS
4268 DEFINE_STATIC_KEY_FALSE(sched_schedstats
);
4270 static void set_schedstats(bool enabled
)
4273 static_branch_enable(&sched_schedstats
);
4275 static_branch_disable(&sched_schedstats
);
4278 void force_schedstat_enabled(void)
4280 if (!schedstat_enabled()) {
4281 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
4282 static_branch_enable(&sched_schedstats
);
4286 static int __init
setup_schedstats(char *str
)
4292 if (!strcmp(str
, "enable")) {
4293 set_schedstats(true);
4295 } else if (!strcmp(str
, "disable")) {
4296 set_schedstats(false);
4301 pr_warn("Unable to parse schedstats=\n");
4305 __setup("schedstats=", setup_schedstats
);
4307 #ifdef CONFIG_PROC_SYSCTL
4308 int sysctl_schedstats(struct ctl_table
*table
, int write
, void *buffer
,
4309 size_t *lenp
, loff_t
*ppos
)
4313 int state
= static_branch_likely(&sched_schedstats
);
4315 if (write
&& !capable(CAP_SYS_ADMIN
))
4320 err
= proc_dointvec_minmax(&t
, write
, buffer
, lenp
, ppos
);
4324 set_schedstats(state
);
4327 #endif /* CONFIG_PROC_SYSCTL */
4328 #endif /* CONFIG_SCHEDSTATS */
4331 * fork()/clone()-time setup:
4333 int sched_fork(unsigned long clone_flags
, struct task_struct
*p
)
4335 __sched_fork(clone_flags
, p
);
4337 * We mark the process as NEW here. This guarantees that
4338 * nobody will actually run it, and a signal or other external
4339 * event cannot wake it up and insert it on the runqueue either.
4341 p
->__state
= TASK_NEW
;
4344 * Make sure we do not leak PI boosting priority to the child.
4346 p
->prio
= current
->normal_prio
;
4351 * Revert to default priority/policy on fork if requested.
4353 if (unlikely(p
->sched_reset_on_fork
)) {
4354 if (task_has_dl_policy(p
) || task_has_rt_policy(p
)) {
4355 p
->policy
= SCHED_NORMAL
;
4356 p
->static_prio
= NICE_TO_PRIO(0);
4358 } else if (PRIO_TO_NICE(p
->static_prio
) < 0)
4359 p
->static_prio
= NICE_TO_PRIO(0);
4361 p
->prio
= p
->normal_prio
= p
->static_prio
;
4362 set_load_weight(p
, false);
4365 * We don't need the reset flag anymore after the fork. It has
4366 * fulfilled its duty:
4368 p
->sched_reset_on_fork
= 0;
4371 if (dl_prio(p
->prio
))
4373 else if (rt_prio(p
->prio
))
4374 p
->sched_class
= &rt_sched_class
;
4376 p
->sched_class
= &fair_sched_class
;
4378 init_entity_runnable_average(&p
->se
);
4381 #ifdef CONFIG_SCHED_INFO
4382 if (likely(sched_info_on()))
4383 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
4385 #if defined(CONFIG_SMP)
4388 init_task_preempt_count(p
);
4390 plist_node_init(&p
->pushable_tasks
, MAX_PRIO
);
4391 RB_CLEAR_NODE(&p
->pushable_dl_tasks
);
4396 void sched_cgroup_fork(struct task_struct
*p
, struct kernel_clone_args
*kargs
)
4398 unsigned long flags
;
4401 * Because we're not yet on the pid-hash, p->pi_lock isn't strictly
4402 * required yet, but lockdep gets upset if rules are violated.
4404 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
4405 #ifdef CONFIG_CGROUP_SCHED
4407 struct task_group
*tg
;
4408 tg
= container_of(kargs
->cset
->subsys
[cpu_cgrp_id
],
4409 struct task_group
, css
);
4410 tg
= autogroup_task_group(p
, tg
);
4411 p
->sched_task_group
= tg
;
4416 * We're setting the CPU for the first time, we don't migrate,
4417 * so use __set_task_cpu().
4419 __set_task_cpu(p
, smp_processor_id());
4420 if (p
->sched_class
->task_fork
)
4421 p
->sched_class
->task_fork(p
);
4422 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4425 void sched_post_fork(struct task_struct
*p
)
4427 uclamp_post_fork(p
);
4430 unsigned long to_ratio(u64 period
, u64 runtime
)
4432 if (runtime
== RUNTIME_INF
)
4436 * Doing this here saves a lot of checks in all
4437 * the calling paths, and returning zero seems
4438 * safe for them anyway.
4443 return div64_u64(runtime
<< BW_SHIFT
, period
);
4447 * wake_up_new_task - wake up a newly created task for the first time.
4449 * This function will do some initial scheduler statistics housekeeping
4450 * that must be done for every newly created context, then puts the task
4451 * on the runqueue and wakes it.
4453 void wake_up_new_task(struct task_struct
*p
)
4458 raw_spin_lock_irqsave(&p
->pi_lock
, rf
.flags
);
4459 WRITE_ONCE(p
->__state
, TASK_RUNNING
);
4462 * Fork balancing, do it here and not earlier because:
4463 * - cpus_ptr can change in the fork path
4464 * - any previously selected CPU might disappear through hotplug
4466 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
4467 * as we're not fully set-up yet.
4469 p
->recent_used_cpu
= task_cpu(p
);
4471 __set_task_cpu(p
, select_task_rq(p
, task_cpu(p
), WF_FORK
));
4473 rq
= __task_rq_lock(p
, &rf
);
4474 update_rq_clock(rq
);
4475 post_init_entity_util_avg(p
);
4477 activate_task(rq
, p
, ENQUEUE_NOCLOCK
);
4478 trace_sched_wakeup_new(p
);
4479 check_preempt_curr(rq
, p
, WF_FORK
);
4481 if (p
->sched_class
->task_woken
) {
4483 * Nothing relies on rq->lock after this, so it's fine to
4486 rq_unpin_lock(rq
, &rf
);
4487 p
->sched_class
->task_woken(rq
, p
);
4488 rq_repin_lock(rq
, &rf
);
4491 task_rq_unlock(rq
, p
, &rf
);
4494 #ifdef CONFIG_PREEMPT_NOTIFIERS
4496 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key
);
4498 void preempt_notifier_inc(void)
4500 static_branch_inc(&preempt_notifier_key
);
4502 EXPORT_SYMBOL_GPL(preempt_notifier_inc
);
4504 void preempt_notifier_dec(void)
4506 static_branch_dec(&preempt_notifier_key
);
4508 EXPORT_SYMBOL_GPL(preempt_notifier_dec
);
4511 * preempt_notifier_register - tell me when current is being preempted & rescheduled
4512 * @notifier: notifier struct to register
4514 void preempt_notifier_register(struct preempt_notifier
*notifier
)
4516 if (!static_branch_unlikely(&preempt_notifier_key
))
4517 WARN(1, "registering preempt_notifier while notifiers disabled\n");
4519 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
4521 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
4524 * preempt_notifier_unregister - no longer interested in preemption notifications
4525 * @notifier: notifier struct to unregister
4527 * This is *not* safe to call from within a preemption notifier.
4529 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
4531 hlist_del(¬ifier
->link
);
4533 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
4535 static void __fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
4537 struct preempt_notifier
*notifier
;
4539 hlist_for_each_entry(notifier
, &curr
->preempt_notifiers
, link
)
4540 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
4543 static __always_inline
void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
4545 if (static_branch_unlikely(&preempt_notifier_key
))
4546 __fire_sched_in_preempt_notifiers(curr
);
4550 __fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
4551 struct task_struct
*next
)
4553 struct preempt_notifier
*notifier
;
4555 hlist_for_each_entry(notifier
, &curr
->preempt_notifiers
, link
)
4556 notifier
->ops
->sched_out(notifier
, next
);
4559 static __always_inline
void
4560 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
4561 struct task_struct
*next
)
4563 if (static_branch_unlikely(&preempt_notifier_key
))
4564 __fire_sched_out_preempt_notifiers(curr
, next
);
4567 #else /* !CONFIG_PREEMPT_NOTIFIERS */
4569 static inline void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
4574 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
4575 struct task_struct
*next
)
4579 #endif /* CONFIG_PREEMPT_NOTIFIERS */
4581 static inline void prepare_task(struct task_struct
*next
)
4585 * Claim the task as running, we do this before switching to it
4586 * such that any running task will have this set.
4588 * See the ttwu() WF_ON_CPU case and its ordering comment.
4590 WRITE_ONCE(next
->on_cpu
, 1);
4594 static inline void finish_task(struct task_struct
*prev
)
4598 * This must be the very last reference to @prev from this CPU. After
4599 * p->on_cpu is cleared, the task can be moved to a different CPU. We
4600 * must ensure this doesn't happen until the switch is completely
4603 * In particular, the load of prev->state in finish_task_switch() must
4604 * happen before this.
4606 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
4608 smp_store_release(&prev
->on_cpu
, 0);
4614 static void do_balance_callbacks(struct rq
*rq
, struct callback_head
*head
)
4616 void (*func
)(struct rq
*rq
);
4617 struct callback_head
*next
;
4619 lockdep_assert_rq_held(rq
);
4622 func
= (void (*)(struct rq
*))head
->func
;
4631 static void balance_push(struct rq
*rq
);
4633 struct callback_head balance_push_callback
= {
4635 .func
= (void (*)(struct callback_head
*))balance_push
,
4638 static inline struct callback_head
*splice_balance_callbacks(struct rq
*rq
)
4640 struct callback_head
*head
= rq
->balance_callback
;
4642 lockdep_assert_rq_held(rq
);
4644 rq
->balance_callback
= NULL
;
4649 static void __balance_callbacks(struct rq
*rq
)
4651 do_balance_callbacks(rq
, splice_balance_callbacks(rq
));
4654 static inline void balance_callbacks(struct rq
*rq
, struct callback_head
*head
)
4656 unsigned long flags
;
4658 if (unlikely(head
)) {
4659 raw_spin_rq_lock_irqsave(rq
, flags
);
4660 do_balance_callbacks(rq
, head
);
4661 raw_spin_rq_unlock_irqrestore(rq
, flags
);
4667 static inline void __balance_callbacks(struct rq
*rq
)
4671 static inline struct callback_head
*splice_balance_callbacks(struct rq
*rq
)
4676 static inline void balance_callbacks(struct rq
*rq
, struct callback_head
*head
)
4683 prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
, struct rq_flags
*rf
)
4686 * Since the runqueue lock will be released by the next
4687 * task (which is an invalid locking op but in the case
4688 * of the scheduler it's an obvious special-case), so we
4689 * do an early lockdep release here:
4691 rq_unpin_lock(rq
, rf
);
4692 spin_release(&__rq_lockp(rq
)->dep_map
, _THIS_IP_
);
4693 #ifdef CONFIG_DEBUG_SPINLOCK
4694 /* this is a valid case when another task releases the spinlock */
4695 rq_lockp(rq
)->owner
= next
;
4699 static inline void finish_lock_switch(struct rq
*rq
)
4702 * If we are tracking spinlock dependencies then we have to
4703 * fix up the runqueue lock - which gets 'carried over' from
4704 * prev into current:
4706 spin_acquire(&__rq_lockp(rq
)->dep_map
, 0, 0, _THIS_IP_
);
4707 __balance_callbacks(rq
);
4708 raw_spin_rq_unlock_irq(rq
);
4712 * NOP if the arch has not defined these:
4715 #ifndef prepare_arch_switch
4716 # define prepare_arch_switch(next) do { } while (0)
4719 #ifndef finish_arch_post_lock_switch
4720 # define finish_arch_post_lock_switch() do { } while (0)
4723 static inline void kmap_local_sched_out(void)
4725 #ifdef CONFIG_KMAP_LOCAL
4726 if (unlikely(current
->kmap_ctrl
.idx
))
4727 __kmap_local_sched_out();
4731 static inline void kmap_local_sched_in(void)
4733 #ifdef CONFIG_KMAP_LOCAL
4734 if (unlikely(current
->kmap_ctrl
.idx
))
4735 __kmap_local_sched_in();
4740 * prepare_task_switch - prepare to switch tasks
4741 * @rq: the runqueue preparing to switch
4742 * @prev: the current task that is being switched out
4743 * @next: the task we are going to switch to.
4745 * This is called with the rq lock held and interrupts off. It must
4746 * be paired with a subsequent finish_task_switch after the context
4749 * prepare_task_switch sets up locking and calls architecture specific
4753 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
4754 struct task_struct
*next
)
4756 kcov_prepare_switch(prev
);
4757 sched_info_switch(rq
, prev
, next
);
4758 perf_event_task_sched_out(prev
, next
);
4760 fire_sched_out_preempt_notifiers(prev
, next
);
4761 kmap_local_sched_out();
4763 prepare_arch_switch(next
);
4767 * finish_task_switch - clean up after a task-switch
4768 * @prev: the thread we just switched away from.
4770 * finish_task_switch must be called after the context switch, paired
4771 * with a prepare_task_switch call before the context switch.
4772 * finish_task_switch will reconcile locking set up by prepare_task_switch,
4773 * and do any other architecture-specific cleanup actions.
4775 * Note that we may have delayed dropping an mm in context_switch(). If
4776 * so, we finish that here outside of the runqueue lock. (Doing it
4777 * with the lock held can cause deadlocks; see schedule() for
4780 * The context switch have flipped the stack from under us and restored the
4781 * local variables which were saved when this task called schedule() in the
4782 * past. prev == current is still correct but we need to recalculate this_rq
4783 * because prev may have moved to another CPU.
4785 static struct rq
*finish_task_switch(struct task_struct
*prev
)
4786 __releases(rq
->lock
)
4788 struct rq
*rq
= this_rq();
4789 struct mm_struct
*mm
= rq
->prev_mm
;
4793 * The previous task will have left us with a preempt_count of 2
4794 * because it left us after:
4797 * preempt_disable(); // 1
4799 * raw_spin_lock_irq(&rq->lock) // 2
4801 * Also, see FORK_PREEMPT_COUNT.
4803 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET
,
4804 "corrupted preempt_count: %s/%d/0x%x\n",
4805 current
->comm
, current
->pid
, preempt_count()))
4806 preempt_count_set(FORK_PREEMPT_COUNT
);
4811 * A task struct has one reference for the use as "current".
4812 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
4813 * schedule one last time. The schedule call will never return, and
4814 * the scheduled task must drop that reference.
4816 * We must observe prev->state before clearing prev->on_cpu (in
4817 * finish_task), otherwise a concurrent wakeup can get prev
4818 * running on another CPU and we could rave with its RUNNING -> DEAD
4819 * transition, resulting in a double drop.
4821 prev_state
= READ_ONCE(prev
->__state
);
4822 vtime_task_switch(prev
);
4823 perf_event_task_sched_in(prev
, current
);
4825 tick_nohz_task_switch();
4826 finish_lock_switch(rq
);
4827 finish_arch_post_lock_switch();
4828 kcov_finish_switch(current
);
4830 * kmap_local_sched_out() is invoked with rq::lock held and
4831 * interrupts disabled. There is no requirement for that, but the
4832 * sched out code does not have an interrupt enabled section.
4833 * Restoring the maps on sched in does not require interrupts being
4836 kmap_local_sched_in();
4838 fire_sched_in_preempt_notifiers(current
);
4840 * When switching through a kernel thread, the loop in
4841 * membarrier_{private,global}_expedited() may have observed that
4842 * kernel thread and not issued an IPI. It is therefore possible to
4843 * schedule between user->kernel->user threads without passing though
4844 * switch_mm(). Membarrier requires a barrier after storing to
4845 * rq->curr, before returning to userspace, so provide them here:
4847 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
4848 * provided by mmdrop(),
4849 * - a sync_core for SYNC_CORE.
4852 membarrier_mm_sync_core_before_usermode(mm
);
4855 if (unlikely(prev_state
== TASK_DEAD
)) {
4856 if (prev
->sched_class
->task_dead
)
4857 prev
->sched_class
->task_dead(prev
);
4860 * Remove function-return probe instances associated with this
4861 * task and put them back on the free list.
4863 kprobe_flush_task(prev
);
4865 /* Task is done with its stack. */
4866 put_task_stack(prev
);
4868 put_task_struct_rcu_user(prev
);
4875 * schedule_tail - first thing a freshly forked thread must call.
4876 * @prev: the thread we just switched away from.
4878 asmlinkage __visible
void schedule_tail(struct task_struct
*prev
)
4879 __releases(rq
->lock
)
4882 * New tasks start with FORK_PREEMPT_COUNT, see there and
4883 * finish_task_switch() for details.
4885 * finish_task_switch() will drop rq->lock() and lower preempt_count
4886 * and the preempt_enable() will end up enabling preemption (on
4887 * PREEMPT_COUNT kernels).
4890 finish_task_switch(prev
);
4893 if (current
->set_child_tid
)
4894 put_user(task_pid_vnr(current
), current
->set_child_tid
);
4896 calculate_sigpending();
4900 * context_switch - switch to the new MM and the new thread's register state.
4902 static __always_inline
struct rq
*
4903 context_switch(struct rq
*rq
, struct task_struct
*prev
,
4904 struct task_struct
*next
, struct rq_flags
*rf
)
4906 prepare_task_switch(rq
, prev
, next
);
4909 * For paravirt, this is coupled with an exit in switch_to to
4910 * combine the page table reload and the switch backend into
4913 arch_start_context_switch(prev
);
4916 * kernel -> kernel lazy + transfer active
4917 * user -> kernel lazy + mmgrab() active
4919 * kernel -> user switch + mmdrop() active
4920 * user -> user switch
4922 if (!next
->mm
) { // to kernel
4923 enter_lazy_tlb(prev
->active_mm
, next
);
4925 next
->active_mm
= prev
->active_mm
;
4926 if (prev
->mm
) // from user
4927 mmgrab(prev
->active_mm
);
4929 prev
->active_mm
= NULL
;
4931 membarrier_switch_mm(rq
, prev
->active_mm
, next
->mm
);
4933 * sys_membarrier() requires an smp_mb() between setting
4934 * rq->curr / membarrier_switch_mm() and returning to userspace.
4936 * The below provides this either through switch_mm(), or in
4937 * case 'prev->active_mm == next->mm' through
4938 * finish_task_switch()'s mmdrop().
4940 switch_mm_irqs_off(prev
->active_mm
, next
->mm
, next
);
4942 if (!prev
->mm
) { // from kernel
4943 /* will mmdrop() in finish_task_switch(). */
4944 rq
->prev_mm
= prev
->active_mm
;
4945 prev
->active_mm
= NULL
;
4949 rq
->clock_update_flags
&= ~(RQCF_ACT_SKIP
|RQCF_REQ_SKIP
);
4951 prepare_lock_switch(rq
, next
, rf
);
4953 /* Here we just switch the register state and the stack. */
4954 switch_to(prev
, next
, prev
);
4957 return finish_task_switch(prev
);
4961 * nr_running and nr_context_switches:
4963 * externally visible scheduler statistics: current number of runnable
4964 * threads, total number of context switches performed since bootup.
4966 unsigned int nr_running(void)
4968 unsigned int i
, sum
= 0;
4970 for_each_online_cpu(i
)
4971 sum
+= cpu_rq(i
)->nr_running
;
4977 * Check if only the current task is running on the CPU.
4979 * Caution: this function does not check that the caller has disabled
4980 * preemption, thus the result might have a time-of-check-to-time-of-use
4981 * race. The caller is responsible to use it correctly, for example:
4983 * - from a non-preemptible section (of course)
4985 * - from a thread that is bound to a single CPU
4987 * - in a loop with very short iterations (e.g. a polling loop)
4989 bool single_task_running(void)
4991 return raw_rq()->nr_running
== 1;
4993 EXPORT_SYMBOL(single_task_running
);
4995 unsigned long long nr_context_switches(void)
4998 unsigned long long sum
= 0;
5000 for_each_possible_cpu(i
)
5001 sum
+= cpu_rq(i
)->nr_switches
;
5007 * Consumers of these two interfaces, like for example the cpuidle menu
5008 * governor, are using nonsensical data. Preferring shallow idle state selection
5009 * for a CPU that has IO-wait which might not even end up running the task when
5010 * it does become runnable.
5013 unsigned int nr_iowait_cpu(int cpu
)
5015 return atomic_read(&cpu_rq(cpu
)->nr_iowait
);
5019 * IO-wait accounting, and how it's mostly bollocks (on SMP).
5021 * The idea behind IO-wait account is to account the idle time that we could
5022 * have spend running if it were not for IO. That is, if we were to improve the
5023 * storage performance, we'd have a proportional reduction in IO-wait time.
5025 * This all works nicely on UP, where, when a task blocks on IO, we account
5026 * idle time as IO-wait, because if the storage were faster, it could've been
5027 * running and we'd not be idle.
5029 * This has been extended to SMP, by doing the same for each CPU. This however
5032 * Imagine for instance the case where two tasks block on one CPU, only the one
5033 * CPU will have IO-wait accounted, while the other has regular idle. Even
5034 * though, if the storage were faster, both could've ran at the same time,
5035 * utilising both CPUs.
5037 * This means, that when looking globally, the current IO-wait accounting on
5038 * SMP is a lower bound, by reason of under accounting.
5040 * Worse, since the numbers are provided per CPU, they are sometimes
5041 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
5042 * associated with any one particular CPU, it can wake to another CPU than it
5043 * blocked on. This means the per CPU IO-wait number is meaningless.
5045 * Task CPU affinities can make all that even more 'interesting'.
5048 unsigned int nr_iowait(void)
5050 unsigned int i
, sum
= 0;
5052 for_each_possible_cpu(i
)
5053 sum
+= nr_iowait_cpu(i
);
5061 * sched_exec - execve() is a valuable balancing opportunity, because at
5062 * this point the task has the smallest effective memory and cache footprint.
5064 void sched_exec(void)
5066 struct task_struct
*p
= current
;
5067 unsigned long flags
;
5070 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
5071 dest_cpu
= p
->sched_class
->select_task_rq(p
, task_cpu(p
), WF_EXEC
);
5072 if (dest_cpu
== smp_processor_id())
5075 if (likely(cpu_active(dest_cpu
))) {
5076 struct migration_arg arg
= { p
, dest_cpu
};
5078 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
5079 stop_one_cpu(task_cpu(p
), migration_cpu_stop
, &arg
);
5083 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
5088 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
5089 DEFINE_PER_CPU(struct kernel_cpustat
, kernel_cpustat
);
5091 EXPORT_PER_CPU_SYMBOL(kstat
);
5092 EXPORT_PER_CPU_SYMBOL(kernel_cpustat
);
5095 * The function fair_sched_class.update_curr accesses the struct curr
5096 * and its field curr->exec_start; when called from task_sched_runtime(),
5097 * we observe a high rate of cache misses in practice.
5098 * Prefetching this data results in improved performance.
5100 static inline void prefetch_curr_exec_start(struct task_struct
*p
)
5102 #ifdef CONFIG_FAIR_GROUP_SCHED
5103 struct sched_entity
*curr
= (&p
->se
)->cfs_rq
->curr
;
5105 struct sched_entity
*curr
= (&task_rq(p
)->cfs
)->curr
;
5108 prefetch(&curr
->exec_start
);
5112 * Return accounted runtime for the task.
5113 * In case the task is currently running, return the runtime plus current's
5114 * pending runtime that have not been accounted yet.
5116 unsigned long long task_sched_runtime(struct task_struct
*p
)
5122 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
5124 * 64-bit doesn't need locks to atomically read a 64-bit value.
5125 * So we have a optimization chance when the task's delta_exec is 0.
5126 * Reading ->on_cpu is racy, but this is ok.
5128 * If we race with it leaving CPU, we'll take a lock. So we're correct.
5129 * If we race with it entering CPU, unaccounted time is 0. This is
5130 * indistinguishable from the read occurring a few cycles earlier.
5131 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
5132 * been accounted, so we're correct here as well.
5134 if (!p
->on_cpu
|| !task_on_rq_queued(p
))
5135 return p
->se
.sum_exec_runtime
;
5138 rq
= task_rq_lock(p
, &rf
);
5140 * Must be ->curr _and_ ->on_rq. If dequeued, we would
5141 * project cycles that may never be accounted to this
5142 * thread, breaking clock_gettime().
5144 if (task_current(rq
, p
) && task_on_rq_queued(p
)) {
5145 prefetch_curr_exec_start(p
);
5146 update_rq_clock(rq
);
5147 p
->sched_class
->update_curr(rq
);
5149 ns
= p
->se
.sum_exec_runtime
;
5150 task_rq_unlock(rq
, p
, &rf
);
5155 #ifdef CONFIG_SCHED_DEBUG
5156 static u64
cpu_resched_latency(struct rq
*rq
)
5158 int latency_warn_ms
= READ_ONCE(sysctl_resched_latency_warn_ms
);
5159 u64 resched_latency
, now
= rq_clock(rq
);
5160 static bool warned_once
;
5162 if (sysctl_resched_latency_warn_once
&& warned_once
)
5165 if (!need_resched() || !latency_warn_ms
)
5168 if (system_state
== SYSTEM_BOOTING
)
5171 if (!rq
->last_seen_need_resched_ns
) {
5172 rq
->last_seen_need_resched_ns
= now
;
5173 rq
->ticks_without_resched
= 0;
5177 rq
->ticks_without_resched
++;
5178 resched_latency
= now
- rq
->last_seen_need_resched_ns
;
5179 if (resched_latency
<= latency_warn_ms
* NSEC_PER_MSEC
)
5184 return resched_latency
;
5187 static int __init
setup_resched_latency_warn_ms(char *str
)
5191 if ((kstrtol(str
, 0, &val
))) {
5192 pr_warn("Unable to set resched_latency_warn_ms\n");
5196 sysctl_resched_latency_warn_ms
= val
;
5199 __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms
);
5201 static inline u64
cpu_resched_latency(struct rq
*rq
) { return 0; }
5202 #endif /* CONFIG_SCHED_DEBUG */
5205 * This function gets called by the timer code, with HZ frequency.
5206 * We call it with interrupts disabled.
5208 void scheduler_tick(void)
5210 int cpu
= smp_processor_id();
5211 struct rq
*rq
= cpu_rq(cpu
);
5212 struct task_struct
*curr
= rq
->curr
;
5214 unsigned long thermal_pressure
;
5215 u64 resched_latency
;
5217 arch_scale_freq_tick();
5222 update_rq_clock(rq
);
5223 thermal_pressure
= arch_scale_thermal_pressure(cpu_of(rq
));
5224 update_thermal_load_avg(rq_clock_thermal(rq
), rq
, thermal_pressure
);
5225 curr
->sched_class
->task_tick(rq
, curr
, 0);
5226 if (sched_feat(LATENCY_WARN
))
5227 resched_latency
= cpu_resched_latency(rq
);
5228 calc_global_load_tick(rq
);
5232 if (sched_feat(LATENCY_WARN
) && resched_latency
)
5233 resched_latency_warn(cpu
, resched_latency
);
5235 perf_event_task_tick();
5238 rq
->idle_balance
= idle_cpu(cpu
);
5239 trigger_load_balance(rq
);
5243 #ifdef CONFIG_NO_HZ_FULL
5248 struct delayed_work work
;
5250 /* Values for ->state, see diagram below. */
5251 #define TICK_SCHED_REMOTE_OFFLINE 0
5252 #define TICK_SCHED_REMOTE_OFFLINING 1
5253 #define TICK_SCHED_REMOTE_RUNNING 2
5256 * State diagram for ->state:
5259 * TICK_SCHED_REMOTE_OFFLINE
5262 * | | sched_tick_remote()
5265 * +--TICK_SCHED_REMOTE_OFFLINING
5268 * sched_tick_start() | | sched_tick_stop()
5271 * TICK_SCHED_REMOTE_RUNNING
5274 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
5275 * and sched_tick_start() are happy to leave the state in RUNNING.
5278 static struct tick_work __percpu
*tick_work_cpu
;
5280 static void sched_tick_remote(struct work_struct
*work
)
5282 struct delayed_work
*dwork
= to_delayed_work(work
);
5283 struct tick_work
*twork
= container_of(dwork
, struct tick_work
, work
);
5284 int cpu
= twork
->cpu
;
5285 struct rq
*rq
= cpu_rq(cpu
);
5286 struct task_struct
*curr
;
5292 * Handle the tick only if it appears the remote CPU is running in full
5293 * dynticks mode. The check is racy by nature, but missing a tick or
5294 * having one too much is no big deal because the scheduler tick updates
5295 * statistics and checks timeslices in a time-independent way, regardless
5296 * of when exactly it is running.
5298 if (!tick_nohz_tick_stopped_cpu(cpu
))
5301 rq_lock_irq(rq
, &rf
);
5303 if (cpu_is_offline(cpu
))
5306 update_rq_clock(rq
);
5308 if (!is_idle_task(curr
)) {
5310 * Make sure the next tick runs within a reasonable
5313 delta
= rq_clock_task(rq
) - curr
->se
.exec_start
;
5314 WARN_ON_ONCE(delta
> (u64
)NSEC_PER_SEC
* 3);
5316 curr
->sched_class
->task_tick(rq
, curr
, 0);
5318 calc_load_nohz_remote(rq
);
5320 rq_unlock_irq(rq
, &rf
);
5324 * Run the remote tick once per second (1Hz). This arbitrary
5325 * frequency is large enough to avoid overload but short enough
5326 * to keep scheduler internal stats reasonably up to date. But
5327 * first update state to reflect hotplug activity if required.
5329 os
= atomic_fetch_add_unless(&twork
->state
, -1, TICK_SCHED_REMOTE_RUNNING
);
5330 WARN_ON_ONCE(os
== TICK_SCHED_REMOTE_OFFLINE
);
5331 if (os
== TICK_SCHED_REMOTE_RUNNING
)
5332 queue_delayed_work(system_unbound_wq
, dwork
, HZ
);
5335 static void sched_tick_start(int cpu
)
5338 struct tick_work
*twork
;
5340 if (housekeeping_cpu(cpu
, HK_FLAG_TICK
))
5343 WARN_ON_ONCE(!tick_work_cpu
);
5345 twork
= per_cpu_ptr(tick_work_cpu
, cpu
);
5346 os
= atomic_xchg(&twork
->state
, TICK_SCHED_REMOTE_RUNNING
);
5347 WARN_ON_ONCE(os
== TICK_SCHED_REMOTE_RUNNING
);
5348 if (os
== TICK_SCHED_REMOTE_OFFLINE
) {
5350 INIT_DELAYED_WORK(&twork
->work
, sched_tick_remote
);
5351 queue_delayed_work(system_unbound_wq
, &twork
->work
, HZ
);
5355 #ifdef CONFIG_HOTPLUG_CPU
5356 static void sched_tick_stop(int cpu
)
5358 struct tick_work
*twork
;
5361 if (housekeeping_cpu(cpu
, HK_FLAG_TICK
))
5364 WARN_ON_ONCE(!tick_work_cpu
);
5366 twork
= per_cpu_ptr(tick_work_cpu
, cpu
);
5367 /* There cannot be competing actions, but don't rely on stop-machine. */
5368 os
= atomic_xchg(&twork
->state
, TICK_SCHED_REMOTE_OFFLINING
);
5369 WARN_ON_ONCE(os
!= TICK_SCHED_REMOTE_RUNNING
);
5370 /* Don't cancel, as this would mess up the state machine. */
5372 #endif /* CONFIG_HOTPLUG_CPU */
5374 int __init
sched_tick_offload_init(void)
5376 tick_work_cpu
= alloc_percpu(struct tick_work
);
5377 BUG_ON(!tick_work_cpu
);
5381 #else /* !CONFIG_NO_HZ_FULL */
5382 static inline void sched_tick_start(int cpu
) { }
5383 static inline void sched_tick_stop(int cpu
) { }
5386 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
5387 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
5389 * If the value passed in is equal to the current preempt count
5390 * then we just disabled preemption. Start timing the latency.
5392 static inline void preempt_latency_start(int val
)
5394 if (preempt_count() == val
) {
5395 unsigned long ip
= get_lock_parent_ip();
5396 #ifdef CONFIG_DEBUG_PREEMPT
5397 current
->preempt_disable_ip
= ip
;
5399 trace_preempt_off(CALLER_ADDR0
, ip
);
5403 void preempt_count_add(int val
)
5405 #ifdef CONFIG_DEBUG_PREEMPT
5409 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5412 __preempt_count_add(val
);
5413 #ifdef CONFIG_DEBUG_PREEMPT
5415 * Spinlock count overflowing soon?
5417 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
5420 preempt_latency_start(val
);
5422 EXPORT_SYMBOL(preempt_count_add
);
5423 NOKPROBE_SYMBOL(preempt_count_add
);
5426 * If the value passed in equals to the current preempt count
5427 * then we just enabled preemption. Stop timing the latency.
5429 static inline void preempt_latency_stop(int val
)
5431 if (preempt_count() == val
)
5432 trace_preempt_on(CALLER_ADDR0
, get_lock_parent_ip());
5435 void preempt_count_sub(int val
)
5437 #ifdef CONFIG_DEBUG_PREEMPT
5441 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
5444 * Is the spinlock portion underflowing?
5446 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
5447 !(preempt_count() & PREEMPT_MASK
)))
5451 preempt_latency_stop(val
);
5452 __preempt_count_sub(val
);
5454 EXPORT_SYMBOL(preempt_count_sub
);
5455 NOKPROBE_SYMBOL(preempt_count_sub
);
5458 static inline void preempt_latency_start(int val
) { }
5459 static inline void preempt_latency_stop(int val
) { }
5462 static inline unsigned long get_preempt_disable_ip(struct task_struct
*p
)
5464 #ifdef CONFIG_DEBUG_PREEMPT
5465 return p
->preempt_disable_ip
;
5472 * Print scheduling while atomic bug:
5474 static noinline
void __schedule_bug(struct task_struct
*prev
)
5476 /* Save this before calling printk(), since that will clobber it */
5477 unsigned long preempt_disable_ip
= get_preempt_disable_ip(current
);
5479 if (oops_in_progress
)
5482 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
5483 prev
->comm
, prev
->pid
, preempt_count());
5485 debug_show_held_locks(prev
);
5487 if (irqs_disabled())
5488 print_irqtrace_events(prev
);
5489 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT
)
5490 && in_atomic_preempt_off()) {
5491 pr_err("Preemption disabled at:");
5492 print_ip_sym(KERN_ERR
, preempt_disable_ip
);
5495 panic("scheduling while atomic\n");
5498 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
5502 * Various schedule()-time debugging checks and statistics:
5504 static inline void schedule_debug(struct task_struct
*prev
, bool preempt
)
5506 #ifdef CONFIG_SCHED_STACK_END_CHECK
5507 if (task_stack_end_corrupted(prev
))
5508 panic("corrupted stack end detected inside scheduler\n");
5510 if (task_scs_end_corrupted(prev
))
5511 panic("corrupted shadow stack detected inside scheduler\n");
5514 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
5515 if (!preempt
&& READ_ONCE(prev
->__state
) && prev
->non_block_count
) {
5516 printk(KERN_ERR
"BUG: scheduling in a non-blocking section: %s/%d/%i\n",
5517 prev
->comm
, prev
->pid
, prev
->non_block_count
);
5519 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
5523 if (unlikely(in_atomic_preempt_off())) {
5524 __schedule_bug(prev
);
5525 preempt_count_set(PREEMPT_DISABLED
);
5528 SCHED_WARN_ON(ct_state() == CONTEXT_USER
);
5530 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
5532 schedstat_inc(this_rq()->sched_count
);
5535 static void put_prev_task_balance(struct rq
*rq
, struct task_struct
*prev
,
5536 struct rq_flags
*rf
)
5539 const struct sched_class
*class;
5541 * We must do the balancing pass before put_prev_task(), such
5542 * that when we release the rq->lock the task is in the same
5543 * state as before we took rq->lock.
5545 * We can terminate the balance pass as soon as we know there is
5546 * a runnable task of @class priority or higher.
5548 for_class_range(class, prev
->sched_class
, &idle_sched_class
) {
5549 if (class->balance(rq
, prev
, rf
))
5554 put_prev_task(rq
, prev
);
5558 * Pick up the highest-prio task:
5560 static inline struct task_struct
*
5561 __pick_next_task(struct rq
*rq
, struct task_struct
*prev
, struct rq_flags
*rf
)
5563 const struct sched_class
*class;
5564 struct task_struct
*p
;
5567 * Optimization: we know that if all tasks are in the fair class we can
5568 * call that function directly, but only if the @prev task wasn't of a
5569 * higher scheduling class, because otherwise those lose the
5570 * opportunity to pull in more work from other CPUs.
5572 if (likely(prev
->sched_class
<= &fair_sched_class
&&
5573 rq
->nr_running
== rq
->cfs
.h_nr_running
)) {
5575 p
= pick_next_task_fair(rq
, prev
, rf
);
5576 if (unlikely(p
== RETRY_TASK
))
5579 /* Assume the next prioritized class is idle_sched_class */
5581 put_prev_task(rq
, prev
);
5582 p
= pick_next_task_idle(rq
);
5589 put_prev_task_balance(rq
, prev
, rf
);
5591 for_each_class(class) {
5592 p
= class->pick_next_task(rq
);
5597 /* The idle class should always have a runnable task: */
5601 #ifdef CONFIG_SCHED_CORE
5602 static inline bool is_task_rq_idle(struct task_struct
*t
)
5604 return (task_rq(t
)->idle
== t
);
5607 static inline bool cookie_equals(struct task_struct
*a
, unsigned long cookie
)
5609 return is_task_rq_idle(a
) || (a
->core_cookie
== cookie
);
5612 static inline bool cookie_match(struct task_struct
*a
, struct task_struct
*b
)
5614 if (is_task_rq_idle(a
) || is_task_rq_idle(b
))
5617 return a
->core_cookie
== b
->core_cookie
;
5620 // XXX fairness/fwd progress conditions
5623 * - NULL if there is no runnable task for this class.
5624 * - the highest priority task for this runqueue if it matches
5625 * rq->core->core_cookie or its priority is greater than max.
5626 * - Else returns idle_task.
5628 static struct task_struct
*
5629 pick_task(struct rq
*rq
, const struct sched_class
*class, struct task_struct
*max
, bool in_fi
)
5631 struct task_struct
*class_pick
, *cookie_pick
;
5632 unsigned long cookie
= rq
->core
->core_cookie
;
5634 class_pick
= class->pick_task(rq
);
5640 * If class_pick is tagged, return it only if it has
5641 * higher priority than max.
5643 if (max
&& class_pick
->core_cookie
&&
5644 prio_less(class_pick
, max
, in_fi
))
5645 return idle_sched_class
.pick_task(rq
);
5651 * If class_pick is idle or matches cookie, return early.
5653 if (cookie_equals(class_pick
, cookie
))
5656 cookie_pick
= sched_core_find(rq
, cookie
);
5659 * If class > max && class > cookie, it is the highest priority task on
5660 * the core (so far) and it must be selected, otherwise we must go with
5661 * the cookie pick in order to satisfy the constraint.
5663 if (prio_less(cookie_pick
, class_pick
, in_fi
) &&
5664 (!max
|| prio_less(max
, class_pick
, in_fi
)))
5670 extern void task_vruntime_update(struct rq
*rq
, struct task_struct
*p
, bool in_fi
);
5672 static struct task_struct
*
5673 pick_next_task(struct rq
*rq
, struct task_struct
*prev
, struct rq_flags
*rf
)
5675 struct task_struct
*next
, *max
= NULL
;
5676 const struct sched_class
*class;
5677 const struct cpumask
*smt_mask
;
5678 bool fi_before
= false;
5679 int i
, j
, cpu
, occ
= 0;
5682 if (!sched_core_enabled(rq
))
5683 return __pick_next_task(rq
, prev
, rf
);
5687 /* Stopper task is switching into idle, no need core-wide selection. */
5688 if (cpu_is_offline(cpu
)) {
5690 * Reset core_pick so that we don't enter the fastpath when
5691 * coming online. core_pick would already be migrated to
5692 * another cpu during offline.
5694 rq
->core_pick
= NULL
;
5695 return __pick_next_task(rq
, prev
, rf
);
5699 * If there were no {en,de}queues since we picked (IOW, the task
5700 * pointers are all still valid), and we haven't scheduled the last
5701 * pick yet, do so now.
5703 * rq->core_pick can be NULL if no selection was made for a CPU because
5704 * it was either offline or went offline during a sibling's core-wide
5705 * selection. In this case, do a core-wide selection.
5707 if (rq
->core
->core_pick_seq
== rq
->core
->core_task_seq
&&
5708 rq
->core
->core_pick_seq
!= rq
->core_sched_seq
&&
5710 WRITE_ONCE(rq
->core_sched_seq
, rq
->core
->core_pick_seq
);
5712 next
= rq
->core_pick
;
5714 put_prev_task(rq
, prev
);
5715 set_next_task(rq
, next
);
5718 rq
->core_pick
= NULL
;
5722 put_prev_task_balance(rq
, prev
, rf
);
5724 smt_mask
= cpu_smt_mask(cpu
);
5725 need_sync
= !!rq
->core
->core_cookie
;
5728 rq
->core
->core_cookie
= 0UL;
5729 if (rq
->core
->core_forceidle
) {
5732 rq
->core
->core_forceidle
= false;
5736 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
5738 * @task_seq guards the task state ({en,de}queues)
5739 * @pick_seq is the @task_seq we did a selection on
5740 * @sched_seq is the @pick_seq we scheduled
5742 * However, preemptions can cause multiple picks on the same task set.
5743 * 'Fix' this by also increasing @task_seq for every pick.
5745 rq
->core
->core_task_seq
++;
5748 * Optimize for common case where this CPU has no cookies
5749 * and there are no cookied tasks running on siblings.
5752 for_each_class(class) {
5753 next
= class->pick_task(rq
);
5758 if (!next
->core_cookie
) {
5759 rq
->core_pick
= NULL
;
5761 * For robustness, update the min_vruntime_fi for
5762 * unconstrained picks as well.
5764 WARN_ON_ONCE(fi_before
);
5765 task_vruntime_update(rq
, next
, false);
5770 for_each_cpu(i
, smt_mask
) {
5771 struct rq
*rq_i
= cpu_rq(i
);
5773 rq_i
->core_pick
= NULL
;
5776 update_rq_clock(rq_i
);
5780 * Try and select tasks for each sibling in descending sched_class
5783 for_each_class(class) {
5785 for_each_cpu_wrap(i
, smt_mask
, cpu
) {
5786 struct rq
*rq_i
= cpu_rq(i
);
5787 struct task_struct
*p
;
5789 if (rq_i
->core_pick
)
5793 * If this sibling doesn't yet have a suitable task to
5794 * run; ask for the most eligible task, given the
5795 * highest priority task already selected for this
5798 p
= pick_task(rq_i
, class, max
, fi_before
);
5802 if (!is_task_rq_idle(p
))
5805 rq_i
->core_pick
= p
;
5806 if (rq_i
->idle
== p
&& rq_i
->nr_running
) {
5807 rq
->core
->core_forceidle
= true;
5809 rq
->core
->core_forceidle_seq
++;
5813 * If this new candidate is of higher priority than the
5814 * previous; and they're incompatible; we need to wipe
5815 * the slate and start over. pick_task makes sure that
5816 * p's priority is more than max if it doesn't match
5819 * NOTE: this is a linear max-filter and is thus bounded
5820 * in execution time.
5822 if (!max
|| !cookie_match(max
, p
)) {
5823 struct task_struct
*old_max
= max
;
5825 rq
->core
->core_cookie
= p
->core_cookie
;
5829 rq
->core
->core_forceidle
= false;
5830 for_each_cpu(j
, smt_mask
) {
5834 cpu_rq(j
)->core_pick
= NULL
;
5843 rq
->core
->core_pick_seq
= rq
->core
->core_task_seq
;
5844 next
= rq
->core_pick
;
5845 rq
->core_sched_seq
= rq
->core
->core_pick_seq
;
5847 /* Something should have been selected for current CPU */
5848 WARN_ON_ONCE(!next
);
5851 * Reschedule siblings
5853 * NOTE: L1TF -- at this point we're no longer running the old task and
5854 * sending an IPI (below) ensures the sibling will no longer be running
5855 * their task. This ensures there is no inter-sibling overlap between
5856 * non-matching user state.
5858 for_each_cpu(i
, smt_mask
) {
5859 struct rq
*rq_i
= cpu_rq(i
);
5862 * An online sibling might have gone offline before a task
5863 * could be picked for it, or it might be offline but later
5864 * happen to come online, but its too late and nothing was
5865 * picked for it. That's Ok - it will pick tasks for itself,
5868 if (!rq_i
->core_pick
)
5872 * Update for new !FI->FI transitions, or if continuing to be in !FI:
5873 * fi_before fi update?
5879 if (!(fi_before
&& rq
->core
->core_forceidle
))
5880 task_vruntime_update(rq_i
, rq_i
->core_pick
, rq
->core
->core_forceidle
);
5882 rq_i
->core_pick
->core_occupation
= occ
;
5885 rq_i
->core_pick
= NULL
;
5889 /* Did we break L1TF mitigation requirements? */
5890 WARN_ON_ONCE(!cookie_match(next
, rq_i
->core_pick
));
5892 if (rq_i
->curr
== rq_i
->core_pick
) {
5893 rq_i
->core_pick
= NULL
;
5901 set_next_task(rq
, next
);
5905 static bool try_steal_cookie(int this, int that
)
5907 struct rq
*dst
= cpu_rq(this), *src
= cpu_rq(that
);
5908 struct task_struct
*p
;
5909 unsigned long cookie
;
5910 bool success
= false;
5912 local_irq_disable();
5913 double_rq_lock(dst
, src
);
5915 cookie
= dst
->core
->core_cookie
;
5919 if (dst
->curr
!= dst
->idle
)
5922 p
= sched_core_find(src
, cookie
);
5927 if (p
== src
->core_pick
|| p
== src
->curr
)
5930 if (!cpumask_test_cpu(this, &p
->cpus_mask
))
5933 if (p
->core_occupation
> dst
->idle
->core_occupation
)
5936 deactivate_task(src
, p
, 0);
5937 set_task_cpu(p
, this);
5938 activate_task(dst
, p
, 0);
5946 p
= sched_core_next(p
, cookie
);
5950 double_rq_unlock(dst
, src
);
5956 static bool steal_cookie_task(int cpu
, struct sched_domain
*sd
)
5960 for_each_cpu_wrap(i
, sched_domain_span(sd
), cpu
) {
5967 if (try_steal_cookie(cpu
, i
))
5974 static void sched_core_balance(struct rq
*rq
)
5976 struct sched_domain
*sd
;
5977 int cpu
= cpu_of(rq
);
5981 raw_spin_rq_unlock_irq(rq
);
5982 for_each_domain(cpu
, sd
) {
5986 if (steal_cookie_task(cpu
, sd
))
5989 raw_spin_rq_lock_irq(rq
);
5994 static DEFINE_PER_CPU(struct callback_head
, core_balance_head
);
5996 void queue_core_balance(struct rq
*rq
)
5998 if (!sched_core_enabled(rq
))
6001 if (!rq
->core
->core_cookie
)
6004 if (!rq
->nr_running
) /* not forced idle */
6007 queue_balance_callback(rq
, &per_cpu(core_balance_head
, rq
->cpu
), sched_core_balance
);
6010 static void sched_core_cpu_starting(unsigned int cpu
)
6012 const struct cpumask
*smt_mask
= cpu_smt_mask(cpu
);
6013 struct rq
*rq
= cpu_rq(cpu
), *core_rq
= NULL
;
6014 unsigned long flags
;
6017 sched_core_lock(cpu
, &flags
);
6019 WARN_ON_ONCE(rq
->core
!= rq
);
6021 /* if we're the first, we'll be our own leader */
6022 if (cpumask_weight(smt_mask
) == 1)
6025 /* find the leader */
6026 for_each_cpu(t
, smt_mask
) {
6030 if (rq
->core
== rq
) {
6036 if (WARN_ON_ONCE(!core_rq
)) /* whoopsie */
6039 /* install and validate core_rq */
6040 for_each_cpu(t
, smt_mask
) {
6046 WARN_ON_ONCE(rq
->core
!= core_rq
);
6050 sched_core_unlock(cpu
, &flags
);
6053 static void sched_core_cpu_deactivate(unsigned int cpu
)
6055 const struct cpumask
*smt_mask
= cpu_smt_mask(cpu
);
6056 struct rq
*rq
= cpu_rq(cpu
), *core_rq
= NULL
;
6057 unsigned long flags
;
6060 sched_core_lock(cpu
, &flags
);
6062 /* if we're the last man standing, nothing to do */
6063 if (cpumask_weight(smt_mask
) == 1) {
6064 WARN_ON_ONCE(rq
->core
!= rq
);
6068 /* if we're not the leader, nothing to do */
6072 /* find a new leader */
6073 for_each_cpu(t
, smt_mask
) {
6076 core_rq
= cpu_rq(t
);
6080 if (WARN_ON_ONCE(!core_rq
)) /* impossible */
6083 /* copy the shared state to the new leader */
6084 core_rq
->core_task_seq
= rq
->core_task_seq
;
6085 core_rq
->core_pick_seq
= rq
->core_pick_seq
;
6086 core_rq
->core_cookie
= rq
->core_cookie
;
6087 core_rq
->core_forceidle
= rq
->core_forceidle
;
6088 core_rq
->core_forceidle_seq
= rq
->core_forceidle_seq
;
6090 /* install new leader */
6091 for_each_cpu(t
, smt_mask
) {
6097 sched_core_unlock(cpu
, &flags
);
6100 static inline void sched_core_cpu_dying(unsigned int cpu
)
6102 struct rq
*rq
= cpu_rq(cpu
);
6108 #else /* !CONFIG_SCHED_CORE */
6110 static inline void sched_core_cpu_starting(unsigned int cpu
) {}
6111 static inline void sched_core_cpu_deactivate(unsigned int cpu
) {}
6112 static inline void sched_core_cpu_dying(unsigned int cpu
) {}
6114 static struct task_struct
*
6115 pick_next_task(struct rq
*rq
, struct task_struct
*prev
, struct rq_flags
*rf
)
6117 return __pick_next_task(rq
, prev
, rf
);
6120 #endif /* CONFIG_SCHED_CORE */
6123 * Constants for the sched_mode argument of __schedule().
6125 * The mode argument allows RT enabled kernels to differentiate a
6126 * preemption from blocking on an 'sleeping' spin/rwlock. Note that
6127 * SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to
6128 * optimize the AND operation out and just check for zero.
6131 #define SM_PREEMPT 0x1
6132 #define SM_RTLOCK_WAIT 0x2
6134 #ifndef CONFIG_PREEMPT_RT
6135 # define SM_MASK_PREEMPT (~0U)
6137 # define SM_MASK_PREEMPT SM_PREEMPT
6141 * __schedule() is the main scheduler function.
6143 * The main means of driving the scheduler and thus entering this function are:
6145 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
6147 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
6148 * paths. For example, see arch/x86/entry_64.S.
6150 * To drive preemption between tasks, the scheduler sets the flag in timer
6151 * interrupt handler scheduler_tick().
6153 * 3. Wakeups don't really cause entry into schedule(). They add a
6154 * task to the run-queue and that's it.
6156 * Now, if the new task added to the run-queue preempts the current
6157 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
6158 * called on the nearest possible occasion:
6160 * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
6162 * - in syscall or exception context, at the next outmost
6163 * preempt_enable(). (this might be as soon as the wake_up()'s
6166 * - in IRQ context, return from interrupt-handler to
6167 * preemptible context
6169 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
6172 * - cond_resched() call
6173 * - explicit schedule() call
6174 * - return from syscall or exception to user-space
6175 * - return from interrupt-handler to user-space
6177 * WARNING: must be called with preemption disabled!
6179 static void __sched notrace
__schedule(unsigned int sched_mode
)
6181 struct task_struct
*prev
, *next
;
6182 unsigned long *switch_count
;
6183 unsigned long prev_state
;
6188 cpu
= smp_processor_id();
6192 schedule_debug(prev
, !!sched_mode
);
6194 if (sched_feat(HRTICK
) || sched_feat(HRTICK_DL
))
6197 local_irq_disable();
6198 rcu_note_context_switch(!!sched_mode
);
6201 * Make sure that signal_pending_state()->signal_pending() below
6202 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
6203 * done by the caller to avoid the race with signal_wake_up():
6205 * __set_current_state(@state) signal_wake_up()
6206 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
6207 * wake_up_state(p, state)
6208 * LOCK rq->lock LOCK p->pi_state
6209 * smp_mb__after_spinlock() smp_mb__after_spinlock()
6210 * if (signal_pending_state()) if (p->state & @state)
6212 * Also, the membarrier system call requires a full memory barrier
6213 * after coming from user-space, before storing to rq->curr.
6216 smp_mb__after_spinlock();
6218 /* Promote REQ to ACT */
6219 rq
->clock_update_flags
<<= 1;
6220 update_rq_clock(rq
);
6222 switch_count
= &prev
->nivcsw
;
6225 * We must load prev->state once (task_struct::state is volatile), such
6228 * - we form a control dependency vs deactivate_task() below.
6229 * - ptrace_{,un}freeze_traced() can change ->state underneath us.
6231 prev_state
= READ_ONCE(prev
->__state
);
6232 if (!(sched_mode
& SM_MASK_PREEMPT
) && prev_state
) {
6233 if (signal_pending_state(prev_state
, prev
)) {
6234 WRITE_ONCE(prev
->__state
, TASK_RUNNING
);
6236 prev
->sched_contributes_to_load
=
6237 (prev_state
& TASK_UNINTERRUPTIBLE
) &&
6238 !(prev_state
& TASK_NOLOAD
) &&
6239 !(prev
->flags
& PF_FROZEN
);
6241 if (prev
->sched_contributes_to_load
)
6242 rq
->nr_uninterruptible
++;
6245 * __schedule() ttwu()
6246 * prev_state = prev->state; if (p->on_rq && ...)
6247 * if (prev_state) goto out;
6248 * p->on_rq = 0; smp_acquire__after_ctrl_dep();
6249 * p->state = TASK_WAKING
6251 * Where __schedule() and ttwu() have matching control dependencies.
6253 * After this, schedule() must not care about p->state any more.
6255 deactivate_task(rq
, prev
, DEQUEUE_SLEEP
| DEQUEUE_NOCLOCK
);
6257 if (prev
->in_iowait
) {
6258 atomic_inc(&rq
->nr_iowait
);
6259 delayacct_blkio_start();
6262 switch_count
= &prev
->nvcsw
;
6265 next
= pick_next_task(rq
, prev
, &rf
);
6266 clear_tsk_need_resched(prev
);
6267 clear_preempt_need_resched();
6268 #ifdef CONFIG_SCHED_DEBUG
6269 rq
->last_seen_need_resched_ns
= 0;
6272 if (likely(prev
!= next
)) {
6275 * RCU users of rcu_dereference(rq->curr) may not see
6276 * changes to task_struct made by pick_next_task().
6278 RCU_INIT_POINTER(rq
->curr
, next
);
6280 * The membarrier system call requires each architecture
6281 * to have a full memory barrier after updating
6282 * rq->curr, before returning to user-space.
6284 * Here are the schemes providing that barrier on the
6285 * various architectures:
6286 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
6287 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
6288 * - finish_lock_switch() for weakly-ordered
6289 * architectures where spin_unlock is a full barrier,
6290 * - switch_to() for arm64 (weakly-ordered, spin_unlock
6291 * is a RELEASE barrier),
6295 migrate_disable_switch(rq
, prev
);
6296 psi_sched_switch(prev
, next
, !task_on_rq_queued(prev
));
6298 trace_sched_switch(sched_mode
& SM_MASK_PREEMPT
, prev
, next
);
6300 /* Also unlocks the rq: */
6301 rq
= context_switch(rq
, prev
, next
, &rf
);
6303 rq
->clock_update_flags
&= ~(RQCF_ACT_SKIP
|RQCF_REQ_SKIP
);
6305 rq_unpin_lock(rq
, &rf
);
6306 __balance_callbacks(rq
);
6307 raw_spin_rq_unlock_irq(rq
);
6311 void __noreturn
do_task_dead(void)
6313 /* Causes final put_task_struct in finish_task_switch(): */
6314 set_special_state(TASK_DEAD
);
6316 /* Tell freezer to ignore us: */
6317 current
->flags
|= PF_NOFREEZE
;
6319 __schedule(SM_NONE
);
6322 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
6327 static inline void sched_submit_work(struct task_struct
*tsk
)
6329 unsigned int task_flags
;
6331 if (task_is_running(tsk
))
6334 task_flags
= tsk
->flags
;
6336 * If a worker went to sleep, notify and ask workqueue whether
6337 * it wants to wake up a task to maintain concurrency.
6338 * As this function is called inside the schedule() context,
6339 * we disable preemption to avoid it calling schedule() again
6340 * in the possible wakeup of a kworker and because wq_worker_sleeping()
6343 if (task_flags
& (PF_WQ_WORKER
| PF_IO_WORKER
)) {
6345 if (task_flags
& PF_WQ_WORKER
)
6346 wq_worker_sleeping(tsk
);
6348 io_wq_worker_sleeping(tsk
);
6349 preempt_enable_no_resched();
6352 if (tsk_is_pi_blocked(tsk
))
6356 * If we are going to sleep and we have plugged IO queued,
6357 * make sure to submit it to avoid deadlocks.
6359 if (blk_needs_flush_plug(tsk
))
6360 blk_schedule_flush_plug(tsk
);
6363 static void sched_update_worker(struct task_struct
*tsk
)
6365 if (tsk
->flags
& (PF_WQ_WORKER
| PF_IO_WORKER
)) {
6366 if (tsk
->flags
& PF_WQ_WORKER
)
6367 wq_worker_running(tsk
);
6369 io_wq_worker_running(tsk
);
6373 asmlinkage __visible
void __sched
schedule(void)
6375 struct task_struct
*tsk
= current
;
6377 sched_submit_work(tsk
);
6380 __schedule(SM_NONE
);
6381 sched_preempt_enable_no_resched();
6382 } while (need_resched());
6383 sched_update_worker(tsk
);
6385 EXPORT_SYMBOL(schedule
);
6388 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
6389 * state (have scheduled out non-voluntarily) by making sure that all
6390 * tasks have either left the run queue or have gone into user space.
6391 * As idle tasks do not do either, they must not ever be preempted
6392 * (schedule out non-voluntarily).
6394 * schedule_idle() is similar to schedule_preempt_disable() except that it
6395 * never enables preemption because it does not call sched_submit_work().
6397 void __sched
schedule_idle(void)
6400 * As this skips calling sched_submit_work(), which the idle task does
6401 * regardless because that function is a nop when the task is in a
6402 * TASK_RUNNING state, make sure this isn't used someplace that the
6403 * current task can be in any other state. Note, idle is always in the
6404 * TASK_RUNNING state.
6406 WARN_ON_ONCE(current
->__state
);
6408 __schedule(SM_NONE
);
6409 } while (need_resched());
6412 #if defined(CONFIG_CONTEXT_TRACKING) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_OFFSTACK)
6413 asmlinkage __visible
void __sched
schedule_user(void)
6416 * If we come here after a random call to set_need_resched(),
6417 * or we have been woken up remotely but the IPI has not yet arrived,
6418 * we haven't yet exited the RCU idle mode. Do it here manually until
6419 * we find a better solution.
6421 * NB: There are buggy callers of this function. Ideally we
6422 * should warn if prev_state != CONTEXT_USER, but that will trigger
6423 * too frequently to make sense yet.
6425 enum ctx_state prev_state
= exception_enter();
6427 exception_exit(prev_state
);
6432 * schedule_preempt_disabled - called with preemption disabled
6434 * Returns with preemption disabled. Note: preempt_count must be 1
6436 void __sched
schedule_preempt_disabled(void)
6438 sched_preempt_enable_no_resched();
6443 #ifdef CONFIG_PREEMPT_RT
6444 void __sched notrace
schedule_rtlock(void)
6448 __schedule(SM_RTLOCK_WAIT
);
6449 sched_preempt_enable_no_resched();
6450 } while (need_resched());
6452 NOKPROBE_SYMBOL(schedule_rtlock
);
6455 static void __sched notrace
preempt_schedule_common(void)
6459 * Because the function tracer can trace preempt_count_sub()
6460 * and it also uses preempt_enable/disable_notrace(), if
6461 * NEED_RESCHED is set, the preempt_enable_notrace() called
6462 * by the function tracer will call this function again and
6463 * cause infinite recursion.
6465 * Preemption must be disabled here before the function
6466 * tracer can trace. Break up preempt_disable() into two
6467 * calls. One to disable preemption without fear of being
6468 * traced. The other to still record the preemption latency,
6469 * which can also be traced by the function tracer.
6471 preempt_disable_notrace();
6472 preempt_latency_start(1);
6473 __schedule(SM_PREEMPT
);
6474 preempt_latency_stop(1);
6475 preempt_enable_no_resched_notrace();
6478 * Check again in case we missed a preemption opportunity
6479 * between schedule and now.
6481 } while (need_resched());
6484 #ifdef CONFIG_PREEMPTION
6486 * This is the entry point to schedule() from in-kernel preemption
6487 * off of preempt_enable.
6489 asmlinkage __visible
void __sched notrace
preempt_schedule(void)
6492 * If there is a non-zero preempt_count or interrupts are disabled,
6493 * we do not want to preempt the current task. Just return..
6495 if (likely(!preemptible()))
6498 preempt_schedule_common();
6500 NOKPROBE_SYMBOL(preempt_schedule
);
6501 EXPORT_SYMBOL(preempt_schedule
);
6503 #ifdef CONFIG_PREEMPT_DYNAMIC
6504 DEFINE_STATIC_CALL(preempt_schedule
, __preempt_schedule_func
);
6505 EXPORT_STATIC_CALL_TRAMP(preempt_schedule
);
6510 * preempt_schedule_notrace - preempt_schedule called by tracing
6512 * The tracing infrastructure uses preempt_enable_notrace to prevent
6513 * recursion and tracing preempt enabling caused by the tracing
6514 * infrastructure itself. But as tracing can happen in areas coming
6515 * from userspace or just about to enter userspace, a preempt enable
6516 * can occur before user_exit() is called. This will cause the scheduler
6517 * to be called when the system is still in usermode.
6519 * To prevent this, the preempt_enable_notrace will use this function
6520 * instead of preempt_schedule() to exit user context if needed before
6521 * calling the scheduler.
6523 asmlinkage __visible
void __sched notrace
preempt_schedule_notrace(void)
6525 enum ctx_state prev_ctx
;
6527 if (likely(!preemptible()))
6532 * Because the function tracer can trace preempt_count_sub()
6533 * and it also uses preempt_enable/disable_notrace(), if
6534 * NEED_RESCHED is set, the preempt_enable_notrace() called
6535 * by the function tracer will call this function again and
6536 * cause infinite recursion.
6538 * Preemption must be disabled here before the function
6539 * tracer can trace. Break up preempt_disable() into two
6540 * calls. One to disable preemption without fear of being
6541 * traced. The other to still record the preemption latency,
6542 * which can also be traced by the function tracer.
6544 preempt_disable_notrace();
6545 preempt_latency_start(1);
6547 * Needs preempt disabled in case user_exit() is traced
6548 * and the tracer calls preempt_enable_notrace() causing
6549 * an infinite recursion.
6551 prev_ctx
= exception_enter();
6552 __schedule(SM_PREEMPT
);
6553 exception_exit(prev_ctx
);
6555 preempt_latency_stop(1);
6556 preempt_enable_no_resched_notrace();
6557 } while (need_resched());
6559 EXPORT_SYMBOL_GPL(preempt_schedule_notrace
);
6561 #ifdef CONFIG_PREEMPT_DYNAMIC
6562 DEFINE_STATIC_CALL(preempt_schedule_notrace
, __preempt_schedule_notrace_func
);
6563 EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace
);
6566 #endif /* CONFIG_PREEMPTION */
6568 #ifdef CONFIG_PREEMPT_DYNAMIC
6570 #include <linux/entry-common.h>
6575 * SC:preempt_schedule
6576 * SC:preempt_schedule_notrace
6577 * SC:irqentry_exit_cond_resched
6581 * cond_resched <- __cond_resched
6582 * might_resched <- RET0
6583 * preempt_schedule <- NOP
6584 * preempt_schedule_notrace <- NOP
6585 * irqentry_exit_cond_resched <- NOP
6588 * cond_resched <- __cond_resched
6589 * might_resched <- __cond_resched
6590 * preempt_schedule <- NOP
6591 * preempt_schedule_notrace <- NOP
6592 * irqentry_exit_cond_resched <- NOP
6595 * cond_resched <- RET0
6596 * might_resched <- RET0
6597 * preempt_schedule <- preempt_schedule
6598 * preempt_schedule_notrace <- preempt_schedule_notrace
6599 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched
6603 preempt_dynamic_none
= 0,
6604 preempt_dynamic_voluntary
,
6605 preempt_dynamic_full
,
6608 int preempt_dynamic_mode
= preempt_dynamic_full
;
6610 int sched_dynamic_mode(const char *str
)
6612 if (!strcmp(str
, "none"))
6613 return preempt_dynamic_none
;
6615 if (!strcmp(str
, "voluntary"))
6616 return preempt_dynamic_voluntary
;
6618 if (!strcmp(str
, "full"))
6619 return preempt_dynamic_full
;
6624 void sched_dynamic_update(int mode
)
6627 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
6628 * the ZERO state, which is invalid.
6630 static_call_update(cond_resched
, __cond_resched
);
6631 static_call_update(might_resched
, __cond_resched
);
6632 static_call_update(preempt_schedule
, __preempt_schedule_func
);
6633 static_call_update(preempt_schedule_notrace
, __preempt_schedule_notrace_func
);
6634 static_call_update(irqentry_exit_cond_resched
, irqentry_exit_cond_resched
);
6637 case preempt_dynamic_none
:
6638 static_call_update(cond_resched
, __cond_resched
);
6639 static_call_update(might_resched
, (void *)&__static_call_return0
);
6640 static_call_update(preempt_schedule
, NULL
);
6641 static_call_update(preempt_schedule_notrace
, NULL
);
6642 static_call_update(irqentry_exit_cond_resched
, NULL
);
6643 pr_info("Dynamic Preempt: none\n");
6646 case preempt_dynamic_voluntary
:
6647 static_call_update(cond_resched
, __cond_resched
);
6648 static_call_update(might_resched
, __cond_resched
);
6649 static_call_update(preempt_schedule
, NULL
);
6650 static_call_update(preempt_schedule_notrace
, NULL
);
6651 static_call_update(irqentry_exit_cond_resched
, NULL
);
6652 pr_info("Dynamic Preempt: voluntary\n");
6655 case preempt_dynamic_full
:
6656 static_call_update(cond_resched
, (void *)&__static_call_return0
);
6657 static_call_update(might_resched
, (void *)&__static_call_return0
);
6658 static_call_update(preempt_schedule
, __preempt_schedule_func
);
6659 static_call_update(preempt_schedule_notrace
, __preempt_schedule_notrace_func
);
6660 static_call_update(irqentry_exit_cond_resched
, irqentry_exit_cond_resched
);
6661 pr_info("Dynamic Preempt: full\n");
6665 preempt_dynamic_mode
= mode
;
6668 static int __init
setup_preempt_mode(char *str
)
6670 int mode
= sched_dynamic_mode(str
);
6672 pr_warn("Dynamic Preempt: unsupported mode: %s\n", str
);
6676 sched_dynamic_update(mode
);
6679 __setup("preempt=", setup_preempt_mode
);
6681 #endif /* CONFIG_PREEMPT_DYNAMIC */
6684 * This is the entry point to schedule() from kernel preemption
6685 * off of irq context.
6686 * Note, that this is called and return with irqs disabled. This will
6687 * protect us against recursive calling from irq.
6689 asmlinkage __visible
void __sched
preempt_schedule_irq(void)
6691 enum ctx_state prev_state
;
6693 /* Catch callers which need to be fixed */
6694 BUG_ON(preempt_count() || !irqs_disabled());
6696 prev_state
= exception_enter();
6701 __schedule(SM_PREEMPT
);
6702 local_irq_disable();
6703 sched_preempt_enable_no_resched();
6704 } while (need_resched());
6706 exception_exit(prev_state
);
6709 int default_wake_function(wait_queue_entry_t
*curr
, unsigned mode
, int wake_flags
,
6712 WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG
) && wake_flags
& ~WF_SYNC
);
6713 return try_to_wake_up(curr
->private, mode
, wake_flags
);
6715 EXPORT_SYMBOL(default_wake_function
);
6717 static void __setscheduler_prio(struct task_struct
*p
, int prio
)
6720 p
->sched_class
= &dl_sched_class
;
6721 else if (rt_prio(prio
))
6722 p
->sched_class
= &rt_sched_class
;
6724 p
->sched_class
= &fair_sched_class
;
6729 #ifdef CONFIG_RT_MUTEXES
6731 static inline int __rt_effective_prio(struct task_struct
*pi_task
, int prio
)
6734 prio
= min(prio
, pi_task
->prio
);
6739 static inline int rt_effective_prio(struct task_struct
*p
, int prio
)
6741 struct task_struct
*pi_task
= rt_mutex_get_top_task(p
);
6743 return __rt_effective_prio(pi_task
, prio
);
6747 * rt_mutex_setprio - set the current priority of a task
6749 * @pi_task: donor task
6751 * This function changes the 'effective' priority of a task. It does
6752 * not touch ->normal_prio like __setscheduler().
6754 * Used by the rt_mutex code to implement priority inheritance
6755 * logic. Call site only calls if the priority of the task changed.
6757 void rt_mutex_setprio(struct task_struct
*p
, struct task_struct
*pi_task
)
6759 int prio
, oldprio
, queued
, running
, queue_flag
=
6760 DEQUEUE_SAVE
| DEQUEUE_MOVE
| DEQUEUE_NOCLOCK
;
6761 const struct sched_class
*prev_class
;
6765 /* XXX used to be waiter->prio, not waiter->task->prio */
6766 prio
= __rt_effective_prio(pi_task
, p
->normal_prio
);
6769 * If nothing changed; bail early.
6771 if (p
->pi_top_task
== pi_task
&& prio
== p
->prio
&& !dl_prio(prio
))
6774 rq
= __task_rq_lock(p
, &rf
);
6775 update_rq_clock(rq
);
6777 * Set under pi_lock && rq->lock, such that the value can be used under
6780 * Note that there is loads of tricky to make this pointer cache work
6781 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
6782 * ensure a task is de-boosted (pi_task is set to NULL) before the
6783 * task is allowed to run again (and can exit). This ensures the pointer
6784 * points to a blocked task -- which guarantees the task is present.
6786 p
->pi_top_task
= pi_task
;
6789 * For FIFO/RR we only need to set prio, if that matches we're done.
6791 if (prio
== p
->prio
&& !dl_prio(prio
))
6795 * Idle task boosting is a nono in general. There is one
6796 * exception, when PREEMPT_RT and NOHZ is active:
6798 * The idle task calls get_next_timer_interrupt() and holds
6799 * the timer wheel base->lock on the CPU and another CPU wants
6800 * to access the timer (probably to cancel it). We can safely
6801 * ignore the boosting request, as the idle CPU runs this code
6802 * with interrupts disabled and will complete the lock
6803 * protected section without being interrupted. So there is no
6804 * real need to boost.
6806 if (unlikely(p
== rq
->idle
)) {
6807 WARN_ON(p
!= rq
->curr
);
6808 WARN_ON(p
->pi_blocked_on
);
6812 trace_sched_pi_setprio(p
, pi_task
);
6815 if (oldprio
== prio
)
6816 queue_flag
&= ~DEQUEUE_MOVE
;
6818 prev_class
= p
->sched_class
;
6819 queued
= task_on_rq_queued(p
);
6820 running
= task_current(rq
, p
);
6822 dequeue_task(rq
, p
, queue_flag
);
6824 put_prev_task(rq
, p
);
6827 * Boosting condition are:
6828 * 1. -rt task is running and holds mutex A
6829 * --> -dl task blocks on mutex A
6831 * 2. -dl task is running and holds mutex A
6832 * --> -dl task blocks on mutex A and could preempt the
6835 if (dl_prio(prio
)) {
6836 if (!dl_prio(p
->normal_prio
) ||
6837 (pi_task
&& dl_prio(pi_task
->prio
) &&
6838 dl_entity_preempt(&pi_task
->dl
, &p
->dl
))) {
6839 p
->dl
.pi_se
= pi_task
->dl
.pi_se
;
6840 queue_flag
|= ENQUEUE_REPLENISH
;
6842 p
->dl
.pi_se
= &p
->dl
;
6844 } else if (rt_prio(prio
)) {
6845 if (dl_prio(oldprio
))
6846 p
->dl
.pi_se
= &p
->dl
;
6848 queue_flag
|= ENQUEUE_HEAD
;
6850 if (dl_prio(oldprio
))
6851 p
->dl
.pi_se
= &p
->dl
;
6852 if (rt_prio(oldprio
))
6856 __setscheduler_prio(p
, prio
);
6859 enqueue_task(rq
, p
, queue_flag
);
6861 set_next_task(rq
, p
);
6863 check_class_changed(rq
, p
, prev_class
, oldprio
);
6865 /* Avoid rq from going away on us: */
6868 rq_unpin_lock(rq
, &rf
);
6869 __balance_callbacks(rq
);
6870 raw_spin_rq_unlock(rq
);
6875 static inline int rt_effective_prio(struct task_struct
*p
, int prio
)
6881 void set_user_nice(struct task_struct
*p
, long nice
)
6883 bool queued
, running
;
6888 if (task_nice(p
) == nice
|| nice
< MIN_NICE
|| nice
> MAX_NICE
)
6891 * We have to be careful, if called from sys_setpriority(),
6892 * the task might be in the middle of scheduling on another CPU.
6894 rq
= task_rq_lock(p
, &rf
);
6895 update_rq_clock(rq
);
6898 * The RT priorities are set via sched_setscheduler(), but we still
6899 * allow the 'normal' nice value to be set - but as expected
6900 * it won't have any effect on scheduling until the task is
6901 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
6903 if (task_has_dl_policy(p
) || task_has_rt_policy(p
)) {
6904 p
->static_prio
= NICE_TO_PRIO(nice
);
6907 queued
= task_on_rq_queued(p
);
6908 running
= task_current(rq
, p
);
6910 dequeue_task(rq
, p
, DEQUEUE_SAVE
| DEQUEUE_NOCLOCK
);
6912 put_prev_task(rq
, p
);
6914 p
->static_prio
= NICE_TO_PRIO(nice
);
6915 set_load_weight(p
, true);
6917 p
->prio
= effective_prio(p
);
6920 enqueue_task(rq
, p
, ENQUEUE_RESTORE
| ENQUEUE_NOCLOCK
);
6922 set_next_task(rq
, p
);
6925 * If the task increased its priority or is running and
6926 * lowered its priority, then reschedule its CPU:
6928 p
->sched_class
->prio_changed(rq
, p
, old_prio
);
6931 task_rq_unlock(rq
, p
, &rf
);
6933 EXPORT_SYMBOL(set_user_nice
);
6936 * can_nice - check if a task can reduce its nice value
6940 int can_nice(const struct task_struct
*p
, const int nice
)
6942 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
6943 int nice_rlim
= nice_to_rlimit(nice
);
6945 return (nice_rlim
<= task_rlimit(p
, RLIMIT_NICE
) ||
6946 capable(CAP_SYS_NICE
));
6948 EXPORT_SYMBOL(can_nice
);
6950 #ifdef __ARCH_WANT_SYS_NICE
6953 * sys_nice - change the priority of the current process.
6954 * @increment: priority increment
6956 * sys_setpriority is a more generic, but much slower function that
6957 * does similar things.
6959 SYSCALL_DEFINE1(nice
, int, increment
)
6964 * Setpriority might change our priority at the same moment.
6965 * We don't have to worry. Conceptually one call occurs first
6966 * and we have a single winner.
6968 increment
= clamp(increment
, -NICE_WIDTH
, NICE_WIDTH
);
6969 nice
= task_nice(current
) + increment
;
6971 nice
= clamp_val(nice
, MIN_NICE
, MAX_NICE
);
6972 if (increment
< 0 && !can_nice(current
, nice
))
6975 retval
= security_task_setnice(current
, nice
);
6979 set_user_nice(current
, nice
);
6986 * task_prio - return the priority value of a given task.
6987 * @p: the task in question.
6989 * Return: The priority value as seen by users in /proc.
6991 * sched policy return value kernel prio user prio/nice
6993 * normal, batch, idle [0 ... 39] [100 ... 139] 0/[-20 ... 19]
6994 * fifo, rr [-2 ... -100] [98 ... 0] [1 ... 99]
6995 * deadline -101 -1 0
6997 int task_prio(const struct task_struct
*p
)
6999 return p
->prio
- MAX_RT_PRIO
;
7003 * idle_cpu - is a given CPU idle currently?
7004 * @cpu: the processor in question.
7006 * Return: 1 if the CPU is currently idle. 0 otherwise.
7008 int idle_cpu(int cpu
)
7010 struct rq
*rq
= cpu_rq(cpu
);
7012 if (rq
->curr
!= rq
->idle
)
7019 if (rq
->ttwu_pending
)
7027 * available_idle_cpu - is a given CPU idle for enqueuing work.
7028 * @cpu: the CPU in question.
7030 * Return: 1 if the CPU is currently idle. 0 otherwise.
7032 int available_idle_cpu(int cpu
)
7037 if (vcpu_is_preempted(cpu
))
7044 * idle_task - return the idle task for a given CPU.
7045 * @cpu: the processor in question.
7047 * Return: The idle task for the CPU @cpu.
7049 struct task_struct
*idle_task(int cpu
)
7051 return cpu_rq(cpu
)->idle
;
7056 * This function computes an effective utilization for the given CPU, to be
7057 * used for frequency selection given the linear relation: f = u * f_max.
7059 * The scheduler tracks the following metrics:
7061 * cpu_util_{cfs,rt,dl,irq}()
7064 * Where the cfs,rt and dl util numbers are tracked with the same metric and
7065 * synchronized windows and are thus directly comparable.
7067 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
7068 * which excludes things like IRQ and steal-time. These latter are then accrued
7069 * in the irq utilization.
7071 * The DL bandwidth number otoh is not a measured metric but a value computed
7072 * based on the task model parameters and gives the minimal utilization
7073 * required to meet deadlines.
7075 unsigned long effective_cpu_util(int cpu
, unsigned long util_cfs
,
7076 unsigned long max
, enum cpu_util_type type
,
7077 struct task_struct
*p
)
7079 unsigned long dl_util
, util
, irq
;
7080 struct rq
*rq
= cpu_rq(cpu
);
7082 if (!uclamp_is_used() &&
7083 type
== FREQUENCY_UTIL
&& rt_rq_is_runnable(&rq
->rt
)) {
7088 * Early check to see if IRQ/steal time saturates the CPU, can be
7089 * because of inaccuracies in how we track these -- see
7090 * update_irq_load_avg().
7092 irq
= cpu_util_irq(rq
);
7093 if (unlikely(irq
>= max
))
7097 * Because the time spend on RT/DL tasks is visible as 'lost' time to
7098 * CFS tasks and we use the same metric to track the effective
7099 * utilization (PELT windows are synchronized) we can directly add them
7100 * to obtain the CPU's actual utilization.
7102 * CFS and RT utilization can be boosted or capped, depending on
7103 * utilization clamp constraints requested by currently RUNNABLE
7105 * When there are no CFS RUNNABLE tasks, clamps are released and
7106 * frequency will be gracefully reduced with the utilization decay.
7108 util
= util_cfs
+ cpu_util_rt(rq
);
7109 if (type
== FREQUENCY_UTIL
)
7110 util
= uclamp_rq_util_with(rq
, util
, p
);
7112 dl_util
= cpu_util_dl(rq
);
7115 * For frequency selection we do not make cpu_util_dl() a permanent part
7116 * of this sum because we want to use cpu_bw_dl() later on, but we need
7117 * to check if the CFS+RT+DL sum is saturated (ie. no idle time) such
7118 * that we select f_max when there is no idle time.
7120 * NOTE: numerical errors or stop class might cause us to not quite hit
7121 * saturation when we should -- something for later.
7123 if (util
+ dl_util
>= max
)
7127 * OTOH, for energy computation we need the estimated running time, so
7128 * include util_dl and ignore dl_bw.
7130 if (type
== ENERGY_UTIL
)
7134 * There is still idle time; further improve the number by using the
7135 * irq metric. Because IRQ/steal time is hidden from the task clock we
7136 * need to scale the task numbers:
7139 * U' = irq + --------- * U
7142 util
= scale_irq_capacity(util
, irq
, max
);
7146 * Bandwidth required by DEADLINE must always be granted while, for
7147 * FAIR and RT, we use blocked utilization of IDLE CPUs as a mechanism
7148 * to gracefully reduce the frequency when no tasks show up for longer
7151 * Ideally we would like to set bw_dl as min/guaranteed freq and util +
7152 * bw_dl as requested freq. However, cpufreq is not yet ready for such
7153 * an interface. So, we only do the latter for now.
7155 if (type
== FREQUENCY_UTIL
)
7156 util
+= cpu_bw_dl(rq
);
7158 return min(max
, util
);
7161 unsigned long sched_cpu_util(int cpu
, unsigned long max
)
7163 return effective_cpu_util(cpu
, cpu_util_cfs(cpu_rq(cpu
)), max
,
7166 #endif /* CONFIG_SMP */
7169 * find_process_by_pid - find a process with a matching PID value.
7170 * @pid: the pid in question.
7172 * The task of @pid, if found. %NULL otherwise.
7174 static struct task_struct
*find_process_by_pid(pid_t pid
)
7176 return pid
? find_task_by_vpid(pid
) : current
;
7180 * sched_setparam() passes in -1 for its policy, to let the functions
7181 * it calls know not to change it.
7183 #define SETPARAM_POLICY -1
7185 static void __setscheduler_params(struct task_struct
*p
,
7186 const struct sched_attr
*attr
)
7188 int policy
= attr
->sched_policy
;
7190 if (policy
== SETPARAM_POLICY
)
7195 if (dl_policy(policy
))
7196 __setparam_dl(p
, attr
);
7197 else if (fair_policy(policy
))
7198 p
->static_prio
= NICE_TO_PRIO(attr
->sched_nice
);
7201 * __sched_setscheduler() ensures attr->sched_priority == 0 when
7202 * !rt_policy. Always setting this ensures that things like
7203 * getparam()/getattr() don't report silly values for !rt tasks.
7205 p
->rt_priority
= attr
->sched_priority
;
7206 p
->normal_prio
= normal_prio(p
);
7207 set_load_weight(p
, true);
7211 * Check the target process has a UID that matches the current process's:
7213 static bool check_same_owner(struct task_struct
*p
)
7215 const struct cred
*cred
= current_cred(), *pcred
;
7219 pcred
= __task_cred(p
);
7220 match
= (uid_eq(cred
->euid
, pcred
->euid
) ||
7221 uid_eq(cred
->euid
, pcred
->uid
));
7226 static int __sched_setscheduler(struct task_struct
*p
,
7227 const struct sched_attr
*attr
,
7230 int oldpolicy
= -1, policy
= attr
->sched_policy
;
7231 int retval
, oldprio
, newprio
, queued
, running
;
7232 const struct sched_class
*prev_class
;
7233 struct callback_head
*head
;
7236 int queue_flags
= DEQUEUE_SAVE
| DEQUEUE_MOVE
| DEQUEUE_NOCLOCK
;
7239 /* The pi code expects interrupts enabled */
7240 BUG_ON(pi
&& in_interrupt());
7242 /* Double check policy once rq lock held: */
7244 reset_on_fork
= p
->sched_reset_on_fork
;
7245 policy
= oldpolicy
= p
->policy
;
7247 reset_on_fork
= !!(attr
->sched_flags
& SCHED_FLAG_RESET_ON_FORK
);
7249 if (!valid_policy(policy
))
7253 if (attr
->sched_flags
& ~(SCHED_FLAG_ALL
| SCHED_FLAG_SUGOV
))
7257 * Valid priorities for SCHED_FIFO and SCHED_RR are
7258 * 1..MAX_RT_PRIO-1, valid priority for SCHED_NORMAL,
7259 * SCHED_BATCH and SCHED_IDLE is 0.
7261 if (attr
->sched_priority
> MAX_RT_PRIO
-1)
7263 if ((dl_policy(policy
) && !__checkparam_dl(attr
)) ||
7264 (rt_policy(policy
) != (attr
->sched_priority
!= 0)))
7268 * Allow unprivileged RT tasks to decrease priority:
7270 if (user
&& !capable(CAP_SYS_NICE
)) {
7271 if (fair_policy(policy
)) {
7272 if (attr
->sched_nice
< task_nice(p
) &&
7273 !can_nice(p
, attr
->sched_nice
))
7277 if (rt_policy(policy
)) {
7278 unsigned long rlim_rtprio
=
7279 task_rlimit(p
, RLIMIT_RTPRIO
);
7281 /* Can't set/change the rt policy: */
7282 if (policy
!= p
->policy
&& !rlim_rtprio
)
7285 /* Can't increase priority: */
7286 if (attr
->sched_priority
> p
->rt_priority
&&
7287 attr
->sched_priority
> rlim_rtprio
)
7292 * Can't set/change SCHED_DEADLINE policy at all for now
7293 * (safest behavior); in the future we would like to allow
7294 * unprivileged DL tasks to increase their relative deadline
7295 * or reduce their runtime (both ways reducing utilization)
7297 if (dl_policy(policy
))
7301 * Treat SCHED_IDLE as nice 20. Only allow a switch to
7302 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
7304 if (task_has_idle_policy(p
) && !idle_policy(policy
)) {
7305 if (!can_nice(p
, task_nice(p
)))
7309 /* Can't change other user's priorities: */
7310 if (!check_same_owner(p
))
7313 /* Normal users shall not reset the sched_reset_on_fork flag: */
7314 if (p
->sched_reset_on_fork
&& !reset_on_fork
)
7319 if (attr
->sched_flags
& SCHED_FLAG_SUGOV
)
7322 retval
= security_task_setscheduler(p
);
7327 /* Update task specific "requested" clamps */
7328 if (attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP
) {
7329 retval
= uclamp_validate(p
, attr
);
7338 * Make sure no PI-waiters arrive (or leave) while we are
7339 * changing the priority of the task:
7341 * To be able to change p->policy safely, the appropriate
7342 * runqueue lock must be held.
7344 rq
= task_rq_lock(p
, &rf
);
7345 update_rq_clock(rq
);
7348 * Changing the policy of the stop threads its a very bad idea:
7350 if (p
== rq
->stop
) {
7356 * If not changing anything there's no need to proceed further,
7357 * but store a possible modification of reset_on_fork.
7359 if (unlikely(policy
== p
->policy
)) {
7360 if (fair_policy(policy
) && attr
->sched_nice
!= task_nice(p
))
7362 if (rt_policy(policy
) && attr
->sched_priority
!= p
->rt_priority
)
7364 if (dl_policy(policy
) && dl_param_changed(p
, attr
))
7366 if (attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP
)
7369 p
->sched_reset_on_fork
= reset_on_fork
;
7376 #ifdef CONFIG_RT_GROUP_SCHED
7378 * Do not allow realtime tasks into groups that have no runtime
7381 if (rt_bandwidth_enabled() && rt_policy(policy
) &&
7382 task_group(p
)->rt_bandwidth
.rt_runtime
== 0 &&
7383 !task_group_is_autogroup(task_group(p
))) {
7389 if (dl_bandwidth_enabled() && dl_policy(policy
) &&
7390 !(attr
->sched_flags
& SCHED_FLAG_SUGOV
)) {
7391 cpumask_t
*span
= rq
->rd
->span
;
7394 * Don't allow tasks with an affinity mask smaller than
7395 * the entire root_domain to become SCHED_DEADLINE. We
7396 * will also fail if there's no bandwidth available.
7398 if (!cpumask_subset(span
, p
->cpus_ptr
) ||
7399 rq
->rd
->dl_bw
.bw
== 0) {
7407 /* Re-check policy now with rq lock held: */
7408 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
7409 policy
= oldpolicy
= -1;
7410 task_rq_unlock(rq
, p
, &rf
);
7412 cpuset_read_unlock();
7417 * If setscheduling to SCHED_DEADLINE (or changing the parameters
7418 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
7421 if ((dl_policy(policy
) || dl_task(p
)) && sched_dl_overflow(p
, policy
, attr
)) {
7426 p
->sched_reset_on_fork
= reset_on_fork
;
7429 newprio
= __normal_prio(policy
, attr
->sched_priority
, attr
->sched_nice
);
7432 * Take priority boosted tasks into account. If the new
7433 * effective priority is unchanged, we just store the new
7434 * normal parameters and do not touch the scheduler class and
7435 * the runqueue. This will be done when the task deboost
7438 newprio
= rt_effective_prio(p
, newprio
);
7439 if (newprio
== oldprio
)
7440 queue_flags
&= ~DEQUEUE_MOVE
;
7443 queued
= task_on_rq_queued(p
);
7444 running
= task_current(rq
, p
);
7446 dequeue_task(rq
, p
, queue_flags
);
7448 put_prev_task(rq
, p
);
7450 prev_class
= p
->sched_class
;
7452 if (!(attr
->sched_flags
& SCHED_FLAG_KEEP_PARAMS
)) {
7453 __setscheduler_params(p
, attr
);
7454 __setscheduler_prio(p
, newprio
);
7456 __setscheduler_uclamp(p
, attr
);
7460 * We enqueue to tail when the priority of a task is
7461 * increased (user space view).
7463 if (oldprio
< p
->prio
)
7464 queue_flags
|= ENQUEUE_HEAD
;
7466 enqueue_task(rq
, p
, queue_flags
);
7469 set_next_task(rq
, p
);
7471 check_class_changed(rq
, p
, prev_class
, oldprio
);
7473 /* Avoid rq from going away on us: */
7475 head
= splice_balance_callbacks(rq
);
7476 task_rq_unlock(rq
, p
, &rf
);
7479 cpuset_read_unlock();
7480 rt_mutex_adjust_pi(p
);
7483 /* Run balance callbacks after we've adjusted the PI chain: */
7484 balance_callbacks(rq
, head
);
7490 task_rq_unlock(rq
, p
, &rf
);
7492 cpuset_read_unlock();
7496 static int _sched_setscheduler(struct task_struct
*p
, int policy
,
7497 const struct sched_param
*param
, bool check
)
7499 struct sched_attr attr
= {
7500 .sched_policy
= policy
,
7501 .sched_priority
= param
->sched_priority
,
7502 .sched_nice
= PRIO_TO_NICE(p
->static_prio
),
7505 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
7506 if ((policy
!= SETPARAM_POLICY
) && (policy
& SCHED_RESET_ON_FORK
)) {
7507 attr
.sched_flags
|= SCHED_FLAG_RESET_ON_FORK
;
7508 policy
&= ~SCHED_RESET_ON_FORK
;
7509 attr
.sched_policy
= policy
;
7512 return __sched_setscheduler(p
, &attr
, check
, true);
7515 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
7516 * @p: the task in question.
7517 * @policy: new policy.
7518 * @param: structure containing the new RT priority.
7520 * Use sched_set_fifo(), read its comment.
7522 * Return: 0 on success. An error code otherwise.
7524 * NOTE that the task may be already dead.
7526 int sched_setscheduler(struct task_struct
*p
, int policy
,
7527 const struct sched_param
*param
)
7529 return _sched_setscheduler(p
, policy
, param
, true);
7532 int sched_setattr(struct task_struct
*p
, const struct sched_attr
*attr
)
7534 return __sched_setscheduler(p
, attr
, true, true);
7537 int sched_setattr_nocheck(struct task_struct
*p
, const struct sched_attr
*attr
)
7539 return __sched_setscheduler(p
, attr
, false, true);
7541 EXPORT_SYMBOL_GPL(sched_setattr_nocheck
);
7544 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
7545 * @p: the task in question.
7546 * @policy: new policy.
7547 * @param: structure containing the new RT priority.
7549 * Just like sched_setscheduler, only don't bother checking if the
7550 * current context has permission. For example, this is needed in
7551 * stop_machine(): we create temporary high priority worker threads,
7552 * but our caller might not have that capability.
7554 * Return: 0 on success. An error code otherwise.
7556 int sched_setscheduler_nocheck(struct task_struct
*p
, int policy
,
7557 const struct sched_param
*param
)
7559 return _sched_setscheduler(p
, policy
, param
, false);
7563 * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
7564 * incapable of resource management, which is the one thing an OS really should
7567 * This is of course the reason it is limited to privileged users only.
7569 * Worse still; it is fundamentally impossible to compose static priority
7570 * workloads. You cannot take two correctly working static prio workloads
7571 * and smash them together and still expect them to work.
7573 * For this reason 'all' FIFO tasks the kernel creates are basically at:
7577 * The administrator _MUST_ configure the system, the kernel simply doesn't
7578 * know enough information to make a sensible choice.
7580 void sched_set_fifo(struct task_struct
*p
)
7582 struct sched_param sp
= { .sched_priority
= MAX_RT_PRIO
/ 2 };
7583 WARN_ON_ONCE(sched_setscheduler_nocheck(p
, SCHED_FIFO
, &sp
) != 0);
7585 EXPORT_SYMBOL_GPL(sched_set_fifo
);
7588 * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
7590 void sched_set_fifo_low(struct task_struct
*p
)
7592 struct sched_param sp
= { .sched_priority
= 1 };
7593 WARN_ON_ONCE(sched_setscheduler_nocheck(p
, SCHED_FIFO
, &sp
) != 0);
7595 EXPORT_SYMBOL_GPL(sched_set_fifo_low
);
7597 void sched_set_normal(struct task_struct
*p
, int nice
)
7599 struct sched_attr attr
= {
7600 .sched_policy
= SCHED_NORMAL
,
7603 WARN_ON_ONCE(sched_setattr_nocheck(p
, &attr
) != 0);
7605 EXPORT_SYMBOL_GPL(sched_set_normal
);
7608 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
7610 struct sched_param lparam
;
7611 struct task_struct
*p
;
7614 if (!param
|| pid
< 0)
7616 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
7621 p
= find_process_by_pid(pid
);
7627 retval
= sched_setscheduler(p
, policy
, &lparam
);
7635 * Mimics kernel/events/core.c perf_copy_attr().
7637 static int sched_copy_attr(struct sched_attr __user
*uattr
, struct sched_attr
*attr
)
7642 /* Zero the full structure, so that a short copy will be nice: */
7643 memset(attr
, 0, sizeof(*attr
));
7645 ret
= get_user(size
, &uattr
->size
);
7649 /* ABI compatibility quirk: */
7651 size
= SCHED_ATTR_SIZE_VER0
;
7652 if (size
< SCHED_ATTR_SIZE_VER0
|| size
> PAGE_SIZE
)
7655 ret
= copy_struct_from_user(attr
, sizeof(*attr
), uattr
, size
);
7662 if ((attr
->sched_flags
& SCHED_FLAG_UTIL_CLAMP
) &&
7663 size
< SCHED_ATTR_SIZE_VER1
)
7667 * XXX: Do we want to be lenient like existing syscalls; or do we want
7668 * to be strict and return an error on out-of-bounds values?
7670 attr
->sched_nice
= clamp(attr
->sched_nice
, MIN_NICE
, MAX_NICE
);
7675 put_user(sizeof(*attr
), &uattr
->size
);
7679 static void get_params(struct task_struct
*p
, struct sched_attr
*attr
)
7681 if (task_has_dl_policy(p
))
7682 __getparam_dl(p
, attr
);
7683 else if (task_has_rt_policy(p
))
7684 attr
->sched_priority
= p
->rt_priority
;
7686 attr
->sched_nice
= task_nice(p
);
7690 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
7691 * @pid: the pid in question.
7692 * @policy: new policy.
7693 * @param: structure containing the new RT priority.
7695 * Return: 0 on success. An error code otherwise.
7697 SYSCALL_DEFINE3(sched_setscheduler
, pid_t
, pid
, int, policy
, struct sched_param __user
*, param
)
7702 return do_sched_setscheduler(pid
, policy
, param
);
7706 * sys_sched_setparam - set/change the RT priority of a thread
7707 * @pid: the pid in question.
7708 * @param: structure containing the new RT priority.
7710 * Return: 0 on success. An error code otherwise.
7712 SYSCALL_DEFINE2(sched_setparam
, pid_t
, pid
, struct sched_param __user
*, param
)
7714 return do_sched_setscheduler(pid
, SETPARAM_POLICY
, param
);
7718 * sys_sched_setattr - same as above, but with extended sched_attr
7719 * @pid: the pid in question.
7720 * @uattr: structure containing the extended parameters.
7721 * @flags: for future extension.
7723 SYSCALL_DEFINE3(sched_setattr
, pid_t
, pid
, struct sched_attr __user
*, uattr
,
7724 unsigned int, flags
)
7726 struct sched_attr attr
;
7727 struct task_struct
*p
;
7730 if (!uattr
|| pid
< 0 || flags
)
7733 retval
= sched_copy_attr(uattr
, &attr
);
7737 if ((int)attr
.sched_policy
< 0)
7739 if (attr
.sched_flags
& SCHED_FLAG_KEEP_POLICY
)
7740 attr
.sched_policy
= SETPARAM_POLICY
;
7744 p
= find_process_by_pid(pid
);
7750 if (attr
.sched_flags
& SCHED_FLAG_KEEP_PARAMS
)
7751 get_params(p
, &attr
);
7752 retval
= sched_setattr(p
, &attr
);
7760 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
7761 * @pid: the pid in question.
7763 * Return: On success, the policy of the thread. Otherwise, a negative error
7766 SYSCALL_DEFINE1(sched_getscheduler
, pid_t
, pid
)
7768 struct task_struct
*p
;
7776 p
= find_process_by_pid(pid
);
7778 retval
= security_task_getscheduler(p
);
7781 | (p
->sched_reset_on_fork
? SCHED_RESET_ON_FORK
: 0);
7788 * sys_sched_getparam - get the RT priority of a thread
7789 * @pid: the pid in question.
7790 * @param: structure containing the RT priority.
7792 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
7795 SYSCALL_DEFINE2(sched_getparam
, pid_t
, pid
, struct sched_param __user
*, param
)
7797 struct sched_param lp
= { .sched_priority
= 0 };
7798 struct task_struct
*p
;
7801 if (!param
|| pid
< 0)
7805 p
= find_process_by_pid(pid
);
7810 retval
= security_task_getscheduler(p
);
7814 if (task_has_rt_policy(p
))
7815 lp
.sched_priority
= p
->rt_priority
;
7819 * This one might sleep, we cannot do it with a spinlock held ...
7821 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
7831 * Copy the kernel size attribute structure (which might be larger
7832 * than what user-space knows about) to user-space.
7834 * Note that all cases are valid: user-space buffer can be larger or
7835 * smaller than the kernel-space buffer. The usual case is that both
7836 * have the same size.
7839 sched_attr_copy_to_user(struct sched_attr __user
*uattr
,
7840 struct sched_attr
*kattr
,
7843 unsigned int ksize
= sizeof(*kattr
);
7845 if (!access_ok(uattr
, usize
))
7849 * sched_getattr() ABI forwards and backwards compatibility:
7851 * If usize == ksize then we just copy everything to user-space and all is good.
7853 * If usize < ksize then we only copy as much as user-space has space for,
7854 * this keeps ABI compatibility as well. We skip the rest.
7856 * If usize > ksize then user-space is using a newer version of the ABI,
7857 * which part the kernel doesn't know about. Just ignore it - tooling can
7858 * detect the kernel's knowledge of attributes from the attr->size value
7859 * which is set to ksize in this case.
7861 kattr
->size
= min(usize
, ksize
);
7863 if (copy_to_user(uattr
, kattr
, kattr
->size
))
7870 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
7871 * @pid: the pid in question.
7872 * @uattr: structure containing the extended parameters.
7873 * @usize: sizeof(attr) for fwd/bwd comp.
7874 * @flags: for future extension.
7876 SYSCALL_DEFINE4(sched_getattr
, pid_t
, pid
, struct sched_attr __user
*, uattr
,
7877 unsigned int, usize
, unsigned int, flags
)
7879 struct sched_attr kattr
= { };
7880 struct task_struct
*p
;
7883 if (!uattr
|| pid
< 0 || usize
> PAGE_SIZE
||
7884 usize
< SCHED_ATTR_SIZE_VER0
|| flags
)
7888 p
= find_process_by_pid(pid
);
7893 retval
= security_task_getscheduler(p
);
7897 kattr
.sched_policy
= p
->policy
;
7898 if (p
->sched_reset_on_fork
)
7899 kattr
.sched_flags
|= SCHED_FLAG_RESET_ON_FORK
;
7900 get_params(p
, &kattr
);
7901 kattr
.sched_flags
&= SCHED_FLAG_ALL
;
7903 #ifdef CONFIG_UCLAMP_TASK
7905 * This could race with another potential updater, but this is fine
7906 * because it'll correctly read the old or the new value. We don't need
7907 * to guarantee who wins the race as long as it doesn't return garbage.
7909 kattr
.sched_util_min
= p
->uclamp_req
[UCLAMP_MIN
].value
;
7910 kattr
.sched_util_max
= p
->uclamp_req
[UCLAMP_MAX
].value
;
7915 return sched_attr_copy_to_user(uattr
, &kattr
, usize
);
7923 int dl_task_check_affinity(struct task_struct
*p
, const struct cpumask
*mask
)
7928 * If the task isn't a deadline task or admission control is
7929 * disabled then we don't care about affinity changes.
7931 if (!task_has_dl_policy(p
) || !dl_bandwidth_enabled())
7935 * Since bandwidth control happens on root_domain basis,
7936 * if admission test is enabled, we only admit -deadline
7937 * tasks allowed to run on all the CPUs in the task's
7941 if (!cpumask_subset(task_rq(p
)->rd
->span
, mask
))
7949 __sched_setaffinity(struct task_struct
*p
, const struct cpumask
*mask
)
7952 cpumask_var_t cpus_allowed
, new_mask
;
7954 if (!alloc_cpumask_var(&cpus_allowed
, GFP_KERNEL
))
7957 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
)) {
7959 goto out_free_cpus_allowed
;
7962 cpuset_cpus_allowed(p
, cpus_allowed
);
7963 cpumask_and(new_mask
, mask
, cpus_allowed
);
7965 retval
= dl_task_check_affinity(p
, new_mask
);
7967 goto out_free_new_mask
;
7969 retval
= __set_cpus_allowed_ptr(p
, new_mask
, SCA_CHECK
| SCA_USER
);
7971 goto out_free_new_mask
;
7973 cpuset_cpus_allowed(p
, cpus_allowed
);
7974 if (!cpumask_subset(new_mask
, cpus_allowed
)) {
7976 * We must have raced with a concurrent cpuset update.
7977 * Just reset the cpumask to the cpuset's cpus_allowed.
7979 cpumask_copy(new_mask
, cpus_allowed
);
7984 free_cpumask_var(new_mask
);
7985 out_free_cpus_allowed
:
7986 free_cpumask_var(cpus_allowed
);
7990 long sched_setaffinity(pid_t pid
, const struct cpumask
*in_mask
)
7992 struct task_struct
*p
;
7997 p
= find_process_by_pid(pid
);
8003 /* Prevent p going away */
8007 if (p
->flags
& PF_NO_SETAFFINITY
) {
8012 if (!check_same_owner(p
)) {
8014 if (!ns_capable(__task_cred(p
)->user_ns
, CAP_SYS_NICE
)) {
8022 retval
= security_task_setscheduler(p
);
8026 retval
= __sched_setaffinity(p
, in_mask
);
8032 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
8033 struct cpumask
*new_mask
)
8035 if (len
< cpumask_size())
8036 cpumask_clear(new_mask
);
8037 else if (len
> cpumask_size())
8038 len
= cpumask_size();
8040 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
8044 * sys_sched_setaffinity - set the CPU affinity of a process
8045 * @pid: pid of the process
8046 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8047 * @user_mask_ptr: user-space pointer to the new CPU mask
8049 * Return: 0 on success. An error code otherwise.
8051 SYSCALL_DEFINE3(sched_setaffinity
, pid_t
, pid
, unsigned int, len
,
8052 unsigned long __user
*, user_mask_ptr
)
8054 cpumask_var_t new_mask
;
8057 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
))
8060 retval
= get_user_cpu_mask(user_mask_ptr
, len
, new_mask
);
8062 retval
= sched_setaffinity(pid
, new_mask
);
8063 free_cpumask_var(new_mask
);
8067 long sched_getaffinity(pid_t pid
, struct cpumask
*mask
)
8069 struct task_struct
*p
;
8070 unsigned long flags
;
8076 p
= find_process_by_pid(pid
);
8080 retval
= security_task_getscheduler(p
);
8084 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
8085 cpumask_and(mask
, &p
->cpus_mask
, cpu_active_mask
);
8086 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
8095 * sys_sched_getaffinity - get the CPU affinity of a process
8096 * @pid: pid of the process
8097 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8098 * @user_mask_ptr: user-space pointer to hold the current CPU mask
8100 * Return: size of CPU mask copied to user_mask_ptr on success. An
8101 * error code otherwise.
8103 SYSCALL_DEFINE3(sched_getaffinity
, pid_t
, pid
, unsigned int, len
,
8104 unsigned long __user
*, user_mask_ptr
)
8109 if ((len
* BITS_PER_BYTE
) < nr_cpu_ids
)
8111 if (len
& (sizeof(unsigned long)-1))
8114 if (!alloc_cpumask_var(&mask
, GFP_KERNEL
))
8117 ret
= sched_getaffinity(pid
, mask
);
8119 unsigned int retlen
= min(len
, cpumask_size());
8121 if (copy_to_user(user_mask_ptr
, mask
, retlen
))
8126 free_cpumask_var(mask
);
8131 static void do_sched_yield(void)
8136 rq
= this_rq_lock_irq(&rf
);
8138 schedstat_inc(rq
->yld_count
);
8139 current
->sched_class
->yield_task(rq
);
8142 rq_unlock_irq(rq
, &rf
);
8143 sched_preempt_enable_no_resched();
8149 * sys_sched_yield - yield the current processor to other threads.
8151 * This function yields the current CPU to other tasks. If there are no
8152 * other threads running on this CPU then this function will return.
8156 SYSCALL_DEFINE0(sched_yield
)
8162 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
8163 int __sched
__cond_resched(void)
8165 if (should_resched(0)) {
8166 preempt_schedule_common();
8170 * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
8171 * whether the current CPU is in an RCU read-side critical section,
8172 * so the tick can report quiescent states even for CPUs looping
8173 * in kernel context. In contrast, in non-preemptible kernels,
8174 * RCU readers leave no in-memory hints, which means that CPU-bound
8175 * processes executing in kernel context might never report an
8176 * RCU quiescent state. Therefore, the following code causes
8177 * cond_resched() to report a quiescent state, but only when RCU
8178 * is in urgent need of one.
8180 #ifndef CONFIG_PREEMPT_RCU
8185 EXPORT_SYMBOL(__cond_resched
);
8188 #ifdef CONFIG_PREEMPT_DYNAMIC
8189 DEFINE_STATIC_CALL_RET0(cond_resched
, __cond_resched
);
8190 EXPORT_STATIC_CALL_TRAMP(cond_resched
);
8192 DEFINE_STATIC_CALL_RET0(might_resched
, __cond_resched
);
8193 EXPORT_STATIC_CALL_TRAMP(might_resched
);
8197 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
8198 * call schedule, and on return reacquire the lock.
8200 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
8201 * operations here to prevent schedule() from being called twice (once via
8202 * spin_unlock(), once by hand).
8204 int __cond_resched_lock(spinlock_t
*lock
)
8206 int resched
= should_resched(PREEMPT_LOCK_OFFSET
);
8209 lockdep_assert_held(lock
);
8211 if (spin_needbreak(lock
) || resched
) {
8213 if (!_cond_resched())
8220 EXPORT_SYMBOL(__cond_resched_lock
);
8222 int __cond_resched_rwlock_read(rwlock_t
*lock
)
8224 int resched
= should_resched(PREEMPT_LOCK_OFFSET
);
8227 lockdep_assert_held_read(lock
);
8229 if (rwlock_needbreak(lock
) || resched
) {
8231 if (!_cond_resched())
8238 EXPORT_SYMBOL(__cond_resched_rwlock_read
);
8240 int __cond_resched_rwlock_write(rwlock_t
*lock
)
8242 int resched
= should_resched(PREEMPT_LOCK_OFFSET
);
8245 lockdep_assert_held_write(lock
);
8247 if (rwlock_needbreak(lock
) || resched
) {
8249 if (!_cond_resched())
8256 EXPORT_SYMBOL(__cond_resched_rwlock_write
);
8259 * yield - yield the current processor to other threads.
8261 * Do not ever use this function, there's a 99% chance you're doing it wrong.
8263 * The scheduler is at all times free to pick the calling task as the most
8264 * eligible task to run, if removing the yield() call from your code breaks
8265 * it, it's already broken.
8267 * Typical broken usage is:
8272 * where one assumes that yield() will let 'the other' process run that will
8273 * make event true. If the current task is a SCHED_FIFO task that will never
8274 * happen. Never use yield() as a progress guarantee!!
8276 * If you want to use yield() to wait for something, use wait_event().
8277 * If you want to use yield() to be 'nice' for others, use cond_resched().
8278 * If you still want to use yield(), do not!
8280 void __sched
yield(void)
8282 set_current_state(TASK_RUNNING
);
8285 EXPORT_SYMBOL(yield
);
8288 * yield_to - yield the current processor to another thread in
8289 * your thread group, or accelerate that thread toward the
8290 * processor it's on.
8292 * @preempt: whether task preemption is allowed or not
8294 * It's the caller's job to ensure that the target task struct
8295 * can't go away on us before we can do any checks.
8298 * true (>0) if we indeed boosted the target task.
8299 * false (0) if we failed to boost the target.
8300 * -ESRCH if there's no task to yield to.
8302 int __sched
yield_to(struct task_struct
*p
, bool preempt
)
8304 struct task_struct
*curr
= current
;
8305 struct rq
*rq
, *p_rq
;
8306 unsigned long flags
;
8309 local_irq_save(flags
);
8315 * If we're the only runnable task on the rq and target rq also
8316 * has only one task, there's absolutely no point in yielding.
8318 if (rq
->nr_running
== 1 && p_rq
->nr_running
== 1) {
8323 double_rq_lock(rq
, p_rq
);
8324 if (task_rq(p
) != p_rq
) {
8325 double_rq_unlock(rq
, p_rq
);
8329 if (!curr
->sched_class
->yield_to_task
)
8332 if (curr
->sched_class
!= p
->sched_class
)
8335 if (task_running(p_rq
, p
) || !task_is_running(p
))
8338 yielded
= curr
->sched_class
->yield_to_task(rq
, p
);
8340 schedstat_inc(rq
->yld_count
);
8342 * Make p's CPU reschedule; pick_next_entity takes care of
8345 if (preempt
&& rq
!= p_rq
)
8350 double_rq_unlock(rq
, p_rq
);
8352 local_irq_restore(flags
);
8359 EXPORT_SYMBOL_GPL(yield_to
);
8361 int io_schedule_prepare(void)
8363 int old_iowait
= current
->in_iowait
;
8365 current
->in_iowait
= 1;
8366 blk_schedule_flush_plug(current
);
8371 void io_schedule_finish(int token
)
8373 current
->in_iowait
= token
;
8377 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
8378 * that process accounting knows that this is a task in IO wait state.
8380 long __sched
io_schedule_timeout(long timeout
)
8385 token
= io_schedule_prepare();
8386 ret
= schedule_timeout(timeout
);
8387 io_schedule_finish(token
);
8391 EXPORT_SYMBOL(io_schedule_timeout
);
8393 void __sched
io_schedule(void)
8397 token
= io_schedule_prepare();
8399 io_schedule_finish(token
);
8401 EXPORT_SYMBOL(io_schedule
);
8404 * sys_sched_get_priority_max - return maximum RT priority.
8405 * @policy: scheduling class.
8407 * Return: On success, this syscall returns the maximum
8408 * rt_priority that can be used by a given scheduling class.
8409 * On failure, a negative error code is returned.
8411 SYSCALL_DEFINE1(sched_get_priority_max
, int, policy
)
8418 ret
= MAX_RT_PRIO
-1;
8420 case SCHED_DEADLINE
:
8431 * sys_sched_get_priority_min - return minimum RT priority.
8432 * @policy: scheduling class.
8434 * Return: On success, this syscall returns the minimum
8435 * rt_priority that can be used by a given scheduling class.
8436 * On failure, a negative error code is returned.
8438 SYSCALL_DEFINE1(sched_get_priority_min
, int, policy
)
8447 case SCHED_DEADLINE
:
8456 static int sched_rr_get_interval(pid_t pid
, struct timespec64
*t
)
8458 struct task_struct
*p
;
8459 unsigned int time_slice
;
8469 p
= find_process_by_pid(pid
);
8473 retval
= security_task_getscheduler(p
);
8477 rq
= task_rq_lock(p
, &rf
);
8479 if (p
->sched_class
->get_rr_interval
)
8480 time_slice
= p
->sched_class
->get_rr_interval(rq
, p
);
8481 task_rq_unlock(rq
, p
, &rf
);
8484 jiffies_to_timespec64(time_slice
, t
);
8493 * sys_sched_rr_get_interval - return the default timeslice of a process.
8494 * @pid: pid of the process.
8495 * @interval: userspace pointer to the timeslice value.
8497 * this syscall writes the default timeslice value of a given process
8498 * into the user-space timespec buffer. A value of '0' means infinity.
8500 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
8503 SYSCALL_DEFINE2(sched_rr_get_interval
, pid_t
, pid
,
8504 struct __kernel_timespec __user
*, interval
)
8506 struct timespec64 t
;
8507 int retval
= sched_rr_get_interval(pid
, &t
);
8510 retval
= put_timespec64(&t
, interval
);
8515 #ifdef CONFIG_COMPAT_32BIT_TIME
8516 SYSCALL_DEFINE2(sched_rr_get_interval_time32
, pid_t
, pid
,
8517 struct old_timespec32 __user
*, interval
)
8519 struct timespec64 t
;
8520 int retval
= sched_rr_get_interval(pid
, &t
);
8523 retval
= put_old_timespec32(&t
, interval
);
8528 void sched_show_task(struct task_struct
*p
)
8530 unsigned long free
= 0;
8533 if (!try_get_task_stack(p
))
8536 pr_info("task:%-15.15s state:%c", p
->comm
, task_state_to_char(p
));
8538 if (task_is_running(p
))
8539 pr_cont(" running task ");
8540 #ifdef CONFIG_DEBUG_STACK_USAGE
8541 free
= stack_not_used(p
);
8546 ppid
= task_pid_nr(rcu_dereference(p
->real_parent
));
8548 pr_cont(" stack:%5lu pid:%5d ppid:%6d flags:0x%08lx\n",
8549 free
, task_pid_nr(p
), ppid
,
8550 (unsigned long)task_thread_info(p
)->flags
);
8552 print_worker_info(KERN_INFO
, p
);
8553 print_stop_info(KERN_INFO
, p
);
8554 show_stack(p
, NULL
, KERN_INFO
);
8557 EXPORT_SYMBOL_GPL(sched_show_task
);
8560 state_filter_match(unsigned long state_filter
, struct task_struct
*p
)
8562 unsigned int state
= READ_ONCE(p
->__state
);
8564 /* no filter, everything matches */
8568 /* filter, but doesn't match */
8569 if (!(state
& state_filter
))
8573 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
8576 if (state_filter
== TASK_UNINTERRUPTIBLE
&& state
== TASK_IDLE
)
8583 void show_state_filter(unsigned int state_filter
)
8585 struct task_struct
*g
, *p
;
8588 for_each_process_thread(g
, p
) {
8590 * reset the NMI-timeout, listing all files on a slow
8591 * console might take a lot of time:
8592 * Also, reset softlockup watchdogs on all CPUs, because
8593 * another CPU might be blocked waiting for us to process
8596 touch_nmi_watchdog();
8597 touch_all_softlockup_watchdogs();
8598 if (state_filter_match(state_filter
, p
))
8602 #ifdef CONFIG_SCHED_DEBUG
8604 sysrq_sched_debug_show();
8608 * Only show locks if all tasks are dumped:
8611 debug_show_all_locks();
8615 * init_idle - set up an idle thread for a given CPU
8616 * @idle: task in question
8617 * @cpu: CPU the idle task belongs to
8619 * NOTE: this function does not set the idle thread's NEED_RESCHED
8620 * flag, to make booting more robust.
8622 void __init
init_idle(struct task_struct
*idle
, int cpu
)
8624 struct rq
*rq
= cpu_rq(cpu
);
8625 unsigned long flags
;
8627 __sched_fork(0, idle
);
8630 * The idle task doesn't need the kthread struct to function, but it
8631 * is dressed up as a per-CPU kthread and thus needs to play the part
8632 * if we want to avoid special-casing it in code that deals with per-CPU
8635 set_kthread_struct(idle
);
8637 raw_spin_lock_irqsave(&idle
->pi_lock
, flags
);
8638 raw_spin_rq_lock(rq
);
8640 idle
->__state
= TASK_RUNNING
;
8641 idle
->se
.exec_start
= sched_clock();
8643 * PF_KTHREAD should already be set at this point; regardless, make it
8644 * look like a proper per-CPU kthread.
8646 idle
->flags
|= PF_IDLE
| PF_KTHREAD
| PF_NO_SETAFFINITY
;
8647 kthread_set_per_cpu(idle
, cpu
);
8651 * It's possible that init_idle() gets called multiple times on a task,
8652 * in that case do_set_cpus_allowed() will not do the right thing.
8654 * And since this is boot we can forgo the serialization.
8656 set_cpus_allowed_common(idle
, cpumask_of(cpu
), 0);
8659 * We're having a chicken and egg problem, even though we are
8660 * holding rq->lock, the CPU isn't yet set to this CPU so the
8661 * lockdep check in task_group() will fail.
8663 * Similar case to sched_fork(). / Alternatively we could
8664 * use task_rq_lock() here and obtain the other rq->lock.
8669 __set_task_cpu(idle
, cpu
);
8673 rcu_assign_pointer(rq
->curr
, idle
);
8674 idle
->on_rq
= TASK_ON_RQ_QUEUED
;
8678 raw_spin_rq_unlock(rq
);
8679 raw_spin_unlock_irqrestore(&idle
->pi_lock
, flags
);
8681 /* Set the preempt count _outside_ the spinlocks! */
8682 init_idle_preempt_count(idle
, cpu
);
8685 * The idle tasks have their own, simple scheduling class:
8687 idle
->sched_class
= &idle_sched_class
;
8688 ftrace_graph_init_idle_task(idle
, cpu
);
8689 vtime_init_idle(idle
, cpu
);
8691 sprintf(idle
->comm
, "%s/%d", INIT_TASK_COMM
, cpu
);
8697 int cpuset_cpumask_can_shrink(const struct cpumask
*cur
,
8698 const struct cpumask
*trial
)
8702 if (!cpumask_weight(cur
))
8705 ret
= dl_cpuset_cpumask_can_shrink(cur
, trial
);
8710 int task_can_attach(struct task_struct
*p
,
8711 const struct cpumask
*cs_cpus_allowed
)
8716 * Kthreads which disallow setaffinity shouldn't be moved
8717 * to a new cpuset; we don't want to change their CPU
8718 * affinity and isolating such threads by their set of
8719 * allowed nodes is unnecessary. Thus, cpusets are not
8720 * applicable for such threads. This prevents checking for
8721 * success of set_cpus_allowed_ptr() on all attached tasks
8722 * before cpus_mask may be changed.
8724 if (p
->flags
& PF_NO_SETAFFINITY
) {
8729 if (dl_task(p
) && !cpumask_intersects(task_rq(p
)->rd
->span
,
8731 ret
= dl_task_can_attach(p
, cs_cpus_allowed
);
8737 bool sched_smp_initialized __read_mostly
;
8739 #ifdef CONFIG_NUMA_BALANCING
8740 /* Migrate current task p to target_cpu */
8741 int migrate_task_to(struct task_struct
*p
, int target_cpu
)
8743 struct migration_arg arg
= { p
, target_cpu
};
8744 int curr_cpu
= task_cpu(p
);
8746 if (curr_cpu
== target_cpu
)
8749 if (!cpumask_test_cpu(target_cpu
, p
->cpus_ptr
))
8752 /* TODO: This is not properly updating schedstats */
8754 trace_sched_move_numa(p
, curr_cpu
, target_cpu
);
8755 return stop_one_cpu(curr_cpu
, migration_cpu_stop
, &arg
);
8759 * Requeue a task on a given node and accurately track the number of NUMA
8760 * tasks on the runqueues
8762 void sched_setnuma(struct task_struct
*p
, int nid
)
8764 bool queued
, running
;
8768 rq
= task_rq_lock(p
, &rf
);
8769 queued
= task_on_rq_queued(p
);
8770 running
= task_current(rq
, p
);
8773 dequeue_task(rq
, p
, DEQUEUE_SAVE
);
8775 put_prev_task(rq
, p
);
8777 p
->numa_preferred_nid
= nid
;
8780 enqueue_task(rq
, p
, ENQUEUE_RESTORE
| ENQUEUE_NOCLOCK
);
8782 set_next_task(rq
, p
);
8783 task_rq_unlock(rq
, p
, &rf
);
8785 #endif /* CONFIG_NUMA_BALANCING */
8787 #ifdef CONFIG_HOTPLUG_CPU
8789 * Ensure that the idle task is using init_mm right before its CPU goes
8792 void idle_task_exit(void)
8794 struct mm_struct
*mm
= current
->active_mm
;
8796 BUG_ON(cpu_online(smp_processor_id()));
8797 BUG_ON(current
!= this_rq()->idle
);
8799 if (mm
!= &init_mm
) {
8800 switch_mm(mm
, &init_mm
, current
);
8801 finish_arch_post_lock_switch();
8804 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
8807 static int __balance_push_cpu_stop(void *arg
)
8809 struct task_struct
*p
= arg
;
8810 struct rq
*rq
= this_rq();
8814 raw_spin_lock_irq(&p
->pi_lock
);
8817 update_rq_clock(rq
);
8819 if (task_rq(p
) == rq
&& task_on_rq_queued(p
)) {
8820 cpu
= select_fallback_rq(rq
->cpu
, p
);
8821 rq
= __migrate_task(rq
, &rf
, p
, cpu
);
8825 raw_spin_unlock_irq(&p
->pi_lock
);
8832 static DEFINE_PER_CPU(struct cpu_stop_work
, push_work
);
8835 * Ensure we only run per-cpu kthreads once the CPU goes !active.
8837 * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
8838 * effective when the hotplug motion is down.
8840 static void balance_push(struct rq
*rq
)
8842 struct task_struct
*push_task
= rq
->curr
;
8844 lockdep_assert_rq_held(rq
);
8847 * Ensure the thing is persistent until balance_push_set(.on = false);
8849 rq
->balance_callback
= &balance_push_callback
;
8852 * Only active while going offline and when invoked on the outgoing
8855 if (!cpu_dying(rq
->cpu
) || rq
!= this_rq())
8859 * Both the cpu-hotplug and stop task are in this case and are
8860 * required to complete the hotplug process.
8862 if (kthread_is_per_cpu(push_task
) ||
8863 is_migration_disabled(push_task
)) {
8866 * If this is the idle task on the outgoing CPU try to wake
8867 * up the hotplug control thread which might wait for the
8868 * last task to vanish. The rcuwait_active() check is
8869 * accurate here because the waiter is pinned on this CPU
8870 * and can't obviously be running in parallel.
8872 * On RT kernels this also has to check whether there are
8873 * pinned and scheduled out tasks on the runqueue. They
8874 * need to leave the migrate disabled section first.
8876 if (!rq
->nr_running
&& !rq_has_pinned_tasks(rq
) &&
8877 rcuwait_active(&rq
->hotplug_wait
)) {
8878 raw_spin_rq_unlock(rq
);
8879 rcuwait_wake_up(&rq
->hotplug_wait
);
8880 raw_spin_rq_lock(rq
);
8885 get_task_struct(push_task
);
8887 * Temporarily drop rq->lock such that we can wake-up the stop task.
8888 * Both preemption and IRQs are still disabled.
8890 raw_spin_rq_unlock(rq
);
8891 stop_one_cpu_nowait(rq
->cpu
, __balance_push_cpu_stop
, push_task
,
8892 this_cpu_ptr(&push_work
));
8894 * At this point need_resched() is true and we'll take the loop in
8895 * schedule(). The next pick is obviously going to be the stop task
8896 * which kthread_is_per_cpu() and will push this task away.
8898 raw_spin_rq_lock(rq
);
8901 static void balance_push_set(int cpu
, bool on
)
8903 struct rq
*rq
= cpu_rq(cpu
);
8906 rq_lock_irqsave(rq
, &rf
);
8908 WARN_ON_ONCE(rq
->balance_callback
);
8909 rq
->balance_callback
= &balance_push_callback
;
8910 } else if (rq
->balance_callback
== &balance_push_callback
) {
8911 rq
->balance_callback
= NULL
;
8913 rq_unlock_irqrestore(rq
, &rf
);
8917 * Invoked from a CPUs hotplug control thread after the CPU has been marked
8918 * inactive. All tasks which are not per CPU kernel threads are either
8919 * pushed off this CPU now via balance_push() or placed on a different CPU
8920 * during wakeup. Wait until the CPU is quiescent.
8922 static void balance_hotplug_wait(void)
8924 struct rq
*rq
= this_rq();
8926 rcuwait_wait_event(&rq
->hotplug_wait
,
8927 rq
->nr_running
== 1 && !rq_has_pinned_tasks(rq
),
8928 TASK_UNINTERRUPTIBLE
);
8933 static inline void balance_push(struct rq
*rq
)
8937 static inline void balance_push_set(int cpu
, bool on
)
8941 static inline void balance_hotplug_wait(void)
8945 #endif /* CONFIG_HOTPLUG_CPU */
8947 void set_rq_online(struct rq
*rq
)
8950 const struct sched_class
*class;
8952 cpumask_set_cpu(rq
->cpu
, rq
->rd
->online
);
8955 for_each_class(class) {
8956 if (class->rq_online
)
8957 class->rq_online(rq
);
8962 void set_rq_offline(struct rq
*rq
)
8965 const struct sched_class
*class;
8967 for_each_class(class) {
8968 if (class->rq_offline
)
8969 class->rq_offline(rq
);
8972 cpumask_clear_cpu(rq
->cpu
, rq
->rd
->online
);
8978 * used to mark begin/end of suspend/resume:
8980 static int num_cpus_frozen
;
8983 * Update cpusets according to cpu_active mask. If cpusets are
8984 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
8985 * around partition_sched_domains().
8987 * If we come here as part of a suspend/resume, don't touch cpusets because we
8988 * want to restore it back to its original state upon resume anyway.
8990 static void cpuset_cpu_active(void)
8992 if (cpuhp_tasks_frozen
) {
8994 * num_cpus_frozen tracks how many CPUs are involved in suspend
8995 * resume sequence. As long as this is not the last online
8996 * operation in the resume sequence, just build a single sched
8997 * domain, ignoring cpusets.
8999 partition_sched_domains(1, NULL
, NULL
);
9000 if (--num_cpus_frozen
)
9003 * This is the last CPU online operation. So fall through and
9004 * restore the original sched domains by considering the
9005 * cpuset configurations.
9007 cpuset_force_rebuild();
9009 cpuset_update_active_cpus();
9012 static int cpuset_cpu_inactive(unsigned int cpu
)
9014 if (!cpuhp_tasks_frozen
) {
9015 if (dl_cpu_busy(cpu
))
9017 cpuset_update_active_cpus();
9020 partition_sched_domains(1, NULL
, NULL
);
9025 int sched_cpu_activate(unsigned int cpu
)
9027 struct rq
*rq
= cpu_rq(cpu
);
9031 * Clear the balance_push callback and prepare to schedule
9034 balance_push_set(cpu
, false);
9036 #ifdef CONFIG_SCHED_SMT
9038 * When going up, increment the number of cores with SMT present.
9040 if (cpumask_weight(cpu_smt_mask(cpu
)) == 2)
9041 static_branch_inc_cpuslocked(&sched_smt_present
);
9043 set_cpu_active(cpu
, true);
9045 if (sched_smp_initialized
) {
9046 sched_domains_numa_masks_set(cpu
);
9047 cpuset_cpu_active();
9051 * Put the rq online, if not already. This happens:
9053 * 1) In the early boot process, because we build the real domains
9054 * after all CPUs have been brought up.
9056 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
9059 rq_lock_irqsave(rq
, &rf
);
9061 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
9064 rq_unlock_irqrestore(rq
, &rf
);
9069 int sched_cpu_deactivate(unsigned int cpu
)
9071 struct rq
*rq
= cpu_rq(cpu
);
9076 * Remove CPU from nohz.idle_cpus_mask to prevent participating in
9077 * load balancing when not active
9079 nohz_balance_exit_idle(rq
);
9081 set_cpu_active(cpu
, false);
9084 * From this point forward, this CPU will refuse to run any task that
9085 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
9086 * push those tasks away until this gets cleared, see
9087 * sched_cpu_dying().
9089 balance_push_set(cpu
, true);
9092 * We've cleared cpu_active_mask / set balance_push, wait for all
9093 * preempt-disabled and RCU users of this state to go away such that
9094 * all new such users will observe it.
9096 * Specifically, we rely on ttwu to no longer target this CPU, see
9097 * ttwu_queue_cond() and is_cpu_allowed().
9099 * Do sync before park smpboot threads to take care the rcu boost case.
9103 rq_lock_irqsave(rq
, &rf
);
9105 update_rq_clock(rq
);
9106 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
9109 rq_unlock_irqrestore(rq
, &rf
);
9111 #ifdef CONFIG_SCHED_SMT
9113 * When going down, decrement the number of cores with SMT present.
9115 if (cpumask_weight(cpu_smt_mask(cpu
)) == 2)
9116 static_branch_dec_cpuslocked(&sched_smt_present
);
9118 sched_core_cpu_deactivate(cpu
);
9121 if (!sched_smp_initialized
)
9124 ret
= cpuset_cpu_inactive(cpu
);
9126 balance_push_set(cpu
, false);
9127 set_cpu_active(cpu
, true);
9130 sched_domains_numa_masks_clear(cpu
);
9134 static void sched_rq_cpu_starting(unsigned int cpu
)
9136 struct rq
*rq
= cpu_rq(cpu
);
9138 rq
->calc_load_update
= calc_load_update
;
9139 update_max_interval();
9142 int sched_cpu_starting(unsigned int cpu
)
9144 sched_core_cpu_starting(cpu
);
9145 sched_rq_cpu_starting(cpu
);
9146 sched_tick_start(cpu
);
9150 #ifdef CONFIG_HOTPLUG_CPU
9153 * Invoked immediately before the stopper thread is invoked to bring the
9154 * CPU down completely. At this point all per CPU kthreads except the
9155 * hotplug thread (current) and the stopper thread (inactive) have been
9156 * either parked or have been unbound from the outgoing CPU. Ensure that
9157 * any of those which might be on the way out are gone.
9159 * If after this point a bound task is being woken on this CPU then the
9160 * responsible hotplug callback has failed to do it's job.
9161 * sched_cpu_dying() will catch it with the appropriate fireworks.
9163 int sched_cpu_wait_empty(unsigned int cpu
)
9165 balance_hotplug_wait();
9170 * Since this CPU is going 'away' for a while, fold any nr_active delta we
9171 * might have. Called from the CPU stopper task after ensuring that the
9172 * stopper is the last running task on the CPU, so nr_active count is
9173 * stable. We need to take the teardown thread which is calling this into
9174 * account, so we hand in adjust = 1 to the load calculation.
9176 * Also see the comment "Global load-average calculations".
9178 static void calc_load_migrate(struct rq
*rq
)
9180 long delta
= calc_load_fold_active(rq
, 1);
9183 atomic_long_add(delta
, &calc_load_tasks
);
9186 static void dump_rq_tasks(struct rq
*rq
, const char *loglvl
)
9188 struct task_struct
*g
, *p
;
9189 int cpu
= cpu_of(rq
);
9191 lockdep_assert_rq_held(rq
);
9193 printk("%sCPU%d enqueued tasks (%u total):\n", loglvl
, cpu
, rq
->nr_running
);
9194 for_each_process_thread(g
, p
) {
9195 if (task_cpu(p
) != cpu
)
9198 if (!task_on_rq_queued(p
))
9201 printk("%s\tpid: %d, name: %s\n", loglvl
, p
->pid
, p
->comm
);
9205 int sched_cpu_dying(unsigned int cpu
)
9207 struct rq
*rq
= cpu_rq(cpu
);
9210 /* Handle pending wakeups and then migrate everything off */
9211 sched_tick_stop(cpu
);
9213 rq_lock_irqsave(rq
, &rf
);
9214 if (rq
->nr_running
!= 1 || rq_has_pinned_tasks(rq
)) {
9215 WARN(true, "Dying CPU not properly vacated!");
9216 dump_rq_tasks(rq
, KERN_WARNING
);
9218 rq_unlock_irqrestore(rq
, &rf
);
9220 calc_load_migrate(rq
);
9221 update_max_interval();
9223 sched_core_cpu_dying(cpu
);
9228 void __init
sched_init_smp(void)
9233 * There's no userspace yet to cause hotplug operations; hence all the
9234 * CPU masks are stable and all blatant races in the below code cannot
9237 mutex_lock(&sched_domains_mutex
);
9238 sched_init_domains(cpu_active_mask
);
9239 mutex_unlock(&sched_domains_mutex
);
9241 /* Move init over to a non-isolated CPU */
9242 if (set_cpus_allowed_ptr(current
, housekeeping_cpumask(HK_FLAG_DOMAIN
)) < 0)
9244 current
->flags
&= ~PF_NO_SETAFFINITY
;
9245 sched_init_granularity();
9247 init_sched_rt_class();
9248 init_sched_dl_class();
9250 sched_smp_initialized
= true;
9253 static int __init
migration_init(void)
9255 sched_cpu_starting(smp_processor_id());
9258 early_initcall(migration_init
);
9261 void __init
sched_init_smp(void)
9263 sched_init_granularity();
9265 #endif /* CONFIG_SMP */
9267 int in_sched_functions(unsigned long addr
)
9269 return in_lock_functions(addr
) ||
9270 (addr
>= (unsigned long)__sched_text_start
9271 && addr
< (unsigned long)__sched_text_end
);
9274 #ifdef CONFIG_CGROUP_SCHED
9276 * Default task group.
9277 * Every task in system belongs to this group at bootup.
9279 struct task_group root_task_group
;
9280 LIST_HEAD(task_groups
);
9282 /* Cacheline aligned slab cache for task_group */
9283 static struct kmem_cache
*task_group_cache __read_mostly
;
9286 DECLARE_PER_CPU(cpumask_var_t
, load_balance_mask
);
9287 DECLARE_PER_CPU(cpumask_var_t
, select_idle_mask
);
9289 void __init
sched_init(void)
9291 unsigned long ptr
= 0;
9294 /* Make sure the linker didn't screw up */
9295 BUG_ON(&idle_sched_class
+ 1 != &fair_sched_class
||
9296 &fair_sched_class
+ 1 != &rt_sched_class
||
9297 &rt_sched_class
+ 1 != &dl_sched_class
);
9299 BUG_ON(&dl_sched_class
+ 1 != &stop_sched_class
);
9304 #ifdef CONFIG_FAIR_GROUP_SCHED
9305 ptr
+= 2 * nr_cpu_ids
* sizeof(void **);
9307 #ifdef CONFIG_RT_GROUP_SCHED
9308 ptr
+= 2 * nr_cpu_ids
* sizeof(void **);
9311 ptr
= (unsigned long)kzalloc(ptr
, GFP_NOWAIT
);
9313 #ifdef CONFIG_FAIR_GROUP_SCHED
9314 root_task_group
.se
= (struct sched_entity
**)ptr
;
9315 ptr
+= nr_cpu_ids
* sizeof(void **);
9317 root_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
9318 ptr
+= nr_cpu_ids
* sizeof(void **);
9320 root_task_group
.shares
= ROOT_TASK_GROUP_LOAD
;
9321 init_cfs_bandwidth(&root_task_group
.cfs_bandwidth
);
9322 #endif /* CONFIG_FAIR_GROUP_SCHED */
9323 #ifdef CONFIG_RT_GROUP_SCHED
9324 root_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
9325 ptr
+= nr_cpu_ids
* sizeof(void **);
9327 root_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
9328 ptr
+= nr_cpu_ids
* sizeof(void **);
9330 #endif /* CONFIG_RT_GROUP_SCHED */
9332 #ifdef CONFIG_CPUMASK_OFFSTACK
9333 for_each_possible_cpu(i
) {
9334 per_cpu(load_balance_mask
, i
) = (cpumask_var_t
)kzalloc_node(
9335 cpumask_size(), GFP_KERNEL
, cpu_to_node(i
));
9336 per_cpu(select_idle_mask
, i
) = (cpumask_var_t
)kzalloc_node(
9337 cpumask_size(), GFP_KERNEL
, cpu_to_node(i
));
9339 #endif /* CONFIG_CPUMASK_OFFSTACK */
9341 init_rt_bandwidth(&def_rt_bandwidth
, global_rt_period(), global_rt_runtime());
9342 init_dl_bandwidth(&def_dl_bandwidth
, global_rt_period(), global_rt_runtime());
9345 init_defrootdomain();
9348 #ifdef CONFIG_RT_GROUP_SCHED
9349 init_rt_bandwidth(&root_task_group
.rt_bandwidth
,
9350 global_rt_period(), global_rt_runtime());
9351 #endif /* CONFIG_RT_GROUP_SCHED */
9353 #ifdef CONFIG_CGROUP_SCHED
9354 task_group_cache
= KMEM_CACHE(task_group
, 0);
9356 list_add(&root_task_group
.list
, &task_groups
);
9357 INIT_LIST_HEAD(&root_task_group
.children
);
9358 INIT_LIST_HEAD(&root_task_group
.siblings
);
9359 autogroup_init(&init_task
);
9360 #endif /* CONFIG_CGROUP_SCHED */
9362 for_each_possible_cpu(i
) {
9366 raw_spin_lock_init(&rq
->__lock
);
9368 rq
->calc_load_active
= 0;
9369 rq
->calc_load_update
= jiffies
+ LOAD_FREQ
;
9370 init_cfs_rq(&rq
->cfs
);
9371 init_rt_rq(&rq
->rt
);
9372 init_dl_rq(&rq
->dl
);
9373 #ifdef CONFIG_FAIR_GROUP_SCHED
9374 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
9375 rq
->tmp_alone_branch
= &rq
->leaf_cfs_rq_list
;
9377 * How much CPU bandwidth does root_task_group get?
9379 * In case of task-groups formed thr' the cgroup filesystem, it
9380 * gets 100% of the CPU resources in the system. This overall
9381 * system CPU resource is divided among the tasks of
9382 * root_task_group and its child task-groups in a fair manner,
9383 * based on each entity's (task or task-group's) weight
9384 * (se->load.weight).
9386 * In other words, if root_task_group has 10 tasks of weight
9387 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9388 * then A0's share of the CPU resource is:
9390 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9392 * We achieve this by letting root_task_group's tasks sit
9393 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
9395 init_tg_cfs_entry(&root_task_group
, &rq
->cfs
, NULL
, i
, NULL
);
9396 #endif /* CONFIG_FAIR_GROUP_SCHED */
9398 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
9399 #ifdef CONFIG_RT_GROUP_SCHED
9400 init_tg_rt_entry(&root_task_group
, &rq
->rt
, NULL
, i
, NULL
);
9405 rq
->cpu_capacity
= rq
->cpu_capacity_orig
= SCHED_CAPACITY_SCALE
;
9406 rq
->balance_callback
= &balance_push_callback
;
9407 rq
->active_balance
= 0;
9408 rq
->next_balance
= jiffies
;
9413 rq
->avg_idle
= 2*sysctl_sched_migration_cost
;
9414 rq
->wake_stamp
= jiffies
;
9415 rq
->wake_avg_idle
= rq
->avg_idle
;
9416 rq
->max_idle_balance_cost
= sysctl_sched_migration_cost
;
9418 INIT_LIST_HEAD(&rq
->cfs_tasks
);
9420 rq_attach_root(rq
, &def_root_domain
);
9421 #ifdef CONFIG_NO_HZ_COMMON
9422 rq
->last_blocked_load_update_tick
= jiffies
;
9423 atomic_set(&rq
->nohz_flags
, 0);
9425 INIT_CSD(&rq
->nohz_csd
, nohz_csd_func
, rq
);
9427 #ifdef CONFIG_HOTPLUG_CPU
9428 rcuwait_init(&rq
->hotplug_wait
);
9430 #endif /* CONFIG_SMP */
9432 atomic_set(&rq
->nr_iowait
, 0);
9434 #ifdef CONFIG_SCHED_CORE
9436 rq
->core_pick
= NULL
;
9437 rq
->core_enabled
= 0;
9438 rq
->core_tree
= RB_ROOT
;
9439 rq
->core_forceidle
= false;
9441 rq
->core_cookie
= 0UL;
9445 set_load_weight(&init_task
, false);
9448 * The boot idle thread does lazy MMU switching as well:
9451 enter_lazy_tlb(&init_mm
, current
);
9454 * Make us the idle thread. Technically, schedule() should not be
9455 * called from this thread, however somewhere below it might be,
9456 * but because we are the idle thread, we just pick up running again
9457 * when this runqueue becomes "idle".
9459 init_idle(current
, smp_processor_id());
9461 calc_load_update
= jiffies
+ LOAD_FREQ
;
9464 idle_thread_set_boot_cpu();
9465 balance_push_set(smp_processor_id(), false);
9467 init_sched_fair_class();
9473 scheduler_running
= 1;
9476 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
9477 static inline int preempt_count_equals(int preempt_offset
)
9479 int nested
= preempt_count() + rcu_preempt_depth();
9481 return (nested
== preempt_offset
);
9484 void __might_sleep(const char *file
, int line
, int preempt_offset
)
9486 unsigned int state
= get_current_state();
9488 * Blocking primitives will set (and therefore destroy) current->state,
9489 * since we will exit with TASK_RUNNING make sure we enter with it,
9490 * otherwise we will destroy state.
9492 WARN_ONCE(state
!= TASK_RUNNING
&& current
->task_state_change
,
9493 "do not call blocking ops when !TASK_RUNNING; "
9494 "state=%x set at [<%p>] %pS\n", state
,
9495 (void *)current
->task_state_change
,
9496 (void *)current
->task_state_change
);
9498 ___might_sleep(file
, line
, preempt_offset
);
9500 EXPORT_SYMBOL(__might_sleep
);
9502 void ___might_sleep(const char *file
, int line
, int preempt_offset
)
9504 /* Ratelimiting timestamp: */
9505 static unsigned long prev_jiffy
;
9507 unsigned long preempt_disable_ip
;
9509 /* WARN_ON_ONCE() by default, no rate limit required: */
9512 if ((preempt_count_equals(preempt_offset
) && !irqs_disabled() &&
9513 !is_idle_task(current
) && !current
->non_block_count
) ||
9514 system_state
== SYSTEM_BOOTING
|| system_state
> SYSTEM_RUNNING
||
9518 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
9520 prev_jiffy
= jiffies
;
9522 /* Save this before calling printk(), since that will clobber it: */
9523 preempt_disable_ip
= get_preempt_disable_ip(current
);
9526 "BUG: sleeping function called from invalid context at %s:%d\n",
9529 "in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
9530 in_atomic(), irqs_disabled(), current
->non_block_count
,
9531 current
->pid
, current
->comm
);
9533 if (task_stack_end_corrupted(current
))
9534 printk(KERN_EMERG
"Thread overran stack, or stack corrupted\n");
9536 debug_show_held_locks(current
);
9537 if (irqs_disabled())
9538 print_irqtrace_events(current
);
9539 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT
)
9540 && !preempt_count_equals(preempt_offset
)) {
9541 pr_err("Preemption disabled at:");
9542 print_ip_sym(KERN_ERR
, preempt_disable_ip
);
9545 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
9547 EXPORT_SYMBOL(___might_sleep
);
9549 void __cant_sleep(const char *file
, int line
, int preempt_offset
)
9551 static unsigned long prev_jiffy
;
9553 if (irqs_disabled())
9556 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT
))
9559 if (preempt_count() > preempt_offset
)
9562 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
9564 prev_jiffy
= jiffies
;
9566 printk(KERN_ERR
"BUG: assuming atomic context at %s:%d\n", file
, line
);
9567 printk(KERN_ERR
"in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9568 in_atomic(), irqs_disabled(),
9569 current
->pid
, current
->comm
);
9571 debug_show_held_locks(current
);
9573 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
9575 EXPORT_SYMBOL_GPL(__cant_sleep
);
9578 void __cant_migrate(const char *file
, int line
)
9580 static unsigned long prev_jiffy
;
9582 if (irqs_disabled())
9585 if (is_migration_disabled(current
))
9588 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT
))
9591 if (preempt_count() > 0)
9594 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
9596 prev_jiffy
= jiffies
;
9598 pr_err("BUG: assuming non migratable context at %s:%d\n", file
, line
);
9599 pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
9600 in_atomic(), irqs_disabled(), is_migration_disabled(current
),
9601 current
->pid
, current
->comm
);
9603 debug_show_held_locks(current
);
9605 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
9607 EXPORT_SYMBOL_GPL(__cant_migrate
);
9611 #ifdef CONFIG_MAGIC_SYSRQ
9612 void normalize_rt_tasks(void)
9614 struct task_struct
*g
, *p
;
9615 struct sched_attr attr
= {
9616 .sched_policy
= SCHED_NORMAL
,
9619 read_lock(&tasklist_lock
);
9620 for_each_process_thread(g
, p
) {
9622 * Only normalize user tasks:
9624 if (p
->flags
& PF_KTHREAD
)
9627 p
->se
.exec_start
= 0;
9628 schedstat_set(p
->se
.statistics
.wait_start
, 0);
9629 schedstat_set(p
->se
.statistics
.sleep_start
, 0);
9630 schedstat_set(p
->se
.statistics
.block_start
, 0);
9632 if (!dl_task(p
) && !rt_task(p
)) {
9634 * Renice negative nice level userspace
9637 if (task_nice(p
) < 0)
9638 set_user_nice(p
, 0);
9642 __sched_setscheduler(p
, &attr
, false, false);
9644 read_unlock(&tasklist_lock
);
9647 #endif /* CONFIG_MAGIC_SYSRQ */
9649 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
9651 * These functions are only useful for the IA64 MCA handling, or kdb.
9653 * They can only be called when the whole system has been
9654 * stopped - every CPU needs to be quiescent, and no scheduling
9655 * activity can take place. Using them for anything else would
9656 * be a serious bug, and as a result, they aren't even visible
9657 * under any other configuration.
9661 * curr_task - return the current task for a given CPU.
9662 * @cpu: the processor in question.
9664 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9666 * Return: The current task for @cpu.
9668 struct task_struct
*curr_task(int cpu
)
9670 return cpu_curr(cpu
);
9673 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
9677 * ia64_set_curr_task - set the current task for a given CPU.
9678 * @cpu: the processor in question.
9679 * @p: the task pointer to set.
9681 * Description: This function must only be used when non-maskable interrupts
9682 * are serviced on a separate stack. It allows the architecture to switch the
9683 * notion of the current task on a CPU in a non-blocking manner. This function
9684 * must be called with all CPU's synchronized, and interrupts disabled, the
9685 * and caller must save the original value of the current task (see
9686 * curr_task() above) and restore that value before reenabling interrupts and
9687 * re-starting the system.
9689 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9691 void ia64_set_curr_task(int cpu
, struct task_struct
*p
)
9698 #ifdef CONFIG_CGROUP_SCHED
9699 /* task_group_lock serializes the addition/removal of task groups */
9700 static DEFINE_SPINLOCK(task_group_lock
);
9702 static inline void alloc_uclamp_sched_group(struct task_group
*tg
,
9703 struct task_group
*parent
)
9705 #ifdef CONFIG_UCLAMP_TASK_GROUP
9706 enum uclamp_id clamp_id
;
9708 for_each_clamp_id(clamp_id
) {
9709 uclamp_se_set(&tg
->uclamp_req
[clamp_id
],
9710 uclamp_none(clamp_id
), false);
9711 tg
->uclamp
[clamp_id
] = parent
->uclamp
[clamp_id
];
9716 static void sched_free_group(struct task_group
*tg
)
9718 free_fair_sched_group(tg
);
9719 free_rt_sched_group(tg
);
9721 kmem_cache_free(task_group_cache
, tg
);
9724 static void sched_free_group_rcu(struct rcu_head
*rcu
)
9726 sched_free_group(container_of(rcu
, struct task_group
, rcu
));
9729 static void sched_unregister_group(struct task_group
*tg
)
9731 unregister_fair_sched_group(tg
);
9732 unregister_rt_sched_group(tg
);
9734 * We have to wait for yet another RCU grace period to expire, as
9735 * print_cfs_stats() might run concurrently.
9737 call_rcu(&tg
->rcu
, sched_free_group_rcu
);
9740 /* allocate runqueue etc for a new task group */
9741 struct task_group
*sched_create_group(struct task_group
*parent
)
9743 struct task_group
*tg
;
9745 tg
= kmem_cache_alloc(task_group_cache
, GFP_KERNEL
| __GFP_ZERO
);
9747 return ERR_PTR(-ENOMEM
);
9749 if (!alloc_fair_sched_group(tg
, parent
))
9752 if (!alloc_rt_sched_group(tg
, parent
))
9755 alloc_uclamp_sched_group(tg
, parent
);
9760 sched_free_group(tg
);
9761 return ERR_PTR(-ENOMEM
);
9764 void sched_online_group(struct task_group
*tg
, struct task_group
*parent
)
9766 unsigned long flags
;
9768 spin_lock_irqsave(&task_group_lock
, flags
);
9769 list_add_rcu(&tg
->list
, &task_groups
);
9771 /* Root should already exist: */
9774 tg
->parent
= parent
;
9775 INIT_LIST_HEAD(&tg
->children
);
9776 list_add_rcu(&tg
->siblings
, &parent
->children
);
9777 spin_unlock_irqrestore(&task_group_lock
, flags
);
9779 online_fair_sched_group(tg
);
9782 /* rcu callback to free various structures associated with a task group */
9783 static void sched_unregister_group_rcu(struct rcu_head
*rhp
)
9785 /* Now it should be safe to free those cfs_rqs: */
9786 sched_unregister_group(container_of(rhp
, struct task_group
, rcu
));
9789 void sched_destroy_group(struct task_group
*tg
)
9791 /* Wait for possible concurrent references to cfs_rqs complete: */
9792 call_rcu(&tg
->rcu
, sched_unregister_group_rcu
);
9795 void sched_release_group(struct task_group
*tg
)
9797 unsigned long flags
;
9800 * Unlink first, to avoid walk_tg_tree_from() from finding us (via
9801 * sched_cfs_period_timer()).
9803 * For this to be effective, we have to wait for all pending users of
9804 * this task group to leave their RCU critical section to ensure no new
9805 * user will see our dying task group any more. Specifically ensure
9806 * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
9808 * We therefore defer calling unregister_fair_sched_group() to
9809 * sched_unregister_group() which is guarantied to get called only after the
9810 * current RCU grace period has expired.
9812 spin_lock_irqsave(&task_group_lock
, flags
);
9813 list_del_rcu(&tg
->list
);
9814 list_del_rcu(&tg
->siblings
);
9815 spin_unlock_irqrestore(&task_group_lock
, flags
);
9818 static void sched_change_group(struct task_struct
*tsk
, int type
)
9820 struct task_group
*tg
;
9823 * All callers are synchronized by task_rq_lock(); we do not use RCU
9824 * which is pointless here. Thus, we pass "true" to task_css_check()
9825 * to prevent lockdep warnings.
9827 tg
= container_of(task_css_check(tsk
, cpu_cgrp_id
, true),
9828 struct task_group
, css
);
9829 tg
= autogroup_task_group(tsk
, tg
);
9830 tsk
->sched_task_group
= tg
;
9832 #ifdef CONFIG_FAIR_GROUP_SCHED
9833 if (tsk
->sched_class
->task_change_group
)
9834 tsk
->sched_class
->task_change_group(tsk
, type
);
9837 set_task_rq(tsk
, task_cpu(tsk
));
9841 * Change task's runqueue when it moves between groups.
9843 * The caller of this function should have put the task in its new group by
9844 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
9847 void sched_move_task(struct task_struct
*tsk
)
9849 int queued
, running
, queue_flags
=
9850 DEQUEUE_SAVE
| DEQUEUE_MOVE
| DEQUEUE_NOCLOCK
;
9854 rq
= task_rq_lock(tsk
, &rf
);
9855 update_rq_clock(rq
);
9857 running
= task_current(rq
, tsk
);
9858 queued
= task_on_rq_queued(tsk
);
9861 dequeue_task(rq
, tsk
, queue_flags
);
9863 put_prev_task(rq
, tsk
);
9865 sched_change_group(tsk
, TASK_MOVE_GROUP
);
9868 enqueue_task(rq
, tsk
, queue_flags
);
9870 set_next_task(rq
, tsk
);
9872 * After changing group, the running task may have joined a
9873 * throttled one but it's still the running task. Trigger a
9874 * resched to make sure that task can still run.
9879 task_rq_unlock(rq
, tsk
, &rf
);
9882 static inline struct task_group
*css_tg(struct cgroup_subsys_state
*css
)
9884 return css
? container_of(css
, struct task_group
, css
) : NULL
;
9887 static struct cgroup_subsys_state
*
9888 cpu_cgroup_css_alloc(struct cgroup_subsys_state
*parent_css
)
9890 struct task_group
*parent
= css_tg(parent_css
);
9891 struct task_group
*tg
;
9894 /* This is early initialization for the top cgroup */
9895 return &root_task_group
.css
;
9898 tg
= sched_create_group(parent
);
9900 return ERR_PTR(-ENOMEM
);
9905 /* Expose task group only after completing cgroup initialization */
9906 static int cpu_cgroup_css_online(struct cgroup_subsys_state
*css
)
9908 struct task_group
*tg
= css_tg(css
);
9909 struct task_group
*parent
= css_tg(css
->parent
);
9912 sched_online_group(tg
, parent
);
9914 #ifdef CONFIG_UCLAMP_TASK_GROUP
9915 /* Propagate the effective uclamp value for the new group */
9916 mutex_lock(&uclamp_mutex
);
9918 cpu_util_update_eff(css
);
9920 mutex_unlock(&uclamp_mutex
);
9926 static void cpu_cgroup_css_released(struct cgroup_subsys_state
*css
)
9928 struct task_group
*tg
= css_tg(css
);
9930 sched_release_group(tg
);
9933 static void cpu_cgroup_css_free(struct cgroup_subsys_state
*css
)
9935 struct task_group
*tg
= css_tg(css
);
9938 * Relies on the RCU grace period between css_released() and this.
9940 sched_unregister_group(tg
);
9944 * This is called before wake_up_new_task(), therefore we really only
9945 * have to set its group bits, all the other stuff does not apply.
9947 static void cpu_cgroup_fork(struct task_struct
*task
)
9952 rq
= task_rq_lock(task
, &rf
);
9954 update_rq_clock(rq
);
9955 sched_change_group(task
, TASK_SET_GROUP
);
9957 task_rq_unlock(rq
, task
, &rf
);
9960 static int cpu_cgroup_can_attach(struct cgroup_taskset
*tset
)
9962 struct task_struct
*task
;
9963 struct cgroup_subsys_state
*css
;
9966 cgroup_taskset_for_each(task
, css
, tset
) {
9967 #ifdef CONFIG_RT_GROUP_SCHED
9968 if (!sched_rt_can_attach(css_tg(css
), task
))
9972 * Serialize against wake_up_new_task() such that if it's
9973 * running, we're sure to observe its full state.
9975 raw_spin_lock_irq(&task
->pi_lock
);
9977 * Avoid calling sched_move_task() before wake_up_new_task()
9978 * has happened. This would lead to problems with PELT, due to
9979 * move wanting to detach+attach while we're not attached yet.
9981 if (READ_ONCE(task
->__state
) == TASK_NEW
)
9983 raw_spin_unlock_irq(&task
->pi_lock
);
9991 static void cpu_cgroup_attach(struct cgroup_taskset
*tset
)
9993 struct task_struct
*task
;
9994 struct cgroup_subsys_state
*css
;
9996 cgroup_taskset_for_each(task
, css
, tset
)
9997 sched_move_task(task
);
10000 #ifdef CONFIG_UCLAMP_TASK_GROUP
10001 static void cpu_util_update_eff(struct cgroup_subsys_state
*css
)
10003 struct cgroup_subsys_state
*top_css
= css
;
10004 struct uclamp_se
*uc_parent
= NULL
;
10005 struct uclamp_se
*uc_se
= NULL
;
10006 unsigned int eff
[UCLAMP_CNT
];
10007 enum uclamp_id clamp_id
;
10008 unsigned int clamps
;
10010 lockdep_assert_held(&uclamp_mutex
);
10011 SCHED_WARN_ON(!rcu_read_lock_held());
10013 css_for_each_descendant_pre(css
, top_css
) {
10014 uc_parent
= css_tg(css
)->parent
10015 ? css_tg(css
)->parent
->uclamp
: NULL
;
10017 for_each_clamp_id(clamp_id
) {
10018 /* Assume effective clamps matches requested clamps */
10019 eff
[clamp_id
] = css_tg(css
)->uclamp_req
[clamp_id
].value
;
10020 /* Cap effective clamps with parent's effective clamps */
10022 eff
[clamp_id
] > uc_parent
[clamp_id
].value
) {
10023 eff
[clamp_id
] = uc_parent
[clamp_id
].value
;
10026 /* Ensure protection is always capped by limit */
10027 eff
[UCLAMP_MIN
] = min(eff
[UCLAMP_MIN
], eff
[UCLAMP_MAX
]);
10029 /* Propagate most restrictive effective clamps */
10031 uc_se
= css_tg(css
)->uclamp
;
10032 for_each_clamp_id(clamp_id
) {
10033 if (eff
[clamp_id
] == uc_se
[clamp_id
].value
)
10035 uc_se
[clamp_id
].value
= eff
[clamp_id
];
10036 uc_se
[clamp_id
].bucket_id
= uclamp_bucket_id(eff
[clamp_id
]);
10037 clamps
|= (0x1 << clamp_id
);
10040 css
= css_rightmost_descendant(css
);
10044 /* Immediately update descendants RUNNABLE tasks */
10045 uclamp_update_active_tasks(css
);
10050 * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
10051 * C expression. Since there is no way to convert a macro argument (N) into a
10052 * character constant, use two levels of macros.
10054 #define _POW10(exp) ((unsigned int)1e##exp)
10055 #define POW10(exp) _POW10(exp)
10057 struct uclamp_request
{
10058 #define UCLAMP_PERCENT_SHIFT 2
10059 #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
10065 static inline struct uclamp_request
10066 capacity_from_percent(char *buf
)
10068 struct uclamp_request req
= {
10069 .percent
= UCLAMP_PERCENT_SCALE
,
10070 .util
= SCHED_CAPACITY_SCALE
,
10075 if (strcmp(buf
, "max")) {
10076 req
.ret
= cgroup_parse_float(buf
, UCLAMP_PERCENT_SHIFT
,
10080 if ((u64
)req
.percent
> UCLAMP_PERCENT_SCALE
) {
10085 req
.util
= req
.percent
<< SCHED_CAPACITY_SHIFT
;
10086 req
.util
= DIV_ROUND_CLOSEST_ULL(req
.util
, UCLAMP_PERCENT_SCALE
);
10092 static ssize_t
cpu_uclamp_write(struct kernfs_open_file
*of
, char *buf
,
10093 size_t nbytes
, loff_t off
,
10094 enum uclamp_id clamp_id
)
10096 struct uclamp_request req
;
10097 struct task_group
*tg
;
10099 req
= capacity_from_percent(buf
);
10103 static_branch_enable(&sched_uclamp_used
);
10105 mutex_lock(&uclamp_mutex
);
10108 tg
= css_tg(of_css(of
));
10109 if (tg
->uclamp_req
[clamp_id
].value
!= req
.util
)
10110 uclamp_se_set(&tg
->uclamp_req
[clamp_id
], req
.util
, false);
10113 * Because of not recoverable conversion rounding we keep track of the
10114 * exact requested value
10116 tg
->uclamp_pct
[clamp_id
] = req
.percent
;
10118 /* Update effective clamps to track the most restrictive value */
10119 cpu_util_update_eff(of_css(of
));
10122 mutex_unlock(&uclamp_mutex
);
10127 static ssize_t
cpu_uclamp_min_write(struct kernfs_open_file
*of
,
10128 char *buf
, size_t nbytes
,
10131 return cpu_uclamp_write(of
, buf
, nbytes
, off
, UCLAMP_MIN
);
10134 static ssize_t
cpu_uclamp_max_write(struct kernfs_open_file
*of
,
10135 char *buf
, size_t nbytes
,
10138 return cpu_uclamp_write(of
, buf
, nbytes
, off
, UCLAMP_MAX
);
10141 static inline void cpu_uclamp_print(struct seq_file
*sf
,
10142 enum uclamp_id clamp_id
)
10144 struct task_group
*tg
;
10150 tg
= css_tg(seq_css(sf
));
10151 util_clamp
= tg
->uclamp_req
[clamp_id
].value
;
10154 if (util_clamp
== SCHED_CAPACITY_SCALE
) {
10155 seq_puts(sf
, "max\n");
10159 percent
= tg
->uclamp_pct
[clamp_id
];
10160 percent
= div_u64_rem(percent
, POW10(UCLAMP_PERCENT_SHIFT
), &rem
);
10161 seq_printf(sf
, "%llu.%0*u\n", percent
, UCLAMP_PERCENT_SHIFT
, rem
);
10164 static int cpu_uclamp_min_show(struct seq_file
*sf
, void *v
)
10166 cpu_uclamp_print(sf
, UCLAMP_MIN
);
10170 static int cpu_uclamp_max_show(struct seq_file
*sf
, void *v
)
10172 cpu_uclamp_print(sf
, UCLAMP_MAX
);
10175 #endif /* CONFIG_UCLAMP_TASK_GROUP */
10177 #ifdef CONFIG_FAIR_GROUP_SCHED
10178 static int cpu_shares_write_u64(struct cgroup_subsys_state
*css
,
10179 struct cftype
*cftype
, u64 shareval
)
10181 if (shareval
> scale_load_down(ULONG_MAX
))
10182 shareval
= MAX_SHARES
;
10183 return sched_group_set_shares(css_tg(css
), scale_load(shareval
));
10186 static u64
cpu_shares_read_u64(struct cgroup_subsys_state
*css
,
10187 struct cftype
*cft
)
10189 struct task_group
*tg
= css_tg(css
);
10191 return (u64
) scale_load_down(tg
->shares
);
10194 #ifdef CONFIG_CFS_BANDWIDTH
10195 static DEFINE_MUTEX(cfs_constraints_mutex
);
10197 const u64 max_cfs_quota_period
= 1 * NSEC_PER_SEC
; /* 1s */
10198 static const u64 min_cfs_quota_period
= 1 * NSEC_PER_MSEC
; /* 1ms */
10199 /* More than 203 days if BW_SHIFT equals 20. */
10200 static const u64 max_cfs_runtime
= MAX_BW
* NSEC_PER_USEC
;
10202 static int __cfs_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
);
10204 static int tg_set_cfs_bandwidth(struct task_group
*tg
, u64 period
, u64 quota
,
10207 int i
, ret
= 0, runtime_enabled
, runtime_was_enabled
;
10208 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
10210 if (tg
== &root_task_group
)
10214 * Ensure we have at some amount of bandwidth every period. This is
10215 * to prevent reaching a state of large arrears when throttled via
10216 * entity_tick() resulting in prolonged exit starvation.
10218 if (quota
< min_cfs_quota_period
|| period
< min_cfs_quota_period
)
10222 * Likewise, bound things on the other side by preventing insane quota
10223 * periods. This also allows us to normalize in computing quota
10226 if (period
> max_cfs_quota_period
)
10230 * Bound quota to defend quota against overflow during bandwidth shift.
10232 if (quota
!= RUNTIME_INF
&& quota
> max_cfs_runtime
)
10235 if (quota
!= RUNTIME_INF
&& (burst
> quota
||
10236 burst
+ quota
> max_cfs_runtime
))
10240 * Prevent race between setting of cfs_rq->runtime_enabled and
10241 * unthrottle_offline_cfs_rqs().
10244 mutex_lock(&cfs_constraints_mutex
);
10245 ret
= __cfs_schedulable(tg
, period
, quota
);
10249 runtime_enabled
= quota
!= RUNTIME_INF
;
10250 runtime_was_enabled
= cfs_b
->quota
!= RUNTIME_INF
;
10252 * If we need to toggle cfs_bandwidth_used, off->on must occur
10253 * before making related changes, and on->off must occur afterwards
10255 if (runtime_enabled
&& !runtime_was_enabled
)
10256 cfs_bandwidth_usage_inc();
10257 raw_spin_lock_irq(&cfs_b
->lock
);
10258 cfs_b
->period
= ns_to_ktime(period
);
10259 cfs_b
->quota
= quota
;
10260 cfs_b
->burst
= burst
;
10262 __refill_cfs_bandwidth_runtime(cfs_b
);
10264 /* Restart the period timer (if active) to handle new period expiry: */
10265 if (runtime_enabled
)
10266 start_cfs_bandwidth(cfs_b
);
10268 raw_spin_unlock_irq(&cfs_b
->lock
);
10270 for_each_online_cpu(i
) {
10271 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[i
];
10272 struct rq
*rq
= cfs_rq
->rq
;
10273 struct rq_flags rf
;
10275 rq_lock_irq(rq
, &rf
);
10276 cfs_rq
->runtime_enabled
= runtime_enabled
;
10277 cfs_rq
->runtime_remaining
= 0;
10279 if (cfs_rq
->throttled
)
10280 unthrottle_cfs_rq(cfs_rq
);
10281 rq_unlock_irq(rq
, &rf
);
10283 if (runtime_was_enabled
&& !runtime_enabled
)
10284 cfs_bandwidth_usage_dec();
10286 mutex_unlock(&cfs_constraints_mutex
);
10287 cpus_read_unlock();
10292 static int tg_set_cfs_quota(struct task_group
*tg
, long cfs_quota_us
)
10294 u64 quota
, period
, burst
;
10296 period
= ktime_to_ns(tg
->cfs_bandwidth
.period
);
10297 burst
= tg
->cfs_bandwidth
.burst
;
10298 if (cfs_quota_us
< 0)
10299 quota
= RUNTIME_INF
;
10300 else if ((u64
)cfs_quota_us
<= U64_MAX
/ NSEC_PER_USEC
)
10301 quota
= (u64
)cfs_quota_us
* NSEC_PER_USEC
;
10305 return tg_set_cfs_bandwidth(tg
, period
, quota
, burst
);
10308 static long tg_get_cfs_quota(struct task_group
*tg
)
10312 if (tg
->cfs_bandwidth
.quota
== RUNTIME_INF
)
10315 quota_us
= tg
->cfs_bandwidth
.quota
;
10316 do_div(quota_us
, NSEC_PER_USEC
);
10321 static int tg_set_cfs_period(struct task_group
*tg
, long cfs_period_us
)
10323 u64 quota
, period
, burst
;
10325 if ((u64
)cfs_period_us
> U64_MAX
/ NSEC_PER_USEC
)
10328 period
= (u64
)cfs_period_us
* NSEC_PER_USEC
;
10329 quota
= tg
->cfs_bandwidth
.quota
;
10330 burst
= tg
->cfs_bandwidth
.burst
;
10332 return tg_set_cfs_bandwidth(tg
, period
, quota
, burst
);
10335 static long tg_get_cfs_period(struct task_group
*tg
)
10339 cfs_period_us
= ktime_to_ns(tg
->cfs_bandwidth
.period
);
10340 do_div(cfs_period_us
, NSEC_PER_USEC
);
10342 return cfs_period_us
;
10345 static int tg_set_cfs_burst(struct task_group
*tg
, long cfs_burst_us
)
10347 u64 quota
, period
, burst
;
10349 if ((u64
)cfs_burst_us
> U64_MAX
/ NSEC_PER_USEC
)
10352 burst
= (u64
)cfs_burst_us
* NSEC_PER_USEC
;
10353 period
= ktime_to_ns(tg
->cfs_bandwidth
.period
);
10354 quota
= tg
->cfs_bandwidth
.quota
;
10356 return tg_set_cfs_bandwidth(tg
, period
, quota
, burst
);
10359 static long tg_get_cfs_burst(struct task_group
*tg
)
10363 burst_us
= tg
->cfs_bandwidth
.burst
;
10364 do_div(burst_us
, NSEC_PER_USEC
);
10369 static s64
cpu_cfs_quota_read_s64(struct cgroup_subsys_state
*css
,
10370 struct cftype
*cft
)
10372 return tg_get_cfs_quota(css_tg(css
));
10375 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state
*css
,
10376 struct cftype
*cftype
, s64 cfs_quota_us
)
10378 return tg_set_cfs_quota(css_tg(css
), cfs_quota_us
);
10381 static u64
cpu_cfs_period_read_u64(struct cgroup_subsys_state
*css
,
10382 struct cftype
*cft
)
10384 return tg_get_cfs_period(css_tg(css
));
10387 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state
*css
,
10388 struct cftype
*cftype
, u64 cfs_period_us
)
10390 return tg_set_cfs_period(css_tg(css
), cfs_period_us
);
10393 static u64
cpu_cfs_burst_read_u64(struct cgroup_subsys_state
*css
,
10394 struct cftype
*cft
)
10396 return tg_get_cfs_burst(css_tg(css
));
10399 static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state
*css
,
10400 struct cftype
*cftype
, u64 cfs_burst_us
)
10402 return tg_set_cfs_burst(css_tg(css
), cfs_burst_us
);
10405 struct cfs_schedulable_data
{
10406 struct task_group
*tg
;
10411 * normalize group quota/period to be quota/max_period
10412 * note: units are usecs
10414 static u64
normalize_cfs_quota(struct task_group
*tg
,
10415 struct cfs_schedulable_data
*d
)
10420 period
= d
->period
;
10423 period
= tg_get_cfs_period(tg
);
10424 quota
= tg_get_cfs_quota(tg
);
10427 /* note: these should typically be equivalent */
10428 if (quota
== RUNTIME_INF
|| quota
== -1)
10429 return RUNTIME_INF
;
10431 return to_ratio(period
, quota
);
10434 static int tg_cfs_schedulable_down(struct task_group
*tg
, void *data
)
10436 struct cfs_schedulable_data
*d
= data
;
10437 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
10438 s64 quota
= 0, parent_quota
= -1;
10441 quota
= RUNTIME_INF
;
10443 struct cfs_bandwidth
*parent_b
= &tg
->parent
->cfs_bandwidth
;
10445 quota
= normalize_cfs_quota(tg
, d
);
10446 parent_quota
= parent_b
->hierarchical_quota
;
10449 * Ensure max(child_quota) <= parent_quota. On cgroup2,
10450 * always take the min. On cgroup1, only inherit when no
10453 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys
)) {
10454 quota
= min(quota
, parent_quota
);
10456 if (quota
== RUNTIME_INF
)
10457 quota
= parent_quota
;
10458 else if (parent_quota
!= RUNTIME_INF
&& quota
> parent_quota
)
10462 cfs_b
->hierarchical_quota
= quota
;
10467 static int __cfs_schedulable(struct task_group
*tg
, u64 period
, u64 quota
)
10470 struct cfs_schedulable_data data
= {
10476 if (quota
!= RUNTIME_INF
) {
10477 do_div(data
.period
, NSEC_PER_USEC
);
10478 do_div(data
.quota
, NSEC_PER_USEC
);
10482 ret
= walk_tg_tree(tg_cfs_schedulable_down
, tg_nop
, &data
);
10488 static int cpu_cfs_stat_show(struct seq_file
*sf
, void *v
)
10490 struct task_group
*tg
= css_tg(seq_css(sf
));
10491 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
10493 seq_printf(sf
, "nr_periods %d\n", cfs_b
->nr_periods
);
10494 seq_printf(sf
, "nr_throttled %d\n", cfs_b
->nr_throttled
);
10495 seq_printf(sf
, "throttled_time %llu\n", cfs_b
->throttled_time
);
10497 if (schedstat_enabled() && tg
!= &root_task_group
) {
10501 for_each_possible_cpu(i
)
10502 ws
+= schedstat_val(tg
->se
[i
]->statistics
.wait_sum
);
10504 seq_printf(sf
, "wait_sum %llu\n", ws
);
10509 #endif /* CONFIG_CFS_BANDWIDTH */
10510 #endif /* CONFIG_FAIR_GROUP_SCHED */
10512 #ifdef CONFIG_RT_GROUP_SCHED
10513 static int cpu_rt_runtime_write(struct cgroup_subsys_state
*css
,
10514 struct cftype
*cft
, s64 val
)
10516 return sched_group_set_rt_runtime(css_tg(css
), val
);
10519 static s64
cpu_rt_runtime_read(struct cgroup_subsys_state
*css
,
10520 struct cftype
*cft
)
10522 return sched_group_rt_runtime(css_tg(css
));
10525 static int cpu_rt_period_write_uint(struct cgroup_subsys_state
*css
,
10526 struct cftype
*cftype
, u64 rt_period_us
)
10528 return sched_group_set_rt_period(css_tg(css
), rt_period_us
);
10531 static u64
cpu_rt_period_read_uint(struct cgroup_subsys_state
*css
,
10532 struct cftype
*cft
)
10534 return sched_group_rt_period(css_tg(css
));
10536 #endif /* CONFIG_RT_GROUP_SCHED */
10538 #ifdef CONFIG_FAIR_GROUP_SCHED
10539 static s64
cpu_idle_read_s64(struct cgroup_subsys_state
*css
,
10540 struct cftype
*cft
)
10542 return css_tg(css
)->idle
;
10545 static int cpu_idle_write_s64(struct cgroup_subsys_state
*css
,
10546 struct cftype
*cft
, s64 idle
)
10548 return sched_group_set_idle(css_tg(css
), idle
);
10552 static struct cftype cpu_legacy_files
[] = {
10553 #ifdef CONFIG_FAIR_GROUP_SCHED
10556 .read_u64
= cpu_shares_read_u64
,
10557 .write_u64
= cpu_shares_write_u64
,
10561 .read_s64
= cpu_idle_read_s64
,
10562 .write_s64
= cpu_idle_write_s64
,
10565 #ifdef CONFIG_CFS_BANDWIDTH
10567 .name
= "cfs_quota_us",
10568 .read_s64
= cpu_cfs_quota_read_s64
,
10569 .write_s64
= cpu_cfs_quota_write_s64
,
10572 .name
= "cfs_period_us",
10573 .read_u64
= cpu_cfs_period_read_u64
,
10574 .write_u64
= cpu_cfs_period_write_u64
,
10577 .name
= "cfs_burst_us",
10578 .read_u64
= cpu_cfs_burst_read_u64
,
10579 .write_u64
= cpu_cfs_burst_write_u64
,
10583 .seq_show
= cpu_cfs_stat_show
,
10586 #ifdef CONFIG_RT_GROUP_SCHED
10588 .name
= "rt_runtime_us",
10589 .read_s64
= cpu_rt_runtime_read
,
10590 .write_s64
= cpu_rt_runtime_write
,
10593 .name
= "rt_period_us",
10594 .read_u64
= cpu_rt_period_read_uint
,
10595 .write_u64
= cpu_rt_period_write_uint
,
10598 #ifdef CONFIG_UCLAMP_TASK_GROUP
10600 .name
= "uclamp.min",
10601 .flags
= CFTYPE_NOT_ON_ROOT
,
10602 .seq_show
= cpu_uclamp_min_show
,
10603 .write
= cpu_uclamp_min_write
,
10606 .name
= "uclamp.max",
10607 .flags
= CFTYPE_NOT_ON_ROOT
,
10608 .seq_show
= cpu_uclamp_max_show
,
10609 .write
= cpu_uclamp_max_write
,
10612 { } /* Terminate */
10615 static int cpu_extra_stat_show(struct seq_file
*sf
,
10616 struct cgroup_subsys_state
*css
)
10618 #ifdef CONFIG_CFS_BANDWIDTH
10620 struct task_group
*tg
= css_tg(css
);
10621 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
10622 u64 throttled_usec
;
10624 throttled_usec
= cfs_b
->throttled_time
;
10625 do_div(throttled_usec
, NSEC_PER_USEC
);
10627 seq_printf(sf
, "nr_periods %d\n"
10628 "nr_throttled %d\n"
10629 "throttled_usec %llu\n",
10630 cfs_b
->nr_periods
, cfs_b
->nr_throttled
,
10637 #ifdef CONFIG_FAIR_GROUP_SCHED
10638 static u64
cpu_weight_read_u64(struct cgroup_subsys_state
*css
,
10639 struct cftype
*cft
)
10641 struct task_group
*tg
= css_tg(css
);
10642 u64 weight
= scale_load_down(tg
->shares
);
10644 return DIV_ROUND_CLOSEST_ULL(weight
* CGROUP_WEIGHT_DFL
, 1024);
10647 static int cpu_weight_write_u64(struct cgroup_subsys_state
*css
,
10648 struct cftype
*cft
, u64 weight
)
10651 * cgroup weight knobs should use the common MIN, DFL and MAX
10652 * values which are 1, 100 and 10000 respectively. While it loses
10653 * a bit of range on both ends, it maps pretty well onto the shares
10654 * value used by scheduler and the round-trip conversions preserve
10655 * the original value over the entire range.
10657 if (weight
< CGROUP_WEIGHT_MIN
|| weight
> CGROUP_WEIGHT_MAX
)
10660 weight
= DIV_ROUND_CLOSEST_ULL(weight
* 1024, CGROUP_WEIGHT_DFL
);
10662 return sched_group_set_shares(css_tg(css
), scale_load(weight
));
10665 static s64
cpu_weight_nice_read_s64(struct cgroup_subsys_state
*css
,
10666 struct cftype
*cft
)
10668 unsigned long weight
= scale_load_down(css_tg(css
)->shares
);
10669 int last_delta
= INT_MAX
;
10672 /* find the closest nice value to the current weight */
10673 for (prio
= 0; prio
< ARRAY_SIZE(sched_prio_to_weight
); prio
++) {
10674 delta
= abs(sched_prio_to_weight
[prio
] - weight
);
10675 if (delta
>= last_delta
)
10677 last_delta
= delta
;
10680 return PRIO_TO_NICE(prio
- 1 + MAX_RT_PRIO
);
10683 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state
*css
,
10684 struct cftype
*cft
, s64 nice
)
10686 unsigned long weight
;
10689 if (nice
< MIN_NICE
|| nice
> MAX_NICE
)
10692 idx
= NICE_TO_PRIO(nice
) - MAX_RT_PRIO
;
10693 idx
= array_index_nospec(idx
, 40);
10694 weight
= sched_prio_to_weight
[idx
];
10696 return sched_group_set_shares(css_tg(css
), scale_load(weight
));
10700 static void __maybe_unused
cpu_period_quota_print(struct seq_file
*sf
,
10701 long period
, long quota
)
10704 seq_puts(sf
, "max");
10706 seq_printf(sf
, "%ld", quota
);
10708 seq_printf(sf
, " %ld\n", period
);
10711 /* caller should put the current value in *@periodp before calling */
10712 static int __maybe_unused
cpu_period_quota_parse(char *buf
,
10713 u64
*periodp
, u64
*quotap
)
10715 char tok
[21]; /* U64_MAX */
10717 if (sscanf(buf
, "%20s %llu", tok
, periodp
) < 1)
10720 *periodp
*= NSEC_PER_USEC
;
10722 if (sscanf(tok
, "%llu", quotap
))
10723 *quotap
*= NSEC_PER_USEC
;
10724 else if (!strcmp(tok
, "max"))
10725 *quotap
= RUNTIME_INF
;
10732 #ifdef CONFIG_CFS_BANDWIDTH
10733 static int cpu_max_show(struct seq_file
*sf
, void *v
)
10735 struct task_group
*tg
= css_tg(seq_css(sf
));
10737 cpu_period_quota_print(sf
, tg_get_cfs_period(tg
), tg_get_cfs_quota(tg
));
10741 static ssize_t
cpu_max_write(struct kernfs_open_file
*of
,
10742 char *buf
, size_t nbytes
, loff_t off
)
10744 struct task_group
*tg
= css_tg(of_css(of
));
10745 u64 period
= tg_get_cfs_period(tg
);
10746 u64 burst
= tg_get_cfs_burst(tg
);
10750 ret
= cpu_period_quota_parse(buf
, &period
, "a
);
10752 ret
= tg_set_cfs_bandwidth(tg
, period
, quota
, burst
);
10753 return ret
?: nbytes
;
10757 static struct cftype cpu_files
[] = {
10758 #ifdef CONFIG_FAIR_GROUP_SCHED
10761 .flags
= CFTYPE_NOT_ON_ROOT
,
10762 .read_u64
= cpu_weight_read_u64
,
10763 .write_u64
= cpu_weight_write_u64
,
10766 .name
= "weight.nice",
10767 .flags
= CFTYPE_NOT_ON_ROOT
,
10768 .read_s64
= cpu_weight_nice_read_s64
,
10769 .write_s64
= cpu_weight_nice_write_s64
,
10773 .flags
= CFTYPE_NOT_ON_ROOT
,
10774 .read_s64
= cpu_idle_read_s64
,
10775 .write_s64
= cpu_idle_write_s64
,
10778 #ifdef CONFIG_CFS_BANDWIDTH
10781 .flags
= CFTYPE_NOT_ON_ROOT
,
10782 .seq_show
= cpu_max_show
,
10783 .write
= cpu_max_write
,
10786 .name
= "max.burst",
10787 .flags
= CFTYPE_NOT_ON_ROOT
,
10788 .read_u64
= cpu_cfs_burst_read_u64
,
10789 .write_u64
= cpu_cfs_burst_write_u64
,
10792 #ifdef CONFIG_UCLAMP_TASK_GROUP
10794 .name
= "uclamp.min",
10795 .flags
= CFTYPE_NOT_ON_ROOT
,
10796 .seq_show
= cpu_uclamp_min_show
,
10797 .write
= cpu_uclamp_min_write
,
10800 .name
= "uclamp.max",
10801 .flags
= CFTYPE_NOT_ON_ROOT
,
10802 .seq_show
= cpu_uclamp_max_show
,
10803 .write
= cpu_uclamp_max_write
,
10806 { } /* terminate */
10809 struct cgroup_subsys cpu_cgrp_subsys
= {
10810 .css_alloc
= cpu_cgroup_css_alloc
,
10811 .css_online
= cpu_cgroup_css_online
,
10812 .css_released
= cpu_cgroup_css_released
,
10813 .css_free
= cpu_cgroup_css_free
,
10814 .css_extra_stat_show
= cpu_extra_stat_show
,
10815 .fork
= cpu_cgroup_fork
,
10816 .can_attach
= cpu_cgroup_can_attach
,
10817 .attach
= cpu_cgroup_attach
,
10818 .legacy_cftypes
= cpu_legacy_files
,
10819 .dfl_cftypes
= cpu_files
,
10820 .early_init
= true,
10824 #endif /* CONFIG_CGROUP_SCHED */
10826 void dump_cpu_task(int cpu
)
10828 pr_info("Task dump for CPU %d:\n", cpu
);
10829 sched_show_task(cpu_curr(cpu
));
10833 * Nice levels are multiplicative, with a gentle 10% change for every
10834 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
10835 * nice 1, it will get ~10% less CPU time than another CPU-bound task
10836 * that remained on nice 0.
10838 * The "10% effect" is relative and cumulative: from _any_ nice level,
10839 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
10840 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
10841 * If a task goes up by ~10% and another task goes down by ~10% then
10842 * the relative distance between them is ~25%.)
10844 const int sched_prio_to_weight
[40] = {
10845 /* -20 */ 88761, 71755, 56483, 46273, 36291,
10846 /* -15 */ 29154, 23254, 18705, 14949, 11916,
10847 /* -10 */ 9548, 7620, 6100, 4904, 3906,
10848 /* -5 */ 3121, 2501, 1991, 1586, 1277,
10849 /* 0 */ 1024, 820, 655, 526, 423,
10850 /* 5 */ 335, 272, 215, 172, 137,
10851 /* 10 */ 110, 87, 70, 56, 45,
10852 /* 15 */ 36, 29, 23, 18, 15,
10856 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
10858 * In cases where the weight does not change often, we can use the
10859 * precalculated inverse to speed up arithmetics by turning divisions
10860 * into multiplications:
10862 const u32 sched_prio_to_wmult
[40] = {
10863 /* -20 */ 48388, 59856, 76040, 92818, 118348,
10864 /* -15 */ 147320, 184698, 229616, 287308, 360437,
10865 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
10866 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
10867 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
10868 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
10869 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
10870 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
10873 void call_trace_sched_update_nr_running(struct rq
*rq
, int count
)
10875 trace_sched_update_nr_running_tp(rq
, count
);