1 // SPDX-License-Identifier: GPL-2.0-only
5 * Core kernel scheduler code and related syscalls
7 * Copyright (C) 1991-2002 Linus Torvalds
9 #include <linux/highmem.h>
10 #include <linux/hrtimer_api.h>
11 #include <linux/ktime_api.h>
12 #include <linux/sched/signal.h>
13 #include <linux/syscalls_api.h>
14 #include <linux/debug_locks.h>
15 #include <linux/prefetch.h>
16 #include <linux/capability.h>
17 #include <linux/pgtable_api.h>
18 #include <linux/wait_bit.h>
19 #include <linux/jiffies.h>
20 #include <linux/spinlock_api.h>
21 #include <linux/cpumask_api.h>
22 #include <linux/lockdep_api.h>
23 #include <linux/hardirq.h>
24 #include <linux/softirq.h>
25 #include <linux/refcount_api.h>
26 #include <linux/topology.h>
27 #include <linux/sched/clock.h>
28 #include <linux/sched/cond_resched.h>
29 #include <linux/sched/cputime.h>
30 #include <linux/sched/debug.h>
31 #include <linux/sched/hotplug.h>
32 #include <linux/sched/init.h>
33 #include <linux/sched/isolation.h>
34 #include <linux/sched/loadavg.h>
35 #include <linux/sched/mm.h>
36 #include <linux/sched/nohz.h>
37 #include <linux/sched/rseq_api.h>
38 #include <linux/sched/rt.h>
40 #include <linux/blkdev.h>
41 #include <linux/context_tracking.h>
42 #include <linux/cpuset.h>
43 #include <linux/delayacct.h>
44 #include <linux/init_task.h>
45 #include <linux/interrupt.h>
46 #include <linux/ioprio.h>
47 #include <linux/kallsyms.h>
48 #include <linux/kcov.h>
49 #include <linux/kprobes.h>
50 #include <linux/llist_api.h>
51 #include <linux/mmu_context.h>
52 #include <linux/mmzone.h>
53 #include <linux/mutex_api.h>
54 #include <linux/nmi.h>
55 #include <linux/nospec.h>
56 #include <linux/perf_event_api.h>
57 #include <linux/profile.h>
58 #include <linux/psi.h>
59 #include <linux/rcuwait_api.h>
60 #include <linux/sched/wake_q.h>
61 #include <linux/scs.h>
62 #include <linux/slab.h>
63 #include <linux/syscalls.h>
64 #include <linux/vtime.h>
65 #include <linux/wait_api.h>
66 #include <linux/workqueue_api.h>
68 #ifdef CONFIG_PREEMPT_DYNAMIC
69 # ifdef CONFIG_GENERIC_ENTRY
70 # include <linux/entry-common.h>
74 #include <uapi/linux/sched/types.h>
76 #include <asm/irq_regs.h>
77 #include <asm/switch_to.h>
80 #define CREATE_TRACE_POINTS
81 #include <linux/sched/rseq_api.h>
82 #include <trace/events/sched.h>
83 #include <trace/events/ipi.h>
84 #undef CREATE_TRACE_POINTS
88 #include "autogroup.h"
90 #include "autogroup.h"
95 #include "../workqueue_internal.h"
96 #include "../../io_uring/io-wq.h"
97 #include "../smpboot.h"
99 EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu);
100 EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask);
103 * Export tracepoints that act as a bare tracehook (ie: have no trace event
104 * associated with them) to allow external modules to probe them.
106 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
107 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
108 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
109 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
110 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
111 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_thermal_tp);
112 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
113 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
114 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
115 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
116 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
118 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
120 #ifdef CONFIG_SCHED_DEBUG
122 * Debugging: various feature bits
124 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
125 * sysctl_sched_features, defined in sched.h, to allow constants propagation
126 * at compile time and compiler optimization based on features default.
128 #define SCHED_FEAT(name, enabled) \
129 (1UL << __SCHED_FEAT_##name) * enabled |
130 const_debug unsigned int sysctl_sched_features =
131 #include "features.h"
136 * Print a warning if need_resched is set for the given duration (if
137 * LATENCY_WARN is enabled).
139 * If sysctl_resched_latency_warn_once is set, only one warning will be shown
142 __read_mostly int sysctl_resched_latency_warn_ms = 100;
143 __read_mostly int sysctl_resched_latency_warn_once = 1;
144 #endif /* CONFIG_SCHED_DEBUG */
147 * Number of tasks to iterate in a single balance run.
148 * Limited because this is done with IRQs disabled.
150 const_debug unsigned int sysctl_sched_nr_migrate = SCHED_NR_MIGRATE_BREAK;
152 __read_mostly int scheduler_running;
154 #ifdef CONFIG_SCHED_CORE
156 DEFINE_STATIC_KEY_FALSE(__sched_core_enabled);
158 /* kernel prio, less is more */
159 static inline int __task_prio(const struct task_struct *p)
161 if (p->sched_class == &stop_sched_class) /* trumps deadline */
164 if (rt_prio(p->prio)) /* includes deadline */
165 return p->prio; /* [-1, 99] */
167 if (p->sched_class == &idle_sched_class)
168 return MAX_RT_PRIO + NICE_WIDTH; /* 140 */
170 return MAX_RT_PRIO + MAX_NICE; /* 120, squash fair */
180 /* real prio, less is less */
181 static inline bool prio_less(const struct task_struct *a,
182 const struct task_struct *b, bool in_fi)
185 int pa = __task_prio(a), pb = __task_prio(b);
193 if (pa == -1) /* dl_prio() doesn't work because of stop_class above */
194 return !dl_time_before(a->dl.deadline, b->dl.deadline);
196 if (pa == MAX_RT_PRIO + MAX_NICE) /* fair */
197 return cfs_prio_less(a, b, in_fi);
202 static inline bool __sched_core_less(const struct task_struct *a,
203 const struct task_struct *b)
205 if (a->core_cookie < b->core_cookie)
208 if (a->core_cookie > b->core_cookie)
211 /* flip prio, so high prio is leftmost */
212 if (prio_less(b, a, !!task_rq(a)->core->core_forceidle_count))
218 #define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
220 static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b)
222 return __sched_core_less(__node_2_sc(a), __node_2_sc(b));
225 static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node)
227 const struct task_struct *p = __node_2_sc(node);
228 unsigned long cookie = (unsigned long)key;
230 if (cookie < p->core_cookie)
233 if (cookie > p->core_cookie)
239 void sched_core_enqueue(struct rq *rq, struct task_struct *p)
241 rq->core->core_task_seq++;
246 rb_add(&p->core_node, &rq->core_tree, rb_sched_core_less);
249 void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags)
251 rq->core->core_task_seq++;
253 if (sched_core_enqueued(p)) {
254 rb_erase(&p->core_node, &rq->core_tree);
255 RB_CLEAR_NODE(&p->core_node);
259 * Migrating the last task off the cpu, with the cpu in forced idle
260 * state. Reschedule to create an accounting edge for forced idle,
261 * and re-examine whether the core is still in forced idle state.
263 if (!(flags & DEQUEUE_SAVE) && rq->nr_running == 1 &&
264 rq->core->core_forceidle_count && rq->curr == rq->idle)
268 static int sched_task_is_throttled(struct task_struct *p, int cpu)
270 if (p->sched_class->task_is_throttled)
271 return p->sched_class->task_is_throttled(p, cpu);
276 static struct task_struct *sched_core_next(struct task_struct *p, unsigned long cookie)
278 struct rb_node *node = &p->core_node;
279 int cpu = task_cpu(p);
282 node = rb_next(node);
286 p = __node_2_sc(node);
287 if (p->core_cookie != cookie)
290 } while (sched_task_is_throttled(p, cpu));
296 * Find left-most (aka, highest priority) and unthrottled task matching @cookie.
297 * If no suitable task is found, NULL will be returned.
299 static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie)
301 struct task_struct *p;
302 struct rb_node *node;
304 node = rb_find_first((void *)cookie, &rq->core_tree, rb_sched_core_cmp);
308 p = __node_2_sc(node);
309 if (!sched_task_is_throttled(p, rq->cpu))
312 return sched_core_next(p, cookie);
316 * Magic required such that:
318 * raw_spin_rq_lock(rq);
320 * raw_spin_rq_unlock(rq);
322 * ends up locking and unlocking the _same_ lock, and all CPUs
323 * always agree on what rq has what lock.
325 * XXX entirely possible to selectively enable cores, don't bother for now.
328 static DEFINE_MUTEX(sched_core_mutex);
329 static atomic_t sched_core_count;
330 static struct cpumask sched_core_mask;
332 static void sched_core_lock(int cpu, unsigned long *flags)
334 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
337 local_irq_save(*flags);
338 for_each_cpu(t, smt_mask)
339 raw_spin_lock_nested(&cpu_rq(t)->__lock, i++);
342 static void sched_core_unlock(int cpu, unsigned long *flags)
344 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
347 for_each_cpu(t, smt_mask)
348 raw_spin_unlock(&cpu_rq(t)->__lock);
349 local_irq_restore(*flags);
352 static void __sched_core_flip(bool enabled)
360 * Toggle the online cores, one by one.
362 cpumask_copy(&sched_core_mask, cpu_online_mask);
363 for_each_cpu(cpu, &sched_core_mask) {
364 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
366 sched_core_lock(cpu, &flags);
368 for_each_cpu(t, smt_mask)
369 cpu_rq(t)->core_enabled = enabled;
371 cpu_rq(cpu)->core->core_forceidle_start = 0;
373 sched_core_unlock(cpu, &flags);
375 cpumask_andnot(&sched_core_mask, &sched_core_mask, smt_mask);
379 * Toggle the offline CPUs.
381 for_each_cpu_andnot(cpu, cpu_possible_mask, cpu_online_mask)
382 cpu_rq(cpu)->core_enabled = enabled;
387 static void sched_core_assert_empty(void)
391 for_each_possible_cpu(cpu)
392 WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu)->core_tree));
395 static void __sched_core_enable(void)
397 static_branch_enable(&__sched_core_enabled);
399 * Ensure all previous instances of raw_spin_rq_*lock() have finished
400 * and future ones will observe !sched_core_disabled().
403 __sched_core_flip(true);
404 sched_core_assert_empty();
407 static void __sched_core_disable(void)
409 sched_core_assert_empty();
410 __sched_core_flip(false);
411 static_branch_disable(&__sched_core_enabled);
414 void sched_core_get(void)
416 if (atomic_inc_not_zero(&sched_core_count))
419 mutex_lock(&sched_core_mutex);
420 if (!atomic_read(&sched_core_count))
421 __sched_core_enable();
423 smp_mb__before_atomic();
424 atomic_inc(&sched_core_count);
425 mutex_unlock(&sched_core_mutex);
428 static void __sched_core_put(struct work_struct *work)
430 if (atomic_dec_and_mutex_lock(&sched_core_count, &sched_core_mutex)) {
431 __sched_core_disable();
432 mutex_unlock(&sched_core_mutex);
436 void sched_core_put(void)
438 static DECLARE_WORK(_work, __sched_core_put);
441 * "There can be only one"
443 * Either this is the last one, or we don't actually need to do any
444 * 'work'. If it is the last *again*, we rely on
445 * WORK_STRUCT_PENDING_BIT.
447 if (!atomic_add_unless(&sched_core_count, -1, 1))
448 schedule_work(&_work);
451 #else /* !CONFIG_SCHED_CORE */
453 static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { }
455 sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { }
457 #endif /* CONFIG_SCHED_CORE */
460 * Serialization rules:
466 * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
469 * rq2->lock where: rq1 < rq2
473 * Normal scheduling state is serialized by rq->lock. __schedule() takes the
474 * local CPU's rq->lock, it optionally removes the task from the runqueue and
475 * always looks at the local rq data structures to find the most eligible task
478 * Task enqueue is also under rq->lock, possibly taken from another CPU.
479 * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
480 * the local CPU to avoid bouncing the runqueue state around [ see
481 * ttwu_queue_wakelist() ]
483 * Task wakeup, specifically wakeups that involve migration, are horribly
484 * complicated to avoid having to take two rq->locks.
488 * System-calls and anything external will use task_rq_lock() which acquires
489 * both p->pi_lock and rq->lock. As a consequence the state they change is
490 * stable while holding either lock:
492 * - sched_setaffinity()/
493 * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
494 * - set_user_nice(): p->se.load, p->*prio
495 * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
496 * p->se.load, p->rt_priority,
497 * p->dl.dl_{runtime, deadline, period, flags, bw, density}
498 * - sched_setnuma(): p->numa_preferred_nid
499 * - sched_move_task(): p->sched_task_group
500 * - uclamp_update_active() p->uclamp*
502 * p->state <- TASK_*:
504 * is changed locklessly using set_current_state(), __set_current_state() or
505 * set_special_state(), see their respective comments, or by
506 * try_to_wake_up(). This latter uses p->pi_lock to serialize against
509 * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
511 * is set by activate_task() and cleared by deactivate_task(), under
512 * rq->lock. Non-zero indicates the task is runnable, the special
513 * ON_RQ_MIGRATING state is used for migration without holding both
514 * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
516 * p->on_cpu <- { 0, 1 }:
518 * is set by prepare_task() and cleared by finish_task() such that it will be
519 * set before p is scheduled-in and cleared after p is scheduled-out, both
520 * under rq->lock. Non-zero indicates the task is running on its CPU.
522 * [ The astute reader will observe that it is possible for two tasks on one
523 * CPU to have ->on_cpu = 1 at the same time. ]
525 * task_cpu(p): is changed by set_task_cpu(), the rules are:
527 * - Don't call set_task_cpu() on a blocked task:
529 * We don't care what CPU we're not running on, this simplifies hotplug,
530 * the CPU assignment of blocked tasks isn't required to be valid.
532 * - for try_to_wake_up(), called under p->pi_lock:
534 * This allows try_to_wake_up() to only take one rq->lock, see its comment.
536 * - for migration called under rq->lock:
537 * [ see task_on_rq_migrating() in task_rq_lock() ]
539 * o move_queued_task()
542 * - for migration called under double_rq_lock():
544 * o __migrate_swap_task()
545 * o push_rt_task() / pull_rt_task()
546 * o push_dl_task() / pull_dl_task()
547 * o dl_task_offline_migration()
551 void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
553 raw_spinlock_t *lock;
555 /* Matches synchronize_rcu() in __sched_core_enable() */
557 if (sched_core_disabled()) {
558 raw_spin_lock_nested(&rq->__lock, subclass);
559 /* preempt_count *MUST* be > 1 */
560 preempt_enable_no_resched();
565 lock = __rq_lockp(rq);
566 raw_spin_lock_nested(lock, subclass);
567 if (likely(lock == __rq_lockp(rq))) {
568 /* preempt_count *MUST* be > 1 */
569 preempt_enable_no_resched();
572 raw_spin_unlock(lock);
576 bool raw_spin_rq_trylock(struct rq *rq)
578 raw_spinlock_t *lock;
581 /* Matches synchronize_rcu() in __sched_core_enable() */
583 if (sched_core_disabled()) {
584 ret = raw_spin_trylock(&rq->__lock);
590 lock = __rq_lockp(rq);
591 ret = raw_spin_trylock(lock);
592 if (!ret || (likely(lock == __rq_lockp(rq)))) {
596 raw_spin_unlock(lock);
600 void raw_spin_rq_unlock(struct rq *rq)
602 raw_spin_unlock(rq_lockp(rq));
607 * double_rq_lock - safely lock two runqueues
609 void double_rq_lock(struct rq *rq1, struct rq *rq2)
611 lockdep_assert_irqs_disabled();
613 if (rq_order_less(rq2, rq1))
616 raw_spin_rq_lock(rq1);
617 if (__rq_lockp(rq1) != __rq_lockp(rq2))
618 raw_spin_rq_lock_nested(rq2, SINGLE_DEPTH_NESTING);
620 double_rq_clock_clear_update(rq1, rq2);
625 * __task_rq_lock - lock the rq @p resides on.
627 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
632 lockdep_assert_held(&p->pi_lock);
636 raw_spin_rq_lock(rq);
637 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
641 raw_spin_rq_unlock(rq);
643 while (unlikely(task_on_rq_migrating(p)))
649 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
651 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
652 __acquires(p->pi_lock)
658 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
660 raw_spin_rq_lock(rq);
662 * move_queued_task() task_rq_lock()
665 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
666 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
667 * [S] ->cpu = new_cpu [L] task_rq()
671 * If we observe the old CPU in task_rq_lock(), the acquire of
672 * the old rq->lock will fully serialize against the stores.
674 * If we observe the new CPU in task_rq_lock(), the address
675 * dependency headed by '[L] rq = task_rq()' and the acquire
676 * will pair with the WMB to ensure we then also see migrating.
678 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
682 raw_spin_rq_unlock(rq);
683 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
685 while (unlikely(task_on_rq_migrating(p)))
691 * RQ-clock updating methods:
694 static void update_rq_clock_task(struct rq *rq, s64 delta)
697 * In theory, the compile should just see 0 here, and optimize out the call
698 * to sched_rt_avg_update. But I don't trust it...
700 s64 __maybe_unused steal = 0, irq_delta = 0;
702 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
703 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
706 * Since irq_time is only updated on {soft,}irq_exit, we might run into
707 * this case when a previous update_rq_clock() happened inside a
710 * When this happens, we stop ->clock_task and only update the
711 * prev_irq_time stamp to account for the part that fit, so that a next
712 * update will consume the rest. This ensures ->clock_task is
715 * It does however cause some slight miss-attribution of {soft,}irq
716 * time, a more accurate solution would be to update the irq_time using
717 * the current rq->clock timestamp, except that would require using
720 if (irq_delta > delta)
723 rq->prev_irq_time += irq_delta;
725 psi_account_irqtime(rq->curr, irq_delta);
726 delayacct_irq(rq->curr, irq_delta);
728 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
729 if (static_key_false((¶virt_steal_rq_enabled))) {
730 steal = paravirt_steal_clock(cpu_of(rq));
731 steal -= rq->prev_steal_time_rq;
733 if (unlikely(steal > delta))
736 rq->prev_steal_time_rq += steal;
741 rq->clock_task += delta;
743 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
744 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
745 update_irq_load_avg(rq, irq_delta + steal);
747 update_rq_clock_pelt(rq, delta);
750 void update_rq_clock(struct rq *rq)
754 lockdep_assert_rq_held(rq);
756 if (rq->clock_update_flags & RQCF_ACT_SKIP)
759 #ifdef CONFIG_SCHED_DEBUG
760 if (sched_feat(WARN_DOUBLE_CLOCK))
761 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
762 rq->clock_update_flags |= RQCF_UPDATED;
765 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
769 update_rq_clock_task(rq, delta);
772 #ifdef CONFIG_SCHED_HRTICK
774 * Use HR-timers to deliver accurate preemption points.
777 static void hrtick_clear(struct rq *rq)
779 if (hrtimer_active(&rq->hrtick_timer))
780 hrtimer_cancel(&rq->hrtick_timer);
784 * High-resolution timer tick.
785 * Runs from hardirq context with interrupts disabled.
787 static enum hrtimer_restart hrtick(struct hrtimer *timer)
789 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
792 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
796 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
799 return HRTIMER_NORESTART;
804 static void __hrtick_restart(struct rq *rq)
806 struct hrtimer *timer = &rq->hrtick_timer;
807 ktime_t time = rq->hrtick_time;
809 hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
813 * called from hardirq (IPI) context
815 static void __hrtick_start(void *arg)
821 __hrtick_restart(rq);
826 * Called to set the hrtick timer state.
828 * called with rq->lock held and irqs disabled
830 void hrtick_start(struct rq *rq, u64 delay)
832 struct hrtimer *timer = &rq->hrtick_timer;
836 * Don't schedule slices shorter than 10000ns, that just
837 * doesn't make sense and can cause timer DoS.
839 delta = max_t(s64, delay, 10000LL);
840 rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
843 __hrtick_restart(rq);
845 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
850 * Called to set the hrtick timer state.
852 * called with rq->lock held and irqs disabled
854 void hrtick_start(struct rq *rq, u64 delay)
857 * Don't schedule slices shorter than 10000ns, that just
858 * doesn't make sense. Rely on vruntime for fairness.
860 delay = max_t(u64, delay, 10000LL);
861 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
862 HRTIMER_MODE_REL_PINNED_HARD);
865 #endif /* CONFIG_SMP */
867 static void hrtick_rq_init(struct rq *rq)
870 INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq);
872 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
873 rq->hrtick_timer.function = hrtick;
875 #else /* CONFIG_SCHED_HRTICK */
876 static inline void hrtick_clear(struct rq *rq)
880 static inline void hrtick_rq_init(struct rq *rq)
883 #endif /* CONFIG_SCHED_HRTICK */
886 * cmpxchg based fetch_or, macro so it works for different integer types
888 #define fetch_or(ptr, mask) \
890 typeof(ptr) _ptr = (ptr); \
891 typeof(mask) _mask = (mask); \
892 typeof(*_ptr) _val = *_ptr; \
895 } while (!try_cmpxchg(_ptr, &_val, _val | _mask)); \
899 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
901 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
902 * this avoids any races wrt polling state changes and thereby avoids
905 static inline bool set_nr_and_not_polling(struct task_struct *p)
907 struct thread_info *ti = task_thread_info(p);
908 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
912 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
914 * If this returns true, then the idle task promises to call
915 * sched_ttwu_pending() and reschedule soon.
917 static bool set_nr_if_polling(struct task_struct *p)
919 struct thread_info *ti = task_thread_info(p);
920 typeof(ti->flags) val = READ_ONCE(ti->flags);
923 if (!(val & _TIF_POLLING_NRFLAG))
925 if (val & _TIF_NEED_RESCHED)
927 if (try_cmpxchg(&ti->flags, &val, val | _TIF_NEED_RESCHED))
934 static inline bool set_nr_and_not_polling(struct task_struct *p)
936 set_tsk_need_resched(p);
941 static inline bool set_nr_if_polling(struct task_struct *p)
948 static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
950 struct wake_q_node *node = &task->wake_q;
953 * Atomically grab the task, if ->wake_q is !nil already it means
954 * it's already queued (either by us or someone else) and will get the
955 * wakeup due to that.
957 * In order to ensure that a pending wakeup will observe our pending
958 * state, even in the failed case, an explicit smp_mb() must be used.
960 smp_mb__before_atomic();
961 if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
965 * The head is context local, there can be no concurrency.
968 head->lastp = &node->next;
973 * wake_q_add() - queue a wakeup for 'later' waking.
974 * @head: the wake_q_head to add @task to
975 * @task: the task to queue for 'later' wakeup
977 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
978 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
981 * This function must be used as-if it were wake_up_process(); IOW the task
982 * must be ready to be woken at this location.
984 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
986 if (__wake_q_add(head, task))
987 get_task_struct(task);
991 * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
992 * @head: the wake_q_head to add @task to
993 * @task: the task to queue for 'later' wakeup
995 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
996 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
999 * This function must be used as-if it were wake_up_process(); IOW the task
1000 * must be ready to be woken at this location.
1002 * This function is essentially a task-safe equivalent to wake_q_add(). Callers
1003 * that already hold reference to @task can call the 'safe' version and trust
1004 * wake_q to do the right thing depending whether or not the @task is already
1005 * queued for wakeup.
1007 void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
1009 if (!__wake_q_add(head, task))
1010 put_task_struct(task);
1013 void wake_up_q(struct wake_q_head *head)
1015 struct wake_q_node *node = head->first;
1017 while (node != WAKE_Q_TAIL) {
1018 struct task_struct *task;
1020 task = container_of(node, struct task_struct, wake_q);
1021 /* Task can safely be re-inserted now: */
1023 task->wake_q.next = NULL;
1026 * wake_up_process() executes a full barrier, which pairs with
1027 * the queueing in wake_q_add() so as not to miss wakeups.
1029 wake_up_process(task);
1030 put_task_struct(task);
1035 * resched_curr - mark rq's current task 'to be rescheduled now'.
1037 * On UP this means the setting of the need_resched flag, on SMP it
1038 * might also involve a cross-CPU call to trigger the scheduler on
1041 void resched_curr(struct rq *rq)
1043 struct task_struct *curr = rq->curr;
1046 lockdep_assert_rq_held(rq);
1048 if (test_tsk_need_resched(curr))
1053 if (cpu == smp_processor_id()) {
1054 set_tsk_need_resched(curr);
1055 set_preempt_need_resched();
1059 if (set_nr_and_not_polling(curr))
1060 smp_send_reschedule(cpu);
1062 trace_sched_wake_idle_without_ipi(cpu);
1065 void resched_cpu(int cpu)
1067 struct rq *rq = cpu_rq(cpu);
1068 unsigned long flags;
1070 raw_spin_rq_lock_irqsave(rq, flags);
1071 if (cpu_online(cpu) || cpu == smp_processor_id())
1073 raw_spin_rq_unlock_irqrestore(rq, flags);
1077 #ifdef CONFIG_NO_HZ_COMMON
1079 * In the semi idle case, use the nearest busy CPU for migrating timers
1080 * from an idle CPU. This is good for power-savings.
1082 * We don't do similar optimization for completely idle system, as
1083 * selecting an idle CPU will add more delays to the timers than intended
1084 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
1086 int get_nohz_timer_target(void)
1088 int i, cpu = smp_processor_id(), default_cpu = -1;
1089 struct sched_domain *sd;
1090 const struct cpumask *hk_mask;
1092 if (housekeeping_cpu(cpu, HK_TYPE_TIMER)) {
1098 hk_mask = housekeeping_cpumask(HK_TYPE_TIMER);
1101 for_each_domain(cpu, sd) {
1102 for_each_cpu_and(i, sched_domain_span(sd), hk_mask) {
1113 if (default_cpu == -1)
1114 default_cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
1122 * When add_timer_on() enqueues a timer into the timer wheel of an
1123 * idle CPU then this timer might expire before the next timer event
1124 * which is scheduled to wake up that CPU. In case of a completely
1125 * idle system the next event might even be infinite time into the
1126 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1127 * leaves the inner idle loop so the newly added timer is taken into
1128 * account when the CPU goes back to idle and evaluates the timer
1129 * wheel for the next timer event.
1131 static void wake_up_idle_cpu(int cpu)
1133 struct rq *rq = cpu_rq(cpu);
1135 if (cpu == smp_processor_id())
1138 if (set_nr_and_not_polling(rq->idle))
1139 smp_send_reschedule(cpu);
1141 trace_sched_wake_idle_without_ipi(cpu);
1144 static bool wake_up_full_nohz_cpu(int cpu)
1147 * We just need the target to call irq_exit() and re-evaluate
1148 * the next tick. The nohz full kick at least implies that.
1149 * If needed we can still optimize that later with an
1152 if (cpu_is_offline(cpu))
1153 return true; /* Don't try to wake offline CPUs. */
1154 if (tick_nohz_full_cpu(cpu)) {
1155 if (cpu != smp_processor_id() ||
1156 tick_nohz_tick_stopped())
1157 tick_nohz_full_kick_cpu(cpu);
1165 * Wake up the specified CPU. If the CPU is going offline, it is the
1166 * caller's responsibility to deal with the lost wakeup, for example,
1167 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
1169 void wake_up_nohz_cpu(int cpu)
1171 if (!wake_up_full_nohz_cpu(cpu))
1172 wake_up_idle_cpu(cpu);
1175 static void nohz_csd_func(void *info)
1177 struct rq *rq = info;
1178 int cpu = cpu_of(rq);
1182 * Release the rq::nohz_csd.
1184 flags = atomic_fetch_andnot(NOHZ_KICK_MASK | NOHZ_NEWILB_KICK, nohz_flags(cpu));
1185 WARN_ON(!(flags & NOHZ_KICK_MASK));
1187 rq->idle_balance = idle_cpu(cpu);
1188 if (rq->idle_balance && !need_resched()) {
1189 rq->nohz_idle_balance = flags;
1190 raise_softirq_irqoff(SCHED_SOFTIRQ);
1194 #endif /* CONFIG_NO_HZ_COMMON */
1196 #ifdef CONFIG_NO_HZ_FULL
1197 bool sched_can_stop_tick(struct rq *rq)
1199 int fifo_nr_running;
1201 /* Deadline tasks, even if single, need the tick */
1202 if (rq->dl.dl_nr_running)
1206 * If there are more than one RR tasks, we need the tick to affect the
1207 * actual RR behaviour.
1209 if (rq->rt.rr_nr_running) {
1210 if (rq->rt.rr_nr_running == 1)
1217 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
1218 * forced preemption between FIFO tasks.
1220 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
1221 if (fifo_nr_running)
1225 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
1226 * if there's more than one we need the tick for involuntary
1229 if (rq->nr_running > 1)
1234 #endif /* CONFIG_NO_HZ_FULL */
1235 #endif /* CONFIG_SMP */
1237 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
1238 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
1240 * Iterate task_group tree rooted at *from, calling @down when first entering a
1241 * node and @up when leaving it for the final time.
1243 * Caller must hold rcu_lock or sufficient equivalent.
1245 int walk_tg_tree_from(struct task_group *from,
1246 tg_visitor down, tg_visitor up, void *data)
1248 struct task_group *parent, *child;
1254 ret = (*down)(parent, data);
1257 list_for_each_entry_rcu(child, &parent->children, siblings) {
1264 ret = (*up)(parent, data);
1265 if (ret || parent == from)
1269 parent = parent->parent;
1276 int tg_nop(struct task_group *tg, void *data)
1282 static void set_load_weight(struct task_struct *p, bool update_load)
1284 int prio = p->static_prio - MAX_RT_PRIO;
1285 struct load_weight *load = &p->se.load;
1288 * SCHED_IDLE tasks get minimal weight:
1290 if (task_has_idle_policy(p)) {
1291 load->weight = scale_load(WEIGHT_IDLEPRIO);
1292 load->inv_weight = WMULT_IDLEPRIO;
1297 * SCHED_OTHER tasks have to update their load when changing their
1300 if (update_load && p->sched_class == &fair_sched_class) {
1301 reweight_task(p, prio);
1303 load->weight = scale_load(sched_prio_to_weight[prio]);
1304 load->inv_weight = sched_prio_to_wmult[prio];
1308 #ifdef CONFIG_UCLAMP_TASK
1310 * Serializes updates of utilization clamp values
1312 * The (slow-path) user-space triggers utilization clamp value updates which
1313 * can require updates on (fast-path) scheduler's data structures used to
1314 * support enqueue/dequeue operations.
1315 * While the per-CPU rq lock protects fast-path update operations, user-space
1316 * requests are serialized using a mutex to reduce the risk of conflicting
1317 * updates or API abuses.
1319 static DEFINE_MUTEX(uclamp_mutex);
1321 /* Max allowed minimum utilization */
1322 static unsigned int __maybe_unused sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
1324 /* Max allowed maximum utilization */
1325 static unsigned int __maybe_unused sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
1328 * By default RT tasks run at the maximum performance point/capacity of the
1329 * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
1330 * SCHED_CAPACITY_SCALE.
1332 * This knob allows admins to change the default behavior when uclamp is being
1333 * used. In battery powered devices, particularly, running at the maximum
1334 * capacity and frequency will increase energy consumption and shorten the
1337 * This knob only affects RT tasks that their uclamp_se->user_defined == false.
1339 * This knob will not override the system default sched_util_clamp_min defined
1342 static unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
1344 /* All clamps are required to be less or equal than these values */
1345 static struct uclamp_se uclamp_default[UCLAMP_CNT];
1348 * This static key is used to reduce the uclamp overhead in the fast path. It
1349 * primarily disables the call to uclamp_rq_{inc, dec}() in
1350 * enqueue/dequeue_task().
1352 * This allows users to continue to enable uclamp in their kernel config with
1353 * minimum uclamp overhead in the fast path.
1355 * As soon as userspace modifies any of the uclamp knobs, the static key is
1356 * enabled, since we have an actual users that make use of uclamp
1359 * The knobs that would enable this static key are:
1361 * * A task modifying its uclamp value with sched_setattr().
1362 * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
1363 * * An admin modifying the cgroup cpu.uclamp.{min, max}
1365 DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
1367 /* Integer rounded range for each bucket */
1368 #define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
1370 #define for_each_clamp_id(clamp_id) \
1371 for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
1373 static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
1375 return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
1378 static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
1380 if (clamp_id == UCLAMP_MIN)
1382 return SCHED_CAPACITY_SCALE;
1385 static inline void uclamp_se_set(struct uclamp_se *uc_se,
1386 unsigned int value, bool user_defined)
1388 uc_se->value = value;
1389 uc_se->bucket_id = uclamp_bucket_id(value);
1390 uc_se->user_defined = user_defined;
1393 static inline unsigned int
1394 uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
1395 unsigned int clamp_value)
1398 * Avoid blocked utilization pushing up the frequency when we go
1399 * idle (which drops the max-clamp) by retaining the last known
1402 if (clamp_id == UCLAMP_MAX) {
1403 rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
1407 return uclamp_none(UCLAMP_MIN);
1410 static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
1411 unsigned int clamp_value)
1413 /* Reset max-clamp retention only on idle exit */
1414 if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1417 uclamp_rq_set(rq, clamp_id, clamp_value);
1421 unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
1422 unsigned int clamp_value)
1424 struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
1425 int bucket_id = UCLAMP_BUCKETS - 1;
1428 * Since both min and max clamps are max aggregated, find the
1429 * top most bucket with tasks in.
1431 for ( ; bucket_id >= 0; bucket_id--) {
1432 if (!bucket[bucket_id].tasks)
1434 return bucket[bucket_id].value;
1437 /* No tasks -- default clamp values */
1438 return uclamp_idle_value(rq, clamp_id, clamp_value);
1441 static void __uclamp_update_util_min_rt_default(struct task_struct *p)
1443 unsigned int default_util_min;
1444 struct uclamp_se *uc_se;
1446 lockdep_assert_held(&p->pi_lock);
1448 uc_se = &p->uclamp_req[UCLAMP_MIN];
1450 /* Only sync if user didn't override the default */
1451 if (uc_se->user_defined)
1454 default_util_min = sysctl_sched_uclamp_util_min_rt_default;
1455 uclamp_se_set(uc_se, default_util_min, false);
1458 static void uclamp_update_util_min_rt_default(struct task_struct *p)
1466 /* Protect updates to p->uclamp_* */
1467 rq = task_rq_lock(p, &rf);
1468 __uclamp_update_util_min_rt_default(p);
1469 task_rq_unlock(rq, p, &rf);
1472 static inline struct uclamp_se
1473 uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
1475 /* Copy by value as we could modify it */
1476 struct uclamp_se uc_req = p->uclamp_req[clamp_id];
1477 #ifdef CONFIG_UCLAMP_TASK_GROUP
1478 unsigned int tg_min, tg_max, value;
1481 * Tasks in autogroups or root task group will be
1482 * restricted by system defaults.
1484 if (task_group_is_autogroup(task_group(p)))
1486 if (task_group(p) == &root_task_group)
1489 tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
1490 tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
1491 value = uc_req.value;
1492 value = clamp(value, tg_min, tg_max);
1493 uclamp_se_set(&uc_req, value, false);
1500 * The effective clamp bucket index of a task depends on, by increasing
1502 * - the task specific clamp value, when explicitly requested from userspace
1503 * - the task group effective clamp value, for tasks not either in the root
1504 * group or in an autogroup
1505 * - the system default clamp value, defined by the sysadmin
1507 static inline struct uclamp_se
1508 uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
1510 struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
1511 struct uclamp_se uc_max = uclamp_default[clamp_id];
1513 /* System default restrictions always apply */
1514 if (unlikely(uc_req.value > uc_max.value))
1520 unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
1522 struct uclamp_se uc_eff;
1524 /* Task currently refcounted: use back-annotated (effective) value */
1525 if (p->uclamp[clamp_id].active)
1526 return (unsigned long)p->uclamp[clamp_id].value;
1528 uc_eff = uclamp_eff_get(p, clamp_id);
1530 return (unsigned long)uc_eff.value;
1534 * When a task is enqueued on a rq, the clamp bucket currently defined by the
1535 * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1536 * updates the rq's clamp value if required.
1538 * Tasks can have a task-specific value requested from user-space, track
1539 * within each bucket the maximum value for tasks refcounted in it.
1540 * This "local max aggregation" allows to track the exact "requested" value
1541 * for each bucket when all its RUNNABLE tasks require the same clamp.
1543 static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
1544 enum uclamp_id clamp_id)
1546 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1547 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1548 struct uclamp_bucket *bucket;
1550 lockdep_assert_rq_held(rq);
1552 /* Update task effective clamp */
1553 p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
1555 bucket = &uc_rq->bucket[uc_se->bucket_id];
1557 uc_se->active = true;
1559 uclamp_idle_reset(rq, clamp_id, uc_se->value);
1562 * Local max aggregation: rq buckets always track the max
1563 * "requested" clamp value of its RUNNABLE tasks.
1565 if (bucket->tasks == 1 || uc_se->value > bucket->value)
1566 bucket->value = uc_se->value;
1568 if (uc_se->value > uclamp_rq_get(rq, clamp_id))
1569 uclamp_rq_set(rq, clamp_id, uc_se->value);
1573 * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1574 * is released. If this is the last task reference counting the rq's max
1575 * active clamp value, then the rq's clamp value is updated.
1577 * Both refcounted tasks and rq's cached clamp values are expected to be
1578 * always valid. If it's detected they are not, as defensive programming,
1579 * enforce the expected state and warn.
1581 static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
1582 enum uclamp_id clamp_id)
1584 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1585 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1586 struct uclamp_bucket *bucket;
1587 unsigned int bkt_clamp;
1588 unsigned int rq_clamp;
1590 lockdep_assert_rq_held(rq);
1593 * If sched_uclamp_used was enabled after task @p was enqueued,
1594 * we could end up with unbalanced call to uclamp_rq_dec_id().
1596 * In this case the uc_se->active flag should be false since no uclamp
1597 * accounting was performed at enqueue time and we can just return
1600 * Need to be careful of the following enqueue/dequeue ordering
1604 * // sched_uclamp_used gets enabled
1607 * // Must not decrement bucket->tasks here
1610 * where we could end up with stale data in uc_se and
1611 * bucket[uc_se->bucket_id].
1613 * The following check here eliminates the possibility of such race.
1615 if (unlikely(!uc_se->active))
1618 bucket = &uc_rq->bucket[uc_se->bucket_id];
1620 SCHED_WARN_ON(!bucket->tasks);
1621 if (likely(bucket->tasks))
1624 uc_se->active = false;
1627 * Keep "local max aggregation" simple and accept to (possibly)
1628 * overboost some RUNNABLE tasks in the same bucket.
1629 * The rq clamp bucket value is reset to its base value whenever
1630 * there are no more RUNNABLE tasks refcounting it.
1632 if (likely(bucket->tasks))
1635 rq_clamp = uclamp_rq_get(rq, clamp_id);
1637 * Defensive programming: this should never happen. If it happens,
1638 * e.g. due to future modification, warn and fixup the expected value.
1640 SCHED_WARN_ON(bucket->value > rq_clamp);
1641 if (bucket->value >= rq_clamp) {
1642 bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
1643 uclamp_rq_set(rq, clamp_id, bkt_clamp);
1647 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
1649 enum uclamp_id clamp_id;
1652 * Avoid any overhead until uclamp is actually used by the userspace.
1654 * The condition is constructed such that a NOP is generated when
1655 * sched_uclamp_used is disabled.
1657 if (!static_branch_unlikely(&sched_uclamp_used))
1660 if (unlikely(!p->sched_class->uclamp_enabled))
1663 for_each_clamp_id(clamp_id)
1664 uclamp_rq_inc_id(rq, p, clamp_id);
1666 /* Reset clamp idle holding when there is one RUNNABLE task */
1667 if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
1668 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1671 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
1673 enum uclamp_id clamp_id;
1676 * Avoid any overhead until uclamp is actually used by the userspace.
1678 * The condition is constructed such that a NOP is generated when
1679 * sched_uclamp_used is disabled.
1681 if (!static_branch_unlikely(&sched_uclamp_used))
1684 if (unlikely(!p->sched_class->uclamp_enabled))
1687 for_each_clamp_id(clamp_id)
1688 uclamp_rq_dec_id(rq, p, clamp_id);
1691 static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
1692 enum uclamp_id clamp_id)
1694 if (!p->uclamp[clamp_id].active)
1697 uclamp_rq_dec_id(rq, p, clamp_id);
1698 uclamp_rq_inc_id(rq, p, clamp_id);
1701 * Make sure to clear the idle flag if we've transiently reached 0
1702 * active tasks on rq.
1704 if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1705 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1709 uclamp_update_active(struct task_struct *p)
1711 enum uclamp_id clamp_id;
1716 * Lock the task and the rq where the task is (or was) queued.
1718 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1719 * price to pay to safely serialize util_{min,max} updates with
1720 * enqueues, dequeues and migration operations.
1721 * This is the same locking schema used by __set_cpus_allowed_ptr().
1723 rq = task_rq_lock(p, &rf);
1726 * Setting the clamp bucket is serialized by task_rq_lock().
1727 * If the task is not yet RUNNABLE and its task_struct is not
1728 * affecting a valid clamp bucket, the next time it's enqueued,
1729 * it will already see the updated clamp bucket value.
1731 for_each_clamp_id(clamp_id)
1732 uclamp_rq_reinc_id(rq, p, clamp_id);
1734 task_rq_unlock(rq, p, &rf);
1737 #ifdef CONFIG_UCLAMP_TASK_GROUP
1739 uclamp_update_active_tasks(struct cgroup_subsys_state *css)
1741 struct css_task_iter it;
1742 struct task_struct *p;
1744 css_task_iter_start(css, 0, &it);
1745 while ((p = css_task_iter_next(&it)))
1746 uclamp_update_active(p);
1747 css_task_iter_end(&it);
1750 static void cpu_util_update_eff(struct cgroup_subsys_state *css);
1753 #ifdef CONFIG_SYSCTL
1754 #ifdef CONFIG_UCLAMP_TASK
1755 #ifdef CONFIG_UCLAMP_TASK_GROUP
1756 static void uclamp_update_root_tg(void)
1758 struct task_group *tg = &root_task_group;
1760 uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
1761 sysctl_sched_uclamp_util_min, false);
1762 uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
1763 sysctl_sched_uclamp_util_max, false);
1766 cpu_util_update_eff(&root_task_group.css);
1770 static void uclamp_update_root_tg(void) { }
1773 static void uclamp_sync_util_min_rt_default(void)
1775 struct task_struct *g, *p;
1778 * copy_process() sysctl_uclamp
1779 * uclamp_min_rt = X;
1780 * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
1781 * // link thread smp_mb__after_spinlock()
1782 * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
1783 * sched_post_fork() for_each_process_thread()
1784 * __uclamp_sync_rt() __uclamp_sync_rt()
1786 * Ensures that either sched_post_fork() will observe the new
1787 * uclamp_min_rt or for_each_process_thread() will observe the new
1790 read_lock(&tasklist_lock);
1791 smp_mb__after_spinlock();
1792 read_unlock(&tasklist_lock);
1795 for_each_process_thread(g, p)
1796 uclamp_update_util_min_rt_default(p);
1800 static int sysctl_sched_uclamp_handler(struct ctl_table *table, int write,
1801 void *buffer, size_t *lenp, loff_t *ppos)
1803 bool update_root_tg = false;
1804 int old_min, old_max, old_min_rt;
1807 mutex_lock(&uclamp_mutex);
1808 old_min = sysctl_sched_uclamp_util_min;
1809 old_max = sysctl_sched_uclamp_util_max;
1810 old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
1812 result = proc_dointvec(table, write, buffer, lenp, ppos);
1818 if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
1819 sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE ||
1820 sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
1826 if (old_min != sysctl_sched_uclamp_util_min) {
1827 uclamp_se_set(&uclamp_default[UCLAMP_MIN],
1828 sysctl_sched_uclamp_util_min, false);
1829 update_root_tg = true;
1831 if (old_max != sysctl_sched_uclamp_util_max) {
1832 uclamp_se_set(&uclamp_default[UCLAMP_MAX],
1833 sysctl_sched_uclamp_util_max, false);
1834 update_root_tg = true;
1837 if (update_root_tg) {
1838 static_branch_enable(&sched_uclamp_used);
1839 uclamp_update_root_tg();
1842 if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
1843 static_branch_enable(&sched_uclamp_used);
1844 uclamp_sync_util_min_rt_default();
1848 * We update all RUNNABLE tasks only when task groups are in use.
1849 * Otherwise, keep it simple and do just a lazy update at each next
1850 * task enqueue time.
1856 sysctl_sched_uclamp_util_min = old_min;
1857 sysctl_sched_uclamp_util_max = old_max;
1858 sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
1860 mutex_unlock(&uclamp_mutex);
1867 static int uclamp_validate(struct task_struct *p,
1868 const struct sched_attr *attr)
1870 int util_min = p->uclamp_req[UCLAMP_MIN].value;
1871 int util_max = p->uclamp_req[UCLAMP_MAX].value;
1873 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
1874 util_min = attr->sched_util_min;
1876 if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
1880 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
1881 util_max = attr->sched_util_max;
1883 if (util_max + 1 > SCHED_CAPACITY_SCALE + 1)
1887 if (util_min != -1 && util_max != -1 && util_min > util_max)
1891 * We have valid uclamp attributes; make sure uclamp is enabled.
1893 * We need to do that here, because enabling static branches is a
1894 * blocking operation which obviously cannot be done while holding
1897 static_branch_enable(&sched_uclamp_used);
1902 static bool uclamp_reset(const struct sched_attr *attr,
1903 enum uclamp_id clamp_id,
1904 struct uclamp_se *uc_se)
1906 /* Reset on sched class change for a non user-defined clamp value. */
1907 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)) &&
1908 !uc_se->user_defined)
1911 /* Reset on sched_util_{min,max} == -1. */
1912 if (clamp_id == UCLAMP_MIN &&
1913 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1914 attr->sched_util_min == -1) {
1918 if (clamp_id == UCLAMP_MAX &&
1919 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1920 attr->sched_util_max == -1) {
1927 static void __setscheduler_uclamp(struct task_struct *p,
1928 const struct sched_attr *attr)
1930 enum uclamp_id clamp_id;
1932 for_each_clamp_id(clamp_id) {
1933 struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
1936 if (!uclamp_reset(attr, clamp_id, uc_se))
1940 * RT by default have a 100% boost value that could be modified
1943 if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
1944 value = sysctl_sched_uclamp_util_min_rt_default;
1946 value = uclamp_none(clamp_id);
1948 uclamp_se_set(uc_se, value, false);
1952 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
1955 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1956 attr->sched_util_min != -1) {
1957 uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
1958 attr->sched_util_min, true);
1961 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1962 attr->sched_util_max != -1) {
1963 uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
1964 attr->sched_util_max, true);
1968 static void uclamp_fork(struct task_struct *p)
1970 enum uclamp_id clamp_id;
1973 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
1974 * as the task is still at its early fork stages.
1976 for_each_clamp_id(clamp_id)
1977 p->uclamp[clamp_id].active = false;
1979 if (likely(!p->sched_reset_on_fork))
1982 for_each_clamp_id(clamp_id) {
1983 uclamp_se_set(&p->uclamp_req[clamp_id],
1984 uclamp_none(clamp_id), false);
1988 static void uclamp_post_fork(struct task_struct *p)
1990 uclamp_update_util_min_rt_default(p);
1993 static void __init init_uclamp_rq(struct rq *rq)
1995 enum uclamp_id clamp_id;
1996 struct uclamp_rq *uc_rq = rq->uclamp;
1998 for_each_clamp_id(clamp_id) {
1999 uc_rq[clamp_id] = (struct uclamp_rq) {
2000 .value = uclamp_none(clamp_id)
2004 rq->uclamp_flags = UCLAMP_FLAG_IDLE;
2007 static void __init init_uclamp(void)
2009 struct uclamp_se uc_max = {};
2010 enum uclamp_id clamp_id;
2013 for_each_possible_cpu(cpu)
2014 init_uclamp_rq(cpu_rq(cpu));
2016 for_each_clamp_id(clamp_id) {
2017 uclamp_se_set(&init_task.uclamp_req[clamp_id],
2018 uclamp_none(clamp_id), false);
2021 /* System defaults allow max clamp values for both indexes */
2022 uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
2023 for_each_clamp_id(clamp_id) {
2024 uclamp_default[clamp_id] = uc_max;
2025 #ifdef CONFIG_UCLAMP_TASK_GROUP
2026 root_task_group.uclamp_req[clamp_id] = uc_max;
2027 root_task_group.uclamp[clamp_id] = uc_max;
2032 #else /* CONFIG_UCLAMP_TASK */
2033 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
2034 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
2035 static inline int uclamp_validate(struct task_struct *p,
2036 const struct sched_attr *attr)
2040 static void __setscheduler_uclamp(struct task_struct *p,
2041 const struct sched_attr *attr) { }
2042 static inline void uclamp_fork(struct task_struct *p) { }
2043 static inline void uclamp_post_fork(struct task_struct *p) { }
2044 static inline void init_uclamp(void) { }
2045 #endif /* CONFIG_UCLAMP_TASK */
2047 bool sched_task_on_rq(struct task_struct *p)
2049 return task_on_rq_queued(p);
2052 unsigned long get_wchan(struct task_struct *p)
2054 unsigned long ip = 0;
2057 if (!p || p == current)
2060 /* Only get wchan if task is blocked and we can keep it that way. */
2061 raw_spin_lock_irq(&p->pi_lock);
2062 state = READ_ONCE(p->__state);
2063 smp_rmb(); /* see try_to_wake_up() */
2064 if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq)
2065 ip = __get_wchan(p);
2066 raw_spin_unlock_irq(&p->pi_lock);
2071 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2073 if (!(flags & ENQUEUE_NOCLOCK))
2074 update_rq_clock(rq);
2076 if (!(flags & ENQUEUE_RESTORE)) {
2077 sched_info_enqueue(rq, p);
2078 psi_enqueue(p, (flags & ENQUEUE_WAKEUP) && !(flags & ENQUEUE_MIGRATED));
2081 uclamp_rq_inc(rq, p);
2082 p->sched_class->enqueue_task(rq, p, flags);
2084 if (sched_core_enabled(rq))
2085 sched_core_enqueue(rq, p);
2088 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
2090 if (sched_core_enabled(rq))
2091 sched_core_dequeue(rq, p, flags);
2093 if (!(flags & DEQUEUE_NOCLOCK))
2094 update_rq_clock(rq);
2096 if (!(flags & DEQUEUE_SAVE)) {
2097 sched_info_dequeue(rq, p);
2098 psi_dequeue(p, flags & DEQUEUE_SLEEP);
2101 uclamp_rq_dec(rq, p);
2102 p->sched_class->dequeue_task(rq, p, flags);
2105 void activate_task(struct rq *rq, struct task_struct *p, int flags)
2107 if (task_on_rq_migrating(p))
2108 flags |= ENQUEUE_MIGRATED;
2109 if (flags & ENQUEUE_MIGRATED)
2110 sched_mm_cid_migrate_to(rq, p);
2112 enqueue_task(rq, p, flags);
2114 p->on_rq = TASK_ON_RQ_QUEUED;
2117 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
2119 p->on_rq = (flags & DEQUEUE_SLEEP) ? 0 : TASK_ON_RQ_MIGRATING;
2121 dequeue_task(rq, p, flags);
2124 static inline int __normal_prio(int policy, int rt_prio, int nice)
2128 if (dl_policy(policy))
2129 prio = MAX_DL_PRIO - 1;
2130 else if (rt_policy(policy))
2131 prio = MAX_RT_PRIO - 1 - rt_prio;
2133 prio = NICE_TO_PRIO(nice);
2139 * Calculate the expected normal priority: i.e. priority
2140 * without taking RT-inheritance into account. Might be
2141 * boosted by interactivity modifiers. Changes upon fork,
2142 * setprio syscalls, and whenever the interactivity
2143 * estimator recalculates.
2145 static inline int normal_prio(struct task_struct *p)
2147 return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio));
2151 * Calculate the current priority, i.e. the priority
2152 * taken into account by the scheduler. This value might
2153 * be boosted by RT tasks, or might be boosted by
2154 * interactivity modifiers. Will be RT if the task got
2155 * RT-boosted. If not then it returns p->normal_prio.
2157 static int effective_prio(struct task_struct *p)
2159 p->normal_prio = normal_prio(p);
2161 * If we are RT tasks or we were boosted to RT priority,
2162 * keep the priority unchanged. Otherwise, update priority
2163 * to the normal priority:
2165 if (!rt_prio(p->prio))
2166 return p->normal_prio;
2171 * task_curr - is this task currently executing on a CPU?
2172 * @p: the task in question.
2174 * Return: 1 if the task is currently executing. 0 otherwise.
2176 inline int task_curr(const struct task_struct *p)
2178 return cpu_curr(task_cpu(p)) == p;
2182 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
2183 * use the balance_callback list if you want balancing.
2185 * this means any call to check_class_changed() must be followed by a call to
2186 * balance_callback().
2188 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2189 const struct sched_class *prev_class,
2192 if (prev_class != p->sched_class) {
2193 if (prev_class->switched_from)
2194 prev_class->switched_from(rq, p);
2196 p->sched_class->switched_to(rq, p);
2197 } else if (oldprio != p->prio || dl_task(p))
2198 p->sched_class->prio_changed(rq, p, oldprio);
2201 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
2203 if (p->sched_class == rq->curr->sched_class)
2204 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
2205 else if (sched_class_above(p->sched_class, rq->curr->sched_class))
2209 * A queue event has occurred, and we're going to schedule. In
2210 * this case, we can save a useless back to back clock update.
2212 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
2213 rq_clock_skip_update(rq);
2217 * wait_task_inactive - wait for a thread to unschedule.
2219 * Wait for the thread to block in any of the states set in @match_state.
2220 * If it changes, i.e. @p might have woken up, then return zero. When we
2221 * succeed in waiting for @p to be off its CPU, we return a positive number
2222 * (its total switch count). If a second call a short while later returns the
2223 * same number, the caller can be sure that @p has remained unscheduled the
2226 * The caller must ensure that the task *will* unschedule sometime soon,
2227 * else this function might spin for a *long* time. This function can't
2228 * be called with interrupts off, or it may introduce deadlock with
2229 * smp_call_function() if an IPI is sent by the same process we are
2230 * waiting to become inactive.
2232 unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state)
2234 int running, queued;
2241 * We do the initial early heuristics without holding
2242 * any task-queue locks at all. We'll only try to get
2243 * the runqueue lock when things look like they will
2249 * If the task is actively running on another CPU
2250 * still, just relax and busy-wait without holding
2253 * NOTE! Since we don't hold any locks, it's not
2254 * even sure that "rq" stays as the right runqueue!
2255 * But we don't care, since "task_on_cpu()" will
2256 * return false if the runqueue has changed and p
2257 * is actually now running somewhere else!
2259 while (task_on_cpu(rq, p)) {
2260 if (!(READ_ONCE(p->__state) & match_state))
2266 * Ok, time to look more closely! We need the rq
2267 * lock now, to be *sure*. If we're wrong, we'll
2268 * just go back and repeat.
2270 rq = task_rq_lock(p, &rf);
2271 trace_sched_wait_task(p);
2272 running = task_on_cpu(rq, p);
2273 queued = task_on_rq_queued(p);
2275 if (READ_ONCE(p->__state) & match_state)
2276 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2277 task_rq_unlock(rq, p, &rf);
2280 * If it changed from the expected state, bail out now.
2282 if (unlikely(!ncsw))
2286 * Was it really running after all now that we
2287 * checked with the proper locks actually held?
2289 * Oops. Go back and try again..
2291 if (unlikely(running)) {
2297 * It's not enough that it's not actively running,
2298 * it must be off the runqueue _entirely_, and not
2301 * So if it was still runnable (but just not actively
2302 * running right now), it's preempted, and we should
2303 * yield - it could be a while.
2305 if (unlikely(queued)) {
2306 ktime_t to = NSEC_PER_SEC / HZ;
2308 set_current_state(TASK_UNINTERRUPTIBLE);
2309 schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD);
2314 * Ahh, all good. It wasn't running, and it wasn't
2315 * runnable, which means that it will never become
2316 * running in the future either. We're all done!
2327 __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx);
2329 static int __set_cpus_allowed_ptr(struct task_struct *p,
2330 struct affinity_context *ctx);
2332 static void migrate_disable_switch(struct rq *rq, struct task_struct *p)
2334 struct affinity_context ac = {
2335 .new_mask = cpumask_of(rq->cpu),
2336 .flags = SCA_MIGRATE_DISABLE,
2339 if (likely(!p->migration_disabled))
2342 if (p->cpus_ptr != &p->cpus_mask)
2346 * Violates locking rules! see comment in __do_set_cpus_allowed().
2348 __do_set_cpus_allowed(p, &ac);
2351 void migrate_disable(void)
2353 struct task_struct *p = current;
2355 if (p->migration_disabled) {
2356 p->migration_disabled++;
2361 this_rq()->nr_pinned++;
2362 p->migration_disabled = 1;
2365 EXPORT_SYMBOL_GPL(migrate_disable);
2367 void migrate_enable(void)
2369 struct task_struct *p = current;
2370 struct affinity_context ac = {
2371 .new_mask = &p->cpus_mask,
2372 .flags = SCA_MIGRATE_ENABLE,
2375 if (p->migration_disabled > 1) {
2376 p->migration_disabled--;
2380 if (WARN_ON_ONCE(!p->migration_disabled))
2384 * Ensure stop_task runs either before or after this, and that
2385 * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
2388 if (p->cpus_ptr != &p->cpus_mask)
2389 __set_cpus_allowed_ptr(p, &ac);
2391 * Mustn't clear migration_disabled() until cpus_ptr points back at the
2392 * regular cpus_mask, otherwise things that race (eg.
2393 * select_fallback_rq) get confused.
2396 p->migration_disabled = 0;
2397 this_rq()->nr_pinned--;
2400 EXPORT_SYMBOL_GPL(migrate_enable);
2402 static inline bool rq_has_pinned_tasks(struct rq *rq)
2404 return rq->nr_pinned;
2408 * Per-CPU kthreads are allowed to run on !active && online CPUs, see
2409 * __set_cpus_allowed_ptr() and select_fallback_rq().
2411 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
2413 /* When not in the task's cpumask, no point in looking further. */
2414 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
2417 /* migrate_disabled() must be allowed to finish. */
2418 if (is_migration_disabled(p))
2419 return cpu_online(cpu);
2421 /* Non kernel threads are not allowed during either online or offline. */
2422 if (!(p->flags & PF_KTHREAD))
2423 return cpu_active(cpu) && task_cpu_possible(cpu, p);
2425 /* KTHREAD_IS_PER_CPU is always allowed. */
2426 if (kthread_is_per_cpu(p))
2427 return cpu_online(cpu);
2429 /* Regular kernel threads don't get to stay during offline. */
2433 /* But are allowed during online. */
2434 return cpu_online(cpu);
2438 * This is how migration works:
2440 * 1) we invoke migration_cpu_stop() on the target CPU using
2442 * 2) stopper starts to run (implicitly forcing the migrated thread
2444 * 3) it checks whether the migrated task is still in the wrong runqueue.
2445 * 4) if it's in the wrong runqueue then the migration thread removes
2446 * it and puts it into the right queue.
2447 * 5) stopper completes and stop_one_cpu() returns and the migration
2452 * move_queued_task - move a queued task to new rq.
2454 * Returns (locked) new rq. Old rq's lock is released.
2456 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
2457 struct task_struct *p, int new_cpu)
2459 lockdep_assert_rq_held(rq);
2461 deactivate_task(rq, p, DEQUEUE_NOCLOCK);
2462 set_task_cpu(p, new_cpu);
2465 rq = cpu_rq(new_cpu);
2468 WARN_ON_ONCE(task_cpu(p) != new_cpu);
2469 activate_task(rq, p, 0);
2470 check_preempt_curr(rq, p, 0);
2475 struct migration_arg {
2476 struct task_struct *task;
2478 struct set_affinity_pending *pending;
2482 * @refs: number of wait_for_completion()
2483 * @stop_pending: is @stop_work in use
2485 struct set_affinity_pending {
2487 unsigned int stop_pending;
2488 struct completion done;
2489 struct cpu_stop_work stop_work;
2490 struct migration_arg arg;
2494 * Move (not current) task off this CPU, onto the destination CPU. We're doing
2495 * this because either it can't run here any more (set_cpus_allowed()
2496 * away from this CPU, or CPU going down), or because we're
2497 * attempting to rebalance this task on exec (sched_exec).
2499 * So we race with normal scheduler movements, but that's OK, as long
2500 * as the task is no longer on this CPU.
2502 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
2503 struct task_struct *p, int dest_cpu)
2505 /* Affinity changed (again). */
2506 if (!is_cpu_allowed(p, dest_cpu))
2509 update_rq_clock(rq);
2510 rq = move_queued_task(rq, rf, p, dest_cpu);
2516 * migration_cpu_stop - this will be executed by a highprio stopper thread
2517 * and performs thread migration by bumping thread off CPU then
2518 * 'pushing' onto another runqueue.
2520 static int migration_cpu_stop(void *data)
2522 struct migration_arg *arg = data;
2523 struct set_affinity_pending *pending = arg->pending;
2524 struct task_struct *p = arg->task;
2525 struct rq *rq = this_rq();
2526 bool complete = false;
2530 * The original target CPU might have gone down and we might
2531 * be on another CPU but it doesn't matter.
2533 local_irq_save(rf.flags);
2535 * We need to explicitly wake pending tasks before running
2536 * __migrate_task() such that we will not miss enforcing cpus_ptr
2537 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
2539 flush_smp_call_function_queue();
2541 raw_spin_lock(&p->pi_lock);
2545 * If we were passed a pending, then ->stop_pending was set, thus
2546 * p->migration_pending must have remained stable.
2548 WARN_ON_ONCE(pending && pending != p->migration_pending);
2551 * If task_rq(p) != rq, it cannot be migrated here, because we're
2552 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
2553 * we're holding p->pi_lock.
2555 if (task_rq(p) == rq) {
2556 if (is_migration_disabled(p))
2560 p->migration_pending = NULL;
2563 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask))
2567 if (task_on_rq_queued(p))
2568 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
2570 p->wake_cpu = arg->dest_cpu;
2573 * XXX __migrate_task() can fail, at which point we might end
2574 * up running on a dodgy CPU, AFAICT this can only happen
2575 * during CPU hotplug, at which point we'll get pushed out
2576 * anyway, so it's probably not a big deal.
2579 } else if (pending) {
2581 * This happens when we get migrated between migrate_enable()'s
2582 * preempt_enable() and scheduling the stopper task. At that
2583 * point we're a regular task again and not current anymore.
2585 * A !PREEMPT kernel has a giant hole here, which makes it far
2590 * The task moved before the stopper got to run. We're holding
2591 * ->pi_lock, so the allowed mask is stable - if it got
2592 * somewhere allowed, we're done.
2594 if (cpumask_test_cpu(task_cpu(p), p->cpus_ptr)) {
2595 p->migration_pending = NULL;
2601 * When migrate_enable() hits a rq mis-match we can't reliably
2602 * determine is_migration_disabled() and so have to chase after
2605 WARN_ON_ONCE(!pending->stop_pending);
2606 task_rq_unlock(rq, p, &rf);
2607 stop_one_cpu_nowait(task_cpu(p), migration_cpu_stop,
2608 &pending->arg, &pending->stop_work);
2613 pending->stop_pending = false;
2614 task_rq_unlock(rq, p, &rf);
2617 complete_all(&pending->done);
2622 int push_cpu_stop(void *arg)
2624 struct rq *lowest_rq = NULL, *rq = this_rq();
2625 struct task_struct *p = arg;
2627 raw_spin_lock_irq(&p->pi_lock);
2628 raw_spin_rq_lock(rq);
2630 if (task_rq(p) != rq)
2633 if (is_migration_disabled(p)) {
2634 p->migration_flags |= MDF_PUSH;
2638 p->migration_flags &= ~MDF_PUSH;
2640 if (p->sched_class->find_lock_rq)
2641 lowest_rq = p->sched_class->find_lock_rq(p, rq);
2646 // XXX validate p is still the highest prio task
2647 if (task_rq(p) == rq) {
2648 deactivate_task(rq, p, 0);
2649 set_task_cpu(p, lowest_rq->cpu);
2650 activate_task(lowest_rq, p, 0);
2651 resched_curr(lowest_rq);
2654 double_unlock_balance(rq, lowest_rq);
2657 rq->push_busy = false;
2658 raw_spin_rq_unlock(rq);
2659 raw_spin_unlock_irq(&p->pi_lock);
2666 * sched_class::set_cpus_allowed must do the below, but is not required to
2667 * actually call this function.
2669 void set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx)
2671 if (ctx->flags & (SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) {
2672 p->cpus_ptr = ctx->new_mask;
2676 cpumask_copy(&p->cpus_mask, ctx->new_mask);
2677 p->nr_cpus_allowed = cpumask_weight(ctx->new_mask);
2680 * Swap in a new user_cpus_ptr if SCA_USER flag set
2682 if (ctx->flags & SCA_USER)
2683 swap(p->user_cpus_ptr, ctx->user_mask);
2687 __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx)
2689 struct rq *rq = task_rq(p);
2690 bool queued, running;
2693 * This here violates the locking rules for affinity, since we're only
2694 * supposed to change these variables while holding both rq->lock and
2697 * HOWEVER, it magically works, because ttwu() is the only code that
2698 * accesses these variables under p->pi_lock and only does so after
2699 * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
2700 * before finish_task().
2702 * XXX do further audits, this smells like something putrid.
2704 if (ctx->flags & SCA_MIGRATE_DISABLE)
2705 SCHED_WARN_ON(!p->on_cpu);
2707 lockdep_assert_held(&p->pi_lock);
2709 queued = task_on_rq_queued(p);
2710 running = task_current(rq, p);
2714 * Because __kthread_bind() calls this on blocked tasks without
2717 lockdep_assert_rq_held(rq);
2718 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
2721 put_prev_task(rq, p);
2723 p->sched_class->set_cpus_allowed(p, ctx);
2726 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
2728 set_next_task(rq, p);
2732 * Used for kthread_bind() and select_fallback_rq(), in both cases the user
2733 * affinity (if any) should be destroyed too.
2735 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
2737 struct affinity_context ac = {
2738 .new_mask = new_mask,
2740 .flags = SCA_USER, /* clear the user requested mask */
2742 union cpumask_rcuhead {
2744 struct rcu_head rcu;
2747 __do_set_cpus_allowed(p, &ac);
2750 * Because this is called with p->pi_lock held, it is not possible
2751 * to use kfree() here (when PREEMPT_RT=y), therefore punt to using
2754 kfree_rcu((union cpumask_rcuhead *)ac.user_mask, rcu);
2757 static cpumask_t *alloc_user_cpus_ptr(int node)
2760 * See do_set_cpus_allowed() above for the rcu_head usage.
2762 int size = max_t(int, cpumask_size(), sizeof(struct rcu_head));
2764 return kmalloc_node(size, GFP_KERNEL, node);
2767 int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src,
2770 cpumask_t *user_mask;
2771 unsigned long flags;
2774 * Always clear dst->user_cpus_ptr first as their user_cpus_ptr's
2775 * may differ by now due to racing.
2777 dst->user_cpus_ptr = NULL;
2780 * This check is racy and losing the race is a valid situation.
2781 * It is not worth the extra overhead of taking the pi_lock on
2784 if (data_race(!src->user_cpus_ptr))
2787 user_mask = alloc_user_cpus_ptr(node);
2792 * Use pi_lock to protect content of user_cpus_ptr
2794 * Though unlikely, user_cpus_ptr can be reset to NULL by a concurrent
2795 * do_set_cpus_allowed().
2797 raw_spin_lock_irqsave(&src->pi_lock, flags);
2798 if (src->user_cpus_ptr) {
2799 swap(dst->user_cpus_ptr, user_mask);
2800 cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr);
2802 raw_spin_unlock_irqrestore(&src->pi_lock, flags);
2804 if (unlikely(user_mask))
2810 static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p)
2812 struct cpumask *user_mask = NULL;
2814 swap(p->user_cpus_ptr, user_mask);
2819 void release_user_cpus_ptr(struct task_struct *p)
2821 kfree(clear_user_cpus_ptr(p));
2825 * This function is wildly self concurrent; here be dragons.
2828 * When given a valid mask, __set_cpus_allowed_ptr() must block until the
2829 * designated task is enqueued on an allowed CPU. If that task is currently
2830 * running, we have to kick it out using the CPU stopper.
2832 * Migrate-Disable comes along and tramples all over our nice sandcastle.
2835 * Initial conditions: P0->cpus_mask = [0, 1]
2839 * migrate_disable();
2841 * set_cpus_allowed_ptr(P0, [1]);
2843 * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
2844 * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
2845 * This means we need the following scheme:
2849 * migrate_disable();
2851 * set_cpus_allowed_ptr(P0, [1]);
2855 * __set_cpus_allowed_ptr();
2856 * <wakes local stopper>
2857 * `--> <woken on migration completion>
2859 * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
2860 * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
2861 * task p are serialized by p->pi_lock, which we can leverage: the one that
2862 * should come into effect at the end of the Migrate-Disable region is the last
2863 * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
2864 * but we still need to properly signal those waiting tasks at the appropriate
2867 * This is implemented using struct set_affinity_pending. The first
2868 * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
2869 * setup an instance of that struct and install it on the targeted task_struct.
2870 * Any and all further callers will reuse that instance. Those then wait for
2871 * a completion signaled at the tail of the CPU stopper callback (1), triggered
2872 * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
2875 * (1) In the cases covered above. There is one more where the completion is
2876 * signaled within affine_move_task() itself: when a subsequent affinity request
2877 * occurs after the stopper bailed out due to the targeted task still being
2878 * Migrate-Disable. Consider:
2880 * Initial conditions: P0->cpus_mask = [0, 1]
2884 * migrate_disable();
2886 * set_cpus_allowed_ptr(P0, [1]);
2889 * migration_cpu_stop()
2890 * is_migration_disabled()
2892 * set_cpus_allowed_ptr(P0, [0, 1]);
2893 * <signal completion>
2896 * Note that the above is safe vs a concurrent migrate_enable(), as any
2897 * pending affinity completion is preceded by an uninstallation of
2898 * p->migration_pending done with p->pi_lock held.
2900 static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf,
2901 int dest_cpu, unsigned int flags)
2902 __releases(rq->lock)
2903 __releases(p->pi_lock)
2905 struct set_affinity_pending my_pending = { }, *pending = NULL;
2906 bool stop_pending, complete = false;
2908 /* Can the task run on the task's current CPU? If so, we're done */
2909 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) {
2910 struct task_struct *push_task = NULL;
2912 if ((flags & SCA_MIGRATE_ENABLE) &&
2913 (p->migration_flags & MDF_PUSH) && !rq->push_busy) {
2914 rq->push_busy = true;
2915 push_task = get_task_struct(p);
2919 * If there are pending waiters, but no pending stop_work,
2920 * then complete now.
2922 pending = p->migration_pending;
2923 if (pending && !pending->stop_pending) {
2924 p->migration_pending = NULL;
2928 task_rq_unlock(rq, p, rf);
2931 stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
2936 complete_all(&pending->done);
2941 if (!(flags & SCA_MIGRATE_ENABLE)) {
2942 /* serialized by p->pi_lock */
2943 if (!p->migration_pending) {
2944 /* Install the request */
2945 refcount_set(&my_pending.refs, 1);
2946 init_completion(&my_pending.done);
2947 my_pending.arg = (struct migration_arg) {
2949 .dest_cpu = dest_cpu,
2950 .pending = &my_pending,
2953 p->migration_pending = &my_pending;
2955 pending = p->migration_pending;
2956 refcount_inc(&pending->refs);
2958 * Affinity has changed, but we've already installed a
2959 * pending. migration_cpu_stop() *must* see this, else
2960 * we risk a completion of the pending despite having a
2961 * task on a disallowed CPU.
2963 * Serialized by p->pi_lock, so this is safe.
2965 pending->arg.dest_cpu = dest_cpu;
2968 pending = p->migration_pending;
2970 * - !MIGRATE_ENABLE:
2971 * we'll have installed a pending if there wasn't one already.
2974 * we're here because the current CPU isn't matching anymore,
2975 * the only way that can happen is because of a concurrent
2976 * set_cpus_allowed_ptr() call, which should then still be
2977 * pending completion.
2979 * Either way, we really should have a @pending here.
2981 if (WARN_ON_ONCE(!pending)) {
2982 task_rq_unlock(rq, p, rf);
2986 if (task_on_cpu(rq, p) || READ_ONCE(p->__state) == TASK_WAKING) {
2988 * MIGRATE_ENABLE gets here because 'p == current', but for
2989 * anything else we cannot do is_migration_disabled(), punt
2990 * and have the stopper function handle it all race-free.
2992 stop_pending = pending->stop_pending;
2994 pending->stop_pending = true;
2996 if (flags & SCA_MIGRATE_ENABLE)
2997 p->migration_flags &= ~MDF_PUSH;
2999 task_rq_unlock(rq, p, rf);
3001 if (!stop_pending) {
3002 stop_one_cpu_nowait(cpu_of(rq), migration_cpu_stop,
3003 &pending->arg, &pending->stop_work);
3006 if (flags & SCA_MIGRATE_ENABLE)
3010 if (!is_migration_disabled(p)) {
3011 if (task_on_rq_queued(p))
3012 rq = move_queued_task(rq, rf, p, dest_cpu);
3014 if (!pending->stop_pending) {
3015 p->migration_pending = NULL;
3019 task_rq_unlock(rq, p, rf);
3022 complete_all(&pending->done);
3025 wait_for_completion(&pending->done);
3027 if (refcount_dec_and_test(&pending->refs))
3028 wake_up_var(&pending->refs); /* No UaF, just an address */
3031 * Block the original owner of &pending until all subsequent callers
3032 * have seen the completion and decremented the refcount
3034 wait_var_event(&my_pending.refs, !refcount_read(&my_pending.refs));
3037 WARN_ON_ONCE(my_pending.stop_pending);
3043 * Called with both p->pi_lock and rq->lock held; drops both before returning.
3045 static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
3046 struct affinity_context *ctx,
3048 struct rq_flags *rf)
3049 __releases(rq->lock)
3050 __releases(p->pi_lock)
3052 const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p);
3053 const struct cpumask *cpu_valid_mask = cpu_active_mask;
3054 bool kthread = p->flags & PF_KTHREAD;
3055 unsigned int dest_cpu;
3058 update_rq_clock(rq);
3060 if (kthread || is_migration_disabled(p)) {
3062 * Kernel threads are allowed on online && !active CPUs,
3063 * however, during cpu-hot-unplug, even these might get pushed
3064 * away if not KTHREAD_IS_PER_CPU.
3066 * Specifically, migration_disabled() tasks must not fail the
3067 * cpumask_any_and_distribute() pick below, esp. so on
3068 * SCA_MIGRATE_ENABLE, otherwise we'll not call
3069 * set_cpus_allowed_common() and actually reset p->cpus_ptr.
3071 cpu_valid_mask = cpu_online_mask;
3074 if (!kthread && !cpumask_subset(ctx->new_mask, cpu_allowed_mask)) {
3080 * Must re-check here, to close a race against __kthread_bind(),
3081 * sched_setaffinity() is not guaranteed to observe the flag.
3083 if ((ctx->flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) {
3088 if (!(ctx->flags & SCA_MIGRATE_ENABLE)) {
3089 if (cpumask_equal(&p->cpus_mask, ctx->new_mask)) {
3090 if (ctx->flags & SCA_USER)
3091 swap(p->user_cpus_ptr, ctx->user_mask);
3095 if (WARN_ON_ONCE(p == current &&
3096 is_migration_disabled(p) &&
3097 !cpumask_test_cpu(task_cpu(p), ctx->new_mask))) {
3104 * Picking a ~random cpu helps in cases where we are changing affinity
3105 * for groups of tasks (ie. cpuset), so that load balancing is not
3106 * immediately required to distribute the tasks within their new mask.
3108 dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, ctx->new_mask);
3109 if (dest_cpu >= nr_cpu_ids) {
3114 __do_set_cpus_allowed(p, ctx);
3116 return affine_move_task(rq, p, rf, dest_cpu, ctx->flags);
3119 task_rq_unlock(rq, p, rf);
3125 * Change a given task's CPU affinity. Migrate the thread to a
3126 * proper CPU and schedule it away if the CPU it's executing on
3127 * is removed from the allowed bitmask.
3129 * NOTE: the caller must have a valid reference to the task, the
3130 * task must not exit() & deallocate itself prematurely. The
3131 * call is not atomic; no spinlocks may be held.
3133 static int __set_cpus_allowed_ptr(struct task_struct *p,
3134 struct affinity_context *ctx)
3139 rq = task_rq_lock(p, &rf);
3141 * Masking should be skipped if SCA_USER or any of the SCA_MIGRATE_*
3144 if (p->user_cpus_ptr &&
3145 !(ctx->flags & (SCA_USER | SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) &&
3146 cpumask_and(rq->scratch_mask, ctx->new_mask, p->user_cpus_ptr))
3147 ctx->new_mask = rq->scratch_mask;
3149 return __set_cpus_allowed_ptr_locked(p, ctx, rq, &rf);
3152 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
3154 struct affinity_context ac = {
3155 .new_mask = new_mask,
3159 return __set_cpus_allowed_ptr(p, &ac);
3161 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
3164 * Change a given task's CPU affinity to the intersection of its current
3165 * affinity mask and @subset_mask, writing the resulting mask to @new_mask.
3166 * If user_cpus_ptr is defined, use it as the basis for restricting CPU
3167 * affinity or use cpu_online_mask instead.
3169 * If the resulting mask is empty, leave the affinity unchanged and return
3172 static int restrict_cpus_allowed_ptr(struct task_struct *p,
3173 struct cpumask *new_mask,
3174 const struct cpumask *subset_mask)
3176 struct affinity_context ac = {
3177 .new_mask = new_mask,
3184 rq = task_rq_lock(p, &rf);
3187 * Forcefully restricting the affinity of a deadline task is
3188 * likely to cause problems, so fail and noisily override the
3191 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
3196 if (!cpumask_and(new_mask, task_user_cpus(p), subset_mask)) {
3201 return __set_cpus_allowed_ptr_locked(p, &ac, rq, &rf);
3204 task_rq_unlock(rq, p, &rf);
3209 * Restrict the CPU affinity of task @p so that it is a subset of
3210 * task_cpu_possible_mask() and point @p->user_cpus_ptr to a copy of the
3211 * old affinity mask. If the resulting mask is empty, we warn and walk
3212 * up the cpuset hierarchy until we find a suitable mask.
3214 void force_compatible_cpus_allowed_ptr(struct task_struct *p)
3216 cpumask_var_t new_mask;
3217 const struct cpumask *override_mask = task_cpu_possible_mask(p);
3219 alloc_cpumask_var(&new_mask, GFP_KERNEL);
3222 * __migrate_task() can fail silently in the face of concurrent
3223 * offlining of the chosen destination CPU, so take the hotplug
3224 * lock to ensure that the migration succeeds.
3227 if (!cpumask_available(new_mask))
3230 if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask))
3234 * We failed to find a valid subset of the affinity mask for the
3235 * task, so override it based on its cpuset hierarchy.
3237 cpuset_cpus_allowed(p, new_mask);
3238 override_mask = new_mask;
3241 if (printk_ratelimit()) {
3242 printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n",
3243 task_pid_nr(p), p->comm,
3244 cpumask_pr_args(override_mask));
3247 WARN_ON(set_cpus_allowed_ptr(p, override_mask));
3250 free_cpumask_var(new_mask);
3254 __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx);
3257 * Restore the affinity of a task @p which was previously restricted by a
3258 * call to force_compatible_cpus_allowed_ptr().
3260 * It is the caller's responsibility to serialise this with any calls to
3261 * force_compatible_cpus_allowed_ptr(@p).
3263 void relax_compatible_cpus_allowed_ptr(struct task_struct *p)
3265 struct affinity_context ac = {
3266 .new_mask = task_user_cpus(p),
3272 * Try to restore the old affinity mask with __sched_setaffinity().
3273 * Cpuset masking will be done there too.
3275 ret = __sched_setaffinity(p, &ac);
3279 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
3281 #ifdef CONFIG_SCHED_DEBUG
3282 unsigned int state = READ_ONCE(p->__state);
3285 * We should never call set_task_cpu() on a blocked task,
3286 * ttwu() will sort out the placement.
3288 WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq);
3291 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
3292 * because schedstat_wait_{start,end} rebase migrating task's wait_start
3293 * time relying on p->on_rq.
3295 WARN_ON_ONCE(state == TASK_RUNNING &&
3296 p->sched_class == &fair_sched_class &&
3297 (p->on_rq && !task_on_rq_migrating(p)));
3299 #ifdef CONFIG_LOCKDEP
3301 * The caller should hold either p->pi_lock or rq->lock, when changing
3302 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
3304 * sched_move_task() holds both and thus holding either pins the cgroup,
3307 * Furthermore, all task_rq users should acquire both locks, see
3310 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
3311 lockdep_is_held(__rq_lockp(task_rq(p)))));
3314 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
3316 WARN_ON_ONCE(!cpu_online(new_cpu));
3318 WARN_ON_ONCE(is_migration_disabled(p));
3321 trace_sched_migrate_task(p, new_cpu);
3323 if (task_cpu(p) != new_cpu) {
3324 if (p->sched_class->migrate_task_rq)
3325 p->sched_class->migrate_task_rq(p, new_cpu);
3326 p->se.nr_migrations++;
3328 sched_mm_cid_migrate_from(p);
3329 perf_event_task_migrate(p);
3332 __set_task_cpu(p, new_cpu);
3335 #ifdef CONFIG_NUMA_BALANCING
3336 static void __migrate_swap_task(struct task_struct *p, int cpu)
3338 if (task_on_rq_queued(p)) {
3339 struct rq *src_rq, *dst_rq;
3340 struct rq_flags srf, drf;
3342 src_rq = task_rq(p);
3343 dst_rq = cpu_rq(cpu);
3345 rq_pin_lock(src_rq, &srf);
3346 rq_pin_lock(dst_rq, &drf);
3348 deactivate_task(src_rq, p, 0);
3349 set_task_cpu(p, cpu);
3350 activate_task(dst_rq, p, 0);
3351 check_preempt_curr(dst_rq, p, 0);
3353 rq_unpin_lock(dst_rq, &drf);
3354 rq_unpin_lock(src_rq, &srf);
3358 * Task isn't running anymore; make it appear like we migrated
3359 * it before it went to sleep. This means on wakeup we make the
3360 * previous CPU our target instead of where it really is.
3366 struct migration_swap_arg {
3367 struct task_struct *src_task, *dst_task;
3368 int src_cpu, dst_cpu;
3371 static int migrate_swap_stop(void *data)
3373 struct migration_swap_arg *arg = data;
3374 struct rq *src_rq, *dst_rq;
3377 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
3380 src_rq = cpu_rq(arg->src_cpu);
3381 dst_rq = cpu_rq(arg->dst_cpu);
3383 double_raw_lock(&arg->src_task->pi_lock,
3384 &arg->dst_task->pi_lock);
3385 double_rq_lock(src_rq, dst_rq);
3387 if (task_cpu(arg->dst_task) != arg->dst_cpu)
3390 if (task_cpu(arg->src_task) != arg->src_cpu)
3393 if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
3396 if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
3399 __migrate_swap_task(arg->src_task, arg->dst_cpu);
3400 __migrate_swap_task(arg->dst_task, arg->src_cpu);
3405 double_rq_unlock(src_rq, dst_rq);
3406 raw_spin_unlock(&arg->dst_task->pi_lock);
3407 raw_spin_unlock(&arg->src_task->pi_lock);
3413 * Cross migrate two tasks
3415 int migrate_swap(struct task_struct *cur, struct task_struct *p,
3416 int target_cpu, int curr_cpu)
3418 struct migration_swap_arg arg;
3421 arg = (struct migration_swap_arg){
3423 .src_cpu = curr_cpu,
3425 .dst_cpu = target_cpu,
3428 if (arg.src_cpu == arg.dst_cpu)
3432 * These three tests are all lockless; this is OK since all of them
3433 * will be re-checked with proper locks held further down the line.
3435 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
3438 if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
3441 if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
3444 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
3445 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
3450 #endif /* CONFIG_NUMA_BALANCING */
3453 * kick_process - kick a running thread to enter/exit the kernel
3454 * @p: the to-be-kicked thread
3456 * Cause a process which is running on another CPU to enter
3457 * kernel-mode, without any delay. (to get signals handled.)
3459 * NOTE: this function doesn't have to take the runqueue lock,
3460 * because all it wants to ensure is that the remote task enters
3461 * the kernel. If the IPI races and the task has been migrated
3462 * to another CPU then no harm is done and the purpose has been
3465 void kick_process(struct task_struct *p)
3471 if ((cpu != smp_processor_id()) && task_curr(p))
3472 smp_send_reschedule(cpu);
3475 EXPORT_SYMBOL_GPL(kick_process);
3478 * ->cpus_ptr is protected by both rq->lock and p->pi_lock
3480 * A few notes on cpu_active vs cpu_online:
3482 * - cpu_active must be a subset of cpu_online
3484 * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
3485 * see __set_cpus_allowed_ptr(). At this point the newly online
3486 * CPU isn't yet part of the sched domains, and balancing will not
3489 * - on CPU-down we clear cpu_active() to mask the sched domains and
3490 * avoid the load balancer to place new tasks on the to be removed
3491 * CPU. Existing tasks will remain running there and will be taken
3494 * This means that fallback selection must not select !active CPUs.
3495 * And can assume that any active CPU must be online. Conversely
3496 * select_task_rq() below may allow selection of !active CPUs in order
3497 * to satisfy the above rules.
3499 static int select_fallback_rq(int cpu, struct task_struct *p)
3501 int nid = cpu_to_node(cpu);
3502 const struct cpumask *nodemask = NULL;
3503 enum { cpuset, possible, fail } state = cpuset;
3507 * If the node that the CPU is on has been offlined, cpu_to_node()
3508 * will return -1. There is no CPU on the node, and we should
3509 * select the CPU on the other node.
3512 nodemask = cpumask_of_node(nid);
3514 /* Look for allowed, online CPU in same node. */
3515 for_each_cpu(dest_cpu, nodemask) {
3516 if (is_cpu_allowed(p, dest_cpu))
3522 /* Any allowed, online CPU? */
3523 for_each_cpu(dest_cpu, p->cpus_ptr) {
3524 if (!is_cpu_allowed(p, dest_cpu))
3530 /* No more Mr. Nice Guy. */
3533 if (cpuset_cpus_allowed_fallback(p)) {
3540 * XXX When called from select_task_rq() we only
3541 * hold p->pi_lock and again violate locking order.
3543 * More yuck to audit.
3545 do_set_cpus_allowed(p, task_cpu_possible_mask(p));
3555 if (state != cpuset) {
3557 * Don't tell them about moving exiting tasks or
3558 * kernel threads (both mm NULL), since they never
3561 if (p->mm && printk_ratelimit()) {
3562 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
3563 task_pid_nr(p), p->comm, cpu);
3571 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
3574 int select_task_rq(struct task_struct *p, int cpu, int wake_flags)
3576 lockdep_assert_held(&p->pi_lock);
3578 if (p->nr_cpus_allowed > 1 && !is_migration_disabled(p))
3579 cpu = p->sched_class->select_task_rq(p, cpu, wake_flags);
3581 cpu = cpumask_any(p->cpus_ptr);
3584 * In order not to call set_task_cpu() on a blocking task we need
3585 * to rely on ttwu() to place the task on a valid ->cpus_ptr
3588 * Since this is common to all placement strategies, this lives here.
3590 * [ this allows ->select_task() to simply return task_cpu(p) and
3591 * not worry about this generic constraint ]
3593 if (unlikely(!is_cpu_allowed(p, cpu)))
3594 cpu = select_fallback_rq(task_cpu(p), p);
3599 void sched_set_stop_task(int cpu, struct task_struct *stop)
3601 static struct lock_class_key stop_pi_lock;
3602 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
3603 struct task_struct *old_stop = cpu_rq(cpu)->stop;
3607 * Make it appear like a SCHED_FIFO task, its something
3608 * userspace knows about and won't get confused about.
3610 * Also, it will make PI more or less work without too
3611 * much confusion -- but then, stop work should not
3612 * rely on PI working anyway.
3614 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
3616 stop->sched_class = &stop_sched_class;
3619 * The PI code calls rt_mutex_setprio() with ->pi_lock held to
3620 * adjust the effective priority of a task. As a result,
3621 * rt_mutex_setprio() can trigger (RT) balancing operations,
3622 * which can then trigger wakeups of the stop thread to push
3623 * around the current task.
3625 * The stop task itself will never be part of the PI-chain, it
3626 * never blocks, therefore that ->pi_lock recursion is safe.
3627 * Tell lockdep about this by placing the stop->pi_lock in its
3630 lockdep_set_class(&stop->pi_lock, &stop_pi_lock);
3633 cpu_rq(cpu)->stop = stop;
3637 * Reset it back to a normal scheduling class so that
3638 * it can die in pieces.
3640 old_stop->sched_class = &rt_sched_class;
3644 #else /* CONFIG_SMP */
3646 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
3647 struct affinity_context *ctx)
3649 return set_cpus_allowed_ptr(p, ctx->new_mask);
3652 static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { }
3654 static inline bool rq_has_pinned_tasks(struct rq *rq)
3659 static inline cpumask_t *alloc_user_cpus_ptr(int node)
3664 #endif /* !CONFIG_SMP */
3667 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
3671 if (!schedstat_enabled())
3677 if (cpu == rq->cpu) {
3678 __schedstat_inc(rq->ttwu_local);
3679 __schedstat_inc(p->stats.nr_wakeups_local);
3681 struct sched_domain *sd;
3683 __schedstat_inc(p->stats.nr_wakeups_remote);
3685 for_each_domain(rq->cpu, sd) {
3686 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
3687 __schedstat_inc(sd->ttwu_wake_remote);
3694 if (wake_flags & WF_MIGRATED)
3695 __schedstat_inc(p->stats.nr_wakeups_migrate);
3696 #endif /* CONFIG_SMP */
3698 __schedstat_inc(rq->ttwu_count);
3699 __schedstat_inc(p->stats.nr_wakeups);
3701 if (wake_flags & WF_SYNC)
3702 __schedstat_inc(p->stats.nr_wakeups_sync);
3706 * Mark the task runnable.
3708 static inline void ttwu_do_wakeup(struct task_struct *p)
3710 WRITE_ONCE(p->__state, TASK_RUNNING);
3711 trace_sched_wakeup(p);
3715 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
3716 struct rq_flags *rf)
3718 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
3720 lockdep_assert_rq_held(rq);
3722 if (p->sched_contributes_to_load)
3723 rq->nr_uninterruptible--;
3726 if (wake_flags & WF_MIGRATED)
3727 en_flags |= ENQUEUE_MIGRATED;
3731 delayacct_blkio_end(p);
3732 atomic_dec(&task_rq(p)->nr_iowait);
3735 activate_task(rq, p, en_flags);
3736 check_preempt_curr(rq, p, wake_flags);
3741 if (p->sched_class->task_woken) {
3743 * Our task @p is fully woken up and running; so it's safe to
3744 * drop the rq->lock, hereafter rq is only used for statistics.
3746 rq_unpin_lock(rq, rf);
3747 p->sched_class->task_woken(rq, p);
3748 rq_repin_lock(rq, rf);
3751 if (rq->idle_stamp) {
3752 u64 delta = rq_clock(rq) - rq->idle_stamp;
3753 u64 max = 2*rq->max_idle_balance_cost;
3755 update_avg(&rq->avg_idle, delta);
3757 if (rq->avg_idle > max)
3760 rq->wake_stamp = jiffies;
3761 rq->wake_avg_idle = rq->avg_idle / 2;
3769 * Consider @p being inside a wait loop:
3772 * set_current_state(TASK_UNINTERRUPTIBLE);
3779 * __set_current_state(TASK_RUNNING);
3781 * between set_current_state() and schedule(). In this case @p is still
3782 * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
3785 * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
3786 * then schedule() must still happen and p->state can be changed to
3787 * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
3788 * need to do a full wakeup with enqueue.
3790 * Returns: %true when the wakeup is done,
3793 static int ttwu_runnable(struct task_struct *p, int wake_flags)
3799 rq = __task_rq_lock(p, &rf);
3800 if (task_on_rq_queued(p)) {
3801 if (!task_on_cpu(rq, p)) {
3803 * When on_rq && !on_cpu the task is preempted, see if
3804 * it should preempt the task that is current now.
3806 update_rq_clock(rq);
3807 check_preempt_curr(rq, p, wake_flags);
3812 __task_rq_unlock(rq, &rf);
3818 void sched_ttwu_pending(void *arg)
3820 struct llist_node *llist = arg;
3821 struct rq *rq = this_rq();
3822 struct task_struct *p, *t;
3828 rq_lock_irqsave(rq, &rf);
3829 update_rq_clock(rq);
3831 llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
3832 if (WARN_ON_ONCE(p->on_cpu))
3833 smp_cond_load_acquire(&p->on_cpu, !VAL);
3835 if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
3836 set_task_cpu(p, cpu_of(rq));
3838 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
3842 * Must be after enqueueing at least once task such that
3843 * idle_cpu() does not observe a false-negative -- if it does,
3844 * it is possible for select_idle_siblings() to stack a number
3845 * of tasks on this CPU during that window.
3847 * It is ok to clear ttwu_pending when another task pending.
3848 * We will receive IPI after local irq enabled and then enqueue it.
3849 * Since now nr_running > 0, idle_cpu() will always get correct result.
3851 WRITE_ONCE(rq->ttwu_pending, 0);
3852 rq_unlock_irqrestore(rq, &rf);
3856 * Prepare the scene for sending an IPI for a remote smp_call
3858 * Returns true if the caller can proceed with sending the IPI.
3859 * Returns false otherwise.
3861 bool call_function_single_prep_ipi(int cpu)
3863 if (set_nr_if_polling(cpu_rq(cpu)->idle)) {
3864 trace_sched_wake_idle_without_ipi(cpu);
3872 * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
3873 * necessary. The wakee CPU on receipt of the IPI will queue the task
3874 * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
3875 * of the wakeup instead of the waker.
3877 static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3879 struct rq *rq = cpu_rq(cpu);
3881 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
3883 WRITE_ONCE(rq->ttwu_pending, 1);
3884 __smp_call_single_queue(cpu, &p->wake_entry.llist);
3887 void wake_up_if_idle(int cpu)
3889 struct rq *rq = cpu_rq(cpu);
3894 if (!is_idle_task(rcu_dereference(rq->curr)))
3897 rq_lock_irqsave(rq, &rf);
3898 if (is_idle_task(rq->curr))
3900 /* Else CPU is not idle, do nothing here: */
3901 rq_unlock_irqrestore(rq, &rf);
3907 bool cpus_share_cache(int this_cpu, int that_cpu)
3909 if (this_cpu == that_cpu)
3912 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
3915 static inline bool ttwu_queue_cond(struct task_struct *p, int cpu)
3918 * Do not complicate things with the async wake_list while the CPU is
3921 if (!cpu_active(cpu))
3924 /* Ensure the task will still be allowed to run on the CPU. */
3925 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
3929 * If the CPU does not share cache, then queue the task on the
3930 * remote rqs wakelist to avoid accessing remote data.
3932 if (!cpus_share_cache(smp_processor_id(), cpu))
3935 if (cpu == smp_processor_id())
3939 * If the wakee cpu is idle, or the task is descheduling and the
3940 * only running task on the CPU, then use the wakelist to offload
3941 * the task activation to the idle (or soon-to-be-idle) CPU as
3942 * the current CPU is likely busy. nr_running is checked to
3943 * avoid unnecessary task stacking.
3945 * Note that we can only get here with (wakee) p->on_rq=0,
3946 * p->on_cpu can be whatever, we've done the dequeue, so
3947 * the wakee has been accounted out of ->nr_running.
3949 if (!cpu_rq(cpu)->nr_running)
3955 static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3957 if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(p, cpu)) {
3958 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
3959 __ttwu_queue_wakelist(p, cpu, wake_flags);
3966 #else /* !CONFIG_SMP */
3968 static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3973 #endif /* CONFIG_SMP */
3975 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
3977 struct rq *rq = cpu_rq(cpu);
3980 if (ttwu_queue_wakelist(p, cpu, wake_flags))
3984 update_rq_clock(rq);
3985 ttwu_do_activate(rq, p, wake_flags, &rf);
3990 * Invoked from try_to_wake_up() to check whether the task can be woken up.
3992 * The caller holds p::pi_lock if p != current or has preemption
3993 * disabled when p == current.
3995 * The rules of PREEMPT_RT saved_state:
3997 * The related locking code always holds p::pi_lock when updating
3998 * p::saved_state, which means the code is fully serialized in both cases.
4000 * The lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. No other
4001 * bits set. This allows to distinguish all wakeup scenarios.
4003 static __always_inline
4004 bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success)
4006 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
4007 WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) &&
4008 state != TASK_RTLOCK_WAIT);
4011 if (READ_ONCE(p->__state) & state) {
4016 #ifdef CONFIG_PREEMPT_RT
4018 * Saved state preserves the task state across blocking on
4019 * an RT lock. If the state matches, set p::saved_state to
4020 * TASK_RUNNING, but do not wake the task because it waits
4021 * for a lock wakeup. Also indicate success because from
4022 * the regular waker's point of view this has succeeded.
4024 * After acquiring the lock the task will restore p::__state
4025 * from p::saved_state which ensures that the regular
4026 * wakeup is not lost. The restore will also set
4027 * p::saved_state to TASK_RUNNING so any further tests will
4028 * not result in false positives vs. @success
4030 if (p->saved_state & state) {
4031 p->saved_state = TASK_RUNNING;
4039 * Notes on Program-Order guarantees on SMP systems.
4043 * The basic program-order guarantee on SMP systems is that when a task [t]
4044 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
4045 * execution on its new CPU [c1].
4047 * For migration (of runnable tasks) this is provided by the following means:
4049 * A) UNLOCK of the rq(c0)->lock scheduling out task t
4050 * B) migration for t is required to synchronize *both* rq(c0)->lock and
4051 * rq(c1)->lock (if not at the same time, then in that order).
4052 * C) LOCK of the rq(c1)->lock scheduling in task
4054 * Release/acquire chaining guarantees that B happens after A and C after B.
4055 * Note: the CPU doing B need not be c0 or c1
4064 * UNLOCK rq(0)->lock
4066 * LOCK rq(0)->lock // orders against CPU0
4068 * UNLOCK rq(0)->lock
4072 * UNLOCK rq(1)->lock
4074 * LOCK rq(1)->lock // orders against CPU2
4077 * UNLOCK rq(1)->lock
4080 * BLOCKING -- aka. SLEEP + WAKEUP
4082 * For blocking we (obviously) need to provide the same guarantee as for
4083 * migration. However the means are completely different as there is no lock
4084 * chain to provide order. Instead we do:
4086 * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
4087 * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
4091 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
4093 * LOCK rq(0)->lock LOCK X->pi_lock
4096 * smp_store_release(X->on_cpu, 0);
4098 * smp_cond_load_acquire(&X->on_cpu, !VAL);
4104 * X->state = RUNNING
4105 * UNLOCK rq(2)->lock
4107 * LOCK rq(2)->lock // orders against CPU1
4110 * UNLOCK rq(2)->lock
4113 * UNLOCK rq(0)->lock
4116 * However, for wakeups there is a second guarantee we must provide, namely we
4117 * must ensure that CONDITION=1 done by the caller can not be reordered with
4118 * accesses to the task state; see try_to_wake_up() and set_current_state().
4122 * try_to_wake_up - wake up a thread
4123 * @p: the thread to be awakened
4124 * @state: the mask of task states that can be woken
4125 * @wake_flags: wake modifier flags (WF_*)
4127 * Conceptually does:
4129 * If (@state & @p->state) @p->state = TASK_RUNNING.
4131 * If the task was not queued/runnable, also place it back on a runqueue.
4133 * This function is atomic against schedule() which would dequeue the task.
4135 * It issues a full memory barrier before accessing @p->state, see the comment
4136 * with set_current_state().
4138 * Uses p->pi_lock to serialize against concurrent wake-ups.
4140 * Relies on p->pi_lock stabilizing:
4143 * - p->sched_task_group
4144 * in order to do migration, see its use of select_task_rq()/set_task_cpu().
4146 * Tries really hard to only take one task_rq(p)->lock for performance.
4147 * Takes rq->lock in:
4148 * - ttwu_runnable() -- old rq, unavoidable, see comment there;
4149 * - ttwu_queue() -- new rq, for enqueue of the task;
4150 * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
4152 * As a consequence we race really badly with just about everything. See the
4153 * many memory barriers and their comments for details.
4155 * Return: %true if @p->state changes (an actual wakeup was done),
4159 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
4161 unsigned long flags;
4162 int cpu, success = 0;
4167 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
4168 * == smp_processor_id()'. Together this means we can special
4169 * case the whole 'p->on_rq && ttwu_runnable()' case below
4170 * without taking any locks.
4173 * - we rely on Program-Order guarantees for all the ordering,
4174 * - we're serialized against set_special_state() by virtue of
4175 * it disabling IRQs (this allows not taking ->pi_lock).
4177 if (!ttwu_state_match(p, state, &success))
4180 trace_sched_waking(p);
4186 * If we are going to wake up a thread waiting for CONDITION we
4187 * need to ensure that CONDITION=1 done by the caller can not be
4188 * reordered with p->state check below. This pairs with smp_store_mb()
4189 * in set_current_state() that the waiting thread does.
4191 raw_spin_lock_irqsave(&p->pi_lock, flags);
4192 smp_mb__after_spinlock();
4193 if (!ttwu_state_match(p, state, &success))
4196 trace_sched_waking(p);
4199 * Ensure we load p->on_rq _after_ p->state, otherwise it would
4200 * be possible to, falsely, observe p->on_rq == 0 and get stuck
4201 * in smp_cond_load_acquire() below.
4203 * sched_ttwu_pending() try_to_wake_up()
4204 * STORE p->on_rq = 1 LOAD p->state
4207 * __schedule() (switch to task 'p')
4208 * LOCK rq->lock smp_rmb();
4209 * smp_mb__after_spinlock();
4213 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
4215 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4216 * __schedule(). See the comment for smp_mb__after_spinlock().
4218 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
4221 if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
4226 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
4227 * possible to, falsely, observe p->on_cpu == 0.
4229 * One must be running (->on_cpu == 1) in order to remove oneself
4230 * from the runqueue.
4232 * __schedule() (switch to task 'p') try_to_wake_up()
4233 * STORE p->on_cpu = 1 LOAD p->on_rq
4236 * __schedule() (put 'p' to sleep)
4237 * LOCK rq->lock smp_rmb();
4238 * smp_mb__after_spinlock();
4239 * STORE p->on_rq = 0 LOAD p->on_cpu
4241 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
4242 * __schedule(). See the comment for smp_mb__after_spinlock().
4244 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
4245 * schedule()'s deactivate_task() has 'happened' and p will no longer
4246 * care about it's own p->state. See the comment in __schedule().
4248 smp_acquire__after_ctrl_dep();
4251 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
4252 * == 0), which means we need to do an enqueue, change p->state to
4253 * TASK_WAKING such that we can unlock p->pi_lock before doing the
4254 * enqueue, such as ttwu_queue_wakelist().
4256 WRITE_ONCE(p->__state, TASK_WAKING);
4259 * If the owning (remote) CPU is still in the middle of schedule() with
4260 * this task as prev, considering queueing p on the remote CPUs wake_list
4261 * which potentially sends an IPI instead of spinning on p->on_cpu to
4262 * let the waker make forward progress. This is safe because IRQs are
4263 * disabled and the IPI will deliver after on_cpu is cleared.
4265 * Ensure we load task_cpu(p) after p->on_cpu:
4267 * set_task_cpu(p, cpu);
4268 * STORE p->cpu = @cpu
4269 * __schedule() (switch to task 'p')
4271 * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
4272 * STORE p->on_cpu = 1 LOAD p->cpu
4274 * to ensure we observe the correct CPU on which the task is currently
4277 if (smp_load_acquire(&p->on_cpu) &&
4278 ttwu_queue_wakelist(p, task_cpu(p), wake_flags))
4282 * If the owning (remote) CPU is still in the middle of schedule() with
4283 * this task as prev, wait until it's done referencing the task.
4285 * Pairs with the smp_store_release() in finish_task().
4287 * This ensures that tasks getting woken will be fully ordered against
4288 * their previous state and preserve Program Order.
4290 smp_cond_load_acquire(&p->on_cpu, !VAL);
4292 cpu = select_task_rq(p, p->wake_cpu, wake_flags | WF_TTWU);
4293 if (task_cpu(p) != cpu) {
4295 delayacct_blkio_end(p);
4296 atomic_dec(&task_rq(p)->nr_iowait);
4299 wake_flags |= WF_MIGRATED;
4300 psi_ttwu_dequeue(p);
4301 set_task_cpu(p, cpu);
4305 #endif /* CONFIG_SMP */
4307 ttwu_queue(p, cpu, wake_flags);
4309 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4312 ttwu_stat(p, task_cpu(p), wake_flags);
4318 static bool __task_needs_rq_lock(struct task_struct *p)
4320 unsigned int state = READ_ONCE(p->__state);
4323 * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when
4324 * the task is blocked. Make sure to check @state since ttwu() can drop
4325 * locks at the end, see ttwu_queue_wakelist().
4327 if (state == TASK_RUNNING || state == TASK_WAKING)
4331 * Ensure we load p->on_rq after p->__state, otherwise it would be
4332 * possible to, falsely, observe p->on_rq == 0.
4334 * See try_to_wake_up() for a longer comment.
4342 * Ensure the task has finished __schedule() and will not be referenced
4343 * anymore. Again, see try_to_wake_up() for a longer comment.
4346 smp_cond_load_acquire(&p->on_cpu, !VAL);
4353 * task_call_func - Invoke a function on task in fixed state
4354 * @p: Process for which the function is to be invoked, can be @current.
4355 * @func: Function to invoke.
4356 * @arg: Argument to function.
4358 * Fix the task in it's current state by avoiding wakeups and or rq operations
4359 * and call @func(@arg) on it. This function can use ->on_rq and task_curr()
4360 * to work out what the state is, if required. Given that @func can be invoked
4361 * with a runqueue lock held, it had better be quite lightweight.
4364 * Whatever @func returns
4366 int task_call_func(struct task_struct *p, task_call_f func, void *arg)
4368 struct rq *rq = NULL;
4372 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
4374 if (__task_needs_rq_lock(p))
4375 rq = __task_rq_lock(p, &rf);
4378 * At this point the task is pinned; either:
4379 * - blocked and we're holding off wakeups (pi->lock)
4380 * - woken, and we're holding off enqueue (rq->lock)
4381 * - queued, and we're holding off schedule (rq->lock)
4382 * - running, and we're holding off de-schedule (rq->lock)
4384 * The called function (@func) can use: task_curr(), p->on_rq and
4385 * p->__state to differentiate between these states.
4392 raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
4397 * cpu_curr_snapshot - Return a snapshot of the currently running task
4398 * @cpu: The CPU on which to snapshot the task.
4400 * Returns the task_struct pointer of the task "currently" running on
4401 * the specified CPU. If the same task is running on that CPU throughout,
4402 * the return value will be a pointer to that task's task_struct structure.
4403 * If the CPU did any context switches even vaguely concurrently with the
4404 * execution of this function, the return value will be a pointer to the
4405 * task_struct structure of a randomly chosen task that was running on
4406 * that CPU somewhere around the time that this function was executing.
4408 * If the specified CPU was offline, the return value is whatever it
4409 * is, perhaps a pointer to the task_struct structure of that CPU's idle
4410 * task, but there is no guarantee. Callers wishing a useful return
4411 * value must take some action to ensure that the specified CPU remains
4412 * online throughout.
4414 * This function executes full memory barriers before and after fetching
4415 * the pointer, which permits the caller to confine this function's fetch
4416 * with respect to the caller's accesses to other shared variables.
4418 struct task_struct *cpu_curr_snapshot(int cpu)
4420 struct task_struct *t;
4422 smp_mb(); /* Pairing determined by caller's synchronization design. */
4423 t = rcu_dereference(cpu_curr(cpu));
4424 smp_mb(); /* Pairing determined by caller's synchronization design. */
4429 * wake_up_process - Wake up a specific process
4430 * @p: The process to be woken up.
4432 * Attempt to wake up the nominated process and move it to the set of runnable
4435 * Return: 1 if the process was woken up, 0 if it was already running.
4437 * This function executes a full memory barrier before accessing the task state.
4439 int wake_up_process(struct task_struct *p)
4441 return try_to_wake_up(p, TASK_NORMAL, 0);
4443 EXPORT_SYMBOL(wake_up_process);
4445 int wake_up_state(struct task_struct *p, unsigned int state)
4447 return try_to_wake_up(p, state, 0);
4451 * Perform scheduler related setup for a newly forked process p.
4452 * p is forked by current.
4454 * __sched_fork() is basic setup used by init_idle() too:
4456 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
4461 p->se.exec_start = 0;
4462 p->se.sum_exec_runtime = 0;
4463 p->se.prev_sum_exec_runtime = 0;
4464 p->se.nr_migrations = 0;
4466 INIT_LIST_HEAD(&p->se.group_node);
4468 #ifdef CONFIG_FAIR_GROUP_SCHED
4469 p->se.cfs_rq = NULL;
4472 #ifdef CONFIG_SCHEDSTATS
4473 /* Even if schedstat is disabled, there should not be garbage */
4474 memset(&p->stats, 0, sizeof(p->stats));
4477 RB_CLEAR_NODE(&p->dl.rb_node);
4478 init_dl_task_timer(&p->dl);
4479 init_dl_inactive_task_timer(&p->dl);
4480 __dl_clear_params(p);
4482 INIT_LIST_HEAD(&p->rt.run_list);
4484 p->rt.time_slice = sched_rr_timeslice;
4488 #ifdef CONFIG_PREEMPT_NOTIFIERS
4489 INIT_HLIST_HEAD(&p->preempt_notifiers);
4492 #ifdef CONFIG_COMPACTION
4493 p->capture_control = NULL;
4495 init_numa_balancing(clone_flags, p);
4497 p->wake_entry.u_flags = CSD_TYPE_TTWU;
4498 p->migration_pending = NULL;
4500 init_sched_mm_cid(p);
4503 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
4505 #ifdef CONFIG_NUMA_BALANCING
4507 int sysctl_numa_balancing_mode;
4509 static void __set_numabalancing_state(bool enabled)
4512 static_branch_enable(&sched_numa_balancing);
4514 static_branch_disable(&sched_numa_balancing);
4517 void set_numabalancing_state(bool enabled)
4520 sysctl_numa_balancing_mode = NUMA_BALANCING_NORMAL;
4522 sysctl_numa_balancing_mode = NUMA_BALANCING_DISABLED;
4523 __set_numabalancing_state(enabled);
4526 #ifdef CONFIG_PROC_SYSCTL
4527 static void reset_memory_tiering(void)
4529 struct pglist_data *pgdat;
4531 for_each_online_pgdat(pgdat) {
4532 pgdat->nbp_threshold = 0;
4533 pgdat->nbp_th_nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
4534 pgdat->nbp_th_start = jiffies_to_msecs(jiffies);
4538 static int sysctl_numa_balancing(struct ctl_table *table, int write,
4539 void *buffer, size_t *lenp, loff_t *ppos)
4543 int state = sysctl_numa_balancing_mode;
4545 if (write && !capable(CAP_SYS_ADMIN))
4550 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4554 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
4555 (state & NUMA_BALANCING_MEMORY_TIERING))
4556 reset_memory_tiering();
4557 sysctl_numa_balancing_mode = state;
4558 __set_numabalancing_state(state);
4565 #ifdef CONFIG_SCHEDSTATS
4567 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
4569 static void set_schedstats(bool enabled)
4572 static_branch_enable(&sched_schedstats);
4574 static_branch_disable(&sched_schedstats);
4577 void force_schedstat_enabled(void)
4579 if (!schedstat_enabled()) {
4580 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
4581 static_branch_enable(&sched_schedstats);
4585 static int __init setup_schedstats(char *str)
4591 if (!strcmp(str, "enable")) {
4592 set_schedstats(true);
4594 } else if (!strcmp(str, "disable")) {
4595 set_schedstats(false);
4600 pr_warn("Unable to parse schedstats=\n");
4604 __setup("schedstats=", setup_schedstats);
4606 #ifdef CONFIG_PROC_SYSCTL
4607 static int sysctl_schedstats(struct ctl_table *table, int write, void *buffer,
4608 size_t *lenp, loff_t *ppos)
4612 int state = static_branch_likely(&sched_schedstats);
4614 if (write && !capable(CAP_SYS_ADMIN))
4619 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4623 set_schedstats(state);
4626 #endif /* CONFIG_PROC_SYSCTL */
4627 #endif /* CONFIG_SCHEDSTATS */
4629 #ifdef CONFIG_SYSCTL
4630 static struct ctl_table sched_core_sysctls[] = {
4631 #ifdef CONFIG_SCHEDSTATS
4633 .procname = "sched_schedstats",
4635 .maxlen = sizeof(unsigned int),
4637 .proc_handler = sysctl_schedstats,
4638 .extra1 = SYSCTL_ZERO,
4639 .extra2 = SYSCTL_ONE,
4641 #endif /* CONFIG_SCHEDSTATS */
4642 #ifdef CONFIG_UCLAMP_TASK
4644 .procname = "sched_util_clamp_min",
4645 .data = &sysctl_sched_uclamp_util_min,
4646 .maxlen = sizeof(unsigned int),
4648 .proc_handler = sysctl_sched_uclamp_handler,
4651 .procname = "sched_util_clamp_max",
4652 .data = &sysctl_sched_uclamp_util_max,
4653 .maxlen = sizeof(unsigned int),
4655 .proc_handler = sysctl_sched_uclamp_handler,
4658 .procname = "sched_util_clamp_min_rt_default",
4659 .data = &sysctl_sched_uclamp_util_min_rt_default,
4660 .maxlen = sizeof(unsigned int),
4662 .proc_handler = sysctl_sched_uclamp_handler,
4664 #endif /* CONFIG_UCLAMP_TASK */
4665 #ifdef CONFIG_NUMA_BALANCING
4667 .procname = "numa_balancing",
4668 .data = NULL, /* filled in by handler */
4669 .maxlen = sizeof(unsigned int),
4671 .proc_handler = sysctl_numa_balancing,
4672 .extra1 = SYSCTL_ZERO,
4673 .extra2 = SYSCTL_FOUR,
4675 #endif /* CONFIG_NUMA_BALANCING */
4678 static int __init sched_core_sysctl_init(void)
4680 register_sysctl_init("kernel", sched_core_sysctls);
4683 late_initcall(sched_core_sysctl_init);
4684 #endif /* CONFIG_SYSCTL */
4687 * fork()/clone()-time setup:
4689 int sched_fork(unsigned long clone_flags, struct task_struct *p)
4691 __sched_fork(clone_flags, p);
4693 * We mark the process as NEW here. This guarantees that
4694 * nobody will actually run it, and a signal or other external
4695 * event cannot wake it up and insert it on the runqueue either.
4697 p->__state = TASK_NEW;
4700 * Make sure we do not leak PI boosting priority to the child.
4702 p->prio = current->normal_prio;
4707 * Revert to default priority/policy on fork if requested.
4709 if (unlikely(p->sched_reset_on_fork)) {
4710 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
4711 p->policy = SCHED_NORMAL;
4712 p->static_prio = NICE_TO_PRIO(0);
4714 } else if (PRIO_TO_NICE(p->static_prio) < 0)
4715 p->static_prio = NICE_TO_PRIO(0);
4717 p->prio = p->normal_prio = p->static_prio;
4718 set_load_weight(p, false);
4721 * We don't need the reset flag anymore after the fork. It has
4722 * fulfilled its duty:
4724 p->sched_reset_on_fork = 0;
4727 if (dl_prio(p->prio))
4729 else if (rt_prio(p->prio))
4730 p->sched_class = &rt_sched_class;
4732 p->sched_class = &fair_sched_class;
4734 init_entity_runnable_average(&p->se);
4737 #ifdef CONFIG_SCHED_INFO
4738 if (likely(sched_info_on()))
4739 memset(&p->sched_info, 0, sizeof(p->sched_info));
4741 #if defined(CONFIG_SMP)
4744 init_task_preempt_count(p);
4746 plist_node_init(&p->pushable_tasks, MAX_PRIO);
4747 RB_CLEAR_NODE(&p->pushable_dl_tasks);
4752 void sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs)
4754 unsigned long flags;
4757 * Because we're not yet on the pid-hash, p->pi_lock isn't strictly
4758 * required yet, but lockdep gets upset if rules are violated.
4760 raw_spin_lock_irqsave(&p->pi_lock, flags);
4761 #ifdef CONFIG_CGROUP_SCHED
4763 struct task_group *tg;
4764 tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
4765 struct task_group, css);
4766 tg = autogroup_task_group(p, tg);
4767 p->sched_task_group = tg;
4772 * We're setting the CPU for the first time, we don't migrate,
4773 * so use __set_task_cpu().
4775 __set_task_cpu(p, smp_processor_id());
4776 if (p->sched_class->task_fork)
4777 p->sched_class->task_fork(p);
4778 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4781 void sched_post_fork(struct task_struct *p)
4783 uclamp_post_fork(p);
4786 unsigned long to_ratio(u64 period, u64 runtime)
4788 if (runtime == RUNTIME_INF)
4792 * Doing this here saves a lot of checks in all
4793 * the calling paths, and returning zero seems
4794 * safe for them anyway.
4799 return div64_u64(runtime << BW_SHIFT, period);
4803 * wake_up_new_task - wake up a newly created task for the first time.
4805 * This function will do some initial scheduler statistics housekeeping
4806 * that must be done for every newly created context, then puts the task
4807 * on the runqueue and wakes it.
4809 void wake_up_new_task(struct task_struct *p)
4814 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
4815 WRITE_ONCE(p->__state, TASK_RUNNING);
4818 * Fork balancing, do it here and not earlier because:
4819 * - cpus_ptr can change in the fork path
4820 * - any previously selected CPU might disappear through hotplug
4822 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
4823 * as we're not fully set-up yet.
4825 p->recent_used_cpu = task_cpu(p);
4827 __set_task_cpu(p, select_task_rq(p, task_cpu(p), WF_FORK));
4829 rq = __task_rq_lock(p, &rf);
4830 update_rq_clock(rq);
4831 post_init_entity_util_avg(p);
4833 activate_task(rq, p, ENQUEUE_NOCLOCK);
4834 trace_sched_wakeup_new(p);
4835 check_preempt_curr(rq, p, WF_FORK);
4837 if (p->sched_class->task_woken) {
4839 * Nothing relies on rq->lock after this, so it's fine to
4842 rq_unpin_lock(rq, &rf);
4843 p->sched_class->task_woken(rq, p);
4844 rq_repin_lock(rq, &rf);
4847 task_rq_unlock(rq, p, &rf);
4850 #ifdef CONFIG_PREEMPT_NOTIFIERS
4852 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
4854 void preempt_notifier_inc(void)
4856 static_branch_inc(&preempt_notifier_key);
4858 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
4860 void preempt_notifier_dec(void)
4862 static_branch_dec(&preempt_notifier_key);
4864 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
4867 * preempt_notifier_register - tell me when current is being preempted & rescheduled
4868 * @notifier: notifier struct to register
4870 void preempt_notifier_register(struct preempt_notifier *notifier)
4872 if (!static_branch_unlikely(&preempt_notifier_key))
4873 WARN(1, "registering preempt_notifier while notifiers disabled\n");
4875 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
4877 EXPORT_SYMBOL_GPL(preempt_notifier_register);
4880 * preempt_notifier_unregister - no longer interested in preemption notifications
4881 * @notifier: notifier struct to unregister
4883 * This is *not* safe to call from within a preemption notifier.
4885 void preempt_notifier_unregister(struct preempt_notifier *notifier)
4887 hlist_del(¬ifier->link);
4889 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
4891 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
4893 struct preempt_notifier *notifier;
4895 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
4896 notifier->ops->sched_in(notifier, raw_smp_processor_id());
4899 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
4901 if (static_branch_unlikely(&preempt_notifier_key))
4902 __fire_sched_in_preempt_notifiers(curr);
4906 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
4907 struct task_struct *next)
4909 struct preempt_notifier *notifier;
4911 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
4912 notifier->ops->sched_out(notifier, next);
4915 static __always_inline void
4916 fire_sched_out_preempt_notifiers(struct task_struct *curr,
4917 struct task_struct *next)
4919 if (static_branch_unlikely(&preempt_notifier_key))
4920 __fire_sched_out_preempt_notifiers(curr, next);
4923 #else /* !CONFIG_PREEMPT_NOTIFIERS */
4925 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
4930 fire_sched_out_preempt_notifiers(struct task_struct *curr,
4931 struct task_struct *next)
4935 #endif /* CONFIG_PREEMPT_NOTIFIERS */
4937 static inline void prepare_task(struct task_struct *next)
4941 * Claim the task as running, we do this before switching to it
4942 * such that any running task will have this set.
4944 * See the smp_load_acquire(&p->on_cpu) case in ttwu() and
4945 * its ordering comment.
4947 WRITE_ONCE(next->on_cpu, 1);
4951 static inline void finish_task(struct task_struct *prev)
4955 * This must be the very last reference to @prev from this CPU. After
4956 * p->on_cpu is cleared, the task can be moved to a different CPU. We
4957 * must ensure this doesn't happen until the switch is completely
4960 * In particular, the load of prev->state in finish_task_switch() must
4961 * happen before this.
4963 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
4965 smp_store_release(&prev->on_cpu, 0);
4971 static void do_balance_callbacks(struct rq *rq, struct balance_callback *head)
4973 void (*func)(struct rq *rq);
4974 struct balance_callback *next;
4976 lockdep_assert_rq_held(rq);
4979 func = (void (*)(struct rq *))head->func;
4988 static void balance_push(struct rq *rq);
4991 * balance_push_callback is a right abuse of the callback interface and plays
4992 * by significantly different rules.
4994 * Where the normal balance_callback's purpose is to be ran in the same context
4995 * that queued it (only later, when it's safe to drop rq->lock again),
4996 * balance_push_callback is specifically targeted at __schedule().
4998 * This abuse is tolerated because it places all the unlikely/odd cases behind
4999 * a single test, namely: rq->balance_callback == NULL.
5001 struct balance_callback balance_push_callback = {
5003 .func = balance_push,
5006 static inline struct balance_callback *
5007 __splice_balance_callbacks(struct rq *rq, bool split)
5009 struct balance_callback *head = rq->balance_callback;
5014 lockdep_assert_rq_held(rq);
5016 * Must not take balance_push_callback off the list when
5017 * splice_balance_callbacks() and balance_callbacks() are not
5018 * in the same rq->lock section.
5020 * In that case it would be possible for __schedule() to interleave
5021 * and observe the list empty.
5023 if (split && head == &balance_push_callback)
5026 rq->balance_callback = NULL;
5031 static inline struct balance_callback *splice_balance_callbacks(struct rq *rq)
5033 return __splice_balance_callbacks(rq, true);
5036 static void __balance_callbacks(struct rq *rq)
5038 do_balance_callbacks(rq, __splice_balance_callbacks(rq, false));
5041 static inline void balance_callbacks(struct rq *rq, struct balance_callback *head)
5043 unsigned long flags;
5045 if (unlikely(head)) {
5046 raw_spin_rq_lock_irqsave(rq, flags);
5047 do_balance_callbacks(rq, head);
5048 raw_spin_rq_unlock_irqrestore(rq, flags);
5054 static inline void __balance_callbacks(struct rq *rq)
5058 static inline struct balance_callback *splice_balance_callbacks(struct rq *rq)
5063 static inline void balance_callbacks(struct rq *rq, struct balance_callback *head)
5070 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
5073 * Since the runqueue lock will be released by the next
5074 * task (which is an invalid locking op but in the case
5075 * of the scheduler it's an obvious special-case), so we
5076 * do an early lockdep release here:
5078 rq_unpin_lock(rq, rf);
5079 spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_);
5080 #ifdef CONFIG_DEBUG_SPINLOCK
5081 /* this is a valid case when another task releases the spinlock */
5082 rq_lockp(rq)->owner = next;
5086 static inline void finish_lock_switch(struct rq *rq)
5089 * If we are tracking spinlock dependencies then we have to
5090 * fix up the runqueue lock - which gets 'carried over' from
5091 * prev into current:
5093 spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_);
5094 __balance_callbacks(rq);
5095 raw_spin_rq_unlock_irq(rq);
5099 * NOP if the arch has not defined these:
5102 #ifndef prepare_arch_switch
5103 # define prepare_arch_switch(next) do { } while (0)
5106 #ifndef finish_arch_post_lock_switch
5107 # define finish_arch_post_lock_switch() do { } while (0)
5110 static inline void kmap_local_sched_out(void)
5112 #ifdef CONFIG_KMAP_LOCAL
5113 if (unlikely(current->kmap_ctrl.idx))
5114 __kmap_local_sched_out();
5118 static inline void kmap_local_sched_in(void)
5120 #ifdef CONFIG_KMAP_LOCAL
5121 if (unlikely(current->kmap_ctrl.idx))
5122 __kmap_local_sched_in();
5127 * prepare_task_switch - prepare to switch tasks
5128 * @rq: the runqueue preparing to switch
5129 * @prev: the current task that is being switched out
5130 * @next: the task we are going to switch to.
5132 * This is called with the rq lock held and interrupts off. It must
5133 * be paired with a subsequent finish_task_switch after the context
5136 * prepare_task_switch sets up locking and calls architecture specific
5140 prepare_task_switch(struct rq *rq, struct task_struct *prev,
5141 struct task_struct *next)
5143 kcov_prepare_switch(prev);
5144 sched_info_switch(rq, prev, next);
5145 perf_event_task_sched_out(prev, next);
5147 fire_sched_out_preempt_notifiers(prev, next);
5148 kmap_local_sched_out();
5150 prepare_arch_switch(next);
5154 * finish_task_switch - clean up after a task-switch
5155 * @prev: the thread we just switched away from.
5157 * finish_task_switch must be called after the context switch, paired
5158 * with a prepare_task_switch call before the context switch.
5159 * finish_task_switch will reconcile locking set up by prepare_task_switch,
5160 * and do any other architecture-specific cleanup actions.
5162 * Note that we may have delayed dropping an mm in context_switch(). If
5163 * so, we finish that here outside of the runqueue lock. (Doing it
5164 * with the lock held can cause deadlocks; see schedule() for
5167 * The context switch have flipped the stack from under us and restored the
5168 * local variables which were saved when this task called schedule() in the
5169 * past. prev == current is still correct but we need to recalculate this_rq
5170 * because prev may have moved to another CPU.
5172 static struct rq *finish_task_switch(struct task_struct *prev)
5173 __releases(rq->lock)
5175 struct rq *rq = this_rq();
5176 struct mm_struct *mm = rq->prev_mm;
5177 unsigned int prev_state;
5180 * The previous task will have left us with a preempt_count of 2
5181 * because it left us after:
5184 * preempt_disable(); // 1
5186 * raw_spin_lock_irq(&rq->lock) // 2
5188 * Also, see FORK_PREEMPT_COUNT.
5190 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
5191 "corrupted preempt_count: %s/%d/0x%x\n",
5192 current->comm, current->pid, preempt_count()))
5193 preempt_count_set(FORK_PREEMPT_COUNT);
5198 * A task struct has one reference for the use as "current".
5199 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
5200 * schedule one last time. The schedule call will never return, and
5201 * the scheduled task must drop that reference.
5203 * We must observe prev->state before clearing prev->on_cpu (in
5204 * finish_task), otherwise a concurrent wakeup can get prev
5205 * running on another CPU and we could rave with its RUNNING -> DEAD
5206 * transition, resulting in a double drop.
5208 prev_state = READ_ONCE(prev->__state);
5209 vtime_task_switch(prev);
5210 perf_event_task_sched_in(prev, current);
5212 tick_nohz_task_switch();
5213 finish_lock_switch(rq);
5214 finish_arch_post_lock_switch();
5215 kcov_finish_switch(current);
5217 * kmap_local_sched_out() is invoked with rq::lock held and
5218 * interrupts disabled. There is no requirement for that, but the
5219 * sched out code does not have an interrupt enabled section.
5220 * Restoring the maps on sched in does not require interrupts being
5223 kmap_local_sched_in();
5225 fire_sched_in_preempt_notifiers(current);
5227 * When switching through a kernel thread, the loop in
5228 * membarrier_{private,global}_expedited() may have observed that
5229 * kernel thread and not issued an IPI. It is therefore possible to
5230 * schedule between user->kernel->user threads without passing though
5231 * switch_mm(). Membarrier requires a barrier after storing to
5232 * rq->curr, before returning to userspace, so provide them here:
5234 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
5235 * provided by mmdrop_lazy_tlb(),
5236 * - a sync_core for SYNC_CORE.
5239 membarrier_mm_sync_core_before_usermode(mm);
5240 mmdrop_lazy_tlb_sched(mm);
5243 if (unlikely(prev_state == TASK_DEAD)) {
5244 if (prev->sched_class->task_dead)
5245 prev->sched_class->task_dead(prev);
5247 /* Task is done with its stack. */
5248 put_task_stack(prev);
5250 put_task_struct_rcu_user(prev);
5257 * schedule_tail - first thing a freshly forked thread must call.
5258 * @prev: the thread we just switched away from.
5260 asmlinkage __visible void schedule_tail(struct task_struct *prev)
5261 __releases(rq->lock)
5264 * New tasks start with FORK_PREEMPT_COUNT, see there and
5265 * finish_task_switch() for details.
5267 * finish_task_switch() will drop rq->lock() and lower preempt_count
5268 * and the preempt_enable() will end up enabling preemption (on
5269 * PREEMPT_COUNT kernels).
5272 finish_task_switch(prev);
5275 if (current->set_child_tid)
5276 put_user(task_pid_vnr(current), current->set_child_tid);
5278 calculate_sigpending();
5282 * context_switch - switch to the new MM and the new thread's register state.
5284 static __always_inline struct rq *
5285 context_switch(struct rq *rq, struct task_struct *prev,
5286 struct task_struct *next, struct rq_flags *rf)
5288 prepare_task_switch(rq, prev, next);
5291 * For paravirt, this is coupled with an exit in switch_to to
5292 * combine the page table reload and the switch backend into
5295 arch_start_context_switch(prev);
5298 * kernel -> kernel lazy + transfer active
5299 * user -> kernel lazy + mmgrab_lazy_tlb() active
5301 * kernel -> user switch + mmdrop_lazy_tlb() active
5302 * user -> user switch
5304 * switch_mm_cid() needs to be updated if the barriers provided
5305 * by context_switch() are modified.
5307 if (!next->mm) { // to kernel
5308 enter_lazy_tlb(prev->active_mm, next);
5310 next->active_mm = prev->active_mm;
5311 if (prev->mm) // from user
5312 mmgrab_lazy_tlb(prev->active_mm);
5314 prev->active_mm = NULL;
5316 membarrier_switch_mm(rq, prev->active_mm, next->mm);
5318 * sys_membarrier() requires an smp_mb() between setting
5319 * rq->curr / membarrier_switch_mm() and returning to userspace.
5321 * The below provides this either through switch_mm(), or in
5322 * case 'prev->active_mm == next->mm' through
5323 * finish_task_switch()'s mmdrop().
5325 switch_mm_irqs_off(prev->active_mm, next->mm, next);
5326 lru_gen_use_mm(next->mm);
5328 if (!prev->mm) { // from kernel
5329 /* will mmdrop_lazy_tlb() in finish_task_switch(). */
5330 rq->prev_mm = prev->active_mm;
5331 prev->active_mm = NULL;
5335 /* switch_mm_cid() requires the memory barriers above. */
5336 switch_mm_cid(rq, prev, next);
5338 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
5340 prepare_lock_switch(rq, next, rf);
5342 /* Here we just switch the register state and the stack. */
5343 switch_to(prev, next, prev);
5346 return finish_task_switch(prev);
5350 * nr_running and nr_context_switches:
5352 * externally visible scheduler statistics: current number of runnable
5353 * threads, total number of context switches performed since bootup.
5355 unsigned int nr_running(void)
5357 unsigned int i, sum = 0;
5359 for_each_online_cpu(i)
5360 sum += cpu_rq(i)->nr_running;
5366 * Check if only the current task is running on the CPU.
5368 * Caution: this function does not check that the caller has disabled
5369 * preemption, thus the result might have a time-of-check-to-time-of-use
5370 * race. The caller is responsible to use it correctly, for example:
5372 * - from a non-preemptible section (of course)
5374 * - from a thread that is bound to a single CPU
5376 * - in a loop with very short iterations (e.g. a polling loop)
5378 bool single_task_running(void)
5380 return raw_rq()->nr_running == 1;
5382 EXPORT_SYMBOL(single_task_running);
5384 unsigned long long nr_context_switches_cpu(int cpu)
5386 return cpu_rq(cpu)->nr_switches;
5389 unsigned long long nr_context_switches(void)
5392 unsigned long long sum = 0;
5394 for_each_possible_cpu(i)
5395 sum += cpu_rq(i)->nr_switches;
5401 * Consumers of these two interfaces, like for example the cpuidle menu
5402 * governor, are using nonsensical data. Preferring shallow idle state selection
5403 * for a CPU that has IO-wait which might not even end up running the task when
5404 * it does become runnable.
5407 unsigned int nr_iowait_cpu(int cpu)
5409 return atomic_read(&cpu_rq(cpu)->nr_iowait);
5413 * IO-wait accounting, and how it's mostly bollocks (on SMP).
5415 * The idea behind IO-wait account is to account the idle time that we could
5416 * have spend running if it were not for IO. That is, if we were to improve the
5417 * storage performance, we'd have a proportional reduction in IO-wait time.
5419 * This all works nicely on UP, where, when a task blocks on IO, we account
5420 * idle time as IO-wait, because if the storage were faster, it could've been
5421 * running and we'd not be idle.
5423 * This has been extended to SMP, by doing the same for each CPU. This however
5426 * Imagine for instance the case where two tasks block on one CPU, only the one
5427 * CPU will have IO-wait accounted, while the other has regular idle. Even
5428 * though, if the storage were faster, both could've ran at the same time,
5429 * utilising both CPUs.
5431 * This means, that when looking globally, the current IO-wait accounting on
5432 * SMP is a lower bound, by reason of under accounting.
5434 * Worse, since the numbers are provided per CPU, they are sometimes
5435 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
5436 * associated with any one particular CPU, it can wake to another CPU than it
5437 * blocked on. This means the per CPU IO-wait number is meaningless.
5439 * Task CPU affinities can make all that even more 'interesting'.
5442 unsigned int nr_iowait(void)
5444 unsigned int i, sum = 0;
5446 for_each_possible_cpu(i)
5447 sum += nr_iowait_cpu(i);
5455 * sched_exec - execve() is a valuable balancing opportunity, because at
5456 * this point the task has the smallest effective memory and cache footprint.
5458 void sched_exec(void)
5460 struct task_struct *p = current;
5461 unsigned long flags;
5464 raw_spin_lock_irqsave(&p->pi_lock, flags);
5465 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC);
5466 if (dest_cpu == smp_processor_id())
5469 if (likely(cpu_active(dest_cpu))) {
5470 struct migration_arg arg = { p, dest_cpu };
5472 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5473 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
5477 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5482 DEFINE_PER_CPU(struct kernel_stat, kstat);
5483 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
5485 EXPORT_PER_CPU_SYMBOL(kstat);
5486 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
5489 * The function fair_sched_class.update_curr accesses the struct curr
5490 * and its field curr->exec_start; when called from task_sched_runtime(),
5491 * we observe a high rate of cache misses in practice.
5492 * Prefetching this data results in improved performance.
5494 static inline void prefetch_curr_exec_start(struct task_struct *p)
5496 #ifdef CONFIG_FAIR_GROUP_SCHED
5497 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
5499 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
5502 prefetch(&curr->exec_start);
5506 * Return accounted runtime for the task.
5507 * In case the task is currently running, return the runtime plus current's
5508 * pending runtime that have not been accounted yet.
5510 unsigned long long task_sched_runtime(struct task_struct *p)
5516 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
5518 * 64-bit doesn't need locks to atomically read a 64-bit value.
5519 * So we have a optimization chance when the task's delta_exec is 0.
5520 * Reading ->on_cpu is racy, but this is ok.
5522 * If we race with it leaving CPU, we'll take a lock. So we're correct.
5523 * If we race with it entering CPU, unaccounted time is 0. This is
5524 * indistinguishable from the read occurring a few cycles earlier.
5525 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
5526 * been accounted, so we're correct here as well.
5528 if (!p->on_cpu || !task_on_rq_queued(p))
5529 return p->se.sum_exec_runtime;
5532 rq = task_rq_lock(p, &rf);
5534 * Must be ->curr _and_ ->on_rq. If dequeued, we would
5535 * project cycles that may never be accounted to this
5536 * thread, breaking clock_gettime().
5538 if (task_current(rq, p) && task_on_rq_queued(p)) {
5539 prefetch_curr_exec_start(p);
5540 update_rq_clock(rq);
5541 p->sched_class->update_curr(rq);
5543 ns = p->se.sum_exec_runtime;
5544 task_rq_unlock(rq, p, &rf);
5549 #ifdef CONFIG_SCHED_DEBUG
5550 static u64 cpu_resched_latency(struct rq *rq)
5552 int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms);
5553 u64 resched_latency, now = rq_clock(rq);
5554 static bool warned_once;
5556 if (sysctl_resched_latency_warn_once && warned_once)
5559 if (!need_resched() || !latency_warn_ms)
5562 if (system_state == SYSTEM_BOOTING)
5565 if (!rq->last_seen_need_resched_ns) {
5566 rq->last_seen_need_resched_ns = now;
5567 rq->ticks_without_resched = 0;
5571 rq->ticks_without_resched++;
5572 resched_latency = now - rq->last_seen_need_resched_ns;
5573 if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC)
5578 return resched_latency;
5581 static int __init setup_resched_latency_warn_ms(char *str)
5585 if ((kstrtol(str, 0, &val))) {
5586 pr_warn("Unable to set resched_latency_warn_ms\n");
5590 sysctl_resched_latency_warn_ms = val;
5593 __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms);
5595 static inline u64 cpu_resched_latency(struct rq *rq) { return 0; }
5596 #endif /* CONFIG_SCHED_DEBUG */
5599 * This function gets called by the timer code, with HZ frequency.
5600 * We call it with interrupts disabled.
5602 void scheduler_tick(void)
5604 int cpu = smp_processor_id();
5605 struct rq *rq = cpu_rq(cpu);
5606 struct task_struct *curr = rq->curr;
5608 unsigned long thermal_pressure;
5609 u64 resched_latency;
5611 if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5612 arch_scale_freq_tick();
5618 update_rq_clock(rq);
5619 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
5620 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure);
5621 curr->sched_class->task_tick(rq, curr, 0);
5622 if (sched_feat(LATENCY_WARN))
5623 resched_latency = cpu_resched_latency(rq);
5624 calc_global_load_tick(rq);
5625 sched_core_tick(rq);
5626 task_tick_mm_cid(rq, curr);
5630 if (sched_feat(LATENCY_WARN) && resched_latency)
5631 resched_latency_warn(cpu, resched_latency);
5633 perf_event_task_tick();
5636 rq->idle_balance = idle_cpu(cpu);
5637 trigger_load_balance(rq);
5641 #ifdef CONFIG_NO_HZ_FULL
5646 struct delayed_work work;
5648 /* Values for ->state, see diagram below. */
5649 #define TICK_SCHED_REMOTE_OFFLINE 0
5650 #define TICK_SCHED_REMOTE_OFFLINING 1
5651 #define TICK_SCHED_REMOTE_RUNNING 2
5654 * State diagram for ->state:
5657 * TICK_SCHED_REMOTE_OFFLINE
5660 * | | sched_tick_remote()
5663 * +--TICK_SCHED_REMOTE_OFFLINING
5666 * sched_tick_start() | | sched_tick_stop()
5669 * TICK_SCHED_REMOTE_RUNNING
5672 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
5673 * and sched_tick_start() are happy to leave the state in RUNNING.
5676 static struct tick_work __percpu *tick_work_cpu;
5678 static void sched_tick_remote(struct work_struct *work)
5680 struct delayed_work *dwork = to_delayed_work(work);
5681 struct tick_work *twork = container_of(dwork, struct tick_work, work);
5682 int cpu = twork->cpu;
5683 struct rq *rq = cpu_rq(cpu);
5684 struct task_struct *curr;
5690 * Handle the tick only if it appears the remote CPU is running in full
5691 * dynticks mode. The check is racy by nature, but missing a tick or
5692 * having one too much is no big deal because the scheduler tick updates
5693 * statistics and checks timeslices in a time-independent way, regardless
5694 * of when exactly it is running.
5696 if (!tick_nohz_tick_stopped_cpu(cpu))
5699 rq_lock_irq(rq, &rf);
5701 if (cpu_is_offline(cpu))
5704 update_rq_clock(rq);
5706 if (!is_idle_task(curr)) {
5708 * Make sure the next tick runs within a reasonable
5711 delta = rq_clock_task(rq) - curr->se.exec_start;
5712 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
5714 curr->sched_class->task_tick(rq, curr, 0);
5716 calc_load_nohz_remote(rq);
5718 rq_unlock_irq(rq, &rf);
5722 * Run the remote tick once per second (1Hz). This arbitrary
5723 * frequency is large enough to avoid overload but short enough
5724 * to keep scheduler internal stats reasonably up to date. But
5725 * first update state to reflect hotplug activity if required.
5727 os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
5728 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
5729 if (os == TICK_SCHED_REMOTE_RUNNING)
5730 queue_delayed_work(system_unbound_wq, dwork, HZ);
5733 static void sched_tick_start(int cpu)
5736 struct tick_work *twork;
5738 if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5741 WARN_ON_ONCE(!tick_work_cpu);
5743 twork = per_cpu_ptr(tick_work_cpu, cpu);
5744 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
5745 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
5746 if (os == TICK_SCHED_REMOTE_OFFLINE) {
5748 INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
5749 queue_delayed_work(system_unbound_wq, &twork->work, HZ);
5753 #ifdef CONFIG_HOTPLUG_CPU
5754 static void sched_tick_stop(int cpu)
5756 struct tick_work *twork;
5759 if (housekeeping_cpu(cpu, HK_TYPE_TICK))
5762 WARN_ON_ONCE(!tick_work_cpu);
5764 twork = per_cpu_ptr(tick_work_cpu, cpu);
5765 /* There cannot be competing actions, but don't rely on stop-machine. */
5766 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
5767 WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
5768 /* Don't cancel, as this would mess up the state machine. */
5770 #endif /* CONFIG_HOTPLUG_CPU */
5772 int __init sched_tick_offload_init(void)
5774 tick_work_cpu = alloc_percpu(struct tick_work);
5775 BUG_ON(!tick_work_cpu);
5779 #else /* !CONFIG_NO_HZ_FULL */
5780 static inline void sched_tick_start(int cpu) { }
5781 static inline void sched_tick_stop(int cpu) { }
5784 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
5785 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
5787 * If the value passed in is equal to the current preempt count
5788 * then we just disabled preemption. Start timing the latency.
5790 static inline void preempt_latency_start(int val)
5792 if (preempt_count() == val) {
5793 unsigned long ip = get_lock_parent_ip();
5794 #ifdef CONFIG_DEBUG_PREEMPT
5795 current->preempt_disable_ip = ip;
5797 trace_preempt_off(CALLER_ADDR0, ip);
5801 void preempt_count_add(int val)
5803 #ifdef CONFIG_DEBUG_PREEMPT
5807 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5810 __preempt_count_add(val);
5811 #ifdef CONFIG_DEBUG_PREEMPT
5813 * Spinlock count overflowing soon?
5815 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5818 preempt_latency_start(val);
5820 EXPORT_SYMBOL(preempt_count_add);
5821 NOKPROBE_SYMBOL(preempt_count_add);
5824 * If the value passed in equals to the current preempt count
5825 * then we just enabled preemption. Stop timing the latency.
5827 static inline void preempt_latency_stop(int val)
5829 if (preempt_count() == val)
5830 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
5833 void preempt_count_sub(int val)
5835 #ifdef CONFIG_DEBUG_PREEMPT
5839 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
5842 * Is the spinlock portion underflowing?
5844 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5845 !(preempt_count() & PREEMPT_MASK)))
5849 preempt_latency_stop(val);
5850 __preempt_count_sub(val);
5852 EXPORT_SYMBOL(preempt_count_sub);
5853 NOKPROBE_SYMBOL(preempt_count_sub);
5856 static inline void preempt_latency_start(int val) { }
5857 static inline void preempt_latency_stop(int val) { }
5860 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
5862 #ifdef CONFIG_DEBUG_PREEMPT
5863 return p->preempt_disable_ip;
5870 * Print scheduling while atomic bug:
5872 static noinline void __schedule_bug(struct task_struct *prev)
5874 /* Save this before calling printk(), since that will clobber it */
5875 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
5877 if (oops_in_progress)
5880 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
5881 prev->comm, prev->pid, preempt_count());
5883 debug_show_held_locks(prev);
5885 if (irqs_disabled())
5886 print_irqtrace_events(prev);
5887 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
5888 && in_atomic_preempt_off()) {
5889 pr_err("Preemption disabled at:");
5890 print_ip_sym(KERN_ERR, preempt_disable_ip);
5892 check_panic_on_warn("scheduling while atomic");
5895 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5899 * Various schedule()-time debugging checks and statistics:
5901 static inline void schedule_debug(struct task_struct *prev, bool preempt)
5903 #ifdef CONFIG_SCHED_STACK_END_CHECK
5904 if (task_stack_end_corrupted(prev))
5905 panic("corrupted stack end detected inside scheduler\n");
5907 if (task_scs_end_corrupted(prev))
5908 panic("corrupted shadow stack detected inside scheduler\n");
5911 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
5912 if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) {
5913 printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
5914 prev->comm, prev->pid, prev->non_block_count);
5916 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5920 if (unlikely(in_atomic_preempt_off())) {
5921 __schedule_bug(prev);
5922 preempt_count_set(PREEMPT_DISABLED);
5925 SCHED_WARN_ON(ct_state() == CONTEXT_USER);
5927 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5929 schedstat_inc(this_rq()->sched_count);
5932 static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
5933 struct rq_flags *rf)
5936 const struct sched_class *class;
5938 * We must do the balancing pass before put_prev_task(), such
5939 * that when we release the rq->lock the task is in the same
5940 * state as before we took rq->lock.
5942 * We can terminate the balance pass as soon as we know there is
5943 * a runnable task of @class priority or higher.
5945 for_class_range(class, prev->sched_class, &idle_sched_class) {
5946 if (class->balance(rq, prev, rf))
5951 put_prev_task(rq, prev);
5955 * Pick up the highest-prio task:
5957 static inline struct task_struct *
5958 __pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5960 const struct sched_class *class;
5961 struct task_struct *p;
5964 * Optimization: we know that if all tasks are in the fair class we can
5965 * call that function directly, but only if the @prev task wasn't of a
5966 * higher scheduling class, because otherwise those lose the
5967 * opportunity to pull in more work from other CPUs.
5969 if (likely(!sched_class_above(prev->sched_class, &fair_sched_class) &&
5970 rq->nr_running == rq->cfs.h_nr_running)) {
5972 p = pick_next_task_fair(rq, prev, rf);
5973 if (unlikely(p == RETRY_TASK))
5976 /* Assume the next prioritized class is idle_sched_class */
5978 put_prev_task(rq, prev);
5979 p = pick_next_task_idle(rq);
5986 put_prev_task_balance(rq, prev, rf);
5988 for_each_class(class) {
5989 p = class->pick_next_task(rq);
5994 BUG(); /* The idle class should always have a runnable task. */
5997 #ifdef CONFIG_SCHED_CORE
5998 static inline bool is_task_rq_idle(struct task_struct *t)
6000 return (task_rq(t)->idle == t);
6003 static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
6005 return is_task_rq_idle(a) || (a->core_cookie == cookie);
6008 static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
6010 if (is_task_rq_idle(a) || is_task_rq_idle(b))
6013 return a->core_cookie == b->core_cookie;
6016 static inline struct task_struct *pick_task(struct rq *rq)
6018 const struct sched_class *class;
6019 struct task_struct *p;
6021 for_each_class(class) {
6022 p = class->pick_task(rq);
6027 BUG(); /* The idle class should always have a runnable task. */
6030 extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
6032 static void queue_core_balance(struct rq *rq);
6034 static struct task_struct *
6035 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6037 struct task_struct *next, *p, *max = NULL;
6038 const struct cpumask *smt_mask;
6039 bool fi_before = false;
6040 bool core_clock_updated = (rq == rq->core);
6041 unsigned long cookie;
6042 int i, cpu, occ = 0;
6046 if (!sched_core_enabled(rq))
6047 return __pick_next_task(rq, prev, rf);
6051 /* Stopper task is switching into idle, no need core-wide selection. */
6052 if (cpu_is_offline(cpu)) {
6054 * Reset core_pick so that we don't enter the fastpath when
6055 * coming online. core_pick would already be migrated to
6056 * another cpu during offline.
6058 rq->core_pick = NULL;
6059 return __pick_next_task(rq, prev, rf);
6063 * If there were no {en,de}queues since we picked (IOW, the task
6064 * pointers are all still valid), and we haven't scheduled the last
6065 * pick yet, do so now.
6067 * rq->core_pick can be NULL if no selection was made for a CPU because
6068 * it was either offline or went offline during a sibling's core-wide
6069 * selection. In this case, do a core-wide selection.
6071 if (rq->core->core_pick_seq == rq->core->core_task_seq &&
6072 rq->core->core_pick_seq != rq->core_sched_seq &&
6074 WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
6076 next = rq->core_pick;
6078 put_prev_task(rq, prev);
6079 set_next_task(rq, next);
6082 rq->core_pick = NULL;
6086 put_prev_task_balance(rq, prev, rf);
6088 smt_mask = cpu_smt_mask(cpu);
6089 need_sync = !!rq->core->core_cookie;
6092 rq->core->core_cookie = 0UL;
6093 if (rq->core->core_forceidle_count) {
6094 if (!core_clock_updated) {
6095 update_rq_clock(rq->core);
6096 core_clock_updated = true;
6098 sched_core_account_forceidle(rq);
6099 /* reset after accounting force idle */
6100 rq->core->core_forceidle_start = 0;
6101 rq->core->core_forceidle_count = 0;
6102 rq->core->core_forceidle_occupation = 0;
6108 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
6110 * @task_seq guards the task state ({en,de}queues)
6111 * @pick_seq is the @task_seq we did a selection on
6112 * @sched_seq is the @pick_seq we scheduled
6114 * However, preemptions can cause multiple picks on the same task set.
6115 * 'Fix' this by also increasing @task_seq for every pick.
6117 rq->core->core_task_seq++;
6120 * Optimize for common case where this CPU has no cookies
6121 * and there are no cookied tasks running on siblings.
6124 next = pick_task(rq);
6125 if (!next->core_cookie) {
6126 rq->core_pick = NULL;
6128 * For robustness, update the min_vruntime_fi for
6129 * unconstrained picks as well.
6131 WARN_ON_ONCE(fi_before);
6132 task_vruntime_update(rq, next, false);
6138 * For each thread: do the regular task pick and find the max prio task
6141 * Tie-break prio towards the current CPU
6143 for_each_cpu_wrap(i, smt_mask, cpu) {
6147 * Current cpu always has its clock updated on entrance to
6148 * pick_next_task(). If the current cpu is not the core,
6149 * the core may also have been updated above.
6151 if (i != cpu && (rq_i != rq->core || !core_clock_updated))
6152 update_rq_clock(rq_i);
6154 p = rq_i->core_pick = pick_task(rq_i);
6155 if (!max || prio_less(max, p, fi_before))
6159 cookie = rq->core->core_cookie = max->core_cookie;
6162 * For each thread: try and find a runnable task that matches @max or
6165 for_each_cpu(i, smt_mask) {
6167 p = rq_i->core_pick;
6169 if (!cookie_equals(p, cookie)) {
6172 p = sched_core_find(rq_i, cookie);
6174 p = idle_sched_class.pick_task(rq_i);
6177 rq_i->core_pick = p;
6179 if (p == rq_i->idle) {
6180 if (rq_i->nr_running) {
6181 rq->core->core_forceidle_count++;
6183 rq->core->core_forceidle_seq++;
6190 if (schedstat_enabled() && rq->core->core_forceidle_count) {
6191 rq->core->core_forceidle_start = rq_clock(rq->core);
6192 rq->core->core_forceidle_occupation = occ;
6195 rq->core->core_pick_seq = rq->core->core_task_seq;
6196 next = rq->core_pick;
6197 rq->core_sched_seq = rq->core->core_pick_seq;
6199 /* Something should have been selected for current CPU */
6200 WARN_ON_ONCE(!next);
6203 * Reschedule siblings
6205 * NOTE: L1TF -- at this point we're no longer running the old task and
6206 * sending an IPI (below) ensures the sibling will no longer be running
6207 * their task. This ensures there is no inter-sibling overlap between
6208 * non-matching user state.
6210 for_each_cpu(i, smt_mask) {
6214 * An online sibling might have gone offline before a task
6215 * could be picked for it, or it might be offline but later
6216 * happen to come online, but its too late and nothing was
6217 * picked for it. That's Ok - it will pick tasks for itself,
6220 if (!rq_i->core_pick)
6224 * Update for new !FI->FI transitions, or if continuing to be in !FI:
6225 * fi_before fi update?
6231 if (!(fi_before && rq->core->core_forceidle_count))
6232 task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count);
6234 rq_i->core_pick->core_occupation = occ;
6237 rq_i->core_pick = NULL;
6241 /* Did we break L1TF mitigation requirements? */
6242 WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
6244 if (rq_i->curr == rq_i->core_pick) {
6245 rq_i->core_pick = NULL;
6253 set_next_task(rq, next);
6255 if (rq->core->core_forceidle_count && next == rq->idle)
6256 queue_core_balance(rq);
6261 static bool try_steal_cookie(int this, int that)
6263 struct rq *dst = cpu_rq(this), *src = cpu_rq(that);
6264 struct task_struct *p;
6265 unsigned long cookie;
6266 bool success = false;
6268 local_irq_disable();
6269 double_rq_lock(dst, src);
6271 cookie = dst->core->core_cookie;
6275 if (dst->curr != dst->idle)
6278 p = sched_core_find(src, cookie);
6283 if (p == src->core_pick || p == src->curr)
6286 if (!is_cpu_allowed(p, this))
6289 if (p->core_occupation > dst->idle->core_occupation)
6292 * sched_core_find() and sched_core_next() will ensure that task @p
6293 * is not throttled now, we also need to check whether the runqueue
6294 * of the destination CPU is being throttled.
6296 if (sched_task_is_throttled(p, this))
6299 deactivate_task(src, p, 0);
6300 set_task_cpu(p, this);
6301 activate_task(dst, p, 0);
6309 p = sched_core_next(p, cookie);
6313 double_rq_unlock(dst, src);
6319 static bool steal_cookie_task(int cpu, struct sched_domain *sd)
6323 for_each_cpu_wrap(i, sched_domain_span(sd), cpu + 1) {
6330 if (try_steal_cookie(cpu, i))
6337 static void sched_core_balance(struct rq *rq)
6339 struct sched_domain *sd;
6340 int cpu = cpu_of(rq);
6344 raw_spin_rq_unlock_irq(rq);
6345 for_each_domain(cpu, sd) {
6349 if (steal_cookie_task(cpu, sd))
6352 raw_spin_rq_lock_irq(rq);
6357 static DEFINE_PER_CPU(struct balance_callback, core_balance_head);
6359 static void queue_core_balance(struct rq *rq)
6361 if (!sched_core_enabled(rq))
6364 if (!rq->core->core_cookie)
6367 if (!rq->nr_running) /* not forced idle */
6370 queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance);
6373 static void sched_core_cpu_starting(unsigned int cpu)
6375 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6376 struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6377 unsigned long flags;
6380 sched_core_lock(cpu, &flags);
6382 WARN_ON_ONCE(rq->core != rq);
6384 /* if we're the first, we'll be our own leader */
6385 if (cpumask_weight(smt_mask) == 1)
6388 /* find the leader */
6389 for_each_cpu(t, smt_mask) {
6393 if (rq->core == rq) {
6399 if (WARN_ON_ONCE(!core_rq)) /* whoopsie */
6402 /* install and validate core_rq */
6403 for_each_cpu(t, smt_mask) {
6409 WARN_ON_ONCE(rq->core != core_rq);
6413 sched_core_unlock(cpu, &flags);
6416 static void sched_core_cpu_deactivate(unsigned int cpu)
6418 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
6419 struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
6420 unsigned long flags;
6423 sched_core_lock(cpu, &flags);
6425 /* if we're the last man standing, nothing to do */
6426 if (cpumask_weight(smt_mask) == 1) {
6427 WARN_ON_ONCE(rq->core != rq);
6431 /* if we're not the leader, nothing to do */
6435 /* find a new leader */
6436 for_each_cpu(t, smt_mask) {
6439 core_rq = cpu_rq(t);
6443 if (WARN_ON_ONCE(!core_rq)) /* impossible */
6446 /* copy the shared state to the new leader */
6447 core_rq->core_task_seq = rq->core_task_seq;
6448 core_rq->core_pick_seq = rq->core_pick_seq;
6449 core_rq->core_cookie = rq->core_cookie;
6450 core_rq->core_forceidle_count = rq->core_forceidle_count;
6451 core_rq->core_forceidle_seq = rq->core_forceidle_seq;
6452 core_rq->core_forceidle_occupation = rq->core_forceidle_occupation;
6455 * Accounting edge for forced idle is handled in pick_next_task().
6456 * Don't need another one here, since the hotplug thread shouldn't
6459 core_rq->core_forceidle_start = 0;
6461 /* install new leader */
6462 for_each_cpu(t, smt_mask) {
6468 sched_core_unlock(cpu, &flags);
6471 static inline void sched_core_cpu_dying(unsigned int cpu)
6473 struct rq *rq = cpu_rq(cpu);
6479 #else /* !CONFIG_SCHED_CORE */
6481 static inline void sched_core_cpu_starting(unsigned int cpu) {}
6482 static inline void sched_core_cpu_deactivate(unsigned int cpu) {}
6483 static inline void sched_core_cpu_dying(unsigned int cpu) {}
6485 static struct task_struct *
6486 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6488 return __pick_next_task(rq, prev, rf);
6491 #endif /* CONFIG_SCHED_CORE */
6494 * Constants for the sched_mode argument of __schedule().
6496 * The mode argument allows RT enabled kernels to differentiate a
6497 * preemption from blocking on an 'sleeping' spin/rwlock. Note that
6498 * SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to
6499 * optimize the AND operation out and just check for zero.
6502 #define SM_PREEMPT 0x1
6503 #define SM_RTLOCK_WAIT 0x2
6505 #ifndef CONFIG_PREEMPT_RT
6506 # define SM_MASK_PREEMPT (~0U)
6508 # define SM_MASK_PREEMPT SM_PREEMPT
6512 * __schedule() is the main scheduler function.
6514 * The main means of driving the scheduler and thus entering this function are:
6516 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
6518 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
6519 * paths. For example, see arch/x86/entry_64.S.
6521 * To drive preemption between tasks, the scheduler sets the flag in timer
6522 * interrupt handler scheduler_tick().
6524 * 3. Wakeups don't really cause entry into schedule(). They add a
6525 * task to the run-queue and that's it.
6527 * Now, if the new task added to the run-queue preempts the current
6528 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
6529 * called on the nearest possible occasion:
6531 * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
6533 * - in syscall or exception context, at the next outmost
6534 * preempt_enable(). (this might be as soon as the wake_up()'s
6537 * - in IRQ context, return from interrupt-handler to
6538 * preemptible context
6540 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
6543 * - cond_resched() call
6544 * - explicit schedule() call
6545 * - return from syscall or exception to user-space
6546 * - return from interrupt-handler to user-space
6548 * WARNING: must be called with preemption disabled!
6550 static void __sched notrace __schedule(unsigned int sched_mode)
6552 struct task_struct *prev, *next;
6553 unsigned long *switch_count;
6554 unsigned long prev_state;
6559 cpu = smp_processor_id();
6563 schedule_debug(prev, !!sched_mode);
6565 if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
6568 local_irq_disable();
6569 rcu_note_context_switch(!!sched_mode);
6572 * Make sure that signal_pending_state()->signal_pending() below
6573 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
6574 * done by the caller to avoid the race with signal_wake_up():
6576 * __set_current_state(@state) signal_wake_up()
6577 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
6578 * wake_up_state(p, state)
6579 * LOCK rq->lock LOCK p->pi_state
6580 * smp_mb__after_spinlock() smp_mb__after_spinlock()
6581 * if (signal_pending_state()) if (p->state & @state)
6583 * Also, the membarrier system call requires a full memory barrier
6584 * after coming from user-space, before storing to rq->curr.
6587 smp_mb__after_spinlock();
6589 /* Promote REQ to ACT */
6590 rq->clock_update_flags <<= 1;
6591 update_rq_clock(rq);
6593 switch_count = &prev->nivcsw;
6596 * We must load prev->state once (task_struct::state is volatile), such
6597 * that we form a control dependency vs deactivate_task() below.
6599 prev_state = READ_ONCE(prev->__state);
6600 if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {
6601 if (signal_pending_state(prev_state, prev)) {
6602 WRITE_ONCE(prev->__state, TASK_RUNNING);
6604 prev->sched_contributes_to_load =
6605 (prev_state & TASK_UNINTERRUPTIBLE) &&
6606 !(prev_state & TASK_NOLOAD) &&
6607 !(prev_state & TASK_FROZEN);
6609 if (prev->sched_contributes_to_load)
6610 rq->nr_uninterruptible++;
6613 * __schedule() ttwu()
6614 * prev_state = prev->state; if (p->on_rq && ...)
6615 * if (prev_state) goto out;
6616 * p->on_rq = 0; smp_acquire__after_ctrl_dep();
6617 * p->state = TASK_WAKING
6619 * Where __schedule() and ttwu() have matching control dependencies.
6621 * After this, schedule() must not care about p->state any more.
6623 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
6625 if (prev->in_iowait) {
6626 atomic_inc(&rq->nr_iowait);
6627 delayacct_blkio_start();
6630 switch_count = &prev->nvcsw;
6633 next = pick_next_task(rq, prev, &rf);
6634 clear_tsk_need_resched(prev);
6635 clear_preempt_need_resched();
6636 #ifdef CONFIG_SCHED_DEBUG
6637 rq->last_seen_need_resched_ns = 0;
6640 if (likely(prev != next)) {
6643 * RCU users of rcu_dereference(rq->curr) may not see
6644 * changes to task_struct made by pick_next_task().
6646 RCU_INIT_POINTER(rq->curr, next);
6648 * The membarrier system call requires each architecture
6649 * to have a full memory barrier after updating
6650 * rq->curr, before returning to user-space.
6652 * Here are the schemes providing that barrier on the
6653 * various architectures:
6654 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
6655 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
6656 * - finish_lock_switch() for weakly-ordered
6657 * architectures where spin_unlock is a full barrier,
6658 * - switch_to() for arm64 (weakly-ordered, spin_unlock
6659 * is a RELEASE barrier),
6663 migrate_disable_switch(rq, prev);
6664 psi_sched_switch(prev, next, !task_on_rq_queued(prev));
6666 trace_sched_switch(sched_mode & SM_MASK_PREEMPT, prev, next, prev_state);
6668 /* Also unlocks the rq: */
6669 rq = context_switch(rq, prev, next, &rf);
6671 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
6673 rq_unpin_lock(rq, &rf);
6674 __balance_callbacks(rq);
6675 raw_spin_rq_unlock_irq(rq);
6679 void __noreturn do_task_dead(void)
6681 /* Causes final put_task_struct in finish_task_switch(): */
6682 set_special_state(TASK_DEAD);
6684 /* Tell freezer to ignore us: */
6685 current->flags |= PF_NOFREEZE;
6687 __schedule(SM_NONE);
6690 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
6695 static inline void sched_submit_work(struct task_struct *tsk)
6697 unsigned int task_flags;
6699 if (task_is_running(tsk))
6702 task_flags = tsk->flags;
6704 * If a worker goes to sleep, notify and ask workqueue whether it
6705 * wants to wake up a task to maintain concurrency.
6707 if (task_flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6708 if (task_flags & PF_WQ_WORKER)
6709 wq_worker_sleeping(tsk);
6711 io_wq_worker_sleeping(tsk);
6715 * spinlock and rwlock must not flush block requests. This will
6716 * deadlock if the callback attempts to acquire a lock which is
6719 SCHED_WARN_ON(current->__state & TASK_RTLOCK_WAIT);
6722 * If we are going to sleep and we have plugged IO queued,
6723 * make sure to submit it to avoid deadlocks.
6725 blk_flush_plug(tsk->plug, true);
6728 static void sched_update_worker(struct task_struct *tsk)
6730 if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6731 if (tsk->flags & PF_WQ_WORKER)
6732 wq_worker_running(tsk);
6734 io_wq_worker_running(tsk);
6738 asmlinkage __visible void __sched schedule(void)
6740 struct task_struct *tsk = current;
6742 sched_submit_work(tsk);
6745 __schedule(SM_NONE);
6746 sched_preempt_enable_no_resched();
6747 } while (need_resched());
6748 sched_update_worker(tsk);
6750 EXPORT_SYMBOL(schedule);
6753 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
6754 * state (have scheduled out non-voluntarily) by making sure that all
6755 * tasks have either left the run queue or have gone into user space.
6756 * As idle tasks do not do either, they must not ever be preempted
6757 * (schedule out non-voluntarily).
6759 * schedule_idle() is similar to schedule_preempt_disable() except that it
6760 * never enables preemption because it does not call sched_submit_work().
6762 void __sched schedule_idle(void)
6765 * As this skips calling sched_submit_work(), which the idle task does
6766 * regardless because that function is a nop when the task is in a
6767 * TASK_RUNNING state, make sure this isn't used someplace that the
6768 * current task can be in any other state. Note, idle is always in the
6769 * TASK_RUNNING state.
6771 WARN_ON_ONCE(current->__state);
6773 __schedule(SM_NONE);
6774 } while (need_resched());
6777 #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK)
6778 asmlinkage __visible void __sched schedule_user(void)
6781 * If we come here after a random call to set_need_resched(),
6782 * or we have been woken up remotely but the IPI has not yet arrived,
6783 * we haven't yet exited the RCU idle mode. Do it here manually until
6784 * we find a better solution.
6786 * NB: There are buggy callers of this function. Ideally we
6787 * should warn if prev_state != CONTEXT_USER, but that will trigger
6788 * too frequently to make sense yet.
6790 enum ctx_state prev_state = exception_enter();
6792 exception_exit(prev_state);
6797 * schedule_preempt_disabled - called with preemption disabled
6799 * Returns with preemption disabled. Note: preempt_count must be 1
6801 void __sched schedule_preempt_disabled(void)
6803 sched_preempt_enable_no_resched();
6808 #ifdef CONFIG_PREEMPT_RT
6809 void __sched notrace schedule_rtlock(void)
6813 __schedule(SM_RTLOCK_WAIT);
6814 sched_preempt_enable_no_resched();
6815 } while (need_resched());
6817 NOKPROBE_SYMBOL(schedule_rtlock);
6820 static void __sched notrace preempt_schedule_common(void)
6824 * Because the function tracer can trace preempt_count_sub()
6825 * and it also uses preempt_enable/disable_notrace(), if
6826 * NEED_RESCHED is set, the preempt_enable_notrace() called
6827 * by the function tracer will call this function again and
6828 * cause infinite recursion.
6830 * Preemption must be disabled here before the function
6831 * tracer can trace. Break up preempt_disable() into two
6832 * calls. One to disable preemption without fear of being
6833 * traced. The other to still record the preemption latency,
6834 * which can also be traced by the function tracer.
6836 preempt_disable_notrace();
6837 preempt_latency_start(1);
6838 __schedule(SM_PREEMPT);
6839 preempt_latency_stop(1);
6840 preempt_enable_no_resched_notrace();
6843 * Check again in case we missed a preemption opportunity
6844 * between schedule and now.
6846 } while (need_resched());
6849 #ifdef CONFIG_PREEMPTION
6851 * This is the entry point to schedule() from in-kernel preemption
6852 * off of preempt_enable.
6854 asmlinkage __visible void __sched notrace preempt_schedule(void)
6857 * If there is a non-zero preempt_count or interrupts are disabled,
6858 * we do not want to preempt the current task. Just return..
6860 if (likely(!preemptible()))
6862 preempt_schedule_common();
6864 NOKPROBE_SYMBOL(preempt_schedule);
6865 EXPORT_SYMBOL(preempt_schedule);
6867 #ifdef CONFIG_PREEMPT_DYNAMIC
6868 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
6869 #ifndef preempt_schedule_dynamic_enabled
6870 #define preempt_schedule_dynamic_enabled preempt_schedule
6871 #define preempt_schedule_dynamic_disabled NULL
6873 DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled);
6874 EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
6875 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6876 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule);
6877 void __sched notrace dynamic_preempt_schedule(void)
6879 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule))
6883 NOKPROBE_SYMBOL(dynamic_preempt_schedule);
6884 EXPORT_SYMBOL(dynamic_preempt_schedule);
6889 * preempt_schedule_notrace - preempt_schedule called by tracing
6891 * The tracing infrastructure uses preempt_enable_notrace to prevent
6892 * recursion and tracing preempt enabling caused by the tracing
6893 * infrastructure itself. But as tracing can happen in areas coming
6894 * from userspace or just about to enter userspace, a preempt enable
6895 * can occur before user_exit() is called. This will cause the scheduler
6896 * to be called when the system is still in usermode.
6898 * To prevent this, the preempt_enable_notrace will use this function
6899 * instead of preempt_schedule() to exit user context if needed before
6900 * calling the scheduler.
6902 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
6904 enum ctx_state prev_ctx;
6906 if (likely(!preemptible()))
6911 * Because the function tracer can trace preempt_count_sub()
6912 * and it also uses preempt_enable/disable_notrace(), if
6913 * NEED_RESCHED is set, the preempt_enable_notrace() called
6914 * by the function tracer will call this function again and
6915 * cause infinite recursion.
6917 * Preemption must be disabled here before the function
6918 * tracer can trace. Break up preempt_disable() into two
6919 * calls. One to disable preemption without fear of being
6920 * traced. The other to still record the preemption latency,
6921 * which can also be traced by the function tracer.
6923 preempt_disable_notrace();
6924 preempt_latency_start(1);
6926 * Needs preempt disabled in case user_exit() is traced
6927 * and the tracer calls preempt_enable_notrace() causing
6928 * an infinite recursion.
6930 prev_ctx = exception_enter();
6931 __schedule(SM_PREEMPT);
6932 exception_exit(prev_ctx);
6934 preempt_latency_stop(1);
6935 preempt_enable_no_resched_notrace();
6936 } while (need_resched());
6938 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
6940 #ifdef CONFIG_PREEMPT_DYNAMIC
6941 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
6942 #ifndef preempt_schedule_notrace_dynamic_enabled
6943 #define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace
6944 #define preempt_schedule_notrace_dynamic_disabled NULL
6946 DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled);
6947 EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
6948 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
6949 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace);
6950 void __sched notrace dynamic_preempt_schedule_notrace(void)
6952 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace))
6954 preempt_schedule_notrace();
6956 NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace);
6957 EXPORT_SYMBOL(dynamic_preempt_schedule_notrace);
6961 #endif /* CONFIG_PREEMPTION */
6964 * This is the entry point to schedule() from kernel preemption
6965 * off of irq context.
6966 * Note, that this is called and return with irqs disabled. This will
6967 * protect us against recursive calling from irq.
6969 asmlinkage __visible void __sched preempt_schedule_irq(void)
6971 enum ctx_state prev_state;
6973 /* Catch callers which need to be fixed */
6974 BUG_ON(preempt_count() || !irqs_disabled());
6976 prev_state = exception_enter();
6981 __schedule(SM_PREEMPT);
6982 local_irq_disable();
6983 sched_preempt_enable_no_resched();
6984 } while (need_resched());
6986 exception_exit(prev_state);
6989 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
6992 WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~WF_SYNC);
6993 return try_to_wake_up(curr->private, mode, wake_flags);
6995 EXPORT_SYMBOL(default_wake_function);
6997 static void __setscheduler_prio(struct task_struct *p, int prio)
7000 p->sched_class = &dl_sched_class;
7001 else if (rt_prio(prio))
7002 p->sched_class = &rt_sched_class;
7004 p->sched_class = &fair_sched_class;
7009 #ifdef CONFIG_RT_MUTEXES
7011 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
7014 prio = min(prio, pi_task->prio);
7019 static inline int rt_effective_prio(struct task_struct *p, int prio)
7021 struct task_struct *pi_task = rt_mutex_get_top_task(p);
7023 return __rt_effective_prio(pi_task, prio);
7027 * rt_mutex_setprio - set the current priority of a task
7029 * @pi_task: donor task
7031 * This function changes the 'effective' priority of a task. It does
7032 * not touch ->normal_prio like __setscheduler().
7034 * Used by the rt_mutex code to implement priority inheritance
7035 * logic. Call site only calls if the priority of the task changed.
7037 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
7039 int prio, oldprio, queued, running, queue_flag =
7040 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
7041 const struct sched_class *prev_class;
7045 /* XXX used to be waiter->prio, not waiter->task->prio */
7046 prio = __rt_effective_prio(pi_task, p->normal_prio);
7049 * If nothing changed; bail early.
7051 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
7054 rq = __task_rq_lock(p, &rf);
7055 update_rq_clock(rq);
7057 * Set under pi_lock && rq->lock, such that the value can be used under
7060 * Note that there is loads of tricky to make this pointer cache work
7061 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
7062 * ensure a task is de-boosted (pi_task is set to NULL) before the
7063 * task is allowed to run again (and can exit). This ensures the pointer
7064 * points to a blocked task -- which guarantees the task is present.
7066 p->pi_top_task = pi_task;
7069 * For FIFO/RR we only need to set prio, if that matches we're done.
7071 if (prio == p->prio && !dl_prio(prio))
7075 * Idle task boosting is a nono in general. There is one
7076 * exception, when PREEMPT_RT and NOHZ is active:
7078 * The idle task calls get_next_timer_interrupt() and holds
7079 * the timer wheel base->lock on the CPU and another CPU wants
7080 * to access the timer (probably to cancel it). We can safely
7081 * ignore the boosting request, as the idle CPU runs this code
7082 * with interrupts disabled and will complete the lock
7083 * protected section without being interrupted. So there is no
7084 * real need to boost.
7086 if (unlikely(p == rq->idle)) {
7087 WARN_ON(p != rq->curr);
7088 WARN_ON(p->pi_blocked_on);
7092 trace_sched_pi_setprio(p, pi_task);
7095 if (oldprio == prio)
7096 queue_flag &= ~DEQUEUE_MOVE;
7098 prev_class = p->sched_class;
7099 queued = task_on_rq_queued(p);
7100 running = task_current(rq, p);
7102 dequeue_task(rq, p, queue_flag);
7104 put_prev_task(rq, p);
7107 * Boosting condition are:
7108 * 1. -rt task is running and holds mutex A
7109 * --> -dl task blocks on mutex A
7111 * 2. -dl task is running and holds mutex A
7112 * --> -dl task blocks on mutex A and could preempt the
7115 if (dl_prio(prio)) {
7116 if (!dl_prio(p->normal_prio) ||
7117 (pi_task && dl_prio(pi_task->prio) &&
7118 dl_entity_preempt(&pi_task->dl, &p->dl))) {
7119 p->dl.pi_se = pi_task->dl.pi_se;
7120 queue_flag |= ENQUEUE_REPLENISH;
7122 p->dl.pi_se = &p->dl;
7124 } else if (rt_prio(prio)) {
7125 if (dl_prio(oldprio))
7126 p->dl.pi_se = &p->dl;
7128 queue_flag |= ENQUEUE_HEAD;
7130 if (dl_prio(oldprio))
7131 p->dl.pi_se = &p->dl;
7132 if (rt_prio(oldprio))
7136 __setscheduler_prio(p, prio);
7139 enqueue_task(rq, p, queue_flag);
7141 set_next_task(rq, p);
7143 check_class_changed(rq, p, prev_class, oldprio);
7145 /* Avoid rq from going away on us: */
7148 rq_unpin_lock(rq, &rf);
7149 __balance_callbacks(rq);
7150 raw_spin_rq_unlock(rq);
7155 static inline int rt_effective_prio(struct task_struct *p, int prio)
7161 void set_user_nice(struct task_struct *p, long nice)
7163 bool queued, running;
7168 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
7171 * We have to be careful, if called from sys_setpriority(),
7172 * the task might be in the middle of scheduling on another CPU.
7174 rq = task_rq_lock(p, &rf);
7175 update_rq_clock(rq);
7178 * The RT priorities are set via sched_setscheduler(), but we still
7179 * allow the 'normal' nice value to be set - but as expected
7180 * it won't have any effect on scheduling until the task is
7181 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
7183 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
7184 p->static_prio = NICE_TO_PRIO(nice);
7187 queued = task_on_rq_queued(p);
7188 running = task_current(rq, p);
7190 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
7192 put_prev_task(rq, p);
7194 p->static_prio = NICE_TO_PRIO(nice);
7195 set_load_weight(p, true);
7197 p->prio = effective_prio(p);
7200 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
7202 set_next_task(rq, p);
7205 * If the task increased its priority or is running and
7206 * lowered its priority, then reschedule its CPU:
7208 p->sched_class->prio_changed(rq, p, old_prio);
7211 task_rq_unlock(rq, p, &rf);
7213 EXPORT_SYMBOL(set_user_nice);
7216 * is_nice_reduction - check if nice value is an actual reduction
7218 * Similar to can_nice() but does not perform a capability check.
7223 static bool is_nice_reduction(const struct task_struct *p, const int nice)
7225 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
7226 int nice_rlim = nice_to_rlimit(nice);
7228 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE));
7232 * can_nice - check if a task can reduce its nice value
7236 int can_nice(const struct task_struct *p, const int nice)
7238 return is_nice_reduction(p, nice) || capable(CAP_SYS_NICE);
7241 #ifdef __ARCH_WANT_SYS_NICE
7244 * sys_nice - change the priority of the current process.
7245 * @increment: priority increment
7247 * sys_setpriority is a more generic, but much slower function that
7248 * does similar things.
7250 SYSCALL_DEFINE1(nice, int, increment)
7255 * Setpriority might change our priority at the same moment.
7256 * We don't have to worry. Conceptually one call occurs first
7257 * and we have a single winner.
7259 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
7260 nice = task_nice(current) + increment;
7262 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
7263 if (increment < 0 && !can_nice(current, nice))
7266 retval = security_task_setnice(current, nice);
7270 set_user_nice(current, nice);
7277 * task_prio - return the priority value of a given task.
7278 * @p: the task in question.
7280 * Return: The priority value as seen by users in /proc.
7282 * sched policy return value kernel prio user prio/nice
7284 * normal, batch, idle [0 ... 39] [100 ... 139] 0/[-20 ... 19]
7285 * fifo, rr [-2 ... -100] [98 ... 0] [1 ... 99]
7286 * deadline -101 -1 0
7288 int task_prio(const struct task_struct *p)
7290 return p->prio - MAX_RT_PRIO;
7294 * idle_cpu - is a given CPU idle currently?
7295 * @cpu: the processor in question.
7297 * Return: 1 if the CPU is currently idle. 0 otherwise.
7299 int idle_cpu(int cpu)
7301 struct rq *rq = cpu_rq(cpu);
7303 if (rq->curr != rq->idle)
7310 if (rq->ttwu_pending)
7318 * available_idle_cpu - is a given CPU idle for enqueuing work.
7319 * @cpu: the CPU in question.
7321 * Return: 1 if the CPU is currently idle. 0 otherwise.
7323 int available_idle_cpu(int cpu)
7328 if (vcpu_is_preempted(cpu))
7335 * idle_task - return the idle task for a given CPU.
7336 * @cpu: the processor in question.
7338 * Return: The idle task for the CPU @cpu.
7340 struct task_struct *idle_task(int cpu)
7342 return cpu_rq(cpu)->idle;
7347 * This function computes an effective utilization for the given CPU, to be
7348 * used for frequency selection given the linear relation: f = u * f_max.
7350 * The scheduler tracks the following metrics:
7352 * cpu_util_{cfs,rt,dl,irq}()
7355 * Where the cfs,rt and dl util numbers are tracked with the same metric and
7356 * synchronized windows and are thus directly comparable.
7358 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
7359 * which excludes things like IRQ and steal-time. These latter are then accrued
7360 * in the irq utilization.
7362 * The DL bandwidth number otoh is not a measured metric but a value computed
7363 * based on the task model parameters and gives the minimal utilization
7364 * required to meet deadlines.
7366 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
7367 enum cpu_util_type type,
7368 struct task_struct *p)
7370 unsigned long dl_util, util, irq, max;
7371 struct rq *rq = cpu_rq(cpu);
7373 max = arch_scale_cpu_capacity(cpu);
7375 if (!uclamp_is_used() &&
7376 type == FREQUENCY_UTIL && rt_rq_is_runnable(&rq->rt)) {
7381 * Early check to see if IRQ/steal time saturates the CPU, can be
7382 * because of inaccuracies in how we track these -- see
7383 * update_irq_load_avg().
7385 irq = cpu_util_irq(rq);
7386 if (unlikely(irq >= max))
7390 * Because the time spend on RT/DL tasks is visible as 'lost' time to
7391 * CFS tasks and we use the same metric to track the effective
7392 * utilization (PELT windows are synchronized) we can directly add them
7393 * to obtain the CPU's actual utilization.
7395 * CFS and RT utilization can be boosted or capped, depending on
7396 * utilization clamp constraints requested by currently RUNNABLE
7398 * When there are no CFS RUNNABLE tasks, clamps are released and
7399 * frequency will be gracefully reduced with the utilization decay.
7401 util = util_cfs + cpu_util_rt(rq);
7402 if (type == FREQUENCY_UTIL)
7403 util = uclamp_rq_util_with(rq, util, p);
7405 dl_util = cpu_util_dl(rq);
7408 * For frequency selection we do not make cpu_util_dl() a permanent part
7409 * of this sum because we want to use cpu_bw_dl() later on, but we need
7410 * to check if the CFS+RT+DL sum is saturated (ie. no idle time) such
7411 * that we select f_max when there is no idle time.
7413 * NOTE: numerical errors or stop class might cause us to not quite hit
7414 * saturation when we should -- something for later.
7416 if (util + dl_util >= max)
7420 * OTOH, for energy computation we need the estimated running time, so
7421 * include util_dl and ignore dl_bw.
7423 if (type == ENERGY_UTIL)
7427 * There is still idle time; further improve the number by using the
7428 * irq metric. Because IRQ/steal time is hidden from the task clock we
7429 * need to scale the task numbers:
7432 * U' = irq + --------- * U
7435 util = scale_irq_capacity(util, irq, max);
7439 * Bandwidth required by DEADLINE must always be granted while, for
7440 * FAIR and RT, we use blocked utilization of IDLE CPUs as a mechanism
7441 * to gracefully reduce the frequency when no tasks show up for longer
7444 * Ideally we would like to set bw_dl as min/guaranteed freq and util +
7445 * bw_dl as requested freq. However, cpufreq is not yet ready for such
7446 * an interface. So, we only do the latter for now.
7448 if (type == FREQUENCY_UTIL)
7449 util += cpu_bw_dl(rq);
7451 return min(max, util);
7454 unsigned long sched_cpu_util(int cpu)
7456 return effective_cpu_util(cpu, cpu_util_cfs(cpu), ENERGY_UTIL, NULL);
7458 #endif /* CONFIG_SMP */
7461 * find_process_by_pid - find a process with a matching PID value.
7462 * @pid: the pid in question.
7464 * The task of @pid, if found. %NULL otherwise.
7466 static struct task_struct *find_process_by_pid(pid_t pid)
7468 return pid ? find_task_by_vpid(pid) : current;
7472 * sched_setparam() passes in -1 for its policy, to let the functions
7473 * it calls know not to change it.
7475 #define SETPARAM_POLICY -1
7477 static void __setscheduler_params(struct task_struct *p,
7478 const struct sched_attr *attr)
7480 int policy = attr->sched_policy;
7482 if (policy == SETPARAM_POLICY)
7487 if (dl_policy(policy))
7488 __setparam_dl(p, attr);
7489 else if (fair_policy(policy))
7490 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
7493 * __sched_setscheduler() ensures attr->sched_priority == 0 when
7494 * !rt_policy. Always setting this ensures that things like
7495 * getparam()/getattr() don't report silly values for !rt tasks.
7497 p->rt_priority = attr->sched_priority;
7498 p->normal_prio = normal_prio(p);
7499 set_load_weight(p, true);
7503 * Check the target process has a UID that matches the current process's:
7505 static bool check_same_owner(struct task_struct *p)
7507 const struct cred *cred = current_cred(), *pcred;
7511 pcred = __task_cred(p);
7512 match = (uid_eq(cred->euid, pcred->euid) ||
7513 uid_eq(cred->euid, pcred->uid));
7519 * Allow unprivileged RT tasks to decrease priority.
7520 * Only issue a capable test if needed and only once to avoid an audit
7521 * event on permitted non-privileged operations:
7523 static int user_check_sched_setscheduler(struct task_struct *p,
7524 const struct sched_attr *attr,
7525 int policy, int reset_on_fork)
7527 if (fair_policy(policy)) {
7528 if (attr->sched_nice < task_nice(p) &&
7529 !is_nice_reduction(p, attr->sched_nice))
7533 if (rt_policy(policy)) {
7534 unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO);
7536 /* Can't set/change the rt policy: */
7537 if (policy != p->policy && !rlim_rtprio)
7540 /* Can't increase priority: */
7541 if (attr->sched_priority > p->rt_priority &&
7542 attr->sched_priority > rlim_rtprio)
7547 * Can't set/change SCHED_DEADLINE policy at all for now
7548 * (safest behavior); in the future we would like to allow
7549 * unprivileged DL tasks to increase their relative deadline
7550 * or reduce their runtime (both ways reducing utilization)
7552 if (dl_policy(policy))
7556 * Treat SCHED_IDLE as nice 20. Only allow a switch to
7557 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
7559 if (task_has_idle_policy(p) && !idle_policy(policy)) {
7560 if (!is_nice_reduction(p, task_nice(p)))
7564 /* Can't change other user's priorities: */
7565 if (!check_same_owner(p))
7568 /* Normal users shall not reset the sched_reset_on_fork flag: */
7569 if (p->sched_reset_on_fork && !reset_on_fork)
7575 if (!capable(CAP_SYS_NICE))
7581 static int __sched_setscheduler(struct task_struct *p,
7582 const struct sched_attr *attr,
7585 int oldpolicy = -1, policy = attr->sched_policy;
7586 int retval, oldprio, newprio, queued, running;
7587 const struct sched_class *prev_class;
7588 struct balance_callback *head;
7591 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
7594 /* The pi code expects interrupts enabled */
7595 BUG_ON(pi && in_interrupt());
7597 /* Double check policy once rq lock held: */
7599 reset_on_fork = p->sched_reset_on_fork;
7600 policy = oldpolicy = p->policy;
7602 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
7604 if (!valid_policy(policy))
7608 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
7612 * Valid priorities for SCHED_FIFO and SCHED_RR are
7613 * 1..MAX_RT_PRIO-1, valid priority for SCHED_NORMAL,
7614 * SCHED_BATCH and SCHED_IDLE is 0.
7616 if (attr->sched_priority > MAX_RT_PRIO-1)
7618 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
7619 (rt_policy(policy) != (attr->sched_priority != 0)))
7623 retval = user_check_sched_setscheduler(p, attr, policy, reset_on_fork);
7627 if (attr->sched_flags & SCHED_FLAG_SUGOV)
7630 retval = security_task_setscheduler(p);
7635 /* Update task specific "requested" clamps */
7636 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
7637 retval = uclamp_validate(p, attr);
7646 * Make sure no PI-waiters arrive (or leave) while we are
7647 * changing the priority of the task:
7649 * To be able to change p->policy safely, the appropriate
7650 * runqueue lock must be held.
7652 rq = task_rq_lock(p, &rf);
7653 update_rq_clock(rq);
7656 * Changing the policy of the stop threads its a very bad idea:
7658 if (p == rq->stop) {
7664 * If not changing anything there's no need to proceed further,
7665 * but store a possible modification of reset_on_fork.
7667 if (unlikely(policy == p->policy)) {
7668 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
7670 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
7672 if (dl_policy(policy) && dl_param_changed(p, attr))
7674 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
7677 p->sched_reset_on_fork = reset_on_fork;
7684 #ifdef CONFIG_RT_GROUP_SCHED
7686 * Do not allow realtime tasks into groups that have no runtime
7689 if (rt_bandwidth_enabled() && rt_policy(policy) &&
7690 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
7691 !task_group_is_autogroup(task_group(p))) {
7697 if (dl_bandwidth_enabled() && dl_policy(policy) &&
7698 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
7699 cpumask_t *span = rq->rd->span;
7702 * Don't allow tasks with an affinity mask smaller than
7703 * the entire root_domain to become SCHED_DEADLINE. We
7704 * will also fail if there's no bandwidth available.
7706 if (!cpumask_subset(span, p->cpus_ptr) ||
7707 rq->rd->dl_bw.bw == 0) {
7715 /* Re-check policy now with rq lock held: */
7716 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
7717 policy = oldpolicy = -1;
7718 task_rq_unlock(rq, p, &rf);
7720 cpuset_read_unlock();
7725 * If setscheduling to SCHED_DEADLINE (or changing the parameters
7726 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
7729 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
7734 p->sched_reset_on_fork = reset_on_fork;
7737 newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
7740 * Take priority boosted tasks into account. If the new
7741 * effective priority is unchanged, we just store the new
7742 * normal parameters and do not touch the scheduler class and
7743 * the runqueue. This will be done when the task deboost
7746 newprio = rt_effective_prio(p, newprio);
7747 if (newprio == oldprio)
7748 queue_flags &= ~DEQUEUE_MOVE;
7751 queued = task_on_rq_queued(p);
7752 running = task_current(rq, p);
7754 dequeue_task(rq, p, queue_flags);
7756 put_prev_task(rq, p);
7758 prev_class = p->sched_class;
7760 if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
7761 __setscheduler_params(p, attr);
7762 __setscheduler_prio(p, newprio);
7764 __setscheduler_uclamp(p, attr);
7768 * We enqueue to tail when the priority of a task is
7769 * increased (user space view).
7771 if (oldprio < p->prio)
7772 queue_flags |= ENQUEUE_HEAD;
7774 enqueue_task(rq, p, queue_flags);
7777 set_next_task(rq, p);
7779 check_class_changed(rq, p, prev_class, oldprio);
7781 /* Avoid rq from going away on us: */
7783 head = splice_balance_callbacks(rq);
7784 task_rq_unlock(rq, p, &rf);
7787 cpuset_read_unlock();
7788 rt_mutex_adjust_pi(p);
7791 /* Run balance callbacks after we've adjusted the PI chain: */
7792 balance_callbacks(rq, head);
7798 task_rq_unlock(rq, p, &rf);
7800 cpuset_read_unlock();
7804 static int _sched_setscheduler(struct task_struct *p, int policy,
7805 const struct sched_param *param, bool check)
7807 struct sched_attr attr = {
7808 .sched_policy = policy,
7809 .sched_priority = param->sched_priority,
7810 .sched_nice = PRIO_TO_NICE(p->static_prio),
7813 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
7814 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
7815 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
7816 policy &= ~SCHED_RESET_ON_FORK;
7817 attr.sched_policy = policy;
7820 return __sched_setscheduler(p, &attr, check, true);
7823 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
7824 * @p: the task in question.
7825 * @policy: new policy.
7826 * @param: structure containing the new RT priority.
7828 * Use sched_set_fifo(), read its comment.
7830 * Return: 0 on success. An error code otherwise.
7832 * NOTE that the task may be already dead.
7834 int sched_setscheduler(struct task_struct *p, int policy,
7835 const struct sched_param *param)
7837 return _sched_setscheduler(p, policy, param, true);
7840 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
7842 return __sched_setscheduler(p, attr, true, true);
7845 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
7847 return __sched_setscheduler(p, attr, false, true);
7849 EXPORT_SYMBOL_GPL(sched_setattr_nocheck);
7852 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
7853 * @p: the task in question.
7854 * @policy: new policy.
7855 * @param: structure containing the new RT priority.
7857 * Just like sched_setscheduler, only don't bother checking if the
7858 * current context has permission. For example, this is needed in
7859 * stop_machine(): we create temporary high priority worker threads,
7860 * but our caller might not have that capability.
7862 * Return: 0 on success. An error code otherwise.
7864 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
7865 const struct sched_param *param)
7867 return _sched_setscheduler(p, policy, param, false);
7871 * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
7872 * incapable of resource management, which is the one thing an OS really should
7875 * This is of course the reason it is limited to privileged users only.
7877 * Worse still; it is fundamentally impossible to compose static priority
7878 * workloads. You cannot take two correctly working static prio workloads
7879 * and smash them together and still expect them to work.
7881 * For this reason 'all' FIFO tasks the kernel creates are basically at:
7885 * The administrator _MUST_ configure the system, the kernel simply doesn't
7886 * know enough information to make a sensible choice.
7888 void sched_set_fifo(struct task_struct *p)
7890 struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
7891 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7893 EXPORT_SYMBOL_GPL(sched_set_fifo);
7896 * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
7898 void sched_set_fifo_low(struct task_struct *p)
7900 struct sched_param sp = { .sched_priority = 1 };
7901 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7903 EXPORT_SYMBOL_GPL(sched_set_fifo_low);
7905 void sched_set_normal(struct task_struct *p, int nice)
7907 struct sched_attr attr = {
7908 .sched_policy = SCHED_NORMAL,
7911 WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
7913 EXPORT_SYMBOL_GPL(sched_set_normal);
7916 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
7918 struct sched_param lparam;
7919 struct task_struct *p;
7922 if (!param || pid < 0)
7924 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
7929 p = find_process_by_pid(pid);
7935 retval = sched_setscheduler(p, policy, &lparam);
7943 * Mimics kernel/events/core.c perf_copy_attr().
7945 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
7950 /* Zero the full structure, so that a short copy will be nice: */
7951 memset(attr, 0, sizeof(*attr));
7953 ret = get_user(size, &uattr->size);
7957 /* ABI compatibility quirk: */
7959 size = SCHED_ATTR_SIZE_VER0;
7960 if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
7963 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
7970 if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
7971 size < SCHED_ATTR_SIZE_VER1)
7975 * XXX: Do we want to be lenient like existing syscalls; or do we want
7976 * to be strict and return an error on out-of-bounds values?
7978 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
7983 put_user(sizeof(*attr), &uattr->size);
7987 static void get_params(struct task_struct *p, struct sched_attr *attr)
7989 if (task_has_dl_policy(p))
7990 __getparam_dl(p, attr);
7991 else if (task_has_rt_policy(p))
7992 attr->sched_priority = p->rt_priority;
7994 attr->sched_nice = task_nice(p);
7998 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
7999 * @pid: the pid in question.
8000 * @policy: new policy.
8001 * @param: structure containing the new RT priority.
8003 * Return: 0 on success. An error code otherwise.
8005 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
8010 return do_sched_setscheduler(pid, policy, param);
8014 * sys_sched_setparam - set/change the RT priority of a thread
8015 * @pid: the pid in question.
8016 * @param: structure containing the new RT priority.
8018 * Return: 0 on success. An error code otherwise.
8020 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
8022 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
8026 * sys_sched_setattr - same as above, but with extended sched_attr
8027 * @pid: the pid in question.
8028 * @uattr: structure containing the extended parameters.
8029 * @flags: for future extension.
8031 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
8032 unsigned int, flags)
8034 struct sched_attr attr;
8035 struct task_struct *p;
8038 if (!uattr || pid < 0 || flags)
8041 retval = sched_copy_attr(uattr, &attr);
8045 if ((int)attr.sched_policy < 0)
8047 if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
8048 attr.sched_policy = SETPARAM_POLICY;
8052 p = find_process_by_pid(pid);
8058 if (attr.sched_flags & SCHED_FLAG_KEEP_PARAMS)
8059 get_params(p, &attr);
8060 retval = sched_setattr(p, &attr);
8068 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
8069 * @pid: the pid in question.
8071 * Return: On success, the policy of the thread. Otherwise, a negative error
8074 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
8076 struct task_struct *p;
8084 p = find_process_by_pid(pid);
8086 retval = security_task_getscheduler(p);
8089 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
8096 * sys_sched_getparam - get the RT priority of a thread
8097 * @pid: the pid in question.
8098 * @param: structure containing the RT priority.
8100 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
8103 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
8105 struct sched_param lp = { .sched_priority = 0 };
8106 struct task_struct *p;
8109 if (!param || pid < 0)
8113 p = find_process_by_pid(pid);
8118 retval = security_task_getscheduler(p);
8122 if (task_has_rt_policy(p))
8123 lp.sched_priority = p->rt_priority;
8127 * This one might sleep, we cannot do it with a spinlock held ...
8129 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
8139 * Copy the kernel size attribute structure (which might be larger
8140 * than what user-space knows about) to user-space.
8142 * Note that all cases are valid: user-space buffer can be larger or
8143 * smaller than the kernel-space buffer. The usual case is that both
8144 * have the same size.
8147 sched_attr_copy_to_user(struct sched_attr __user *uattr,
8148 struct sched_attr *kattr,
8151 unsigned int ksize = sizeof(*kattr);
8153 if (!access_ok(uattr, usize))
8157 * sched_getattr() ABI forwards and backwards compatibility:
8159 * If usize == ksize then we just copy everything to user-space and all is good.
8161 * If usize < ksize then we only copy as much as user-space has space for,
8162 * this keeps ABI compatibility as well. We skip the rest.
8164 * If usize > ksize then user-space is using a newer version of the ABI,
8165 * which part the kernel doesn't know about. Just ignore it - tooling can
8166 * detect the kernel's knowledge of attributes from the attr->size value
8167 * which is set to ksize in this case.
8169 kattr->size = min(usize, ksize);
8171 if (copy_to_user(uattr, kattr, kattr->size))
8178 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
8179 * @pid: the pid in question.
8180 * @uattr: structure containing the extended parameters.
8181 * @usize: sizeof(attr) for fwd/bwd comp.
8182 * @flags: for future extension.
8184 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
8185 unsigned int, usize, unsigned int, flags)
8187 struct sched_attr kattr = { };
8188 struct task_struct *p;
8191 if (!uattr || pid < 0 || usize > PAGE_SIZE ||
8192 usize < SCHED_ATTR_SIZE_VER0 || flags)
8196 p = find_process_by_pid(pid);
8201 retval = security_task_getscheduler(p);
8205 kattr.sched_policy = p->policy;
8206 if (p->sched_reset_on_fork)
8207 kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
8208 get_params(p, &kattr);
8209 kattr.sched_flags &= SCHED_FLAG_ALL;
8211 #ifdef CONFIG_UCLAMP_TASK
8213 * This could race with another potential updater, but this is fine
8214 * because it'll correctly read the old or the new value. We don't need
8215 * to guarantee who wins the race as long as it doesn't return garbage.
8217 kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
8218 kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
8223 return sched_attr_copy_to_user(uattr, &kattr, usize);
8231 int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
8236 * If the task isn't a deadline task or admission control is
8237 * disabled then we don't care about affinity changes.
8239 if (!task_has_dl_policy(p) || !dl_bandwidth_enabled())
8243 * Since bandwidth control happens on root_domain basis,
8244 * if admission test is enabled, we only admit -deadline
8245 * tasks allowed to run on all the CPUs in the task's
8249 if (!cpumask_subset(task_rq(p)->rd->span, mask))
8257 __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)
8260 cpumask_var_t cpus_allowed, new_mask;
8262 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL))
8265 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
8267 goto out_free_cpus_allowed;
8270 cpuset_cpus_allowed(p, cpus_allowed);
8271 cpumask_and(new_mask, ctx->new_mask, cpus_allowed);
8273 ctx->new_mask = new_mask;
8274 ctx->flags |= SCA_CHECK;
8276 retval = dl_task_check_affinity(p, new_mask);
8278 goto out_free_new_mask;
8280 retval = __set_cpus_allowed_ptr(p, ctx);
8282 goto out_free_new_mask;
8284 cpuset_cpus_allowed(p, cpus_allowed);
8285 if (!cpumask_subset(new_mask, cpus_allowed)) {
8287 * We must have raced with a concurrent cpuset update.
8288 * Just reset the cpumask to the cpuset's cpus_allowed.
8290 cpumask_copy(new_mask, cpus_allowed);
8293 * If SCA_USER is set, a 2nd call to __set_cpus_allowed_ptr()
8294 * will restore the previous user_cpus_ptr value.
8296 * In the unlikely event a previous user_cpus_ptr exists,
8297 * we need to further restrict the mask to what is allowed
8298 * by that old user_cpus_ptr.
8300 if (unlikely((ctx->flags & SCA_USER) && ctx->user_mask)) {
8301 bool empty = !cpumask_and(new_mask, new_mask,
8304 if (WARN_ON_ONCE(empty))
8305 cpumask_copy(new_mask, cpus_allowed);
8307 __set_cpus_allowed_ptr(p, ctx);
8312 free_cpumask_var(new_mask);
8313 out_free_cpus_allowed:
8314 free_cpumask_var(cpus_allowed);
8318 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
8320 struct affinity_context ac;
8321 struct cpumask *user_mask;
8322 struct task_struct *p;
8327 p = find_process_by_pid(pid);
8333 /* Prevent p going away */
8337 if (p->flags & PF_NO_SETAFFINITY) {
8342 if (!check_same_owner(p)) {
8344 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
8352 retval = security_task_setscheduler(p);
8357 * With non-SMP configs, user_cpus_ptr/user_mask isn't used and
8358 * alloc_user_cpus_ptr() returns NULL.
8360 user_mask = alloc_user_cpus_ptr(NUMA_NO_NODE);
8362 cpumask_copy(user_mask, in_mask);
8363 } else if (IS_ENABLED(CONFIG_SMP)) {
8368 ac = (struct affinity_context){
8369 .new_mask = in_mask,
8370 .user_mask = user_mask,
8374 retval = __sched_setaffinity(p, &ac);
8375 kfree(ac.user_mask);
8382 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
8383 struct cpumask *new_mask)
8385 if (len < cpumask_size())
8386 cpumask_clear(new_mask);
8387 else if (len > cpumask_size())
8388 len = cpumask_size();
8390 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
8394 * sys_sched_setaffinity - set the CPU affinity of a process
8395 * @pid: pid of the process
8396 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8397 * @user_mask_ptr: user-space pointer to the new CPU mask
8399 * Return: 0 on success. An error code otherwise.
8401 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
8402 unsigned long __user *, user_mask_ptr)
8404 cpumask_var_t new_mask;
8407 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
8410 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
8412 retval = sched_setaffinity(pid, new_mask);
8413 free_cpumask_var(new_mask);
8417 long sched_getaffinity(pid_t pid, struct cpumask *mask)
8419 struct task_struct *p;
8420 unsigned long flags;
8426 p = find_process_by_pid(pid);
8430 retval = security_task_getscheduler(p);
8434 raw_spin_lock_irqsave(&p->pi_lock, flags);
8435 cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
8436 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
8445 * sys_sched_getaffinity - get the CPU affinity of a process
8446 * @pid: pid of the process
8447 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
8448 * @user_mask_ptr: user-space pointer to hold the current CPU mask
8450 * Return: size of CPU mask copied to user_mask_ptr on success. An
8451 * error code otherwise.
8453 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
8454 unsigned long __user *, user_mask_ptr)
8459 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
8461 if (len & (sizeof(unsigned long)-1))
8464 if (!zalloc_cpumask_var(&mask, GFP_KERNEL))
8467 ret = sched_getaffinity(pid, mask);
8469 unsigned int retlen = min(len, cpumask_size());
8471 if (copy_to_user(user_mask_ptr, cpumask_bits(mask), retlen))
8476 free_cpumask_var(mask);
8481 static void do_sched_yield(void)
8486 rq = this_rq_lock_irq(&rf);
8488 schedstat_inc(rq->yld_count);
8489 current->sched_class->yield_task(rq);
8492 rq_unlock_irq(rq, &rf);
8493 sched_preempt_enable_no_resched();
8499 * sys_sched_yield - yield the current processor to other threads.
8501 * This function yields the current CPU to other tasks. If there are no
8502 * other threads running on this CPU then this function will return.
8506 SYSCALL_DEFINE0(sched_yield)
8512 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
8513 int __sched __cond_resched(void)
8515 if (should_resched(0)) {
8516 preempt_schedule_common();
8520 * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
8521 * whether the current CPU is in an RCU read-side critical section,
8522 * so the tick can report quiescent states even for CPUs looping
8523 * in kernel context. In contrast, in non-preemptible kernels,
8524 * RCU readers leave no in-memory hints, which means that CPU-bound
8525 * processes executing in kernel context might never report an
8526 * RCU quiescent state. Therefore, the following code causes
8527 * cond_resched() to report a quiescent state, but only when RCU
8528 * is in urgent need of one.
8530 #ifndef CONFIG_PREEMPT_RCU
8535 EXPORT_SYMBOL(__cond_resched);
8538 #ifdef CONFIG_PREEMPT_DYNAMIC
8539 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8540 #define cond_resched_dynamic_enabled __cond_resched
8541 #define cond_resched_dynamic_disabled ((void *)&__static_call_return0)
8542 DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
8543 EXPORT_STATIC_CALL_TRAMP(cond_resched);
8545 #define might_resched_dynamic_enabled __cond_resched
8546 #define might_resched_dynamic_disabled ((void *)&__static_call_return0)
8547 DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
8548 EXPORT_STATIC_CALL_TRAMP(might_resched);
8549 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8550 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched);
8551 int __sched dynamic_cond_resched(void)
8553 klp_sched_try_switch();
8554 if (!static_branch_unlikely(&sk_dynamic_cond_resched))
8556 return __cond_resched();
8558 EXPORT_SYMBOL(dynamic_cond_resched);
8560 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched);
8561 int __sched dynamic_might_resched(void)
8563 if (!static_branch_unlikely(&sk_dynamic_might_resched))
8565 return __cond_resched();
8567 EXPORT_SYMBOL(dynamic_might_resched);
8572 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
8573 * call schedule, and on return reacquire the lock.
8575 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
8576 * operations here to prevent schedule() from being called twice (once via
8577 * spin_unlock(), once by hand).
8579 int __cond_resched_lock(spinlock_t *lock)
8581 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8584 lockdep_assert_held(lock);
8586 if (spin_needbreak(lock) || resched) {
8588 if (!_cond_resched())
8595 EXPORT_SYMBOL(__cond_resched_lock);
8597 int __cond_resched_rwlock_read(rwlock_t *lock)
8599 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8602 lockdep_assert_held_read(lock);
8604 if (rwlock_needbreak(lock) || resched) {
8606 if (!_cond_resched())
8613 EXPORT_SYMBOL(__cond_resched_rwlock_read);
8615 int __cond_resched_rwlock_write(rwlock_t *lock)
8617 int resched = should_resched(PREEMPT_LOCK_OFFSET);
8620 lockdep_assert_held_write(lock);
8622 if (rwlock_needbreak(lock) || resched) {
8624 if (!_cond_resched())
8631 EXPORT_SYMBOL(__cond_resched_rwlock_write);
8633 #ifdef CONFIG_PREEMPT_DYNAMIC
8635 #ifdef CONFIG_GENERIC_ENTRY
8636 #include <linux/entry-common.h>
8642 * SC:preempt_schedule
8643 * SC:preempt_schedule_notrace
8644 * SC:irqentry_exit_cond_resched
8648 * cond_resched <- __cond_resched
8649 * might_resched <- RET0
8650 * preempt_schedule <- NOP
8651 * preempt_schedule_notrace <- NOP
8652 * irqentry_exit_cond_resched <- NOP
8655 * cond_resched <- __cond_resched
8656 * might_resched <- __cond_resched
8657 * preempt_schedule <- NOP
8658 * preempt_schedule_notrace <- NOP
8659 * irqentry_exit_cond_resched <- NOP
8662 * cond_resched <- RET0
8663 * might_resched <- RET0
8664 * preempt_schedule <- preempt_schedule
8665 * preempt_schedule_notrace <- preempt_schedule_notrace
8666 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched
8670 preempt_dynamic_undefined = -1,
8671 preempt_dynamic_none,
8672 preempt_dynamic_voluntary,
8673 preempt_dynamic_full,
8676 int preempt_dynamic_mode = preempt_dynamic_undefined;
8678 int sched_dynamic_mode(const char *str)
8680 if (!strcmp(str, "none"))
8681 return preempt_dynamic_none;
8683 if (!strcmp(str, "voluntary"))
8684 return preempt_dynamic_voluntary;
8686 if (!strcmp(str, "full"))
8687 return preempt_dynamic_full;
8692 #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
8693 #define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled)
8694 #define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled)
8695 #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
8696 #define preempt_dynamic_enable(f) static_key_enable(&sk_dynamic_##f.key)
8697 #define preempt_dynamic_disable(f) static_key_disable(&sk_dynamic_##f.key)
8699 #error "Unsupported PREEMPT_DYNAMIC mechanism"
8702 static DEFINE_MUTEX(sched_dynamic_mutex);
8703 static bool klp_override;
8705 static void __sched_dynamic_update(int mode)
8708 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
8709 * the ZERO state, which is invalid.
8712 preempt_dynamic_enable(cond_resched);
8713 preempt_dynamic_enable(might_resched);
8714 preempt_dynamic_enable(preempt_schedule);
8715 preempt_dynamic_enable(preempt_schedule_notrace);
8716 preempt_dynamic_enable(irqentry_exit_cond_resched);
8719 case preempt_dynamic_none:
8721 preempt_dynamic_enable(cond_resched);
8722 preempt_dynamic_disable(might_resched);
8723 preempt_dynamic_disable(preempt_schedule);
8724 preempt_dynamic_disable(preempt_schedule_notrace);
8725 preempt_dynamic_disable(irqentry_exit_cond_resched);
8726 if (mode != preempt_dynamic_mode)
8727 pr_info("Dynamic Preempt: none\n");
8730 case preempt_dynamic_voluntary:
8732 preempt_dynamic_enable(cond_resched);
8733 preempt_dynamic_enable(might_resched);
8734 preempt_dynamic_disable(preempt_schedule);
8735 preempt_dynamic_disable(preempt_schedule_notrace);
8736 preempt_dynamic_disable(irqentry_exit_cond_resched);
8737 if (mode != preempt_dynamic_mode)
8738 pr_info("Dynamic Preempt: voluntary\n");
8741 case preempt_dynamic_full:
8743 preempt_dynamic_disable(cond_resched);
8744 preempt_dynamic_disable(might_resched);
8745 preempt_dynamic_enable(preempt_schedule);
8746 preempt_dynamic_enable(preempt_schedule_notrace);
8747 preempt_dynamic_enable(irqentry_exit_cond_resched);
8748 if (mode != preempt_dynamic_mode)
8749 pr_info("Dynamic Preempt: full\n");
8753 preempt_dynamic_mode = mode;
8756 void sched_dynamic_update(int mode)
8758 mutex_lock(&sched_dynamic_mutex);
8759 __sched_dynamic_update(mode);
8760 mutex_unlock(&sched_dynamic_mutex);
8763 #ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL
8765 static int klp_cond_resched(void)
8767 __klp_sched_try_switch();
8768 return __cond_resched();
8771 void sched_dynamic_klp_enable(void)
8773 mutex_lock(&sched_dynamic_mutex);
8775 klp_override = true;
8776 static_call_update(cond_resched, klp_cond_resched);
8778 mutex_unlock(&sched_dynamic_mutex);
8781 void sched_dynamic_klp_disable(void)
8783 mutex_lock(&sched_dynamic_mutex);
8785 klp_override = false;
8786 __sched_dynamic_update(preempt_dynamic_mode);
8788 mutex_unlock(&sched_dynamic_mutex);
8791 #endif /* CONFIG_HAVE_PREEMPT_DYNAMIC_CALL */
8793 static int __init setup_preempt_mode(char *str)
8795 int mode = sched_dynamic_mode(str);
8797 pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
8801 sched_dynamic_update(mode);
8804 __setup("preempt=", setup_preempt_mode);
8806 static void __init preempt_dynamic_init(void)
8808 if (preempt_dynamic_mode == preempt_dynamic_undefined) {
8809 if (IS_ENABLED(CONFIG_PREEMPT_NONE)) {
8810 sched_dynamic_update(preempt_dynamic_none);
8811 } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) {
8812 sched_dynamic_update(preempt_dynamic_voluntary);
8814 /* Default static call setting, nothing to do */
8815 WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT));
8816 preempt_dynamic_mode = preempt_dynamic_full;
8817 pr_info("Dynamic Preempt: full\n");
8822 #define PREEMPT_MODEL_ACCESSOR(mode) \
8823 bool preempt_model_##mode(void) \
8825 WARN_ON_ONCE(preempt_dynamic_mode == preempt_dynamic_undefined); \
8826 return preempt_dynamic_mode == preempt_dynamic_##mode; \
8828 EXPORT_SYMBOL_GPL(preempt_model_##mode)
8830 PREEMPT_MODEL_ACCESSOR(none);
8831 PREEMPT_MODEL_ACCESSOR(voluntary);
8832 PREEMPT_MODEL_ACCESSOR(full);
8834 #else /* !CONFIG_PREEMPT_DYNAMIC */
8836 static inline void preempt_dynamic_init(void) { }
8838 #endif /* #ifdef CONFIG_PREEMPT_DYNAMIC */
8841 * yield - yield the current processor to other threads.
8843 * Do not ever use this function, there's a 99% chance you're doing it wrong.
8845 * The scheduler is at all times free to pick the calling task as the most
8846 * eligible task to run, if removing the yield() call from your code breaks
8847 * it, it's already broken.
8849 * Typical broken usage is:
8854 * where one assumes that yield() will let 'the other' process run that will
8855 * make event true. If the current task is a SCHED_FIFO task that will never
8856 * happen. Never use yield() as a progress guarantee!!
8858 * If you want to use yield() to wait for something, use wait_event().
8859 * If you want to use yield() to be 'nice' for others, use cond_resched().
8860 * If you still want to use yield(), do not!
8862 void __sched yield(void)
8864 set_current_state(TASK_RUNNING);
8867 EXPORT_SYMBOL(yield);
8870 * yield_to - yield the current processor to another thread in
8871 * your thread group, or accelerate that thread toward the
8872 * processor it's on.
8874 * @preempt: whether task preemption is allowed or not
8876 * It's the caller's job to ensure that the target task struct
8877 * can't go away on us before we can do any checks.
8880 * true (>0) if we indeed boosted the target task.
8881 * false (0) if we failed to boost the target.
8882 * -ESRCH if there's no task to yield to.
8884 int __sched yield_to(struct task_struct *p, bool preempt)
8886 struct task_struct *curr = current;
8887 struct rq *rq, *p_rq;
8888 unsigned long flags;
8891 local_irq_save(flags);
8897 * If we're the only runnable task on the rq and target rq also
8898 * has only one task, there's absolutely no point in yielding.
8900 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
8905 double_rq_lock(rq, p_rq);
8906 if (task_rq(p) != p_rq) {
8907 double_rq_unlock(rq, p_rq);
8911 if (!curr->sched_class->yield_to_task)
8914 if (curr->sched_class != p->sched_class)
8917 if (task_on_cpu(p_rq, p) || !task_is_running(p))
8920 yielded = curr->sched_class->yield_to_task(rq, p);
8922 schedstat_inc(rq->yld_count);
8924 * Make p's CPU reschedule; pick_next_entity takes care of
8927 if (preempt && rq != p_rq)
8932 double_rq_unlock(rq, p_rq);
8934 local_irq_restore(flags);
8941 EXPORT_SYMBOL_GPL(yield_to);
8943 int io_schedule_prepare(void)
8945 int old_iowait = current->in_iowait;
8947 current->in_iowait = 1;
8948 blk_flush_plug(current->plug, true);
8952 void io_schedule_finish(int token)
8954 current->in_iowait = token;
8958 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
8959 * that process accounting knows that this is a task in IO wait state.
8961 long __sched io_schedule_timeout(long timeout)
8966 token = io_schedule_prepare();
8967 ret = schedule_timeout(timeout);
8968 io_schedule_finish(token);
8972 EXPORT_SYMBOL(io_schedule_timeout);
8974 void __sched io_schedule(void)
8978 token = io_schedule_prepare();
8980 io_schedule_finish(token);
8982 EXPORT_SYMBOL(io_schedule);
8985 * sys_sched_get_priority_max - return maximum RT priority.
8986 * @policy: scheduling class.
8988 * Return: On success, this syscall returns the maximum
8989 * rt_priority that can be used by a given scheduling class.
8990 * On failure, a negative error code is returned.
8992 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
8999 ret = MAX_RT_PRIO-1;
9001 case SCHED_DEADLINE:
9012 * sys_sched_get_priority_min - return minimum RT priority.
9013 * @policy: scheduling class.
9015 * Return: On success, this syscall returns the minimum
9016 * rt_priority that can be used by a given scheduling class.
9017 * On failure, a negative error code is returned.
9019 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
9028 case SCHED_DEADLINE:
9037 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
9039 struct task_struct *p;
9040 unsigned int time_slice;
9050 p = find_process_by_pid(pid);
9054 retval = security_task_getscheduler(p);
9058 rq = task_rq_lock(p, &rf);
9060 if (p->sched_class->get_rr_interval)
9061 time_slice = p->sched_class->get_rr_interval(rq, p);
9062 task_rq_unlock(rq, p, &rf);
9065 jiffies_to_timespec64(time_slice, t);
9074 * sys_sched_rr_get_interval - return the default timeslice of a process.
9075 * @pid: pid of the process.
9076 * @interval: userspace pointer to the timeslice value.
9078 * this syscall writes the default timeslice value of a given process
9079 * into the user-space timespec buffer. A value of '0' means infinity.
9081 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
9084 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
9085 struct __kernel_timespec __user *, interval)
9087 struct timespec64 t;
9088 int retval = sched_rr_get_interval(pid, &t);
9091 retval = put_timespec64(&t, interval);
9096 #ifdef CONFIG_COMPAT_32BIT_TIME
9097 SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
9098 struct old_timespec32 __user *, interval)
9100 struct timespec64 t;
9101 int retval = sched_rr_get_interval(pid, &t);
9104 retval = put_old_timespec32(&t, interval);
9109 void sched_show_task(struct task_struct *p)
9111 unsigned long free = 0;
9114 if (!try_get_task_stack(p))
9117 pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
9119 if (task_is_running(p))
9120 pr_cont(" running task ");
9121 #ifdef CONFIG_DEBUG_STACK_USAGE
9122 free = stack_not_used(p);
9127 ppid = task_pid_nr(rcu_dereference(p->real_parent));
9129 pr_cont(" stack:%-5lu pid:%-5d ppid:%-6d flags:0x%08lx\n",
9130 free, task_pid_nr(p), ppid,
9131 read_task_thread_flags(p));
9133 print_worker_info(KERN_INFO, p);
9134 print_stop_info(KERN_INFO, p);
9135 show_stack(p, NULL, KERN_INFO);
9138 EXPORT_SYMBOL_GPL(sched_show_task);
9141 state_filter_match(unsigned long state_filter, struct task_struct *p)
9143 unsigned int state = READ_ONCE(p->__state);
9145 /* no filter, everything matches */
9149 /* filter, but doesn't match */
9150 if (!(state & state_filter))
9154 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
9157 if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD))
9164 void show_state_filter(unsigned int state_filter)
9166 struct task_struct *g, *p;
9169 for_each_process_thread(g, p) {
9171 * reset the NMI-timeout, listing all files on a slow
9172 * console might take a lot of time:
9173 * Also, reset softlockup watchdogs on all CPUs, because
9174 * another CPU might be blocked waiting for us to process
9177 touch_nmi_watchdog();
9178 touch_all_softlockup_watchdogs();
9179 if (state_filter_match(state_filter, p))
9183 #ifdef CONFIG_SCHED_DEBUG
9185 sysrq_sched_debug_show();
9189 * Only show locks if all tasks are dumped:
9192 debug_show_all_locks();
9196 * init_idle - set up an idle thread for a given CPU
9197 * @idle: task in question
9198 * @cpu: CPU the idle task belongs to
9200 * NOTE: this function does not set the idle thread's NEED_RESCHED
9201 * flag, to make booting more robust.
9203 void __init init_idle(struct task_struct *idle, int cpu)
9206 struct affinity_context ac = (struct affinity_context) {
9207 .new_mask = cpumask_of(cpu),
9211 struct rq *rq = cpu_rq(cpu);
9212 unsigned long flags;
9214 __sched_fork(0, idle);
9216 raw_spin_lock_irqsave(&idle->pi_lock, flags);
9217 raw_spin_rq_lock(rq);
9219 idle->__state = TASK_RUNNING;
9220 idle->se.exec_start = sched_clock();
9222 * PF_KTHREAD should already be set at this point; regardless, make it
9223 * look like a proper per-CPU kthread.
9225 idle->flags |= PF_IDLE | PF_KTHREAD | PF_NO_SETAFFINITY;
9226 kthread_set_per_cpu(idle, cpu);
9230 * It's possible that init_idle() gets called multiple times on a task,
9231 * in that case do_set_cpus_allowed() will not do the right thing.
9233 * And since this is boot we can forgo the serialization.
9235 set_cpus_allowed_common(idle, &ac);
9238 * We're having a chicken and egg problem, even though we are
9239 * holding rq->lock, the CPU isn't yet set to this CPU so the
9240 * lockdep check in task_group() will fail.
9242 * Similar case to sched_fork(). / Alternatively we could
9243 * use task_rq_lock() here and obtain the other rq->lock.
9248 __set_task_cpu(idle, cpu);
9252 rcu_assign_pointer(rq->curr, idle);
9253 idle->on_rq = TASK_ON_RQ_QUEUED;
9257 raw_spin_rq_unlock(rq);
9258 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
9260 /* Set the preempt count _outside_ the spinlocks! */
9261 init_idle_preempt_count(idle, cpu);
9264 * The idle tasks have their own, simple scheduling class:
9266 idle->sched_class = &idle_sched_class;
9267 ftrace_graph_init_idle_task(idle, cpu);
9268 vtime_init_idle(idle, cpu);
9270 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
9276 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
9277 const struct cpumask *trial)
9281 if (cpumask_empty(cur))
9284 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
9289 int task_can_attach(struct task_struct *p,
9290 const struct cpumask *cs_effective_cpus)
9295 * Kthreads which disallow setaffinity shouldn't be moved
9296 * to a new cpuset; we don't want to change their CPU
9297 * affinity and isolating such threads by their set of
9298 * allowed nodes is unnecessary. Thus, cpusets are not
9299 * applicable for such threads. This prevents checking for
9300 * success of set_cpus_allowed_ptr() on all attached tasks
9301 * before cpus_mask may be changed.
9303 if (p->flags & PF_NO_SETAFFINITY) {
9308 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
9309 cs_effective_cpus)) {
9310 int cpu = cpumask_any_and(cpu_active_mask, cs_effective_cpus);
9312 if (unlikely(cpu >= nr_cpu_ids))
9314 ret = dl_cpu_busy(cpu, p);
9321 bool sched_smp_initialized __read_mostly;
9323 #ifdef CONFIG_NUMA_BALANCING
9324 /* Migrate current task p to target_cpu */
9325 int migrate_task_to(struct task_struct *p, int target_cpu)
9327 struct migration_arg arg = { p, target_cpu };
9328 int curr_cpu = task_cpu(p);
9330 if (curr_cpu == target_cpu)
9333 if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
9336 /* TODO: This is not properly updating schedstats */
9338 trace_sched_move_numa(p, curr_cpu, target_cpu);
9339 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
9343 * Requeue a task on a given node and accurately track the number of NUMA
9344 * tasks on the runqueues
9346 void sched_setnuma(struct task_struct *p, int nid)
9348 bool queued, running;
9352 rq = task_rq_lock(p, &rf);
9353 queued = task_on_rq_queued(p);
9354 running = task_current(rq, p);
9357 dequeue_task(rq, p, DEQUEUE_SAVE);
9359 put_prev_task(rq, p);
9361 p->numa_preferred_nid = nid;
9364 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
9366 set_next_task(rq, p);
9367 task_rq_unlock(rq, p, &rf);
9369 #endif /* CONFIG_NUMA_BALANCING */
9371 #ifdef CONFIG_HOTPLUG_CPU
9373 * Ensure that the idle task is using init_mm right before its CPU goes
9376 void idle_task_exit(void)
9378 struct mm_struct *mm = current->active_mm;
9380 BUG_ON(cpu_online(smp_processor_id()));
9381 BUG_ON(current != this_rq()->idle);
9383 if (mm != &init_mm) {
9384 switch_mm(mm, &init_mm, current);
9385 finish_arch_post_lock_switch();
9388 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
9391 static int __balance_push_cpu_stop(void *arg)
9393 struct task_struct *p = arg;
9394 struct rq *rq = this_rq();
9398 raw_spin_lock_irq(&p->pi_lock);
9401 update_rq_clock(rq);
9403 if (task_rq(p) == rq && task_on_rq_queued(p)) {
9404 cpu = select_fallback_rq(rq->cpu, p);
9405 rq = __migrate_task(rq, &rf, p, cpu);
9409 raw_spin_unlock_irq(&p->pi_lock);
9416 static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
9419 * Ensure we only run per-cpu kthreads once the CPU goes !active.
9421 * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
9422 * effective when the hotplug motion is down.
9424 static void balance_push(struct rq *rq)
9426 struct task_struct *push_task = rq->curr;
9428 lockdep_assert_rq_held(rq);
9431 * Ensure the thing is persistent until balance_push_set(.on = false);
9433 rq->balance_callback = &balance_push_callback;
9436 * Only active while going offline and when invoked on the outgoing
9439 if (!cpu_dying(rq->cpu) || rq != this_rq())
9443 * Both the cpu-hotplug and stop task are in this case and are
9444 * required to complete the hotplug process.
9446 if (kthread_is_per_cpu(push_task) ||
9447 is_migration_disabled(push_task)) {
9450 * If this is the idle task on the outgoing CPU try to wake
9451 * up the hotplug control thread which might wait for the
9452 * last task to vanish. The rcuwait_active() check is
9453 * accurate here because the waiter is pinned on this CPU
9454 * and can't obviously be running in parallel.
9456 * On RT kernels this also has to check whether there are
9457 * pinned and scheduled out tasks on the runqueue. They
9458 * need to leave the migrate disabled section first.
9460 if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
9461 rcuwait_active(&rq->hotplug_wait)) {
9462 raw_spin_rq_unlock(rq);
9463 rcuwait_wake_up(&rq->hotplug_wait);
9464 raw_spin_rq_lock(rq);
9469 get_task_struct(push_task);
9471 * Temporarily drop rq->lock such that we can wake-up the stop task.
9472 * Both preemption and IRQs are still disabled.
9474 raw_spin_rq_unlock(rq);
9475 stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
9476 this_cpu_ptr(&push_work));
9478 * At this point need_resched() is true and we'll take the loop in
9479 * schedule(). The next pick is obviously going to be the stop task
9480 * which kthread_is_per_cpu() and will push this task away.
9482 raw_spin_rq_lock(rq);
9485 static void balance_push_set(int cpu, bool on)
9487 struct rq *rq = cpu_rq(cpu);
9490 rq_lock_irqsave(rq, &rf);
9492 WARN_ON_ONCE(rq->balance_callback);
9493 rq->balance_callback = &balance_push_callback;
9494 } else if (rq->balance_callback == &balance_push_callback) {
9495 rq->balance_callback = NULL;
9497 rq_unlock_irqrestore(rq, &rf);
9501 * Invoked from a CPUs hotplug control thread after the CPU has been marked
9502 * inactive. All tasks which are not per CPU kernel threads are either
9503 * pushed off this CPU now via balance_push() or placed on a different CPU
9504 * during wakeup. Wait until the CPU is quiescent.
9506 static void balance_hotplug_wait(void)
9508 struct rq *rq = this_rq();
9510 rcuwait_wait_event(&rq->hotplug_wait,
9511 rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
9512 TASK_UNINTERRUPTIBLE);
9517 static inline void balance_push(struct rq *rq)
9521 static inline void balance_push_set(int cpu, bool on)
9525 static inline void balance_hotplug_wait(void)
9529 #endif /* CONFIG_HOTPLUG_CPU */
9531 void set_rq_online(struct rq *rq)
9534 const struct sched_class *class;
9536 cpumask_set_cpu(rq->cpu, rq->rd->online);
9539 for_each_class(class) {
9540 if (class->rq_online)
9541 class->rq_online(rq);
9546 void set_rq_offline(struct rq *rq)
9549 const struct sched_class *class;
9551 for_each_class(class) {
9552 if (class->rq_offline)
9553 class->rq_offline(rq);
9556 cpumask_clear_cpu(rq->cpu, rq->rd->online);
9562 * used to mark begin/end of suspend/resume:
9564 static int num_cpus_frozen;
9567 * Update cpusets according to cpu_active mask. If cpusets are
9568 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
9569 * around partition_sched_domains().
9571 * If we come here as part of a suspend/resume, don't touch cpusets because we
9572 * want to restore it back to its original state upon resume anyway.
9574 static void cpuset_cpu_active(void)
9576 if (cpuhp_tasks_frozen) {
9578 * num_cpus_frozen tracks how many CPUs are involved in suspend
9579 * resume sequence. As long as this is not the last online
9580 * operation in the resume sequence, just build a single sched
9581 * domain, ignoring cpusets.
9583 partition_sched_domains(1, NULL, NULL);
9584 if (--num_cpus_frozen)
9587 * This is the last CPU online operation. So fall through and
9588 * restore the original sched domains by considering the
9589 * cpuset configurations.
9591 cpuset_force_rebuild();
9593 cpuset_update_active_cpus();
9596 static int cpuset_cpu_inactive(unsigned int cpu)
9598 if (!cpuhp_tasks_frozen) {
9599 int ret = dl_cpu_busy(cpu, NULL);
9603 cpuset_update_active_cpus();
9606 partition_sched_domains(1, NULL, NULL);
9611 int sched_cpu_activate(unsigned int cpu)
9613 struct rq *rq = cpu_rq(cpu);
9617 * Clear the balance_push callback and prepare to schedule
9620 balance_push_set(cpu, false);
9622 #ifdef CONFIG_SCHED_SMT
9624 * When going up, increment the number of cores with SMT present.
9626 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9627 static_branch_inc_cpuslocked(&sched_smt_present);
9629 set_cpu_active(cpu, true);
9631 if (sched_smp_initialized) {
9632 sched_update_numa(cpu, true);
9633 sched_domains_numa_masks_set(cpu);
9634 cpuset_cpu_active();
9638 * Put the rq online, if not already. This happens:
9640 * 1) In the early boot process, because we build the real domains
9641 * after all CPUs have been brought up.
9643 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
9646 rq_lock_irqsave(rq, &rf);
9648 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9651 rq_unlock_irqrestore(rq, &rf);
9656 int sched_cpu_deactivate(unsigned int cpu)
9658 struct rq *rq = cpu_rq(cpu);
9663 * Remove CPU from nohz.idle_cpus_mask to prevent participating in
9664 * load balancing when not active
9666 nohz_balance_exit_idle(rq);
9668 set_cpu_active(cpu, false);
9671 * From this point forward, this CPU will refuse to run any task that
9672 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
9673 * push those tasks away until this gets cleared, see
9674 * sched_cpu_dying().
9676 balance_push_set(cpu, true);
9679 * We've cleared cpu_active_mask / set balance_push, wait for all
9680 * preempt-disabled and RCU users of this state to go away such that
9681 * all new such users will observe it.
9683 * Specifically, we rely on ttwu to no longer target this CPU, see
9684 * ttwu_queue_cond() and is_cpu_allowed().
9686 * Do sync before park smpboot threads to take care the rcu boost case.
9690 rq_lock_irqsave(rq, &rf);
9692 update_rq_clock(rq);
9693 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
9696 rq_unlock_irqrestore(rq, &rf);
9698 #ifdef CONFIG_SCHED_SMT
9700 * When going down, decrement the number of cores with SMT present.
9702 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
9703 static_branch_dec_cpuslocked(&sched_smt_present);
9705 sched_core_cpu_deactivate(cpu);
9708 if (!sched_smp_initialized)
9711 sched_update_numa(cpu, false);
9712 ret = cpuset_cpu_inactive(cpu);
9714 balance_push_set(cpu, false);
9715 set_cpu_active(cpu, true);
9716 sched_update_numa(cpu, true);
9719 sched_domains_numa_masks_clear(cpu);
9723 static void sched_rq_cpu_starting(unsigned int cpu)
9725 struct rq *rq = cpu_rq(cpu);
9727 rq->calc_load_update = calc_load_update;
9728 update_max_interval();
9731 int sched_cpu_starting(unsigned int cpu)
9733 sched_core_cpu_starting(cpu);
9734 sched_rq_cpu_starting(cpu);
9735 sched_tick_start(cpu);
9739 #ifdef CONFIG_HOTPLUG_CPU
9742 * Invoked immediately before the stopper thread is invoked to bring the
9743 * CPU down completely. At this point all per CPU kthreads except the
9744 * hotplug thread (current) and the stopper thread (inactive) have been
9745 * either parked or have been unbound from the outgoing CPU. Ensure that
9746 * any of those which might be on the way out are gone.
9748 * If after this point a bound task is being woken on this CPU then the
9749 * responsible hotplug callback has failed to do it's job.
9750 * sched_cpu_dying() will catch it with the appropriate fireworks.
9752 int sched_cpu_wait_empty(unsigned int cpu)
9754 balance_hotplug_wait();
9759 * Since this CPU is going 'away' for a while, fold any nr_active delta we
9760 * might have. Called from the CPU stopper task after ensuring that the
9761 * stopper is the last running task on the CPU, so nr_active count is
9762 * stable. We need to take the teardown thread which is calling this into
9763 * account, so we hand in adjust = 1 to the load calculation.
9765 * Also see the comment "Global load-average calculations".
9767 static void calc_load_migrate(struct rq *rq)
9769 long delta = calc_load_fold_active(rq, 1);
9772 atomic_long_add(delta, &calc_load_tasks);
9775 static void dump_rq_tasks(struct rq *rq, const char *loglvl)
9777 struct task_struct *g, *p;
9778 int cpu = cpu_of(rq);
9780 lockdep_assert_rq_held(rq);
9782 printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
9783 for_each_process_thread(g, p) {
9784 if (task_cpu(p) != cpu)
9787 if (!task_on_rq_queued(p))
9790 printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
9794 int sched_cpu_dying(unsigned int cpu)
9796 struct rq *rq = cpu_rq(cpu);
9799 /* Handle pending wakeups and then migrate everything off */
9800 sched_tick_stop(cpu);
9802 rq_lock_irqsave(rq, &rf);
9803 if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
9804 WARN(true, "Dying CPU not properly vacated!");
9805 dump_rq_tasks(rq, KERN_WARNING);
9807 rq_unlock_irqrestore(rq, &rf);
9809 calc_load_migrate(rq);
9810 update_max_interval();
9812 sched_core_cpu_dying(cpu);
9817 void __init sched_init_smp(void)
9819 sched_init_numa(NUMA_NO_NODE);
9822 * There's no userspace yet to cause hotplug operations; hence all the
9823 * CPU masks are stable and all blatant races in the below code cannot
9826 mutex_lock(&sched_domains_mutex);
9827 sched_init_domains(cpu_active_mask);
9828 mutex_unlock(&sched_domains_mutex);
9830 /* Move init over to a non-isolated CPU */
9831 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0)
9833 current->flags &= ~PF_NO_SETAFFINITY;
9834 sched_init_granularity();
9836 init_sched_rt_class();
9837 init_sched_dl_class();
9839 sched_smp_initialized = true;
9842 static int __init migration_init(void)
9844 sched_cpu_starting(smp_processor_id());
9847 early_initcall(migration_init);
9850 void __init sched_init_smp(void)
9852 sched_init_granularity();
9854 #endif /* CONFIG_SMP */
9856 int in_sched_functions(unsigned long addr)
9858 return in_lock_functions(addr) ||
9859 (addr >= (unsigned long)__sched_text_start
9860 && addr < (unsigned long)__sched_text_end);
9863 #ifdef CONFIG_CGROUP_SCHED
9865 * Default task group.
9866 * Every task in system belongs to this group at bootup.
9868 struct task_group root_task_group;
9869 LIST_HEAD(task_groups);
9871 /* Cacheline aligned slab cache for task_group */
9872 static struct kmem_cache *task_group_cache __read_mostly;
9875 void __init sched_init(void)
9877 unsigned long ptr = 0;
9880 /* Make sure the linker didn't screw up */
9881 BUG_ON(&idle_sched_class != &fair_sched_class + 1 ||
9882 &fair_sched_class != &rt_sched_class + 1 ||
9883 &rt_sched_class != &dl_sched_class + 1);
9885 BUG_ON(&dl_sched_class != &stop_sched_class + 1);
9890 #ifdef CONFIG_FAIR_GROUP_SCHED
9891 ptr += 2 * nr_cpu_ids * sizeof(void **);
9893 #ifdef CONFIG_RT_GROUP_SCHED
9894 ptr += 2 * nr_cpu_ids * sizeof(void **);
9897 ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
9899 #ifdef CONFIG_FAIR_GROUP_SCHED
9900 root_task_group.se = (struct sched_entity **)ptr;
9901 ptr += nr_cpu_ids * sizeof(void **);
9903 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
9904 ptr += nr_cpu_ids * sizeof(void **);
9906 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
9907 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
9908 #endif /* CONFIG_FAIR_GROUP_SCHED */
9909 #ifdef CONFIG_RT_GROUP_SCHED
9910 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
9911 ptr += nr_cpu_ids * sizeof(void **);
9913 root_task_group.rt_rq = (struct rt_rq **)ptr;
9914 ptr += nr_cpu_ids * sizeof(void **);
9916 #endif /* CONFIG_RT_GROUP_SCHED */
9919 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
9922 init_defrootdomain();
9925 #ifdef CONFIG_RT_GROUP_SCHED
9926 init_rt_bandwidth(&root_task_group.rt_bandwidth,
9927 global_rt_period(), global_rt_runtime());
9928 #endif /* CONFIG_RT_GROUP_SCHED */
9930 #ifdef CONFIG_CGROUP_SCHED
9931 task_group_cache = KMEM_CACHE(task_group, 0);
9933 list_add(&root_task_group.list, &task_groups);
9934 INIT_LIST_HEAD(&root_task_group.children);
9935 INIT_LIST_HEAD(&root_task_group.siblings);
9936 autogroup_init(&init_task);
9937 #endif /* CONFIG_CGROUP_SCHED */
9939 for_each_possible_cpu(i) {
9943 raw_spin_lock_init(&rq->__lock);
9945 rq->calc_load_active = 0;
9946 rq->calc_load_update = jiffies + LOAD_FREQ;
9947 init_cfs_rq(&rq->cfs);
9948 init_rt_rq(&rq->rt);
9949 init_dl_rq(&rq->dl);
9950 #ifdef CONFIG_FAIR_GROUP_SCHED
9951 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9952 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
9954 * How much CPU bandwidth does root_task_group get?
9956 * In case of task-groups formed thr' the cgroup filesystem, it
9957 * gets 100% of the CPU resources in the system. This overall
9958 * system CPU resource is divided among the tasks of
9959 * root_task_group and its child task-groups in a fair manner,
9960 * based on each entity's (task or task-group's) weight
9961 * (se->load.weight).
9963 * In other words, if root_task_group has 10 tasks of weight
9964 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9965 * then A0's share of the CPU resource is:
9967 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9969 * We achieve this by letting root_task_group's tasks sit
9970 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
9972 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
9973 #endif /* CONFIG_FAIR_GROUP_SCHED */
9975 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
9976 #ifdef CONFIG_RT_GROUP_SCHED
9977 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
9982 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
9983 rq->balance_callback = &balance_push_callback;
9984 rq->active_balance = 0;
9985 rq->next_balance = jiffies;
9990 rq->avg_idle = 2*sysctl_sched_migration_cost;
9991 rq->wake_stamp = jiffies;
9992 rq->wake_avg_idle = rq->avg_idle;
9993 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
9995 INIT_LIST_HEAD(&rq->cfs_tasks);
9997 rq_attach_root(rq, &def_root_domain);
9998 #ifdef CONFIG_NO_HZ_COMMON
9999 rq->last_blocked_load_update_tick = jiffies;
10000 atomic_set(&rq->nohz_flags, 0);
10002 INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
10004 #ifdef CONFIG_HOTPLUG_CPU
10005 rcuwait_init(&rq->hotplug_wait);
10007 #endif /* CONFIG_SMP */
10008 hrtick_rq_init(rq);
10009 atomic_set(&rq->nr_iowait, 0);
10011 #ifdef CONFIG_SCHED_CORE
10013 rq->core_pick = NULL;
10014 rq->core_enabled = 0;
10015 rq->core_tree = RB_ROOT;
10016 rq->core_forceidle_count = 0;
10017 rq->core_forceidle_occupation = 0;
10018 rq->core_forceidle_start = 0;
10020 rq->core_cookie = 0UL;
10022 zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i));
10025 set_load_weight(&init_task, false);
10028 * The boot idle thread does lazy MMU switching as well:
10030 mmgrab_lazy_tlb(&init_mm);
10031 enter_lazy_tlb(&init_mm, current);
10034 * The idle task doesn't need the kthread struct to function, but it
10035 * is dressed up as a per-CPU kthread and thus needs to play the part
10036 * if we want to avoid special-casing it in code that deals with per-CPU
10039 WARN_ON(!set_kthread_struct(current));
10042 * Make us the idle thread. Technically, schedule() should not be
10043 * called from this thread, however somewhere below it might be,
10044 * but because we are the idle thread, we just pick up running again
10045 * when this runqueue becomes "idle".
10047 init_idle(current, smp_processor_id());
10049 calc_load_update = jiffies + LOAD_FREQ;
10052 idle_thread_set_boot_cpu();
10053 balance_push_set(smp_processor_id(), false);
10055 init_sched_fair_class();
10061 preempt_dynamic_init();
10063 scheduler_running = 1;
10066 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
10068 void __might_sleep(const char *file, int line)
10070 unsigned int state = get_current_state();
10072 * Blocking primitives will set (and therefore destroy) current->state,
10073 * since we will exit with TASK_RUNNING make sure we enter with it,
10074 * otherwise we will destroy state.
10076 WARN_ONCE(state != TASK_RUNNING && current->task_state_change,
10077 "do not call blocking ops when !TASK_RUNNING; "
10078 "state=%x set at [<%p>] %pS\n", state,
10079 (void *)current->task_state_change,
10080 (void *)current->task_state_change);
10082 __might_resched(file, line, 0);
10084 EXPORT_SYMBOL(__might_sleep);
10086 static void print_preempt_disable_ip(int preempt_offset, unsigned long ip)
10088 if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT))
10091 if (preempt_count() == preempt_offset)
10094 pr_err("Preemption disabled at:");
10095 print_ip_sym(KERN_ERR, ip);
10098 static inline bool resched_offsets_ok(unsigned int offsets)
10100 unsigned int nested = preempt_count();
10102 nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT;
10104 return nested == offsets;
10107 void __might_resched(const char *file, int line, unsigned int offsets)
10109 /* Ratelimiting timestamp: */
10110 static unsigned long prev_jiffy;
10112 unsigned long preempt_disable_ip;
10114 /* WARN_ON_ONCE() by default, no rate limit required: */
10117 if ((resched_offsets_ok(offsets) && !irqs_disabled() &&
10118 !is_idle_task(current) && !current->non_block_count) ||
10119 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
10123 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
10125 prev_jiffy = jiffies;
10127 /* Save this before calling printk(), since that will clobber it: */
10128 preempt_disable_ip = get_preempt_disable_ip(current);
10130 pr_err("BUG: sleeping function called from invalid context at %s:%d\n",
10132 pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
10133 in_atomic(), irqs_disabled(), current->non_block_count,
10134 current->pid, current->comm);
10135 pr_err("preempt_count: %x, expected: %x\n", preempt_count(),
10136 offsets & MIGHT_RESCHED_PREEMPT_MASK);
10138 if (IS_ENABLED(CONFIG_PREEMPT_RCU)) {
10139 pr_err("RCU nest depth: %d, expected: %u\n",
10140 rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT);
10143 if (task_stack_end_corrupted(current))
10144 pr_emerg("Thread overran stack, or stack corrupted\n");
10146 debug_show_held_locks(current);
10147 if (irqs_disabled())
10148 print_irqtrace_events(current);
10150 print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK,
10151 preempt_disable_ip);
10154 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
10156 EXPORT_SYMBOL(__might_resched);
10158 void __cant_sleep(const char *file, int line, int preempt_offset)
10160 static unsigned long prev_jiffy;
10162 if (irqs_disabled())
10165 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
10168 if (preempt_count() > preempt_offset)
10171 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
10173 prev_jiffy = jiffies;
10175 printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
10176 printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
10177 in_atomic(), irqs_disabled(),
10178 current->pid, current->comm);
10180 debug_show_held_locks(current);
10182 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
10184 EXPORT_SYMBOL_GPL(__cant_sleep);
10187 void __cant_migrate(const char *file, int line)
10189 static unsigned long prev_jiffy;
10191 if (irqs_disabled())
10194 if (is_migration_disabled(current))
10197 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
10200 if (preempt_count() > 0)
10203 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
10205 prev_jiffy = jiffies;
10207 pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
10208 pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
10209 in_atomic(), irqs_disabled(), is_migration_disabled(current),
10210 current->pid, current->comm);
10212 debug_show_held_locks(current);
10214 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
10216 EXPORT_SYMBOL_GPL(__cant_migrate);
10220 #ifdef CONFIG_MAGIC_SYSRQ
10221 void normalize_rt_tasks(void)
10223 struct task_struct *g, *p;
10224 struct sched_attr attr = {
10225 .sched_policy = SCHED_NORMAL,
10228 read_lock(&tasklist_lock);
10229 for_each_process_thread(g, p) {
10231 * Only normalize user tasks:
10233 if (p->flags & PF_KTHREAD)
10236 p->se.exec_start = 0;
10237 schedstat_set(p->stats.wait_start, 0);
10238 schedstat_set(p->stats.sleep_start, 0);
10239 schedstat_set(p->stats.block_start, 0);
10241 if (!dl_task(p) && !rt_task(p)) {
10243 * Renice negative nice level userspace
10246 if (task_nice(p) < 0)
10247 set_user_nice(p, 0);
10251 __sched_setscheduler(p, &attr, false, false);
10253 read_unlock(&tasklist_lock);
10256 #endif /* CONFIG_MAGIC_SYSRQ */
10258 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
10260 * These functions are only useful for the IA64 MCA handling, or kdb.
10262 * They can only be called when the whole system has been
10263 * stopped - every CPU needs to be quiescent, and no scheduling
10264 * activity can take place. Using them for anything else would
10265 * be a serious bug, and as a result, they aren't even visible
10266 * under any other configuration.
10270 * curr_task - return the current task for a given CPU.
10271 * @cpu: the processor in question.
10273 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
10275 * Return: The current task for @cpu.
10277 struct task_struct *curr_task(int cpu)
10279 return cpu_curr(cpu);
10282 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
10286 * ia64_set_curr_task - set the current task for a given CPU.
10287 * @cpu: the processor in question.
10288 * @p: the task pointer to set.
10290 * Description: This function must only be used when non-maskable interrupts
10291 * are serviced on a separate stack. It allows the architecture to switch the
10292 * notion of the current task on a CPU in a non-blocking manner. This function
10293 * must be called with all CPU's synchronized, and interrupts disabled, the
10294 * and caller must save the original value of the current task (see
10295 * curr_task() above) and restore that value before reenabling interrupts and
10296 * re-starting the system.
10298 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
10300 void ia64_set_curr_task(int cpu, struct task_struct *p)
10307 #ifdef CONFIG_CGROUP_SCHED
10308 /* task_group_lock serializes the addition/removal of task groups */
10309 static DEFINE_SPINLOCK(task_group_lock);
10311 static inline void alloc_uclamp_sched_group(struct task_group *tg,
10312 struct task_group *parent)
10314 #ifdef CONFIG_UCLAMP_TASK_GROUP
10315 enum uclamp_id clamp_id;
10317 for_each_clamp_id(clamp_id) {
10318 uclamp_se_set(&tg->uclamp_req[clamp_id],
10319 uclamp_none(clamp_id), false);
10320 tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
10325 static void sched_free_group(struct task_group *tg)
10327 free_fair_sched_group(tg);
10328 free_rt_sched_group(tg);
10329 autogroup_free(tg);
10330 kmem_cache_free(task_group_cache, tg);
10333 static void sched_free_group_rcu(struct rcu_head *rcu)
10335 sched_free_group(container_of(rcu, struct task_group, rcu));
10338 static void sched_unregister_group(struct task_group *tg)
10340 unregister_fair_sched_group(tg);
10341 unregister_rt_sched_group(tg);
10343 * We have to wait for yet another RCU grace period to expire, as
10344 * print_cfs_stats() might run concurrently.
10346 call_rcu(&tg->rcu, sched_free_group_rcu);
10349 /* allocate runqueue etc for a new task group */
10350 struct task_group *sched_create_group(struct task_group *parent)
10352 struct task_group *tg;
10354 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
10356 return ERR_PTR(-ENOMEM);
10358 if (!alloc_fair_sched_group(tg, parent))
10361 if (!alloc_rt_sched_group(tg, parent))
10364 alloc_uclamp_sched_group(tg, parent);
10369 sched_free_group(tg);
10370 return ERR_PTR(-ENOMEM);
10373 void sched_online_group(struct task_group *tg, struct task_group *parent)
10375 unsigned long flags;
10377 spin_lock_irqsave(&task_group_lock, flags);
10378 list_add_rcu(&tg->list, &task_groups);
10380 /* Root should already exist: */
10383 tg->parent = parent;
10384 INIT_LIST_HEAD(&tg->children);
10385 list_add_rcu(&tg->siblings, &parent->children);
10386 spin_unlock_irqrestore(&task_group_lock, flags);
10388 online_fair_sched_group(tg);
10391 /* rcu callback to free various structures associated with a task group */
10392 static void sched_unregister_group_rcu(struct rcu_head *rhp)
10394 /* Now it should be safe to free those cfs_rqs: */
10395 sched_unregister_group(container_of(rhp, struct task_group, rcu));
10398 void sched_destroy_group(struct task_group *tg)
10400 /* Wait for possible concurrent references to cfs_rqs complete: */
10401 call_rcu(&tg->rcu, sched_unregister_group_rcu);
10404 void sched_release_group(struct task_group *tg)
10406 unsigned long flags;
10409 * Unlink first, to avoid walk_tg_tree_from() from finding us (via
10410 * sched_cfs_period_timer()).
10412 * For this to be effective, we have to wait for all pending users of
10413 * this task group to leave their RCU critical section to ensure no new
10414 * user will see our dying task group any more. Specifically ensure
10415 * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
10417 * We therefore defer calling unregister_fair_sched_group() to
10418 * sched_unregister_group() which is guarantied to get called only after the
10419 * current RCU grace period has expired.
10421 spin_lock_irqsave(&task_group_lock, flags);
10422 list_del_rcu(&tg->list);
10423 list_del_rcu(&tg->siblings);
10424 spin_unlock_irqrestore(&task_group_lock, flags);
10427 static struct task_group *sched_get_task_group(struct task_struct *tsk)
10429 struct task_group *tg;
10432 * All callers are synchronized by task_rq_lock(); we do not use RCU
10433 * which is pointless here. Thus, we pass "true" to task_css_check()
10434 * to prevent lockdep warnings.
10436 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
10437 struct task_group, css);
10438 tg = autogroup_task_group(tsk, tg);
10443 static void sched_change_group(struct task_struct *tsk, struct task_group *group)
10445 tsk->sched_task_group = group;
10447 #ifdef CONFIG_FAIR_GROUP_SCHED
10448 if (tsk->sched_class->task_change_group)
10449 tsk->sched_class->task_change_group(tsk);
10452 set_task_rq(tsk, task_cpu(tsk));
10456 * Change task's runqueue when it moves between groups.
10458 * The caller of this function should have put the task in its new group by
10459 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
10462 void sched_move_task(struct task_struct *tsk)
10464 int queued, running, queue_flags =
10465 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
10466 struct task_group *group;
10467 struct rq_flags rf;
10470 rq = task_rq_lock(tsk, &rf);
10472 * Esp. with SCHED_AUTOGROUP enabled it is possible to get superfluous
10475 group = sched_get_task_group(tsk);
10476 if (group == tsk->sched_task_group)
10479 update_rq_clock(rq);
10481 running = task_current(rq, tsk);
10482 queued = task_on_rq_queued(tsk);
10485 dequeue_task(rq, tsk, queue_flags);
10487 put_prev_task(rq, tsk);
10489 sched_change_group(tsk, group);
10492 enqueue_task(rq, tsk, queue_flags);
10494 set_next_task(rq, tsk);
10496 * After changing group, the running task may have joined a
10497 * throttled one but it's still the running task. Trigger a
10498 * resched to make sure that task can still run.
10504 task_rq_unlock(rq, tsk, &rf);
10507 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
10509 return css ? container_of(css, struct task_group, css) : NULL;
10512 static struct cgroup_subsys_state *
10513 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10515 struct task_group *parent = css_tg(parent_css);
10516 struct task_group *tg;
10519 /* This is early initialization for the top cgroup */
10520 return &root_task_group.css;
10523 tg = sched_create_group(parent);
10525 return ERR_PTR(-ENOMEM);
10530 /* Expose task group only after completing cgroup initialization */
10531 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
10533 struct task_group *tg = css_tg(css);
10534 struct task_group *parent = css_tg(css->parent);
10537 sched_online_group(tg, parent);
10539 #ifdef CONFIG_UCLAMP_TASK_GROUP
10540 /* Propagate the effective uclamp value for the new group */
10541 mutex_lock(&uclamp_mutex);
10543 cpu_util_update_eff(css);
10545 mutex_unlock(&uclamp_mutex);
10551 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
10553 struct task_group *tg = css_tg(css);
10555 sched_release_group(tg);
10558 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
10560 struct task_group *tg = css_tg(css);
10563 * Relies on the RCU grace period between css_released() and this.
10565 sched_unregister_group(tg);
10568 #ifdef CONFIG_RT_GROUP_SCHED
10569 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
10571 struct task_struct *task;
10572 struct cgroup_subsys_state *css;
10574 cgroup_taskset_for_each(task, css, tset) {
10575 if (!sched_rt_can_attach(css_tg(css), task))
10582 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
10584 struct task_struct *task;
10585 struct cgroup_subsys_state *css;
10587 cgroup_taskset_for_each(task, css, tset)
10588 sched_move_task(task);
10591 #ifdef CONFIG_UCLAMP_TASK_GROUP
10592 static void cpu_util_update_eff(struct cgroup_subsys_state *css)
10594 struct cgroup_subsys_state *top_css = css;
10595 struct uclamp_se *uc_parent = NULL;
10596 struct uclamp_se *uc_se = NULL;
10597 unsigned int eff[UCLAMP_CNT];
10598 enum uclamp_id clamp_id;
10599 unsigned int clamps;
10601 lockdep_assert_held(&uclamp_mutex);
10602 SCHED_WARN_ON(!rcu_read_lock_held());
10604 css_for_each_descendant_pre(css, top_css) {
10605 uc_parent = css_tg(css)->parent
10606 ? css_tg(css)->parent->uclamp : NULL;
10608 for_each_clamp_id(clamp_id) {
10609 /* Assume effective clamps matches requested clamps */
10610 eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
10611 /* Cap effective clamps with parent's effective clamps */
10613 eff[clamp_id] > uc_parent[clamp_id].value) {
10614 eff[clamp_id] = uc_parent[clamp_id].value;
10617 /* Ensure protection is always capped by limit */
10618 eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
10620 /* Propagate most restrictive effective clamps */
10622 uc_se = css_tg(css)->uclamp;
10623 for_each_clamp_id(clamp_id) {
10624 if (eff[clamp_id] == uc_se[clamp_id].value)
10626 uc_se[clamp_id].value = eff[clamp_id];
10627 uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
10628 clamps |= (0x1 << clamp_id);
10631 css = css_rightmost_descendant(css);
10635 /* Immediately update descendants RUNNABLE tasks */
10636 uclamp_update_active_tasks(css);
10641 * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
10642 * C expression. Since there is no way to convert a macro argument (N) into a
10643 * character constant, use two levels of macros.
10645 #define _POW10(exp) ((unsigned int)1e##exp)
10646 #define POW10(exp) _POW10(exp)
10648 struct uclamp_request {
10649 #define UCLAMP_PERCENT_SHIFT 2
10650 #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
10656 static inline struct uclamp_request
10657 capacity_from_percent(char *buf)
10659 struct uclamp_request req = {
10660 .percent = UCLAMP_PERCENT_SCALE,
10661 .util = SCHED_CAPACITY_SCALE,
10666 if (strcmp(buf, "max")) {
10667 req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
10671 if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
10676 req.util = req.percent << SCHED_CAPACITY_SHIFT;
10677 req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
10683 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
10684 size_t nbytes, loff_t off,
10685 enum uclamp_id clamp_id)
10687 struct uclamp_request req;
10688 struct task_group *tg;
10690 req = capacity_from_percent(buf);
10694 static_branch_enable(&sched_uclamp_used);
10696 mutex_lock(&uclamp_mutex);
10699 tg = css_tg(of_css(of));
10700 if (tg->uclamp_req[clamp_id].value != req.util)
10701 uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
10704 * Because of not recoverable conversion rounding we keep track of the
10705 * exact requested value
10707 tg->uclamp_pct[clamp_id] = req.percent;
10709 /* Update effective clamps to track the most restrictive value */
10710 cpu_util_update_eff(of_css(of));
10713 mutex_unlock(&uclamp_mutex);
10718 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
10719 char *buf, size_t nbytes,
10722 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
10725 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
10726 char *buf, size_t nbytes,
10729 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
10732 static inline void cpu_uclamp_print(struct seq_file *sf,
10733 enum uclamp_id clamp_id)
10735 struct task_group *tg;
10741 tg = css_tg(seq_css(sf));
10742 util_clamp = tg->uclamp_req[clamp_id].value;
10745 if (util_clamp == SCHED_CAPACITY_SCALE) {
10746 seq_puts(sf, "max\n");
10750 percent = tg->uclamp_pct[clamp_id];
10751 percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
10752 seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
10755 static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
10757 cpu_uclamp_print(sf, UCLAMP_MIN);
10761 static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
10763 cpu_uclamp_print(sf, UCLAMP_MAX);
10766 #endif /* CONFIG_UCLAMP_TASK_GROUP */
10768 #ifdef CONFIG_FAIR_GROUP_SCHED
10769 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
10770 struct cftype *cftype, u64 shareval)
10772 if (shareval > scale_load_down(ULONG_MAX))
10773 shareval = MAX_SHARES;
10774 return sched_group_set_shares(css_tg(css), scale_load(shareval));
10777 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
10778 struct cftype *cft)
10780 struct task_group *tg = css_tg(css);
10782 return (u64) scale_load_down(tg->shares);
10785 #ifdef CONFIG_CFS_BANDWIDTH
10786 static DEFINE_MUTEX(cfs_constraints_mutex);
10788 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
10789 static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
10790 /* More than 203 days if BW_SHIFT equals 20. */
10791 static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
10793 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
10795 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota,
10798 int i, ret = 0, runtime_enabled, runtime_was_enabled;
10799 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
10801 if (tg == &root_task_group)
10805 * Ensure we have at some amount of bandwidth every period. This is
10806 * to prevent reaching a state of large arrears when throttled via
10807 * entity_tick() resulting in prolonged exit starvation.
10809 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
10813 * Likewise, bound things on the other side by preventing insane quota
10814 * periods. This also allows us to normalize in computing quota
10817 if (period > max_cfs_quota_period)
10821 * Bound quota to defend quota against overflow during bandwidth shift.
10823 if (quota != RUNTIME_INF && quota > max_cfs_runtime)
10826 if (quota != RUNTIME_INF && (burst > quota ||
10827 burst + quota > max_cfs_runtime))
10831 * Prevent race between setting of cfs_rq->runtime_enabled and
10832 * unthrottle_offline_cfs_rqs().
10835 mutex_lock(&cfs_constraints_mutex);
10836 ret = __cfs_schedulable(tg, period, quota);
10840 runtime_enabled = quota != RUNTIME_INF;
10841 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
10843 * If we need to toggle cfs_bandwidth_used, off->on must occur
10844 * before making related changes, and on->off must occur afterwards
10846 if (runtime_enabled && !runtime_was_enabled)
10847 cfs_bandwidth_usage_inc();
10848 raw_spin_lock_irq(&cfs_b->lock);
10849 cfs_b->period = ns_to_ktime(period);
10850 cfs_b->quota = quota;
10851 cfs_b->burst = burst;
10853 __refill_cfs_bandwidth_runtime(cfs_b);
10855 /* Restart the period timer (if active) to handle new period expiry: */
10856 if (runtime_enabled)
10857 start_cfs_bandwidth(cfs_b);
10859 raw_spin_unlock_irq(&cfs_b->lock);
10861 for_each_online_cpu(i) {
10862 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
10863 struct rq *rq = cfs_rq->rq;
10864 struct rq_flags rf;
10866 rq_lock_irq(rq, &rf);
10867 cfs_rq->runtime_enabled = runtime_enabled;
10868 cfs_rq->runtime_remaining = 0;
10870 if (cfs_rq->throttled)
10871 unthrottle_cfs_rq(cfs_rq);
10872 rq_unlock_irq(rq, &rf);
10874 if (runtime_was_enabled && !runtime_enabled)
10875 cfs_bandwidth_usage_dec();
10877 mutex_unlock(&cfs_constraints_mutex);
10878 cpus_read_unlock();
10883 static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
10885 u64 quota, period, burst;
10887 period = ktime_to_ns(tg->cfs_bandwidth.period);
10888 burst = tg->cfs_bandwidth.burst;
10889 if (cfs_quota_us < 0)
10890 quota = RUNTIME_INF;
10891 else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
10892 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
10896 return tg_set_cfs_bandwidth(tg, period, quota, burst);
10899 static long tg_get_cfs_quota(struct task_group *tg)
10903 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
10906 quota_us = tg->cfs_bandwidth.quota;
10907 do_div(quota_us, NSEC_PER_USEC);
10912 static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
10914 u64 quota, period, burst;
10916 if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
10919 period = (u64)cfs_period_us * NSEC_PER_USEC;
10920 quota = tg->cfs_bandwidth.quota;
10921 burst = tg->cfs_bandwidth.burst;
10923 return tg_set_cfs_bandwidth(tg, period, quota, burst);
10926 static long tg_get_cfs_period(struct task_group *tg)
10930 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
10931 do_div(cfs_period_us, NSEC_PER_USEC);
10933 return cfs_period_us;
10936 static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us)
10938 u64 quota, period, burst;
10940 if ((u64)cfs_burst_us > U64_MAX / NSEC_PER_USEC)
10943 burst = (u64)cfs_burst_us * NSEC_PER_USEC;
10944 period = ktime_to_ns(tg->cfs_bandwidth.period);
10945 quota = tg->cfs_bandwidth.quota;
10947 return tg_set_cfs_bandwidth(tg, period, quota, burst);
10950 static long tg_get_cfs_burst(struct task_group *tg)
10954 burst_us = tg->cfs_bandwidth.burst;
10955 do_div(burst_us, NSEC_PER_USEC);
10960 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
10961 struct cftype *cft)
10963 return tg_get_cfs_quota(css_tg(css));
10966 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
10967 struct cftype *cftype, s64 cfs_quota_us)
10969 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
10972 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
10973 struct cftype *cft)
10975 return tg_get_cfs_period(css_tg(css));
10978 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
10979 struct cftype *cftype, u64 cfs_period_us)
10981 return tg_set_cfs_period(css_tg(css), cfs_period_us);
10984 static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css,
10985 struct cftype *cft)
10987 return tg_get_cfs_burst(css_tg(css));
10990 static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css,
10991 struct cftype *cftype, u64 cfs_burst_us)
10993 return tg_set_cfs_burst(css_tg(css), cfs_burst_us);
10996 struct cfs_schedulable_data {
10997 struct task_group *tg;
11002 * normalize group quota/period to be quota/max_period
11003 * note: units are usecs
11005 static u64 normalize_cfs_quota(struct task_group *tg,
11006 struct cfs_schedulable_data *d)
11011 period = d->period;
11014 period = tg_get_cfs_period(tg);
11015 quota = tg_get_cfs_quota(tg);
11018 /* note: these should typically be equivalent */
11019 if (quota == RUNTIME_INF || quota == -1)
11020 return RUNTIME_INF;
11022 return to_ratio(period, quota);
11025 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
11027 struct cfs_schedulable_data *d = data;
11028 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
11029 s64 quota = 0, parent_quota = -1;
11032 quota = RUNTIME_INF;
11034 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
11036 quota = normalize_cfs_quota(tg, d);
11037 parent_quota = parent_b->hierarchical_quota;
11040 * Ensure max(child_quota) <= parent_quota. On cgroup2,
11041 * always take the min. On cgroup1, only inherit when no
11044 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
11045 quota = min(quota, parent_quota);
11047 if (quota == RUNTIME_INF)
11048 quota = parent_quota;
11049 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
11053 cfs_b->hierarchical_quota = quota;
11058 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
11061 struct cfs_schedulable_data data = {
11067 if (quota != RUNTIME_INF) {
11068 do_div(data.period, NSEC_PER_USEC);
11069 do_div(data.quota, NSEC_PER_USEC);
11073 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
11079 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
11081 struct task_group *tg = css_tg(seq_css(sf));
11082 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
11084 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
11085 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
11086 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
11088 if (schedstat_enabled() && tg != &root_task_group) {
11089 struct sched_statistics *stats;
11093 for_each_possible_cpu(i) {
11094 stats = __schedstats_from_se(tg->se[i]);
11095 ws += schedstat_val(stats->wait_sum);
11098 seq_printf(sf, "wait_sum %llu\n", ws);
11101 seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst);
11102 seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time);
11106 #endif /* CONFIG_CFS_BANDWIDTH */
11107 #endif /* CONFIG_FAIR_GROUP_SCHED */
11109 #ifdef CONFIG_RT_GROUP_SCHED
11110 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
11111 struct cftype *cft, s64 val)
11113 return sched_group_set_rt_runtime(css_tg(css), val);
11116 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
11117 struct cftype *cft)
11119 return sched_group_rt_runtime(css_tg(css));
11122 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
11123 struct cftype *cftype, u64 rt_period_us)
11125 return sched_group_set_rt_period(css_tg(css), rt_period_us);
11128 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
11129 struct cftype *cft)
11131 return sched_group_rt_period(css_tg(css));
11133 #endif /* CONFIG_RT_GROUP_SCHED */
11135 #ifdef CONFIG_FAIR_GROUP_SCHED
11136 static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css,
11137 struct cftype *cft)
11139 return css_tg(css)->idle;
11142 static int cpu_idle_write_s64(struct cgroup_subsys_state *css,
11143 struct cftype *cft, s64 idle)
11145 return sched_group_set_idle(css_tg(css), idle);
11149 static struct cftype cpu_legacy_files[] = {
11150 #ifdef CONFIG_FAIR_GROUP_SCHED
11153 .read_u64 = cpu_shares_read_u64,
11154 .write_u64 = cpu_shares_write_u64,
11158 .read_s64 = cpu_idle_read_s64,
11159 .write_s64 = cpu_idle_write_s64,
11162 #ifdef CONFIG_CFS_BANDWIDTH
11164 .name = "cfs_quota_us",
11165 .read_s64 = cpu_cfs_quota_read_s64,
11166 .write_s64 = cpu_cfs_quota_write_s64,
11169 .name = "cfs_period_us",
11170 .read_u64 = cpu_cfs_period_read_u64,
11171 .write_u64 = cpu_cfs_period_write_u64,
11174 .name = "cfs_burst_us",
11175 .read_u64 = cpu_cfs_burst_read_u64,
11176 .write_u64 = cpu_cfs_burst_write_u64,
11180 .seq_show = cpu_cfs_stat_show,
11183 #ifdef CONFIG_RT_GROUP_SCHED
11185 .name = "rt_runtime_us",
11186 .read_s64 = cpu_rt_runtime_read,
11187 .write_s64 = cpu_rt_runtime_write,
11190 .name = "rt_period_us",
11191 .read_u64 = cpu_rt_period_read_uint,
11192 .write_u64 = cpu_rt_period_write_uint,
11195 #ifdef CONFIG_UCLAMP_TASK_GROUP
11197 .name = "uclamp.min",
11198 .flags = CFTYPE_NOT_ON_ROOT,
11199 .seq_show = cpu_uclamp_min_show,
11200 .write = cpu_uclamp_min_write,
11203 .name = "uclamp.max",
11204 .flags = CFTYPE_NOT_ON_ROOT,
11205 .seq_show = cpu_uclamp_max_show,
11206 .write = cpu_uclamp_max_write,
11209 { } /* Terminate */
11212 static int cpu_extra_stat_show(struct seq_file *sf,
11213 struct cgroup_subsys_state *css)
11215 #ifdef CONFIG_CFS_BANDWIDTH
11217 struct task_group *tg = css_tg(css);
11218 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
11219 u64 throttled_usec, burst_usec;
11221 throttled_usec = cfs_b->throttled_time;
11222 do_div(throttled_usec, NSEC_PER_USEC);
11223 burst_usec = cfs_b->burst_time;
11224 do_div(burst_usec, NSEC_PER_USEC);
11226 seq_printf(sf, "nr_periods %d\n"
11227 "nr_throttled %d\n"
11228 "throttled_usec %llu\n"
11230 "burst_usec %llu\n",
11231 cfs_b->nr_periods, cfs_b->nr_throttled,
11232 throttled_usec, cfs_b->nr_burst, burst_usec);
11238 #ifdef CONFIG_FAIR_GROUP_SCHED
11239 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
11240 struct cftype *cft)
11242 struct task_group *tg = css_tg(css);
11243 u64 weight = scale_load_down(tg->shares);
11245 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
11248 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
11249 struct cftype *cft, u64 weight)
11252 * cgroup weight knobs should use the common MIN, DFL and MAX
11253 * values which are 1, 100 and 10000 respectively. While it loses
11254 * a bit of range on both ends, it maps pretty well onto the shares
11255 * value used by scheduler and the round-trip conversions preserve
11256 * the original value over the entire range.
11258 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
11261 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
11263 return sched_group_set_shares(css_tg(css), scale_load(weight));
11266 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
11267 struct cftype *cft)
11269 unsigned long weight = scale_load_down(css_tg(css)->shares);
11270 int last_delta = INT_MAX;
11273 /* find the closest nice value to the current weight */
11274 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
11275 delta = abs(sched_prio_to_weight[prio] - weight);
11276 if (delta >= last_delta)
11278 last_delta = delta;
11281 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
11284 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
11285 struct cftype *cft, s64 nice)
11287 unsigned long weight;
11290 if (nice < MIN_NICE || nice > MAX_NICE)
11293 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
11294 idx = array_index_nospec(idx, 40);
11295 weight = sched_prio_to_weight[idx];
11297 return sched_group_set_shares(css_tg(css), scale_load(weight));
11301 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
11302 long period, long quota)
11305 seq_puts(sf, "max");
11307 seq_printf(sf, "%ld", quota);
11309 seq_printf(sf, " %ld\n", period);
11312 /* caller should put the current value in *@periodp before calling */
11313 static int __maybe_unused cpu_period_quota_parse(char *buf,
11314 u64 *periodp, u64 *quotap)
11316 char tok[21]; /* U64_MAX */
11318 if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
11321 *periodp *= NSEC_PER_USEC;
11323 if (sscanf(tok, "%llu", quotap))
11324 *quotap *= NSEC_PER_USEC;
11325 else if (!strcmp(tok, "max"))
11326 *quotap = RUNTIME_INF;
11333 #ifdef CONFIG_CFS_BANDWIDTH
11334 static int cpu_max_show(struct seq_file *sf, void *v)
11336 struct task_group *tg = css_tg(seq_css(sf));
11338 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
11342 static ssize_t cpu_max_write(struct kernfs_open_file *of,
11343 char *buf, size_t nbytes, loff_t off)
11345 struct task_group *tg = css_tg(of_css(of));
11346 u64 period = tg_get_cfs_period(tg);
11347 u64 burst = tg_get_cfs_burst(tg);
11351 ret = cpu_period_quota_parse(buf, &period, "a);
11353 ret = tg_set_cfs_bandwidth(tg, period, quota, burst);
11354 return ret ?: nbytes;
11358 static struct cftype cpu_files[] = {
11359 #ifdef CONFIG_FAIR_GROUP_SCHED
11362 .flags = CFTYPE_NOT_ON_ROOT,
11363 .read_u64 = cpu_weight_read_u64,
11364 .write_u64 = cpu_weight_write_u64,
11367 .name = "weight.nice",
11368 .flags = CFTYPE_NOT_ON_ROOT,
11369 .read_s64 = cpu_weight_nice_read_s64,
11370 .write_s64 = cpu_weight_nice_write_s64,
11374 .flags = CFTYPE_NOT_ON_ROOT,
11375 .read_s64 = cpu_idle_read_s64,
11376 .write_s64 = cpu_idle_write_s64,
11379 #ifdef CONFIG_CFS_BANDWIDTH
11382 .flags = CFTYPE_NOT_ON_ROOT,
11383 .seq_show = cpu_max_show,
11384 .write = cpu_max_write,
11387 .name = "max.burst",
11388 .flags = CFTYPE_NOT_ON_ROOT,
11389 .read_u64 = cpu_cfs_burst_read_u64,
11390 .write_u64 = cpu_cfs_burst_write_u64,
11393 #ifdef CONFIG_UCLAMP_TASK_GROUP
11395 .name = "uclamp.min",
11396 .flags = CFTYPE_NOT_ON_ROOT,
11397 .seq_show = cpu_uclamp_min_show,
11398 .write = cpu_uclamp_min_write,
11401 .name = "uclamp.max",
11402 .flags = CFTYPE_NOT_ON_ROOT,
11403 .seq_show = cpu_uclamp_max_show,
11404 .write = cpu_uclamp_max_write,
11407 { } /* terminate */
11410 struct cgroup_subsys cpu_cgrp_subsys = {
11411 .css_alloc = cpu_cgroup_css_alloc,
11412 .css_online = cpu_cgroup_css_online,
11413 .css_released = cpu_cgroup_css_released,
11414 .css_free = cpu_cgroup_css_free,
11415 .css_extra_stat_show = cpu_extra_stat_show,
11416 #ifdef CONFIG_RT_GROUP_SCHED
11417 .can_attach = cpu_cgroup_can_attach,
11419 .attach = cpu_cgroup_attach,
11420 .legacy_cftypes = cpu_legacy_files,
11421 .dfl_cftypes = cpu_files,
11422 .early_init = true,
11426 #endif /* CONFIG_CGROUP_SCHED */
11428 void dump_cpu_task(int cpu)
11430 if (cpu == smp_processor_id() && in_hardirq()) {
11431 struct pt_regs *regs;
11433 regs = get_irq_regs();
11440 if (trigger_single_cpu_backtrace(cpu))
11443 pr_info("Task dump for CPU %d:\n", cpu);
11444 sched_show_task(cpu_curr(cpu));
11448 * Nice levels are multiplicative, with a gentle 10% change for every
11449 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
11450 * nice 1, it will get ~10% less CPU time than another CPU-bound task
11451 * that remained on nice 0.
11453 * The "10% effect" is relative and cumulative: from _any_ nice level,
11454 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
11455 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
11456 * If a task goes up by ~10% and another task goes down by ~10% then
11457 * the relative distance between them is ~25%.)
11459 const int sched_prio_to_weight[40] = {
11460 /* -20 */ 88761, 71755, 56483, 46273, 36291,
11461 /* -15 */ 29154, 23254, 18705, 14949, 11916,
11462 /* -10 */ 9548, 7620, 6100, 4904, 3906,
11463 /* -5 */ 3121, 2501, 1991, 1586, 1277,
11464 /* 0 */ 1024, 820, 655, 526, 423,
11465 /* 5 */ 335, 272, 215, 172, 137,
11466 /* 10 */ 110, 87, 70, 56, 45,
11467 /* 15 */ 36, 29, 23, 18, 15,
11471 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
11473 * In cases where the weight does not change often, we can use the
11474 * precalculated inverse to speed up arithmetics by turning divisions
11475 * into multiplications:
11477 const u32 sched_prio_to_wmult[40] = {
11478 /* -20 */ 48388, 59856, 76040, 92818, 118348,
11479 /* -15 */ 147320, 184698, 229616, 287308, 360437,
11480 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
11481 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
11482 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
11483 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
11484 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
11485 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
11488 void call_trace_sched_update_nr_running(struct rq *rq, int count)
11490 trace_sched_update_nr_running_tp(rq, count);
11493 #ifdef CONFIG_SCHED_MM_CID
11496 * @cid_lock: Guarantee forward-progress of cid allocation.
11498 * Concurrency ID allocation within a bitmap is mostly lock-free. The cid_lock
11499 * is only used when contention is detected by the lock-free allocation so
11500 * forward progress can be guaranteed.
11502 DEFINE_RAW_SPINLOCK(cid_lock);
11505 * @use_cid_lock: Select cid allocation behavior: lock-free vs spinlock.
11507 * When @use_cid_lock is 0, the cid allocation is lock-free. When contention is
11508 * detected, it is set to 1 to ensure that all newly coming allocations are
11509 * serialized by @cid_lock until the allocation which detected contention
11510 * completes and sets @use_cid_lock back to 0. This guarantees forward progress
11511 * of a cid allocation.
11516 * mm_cid remote-clear implements a lock-free algorithm to clear per-mm/cpu cid
11517 * concurrently with respect to the execution of the source runqueue context
11520 * There is one basic properties we want to guarantee here:
11522 * (1) Remote-clear should _never_ mark a per-cpu cid UNSET when it is actively
11523 * used by a task. That would lead to concurrent allocation of the cid and
11524 * userspace corruption.
11526 * Provide this guarantee by introducing a Dekker memory ordering to guarantee
11527 * that a pair of loads observe at least one of a pair of stores, which can be
11536 * Which guarantees that x==0 && y==0 is impossible. But rather than using
11537 * values 0 and 1, this algorithm cares about specific state transitions of the
11538 * runqueue current task (as updated by the scheduler context switch), and the
11539 * per-mm/cpu cid value.
11541 * Let's introduce task (Y) which has task->mm == mm and task (N) which has
11542 * task->mm != mm for the rest of the discussion. There are two scheduler state
11543 * transitions on context switch we care about:
11545 * (TSA) Store to rq->curr with transition from (N) to (Y)
11547 * (TSB) Store to rq->curr with transition from (Y) to (N)
11549 * On the remote-clear side, there is one transition we care about:
11551 * (TMA) cmpxchg to *pcpu_cid to set the LAZY flag
11553 * There is also a transition to UNSET state which can be performed from all
11554 * sides (scheduler, remote-clear). It is always performed with a cmpxchg which
11555 * guarantees that only a single thread will succeed:
11557 * (TMB) cmpxchg to *pcpu_cid to mark UNSET
11559 * Just to be clear, what we do _not_ want to happen is a transition to UNSET
11560 * when a thread is actively using the cid (property (1)).
11562 * Let's looks at the relevant combinations of TSA/TSB, and TMA transitions.
11564 * Scenario A) (TSA)+(TMA) (from next task perspective)
11568 * Context switch CS-1 Remote-clear
11569 * - store to rq->curr: (N)->(Y) (TSA) - cmpxchg to *pcpu_id to LAZY (TMA)
11570 * (implied barrier after cmpxchg)
11571 * - switch_mm_cid()
11572 * - memory barrier (see switch_mm_cid()
11573 * comment explaining how this barrier
11574 * is combined with other scheduler
11576 * - mm_cid_get (next)
11577 * - READ_ONCE(*pcpu_cid) - rcu_dereference(src_rq->curr)
11579 * This Dekker ensures that either task (Y) is observed by the
11580 * rcu_dereference() or the LAZY flag is observed by READ_ONCE(), or both are
11583 * If task (Y) store is observed by rcu_dereference(), it means that there is
11584 * still an active task on the cpu. Remote-clear will therefore not transition
11585 * to UNSET, which fulfills property (1).
11587 * If task (Y) is not observed, but the lazy flag is observed by READ_ONCE(),
11588 * it will move its state to UNSET, which clears the percpu cid perhaps
11589 * uselessly (which is not an issue for correctness). Because task (Y) is not
11590 * observed, CPU1 can move ahead to set the state to UNSET. Because moving
11591 * state to UNSET is done with a cmpxchg expecting that the old state has the
11592 * LAZY flag set, only one thread will successfully UNSET.
11594 * If both states (LAZY flag and task (Y)) are observed, the thread on CPU0
11595 * will observe the LAZY flag and transition to UNSET (perhaps uselessly), and
11596 * CPU1 will observe task (Y) and do nothing more, which is fine.
11598 * What we are effectively preventing with this Dekker is a scenario where
11599 * neither LAZY flag nor store (Y) are observed, which would fail property (1)
11600 * because this would UNSET a cid which is actively used.
11603 void sched_mm_cid_migrate_from(struct task_struct *t)
11605 t->migrate_from_cpu = task_cpu(t);
11609 int __sched_mm_cid_migrate_from_fetch_cid(struct rq *src_rq,
11610 struct task_struct *t,
11611 struct mm_cid *src_pcpu_cid)
11613 struct mm_struct *mm = t->mm;
11614 struct task_struct *src_task;
11615 int src_cid, last_mm_cid;
11620 last_mm_cid = t->last_mm_cid;
11622 * If the migrated task has no last cid, or if the current
11623 * task on src rq uses the cid, it means the source cid does not need
11624 * to be moved to the destination cpu.
11626 if (last_mm_cid == -1)
11628 src_cid = READ_ONCE(src_pcpu_cid->cid);
11629 if (!mm_cid_is_valid(src_cid) || last_mm_cid != src_cid)
11633 * If we observe an active task using the mm on this rq, it means we
11634 * are not the last task to be migrated from this cpu for this mm, so
11635 * there is no need to move src_cid to the destination cpu.
11638 src_task = rcu_dereference(src_rq->curr);
11639 if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
11641 t->last_mm_cid = -1;
11650 int __sched_mm_cid_migrate_from_try_steal_cid(struct rq *src_rq,
11651 struct task_struct *t,
11652 struct mm_cid *src_pcpu_cid,
11655 struct task_struct *src_task;
11656 struct mm_struct *mm = t->mm;
11663 * Attempt to clear the source cpu cid to move it to the destination
11666 lazy_cid = mm_cid_set_lazy_put(src_cid);
11667 if (!try_cmpxchg(&src_pcpu_cid->cid, &src_cid, lazy_cid))
11671 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
11672 * rq->curr->mm matches the scheduler barrier in context_switch()
11673 * between store to rq->curr and load of prev and next task's
11676 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
11677 * rq->curr->mm_cid_active matches the barrier in
11678 * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
11679 * sched_mm_cid_after_execve() between store to t->mm_cid_active and
11680 * load of per-mm/cpu cid.
11684 * If we observe an active task using the mm on this rq after setting
11685 * the lazy-put flag, this task will be responsible for transitioning
11686 * from lazy-put flag set to MM_CID_UNSET.
11689 src_task = rcu_dereference(src_rq->curr);
11690 if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
11693 * We observed an active task for this mm, there is therefore
11694 * no point in moving this cid to the destination cpu.
11696 t->last_mm_cid = -1;
11702 * The src_cid is unused, so it can be unset.
11704 if (!try_cmpxchg(&src_pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
11710 * Migration to dst cpu. Called with dst_rq lock held.
11711 * Interrupts are disabled, which keeps the window of cid ownership without the
11712 * source rq lock held small.
11714 void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t)
11716 struct mm_cid *src_pcpu_cid, *dst_pcpu_cid;
11717 struct mm_struct *mm = t->mm;
11718 int src_cid, dst_cid, src_cpu;
11721 lockdep_assert_rq_held(dst_rq);
11725 src_cpu = t->migrate_from_cpu;
11726 if (src_cpu == -1) {
11727 t->last_mm_cid = -1;
11731 * Move the src cid if the dst cid is unset. This keeps id
11732 * allocation closest to 0 in cases where few threads migrate around
11735 * If destination cid is already set, we may have to just clear
11736 * the src cid to ensure compactness in frequent migrations
11739 * It is not useful to clear the src cid when the number of threads is
11740 * greater or equal to the number of allowed cpus, because user-space
11741 * can expect that the number of allowed cids can reach the number of
11744 dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
11745 dst_cid = READ_ONCE(dst_pcpu_cid->cid);
11746 if (!mm_cid_is_unset(dst_cid) &&
11747 atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
11749 src_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, src_cpu);
11750 src_rq = cpu_rq(src_cpu);
11751 src_cid = __sched_mm_cid_migrate_from_fetch_cid(src_rq, t, src_pcpu_cid);
11754 src_cid = __sched_mm_cid_migrate_from_try_steal_cid(src_rq, t, src_pcpu_cid,
11758 if (!mm_cid_is_unset(dst_cid)) {
11759 __mm_cid_put(mm, src_cid);
11762 /* Move src_cid to dst cpu. */
11763 mm_cid_snapshot_time(dst_rq, mm);
11764 WRITE_ONCE(dst_pcpu_cid->cid, src_cid);
11767 static void sched_mm_cid_remote_clear(struct mm_struct *mm, struct mm_cid *pcpu_cid,
11770 struct rq *rq = cpu_rq(cpu);
11771 struct task_struct *t;
11772 unsigned long flags;
11775 cid = READ_ONCE(pcpu_cid->cid);
11776 if (!mm_cid_is_valid(cid))
11780 * Clear the cpu cid if it is set to keep cid allocation compact. If
11781 * there happens to be other tasks left on the source cpu using this
11782 * mm, the next task using this mm will reallocate its cid on context
11785 lazy_cid = mm_cid_set_lazy_put(cid);
11786 if (!try_cmpxchg(&pcpu_cid->cid, &cid, lazy_cid))
11790 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
11791 * rq->curr->mm matches the scheduler barrier in context_switch()
11792 * between store to rq->curr and load of prev and next task's
11795 * The implicit barrier after cmpxchg per-mm/cpu cid before loading
11796 * rq->curr->mm_cid_active matches the barrier in
11797 * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
11798 * sched_mm_cid_after_execve() between store to t->mm_cid_active and
11799 * load of per-mm/cpu cid.
11803 * If we observe an active task using the mm on this rq after setting
11804 * the lazy-put flag, that task will be responsible for transitioning
11805 * from lazy-put flag set to MM_CID_UNSET.
11808 t = rcu_dereference(rq->curr);
11809 if (READ_ONCE(t->mm_cid_active) && t->mm == mm) {
11816 * The cid is unused, so it can be unset.
11817 * Disable interrupts to keep the window of cid ownership without rq
11820 local_irq_save(flags);
11821 if (try_cmpxchg(&pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
11822 __mm_cid_put(mm, cid);
11823 local_irq_restore(flags);
11826 static void sched_mm_cid_remote_clear_old(struct mm_struct *mm, int cpu)
11828 struct rq *rq = cpu_rq(cpu);
11829 struct mm_cid *pcpu_cid;
11830 struct task_struct *curr;
11834 * rq->clock load is racy on 32-bit but one spurious clear once in a
11835 * while is irrelevant.
11837 rq_clock = READ_ONCE(rq->clock);
11838 pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
11841 * In order to take care of infrequently scheduled tasks, bump the time
11842 * snapshot associated with this cid if an active task using the mm is
11843 * observed on this rq.
11846 curr = rcu_dereference(rq->curr);
11847 if (READ_ONCE(curr->mm_cid_active) && curr->mm == mm) {
11848 WRITE_ONCE(pcpu_cid->time, rq_clock);
11854 if (rq_clock < pcpu_cid->time + SCHED_MM_CID_PERIOD_NS)
11856 sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
11859 static void sched_mm_cid_remote_clear_weight(struct mm_struct *mm, int cpu,
11862 struct mm_cid *pcpu_cid;
11865 pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
11866 cid = READ_ONCE(pcpu_cid->cid);
11867 if (!mm_cid_is_valid(cid) || cid < weight)
11869 sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
11872 static void task_mm_cid_work(struct callback_head *work)
11874 unsigned long now = jiffies, old_scan, next_scan;
11875 struct task_struct *t = current;
11876 struct cpumask *cidmask;
11877 struct mm_struct *mm;
11880 SCHED_WARN_ON(t != container_of(work, struct task_struct, cid_work));
11882 work->next = work; /* Prevent double-add */
11883 if (t->flags & PF_EXITING)
11888 old_scan = READ_ONCE(mm->mm_cid_next_scan);
11889 next_scan = now + msecs_to_jiffies(MM_CID_SCAN_DELAY);
11893 res = cmpxchg(&mm->mm_cid_next_scan, old_scan, next_scan);
11894 if (res != old_scan)
11897 old_scan = next_scan;
11899 if (time_before(now, old_scan))
11901 if (!try_cmpxchg(&mm->mm_cid_next_scan, &old_scan, next_scan))
11903 cidmask = mm_cidmask(mm);
11904 /* Clear cids that were not recently used. */
11905 for_each_possible_cpu(cpu)
11906 sched_mm_cid_remote_clear_old(mm, cpu);
11907 weight = cpumask_weight(cidmask);
11909 * Clear cids that are greater or equal to the cidmask weight to
11912 for_each_possible_cpu(cpu)
11913 sched_mm_cid_remote_clear_weight(mm, cpu, weight);
11916 void init_sched_mm_cid(struct task_struct *t)
11918 struct mm_struct *mm = t->mm;
11922 mm_users = atomic_read(&mm->mm_users);
11924 mm->mm_cid_next_scan = jiffies + msecs_to_jiffies(MM_CID_SCAN_DELAY);
11926 t->cid_work.next = &t->cid_work; /* Protect against double add */
11927 init_task_work(&t->cid_work, task_mm_cid_work);
11930 void task_tick_mm_cid(struct rq *rq, struct task_struct *curr)
11932 struct callback_head *work = &curr->cid_work;
11933 unsigned long now = jiffies;
11935 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) ||
11936 work->next != work)
11938 if (time_before(now, READ_ONCE(curr->mm->mm_cid_next_scan)))
11940 task_work_add(curr, work, TWA_RESUME);
11943 void sched_mm_cid_exit_signals(struct task_struct *t)
11945 struct mm_struct *mm = t->mm;
11946 struct rq_flags rf;
11954 rq_lock_irqsave(rq, &rf);
11955 preempt_enable_no_resched(); /* holding spinlock */
11956 WRITE_ONCE(t->mm_cid_active, 0);
11958 * Store t->mm_cid_active before loading per-mm/cpu cid.
11959 * Matches barrier in sched_mm_cid_remote_clear_old().
11963 t->last_mm_cid = t->mm_cid = -1;
11964 rq_unlock_irqrestore(rq, &rf);
11967 void sched_mm_cid_before_execve(struct task_struct *t)
11969 struct mm_struct *mm = t->mm;
11970 struct rq_flags rf;
11978 rq_lock_irqsave(rq, &rf);
11979 preempt_enable_no_resched(); /* holding spinlock */
11980 WRITE_ONCE(t->mm_cid_active, 0);
11982 * Store t->mm_cid_active before loading per-mm/cpu cid.
11983 * Matches barrier in sched_mm_cid_remote_clear_old().
11987 t->last_mm_cid = t->mm_cid = -1;
11988 rq_unlock_irqrestore(rq, &rf);
11991 void sched_mm_cid_after_execve(struct task_struct *t)
11993 struct mm_struct *mm = t->mm;
11994 struct rq_flags rf;
12002 rq_lock_irqsave(rq, &rf);
12003 preempt_enable_no_resched(); /* holding spinlock */
12004 WRITE_ONCE(t->mm_cid_active, 1);
12006 * Store t->mm_cid_active before loading per-mm/cpu cid.
12007 * Matches barrier in sched_mm_cid_remote_clear_old().
12010 t->last_mm_cid = t->mm_cid = mm_cid_get(rq, mm);
12011 rq_unlock_irqrestore(rq, &rf);
12012 rseq_set_notify_resume(t);
12015 void sched_mm_cid_fork(struct task_struct *t)
12017 WARN_ON_ONCE(!t->mm || t->mm_cid != -1);
12018 t->mm_cid_active = 1;