1 // SPDX-License-Identifier: GPL-2.0-only
5 * Core kernel scheduler code and related syscalls
7 * Copyright (C) 1991-2002 Linus Torvalds
9 #define CREATE_TRACE_POINTS
10 #include <trace/events/sched.h>
11 #undef CREATE_TRACE_POINTS
15 #include <linux/nospec.h>
17 #include <linux/kcov.h>
18 #include <linux/scs.h>
20 #include <asm/switch_to.h>
23 #include "../workqueue_internal.h"
24 #include "../../io_uring/io-wq.h"
25 #include "../smpboot.h"
31 * Export tracepoints that act as a bare tracehook (ie: have no trace event
32 * associated with them) to allow external modules to probe them.
34 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
35 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
36 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
37 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
38 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
39 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_thermal_tp);
40 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
41 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
42 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
43 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
46 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
48 #ifdef CONFIG_SCHED_DEBUG
50 * Debugging: various feature bits
52 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
53 * sysctl_sched_features, defined in sched.h, to allow constants propagation
54 * at compile time and compiler optimization based on features default.
56 #define SCHED_FEAT(name, enabled) \
57 (1UL << __SCHED_FEAT_##name) * enabled |
58 const_debug unsigned int sysctl_sched_features =
65 * Number of tasks to iterate in a single balance run.
66 * Limited because this is done with IRQs disabled.
68 const_debug unsigned int sysctl_sched_nr_migrate = 32;
71 * period over which we measure -rt task CPU usage in us.
74 unsigned int sysctl_sched_rt_period = 1000000;
76 __read_mostly int scheduler_running;
79 * part of the period that we allow rt tasks to run in us.
82 int sysctl_sched_rt_runtime = 950000;
86 * Serialization rules:
92 * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
95 * rq2->lock where: rq1 < rq2
99 * Normal scheduling state is serialized by rq->lock. __schedule() takes the
100 * local CPU's rq->lock, it optionally removes the task from the runqueue and
101 * always looks at the local rq data structures to find the most elegible task
104 * Task enqueue is also under rq->lock, possibly taken from another CPU.
105 * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
106 * the local CPU to avoid bouncing the runqueue state around [ see
107 * ttwu_queue_wakelist() ]
109 * Task wakeup, specifically wakeups that involve migration, are horribly
110 * complicated to avoid having to take two rq->locks.
114 * System-calls and anything external will use task_rq_lock() which acquires
115 * both p->pi_lock and rq->lock. As a consequence the state they change is
116 * stable while holding either lock:
118 * - sched_setaffinity()/
119 * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
120 * - set_user_nice(): p->se.load, p->*prio
121 * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
122 * p->se.load, p->rt_priority,
123 * p->dl.dl_{runtime, deadline, period, flags, bw, density}
124 * - sched_setnuma(): p->numa_preferred_nid
125 * - sched_move_task()/
126 * cpu_cgroup_fork(): p->sched_task_group
127 * - uclamp_update_active() p->uclamp*
129 * p->state <- TASK_*:
131 * is changed locklessly using set_current_state(), __set_current_state() or
132 * set_special_state(), see their respective comments, or by
133 * try_to_wake_up(). This latter uses p->pi_lock to serialize against
136 * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
138 * is set by activate_task() and cleared by deactivate_task(), under
139 * rq->lock. Non-zero indicates the task is runnable, the special
140 * ON_RQ_MIGRATING state is used for migration without holding both
141 * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
143 * p->on_cpu <- { 0, 1 }:
145 * is set by prepare_task() and cleared by finish_task() such that it will be
146 * set before p is scheduled-in and cleared after p is scheduled-out, both
147 * under rq->lock. Non-zero indicates the task is running on its CPU.
149 * [ The astute reader will observe that it is possible for two tasks on one
150 * CPU to have ->on_cpu = 1 at the same time. ]
152 * task_cpu(p): is changed by set_task_cpu(), the rules are:
154 * - Don't call set_task_cpu() on a blocked task:
156 * We don't care what CPU we're not running on, this simplifies hotplug,
157 * the CPU assignment of blocked tasks isn't required to be valid.
159 * - for try_to_wake_up(), called under p->pi_lock:
161 * This allows try_to_wake_up() to only take one rq->lock, see its comment.
163 * - for migration called under rq->lock:
164 * [ see task_on_rq_migrating() in task_rq_lock() ]
166 * o move_queued_task()
169 * - for migration called under double_rq_lock():
171 * o __migrate_swap_task()
172 * o push_rt_task() / pull_rt_task()
173 * o push_dl_task() / pull_dl_task()
174 * o dl_task_offline_migration()
179 * __task_rq_lock - lock the rq @p resides on.
181 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
186 lockdep_assert_held(&p->pi_lock);
190 raw_spin_lock(&rq->lock);
191 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
195 raw_spin_unlock(&rq->lock);
197 while (unlikely(task_on_rq_migrating(p)))
203 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
205 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
206 __acquires(p->pi_lock)
212 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
214 raw_spin_lock(&rq->lock);
216 * move_queued_task() task_rq_lock()
219 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
220 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
221 * [S] ->cpu = new_cpu [L] task_rq()
225 * If we observe the old CPU in task_rq_lock(), the acquire of
226 * the old rq->lock will fully serialize against the stores.
228 * If we observe the new CPU in task_rq_lock(), the address
229 * dependency headed by '[L] rq = task_rq()' and the acquire
230 * will pair with the WMB to ensure we then also see migrating.
232 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
236 raw_spin_unlock(&rq->lock);
237 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
239 while (unlikely(task_on_rq_migrating(p)))
245 * RQ-clock updating methods:
248 static void update_rq_clock_task(struct rq *rq, s64 delta)
251 * In theory, the compile should just see 0 here, and optimize out the call
252 * to sched_rt_avg_update. But I don't trust it...
254 s64 __maybe_unused steal = 0, irq_delta = 0;
256 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
257 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
260 * Since irq_time is only updated on {soft,}irq_exit, we might run into
261 * this case when a previous update_rq_clock() happened inside a
264 * When this happens, we stop ->clock_task and only update the
265 * prev_irq_time stamp to account for the part that fit, so that a next
266 * update will consume the rest. This ensures ->clock_task is
269 * It does however cause some slight miss-attribution of {soft,}irq
270 * time, a more accurate solution would be to update the irq_time using
271 * the current rq->clock timestamp, except that would require using
274 if (irq_delta > delta)
277 rq->prev_irq_time += irq_delta;
280 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
281 if (static_key_false((¶virt_steal_rq_enabled))) {
282 steal = paravirt_steal_clock(cpu_of(rq));
283 steal -= rq->prev_steal_time_rq;
285 if (unlikely(steal > delta))
288 rq->prev_steal_time_rq += steal;
293 rq->clock_task += delta;
295 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
296 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
297 update_irq_load_avg(rq, irq_delta + steal);
299 update_rq_clock_pelt(rq, delta);
302 void update_rq_clock(struct rq *rq)
306 lockdep_assert_held(&rq->lock);
308 if (rq->clock_update_flags & RQCF_ACT_SKIP)
311 #ifdef CONFIG_SCHED_DEBUG
312 if (sched_feat(WARN_DOUBLE_CLOCK))
313 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
314 rq->clock_update_flags |= RQCF_UPDATED;
317 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
321 update_rq_clock_task(rq, delta);
325 rq_csd_init(struct rq *rq, struct __call_single_data *csd, smp_call_func_t func)
332 #ifdef CONFIG_SCHED_HRTICK
334 * Use HR-timers to deliver accurate preemption points.
337 static void hrtick_clear(struct rq *rq)
339 if (hrtimer_active(&rq->hrtick_timer))
340 hrtimer_cancel(&rq->hrtick_timer);
344 * High-resolution timer tick.
345 * Runs from hardirq context with interrupts disabled.
347 static enum hrtimer_restart hrtick(struct hrtimer *timer)
349 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
352 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
356 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
359 return HRTIMER_NORESTART;
364 static void __hrtick_restart(struct rq *rq)
366 struct hrtimer *timer = &rq->hrtick_timer;
367 ktime_t time = rq->hrtick_time;
369 hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
373 * called from hardirq (IPI) context
375 static void __hrtick_start(void *arg)
381 __hrtick_restart(rq);
386 * Called to set the hrtick timer state.
388 * called with rq->lock held and irqs disabled
390 void hrtick_start(struct rq *rq, u64 delay)
392 struct hrtimer *timer = &rq->hrtick_timer;
396 * Don't schedule slices shorter than 10000ns, that just
397 * doesn't make sense and can cause timer DoS.
399 delta = max_t(s64, delay, 10000LL);
400 rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
403 __hrtick_restart(rq);
405 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
410 * Called to set the hrtick timer state.
412 * called with rq->lock held and irqs disabled
414 void hrtick_start(struct rq *rq, u64 delay)
417 * Don't schedule slices shorter than 10000ns, that just
418 * doesn't make sense. Rely on vruntime for fairness.
420 delay = max_t(u64, delay, 10000LL);
421 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
422 HRTIMER_MODE_REL_PINNED_HARD);
425 #endif /* CONFIG_SMP */
427 static void hrtick_rq_init(struct rq *rq)
430 rq_csd_init(rq, &rq->hrtick_csd, __hrtick_start);
432 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
433 rq->hrtick_timer.function = hrtick;
435 #else /* CONFIG_SCHED_HRTICK */
436 static inline void hrtick_clear(struct rq *rq)
440 static inline void hrtick_rq_init(struct rq *rq)
443 #endif /* CONFIG_SCHED_HRTICK */
446 * cmpxchg based fetch_or, macro so it works for different integer types
448 #define fetch_or(ptr, mask) \
450 typeof(ptr) _ptr = (ptr); \
451 typeof(mask) _mask = (mask); \
452 typeof(*_ptr) _old, _val = *_ptr; \
455 _old = cmpxchg(_ptr, _val, _val | _mask); \
463 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
465 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
466 * this avoids any races wrt polling state changes and thereby avoids
469 static bool set_nr_and_not_polling(struct task_struct *p)
471 struct thread_info *ti = task_thread_info(p);
472 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
476 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
478 * If this returns true, then the idle task promises to call
479 * sched_ttwu_pending() and reschedule soon.
481 static bool set_nr_if_polling(struct task_struct *p)
483 struct thread_info *ti = task_thread_info(p);
484 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
487 if (!(val & _TIF_POLLING_NRFLAG))
489 if (val & _TIF_NEED_RESCHED)
491 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
500 static bool set_nr_and_not_polling(struct task_struct *p)
502 set_tsk_need_resched(p);
507 static bool set_nr_if_polling(struct task_struct *p)
514 static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
516 struct wake_q_node *node = &task->wake_q;
519 * Atomically grab the task, if ->wake_q is !nil already it means
520 * its already queued (either by us or someone else) and will get the
521 * wakeup due to that.
523 * In order to ensure that a pending wakeup will observe our pending
524 * state, even in the failed case, an explicit smp_mb() must be used.
526 smp_mb__before_atomic();
527 if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
531 * The head is context local, there can be no concurrency.
534 head->lastp = &node->next;
539 * wake_q_add() - queue a wakeup for 'later' waking.
540 * @head: the wake_q_head to add @task to
541 * @task: the task to queue for 'later' wakeup
543 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
544 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
547 * This function must be used as-if it were wake_up_process(); IOW the task
548 * must be ready to be woken at this location.
550 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
552 if (__wake_q_add(head, task))
553 get_task_struct(task);
557 * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
558 * @head: the wake_q_head to add @task to
559 * @task: the task to queue for 'later' wakeup
561 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
562 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
565 * This function must be used as-if it were wake_up_process(); IOW the task
566 * must be ready to be woken at this location.
568 * This function is essentially a task-safe equivalent to wake_q_add(). Callers
569 * that already hold reference to @task can call the 'safe' version and trust
570 * wake_q to do the right thing depending whether or not the @task is already
573 void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
575 if (!__wake_q_add(head, task))
576 put_task_struct(task);
579 void wake_up_q(struct wake_q_head *head)
581 struct wake_q_node *node = head->first;
583 while (node != WAKE_Q_TAIL) {
584 struct task_struct *task;
586 task = container_of(node, struct task_struct, wake_q);
588 /* Task can safely be re-inserted now: */
590 task->wake_q.next = NULL;
593 * wake_up_process() executes a full barrier, which pairs with
594 * the queueing in wake_q_add() so as not to miss wakeups.
596 wake_up_process(task);
597 put_task_struct(task);
602 * resched_curr - mark rq's current task 'to be rescheduled now'.
604 * On UP this means the setting of the need_resched flag, on SMP it
605 * might also involve a cross-CPU call to trigger the scheduler on
608 void resched_curr(struct rq *rq)
610 struct task_struct *curr = rq->curr;
613 lockdep_assert_held(&rq->lock);
615 if (test_tsk_need_resched(curr))
620 if (cpu == smp_processor_id()) {
621 set_tsk_need_resched(curr);
622 set_preempt_need_resched();
626 if (set_nr_and_not_polling(curr))
627 smp_send_reschedule(cpu);
629 trace_sched_wake_idle_without_ipi(cpu);
632 void resched_cpu(int cpu)
634 struct rq *rq = cpu_rq(cpu);
637 raw_spin_lock_irqsave(&rq->lock, flags);
638 if (cpu_online(cpu) || cpu == smp_processor_id())
640 raw_spin_unlock_irqrestore(&rq->lock, flags);
644 #ifdef CONFIG_NO_HZ_COMMON
646 * In the semi idle case, use the nearest busy CPU for migrating timers
647 * from an idle CPU. This is good for power-savings.
649 * We don't do similar optimization for completely idle system, as
650 * selecting an idle CPU will add more delays to the timers than intended
651 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
653 int get_nohz_timer_target(void)
655 int i, cpu = smp_processor_id(), default_cpu = -1;
656 struct sched_domain *sd;
658 if (housekeeping_cpu(cpu, HK_FLAG_TIMER)) {
665 for_each_domain(cpu, sd) {
666 for_each_cpu_and(i, sched_domain_span(sd),
667 housekeeping_cpumask(HK_FLAG_TIMER)) {
678 if (default_cpu == -1)
679 default_cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
687 * When add_timer_on() enqueues a timer into the timer wheel of an
688 * idle CPU then this timer might expire before the next timer event
689 * which is scheduled to wake up that CPU. In case of a completely
690 * idle system the next event might even be infinite time into the
691 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
692 * leaves the inner idle loop so the newly added timer is taken into
693 * account when the CPU goes back to idle and evaluates the timer
694 * wheel for the next timer event.
696 static void wake_up_idle_cpu(int cpu)
698 struct rq *rq = cpu_rq(cpu);
700 if (cpu == smp_processor_id())
703 if (set_nr_and_not_polling(rq->idle))
704 smp_send_reschedule(cpu);
706 trace_sched_wake_idle_without_ipi(cpu);
709 static bool wake_up_full_nohz_cpu(int cpu)
712 * We just need the target to call irq_exit() and re-evaluate
713 * the next tick. The nohz full kick at least implies that.
714 * If needed we can still optimize that later with an
717 if (cpu_is_offline(cpu))
718 return true; /* Don't try to wake offline CPUs. */
719 if (tick_nohz_full_cpu(cpu)) {
720 if (cpu != smp_processor_id() ||
721 tick_nohz_tick_stopped())
722 tick_nohz_full_kick_cpu(cpu);
730 * Wake up the specified CPU. If the CPU is going offline, it is the
731 * caller's responsibility to deal with the lost wakeup, for example,
732 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
734 void wake_up_nohz_cpu(int cpu)
736 if (!wake_up_full_nohz_cpu(cpu))
737 wake_up_idle_cpu(cpu);
740 static void nohz_csd_func(void *info)
742 struct rq *rq = info;
743 int cpu = cpu_of(rq);
747 * Release the rq::nohz_csd.
749 flags = atomic_fetch_andnot(NOHZ_KICK_MASK, nohz_flags(cpu));
750 WARN_ON(!(flags & NOHZ_KICK_MASK));
752 rq->idle_balance = idle_cpu(cpu);
753 if (rq->idle_balance && !need_resched()) {
754 rq->nohz_idle_balance = flags;
755 raise_softirq_irqoff(SCHED_SOFTIRQ);
759 #endif /* CONFIG_NO_HZ_COMMON */
761 #ifdef CONFIG_NO_HZ_FULL
762 bool sched_can_stop_tick(struct rq *rq)
766 /* Deadline tasks, even if single, need the tick */
767 if (rq->dl.dl_nr_running)
771 * If there are more than one RR tasks, we need the tick to effect the
772 * actual RR behaviour.
774 if (rq->rt.rr_nr_running) {
775 if (rq->rt.rr_nr_running == 1)
782 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
783 * forced preemption between FIFO tasks.
785 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
790 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
791 * if there's more than one we need the tick for involuntary
794 if (rq->nr_running > 1)
799 #endif /* CONFIG_NO_HZ_FULL */
800 #endif /* CONFIG_SMP */
802 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
803 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
805 * Iterate task_group tree rooted at *from, calling @down when first entering a
806 * node and @up when leaving it for the final time.
808 * Caller must hold rcu_lock or sufficient equivalent.
810 int walk_tg_tree_from(struct task_group *from,
811 tg_visitor down, tg_visitor up, void *data)
813 struct task_group *parent, *child;
819 ret = (*down)(parent, data);
822 list_for_each_entry_rcu(child, &parent->children, siblings) {
829 ret = (*up)(parent, data);
830 if (ret || parent == from)
834 parent = parent->parent;
841 int tg_nop(struct task_group *tg, void *data)
847 static void set_load_weight(struct task_struct *p)
849 bool update_load = !(READ_ONCE(p->state) & TASK_NEW);
850 int prio = p->static_prio - MAX_RT_PRIO;
851 struct load_weight *load = &p->se.load;
854 * SCHED_IDLE tasks get minimal weight:
856 if (task_has_idle_policy(p)) {
857 load->weight = scale_load(WEIGHT_IDLEPRIO);
858 load->inv_weight = WMULT_IDLEPRIO;
863 * SCHED_OTHER tasks have to update their load when changing their
866 if (update_load && p->sched_class == &fair_sched_class) {
867 reweight_task(p, prio);
869 load->weight = scale_load(sched_prio_to_weight[prio]);
870 load->inv_weight = sched_prio_to_wmult[prio];
874 #ifdef CONFIG_UCLAMP_TASK
876 * Serializes updates of utilization clamp values
878 * The (slow-path) user-space triggers utilization clamp value updates which
879 * can require updates on (fast-path) scheduler's data structures used to
880 * support enqueue/dequeue operations.
881 * While the per-CPU rq lock protects fast-path update operations, user-space
882 * requests are serialized using a mutex to reduce the risk of conflicting
883 * updates or API abuses.
885 static DEFINE_MUTEX(uclamp_mutex);
887 /* Max allowed minimum utilization */
888 unsigned int sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
890 /* Max allowed maximum utilization */
891 unsigned int sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
894 * By default RT tasks run at the maximum performance point/capacity of the
895 * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
896 * SCHED_CAPACITY_SCALE.
898 * This knob allows admins to change the default behavior when uclamp is being
899 * used. In battery powered devices, particularly, running at the maximum
900 * capacity and frequency will increase energy consumption and shorten the
903 * This knob only affects RT tasks that their uclamp_se->user_defined == false.
905 * This knob will not override the system default sched_util_clamp_min defined
908 unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
910 /* All clamps are required to be less or equal than these values */
911 static struct uclamp_se uclamp_default[UCLAMP_CNT];
914 * This static key is used to reduce the uclamp overhead in the fast path. It
915 * primarily disables the call to uclamp_rq_{inc, dec}() in
916 * enqueue/dequeue_task().
918 * This allows users to continue to enable uclamp in their kernel config with
919 * minimum uclamp overhead in the fast path.
921 * As soon as userspace modifies any of the uclamp knobs, the static key is
922 * enabled, since we have an actual users that make use of uclamp
925 * The knobs that would enable this static key are:
927 * * A task modifying its uclamp value with sched_setattr().
928 * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
929 * * An admin modifying the cgroup cpu.uclamp.{min, max}
931 DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
933 /* Integer rounded range for each bucket */
934 #define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
936 #define for_each_clamp_id(clamp_id) \
937 for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
939 static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
941 return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
944 static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
946 if (clamp_id == UCLAMP_MIN)
948 return SCHED_CAPACITY_SCALE;
951 static inline void uclamp_se_set(struct uclamp_se *uc_se,
952 unsigned int value, bool user_defined)
954 uc_se->value = value;
955 uc_se->bucket_id = uclamp_bucket_id(value);
956 uc_se->user_defined = user_defined;
959 static inline unsigned int
960 uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
961 unsigned int clamp_value)
964 * Avoid blocked utilization pushing up the frequency when we go
965 * idle (which drops the max-clamp) by retaining the last known
968 if (clamp_id == UCLAMP_MAX) {
969 rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
973 return uclamp_none(UCLAMP_MIN);
976 static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
977 unsigned int clamp_value)
979 /* Reset max-clamp retention only on idle exit */
980 if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
983 uclamp_rq_set(rq, clamp_id, clamp_value);
987 unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
988 unsigned int clamp_value)
990 struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
991 int bucket_id = UCLAMP_BUCKETS - 1;
994 * Since both min and max clamps are max aggregated, find the
995 * top most bucket with tasks in.
997 for ( ; bucket_id >= 0; bucket_id--) {
998 if (!bucket[bucket_id].tasks)
1000 return bucket[bucket_id].value;
1003 /* No tasks -- default clamp values */
1004 return uclamp_idle_value(rq, clamp_id, clamp_value);
1007 static void __uclamp_update_util_min_rt_default(struct task_struct *p)
1009 unsigned int default_util_min;
1010 struct uclamp_se *uc_se;
1012 lockdep_assert_held(&p->pi_lock);
1014 uc_se = &p->uclamp_req[UCLAMP_MIN];
1016 /* Only sync if user didn't override the default */
1017 if (uc_se->user_defined)
1020 default_util_min = sysctl_sched_uclamp_util_min_rt_default;
1021 uclamp_se_set(uc_se, default_util_min, false);
1024 static void uclamp_update_util_min_rt_default(struct task_struct *p)
1032 /* Protect updates to p->uclamp_* */
1033 rq = task_rq_lock(p, &rf);
1034 __uclamp_update_util_min_rt_default(p);
1035 task_rq_unlock(rq, p, &rf);
1038 static void uclamp_sync_util_min_rt_default(void)
1040 struct task_struct *g, *p;
1043 * copy_process() sysctl_uclamp
1044 * uclamp_min_rt = X;
1045 * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
1046 * // link thread smp_mb__after_spinlock()
1047 * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
1048 * sched_post_fork() for_each_process_thread()
1049 * __uclamp_sync_rt() __uclamp_sync_rt()
1051 * Ensures that either sched_post_fork() will observe the new
1052 * uclamp_min_rt or for_each_process_thread() will observe the new
1055 read_lock(&tasklist_lock);
1056 smp_mb__after_spinlock();
1057 read_unlock(&tasklist_lock);
1060 for_each_process_thread(g, p)
1061 uclamp_update_util_min_rt_default(p);
1065 static inline struct uclamp_se
1066 uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
1068 /* Copy by value as we could modify it */
1069 struct uclamp_se uc_req = p->uclamp_req[clamp_id];
1070 #ifdef CONFIG_UCLAMP_TASK_GROUP
1071 unsigned int tg_min, tg_max, value;
1074 * Tasks in autogroups or root task group will be
1075 * restricted by system defaults.
1077 if (task_group_is_autogroup(task_group(p)))
1079 if (task_group(p) == &root_task_group)
1082 tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
1083 tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
1084 value = uc_req.value;
1085 value = clamp(value, tg_min, tg_max);
1086 uclamp_se_set(&uc_req, value, false);
1093 * The effective clamp bucket index of a task depends on, by increasing
1095 * - the task specific clamp value, when explicitly requested from userspace
1096 * - the task group effective clamp value, for tasks not either in the root
1097 * group or in an autogroup
1098 * - the system default clamp value, defined by the sysadmin
1100 static inline struct uclamp_se
1101 uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
1103 struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
1104 struct uclamp_se uc_max = uclamp_default[clamp_id];
1106 /* System default restrictions always apply */
1107 if (unlikely(uc_req.value > uc_max.value))
1113 unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
1115 struct uclamp_se uc_eff;
1117 /* Task currently refcounted: use back-annotated (effective) value */
1118 if (p->uclamp[clamp_id].active)
1119 return (unsigned long)p->uclamp[clamp_id].value;
1121 uc_eff = uclamp_eff_get(p, clamp_id);
1123 return (unsigned long)uc_eff.value;
1127 * When a task is enqueued on a rq, the clamp bucket currently defined by the
1128 * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1129 * updates the rq's clamp value if required.
1131 * Tasks can have a task-specific value requested from user-space, track
1132 * within each bucket the maximum value for tasks refcounted in it.
1133 * This "local max aggregation" allows to track the exact "requested" value
1134 * for each bucket when all its RUNNABLE tasks require the same clamp.
1136 static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
1137 enum uclamp_id clamp_id)
1139 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1140 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1141 struct uclamp_bucket *bucket;
1143 lockdep_assert_held(&rq->lock);
1145 /* Update task effective clamp */
1146 p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
1148 bucket = &uc_rq->bucket[uc_se->bucket_id];
1150 uc_se->active = true;
1152 uclamp_idle_reset(rq, clamp_id, uc_se->value);
1155 * Local max aggregation: rq buckets always track the max
1156 * "requested" clamp value of its RUNNABLE tasks.
1158 if (bucket->tasks == 1 || uc_se->value > bucket->value)
1159 bucket->value = uc_se->value;
1161 if (uc_se->value > uclamp_rq_get(rq, clamp_id))
1162 uclamp_rq_set(rq, clamp_id, uc_se->value);
1166 * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1167 * is released. If this is the last task reference counting the rq's max
1168 * active clamp value, then the rq's clamp value is updated.
1170 * Both refcounted tasks and rq's cached clamp values are expected to be
1171 * always valid. If it's detected they are not, as defensive programming,
1172 * enforce the expected state and warn.
1174 static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
1175 enum uclamp_id clamp_id)
1177 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1178 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1179 struct uclamp_bucket *bucket;
1180 unsigned int bkt_clamp;
1181 unsigned int rq_clamp;
1183 lockdep_assert_held(&rq->lock);
1186 * If sched_uclamp_used was enabled after task @p was enqueued,
1187 * we could end up with unbalanced call to uclamp_rq_dec_id().
1189 * In this case the uc_se->active flag should be false since no uclamp
1190 * accounting was performed at enqueue time and we can just return
1193 * Need to be careful of the following enqeueue/dequeue ordering
1197 * // sched_uclamp_used gets enabled
1200 * // Must not decrement bukcet->tasks here
1203 * where we could end up with stale data in uc_se and
1204 * bucket[uc_se->bucket_id].
1206 * The following check here eliminates the possibility of such race.
1208 if (unlikely(!uc_se->active))
1211 bucket = &uc_rq->bucket[uc_se->bucket_id];
1213 SCHED_WARN_ON(!bucket->tasks);
1214 if (likely(bucket->tasks))
1217 uc_se->active = false;
1220 * Keep "local max aggregation" simple and accept to (possibly)
1221 * overboost some RUNNABLE tasks in the same bucket.
1222 * The rq clamp bucket value is reset to its base value whenever
1223 * there are no more RUNNABLE tasks refcounting it.
1225 if (likely(bucket->tasks))
1228 rq_clamp = uclamp_rq_get(rq, clamp_id);
1230 * Defensive programming: this should never happen. If it happens,
1231 * e.g. due to future modification, warn and fixup the expected value.
1233 SCHED_WARN_ON(bucket->value > rq_clamp);
1234 if (bucket->value >= rq_clamp) {
1235 bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
1236 uclamp_rq_set(rq, clamp_id, bkt_clamp);
1240 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
1242 enum uclamp_id clamp_id;
1245 * Avoid any overhead until uclamp is actually used by the userspace.
1247 * The condition is constructed such that a NOP is generated when
1248 * sched_uclamp_used is disabled.
1250 if (!static_branch_unlikely(&sched_uclamp_used))
1253 if (unlikely(!p->sched_class->uclamp_enabled))
1256 for_each_clamp_id(clamp_id)
1257 uclamp_rq_inc_id(rq, p, clamp_id);
1259 /* Reset clamp idle holding when there is one RUNNABLE task */
1260 if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
1261 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1264 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
1266 enum uclamp_id clamp_id;
1269 * Avoid any overhead until uclamp is actually used by the userspace.
1271 * The condition is constructed such that a NOP is generated when
1272 * sched_uclamp_used is disabled.
1274 if (!static_branch_unlikely(&sched_uclamp_used))
1277 if (unlikely(!p->sched_class->uclamp_enabled))
1280 for_each_clamp_id(clamp_id)
1281 uclamp_rq_dec_id(rq, p, clamp_id);
1284 static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
1285 enum uclamp_id clamp_id)
1287 if (!p->uclamp[clamp_id].active)
1290 uclamp_rq_dec_id(rq, p, clamp_id);
1291 uclamp_rq_inc_id(rq, p, clamp_id);
1294 * Make sure to clear the idle flag if we've transiently reached 0
1295 * active tasks on rq.
1297 if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1298 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1302 uclamp_update_active(struct task_struct *p)
1304 enum uclamp_id clamp_id;
1309 * Lock the task and the rq where the task is (or was) queued.
1311 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1312 * price to pay to safely serialize util_{min,max} updates with
1313 * enqueues, dequeues and migration operations.
1314 * This is the same locking schema used by __set_cpus_allowed_ptr().
1316 rq = task_rq_lock(p, &rf);
1319 * Setting the clamp bucket is serialized by task_rq_lock().
1320 * If the task is not yet RUNNABLE and its task_struct is not
1321 * affecting a valid clamp bucket, the next time it's enqueued,
1322 * it will already see the updated clamp bucket value.
1324 for_each_clamp_id(clamp_id)
1325 uclamp_rq_reinc_id(rq, p, clamp_id);
1327 task_rq_unlock(rq, p, &rf);
1330 #ifdef CONFIG_UCLAMP_TASK_GROUP
1332 uclamp_update_active_tasks(struct cgroup_subsys_state *css)
1334 struct css_task_iter it;
1335 struct task_struct *p;
1337 css_task_iter_start(css, 0, &it);
1338 while ((p = css_task_iter_next(&it)))
1339 uclamp_update_active(p);
1340 css_task_iter_end(&it);
1343 static void cpu_util_update_eff(struct cgroup_subsys_state *css);
1344 static void uclamp_update_root_tg(void)
1346 struct task_group *tg = &root_task_group;
1348 uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
1349 sysctl_sched_uclamp_util_min, false);
1350 uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
1351 sysctl_sched_uclamp_util_max, false);
1354 cpu_util_update_eff(&root_task_group.css);
1358 static void uclamp_update_root_tg(void) { }
1361 int sysctl_sched_uclamp_handler(struct ctl_table *table, int write,
1362 void *buffer, size_t *lenp, loff_t *ppos)
1364 bool update_root_tg = false;
1365 int old_min, old_max, old_min_rt;
1368 mutex_lock(&uclamp_mutex);
1369 old_min = sysctl_sched_uclamp_util_min;
1370 old_max = sysctl_sched_uclamp_util_max;
1371 old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
1373 result = proc_dointvec(table, write, buffer, lenp, ppos);
1379 if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
1380 sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE ||
1381 sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
1387 if (old_min != sysctl_sched_uclamp_util_min) {
1388 uclamp_se_set(&uclamp_default[UCLAMP_MIN],
1389 sysctl_sched_uclamp_util_min, false);
1390 update_root_tg = true;
1392 if (old_max != sysctl_sched_uclamp_util_max) {
1393 uclamp_se_set(&uclamp_default[UCLAMP_MAX],
1394 sysctl_sched_uclamp_util_max, false);
1395 update_root_tg = true;
1398 if (update_root_tg) {
1399 static_branch_enable(&sched_uclamp_used);
1400 uclamp_update_root_tg();
1403 if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
1404 static_branch_enable(&sched_uclamp_used);
1405 uclamp_sync_util_min_rt_default();
1409 * We update all RUNNABLE tasks only when task groups are in use.
1410 * Otherwise, keep it simple and do just a lazy update at each next
1411 * task enqueue time.
1417 sysctl_sched_uclamp_util_min = old_min;
1418 sysctl_sched_uclamp_util_max = old_max;
1419 sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
1421 mutex_unlock(&uclamp_mutex);
1426 static int uclamp_validate(struct task_struct *p,
1427 const struct sched_attr *attr)
1429 unsigned int lower_bound = p->uclamp_req[UCLAMP_MIN].value;
1430 unsigned int upper_bound = p->uclamp_req[UCLAMP_MAX].value;
1432 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN)
1433 lower_bound = attr->sched_util_min;
1434 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX)
1435 upper_bound = attr->sched_util_max;
1437 if (lower_bound > upper_bound)
1439 if (upper_bound > SCHED_CAPACITY_SCALE)
1443 * We have valid uclamp attributes; make sure uclamp is enabled.
1445 * We need to do that here, because enabling static branches is a
1446 * blocking operation which obviously cannot be done while holding
1449 static_branch_enable(&sched_uclamp_used);
1454 static void __setscheduler_uclamp(struct task_struct *p,
1455 const struct sched_attr *attr)
1457 enum uclamp_id clamp_id;
1460 * On scheduling class change, reset to default clamps for tasks
1461 * without a task-specific value.
1463 for_each_clamp_id(clamp_id) {
1464 struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
1466 /* Keep using defined clamps across class changes */
1467 if (uc_se->user_defined)
1471 * RT by default have a 100% boost value that could be modified
1474 if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
1475 __uclamp_update_util_min_rt_default(p);
1477 uclamp_se_set(uc_se, uclamp_none(clamp_id), false);
1481 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
1484 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
1485 uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
1486 attr->sched_util_min, true);
1489 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
1490 uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
1491 attr->sched_util_max, true);
1495 static void uclamp_fork(struct task_struct *p)
1497 enum uclamp_id clamp_id;
1500 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
1501 * as the task is still at its early fork stages.
1503 for_each_clamp_id(clamp_id)
1504 p->uclamp[clamp_id].active = false;
1506 if (likely(!p->sched_reset_on_fork))
1509 for_each_clamp_id(clamp_id) {
1510 uclamp_se_set(&p->uclamp_req[clamp_id],
1511 uclamp_none(clamp_id), false);
1515 static void uclamp_post_fork(struct task_struct *p)
1517 uclamp_update_util_min_rt_default(p);
1520 static void __init init_uclamp_rq(struct rq *rq)
1522 enum uclamp_id clamp_id;
1523 struct uclamp_rq *uc_rq = rq->uclamp;
1525 for_each_clamp_id(clamp_id) {
1526 uc_rq[clamp_id] = (struct uclamp_rq) {
1527 .value = uclamp_none(clamp_id)
1531 rq->uclamp_flags = UCLAMP_FLAG_IDLE;
1534 static void __init init_uclamp(void)
1536 struct uclamp_se uc_max = {};
1537 enum uclamp_id clamp_id;
1540 for_each_possible_cpu(cpu)
1541 init_uclamp_rq(cpu_rq(cpu));
1543 for_each_clamp_id(clamp_id) {
1544 uclamp_se_set(&init_task.uclamp_req[clamp_id],
1545 uclamp_none(clamp_id), false);
1548 /* System defaults allow max clamp values for both indexes */
1549 uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
1550 for_each_clamp_id(clamp_id) {
1551 uclamp_default[clamp_id] = uc_max;
1552 #ifdef CONFIG_UCLAMP_TASK_GROUP
1553 root_task_group.uclamp_req[clamp_id] = uc_max;
1554 root_task_group.uclamp[clamp_id] = uc_max;
1559 #else /* CONFIG_UCLAMP_TASK */
1560 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
1561 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
1562 static inline int uclamp_validate(struct task_struct *p,
1563 const struct sched_attr *attr)
1567 static void __setscheduler_uclamp(struct task_struct *p,
1568 const struct sched_attr *attr) { }
1569 static inline void uclamp_fork(struct task_struct *p) { }
1570 static inline void uclamp_post_fork(struct task_struct *p) { }
1571 static inline void init_uclamp(void) { }
1572 #endif /* CONFIG_UCLAMP_TASK */
1574 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
1576 if (!(flags & ENQUEUE_NOCLOCK))
1577 update_rq_clock(rq);
1579 if (!(flags & ENQUEUE_RESTORE)) {
1580 sched_info_queued(rq, p);
1581 psi_enqueue(p, flags & ENQUEUE_WAKEUP);
1584 uclamp_rq_inc(rq, p);
1585 p->sched_class->enqueue_task(rq, p, flags);
1588 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
1590 if (!(flags & DEQUEUE_NOCLOCK))
1591 update_rq_clock(rq);
1593 if (!(flags & DEQUEUE_SAVE)) {
1594 sched_info_dequeued(rq, p);
1595 psi_dequeue(p, flags & DEQUEUE_SLEEP);
1598 uclamp_rq_dec(rq, p);
1599 p->sched_class->dequeue_task(rq, p, flags);
1602 void activate_task(struct rq *rq, struct task_struct *p, int flags)
1604 if (task_on_rq_migrating(p))
1605 flags |= ENQUEUE_MIGRATED;
1607 enqueue_task(rq, p, flags);
1609 p->on_rq = TASK_ON_RQ_QUEUED;
1612 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1614 p->on_rq = (flags & DEQUEUE_SLEEP) ? 0 : TASK_ON_RQ_MIGRATING;
1616 dequeue_task(rq, p, flags);
1619 static inline int __normal_prio(int policy, int rt_prio, int nice)
1623 if (dl_policy(policy))
1624 prio = MAX_DL_PRIO - 1;
1625 else if (rt_policy(policy))
1626 prio = MAX_RT_PRIO - 1 - rt_prio;
1628 prio = NICE_TO_PRIO(nice);
1634 * Calculate the expected normal priority: i.e. priority
1635 * without taking RT-inheritance into account. Might be
1636 * boosted by interactivity modifiers. Changes upon fork,
1637 * setprio syscalls, and whenever the interactivity
1638 * estimator recalculates.
1640 static inline int normal_prio(struct task_struct *p)
1642 return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio));
1646 * Calculate the current priority, i.e. the priority
1647 * taken into account by the scheduler. This value might
1648 * be boosted by RT tasks, or might be boosted by
1649 * interactivity modifiers. Will be RT if the task got
1650 * RT-boosted. If not then it returns p->normal_prio.
1652 static int effective_prio(struct task_struct *p)
1654 p->normal_prio = normal_prio(p);
1656 * If we are RT tasks or we were boosted to RT priority,
1657 * keep the priority unchanged. Otherwise, update priority
1658 * to the normal priority:
1660 if (!rt_prio(p->prio))
1661 return p->normal_prio;
1666 * task_curr - is this task currently executing on a CPU?
1667 * @p: the task in question.
1669 * Return: 1 if the task is currently executing. 0 otherwise.
1671 inline int task_curr(const struct task_struct *p)
1673 return cpu_curr(task_cpu(p)) == p;
1677 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
1678 * use the balance_callback list if you want balancing.
1680 * this means any call to check_class_changed() must be followed by a call to
1681 * balance_callback().
1683 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1684 const struct sched_class *prev_class,
1687 if (prev_class != p->sched_class) {
1688 if (prev_class->switched_from)
1689 prev_class->switched_from(rq, p);
1691 p->sched_class->switched_to(rq, p);
1692 } else if (oldprio != p->prio || dl_task(p))
1693 p->sched_class->prio_changed(rq, p, oldprio);
1696 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1698 if (p->sched_class == rq->curr->sched_class)
1699 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
1700 else if (p->sched_class > rq->curr->sched_class)
1704 * A queue event has occurred, and we're going to schedule. In
1705 * this case, we can save a useless back to back clock update.
1707 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
1708 rq_clock_skip_update(rq);
1714 * Per-CPU kthreads are allowed to run on !active && online CPUs, see
1715 * __set_cpus_allowed_ptr() and select_fallback_rq().
1717 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
1719 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
1722 if (is_per_cpu_kthread(p))
1723 return cpu_online(cpu);
1725 return cpu_active(cpu);
1729 * This is how migration works:
1731 * 1) we invoke migration_cpu_stop() on the target CPU using
1733 * 2) stopper starts to run (implicitly forcing the migrated thread
1735 * 3) it checks whether the migrated task is still in the wrong runqueue.
1736 * 4) if it's in the wrong runqueue then the migration thread removes
1737 * it and puts it into the right queue.
1738 * 5) stopper completes and stop_one_cpu() returns and the migration
1743 * move_queued_task - move a queued task to new rq.
1745 * Returns (locked) new rq. Old rq's lock is released.
1747 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
1748 struct task_struct *p, int new_cpu)
1750 lockdep_assert_held(&rq->lock);
1752 deactivate_task(rq, p, DEQUEUE_NOCLOCK);
1753 set_task_cpu(p, new_cpu);
1756 rq = cpu_rq(new_cpu);
1759 BUG_ON(task_cpu(p) != new_cpu);
1760 activate_task(rq, p, 0);
1761 check_preempt_curr(rq, p, 0);
1766 struct migration_arg {
1767 struct task_struct *task;
1772 * Move (not current) task off this CPU, onto the destination CPU. We're doing
1773 * this because either it can't run here any more (set_cpus_allowed()
1774 * away from this CPU, or CPU going down), or because we're
1775 * attempting to rebalance this task on exec (sched_exec).
1777 * So we race with normal scheduler movements, but that's OK, as long
1778 * as the task is no longer on this CPU.
1780 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
1781 struct task_struct *p, int dest_cpu)
1783 /* Affinity changed (again). */
1784 if (!is_cpu_allowed(p, dest_cpu))
1787 update_rq_clock(rq);
1788 rq = move_queued_task(rq, rf, p, dest_cpu);
1794 * migration_cpu_stop - this will be executed by a highprio stopper thread
1795 * and performs thread migration by bumping thread off CPU then
1796 * 'pushing' onto another runqueue.
1798 static int migration_cpu_stop(void *data)
1800 struct migration_arg *arg = data;
1801 struct task_struct *p = arg->task;
1802 struct rq *rq = this_rq();
1806 * The original target CPU might have gone down and we might
1807 * be on another CPU but it doesn't matter.
1809 local_irq_disable();
1811 * We need to explicitly wake pending tasks before running
1812 * __migrate_task() such that we will not miss enforcing cpus_ptr
1813 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1815 flush_smp_call_function_from_idle();
1817 raw_spin_lock(&p->pi_lock);
1820 * If task_rq(p) != rq, it cannot be migrated here, because we're
1821 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1822 * we're holding p->pi_lock.
1824 if (task_rq(p) == rq) {
1825 if (task_on_rq_queued(p))
1826 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
1828 p->wake_cpu = arg->dest_cpu;
1831 raw_spin_unlock(&p->pi_lock);
1838 * sched_class::set_cpus_allowed must do the below, but is not required to
1839 * actually call this function.
1841 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1843 cpumask_copy(&p->cpus_mask, new_mask);
1844 p->nr_cpus_allowed = cpumask_weight(new_mask);
1847 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1849 struct rq *rq = task_rq(p);
1850 bool queued, running;
1852 lockdep_assert_held(&p->pi_lock);
1854 queued = task_on_rq_queued(p);
1855 running = task_current(rq, p);
1859 * Because __kthread_bind() calls this on blocked tasks without
1862 lockdep_assert_held(&rq->lock);
1863 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
1866 put_prev_task(rq, p);
1868 p->sched_class->set_cpus_allowed(p, new_mask);
1871 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1873 set_next_task(rq, p);
1877 * Change a given task's CPU affinity. Migrate the thread to a
1878 * proper CPU and schedule it away if the CPU it's executing on
1879 * is removed from the allowed bitmask.
1881 * NOTE: the caller must have a valid reference to the task, the
1882 * task must not exit() & deallocate itself prematurely. The
1883 * call is not atomic; no spinlocks may be held.
1885 static int __set_cpus_allowed_ptr(struct task_struct *p,
1886 const struct cpumask *new_mask, bool check)
1888 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1889 unsigned int dest_cpu;
1894 rq = task_rq_lock(p, &rf);
1895 update_rq_clock(rq);
1897 if (p->flags & PF_KTHREAD) {
1899 * Kernel threads are allowed on online && !active CPUs
1901 cpu_valid_mask = cpu_online_mask;
1905 * Must re-check here, to close a race against __kthread_bind(),
1906 * sched_setaffinity() is not guaranteed to observe the flag.
1908 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1913 if (cpumask_equal(&p->cpus_mask, new_mask))
1917 * Picking a ~random cpu helps in cases where we are changing affinity
1918 * for groups of tasks (ie. cpuset), so that load balancing is not
1919 * immediately required to distribute the tasks within their new mask.
1921 dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, new_mask);
1922 if (dest_cpu >= nr_cpu_ids) {
1927 do_set_cpus_allowed(p, new_mask);
1929 if (p->flags & PF_KTHREAD) {
1931 * For kernel threads that do indeed end up on online &&
1932 * !active we want to ensure they are strict per-CPU threads.
1934 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1935 !cpumask_intersects(new_mask, cpu_active_mask) &&
1936 p->nr_cpus_allowed != 1);
1939 /* Can the task run on the task's current CPU? If so, we're done */
1940 if (cpumask_test_cpu(task_cpu(p), new_mask))
1943 if (task_running(rq, p) || p->state == TASK_WAKING) {
1944 struct migration_arg arg = { p, dest_cpu };
1945 /* Need help from migration thread: drop lock and wait. */
1946 task_rq_unlock(rq, p, &rf);
1947 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1949 } else if (task_on_rq_queued(p)) {
1951 * OK, since we're going to drop the lock immediately
1952 * afterwards anyway.
1954 rq = move_queued_task(rq, &rf, p, dest_cpu);
1957 task_rq_unlock(rq, p, &rf);
1962 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1964 return __set_cpus_allowed_ptr(p, new_mask, false);
1966 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1968 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1970 #ifdef CONFIG_SCHED_DEBUG
1972 * We should never call set_task_cpu() on a blocked task,
1973 * ttwu() will sort out the placement.
1975 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1979 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1980 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1981 * time relying on p->on_rq.
1983 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1984 p->sched_class == &fair_sched_class &&
1985 (p->on_rq && !task_on_rq_migrating(p)));
1987 #ifdef CONFIG_LOCKDEP
1989 * The caller should hold either p->pi_lock or rq->lock, when changing
1990 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1992 * sched_move_task() holds both and thus holding either pins the cgroup,
1995 * Furthermore, all task_rq users should acquire both locks, see
1998 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1999 lockdep_is_held(&task_rq(p)->lock)));
2002 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
2004 WARN_ON_ONCE(!cpu_online(new_cpu));
2007 trace_sched_migrate_task(p, new_cpu);
2009 if (task_cpu(p) != new_cpu) {
2010 if (p->sched_class->migrate_task_rq)
2011 p->sched_class->migrate_task_rq(p, new_cpu);
2012 p->se.nr_migrations++;
2014 perf_event_task_migrate(p);
2017 __set_task_cpu(p, new_cpu);
2020 #ifdef CONFIG_NUMA_BALANCING
2021 static void __migrate_swap_task(struct task_struct *p, int cpu)
2023 if (task_on_rq_queued(p)) {
2024 struct rq *src_rq, *dst_rq;
2025 struct rq_flags srf, drf;
2027 src_rq = task_rq(p);
2028 dst_rq = cpu_rq(cpu);
2030 rq_pin_lock(src_rq, &srf);
2031 rq_pin_lock(dst_rq, &drf);
2033 deactivate_task(src_rq, p, 0);
2034 set_task_cpu(p, cpu);
2035 activate_task(dst_rq, p, 0);
2036 check_preempt_curr(dst_rq, p, 0);
2038 rq_unpin_lock(dst_rq, &drf);
2039 rq_unpin_lock(src_rq, &srf);
2043 * Task isn't running anymore; make it appear like we migrated
2044 * it before it went to sleep. This means on wakeup we make the
2045 * previous CPU our target instead of where it really is.
2051 struct migration_swap_arg {
2052 struct task_struct *src_task, *dst_task;
2053 int src_cpu, dst_cpu;
2056 static int migrate_swap_stop(void *data)
2058 struct migration_swap_arg *arg = data;
2059 struct rq *src_rq, *dst_rq;
2062 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
2065 src_rq = cpu_rq(arg->src_cpu);
2066 dst_rq = cpu_rq(arg->dst_cpu);
2068 double_raw_lock(&arg->src_task->pi_lock,
2069 &arg->dst_task->pi_lock);
2070 double_rq_lock(src_rq, dst_rq);
2072 if (task_cpu(arg->dst_task) != arg->dst_cpu)
2075 if (task_cpu(arg->src_task) != arg->src_cpu)
2078 if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
2081 if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
2084 __migrate_swap_task(arg->src_task, arg->dst_cpu);
2085 __migrate_swap_task(arg->dst_task, arg->src_cpu);
2090 double_rq_unlock(src_rq, dst_rq);
2091 raw_spin_unlock(&arg->dst_task->pi_lock);
2092 raw_spin_unlock(&arg->src_task->pi_lock);
2098 * Cross migrate two tasks
2100 int migrate_swap(struct task_struct *cur, struct task_struct *p,
2101 int target_cpu, int curr_cpu)
2103 struct migration_swap_arg arg;
2106 arg = (struct migration_swap_arg){
2108 .src_cpu = curr_cpu,
2110 .dst_cpu = target_cpu,
2113 if (arg.src_cpu == arg.dst_cpu)
2117 * These three tests are all lockless; this is OK since all of them
2118 * will be re-checked with proper locks held further down the line.
2120 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
2123 if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
2126 if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
2129 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
2130 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
2135 #endif /* CONFIG_NUMA_BALANCING */
2138 * wait_task_inactive - wait for a thread to unschedule.
2140 * If @match_state is nonzero, it's the @p->state value just checked and
2141 * not expected to change. If it changes, i.e. @p might have woken up,
2142 * then return zero. When we succeed in waiting for @p to be off its CPU,
2143 * we return a positive number (its total switch count). If a second call
2144 * a short while later returns the same number, the caller can be sure that
2145 * @p has remained unscheduled the whole time.
2147 * The caller must ensure that the task *will* unschedule sometime soon,
2148 * else this function might spin for a *long* time. This function can't
2149 * be called with interrupts off, or it may introduce deadlock with
2150 * smp_call_function() if an IPI is sent by the same process we are
2151 * waiting to become inactive.
2153 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2155 int running, queued;
2162 * We do the initial early heuristics without holding
2163 * any task-queue locks at all. We'll only try to get
2164 * the runqueue lock when things look like they will
2170 * If the task is actively running on another CPU
2171 * still, just relax and busy-wait without holding
2174 * NOTE! Since we don't hold any locks, it's not
2175 * even sure that "rq" stays as the right runqueue!
2176 * But we don't care, since "task_running()" will
2177 * return false if the runqueue has changed and p
2178 * is actually now running somewhere else!
2180 while (task_running(rq, p)) {
2181 if (match_state && unlikely(p->state != match_state))
2187 * Ok, time to look more closely! We need the rq
2188 * lock now, to be *sure*. If we're wrong, we'll
2189 * just go back and repeat.
2191 rq = task_rq_lock(p, &rf);
2192 trace_sched_wait_task(p);
2193 running = task_running(rq, p);
2194 queued = task_on_rq_queued(p);
2196 if (!match_state || p->state == match_state)
2197 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2198 task_rq_unlock(rq, p, &rf);
2201 * If it changed from the expected state, bail out now.
2203 if (unlikely(!ncsw))
2207 * Was it really running after all now that we
2208 * checked with the proper locks actually held?
2210 * Oops. Go back and try again..
2212 if (unlikely(running)) {
2218 * It's not enough that it's not actively running,
2219 * it must be off the runqueue _entirely_, and not
2222 * So if it was still runnable (but just not actively
2223 * running right now), it's preempted, and we should
2224 * yield - it could be a while.
2226 if (unlikely(queued)) {
2227 ktime_t to = NSEC_PER_SEC / HZ;
2229 set_current_state(TASK_UNINTERRUPTIBLE);
2230 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
2235 * Ahh, all good. It wasn't running, and it wasn't
2236 * runnable, which means that it will never become
2237 * running in the future either. We're all done!
2246 * kick_process - kick a running thread to enter/exit the kernel
2247 * @p: the to-be-kicked thread
2249 * Cause a process which is running on another CPU to enter
2250 * kernel-mode, without any delay. (to get signals handled.)
2252 * NOTE: this function doesn't have to take the runqueue lock,
2253 * because all it wants to ensure is that the remote task enters
2254 * the kernel. If the IPI races and the task has been migrated
2255 * to another CPU then no harm is done and the purpose has been
2258 void kick_process(struct task_struct *p)
2264 if ((cpu != smp_processor_id()) && task_curr(p))
2265 smp_send_reschedule(cpu);
2268 EXPORT_SYMBOL_GPL(kick_process);
2271 * ->cpus_ptr is protected by both rq->lock and p->pi_lock
2273 * A few notes on cpu_active vs cpu_online:
2275 * - cpu_active must be a subset of cpu_online
2277 * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
2278 * see __set_cpus_allowed_ptr(). At this point the newly online
2279 * CPU isn't yet part of the sched domains, and balancing will not
2282 * - on CPU-down we clear cpu_active() to mask the sched domains and
2283 * avoid the load balancer to place new tasks on the to be removed
2284 * CPU. Existing tasks will remain running there and will be taken
2287 * This means that fallback selection must not select !active CPUs.
2288 * And can assume that any active CPU must be online. Conversely
2289 * select_task_rq() below may allow selection of !active CPUs in order
2290 * to satisfy the above rules.
2292 static int select_fallback_rq(int cpu, struct task_struct *p)
2294 int nid = cpu_to_node(cpu);
2295 const struct cpumask *nodemask = NULL;
2296 enum { cpuset, possible, fail } state = cpuset;
2300 * If the node that the CPU is on has been offlined, cpu_to_node()
2301 * will return -1. There is no CPU on the node, and we should
2302 * select the CPU on the other node.
2305 nodemask = cpumask_of_node(nid);
2307 /* Look for allowed, online CPU in same node. */
2308 for_each_cpu(dest_cpu, nodemask) {
2309 if (!cpu_active(dest_cpu))
2311 if (cpumask_test_cpu(dest_cpu, p->cpus_ptr))
2317 /* Any allowed, online CPU? */
2318 for_each_cpu(dest_cpu, p->cpus_ptr) {
2319 if (!is_cpu_allowed(p, dest_cpu))
2325 /* No more Mr. Nice Guy. */
2328 if (IS_ENABLED(CONFIG_CPUSETS)) {
2329 cpuset_cpus_allowed_fallback(p);
2335 do_set_cpus_allowed(p, cpu_possible_mask);
2346 if (state != cpuset) {
2348 * Don't tell them about moving exiting tasks or
2349 * kernel threads (both mm NULL), since they never
2352 if (p->mm && printk_ratelimit()) {
2353 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
2354 task_pid_nr(p), p->comm, cpu);
2362 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
2365 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
2367 lockdep_assert_held(&p->pi_lock);
2369 if (p->nr_cpus_allowed > 1)
2370 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
2372 cpu = cpumask_any(p->cpus_ptr);
2375 * In order not to call set_task_cpu() on a blocking task we need
2376 * to rely on ttwu() to place the task on a valid ->cpus_ptr
2379 * Since this is common to all placement strategies, this lives here.
2381 * [ this allows ->select_task() to simply return task_cpu(p) and
2382 * not worry about this generic constraint ]
2384 if (unlikely(!is_cpu_allowed(p, cpu)))
2385 cpu = select_fallback_rq(task_cpu(p), p);
2390 void sched_set_stop_task(int cpu, struct task_struct *stop)
2392 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
2393 struct task_struct *old_stop = cpu_rq(cpu)->stop;
2397 * Make it appear like a SCHED_FIFO task, its something
2398 * userspace knows about and won't get confused about.
2400 * Also, it will make PI more or less work without too
2401 * much confusion -- but then, stop work should not
2402 * rely on PI working anyway.
2404 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
2406 stop->sched_class = &stop_sched_class;
2409 cpu_rq(cpu)->stop = stop;
2413 * Reset it back to a normal scheduling class so that
2414 * it can die in pieces.
2416 old_stop->sched_class = &rt_sched_class;
2422 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
2423 const struct cpumask *new_mask, bool check)
2425 return set_cpus_allowed_ptr(p, new_mask);
2428 #endif /* CONFIG_SMP */
2431 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
2435 if (!schedstat_enabled())
2441 if (cpu == rq->cpu) {
2442 __schedstat_inc(rq->ttwu_local);
2443 __schedstat_inc(p->se.statistics.nr_wakeups_local);
2445 struct sched_domain *sd;
2447 __schedstat_inc(p->se.statistics.nr_wakeups_remote);
2449 for_each_domain(rq->cpu, sd) {
2450 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2451 __schedstat_inc(sd->ttwu_wake_remote);
2458 if (wake_flags & WF_MIGRATED)
2459 __schedstat_inc(p->se.statistics.nr_wakeups_migrate);
2460 #endif /* CONFIG_SMP */
2462 __schedstat_inc(rq->ttwu_count);
2463 __schedstat_inc(p->se.statistics.nr_wakeups);
2465 if (wake_flags & WF_SYNC)
2466 __schedstat_inc(p->se.statistics.nr_wakeups_sync);
2470 * Mark the task runnable and perform wakeup-preemption.
2472 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
2473 struct rq_flags *rf)
2475 check_preempt_curr(rq, p, wake_flags);
2476 p->state = TASK_RUNNING;
2477 trace_sched_wakeup(p);
2480 if (p->sched_class->task_woken) {
2482 * Our task @p is fully woken up and running; so its safe to
2483 * drop the rq->lock, hereafter rq is only used for statistics.
2485 rq_unpin_lock(rq, rf);
2486 p->sched_class->task_woken(rq, p);
2487 rq_repin_lock(rq, rf);
2490 if (rq->idle_stamp) {
2491 u64 delta = rq_clock(rq) - rq->idle_stamp;
2492 u64 max = 2*rq->max_idle_balance_cost;
2494 update_avg(&rq->avg_idle, delta);
2496 if (rq->avg_idle > max)
2505 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
2506 struct rq_flags *rf)
2508 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
2510 lockdep_assert_held(&rq->lock);
2512 if (p->sched_contributes_to_load)
2513 rq->nr_uninterruptible--;
2516 if (wake_flags & WF_MIGRATED)
2517 en_flags |= ENQUEUE_MIGRATED;
2521 delayacct_blkio_end(p);
2522 atomic_dec(&task_rq(p)->nr_iowait);
2525 activate_task(rq, p, en_flags);
2526 ttwu_do_wakeup(rq, p, wake_flags, rf);
2530 * Consider @p being inside a wait loop:
2533 * set_current_state(TASK_UNINTERRUPTIBLE);
2540 * __set_current_state(TASK_RUNNING);
2542 * between set_current_state() and schedule(). In this case @p is still
2543 * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
2546 * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
2547 * then schedule() must still happen and p->state can be changed to
2548 * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
2549 * need to do a full wakeup with enqueue.
2551 * Returns: %true when the wakeup is done,
2554 static int ttwu_runnable(struct task_struct *p, int wake_flags)
2560 rq = __task_rq_lock(p, &rf);
2561 if (task_on_rq_queued(p)) {
2562 /* check_preempt_curr() may use rq clock */
2563 update_rq_clock(rq);
2564 ttwu_do_wakeup(rq, p, wake_flags, &rf);
2567 __task_rq_unlock(rq, &rf);
2573 void sched_ttwu_pending(void *arg)
2575 struct llist_node *llist = arg;
2576 struct rq *rq = this_rq();
2577 struct task_struct *p, *t;
2584 * rq::ttwu_pending racy indication of out-standing wakeups.
2585 * Races such that false-negatives are possible, since they
2586 * are shorter lived that false-positives would be.
2588 WRITE_ONCE(rq->ttwu_pending, 0);
2590 rq_lock_irqsave(rq, &rf);
2591 update_rq_clock(rq);
2593 llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
2594 if (WARN_ON_ONCE(p->on_cpu))
2595 smp_cond_load_acquire(&p->on_cpu, !VAL);
2597 if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
2598 set_task_cpu(p, cpu_of(rq));
2600 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
2603 rq_unlock_irqrestore(rq, &rf);
2606 void send_call_function_single_ipi(int cpu)
2608 struct rq *rq = cpu_rq(cpu);
2610 if (!set_nr_if_polling(rq->idle))
2611 arch_send_call_function_single_ipi(cpu);
2613 trace_sched_wake_idle_without_ipi(cpu);
2617 * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
2618 * necessary. The wakee CPU on receipt of the IPI will queue the task
2619 * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
2620 * of the wakeup instead of the waker.
2622 static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
2624 struct rq *rq = cpu_rq(cpu);
2626 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
2628 WRITE_ONCE(rq->ttwu_pending, 1);
2629 __smp_call_single_queue(cpu, &p->wake_entry.llist);
2632 void wake_up_if_idle(int cpu)
2634 struct rq *rq = cpu_rq(cpu);
2639 if (!is_idle_task(rcu_dereference(rq->curr)))
2642 if (set_nr_if_polling(rq->idle)) {
2643 trace_sched_wake_idle_without_ipi(cpu);
2645 rq_lock_irqsave(rq, &rf);
2646 if (is_idle_task(rq->curr))
2647 smp_send_reschedule(cpu);
2648 /* Else CPU is not idle, do nothing here: */
2649 rq_unlock_irqrestore(rq, &rf);
2656 bool cpus_share_cache(int this_cpu, int that_cpu)
2658 if (this_cpu == that_cpu)
2661 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
2664 static inline bool ttwu_queue_cond(int cpu, int wake_flags)
2667 * If the CPU does not share cache, then queue the task on the
2668 * remote rqs wakelist to avoid accessing remote data.
2670 if (!cpus_share_cache(smp_processor_id(), cpu))
2674 * If the task is descheduling and the only running task on the
2675 * CPU then use the wakelist to offload the task activation to
2676 * the soon-to-be-idle CPU as the current CPU is likely busy.
2677 * nr_running is checked to avoid unnecessary task stacking.
2679 * Note that we can only get here with (wakee) p->on_rq=0,
2680 * p->on_cpu can be whatever, we've done the dequeue, so
2681 * the wakee has been accounted out of ->nr_running.
2683 if ((wake_flags & WF_ON_CPU) && !cpu_rq(cpu)->nr_running)
2689 static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
2691 if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(cpu, wake_flags)) {
2692 if (WARN_ON_ONCE(cpu == smp_processor_id()))
2695 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
2696 __ttwu_queue_wakelist(p, cpu, wake_flags);
2703 #else /* !CONFIG_SMP */
2705 static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
2710 #endif /* CONFIG_SMP */
2712 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
2714 struct rq *rq = cpu_rq(cpu);
2717 if (ttwu_queue_wakelist(p, cpu, wake_flags))
2721 update_rq_clock(rq);
2722 ttwu_do_activate(rq, p, wake_flags, &rf);
2727 * Notes on Program-Order guarantees on SMP systems.
2731 * The basic program-order guarantee on SMP systems is that when a task [t]
2732 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
2733 * execution on its new CPU [c1].
2735 * For migration (of runnable tasks) this is provided by the following means:
2737 * A) UNLOCK of the rq(c0)->lock scheduling out task t
2738 * B) migration for t is required to synchronize *both* rq(c0)->lock and
2739 * rq(c1)->lock (if not at the same time, then in that order).
2740 * C) LOCK of the rq(c1)->lock scheduling in task
2742 * Release/acquire chaining guarantees that B happens after A and C after B.
2743 * Note: the CPU doing B need not be c0 or c1
2752 * UNLOCK rq(0)->lock
2754 * LOCK rq(0)->lock // orders against CPU0
2756 * UNLOCK rq(0)->lock
2760 * UNLOCK rq(1)->lock
2762 * LOCK rq(1)->lock // orders against CPU2
2765 * UNLOCK rq(1)->lock
2768 * BLOCKING -- aka. SLEEP + WAKEUP
2770 * For blocking we (obviously) need to provide the same guarantee as for
2771 * migration. However the means are completely different as there is no lock
2772 * chain to provide order. Instead we do:
2774 * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
2775 * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
2779 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
2781 * LOCK rq(0)->lock LOCK X->pi_lock
2784 * smp_store_release(X->on_cpu, 0);
2786 * smp_cond_load_acquire(&X->on_cpu, !VAL);
2792 * X->state = RUNNING
2793 * UNLOCK rq(2)->lock
2795 * LOCK rq(2)->lock // orders against CPU1
2798 * UNLOCK rq(2)->lock
2801 * UNLOCK rq(0)->lock
2804 * However, for wakeups there is a second guarantee we must provide, namely we
2805 * must ensure that CONDITION=1 done by the caller can not be reordered with
2806 * accesses to the task state; see try_to_wake_up() and set_current_state().
2810 * try_to_wake_up - wake up a thread
2811 * @p: the thread to be awakened
2812 * @state: the mask of task states that can be woken
2813 * @wake_flags: wake modifier flags (WF_*)
2815 * Conceptually does:
2817 * If (@state & @p->state) @p->state = TASK_RUNNING.
2819 * If the task was not queued/runnable, also place it back on a runqueue.
2821 * This function is atomic against schedule() which would dequeue the task.
2823 * It issues a full memory barrier before accessing @p->state, see the comment
2824 * with set_current_state().
2826 * Uses p->pi_lock to serialize against concurrent wake-ups.
2828 * Relies on p->pi_lock stabilizing:
2831 * - p->sched_task_group
2832 * in order to do migration, see its use of select_task_rq()/set_task_cpu().
2834 * Tries really hard to only take one task_rq(p)->lock for performance.
2835 * Takes rq->lock in:
2836 * - ttwu_runnable() -- old rq, unavoidable, see comment there;
2837 * - ttwu_queue() -- new rq, for enqueue of the task;
2838 * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
2840 * As a consequence we race really badly with just about everything. See the
2841 * many memory barriers and their comments for details.
2843 * Return: %true if @p->state changes (an actual wakeup was done),
2847 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
2849 unsigned long flags;
2850 int cpu, success = 0;
2855 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
2856 * == smp_processor_id()'. Together this means we can special
2857 * case the whole 'p->on_rq && ttwu_runnable()' case below
2858 * without taking any locks.
2861 * - we rely on Program-Order guarantees for all the ordering,
2862 * - we're serialized against set_special_state() by virtue of
2863 * it disabling IRQs (this allows not taking ->pi_lock).
2865 if (!(p->state & state))
2869 trace_sched_waking(p);
2870 p->state = TASK_RUNNING;
2871 trace_sched_wakeup(p);
2876 * If we are going to wake up a thread waiting for CONDITION we
2877 * need to ensure that CONDITION=1 done by the caller can not be
2878 * reordered with p->state check below. This pairs with smp_store_mb()
2879 * in set_current_state() that the waiting thread does.
2881 raw_spin_lock_irqsave(&p->pi_lock, flags);
2882 smp_mb__after_spinlock();
2883 if (!(p->state & state))
2886 trace_sched_waking(p);
2888 /* We're going to change ->state: */
2892 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2893 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2894 * in smp_cond_load_acquire() below.
2896 * sched_ttwu_pending() try_to_wake_up()
2897 * STORE p->on_rq = 1 LOAD p->state
2900 * __schedule() (switch to task 'p')
2901 * LOCK rq->lock smp_rmb();
2902 * smp_mb__after_spinlock();
2906 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
2908 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
2909 * __schedule(). See the comment for smp_mb__after_spinlock().
2911 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
2914 if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
2919 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2920 * possible to, falsely, observe p->on_cpu == 0.
2922 * One must be running (->on_cpu == 1) in order to remove oneself
2923 * from the runqueue.
2925 * __schedule() (switch to task 'p') try_to_wake_up()
2926 * STORE p->on_cpu = 1 LOAD p->on_rq
2929 * __schedule() (put 'p' to sleep)
2930 * LOCK rq->lock smp_rmb();
2931 * smp_mb__after_spinlock();
2932 * STORE p->on_rq = 0 LOAD p->on_cpu
2934 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
2935 * __schedule(). See the comment for smp_mb__after_spinlock().
2937 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
2938 * schedule()'s deactivate_task() has 'happened' and p will no longer
2939 * care about it's own p->state. See the comment in __schedule().
2941 smp_acquire__after_ctrl_dep();
2944 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
2945 * == 0), which means we need to do an enqueue, change p->state to
2946 * TASK_WAKING such that we can unlock p->pi_lock before doing the
2947 * enqueue, such as ttwu_queue_wakelist().
2949 p->state = TASK_WAKING;
2952 * If the owning (remote) CPU is still in the middle of schedule() with
2953 * this task as prev, considering queueing p on the remote CPUs wake_list
2954 * which potentially sends an IPI instead of spinning on p->on_cpu to
2955 * let the waker make forward progress. This is safe because IRQs are
2956 * disabled and the IPI will deliver after on_cpu is cleared.
2958 * Ensure we load task_cpu(p) after p->on_cpu:
2960 * set_task_cpu(p, cpu);
2961 * STORE p->cpu = @cpu
2962 * __schedule() (switch to task 'p')
2964 * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
2965 * STORE p->on_cpu = 1 LOAD p->cpu
2967 * to ensure we observe the correct CPU on which the task is currently
2970 if (smp_load_acquire(&p->on_cpu) &&
2971 ttwu_queue_wakelist(p, task_cpu(p), wake_flags | WF_ON_CPU))
2975 * If the owning (remote) CPU is still in the middle of schedule() with
2976 * this task as prev, wait until its done referencing the task.
2978 * Pairs with the smp_store_release() in finish_task().
2980 * This ensures that tasks getting woken will be fully ordered against
2981 * their previous state and preserve Program Order.
2983 smp_cond_load_acquire(&p->on_cpu, !VAL);
2985 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2986 if (task_cpu(p) != cpu) {
2988 delayacct_blkio_end(p);
2989 atomic_dec(&task_rq(p)->nr_iowait);
2992 wake_flags |= WF_MIGRATED;
2993 psi_ttwu_dequeue(p);
2994 set_task_cpu(p, cpu);
2998 #endif /* CONFIG_SMP */
3000 ttwu_queue(p, cpu, wake_flags);
3002 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3005 ttwu_stat(p, task_cpu(p), wake_flags);
3012 * try_invoke_on_locked_down_task - Invoke a function on task in fixed state
3013 * @p: Process for which the function is to be invoked, can be @current.
3014 * @func: Function to invoke.
3015 * @arg: Argument to function.
3017 * If the specified task can be quickly locked into a definite state
3018 * (either sleeping or on a given runqueue), arrange to keep it in that
3019 * state while invoking @func(@arg). This function can use ->on_rq and
3020 * task_curr() to work out what the state is, if required. Given that
3021 * @func can be invoked with a runqueue lock held, it had better be quite
3025 * @false if the task slipped out from under the locks.
3026 * @true if the task was locked onto a runqueue or is sleeping.
3027 * However, @func can override this by returning @false.
3029 bool try_invoke_on_locked_down_task(struct task_struct *p, bool (*func)(struct task_struct *t, void *arg), void *arg)
3035 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
3037 rq = __task_rq_lock(p, &rf);
3038 if (task_rq(p) == rq)
3047 smp_rmb(); // See smp_rmb() comment in try_to_wake_up().
3052 raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
3057 * wake_up_process - Wake up a specific process
3058 * @p: The process to be woken up.
3060 * Attempt to wake up the nominated process and move it to the set of runnable
3063 * Return: 1 if the process was woken up, 0 if it was already running.
3065 * This function executes a full memory barrier before accessing the task state.
3067 int wake_up_process(struct task_struct *p)
3069 return try_to_wake_up(p, TASK_NORMAL, 0);
3071 EXPORT_SYMBOL(wake_up_process);
3073 int wake_up_state(struct task_struct *p, unsigned int state)
3075 return try_to_wake_up(p, state, 0);
3079 * Perform scheduler related setup for a newly forked process p.
3080 * p is forked by current.
3082 * __sched_fork() is basic setup used by init_idle() too:
3084 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
3089 p->se.exec_start = 0;
3090 p->se.sum_exec_runtime = 0;
3091 p->se.prev_sum_exec_runtime = 0;
3092 p->se.nr_migrations = 0;
3094 INIT_LIST_HEAD(&p->se.group_node);
3096 #ifdef CONFIG_FAIR_GROUP_SCHED
3097 p->se.cfs_rq = NULL;
3100 #ifdef CONFIG_SCHEDSTATS
3101 /* Even if schedstat is disabled, there should not be garbage */
3102 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
3105 RB_CLEAR_NODE(&p->dl.rb_node);
3106 init_dl_task_timer(&p->dl);
3107 init_dl_inactive_task_timer(&p->dl);
3108 __dl_clear_params(p);
3110 INIT_LIST_HEAD(&p->rt.run_list);
3112 p->rt.time_slice = sched_rr_timeslice;
3116 #ifdef CONFIG_PREEMPT_NOTIFIERS
3117 INIT_HLIST_HEAD(&p->preempt_notifiers);
3120 #ifdef CONFIG_COMPACTION
3121 p->capture_control = NULL;
3123 init_numa_balancing(clone_flags, p);
3125 p->wake_entry.u_flags = CSD_TYPE_TTWU;
3129 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
3131 #ifdef CONFIG_NUMA_BALANCING
3133 void set_numabalancing_state(bool enabled)
3136 static_branch_enable(&sched_numa_balancing);
3138 static_branch_disable(&sched_numa_balancing);
3141 #ifdef CONFIG_PROC_SYSCTL
3142 int sysctl_numa_balancing(struct ctl_table *table, int write,
3143 void *buffer, size_t *lenp, loff_t *ppos)
3147 int state = static_branch_likely(&sched_numa_balancing);
3149 if (write && !capable(CAP_SYS_ADMIN))
3154 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3158 set_numabalancing_state(state);
3164 #ifdef CONFIG_SCHEDSTATS
3166 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
3167 static bool __initdata __sched_schedstats = false;
3169 static void set_schedstats(bool enabled)
3172 static_branch_enable(&sched_schedstats);
3174 static_branch_disable(&sched_schedstats);
3177 void force_schedstat_enabled(void)
3179 if (!schedstat_enabled()) {
3180 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
3181 static_branch_enable(&sched_schedstats);
3185 static int __init setup_schedstats(char *str)
3192 * This code is called before jump labels have been set up, so we can't
3193 * change the static branch directly just yet. Instead set a temporary
3194 * variable so init_schedstats() can do it later.
3196 if (!strcmp(str, "enable")) {
3197 __sched_schedstats = true;
3199 } else if (!strcmp(str, "disable")) {
3200 __sched_schedstats = false;
3205 pr_warn("Unable to parse schedstats=\n");
3209 __setup("schedstats=", setup_schedstats);
3211 static void __init init_schedstats(void)
3213 set_schedstats(__sched_schedstats);
3216 #ifdef CONFIG_PROC_SYSCTL
3217 int sysctl_schedstats(struct ctl_table *table, int write, void *buffer,
3218 size_t *lenp, loff_t *ppos)
3222 int state = static_branch_likely(&sched_schedstats);
3224 if (write && !capable(CAP_SYS_ADMIN))
3229 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3233 set_schedstats(state);
3236 #endif /* CONFIG_PROC_SYSCTL */
3237 #else /* !CONFIG_SCHEDSTATS */
3238 static inline void init_schedstats(void) {}
3239 #endif /* CONFIG_SCHEDSTATS */
3242 * fork()/clone()-time setup:
3244 int sched_fork(unsigned long clone_flags, struct task_struct *p)
3246 __sched_fork(clone_flags, p);
3248 * We mark the process as NEW here. This guarantees that
3249 * nobody will actually run it, and a signal or other external
3250 * event cannot wake it up and insert it on the runqueue either.
3252 p->state = TASK_NEW;
3255 * Make sure we do not leak PI boosting priority to the child.
3257 p->prio = current->normal_prio;
3262 * Revert to default priority/policy on fork if requested.
3264 if (unlikely(p->sched_reset_on_fork)) {
3265 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3266 p->policy = SCHED_NORMAL;
3267 p->static_prio = NICE_TO_PRIO(0);
3269 } else if (PRIO_TO_NICE(p->static_prio) < 0)
3270 p->static_prio = NICE_TO_PRIO(0);
3272 p->prio = p->normal_prio = p->static_prio;
3276 * We don't need the reset flag anymore after the fork. It has
3277 * fulfilled its duty:
3279 p->sched_reset_on_fork = 0;
3282 if (dl_prio(p->prio))
3284 else if (rt_prio(p->prio))
3285 p->sched_class = &rt_sched_class;
3287 p->sched_class = &fair_sched_class;
3289 init_entity_runnable_average(&p->se);
3291 #ifdef CONFIG_SCHED_INFO
3292 if (likely(sched_info_on()))
3293 memset(&p->sched_info, 0, sizeof(p->sched_info));
3295 #if defined(CONFIG_SMP)
3298 init_task_preempt_count(p);
3300 plist_node_init(&p->pushable_tasks, MAX_PRIO);
3301 RB_CLEAR_NODE(&p->pushable_dl_tasks);
3306 void sched_post_fork(struct task_struct *p, struct kernel_clone_args *kargs)
3308 unsigned long flags;
3309 #ifdef CONFIG_CGROUP_SCHED
3310 struct task_group *tg;
3313 raw_spin_lock_irqsave(&p->pi_lock, flags);
3314 #ifdef CONFIG_CGROUP_SCHED
3315 tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
3316 struct task_group, css);
3317 p->sched_task_group = autogroup_task_group(p, tg);
3321 * We're setting the CPU for the first time, we don't migrate,
3322 * so use __set_task_cpu().
3324 __set_task_cpu(p, smp_processor_id());
3325 if (p->sched_class->task_fork)
3326 p->sched_class->task_fork(p);
3327 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3329 uclamp_post_fork(p);
3332 unsigned long to_ratio(u64 period, u64 runtime)
3334 if (runtime == RUNTIME_INF)
3338 * Doing this here saves a lot of checks in all
3339 * the calling paths, and returning zero seems
3340 * safe for them anyway.
3345 return div64_u64(runtime << BW_SHIFT, period);
3349 * wake_up_new_task - wake up a newly created task for the first time.
3351 * This function will do some initial scheduler statistics housekeeping
3352 * that must be done for every newly created context, then puts the task
3353 * on the runqueue and wakes it.
3355 void wake_up_new_task(struct task_struct *p)
3360 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
3361 p->state = TASK_RUNNING;
3364 * Fork balancing, do it here and not earlier because:
3365 * - cpus_ptr can change in the fork path
3366 * - any previously selected CPU might disappear through hotplug
3368 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
3369 * as we're not fully set-up yet.
3371 p->recent_used_cpu = task_cpu(p);
3373 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
3375 rq = __task_rq_lock(p, &rf);
3376 update_rq_clock(rq);
3377 post_init_entity_util_avg(p);
3379 activate_task(rq, p, ENQUEUE_NOCLOCK);
3380 trace_sched_wakeup_new(p);
3381 check_preempt_curr(rq, p, WF_FORK);
3383 if (p->sched_class->task_woken) {
3385 * Nothing relies on rq->lock after this, so its fine to
3388 rq_unpin_lock(rq, &rf);
3389 p->sched_class->task_woken(rq, p);
3390 rq_repin_lock(rq, &rf);
3393 task_rq_unlock(rq, p, &rf);
3396 #ifdef CONFIG_PREEMPT_NOTIFIERS
3398 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
3400 void preempt_notifier_inc(void)
3402 static_branch_inc(&preempt_notifier_key);
3404 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
3406 void preempt_notifier_dec(void)
3408 static_branch_dec(&preempt_notifier_key);
3410 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
3413 * preempt_notifier_register - tell me when current is being preempted & rescheduled
3414 * @notifier: notifier struct to register
3416 void preempt_notifier_register(struct preempt_notifier *notifier)
3418 if (!static_branch_unlikely(&preempt_notifier_key))
3419 WARN(1, "registering preempt_notifier while notifiers disabled\n");
3421 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
3423 EXPORT_SYMBOL_GPL(preempt_notifier_register);
3426 * preempt_notifier_unregister - no longer interested in preemption notifications
3427 * @notifier: notifier struct to unregister
3429 * This is *not* safe to call from within a preemption notifier.
3431 void preempt_notifier_unregister(struct preempt_notifier *notifier)
3433 hlist_del(¬ifier->link);
3435 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
3437 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
3439 struct preempt_notifier *notifier;
3441 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
3442 notifier->ops->sched_in(notifier, raw_smp_processor_id());
3445 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
3447 if (static_branch_unlikely(&preempt_notifier_key))
3448 __fire_sched_in_preempt_notifiers(curr);
3452 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
3453 struct task_struct *next)
3455 struct preempt_notifier *notifier;
3457 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
3458 notifier->ops->sched_out(notifier, next);
3461 static __always_inline void
3462 fire_sched_out_preempt_notifiers(struct task_struct *curr,
3463 struct task_struct *next)
3465 if (static_branch_unlikely(&preempt_notifier_key))
3466 __fire_sched_out_preempt_notifiers(curr, next);
3469 #else /* !CONFIG_PREEMPT_NOTIFIERS */
3471 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
3476 fire_sched_out_preempt_notifiers(struct task_struct *curr,
3477 struct task_struct *next)
3481 #endif /* CONFIG_PREEMPT_NOTIFIERS */
3483 static inline void prepare_task(struct task_struct *next)
3487 * Claim the task as running, we do this before switching to it
3488 * such that any running task will have this set.
3490 * See the ttwu() WF_ON_CPU case and its ordering comment.
3492 WRITE_ONCE(next->on_cpu, 1);
3496 static inline void finish_task(struct task_struct *prev)
3500 * This must be the very last reference to @prev from this CPU. After
3501 * p->on_cpu is cleared, the task can be moved to a different CPU. We
3502 * must ensure this doesn't happen until the switch is completely
3505 * In particular, the load of prev->state in finish_task_switch() must
3506 * happen before this.
3508 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
3510 smp_store_release(&prev->on_cpu, 0);
3515 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
3518 * Since the runqueue lock will be released by the next
3519 * task (which is an invalid locking op but in the case
3520 * of the scheduler it's an obvious special-case), so we
3521 * do an early lockdep release here:
3523 rq_unpin_lock(rq, rf);
3524 spin_release(&rq->lock.dep_map, _THIS_IP_);
3525 #ifdef CONFIG_DEBUG_SPINLOCK
3526 /* this is a valid case when another task releases the spinlock */
3527 rq->lock.owner = next;
3531 static inline void finish_lock_switch(struct rq *rq)
3534 * If we are tracking spinlock dependencies then we have to
3535 * fix up the runqueue lock - which gets 'carried over' from
3536 * prev into current:
3538 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
3539 raw_spin_unlock_irq(&rq->lock);
3543 * NOP if the arch has not defined these:
3546 #ifndef prepare_arch_switch
3547 # define prepare_arch_switch(next) do { } while (0)
3550 #ifndef finish_arch_post_lock_switch
3551 # define finish_arch_post_lock_switch() do { } while (0)
3555 * prepare_task_switch - prepare to switch tasks
3556 * @rq: the runqueue preparing to switch
3557 * @prev: the current task that is being switched out
3558 * @next: the task we are going to switch to.
3560 * This is called with the rq lock held and interrupts off. It must
3561 * be paired with a subsequent finish_task_switch after the context
3564 * prepare_task_switch sets up locking and calls architecture specific
3568 prepare_task_switch(struct rq *rq, struct task_struct *prev,
3569 struct task_struct *next)
3571 kcov_prepare_switch(prev);
3572 sched_info_switch(rq, prev, next);
3573 perf_event_task_sched_out(prev, next);
3575 fire_sched_out_preempt_notifiers(prev, next);
3577 prepare_arch_switch(next);
3581 * finish_task_switch - clean up after a task-switch
3582 * @prev: the thread we just switched away from.
3584 * finish_task_switch must be called after the context switch, paired
3585 * with a prepare_task_switch call before the context switch.
3586 * finish_task_switch will reconcile locking set up by prepare_task_switch,
3587 * and do any other architecture-specific cleanup actions.
3589 * Note that we may have delayed dropping an mm in context_switch(). If
3590 * so, we finish that here outside of the runqueue lock. (Doing it
3591 * with the lock held can cause deadlocks; see schedule() for
3594 * The context switch have flipped the stack from under us and restored the
3595 * local variables which were saved when this task called schedule() in the
3596 * past. prev == current is still correct but we need to recalculate this_rq
3597 * because prev may have moved to another CPU.
3599 static struct rq *finish_task_switch(struct task_struct *prev)
3600 __releases(rq->lock)
3602 struct rq *rq = this_rq();
3603 struct mm_struct *mm = rq->prev_mm;
3607 * The previous task will have left us with a preempt_count of 2
3608 * because it left us after:
3611 * preempt_disable(); // 1
3613 * raw_spin_lock_irq(&rq->lock) // 2
3615 * Also, see FORK_PREEMPT_COUNT.
3617 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
3618 "corrupted preempt_count: %s/%d/0x%x\n",
3619 current->comm, current->pid, preempt_count()))
3620 preempt_count_set(FORK_PREEMPT_COUNT);
3625 * A task struct has one reference for the use as "current".
3626 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
3627 * schedule one last time. The schedule call will never return, and
3628 * the scheduled task must drop that reference.
3630 * We must observe prev->state before clearing prev->on_cpu (in
3631 * finish_task), otherwise a concurrent wakeup can get prev
3632 * running on another CPU and we could rave with its RUNNING -> DEAD
3633 * transition, resulting in a double drop.
3635 prev_state = prev->state;
3636 vtime_task_switch(prev);
3637 perf_event_task_sched_in(prev, current);
3639 finish_lock_switch(rq);
3640 finish_arch_post_lock_switch();
3641 kcov_finish_switch(current);
3643 fire_sched_in_preempt_notifiers(current);
3645 * When switching through a kernel thread, the loop in
3646 * membarrier_{private,global}_expedited() may have observed that
3647 * kernel thread and not issued an IPI. It is therefore possible to
3648 * schedule between user->kernel->user threads without passing though
3649 * switch_mm(). Membarrier requires a barrier after storing to
3650 * rq->curr, before returning to userspace, so provide them here:
3652 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
3653 * provided by mmdrop(),
3654 * - a sync_core for SYNC_CORE.
3657 membarrier_mm_sync_core_before_usermode(mm);
3660 if (unlikely(prev_state == TASK_DEAD)) {
3661 if (prev->sched_class->task_dead)
3662 prev->sched_class->task_dead(prev);
3665 * Remove function-return probe instances associated with this
3666 * task and put them back on the free list.
3668 kprobe_flush_task(prev);
3670 /* Task is done with its stack. */
3671 put_task_stack(prev);
3673 put_task_struct_rcu_user(prev);
3676 tick_nohz_task_switch();
3682 /* rq->lock is NOT held, but preemption is disabled */
3683 static void __balance_callback(struct rq *rq)
3685 struct callback_head *head, *next;
3686 void (*func)(struct rq *rq);
3687 unsigned long flags;
3689 raw_spin_lock_irqsave(&rq->lock, flags);
3690 head = rq->balance_callback;
3691 rq->balance_callback = NULL;
3693 func = (void (*)(struct rq *))head->func;
3700 raw_spin_unlock_irqrestore(&rq->lock, flags);
3703 static inline void balance_callback(struct rq *rq)
3705 if (unlikely(rq->balance_callback))
3706 __balance_callback(rq);
3711 static inline void balance_callback(struct rq *rq)
3718 * schedule_tail - first thing a freshly forked thread must call.
3719 * @prev: the thread we just switched away from.
3721 asmlinkage __visible void schedule_tail(struct task_struct *prev)
3722 __releases(rq->lock)
3727 * New tasks start with FORK_PREEMPT_COUNT, see there and
3728 * finish_task_switch() for details.
3730 * finish_task_switch() will drop rq->lock() and lower preempt_count
3731 * and the preempt_enable() will end up enabling preemption (on
3732 * PREEMPT_COUNT kernels).
3735 rq = finish_task_switch(prev);
3736 balance_callback(rq);
3739 if (current->set_child_tid)
3740 put_user(task_pid_vnr(current), current->set_child_tid);
3742 calculate_sigpending();
3746 * context_switch - switch to the new MM and the new thread's register state.
3748 static __always_inline struct rq *
3749 context_switch(struct rq *rq, struct task_struct *prev,
3750 struct task_struct *next, struct rq_flags *rf)
3752 prepare_task_switch(rq, prev, next);
3755 * For paravirt, this is coupled with an exit in switch_to to
3756 * combine the page table reload and the switch backend into
3759 arch_start_context_switch(prev);
3762 * kernel -> kernel lazy + transfer active
3763 * user -> kernel lazy + mmgrab() active
3765 * kernel -> user switch + mmdrop() active
3766 * user -> user switch
3768 if (!next->mm) { // to kernel
3769 enter_lazy_tlb(prev->active_mm, next);
3771 next->active_mm = prev->active_mm;
3772 if (prev->mm) // from user
3773 mmgrab(prev->active_mm);
3775 prev->active_mm = NULL;
3777 membarrier_switch_mm(rq, prev->active_mm, next->mm);
3779 * sys_membarrier() requires an smp_mb() between setting
3780 * rq->curr / membarrier_switch_mm() and returning to userspace.
3782 * The below provides this either through switch_mm(), or in
3783 * case 'prev->active_mm == next->mm' through
3784 * finish_task_switch()'s mmdrop().
3786 switch_mm_irqs_off(prev->active_mm, next->mm, next);
3788 if (!prev->mm) { // from kernel
3789 /* will mmdrop() in finish_task_switch(). */
3790 rq->prev_mm = prev->active_mm;
3791 prev->active_mm = NULL;
3795 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3797 prepare_lock_switch(rq, next, rf);
3799 /* Here we just switch the register state and the stack. */
3800 switch_to(prev, next, prev);
3803 return finish_task_switch(prev);
3807 * nr_running and nr_context_switches:
3809 * externally visible scheduler statistics: current number of runnable
3810 * threads, total number of context switches performed since bootup.
3812 unsigned long nr_running(void)
3814 unsigned long i, sum = 0;
3816 for_each_online_cpu(i)
3817 sum += cpu_rq(i)->nr_running;
3823 * Check if only the current task is running on the CPU.
3825 * Caution: this function does not check that the caller has disabled
3826 * preemption, thus the result might have a time-of-check-to-time-of-use
3827 * race. The caller is responsible to use it correctly, for example:
3829 * - from a non-preemptible section (of course)
3831 * - from a thread that is bound to a single CPU
3833 * - in a loop with very short iterations (e.g. a polling loop)
3835 bool single_task_running(void)
3837 return raw_rq()->nr_running == 1;
3839 EXPORT_SYMBOL(single_task_running);
3841 unsigned long long nr_context_switches(void)
3844 unsigned long long sum = 0;
3846 for_each_possible_cpu(i)
3847 sum += cpu_rq(i)->nr_switches;
3853 * Consumers of these two interfaces, like for example the cpuidle menu
3854 * governor, are using nonsensical data. Preferring shallow idle state selection
3855 * for a CPU that has IO-wait which might not even end up running the task when
3856 * it does become runnable.
3859 unsigned long nr_iowait_cpu(int cpu)
3861 return atomic_read(&cpu_rq(cpu)->nr_iowait);
3865 * IO-wait accounting, and how its mostly bollocks (on SMP).
3867 * The idea behind IO-wait account is to account the idle time that we could
3868 * have spend running if it were not for IO. That is, if we were to improve the
3869 * storage performance, we'd have a proportional reduction in IO-wait time.
3871 * This all works nicely on UP, where, when a task blocks on IO, we account
3872 * idle time as IO-wait, because if the storage were faster, it could've been
3873 * running and we'd not be idle.
3875 * This has been extended to SMP, by doing the same for each CPU. This however
3878 * Imagine for instance the case where two tasks block on one CPU, only the one
3879 * CPU will have IO-wait accounted, while the other has regular idle. Even
3880 * though, if the storage were faster, both could've ran at the same time,
3881 * utilising both CPUs.
3883 * This means, that when looking globally, the current IO-wait accounting on
3884 * SMP is a lower bound, by reason of under accounting.
3886 * Worse, since the numbers are provided per CPU, they are sometimes
3887 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
3888 * associated with any one particular CPU, it can wake to another CPU than it
3889 * blocked on. This means the per CPU IO-wait number is meaningless.
3891 * Task CPU affinities can make all that even more 'interesting'.
3894 unsigned long nr_iowait(void)
3896 unsigned long i, sum = 0;
3898 for_each_possible_cpu(i)
3899 sum += nr_iowait_cpu(i);
3907 * sched_exec - execve() is a valuable balancing opportunity, because at
3908 * this point the task has the smallest effective memory and cache footprint.
3910 void sched_exec(void)
3912 struct task_struct *p = current;
3913 unsigned long flags;
3916 raw_spin_lock_irqsave(&p->pi_lock, flags);
3917 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
3918 if (dest_cpu == smp_processor_id())
3921 if (likely(cpu_active(dest_cpu))) {
3922 struct migration_arg arg = { p, dest_cpu };
3924 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3925 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
3929 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3934 DEFINE_PER_CPU(struct kernel_stat, kstat);
3935 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
3937 EXPORT_PER_CPU_SYMBOL(kstat);
3938 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3941 * The function fair_sched_class.update_curr accesses the struct curr
3942 * and its field curr->exec_start; when called from task_sched_runtime(),
3943 * we observe a high rate of cache misses in practice.
3944 * Prefetching this data results in improved performance.
3946 static inline void prefetch_curr_exec_start(struct task_struct *p)
3948 #ifdef CONFIG_FAIR_GROUP_SCHED
3949 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3951 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3954 prefetch(&curr->exec_start);
3958 * Return accounted runtime for the task.
3959 * In case the task is currently running, return the runtime plus current's
3960 * pending runtime that have not been accounted yet.
3962 unsigned long long task_sched_runtime(struct task_struct *p)
3968 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3970 * 64-bit doesn't need locks to atomically read a 64-bit value.
3971 * So we have a optimization chance when the task's delta_exec is 0.
3972 * Reading ->on_cpu is racy, but this is ok.
3974 * If we race with it leaving CPU, we'll take a lock. So we're correct.
3975 * If we race with it entering CPU, unaccounted time is 0. This is
3976 * indistinguishable from the read occurring a few cycles earlier.
3977 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3978 * been accounted, so we're correct here as well.
3980 if (!p->on_cpu || !task_on_rq_queued(p))
3981 return p->se.sum_exec_runtime;
3984 rq = task_rq_lock(p, &rf);
3986 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3987 * project cycles that may never be accounted to this
3988 * thread, breaking clock_gettime().
3990 if (task_current(rq, p) && task_on_rq_queued(p)) {
3991 prefetch_curr_exec_start(p);
3992 update_rq_clock(rq);
3993 p->sched_class->update_curr(rq);
3995 ns = p->se.sum_exec_runtime;
3996 task_rq_unlock(rq, p, &rf);
4002 * This function gets called by the timer code, with HZ frequency.
4003 * We call it with interrupts disabled.
4005 void scheduler_tick(void)
4007 int cpu = smp_processor_id();
4008 struct rq *rq = cpu_rq(cpu);
4009 struct task_struct *curr = rq->curr;
4011 unsigned long thermal_pressure;
4013 arch_scale_freq_tick();
4018 update_rq_clock(rq);
4019 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
4020 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure);
4021 curr->sched_class->task_tick(rq, curr, 0);
4022 calc_global_load_tick(rq);
4027 perf_event_task_tick();
4030 rq->idle_balance = idle_cpu(cpu);
4031 trigger_load_balance(rq);
4035 #ifdef CONFIG_NO_HZ_FULL
4040 struct delayed_work work;
4042 /* Values for ->state, see diagram below. */
4043 #define TICK_SCHED_REMOTE_OFFLINE 0
4044 #define TICK_SCHED_REMOTE_OFFLINING 1
4045 #define TICK_SCHED_REMOTE_RUNNING 2
4048 * State diagram for ->state:
4051 * TICK_SCHED_REMOTE_OFFLINE
4054 * | | sched_tick_remote()
4057 * +--TICK_SCHED_REMOTE_OFFLINING
4060 * sched_tick_start() | | sched_tick_stop()
4063 * TICK_SCHED_REMOTE_RUNNING
4066 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
4067 * and sched_tick_start() are happy to leave the state in RUNNING.
4070 static struct tick_work __percpu *tick_work_cpu;
4072 static void sched_tick_remote(struct work_struct *work)
4074 struct delayed_work *dwork = to_delayed_work(work);
4075 struct tick_work *twork = container_of(dwork, struct tick_work, work);
4076 int cpu = twork->cpu;
4077 struct rq *rq = cpu_rq(cpu);
4078 struct task_struct *curr;
4084 * Handle the tick only if it appears the remote CPU is running in full
4085 * dynticks mode. The check is racy by nature, but missing a tick or
4086 * having one too much is no big deal because the scheduler tick updates
4087 * statistics and checks timeslices in a time-independent way, regardless
4088 * of when exactly it is running.
4090 if (!tick_nohz_tick_stopped_cpu(cpu))
4093 rq_lock_irq(rq, &rf);
4095 if (cpu_is_offline(cpu))
4098 update_rq_clock(rq);
4100 if (!is_idle_task(curr)) {
4102 * Make sure the next tick runs within a reasonable
4105 delta = rq_clock_task(rq) - curr->se.exec_start;
4106 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
4108 curr->sched_class->task_tick(rq, curr, 0);
4110 calc_load_nohz_remote(rq);
4112 rq_unlock_irq(rq, &rf);
4116 * Run the remote tick once per second (1Hz). This arbitrary
4117 * frequency is large enough to avoid overload but short enough
4118 * to keep scheduler internal stats reasonably up to date. But
4119 * first update state to reflect hotplug activity if required.
4121 os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
4122 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
4123 if (os == TICK_SCHED_REMOTE_RUNNING)
4124 queue_delayed_work(system_unbound_wq, dwork, HZ);
4127 static void sched_tick_start(int cpu)
4130 struct tick_work *twork;
4132 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
4135 WARN_ON_ONCE(!tick_work_cpu);
4137 twork = per_cpu_ptr(tick_work_cpu, cpu);
4138 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
4139 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
4140 if (os == TICK_SCHED_REMOTE_OFFLINE) {
4142 INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
4143 queue_delayed_work(system_unbound_wq, &twork->work, HZ);
4147 #ifdef CONFIG_HOTPLUG_CPU
4148 static void sched_tick_stop(int cpu)
4150 struct tick_work *twork;
4153 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
4156 WARN_ON_ONCE(!tick_work_cpu);
4158 twork = per_cpu_ptr(tick_work_cpu, cpu);
4159 /* There cannot be competing actions, but don't rely on stop-machine. */
4160 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
4161 WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
4162 /* Don't cancel, as this would mess up the state machine. */
4164 #endif /* CONFIG_HOTPLUG_CPU */
4166 int __init sched_tick_offload_init(void)
4168 tick_work_cpu = alloc_percpu(struct tick_work);
4169 BUG_ON(!tick_work_cpu);
4173 #else /* !CONFIG_NO_HZ_FULL */
4174 static inline void sched_tick_start(int cpu) { }
4175 static inline void sched_tick_stop(int cpu) { }
4178 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
4179 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
4181 * If the value passed in is equal to the current preempt count
4182 * then we just disabled preemption. Start timing the latency.
4184 static inline void preempt_latency_start(int val)
4186 if (preempt_count() == val) {
4187 unsigned long ip = get_lock_parent_ip();
4188 #ifdef CONFIG_DEBUG_PREEMPT
4189 current->preempt_disable_ip = ip;
4191 trace_preempt_off(CALLER_ADDR0, ip);
4195 void preempt_count_add(int val)
4197 #ifdef CONFIG_DEBUG_PREEMPT
4201 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4204 __preempt_count_add(val);
4205 #ifdef CONFIG_DEBUG_PREEMPT
4207 * Spinlock count overflowing soon?
4209 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4212 preempt_latency_start(val);
4214 EXPORT_SYMBOL(preempt_count_add);
4215 NOKPROBE_SYMBOL(preempt_count_add);
4218 * If the value passed in equals to the current preempt count
4219 * then we just enabled preemption. Stop timing the latency.
4221 static inline void preempt_latency_stop(int val)
4223 if (preempt_count() == val)
4224 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
4227 void preempt_count_sub(int val)
4229 #ifdef CONFIG_DEBUG_PREEMPT
4233 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4236 * Is the spinlock portion underflowing?
4238 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4239 !(preempt_count() & PREEMPT_MASK)))
4243 preempt_latency_stop(val);
4244 __preempt_count_sub(val);
4246 EXPORT_SYMBOL(preempt_count_sub);
4247 NOKPROBE_SYMBOL(preempt_count_sub);
4250 static inline void preempt_latency_start(int val) { }
4251 static inline void preempt_latency_stop(int val) { }
4254 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
4256 #ifdef CONFIG_DEBUG_PREEMPT
4257 return p->preempt_disable_ip;
4264 * Print scheduling while atomic bug:
4266 static noinline void __schedule_bug(struct task_struct *prev)
4268 /* Save this before calling printk(), since that will clobber it */
4269 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
4271 if (oops_in_progress)
4274 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4275 prev->comm, prev->pid, preempt_count());
4277 debug_show_held_locks(prev);
4279 if (irqs_disabled())
4280 print_irqtrace_events(prev);
4281 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
4282 && in_atomic_preempt_off()) {
4283 pr_err("Preemption disabled at:");
4284 print_ip_sym(KERN_ERR, preempt_disable_ip);
4286 check_panic_on_warn("scheduling while atomic");
4289 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
4293 * Various schedule()-time debugging checks and statistics:
4295 static inline void schedule_debug(struct task_struct *prev, bool preempt)
4297 #ifdef CONFIG_SCHED_STACK_END_CHECK
4298 if (task_stack_end_corrupted(prev))
4299 panic("corrupted stack end detected inside scheduler\n");
4301 if (task_scs_end_corrupted(prev))
4302 panic("corrupted shadow stack detected inside scheduler\n");
4305 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
4306 if (!preempt && prev->state && prev->non_block_count) {
4307 printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
4308 prev->comm, prev->pid, prev->non_block_count);
4310 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
4314 if (unlikely(in_atomic_preempt_off())) {
4315 __schedule_bug(prev);
4316 preempt_count_set(PREEMPT_DISABLED);
4320 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4322 schedstat_inc(this_rq()->sched_count);
4325 static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
4326 struct rq_flags *rf)
4329 const struct sched_class *class;
4331 * We must do the balancing pass before put_prev_task(), such
4332 * that when we release the rq->lock the task is in the same
4333 * state as before we took rq->lock.
4335 * We can terminate the balance pass as soon as we know there is
4336 * a runnable task of @class priority or higher.
4338 for_class_range(class, prev->sched_class, &idle_sched_class) {
4339 if (class->balance(rq, prev, rf))
4344 put_prev_task(rq, prev);
4348 * Pick up the highest-prio task:
4350 static inline struct task_struct *
4351 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
4353 const struct sched_class *class;
4354 struct task_struct *p;
4357 * Optimization: we know that if all tasks are in the fair class we can
4358 * call that function directly, but only if the @prev task wasn't of a
4359 * higher scheduling class, because otherwise those loose the
4360 * opportunity to pull in more work from other CPUs.
4362 if (likely(prev->sched_class <= &fair_sched_class &&
4363 rq->nr_running == rq->cfs.h_nr_running)) {
4365 p = pick_next_task_fair(rq, prev, rf);
4366 if (unlikely(p == RETRY_TASK))
4369 /* Assumes fair_sched_class->next == idle_sched_class */
4371 put_prev_task(rq, prev);
4372 p = pick_next_task_idle(rq);
4379 put_prev_task_balance(rq, prev, rf);
4381 for_each_class(class) {
4382 p = class->pick_next_task(rq);
4387 /* The idle class should always have a runnable task: */
4392 * __schedule() is the main scheduler function.
4394 * The main means of driving the scheduler and thus entering this function are:
4396 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
4398 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
4399 * paths. For example, see arch/x86/entry_64.S.
4401 * To drive preemption between tasks, the scheduler sets the flag in timer
4402 * interrupt handler scheduler_tick().
4404 * 3. Wakeups don't really cause entry into schedule(). They add a
4405 * task to the run-queue and that's it.
4407 * Now, if the new task added to the run-queue preempts the current
4408 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
4409 * called on the nearest possible occasion:
4411 * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
4413 * - in syscall or exception context, at the next outmost
4414 * preempt_enable(). (this might be as soon as the wake_up()'s
4417 * - in IRQ context, return from interrupt-handler to
4418 * preemptible context
4420 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
4423 * - cond_resched() call
4424 * - explicit schedule() call
4425 * - return from syscall or exception to user-space
4426 * - return from interrupt-handler to user-space
4428 * WARNING: must be called with preemption disabled!
4430 static void __sched notrace __schedule(bool preempt)
4432 struct task_struct *prev, *next;
4433 unsigned long *switch_count;
4434 unsigned long prev_state;
4439 cpu = smp_processor_id();
4443 schedule_debug(prev, preempt);
4445 if (sched_feat(HRTICK))
4448 local_irq_disable();
4449 rcu_note_context_switch(preempt);
4452 * Make sure that signal_pending_state()->signal_pending() below
4453 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
4454 * done by the caller to avoid the race with signal_wake_up():
4456 * __set_current_state(@state) signal_wake_up()
4457 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
4458 * wake_up_state(p, state)
4459 * LOCK rq->lock LOCK p->pi_state
4460 * smp_mb__after_spinlock() smp_mb__after_spinlock()
4461 * if (signal_pending_state()) if (p->state & @state)
4463 * Also, the membarrier system call requires a full memory barrier
4464 * after coming from user-space, before storing to rq->curr.
4467 smp_mb__after_spinlock();
4469 /* Promote REQ to ACT */
4470 rq->clock_update_flags <<= 1;
4471 update_rq_clock(rq);
4473 switch_count = &prev->nivcsw;
4476 * We must load prev->state once (task_struct::state is volatile), such
4479 * - we form a control dependency vs deactivate_task() below.
4480 * - ptrace_{,un}freeze_traced() can change ->state underneath us.
4482 prev_state = prev->state;
4483 if (!preempt && prev_state) {
4484 if (signal_pending_state(prev_state, prev)) {
4485 prev->state = TASK_RUNNING;
4487 prev->sched_contributes_to_load =
4488 (prev_state & TASK_UNINTERRUPTIBLE) &&
4489 !(prev_state & TASK_NOLOAD) &&
4490 !(prev->flags & PF_FROZEN);
4492 if (prev->sched_contributes_to_load)
4493 rq->nr_uninterruptible++;
4496 * __schedule() ttwu()
4497 * prev_state = prev->state; if (p->on_rq && ...)
4498 * if (prev_state) goto out;
4499 * p->on_rq = 0; smp_acquire__after_ctrl_dep();
4500 * p->state = TASK_WAKING
4502 * Where __schedule() and ttwu() have matching control dependencies.
4504 * After this, schedule() must not care about p->state any more.
4506 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
4508 if (prev->in_iowait) {
4509 atomic_inc(&rq->nr_iowait);
4510 delayacct_blkio_start();
4513 switch_count = &prev->nvcsw;
4516 next = pick_next_task(rq, prev, &rf);
4517 clear_tsk_need_resched(prev);
4518 clear_preempt_need_resched();
4520 if (likely(prev != next)) {
4523 * RCU users of rcu_dereference(rq->curr) may not see
4524 * changes to task_struct made by pick_next_task().
4526 RCU_INIT_POINTER(rq->curr, next);
4528 * The membarrier system call requires each architecture
4529 * to have a full memory barrier after updating
4530 * rq->curr, before returning to user-space.
4532 * Here are the schemes providing that barrier on the
4533 * various architectures:
4534 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
4535 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
4536 * - finish_lock_switch() for weakly-ordered
4537 * architectures where spin_unlock is a full barrier,
4538 * - switch_to() for arm64 (weakly-ordered, spin_unlock
4539 * is a RELEASE barrier),
4543 psi_sched_switch(prev, next, !task_on_rq_queued(prev));
4545 trace_sched_switch(preempt, prev, next);
4547 /* Also unlocks the rq: */
4548 rq = context_switch(rq, prev, next, &rf);
4550 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
4551 rq_unlock_irq(rq, &rf);
4554 balance_callback(rq);
4557 void __noreturn do_task_dead(void)
4559 /* Causes final put_task_struct in finish_task_switch(): */
4560 set_special_state(TASK_DEAD);
4562 /* Tell freezer to ignore us: */
4563 current->flags |= PF_NOFREEZE;
4568 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
4573 static inline void sched_submit_work(struct task_struct *tsk)
4575 unsigned int task_flags;
4580 task_flags = tsk->flags;
4582 * If a worker went to sleep, notify and ask workqueue whether
4583 * it wants to wake up a task to maintain concurrency.
4584 * As this function is called inside the schedule() context,
4585 * we disable preemption to avoid it calling schedule() again
4586 * in the possible wakeup of a kworker and because wq_worker_sleeping()
4589 if (task_flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
4591 if (task_flags & PF_WQ_WORKER)
4592 wq_worker_sleeping(tsk);
4594 io_wq_worker_sleeping(tsk);
4595 preempt_enable_no_resched();
4598 if (tsk_is_pi_blocked(tsk))
4602 * If we are going to sleep and we have plugged IO queued,
4603 * make sure to submit it to avoid deadlocks.
4605 if (blk_needs_flush_plug(tsk))
4606 blk_schedule_flush_plug(tsk);
4609 static void sched_update_worker(struct task_struct *tsk)
4611 if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
4612 if (tsk->flags & PF_WQ_WORKER)
4613 wq_worker_running(tsk);
4615 io_wq_worker_running(tsk);
4619 asmlinkage __visible void __sched schedule(void)
4621 struct task_struct *tsk = current;
4623 sched_submit_work(tsk);
4627 sched_preempt_enable_no_resched();
4628 } while (need_resched());
4629 sched_update_worker(tsk);
4631 EXPORT_SYMBOL(schedule);
4634 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
4635 * state (have scheduled out non-voluntarily) by making sure that all
4636 * tasks have either left the run queue or have gone into user space.
4637 * As idle tasks do not do either, they must not ever be preempted
4638 * (schedule out non-voluntarily).
4640 * schedule_idle() is similar to schedule_preempt_disable() except that it
4641 * never enables preemption because it does not call sched_submit_work().
4643 void __sched schedule_idle(void)
4646 * As this skips calling sched_submit_work(), which the idle task does
4647 * regardless because that function is a nop when the task is in a
4648 * TASK_RUNNING state, make sure this isn't used someplace that the
4649 * current task can be in any other state. Note, idle is always in the
4650 * TASK_RUNNING state.
4652 WARN_ON_ONCE(current->state);
4655 } while (need_resched());
4658 #ifdef CONFIG_CONTEXT_TRACKING
4659 asmlinkage __visible void __sched schedule_user(void)
4662 * If we come here after a random call to set_need_resched(),
4663 * or we have been woken up remotely but the IPI has not yet arrived,
4664 * we haven't yet exited the RCU idle mode. Do it here manually until
4665 * we find a better solution.
4667 * NB: There are buggy callers of this function. Ideally we
4668 * should warn if prev_state != CONTEXT_USER, but that will trigger
4669 * too frequently to make sense yet.
4671 enum ctx_state prev_state = exception_enter();
4673 exception_exit(prev_state);
4678 * schedule_preempt_disabled - called with preemption disabled
4680 * Returns with preemption disabled. Note: preempt_count must be 1
4682 void __sched schedule_preempt_disabled(void)
4684 sched_preempt_enable_no_resched();
4689 static void __sched notrace preempt_schedule_common(void)
4693 * Because the function tracer can trace preempt_count_sub()
4694 * and it also uses preempt_enable/disable_notrace(), if
4695 * NEED_RESCHED is set, the preempt_enable_notrace() called
4696 * by the function tracer will call this function again and
4697 * cause infinite recursion.
4699 * Preemption must be disabled here before the function
4700 * tracer can trace. Break up preempt_disable() into two
4701 * calls. One to disable preemption without fear of being
4702 * traced. The other to still record the preemption latency,
4703 * which can also be traced by the function tracer.
4705 preempt_disable_notrace();
4706 preempt_latency_start(1);
4708 preempt_latency_stop(1);
4709 preempt_enable_no_resched_notrace();
4712 * Check again in case we missed a preemption opportunity
4713 * between schedule and now.
4715 } while (need_resched());
4718 #ifdef CONFIG_PREEMPTION
4720 * This is the entry point to schedule() from in-kernel preemption
4721 * off of preempt_enable.
4723 asmlinkage __visible void __sched notrace preempt_schedule(void)
4726 * If there is a non-zero preempt_count or interrupts are disabled,
4727 * we do not want to preempt the current task. Just return..
4729 if (likely(!preemptible()))
4732 preempt_schedule_common();
4734 NOKPROBE_SYMBOL(preempt_schedule);
4735 EXPORT_SYMBOL(preempt_schedule);
4738 * preempt_schedule_notrace - preempt_schedule called by tracing
4740 * The tracing infrastructure uses preempt_enable_notrace to prevent
4741 * recursion and tracing preempt enabling caused by the tracing
4742 * infrastructure itself. But as tracing can happen in areas coming
4743 * from userspace or just about to enter userspace, a preempt enable
4744 * can occur before user_exit() is called. This will cause the scheduler
4745 * to be called when the system is still in usermode.
4747 * To prevent this, the preempt_enable_notrace will use this function
4748 * instead of preempt_schedule() to exit user context if needed before
4749 * calling the scheduler.
4751 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
4753 enum ctx_state prev_ctx;
4755 if (likely(!preemptible()))
4760 * Because the function tracer can trace preempt_count_sub()
4761 * and it also uses preempt_enable/disable_notrace(), if
4762 * NEED_RESCHED is set, the preempt_enable_notrace() called
4763 * by the function tracer will call this function again and
4764 * cause infinite recursion.
4766 * Preemption must be disabled here before the function
4767 * tracer can trace. Break up preempt_disable() into two
4768 * calls. One to disable preemption without fear of being
4769 * traced. The other to still record the preemption latency,
4770 * which can also be traced by the function tracer.
4772 preempt_disable_notrace();
4773 preempt_latency_start(1);
4775 * Needs preempt disabled in case user_exit() is traced
4776 * and the tracer calls preempt_enable_notrace() causing
4777 * an infinite recursion.
4779 prev_ctx = exception_enter();
4781 exception_exit(prev_ctx);
4783 preempt_latency_stop(1);
4784 preempt_enable_no_resched_notrace();
4785 } while (need_resched());
4787 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
4789 #endif /* CONFIG_PREEMPTION */
4792 * This is the entry point to schedule() from kernel preemption
4793 * off of irq context.
4794 * Note, that this is called and return with irqs disabled. This will
4795 * protect us against recursive calling from irq.
4797 asmlinkage __visible void __sched preempt_schedule_irq(void)
4799 enum ctx_state prev_state;
4801 /* Catch callers which need to be fixed */
4802 BUG_ON(preempt_count() || !irqs_disabled());
4804 prev_state = exception_enter();
4810 local_irq_disable();
4811 sched_preempt_enable_no_resched();
4812 } while (need_resched());
4814 exception_exit(prev_state);
4817 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
4820 WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~WF_SYNC);
4821 return try_to_wake_up(curr->private, mode, wake_flags);
4823 EXPORT_SYMBOL(default_wake_function);
4825 static void __setscheduler_prio(struct task_struct *p, int prio)
4828 p->sched_class = &dl_sched_class;
4829 else if (rt_prio(prio))
4830 p->sched_class = &rt_sched_class;
4832 p->sched_class = &fair_sched_class;
4837 #ifdef CONFIG_RT_MUTEXES
4839 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
4842 prio = min(prio, pi_task->prio);
4847 static inline int rt_effective_prio(struct task_struct *p, int prio)
4849 struct task_struct *pi_task = rt_mutex_get_top_task(p);
4851 return __rt_effective_prio(pi_task, prio);
4855 * rt_mutex_setprio - set the current priority of a task
4857 * @pi_task: donor task
4859 * This function changes the 'effective' priority of a task. It does
4860 * not touch ->normal_prio like __setscheduler().
4862 * Used by the rt_mutex code to implement priority inheritance
4863 * logic. Call site only calls if the priority of the task changed.
4865 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
4867 int prio, oldprio, queued, running, queue_flag =
4868 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
4869 const struct sched_class *prev_class;
4873 /* XXX used to be waiter->prio, not waiter->task->prio */
4874 prio = __rt_effective_prio(pi_task, p->normal_prio);
4877 * If nothing changed; bail early.
4879 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
4882 rq = __task_rq_lock(p, &rf);
4883 update_rq_clock(rq);
4885 * Set under pi_lock && rq->lock, such that the value can be used under
4888 * Note that there is loads of tricky to make this pointer cache work
4889 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
4890 * ensure a task is de-boosted (pi_task is set to NULL) before the
4891 * task is allowed to run again (and can exit). This ensures the pointer
4892 * points to a blocked task -- which guaratees the task is present.
4894 p->pi_top_task = pi_task;
4897 * For FIFO/RR we only need to set prio, if that matches we're done.
4899 if (prio == p->prio && !dl_prio(prio))
4903 * Idle task boosting is a nono in general. There is one
4904 * exception, when PREEMPT_RT and NOHZ is active:
4906 * The idle task calls get_next_timer_interrupt() and holds
4907 * the timer wheel base->lock on the CPU and another CPU wants
4908 * to access the timer (probably to cancel it). We can safely
4909 * ignore the boosting request, as the idle CPU runs this code
4910 * with interrupts disabled and will complete the lock
4911 * protected section without being interrupted. So there is no
4912 * real need to boost.
4914 if (unlikely(p == rq->idle)) {
4915 WARN_ON(p != rq->curr);
4916 WARN_ON(p->pi_blocked_on);
4920 trace_sched_pi_setprio(p, pi_task);
4923 if (oldprio == prio)
4924 queue_flag &= ~DEQUEUE_MOVE;
4926 prev_class = p->sched_class;
4927 queued = task_on_rq_queued(p);
4928 running = task_current(rq, p);
4930 dequeue_task(rq, p, queue_flag);
4932 put_prev_task(rq, p);
4935 * Boosting condition are:
4936 * 1. -rt task is running and holds mutex A
4937 * --> -dl task blocks on mutex A
4939 * 2. -dl task is running and holds mutex A
4940 * --> -dl task blocks on mutex A and could preempt the
4943 if (dl_prio(prio)) {
4944 if (!dl_prio(p->normal_prio) ||
4945 (pi_task && dl_prio(pi_task->prio) &&
4946 dl_entity_preempt(&pi_task->dl, &p->dl))) {
4947 p->dl.pi_se = pi_task->dl.pi_se;
4948 queue_flag |= ENQUEUE_REPLENISH;
4950 p->dl.pi_se = &p->dl;
4952 } else if (rt_prio(prio)) {
4953 if (dl_prio(oldprio))
4954 p->dl.pi_se = &p->dl;
4956 queue_flag |= ENQUEUE_HEAD;
4958 if (dl_prio(oldprio))
4959 p->dl.pi_se = &p->dl;
4960 if (rt_prio(oldprio))
4964 __setscheduler_prio(p, prio);
4967 enqueue_task(rq, p, queue_flag);
4969 set_next_task(rq, p);
4971 check_class_changed(rq, p, prev_class, oldprio);
4973 /* Avoid rq from going away on us: */
4975 __task_rq_unlock(rq, &rf);
4977 balance_callback(rq);
4981 static inline int rt_effective_prio(struct task_struct *p, int prio)
4987 void set_user_nice(struct task_struct *p, long nice)
4989 bool queued, running;
4994 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
4997 * We have to be careful, if called from sys_setpriority(),
4998 * the task might be in the middle of scheduling on another CPU.
5000 rq = task_rq_lock(p, &rf);
5001 update_rq_clock(rq);
5004 * The RT priorities are set via sched_setscheduler(), but we still
5005 * allow the 'normal' nice value to be set - but as expected
5006 * it wont have any effect on scheduling until the task is
5007 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
5009 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
5010 p->static_prio = NICE_TO_PRIO(nice);
5013 queued = task_on_rq_queued(p);
5014 running = task_current(rq, p);
5016 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
5018 put_prev_task(rq, p);
5020 p->static_prio = NICE_TO_PRIO(nice);
5023 p->prio = effective_prio(p);
5026 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
5028 set_next_task(rq, p);
5031 * If the task increased its priority or is running and
5032 * lowered its priority, then reschedule its CPU:
5034 p->sched_class->prio_changed(rq, p, old_prio);
5037 task_rq_unlock(rq, p, &rf);
5039 EXPORT_SYMBOL(set_user_nice);
5042 * can_nice - check if a task can reduce its nice value
5046 int can_nice(const struct task_struct *p, const int nice)
5048 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
5049 int nice_rlim = nice_to_rlimit(nice);
5051 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
5052 capable(CAP_SYS_NICE));
5055 #ifdef __ARCH_WANT_SYS_NICE
5058 * sys_nice - change the priority of the current process.
5059 * @increment: priority increment
5061 * sys_setpriority is a more generic, but much slower function that
5062 * does similar things.
5064 SYSCALL_DEFINE1(nice, int, increment)
5069 * Setpriority might change our priority at the same moment.
5070 * We don't have to worry. Conceptually one call occurs first
5071 * and we have a single winner.
5073 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
5074 nice = task_nice(current) + increment;
5076 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
5077 if (increment < 0 && !can_nice(current, nice))
5080 retval = security_task_setnice(current, nice);
5084 set_user_nice(current, nice);
5091 * task_prio - return the priority value of a given task.
5092 * @p: the task in question.
5094 * Return: The priority value as seen by users in /proc.
5095 * RT tasks are offset by -200. Normal tasks are centered
5096 * around 0, value goes from -16 to +15.
5098 int task_prio(const struct task_struct *p)
5100 return p->prio - MAX_RT_PRIO;
5104 * idle_cpu - is a given CPU idle currently?
5105 * @cpu: the processor in question.
5107 * Return: 1 if the CPU is currently idle. 0 otherwise.
5109 int idle_cpu(int cpu)
5111 struct rq *rq = cpu_rq(cpu);
5113 if (rq->curr != rq->idle)
5120 if (rq->ttwu_pending)
5128 * available_idle_cpu - is a given CPU idle for enqueuing work.
5129 * @cpu: the CPU in question.
5131 * Return: 1 if the CPU is currently idle. 0 otherwise.
5133 int available_idle_cpu(int cpu)
5138 if (vcpu_is_preempted(cpu))
5145 * idle_task - return the idle task for a given CPU.
5146 * @cpu: the processor in question.
5148 * Return: The idle task for the CPU @cpu.
5150 struct task_struct *idle_task(int cpu)
5152 return cpu_rq(cpu)->idle;
5156 * find_process_by_pid - find a process with a matching PID value.
5157 * @pid: the pid in question.
5159 * The task of @pid, if found. %NULL otherwise.
5161 static struct task_struct *find_process_by_pid(pid_t pid)
5163 return pid ? find_task_by_vpid(pid) : current;
5167 * sched_setparam() passes in -1 for its policy, to let the functions
5168 * it calls know not to change it.
5170 #define SETPARAM_POLICY -1
5172 static void __setscheduler_params(struct task_struct *p,
5173 const struct sched_attr *attr)
5175 int policy = attr->sched_policy;
5177 if (policy == SETPARAM_POLICY)
5182 if (dl_policy(policy))
5183 __setparam_dl(p, attr);
5184 else if (fair_policy(policy))
5185 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5188 * __sched_setscheduler() ensures attr->sched_priority == 0 when
5189 * !rt_policy. Always setting this ensures that things like
5190 * getparam()/getattr() don't report silly values for !rt tasks.
5192 p->rt_priority = attr->sched_priority;
5193 p->normal_prio = normal_prio(p);
5198 * Check the target process has a UID that matches the current process's:
5200 static bool check_same_owner(struct task_struct *p)
5202 const struct cred *cred = current_cred(), *pcred;
5206 pcred = __task_cred(p);
5207 match = (uid_eq(cred->euid, pcred->euid) ||
5208 uid_eq(cred->euid, pcred->uid));
5213 static int __sched_setscheduler(struct task_struct *p,
5214 const struct sched_attr *attr,
5217 int oldpolicy = -1, policy = attr->sched_policy;
5218 int retval, oldprio, newprio, queued, running;
5219 const struct sched_class *prev_class;
5222 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
5224 bool cpuset_locked = false;
5226 /* The pi code expects interrupts enabled */
5227 BUG_ON(pi && in_interrupt());
5229 /* Double check policy once rq lock held: */
5231 reset_on_fork = p->sched_reset_on_fork;
5232 policy = oldpolicy = p->policy;
5234 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
5236 if (!valid_policy(policy))
5240 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
5244 * Valid priorities for SCHED_FIFO and SCHED_RR are
5245 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5246 * SCHED_BATCH and SCHED_IDLE is 0.
5248 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
5249 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
5251 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
5252 (rt_policy(policy) != (attr->sched_priority != 0)))
5256 * Allow unprivileged RT tasks to decrease priority:
5258 if (user && !capable(CAP_SYS_NICE)) {
5259 if (fair_policy(policy)) {
5260 if (attr->sched_nice < task_nice(p) &&
5261 !can_nice(p, attr->sched_nice))
5265 if (rt_policy(policy)) {
5266 unsigned long rlim_rtprio =
5267 task_rlimit(p, RLIMIT_RTPRIO);
5269 /* Can't set/change the rt policy: */
5270 if (policy != p->policy && !rlim_rtprio)
5273 /* Can't increase priority: */
5274 if (attr->sched_priority > p->rt_priority &&
5275 attr->sched_priority > rlim_rtprio)
5280 * Can't set/change SCHED_DEADLINE policy at all for now
5281 * (safest behavior); in the future we would like to allow
5282 * unprivileged DL tasks to increase their relative deadline
5283 * or reduce their runtime (both ways reducing utilization)
5285 if (dl_policy(policy))
5289 * Treat SCHED_IDLE as nice 20. Only allow a switch to
5290 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
5292 if (task_has_idle_policy(p) && !idle_policy(policy)) {
5293 if (!can_nice(p, task_nice(p)))
5297 /* Can't change other user's priorities: */
5298 if (!check_same_owner(p))
5301 /* Normal users shall not reset the sched_reset_on_fork flag: */
5302 if (p->sched_reset_on_fork && !reset_on_fork)
5307 if (attr->sched_flags & SCHED_FLAG_SUGOV)
5310 retval = security_task_setscheduler(p);
5315 /* Update task specific "requested" clamps */
5316 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
5317 retval = uclamp_validate(p, attr);
5323 * SCHED_DEADLINE bandwidth accounting relies on stable cpusets
5326 if (dl_policy(policy) || dl_policy(p->policy)) {
5327 cpuset_locked = true;
5332 * Make sure no PI-waiters arrive (or leave) while we are
5333 * changing the priority of the task:
5335 * To be able to change p->policy safely, the appropriate
5336 * runqueue lock must be held.
5338 rq = task_rq_lock(p, &rf);
5339 update_rq_clock(rq);
5342 * Changing the policy of the stop threads its a very bad idea:
5344 if (p == rq->stop) {
5350 * If not changing anything there's no need to proceed further,
5351 * but store a possible modification of reset_on_fork.
5353 if (unlikely(policy == p->policy)) {
5354 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
5356 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
5358 if (dl_policy(policy) && dl_param_changed(p, attr))
5360 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
5363 p->sched_reset_on_fork = reset_on_fork;
5370 #ifdef CONFIG_RT_GROUP_SCHED
5372 * Do not allow realtime tasks into groups that have no runtime
5375 if (rt_bandwidth_enabled() && rt_policy(policy) &&
5376 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
5377 !task_group_is_autogroup(task_group(p))) {
5383 if (dl_bandwidth_enabled() && dl_policy(policy) &&
5384 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
5385 cpumask_t *span = rq->rd->span;
5388 * Don't allow tasks with an affinity mask smaller than
5389 * the entire root_domain to become SCHED_DEADLINE. We
5390 * will also fail if there's no bandwidth available.
5392 if (!cpumask_subset(span, p->cpus_ptr) ||
5393 rq->rd->dl_bw.bw == 0) {
5401 /* Re-check policy now with rq lock held: */
5402 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5403 policy = oldpolicy = -1;
5404 task_rq_unlock(rq, p, &rf);
5411 * If setscheduling to SCHED_DEADLINE (or changing the parameters
5412 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
5415 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
5420 p->sched_reset_on_fork = reset_on_fork;
5423 newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
5426 * Take priority boosted tasks into account. If the new
5427 * effective priority is unchanged, we just store the new
5428 * normal parameters and do not touch the scheduler class and
5429 * the runqueue. This will be done when the task deboost
5432 newprio = rt_effective_prio(p, newprio);
5433 if (newprio == oldprio)
5434 queue_flags &= ~DEQUEUE_MOVE;
5437 queued = task_on_rq_queued(p);
5438 running = task_current(rq, p);
5440 dequeue_task(rq, p, queue_flags);
5442 put_prev_task(rq, p);
5444 prev_class = p->sched_class;
5446 if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
5447 __setscheduler_params(p, attr);
5448 __setscheduler_prio(p, newprio);
5450 __setscheduler_uclamp(p, attr);
5454 * We enqueue to tail when the priority of a task is
5455 * increased (user space view).
5457 if (oldprio < p->prio)
5458 queue_flags |= ENQUEUE_HEAD;
5460 enqueue_task(rq, p, queue_flags);
5463 set_next_task(rq, p);
5465 check_class_changed(rq, p, prev_class, oldprio);
5467 /* Avoid rq from going away on us: */
5469 task_rq_unlock(rq, p, &rf);
5474 rt_mutex_adjust_pi(p);
5477 /* Run balance callbacks after we've adjusted the PI chain: */
5478 balance_callback(rq);
5484 task_rq_unlock(rq, p, &rf);
5490 static int _sched_setscheduler(struct task_struct *p, int policy,
5491 const struct sched_param *param, bool check)
5493 struct sched_attr attr = {
5494 .sched_policy = policy,
5495 .sched_priority = param->sched_priority,
5496 .sched_nice = PRIO_TO_NICE(p->static_prio),
5499 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
5500 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
5501 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
5502 policy &= ~SCHED_RESET_ON_FORK;
5503 attr.sched_policy = policy;
5506 return __sched_setscheduler(p, &attr, check, true);
5509 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5510 * @p: the task in question.
5511 * @policy: new policy.
5512 * @param: structure containing the new RT priority.
5514 * Use sched_set_fifo(), read its comment.
5516 * Return: 0 on success. An error code otherwise.
5518 * NOTE that the task may be already dead.
5520 int sched_setscheduler(struct task_struct *p, int policy,
5521 const struct sched_param *param)
5523 return _sched_setscheduler(p, policy, param, true);
5526 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
5528 return __sched_setscheduler(p, attr, true, true);
5531 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
5533 return __sched_setscheduler(p, attr, false, true);
5537 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5538 * @p: the task in question.
5539 * @policy: new policy.
5540 * @param: structure containing the new RT priority.
5542 * Just like sched_setscheduler, only don't bother checking if the
5543 * current context has permission. For example, this is needed in
5544 * stop_machine(): we create temporary high priority worker threads,
5545 * but our caller might not have that capability.
5547 * Return: 0 on success. An error code otherwise.
5549 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5550 const struct sched_param *param)
5552 return _sched_setscheduler(p, policy, param, false);
5556 * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
5557 * incapable of resource management, which is the one thing an OS really should
5560 * This is of course the reason it is limited to privileged users only.
5562 * Worse still; it is fundamentally impossible to compose static priority
5563 * workloads. You cannot take two correctly working static prio workloads
5564 * and smash them together and still expect them to work.
5566 * For this reason 'all' FIFO tasks the kernel creates are basically at:
5570 * The administrator _MUST_ configure the system, the kernel simply doesn't
5571 * know enough information to make a sensible choice.
5573 void sched_set_fifo(struct task_struct *p)
5575 struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
5576 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
5578 EXPORT_SYMBOL_GPL(sched_set_fifo);
5581 * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
5583 void sched_set_fifo_low(struct task_struct *p)
5585 struct sched_param sp = { .sched_priority = 1 };
5586 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
5588 EXPORT_SYMBOL_GPL(sched_set_fifo_low);
5590 void sched_set_normal(struct task_struct *p, int nice)
5592 struct sched_attr attr = {
5593 .sched_policy = SCHED_NORMAL,
5596 WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
5598 EXPORT_SYMBOL_GPL(sched_set_normal);
5601 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5603 struct sched_param lparam;
5604 struct task_struct *p;
5607 if (!param || pid < 0)
5609 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5614 p = find_process_by_pid(pid);
5620 retval = sched_setscheduler(p, policy, &lparam);
5628 * Mimics kernel/events/core.c perf_copy_attr().
5630 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
5635 /* Zero the full structure, so that a short copy will be nice: */
5636 memset(attr, 0, sizeof(*attr));
5638 ret = get_user(size, &uattr->size);
5642 /* ABI compatibility quirk: */
5644 size = SCHED_ATTR_SIZE_VER0;
5645 if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
5648 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
5655 if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
5656 size < SCHED_ATTR_SIZE_VER1)
5660 * XXX: Do we want to be lenient like existing syscalls; or do we want
5661 * to be strict and return an error on out-of-bounds values?
5663 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
5668 put_user(sizeof(*attr), &uattr->size);
5673 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5674 * @pid: the pid in question.
5675 * @policy: new policy.
5676 * @param: structure containing the new RT priority.
5678 * Return: 0 on success. An error code otherwise.
5680 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
5685 return do_sched_setscheduler(pid, policy, param);
5689 * sys_sched_setparam - set/change the RT priority of a thread
5690 * @pid: the pid in question.
5691 * @param: structure containing the new RT priority.
5693 * Return: 0 on success. An error code otherwise.
5695 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
5697 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
5701 * sys_sched_setattr - same as above, but with extended sched_attr
5702 * @pid: the pid in question.
5703 * @uattr: structure containing the extended parameters.
5704 * @flags: for future extension.
5706 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
5707 unsigned int, flags)
5709 struct sched_attr attr;
5710 struct task_struct *p;
5713 if (!uattr || pid < 0 || flags)
5716 retval = sched_copy_attr(uattr, &attr);
5720 if ((int)attr.sched_policy < 0)
5722 if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
5723 attr.sched_policy = SETPARAM_POLICY;
5727 p = find_process_by_pid(pid);
5733 retval = sched_setattr(p, &attr);
5741 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5742 * @pid: the pid in question.
5744 * Return: On success, the policy of the thread. Otherwise, a negative error
5747 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
5749 struct task_struct *p;
5757 p = find_process_by_pid(pid);
5759 retval = security_task_getscheduler(p);
5762 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
5769 * sys_sched_getparam - get the RT priority of a thread
5770 * @pid: the pid in question.
5771 * @param: structure containing the RT priority.
5773 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
5776 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
5778 struct sched_param lp = { .sched_priority = 0 };
5779 struct task_struct *p;
5782 if (!param || pid < 0)
5786 p = find_process_by_pid(pid);
5791 retval = security_task_getscheduler(p);
5795 if (task_has_rt_policy(p))
5796 lp.sched_priority = p->rt_priority;
5800 * This one might sleep, we cannot do it with a spinlock held ...
5802 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5812 * Copy the kernel size attribute structure (which might be larger
5813 * than what user-space knows about) to user-space.
5815 * Note that all cases are valid: user-space buffer can be larger or
5816 * smaller than the kernel-space buffer. The usual case is that both
5817 * have the same size.
5820 sched_attr_copy_to_user(struct sched_attr __user *uattr,
5821 struct sched_attr *kattr,
5824 unsigned int ksize = sizeof(*kattr);
5826 if (!access_ok(uattr, usize))
5830 * sched_getattr() ABI forwards and backwards compatibility:
5832 * If usize == ksize then we just copy everything to user-space and all is good.
5834 * If usize < ksize then we only copy as much as user-space has space for,
5835 * this keeps ABI compatibility as well. We skip the rest.
5837 * If usize > ksize then user-space is using a newer version of the ABI,
5838 * which part the kernel doesn't know about. Just ignore it - tooling can
5839 * detect the kernel's knowledge of attributes from the attr->size value
5840 * which is set to ksize in this case.
5842 kattr->size = min(usize, ksize);
5844 if (copy_to_user(uattr, kattr, kattr->size))
5851 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
5852 * @pid: the pid in question.
5853 * @uattr: structure containing the extended parameters.
5854 * @usize: sizeof(attr) for fwd/bwd comp.
5855 * @flags: for future extension.
5857 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
5858 unsigned int, usize, unsigned int, flags)
5860 struct sched_attr kattr = { };
5861 struct task_struct *p;
5864 if (!uattr || pid < 0 || usize > PAGE_SIZE ||
5865 usize < SCHED_ATTR_SIZE_VER0 || flags)
5869 p = find_process_by_pid(pid);
5874 retval = security_task_getscheduler(p);
5878 kattr.sched_policy = p->policy;
5879 if (p->sched_reset_on_fork)
5880 kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
5881 if (task_has_dl_policy(p))
5882 __getparam_dl(p, &kattr);
5883 else if (task_has_rt_policy(p))
5884 kattr.sched_priority = p->rt_priority;
5886 kattr.sched_nice = task_nice(p);
5888 #ifdef CONFIG_UCLAMP_TASK
5890 * This could race with another potential updater, but this is fine
5891 * because it'll correctly read the old or the new value. We don't need
5892 * to guarantee who wins the race as long as it doesn't return garbage.
5894 kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
5895 kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
5900 return sched_attr_copy_to_user(uattr, &kattr, usize);
5907 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
5909 cpumask_var_t cpus_allowed, new_mask;
5910 struct task_struct *p;
5915 p = find_process_by_pid(pid);
5921 /* Prevent p going away */
5925 if (p->flags & PF_NO_SETAFFINITY) {
5929 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
5933 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
5935 goto out_free_cpus_allowed;
5938 if (!check_same_owner(p)) {
5940 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
5942 goto out_free_new_mask;
5947 retval = security_task_setscheduler(p);
5949 goto out_free_new_mask;
5952 cpuset_cpus_allowed(p, cpus_allowed);
5953 cpumask_and(new_mask, in_mask, cpus_allowed);
5956 * Since bandwidth control happens on root_domain basis,
5957 * if admission test is enabled, we only admit -deadline
5958 * tasks allowed to run on all the CPUs in the task's
5962 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
5964 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
5967 goto out_free_new_mask;
5973 retval = __set_cpus_allowed_ptr(p, new_mask, true);
5976 cpuset_cpus_allowed(p, cpus_allowed);
5977 if (!cpumask_subset(new_mask, cpus_allowed)) {
5979 * We must have raced with a concurrent cpuset
5980 * update. Just reset the cpus_allowed to the
5981 * cpuset's cpus_allowed
5983 cpumask_copy(new_mask, cpus_allowed);
5988 free_cpumask_var(new_mask);
5989 out_free_cpus_allowed:
5990 free_cpumask_var(cpus_allowed);
5996 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5997 struct cpumask *new_mask)
5999 if (len < cpumask_size())
6000 cpumask_clear(new_mask);
6001 else if (len > cpumask_size())
6002 len = cpumask_size();
6004 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6008 * sys_sched_setaffinity - set the CPU affinity of a process
6009 * @pid: pid of the process
6010 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6011 * @user_mask_ptr: user-space pointer to the new CPU mask
6013 * Return: 0 on success. An error code otherwise.
6015 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6016 unsigned long __user *, user_mask_ptr)
6018 cpumask_var_t new_mask;
6021 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6024 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6026 retval = sched_setaffinity(pid, new_mask);
6027 free_cpumask_var(new_mask);
6031 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6033 struct task_struct *p;
6034 unsigned long flags;
6040 p = find_process_by_pid(pid);
6044 retval = security_task_getscheduler(p);
6048 raw_spin_lock_irqsave(&p->pi_lock, flags);
6049 cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
6050 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
6059 * sys_sched_getaffinity - get the CPU affinity of a process
6060 * @pid: pid of the process
6061 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6062 * @user_mask_ptr: user-space pointer to hold the current CPU mask
6064 * Return: size of CPU mask copied to user_mask_ptr on success. An
6065 * error code otherwise.
6067 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6068 unsigned long __user *, user_mask_ptr)
6073 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
6075 if (len & (sizeof(unsigned long)-1))
6078 if (!zalloc_cpumask_var(&mask, GFP_KERNEL))
6081 ret = sched_getaffinity(pid, mask);
6083 unsigned int retlen = min(len, cpumask_size());
6085 if (copy_to_user(user_mask_ptr, cpumask_bits(mask), retlen))
6090 free_cpumask_var(mask);
6096 * sys_sched_yield - yield the current processor to other threads.
6098 * This function yields the current CPU to other tasks. If there are no
6099 * other threads running on this CPU then this function will return.
6103 static void do_sched_yield(void)
6108 rq = this_rq_lock_irq(&rf);
6110 schedstat_inc(rq->yld_count);
6111 current->sched_class->yield_task(rq);
6114 rq_unlock_irq(rq, &rf);
6115 sched_preempt_enable_no_resched();
6120 SYSCALL_DEFINE0(sched_yield)
6126 #ifndef CONFIG_PREEMPTION
6127 int __sched _cond_resched(void)
6129 if (should_resched(0)) {
6130 preempt_schedule_common();
6136 EXPORT_SYMBOL(_cond_resched);
6140 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
6141 * call schedule, and on return reacquire the lock.
6143 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
6144 * operations here to prevent schedule() from being called twice (once via
6145 * spin_unlock(), once by hand).
6147 int __cond_resched_lock(spinlock_t *lock)
6149 int resched = should_resched(PREEMPT_LOCK_OFFSET);
6152 lockdep_assert_held(lock);
6154 if (spin_needbreak(lock) || resched) {
6157 preempt_schedule_common();
6165 EXPORT_SYMBOL(__cond_resched_lock);
6168 * yield - yield the current processor to other threads.
6170 * Do not ever use this function, there's a 99% chance you're doing it wrong.
6172 * The scheduler is at all times free to pick the calling task as the most
6173 * eligible task to run, if removing the yield() call from your code breaks
6174 * it, its already broken.
6176 * Typical broken usage is:
6181 * where one assumes that yield() will let 'the other' process run that will
6182 * make event true. If the current task is a SCHED_FIFO task that will never
6183 * happen. Never use yield() as a progress guarantee!!
6185 * If you want to use yield() to wait for something, use wait_event().
6186 * If you want to use yield() to be 'nice' for others, use cond_resched().
6187 * If you still want to use yield(), do not!
6189 void __sched yield(void)
6191 set_current_state(TASK_RUNNING);
6194 EXPORT_SYMBOL(yield);
6197 * yield_to - yield the current processor to another thread in
6198 * your thread group, or accelerate that thread toward the
6199 * processor it's on.
6201 * @preempt: whether task preemption is allowed or not
6203 * It's the caller's job to ensure that the target task struct
6204 * can't go away on us before we can do any checks.
6207 * true (>0) if we indeed boosted the target task.
6208 * false (0) if we failed to boost the target.
6209 * -ESRCH if there's no task to yield to.
6211 int __sched yield_to(struct task_struct *p, bool preempt)
6213 struct task_struct *curr = current;
6214 struct rq *rq, *p_rq;
6215 unsigned long flags;
6218 local_irq_save(flags);
6224 * If we're the only runnable task on the rq and target rq also
6225 * has only one task, there's absolutely no point in yielding.
6227 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
6232 double_rq_lock(rq, p_rq);
6233 if (task_rq(p) != p_rq) {
6234 double_rq_unlock(rq, p_rq);
6238 if (!curr->sched_class->yield_to_task)
6241 if (curr->sched_class != p->sched_class)
6244 if (task_running(p_rq, p) || p->state)
6247 yielded = curr->sched_class->yield_to_task(rq, p);
6249 schedstat_inc(rq->yld_count);
6251 * Make p's CPU reschedule; pick_next_entity takes care of
6254 if (preempt && rq != p_rq)
6259 double_rq_unlock(rq, p_rq);
6261 local_irq_restore(flags);
6268 EXPORT_SYMBOL_GPL(yield_to);
6270 int io_schedule_prepare(void)
6272 int old_iowait = current->in_iowait;
6274 current->in_iowait = 1;
6275 blk_schedule_flush_plug(current);
6280 void io_schedule_finish(int token)
6282 current->in_iowait = token;
6286 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6287 * that process accounting knows that this is a task in IO wait state.
6289 long __sched io_schedule_timeout(long timeout)
6294 token = io_schedule_prepare();
6295 ret = schedule_timeout(timeout);
6296 io_schedule_finish(token);
6300 EXPORT_SYMBOL(io_schedule_timeout);
6302 void __sched io_schedule(void)
6306 token = io_schedule_prepare();
6308 io_schedule_finish(token);
6310 EXPORT_SYMBOL(io_schedule);
6313 * sys_sched_get_priority_max - return maximum RT priority.
6314 * @policy: scheduling class.
6316 * Return: On success, this syscall returns the maximum
6317 * rt_priority that can be used by a given scheduling class.
6318 * On failure, a negative error code is returned.
6320 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6327 ret = MAX_USER_RT_PRIO-1;
6329 case SCHED_DEADLINE:
6340 * sys_sched_get_priority_min - return minimum RT priority.
6341 * @policy: scheduling class.
6343 * Return: On success, this syscall returns the minimum
6344 * rt_priority that can be used by a given scheduling class.
6345 * On failure, a negative error code is returned.
6347 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6356 case SCHED_DEADLINE:
6365 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
6367 struct task_struct *p;
6368 unsigned int time_slice;
6378 p = find_process_by_pid(pid);
6382 retval = security_task_getscheduler(p);
6386 rq = task_rq_lock(p, &rf);
6388 if (p->sched_class->get_rr_interval)
6389 time_slice = p->sched_class->get_rr_interval(rq, p);
6390 task_rq_unlock(rq, p, &rf);
6393 jiffies_to_timespec64(time_slice, t);
6402 * sys_sched_rr_get_interval - return the default timeslice of a process.
6403 * @pid: pid of the process.
6404 * @interval: userspace pointer to the timeslice value.
6406 * this syscall writes the default timeslice value of a given process
6407 * into the user-space timespec buffer. A value of '0' means infinity.
6409 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
6412 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
6413 struct __kernel_timespec __user *, interval)
6415 struct timespec64 t;
6416 int retval = sched_rr_get_interval(pid, &t);
6419 retval = put_timespec64(&t, interval);
6424 #ifdef CONFIG_COMPAT_32BIT_TIME
6425 SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
6426 struct old_timespec32 __user *, interval)
6428 struct timespec64 t;
6429 int retval = sched_rr_get_interval(pid, &t);
6432 retval = put_old_timespec32(&t, interval);
6437 void sched_show_task(struct task_struct *p)
6439 unsigned long free = 0;
6442 if (!try_get_task_stack(p))
6445 pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
6447 if (p->state == TASK_RUNNING)
6448 pr_cont(" running task ");
6449 #ifdef CONFIG_DEBUG_STACK_USAGE
6450 free = stack_not_used(p);
6455 ppid = task_pid_nr(rcu_dereference(p->real_parent));
6457 pr_cont(" stack:%5lu pid:%5d ppid:%6d flags:0x%08lx\n",
6458 free, task_pid_nr(p), ppid,
6459 (unsigned long)task_thread_info(p)->flags);
6461 print_worker_info(KERN_INFO, p);
6462 show_stack(p, NULL, KERN_INFO);
6465 EXPORT_SYMBOL_GPL(sched_show_task);
6468 state_filter_match(unsigned long state_filter, struct task_struct *p)
6470 /* no filter, everything matches */
6474 /* filter, but doesn't match */
6475 if (!(p->state & state_filter))
6479 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
6482 if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
6489 void show_state_filter(unsigned long state_filter)
6491 struct task_struct *g, *p;
6494 for_each_process_thread(g, p) {
6496 * reset the NMI-timeout, listing all files on a slow
6497 * console might take a lot of time:
6498 * Also, reset softlockup watchdogs on all CPUs, because
6499 * another CPU might be blocked waiting for us to process
6502 touch_nmi_watchdog();
6503 touch_all_softlockup_watchdogs();
6504 if (state_filter_match(state_filter, p))
6508 #ifdef CONFIG_SCHED_DEBUG
6510 sysrq_sched_debug_show();
6514 * Only show locks if all tasks are dumped:
6517 debug_show_all_locks();
6521 * init_idle - set up an idle thread for a given CPU
6522 * @idle: task in question
6523 * @cpu: CPU the idle task belongs to
6525 * NOTE: this function does not set the idle thread's NEED_RESCHED
6526 * flag, to make booting more robust.
6528 void __init init_idle(struct task_struct *idle, int cpu)
6530 struct rq *rq = cpu_rq(cpu);
6531 unsigned long flags;
6533 __sched_fork(0, idle);
6535 raw_spin_lock_irqsave(&idle->pi_lock, flags);
6536 raw_spin_lock(&rq->lock);
6538 idle->state = TASK_RUNNING;
6539 idle->se.exec_start = sched_clock();
6540 idle->flags |= PF_IDLE;
6544 * Its possible that init_idle() gets called multiple times on a task,
6545 * in that case do_set_cpus_allowed() will not do the right thing.
6547 * And since this is boot we can forgo the serialization.
6549 set_cpus_allowed_common(idle, cpumask_of(cpu));
6552 * We're having a chicken and egg problem, even though we are
6553 * holding rq->lock, the CPU isn't yet set to this CPU so the
6554 * lockdep check in task_group() will fail.
6556 * Similar case to sched_fork(). / Alternatively we could
6557 * use task_rq_lock() here and obtain the other rq->lock.
6562 __set_task_cpu(idle, cpu);
6566 rcu_assign_pointer(rq->curr, idle);
6567 idle->on_rq = TASK_ON_RQ_QUEUED;
6571 raw_spin_unlock(&rq->lock);
6572 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
6574 /* Set the preempt count _outside_ the spinlocks! */
6575 init_idle_preempt_count(idle, cpu);
6578 * The idle tasks have their own, simple scheduling class:
6580 idle->sched_class = &idle_sched_class;
6581 ftrace_graph_init_idle_task(idle, cpu);
6582 vtime_init_idle(idle, cpu);
6584 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
6590 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
6591 const struct cpumask *trial)
6595 if (!cpumask_weight(cur))
6598 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
6603 int task_can_attach(struct task_struct *p)
6608 * Kthreads which disallow setaffinity shouldn't be moved
6609 * to a new cpuset; we don't want to change their CPU
6610 * affinity and isolating such threads by their set of
6611 * allowed nodes is unnecessary. Thus, cpusets are not
6612 * applicable for such threads. This prevents checking for
6613 * success of set_cpus_allowed_ptr() on all attached tasks
6614 * before cpus_mask may be changed.
6616 if (p->flags & PF_NO_SETAFFINITY)
6622 bool sched_smp_initialized __read_mostly;
6624 #ifdef CONFIG_NUMA_BALANCING
6625 /* Migrate current task p to target_cpu */
6626 int migrate_task_to(struct task_struct *p, int target_cpu)
6628 struct migration_arg arg = { p, target_cpu };
6629 int curr_cpu = task_cpu(p);
6631 if (curr_cpu == target_cpu)
6634 if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
6637 /* TODO: This is not properly updating schedstats */
6639 trace_sched_move_numa(p, curr_cpu, target_cpu);
6640 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
6644 * Requeue a task on a given node and accurately track the number of NUMA
6645 * tasks on the runqueues
6647 void sched_setnuma(struct task_struct *p, int nid)
6649 bool queued, running;
6653 rq = task_rq_lock(p, &rf);
6654 queued = task_on_rq_queued(p);
6655 running = task_current(rq, p);
6658 dequeue_task(rq, p, DEQUEUE_SAVE);
6660 put_prev_task(rq, p);
6662 p->numa_preferred_nid = nid;
6665 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
6667 set_next_task(rq, p);
6668 task_rq_unlock(rq, p, &rf);
6670 #endif /* CONFIG_NUMA_BALANCING */
6672 #ifdef CONFIG_HOTPLUG_CPU
6674 * Ensure that the idle task is using init_mm right before its CPU goes
6677 void idle_task_exit(void)
6679 struct mm_struct *mm = current->active_mm;
6681 BUG_ON(cpu_online(smp_processor_id()));
6682 BUG_ON(current != this_rq()->idle);
6684 if (mm != &init_mm) {
6685 switch_mm(mm, &init_mm, current);
6686 finish_arch_post_lock_switch();
6689 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
6693 * Since this CPU is going 'away' for a while, fold any nr_active delta
6694 * we might have. Assumes we're called after migrate_tasks() so that the
6695 * nr_active count is stable. We need to take the teardown thread which
6696 * is calling this into account, so we hand in adjust = 1 to the load
6699 * Also see the comment "Global load-average calculations".
6701 static void calc_load_migrate(struct rq *rq)
6703 long delta = calc_load_fold_active(rq, 1);
6705 atomic_long_add(delta, &calc_load_tasks);
6708 static struct task_struct *__pick_migrate_task(struct rq *rq)
6710 const struct sched_class *class;
6711 struct task_struct *next;
6713 for_each_class(class) {
6714 next = class->pick_next_task(rq);
6716 next->sched_class->put_prev_task(rq, next);
6721 /* The idle class should always have a runnable task */
6726 * Migrate all tasks from the rq, sleeping tasks will be migrated by
6727 * try_to_wake_up()->select_task_rq().
6729 * Called with rq->lock held even though we'er in stop_machine() and
6730 * there's no concurrency possible, we hold the required locks anyway
6731 * because of lock validation efforts.
6733 static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
6735 struct rq *rq = dead_rq;
6736 struct task_struct *next, *stop = rq->stop;
6737 struct rq_flags orf = *rf;
6741 * Fudge the rq selection such that the below task selection loop
6742 * doesn't get stuck on the currently eligible stop task.
6744 * We're currently inside stop_machine() and the rq is either stuck
6745 * in the stop_machine_cpu_stop() loop, or we're executing this code,
6746 * either way we should never end up calling schedule() until we're
6752 * put_prev_task() and pick_next_task() sched
6753 * class method both need to have an up-to-date
6754 * value of rq->clock[_task]
6756 update_rq_clock(rq);
6760 * There's this thread running, bail when that's the only
6763 if (rq->nr_running == 1)
6766 next = __pick_migrate_task(rq);
6769 * Rules for changing task_struct::cpus_mask are holding
6770 * both pi_lock and rq->lock, such that holding either
6771 * stabilizes the mask.
6773 * Drop rq->lock is not quite as disastrous as it usually is
6774 * because !cpu_active at this point, which means load-balance
6775 * will not interfere. Also, stop-machine.
6778 raw_spin_lock(&next->pi_lock);
6782 * Since we're inside stop-machine, _nothing_ should have
6783 * changed the task, WARN if weird stuff happened, because in
6784 * that case the above rq->lock drop is a fail too.
6786 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
6787 raw_spin_unlock(&next->pi_lock);
6791 /* Find suitable destination for @next, with force if needed. */
6792 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
6793 rq = __migrate_task(rq, rf, next, dest_cpu);
6794 if (rq != dead_rq) {
6800 raw_spin_unlock(&next->pi_lock);
6805 #endif /* CONFIG_HOTPLUG_CPU */
6807 void set_rq_online(struct rq *rq)
6810 const struct sched_class *class;
6812 cpumask_set_cpu(rq->cpu, rq->rd->online);
6815 for_each_class(class) {
6816 if (class->rq_online)
6817 class->rq_online(rq);
6822 void set_rq_offline(struct rq *rq)
6825 const struct sched_class *class;
6827 for_each_class(class) {
6828 if (class->rq_offline)
6829 class->rq_offline(rq);
6832 cpumask_clear_cpu(rq->cpu, rq->rd->online);
6838 * used to mark begin/end of suspend/resume:
6840 static int num_cpus_frozen;
6843 * Update cpusets according to cpu_active mask. If cpusets are
6844 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
6845 * around partition_sched_domains().
6847 * If we come here as part of a suspend/resume, don't touch cpusets because we
6848 * want to restore it back to its original state upon resume anyway.
6850 static void cpuset_cpu_active(void)
6852 if (cpuhp_tasks_frozen) {
6854 * num_cpus_frozen tracks how many CPUs are involved in suspend
6855 * resume sequence. As long as this is not the last online
6856 * operation in the resume sequence, just build a single sched
6857 * domain, ignoring cpusets.
6859 partition_sched_domains(1, NULL, NULL);
6860 if (--num_cpus_frozen)
6863 * This is the last CPU online operation. So fall through and
6864 * restore the original sched domains by considering the
6865 * cpuset configurations.
6867 cpuset_force_rebuild();
6869 cpuset_update_active_cpus();
6872 static int cpuset_cpu_inactive(unsigned int cpu)
6874 if (!cpuhp_tasks_frozen) {
6875 int ret = dl_bw_check_overflow(cpu);
6879 cpuset_update_active_cpus();
6882 partition_sched_domains(1, NULL, NULL);
6887 int sched_cpu_activate(unsigned int cpu)
6889 struct rq *rq = cpu_rq(cpu);
6892 #ifdef CONFIG_SCHED_SMT
6894 * When going up, increment the number of cores with SMT present.
6896 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
6897 static_branch_inc_cpuslocked(&sched_smt_present);
6899 set_cpu_active(cpu, true);
6901 if (sched_smp_initialized) {
6902 sched_domains_numa_masks_set(cpu);
6903 cpuset_cpu_active();
6907 * Put the rq online, if not already. This happens:
6909 * 1) In the early boot process, because we build the real domains
6910 * after all CPUs have been brought up.
6912 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
6915 rq_lock_irqsave(rq, &rf);
6917 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6920 rq_unlock_irqrestore(rq, &rf);
6925 int sched_cpu_deactivate(unsigned int cpu)
6929 set_cpu_active(cpu, false);
6931 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
6932 * users of this state to go away such that all new such users will
6935 * Do sync before park smpboot threads to take care the rcu boost case.
6939 #ifdef CONFIG_SCHED_SMT
6941 * When going down, decrement the number of cores with SMT present.
6943 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
6944 static_branch_dec_cpuslocked(&sched_smt_present);
6947 if (!sched_smp_initialized)
6950 ret = cpuset_cpu_inactive(cpu);
6952 set_cpu_active(cpu, true);
6955 sched_domains_numa_masks_clear(cpu);
6959 static void sched_rq_cpu_starting(unsigned int cpu)
6961 struct rq *rq = cpu_rq(cpu);
6963 rq->calc_load_update = calc_load_update;
6964 update_max_interval();
6967 int sched_cpu_starting(unsigned int cpu)
6969 sched_rq_cpu_starting(cpu);
6970 sched_tick_start(cpu);
6974 #ifdef CONFIG_HOTPLUG_CPU
6975 int sched_cpu_dying(unsigned int cpu)
6977 struct rq *rq = cpu_rq(cpu);
6980 /* Handle pending wakeups and then migrate everything off */
6981 sched_tick_stop(cpu);
6983 rq_lock_irqsave(rq, &rf);
6985 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6988 migrate_tasks(rq, &rf);
6989 BUG_ON(rq->nr_running != 1);
6990 rq_unlock_irqrestore(rq, &rf);
6992 calc_load_migrate(rq);
6993 update_max_interval();
6994 nohz_balance_exit_idle(rq);
7000 void __init sched_init_smp(void)
7005 * There's no userspace yet to cause hotplug operations; hence all the
7006 * CPU masks are stable and all blatant races in the below code cannot
7009 mutex_lock(&sched_domains_mutex);
7010 sched_init_domains(cpu_active_mask);
7011 mutex_unlock(&sched_domains_mutex);
7013 /* Move init over to a non-isolated CPU */
7014 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
7016 sched_init_granularity();
7018 init_sched_rt_class();
7019 init_sched_dl_class();
7021 sched_smp_initialized = true;
7024 static int __init migration_init(void)
7026 sched_cpu_starting(smp_processor_id());
7029 early_initcall(migration_init);
7032 void __init sched_init_smp(void)
7034 sched_init_granularity();
7036 #endif /* CONFIG_SMP */
7038 int in_sched_functions(unsigned long addr)
7040 return in_lock_functions(addr) ||
7041 (addr >= (unsigned long)__sched_text_start
7042 && addr < (unsigned long)__sched_text_end);
7045 #ifdef CONFIG_CGROUP_SCHED
7047 * Default task group.
7048 * Every task in system belongs to this group at bootup.
7050 struct task_group root_task_group;
7051 LIST_HEAD(task_groups);
7053 /* Cacheline aligned slab cache for task_group */
7054 static struct kmem_cache *task_group_cache __read_mostly;
7057 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7058 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
7060 void __init sched_init(void)
7062 unsigned long ptr = 0;
7065 /* Make sure the linker didn't screw up */
7066 BUG_ON(&idle_sched_class + 1 != &fair_sched_class ||
7067 &fair_sched_class + 1 != &rt_sched_class ||
7068 &rt_sched_class + 1 != &dl_sched_class);
7070 BUG_ON(&dl_sched_class + 1 != &stop_sched_class);
7075 #ifdef CONFIG_FAIR_GROUP_SCHED
7076 ptr += 2 * nr_cpu_ids * sizeof(void **);
7078 #ifdef CONFIG_RT_GROUP_SCHED
7079 ptr += 2 * nr_cpu_ids * sizeof(void **);
7082 ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
7084 #ifdef CONFIG_FAIR_GROUP_SCHED
7085 root_task_group.se = (struct sched_entity **)ptr;
7086 ptr += nr_cpu_ids * sizeof(void **);
7088 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7089 ptr += nr_cpu_ids * sizeof(void **);
7091 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7092 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7093 #endif /* CONFIG_FAIR_GROUP_SCHED */
7094 #ifdef CONFIG_RT_GROUP_SCHED
7095 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7096 ptr += nr_cpu_ids * sizeof(void **);
7098 root_task_group.rt_rq = (struct rt_rq **)ptr;
7099 ptr += nr_cpu_ids * sizeof(void **);
7101 #endif /* CONFIG_RT_GROUP_SCHED */
7103 #ifdef CONFIG_CPUMASK_OFFSTACK
7104 for_each_possible_cpu(i) {
7105 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7106 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7107 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
7108 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7110 #endif /* CONFIG_CPUMASK_OFFSTACK */
7112 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
7113 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
7116 init_defrootdomain();
7119 #ifdef CONFIG_RT_GROUP_SCHED
7120 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7121 global_rt_period(), global_rt_runtime());
7122 #endif /* CONFIG_RT_GROUP_SCHED */
7124 #ifdef CONFIG_CGROUP_SCHED
7125 task_group_cache = KMEM_CACHE(task_group, 0);
7127 list_add(&root_task_group.list, &task_groups);
7128 INIT_LIST_HEAD(&root_task_group.children);
7129 INIT_LIST_HEAD(&root_task_group.siblings);
7130 autogroup_init(&init_task);
7131 #endif /* CONFIG_CGROUP_SCHED */
7133 for_each_possible_cpu(i) {
7137 raw_spin_lock_init(&rq->lock);
7139 rq->calc_load_active = 0;
7140 rq->calc_load_update = jiffies + LOAD_FREQ;
7141 init_cfs_rq(&rq->cfs);
7142 init_rt_rq(&rq->rt);
7143 init_dl_rq(&rq->dl);
7144 #ifdef CONFIG_FAIR_GROUP_SCHED
7145 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7146 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
7148 * How much CPU bandwidth does root_task_group get?
7150 * In case of task-groups formed thr' the cgroup filesystem, it
7151 * gets 100% of the CPU resources in the system. This overall
7152 * system CPU resource is divided among the tasks of
7153 * root_task_group and its child task-groups in a fair manner,
7154 * based on each entity's (task or task-group's) weight
7155 * (se->load.weight).
7157 * In other words, if root_task_group has 10 tasks of weight
7158 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7159 * then A0's share of the CPU resource is:
7161 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7163 * We achieve this by letting root_task_group's tasks sit
7164 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7166 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7167 #endif /* CONFIG_FAIR_GROUP_SCHED */
7169 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7170 #ifdef CONFIG_RT_GROUP_SCHED
7171 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7176 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7177 rq->balance_callback = NULL;
7178 rq->active_balance = 0;
7179 rq->next_balance = jiffies;
7184 rq->avg_idle = 2*sysctl_sched_migration_cost;
7185 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7187 INIT_LIST_HEAD(&rq->cfs_tasks);
7189 rq_attach_root(rq, &def_root_domain);
7190 #ifdef CONFIG_NO_HZ_COMMON
7191 rq->last_blocked_load_update_tick = jiffies;
7192 atomic_set(&rq->nohz_flags, 0);
7194 rq_csd_init(rq, &rq->nohz_csd, nohz_csd_func);
7196 #endif /* CONFIG_SMP */
7198 atomic_set(&rq->nr_iowait, 0);
7201 set_load_weight(&init_task);
7204 * The boot idle thread does lazy MMU switching as well:
7207 enter_lazy_tlb(&init_mm, current);
7210 * Make us the idle thread. Technically, schedule() should not be
7211 * called from this thread, however somewhere below it might be,
7212 * but because we are the idle thread, we just pick up running again
7213 * when this runqueue becomes "idle".
7215 init_idle(current, smp_processor_id());
7217 calc_load_update = jiffies + LOAD_FREQ;
7220 idle_thread_set_boot_cpu();
7222 init_sched_fair_class();
7230 scheduler_running = 1;
7233 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7234 static inline int preempt_count_equals(int preempt_offset)
7236 int nested = preempt_count() + rcu_preempt_depth();
7238 return (nested == preempt_offset);
7241 void __might_sleep(const char *file, int line, int preempt_offset)
7244 * Blocking primitives will set (and therefore destroy) current->state,
7245 * since we will exit with TASK_RUNNING make sure we enter with it,
7246 * otherwise we will destroy state.
7248 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7249 "do not call blocking ops when !TASK_RUNNING; "
7250 "state=%lx set at [<%p>] %pS\n",
7252 (void *)current->task_state_change,
7253 (void *)current->task_state_change);
7255 ___might_sleep(file, line, preempt_offset);
7257 EXPORT_SYMBOL(__might_sleep);
7259 void ___might_sleep(const char *file, int line, int preempt_offset)
7261 /* Ratelimiting timestamp: */
7262 static unsigned long prev_jiffy;
7264 unsigned long preempt_disable_ip;
7266 /* WARN_ON_ONCE() by default, no rate limit required: */
7269 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7270 !is_idle_task(current) && !current->non_block_count) ||
7271 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
7275 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7277 prev_jiffy = jiffies;
7279 /* Save this before calling printk(), since that will clobber it: */
7280 preempt_disable_ip = get_preempt_disable_ip(current);
7283 "BUG: sleeping function called from invalid context at %s:%d\n",
7286 "in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
7287 in_atomic(), irqs_disabled(), current->non_block_count,
7288 current->pid, current->comm);
7290 if (task_stack_end_corrupted(current))
7291 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
7293 debug_show_held_locks(current);
7294 if (irqs_disabled())
7295 print_irqtrace_events(current);
7296 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
7297 && !preempt_count_equals(preempt_offset)) {
7298 pr_err("Preemption disabled at:");
7299 print_ip_sym(KERN_ERR, preempt_disable_ip);
7302 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
7304 EXPORT_SYMBOL(___might_sleep);
7306 void __cant_sleep(const char *file, int line, int preempt_offset)
7308 static unsigned long prev_jiffy;
7310 if (irqs_disabled())
7313 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
7316 if (preempt_count() > preempt_offset)
7319 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7321 prev_jiffy = jiffies;
7323 printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
7324 printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7325 in_atomic(), irqs_disabled(),
7326 current->pid, current->comm);
7328 debug_show_held_locks(current);
7330 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
7332 EXPORT_SYMBOL_GPL(__cant_sleep);
7335 #ifdef CONFIG_MAGIC_SYSRQ
7336 void normalize_rt_tasks(void)
7338 struct task_struct *g, *p;
7339 struct sched_attr attr = {
7340 .sched_policy = SCHED_NORMAL,
7343 read_lock(&tasklist_lock);
7344 for_each_process_thread(g, p) {
7346 * Only normalize user tasks:
7348 if (p->flags & PF_KTHREAD)
7351 p->se.exec_start = 0;
7352 schedstat_set(p->se.statistics.wait_start, 0);
7353 schedstat_set(p->se.statistics.sleep_start, 0);
7354 schedstat_set(p->se.statistics.block_start, 0);
7356 if (!dl_task(p) && !rt_task(p)) {
7358 * Renice negative nice level userspace
7361 if (task_nice(p) < 0)
7362 set_user_nice(p, 0);
7366 __sched_setscheduler(p, &attr, false, false);
7368 read_unlock(&tasklist_lock);
7371 #endif /* CONFIG_MAGIC_SYSRQ */
7373 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7375 * These functions are only useful for the IA64 MCA handling, or kdb.
7377 * They can only be called when the whole system has been
7378 * stopped - every CPU needs to be quiescent, and no scheduling
7379 * activity can take place. Using them for anything else would
7380 * be a serious bug, and as a result, they aren't even visible
7381 * under any other configuration.
7385 * curr_task - return the current task for a given CPU.
7386 * @cpu: the processor in question.
7388 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7390 * Return: The current task for @cpu.
7392 struct task_struct *curr_task(int cpu)
7394 return cpu_curr(cpu);
7397 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7401 * ia64_set_curr_task - set the current task for a given CPU.
7402 * @cpu: the processor in question.
7403 * @p: the task pointer to set.
7405 * Description: This function must only be used when non-maskable interrupts
7406 * are serviced on a separate stack. It allows the architecture to switch the
7407 * notion of the current task on a CPU in a non-blocking manner. This function
7408 * must be called with all CPU's synchronized, and interrupts disabled, the
7409 * and caller must save the original value of the current task (see
7410 * curr_task() above) and restore that value before reenabling interrupts and
7411 * re-starting the system.
7413 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7415 void ia64_set_curr_task(int cpu, struct task_struct *p)
7422 #ifdef CONFIG_CGROUP_SCHED
7423 /* task_group_lock serializes the addition/removal of task groups */
7424 static DEFINE_SPINLOCK(task_group_lock);
7426 static inline void alloc_uclamp_sched_group(struct task_group *tg,
7427 struct task_group *parent)
7429 #ifdef CONFIG_UCLAMP_TASK_GROUP
7430 enum uclamp_id clamp_id;
7432 for_each_clamp_id(clamp_id) {
7433 uclamp_se_set(&tg->uclamp_req[clamp_id],
7434 uclamp_none(clamp_id), false);
7435 tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
7440 static void sched_free_group(struct task_group *tg)
7442 free_fair_sched_group(tg);
7443 free_rt_sched_group(tg);
7445 kmem_cache_free(task_group_cache, tg);
7448 /* allocate runqueue etc for a new task group */
7449 struct task_group *sched_create_group(struct task_group *parent)
7451 struct task_group *tg;
7453 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
7455 return ERR_PTR(-ENOMEM);
7457 if (!alloc_fair_sched_group(tg, parent))
7460 if (!alloc_rt_sched_group(tg, parent))
7463 alloc_uclamp_sched_group(tg, parent);
7468 sched_free_group(tg);
7469 return ERR_PTR(-ENOMEM);
7472 void sched_online_group(struct task_group *tg, struct task_group *parent)
7474 unsigned long flags;
7476 spin_lock_irqsave(&task_group_lock, flags);
7477 list_add_rcu(&tg->list, &task_groups);
7479 /* Root should already exist: */
7482 tg->parent = parent;
7483 INIT_LIST_HEAD(&tg->children);
7484 list_add_rcu(&tg->siblings, &parent->children);
7485 spin_unlock_irqrestore(&task_group_lock, flags);
7487 online_fair_sched_group(tg);
7490 /* rcu callback to free various structures associated with a task group */
7491 static void sched_free_group_rcu(struct rcu_head *rhp)
7493 /* Now it should be safe to free those cfs_rqs: */
7494 sched_free_group(container_of(rhp, struct task_group, rcu));
7497 void sched_destroy_group(struct task_group *tg)
7499 /* Wait for possible concurrent references to cfs_rqs complete: */
7500 call_rcu(&tg->rcu, sched_free_group_rcu);
7503 void sched_offline_group(struct task_group *tg)
7505 unsigned long flags;
7507 /* End participation in shares distribution: */
7508 unregister_fair_sched_group(tg);
7510 spin_lock_irqsave(&task_group_lock, flags);
7511 list_del_rcu(&tg->list);
7512 list_del_rcu(&tg->siblings);
7513 spin_unlock_irqrestore(&task_group_lock, flags);
7516 static void sched_change_group(struct task_struct *tsk, int type)
7518 struct task_group *tg;
7521 * All callers are synchronized by task_rq_lock(); we do not use RCU
7522 * which is pointless here. Thus, we pass "true" to task_css_check()
7523 * to prevent lockdep warnings.
7525 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
7526 struct task_group, css);
7527 tg = autogroup_task_group(tsk, tg);
7528 tsk->sched_task_group = tg;
7530 #ifdef CONFIG_FAIR_GROUP_SCHED
7531 if (tsk->sched_class->task_change_group)
7532 tsk->sched_class->task_change_group(tsk, type);
7535 set_task_rq(tsk, task_cpu(tsk));
7539 * Change task's runqueue when it moves between groups.
7541 * The caller of this function should have put the task in its new group by
7542 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
7545 void sched_move_task(struct task_struct *tsk)
7547 int queued, running, queue_flags =
7548 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
7552 rq = task_rq_lock(tsk, &rf);
7553 update_rq_clock(rq);
7555 running = task_current(rq, tsk);
7556 queued = task_on_rq_queued(tsk);
7559 dequeue_task(rq, tsk, queue_flags);
7561 put_prev_task(rq, tsk);
7563 sched_change_group(tsk, TASK_MOVE_GROUP);
7566 enqueue_task(rq, tsk, queue_flags);
7568 set_next_task(rq, tsk);
7570 * After changing group, the running task may have joined a
7571 * throttled one but it's still the running task. Trigger a
7572 * resched to make sure that task can still run.
7577 task_rq_unlock(rq, tsk, &rf);
7580 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
7582 return css ? container_of(css, struct task_group, css) : NULL;
7585 static struct cgroup_subsys_state *
7586 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
7588 struct task_group *parent = css_tg(parent_css);
7589 struct task_group *tg;
7592 /* This is early initialization for the top cgroup */
7593 return &root_task_group.css;
7596 tg = sched_create_group(parent);
7598 return ERR_PTR(-ENOMEM);
7603 /* Expose task group only after completing cgroup initialization */
7604 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
7606 struct task_group *tg = css_tg(css);
7607 struct task_group *parent = css_tg(css->parent);
7610 sched_online_group(tg, parent);
7612 #ifdef CONFIG_UCLAMP_TASK_GROUP
7613 /* Propagate the effective uclamp value for the new group */
7614 mutex_lock(&uclamp_mutex);
7616 cpu_util_update_eff(css);
7618 mutex_unlock(&uclamp_mutex);
7624 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
7626 struct task_group *tg = css_tg(css);
7628 sched_offline_group(tg);
7631 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
7633 struct task_group *tg = css_tg(css);
7636 * Relies on the RCU grace period between css_released() and this.
7638 sched_free_group(tg);
7642 * This is called before wake_up_new_task(), therefore we really only
7643 * have to set its group bits, all the other stuff does not apply.
7645 static void cpu_cgroup_fork(struct task_struct *task)
7650 rq = task_rq_lock(task, &rf);
7652 update_rq_clock(rq);
7653 sched_change_group(task, TASK_SET_GROUP);
7655 task_rq_unlock(rq, task, &rf);
7658 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
7660 struct task_struct *task;
7661 struct cgroup_subsys_state *css;
7664 cgroup_taskset_for_each(task, css, tset) {
7665 #ifdef CONFIG_RT_GROUP_SCHED
7666 if (!sched_rt_can_attach(css_tg(css), task))
7670 * Serialize against wake_up_new_task() such that if its
7671 * running, we're sure to observe its full state.
7673 raw_spin_lock_irq(&task->pi_lock);
7675 * Avoid calling sched_move_task() before wake_up_new_task()
7676 * has happened. This would lead to problems with PELT, due to
7677 * move wanting to detach+attach while we're not attached yet.
7679 if (task->state == TASK_NEW)
7681 raw_spin_unlock_irq(&task->pi_lock);
7689 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
7691 struct task_struct *task;
7692 struct cgroup_subsys_state *css;
7694 cgroup_taskset_for_each(task, css, tset)
7695 sched_move_task(task);
7698 #ifdef CONFIG_UCLAMP_TASK_GROUP
7699 static void cpu_util_update_eff(struct cgroup_subsys_state *css)
7701 struct cgroup_subsys_state *top_css = css;
7702 struct uclamp_se *uc_parent = NULL;
7703 struct uclamp_se *uc_se = NULL;
7704 unsigned int eff[UCLAMP_CNT];
7705 enum uclamp_id clamp_id;
7706 unsigned int clamps;
7708 lockdep_assert_held(&uclamp_mutex);
7709 SCHED_WARN_ON(!rcu_read_lock_held());
7711 css_for_each_descendant_pre(css, top_css) {
7712 uc_parent = css_tg(css)->parent
7713 ? css_tg(css)->parent->uclamp : NULL;
7715 for_each_clamp_id(clamp_id) {
7716 /* Assume effective clamps matches requested clamps */
7717 eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
7718 /* Cap effective clamps with parent's effective clamps */
7720 eff[clamp_id] > uc_parent[clamp_id].value) {
7721 eff[clamp_id] = uc_parent[clamp_id].value;
7724 /* Ensure protection is always capped by limit */
7725 eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
7727 /* Propagate most restrictive effective clamps */
7729 uc_se = css_tg(css)->uclamp;
7730 for_each_clamp_id(clamp_id) {
7731 if (eff[clamp_id] == uc_se[clamp_id].value)
7733 uc_se[clamp_id].value = eff[clamp_id];
7734 uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
7735 clamps |= (0x1 << clamp_id);
7738 css = css_rightmost_descendant(css);
7742 /* Immediately update descendants RUNNABLE tasks */
7743 uclamp_update_active_tasks(css);
7748 * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
7749 * C expression. Since there is no way to convert a macro argument (N) into a
7750 * character constant, use two levels of macros.
7752 #define _POW10(exp) ((unsigned int)1e##exp)
7753 #define POW10(exp) _POW10(exp)
7755 struct uclamp_request {
7756 #define UCLAMP_PERCENT_SHIFT 2
7757 #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
7763 static inline struct uclamp_request
7764 capacity_from_percent(char *buf)
7766 struct uclamp_request req = {
7767 .percent = UCLAMP_PERCENT_SCALE,
7768 .util = SCHED_CAPACITY_SCALE,
7773 if (strcmp(buf, "max")) {
7774 req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
7778 if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
7783 req.util = req.percent << SCHED_CAPACITY_SHIFT;
7784 req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
7790 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
7791 size_t nbytes, loff_t off,
7792 enum uclamp_id clamp_id)
7794 struct uclamp_request req;
7795 struct task_group *tg;
7797 req = capacity_from_percent(buf);
7801 static_branch_enable(&sched_uclamp_used);
7803 mutex_lock(&uclamp_mutex);
7806 tg = css_tg(of_css(of));
7807 if (tg->uclamp_req[clamp_id].value != req.util)
7808 uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
7811 * Because of not recoverable conversion rounding we keep track of the
7812 * exact requested value
7814 tg->uclamp_pct[clamp_id] = req.percent;
7816 /* Update effective clamps to track the most restrictive value */
7817 cpu_util_update_eff(of_css(of));
7820 mutex_unlock(&uclamp_mutex);
7825 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
7826 char *buf, size_t nbytes,
7829 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
7832 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
7833 char *buf, size_t nbytes,
7836 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
7839 static inline void cpu_uclamp_print(struct seq_file *sf,
7840 enum uclamp_id clamp_id)
7842 struct task_group *tg;
7848 tg = css_tg(seq_css(sf));
7849 util_clamp = tg->uclamp_req[clamp_id].value;
7852 if (util_clamp == SCHED_CAPACITY_SCALE) {
7853 seq_puts(sf, "max\n");
7857 percent = tg->uclamp_pct[clamp_id];
7858 percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
7859 seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
7862 static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
7864 cpu_uclamp_print(sf, UCLAMP_MIN);
7868 static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
7870 cpu_uclamp_print(sf, UCLAMP_MAX);
7873 #endif /* CONFIG_UCLAMP_TASK_GROUP */
7875 #ifdef CONFIG_FAIR_GROUP_SCHED
7876 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
7877 struct cftype *cftype, u64 shareval)
7879 if (shareval > scale_load_down(ULONG_MAX))
7880 shareval = MAX_SHARES;
7881 return sched_group_set_shares(css_tg(css), scale_load(shareval));
7884 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
7887 struct task_group *tg = css_tg(css);
7889 return (u64) scale_load_down(tg->shares);
7892 #ifdef CONFIG_CFS_BANDWIDTH
7893 static DEFINE_MUTEX(cfs_constraints_mutex);
7895 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
7896 static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
7897 /* More than 203 days if BW_SHIFT equals 20. */
7898 static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
7900 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
7902 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
7904 int i, ret = 0, runtime_enabled, runtime_was_enabled;
7905 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7907 if (tg == &root_task_group)
7911 * Ensure we have at some amount of bandwidth every period. This is
7912 * to prevent reaching a state of large arrears when throttled via
7913 * entity_tick() resulting in prolonged exit starvation.
7915 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
7919 * Likewise, bound things on the otherside by preventing insane quota
7920 * periods. This also allows us to normalize in computing quota
7923 if (period > max_cfs_quota_period)
7927 * Bound quota to defend quota against overflow during bandwidth shift.
7929 if (quota != RUNTIME_INF && quota > max_cfs_runtime)
7933 * Prevent race between setting of cfs_rq->runtime_enabled and
7934 * unthrottle_offline_cfs_rqs().
7937 mutex_lock(&cfs_constraints_mutex);
7938 ret = __cfs_schedulable(tg, period, quota);
7942 runtime_enabled = quota != RUNTIME_INF;
7943 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
7945 * If we need to toggle cfs_bandwidth_used, off->on must occur
7946 * before making related changes, and on->off must occur afterwards
7948 if (runtime_enabled && !runtime_was_enabled)
7949 cfs_bandwidth_usage_inc();
7950 raw_spin_lock_irq(&cfs_b->lock);
7951 cfs_b->period = ns_to_ktime(period);
7952 cfs_b->quota = quota;
7954 __refill_cfs_bandwidth_runtime(cfs_b);
7956 /* Restart the period timer (if active) to handle new period expiry: */
7957 if (runtime_enabled)
7958 start_cfs_bandwidth(cfs_b);
7960 raw_spin_unlock_irq(&cfs_b->lock);
7962 for_each_online_cpu(i) {
7963 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
7964 struct rq *rq = cfs_rq->rq;
7967 rq_lock_irq(rq, &rf);
7968 cfs_rq->runtime_enabled = runtime_enabled;
7969 cfs_rq->runtime_remaining = 0;
7971 if (cfs_rq->throttled)
7972 unthrottle_cfs_rq(cfs_rq);
7973 rq_unlock_irq(rq, &rf);
7975 if (runtime_was_enabled && !runtime_enabled)
7976 cfs_bandwidth_usage_dec();
7978 mutex_unlock(&cfs_constraints_mutex);
7984 static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
7988 period = ktime_to_ns(tg->cfs_bandwidth.period);
7989 if (cfs_quota_us < 0)
7990 quota = RUNTIME_INF;
7991 else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
7992 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
7996 return tg_set_cfs_bandwidth(tg, period, quota);
7999 static long tg_get_cfs_quota(struct task_group *tg)
8003 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8006 quota_us = tg->cfs_bandwidth.quota;
8007 do_div(quota_us, NSEC_PER_USEC);
8012 static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8016 if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
8019 period = (u64)cfs_period_us * NSEC_PER_USEC;
8020 quota = tg->cfs_bandwidth.quota;
8022 return tg_set_cfs_bandwidth(tg, period, quota);
8025 static long tg_get_cfs_period(struct task_group *tg)
8029 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8030 do_div(cfs_period_us, NSEC_PER_USEC);
8032 return cfs_period_us;
8035 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8038 return tg_get_cfs_quota(css_tg(css));
8041 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8042 struct cftype *cftype, s64 cfs_quota_us)
8044 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8047 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8050 return tg_get_cfs_period(css_tg(css));
8053 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8054 struct cftype *cftype, u64 cfs_period_us)
8056 return tg_set_cfs_period(css_tg(css), cfs_period_us);
8059 struct cfs_schedulable_data {
8060 struct task_group *tg;
8065 * normalize group quota/period to be quota/max_period
8066 * note: units are usecs
8068 static u64 normalize_cfs_quota(struct task_group *tg,
8069 struct cfs_schedulable_data *d)
8077 period = tg_get_cfs_period(tg);
8078 quota = tg_get_cfs_quota(tg);
8081 /* note: these should typically be equivalent */
8082 if (quota == RUNTIME_INF || quota == -1)
8085 return to_ratio(period, quota);
8088 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8090 struct cfs_schedulable_data *d = data;
8091 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8092 s64 quota = 0, parent_quota = -1;
8095 quota = RUNTIME_INF;
8097 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8099 quota = normalize_cfs_quota(tg, d);
8100 parent_quota = parent_b->hierarchical_quota;
8103 * Ensure max(child_quota) <= parent_quota. On cgroup2,
8104 * always take the min. On cgroup1, only inherit when no
8107 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
8108 quota = min(quota, parent_quota);
8110 if (quota == RUNTIME_INF)
8111 quota = parent_quota;
8112 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8116 cfs_b->hierarchical_quota = quota;
8121 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8124 struct cfs_schedulable_data data = {
8130 if (quota != RUNTIME_INF) {
8131 do_div(data.period, NSEC_PER_USEC);
8132 do_div(data.quota, NSEC_PER_USEC);
8136 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8142 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
8144 struct task_group *tg = css_tg(seq_css(sf));
8145 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8147 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8148 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8149 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8151 if (schedstat_enabled() && tg != &root_task_group) {
8155 for_each_possible_cpu(i)
8156 ws += schedstat_val(tg->se[i]->statistics.wait_sum);
8158 seq_printf(sf, "wait_sum %llu\n", ws);
8163 #endif /* CONFIG_CFS_BANDWIDTH */
8164 #endif /* CONFIG_FAIR_GROUP_SCHED */
8166 #ifdef CONFIG_RT_GROUP_SCHED
8167 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8168 struct cftype *cft, s64 val)
8170 return sched_group_set_rt_runtime(css_tg(css), val);
8173 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8176 return sched_group_rt_runtime(css_tg(css));
8179 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8180 struct cftype *cftype, u64 rt_period_us)
8182 return sched_group_set_rt_period(css_tg(css), rt_period_us);
8185 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8188 return sched_group_rt_period(css_tg(css));
8190 #endif /* CONFIG_RT_GROUP_SCHED */
8192 static struct cftype cpu_legacy_files[] = {
8193 #ifdef CONFIG_FAIR_GROUP_SCHED
8196 .read_u64 = cpu_shares_read_u64,
8197 .write_u64 = cpu_shares_write_u64,
8200 #ifdef CONFIG_CFS_BANDWIDTH
8202 .name = "cfs_quota_us",
8203 .read_s64 = cpu_cfs_quota_read_s64,
8204 .write_s64 = cpu_cfs_quota_write_s64,
8207 .name = "cfs_period_us",
8208 .read_u64 = cpu_cfs_period_read_u64,
8209 .write_u64 = cpu_cfs_period_write_u64,
8213 .seq_show = cpu_cfs_stat_show,
8216 #ifdef CONFIG_RT_GROUP_SCHED
8218 .name = "rt_runtime_us",
8219 .read_s64 = cpu_rt_runtime_read,
8220 .write_s64 = cpu_rt_runtime_write,
8223 .name = "rt_period_us",
8224 .read_u64 = cpu_rt_period_read_uint,
8225 .write_u64 = cpu_rt_period_write_uint,
8228 #ifdef CONFIG_UCLAMP_TASK_GROUP
8230 .name = "uclamp.min",
8231 .flags = CFTYPE_NOT_ON_ROOT,
8232 .seq_show = cpu_uclamp_min_show,
8233 .write = cpu_uclamp_min_write,
8236 .name = "uclamp.max",
8237 .flags = CFTYPE_NOT_ON_ROOT,
8238 .seq_show = cpu_uclamp_max_show,
8239 .write = cpu_uclamp_max_write,
8245 static int cpu_extra_stat_show(struct seq_file *sf,
8246 struct cgroup_subsys_state *css)
8248 #ifdef CONFIG_CFS_BANDWIDTH
8250 struct task_group *tg = css_tg(css);
8251 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8254 throttled_usec = cfs_b->throttled_time;
8255 do_div(throttled_usec, NSEC_PER_USEC);
8257 seq_printf(sf, "nr_periods %d\n"
8259 "throttled_usec %llu\n",
8260 cfs_b->nr_periods, cfs_b->nr_throttled,
8267 #ifdef CONFIG_FAIR_GROUP_SCHED
8268 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
8271 struct task_group *tg = css_tg(css);
8272 u64 weight = scale_load_down(tg->shares);
8274 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
8277 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
8278 struct cftype *cft, u64 weight)
8281 * cgroup weight knobs should use the common MIN, DFL and MAX
8282 * values which are 1, 100 and 10000 respectively. While it loses
8283 * a bit of range on both ends, it maps pretty well onto the shares
8284 * value used by scheduler and the round-trip conversions preserve
8285 * the original value over the entire range.
8287 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
8290 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
8292 return sched_group_set_shares(css_tg(css), scale_load(weight));
8295 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
8298 unsigned long weight = scale_load_down(css_tg(css)->shares);
8299 int last_delta = INT_MAX;
8302 /* find the closest nice value to the current weight */
8303 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
8304 delta = abs(sched_prio_to_weight[prio] - weight);
8305 if (delta >= last_delta)
8310 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
8313 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
8314 struct cftype *cft, s64 nice)
8316 unsigned long weight;
8319 if (nice < MIN_NICE || nice > MAX_NICE)
8322 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
8323 idx = array_index_nospec(idx, 40);
8324 weight = sched_prio_to_weight[idx];
8326 return sched_group_set_shares(css_tg(css), scale_load(weight));
8330 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
8331 long period, long quota)
8334 seq_puts(sf, "max");
8336 seq_printf(sf, "%ld", quota);
8338 seq_printf(sf, " %ld\n", period);
8341 /* caller should put the current value in *@periodp before calling */
8342 static int __maybe_unused cpu_period_quota_parse(char *buf,
8343 u64 *periodp, u64 *quotap)
8345 char tok[21]; /* U64_MAX */
8347 if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
8350 *periodp *= NSEC_PER_USEC;
8352 if (sscanf(tok, "%llu", quotap))
8353 *quotap *= NSEC_PER_USEC;
8354 else if (!strcmp(tok, "max"))
8355 *quotap = RUNTIME_INF;
8362 #ifdef CONFIG_CFS_BANDWIDTH
8363 static int cpu_max_show(struct seq_file *sf, void *v)
8365 struct task_group *tg = css_tg(seq_css(sf));
8367 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
8371 static ssize_t cpu_max_write(struct kernfs_open_file *of,
8372 char *buf, size_t nbytes, loff_t off)
8374 struct task_group *tg = css_tg(of_css(of));
8375 u64 period = tg_get_cfs_period(tg);
8379 ret = cpu_period_quota_parse(buf, &period, "a);
8381 ret = tg_set_cfs_bandwidth(tg, period, quota);
8382 return ret ?: nbytes;
8386 static struct cftype cpu_files[] = {
8387 #ifdef CONFIG_FAIR_GROUP_SCHED
8390 .flags = CFTYPE_NOT_ON_ROOT,
8391 .read_u64 = cpu_weight_read_u64,
8392 .write_u64 = cpu_weight_write_u64,
8395 .name = "weight.nice",
8396 .flags = CFTYPE_NOT_ON_ROOT,
8397 .read_s64 = cpu_weight_nice_read_s64,
8398 .write_s64 = cpu_weight_nice_write_s64,
8401 #ifdef CONFIG_CFS_BANDWIDTH
8404 .flags = CFTYPE_NOT_ON_ROOT,
8405 .seq_show = cpu_max_show,
8406 .write = cpu_max_write,
8409 #ifdef CONFIG_UCLAMP_TASK_GROUP
8411 .name = "uclamp.min",
8412 .flags = CFTYPE_NOT_ON_ROOT,
8413 .seq_show = cpu_uclamp_min_show,
8414 .write = cpu_uclamp_min_write,
8417 .name = "uclamp.max",
8418 .flags = CFTYPE_NOT_ON_ROOT,
8419 .seq_show = cpu_uclamp_max_show,
8420 .write = cpu_uclamp_max_write,
8426 struct cgroup_subsys cpu_cgrp_subsys = {
8427 .css_alloc = cpu_cgroup_css_alloc,
8428 .css_online = cpu_cgroup_css_online,
8429 .css_released = cpu_cgroup_css_released,
8430 .css_free = cpu_cgroup_css_free,
8431 .css_extra_stat_show = cpu_extra_stat_show,
8432 .fork = cpu_cgroup_fork,
8433 .can_attach = cpu_cgroup_can_attach,
8434 .attach = cpu_cgroup_attach,
8435 .legacy_cftypes = cpu_legacy_files,
8436 .dfl_cftypes = cpu_files,
8441 #endif /* CONFIG_CGROUP_SCHED */
8443 void dump_cpu_task(int cpu)
8445 pr_info("Task dump for CPU %d:\n", cpu);
8446 sched_show_task(cpu_curr(cpu));
8450 * Nice levels are multiplicative, with a gentle 10% change for every
8451 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
8452 * nice 1, it will get ~10% less CPU time than another CPU-bound task
8453 * that remained on nice 0.
8455 * The "10% effect" is relative and cumulative: from _any_ nice level,
8456 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
8457 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
8458 * If a task goes up by ~10% and another task goes down by ~10% then
8459 * the relative distance between them is ~25%.)
8461 const int sched_prio_to_weight[40] = {
8462 /* -20 */ 88761, 71755, 56483, 46273, 36291,
8463 /* -15 */ 29154, 23254, 18705, 14949, 11916,
8464 /* -10 */ 9548, 7620, 6100, 4904, 3906,
8465 /* -5 */ 3121, 2501, 1991, 1586, 1277,
8466 /* 0 */ 1024, 820, 655, 526, 423,
8467 /* 5 */ 335, 272, 215, 172, 137,
8468 /* 10 */ 110, 87, 70, 56, 45,
8469 /* 15 */ 36, 29, 23, 18, 15,
8473 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
8475 * In cases where the weight does not change often, we can use the
8476 * precalculated inverse to speed up arithmetics by turning divisions
8477 * into multiplications:
8479 const u32 sched_prio_to_wmult[40] = {
8480 /* -20 */ 48388, 59856, 76040, 92818, 118348,
8481 /* -15 */ 147320, 184698, 229616, 287308, 360437,
8482 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
8483 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
8484 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
8485 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
8486 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
8487 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
8490 void call_trace_sched_update_nr_running(struct rq *rq, int count)
8492 trace_sched_update_nr_running_tp(rq, count);