4 * Core kernel scheduler code and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
10 #include <linux/nospec.h>
12 #include <linux/kcov.h>
14 #include <asm/switch_to.h>
17 #include "../workqueue_internal.h"
18 #include "../smpboot.h"
22 #define CREATE_TRACE_POINTS
23 #include <trace/events/sched.h>
25 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
27 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_JUMP_LABEL)
29 * Debugging: various feature bits
31 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
32 * sysctl_sched_features, defined in sched.h, to allow constants propagation
33 * at compile time and compiler optimization based on features default.
35 #define SCHED_FEAT(name, enabled) \
36 (1UL << __SCHED_FEAT_##name) * enabled |
37 const_debug unsigned int sysctl_sched_features =
44 * Number of tasks to iterate in a single balance run.
45 * Limited because this is done with IRQs disabled.
47 const_debug unsigned int sysctl_sched_nr_migrate = 32;
50 * period over which we measure -rt task CPU usage in us.
53 unsigned int sysctl_sched_rt_period = 1000000;
55 __read_mostly int scheduler_running;
58 * part of the period that we allow rt tasks to run in us.
61 int sysctl_sched_rt_runtime = 950000;
64 * __task_rq_lock - lock the rq @p resides on.
66 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
71 lockdep_assert_held(&p->pi_lock);
75 raw_spin_lock(&rq->lock);
76 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
80 raw_spin_unlock(&rq->lock);
82 while (unlikely(task_on_rq_migrating(p)))
88 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
90 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
91 __acquires(p->pi_lock)
97 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
99 raw_spin_lock(&rq->lock);
101 * move_queued_task() task_rq_lock()
104 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
105 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
106 * [S] ->cpu = new_cpu [L] task_rq()
110 * If we observe the old CPU in task_rq_lock(), the acquire of
111 * the old rq->lock will fully serialize against the stores.
113 * If we observe the new CPU in task_rq_lock(), the address
114 * dependency headed by '[L] rq = task_rq()' and the acquire
115 * will pair with the WMB to ensure we then also see migrating.
117 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
121 raw_spin_unlock(&rq->lock);
122 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
124 while (unlikely(task_on_rq_migrating(p)))
130 * RQ-clock updating methods:
133 static void update_rq_clock_task(struct rq *rq, s64 delta)
136 * In theory, the compile should just see 0 here, and optimize out the call
137 * to sched_rt_avg_update. But I don't trust it...
139 s64 __maybe_unused steal = 0, irq_delta = 0;
141 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
142 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
145 * Since irq_time is only updated on {soft,}irq_exit, we might run into
146 * this case when a previous update_rq_clock() happened inside a
149 * When this happens, we stop ->clock_task and only update the
150 * prev_irq_time stamp to account for the part that fit, so that a next
151 * update will consume the rest. This ensures ->clock_task is
154 * It does however cause some slight miss-attribution of {soft,}irq
155 * time, a more accurate solution would be to update the irq_time using
156 * the current rq->clock timestamp, except that would require using
159 if (irq_delta > delta)
162 rq->prev_irq_time += irq_delta;
165 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
166 if (static_key_false((¶virt_steal_rq_enabled))) {
167 steal = paravirt_steal_clock(cpu_of(rq));
168 steal -= rq->prev_steal_time_rq;
170 if (unlikely(steal > delta))
173 rq->prev_steal_time_rq += steal;
178 rq->clock_task += delta;
180 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
181 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
182 update_irq_load_avg(rq, irq_delta + steal);
184 update_rq_clock_pelt(rq, delta);
187 void update_rq_clock(struct rq *rq)
191 lockdep_assert_held(&rq->lock);
193 if (rq->clock_update_flags & RQCF_ACT_SKIP)
196 #ifdef CONFIG_SCHED_DEBUG
197 if (sched_feat(WARN_DOUBLE_CLOCK))
198 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
199 rq->clock_update_flags |= RQCF_UPDATED;
202 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
206 update_rq_clock_task(rq, delta);
210 #ifdef CONFIG_SCHED_HRTICK
212 * Use HR-timers to deliver accurate preemption points.
215 static void hrtick_clear(struct rq *rq)
217 if (hrtimer_active(&rq->hrtick_timer))
218 hrtimer_cancel(&rq->hrtick_timer);
222 * High-resolution timer tick.
223 * Runs from hardirq context with interrupts disabled.
225 static enum hrtimer_restart hrtick(struct hrtimer *timer)
227 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
230 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
234 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
237 return HRTIMER_NORESTART;
242 static void __hrtick_restart(struct rq *rq)
244 struct hrtimer *timer = &rq->hrtick_timer;
246 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
250 * called from hardirq (IPI) context
252 static void __hrtick_start(void *arg)
258 __hrtick_restart(rq);
259 rq->hrtick_csd_pending = 0;
264 * Called to set the hrtick timer state.
266 * called with rq->lock held and irqs disabled
268 void hrtick_start(struct rq *rq, u64 delay)
270 struct hrtimer *timer = &rq->hrtick_timer;
275 * Don't schedule slices shorter than 10000ns, that just
276 * doesn't make sense and can cause timer DoS.
278 delta = max_t(s64, delay, 10000LL);
279 time = ktime_add_ns(timer->base->get_time(), delta);
281 hrtimer_set_expires(timer, time);
283 if (rq == this_rq()) {
284 __hrtick_restart(rq);
285 } else if (!rq->hrtick_csd_pending) {
286 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
287 rq->hrtick_csd_pending = 1;
293 * Called to set the hrtick timer state.
295 * called with rq->lock held and irqs disabled
297 void hrtick_start(struct rq *rq, u64 delay)
300 * Don't schedule slices shorter than 10000ns, that just
301 * doesn't make sense. Rely on vruntime for fairness.
303 delay = max_t(u64, delay, 10000LL);
304 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
305 HRTIMER_MODE_REL_PINNED);
307 #endif /* CONFIG_SMP */
309 static void hrtick_rq_init(struct rq *rq)
312 rq->hrtick_csd_pending = 0;
314 rq->hrtick_csd.flags = 0;
315 rq->hrtick_csd.func = __hrtick_start;
316 rq->hrtick_csd.info = rq;
319 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
320 rq->hrtick_timer.function = hrtick;
322 #else /* CONFIG_SCHED_HRTICK */
323 static inline void hrtick_clear(struct rq *rq)
327 static inline void hrtick_rq_init(struct rq *rq)
330 #endif /* CONFIG_SCHED_HRTICK */
333 * cmpxchg based fetch_or, macro so it works for different integer types
335 #define fetch_or(ptr, mask) \
337 typeof(ptr) _ptr = (ptr); \
338 typeof(mask) _mask = (mask); \
339 typeof(*_ptr) _old, _val = *_ptr; \
342 _old = cmpxchg(_ptr, _val, _val | _mask); \
350 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
352 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
353 * this avoids any races wrt polling state changes and thereby avoids
356 static bool set_nr_and_not_polling(struct task_struct *p)
358 struct thread_info *ti = task_thread_info(p);
359 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
363 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
365 * If this returns true, then the idle task promises to call
366 * sched_ttwu_pending() and reschedule soon.
368 static bool set_nr_if_polling(struct task_struct *p)
370 struct thread_info *ti = task_thread_info(p);
371 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
374 if (!(val & _TIF_POLLING_NRFLAG))
376 if (val & _TIF_NEED_RESCHED)
378 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
387 static bool set_nr_and_not_polling(struct task_struct *p)
389 set_tsk_need_resched(p);
394 static bool set_nr_if_polling(struct task_struct *p)
402 * wake_q_add() - queue a wakeup for 'later' waking.
403 * @head: the wake_q_head to add @task to
404 * @task: the task to queue for 'later' wakeup
406 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
407 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
410 * This function must be used as-if it were wake_up_process(); IOW the task
411 * must be ready to be woken at this location.
413 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
415 struct wake_q_node *node = &task->wake_q;
418 * Atomically grab the task, if ->wake_q is !nil already it means
419 * its already queued (either by us or someone else) and will get the
420 * wakeup due to that.
422 * In order to ensure that a pending wakeup will observe our pending
423 * state, even in the failed case, an explicit smp_mb() must be used.
425 smp_mb__before_atomic();
426 if (cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL))
429 get_task_struct(task);
432 * The head is context local, there can be no concurrency.
435 head->lastp = &node->next;
438 void wake_up_q(struct wake_q_head *head)
440 struct wake_q_node *node = head->first;
442 while (node != WAKE_Q_TAIL) {
443 struct task_struct *task;
445 task = container_of(node, struct task_struct, wake_q);
447 /* Task can safely be re-inserted now: */
449 task->wake_q.next = NULL;
452 * wake_up_process() executes a full barrier, which pairs with
453 * the queueing in wake_q_add() so as not to miss wakeups.
455 wake_up_process(task);
456 put_task_struct(task);
461 * resched_curr - mark rq's current task 'to be rescheduled now'.
463 * On UP this means the setting of the need_resched flag, on SMP it
464 * might also involve a cross-CPU call to trigger the scheduler on
467 void resched_curr(struct rq *rq)
469 struct task_struct *curr = rq->curr;
472 lockdep_assert_held(&rq->lock);
474 if (test_tsk_need_resched(curr))
479 if (cpu == smp_processor_id()) {
480 set_tsk_need_resched(curr);
481 set_preempt_need_resched();
485 if (set_nr_and_not_polling(curr))
486 smp_send_reschedule(cpu);
488 trace_sched_wake_idle_without_ipi(cpu);
491 void resched_cpu(int cpu)
493 struct rq *rq = cpu_rq(cpu);
496 raw_spin_lock_irqsave(&rq->lock, flags);
497 if (cpu_online(cpu) || cpu == smp_processor_id())
499 raw_spin_unlock_irqrestore(&rq->lock, flags);
503 #ifdef CONFIG_NO_HZ_COMMON
505 * In the semi idle case, use the nearest busy CPU for migrating timers
506 * from an idle CPU. This is good for power-savings.
508 * We don't do similar optimization for completely idle system, as
509 * selecting an idle CPU will add more delays to the timers than intended
510 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
512 int get_nohz_timer_target(void)
514 int i, cpu = smp_processor_id();
515 struct sched_domain *sd;
517 if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
521 for_each_domain(cpu, sd) {
522 for_each_cpu(i, sched_domain_span(sd)) {
526 if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
533 if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
534 cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
541 * When add_timer_on() enqueues a timer into the timer wheel of an
542 * idle CPU then this timer might expire before the next timer event
543 * which is scheduled to wake up that CPU. In case of a completely
544 * idle system the next event might even be infinite time into the
545 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
546 * leaves the inner idle loop so the newly added timer is taken into
547 * account when the CPU goes back to idle and evaluates the timer
548 * wheel for the next timer event.
550 static void wake_up_idle_cpu(int cpu)
552 struct rq *rq = cpu_rq(cpu);
554 if (cpu == smp_processor_id())
557 if (set_nr_and_not_polling(rq->idle))
558 smp_send_reschedule(cpu);
560 trace_sched_wake_idle_without_ipi(cpu);
563 static bool wake_up_full_nohz_cpu(int cpu)
566 * We just need the target to call irq_exit() and re-evaluate
567 * the next tick. The nohz full kick at least implies that.
568 * If needed we can still optimize that later with an
571 if (cpu_is_offline(cpu))
572 return true; /* Don't try to wake offline CPUs. */
573 if (tick_nohz_full_cpu(cpu)) {
574 if (cpu != smp_processor_id() ||
575 tick_nohz_tick_stopped())
576 tick_nohz_full_kick_cpu(cpu);
584 * Wake up the specified CPU. If the CPU is going offline, it is the
585 * caller's responsibility to deal with the lost wakeup, for example,
586 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
588 void wake_up_nohz_cpu(int cpu)
590 if (!wake_up_full_nohz_cpu(cpu))
591 wake_up_idle_cpu(cpu);
594 static inline bool got_nohz_idle_kick(void)
596 int cpu = smp_processor_id();
598 if (!(atomic_read(nohz_flags(cpu)) & NOHZ_KICK_MASK))
601 if (idle_cpu(cpu) && !need_resched())
605 * We can't run Idle Load Balance on this CPU for this time so we
606 * cancel it and clear NOHZ_BALANCE_KICK
608 atomic_andnot(NOHZ_KICK_MASK, nohz_flags(cpu));
612 #else /* CONFIG_NO_HZ_COMMON */
614 static inline bool got_nohz_idle_kick(void)
619 #endif /* CONFIG_NO_HZ_COMMON */
621 #ifdef CONFIG_NO_HZ_FULL
622 bool sched_can_stop_tick(struct rq *rq)
626 /* Deadline tasks, even if single, need the tick */
627 if (rq->dl.dl_nr_running)
631 * If there are more than one RR tasks, we need the tick to effect the
632 * actual RR behaviour.
634 if (rq->rt.rr_nr_running) {
635 if (rq->rt.rr_nr_running == 1)
642 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
643 * forced preemption between FIFO tasks.
645 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
650 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
651 * if there's more than one we need the tick for involuntary
654 if (rq->nr_running > 1)
659 #endif /* CONFIG_NO_HZ_FULL */
660 #endif /* CONFIG_SMP */
662 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
663 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
665 * Iterate task_group tree rooted at *from, calling @down when first entering a
666 * node and @up when leaving it for the final time.
668 * Caller must hold rcu_lock or sufficient equivalent.
670 int walk_tg_tree_from(struct task_group *from,
671 tg_visitor down, tg_visitor up, void *data)
673 struct task_group *parent, *child;
679 ret = (*down)(parent, data);
682 list_for_each_entry_rcu(child, &parent->children, siblings) {
689 ret = (*up)(parent, data);
690 if (ret || parent == from)
694 parent = parent->parent;
701 int tg_nop(struct task_group *tg, void *data)
707 static void set_load_weight(struct task_struct *p, bool update_load)
709 int prio = p->static_prio - MAX_RT_PRIO;
710 struct load_weight *load = &p->se.load;
713 * SCHED_IDLE tasks get minimal weight:
715 if (task_has_idle_policy(p)) {
716 load->weight = scale_load(WEIGHT_IDLEPRIO);
717 load->inv_weight = WMULT_IDLEPRIO;
718 p->se.runnable_weight = load->weight;
723 * SCHED_OTHER tasks have to update their load when changing their
726 if (update_load && p->sched_class == &fair_sched_class) {
727 reweight_task(p, prio);
729 load->weight = scale_load(sched_prio_to_weight[prio]);
730 load->inv_weight = sched_prio_to_wmult[prio];
731 p->se.runnable_weight = load->weight;
735 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
737 if (!(flags & ENQUEUE_NOCLOCK))
740 if (!(flags & ENQUEUE_RESTORE)) {
741 sched_info_queued(rq, p);
742 psi_enqueue(p, flags & ENQUEUE_WAKEUP);
745 p->sched_class->enqueue_task(rq, p, flags);
748 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
750 if (!(flags & DEQUEUE_NOCLOCK))
753 if (!(flags & DEQUEUE_SAVE)) {
754 sched_info_dequeued(rq, p);
755 psi_dequeue(p, flags & DEQUEUE_SLEEP);
758 p->sched_class->dequeue_task(rq, p, flags);
761 void activate_task(struct rq *rq, struct task_struct *p, int flags)
763 if (task_contributes_to_load(p))
764 rq->nr_uninterruptible--;
766 enqueue_task(rq, p, flags);
769 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
771 if (task_contributes_to_load(p))
772 rq->nr_uninterruptible++;
774 dequeue_task(rq, p, flags);
778 * __normal_prio - return the priority that is based on the static prio
780 static inline int __normal_prio(struct task_struct *p)
782 return p->static_prio;
786 * Calculate the expected normal priority: i.e. priority
787 * without taking RT-inheritance into account. Might be
788 * boosted by interactivity modifiers. Changes upon fork,
789 * setprio syscalls, and whenever the interactivity
790 * estimator recalculates.
792 static inline int normal_prio(struct task_struct *p)
796 if (task_has_dl_policy(p))
797 prio = MAX_DL_PRIO-1;
798 else if (task_has_rt_policy(p))
799 prio = MAX_RT_PRIO-1 - p->rt_priority;
801 prio = __normal_prio(p);
806 * Calculate the current priority, i.e. the priority
807 * taken into account by the scheduler. This value might
808 * be boosted by RT tasks, or might be boosted by
809 * interactivity modifiers. Will be RT if the task got
810 * RT-boosted. If not then it returns p->normal_prio.
812 static int effective_prio(struct task_struct *p)
814 p->normal_prio = normal_prio(p);
816 * If we are RT tasks or we were boosted to RT priority,
817 * keep the priority unchanged. Otherwise, update priority
818 * to the normal priority:
820 if (!rt_prio(p->prio))
821 return p->normal_prio;
826 * task_curr - is this task currently executing on a CPU?
827 * @p: the task in question.
829 * Return: 1 if the task is currently executing. 0 otherwise.
831 inline int task_curr(const struct task_struct *p)
833 return cpu_curr(task_cpu(p)) == p;
837 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
838 * use the balance_callback list if you want balancing.
840 * this means any call to check_class_changed() must be followed by a call to
841 * balance_callback().
843 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
844 const struct sched_class *prev_class,
847 if (prev_class != p->sched_class) {
848 if (prev_class->switched_from)
849 prev_class->switched_from(rq, p);
851 p->sched_class->switched_to(rq, p);
852 } else if (oldprio != p->prio || dl_task(p))
853 p->sched_class->prio_changed(rq, p, oldprio);
856 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
858 const struct sched_class *class;
860 if (p->sched_class == rq->curr->sched_class) {
861 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
863 for_each_class(class) {
864 if (class == rq->curr->sched_class)
866 if (class == p->sched_class) {
874 * A queue event has occurred, and we're going to schedule. In
875 * this case, we can save a useless back to back clock update.
877 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
878 rq_clock_skip_update(rq);
883 static inline bool is_per_cpu_kthread(struct task_struct *p)
885 if (!(p->flags & PF_KTHREAD))
888 if (p->nr_cpus_allowed != 1)
895 * Per-CPU kthreads are allowed to run on !actie && online CPUs, see
896 * __set_cpus_allowed_ptr() and select_fallback_rq().
898 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
900 if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
903 if (is_per_cpu_kthread(p))
904 return cpu_online(cpu);
906 return cpu_active(cpu);
910 * This is how migration works:
912 * 1) we invoke migration_cpu_stop() on the target CPU using
914 * 2) stopper starts to run (implicitly forcing the migrated thread
916 * 3) it checks whether the migrated task is still in the wrong runqueue.
917 * 4) if it's in the wrong runqueue then the migration thread removes
918 * it and puts it into the right queue.
919 * 5) stopper completes and stop_one_cpu() returns and the migration
924 * move_queued_task - move a queued task to new rq.
926 * Returns (locked) new rq. Old rq's lock is released.
928 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
929 struct task_struct *p, int new_cpu)
931 lockdep_assert_held(&rq->lock);
933 WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING);
934 dequeue_task(rq, p, DEQUEUE_NOCLOCK);
935 set_task_cpu(p, new_cpu);
938 rq = cpu_rq(new_cpu);
941 BUG_ON(task_cpu(p) != new_cpu);
942 enqueue_task(rq, p, 0);
943 p->on_rq = TASK_ON_RQ_QUEUED;
944 check_preempt_curr(rq, p, 0);
949 struct migration_arg {
950 struct task_struct *task;
955 * Move (not current) task off this CPU, onto the destination CPU. We're doing
956 * this because either it can't run here any more (set_cpus_allowed()
957 * away from this CPU, or CPU going down), or because we're
958 * attempting to rebalance this task on exec (sched_exec).
960 * So we race with normal scheduler movements, but that's OK, as long
961 * as the task is no longer on this CPU.
963 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
964 struct task_struct *p, int dest_cpu)
966 /* Affinity changed (again). */
967 if (!is_cpu_allowed(p, dest_cpu))
971 rq = move_queued_task(rq, rf, p, dest_cpu);
977 * migration_cpu_stop - this will be executed by a highprio stopper thread
978 * and performs thread migration by bumping thread off CPU then
979 * 'pushing' onto another runqueue.
981 static int migration_cpu_stop(void *data)
983 struct migration_arg *arg = data;
984 struct task_struct *p = arg->task;
985 struct rq *rq = this_rq();
989 * The original target CPU might have gone down and we might
990 * be on another CPU but it doesn't matter.
994 * We need to explicitly wake pending tasks before running
995 * __migrate_task() such that we will not miss enforcing cpus_allowed
996 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
998 sched_ttwu_pending();
1000 raw_spin_lock(&p->pi_lock);
1003 * If task_rq(p) != rq, it cannot be migrated here, because we're
1004 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1005 * we're holding p->pi_lock.
1007 if (task_rq(p) == rq) {
1008 if (task_on_rq_queued(p))
1009 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
1011 p->wake_cpu = arg->dest_cpu;
1014 raw_spin_unlock(&p->pi_lock);
1021 * sched_class::set_cpus_allowed must do the below, but is not required to
1022 * actually call this function.
1024 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1026 cpumask_copy(&p->cpus_allowed, new_mask);
1027 p->nr_cpus_allowed = cpumask_weight(new_mask);
1030 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1032 struct rq *rq = task_rq(p);
1033 bool queued, running;
1035 lockdep_assert_held(&p->pi_lock);
1037 queued = task_on_rq_queued(p);
1038 running = task_current(rq, p);
1042 * Because __kthread_bind() calls this on blocked tasks without
1045 lockdep_assert_held(&rq->lock);
1046 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
1049 put_prev_task(rq, p);
1051 p->sched_class->set_cpus_allowed(p, new_mask);
1054 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1056 set_curr_task(rq, p);
1060 * Change a given task's CPU affinity. Migrate the thread to a
1061 * proper CPU and schedule it away if the CPU it's executing on
1062 * is removed from the allowed bitmask.
1064 * NOTE: the caller must have a valid reference to the task, the
1065 * task must not exit() & deallocate itself prematurely. The
1066 * call is not atomic; no spinlocks may be held.
1068 static int __set_cpus_allowed_ptr(struct task_struct *p,
1069 const struct cpumask *new_mask, bool check)
1071 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1072 unsigned int dest_cpu;
1077 rq = task_rq_lock(p, &rf);
1078 update_rq_clock(rq);
1080 if (p->flags & PF_KTHREAD) {
1082 * Kernel threads are allowed on online && !active CPUs
1084 cpu_valid_mask = cpu_online_mask;
1088 * Must re-check here, to close a race against __kthread_bind(),
1089 * sched_setaffinity() is not guaranteed to observe the flag.
1091 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1096 if (cpumask_equal(&p->cpus_allowed, new_mask))
1099 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1104 do_set_cpus_allowed(p, new_mask);
1106 if (p->flags & PF_KTHREAD) {
1108 * For kernel threads that do indeed end up on online &&
1109 * !active we want to ensure they are strict per-CPU threads.
1111 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1112 !cpumask_intersects(new_mask, cpu_active_mask) &&
1113 p->nr_cpus_allowed != 1);
1116 /* Can the task run on the task's current CPU? If so, we're done */
1117 if (cpumask_test_cpu(task_cpu(p), new_mask))
1120 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1121 if (task_running(rq, p) || p->state == TASK_WAKING) {
1122 struct migration_arg arg = { p, dest_cpu };
1123 /* Need help from migration thread: drop lock and wait. */
1124 task_rq_unlock(rq, p, &rf);
1125 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1126 tlb_migrate_finish(p->mm);
1128 } else if (task_on_rq_queued(p)) {
1130 * OK, since we're going to drop the lock immediately
1131 * afterwards anyway.
1133 rq = move_queued_task(rq, &rf, p, dest_cpu);
1136 task_rq_unlock(rq, p, &rf);
1141 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1143 return __set_cpus_allowed_ptr(p, new_mask, false);
1145 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1147 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1149 #ifdef CONFIG_SCHED_DEBUG
1151 * We should never call set_task_cpu() on a blocked task,
1152 * ttwu() will sort out the placement.
1154 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1158 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1159 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1160 * time relying on p->on_rq.
1162 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1163 p->sched_class == &fair_sched_class &&
1164 (p->on_rq && !task_on_rq_migrating(p)));
1166 #ifdef CONFIG_LOCKDEP
1168 * The caller should hold either p->pi_lock or rq->lock, when changing
1169 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1171 * sched_move_task() holds both and thus holding either pins the cgroup,
1174 * Furthermore, all task_rq users should acquire both locks, see
1177 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1178 lockdep_is_held(&task_rq(p)->lock)));
1181 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1183 WARN_ON_ONCE(!cpu_online(new_cpu));
1186 trace_sched_migrate_task(p, new_cpu);
1188 if (task_cpu(p) != new_cpu) {
1189 if (p->sched_class->migrate_task_rq)
1190 p->sched_class->migrate_task_rq(p, new_cpu);
1191 p->se.nr_migrations++;
1193 perf_event_task_migrate(p);
1196 __set_task_cpu(p, new_cpu);
1199 #ifdef CONFIG_NUMA_BALANCING
1200 static void __migrate_swap_task(struct task_struct *p, int cpu)
1202 if (task_on_rq_queued(p)) {
1203 struct rq *src_rq, *dst_rq;
1204 struct rq_flags srf, drf;
1206 src_rq = task_rq(p);
1207 dst_rq = cpu_rq(cpu);
1209 rq_pin_lock(src_rq, &srf);
1210 rq_pin_lock(dst_rq, &drf);
1212 p->on_rq = TASK_ON_RQ_MIGRATING;
1213 deactivate_task(src_rq, p, 0);
1214 set_task_cpu(p, cpu);
1215 activate_task(dst_rq, p, 0);
1216 p->on_rq = TASK_ON_RQ_QUEUED;
1217 check_preempt_curr(dst_rq, p, 0);
1219 rq_unpin_lock(dst_rq, &drf);
1220 rq_unpin_lock(src_rq, &srf);
1224 * Task isn't running anymore; make it appear like we migrated
1225 * it before it went to sleep. This means on wakeup we make the
1226 * previous CPU our target instead of where it really is.
1232 struct migration_swap_arg {
1233 struct task_struct *src_task, *dst_task;
1234 int src_cpu, dst_cpu;
1237 static int migrate_swap_stop(void *data)
1239 struct migration_swap_arg *arg = data;
1240 struct rq *src_rq, *dst_rq;
1243 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1246 src_rq = cpu_rq(arg->src_cpu);
1247 dst_rq = cpu_rq(arg->dst_cpu);
1249 double_raw_lock(&arg->src_task->pi_lock,
1250 &arg->dst_task->pi_lock);
1251 double_rq_lock(src_rq, dst_rq);
1253 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1256 if (task_cpu(arg->src_task) != arg->src_cpu)
1259 if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
1262 if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
1265 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1266 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1271 double_rq_unlock(src_rq, dst_rq);
1272 raw_spin_unlock(&arg->dst_task->pi_lock);
1273 raw_spin_unlock(&arg->src_task->pi_lock);
1279 * Cross migrate two tasks
1281 int migrate_swap(struct task_struct *cur, struct task_struct *p,
1282 int target_cpu, int curr_cpu)
1284 struct migration_swap_arg arg;
1287 arg = (struct migration_swap_arg){
1289 .src_cpu = curr_cpu,
1291 .dst_cpu = target_cpu,
1294 if (arg.src_cpu == arg.dst_cpu)
1298 * These three tests are all lockless; this is OK since all of them
1299 * will be re-checked with proper locks held further down the line.
1301 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1304 if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
1307 if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
1310 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1311 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1316 #endif /* CONFIG_NUMA_BALANCING */
1319 * wait_task_inactive - wait for a thread to unschedule.
1321 * If @match_state is nonzero, it's the @p->state value just checked and
1322 * not expected to change. If it changes, i.e. @p might have woken up,
1323 * then return zero. When we succeed in waiting for @p to be off its CPU,
1324 * we return a positive number (its total switch count). If a second call
1325 * a short while later returns the same number, the caller can be sure that
1326 * @p has remained unscheduled the whole time.
1328 * The caller must ensure that the task *will* unschedule sometime soon,
1329 * else this function might spin for a *long* time. This function can't
1330 * be called with interrupts off, or it may introduce deadlock with
1331 * smp_call_function() if an IPI is sent by the same process we are
1332 * waiting to become inactive.
1334 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1336 int running, queued;
1343 * We do the initial early heuristics without holding
1344 * any task-queue locks at all. We'll only try to get
1345 * the runqueue lock when things look like they will
1351 * If the task is actively running on another CPU
1352 * still, just relax and busy-wait without holding
1355 * NOTE! Since we don't hold any locks, it's not
1356 * even sure that "rq" stays as the right runqueue!
1357 * But we don't care, since "task_running()" will
1358 * return false if the runqueue has changed and p
1359 * is actually now running somewhere else!
1361 while (task_running(rq, p)) {
1362 if (match_state && unlikely(p->state != match_state))
1368 * Ok, time to look more closely! We need the rq
1369 * lock now, to be *sure*. If we're wrong, we'll
1370 * just go back and repeat.
1372 rq = task_rq_lock(p, &rf);
1373 trace_sched_wait_task(p);
1374 running = task_running(rq, p);
1375 queued = task_on_rq_queued(p);
1377 if (!match_state || p->state == match_state)
1378 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1379 task_rq_unlock(rq, p, &rf);
1382 * If it changed from the expected state, bail out now.
1384 if (unlikely(!ncsw))
1388 * Was it really running after all now that we
1389 * checked with the proper locks actually held?
1391 * Oops. Go back and try again..
1393 if (unlikely(running)) {
1399 * It's not enough that it's not actively running,
1400 * it must be off the runqueue _entirely_, and not
1403 * So if it was still runnable (but just not actively
1404 * running right now), it's preempted, and we should
1405 * yield - it could be a while.
1407 if (unlikely(queued)) {
1408 ktime_t to = NSEC_PER_SEC / HZ;
1410 set_current_state(TASK_UNINTERRUPTIBLE);
1411 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1416 * Ahh, all good. It wasn't running, and it wasn't
1417 * runnable, which means that it will never become
1418 * running in the future either. We're all done!
1427 * kick_process - kick a running thread to enter/exit the kernel
1428 * @p: the to-be-kicked thread
1430 * Cause a process which is running on another CPU to enter
1431 * kernel-mode, without any delay. (to get signals handled.)
1433 * NOTE: this function doesn't have to take the runqueue lock,
1434 * because all it wants to ensure is that the remote task enters
1435 * the kernel. If the IPI races and the task has been migrated
1436 * to another CPU then no harm is done and the purpose has been
1439 void kick_process(struct task_struct *p)
1445 if ((cpu != smp_processor_id()) && task_curr(p))
1446 smp_send_reschedule(cpu);
1449 EXPORT_SYMBOL_GPL(kick_process);
1452 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1454 * A few notes on cpu_active vs cpu_online:
1456 * - cpu_active must be a subset of cpu_online
1458 * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
1459 * see __set_cpus_allowed_ptr(). At this point the newly online
1460 * CPU isn't yet part of the sched domains, and balancing will not
1463 * - on CPU-down we clear cpu_active() to mask the sched domains and
1464 * avoid the load balancer to place new tasks on the to be removed
1465 * CPU. Existing tasks will remain running there and will be taken
1468 * This means that fallback selection must not select !active CPUs.
1469 * And can assume that any active CPU must be online. Conversely
1470 * select_task_rq() below may allow selection of !active CPUs in order
1471 * to satisfy the above rules.
1473 static int select_fallback_rq(int cpu, struct task_struct *p)
1475 int nid = cpu_to_node(cpu);
1476 const struct cpumask *nodemask = NULL;
1477 enum { cpuset, possible, fail } state = cpuset;
1481 * If the node that the CPU is on has been offlined, cpu_to_node()
1482 * will return -1. There is no CPU on the node, and we should
1483 * select the CPU on the other node.
1486 nodemask = cpumask_of_node(nid);
1488 /* Look for allowed, online CPU in same node. */
1489 for_each_cpu(dest_cpu, nodemask) {
1490 if (!cpu_active(dest_cpu))
1492 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
1498 /* Any allowed, online CPU? */
1499 for_each_cpu(dest_cpu, &p->cpus_allowed) {
1500 if (!is_cpu_allowed(p, dest_cpu))
1506 /* No more Mr. Nice Guy. */
1509 if (IS_ENABLED(CONFIG_CPUSETS)) {
1510 cpuset_cpus_allowed_fallback(p);
1516 do_set_cpus_allowed(p, cpu_possible_mask);
1527 if (state != cpuset) {
1529 * Don't tell them about moving exiting tasks or
1530 * kernel threads (both mm NULL), since they never
1533 if (p->mm && printk_ratelimit()) {
1534 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1535 task_pid_nr(p), p->comm, cpu);
1543 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1546 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1548 lockdep_assert_held(&p->pi_lock);
1550 if (p->nr_cpus_allowed > 1)
1551 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1553 cpu = cpumask_any(&p->cpus_allowed);
1556 * In order not to call set_task_cpu() on a blocking task we need
1557 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1560 * Since this is common to all placement strategies, this lives here.
1562 * [ this allows ->select_task() to simply return task_cpu(p) and
1563 * not worry about this generic constraint ]
1565 if (unlikely(!is_cpu_allowed(p, cpu)))
1566 cpu = select_fallback_rq(task_cpu(p), p);
1571 static void update_avg(u64 *avg, u64 sample)
1573 s64 diff = sample - *avg;
1577 void sched_set_stop_task(int cpu, struct task_struct *stop)
1579 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1580 struct task_struct *old_stop = cpu_rq(cpu)->stop;
1584 * Make it appear like a SCHED_FIFO task, its something
1585 * userspace knows about and won't get confused about.
1587 * Also, it will make PI more or less work without too
1588 * much confusion -- but then, stop work should not
1589 * rely on PI working anyway.
1591 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
1593 stop->sched_class = &stop_sched_class;
1596 cpu_rq(cpu)->stop = stop;
1600 * Reset it back to a normal scheduling class so that
1601 * it can die in pieces.
1603 old_stop->sched_class = &rt_sched_class;
1609 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1610 const struct cpumask *new_mask, bool check)
1612 return set_cpus_allowed_ptr(p, new_mask);
1615 #endif /* CONFIG_SMP */
1618 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1622 if (!schedstat_enabled())
1628 if (cpu == rq->cpu) {
1629 __schedstat_inc(rq->ttwu_local);
1630 __schedstat_inc(p->se.statistics.nr_wakeups_local);
1632 struct sched_domain *sd;
1634 __schedstat_inc(p->se.statistics.nr_wakeups_remote);
1636 for_each_domain(rq->cpu, sd) {
1637 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1638 __schedstat_inc(sd->ttwu_wake_remote);
1645 if (wake_flags & WF_MIGRATED)
1646 __schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1647 #endif /* CONFIG_SMP */
1649 __schedstat_inc(rq->ttwu_count);
1650 __schedstat_inc(p->se.statistics.nr_wakeups);
1652 if (wake_flags & WF_SYNC)
1653 __schedstat_inc(p->se.statistics.nr_wakeups_sync);
1656 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1658 activate_task(rq, p, en_flags);
1659 p->on_rq = TASK_ON_RQ_QUEUED;
1661 /* If a worker is waking up, notify the workqueue: */
1662 if (p->flags & PF_WQ_WORKER)
1663 wq_worker_waking_up(p, cpu_of(rq));
1667 * Mark the task runnable and perform wakeup-preemption.
1669 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1670 struct rq_flags *rf)
1672 check_preempt_curr(rq, p, wake_flags);
1673 p->state = TASK_RUNNING;
1674 trace_sched_wakeup(p);
1677 if (p->sched_class->task_woken) {
1679 * Our task @p is fully woken up and running; so its safe to
1680 * drop the rq->lock, hereafter rq is only used for statistics.
1682 rq_unpin_lock(rq, rf);
1683 p->sched_class->task_woken(rq, p);
1684 rq_repin_lock(rq, rf);
1687 if (rq->idle_stamp) {
1688 u64 delta = rq_clock(rq) - rq->idle_stamp;
1689 u64 max = 2*rq->max_idle_balance_cost;
1691 update_avg(&rq->avg_idle, delta);
1693 if (rq->avg_idle > max)
1702 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1703 struct rq_flags *rf)
1705 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
1707 lockdep_assert_held(&rq->lock);
1710 if (p->sched_contributes_to_load)
1711 rq->nr_uninterruptible--;
1713 if (wake_flags & WF_MIGRATED)
1714 en_flags |= ENQUEUE_MIGRATED;
1717 ttwu_activate(rq, p, en_flags);
1718 ttwu_do_wakeup(rq, p, wake_flags, rf);
1722 * Called in case the task @p isn't fully descheduled from its runqueue,
1723 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1724 * since all we need to do is flip p->state to TASK_RUNNING, since
1725 * the task is still ->on_rq.
1727 static int ttwu_remote(struct task_struct *p, int wake_flags)
1733 rq = __task_rq_lock(p, &rf);
1734 if (task_on_rq_queued(p)) {
1735 /* check_preempt_curr() may use rq clock */
1736 update_rq_clock(rq);
1737 ttwu_do_wakeup(rq, p, wake_flags, &rf);
1740 __task_rq_unlock(rq, &rf);
1746 void sched_ttwu_pending(void)
1748 struct rq *rq = this_rq();
1749 struct llist_node *llist = llist_del_all(&rq->wake_list);
1750 struct task_struct *p, *t;
1756 rq_lock_irqsave(rq, &rf);
1757 update_rq_clock(rq);
1759 llist_for_each_entry_safe(p, t, llist, wake_entry)
1760 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
1762 rq_unlock_irqrestore(rq, &rf);
1765 void scheduler_ipi(void)
1768 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1769 * TIF_NEED_RESCHED remotely (for the first time) will also send
1772 preempt_fold_need_resched();
1774 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1778 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1779 * traditionally all their work was done from the interrupt return
1780 * path. Now that we actually do some work, we need to make sure
1783 * Some archs already do call them, luckily irq_enter/exit nest
1786 * Arguably we should visit all archs and update all handlers,
1787 * however a fair share of IPIs are still resched only so this would
1788 * somewhat pessimize the simple resched case.
1791 sched_ttwu_pending();
1794 * Check if someone kicked us for doing the nohz idle load balance.
1796 if (unlikely(got_nohz_idle_kick())) {
1797 this_rq()->idle_balance = 1;
1798 raise_softirq_irqoff(SCHED_SOFTIRQ);
1803 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1805 struct rq *rq = cpu_rq(cpu);
1807 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1809 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1810 if (!set_nr_if_polling(rq->idle))
1811 smp_send_reschedule(cpu);
1813 trace_sched_wake_idle_without_ipi(cpu);
1817 void wake_up_if_idle(int cpu)
1819 struct rq *rq = cpu_rq(cpu);
1824 if (!is_idle_task(rcu_dereference(rq->curr)))
1827 if (set_nr_if_polling(rq->idle)) {
1828 trace_sched_wake_idle_without_ipi(cpu);
1830 rq_lock_irqsave(rq, &rf);
1831 if (is_idle_task(rq->curr))
1832 smp_send_reschedule(cpu);
1833 /* Else CPU is not idle, do nothing here: */
1834 rq_unlock_irqrestore(rq, &rf);
1841 bool cpus_share_cache(int this_cpu, int that_cpu)
1843 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1845 #endif /* CONFIG_SMP */
1847 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1849 struct rq *rq = cpu_rq(cpu);
1852 #if defined(CONFIG_SMP)
1853 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1854 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
1855 ttwu_queue_remote(p, cpu, wake_flags);
1861 update_rq_clock(rq);
1862 ttwu_do_activate(rq, p, wake_flags, &rf);
1867 * Notes on Program-Order guarantees on SMP systems.
1871 * The basic program-order guarantee on SMP systems is that when a task [t]
1872 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1873 * execution on its new CPU [c1].
1875 * For migration (of runnable tasks) this is provided by the following means:
1877 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1878 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1879 * rq(c1)->lock (if not at the same time, then in that order).
1880 * C) LOCK of the rq(c1)->lock scheduling in task
1882 * Release/acquire chaining guarantees that B happens after A and C after B.
1883 * Note: the CPU doing B need not be c0 or c1
1892 * UNLOCK rq(0)->lock
1894 * LOCK rq(0)->lock // orders against CPU0
1896 * UNLOCK rq(0)->lock
1900 * UNLOCK rq(1)->lock
1902 * LOCK rq(1)->lock // orders against CPU2
1905 * UNLOCK rq(1)->lock
1908 * BLOCKING -- aka. SLEEP + WAKEUP
1910 * For blocking we (obviously) need to provide the same guarantee as for
1911 * migration. However the means are completely different as there is no lock
1912 * chain to provide order. Instead we do:
1914 * 1) smp_store_release(X->on_cpu, 0)
1915 * 2) smp_cond_load_acquire(!X->on_cpu)
1919 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1921 * LOCK rq(0)->lock LOCK X->pi_lock
1924 * smp_store_release(X->on_cpu, 0);
1926 * smp_cond_load_acquire(&X->on_cpu, !VAL);
1932 * X->state = RUNNING
1933 * UNLOCK rq(2)->lock
1935 * LOCK rq(2)->lock // orders against CPU1
1938 * UNLOCK rq(2)->lock
1941 * UNLOCK rq(0)->lock
1944 * However, for wakeups there is a second guarantee we must provide, namely we
1945 * must ensure that CONDITION=1 done by the caller can not be reordered with
1946 * accesses to the task state; see try_to_wake_up() and set_current_state().
1950 * try_to_wake_up - wake up a thread
1951 * @p: the thread to be awakened
1952 * @state: the mask of task states that can be woken
1953 * @wake_flags: wake modifier flags (WF_*)
1955 * If (@state & @p->state) @p->state = TASK_RUNNING.
1957 * If the task was not queued/runnable, also place it back on a runqueue.
1959 * Atomic against schedule() which would dequeue a task, also see
1960 * set_current_state().
1962 * This function executes a full memory barrier before accessing the task
1963 * state; see set_current_state().
1965 * Return: %true if @p->state changes (an actual wakeup was done),
1969 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1971 unsigned long flags;
1972 int cpu, success = 0;
1975 * If we are going to wake up a thread waiting for CONDITION we
1976 * need to ensure that CONDITION=1 done by the caller can not be
1977 * reordered with p->state check below. This pairs with mb() in
1978 * set_current_state() the waiting thread does.
1980 raw_spin_lock_irqsave(&p->pi_lock, flags);
1981 smp_mb__after_spinlock();
1982 if (!(p->state & state))
1985 trace_sched_waking(p);
1987 /* We're going to change ->state: */
1992 * Ensure we load p->on_rq _after_ p->state, otherwise it would
1993 * be possible to, falsely, observe p->on_rq == 0 and get stuck
1994 * in smp_cond_load_acquire() below.
1996 * sched_ttwu_pending() try_to_wake_up()
1997 * STORE p->on_rq = 1 LOAD p->state
2000 * __schedule() (switch to task 'p')
2001 * LOCK rq->lock smp_rmb();
2002 * smp_mb__after_spinlock();
2006 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
2008 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
2009 * __schedule(). See the comment for smp_mb__after_spinlock().
2012 if (p->on_rq && ttwu_remote(p, wake_flags))
2017 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2018 * possible to, falsely, observe p->on_cpu == 0.
2020 * One must be running (->on_cpu == 1) in order to remove oneself
2021 * from the runqueue.
2023 * __schedule() (switch to task 'p') try_to_wake_up()
2024 * STORE p->on_cpu = 1 LOAD p->on_rq
2027 * __schedule() (put 'p' to sleep)
2028 * LOCK rq->lock smp_rmb();
2029 * smp_mb__after_spinlock();
2030 * STORE p->on_rq = 0 LOAD p->on_cpu
2032 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
2033 * __schedule(). See the comment for smp_mb__after_spinlock().
2038 * If the owning (remote) CPU is still in the middle of schedule() with
2039 * this task as prev, wait until its done referencing the task.
2041 * Pairs with the smp_store_release() in finish_task().
2043 * This ensures that tasks getting woken will be fully ordered against
2044 * their previous state and preserve Program Order.
2046 smp_cond_load_acquire(&p->on_cpu, !VAL);
2048 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2049 p->state = TASK_WAKING;
2052 delayacct_blkio_end(p);
2053 atomic_dec(&task_rq(p)->nr_iowait);
2056 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2057 if (task_cpu(p) != cpu) {
2058 wake_flags |= WF_MIGRATED;
2059 psi_ttwu_dequeue(p);
2060 set_task_cpu(p, cpu);
2063 #else /* CONFIG_SMP */
2066 delayacct_blkio_end(p);
2067 atomic_dec(&task_rq(p)->nr_iowait);
2070 #endif /* CONFIG_SMP */
2072 ttwu_queue(p, cpu, wake_flags);
2074 ttwu_stat(p, cpu, wake_flags);
2076 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2082 * try_to_wake_up_local - try to wake up a local task with rq lock held
2083 * @p: the thread to be awakened
2084 * @rf: request-queue flags for pinning
2086 * Put @p on the run-queue if it's not already there. The caller must
2087 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2090 static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
2092 struct rq *rq = task_rq(p);
2094 if (WARN_ON_ONCE(rq != this_rq()) ||
2095 WARN_ON_ONCE(p == current))
2098 lockdep_assert_held(&rq->lock);
2100 if (!raw_spin_trylock(&p->pi_lock)) {
2102 * This is OK, because current is on_cpu, which avoids it being
2103 * picked for load-balance and preemption/IRQs are still
2104 * disabled avoiding further scheduler activity on it and we've
2105 * not yet picked a replacement task.
2108 raw_spin_lock(&p->pi_lock);
2112 if (!(p->state & TASK_NORMAL))
2115 trace_sched_waking(p);
2117 if (!task_on_rq_queued(p)) {
2119 delayacct_blkio_end(p);
2120 atomic_dec(&rq->nr_iowait);
2122 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
2125 ttwu_do_wakeup(rq, p, 0, rf);
2126 ttwu_stat(p, smp_processor_id(), 0);
2128 raw_spin_unlock(&p->pi_lock);
2132 * wake_up_process - Wake up a specific process
2133 * @p: The process to be woken up.
2135 * Attempt to wake up the nominated process and move it to the set of runnable
2138 * Return: 1 if the process was woken up, 0 if it was already running.
2140 * This function executes a full memory barrier before accessing the task state.
2142 int wake_up_process(struct task_struct *p)
2144 return try_to_wake_up(p, TASK_NORMAL, 0);
2146 EXPORT_SYMBOL(wake_up_process);
2148 int wake_up_state(struct task_struct *p, unsigned int state)
2150 return try_to_wake_up(p, state, 0);
2154 * Perform scheduler related setup for a newly forked process p.
2155 * p is forked by current.
2157 * __sched_fork() is basic setup used by init_idle() too:
2159 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2164 p->se.exec_start = 0;
2165 p->se.sum_exec_runtime = 0;
2166 p->se.prev_sum_exec_runtime = 0;
2167 p->se.nr_migrations = 0;
2169 INIT_LIST_HEAD(&p->se.group_node);
2171 #ifdef CONFIG_FAIR_GROUP_SCHED
2172 p->se.cfs_rq = NULL;
2175 #ifdef CONFIG_SCHEDSTATS
2176 /* Even if schedstat is disabled, there should not be garbage */
2177 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2180 RB_CLEAR_NODE(&p->dl.rb_node);
2181 init_dl_task_timer(&p->dl);
2182 init_dl_inactive_task_timer(&p->dl);
2183 __dl_clear_params(p);
2185 INIT_LIST_HEAD(&p->rt.run_list);
2187 p->rt.time_slice = sched_rr_timeslice;
2191 #ifdef CONFIG_PREEMPT_NOTIFIERS
2192 INIT_HLIST_HEAD(&p->preempt_notifiers);
2195 init_numa_balancing(clone_flags, p);
2198 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2200 #ifdef CONFIG_NUMA_BALANCING
2202 void set_numabalancing_state(bool enabled)
2205 static_branch_enable(&sched_numa_balancing);
2207 static_branch_disable(&sched_numa_balancing);
2210 #ifdef CONFIG_PROC_SYSCTL
2211 int sysctl_numa_balancing(struct ctl_table *table, int write,
2212 void __user *buffer, size_t *lenp, loff_t *ppos)
2216 int state = static_branch_likely(&sched_numa_balancing);
2218 if (write && !capable(CAP_SYS_ADMIN))
2223 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2227 set_numabalancing_state(state);
2233 #ifdef CONFIG_SCHEDSTATS
2235 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2236 static bool __initdata __sched_schedstats = false;
2238 static void set_schedstats(bool enabled)
2241 static_branch_enable(&sched_schedstats);
2243 static_branch_disable(&sched_schedstats);
2246 void force_schedstat_enabled(void)
2248 if (!schedstat_enabled()) {
2249 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2250 static_branch_enable(&sched_schedstats);
2254 static int __init setup_schedstats(char *str)
2261 * This code is called before jump labels have been set up, so we can't
2262 * change the static branch directly just yet. Instead set a temporary
2263 * variable so init_schedstats() can do it later.
2265 if (!strcmp(str, "enable")) {
2266 __sched_schedstats = true;
2268 } else if (!strcmp(str, "disable")) {
2269 __sched_schedstats = false;
2274 pr_warn("Unable to parse schedstats=\n");
2278 __setup("schedstats=", setup_schedstats);
2280 static void __init init_schedstats(void)
2282 set_schedstats(__sched_schedstats);
2285 #ifdef CONFIG_PROC_SYSCTL
2286 int sysctl_schedstats(struct ctl_table *table, int write,
2287 void __user *buffer, size_t *lenp, loff_t *ppos)
2291 int state = static_branch_likely(&sched_schedstats);
2293 if (write && !capable(CAP_SYS_ADMIN))
2298 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2302 set_schedstats(state);
2305 #endif /* CONFIG_PROC_SYSCTL */
2306 #else /* !CONFIG_SCHEDSTATS */
2307 static inline void init_schedstats(void) {}
2308 #endif /* CONFIG_SCHEDSTATS */
2311 * fork()/clone()-time setup:
2313 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2315 unsigned long flags;
2317 __sched_fork(clone_flags, p);
2319 * We mark the process as NEW here. This guarantees that
2320 * nobody will actually run it, and a signal or other external
2321 * event cannot wake it up and insert it on the runqueue either.
2323 p->state = TASK_NEW;
2326 * Make sure we do not leak PI boosting priority to the child.
2328 p->prio = current->normal_prio;
2331 * Revert to default priority/policy on fork if requested.
2333 if (unlikely(p->sched_reset_on_fork)) {
2334 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2335 p->policy = SCHED_NORMAL;
2336 p->static_prio = NICE_TO_PRIO(0);
2338 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2339 p->static_prio = NICE_TO_PRIO(0);
2341 p->prio = p->normal_prio = __normal_prio(p);
2342 set_load_weight(p, false);
2345 * We don't need the reset flag anymore after the fork. It has
2346 * fulfilled its duty:
2348 p->sched_reset_on_fork = 0;
2351 if (dl_prio(p->prio))
2353 else if (rt_prio(p->prio))
2354 p->sched_class = &rt_sched_class;
2356 p->sched_class = &fair_sched_class;
2358 init_entity_runnable_average(&p->se);
2361 * The child is not yet in the pid-hash so no cgroup attach races,
2362 * and the cgroup is pinned to this child due to cgroup_fork()
2363 * is ran before sched_fork().
2365 * Silence PROVE_RCU.
2367 raw_spin_lock_irqsave(&p->pi_lock, flags);
2369 * We're setting the CPU for the first time, we don't migrate,
2370 * so use __set_task_cpu().
2372 __set_task_cpu(p, smp_processor_id());
2373 if (p->sched_class->task_fork)
2374 p->sched_class->task_fork(p);
2375 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2377 #ifdef CONFIG_SCHED_INFO
2378 if (likely(sched_info_on()))
2379 memset(&p->sched_info, 0, sizeof(p->sched_info));
2381 #if defined(CONFIG_SMP)
2384 init_task_preempt_count(p);
2386 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2387 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2392 unsigned long to_ratio(u64 period, u64 runtime)
2394 if (runtime == RUNTIME_INF)
2398 * Doing this here saves a lot of checks in all
2399 * the calling paths, and returning zero seems
2400 * safe for them anyway.
2405 return div64_u64(runtime << BW_SHIFT, period);
2409 * wake_up_new_task - wake up a newly created task for the first time.
2411 * This function will do some initial scheduler statistics housekeeping
2412 * that must be done for every newly created context, then puts the task
2413 * on the runqueue and wakes it.
2415 void wake_up_new_task(struct task_struct *p)
2420 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2421 p->state = TASK_RUNNING;
2424 * Fork balancing, do it here and not earlier because:
2425 * - cpus_allowed can change in the fork path
2426 * - any previously selected CPU might disappear through hotplug
2428 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2429 * as we're not fully set-up yet.
2431 p->recent_used_cpu = task_cpu(p);
2432 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2434 rq = __task_rq_lock(p, &rf);
2435 update_rq_clock(rq);
2436 post_init_entity_util_avg(p);
2438 activate_task(rq, p, ENQUEUE_NOCLOCK);
2439 p->on_rq = TASK_ON_RQ_QUEUED;
2440 trace_sched_wakeup_new(p);
2441 check_preempt_curr(rq, p, WF_FORK);
2443 if (p->sched_class->task_woken) {
2445 * Nothing relies on rq->lock after this, so its fine to
2448 rq_unpin_lock(rq, &rf);
2449 p->sched_class->task_woken(rq, p);
2450 rq_repin_lock(rq, &rf);
2453 task_rq_unlock(rq, p, &rf);
2456 #ifdef CONFIG_PREEMPT_NOTIFIERS
2458 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
2460 void preempt_notifier_inc(void)
2462 static_branch_inc(&preempt_notifier_key);
2464 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2466 void preempt_notifier_dec(void)
2468 static_branch_dec(&preempt_notifier_key);
2470 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2473 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2474 * @notifier: notifier struct to register
2476 void preempt_notifier_register(struct preempt_notifier *notifier)
2478 if (!static_branch_unlikely(&preempt_notifier_key))
2479 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2481 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2483 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2486 * preempt_notifier_unregister - no longer interested in preemption notifications
2487 * @notifier: notifier struct to unregister
2489 * This is *not* safe to call from within a preemption notifier.
2491 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2493 hlist_del(¬ifier->link);
2495 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2497 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2499 struct preempt_notifier *notifier;
2501 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2502 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2505 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2507 if (static_branch_unlikely(&preempt_notifier_key))
2508 __fire_sched_in_preempt_notifiers(curr);
2512 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2513 struct task_struct *next)
2515 struct preempt_notifier *notifier;
2517 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2518 notifier->ops->sched_out(notifier, next);
2521 static __always_inline void
2522 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2523 struct task_struct *next)
2525 if (static_branch_unlikely(&preempt_notifier_key))
2526 __fire_sched_out_preempt_notifiers(curr, next);
2529 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2531 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2536 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2537 struct task_struct *next)
2541 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2543 static inline void prepare_task(struct task_struct *next)
2547 * Claim the task as running, we do this before switching to it
2548 * such that any running task will have this set.
2554 static inline void finish_task(struct task_struct *prev)
2558 * After ->on_cpu is cleared, the task can be moved to a different CPU.
2559 * We must ensure this doesn't happen until the switch is completely
2562 * In particular, the load of prev->state in finish_task_switch() must
2563 * happen before this.
2565 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
2567 smp_store_release(&prev->on_cpu, 0);
2572 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
2575 * Since the runqueue lock will be released by the next
2576 * task (which is an invalid locking op but in the case
2577 * of the scheduler it's an obvious special-case), so we
2578 * do an early lockdep release here:
2580 rq_unpin_lock(rq, rf);
2581 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2582 #ifdef CONFIG_DEBUG_SPINLOCK
2583 /* this is a valid case when another task releases the spinlock */
2584 rq->lock.owner = next;
2588 static inline void finish_lock_switch(struct rq *rq)
2591 * If we are tracking spinlock dependencies then we have to
2592 * fix up the runqueue lock - which gets 'carried over' from
2593 * prev into current:
2595 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
2596 raw_spin_unlock_irq(&rq->lock);
2600 * NOP if the arch has not defined these:
2603 #ifndef prepare_arch_switch
2604 # define prepare_arch_switch(next) do { } while (0)
2607 #ifndef finish_arch_post_lock_switch
2608 # define finish_arch_post_lock_switch() do { } while (0)
2612 * prepare_task_switch - prepare to switch tasks
2613 * @rq: the runqueue preparing to switch
2614 * @prev: the current task that is being switched out
2615 * @next: the task we are going to switch to.
2617 * This is called with the rq lock held and interrupts off. It must
2618 * be paired with a subsequent finish_task_switch after the context
2621 * prepare_task_switch sets up locking and calls architecture specific
2625 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2626 struct task_struct *next)
2628 kcov_prepare_switch(prev);
2629 sched_info_switch(rq, prev, next);
2630 perf_event_task_sched_out(prev, next);
2632 fire_sched_out_preempt_notifiers(prev, next);
2634 prepare_arch_switch(next);
2638 * finish_task_switch - clean up after a task-switch
2639 * @prev: the thread we just switched away from.
2641 * finish_task_switch must be called after the context switch, paired
2642 * with a prepare_task_switch call before the context switch.
2643 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2644 * and do any other architecture-specific cleanup actions.
2646 * Note that we may have delayed dropping an mm in context_switch(). If
2647 * so, we finish that here outside of the runqueue lock. (Doing it
2648 * with the lock held can cause deadlocks; see schedule() for
2651 * The context switch have flipped the stack from under us and restored the
2652 * local variables which were saved when this task called schedule() in the
2653 * past. prev == current is still correct but we need to recalculate this_rq
2654 * because prev may have moved to another CPU.
2656 static struct rq *finish_task_switch(struct task_struct *prev)
2657 __releases(rq->lock)
2659 struct rq *rq = this_rq();
2660 struct mm_struct *mm = rq->prev_mm;
2664 * The previous task will have left us with a preempt_count of 2
2665 * because it left us after:
2668 * preempt_disable(); // 1
2670 * raw_spin_lock_irq(&rq->lock) // 2
2672 * Also, see FORK_PREEMPT_COUNT.
2674 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2675 "corrupted preempt_count: %s/%d/0x%x\n",
2676 current->comm, current->pid, preempt_count()))
2677 preempt_count_set(FORK_PREEMPT_COUNT);
2682 * A task struct has one reference for the use as "current".
2683 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2684 * schedule one last time. The schedule call will never return, and
2685 * the scheduled task must drop that reference.
2687 * We must observe prev->state before clearing prev->on_cpu (in
2688 * finish_task), otherwise a concurrent wakeup can get prev
2689 * running on another CPU and we could rave with its RUNNING -> DEAD
2690 * transition, resulting in a double drop.
2692 prev_state = prev->state;
2693 vtime_task_switch(prev);
2694 perf_event_task_sched_in(prev, current);
2696 finish_lock_switch(rq);
2697 finish_arch_post_lock_switch();
2698 kcov_finish_switch(current);
2700 fire_sched_in_preempt_notifiers(current);
2702 * When switching through a kernel thread, the loop in
2703 * membarrier_{private,global}_expedited() may have observed that
2704 * kernel thread and not issued an IPI. It is therefore possible to
2705 * schedule between user->kernel->user threads without passing though
2706 * switch_mm(). Membarrier requires a barrier after storing to
2707 * rq->curr, before returning to userspace, so provide them here:
2709 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
2710 * provided by mmdrop(),
2711 * - a sync_core for SYNC_CORE.
2714 membarrier_mm_sync_core_before_usermode(mm);
2717 if (unlikely(prev_state == TASK_DEAD)) {
2718 if (prev->sched_class->task_dead)
2719 prev->sched_class->task_dead(prev);
2722 * Remove function-return probe instances associated with this
2723 * task and put them back on the free list.
2725 kprobe_flush_task(prev);
2727 /* Task is done with its stack. */
2728 put_task_stack(prev);
2730 put_task_struct(prev);
2733 tick_nohz_task_switch();
2739 /* rq->lock is NOT held, but preemption is disabled */
2740 static void __balance_callback(struct rq *rq)
2742 struct callback_head *head, *next;
2743 void (*func)(struct rq *rq);
2744 unsigned long flags;
2746 raw_spin_lock_irqsave(&rq->lock, flags);
2747 head = rq->balance_callback;
2748 rq->balance_callback = NULL;
2750 func = (void (*)(struct rq *))head->func;
2757 raw_spin_unlock_irqrestore(&rq->lock, flags);
2760 static inline void balance_callback(struct rq *rq)
2762 if (unlikely(rq->balance_callback))
2763 __balance_callback(rq);
2768 static inline void balance_callback(struct rq *rq)
2775 * schedule_tail - first thing a freshly forked thread must call.
2776 * @prev: the thread we just switched away from.
2778 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2779 __releases(rq->lock)
2784 * New tasks start with FORK_PREEMPT_COUNT, see there and
2785 * finish_task_switch() for details.
2787 * finish_task_switch() will drop rq->lock() and lower preempt_count
2788 * and the preempt_enable() will end up enabling preemption (on
2789 * PREEMPT_COUNT kernels).
2792 rq = finish_task_switch(prev);
2793 balance_callback(rq);
2796 if (current->set_child_tid)
2797 put_user(task_pid_vnr(current), current->set_child_tid);
2799 calculate_sigpending();
2803 * context_switch - switch to the new MM and the new thread's register state.
2805 static __always_inline struct rq *
2806 context_switch(struct rq *rq, struct task_struct *prev,
2807 struct task_struct *next, struct rq_flags *rf)
2809 struct mm_struct *mm, *oldmm;
2811 prepare_task_switch(rq, prev, next);
2814 oldmm = prev->active_mm;
2816 * For paravirt, this is coupled with an exit in switch_to to
2817 * combine the page table reload and the switch backend into
2820 arch_start_context_switch(prev);
2823 * If mm is non-NULL, we pass through switch_mm(). If mm is
2824 * NULL, we will pass through mmdrop() in finish_task_switch().
2825 * Both of these contain the full memory barrier required by
2826 * membarrier after storing to rq->curr, before returning to
2830 next->active_mm = oldmm;
2832 enter_lazy_tlb(oldmm, next);
2834 switch_mm_irqs_off(oldmm, mm, next);
2837 prev->active_mm = NULL;
2838 rq->prev_mm = oldmm;
2841 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
2843 prepare_lock_switch(rq, next, rf);
2845 /* Here we just switch the register state and the stack. */
2846 switch_to(prev, next, prev);
2849 return finish_task_switch(prev);
2853 * nr_running and nr_context_switches:
2855 * externally visible scheduler statistics: current number of runnable
2856 * threads, total number of context switches performed since bootup.
2858 unsigned long nr_running(void)
2860 unsigned long i, sum = 0;
2862 for_each_online_cpu(i)
2863 sum += cpu_rq(i)->nr_running;
2869 * Check if only the current task is running on the CPU.
2871 * Caution: this function does not check that the caller has disabled
2872 * preemption, thus the result might have a time-of-check-to-time-of-use
2873 * race. The caller is responsible to use it correctly, for example:
2875 * - from a non-preemptible section (of course)
2877 * - from a thread that is bound to a single CPU
2879 * - in a loop with very short iterations (e.g. a polling loop)
2881 bool single_task_running(void)
2883 return raw_rq()->nr_running == 1;
2885 EXPORT_SYMBOL(single_task_running);
2887 unsigned long long nr_context_switches(void)
2890 unsigned long long sum = 0;
2892 for_each_possible_cpu(i)
2893 sum += cpu_rq(i)->nr_switches;
2899 * Consumers of these two interfaces, like for example the cpuidle menu
2900 * governor, are using nonsensical data. Preferring shallow idle state selection
2901 * for a CPU that has IO-wait which might not even end up running the task when
2902 * it does become runnable.
2905 unsigned long nr_iowait_cpu(int cpu)
2907 return atomic_read(&cpu_rq(cpu)->nr_iowait);
2911 * IO-wait accounting, and how its mostly bollocks (on SMP).
2913 * The idea behind IO-wait account is to account the idle time that we could
2914 * have spend running if it were not for IO. That is, if we were to improve the
2915 * storage performance, we'd have a proportional reduction in IO-wait time.
2917 * This all works nicely on UP, where, when a task blocks on IO, we account
2918 * idle time as IO-wait, because if the storage were faster, it could've been
2919 * running and we'd not be idle.
2921 * This has been extended to SMP, by doing the same for each CPU. This however
2924 * Imagine for instance the case where two tasks block on one CPU, only the one
2925 * CPU will have IO-wait accounted, while the other has regular idle. Even
2926 * though, if the storage were faster, both could've ran at the same time,
2927 * utilising both CPUs.
2929 * This means, that when looking globally, the current IO-wait accounting on
2930 * SMP is a lower bound, by reason of under accounting.
2932 * Worse, since the numbers are provided per CPU, they are sometimes
2933 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2934 * associated with any one particular CPU, it can wake to another CPU than it
2935 * blocked on. This means the per CPU IO-wait number is meaningless.
2937 * Task CPU affinities can make all that even more 'interesting'.
2940 unsigned long nr_iowait(void)
2942 unsigned long i, sum = 0;
2944 for_each_possible_cpu(i)
2945 sum += nr_iowait_cpu(i);
2953 * sched_exec - execve() is a valuable balancing opportunity, because at
2954 * this point the task has the smallest effective memory and cache footprint.
2956 void sched_exec(void)
2958 struct task_struct *p = current;
2959 unsigned long flags;
2962 raw_spin_lock_irqsave(&p->pi_lock, flags);
2963 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2964 if (dest_cpu == smp_processor_id())
2967 if (likely(cpu_active(dest_cpu))) {
2968 struct migration_arg arg = { p, dest_cpu };
2970 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2971 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2975 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2980 DEFINE_PER_CPU(struct kernel_stat, kstat);
2981 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2983 EXPORT_PER_CPU_SYMBOL(kstat);
2984 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
2987 * The function fair_sched_class.update_curr accesses the struct curr
2988 * and its field curr->exec_start; when called from task_sched_runtime(),
2989 * we observe a high rate of cache misses in practice.
2990 * Prefetching this data results in improved performance.
2992 static inline void prefetch_curr_exec_start(struct task_struct *p)
2994 #ifdef CONFIG_FAIR_GROUP_SCHED
2995 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
2997 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3000 prefetch(&curr->exec_start);
3004 * Return accounted runtime for the task.
3005 * In case the task is currently running, return the runtime plus current's
3006 * pending runtime that have not been accounted yet.
3008 unsigned long long task_sched_runtime(struct task_struct *p)
3014 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3016 * 64-bit doesn't need locks to atomically read a 64-bit value.
3017 * So we have a optimization chance when the task's delta_exec is 0.
3018 * Reading ->on_cpu is racy, but this is ok.
3020 * If we race with it leaving CPU, we'll take a lock. So we're correct.
3021 * If we race with it entering CPU, unaccounted time is 0. This is
3022 * indistinguishable from the read occurring a few cycles earlier.
3023 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3024 * been accounted, so we're correct here as well.
3026 if (!p->on_cpu || !task_on_rq_queued(p))
3027 return p->se.sum_exec_runtime;
3030 rq = task_rq_lock(p, &rf);
3032 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3033 * project cycles that may never be accounted to this
3034 * thread, breaking clock_gettime().
3036 if (task_current(rq, p) && task_on_rq_queued(p)) {
3037 prefetch_curr_exec_start(p);
3038 update_rq_clock(rq);
3039 p->sched_class->update_curr(rq);
3041 ns = p->se.sum_exec_runtime;
3042 task_rq_unlock(rq, p, &rf);
3048 * This function gets called by the timer code, with HZ frequency.
3049 * We call it with interrupts disabled.
3051 void scheduler_tick(void)
3053 int cpu = smp_processor_id();
3054 struct rq *rq = cpu_rq(cpu);
3055 struct task_struct *curr = rq->curr;
3062 update_rq_clock(rq);
3063 curr->sched_class->task_tick(rq, curr, 0);
3064 cpu_load_update_active(rq);
3065 calc_global_load_tick(rq);
3070 perf_event_task_tick();
3073 rq->idle_balance = idle_cpu(cpu);
3074 trigger_load_balance(rq);
3078 #ifdef CONFIG_NO_HZ_FULL
3082 struct delayed_work work;
3085 static struct tick_work __percpu *tick_work_cpu;
3087 static void sched_tick_remote(struct work_struct *work)
3089 struct delayed_work *dwork = to_delayed_work(work);
3090 struct tick_work *twork = container_of(dwork, struct tick_work, work);
3091 int cpu = twork->cpu;
3092 struct rq *rq = cpu_rq(cpu);
3093 struct task_struct *curr;
3098 * Handle the tick only if it appears the remote CPU is running in full
3099 * dynticks mode. The check is racy by nature, but missing a tick or
3100 * having one too much is no big deal because the scheduler tick updates
3101 * statistics and checks timeslices in a time-independent way, regardless
3102 * of when exactly it is running.
3104 if (idle_cpu(cpu) || !tick_nohz_tick_stopped_cpu(cpu))
3107 rq_lock_irq(rq, &rf);
3109 if (is_idle_task(curr))
3112 update_rq_clock(rq);
3113 delta = rq_clock_task(rq) - curr->se.exec_start;
3116 * Make sure the next tick runs within a reasonable
3119 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
3120 curr->sched_class->task_tick(rq, curr, 0);
3123 rq_unlock_irq(rq, &rf);
3127 * Run the remote tick once per second (1Hz). This arbitrary
3128 * frequency is large enough to avoid overload but short enough
3129 * to keep scheduler internal stats reasonably up to date.
3131 queue_delayed_work(system_unbound_wq, dwork, HZ);
3134 static void sched_tick_start(int cpu)
3136 struct tick_work *twork;
3138 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3141 WARN_ON_ONCE(!tick_work_cpu);
3143 twork = per_cpu_ptr(tick_work_cpu, cpu);
3145 INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
3146 queue_delayed_work(system_unbound_wq, &twork->work, HZ);
3149 #ifdef CONFIG_HOTPLUG_CPU
3150 static void sched_tick_stop(int cpu)
3152 struct tick_work *twork;
3154 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3157 WARN_ON_ONCE(!tick_work_cpu);
3159 twork = per_cpu_ptr(tick_work_cpu, cpu);
3160 cancel_delayed_work_sync(&twork->work);
3162 #endif /* CONFIG_HOTPLUG_CPU */
3164 int __init sched_tick_offload_init(void)
3166 tick_work_cpu = alloc_percpu(struct tick_work);
3167 BUG_ON(!tick_work_cpu);
3172 #else /* !CONFIG_NO_HZ_FULL */
3173 static inline void sched_tick_start(int cpu) { }
3174 static inline void sched_tick_stop(int cpu) { }
3177 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3178 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
3180 * If the value passed in is equal to the current preempt count
3181 * then we just disabled preemption. Start timing the latency.
3183 static inline void preempt_latency_start(int val)
3185 if (preempt_count() == val) {
3186 unsigned long ip = get_lock_parent_ip();
3187 #ifdef CONFIG_DEBUG_PREEMPT
3188 current->preempt_disable_ip = ip;
3190 trace_preempt_off(CALLER_ADDR0, ip);
3194 void preempt_count_add(int val)
3196 #ifdef CONFIG_DEBUG_PREEMPT
3200 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3203 __preempt_count_add(val);
3204 #ifdef CONFIG_DEBUG_PREEMPT
3206 * Spinlock count overflowing soon?
3208 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3211 preempt_latency_start(val);
3213 EXPORT_SYMBOL(preempt_count_add);
3214 NOKPROBE_SYMBOL(preempt_count_add);
3217 * If the value passed in equals to the current preempt count
3218 * then we just enabled preemption. Stop timing the latency.
3220 static inline void preempt_latency_stop(int val)
3222 if (preempt_count() == val)
3223 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3226 void preempt_count_sub(int val)
3228 #ifdef CONFIG_DEBUG_PREEMPT
3232 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3235 * Is the spinlock portion underflowing?
3237 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3238 !(preempt_count() & PREEMPT_MASK)))
3242 preempt_latency_stop(val);
3243 __preempt_count_sub(val);
3245 EXPORT_SYMBOL(preempt_count_sub);
3246 NOKPROBE_SYMBOL(preempt_count_sub);
3249 static inline void preempt_latency_start(int val) { }
3250 static inline void preempt_latency_stop(int val) { }
3253 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3255 #ifdef CONFIG_DEBUG_PREEMPT
3256 return p->preempt_disable_ip;
3263 * Print scheduling while atomic bug:
3265 static noinline void __schedule_bug(struct task_struct *prev)
3267 /* Save this before calling printk(), since that will clobber it */
3268 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3270 if (oops_in_progress)
3273 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3274 prev->comm, prev->pid, preempt_count());
3276 debug_show_held_locks(prev);
3278 if (irqs_disabled())
3279 print_irqtrace_events(prev);
3280 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3281 && in_atomic_preempt_off()) {
3282 pr_err("Preemption disabled at:");
3283 print_ip_sym(preempt_disable_ip);
3287 panic("scheduling while atomic\n");
3290 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3294 * Various schedule()-time debugging checks and statistics:
3296 static inline void schedule_debug(struct task_struct *prev)
3298 #ifdef CONFIG_SCHED_STACK_END_CHECK
3299 if (task_stack_end_corrupted(prev))
3300 panic("corrupted stack end detected inside scheduler\n");
3303 if (unlikely(in_atomic_preempt_off())) {
3304 __schedule_bug(prev);
3305 preempt_count_set(PREEMPT_DISABLED);
3309 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3311 schedstat_inc(this_rq()->sched_count);
3315 * Pick up the highest-prio task:
3317 static inline struct task_struct *
3318 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
3320 const struct sched_class *class;
3321 struct task_struct *p;
3324 * Optimization: we know that if all tasks are in the fair class we can
3325 * call that function directly, but only if the @prev task wasn't of a
3326 * higher scheduling class, because otherwise those loose the
3327 * opportunity to pull in more work from other CPUs.
3329 if (likely((prev->sched_class == &idle_sched_class ||
3330 prev->sched_class == &fair_sched_class) &&
3331 rq->nr_running == rq->cfs.h_nr_running)) {
3333 p = fair_sched_class.pick_next_task(rq, prev, rf);
3334 if (unlikely(p == RETRY_TASK))
3337 /* Assumes fair_sched_class->next == idle_sched_class */
3339 p = idle_sched_class.pick_next_task(rq, prev, rf);
3345 for_each_class(class) {
3346 p = class->pick_next_task(rq, prev, rf);
3348 if (unlikely(p == RETRY_TASK))
3354 /* The idle class should always have a runnable task: */
3359 * __schedule() is the main scheduler function.
3361 * The main means of driving the scheduler and thus entering this function are:
3363 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3365 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3366 * paths. For example, see arch/x86/entry_64.S.
3368 * To drive preemption between tasks, the scheduler sets the flag in timer
3369 * interrupt handler scheduler_tick().
3371 * 3. Wakeups don't really cause entry into schedule(). They add a
3372 * task to the run-queue and that's it.
3374 * Now, if the new task added to the run-queue preempts the current
3375 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3376 * called on the nearest possible occasion:
3378 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3380 * - in syscall or exception context, at the next outmost
3381 * preempt_enable(). (this might be as soon as the wake_up()'s
3384 * - in IRQ context, return from interrupt-handler to
3385 * preemptible context
3387 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3390 * - cond_resched() call
3391 * - explicit schedule() call
3392 * - return from syscall or exception to user-space
3393 * - return from interrupt-handler to user-space
3395 * WARNING: must be called with preemption disabled!
3397 static void __sched notrace __schedule(bool preempt)
3399 struct task_struct *prev, *next;
3400 unsigned long *switch_count;
3405 cpu = smp_processor_id();
3409 schedule_debug(prev);
3411 if (sched_feat(HRTICK))
3414 local_irq_disable();
3415 rcu_note_context_switch(preempt);
3418 * Make sure that signal_pending_state()->signal_pending() below
3419 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3420 * done by the caller to avoid the race with signal_wake_up().
3422 * The membarrier system call requires a full memory barrier
3423 * after coming from user-space, before storing to rq->curr.
3426 smp_mb__after_spinlock();
3428 /* Promote REQ to ACT */
3429 rq->clock_update_flags <<= 1;
3430 update_rq_clock(rq);
3432 switch_count = &prev->nivcsw;
3433 if (!preempt && prev->state) {
3434 if (signal_pending_state(prev->state, prev)) {
3435 prev->state = TASK_RUNNING;
3437 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
3440 if (prev->in_iowait) {
3441 atomic_inc(&rq->nr_iowait);
3442 delayacct_blkio_start();
3446 * If a worker went to sleep, notify and ask workqueue
3447 * whether it wants to wake up a task to maintain
3450 if (prev->flags & PF_WQ_WORKER) {
3451 struct task_struct *to_wakeup;
3453 to_wakeup = wq_worker_sleeping(prev);
3455 try_to_wake_up_local(to_wakeup, &rf);
3458 switch_count = &prev->nvcsw;
3461 next = pick_next_task(rq, prev, &rf);
3462 clear_tsk_need_resched(prev);
3463 clear_preempt_need_resched();
3465 if (likely(prev != next)) {
3469 * The membarrier system call requires each architecture
3470 * to have a full memory barrier after updating
3471 * rq->curr, before returning to user-space.
3473 * Here are the schemes providing that barrier on the
3474 * various architectures:
3475 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
3476 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
3477 * - finish_lock_switch() for weakly-ordered
3478 * architectures where spin_unlock is a full barrier,
3479 * - switch_to() for arm64 (weakly-ordered, spin_unlock
3480 * is a RELEASE barrier),
3484 trace_sched_switch(preempt, prev, next);
3486 /* Also unlocks the rq: */
3487 rq = context_switch(rq, prev, next, &rf);
3489 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3490 rq_unlock_irq(rq, &rf);
3493 balance_callback(rq);
3496 void __noreturn do_task_dead(void)
3498 /* Causes final put_task_struct in finish_task_switch(): */
3499 set_special_state(TASK_DEAD);
3501 /* Tell freezer to ignore us: */
3502 current->flags |= PF_NOFREEZE;
3507 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
3512 static inline void sched_submit_work(struct task_struct *tsk)
3514 if (!tsk->state || tsk_is_pi_blocked(tsk))
3517 * If we are going to sleep and we have plugged IO queued,
3518 * make sure to submit it to avoid deadlocks.
3520 if (blk_needs_flush_plug(tsk))
3521 blk_schedule_flush_plug(tsk);
3524 asmlinkage __visible void __sched schedule(void)
3526 struct task_struct *tsk = current;
3528 sched_submit_work(tsk);
3532 sched_preempt_enable_no_resched();
3533 } while (need_resched());
3535 EXPORT_SYMBOL(schedule);
3538 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3539 * state (have scheduled out non-voluntarily) by making sure that all
3540 * tasks have either left the run queue or have gone into user space.
3541 * As idle tasks do not do either, they must not ever be preempted
3542 * (schedule out non-voluntarily).
3544 * schedule_idle() is similar to schedule_preempt_disable() except that it
3545 * never enables preemption because it does not call sched_submit_work().
3547 void __sched schedule_idle(void)
3550 * As this skips calling sched_submit_work(), which the idle task does
3551 * regardless because that function is a nop when the task is in a
3552 * TASK_RUNNING state, make sure this isn't used someplace that the
3553 * current task can be in any other state. Note, idle is always in the
3554 * TASK_RUNNING state.
3556 WARN_ON_ONCE(current->state);
3559 } while (need_resched());
3562 #ifdef CONFIG_CONTEXT_TRACKING
3563 asmlinkage __visible void __sched schedule_user(void)
3566 * If we come here after a random call to set_need_resched(),
3567 * or we have been woken up remotely but the IPI has not yet arrived,
3568 * we haven't yet exited the RCU idle mode. Do it here manually until
3569 * we find a better solution.
3571 * NB: There are buggy callers of this function. Ideally we
3572 * should warn if prev_state != CONTEXT_USER, but that will trigger
3573 * too frequently to make sense yet.
3575 enum ctx_state prev_state = exception_enter();
3577 exception_exit(prev_state);
3582 * schedule_preempt_disabled - called with preemption disabled
3584 * Returns with preemption disabled. Note: preempt_count must be 1
3586 void __sched schedule_preempt_disabled(void)
3588 sched_preempt_enable_no_resched();
3593 static void __sched notrace preempt_schedule_common(void)
3597 * Because the function tracer can trace preempt_count_sub()
3598 * and it also uses preempt_enable/disable_notrace(), if
3599 * NEED_RESCHED is set, the preempt_enable_notrace() called
3600 * by the function tracer will call this function again and
3601 * cause infinite recursion.
3603 * Preemption must be disabled here before the function
3604 * tracer can trace. Break up preempt_disable() into two
3605 * calls. One to disable preemption without fear of being
3606 * traced. The other to still record the preemption latency,
3607 * which can also be traced by the function tracer.
3609 preempt_disable_notrace();
3610 preempt_latency_start(1);
3612 preempt_latency_stop(1);
3613 preempt_enable_no_resched_notrace();
3616 * Check again in case we missed a preemption opportunity
3617 * between schedule and now.
3619 } while (need_resched());
3622 #ifdef CONFIG_PREEMPT
3624 * this is the entry point to schedule() from in-kernel preemption
3625 * off of preempt_enable. Kernel preemptions off return from interrupt
3626 * occur there and call schedule directly.
3628 asmlinkage __visible void __sched notrace preempt_schedule(void)
3631 * If there is a non-zero preempt_count or interrupts are disabled,
3632 * we do not want to preempt the current task. Just return..
3634 if (likely(!preemptible()))
3637 preempt_schedule_common();
3639 NOKPROBE_SYMBOL(preempt_schedule);
3640 EXPORT_SYMBOL(preempt_schedule);
3643 * preempt_schedule_notrace - preempt_schedule called by tracing
3645 * The tracing infrastructure uses preempt_enable_notrace to prevent
3646 * recursion and tracing preempt enabling caused by the tracing
3647 * infrastructure itself. But as tracing can happen in areas coming
3648 * from userspace or just about to enter userspace, a preempt enable
3649 * can occur before user_exit() is called. This will cause the scheduler
3650 * to be called when the system is still in usermode.
3652 * To prevent this, the preempt_enable_notrace will use this function
3653 * instead of preempt_schedule() to exit user context if needed before
3654 * calling the scheduler.
3656 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3658 enum ctx_state prev_ctx;
3660 if (likely(!preemptible()))
3665 * Because the function tracer can trace preempt_count_sub()
3666 * and it also uses preempt_enable/disable_notrace(), if
3667 * NEED_RESCHED is set, the preempt_enable_notrace() called
3668 * by the function tracer will call this function again and
3669 * cause infinite recursion.
3671 * Preemption must be disabled here before the function
3672 * tracer can trace. Break up preempt_disable() into two
3673 * calls. One to disable preemption without fear of being
3674 * traced. The other to still record the preemption latency,
3675 * which can also be traced by the function tracer.
3677 preempt_disable_notrace();
3678 preempt_latency_start(1);
3680 * Needs preempt disabled in case user_exit() is traced
3681 * and the tracer calls preempt_enable_notrace() causing
3682 * an infinite recursion.
3684 prev_ctx = exception_enter();
3686 exception_exit(prev_ctx);
3688 preempt_latency_stop(1);
3689 preempt_enable_no_resched_notrace();
3690 } while (need_resched());
3692 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3694 #endif /* CONFIG_PREEMPT */
3697 * this is the entry point to schedule() from kernel preemption
3698 * off of irq context.
3699 * Note, that this is called and return with irqs disabled. This will
3700 * protect us against recursive calling from irq.
3702 asmlinkage __visible void __sched preempt_schedule_irq(void)
3704 enum ctx_state prev_state;
3706 /* Catch callers which need to be fixed */
3707 BUG_ON(preempt_count() || !irqs_disabled());
3709 prev_state = exception_enter();
3715 local_irq_disable();
3716 sched_preempt_enable_no_resched();
3717 } while (need_resched());
3719 exception_exit(prev_state);
3722 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
3725 return try_to_wake_up(curr->private, mode, wake_flags);
3727 EXPORT_SYMBOL(default_wake_function);
3729 #ifdef CONFIG_RT_MUTEXES
3731 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
3734 prio = min(prio, pi_task->prio);
3739 static inline int rt_effective_prio(struct task_struct *p, int prio)
3741 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3743 return __rt_effective_prio(pi_task, prio);
3747 * rt_mutex_setprio - set the current priority of a task
3749 * @pi_task: donor task
3751 * This function changes the 'effective' priority of a task. It does
3752 * not touch ->normal_prio like __setscheduler().
3754 * Used by the rt_mutex code to implement priority inheritance
3755 * logic. Call site only calls if the priority of the task changed.
3757 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
3759 int prio, oldprio, queued, running, queue_flag =
3760 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
3761 const struct sched_class *prev_class;
3765 /* XXX used to be waiter->prio, not waiter->task->prio */
3766 prio = __rt_effective_prio(pi_task, p->normal_prio);
3769 * If nothing changed; bail early.
3771 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
3774 rq = __task_rq_lock(p, &rf);
3775 update_rq_clock(rq);
3777 * Set under pi_lock && rq->lock, such that the value can be used under
3780 * Note that there is loads of tricky to make this pointer cache work
3781 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3782 * ensure a task is de-boosted (pi_task is set to NULL) before the
3783 * task is allowed to run again (and can exit). This ensures the pointer
3784 * points to a blocked task -- which guaratees the task is present.
3786 p->pi_top_task = pi_task;
3789 * For FIFO/RR we only need to set prio, if that matches we're done.
3791 if (prio == p->prio && !dl_prio(prio))
3795 * Idle task boosting is a nono in general. There is one
3796 * exception, when PREEMPT_RT and NOHZ is active:
3798 * The idle task calls get_next_timer_interrupt() and holds
3799 * the timer wheel base->lock on the CPU and another CPU wants
3800 * to access the timer (probably to cancel it). We can safely
3801 * ignore the boosting request, as the idle CPU runs this code
3802 * with interrupts disabled and will complete the lock
3803 * protected section without being interrupted. So there is no
3804 * real need to boost.
3806 if (unlikely(p == rq->idle)) {
3807 WARN_ON(p != rq->curr);
3808 WARN_ON(p->pi_blocked_on);
3812 trace_sched_pi_setprio(p, pi_task);
3815 if (oldprio == prio)
3816 queue_flag &= ~DEQUEUE_MOVE;
3818 prev_class = p->sched_class;
3819 queued = task_on_rq_queued(p);
3820 running = task_current(rq, p);
3822 dequeue_task(rq, p, queue_flag);
3824 put_prev_task(rq, p);
3827 * Boosting condition are:
3828 * 1. -rt task is running and holds mutex A
3829 * --> -dl task blocks on mutex A
3831 * 2. -dl task is running and holds mutex A
3832 * --> -dl task blocks on mutex A and could preempt the
3835 if (dl_prio(prio)) {
3836 if (!dl_prio(p->normal_prio) ||
3837 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3838 p->dl.dl_boosted = 1;
3839 queue_flag |= ENQUEUE_REPLENISH;
3841 p->dl.dl_boosted = 0;
3842 p->sched_class = &dl_sched_class;
3843 } else if (rt_prio(prio)) {
3844 if (dl_prio(oldprio))
3845 p->dl.dl_boosted = 0;
3847 queue_flag |= ENQUEUE_HEAD;
3848 p->sched_class = &rt_sched_class;
3850 if (dl_prio(oldprio))
3851 p->dl.dl_boosted = 0;
3852 if (rt_prio(oldprio))
3854 p->sched_class = &fair_sched_class;
3860 enqueue_task(rq, p, queue_flag);
3862 set_curr_task(rq, p);
3864 check_class_changed(rq, p, prev_class, oldprio);
3866 /* Avoid rq from going away on us: */
3868 __task_rq_unlock(rq, &rf);
3870 balance_callback(rq);
3874 static inline int rt_effective_prio(struct task_struct *p, int prio)
3880 void set_user_nice(struct task_struct *p, long nice)
3882 bool queued, running;
3883 int old_prio, delta;
3887 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3890 * We have to be careful, if called from sys_setpriority(),
3891 * the task might be in the middle of scheduling on another CPU.
3893 rq = task_rq_lock(p, &rf);
3894 update_rq_clock(rq);
3897 * The RT priorities are set via sched_setscheduler(), but we still
3898 * allow the 'normal' nice value to be set - but as expected
3899 * it wont have any effect on scheduling until the task is
3900 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3902 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3903 p->static_prio = NICE_TO_PRIO(nice);
3906 queued = task_on_rq_queued(p);
3907 running = task_current(rq, p);
3909 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
3911 put_prev_task(rq, p);
3913 p->static_prio = NICE_TO_PRIO(nice);
3914 set_load_weight(p, true);
3916 p->prio = effective_prio(p);
3917 delta = p->prio - old_prio;
3920 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
3922 * If the task increased its priority or is running and
3923 * lowered its priority, then reschedule its CPU:
3925 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3929 set_curr_task(rq, p);
3931 task_rq_unlock(rq, p, &rf);
3933 EXPORT_SYMBOL(set_user_nice);
3936 * can_nice - check if a task can reduce its nice value
3940 int can_nice(const struct task_struct *p, const int nice)
3942 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
3943 int nice_rlim = nice_to_rlimit(nice);
3945 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3946 capable(CAP_SYS_NICE));
3949 #ifdef __ARCH_WANT_SYS_NICE
3952 * sys_nice - change the priority of the current process.
3953 * @increment: priority increment
3955 * sys_setpriority is a more generic, but much slower function that
3956 * does similar things.
3958 SYSCALL_DEFINE1(nice, int, increment)
3963 * Setpriority might change our priority at the same moment.
3964 * We don't have to worry. Conceptually one call occurs first
3965 * and we have a single winner.
3967 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3968 nice = task_nice(current) + increment;
3970 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3971 if (increment < 0 && !can_nice(current, nice))
3974 retval = security_task_setnice(current, nice);
3978 set_user_nice(current, nice);
3985 * task_prio - return the priority value of a given task.
3986 * @p: the task in question.
3988 * Return: The priority value as seen by users in /proc.
3989 * RT tasks are offset by -200. Normal tasks are centered
3990 * around 0, value goes from -16 to +15.
3992 int task_prio(const struct task_struct *p)
3994 return p->prio - MAX_RT_PRIO;
3998 * idle_cpu - is a given CPU idle currently?
3999 * @cpu: the processor in question.
4001 * Return: 1 if the CPU is currently idle. 0 otherwise.
4003 int idle_cpu(int cpu)
4005 struct rq *rq = cpu_rq(cpu);
4007 if (rq->curr != rq->idle)
4014 if (!llist_empty(&rq->wake_list))
4022 * available_idle_cpu - is a given CPU idle for enqueuing work.
4023 * @cpu: the CPU in question.
4025 * Return: 1 if the CPU is currently idle. 0 otherwise.
4027 int available_idle_cpu(int cpu)
4032 if (vcpu_is_preempted(cpu))
4039 * idle_task - return the idle task for a given CPU.
4040 * @cpu: the processor in question.
4042 * Return: The idle task for the CPU @cpu.
4044 struct task_struct *idle_task(int cpu)
4046 return cpu_rq(cpu)->idle;
4050 * find_process_by_pid - find a process with a matching PID value.
4051 * @pid: the pid in question.
4053 * The task of @pid, if found. %NULL otherwise.
4055 static struct task_struct *find_process_by_pid(pid_t pid)
4057 return pid ? find_task_by_vpid(pid) : current;
4061 * sched_setparam() passes in -1 for its policy, to let the functions
4062 * it calls know not to change it.
4064 #define SETPARAM_POLICY -1
4066 static void __setscheduler_params(struct task_struct *p,
4067 const struct sched_attr *attr)
4069 int policy = attr->sched_policy;
4071 if (policy == SETPARAM_POLICY)
4076 if (dl_policy(policy))
4077 __setparam_dl(p, attr);
4078 else if (fair_policy(policy))
4079 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4082 * __sched_setscheduler() ensures attr->sched_priority == 0 when
4083 * !rt_policy. Always setting this ensures that things like
4084 * getparam()/getattr() don't report silly values for !rt tasks.
4086 p->rt_priority = attr->sched_priority;
4087 p->normal_prio = normal_prio(p);
4088 set_load_weight(p, true);
4091 /* Actually do priority change: must hold pi & rq lock. */
4092 static void __setscheduler(struct rq *rq, struct task_struct *p,
4093 const struct sched_attr *attr, bool keep_boost)
4095 __setscheduler_params(p, attr);
4098 * Keep a potential priority boosting if called from
4099 * sched_setscheduler().
4101 p->prio = normal_prio(p);
4103 p->prio = rt_effective_prio(p, p->prio);
4105 if (dl_prio(p->prio))
4106 p->sched_class = &dl_sched_class;
4107 else if (rt_prio(p->prio))
4108 p->sched_class = &rt_sched_class;
4110 p->sched_class = &fair_sched_class;
4114 * Check the target process has a UID that matches the current process's:
4116 static bool check_same_owner(struct task_struct *p)
4118 const struct cred *cred = current_cred(), *pcred;
4122 pcred = __task_cred(p);
4123 match = (uid_eq(cred->euid, pcred->euid) ||
4124 uid_eq(cred->euid, pcred->uid));
4129 static int __sched_setscheduler(struct task_struct *p,
4130 const struct sched_attr *attr,
4133 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4134 MAX_RT_PRIO - 1 - attr->sched_priority;
4135 int retval, oldprio, oldpolicy = -1, queued, running;
4136 int new_effective_prio, policy = attr->sched_policy;
4137 const struct sched_class *prev_class;
4140 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
4143 /* The pi code expects interrupts enabled */
4144 BUG_ON(pi && in_interrupt());
4146 /* Double check policy once rq lock held: */
4148 reset_on_fork = p->sched_reset_on_fork;
4149 policy = oldpolicy = p->policy;
4151 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4153 if (!valid_policy(policy))
4157 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
4161 * Valid priorities for SCHED_FIFO and SCHED_RR are
4162 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4163 * SCHED_BATCH and SCHED_IDLE is 0.
4165 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4166 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4168 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4169 (rt_policy(policy) != (attr->sched_priority != 0)))
4173 * Allow unprivileged RT tasks to decrease priority:
4175 if (user && !capable(CAP_SYS_NICE)) {
4176 if (fair_policy(policy)) {
4177 if (attr->sched_nice < task_nice(p) &&
4178 !can_nice(p, attr->sched_nice))
4182 if (rt_policy(policy)) {
4183 unsigned long rlim_rtprio =
4184 task_rlimit(p, RLIMIT_RTPRIO);
4186 /* Can't set/change the rt policy: */
4187 if (policy != p->policy && !rlim_rtprio)
4190 /* Can't increase priority: */
4191 if (attr->sched_priority > p->rt_priority &&
4192 attr->sched_priority > rlim_rtprio)
4197 * Can't set/change SCHED_DEADLINE policy at all for now
4198 * (safest behavior); in the future we would like to allow
4199 * unprivileged DL tasks to increase their relative deadline
4200 * or reduce their runtime (both ways reducing utilization)
4202 if (dl_policy(policy))
4206 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4207 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4209 if (task_has_idle_policy(p) && !idle_policy(policy)) {
4210 if (!can_nice(p, task_nice(p)))
4214 /* Can't change other user's priorities: */
4215 if (!check_same_owner(p))
4218 /* Normal users shall not reset the sched_reset_on_fork flag: */
4219 if (p->sched_reset_on_fork && !reset_on_fork)
4224 if (attr->sched_flags & SCHED_FLAG_SUGOV)
4227 retval = security_task_setscheduler(p);
4233 * Make sure no PI-waiters arrive (or leave) while we are
4234 * changing the priority of the task:
4236 * To be able to change p->policy safely, the appropriate
4237 * runqueue lock must be held.
4239 rq = task_rq_lock(p, &rf);
4240 update_rq_clock(rq);
4243 * Changing the policy of the stop threads its a very bad idea:
4245 if (p == rq->stop) {
4246 task_rq_unlock(rq, p, &rf);
4251 * If not changing anything there's no need to proceed further,
4252 * but store a possible modification of reset_on_fork.
4254 if (unlikely(policy == p->policy)) {
4255 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4257 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4259 if (dl_policy(policy) && dl_param_changed(p, attr))
4262 p->sched_reset_on_fork = reset_on_fork;
4263 task_rq_unlock(rq, p, &rf);
4269 #ifdef CONFIG_RT_GROUP_SCHED
4271 * Do not allow realtime tasks into groups that have no runtime
4274 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4275 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4276 !task_group_is_autogroup(task_group(p))) {
4277 task_rq_unlock(rq, p, &rf);
4282 if (dl_bandwidth_enabled() && dl_policy(policy) &&
4283 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
4284 cpumask_t *span = rq->rd->span;
4287 * Don't allow tasks with an affinity mask smaller than
4288 * the entire root_domain to become SCHED_DEADLINE. We
4289 * will also fail if there's no bandwidth available.
4291 if (!cpumask_subset(span, &p->cpus_allowed) ||
4292 rq->rd->dl_bw.bw == 0) {
4293 task_rq_unlock(rq, p, &rf);
4300 /* Re-check policy now with rq lock held: */
4301 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4302 policy = oldpolicy = -1;
4303 task_rq_unlock(rq, p, &rf);
4308 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4309 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4312 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
4313 task_rq_unlock(rq, p, &rf);
4317 p->sched_reset_on_fork = reset_on_fork;
4322 * Take priority boosted tasks into account. If the new
4323 * effective priority is unchanged, we just store the new
4324 * normal parameters and do not touch the scheduler class and
4325 * the runqueue. This will be done when the task deboost
4328 new_effective_prio = rt_effective_prio(p, newprio);
4329 if (new_effective_prio == oldprio)
4330 queue_flags &= ~DEQUEUE_MOVE;
4333 queued = task_on_rq_queued(p);
4334 running = task_current(rq, p);
4336 dequeue_task(rq, p, queue_flags);
4338 put_prev_task(rq, p);
4340 prev_class = p->sched_class;
4341 __setscheduler(rq, p, attr, pi);
4345 * We enqueue to tail when the priority of a task is
4346 * increased (user space view).
4348 if (oldprio < p->prio)
4349 queue_flags |= ENQUEUE_HEAD;
4351 enqueue_task(rq, p, queue_flags);
4354 set_curr_task(rq, p);
4356 check_class_changed(rq, p, prev_class, oldprio);
4358 /* Avoid rq from going away on us: */
4360 task_rq_unlock(rq, p, &rf);
4363 rt_mutex_adjust_pi(p);
4365 /* Run balance callbacks after we've adjusted the PI chain: */
4366 balance_callback(rq);
4372 static int _sched_setscheduler(struct task_struct *p, int policy,
4373 const struct sched_param *param, bool check)
4375 struct sched_attr attr = {
4376 .sched_policy = policy,
4377 .sched_priority = param->sched_priority,
4378 .sched_nice = PRIO_TO_NICE(p->static_prio),
4381 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4382 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4383 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4384 policy &= ~SCHED_RESET_ON_FORK;
4385 attr.sched_policy = policy;
4388 return __sched_setscheduler(p, &attr, check, true);
4391 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4392 * @p: the task in question.
4393 * @policy: new policy.
4394 * @param: structure containing the new RT priority.
4396 * Return: 0 on success. An error code otherwise.
4398 * NOTE that the task may be already dead.
4400 int sched_setscheduler(struct task_struct *p, int policy,
4401 const struct sched_param *param)
4403 return _sched_setscheduler(p, policy, param, true);
4405 EXPORT_SYMBOL_GPL(sched_setscheduler);
4407 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4409 return __sched_setscheduler(p, attr, true, true);
4411 EXPORT_SYMBOL_GPL(sched_setattr);
4413 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
4415 return __sched_setscheduler(p, attr, false, true);
4419 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4420 * @p: the task in question.
4421 * @policy: new policy.
4422 * @param: structure containing the new RT priority.
4424 * Just like sched_setscheduler, only don't bother checking if the
4425 * current context has permission. For example, this is needed in
4426 * stop_machine(): we create temporary high priority worker threads,
4427 * but our caller might not have that capability.
4429 * Return: 0 on success. An error code otherwise.
4431 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4432 const struct sched_param *param)
4434 return _sched_setscheduler(p, policy, param, false);
4436 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4439 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4441 struct sched_param lparam;
4442 struct task_struct *p;
4445 if (!param || pid < 0)
4447 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4452 p = find_process_by_pid(pid);
4454 retval = sched_setscheduler(p, policy, &lparam);
4461 * Mimics kernel/events/core.c perf_copy_attr().
4463 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
4468 if (!access_ok(uattr, SCHED_ATTR_SIZE_VER0))
4471 /* Zero the full structure, so that a short copy will be nice: */
4472 memset(attr, 0, sizeof(*attr));
4474 ret = get_user(size, &uattr->size);
4478 /* Bail out on silly large: */
4479 if (size > PAGE_SIZE)
4482 /* ABI compatibility quirk: */
4484 size = SCHED_ATTR_SIZE_VER0;
4486 if (size < SCHED_ATTR_SIZE_VER0)
4490 * If we're handed a bigger struct than we know of,
4491 * ensure all the unknown bits are 0 - i.e. new
4492 * user-space does not rely on any kernel feature
4493 * extensions we dont know about yet.
4495 if (size > sizeof(*attr)) {
4496 unsigned char __user *addr;
4497 unsigned char __user *end;
4500 addr = (void __user *)uattr + sizeof(*attr);
4501 end = (void __user *)uattr + size;
4503 for (; addr < end; addr++) {
4504 ret = get_user(val, addr);
4510 size = sizeof(*attr);
4513 ret = copy_from_user(attr, uattr, size);
4518 * XXX: Do we want to be lenient like existing syscalls; or do we want
4519 * to be strict and return an error on out-of-bounds values?
4521 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4526 put_user(sizeof(*attr), &uattr->size);
4531 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4532 * @pid: the pid in question.
4533 * @policy: new policy.
4534 * @param: structure containing the new RT priority.
4536 * Return: 0 on success. An error code otherwise.
4538 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
4543 return do_sched_setscheduler(pid, policy, param);
4547 * sys_sched_setparam - set/change the RT priority of a thread
4548 * @pid: the pid in question.
4549 * @param: structure containing the new RT priority.
4551 * Return: 0 on success. An error code otherwise.
4553 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4555 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4559 * sys_sched_setattr - same as above, but with extended sched_attr
4560 * @pid: the pid in question.
4561 * @uattr: structure containing the extended parameters.
4562 * @flags: for future extension.
4564 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4565 unsigned int, flags)
4567 struct sched_attr attr;
4568 struct task_struct *p;
4571 if (!uattr || pid < 0 || flags)
4574 retval = sched_copy_attr(uattr, &attr);
4578 if ((int)attr.sched_policy < 0)
4583 p = find_process_by_pid(pid);
4585 retval = sched_setattr(p, &attr);
4592 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4593 * @pid: the pid in question.
4595 * Return: On success, the policy of the thread. Otherwise, a negative error
4598 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4600 struct task_struct *p;
4608 p = find_process_by_pid(pid);
4610 retval = security_task_getscheduler(p);
4613 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4620 * sys_sched_getparam - get the RT priority of a thread
4621 * @pid: the pid in question.
4622 * @param: structure containing the RT priority.
4624 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4627 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4629 struct sched_param lp = { .sched_priority = 0 };
4630 struct task_struct *p;
4633 if (!param || pid < 0)
4637 p = find_process_by_pid(pid);
4642 retval = security_task_getscheduler(p);
4646 if (task_has_rt_policy(p))
4647 lp.sched_priority = p->rt_priority;
4651 * This one might sleep, we cannot do it with a spinlock held ...
4653 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4662 static int sched_read_attr(struct sched_attr __user *uattr,
4663 struct sched_attr *attr,
4668 if (!access_ok(uattr, usize))
4672 * If we're handed a smaller struct than we know of,
4673 * ensure all the unknown bits are 0 - i.e. old
4674 * user-space does not get uncomplete information.
4676 if (usize < sizeof(*attr)) {
4677 unsigned char *addr;
4680 addr = (void *)attr + usize;
4681 end = (void *)attr + sizeof(*attr);
4683 for (; addr < end; addr++) {
4691 ret = copy_to_user(uattr, attr, attr->size);
4699 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4700 * @pid: the pid in question.
4701 * @uattr: structure containing the extended parameters.
4702 * @size: sizeof(attr) for fwd/bwd comp.
4703 * @flags: for future extension.
4705 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4706 unsigned int, size, unsigned int, flags)
4708 struct sched_attr attr = {
4709 .size = sizeof(struct sched_attr),
4711 struct task_struct *p;
4714 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4715 size < SCHED_ATTR_SIZE_VER0 || flags)
4719 p = find_process_by_pid(pid);
4724 retval = security_task_getscheduler(p);
4728 attr.sched_policy = p->policy;
4729 if (p->sched_reset_on_fork)
4730 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4731 if (task_has_dl_policy(p))
4732 __getparam_dl(p, &attr);
4733 else if (task_has_rt_policy(p))
4734 attr.sched_priority = p->rt_priority;
4736 attr.sched_nice = task_nice(p);
4740 retval = sched_read_attr(uattr, &attr, size);
4748 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4750 cpumask_var_t cpus_allowed, new_mask;
4751 struct task_struct *p;
4756 p = find_process_by_pid(pid);
4762 /* Prevent p going away */
4766 if (p->flags & PF_NO_SETAFFINITY) {
4770 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4774 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4776 goto out_free_cpus_allowed;
4779 if (!check_same_owner(p)) {
4781 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4783 goto out_free_new_mask;
4788 retval = security_task_setscheduler(p);
4790 goto out_free_new_mask;
4793 cpuset_cpus_allowed(p, cpus_allowed);
4794 cpumask_and(new_mask, in_mask, cpus_allowed);
4797 * Since bandwidth control happens on root_domain basis,
4798 * if admission test is enabled, we only admit -deadline
4799 * tasks allowed to run on all the CPUs in the task's
4803 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4805 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4808 goto out_free_new_mask;
4814 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4817 cpuset_cpus_allowed(p, cpus_allowed);
4818 if (!cpumask_subset(new_mask, cpus_allowed)) {
4820 * We must have raced with a concurrent cpuset
4821 * update. Just reset the cpus_allowed to the
4822 * cpuset's cpus_allowed
4824 cpumask_copy(new_mask, cpus_allowed);
4829 free_cpumask_var(new_mask);
4830 out_free_cpus_allowed:
4831 free_cpumask_var(cpus_allowed);
4837 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4838 struct cpumask *new_mask)
4840 if (len < cpumask_size())
4841 cpumask_clear(new_mask);
4842 else if (len > cpumask_size())
4843 len = cpumask_size();
4845 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4849 * sys_sched_setaffinity - set the CPU affinity of a process
4850 * @pid: pid of the process
4851 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4852 * @user_mask_ptr: user-space pointer to the new CPU mask
4854 * Return: 0 on success. An error code otherwise.
4856 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4857 unsigned long __user *, user_mask_ptr)
4859 cpumask_var_t new_mask;
4862 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4865 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4867 retval = sched_setaffinity(pid, new_mask);
4868 free_cpumask_var(new_mask);
4872 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4874 struct task_struct *p;
4875 unsigned long flags;
4881 p = find_process_by_pid(pid);
4885 retval = security_task_getscheduler(p);
4889 raw_spin_lock_irqsave(&p->pi_lock, flags);
4890 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4891 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4900 * sys_sched_getaffinity - get the CPU affinity of a process
4901 * @pid: pid of the process
4902 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4903 * @user_mask_ptr: user-space pointer to hold the current CPU mask
4905 * Return: size of CPU mask copied to user_mask_ptr on success. An
4906 * error code otherwise.
4908 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4909 unsigned long __user *, user_mask_ptr)
4914 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4916 if (len & (sizeof(unsigned long)-1))
4919 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4922 ret = sched_getaffinity(pid, mask);
4924 unsigned int retlen = min(len, cpumask_size());
4926 if (copy_to_user(user_mask_ptr, mask, retlen))
4931 free_cpumask_var(mask);
4937 * sys_sched_yield - yield the current processor to other threads.
4939 * This function yields the current CPU to other tasks. If there are no
4940 * other threads running on this CPU then this function will return.
4944 static void do_sched_yield(void)
4949 rq = this_rq_lock_irq(&rf);
4951 schedstat_inc(rq->yld_count);
4952 current->sched_class->yield_task(rq);
4955 * Since we are going to call schedule() anyway, there's
4956 * no need to preempt or enable interrupts:
4960 sched_preempt_enable_no_resched();
4965 SYSCALL_DEFINE0(sched_yield)
4971 #ifndef CONFIG_PREEMPT
4972 int __sched _cond_resched(void)
4974 if (should_resched(0)) {
4975 preempt_schedule_common();
4981 EXPORT_SYMBOL(_cond_resched);
4985 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4986 * call schedule, and on return reacquire the lock.
4988 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4989 * operations here to prevent schedule() from being called twice (once via
4990 * spin_unlock(), once by hand).
4992 int __cond_resched_lock(spinlock_t *lock)
4994 int resched = should_resched(PREEMPT_LOCK_OFFSET);
4997 lockdep_assert_held(lock);
4999 if (spin_needbreak(lock) || resched) {
5002 preempt_schedule_common();
5010 EXPORT_SYMBOL(__cond_resched_lock);
5013 * yield - yield the current processor to other threads.
5015 * Do not ever use this function, there's a 99% chance you're doing it wrong.
5017 * The scheduler is at all times free to pick the calling task as the most
5018 * eligible task to run, if removing the yield() call from your code breaks
5019 * it, its already broken.
5021 * Typical broken usage is:
5026 * where one assumes that yield() will let 'the other' process run that will
5027 * make event true. If the current task is a SCHED_FIFO task that will never
5028 * happen. Never use yield() as a progress guarantee!!
5030 * If you want to use yield() to wait for something, use wait_event().
5031 * If you want to use yield() to be 'nice' for others, use cond_resched().
5032 * If you still want to use yield(), do not!
5034 void __sched yield(void)
5036 set_current_state(TASK_RUNNING);
5039 EXPORT_SYMBOL(yield);
5042 * yield_to - yield the current processor to another thread in
5043 * your thread group, or accelerate that thread toward the
5044 * processor it's on.
5046 * @preempt: whether task preemption is allowed or not
5048 * It's the caller's job to ensure that the target task struct
5049 * can't go away on us before we can do any checks.
5052 * true (>0) if we indeed boosted the target task.
5053 * false (0) if we failed to boost the target.
5054 * -ESRCH if there's no task to yield to.
5056 int __sched yield_to(struct task_struct *p, bool preempt)
5058 struct task_struct *curr = current;
5059 struct rq *rq, *p_rq;
5060 unsigned long flags;
5063 local_irq_save(flags);
5069 * If we're the only runnable task on the rq and target rq also
5070 * has only one task, there's absolutely no point in yielding.
5072 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5077 double_rq_lock(rq, p_rq);
5078 if (task_rq(p) != p_rq) {
5079 double_rq_unlock(rq, p_rq);
5083 if (!curr->sched_class->yield_to_task)
5086 if (curr->sched_class != p->sched_class)
5089 if (task_running(p_rq, p) || p->state)
5092 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5094 schedstat_inc(rq->yld_count);
5096 * Make p's CPU reschedule; pick_next_entity takes care of
5099 if (preempt && rq != p_rq)
5104 double_rq_unlock(rq, p_rq);
5106 local_irq_restore(flags);
5113 EXPORT_SYMBOL_GPL(yield_to);
5115 int io_schedule_prepare(void)
5117 int old_iowait = current->in_iowait;
5119 current->in_iowait = 1;
5120 blk_schedule_flush_plug(current);
5125 void io_schedule_finish(int token)
5127 current->in_iowait = token;
5131 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5132 * that process accounting knows that this is a task in IO wait state.
5134 long __sched io_schedule_timeout(long timeout)
5139 token = io_schedule_prepare();
5140 ret = schedule_timeout(timeout);
5141 io_schedule_finish(token);
5145 EXPORT_SYMBOL(io_schedule_timeout);
5147 void io_schedule(void)
5151 token = io_schedule_prepare();
5153 io_schedule_finish(token);
5155 EXPORT_SYMBOL(io_schedule);
5158 * sys_sched_get_priority_max - return maximum RT priority.
5159 * @policy: scheduling class.
5161 * Return: On success, this syscall returns the maximum
5162 * rt_priority that can be used by a given scheduling class.
5163 * On failure, a negative error code is returned.
5165 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5172 ret = MAX_USER_RT_PRIO-1;
5174 case SCHED_DEADLINE:
5185 * sys_sched_get_priority_min - return minimum RT priority.
5186 * @policy: scheduling class.
5188 * Return: On success, this syscall returns the minimum
5189 * rt_priority that can be used by a given scheduling class.
5190 * On failure, a negative error code is returned.
5192 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5201 case SCHED_DEADLINE:
5210 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
5212 struct task_struct *p;
5213 unsigned int time_slice;
5223 p = find_process_by_pid(pid);
5227 retval = security_task_getscheduler(p);
5231 rq = task_rq_lock(p, &rf);
5233 if (p->sched_class->get_rr_interval)
5234 time_slice = p->sched_class->get_rr_interval(rq, p);
5235 task_rq_unlock(rq, p, &rf);
5238 jiffies_to_timespec64(time_slice, t);
5247 * sys_sched_rr_get_interval - return the default timeslice of a process.
5248 * @pid: pid of the process.
5249 * @interval: userspace pointer to the timeslice value.
5251 * this syscall writes the default timeslice value of a given process
5252 * into the user-space timespec buffer. A value of '0' means infinity.
5254 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5257 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5258 struct __kernel_timespec __user *, interval)
5260 struct timespec64 t;
5261 int retval = sched_rr_get_interval(pid, &t);
5264 retval = put_timespec64(&t, interval);
5269 #ifdef CONFIG_COMPAT_32BIT_TIME
5270 COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
5272 struct old_timespec32 __user *, interval)
5274 struct timespec64 t;
5275 int retval = sched_rr_get_interval(pid, &t);
5278 retval = put_old_timespec32(&t, interval);
5283 void sched_show_task(struct task_struct *p)
5285 unsigned long free = 0;
5288 if (!try_get_task_stack(p))
5291 printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
5293 if (p->state == TASK_RUNNING)
5294 printk(KERN_CONT " running task ");
5295 #ifdef CONFIG_DEBUG_STACK_USAGE
5296 free = stack_not_used(p);
5301 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5303 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5304 task_pid_nr(p), ppid,
5305 (unsigned long)task_thread_info(p)->flags);
5307 print_worker_info(KERN_INFO, p);
5308 show_stack(p, NULL);
5311 EXPORT_SYMBOL_GPL(sched_show_task);
5314 state_filter_match(unsigned long state_filter, struct task_struct *p)
5316 /* no filter, everything matches */
5320 /* filter, but doesn't match */
5321 if (!(p->state & state_filter))
5325 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5328 if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
5335 void show_state_filter(unsigned long state_filter)
5337 struct task_struct *g, *p;
5339 #if BITS_PER_LONG == 32
5341 " task PC stack pid father\n");
5344 " task PC stack pid father\n");
5347 for_each_process_thread(g, p) {
5349 * reset the NMI-timeout, listing all files on a slow
5350 * console might take a lot of time:
5351 * Also, reset softlockup watchdogs on all CPUs, because
5352 * another CPU might be blocked waiting for us to process
5355 touch_nmi_watchdog();
5356 touch_all_softlockup_watchdogs();
5357 if (state_filter_match(state_filter, p))
5361 #ifdef CONFIG_SCHED_DEBUG
5363 sysrq_sched_debug_show();
5367 * Only show locks if all tasks are dumped:
5370 debug_show_all_locks();
5374 * init_idle - set up an idle thread for a given CPU
5375 * @idle: task in question
5376 * @cpu: CPU the idle task belongs to
5378 * NOTE: this function does not set the idle thread's NEED_RESCHED
5379 * flag, to make booting more robust.
5381 void init_idle(struct task_struct *idle, int cpu)
5383 struct rq *rq = cpu_rq(cpu);
5384 unsigned long flags;
5386 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5387 raw_spin_lock(&rq->lock);
5389 __sched_fork(0, idle);
5390 idle->state = TASK_RUNNING;
5391 idle->se.exec_start = sched_clock();
5392 idle->flags |= PF_IDLE;
5394 kasan_unpoison_task_stack(idle);
5398 * Its possible that init_idle() gets called multiple times on a task,
5399 * in that case do_set_cpus_allowed() will not do the right thing.
5401 * And since this is boot we can forgo the serialization.
5403 set_cpus_allowed_common(idle, cpumask_of(cpu));
5406 * We're having a chicken and egg problem, even though we are
5407 * holding rq->lock, the CPU isn't yet set to this CPU so the
5408 * lockdep check in task_group() will fail.
5410 * Similar case to sched_fork(). / Alternatively we could
5411 * use task_rq_lock() here and obtain the other rq->lock.
5416 __set_task_cpu(idle, cpu);
5419 rq->curr = rq->idle = idle;
5420 idle->on_rq = TASK_ON_RQ_QUEUED;
5424 raw_spin_unlock(&rq->lock);
5425 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5427 /* Set the preempt count _outside_ the spinlocks! */
5428 init_idle_preempt_count(idle, cpu);
5431 * The idle tasks have their own, simple scheduling class:
5433 idle->sched_class = &idle_sched_class;
5434 ftrace_graph_init_idle_task(idle, cpu);
5435 vtime_init_idle(idle, cpu);
5437 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5443 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5444 const struct cpumask *trial)
5448 if (!cpumask_weight(cur))
5451 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
5456 int task_can_attach(struct task_struct *p,
5457 const struct cpumask *cs_cpus_allowed)
5462 * Kthreads which disallow setaffinity shouldn't be moved
5463 * to a new cpuset; we don't want to change their CPU
5464 * affinity and isolating such threads by their set of
5465 * allowed nodes is unnecessary. Thus, cpusets are not
5466 * applicable for such threads. This prevents checking for
5467 * success of set_cpus_allowed_ptr() on all attached tasks
5468 * before cpus_allowed may be changed.
5470 if (p->flags & PF_NO_SETAFFINITY) {
5475 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5477 ret = dl_task_can_attach(p, cs_cpus_allowed);
5483 bool sched_smp_initialized __read_mostly;
5485 #ifdef CONFIG_NUMA_BALANCING
5486 /* Migrate current task p to target_cpu */
5487 int migrate_task_to(struct task_struct *p, int target_cpu)
5489 struct migration_arg arg = { p, target_cpu };
5490 int curr_cpu = task_cpu(p);
5492 if (curr_cpu == target_cpu)
5495 if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
5498 /* TODO: This is not properly updating schedstats */
5500 trace_sched_move_numa(p, curr_cpu, target_cpu);
5501 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5505 * Requeue a task on a given node and accurately track the number of NUMA
5506 * tasks on the runqueues
5508 void sched_setnuma(struct task_struct *p, int nid)
5510 bool queued, running;
5514 rq = task_rq_lock(p, &rf);
5515 queued = task_on_rq_queued(p);
5516 running = task_current(rq, p);
5519 dequeue_task(rq, p, DEQUEUE_SAVE);
5521 put_prev_task(rq, p);
5523 p->numa_preferred_nid = nid;
5526 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
5528 set_curr_task(rq, p);
5529 task_rq_unlock(rq, p, &rf);
5531 #endif /* CONFIG_NUMA_BALANCING */
5533 #ifdef CONFIG_HOTPLUG_CPU
5535 * Ensure that the idle task is using init_mm right before its CPU goes
5538 void idle_task_exit(void)
5540 struct mm_struct *mm = current->active_mm;
5542 BUG_ON(cpu_online(smp_processor_id()));
5544 if (mm != &init_mm) {
5545 switch_mm(mm, &init_mm, current);
5546 current->active_mm = &init_mm;
5547 finish_arch_post_lock_switch();
5553 * Since this CPU is going 'away' for a while, fold any nr_active delta
5554 * we might have. Assumes we're called after migrate_tasks() so that the
5555 * nr_active count is stable. We need to take the teardown thread which
5556 * is calling this into account, so we hand in adjust = 1 to the load
5559 * Also see the comment "Global load-average calculations".
5561 static void calc_load_migrate(struct rq *rq)
5563 long delta = calc_load_fold_active(rq, 1);
5565 atomic_long_add(delta, &calc_load_tasks);
5568 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5572 static const struct sched_class fake_sched_class = {
5573 .put_prev_task = put_prev_task_fake,
5576 static struct task_struct fake_task = {
5578 * Avoid pull_{rt,dl}_task()
5580 .prio = MAX_PRIO + 1,
5581 .sched_class = &fake_sched_class,
5585 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5586 * try_to_wake_up()->select_task_rq().
5588 * Called with rq->lock held even though we'er in stop_machine() and
5589 * there's no concurrency possible, we hold the required locks anyway
5590 * because of lock validation efforts.
5592 static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
5594 struct rq *rq = dead_rq;
5595 struct task_struct *next, *stop = rq->stop;
5596 struct rq_flags orf = *rf;
5600 * Fudge the rq selection such that the below task selection loop
5601 * doesn't get stuck on the currently eligible stop task.
5603 * We're currently inside stop_machine() and the rq is either stuck
5604 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5605 * either way we should never end up calling schedule() until we're
5611 * put_prev_task() and pick_next_task() sched
5612 * class method both need to have an up-to-date
5613 * value of rq->clock[_task]
5615 update_rq_clock(rq);
5619 * There's this thread running, bail when that's the only
5622 if (rq->nr_running == 1)
5626 * pick_next_task() assumes pinned rq->lock:
5628 next = pick_next_task(rq, &fake_task, rf);
5630 put_prev_task(rq, next);
5633 * Rules for changing task_struct::cpus_allowed are holding
5634 * both pi_lock and rq->lock, such that holding either
5635 * stabilizes the mask.
5637 * Drop rq->lock is not quite as disastrous as it usually is
5638 * because !cpu_active at this point, which means load-balance
5639 * will not interfere. Also, stop-machine.
5642 raw_spin_lock(&next->pi_lock);
5646 * Since we're inside stop-machine, _nothing_ should have
5647 * changed the task, WARN if weird stuff happened, because in
5648 * that case the above rq->lock drop is a fail too.
5650 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5651 raw_spin_unlock(&next->pi_lock);
5655 /* Find suitable destination for @next, with force if needed. */
5656 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5657 rq = __migrate_task(rq, rf, next, dest_cpu);
5658 if (rq != dead_rq) {
5664 raw_spin_unlock(&next->pi_lock);
5669 #endif /* CONFIG_HOTPLUG_CPU */
5671 void set_rq_online(struct rq *rq)
5674 const struct sched_class *class;
5676 cpumask_set_cpu(rq->cpu, rq->rd->online);
5679 for_each_class(class) {
5680 if (class->rq_online)
5681 class->rq_online(rq);
5686 void set_rq_offline(struct rq *rq)
5689 const struct sched_class *class;
5691 for_each_class(class) {
5692 if (class->rq_offline)
5693 class->rq_offline(rq);
5696 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5702 * used to mark begin/end of suspend/resume:
5704 static int num_cpus_frozen;
5707 * Update cpusets according to cpu_active mask. If cpusets are
5708 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5709 * around partition_sched_domains().
5711 * If we come here as part of a suspend/resume, don't touch cpusets because we
5712 * want to restore it back to its original state upon resume anyway.
5714 static void cpuset_cpu_active(void)
5716 if (cpuhp_tasks_frozen) {
5718 * num_cpus_frozen tracks how many CPUs are involved in suspend
5719 * resume sequence. As long as this is not the last online
5720 * operation in the resume sequence, just build a single sched
5721 * domain, ignoring cpusets.
5723 partition_sched_domains(1, NULL, NULL);
5724 if (--num_cpus_frozen)
5727 * This is the last CPU online operation. So fall through and
5728 * restore the original sched domains by considering the
5729 * cpuset configurations.
5731 cpuset_force_rebuild();
5733 cpuset_update_active_cpus();
5736 static int cpuset_cpu_inactive(unsigned int cpu)
5738 if (!cpuhp_tasks_frozen) {
5739 if (dl_cpu_busy(cpu))
5741 cpuset_update_active_cpus();
5744 partition_sched_domains(1, NULL, NULL);
5749 int sched_cpu_activate(unsigned int cpu)
5751 struct rq *rq = cpu_rq(cpu);
5754 #ifdef CONFIG_SCHED_SMT
5756 * When going up, increment the number of cores with SMT present.
5758 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
5759 static_branch_inc_cpuslocked(&sched_smt_present);
5761 set_cpu_active(cpu, true);
5763 if (sched_smp_initialized) {
5764 sched_domains_numa_masks_set(cpu);
5765 cpuset_cpu_active();
5769 * Put the rq online, if not already. This happens:
5771 * 1) In the early boot process, because we build the real domains
5772 * after all CPUs have been brought up.
5774 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5777 rq_lock_irqsave(rq, &rf);
5779 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5782 rq_unlock_irqrestore(rq, &rf);
5784 update_max_interval();
5789 int sched_cpu_deactivate(unsigned int cpu)
5793 set_cpu_active(cpu, false);
5795 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5796 * users of this state to go away such that all new such users will
5799 * Do sync before park smpboot threads to take care the rcu boost case.
5803 #ifdef CONFIG_SCHED_SMT
5805 * When going down, decrement the number of cores with SMT present.
5807 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
5808 static_branch_dec_cpuslocked(&sched_smt_present);
5811 if (!sched_smp_initialized)
5814 ret = cpuset_cpu_inactive(cpu);
5816 set_cpu_active(cpu, true);
5819 sched_domains_numa_masks_clear(cpu);
5823 static void sched_rq_cpu_starting(unsigned int cpu)
5825 struct rq *rq = cpu_rq(cpu);
5827 rq->calc_load_update = calc_load_update;
5828 update_max_interval();
5831 int sched_cpu_starting(unsigned int cpu)
5833 sched_rq_cpu_starting(cpu);
5834 sched_tick_start(cpu);
5838 #ifdef CONFIG_HOTPLUG_CPU
5839 int sched_cpu_dying(unsigned int cpu)
5841 struct rq *rq = cpu_rq(cpu);
5844 /* Handle pending wakeups and then migrate everything off */
5845 sched_ttwu_pending();
5846 sched_tick_stop(cpu);
5848 rq_lock_irqsave(rq, &rf);
5850 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5853 migrate_tasks(rq, &rf);
5854 BUG_ON(rq->nr_running != 1);
5855 rq_unlock_irqrestore(rq, &rf);
5857 calc_load_migrate(rq);
5858 update_max_interval();
5859 nohz_balance_exit_idle(rq);
5865 void __init sched_init_smp(void)
5870 * There's no userspace yet to cause hotplug operations; hence all the
5871 * CPU masks are stable and all blatant races in the below code cannot
5872 * happen. The hotplug lock is nevertheless taken to satisfy lockdep,
5873 * but there won't be any contention on it.
5876 mutex_lock(&sched_domains_mutex);
5877 sched_init_domains(cpu_active_mask);
5878 mutex_unlock(&sched_domains_mutex);
5881 /* Move init over to a non-isolated CPU */
5882 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5884 sched_init_granularity();
5886 init_sched_rt_class();
5887 init_sched_dl_class();
5889 sched_smp_initialized = true;
5892 static int __init migration_init(void)
5894 sched_rq_cpu_starting(smp_processor_id());
5897 early_initcall(migration_init);
5900 void __init sched_init_smp(void)
5902 sched_init_granularity();
5904 #endif /* CONFIG_SMP */
5906 int in_sched_functions(unsigned long addr)
5908 return in_lock_functions(addr) ||
5909 (addr >= (unsigned long)__sched_text_start
5910 && addr < (unsigned long)__sched_text_end);
5913 #ifdef CONFIG_CGROUP_SCHED
5915 * Default task group.
5916 * Every task in system belongs to this group at bootup.
5918 struct task_group root_task_group;
5919 LIST_HEAD(task_groups);
5921 /* Cacheline aligned slab cache for task_group */
5922 static struct kmem_cache *task_group_cache __read_mostly;
5925 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
5926 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
5928 void __init sched_init(void)
5931 unsigned long alloc_size = 0, ptr;
5935 #ifdef CONFIG_FAIR_GROUP_SCHED
5936 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5938 #ifdef CONFIG_RT_GROUP_SCHED
5939 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5942 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
5944 #ifdef CONFIG_FAIR_GROUP_SCHED
5945 root_task_group.se = (struct sched_entity **)ptr;
5946 ptr += nr_cpu_ids * sizeof(void **);
5948 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
5949 ptr += nr_cpu_ids * sizeof(void **);
5951 #endif /* CONFIG_FAIR_GROUP_SCHED */
5952 #ifdef CONFIG_RT_GROUP_SCHED
5953 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
5954 ptr += nr_cpu_ids * sizeof(void **);
5956 root_task_group.rt_rq = (struct rt_rq **)ptr;
5957 ptr += nr_cpu_ids * sizeof(void **);
5959 #endif /* CONFIG_RT_GROUP_SCHED */
5961 #ifdef CONFIG_CPUMASK_OFFSTACK
5962 for_each_possible_cpu(i) {
5963 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
5964 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5965 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
5966 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5968 #endif /* CONFIG_CPUMASK_OFFSTACK */
5970 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
5971 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
5974 init_defrootdomain();
5977 #ifdef CONFIG_RT_GROUP_SCHED
5978 init_rt_bandwidth(&root_task_group.rt_bandwidth,
5979 global_rt_period(), global_rt_runtime());
5980 #endif /* CONFIG_RT_GROUP_SCHED */
5982 #ifdef CONFIG_CGROUP_SCHED
5983 task_group_cache = KMEM_CACHE(task_group, 0);
5985 list_add(&root_task_group.list, &task_groups);
5986 INIT_LIST_HEAD(&root_task_group.children);
5987 INIT_LIST_HEAD(&root_task_group.siblings);
5988 autogroup_init(&init_task);
5989 #endif /* CONFIG_CGROUP_SCHED */
5991 for_each_possible_cpu(i) {
5995 raw_spin_lock_init(&rq->lock);
5997 rq->calc_load_active = 0;
5998 rq->calc_load_update = jiffies + LOAD_FREQ;
5999 init_cfs_rq(&rq->cfs);
6000 init_rt_rq(&rq->rt);
6001 init_dl_rq(&rq->dl);
6002 #ifdef CONFIG_FAIR_GROUP_SCHED
6003 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6004 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6005 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
6007 * How much CPU bandwidth does root_task_group get?
6009 * In case of task-groups formed thr' the cgroup filesystem, it
6010 * gets 100% of the CPU resources in the system. This overall
6011 * system CPU resource is divided among the tasks of
6012 * root_task_group and its child task-groups in a fair manner,
6013 * based on each entity's (task or task-group's) weight
6014 * (se->load.weight).
6016 * In other words, if root_task_group has 10 tasks of weight
6017 * 1024) and two child groups A0 and A1 (of weight 1024 each),
6018 * then A0's share of the CPU resource is:
6020 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
6022 * We achieve this by letting root_task_group's tasks sit
6023 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
6025 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
6026 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
6027 #endif /* CONFIG_FAIR_GROUP_SCHED */
6029 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
6030 #ifdef CONFIG_RT_GROUP_SCHED
6031 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
6034 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6035 rq->cpu_load[j] = 0;
6040 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
6041 rq->balance_callback = NULL;
6042 rq->active_balance = 0;
6043 rq->next_balance = jiffies;
6048 rq->avg_idle = 2*sysctl_sched_migration_cost;
6049 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
6051 INIT_LIST_HEAD(&rq->cfs_tasks);
6053 rq_attach_root(rq, &def_root_domain);
6054 #ifdef CONFIG_NO_HZ_COMMON
6055 rq->last_load_update_tick = jiffies;
6056 rq->last_blocked_load_update_tick = jiffies;
6057 atomic_set(&rq->nohz_flags, 0);
6059 #endif /* CONFIG_SMP */
6061 atomic_set(&rq->nr_iowait, 0);
6064 set_load_weight(&init_task, false);
6067 * The boot idle thread does lazy MMU switching as well:
6070 enter_lazy_tlb(&init_mm, current);
6073 * Make us the idle thread. Technically, schedule() should not be
6074 * called from this thread, however somewhere below it might be,
6075 * but because we are the idle thread, we just pick up running again
6076 * when this runqueue becomes "idle".
6078 init_idle(current, smp_processor_id());
6080 calc_load_update = jiffies + LOAD_FREQ;
6083 idle_thread_set_boot_cpu();
6085 init_sched_fair_class();
6091 scheduler_running = 1;
6094 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
6095 static inline int preempt_count_equals(int preempt_offset)
6097 int nested = preempt_count() + rcu_preempt_depth();
6099 return (nested == preempt_offset);
6102 void __might_sleep(const char *file, int line, int preempt_offset)
6105 * Blocking primitives will set (and therefore destroy) current->state,
6106 * since we will exit with TASK_RUNNING make sure we enter with it,
6107 * otherwise we will destroy state.
6109 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
6110 "do not call blocking ops when !TASK_RUNNING; "
6111 "state=%lx set at [<%p>] %pS\n",
6113 (void *)current->task_state_change,
6114 (void *)current->task_state_change);
6116 ___might_sleep(file, line, preempt_offset);
6118 EXPORT_SYMBOL(__might_sleep);
6120 void ___might_sleep(const char *file, int line, int preempt_offset)
6122 /* Ratelimiting timestamp: */
6123 static unsigned long prev_jiffy;
6125 unsigned long preempt_disable_ip;
6127 /* WARN_ON_ONCE() by default, no rate limit required: */
6130 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6131 !is_idle_task(current)) ||
6132 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
6136 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6138 prev_jiffy = jiffies;
6140 /* Save this before calling printk(), since that will clobber it: */
6141 preempt_disable_ip = get_preempt_disable_ip(current);
6144 "BUG: sleeping function called from invalid context at %s:%d\n",
6147 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6148 in_atomic(), irqs_disabled(),
6149 current->pid, current->comm);
6151 if (task_stack_end_corrupted(current))
6152 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6154 debug_show_held_locks(current);
6155 if (irqs_disabled())
6156 print_irqtrace_events(current);
6157 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6158 && !preempt_count_equals(preempt_offset)) {
6159 pr_err("Preemption disabled at:");
6160 print_ip_sym(preempt_disable_ip);
6164 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6166 EXPORT_SYMBOL(___might_sleep);
6169 #ifdef CONFIG_MAGIC_SYSRQ
6170 void normalize_rt_tasks(void)
6172 struct task_struct *g, *p;
6173 struct sched_attr attr = {
6174 .sched_policy = SCHED_NORMAL,
6177 read_lock(&tasklist_lock);
6178 for_each_process_thread(g, p) {
6180 * Only normalize user tasks:
6182 if (p->flags & PF_KTHREAD)
6185 p->se.exec_start = 0;
6186 schedstat_set(p->se.statistics.wait_start, 0);
6187 schedstat_set(p->se.statistics.sleep_start, 0);
6188 schedstat_set(p->se.statistics.block_start, 0);
6190 if (!dl_task(p) && !rt_task(p)) {
6192 * Renice negative nice level userspace
6195 if (task_nice(p) < 0)
6196 set_user_nice(p, 0);
6200 __sched_setscheduler(p, &attr, false, false);
6202 read_unlock(&tasklist_lock);
6205 #endif /* CONFIG_MAGIC_SYSRQ */
6207 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
6209 * These functions are only useful for the IA64 MCA handling, or kdb.
6211 * They can only be called when the whole system has been
6212 * stopped - every CPU needs to be quiescent, and no scheduling
6213 * activity can take place. Using them for anything else would
6214 * be a serious bug, and as a result, they aren't even visible
6215 * under any other configuration.
6219 * curr_task - return the current task for a given CPU.
6220 * @cpu: the processor in question.
6222 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6224 * Return: The current task for @cpu.
6226 struct task_struct *curr_task(int cpu)
6228 return cpu_curr(cpu);
6231 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6235 * set_curr_task - set the current task for a given CPU.
6236 * @cpu: the processor in question.
6237 * @p: the task pointer to set.
6239 * Description: This function must only be used when non-maskable interrupts
6240 * are serviced on a separate stack. It allows the architecture to switch the
6241 * notion of the current task on a CPU in a non-blocking manner. This function
6242 * must be called with all CPU's synchronized, and interrupts disabled, the
6243 * and caller must save the original value of the current task (see
6244 * curr_task() above) and restore that value before reenabling interrupts and
6245 * re-starting the system.
6247 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6249 void ia64_set_curr_task(int cpu, struct task_struct *p)
6256 #ifdef CONFIG_CGROUP_SCHED
6257 /* task_group_lock serializes the addition/removal of task groups */
6258 static DEFINE_SPINLOCK(task_group_lock);
6260 static void sched_free_group(struct task_group *tg)
6262 free_fair_sched_group(tg);
6263 free_rt_sched_group(tg);
6265 kmem_cache_free(task_group_cache, tg);
6268 /* allocate runqueue etc for a new task group */
6269 struct task_group *sched_create_group(struct task_group *parent)
6271 struct task_group *tg;
6273 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
6275 return ERR_PTR(-ENOMEM);
6277 if (!alloc_fair_sched_group(tg, parent))
6280 if (!alloc_rt_sched_group(tg, parent))
6286 sched_free_group(tg);
6287 return ERR_PTR(-ENOMEM);
6290 void sched_online_group(struct task_group *tg, struct task_group *parent)
6292 unsigned long flags;
6294 spin_lock_irqsave(&task_group_lock, flags);
6295 list_add_rcu(&tg->list, &task_groups);
6297 /* Root should already exist: */
6300 tg->parent = parent;
6301 INIT_LIST_HEAD(&tg->children);
6302 list_add_rcu(&tg->siblings, &parent->children);
6303 spin_unlock_irqrestore(&task_group_lock, flags);
6305 online_fair_sched_group(tg);
6308 /* rcu callback to free various structures associated with a task group */
6309 static void sched_free_group_rcu(struct rcu_head *rhp)
6311 /* Now it should be safe to free those cfs_rqs: */
6312 sched_free_group(container_of(rhp, struct task_group, rcu));
6315 void sched_destroy_group(struct task_group *tg)
6317 /* Wait for possible concurrent references to cfs_rqs complete: */
6318 call_rcu(&tg->rcu, sched_free_group_rcu);
6321 void sched_offline_group(struct task_group *tg)
6323 unsigned long flags;
6325 /* End participation in shares distribution: */
6326 unregister_fair_sched_group(tg);
6328 spin_lock_irqsave(&task_group_lock, flags);
6329 list_del_rcu(&tg->list);
6330 list_del_rcu(&tg->siblings);
6331 spin_unlock_irqrestore(&task_group_lock, flags);
6334 static void sched_change_group(struct task_struct *tsk, int type)
6336 struct task_group *tg;
6339 * All callers are synchronized by task_rq_lock(); we do not use RCU
6340 * which is pointless here. Thus, we pass "true" to task_css_check()
6341 * to prevent lockdep warnings.
6343 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
6344 struct task_group, css);
6345 tg = autogroup_task_group(tsk, tg);
6346 tsk->sched_task_group = tg;
6348 #ifdef CONFIG_FAIR_GROUP_SCHED
6349 if (tsk->sched_class->task_change_group)
6350 tsk->sched_class->task_change_group(tsk, type);
6353 set_task_rq(tsk, task_cpu(tsk));
6357 * Change task's runqueue when it moves between groups.
6359 * The caller of this function should have put the task in its new group by
6360 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6363 void sched_move_task(struct task_struct *tsk)
6365 int queued, running, queue_flags =
6366 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6370 rq = task_rq_lock(tsk, &rf);
6371 update_rq_clock(rq);
6373 running = task_current(rq, tsk);
6374 queued = task_on_rq_queued(tsk);
6377 dequeue_task(rq, tsk, queue_flags);
6379 put_prev_task(rq, tsk);
6381 sched_change_group(tsk, TASK_MOVE_GROUP);
6384 enqueue_task(rq, tsk, queue_flags);
6386 set_curr_task(rq, tsk);
6388 task_rq_unlock(rq, tsk, &rf);
6391 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
6393 return css ? container_of(css, struct task_group, css) : NULL;
6396 static struct cgroup_subsys_state *
6397 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6399 struct task_group *parent = css_tg(parent_css);
6400 struct task_group *tg;
6403 /* This is early initialization for the top cgroup */
6404 return &root_task_group.css;
6407 tg = sched_create_group(parent);
6409 return ERR_PTR(-ENOMEM);
6414 /* Expose task group only after completing cgroup initialization */
6415 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6417 struct task_group *tg = css_tg(css);
6418 struct task_group *parent = css_tg(css->parent);
6421 sched_online_group(tg, parent);
6425 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
6427 struct task_group *tg = css_tg(css);
6429 sched_offline_group(tg);
6432 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
6434 struct task_group *tg = css_tg(css);
6437 * Relies on the RCU grace period between css_released() and this.
6439 sched_free_group(tg);
6443 * This is called before wake_up_new_task(), therefore we really only
6444 * have to set its group bits, all the other stuff does not apply.
6446 static void cpu_cgroup_fork(struct task_struct *task)
6451 rq = task_rq_lock(task, &rf);
6453 update_rq_clock(rq);
6454 sched_change_group(task, TASK_SET_GROUP);
6456 task_rq_unlock(rq, task, &rf);
6459 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
6461 struct task_struct *task;
6462 struct cgroup_subsys_state *css;
6465 cgroup_taskset_for_each(task, css, tset) {
6466 #ifdef CONFIG_RT_GROUP_SCHED
6467 if (!sched_rt_can_attach(css_tg(css), task))
6470 /* We don't support RT-tasks being in separate groups */
6471 if (task->sched_class != &fair_sched_class)
6475 * Serialize against wake_up_new_task() such that if its
6476 * running, we're sure to observe its full state.
6478 raw_spin_lock_irq(&task->pi_lock);
6480 * Avoid calling sched_move_task() before wake_up_new_task()
6481 * has happened. This would lead to problems with PELT, due to
6482 * move wanting to detach+attach while we're not attached yet.
6484 if (task->state == TASK_NEW)
6486 raw_spin_unlock_irq(&task->pi_lock);
6494 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
6496 struct task_struct *task;
6497 struct cgroup_subsys_state *css;
6499 cgroup_taskset_for_each(task, css, tset)
6500 sched_move_task(task);
6503 #ifdef CONFIG_FAIR_GROUP_SCHED
6504 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6505 struct cftype *cftype, u64 shareval)
6507 return sched_group_set_shares(css_tg(css), scale_load(shareval));
6510 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6513 struct task_group *tg = css_tg(css);
6515 return (u64) scale_load_down(tg->shares);
6518 #ifdef CONFIG_CFS_BANDWIDTH
6519 static DEFINE_MUTEX(cfs_constraints_mutex);
6521 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6522 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6524 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6526 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6528 int i, ret = 0, runtime_enabled, runtime_was_enabled;
6529 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6531 if (tg == &root_task_group)
6535 * Ensure we have at some amount of bandwidth every period. This is
6536 * to prevent reaching a state of large arrears when throttled via
6537 * entity_tick() resulting in prolonged exit starvation.
6539 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6543 * Likewise, bound things on the otherside by preventing insane quota
6544 * periods. This also allows us to normalize in computing quota
6547 if (period > max_cfs_quota_period)
6551 * Prevent race between setting of cfs_rq->runtime_enabled and
6552 * unthrottle_offline_cfs_rqs().
6555 mutex_lock(&cfs_constraints_mutex);
6556 ret = __cfs_schedulable(tg, period, quota);
6560 runtime_enabled = quota != RUNTIME_INF;
6561 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
6563 * If we need to toggle cfs_bandwidth_used, off->on must occur
6564 * before making related changes, and on->off must occur afterwards
6566 if (runtime_enabled && !runtime_was_enabled)
6567 cfs_bandwidth_usage_inc();
6568 raw_spin_lock_irq(&cfs_b->lock);
6569 cfs_b->period = ns_to_ktime(period);
6570 cfs_b->quota = quota;
6572 __refill_cfs_bandwidth_runtime(cfs_b);
6574 /* Restart the period timer (if active) to handle new period expiry: */
6575 if (runtime_enabled)
6576 start_cfs_bandwidth(cfs_b);
6578 raw_spin_unlock_irq(&cfs_b->lock);
6580 for_each_online_cpu(i) {
6581 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
6582 struct rq *rq = cfs_rq->rq;
6585 rq_lock_irq(rq, &rf);
6586 cfs_rq->runtime_enabled = runtime_enabled;
6587 cfs_rq->runtime_remaining = 0;
6589 if (cfs_rq->throttled)
6590 unthrottle_cfs_rq(cfs_rq);
6591 rq_unlock_irq(rq, &rf);
6593 if (runtime_was_enabled && !runtime_enabled)
6594 cfs_bandwidth_usage_dec();
6596 mutex_unlock(&cfs_constraints_mutex);
6602 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
6606 period = ktime_to_ns(tg->cfs_bandwidth.period);
6607 if (cfs_quota_us < 0)
6608 quota = RUNTIME_INF;
6610 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
6612 return tg_set_cfs_bandwidth(tg, period, quota);
6615 long tg_get_cfs_quota(struct task_group *tg)
6619 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
6622 quota_us = tg->cfs_bandwidth.quota;
6623 do_div(quota_us, NSEC_PER_USEC);
6628 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
6632 period = (u64)cfs_period_us * NSEC_PER_USEC;
6633 quota = tg->cfs_bandwidth.quota;
6635 return tg_set_cfs_bandwidth(tg, period, quota);
6638 long tg_get_cfs_period(struct task_group *tg)
6642 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
6643 do_div(cfs_period_us, NSEC_PER_USEC);
6645 return cfs_period_us;
6648 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
6651 return tg_get_cfs_quota(css_tg(css));
6654 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
6655 struct cftype *cftype, s64 cfs_quota_us)
6657 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
6660 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
6663 return tg_get_cfs_period(css_tg(css));
6666 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
6667 struct cftype *cftype, u64 cfs_period_us)
6669 return tg_set_cfs_period(css_tg(css), cfs_period_us);
6672 struct cfs_schedulable_data {
6673 struct task_group *tg;
6678 * normalize group quota/period to be quota/max_period
6679 * note: units are usecs
6681 static u64 normalize_cfs_quota(struct task_group *tg,
6682 struct cfs_schedulable_data *d)
6690 period = tg_get_cfs_period(tg);
6691 quota = tg_get_cfs_quota(tg);
6694 /* note: these should typically be equivalent */
6695 if (quota == RUNTIME_INF || quota == -1)
6698 return to_ratio(period, quota);
6701 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
6703 struct cfs_schedulable_data *d = data;
6704 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6705 s64 quota = 0, parent_quota = -1;
6708 quota = RUNTIME_INF;
6710 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
6712 quota = normalize_cfs_quota(tg, d);
6713 parent_quota = parent_b->hierarchical_quota;
6716 * Ensure max(child_quota) <= parent_quota. On cgroup2,
6717 * always take the min. On cgroup1, only inherit when no
6720 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
6721 quota = min(quota, parent_quota);
6723 if (quota == RUNTIME_INF)
6724 quota = parent_quota;
6725 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
6729 cfs_b->hierarchical_quota = quota;
6734 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
6737 struct cfs_schedulable_data data = {
6743 if (quota != RUNTIME_INF) {
6744 do_div(data.period, NSEC_PER_USEC);
6745 do_div(data.quota, NSEC_PER_USEC);
6749 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
6755 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
6757 struct task_group *tg = css_tg(seq_css(sf));
6758 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6760 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
6761 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
6762 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
6764 if (schedstat_enabled() && tg != &root_task_group) {
6768 for_each_possible_cpu(i)
6769 ws += schedstat_val(tg->se[i]->statistics.wait_sum);
6771 seq_printf(sf, "wait_sum %llu\n", ws);
6776 #endif /* CONFIG_CFS_BANDWIDTH */
6777 #endif /* CONFIG_FAIR_GROUP_SCHED */
6779 #ifdef CONFIG_RT_GROUP_SCHED
6780 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
6781 struct cftype *cft, s64 val)
6783 return sched_group_set_rt_runtime(css_tg(css), val);
6786 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
6789 return sched_group_rt_runtime(css_tg(css));
6792 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
6793 struct cftype *cftype, u64 rt_period_us)
6795 return sched_group_set_rt_period(css_tg(css), rt_period_us);
6798 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
6801 return sched_group_rt_period(css_tg(css));
6803 #endif /* CONFIG_RT_GROUP_SCHED */
6805 static struct cftype cpu_legacy_files[] = {
6806 #ifdef CONFIG_FAIR_GROUP_SCHED
6809 .read_u64 = cpu_shares_read_u64,
6810 .write_u64 = cpu_shares_write_u64,
6813 #ifdef CONFIG_CFS_BANDWIDTH
6815 .name = "cfs_quota_us",
6816 .read_s64 = cpu_cfs_quota_read_s64,
6817 .write_s64 = cpu_cfs_quota_write_s64,
6820 .name = "cfs_period_us",
6821 .read_u64 = cpu_cfs_period_read_u64,
6822 .write_u64 = cpu_cfs_period_write_u64,
6826 .seq_show = cpu_cfs_stat_show,
6829 #ifdef CONFIG_RT_GROUP_SCHED
6831 .name = "rt_runtime_us",
6832 .read_s64 = cpu_rt_runtime_read,
6833 .write_s64 = cpu_rt_runtime_write,
6836 .name = "rt_period_us",
6837 .read_u64 = cpu_rt_period_read_uint,
6838 .write_u64 = cpu_rt_period_write_uint,
6844 static int cpu_extra_stat_show(struct seq_file *sf,
6845 struct cgroup_subsys_state *css)
6847 #ifdef CONFIG_CFS_BANDWIDTH
6849 struct task_group *tg = css_tg(css);
6850 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6853 throttled_usec = cfs_b->throttled_time;
6854 do_div(throttled_usec, NSEC_PER_USEC);
6856 seq_printf(sf, "nr_periods %d\n"
6858 "throttled_usec %llu\n",
6859 cfs_b->nr_periods, cfs_b->nr_throttled,
6866 #ifdef CONFIG_FAIR_GROUP_SCHED
6867 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
6870 struct task_group *tg = css_tg(css);
6871 u64 weight = scale_load_down(tg->shares);
6873 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
6876 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
6877 struct cftype *cft, u64 weight)
6880 * cgroup weight knobs should use the common MIN, DFL and MAX
6881 * values which are 1, 100 and 10000 respectively. While it loses
6882 * a bit of range on both ends, it maps pretty well onto the shares
6883 * value used by scheduler and the round-trip conversions preserve
6884 * the original value over the entire range.
6886 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
6889 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
6891 return sched_group_set_shares(css_tg(css), scale_load(weight));
6894 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
6897 unsigned long weight = scale_load_down(css_tg(css)->shares);
6898 int last_delta = INT_MAX;
6901 /* find the closest nice value to the current weight */
6902 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
6903 delta = abs(sched_prio_to_weight[prio] - weight);
6904 if (delta >= last_delta)
6909 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
6912 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
6913 struct cftype *cft, s64 nice)
6915 unsigned long weight;
6918 if (nice < MIN_NICE || nice > MAX_NICE)
6921 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
6922 idx = array_index_nospec(idx, 40);
6923 weight = sched_prio_to_weight[idx];
6925 return sched_group_set_shares(css_tg(css), scale_load(weight));
6929 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
6930 long period, long quota)
6933 seq_puts(sf, "max");
6935 seq_printf(sf, "%ld", quota);
6937 seq_printf(sf, " %ld\n", period);
6940 /* caller should put the current value in *@periodp before calling */
6941 static int __maybe_unused cpu_period_quota_parse(char *buf,
6942 u64 *periodp, u64 *quotap)
6944 char tok[21]; /* U64_MAX */
6946 if (!sscanf(buf, "%s %llu", tok, periodp))
6949 *periodp *= NSEC_PER_USEC;
6951 if (sscanf(tok, "%llu", quotap))
6952 *quotap *= NSEC_PER_USEC;
6953 else if (!strcmp(tok, "max"))
6954 *quotap = RUNTIME_INF;
6961 #ifdef CONFIG_CFS_BANDWIDTH
6962 static int cpu_max_show(struct seq_file *sf, void *v)
6964 struct task_group *tg = css_tg(seq_css(sf));
6966 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
6970 static ssize_t cpu_max_write(struct kernfs_open_file *of,
6971 char *buf, size_t nbytes, loff_t off)
6973 struct task_group *tg = css_tg(of_css(of));
6974 u64 period = tg_get_cfs_period(tg);
6978 ret = cpu_period_quota_parse(buf, &period, "a);
6980 ret = tg_set_cfs_bandwidth(tg, period, quota);
6981 return ret ?: nbytes;
6985 static struct cftype cpu_files[] = {
6986 #ifdef CONFIG_FAIR_GROUP_SCHED
6989 .flags = CFTYPE_NOT_ON_ROOT,
6990 .read_u64 = cpu_weight_read_u64,
6991 .write_u64 = cpu_weight_write_u64,
6994 .name = "weight.nice",
6995 .flags = CFTYPE_NOT_ON_ROOT,
6996 .read_s64 = cpu_weight_nice_read_s64,
6997 .write_s64 = cpu_weight_nice_write_s64,
7000 #ifdef CONFIG_CFS_BANDWIDTH
7003 .flags = CFTYPE_NOT_ON_ROOT,
7004 .seq_show = cpu_max_show,
7005 .write = cpu_max_write,
7011 struct cgroup_subsys cpu_cgrp_subsys = {
7012 .css_alloc = cpu_cgroup_css_alloc,
7013 .css_online = cpu_cgroup_css_online,
7014 .css_released = cpu_cgroup_css_released,
7015 .css_free = cpu_cgroup_css_free,
7016 .css_extra_stat_show = cpu_extra_stat_show,
7017 .fork = cpu_cgroup_fork,
7018 .can_attach = cpu_cgroup_can_attach,
7019 .attach = cpu_cgroup_attach,
7020 .legacy_cftypes = cpu_legacy_files,
7021 .dfl_cftypes = cpu_files,
7026 #endif /* CONFIG_CGROUP_SCHED */
7028 void dump_cpu_task(int cpu)
7030 pr_info("Task dump for CPU %d:\n", cpu);
7031 sched_show_task(cpu_curr(cpu));
7035 * Nice levels are multiplicative, with a gentle 10% change for every
7036 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
7037 * nice 1, it will get ~10% less CPU time than another CPU-bound task
7038 * that remained on nice 0.
7040 * The "10% effect" is relative and cumulative: from _any_ nice level,
7041 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
7042 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
7043 * If a task goes up by ~10% and another task goes down by ~10% then
7044 * the relative distance between them is ~25%.)
7046 const int sched_prio_to_weight[40] = {
7047 /* -20 */ 88761, 71755, 56483, 46273, 36291,
7048 /* -15 */ 29154, 23254, 18705, 14949, 11916,
7049 /* -10 */ 9548, 7620, 6100, 4904, 3906,
7050 /* -5 */ 3121, 2501, 1991, 1586, 1277,
7051 /* 0 */ 1024, 820, 655, 526, 423,
7052 /* 5 */ 335, 272, 215, 172, 137,
7053 /* 10 */ 110, 87, 70, 56, 45,
7054 /* 15 */ 36, 29, 23, 18, 15,
7058 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
7060 * In cases where the weight does not change often, we can use the
7061 * precalculated inverse to speed up arithmetics by turning divisions
7062 * into multiplications:
7064 const u32 sched_prio_to_wmult[40] = {
7065 /* -20 */ 48388, 59856, 76040, 92818, 118348,
7066 /* -15 */ 147320, 184698, 229616, 287308, 360437,
7067 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
7068 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
7069 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
7070 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
7071 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
7072 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
7075 #undef CREATE_TRACE_POINTS