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"
20 #define CREATE_TRACE_POINTS
21 #include <trace/events/sched.h>
23 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
25 #if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL)
27 * Debugging: various feature bits
29 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
30 * sysctl_sched_features, defined in sched.h, to allow constants propagation
31 * at compile time and compiler optimization based on features default.
33 #define SCHED_FEAT(name, enabled) \
34 (1UL << __SCHED_FEAT_##name) * enabled |
35 const_debug unsigned int sysctl_sched_features =
42 * Number of tasks to iterate in a single balance run.
43 * Limited because this is done with IRQs disabled.
45 const_debug unsigned int sysctl_sched_nr_migrate = 32;
48 * period over which we average the RT time consumption, measured
53 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
56 * period over which we measure -rt task CPU usage in us.
59 unsigned int sysctl_sched_rt_period = 1000000;
61 __read_mostly int scheduler_running;
64 * part of the period that we allow rt tasks to run in us.
67 int sysctl_sched_rt_runtime = 950000;
70 * __task_rq_lock - lock the rq @p resides on.
72 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
77 lockdep_assert_held(&p->pi_lock);
81 raw_spin_lock(&rq->lock);
82 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
86 raw_spin_unlock(&rq->lock);
88 while (unlikely(task_on_rq_migrating(p)))
94 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
96 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
97 __acquires(p->pi_lock)
103 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
105 raw_spin_lock(&rq->lock);
107 * move_queued_task() task_rq_lock()
110 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
111 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
112 * [S] ->cpu = new_cpu [L] task_rq()
116 * If we observe the old CPU in task_rq_lock, the acquire of
117 * the old rq->lock will fully serialize against the stores.
119 * If we observe the new CPU in task_rq_lock, the acquire will
120 * pair with the WMB to ensure we must then also see migrating.
122 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
126 raw_spin_unlock(&rq->lock);
127 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
129 while (unlikely(task_on_rq_migrating(p)))
135 * RQ-clock updating methods:
138 static void update_rq_clock_task(struct rq *rq, s64 delta)
141 * In theory, the compile should just see 0 here, and optimize out the call
142 * to sched_rt_avg_update. But I don't trust it...
144 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
145 s64 steal = 0, irq_delta = 0;
147 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
148 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
151 * Since irq_time is only updated on {soft,}irq_exit, we might run into
152 * this case when a previous update_rq_clock() happened inside a
155 * When this happens, we stop ->clock_task and only update the
156 * prev_irq_time stamp to account for the part that fit, so that a next
157 * update will consume the rest. This ensures ->clock_task is
160 * It does however cause some slight miss-attribution of {soft,}irq
161 * time, a more accurate solution would be to update the irq_time using
162 * the current rq->clock timestamp, except that would require using
165 if (irq_delta > delta)
168 rq->prev_irq_time += irq_delta;
171 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
172 if (static_key_false((¶virt_steal_rq_enabled))) {
173 steal = paravirt_steal_clock(cpu_of(rq));
174 steal -= rq->prev_steal_time_rq;
176 if (unlikely(steal > delta))
179 rq->prev_steal_time_rq += steal;
184 rq->clock_task += delta;
186 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
187 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
188 sched_rt_avg_update(rq, irq_delta + steal);
192 void update_rq_clock(struct rq *rq)
196 lockdep_assert_held(&rq->lock);
198 if (rq->clock_update_flags & RQCF_ACT_SKIP)
201 #ifdef CONFIG_SCHED_DEBUG
202 if (sched_feat(WARN_DOUBLE_CLOCK))
203 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
204 rq->clock_update_flags |= RQCF_UPDATED;
207 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
211 update_rq_clock_task(rq, delta);
215 #ifdef CONFIG_SCHED_HRTICK
217 * Use HR-timers to deliver accurate preemption points.
220 static void hrtick_clear(struct rq *rq)
222 if (hrtimer_active(&rq->hrtick_timer))
223 hrtimer_cancel(&rq->hrtick_timer);
227 * High-resolution timer tick.
228 * Runs from hardirq context with interrupts disabled.
230 static enum hrtimer_restart hrtick(struct hrtimer *timer)
232 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
235 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
239 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
242 return HRTIMER_NORESTART;
247 static void __hrtick_restart(struct rq *rq)
249 struct hrtimer *timer = &rq->hrtick_timer;
251 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
255 * called from hardirq (IPI) context
257 static void __hrtick_start(void *arg)
263 __hrtick_restart(rq);
264 rq->hrtick_csd_pending = 0;
269 * Called to set the hrtick timer state.
271 * called with rq->lock held and irqs disabled
273 void hrtick_start(struct rq *rq, u64 delay)
275 struct hrtimer *timer = &rq->hrtick_timer;
280 * Don't schedule slices shorter than 10000ns, that just
281 * doesn't make sense and can cause timer DoS.
283 delta = max_t(s64, delay, 10000LL);
284 time = ktime_add_ns(timer->base->get_time(), delta);
286 hrtimer_set_expires(timer, time);
288 if (rq == this_rq()) {
289 __hrtick_restart(rq);
290 } else if (!rq->hrtick_csd_pending) {
291 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
292 rq->hrtick_csd_pending = 1;
298 * Called to set the hrtick timer state.
300 * called with rq->lock held and irqs disabled
302 void hrtick_start(struct rq *rq, u64 delay)
305 * Don't schedule slices shorter than 10000ns, that just
306 * doesn't make sense. Rely on vruntime for fairness.
308 delay = max_t(u64, delay, 10000LL);
309 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
310 HRTIMER_MODE_REL_PINNED);
312 #endif /* CONFIG_SMP */
314 static void hrtick_rq_init(struct rq *rq)
317 rq->hrtick_csd_pending = 0;
319 rq->hrtick_csd.flags = 0;
320 rq->hrtick_csd.func = __hrtick_start;
321 rq->hrtick_csd.info = rq;
324 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
325 rq->hrtick_timer.function = hrtick;
327 #else /* CONFIG_SCHED_HRTICK */
328 static inline void hrtick_clear(struct rq *rq)
332 static inline void hrtick_rq_init(struct rq *rq)
335 #endif /* CONFIG_SCHED_HRTICK */
338 * cmpxchg based fetch_or, macro so it works for different integer types
340 #define fetch_or(ptr, mask) \
342 typeof(ptr) _ptr = (ptr); \
343 typeof(mask) _mask = (mask); \
344 typeof(*_ptr) _old, _val = *_ptr; \
347 _old = cmpxchg(_ptr, _val, _val | _mask); \
355 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
357 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
358 * this avoids any races wrt polling state changes and thereby avoids
361 static bool set_nr_and_not_polling(struct task_struct *p)
363 struct thread_info *ti = task_thread_info(p);
364 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
368 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
370 * If this returns true, then the idle task promises to call
371 * sched_ttwu_pending() and reschedule soon.
373 static bool set_nr_if_polling(struct task_struct *p)
375 struct thread_info *ti = task_thread_info(p);
376 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
379 if (!(val & _TIF_POLLING_NRFLAG))
381 if (val & _TIF_NEED_RESCHED)
383 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
392 static bool set_nr_and_not_polling(struct task_struct *p)
394 set_tsk_need_resched(p);
399 static bool set_nr_if_polling(struct task_struct *p)
406 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
408 struct wake_q_node *node = &task->wake_q;
411 * Atomically grab the task, if ->wake_q is !nil already it means
412 * its already queued (either by us or someone else) and will get the
413 * wakeup due to that.
415 * This cmpxchg() implies a full barrier, which pairs with the write
416 * barrier implied by the wakeup in wake_up_q().
418 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
421 get_task_struct(task);
424 * The head is context local, there can be no concurrency.
427 head->lastp = &node->next;
430 void wake_up_q(struct wake_q_head *head)
432 struct wake_q_node *node = head->first;
434 while (node != WAKE_Q_TAIL) {
435 struct task_struct *task;
437 task = container_of(node, struct task_struct, wake_q);
439 /* Task can safely be re-inserted now: */
441 task->wake_q.next = NULL;
444 * wake_up_process() implies a wmb() to pair with the queueing
445 * in wake_q_add() so as not to miss wakeups.
447 wake_up_process(task);
448 put_task_struct(task);
453 * resched_curr - mark rq's current task 'to be rescheduled now'.
455 * On UP this means the setting of the need_resched flag, on SMP it
456 * might also involve a cross-CPU call to trigger the scheduler on
459 void resched_curr(struct rq *rq)
461 struct task_struct *curr = rq->curr;
464 lockdep_assert_held(&rq->lock);
466 if (test_tsk_need_resched(curr))
471 if (cpu == smp_processor_id()) {
472 set_tsk_need_resched(curr);
473 set_preempt_need_resched();
477 if (set_nr_and_not_polling(curr))
478 smp_send_reschedule(cpu);
480 trace_sched_wake_idle_without_ipi(cpu);
483 void resched_cpu(int cpu)
485 struct rq *rq = cpu_rq(cpu);
488 raw_spin_lock_irqsave(&rq->lock, flags);
489 if (cpu_online(cpu) || cpu == smp_processor_id())
491 raw_spin_unlock_irqrestore(&rq->lock, flags);
495 #ifdef CONFIG_NO_HZ_COMMON
497 * In the semi idle case, use the nearest busy CPU for migrating timers
498 * from an idle CPU. This is good for power-savings.
500 * We don't do similar optimization for completely idle system, as
501 * selecting an idle CPU will add more delays to the timers than intended
502 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
504 int get_nohz_timer_target(void)
506 int i, cpu = smp_processor_id();
507 struct sched_domain *sd;
509 if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
513 for_each_domain(cpu, sd) {
514 for_each_cpu(i, sched_domain_span(sd)) {
518 if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
525 if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
526 cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
533 * When add_timer_on() enqueues a timer into the timer wheel of an
534 * idle CPU then this timer might expire before the next timer event
535 * which is scheduled to wake up that CPU. In case of a completely
536 * idle system the next event might even be infinite time into the
537 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
538 * leaves the inner idle loop so the newly added timer is taken into
539 * account when the CPU goes back to idle and evaluates the timer
540 * wheel for the next timer event.
542 static void wake_up_idle_cpu(int cpu)
544 struct rq *rq = cpu_rq(cpu);
546 if (cpu == smp_processor_id())
549 if (set_nr_and_not_polling(rq->idle))
550 smp_send_reschedule(cpu);
552 trace_sched_wake_idle_without_ipi(cpu);
555 static bool wake_up_full_nohz_cpu(int cpu)
558 * We just need the target to call irq_exit() and re-evaluate
559 * the next tick. The nohz full kick at least implies that.
560 * If needed we can still optimize that later with an
563 if (cpu_is_offline(cpu))
564 return true; /* Don't try to wake offline CPUs. */
565 if (tick_nohz_full_cpu(cpu)) {
566 if (cpu != smp_processor_id() ||
567 tick_nohz_tick_stopped())
568 tick_nohz_full_kick_cpu(cpu);
576 * Wake up the specified CPU. If the CPU is going offline, it is the
577 * caller's responsibility to deal with the lost wakeup, for example,
578 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
580 void wake_up_nohz_cpu(int cpu)
582 if (!wake_up_full_nohz_cpu(cpu))
583 wake_up_idle_cpu(cpu);
586 static inline bool got_nohz_idle_kick(void)
588 int cpu = smp_processor_id();
590 if (!(atomic_read(nohz_flags(cpu)) & NOHZ_KICK_MASK))
593 if (idle_cpu(cpu) && !need_resched())
597 * We can't run Idle Load Balance on this CPU for this time so we
598 * cancel it and clear NOHZ_BALANCE_KICK
600 atomic_andnot(NOHZ_KICK_MASK, nohz_flags(cpu));
604 #else /* CONFIG_NO_HZ_COMMON */
606 static inline bool got_nohz_idle_kick(void)
611 #endif /* CONFIG_NO_HZ_COMMON */
613 #ifdef CONFIG_NO_HZ_FULL
614 bool sched_can_stop_tick(struct rq *rq)
618 /* Deadline tasks, even if single, need the tick */
619 if (rq->dl.dl_nr_running)
623 * If there are more than one RR tasks, we need the tick to effect the
624 * actual RR behaviour.
626 if (rq->rt.rr_nr_running) {
627 if (rq->rt.rr_nr_running == 1)
634 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
635 * forced preemption between FIFO tasks.
637 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
642 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
643 * if there's more than one we need the tick for involuntary
646 if (rq->nr_running > 1)
651 #endif /* CONFIG_NO_HZ_FULL */
653 void sched_avg_update(struct rq *rq)
655 s64 period = sched_avg_period();
657 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
659 * Inline assembly required to prevent the compiler
660 * optimising this loop into a divmod call.
661 * See __iter_div_u64_rem() for another example of this.
663 asm("" : "+rm" (rq->age_stamp));
664 rq->age_stamp += period;
669 #endif /* CONFIG_SMP */
671 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
672 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
674 * Iterate task_group tree rooted at *from, calling @down when first entering a
675 * node and @up when leaving it for the final time.
677 * Caller must hold rcu_lock or sufficient equivalent.
679 int walk_tg_tree_from(struct task_group *from,
680 tg_visitor down, tg_visitor up, void *data)
682 struct task_group *parent, *child;
688 ret = (*down)(parent, data);
691 list_for_each_entry_rcu(child, &parent->children, siblings) {
698 ret = (*up)(parent, data);
699 if (ret || parent == from)
703 parent = parent->parent;
710 int tg_nop(struct task_group *tg, void *data)
716 static void set_load_weight(struct task_struct *p, bool update_load)
718 int prio = p->static_prio - MAX_RT_PRIO;
719 struct load_weight *load = &p->se.load;
722 * SCHED_IDLE tasks get minimal weight:
724 if (idle_policy(p->policy)) {
725 load->weight = scale_load(WEIGHT_IDLEPRIO);
726 load->inv_weight = WMULT_IDLEPRIO;
731 * SCHED_OTHER tasks have to update their load when changing their
734 if (update_load && p->sched_class == &fair_sched_class) {
735 reweight_task(p, prio);
737 load->weight = scale_load(sched_prio_to_weight[prio]);
738 load->inv_weight = sched_prio_to_wmult[prio];
742 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
744 if (!(flags & ENQUEUE_NOCLOCK))
747 if (!(flags & ENQUEUE_RESTORE))
748 sched_info_queued(rq, p);
750 p->sched_class->enqueue_task(rq, p, flags);
753 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
755 if (!(flags & DEQUEUE_NOCLOCK))
758 if (!(flags & DEQUEUE_SAVE))
759 sched_info_dequeued(rq, p);
761 p->sched_class->dequeue_task(rq, p, flags);
764 void activate_task(struct rq *rq, struct task_struct *p, int flags)
766 if (task_contributes_to_load(p))
767 rq->nr_uninterruptible--;
769 enqueue_task(rq, p, flags);
772 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
774 if (task_contributes_to_load(p))
775 rq->nr_uninterruptible++;
777 dequeue_task(rq, p, flags);
781 * __normal_prio - return the priority that is based on the static prio
783 static inline int __normal_prio(struct task_struct *p)
785 return p->static_prio;
789 * Calculate the expected normal priority: i.e. priority
790 * without taking RT-inheritance into account. Might be
791 * boosted by interactivity modifiers. Changes upon fork,
792 * setprio syscalls, and whenever the interactivity
793 * estimator recalculates.
795 static inline int normal_prio(struct task_struct *p)
799 if (task_has_dl_policy(p))
800 prio = MAX_DL_PRIO-1;
801 else if (task_has_rt_policy(p))
802 prio = MAX_RT_PRIO-1 - p->rt_priority;
804 prio = __normal_prio(p);
809 * Calculate the current priority, i.e. the priority
810 * taken into account by the scheduler. This value might
811 * be boosted by RT tasks, or might be boosted by
812 * interactivity modifiers. Will be RT if the task got
813 * RT-boosted. If not then it returns p->normal_prio.
815 static int effective_prio(struct task_struct *p)
817 p->normal_prio = normal_prio(p);
819 * If we are RT tasks or we were boosted to RT priority,
820 * keep the priority unchanged. Otherwise, update priority
821 * to the normal priority:
823 if (!rt_prio(p->prio))
824 return p->normal_prio;
829 * task_curr - is this task currently executing on a CPU?
830 * @p: the task in question.
832 * Return: 1 if the task is currently executing. 0 otherwise.
834 inline int task_curr(const struct task_struct *p)
836 return cpu_curr(task_cpu(p)) == p;
840 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
841 * use the balance_callback list if you want balancing.
843 * this means any call to check_class_changed() must be followed by a call to
844 * balance_callback().
846 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
847 const struct sched_class *prev_class,
850 if (prev_class != p->sched_class) {
851 if (prev_class->switched_from)
852 prev_class->switched_from(rq, p);
854 p->sched_class->switched_to(rq, p);
855 } else if (oldprio != p->prio || dl_task(p))
856 p->sched_class->prio_changed(rq, p, oldprio);
859 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
861 const struct sched_class *class;
863 if (p->sched_class == rq->curr->sched_class) {
864 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
866 for_each_class(class) {
867 if (class == rq->curr->sched_class)
869 if (class == p->sched_class) {
877 * A queue event has occurred, and we're going to schedule. In
878 * this case, we can save a useless back to back clock update.
880 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
881 rq_clock_skip_update(rq);
886 static inline bool is_per_cpu_kthread(struct task_struct *p)
888 if (!(p->flags & PF_KTHREAD))
891 if (p->nr_cpus_allowed != 1)
898 * Per-CPU kthreads are allowed to run on !actie && online CPUs, see
899 * __set_cpus_allowed_ptr() and select_fallback_rq().
901 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
903 if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
906 if (is_per_cpu_kthread(p))
907 return cpu_online(cpu);
909 return cpu_active(cpu);
913 * This is how migration works:
915 * 1) we invoke migration_cpu_stop() on the target CPU using
917 * 2) stopper starts to run (implicitly forcing the migrated thread
919 * 3) it checks whether the migrated task is still in the wrong runqueue.
920 * 4) if it's in the wrong runqueue then the migration thread removes
921 * it and puts it into the right queue.
922 * 5) stopper completes and stop_one_cpu() returns and the migration
927 * move_queued_task - move a queued task to new rq.
929 * Returns (locked) new rq. Old rq's lock is released.
931 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
932 struct task_struct *p, int new_cpu)
934 lockdep_assert_held(&rq->lock);
936 p->on_rq = TASK_ON_RQ_MIGRATING;
937 dequeue_task(rq, p, DEQUEUE_NOCLOCK);
938 set_task_cpu(p, new_cpu);
941 rq = cpu_rq(new_cpu);
944 BUG_ON(task_cpu(p) != new_cpu);
945 enqueue_task(rq, p, 0);
946 p->on_rq = TASK_ON_RQ_QUEUED;
947 check_preempt_curr(rq, p, 0);
952 struct migration_arg {
953 struct task_struct *task;
958 * Move (not current) task off this CPU, onto the destination CPU. We're doing
959 * this because either it can't run here any more (set_cpus_allowed()
960 * away from this CPU, or CPU going down), or because we're
961 * attempting to rebalance this task on exec (sched_exec).
963 * So we race with normal scheduler movements, but that's OK, as long
964 * as the task is no longer on this CPU.
966 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
967 struct task_struct *p, int dest_cpu)
969 /* Affinity changed (again). */
970 if (!is_cpu_allowed(p, dest_cpu))
974 rq = move_queued_task(rq, rf, p, dest_cpu);
980 * migration_cpu_stop - this will be executed by a highprio stopper thread
981 * and performs thread migration by bumping thread off CPU then
982 * 'pushing' onto another runqueue.
984 static int migration_cpu_stop(void *data)
986 struct migration_arg *arg = data;
987 struct task_struct *p = arg->task;
988 struct rq *rq = this_rq();
992 * The original target CPU might have gone down and we might
993 * be on another CPU but it doesn't matter.
997 * We need to explicitly wake pending tasks before running
998 * __migrate_task() such that we will not miss enforcing cpus_allowed
999 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1001 sched_ttwu_pending();
1003 raw_spin_lock(&p->pi_lock);
1006 * If task_rq(p) != rq, it cannot be migrated here, because we're
1007 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1008 * we're holding p->pi_lock.
1010 if (task_rq(p) == rq) {
1011 if (task_on_rq_queued(p))
1012 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
1014 p->wake_cpu = arg->dest_cpu;
1017 raw_spin_unlock(&p->pi_lock);
1024 * sched_class::set_cpus_allowed must do the below, but is not required to
1025 * actually call this function.
1027 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1029 cpumask_copy(&p->cpus_allowed, new_mask);
1030 p->nr_cpus_allowed = cpumask_weight(new_mask);
1033 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1035 struct rq *rq = task_rq(p);
1036 bool queued, running;
1038 lockdep_assert_held(&p->pi_lock);
1040 queued = task_on_rq_queued(p);
1041 running = task_current(rq, p);
1045 * Because __kthread_bind() calls this on blocked tasks without
1048 lockdep_assert_held(&rq->lock);
1049 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
1052 put_prev_task(rq, p);
1054 p->sched_class->set_cpus_allowed(p, new_mask);
1057 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1059 set_curr_task(rq, p);
1063 * Change a given task's CPU affinity. Migrate the thread to a
1064 * proper CPU and schedule it away if the CPU it's executing on
1065 * is removed from the allowed bitmask.
1067 * NOTE: the caller must have a valid reference to the task, the
1068 * task must not exit() & deallocate itself prematurely. The
1069 * call is not atomic; no spinlocks may be held.
1071 static int __set_cpus_allowed_ptr(struct task_struct *p,
1072 const struct cpumask *new_mask, bool check)
1074 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1075 unsigned int dest_cpu;
1080 rq = task_rq_lock(p, &rf);
1081 update_rq_clock(rq);
1083 if (p->flags & PF_KTHREAD) {
1085 * Kernel threads are allowed on online && !active CPUs
1087 cpu_valid_mask = cpu_online_mask;
1091 * Must re-check here, to close a race against __kthread_bind(),
1092 * sched_setaffinity() is not guaranteed to observe the flag.
1094 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1099 if (cpumask_equal(&p->cpus_allowed, new_mask))
1102 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1107 do_set_cpus_allowed(p, new_mask);
1109 if (p->flags & PF_KTHREAD) {
1111 * For kernel threads that do indeed end up on online &&
1112 * !active we want to ensure they are strict per-CPU threads.
1114 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1115 !cpumask_intersects(new_mask, cpu_active_mask) &&
1116 p->nr_cpus_allowed != 1);
1119 /* Can the task run on the task's current CPU? If so, we're done */
1120 if (cpumask_test_cpu(task_cpu(p), new_mask))
1123 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1124 if (task_running(rq, p) || p->state == TASK_WAKING) {
1125 struct migration_arg arg = { p, dest_cpu };
1126 /* Need help from migration thread: drop lock and wait. */
1127 task_rq_unlock(rq, p, &rf);
1128 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1129 tlb_migrate_finish(p->mm);
1131 } else if (task_on_rq_queued(p)) {
1133 * OK, since we're going to drop the lock immediately
1134 * afterwards anyway.
1136 rq = move_queued_task(rq, &rf, p, dest_cpu);
1139 task_rq_unlock(rq, p, &rf);
1144 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1146 return __set_cpus_allowed_ptr(p, new_mask, false);
1148 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1150 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1152 #ifdef CONFIG_SCHED_DEBUG
1154 * We should never call set_task_cpu() on a blocked task,
1155 * ttwu() will sort out the placement.
1157 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1161 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1162 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1163 * time relying on p->on_rq.
1165 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1166 p->sched_class == &fair_sched_class &&
1167 (p->on_rq && !task_on_rq_migrating(p)));
1169 #ifdef CONFIG_LOCKDEP
1171 * The caller should hold either p->pi_lock or rq->lock, when changing
1172 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1174 * sched_move_task() holds both and thus holding either pins the cgroup,
1177 * Furthermore, all task_rq users should acquire both locks, see
1180 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1181 lockdep_is_held(&task_rq(p)->lock)));
1184 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1186 WARN_ON_ONCE(!cpu_online(new_cpu));
1189 trace_sched_migrate_task(p, new_cpu);
1191 if (task_cpu(p) != new_cpu) {
1192 if (p->sched_class->migrate_task_rq)
1193 p->sched_class->migrate_task_rq(p);
1194 p->se.nr_migrations++;
1196 perf_event_task_migrate(p);
1199 __set_task_cpu(p, new_cpu);
1202 static void __migrate_swap_task(struct task_struct *p, int cpu)
1204 if (task_on_rq_queued(p)) {
1205 struct rq *src_rq, *dst_rq;
1206 struct rq_flags srf, drf;
1208 src_rq = task_rq(p);
1209 dst_rq = cpu_rq(cpu);
1211 rq_pin_lock(src_rq, &srf);
1212 rq_pin_lock(dst_rq, &drf);
1214 p->on_rq = TASK_ON_RQ_MIGRATING;
1215 deactivate_task(src_rq, p, 0);
1216 set_task_cpu(p, cpu);
1217 activate_task(dst_rq, p, 0);
1218 p->on_rq = TASK_ON_RQ_QUEUED;
1219 check_preempt_curr(dst_rq, p, 0);
1221 rq_unpin_lock(dst_rq, &drf);
1222 rq_unpin_lock(src_rq, &srf);
1226 * Task isn't running anymore; make it appear like we migrated
1227 * it before it went to sleep. This means on wakeup we make the
1228 * previous CPU our target instead of where it really is.
1234 struct migration_swap_arg {
1235 struct task_struct *src_task, *dst_task;
1236 int src_cpu, dst_cpu;
1239 static int migrate_swap_stop(void *data)
1241 struct migration_swap_arg *arg = data;
1242 struct rq *src_rq, *dst_rq;
1245 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1248 src_rq = cpu_rq(arg->src_cpu);
1249 dst_rq = cpu_rq(arg->dst_cpu);
1251 double_raw_lock(&arg->src_task->pi_lock,
1252 &arg->dst_task->pi_lock);
1253 double_rq_lock(src_rq, dst_rq);
1255 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1258 if (task_cpu(arg->src_task) != arg->src_cpu)
1261 if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
1264 if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
1267 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1268 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1273 double_rq_unlock(src_rq, dst_rq);
1274 raw_spin_unlock(&arg->dst_task->pi_lock);
1275 raw_spin_unlock(&arg->src_task->pi_lock);
1281 * Cross migrate two tasks
1283 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1285 struct migration_swap_arg arg;
1288 arg = (struct migration_swap_arg){
1290 .src_cpu = task_cpu(cur),
1292 .dst_cpu = task_cpu(p),
1295 if (arg.src_cpu == arg.dst_cpu)
1299 * These three tests are all lockless; this is OK since all of them
1300 * will be re-checked with proper locks held further down the line.
1302 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1305 if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
1308 if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
1311 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1312 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
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 * Transitivity guarantees that B happens after A and C after B.
1883 * Note: we only require RCpc transitivity.
1884 * Note: the CPU doing B need not be c0 or c1
1893 * UNLOCK rq(0)->lock
1895 * LOCK rq(0)->lock // orders against CPU0
1897 * UNLOCK rq(0)->lock
1901 * UNLOCK rq(1)->lock
1903 * LOCK rq(1)->lock // orders against CPU2
1906 * UNLOCK rq(1)->lock
1909 * BLOCKING -- aka. SLEEP + WAKEUP
1911 * For blocking we (obviously) need to provide the same guarantee as for
1912 * migration. However the means are completely different as there is no lock
1913 * chain to provide order. Instead we do:
1915 * 1) smp_store_release(X->on_cpu, 0)
1916 * 2) smp_cond_load_acquire(!X->on_cpu)
1920 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1922 * LOCK rq(0)->lock LOCK X->pi_lock
1925 * smp_store_release(X->on_cpu, 0);
1927 * smp_cond_load_acquire(&X->on_cpu, !VAL);
1933 * X->state = RUNNING
1934 * UNLOCK rq(2)->lock
1936 * LOCK rq(2)->lock // orders against CPU1
1939 * UNLOCK rq(2)->lock
1942 * UNLOCK rq(0)->lock
1945 * However; for wakeups there is a second guarantee we must provide, namely we
1946 * must observe the state that lead to our wakeup. That is, not only must our
1947 * task observe its own prior state, it must also observe the stores prior to
1950 * This means that any means of doing remote wakeups must order the CPU doing
1951 * the wakeup against the CPU the task is going to end up running on. This,
1952 * however, is already required for the regular Program-Order guarantee above,
1953 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
1958 * try_to_wake_up - wake up a thread
1959 * @p: the thread to be awakened
1960 * @state: the mask of task states that can be woken
1961 * @wake_flags: wake modifier flags (WF_*)
1963 * If (@state & @p->state) @p->state = TASK_RUNNING.
1965 * If the task was not queued/runnable, also place it back on a runqueue.
1967 * Atomic against schedule() which would dequeue a task, also see
1968 * set_current_state().
1970 * Return: %true if @p->state changes (an actual wakeup was done),
1974 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1976 unsigned long flags;
1977 int cpu, success = 0;
1980 * If we are going to wake up a thread waiting for CONDITION we
1981 * need to ensure that CONDITION=1 done by the caller can not be
1982 * reordered with p->state check below. This pairs with mb() in
1983 * set_current_state() the waiting thread does.
1985 raw_spin_lock_irqsave(&p->pi_lock, flags);
1986 smp_mb__after_spinlock();
1987 if (!(p->state & state))
1990 trace_sched_waking(p);
1992 /* We're going to change ->state: */
1997 * Ensure we load p->on_rq _after_ p->state, otherwise it would
1998 * be possible to, falsely, observe p->on_rq == 0 and get stuck
1999 * in smp_cond_load_acquire() below.
2001 * sched_ttwu_pending() try_to_wake_up()
2002 * [S] p->on_rq = 1; [L] P->state
2003 * UNLOCK rq->lock -----.
2007 * LOCK rq->lock -----'
2011 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2013 * Pairs with the UNLOCK+LOCK on rq->lock from the
2014 * last wakeup of our task and the schedule that got our task
2018 if (p->on_rq && ttwu_remote(p, wake_flags))
2023 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2024 * possible to, falsely, observe p->on_cpu == 0.
2026 * One must be running (->on_cpu == 1) in order to remove oneself
2027 * from the runqueue.
2029 * [S] ->on_cpu = 1; [L] ->on_rq
2033 * [S] ->on_rq = 0; [L] ->on_cpu
2035 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2036 * from the consecutive calls to schedule(); the first switching to our
2037 * task, the second putting it to sleep.
2042 * If the owning (remote) CPU is still in the middle of schedule() with
2043 * this task as prev, wait until its done referencing the task.
2045 * Pairs with the smp_store_release() in finish_task().
2047 * This ensures that tasks getting woken will be fully ordered against
2048 * their previous state and preserve Program Order.
2050 smp_cond_load_acquire(&p->on_cpu, !VAL);
2052 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2053 p->state = TASK_WAKING;
2056 delayacct_blkio_end(p);
2057 atomic_dec(&task_rq(p)->nr_iowait);
2060 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2061 if (task_cpu(p) != cpu) {
2062 wake_flags |= WF_MIGRATED;
2063 set_task_cpu(p, cpu);
2066 #else /* CONFIG_SMP */
2069 delayacct_blkio_end(p);
2070 atomic_dec(&task_rq(p)->nr_iowait);
2073 #endif /* CONFIG_SMP */
2075 ttwu_queue(p, cpu, wake_flags);
2077 ttwu_stat(p, cpu, wake_flags);
2079 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2085 * try_to_wake_up_local - try to wake up a local task with rq lock held
2086 * @p: the thread to be awakened
2087 * @rf: request-queue flags for pinning
2089 * Put @p on the run-queue if it's not already there. The caller must
2090 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2093 static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
2095 struct rq *rq = task_rq(p);
2097 if (WARN_ON_ONCE(rq != this_rq()) ||
2098 WARN_ON_ONCE(p == current))
2101 lockdep_assert_held(&rq->lock);
2103 if (!raw_spin_trylock(&p->pi_lock)) {
2105 * This is OK, because current is on_cpu, which avoids it being
2106 * picked for load-balance and preemption/IRQs are still
2107 * disabled avoiding further scheduler activity on it and we've
2108 * not yet picked a replacement task.
2111 raw_spin_lock(&p->pi_lock);
2115 if (!(p->state & TASK_NORMAL))
2118 trace_sched_waking(p);
2120 if (!task_on_rq_queued(p)) {
2122 delayacct_blkio_end(p);
2123 atomic_dec(&rq->nr_iowait);
2125 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
2128 ttwu_do_wakeup(rq, p, 0, rf);
2129 ttwu_stat(p, smp_processor_id(), 0);
2131 raw_spin_unlock(&p->pi_lock);
2135 * wake_up_process - Wake up a specific process
2136 * @p: The process to be woken up.
2138 * Attempt to wake up the nominated process and move it to the set of runnable
2141 * Return: 1 if the process was woken up, 0 if it was already running.
2143 * It may be assumed that this function implies a write memory barrier before
2144 * changing the task state if and only if any tasks are woken up.
2146 int wake_up_process(struct task_struct *p)
2148 return try_to_wake_up(p, TASK_NORMAL, 0);
2150 EXPORT_SYMBOL(wake_up_process);
2152 int wake_up_state(struct task_struct *p, unsigned int state)
2154 return try_to_wake_up(p, state, 0);
2158 * Perform scheduler related setup for a newly forked process p.
2159 * p is forked by current.
2161 * __sched_fork() is basic setup used by init_idle() too:
2163 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2168 p->se.exec_start = 0;
2169 p->se.sum_exec_runtime = 0;
2170 p->se.prev_sum_exec_runtime = 0;
2171 p->se.nr_migrations = 0;
2173 INIT_LIST_HEAD(&p->se.group_node);
2175 #ifdef CONFIG_FAIR_GROUP_SCHED
2176 p->se.cfs_rq = NULL;
2179 #ifdef CONFIG_SCHEDSTATS
2180 /* Even if schedstat is disabled, there should not be garbage */
2181 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2184 RB_CLEAR_NODE(&p->dl.rb_node);
2185 init_dl_task_timer(&p->dl);
2186 init_dl_inactive_task_timer(&p->dl);
2187 __dl_clear_params(p);
2189 INIT_LIST_HEAD(&p->rt.run_list);
2191 p->rt.time_slice = sched_rr_timeslice;
2195 #ifdef CONFIG_PREEMPT_NOTIFIERS
2196 INIT_HLIST_HEAD(&p->preempt_notifiers);
2199 init_numa_balancing(clone_flags, p);
2202 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2204 #ifdef CONFIG_NUMA_BALANCING
2206 void set_numabalancing_state(bool enabled)
2209 static_branch_enable(&sched_numa_balancing);
2211 static_branch_disable(&sched_numa_balancing);
2214 #ifdef CONFIG_PROC_SYSCTL
2215 int sysctl_numa_balancing(struct ctl_table *table, int write,
2216 void __user *buffer, size_t *lenp, loff_t *ppos)
2220 int state = static_branch_likely(&sched_numa_balancing);
2222 if (write && !capable(CAP_SYS_ADMIN))
2227 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2231 set_numabalancing_state(state);
2237 #ifdef CONFIG_SCHEDSTATS
2239 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2240 static bool __initdata __sched_schedstats = false;
2242 static void set_schedstats(bool enabled)
2245 static_branch_enable(&sched_schedstats);
2247 static_branch_disable(&sched_schedstats);
2250 void force_schedstat_enabled(void)
2252 if (!schedstat_enabled()) {
2253 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2254 static_branch_enable(&sched_schedstats);
2258 static int __init setup_schedstats(char *str)
2265 * This code is called before jump labels have been set up, so we can't
2266 * change the static branch directly just yet. Instead set a temporary
2267 * variable so init_schedstats() can do it later.
2269 if (!strcmp(str, "enable")) {
2270 __sched_schedstats = true;
2272 } else if (!strcmp(str, "disable")) {
2273 __sched_schedstats = false;
2278 pr_warn("Unable to parse schedstats=\n");
2282 __setup("schedstats=", setup_schedstats);
2284 static void __init init_schedstats(void)
2286 set_schedstats(__sched_schedstats);
2289 #ifdef CONFIG_PROC_SYSCTL
2290 int sysctl_schedstats(struct ctl_table *table, int write,
2291 void __user *buffer, size_t *lenp, loff_t *ppos)
2295 int state = static_branch_likely(&sched_schedstats);
2297 if (write && !capable(CAP_SYS_ADMIN))
2302 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2306 set_schedstats(state);
2309 #endif /* CONFIG_PROC_SYSCTL */
2310 #else /* !CONFIG_SCHEDSTATS */
2311 static inline void init_schedstats(void) {}
2312 #endif /* CONFIG_SCHEDSTATS */
2315 * fork()/clone()-time setup:
2317 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2319 unsigned long flags;
2320 int cpu = get_cpu();
2322 __sched_fork(clone_flags, p);
2324 * We mark the process as NEW here. This guarantees that
2325 * nobody will actually run it, and a signal or other external
2326 * event cannot wake it up and insert it on the runqueue either.
2328 p->state = TASK_NEW;
2331 * Make sure we do not leak PI boosting priority to the child.
2333 p->prio = current->normal_prio;
2336 * Revert to default priority/policy on fork if requested.
2338 if (unlikely(p->sched_reset_on_fork)) {
2339 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2340 p->policy = SCHED_NORMAL;
2341 p->static_prio = NICE_TO_PRIO(0);
2343 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2344 p->static_prio = NICE_TO_PRIO(0);
2346 p->prio = p->normal_prio = __normal_prio(p);
2347 set_load_weight(p, false);
2350 * We don't need the reset flag anymore after the fork. It has
2351 * fulfilled its duty:
2353 p->sched_reset_on_fork = 0;
2356 if (dl_prio(p->prio)) {
2359 } else if (rt_prio(p->prio)) {
2360 p->sched_class = &rt_sched_class;
2362 p->sched_class = &fair_sched_class;
2365 init_entity_runnable_average(&p->se);
2368 * The child is not yet in the pid-hash so no cgroup attach races,
2369 * and the cgroup is pinned to this child due to cgroup_fork()
2370 * is ran before sched_fork().
2372 * Silence PROVE_RCU.
2374 raw_spin_lock_irqsave(&p->pi_lock, flags);
2376 * We're setting the CPU for the first time, we don't migrate,
2377 * so use __set_task_cpu().
2379 __set_task_cpu(p, cpu);
2380 if (p->sched_class->task_fork)
2381 p->sched_class->task_fork(p);
2382 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2384 #ifdef CONFIG_SCHED_INFO
2385 if (likely(sched_info_on()))
2386 memset(&p->sched_info, 0, sizeof(p->sched_info));
2388 #if defined(CONFIG_SMP)
2391 init_task_preempt_count(p);
2393 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2394 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2401 unsigned long to_ratio(u64 period, u64 runtime)
2403 if (runtime == RUNTIME_INF)
2407 * Doing this here saves a lot of checks in all
2408 * the calling paths, and returning zero seems
2409 * safe for them anyway.
2414 return div64_u64(runtime << BW_SHIFT, period);
2418 * wake_up_new_task - wake up a newly created task for the first time.
2420 * This function will do some initial scheduler statistics housekeeping
2421 * that must be done for every newly created context, then puts the task
2422 * on the runqueue and wakes it.
2424 void wake_up_new_task(struct task_struct *p)
2429 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2430 p->state = TASK_RUNNING;
2433 * Fork balancing, do it here and not earlier because:
2434 * - cpus_allowed can change in the fork path
2435 * - any previously selected CPU might disappear through hotplug
2437 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2438 * as we're not fully set-up yet.
2440 p->recent_used_cpu = task_cpu(p);
2441 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2443 rq = __task_rq_lock(p, &rf);
2444 update_rq_clock(rq);
2445 post_init_entity_util_avg(&p->se);
2447 activate_task(rq, p, ENQUEUE_NOCLOCK);
2448 p->on_rq = TASK_ON_RQ_QUEUED;
2449 trace_sched_wakeup_new(p);
2450 check_preempt_curr(rq, p, WF_FORK);
2452 if (p->sched_class->task_woken) {
2454 * Nothing relies on rq->lock after this, so its fine to
2457 rq_unpin_lock(rq, &rf);
2458 p->sched_class->task_woken(rq, p);
2459 rq_repin_lock(rq, &rf);
2462 task_rq_unlock(rq, p, &rf);
2465 #ifdef CONFIG_PREEMPT_NOTIFIERS
2467 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
2469 void preempt_notifier_inc(void)
2471 static_branch_inc(&preempt_notifier_key);
2473 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2475 void preempt_notifier_dec(void)
2477 static_branch_dec(&preempt_notifier_key);
2479 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2482 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2483 * @notifier: notifier struct to register
2485 void preempt_notifier_register(struct preempt_notifier *notifier)
2487 if (!static_branch_unlikely(&preempt_notifier_key))
2488 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2490 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2492 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2495 * preempt_notifier_unregister - no longer interested in preemption notifications
2496 * @notifier: notifier struct to unregister
2498 * This is *not* safe to call from within a preemption notifier.
2500 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2502 hlist_del(¬ifier->link);
2504 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2506 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2508 struct preempt_notifier *notifier;
2510 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2511 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2514 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2516 if (static_branch_unlikely(&preempt_notifier_key))
2517 __fire_sched_in_preempt_notifiers(curr);
2521 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2522 struct task_struct *next)
2524 struct preempt_notifier *notifier;
2526 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2527 notifier->ops->sched_out(notifier, next);
2530 static __always_inline void
2531 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2532 struct task_struct *next)
2534 if (static_branch_unlikely(&preempt_notifier_key))
2535 __fire_sched_out_preempt_notifiers(curr, next);
2538 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2540 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2545 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2546 struct task_struct *next)
2550 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2552 static inline void prepare_task(struct task_struct *next)
2556 * Claim the task as running, we do this before switching to it
2557 * such that any running task will have this set.
2563 static inline void finish_task(struct task_struct *prev)
2567 * After ->on_cpu is cleared, the task can be moved to a different CPU.
2568 * We must ensure this doesn't happen until the switch is completely
2571 * In particular, the load of prev->state in finish_task_switch() must
2572 * happen before this.
2574 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
2576 smp_store_release(&prev->on_cpu, 0);
2581 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
2584 * Since the runqueue lock will be released by the next
2585 * task (which is an invalid locking op but in the case
2586 * of the scheduler it's an obvious special-case), so we
2587 * do an early lockdep release here:
2589 rq_unpin_lock(rq, rf);
2590 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2591 #ifdef CONFIG_DEBUG_SPINLOCK
2592 /* this is a valid case when another task releases the spinlock */
2593 rq->lock.owner = next;
2597 static inline void finish_lock_switch(struct rq *rq)
2600 * If we are tracking spinlock dependencies then we have to
2601 * fix up the runqueue lock - which gets 'carried over' from
2602 * prev into current:
2604 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
2605 raw_spin_unlock_irq(&rq->lock);
2609 * NOP if the arch has not defined these:
2612 #ifndef prepare_arch_switch
2613 # define prepare_arch_switch(next) do { } while (0)
2616 #ifndef finish_arch_post_lock_switch
2617 # define finish_arch_post_lock_switch() do { } while (0)
2621 * prepare_task_switch - prepare to switch tasks
2622 * @rq: the runqueue preparing to switch
2623 * @prev: the current task that is being switched out
2624 * @next: the task we are going to switch to.
2626 * This is called with the rq lock held and interrupts off. It must
2627 * be paired with a subsequent finish_task_switch after the context
2630 * prepare_task_switch sets up locking and calls architecture specific
2634 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2635 struct task_struct *next)
2637 kcov_prepare_switch(prev);
2638 sched_info_switch(rq, prev, next);
2639 perf_event_task_sched_out(prev, next);
2641 fire_sched_out_preempt_notifiers(prev, next);
2643 prepare_arch_switch(next);
2647 * finish_task_switch - clean up after a task-switch
2648 * @prev: the thread we just switched away from.
2650 * finish_task_switch must be called after the context switch, paired
2651 * with a prepare_task_switch call before the context switch.
2652 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2653 * and do any other architecture-specific cleanup actions.
2655 * Note that we may have delayed dropping an mm in context_switch(). If
2656 * so, we finish that here outside of the runqueue lock. (Doing it
2657 * with the lock held can cause deadlocks; see schedule() for
2660 * The context switch have flipped the stack from under us and restored the
2661 * local variables which were saved when this task called schedule() in the
2662 * past. prev == current is still correct but we need to recalculate this_rq
2663 * because prev may have moved to another CPU.
2665 static struct rq *finish_task_switch(struct task_struct *prev)
2666 __releases(rq->lock)
2668 struct rq *rq = this_rq();
2669 struct mm_struct *mm = rq->prev_mm;
2673 * The previous task will have left us with a preempt_count of 2
2674 * because it left us after:
2677 * preempt_disable(); // 1
2679 * raw_spin_lock_irq(&rq->lock) // 2
2681 * Also, see FORK_PREEMPT_COUNT.
2683 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2684 "corrupted preempt_count: %s/%d/0x%x\n",
2685 current->comm, current->pid, preempt_count()))
2686 preempt_count_set(FORK_PREEMPT_COUNT);
2691 * A task struct has one reference for the use as "current".
2692 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2693 * schedule one last time. The schedule call will never return, and
2694 * the scheduled task must drop that reference.
2696 * We must observe prev->state before clearing prev->on_cpu (in
2697 * finish_task), otherwise a concurrent wakeup can get prev
2698 * running on another CPU and we could rave with its RUNNING -> DEAD
2699 * transition, resulting in a double drop.
2701 prev_state = prev->state;
2702 vtime_task_switch(prev);
2703 perf_event_task_sched_in(prev, current);
2705 finish_lock_switch(rq);
2706 finish_arch_post_lock_switch();
2707 kcov_finish_switch(current);
2709 fire_sched_in_preempt_notifiers(current);
2711 * When switching through a kernel thread, the loop in
2712 * membarrier_{private,global}_expedited() may have observed that
2713 * kernel thread and not issued an IPI. It is therefore possible to
2714 * schedule between user->kernel->user threads without passing though
2715 * switch_mm(). Membarrier requires a barrier after storing to
2716 * rq->curr, before returning to userspace, so provide them here:
2718 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
2719 * provided by mmdrop(),
2720 * - a sync_core for SYNC_CORE.
2723 membarrier_mm_sync_core_before_usermode(mm);
2726 if (unlikely(prev_state == TASK_DEAD)) {
2727 if (prev->sched_class->task_dead)
2728 prev->sched_class->task_dead(prev);
2731 * Remove function-return probe instances associated with this
2732 * task and put them back on the free list.
2734 kprobe_flush_task(prev);
2736 /* Task is done with its stack. */
2737 put_task_stack(prev);
2739 put_task_struct(prev);
2742 tick_nohz_task_switch();
2748 /* rq->lock is NOT held, but preemption is disabled */
2749 static void __balance_callback(struct rq *rq)
2751 struct callback_head *head, *next;
2752 void (*func)(struct rq *rq);
2753 unsigned long flags;
2755 raw_spin_lock_irqsave(&rq->lock, flags);
2756 head = rq->balance_callback;
2757 rq->balance_callback = NULL;
2759 func = (void (*)(struct rq *))head->func;
2766 raw_spin_unlock_irqrestore(&rq->lock, flags);
2769 static inline void balance_callback(struct rq *rq)
2771 if (unlikely(rq->balance_callback))
2772 __balance_callback(rq);
2777 static inline void balance_callback(struct rq *rq)
2784 * schedule_tail - first thing a freshly forked thread must call.
2785 * @prev: the thread we just switched away from.
2787 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2788 __releases(rq->lock)
2793 * New tasks start with FORK_PREEMPT_COUNT, see there and
2794 * finish_task_switch() for details.
2796 * finish_task_switch() will drop rq->lock() and lower preempt_count
2797 * and the preempt_enable() will end up enabling preemption (on
2798 * PREEMPT_COUNT kernels).
2801 rq = finish_task_switch(prev);
2802 balance_callback(rq);
2805 if (current->set_child_tid)
2806 put_user(task_pid_vnr(current), current->set_child_tid);
2810 * context_switch - switch to the new MM and the new thread's register state.
2812 static __always_inline struct rq *
2813 context_switch(struct rq *rq, struct task_struct *prev,
2814 struct task_struct *next, struct rq_flags *rf)
2816 struct mm_struct *mm, *oldmm;
2818 prepare_task_switch(rq, prev, next);
2821 oldmm = prev->active_mm;
2823 * For paravirt, this is coupled with an exit in switch_to to
2824 * combine the page table reload and the switch backend into
2827 arch_start_context_switch(prev);
2830 * If mm is non-NULL, we pass through switch_mm(). If mm is
2831 * NULL, we will pass through mmdrop() in finish_task_switch().
2832 * Both of these contain the full memory barrier required by
2833 * membarrier after storing to rq->curr, before returning to
2837 next->active_mm = oldmm;
2839 enter_lazy_tlb(oldmm, next);
2841 switch_mm_irqs_off(oldmm, mm, next);
2844 prev->active_mm = NULL;
2845 rq->prev_mm = oldmm;
2848 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
2850 prepare_lock_switch(rq, next, rf);
2852 /* Here we just switch the register state and the stack. */
2853 switch_to(prev, next, prev);
2856 return finish_task_switch(prev);
2860 * nr_running and nr_context_switches:
2862 * externally visible scheduler statistics: current number of runnable
2863 * threads, total number of context switches performed since bootup.
2865 unsigned long nr_running(void)
2867 unsigned long i, sum = 0;
2869 for_each_online_cpu(i)
2870 sum += cpu_rq(i)->nr_running;
2876 * Check if only the current task is running on the CPU.
2878 * Caution: this function does not check that the caller has disabled
2879 * preemption, thus the result might have a time-of-check-to-time-of-use
2880 * race. The caller is responsible to use it correctly, for example:
2882 * - from a non-preemptable section (of course)
2884 * - from a thread that is bound to a single CPU
2886 * - in a loop with very short iterations (e.g. a polling loop)
2888 bool single_task_running(void)
2890 return raw_rq()->nr_running == 1;
2892 EXPORT_SYMBOL(single_task_running);
2894 unsigned long long nr_context_switches(void)
2897 unsigned long long sum = 0;
2899 for_each_possible_cpu(i)
2900 sum += cpu_rq(i)->nr_switches;
2906 * IO-wait accounting, and how its mostly bollocks (on SMP).
2908 * The idea behind IO-wait account is to account the idle time that we could
2909 * have spend running if it were not for IO. That is, if we were to improve the
2910 * storage performance, we'd have a proportional reduction in IO-wait time.
2912 * This all works nicely on UP, where, when a task blocks on IO, we account
2913 * idle time as IO-wait, because if the storage were faster, it could've been
2914 * running and we'd not be idle.
2916 * This has been extended to SMP, by doing the same for each CPU. This however
2919 * Imagine for instance the case where two tasks block on one CPU, only the one
2920 * CPU will have IO-wait accounted, while the other has regular idle. Even
2921 * though, if the storage were faster, both could've ran at the same time,
2922 * utilising both CPUs.
2924 * This means, that when looking globally, the current IO-wait accounting on
2925 * SMP is a lower bound, by reason of under accounting.
2927 * Worse, since the numbers are provided per CPU, they are sometimes
2928 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2929 * associated with any one particular CPU, it can wake to another CPU than it
2930 * blocked on. This means the per CPU IO-wait number is meaningless.
2932 * Task CPU affinities can make all that even more 'interesting'.
2935 unsigned long nr_iowait(void)
2937 unsigned long i, sum = 0;
2939 for_each_possible_cpu(i)
2940 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2946 * Consumers of these two interfaces, like for example the cpufreq menu
2947 * governor are using nonsensical data. Boosting frequency for a CPU that has
2948 * IO-wait which might not even end up running the task when it does become
2952 unsigned long nr_iowait_cpu(int cpu)
2954 struct rq *this = cpu_rq(cpu);
2955 return atomic_read(&this->nr_iowait);
2958 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2960 struct rq *rq = this_rq();
2961 *nr_waiters = atomic_read(&rq->nr_iowait);
2962 *load = rq->load.weight;
2968 * sched_exec - execve() is a valuable balancing opportunity, because at
2969 * this point the task has the smallest effective memory and cache footprint.
2971 void sched_exec(void)
2973 struct task_struct *p = current;
2974 unsigned long flags;
2977 raw_spin_lock_irqsave(&p->pi_lock, flags);
2978 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2979 if (dest_cpu == smp_processor_id())
2982 if (likely(cpu_active(dest_cpu))) {
2983 struct migration_arg arg = { p, dest_cpu };
2985 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2986 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2990 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2995 DEFINE_PER_CPU(struct kernel_stat, kstat);
2996 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2998 EXPORT_PER_CPU_SYMBOL(kstat);
2999 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3002 * The function fair_sched_class.update_curr accesses the struct curr
3003 * and its field curr->exec_start; when called from task_sched_runtime(),
3004 * we observe a high rate of cache misses in practice.
3005 * Prefetching this data results in improved performance.
3007 static inline void prefetch_curr_exec_start(struct task_struct *p)
3009 #ifdef CONFIG_FAIR_GROUP_SCHED
3010 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3012 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3015 prefetch(&curr->exec_start);
3019 * Return accounted runtime for the task.
3020 * In case the task is currently running, return the runtime plus current's
3021 * pending runtime that have not been accounted yet.
3023 unsigned long long task_sched_runtime(struct task_struct *p)
3029 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3031 * 64-bit doesn't need locks to atomically read a 64-bit value.
3032 * So we have a optimization chance when the task's delta_exec is 0.
3033 * Reading ->on_cpu is racy, but this is ok.
3035 * If we race with it leaving CPU, we'll take a lock. So we're correct.
3036 * If we race with it entering CPU, unaccounted time is 0. This is
3037 * indistinguishable from the read occurring a few cycles earlier.
3038 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3039 * been accounted, so we're correct here as well.
3041 if (!p->on_cpu || !task_on_rq_queued(p))
3042 return p->se.sum_exec_runtime;
3045 rq = task_rq_lock(p, &rf);
3047 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3048 * project cycles that may never be accounted to this
3049 * thread, breaking clock_gettime().
3051 if (task_current(rq, p) && task_on_rq_queued(p)) {
3052 prefetch_curr_exec_start(p);
3053 update_rq_clock(rq);
3054 p->sched_class->update_curr(rq);
3056 ns = p->se.sum_exec_runtime;
3057 task_rq_unlock(rq, p, &rf);
3063 * This function gets called by the timer code, with HZ frequency.
3064 * We call it with interrupts disabled.
3066 void scheduler_tick(void)
3068 int cpu = smp_processor_id();
3069 struct rq *rq = cpu_rq(cpu);
3070 struct task_struct *curr = rq->curr;
3077 update_rq_clock(rq);
3078 curr->sched_class->task_tick(rq, curr, 0);
3079 cpu_load_update_active(rq);
3080 calc_global_load_tick(rq);
3084 perf_event_task_tick();
3087 rq->idle_balance = idle_cpu(cpu);
3088 trigger_load_balance(rq);
3092 #ifdef CONFIG_NO_HZ_FULL
3096 struct delayed_work work;
3099 static struct tick_work __percpu *tick_work_cpu;
3101 static void sched_tick_remote(struct work_struct *work)
3103 struct delayed_work *dwork = to_delayed_work(work);
3104 struct tick_work *twork = container_of(dwork, struct tick_work, work);
3105 int cpu = twork->cpu;
3106 struct rq *rq = cpu_rq(cpu);
3107 struct task_struct *curr;
3112 * Handle the tick only if it appears the remote CPU is running in full
3113 * dynticks mode. The check is racy by nature, but missing a tick or
3114 * having one too much is no big deal because the scheduler tick updates
3115 * statistics and checks timeslices in a time-independent way, regardless
3116 * of when exactly it is running.
3118 if (idle_cpu(cpu) || !tick_nohz_tick_stopped_cpu(cpu))
3121 rq_lock_irq(rq, &rf);
3123 if (is_idle_task(curr))
3126 update_rq_clock(rq);
3127 delta = rq_clock_task(rq) - curr->se.exec_start;
3130 * Make sure the next tick runs within a reasonable
3133 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
3134 curr->sched_class->task_tick(rq, curr, 0);
3137 rq_unlock_irq(rq, &rf);
3141 * Run the remote tick once per second (1Hz). This arbitrary
3142 * frequency is large enough to avoid overload but short enough
3143 * to keep scheduler internal stats reasonably up to date.
3145 queue_delayed_work(system_unbound_wq, dwork, HZ);
3148 static void sched_tick_start(int cpu)
3150 struct tick_work *twork;
3152 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3155 WARN_ON_ONCE(!tick_work_cpu);
3157 twork = per_cpu_ptr(tick_work_cpu, cpu);
3159 INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
3160 queue_delayed_work(system_unbound_wq, &twork->work, HZ);
3163 #ifdef CONFIG_HOTPLUG_CPU
3164 static void sched_tick_stop(int cpu)
3166 struct tick_work *twork;
3168 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3171 WARN_ON_ONCE(!tick_work_cpu);
3173 twork = per_cpu_ptr(tick_work_cpu, cpu);
3174 cancel_delayed_work_sync(&twork->work);
3176 #endif /* CONFIG_HOTPLUG_CPU */
3178 int __init sched_tick_offload_init(void)
3180 tick_work_cpu = alloc_percpu(struct tick_work);
3181 BUG_ON(!tick_work_cpu);
3186 #else /* !CONFIG_NO_HZ_FULL */
3187 static inline void sched_tick_start(int cpu) { }
3188 static inline void sched_tick_stop(int cpu) { }
3191 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3192 defined(CONFIG_PREEMPT_TRACER))
3194 * If the value passed in is equal to the current preempt count
3195 * then we just disabled preemption. Start timing the latency.
3197 static inline void preempt_latency_start(int val)
3199 if (preempt_count() == val) {
3200 unsigned long ip = get_lock_parent_ip();
3201 #ifdef CONFIG_DEBUG_PREEMPT
3202 current->preempt_disable_ip = ip;
3204 trace_preempt_off(CALLER_ADDR0, ip);
3208 void preempt_count_add(int val)
3210 #ifdef CONFIG_DEBUG_PREEMPT
3214 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3217 __preempt_count_add(val);
3218 #ifdef CONFIG_DEBUG_PREEMPT
3220 * Spinlock count overflowing soon?
3222 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3225 preempt_latency_start(val);
3227 EXPORT_SYMBOL(preempt_count_add);
3228 NOKPROBE_SYMBOL(preempt_count_add);
3231 * If the value passed in equals to the current preempt count
3232 * then we just enabled preemption. Stop timing the latency.
3234 static inline void preempt_latency_stop(int val)
3236 if (preempt_count() == val)
3237 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3240 void preempt_count_sub(int val)
3242 #ifdef CONFIG_DEBUG_PREEMPT
3246 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3249 * Is the spinlock portion underflowing?
3251 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3252 !(preempt_count() & PREEMPT_MASK)))
3256 preempt_latency_stop(val);
3257 __preempt_count_sub(val);
3259 EXPORT_SYMBOL(preempt_count_sub);
3260 NOKPROBE_SYMBOL(preempt_count_sub);
3263 static inline void preempt_latency_start(int val) { }
3264 static inline void preempt_latency_stop(int val) { }
3267 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3269 #ifdef CONFIG_DEBUG_PREEMPT
3270 return p->preempt_disable_ip;
3277 * Print scheduling while atomic bug:
3279 static noinline void __schedule_bug(struct task_struct *prev)
3281 /* Save this before calling printk(), since that will clobber it */
3282 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3284 if (oops_in_progress)
3287 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3288 prev->comm, prev->pid, preempt_count());
3290 debug_show_held_locks(prev);
3292 if (irqs_disabled())
3293 print_irqtrace_events(prev);
3294 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3295 && in_atomic_preempt_off()) {
3296 pr_err("Preemption disabled at:");
3297 print_ip_sym(preempt_disable_ip);
3301 panic("scheduling while atomic\n");
3304 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3308 * Various schedule()-time debugging checks and statistics:
3310 static inline void schedule_debug(struct task_struct *prev)
3312 #ifdef CONFIG_SCHED_STACK_END_CHECK
3313 if (task_stack_end_corrupted(prev))
3314 panic("corrupted stack end detected inside scheduler\n");
3317 if (unlikely(in_atomic_preempt_off())) {
3318 __schedule_bug(prev);
3319 preempt_count_set(PREEMPT_DISABLED);
3323 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3325 schedstat_inc(this_rq()->sched_count);
3329 * Pick up the highest-prio task:
3331 static inline struct task_struct *
3332 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
3334 const struct sched_class *class;
3335 struct task_struct *p;
3338 * Optimization: we know that if all tasks are in the fair class we can
3339 * call that function directly, but only if the @prev task wasn't of a
3340 * higher scheduling class, because otherwise those loose the
3341 * opportunity to pull in more work from other CPUs.
3343 if (likely((prev->sched_class == &idle_sched_class ||
3344 prev->sched_class == &fair_sched_class) &&
3345 rq->nr_running == rq->cfs.h_nr_running)) {
3347 p = fair_sched_class.pick_next_task(rq, prev, rf);
3348 if (unlikely(p == RETRY_TASK))
3351 /* Assumes fair_sched_class->next == idle_sched_class */
3353 p = idle_sched_class.pick_next_task(rq, prev, rf);
3359 for_each_class(class) {
3360 p = class->pick_next_task(rq, prev, rf);
3362 if (unlikely(p == RETRY_TASK))
3368 /* The idle class should always have a runnable task: */
3373 * __schedule() is the main scheduler function.
3375 * The main means of driving the scheduler and thus entering this function are:
3377 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3379 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3380 * paths. For example, see arch/x86/entry_64.S.
3382 * To drive preemption between tasks, the scheduler sets the flag in timer
3383 * interrupt handler scheduler_tick().
3385 * 3. Wakeups don't really cause entry into schedule(). They add a
3386 * task to the run-queue and that's it.
3388 * Now, if the new task added to the run-queue preempts the current
3389 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3390 * called on the nearest possible occasion:
3392 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3394 * - in syscall or exception context, at the next outmost
3395 * preempt_enable(). (this might be as soon as the wake_up()'s
3398 * - in IRQ context, return from interrupt-handler to
3399 * preemptible context
3401 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3404 * - cond_resched() call
3405 * - explicit schedule() call
3406 * - return from syscall or exception to user-space
3407 * - return from interrupt-handler to user-space
3409 * WARNING: must be called with preemption disabled!
3411 static void __sched notrace __schedule(bool preempt)
3413 struct task_struct *prev, *next;
3414 unsigned long *switch_count;
3419 cpu = smp_processor_id();
3423 schedule_debug(prev);
3425 if (sched_feat(HRTICK))
3428 local_irq_disable();
3429 rcu_note_context_switch(preempt);
3432 * Make sure that signal_pending_state()->signal_pending() below
3433 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3434 * done by the caller to avoid the race with signal_wake_up().
3436 * The membarrier system call requires a full memory barrier
3437 * after coming from user-space, before storing to rq->curr.
3440 smp_mb__after_spinlock();
3442 /* Promote REQ to ACT */
3443 rq->clock_update_flags <<= 1;
3444 update_rq_clock(rq);
3446 switch_count = &prev->nivcsw;
3447 if (!preempt && prev->state) {
3448 if (unlikely(signal_pending_state(prev->state, prev))) {
3449 prev->state = TASK_RUNNING;
3451 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
3454 if (prev->in_iowait) {
3455 atomic_inc(&rq->nr_iowait);
3456 delayacct_blkio_start();
3460 * If a worker went to sleep, notify and ask workqueue
3461 * whether it wants to wake up a task to maintain
3464 if (prev->flags & PF_WQ_WORKER) {
3465 struct task_struct *to_wakeup;
3467 to_wakeup = wq_worker_sleeping(prev);
3469 try_to_wake_up_local(to_wakeup, &rf);
3472 switch_count = &prev->nvcsw;
3475 next = pick_next_task(rq, prev, &rf);
3476 clear_tsk_need_resched(prev);
3477 clear_preempt_need_resched();
3479 if (likely(prev != next)) {
3483 * The membarrier system call requires each architecture
3484 * to have a full memory barrier after updating
3485 * rq->curr, before returning to user-space.
3487 * Here are the schemes providing that barrier on the
3488 * various architectures:
3489 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
3490 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
3491 * - finish_lock_switch() for weakly-ordered
3492 * architectures where spin_unlock is a full barrier,
3493 * - switch_to() for arm64 (weakly-ordered, spin_unlock
3494 * is a RELEASE barrier),
3498 trace_sched_switch(preempt, prev, next);
3500 /* Also unlocks the rq: */
3501 rq = context_switch(rq, prev, next, &rf);
3503 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3504 rq_unlock_irq(rq, &rf);
3507 balance_callback(rq);
3510 void __noreturn do_task_dead(void)
3512 /* Causes final put_task_struct in finish_task_switch(): */
3513 set_special_state(TASK_DEAD);
3515 /* Tell freezer to ignore us: */
3516 current->flags |= PF_NOFREEZE;
3521 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
3526 static inline void sched_submit_work(struct task_struct *tsk)
3528 if (!tsk->state || tsk_is_pi_blocked(tsk))
3531 * If we are going to sleep and we have plugged IO queued,
3532 * make sure to submit it to avoid deadlocks.
3534 if (blk_needs_flush_plug(tsk))
3535 blk_schedule_flush_plug(tsk);
3538 asmlinkage __visible void __sched schedule(void)
3540 struct task_struct *tsk = current;
3542 sched_submit_work(tsk);
3546 sched_preempt_enable_no_resched();
3547 } while (need_resched());
3549 EXPORT_SYMBOL(schedule);
3552 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3553 * state (have scheduled out non-voluntarily) by making sure that all
3554 * tasks have either left the run queue or have gone into user space.
3555 * As idle tasks do not do either, they must not ever be preempted
3556 * (schedule out non-voluntarily).
3558 * schedule_idle() is similar to schedule_preempt_disable() except that it
3559 * never enables preemption because it does not call sched_submit_work().
3561 void __sched schedule_idle(void)
3564 * As this skips calling sched_submit_work(), which the idle task does
3565 * regardless because that function is a nop when the task is in a
3566 * TASK_RUNNING state, make sure this isn't used someplace that the
3567 * current task can be in any other state. Note, idle is always in the
3568 * TASK_RUNNING state.
3570 WARN_ON_ONCE(current->state);
3573 } while (need_resched());
3576 #ifdef CONFIG_CONTEXT_TRACKING
3577 asmlinkage __visible void __sched schedule_user(void)
3580 * If we come here after a random call to set_need_resched(),
3581 * or we have been woken up remotely but the IPI has not yet arrived,
3582 * we haven't yet exited the RCU idle mode. Do it here manually until
3583 * we find a better solution.
3585 * NB: There are buggy callers of this function. Ideally we
3586 * should warn if prev_state != CONTEXT_USER, but that will trigger
3587 * too frequently to make sense yet.
3589 enum ctx_state prev_state = exception_enter();
3591 exception_exit(prev_state);
3596 * schedule_preempt_disabled - called with preemption disabled
3598 * Returns with preemption disabled. Note: preempt_count must be 1
3600 void __sched schedule_preempt_disabled(void)
3602 sched_preempt_enable_no_resched();
3607 static void __sched notrace preempt_schedule_common(void)
3611 * Because the function tracer can trace preempt_count_sub()
3612 * and it also uses preempt_enable/disable_notrace(), if
3613 * NEED_RESCHED is set, the preempt_enable_notrace() called
3614 * by the function tracer will call this function again and
3615 * cause infinite recursion.
3617 * Preemption must be disabled here before the function
3618 * tracer can trace. Break up preempt_disable() into two
3619 * calls. One to disable preemption without fear of being
3620 * traced. The other to still record the preemption latency,
3621 * which can also be traced by the function tracer.
3623 preempt_disable_notrace();
3624 preempt_latency_start(1);
3626 preempt_latency_stop(1);
3627 preempt_enable_no_resched_notrace();
3630 * Check again in case we missed a preemption opportunity
3631 * between schedule and now.
3633 } while (need_resched());
3636 #ifdef CONFIG_PREEMPT
3638 * this is the entry point to schedule() from in-kernel preemption
3639 * off of preempt_enable. Kernel preemptions off return from interrupt
3640 * occur there and call schedule directly.
3642 asmlinkage __visible void __sched notrace preempt_schedule(void)
3645 * If there is a non-zero preempt_count or interrupts are disabled,
3646 * we do not want to preempt the current task. Just return..
3648 if (likely(!preemptible()))
3651 preempt_schedule_common();
3653 NOKPROBE_SYMBOL(preempt_schedule);
3654 EXPORT_SYMBOL(preempt_schedule);
3657 * preempt_schedule_notrace - preempt_schedule called by tracing
3659 * The tracing infrastructure uses preempt_enable_notrace to prevent
3660 * recursion and tracing preempt enabling caused by the tracing
3661 * infrastructure itself. But as tracing can happen in areas coming
3662 * from userspace or just about to enter userspace, a preempt enable
3663 * can occur before user_exit() is called. This will cause the scheduler
3664 * to be called when the system is still in usermode.
3666 * To prevent this, the preempt_enable_notrace will use this function
3667 * instead of preempt_schedule() to exit user context if needed before
3668 * calling the scheduler.
3670 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3672 enum ctx_state prev_ctx;
3674 if (likely(!preemptible()))
3679 * Because the function tracer can trace preempt_count_sub()
3680 * and it also uses preempt_enable/disable_notrace(), if
3681 * NEED_RESCHED is set, the preempt_enable_notrace() called
3682 * by the function tracer will call this function again and
3683 * cause infinite recursion.
3685 * Preemption must be disabled here before the function
3686 * tracer can trace. Break up preempt_disable() into two
3687 * calls. One to disable preemption without fear of being
3688 * traced. The other to still record the preemption latency,
3689 * which can also be traced by the function tracer.
3691 preempt_disable_notrace();
3692 preempt_latency_start(1);
3694 * Needs preempt disabled in case user_exit() is traced
3695 * and the tracer calls preempt_enable_notrace() causing
3696 * an infinite recursion.
3698 prev_ctx = exception_enter();
3700 exception_exit(prev_ctx);
3702 preempt_latency_stop(1);
3703 preempt_enable_no_resched_notrace();
3704 } while (need_resched());
3706 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3708 #endif /* CONFIG_PREEMPT */
3711 * this is the entry point to schedule() from kernel preemption
3712 * off of irq context.
3713 * Note, that this is called and return with irqs disabled. This will
3714 * protect us against recursive calling from irq.
3716 asmlinkage __visible void __sched preempt_schedule_irq(void)
3718 enum ctx_state prev_state;
3720 /* Catch callers which need to be fixed */
3721 BUG_ON(preempt_count() || !irqs_disabled());
3723 prev_state = exception_enter();
3729 local_irq_disable();
3730 sched_preempt_enable_no_resched();
3731 } while (need_resched());
3733 exception_exit(prev_state);
3736 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
3739 return try_to_wake_up(curr->private, mode, wake_flags);
3741 EXPORT_SYMBOL(default_wake_function);
3743 #ifdef CONFIG_RT_MUTEXES
3745 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
3748 prio = min(prio, pi_task->prio);
3753 static inline int rt_effective_prio(struct task_struct *p, int prio)
3755 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3757 return __rt_effective_prio(pi_task, prio);
3761 * rt_mutex_setprio - set the current priority of a task
3763 * @pi_task: donor task
3765 * This function changes the 'effective' priority of a task. It does
3766 * not touch ->normal_prio like __setscheduler().
3768 * Used by the rt_mutex code to implement priority inheritance
3769 * logic. Call site only calls if the priority of the task changed.
3771 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
3773 int prio, oldprio, queued, running, queue_flag =
3774 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
3775 const struct sched_class *prev_class;
3779 /* XXX used to be waiter->prio, not waiter->task->prio */
3780 prio = __rt_effective_prio(pi_task, p->normal_prio);
3783 * If nothing changed; bail early.
3785 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
3788 rq = __task_rq_lock(p, &rf);
3789 update_rq_clock(rq);
3791 * Set under pi_lock && rq->lock, such that the value can be used under
3794 * Note that there is loads of tricky to make this pointer cache work
3795 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3796 * ensure a task is de-boosted (pi_task is set to NULL) before the
3797 * task is allowed to run again (and can exit). This ensures the pointer
3798 * points to a blocked task -- which guaratees the task is present.
3800 p->pi_top_task = pi_task;
3803 * For FIFO/RR we only need to set prio, if that matches we're done.
3805 if (prio == p->prio && !dl_prio(prio))
3809 * Idle task boosting is a nono in general. There is one
3810 * exception, when PREEMPT_RT and NOHZ is active:
3812 * The idle task calls get_next_timer_interrupt() and holds
3813 * the timer wheel base->lock on the CPU and another CPU wants
3814 * to access the timer (probably to cancel it). We can safely
3815 * ignore the boosting request, as the idle CPU runs this code
3816 * with interrupts disabled and will complete the lock
3817 * protected section without being interrupted. So there is no
3818 * real need to boost.
3820 if (unlikely(p == rq->idle)) {
3821 WARN_ON(p != rq->curr);
3822 WARN_ON(p->pi_blocked_on);
3826 trace_sched_pi_setprio(p, pi_task);
3829 if (oldprio == prio)
3830 queue_flag &= ~DEQUEUE_MOVE;
3832 prev_class = p->sched_class;
3833 queued = task_on_rq_queued(p);
3834 running = task_current(rq, p);
3836 dequeue_task(rq, p, queue_flag);
3838 put_prev_task(rq, p);
3841 * Boosting condition are:
3842 * 1. -rt task is running and holds mutex A
3843 * --> -dl task blocks on mutex A
3845 * 2. -dl task is running and holds mutex A
3846 * --> -dl task blocks on mutex A and could preempt the
3849 if (dl_prio(prio)) {
3850 if (!dl_prio(p->normal_prio) ||
3851 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3852 p->dl.dl_boosted = 1;
3853 queue_flag |= ENQUEUE_REPLENISH;
3855 p->dl.dl_boosted = 0;
3856 p->sched_class = &dl_sched_class;
3857 } else if (rt_prio(prio)) {
3858 if (dl_prio(oldprio))
3859 p->dl.dl_boosted = 0;
3861 queue_flag |= ENQUEUE_HEAD;
3862 p->sched_class = &rt_sched_class;
3864 if (dl_prio(oldprio))
3865 p->dl.dl_boosted = 0;
3866 if (rt_prio(oldprio))
3868 p->sched_class = &fair_sched_class;
3874 enqueue_task(rq, p, queue_flag);
3876 set_curr_task(rq, p);
3878 check_class_changed(rq, p, prev_class, oldprio);
3880 /* Avoid rq from going away on us: */
3882 __task_rq_unlock(rq, &rf);
3884 balance_callback(rq);
3888 static inline int rt_effective_prio(struct task_struct *p, int prio)
3894 void set_user_nice(struct task_struct *p, long nice)
3896 bool queued, running;
3897 int old_prio, delta;
3901 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3904 * We have to be careful, if called from sys_setpriority(),
3905 * the task might be in the middle of scheduling on another CPU.
3907 rq = task_rq_lock(p, &rf);
3908 update_rq_clock(rq);
3911 * The RT priorities are set via sched_setscheduler(), but we still
3912 * allow the 'normal' nice value to be set - but as expected
3913 * it wont have any effect on scheduling until the task is
3914 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3916 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3917 p->static_prio = NICE_TO_PRIO(nice);
3920 queued = task_on_rq_queued(p);
3921 running = task_current(rq, p);
3923 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
3925 put_prev_task(rq, p);
3927 p->static_prio = NICE_TO_PRIO(nice);
3928 set_load_weight(p, true);
3930 p->prio = effective_prio(p);
3931 delta = p->prio - old_prio;
3934 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
3936 * If the task increased its priority or is running and
3937 * lowered its priority, then reschedule its CPU:
3939 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3943 set_curr_task(rq, p);
3945 task_rq_unlock(rq, p, &rf);
3947 EXPORT_SYMBOL(set_user_nice);
3950 * can_nice - check if a task can reduce its nice value
3954 int can_nice(const struct task_struct *p, const int nice)
3956 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
3957 int nice_rlim = nice_to_rlimit(nice);
3959 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3960 capable(CAP_SYS_NICE));
3963 #ifdef __ARCH_WANT_SYS_NICE
3966 * sys_nice - change the priority of the current process.
3967 * @increment: priority increment
3969 * sys_setpriority is a more generic, but much slower function that
3970 * does similar things.
3972 SYSCALL_DEFINE1(nice, int, increment)
3977 * Setpriority might change our priority at the same moment.
3978 * We don't have to worry. Conceptually one call occurs first
3979 * and we have a single winner.
3981 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3982 nice = task_nice(current) + increment;
3984 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3985 if (increment < 0 && !can_nice(current, nice))
3988 retval = security_task_setnice(current, nice);
3992 set_user_nice(current, nice);
3999 * task_prio - return the priority value of a given task.
4000 * @p: the task in question.
4002 * Return: The priority value as seen by users in /proc.
4003 * RT tasks are offset by -200. Normal tasks are centered
4004 * around 0, value goes from -16 to +15.
4006 int task_prio(const struct task_struct *p)
4008 return p->prio - MAX_RT_PRIO;
4012 * idle_cpu - is a given CPU idle currently?
4013 * @cpu: the processor in question.
4015 * Return: 1 if the CPU is currently idle. 0 otherwise.
4017 int idle_cpu(int cpu)
4019 struct rq *rq = cpu_rq(cpu);
4021 if (rq->curr != rq->idle)
4028 if (!llist_empty(&rq->wake_list))
4036 * available_idle_cpu - is a given CPU idle for enqueuing work.
4037 * @cpu: the CPU in question.
4039 * Return: 1 if the CPU is currently idle. 0 otherwise.
4041 int available_idle_cpu(int cpu)
4046 if (vcpu_is_preempted(cpu))
4053 * idle_task - return the idle task for a given CPU.
4054 * @cpu: the processor in question.
4056 * Return: The idle task for the CPU @cpu.
4058 struct task_struct *idle_task(int cpu)
4060 return cpu_rq(cpu)->idle;
4064 * find_process_by_pid - find a process with a matching PID value.
4065 * @pid: the pid in question.
4067 * The task of @pid, if found. %NULL otherwise.
4069 static struct task_struct *find_process_by_pid(pid_t pid)
4071 return pid ? find_task_by_vpid(pid) : current;
4075 * sched_setparam() passes in -1 for its policy, to let the functions
4076 * it calls know not to change it.
4078 #define SETPARAM_POLICY -1
4080 static void __setscheduler_params(struct task_struct *p,
4081 const struct sched_attr *attr)
4083 int policy = attr->sched_policy;
4085 if (policy == SETPARAM_POLICY)
4090 if (dl_policy(policy))
4091 __setparam_dl(p, attr);
4092 else if (fair_policy(policy))
4093 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4096 * __sched_setscheduler() ensures attr->sched_priority == 0 when
4097 * !rt_policy. Always setting this ensures that things like
4098 * getparam()/getattr() don't report silly values for !rt tasks.
4100 p->rt_priority = attr->sched_priority;
4101 p->normal_prio = normal_prio(p);
4102 set_load_weight(p, true);
4105 /* Actually do priority change: must hold pi & rq lock. */
4106 static void __setscheduler(struct rq *rq, struct task_struct *p,
4107 const struct sched_attr *attr, bool keep_boost)
4109 __setscheduler_params(p, attr);
4112 * Keep a potential priority boosting if called from
4113 * sched_setscheduler().
4115 p->prio = normal_prio(p);
4117 p->prio = rt_effective_prio(p, p->prio);
4119 if (dl_prio(p->prio))
4120 p->sched_class = &dl_sched_class;
4121 else if (rt_prio(p->prio))
4122 p->sched_class = &rt_sched_class;
4124 p->sched_class = &fair_sched_class;
4128 * Check the target process has a UID that matches the current process's:
4130 static bool check_same_owner(struct task_struct *p)
4132 const struct cred *cred = current_cred(), *pcred;
4136 pcred = __task_cred(p);
4137 match = (uid_eq(cred->euid, pcred->euid) ||
4138 uid_eq(cred->euid, pcred->uid));
4143 static int __sched_setscheduler(struct task_struct *p,
4144 const struct sched_attr *attr,
4147 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4148 MAX_RT_PRIO - 1 - attr->sched_priority;
4149 int retval, oldprio, oldpolicy = -1, queued, running;
4150 int new_effective_prio, policy = attr->sched_policy;
4151 const struct sched_class *prev_class;
4154 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
4157 /* The pi code expects interrupts enabled */
4158 BUG_ON(pi && in_interrupt());
4160 /* Double check policy once rq lock held: */
4162 reset_on_fork = p->sched_reset_on_fork;
4163 policy = oldpolicy = p->policy;
4165 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4167 if (!valid_policy(policy))
4171 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
4175 * Valid priorities for SCHED_FIFO and SCHED_RR are
4176 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4177 * SCHED_BATCH and SCHED_IDLE is 0.
4179 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4180 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4182 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4183 (rt_policy(policy) != (attr->sched_priority != 0)))
4187 * Allow unprivileged RT tasks to decrease priority:
4189 if (user && !capable(CAP_SYS_NICE)) {
4190 if (fair_policy(policy)) {
4191 if (attr->sched_nice < task_nice(p) &&
4192 !can_nice(p, attr->sched_nice))
4196 if (rt_policy(policy)) {
4197 unsigned long rlim_rtprio =
4198 task_rlimit(p, RLIMIT_RTPRIO);
4200 /* Can't set/change the rt policy: */
4201 if (policy != p->policy && !rlim_rtprio)
4204 /* Can't increase priority: */
4205 if (attr->sched_priority > p->rt_priority &&
4206 attr->sched_priority > rlim_rtprio)
4211 * Can't set/change SCHED_DEADLINE policy at all for now
4212 * (safest behavior); in the future we would like to allow
4213 * unprivileged DL tasks to increase their relative deadline
4214 * or reduce their runtime (both ways reducing utilization)
4216 if (dl_policy(policy))
4220 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4221 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4223 if (idle_policy(p->policy) && !idle_policy(policy)) {
4224 if (!can_nice(p, task_nice(p)))
4228 /* Can't change other user's priorities: */
4229 if (!check_same_owner(p))
4232 /* Normal users shall not reset the sched_reset_on_fork flag: */
4233 if (p->sched_reset_on_fork && !reset_on_fork)
4238 if (attr->sched_flags & SCHED_FLAG_SUGOV)
4241 retval = security_task_setscheduler(p);
4247 * Make sure no PI-waiters arrive (or leave) while we are
4248 * changing the priority of the task:
4250 * To be able to change p->policy safely, the appropriate
4251 * runqueue lock must be held.
4253 rq = task_rq_lock(p, &rf);
4254 update_rq_clock(rq);
4257 * Changing the policy of the stop threads its a very bad idea:
4259 if (p == rq->stop) {
4260 task_rq_unlock(rq, p, &rf);
4265 * If not changing anything there's no need to proceed further,
4266 * but store a possible modification of reset_on_fork.
4268 if (unlikely(policy == p->policy)) {
4269 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4271 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4273 if (dl_policy(policy) && dl_param_changed(p, attr))
4276 p->sched_reset_on_fork = reset_on_fork;
4277 task_rq_unlock(rq, p, &rf);
4283 #ifdef CONFIG_RT_GROUP_SCHED
4285 * Do not allow realtime tasks into groups that have no runtime
4288 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4289 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4290 !task_group_is_autogroup(task_group(p))) {
4291 task_rq_unlock(rq, p, &rf);
4296 if (dl_bandwidth_enabled() && dl_policy(policy) &&
4297 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
4298 cpumask_t *span = rq->rd->span;
4301 * Don't allow tasks with an affinity mask smaller than
4302 * the entire root_domain to become SCHED_DEADLINE. We
4303 * will also fail if there's no bandwidth available.
4305 if (!cpumask_subset(span, &p->cpus_allowed) ||
4306 rq->rd->dl_bw.bw == 0) {
4307 task_rq_unlock(rq, p, &rf);
4314 /* Re-check policy now with rq lock held: */
4315 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4316 policy = oldpolicy = -1;
4317 task_rq_unlock(rq, p, &rf);
4322 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4323 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4326 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
4327 task_rq_unlock(rq, p, &rf);
4331 p->sched_reset_on_fork = reset_on_fork;
4336 * Take priority boosted tasks into account. If the new
4337 * effective priority is unchanged, we just store the new
4338 * normal parameters and do not touch the scheduler class and
4339 * the runqueue. This will be done when the task deboost
4342 new_effective_prio = rt_effective_prio(p, newprio);
4343 if (new_effective_prio == oldprio)
4344 queue_flags &= ~DEQUEUE_MOVE;
4347 queued = task_on_rq_queued(p);
4348 running = task_current(rq, p);
4350 dequeue_task(rq, p, queue_flags);
4352 put_prev_task(rq, p);
4354 prev_class = p->sched_class;
4355 __setscheduler(rq, p, attr, pi);
4359 * We enqueue to tail when the priority of a task is
4360 * increased (user space view).
4362 if (oldprio < p->prio)
4363 queue_flags |= ENQUEUE_HEAD;
4365 enqueue_task(rq, p, queue_flags);
4368 set_curr_task(rq, p);
4370 check_class_changed(rq, p, prev_class, oldprio);
4372 /* Avoid rq from going away on us: */
4374 task_rq_unlock(rq, p, &rf);
4377 rt_mutex_adjust_pi(p);
4379 /* Run balance callbacks after we've adjusted the PI chain: */
4380 balance_callback(rq);
4386 static int _sched_setscheduler(struct task_struct *p, int policy,
4387 const struct sched_param *param, bool check)
4389 struct sched_attr attr = {
4390 .sched_policy = policy,
4391 .sched_priority = param->sched_priority,
4392 .sched_nice = PRIO_TO_NICE(p->static_prio),
4395 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4396 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4397 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4398 policy &= ~SCHED_RESET_ON_FORK;
4399 attr.sched_policy = policy;
4402 return __sched_setscheduler(p, &attr, check, true);
4405 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4406 * @p: the task in question.
4407 * @policy: new policy.
4408 * @param: structure containing the new RT priority.
4410 * Return: 0 on success. An error code otherwise.
4412 * NOTE that the task may be already dead.
4414 int sched_setscheduler(struct task_struct *p, int policy,
4415 const struct sched_param *param)
4417 return _sched_setscheduler(p, policy, param, true);
4419 EXPORT_SYMBOL_GPL(sched_setscheduler);
4421 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4423 return __sched_setscheduler(p, attr, true, true);
4425 EXPORT_SYMBOL_GPL(sched_setattr);
4427 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
4429 return __sched_setscheduler(p, attr, false, true);
4433 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4434 * @p: the task in question.
4435 * @policy: new policy.
4436 * @param: structure containing the new RT priority.
4438 * Just like sched_setscheduler, only don't bother checking if the
4439 * current context has permission. For example, this is needed in
4440 * stop_machine(): we create temporary high priority worker threads,
4441 * but our caller might not have that capability.
4443 * Return: 0 on success. An error code otherwise.
4445 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4446 const struct sched_param *param)
4448 return _sched_setscheduler(p, policy, param, false);
4450 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4453 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4455 struct sched_param lparam;
4456 struct task_struct *p;
4459 if (!param || pid < 0)
4461 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4466 p = find_process_by_pid(pid);
4468 retval = sched_setscheduler(p, policy, &lparam);
4475 * Mimics kernel/events/core.c perf_copy_attr().
4477 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
4482 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4485 /* Zero the full structure, so that a short copy will be nice: */
4486 memset(attr, 0, sizeof(*attr));
4488 ret = get_user(size, &uattr->size);
4492 /* Bail out on silly large: */
4493 if (size > PAGE_SIZE)
4496 /* ABI compatibility quirk: */
4498 size = SCHED_ATTR_SIZE_VER0;
4500 if (size < SCHED_ATTR_SIZE_VER0)
4504 * If we're handed a bigger struct than we know of,
4505 * ensure all the unknown bits are 0 - i.e. new
4506 * user-space does not rely on any kernel feature
4507 * extensions we dont know about yet.
4509 if (size > sizeof(*attr)) {
4510 unsigned char __user *addr;
4511 unsigned char __user *end;
4514 addr = (void __user *)uattr + sizeof(*attr);
4515 end = (void __user *)uattr + size;
4517 for (; addr < end; addr++) {
4518 ret = get_user(val, addr);
4524 size = sizeof(*attr);
4527 ret = copy_from_user(attr, uattr, size);
4532 * XXX: Do we want to be lenient like existing syscalls; or do we want
4533 * to be strict and return an error on out-of-bounds values?
4535 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4540 put_user(sizeof(*attr), &uattr->size);
4545 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4546 * @pid: the pid in question.
4547 * @policy: new policy.
4548 * @param: structure containing the new RT priority.
4550 * Return: 0 on success. An error code otherwise.
4552 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
4557 return do_sched_setscheduler(pid, policy, param);
4561 * sys_sched_setparam - set/change the RT priority of a thread
4562 * @pid: the pid in question.
4563 * @param: structure containing the new RT priority.
4565 * Return: 0 on success. An error code otherwise.
4567 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4569 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4573 * sys_sched_setattr - same as above, but with extended sched_attr
4574 * @pid: the pid in question.
4575 * @uattr: structure containing the extended parameters.
4576 * @flags: for future extension.
4578 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4579 unsigned int, flags)
4581 struct sched_attr attr;
4582 struct task_struct *p;
4585 if (!uattr || pid < 0 || flags)
4588 retval = sched_copy_attr(uattr, &attr);
4592 if ((int)attr.sched_policy < 0)
4597 p = find_process_by_pid(pid);
4599 retval = sched_setattr(p, &attr);
4606 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4607 * @pid: the pid in question.
4609 * Return: On success, the policy of the thread. Otherwise, a negative error
4612 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4614 struct task_struct *p;
4622 p = find_process_by_pid(pid);
4624 retval = security_task_getscheduler(p);
4627 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4634 * sys_sched_getparam - get the RT priority of a thread
4635 * @pid: the pid in question.
4636 * @param: structure containing the RT priority.
4638 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4641 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4643 struct sched_param lp = { .sched_priority = 0 };
4644 struct task_struct *p;
4647 if (!param || pid < 0)
4651 p = find_process_by_pid(pid);
4656 retval = security_task_getscheduler(p);
4660 if (task_has_rt_policy(p))
4661 lp.sched_priority = p->rt_priority;
4665 * This one might sleep, we cannot do it with a spinlock held ...
4667 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4676 static int sched_read_attr(struct sched_attr __user *uattr,
4677 struct sched_attr *attr,
4682 if (!access_ok(VERIFY_WRITE, uattr, usize))
4686 * If we're handed a smaller struct than we know of,
4687 * ensure all the unknown bits are 0 - i.e. old
4688 * user-space does not get uncomplete information.
4690 if (usize < sizeof(*attr)) {
4691 unsigned char *addr;
4694 addr = (void *)attr + usize;
4695 end = (void *)attr + sizeof(*attr);
4697 for (; addr < end; addr++) {
4705 ret = copy_to_user(uattr, attr, attr->size);
4713 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4714 * @pid: the pid in question.
4715 * @uattr: structure containing the extended parameters.
4716 * @size: sizeof(attr) for fwd/bwd comp.
4717 * @flags: for future extension.
4719 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4720 unsigned int, size, unsigned int, flags)
4722 struct sched_attr attr = {
4723 .size = sizeof(struct sched_attr),
4725 struct task_struct *p;
4728 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4729 size < SCHED_ATTR_SIZE_VER0 || flags)
4733 p = find_process_by_pid(pid);
4738 retval = security_task_getscheduler(p);
4742 attr.sched_policy = p->policy;
4743 if (p->sched_reset_on_fork)
4744 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4745 if (task_has_dl_policy(p))
4746 __getparam_dl(p, &attr);
4747 else if (task_has_rt_policy(p))
4748 attr.sched_priority = p->rt_priority;
4750 attr.sched_nice = task_nice(p);
4754 retval = sched_read_attr(uattr, &attr, size);
4762 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4764 cpumask_var_t cpus_allowed, new_mask;
4765 struct task_struct *p;
4770 p = find_process_by_pid(pid);
4776 /* Prevent p going away */
4780 if (p->flags & PF_NO_SETAFFINITY) {
4784 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4788 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4790 goto out_free_cpus_allowed;
4793 if (!check_same_owner(p)) {
4795 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4797 goto out_free_new_mask;
4802 retval = security_task_setscheduler(p);
4804 goto out_free_new_mask;
4807 cpuset_cpus_allowed(p, cpus_allowed);
4808 cpumask_and(new_mask, in_mask, cpus_allowed);
4811 * Since bandwidth control happens on root_domain basis,
4812 * if admission test is enabled, we only admit -deadline
4813 * tasks allowed to run on all the CPUs in the task's
4817 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4819 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4822 goto out_free_new_mask;
4828 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4831 cpuset_cpus_allowed(p, cpus_allowed);
4832 if (!cpumask_subset(new_mask, cpus_allowed)) {
4834 * We must have raced with a concurrent cpuset
4835 * update. Just reset the cpus_allowed to the
4836 * cpuset's cpus_allowed
4838 cpumask_copy(new_mask, cpus_allowed);
4843 free_cpumask_var(new_mask);
4844 out_free_cpus_allowed:
4845 free_cpumask_var(cpus_allowed);
4851 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4852 struct cpumask *new_mask)
4854 if (len < cpumask_size())
4855 cpumask_clear(new_mask);
4856 else if (len > cpumask_size())
4857 len = cpumask_size();
4859 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4863 * sys_sched_setaffinity - set the CPU affinity of a process
4864 * @pid: pid of the process
4865 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4866 * @user_mask_ptr: user-space pointer to the new CPU mask
4868 * Return: 0 on success. An error code otherwise.
4870 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4871 unsigned long __user *, user_mask_ptr)
4873 cpumask_var_t new_mask;
4876 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4879 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4881 retval = sched_setaffinity(pid, new_mask);
4882 free_cpumask_var(new_mask);
4886 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4888 struct task_struct *p;
4889 unsigned long flags;
4895 p = find_process_by_pid(pid);
4899 retval = security_task_getscheduler(p);
4903 raw_spin_lock_irqsave(&p->pi_lock, flags);
4904 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4905 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4914 * sys_sched_getaffinity - get the CPU affinity of a process
4915 * @pid: pid of the process
4916 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4917 * @user_mask_ptr: user-space pointer to hold the current CPU mask
4919 * Return: size of CPU mask copied to user_mask_ptr on success. An
4920 * error code otherwise.
4922 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4923 unsigned long __user *, user_mask_ptr)
4928 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4930 if (len & (sizeof(unsigned long)-1))
4933 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4936 ret = sched_getaffinity(pid, mask);
4938 unsigned int retlen = min(len, cpumask_size());
4940 if (copy_to_user(user_mask_ptr, mask, retlen))
4945 free_cpumask_var(mask);
4951 * sys_sched_yield - yield the current processor to other threads.
4953 * This function yields the current CPU to other tasks. If there are no
4954 * other threads running on this CPU then this function will return.
4958 static void do_sched_yield(void)
4963 local_irq_disable();
4967 schedstat_inc(rq->yld_count);
4968 current->sched_class->yield_task(rq);
4971 * Since we are going to call schedule() anyway, there's
4972 * no need to preempt or enable interrupts:
4976 sched_preempt_enable_no_resched();
4981 SYSCALL_DEFINE0(sched_yield)
4987 #ifndef CONFIG_PREEMPT
4988 int __sched _cond_resched(void)
4990 if (should_resched(0)) {
4991 preempt_schedule_common();
4997 EXPORT_SYMBOL(_cond_resched);
5001 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5002 * call schedule, and on return reacquire the lock.
5004 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5005 * operations here to prevent schedule() from being called twice (once via
5006 * spin_unlock(), once by hand).
5008 int __cond_resched_lock(spinlock_t *lock)
5010 int resched = should_resched(PREEMPT_LOCK_OFFSET);
5013 lockdep_assert_held(lock);
5015 if (spin_needbreak(lock) || resched) {
5018 preempt_schedule_common();
5026 EXPORT_SYMBOL(__cond_resched_lock);
5029 * yield - yield the current processor to other threads.
5031 * Do not ever use this function, there's a 99% chance you're doing it wrong.
5033 * The scheduler is at all times free to pick the calling task as the most
5034 * eligible task to run, if removing the yield() call from your code breaks
5035 * it, its already broken.
5037 * Typical broken usage is:
5042 * where one assumes that yield() will let 'the other' process run that will
5043 * make event true. If the current task is a SCHED_FIFO task that will never
5044 * happen. Never use yield() as a progress guarantee!!
5046 * If you want to use yield() to wait for something, use wait_event().
5047 * If you want to use yield() to be 'nice' for others, use cond_resched().
5048 * If you still want to use yield(), do not!
5050 void __sched yield(void)
5052 set_current_state(TASK_RUNNING);
5055 EXPORT_SYMBOL(yield);
5058 * yield_to - yield the current processor to another thread in
5059 * your thread group, or accelerate that thread toward the
5060 * processor it's on.
5062 * @preempt: whether task preemption is allowed or not
5064 * It's the caller's job to ensure that the target task struct
5065 * can't go away on us before we can do any checks.
5068 * true (>0) if we indeed boosted the target task.
5069 * false (0) if we failed to boost the target.
5070 * -ESRCH if there's no task to yield to.
5072 int __sched yield_to(struct task_struct *p, bool preempt)
5074 struct task_struct *curr = current;
5075 struct rq *rq, *p_rq;
5076 unsigned long flags;
5079 local_irq_save(flags);
5085 * If we're the only runnable task on the rq and target rq also
5086 * has only one task, there's absolutely no point in yielding.
5088 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5093 double_rq_lock(rq, p_rq);
5094 if (task_rq(p) != p_rq) {
5095 double_rq_unlock(rq, p_rq);
5099 if (!curr->sched_class->yield_to_task)
5102 if (curr->sched_class != p->sched_class)
5105 if (task_running(p_rq, p) || p->state)
5108 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5110 schedstat_inc(rq->yld_count);
5112 * Make p's CPU reschedule; pick_next_entity takes care of
5115 if (preempt && rq != p_rq)
5120 double_rq_unlock(rq, p_rq);
5122 local_irq_restore(flags);
5129 EXPORT_SYMBOL_GPL(yield_to);
5131 int io_schedule_prepare(void)
5133 int old_iowait = current->in_iowait;
5135 current->in_iowait = 1;
5136 blk_schedule_flush_plug(current);
5141 void io_schedule_finish(int token)
5143 current->in_iowait = token;
5147 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5148 * that process accounting knows that this is a task in IO wait state.
5150 long __sched io_schedule_timeout(long timeout)
5155 token = io_schedule_prepare();
5156 ret = schedule_timeout(timeout);
5157 io_schedule_finish(token);
5161 EXPORT_SYMBOL(io_schedule_timeout);
5163 void io_schedule(void)
5167 token = io_schedule_prepare();
5169 io_schedule_finish(token);
5171 EXPORT_SYMBOL(io_schedule);
5174 * sys_sched_get_priority_max - return maximum RT priority.
5175 * @policy: scheduling class.
5177 * Return: On success, this syscall returns the maximum
5178 * rt_priority that can be used by a given scheduling class.
5179 * On failure, a negative error code is returned.
5181 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5188 ret = MAX_USER_RT_PRIO-1;
5190 case SCHED_DEADLINE:
5201 * sys_sched_get_priority_min - return minimum RT priority.
5202 * @policy: scheduling class.
5204 * Return: On success, this syscall returns the minimum
5205 * rt_priority that can be used by a given scheduling class.
5206 * On failure, a negative error code is returned.
5208 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5217 case SCHED_DEADLINE:
5226 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
5228 struct task_struct *p;
5229 unsigned int time_slice;
5239 p = find_process_by_pid(pid);
5243 retval = security_task_getscheduler(p);
5247 rq = task_rq_lock(p, &rf);
5249 if (p->sched_class->get_rr_interval)
5250 time_slice = p->sched_class->get_rr_interval(rq, p);
5251 task_rq_unlock(rq, p, &rf);
5254 jiffies_to_timespec64(time_slice, t);
5263 * sys_sched_rr_get_interval - return the default timeslice of a process.
5264 * @pid: pid of the process.
5265 * @interval: userspace pointer to the timeslice value.
5267 * this syscall writes the default timeslice value of a given process
5268 * into the user-space timespec buffer. A value of '0' means infinity.
5270 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5273 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5274 struct timespec __user *, interval)
5276 struct timespec64 t;
5277 int retval = sched_rr_get_interval(pid, &t);
5280 retval = put_timespec64(&t, interval);
5285 #ifdef CONFIG_COMPAT
5286 COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
5288 struct compat_timespec __user *, interval)
5290 struct timespec64 t;
5291 int retval = sched_rr_get_interval(pid, &t);
5294 retval = compat_put_timespec64(&t, interval);
5299 void sched_show_task(struct task_struct *p)
5301 unsigned long free = 0;
5304 if (!try_get_task_stack(p))
5307 printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
5309 if (p->state == TASK_RUNNING)
5310 printk(KERN_CONT " running task ");
5311 #ifdef CONFIG_DEBUG_STACK_USAGE
5312 free = stack_not_used(p);
5317 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5319 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5320 task_pid_nr(p), ppid,
5321 (unsigned long)task_thread_info(p)->flags);
5323 print_worker_info(KERN_INFO, p);
5324 show_stack(p, NULL);
5327 EXPORT_SYMBOL_GPL(sched_show_task);
5330 state_filter_match(unsigned long state_filter, struct task_struct *p)
5332 /* no filter, everything matches */
5336 /* filter, but doesn't match */
5337 if (!(p->state & state_filter))
5341 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5344 if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
5351 void show_state_filter(unsigned long state_filter)
5353 struct task_struct *g, *p;
5355 #if BITS_PER_LONG == 32
5357 " task PC stack pid father\n");
5360 " task PC stack pid father\n");
5363 for_each_process_thread(g, p) {
5365 * reset the NMI-timeout, listing all files on a slow
5366 * console might take a lot of time:
5367 * Also, reset softlockup watchdogs on all CPUs, because
5368 * another CPU might be blocked waiting for us to process
5371 touch_nmi_watchdog();
5372 touch_all_softlockup_watchdogs();
5373 if (state_filter_match(state_filter, p))
5377 #ifdef CONFIG_SCHED_DEBUG
5379 sysrq_sched_debug_show();
5383 * Only show locks if all tasks are dumped:
5386 debug_show_all_locks();
5390 * init_idle - set up an idle thread for a given CPU
5391 * @idle: task in question
5392 * @cpu: CPU the idle task belongs to
5394 * NOTE: this function does not set the idle thread's NEED_RESCHED
5395 * flag, to make booting more robust.
5397 void init_idle(struct task_struct *idle, int cpu)
5399 struct rq *rq = cpu_rq(cpu);
5400 unsigned long flags;
5402 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5403 raw_spin_lock(&rq->lock);
5405 __sched_fork(0, idle);
5406 idle->state = TASK_RUNNING;
5407 idle->se.exec_start = sched_clock();
5408 idle->flags |= PF_IDLE;
5410 kasan_unpoison_task_stack(idle);
5414 * Its possible that init_idle() gets called multiple times on a task,
5415 * in that case do_set_cpus_allowed() will not do the right thing.
5417 * And since this is boot we can forgo the serialization.
5419 set_cpus_allowed_common(idle, cpumask_of(cpu));
5422 * We're having a chicken and egg problem, even though we are
5423 * holding rq->lock, the CPU isn't yet set to this CPU so the
5424 * lockdep check in task_group() will fail.
5426 * Similar case to sched_fork(). / Alternatively we could
5427 * use task_rq_lock() here and obtain the other rq->lock.
5432 __set_task_cpu(idle, cpu);
5435 rq->curr = rq->idle = idle;
5436 idle->on_rq = TASK_ON_RQ_QUEUED;
5440 raw_spin_unlock(&rq->lock);
5441 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5443 /* Set the preempt count _outside_ the spinlocks! */
5444 init_idle_preempt_count(idle, cpu);
5447 * The idle tasks have their own, simple scheduling class:
5449 idle->sched_class = &idle_sched_class;
5450 ftrace_graph_init_idle_task(idle, cpu);
5451 vtime_init_idle(idle, cpu);
5453 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5459 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5460 const struct cpumask *trial)
5464 if (!cpumask_weight(cur))
5467 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
5472 int task_can_attach(struct task_struct *p,
5473 const struct cpumask *cs_cpus_allowed)
5478 * Kthreads which disallow setaffinity shouldn't be moved
5479 * to a new cpuset; we don't want to change their CPU
5480 * affinity and isolating such threads by their set of
5481 * allowed nodes is unnecessary. Thus, cpusets are not
5482 * applicable for such threads. This prevents checking for
5483 * success of set_cpus_allowed_ptr() on all attached tasks
5484 * before cpus_allowed may be changed.
5486 if (p->flags & PF_NO_SETAFFINITY) {
5491 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5493 ret = dl_task_can_attach(p, cs_cpus_allowed);
5499 bool sched_smp_initialized __read_mostly;
5501 #ifdef CONFIG_NUMA_BALANCING
5502 /* Migrate current task p to target_cpu */
5503 int migrate_task_to(struct task_struct *p, int target_cpu)
5505 struct migration_arg arg = { p, target_cpu };
5506 int curr_cpu = task_cpu(p);
5508 if (curr_cpu == target_cpu)
5511 if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
5514 /* TODO: This is not properly updating schedstats */
5516 trace_sched_move_numa(p, curr_cpu, target_cpu);
5517 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5521 * Requeue a task on a given node and accurately track the number of NUMA
5522 * tasks on the runqueues
5524 void sched_setnuma(struct task_struct *p, int nid)
5526 bool queued, running;
5530 rq = task_rq_lock(p, &rf);
5531 queued = task_on_rq_queued(p);
5532 running = task_current(rq, p);
5535 dequeue_task(rq, p, DEQUEUE_SAVE);
5537 put_prev_task(rq, p);
5539 p->numa_preferred_nid = nid;
5542 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
5544 set_curr_task(rq, p);
5545 task_rq_unlock(rq, p, &rf);
5547 #endif /* CONFIG_NUMA_BALANCING */
5549 #ifdef CONFIG_HOTPLUG_CPU
5551 * Ensure that the idle task is using init_mm right before its CPU goes
5554 void idle_task_exit(void)
5556 struct mm_struct *mm = current->active_mm;
5558 BUG_ON(cpu_online(smp_processor_id()));
5560 if (mm != &init_mm) {
5561 switch_mm(mm, &init_mm, current);
5562 current->active_mm = &init_mm;
5563 finish_arch_post_lock_switch();
5569 * Since this CPU is going 'away' for a while, fold any nr_active delta
5570 * we might have. Assumes we're called after migrate_tasks() so that the
5571 * nr_active count is stable. We need to take the teardown thread which
5572 * is calling this into account, so we hand in adjust = 1 to the load
5575 * Also see the comment "Global load-average calculations".
5577 static void calc_load_migrate(struct rq *rq)
5579 long delta = calc_load_fold_active(rq, 1);
5581 atomic_long_add(delta, &calc_load_tasks);
5584 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5588 static const struct sched_class fake_sched_class = {
5589 .put_prev_task = put_prev_task_fake,
5592 static struct task_struct fake_task = {
5594 * Avoid pull_{rt,dl}_task()
5596 .prio = MAX_PRIO + 1,
5597 .sched_class = &fake_sched_class,
5601 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5602 * try_to_wake_up()->select_task_rq().
5604 * Called with rq->lock held even though we'er in stop_machine() and
5605 * there's no concurrency possible, we hold the required locks anyway
5606 * because of lock validation efforts.
5608 static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
5610 struct rq *rq = dead_rq;
5611 struct task_struct *next, *stop = rq->stop;
5612 struct rq_flags orf = *rf;
5616 * Fudge the rq selection such that the below task selection loop
5617 * doesn't get stuck on the currently eligible stop task.
5619 * We're currently inside stop_machine() and the rq is either stuck
5620 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5621 * either way we should never end up calling schedule() until we're
5627 * put_prev_task() and pick_next_task() sched
5628 * class method both need to have an up-to-date
5629 * value of rq->clock[_task]
5631 update_rq_clock(rq);
5635 * There's this thread running, bail when that's the only
5638 if (rq->nr_running == 1)
5642 * pick_next_task() assumes pinned rq->lock:
5644 next = pick_next_task(rq, &fake_task, rf);
5646 put_prev_task(rq, next);
5649 * Rules for changing task_struct::cpus_allowed are holding
5650 * both pi_lock and rq->lock, such that holding either
5651 * stabilizes the mask.
5653 * Drop rq->lock is not quite as disastrous as it usually is
5654 * because !cpu_active at this point, which means load-balance
5655 * will not interfere. Also, stop-machine.
5658 raw_spin_lock(&next->pi_lock);
5662 * Since we're inside stop-machine, _nothing_ should have
5663 * changed the task, WARN if weird stuff happened, because in
5664 * that case the above rq->lock drop is a fail too.
5666 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5667 raw_spin_unlock(&next->pi_lock);
5671 /* Find suitable destination for @next, with force if needed. */
5672 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5673 rq = __migrate_task(rq, rf, next, dest_cpu);
5674 if (rq != dead_rq) {
5680 raw_spin_unlock(&next->pi_lock);
5685 #endif /* CONFIG_HOTPLUG_CPU */
5687 void set_rq_online(struct rq *rq)
5690 const struct sched_class *class;
5692 cpumask_set_cpu(rq->cpu, rq->rd->online);
5695 for_each_class(class) {
5696 if (class->rq_online)
5697 class->rq_online(rq);
5702 void set_rq_offline(struct rq *rq)
5705 const struct sched_class *class;
5707 for_each_class(class) {
5708 if (class->rq_offline)
5709 class->rq_offline(rq);
5712 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5717 static void set_cpu_rq_start_time(unsigned int cpu)
5719 struct rq *rq = cpu_rq(cpu);
5721 rq->age_stamp = sched_clock_cpu(cpu);
5725 * used to mark begin/end of suspend/resume:
5727 static int num_cpus_frozen;
5730 * Update cpusets according to cpu_active mask. If cpusets are
5731 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5732 * around partition_sched_domains().
5734 * If we come here as part of a suspend/resume, don't touch cpusets because we
5735 * want to restore it back to its original state upon resume anyway.
5737 static void cpuset_cpu_active(void)
5739 if (cpuhp_tasks_frozen) {
5741 * num_cpus_frozen tracks how many CPUs are involved in suspend
5742 * resume sequence. As long as this is not the last online
5743 * operation in the resume sequence, just build a single sched
5744 * domain, ignoring cpusets.
5746 partition_sched_domains(1, NULL, NULL);
5747 if (--num_cpus_frozen)
5750 * This is the last CPU online operation. So fall through and
5751 * restore the original sched domains by considering the
5752 * cpuset configurations.
5754 cpuset_force_rebuild();
5756 cpuset_update_active_cpus();
5759 static int cpuset_cpu_inactive(unsigned int cpu)
5761 if (!cpuhp_tasks_frozen) {
5762 if (dl_cpu_busy(cpu))
5764 cpuset_update_active_cpus();
5767 partition_sched_domains(1, NULL, NULL);
5772 int sched_cpu_activate(unsigned int cpu)
5774 struct rq *rq = cpu_rq(cpu);
5777 set_cpu_active(cpu, true);
5779 if (sched_smp_initialized) {
5780 sched_domains_numa_masks_set(cpu);
5781 cpuset_cpu_active();
5785 * Put the rq online, if not already. This happens:
5787 * 1) In the early boot process, because we build the real domains
5788 * after all CPUs have been brought up.
5790 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5793 rq_lock_irqsave(rq, &rf);
5795 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5798 rq_unlock_irqrestore(rq, &rf);
5800 update_max_interval();
5805 int sched_cpu_deactivate(unsigned int cpu)
5809 set_cpu_active(cpu, false);
5811 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5812 * users of this state to go away such that all new such users will
5815 * Do sync before park smpboot threads to take care the rcu boost case.
5817 synchronize_rcu_mult(call_rcu, call_rcu_sched);
5819 if (!sched_smp_initialized)
5822 ret = cpuset_cpu_inactive(cpu);
5824 set_cpu_active(cpu, true);
5827 sched_domains_numa_masks_clear(cpu);
5831 static void sched_rq_cpu_starting(unsigned int cpu)
5833 struct rq *rq = cpu_rq(cpu);
5835 rq->calc_load_update = calc_load_update;
5836 update_max_interval();
5839 int sched_cpu_starting(unsigned int cpu)
5841 set_cpu_rq_start_time(cpu);
5842 sched_rq_cpu_starting(cpu);
5843 sched_tick_start(cpu);
5847 #ifdef CONFIG_HOTPLUG_CPU
5848 int sched_cpu_dying(unsigned int cpu)
5850 struct rq *rq = cpu_rq(cpu);
5853 /* Handle pending wakeups and then migrate everything off */
5854 sched_ttwu_pending();
5855 sched_tick_stop(cpu);
5857 rq_lock_irqsave(rq, &rf);
5859 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5862 migrate_tasks(rq, &rf);
5863 BUG_ON(rq->nr_running != 1);
5864 rq_unlock_irqrestore(rq, &rf);
5866 calc_load_migrate(rq);
5867 update_max_interval();
5868 nohz_balance_exit_idle(rq);
5874 #ifdef CONFIG_SCHED_SMT
5875 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
5877 static void sched_init_smt(void)
5880 * We've enumerated all CPUs and will assume that if any CPU
5881 * has SMT siblings, CPU0 will too.
5883 if (cpumask_weight(cpu_smt_mask(0)) > 1)
5884 static_branch_enable(&sched_smt_present);
5887 static inline void sched_init_smt(void) { }
5890 void __init sched_init_smp(void)
5895 * There's no userspace yet to cause hotplug operations; hence all the
5896 * CPU masks are stable and all blatant races in the below code cannot
5899 mutex_lock(&sched_domains_mutex);
5900 sched_init_domains(cpu_active_mask);
5901 mutex_unlock(&sched_domains_mutex);
5903 /* Move init over to a non-isolated CPU */
5904 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5906 sched_init_granularity();
5908 init_sched_rt_class();
5909 init_sched_dl_class();
5913 sched_smp_initialized = true;
5916 static int __init migration_init(void)
5918 sched_rq_cpu_starting(smp_processor_id());
5921 early_initcall(migration_init);
5924 void __init sched_init_smp(void)
5926 sched_init_granularity();
5928 #endif /* CONFIG_SMP */
5930 int in_sched_functions(unsigned long addr)
5932 return in_lock_functions(addr) ||
5933 (addr >= (unsigned long)__sched_text_start
5934 && addr < (unsigned long)__sched_text_end);
5937 #ifdef CONFIG_CGROUP_SCHED
5939 * Default task group.
5940 * Every task in system belongs to this group at bootup.
5942 struct task_group root_task_group;
5943 LIST_HEAD(task_groups);
5945 /* Cacheline aligned slab cache for task_group */
5946 static struct kmem_cache *task_group_cache __read_mostly;
5949 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
5950 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
5952 void __init sched_init(void)
5955 unsigned long alloc_size = 0, ptr;
5960 #ifdef CONFIG_FAIR_GROUP_SCHED
5961 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5963 #ifdef CONFIG_RT_GROUP_SCHED
5964 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5967 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
5969 #ifdef CONFIG_FAIR_GROUP_SCHED
5970 root_task_group.se = (struct sched_entity **)ptr;
5971 ptr += nr_cpu_ids * sizeof(void **);
5973 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
5974 ptr += nr_cpu_ids * sizeof(void **);
5976 #endif /* CONFIG_FAIR_GROUP_SCHED */
5977 #ifdef CONFIG_RT_GROUP_SCHED
5978 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
5979 ptr += nr_cpu_ids * sizeof(void **);
5981 root_task_group.rt_rq = (struct rt_rq **)ptr;
5982 ptr += nr_cpu_ids * sizeof(void **);
5984 #endif /* CONFIG_RT_GROUP_SCHED */
5986 #ifdef CONFIG_CPUMASK_OFFSTACK
5987 for_each_possible_cpu(i) {
5988 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
5989 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5990 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
5991 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5993 #endif /* CONFIG_CPUMASK_OFFSTACK */
5995 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
5996 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
5999 init_defrootdomain();
6002 #ifdef CONFIG_RT_GROUP_SCHED
6003 init_rt_bandwidth(&root_task_group.rt_bandwidth,
6004 global_rt_period(), global_rt_runtime());
6005 #endif /* CONFIG_RT_GROUP_SCHED */
6007 #ifdef CONFIG_CGROUP_SCHED
6008 task_group_cache = KMEM_CACHE(task_group, 0);
6010 list_add(&root_task_group.list, &task_groups);
6011 INIT_LIST_HEAD(&root_task_group.children);
6012 INIT_LIST_HEAD(&root_task_group.siblings);
6013 autogroup_init(&init_task);
6014 #endif /* CONFIG_CGROUP_SCHED */
6016 for_each_possible_cpu(i) {
6020 raw_spin_lock_init(&rq->lock);
6022 rq->calc_load_active = 0;
6023 rq->calc_load_update = jiffies + LOAD_FREQ;
6024 init_cfs_rq(&rq->cfs);
6025 init_rt_rq(&rq->rt);
6026 init_dl_rq(&rq->dl);
6027 #ifdef CONFIG_FAIR_GROUP_SCHED
6028 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6029 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6030 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
6032 * How much CPU bandwidth does root_task_group get?
6034 * In case of task-groups formed thr' the cgroup filesystem, it
6035 * gets 100% of the CPU resources in the system. This overall
6036 * system CPU resource is divided among the tasks of
6037 * root_task_group and its child task-groups in a fair manner,
6038 * based on each entity's (task or task-group's) weight
6039 * (se->load.weight).
6041 * In other words, if root_task_group has 10 tasks of weight
6042 * 1024) and two child groups A0 and A1 (of weight 1024 each),
6043 * then A0's share of the CPU resource is:
6045 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
6047 * We achieve this by letting root_task_group's tasks sit
6048 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
6050 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
6051 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
6052 #endif /* CONFIG_FAIR_GROUP_SCHED */
6054 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
6055 #ifdef CONFIG_RT_GROUP_SCHED
6056 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
6059 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6060 rq->cpu_load[j] = 0;
6065 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
6066 rq->balance_callback = NULL;
6067 rq->active_balance = 0;
6068 rq->next_balance = jiffies;
6073 rq->avg_idle = 2*sysctl_sched_migration_cost;
6074 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
6076 INIT_LIST_HEAD(&rq->cfs_tasks);
6078 rq_attach_root(rq, &def_root_domain);
6079 #ifdef CONFIG_NO_HZ_COMMON
6080 rq->last_load_update_tick = jiffies;
6081 rq->last_blocked_load_update_tick = jiffies;
6082 atomic_set(&rq->nohz_flags, 0);
6084 #endif /* CONFIG_SMP */
6086 atomic_set(&rq->nr_iowait, 0);
6089 set_load_weight(&init_task, false);
6092 * The boot idle thread does lazy MMU switching as well:
6095 enter_lazy_tlb(&init_mm, current);
6098 * Make us the idle thread. Technically, schedule() should not be
6099 * called from this thread, however somewhere below it might be,
6100 * but because we are the idle thread, we just pick up running again
6101 * when this runqueue becomes "idle".
6103 init_idle(current, smp_processor_id());
6105 calc_load_update = jiffies + LOAD_FREQ;
6108 idle_thread_set_boot_cpu();
6109 set_cpu_rq_start_time(smp_processor_id());
6111 init_sched_fair_class();
6115 scheduler_running = 1;
6118 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
6119 static inline int preempt_count_equals(int preempt_offset)
6121 int nested = preempt_count() + rcu_preempt_depth();
6123 return (nested == preempt_offset);
6126 void __might_sleep(const char *file, int line, int preempt_offset)
6129 * Blocking primitives will set (and therefore destroy) current->state,
6130 * since we will exit with TASK_RUNNING make sure we enter with it,
6131 * otherwise we will destroy state.
6133 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
6134 "do not call blocking ops when !TASK_RUNNING; "
6135 "state=%lx set at [<%p>] %pS\n",
6137 (void *)current->task_state_change,
6138 (void *)current->task_state_change);
6140 ___might_sleep(file, line, preempt_offset);
6142 EXPORT_SYMBOL(__might_sleep);
6144 void ___might_sleep(const char *file, int line, int preempt_offset)
6146 /* Ratelimiting timestamp: */
6147 static unsigned long prev_jiffy;
6149 unsigned long preempt_disable_ip;
6151 /* WARN_ON_ONCE() by default, no rate limit required: */
6154 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6155 !is_idle_task(current)) ||
6156 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
6160 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6162 prev_jiffy = jiffies;
6164 /* Save this before calling printk(), since that will clobber it: */
6165 preempt_disable_ip = get_preempt_disable_ip(current);
6168 "BUG: sleeping function called from invalid context at %s:%d\n",
6171 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6172 in_atomic(), irqs_disabled(),
6173 current->pid, current->comm);
6175 if (task_stack_end_corrupted(current))
6176 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6178 debug_show_held_locks(current);
6179 if (irqs_disabled())
6180 print_irqtrace_events(current);
6181 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6182 && !preempt_count_equals(preempt_offset)) {
6183 pr_err("Preemption disabled at:");
6184 print_ip_sym(preempt_disable_ip);
6188 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6190 EXPORT_SYMBOL(___might_sleep);
6193 #ifdef CONFIG_MAGIC_SYSRQ
6194 void normalize_rt_tasks(void)
6196 struct task_struct *g, *p;
6197 struct sched_attr attr = {
6198 .sched_policy = SCHED_NORMAL,
6201 read_lock(&tasklist_lock);
6202 for_each_process_thread(g, p) {
6204 * Only normalize user tasks:
6206 if (p->flags & PF_KTHREAD)
6209 p->se.exec_start = 0;
6210 schedstat_set(p->se.statistics.wait_start, 0);
6211 schedstat_set(p->se.statistics.sleep_start, 0);
6212 schedstat_set(p->se.statistics.block_start, 0);
6214 if (!dl_task(p) && !rt_task(p)) {
6216 * Renice negative nice level userspace
6219 if (task_nice(p) < 0)
6220 set_user_nice(p, 0);
6224 __sched_setscheduler(p, &attr, false, false);
6226 read_unlock(&tasklist_lock);
6229 #endif /* CONFIG_MAGIC_SYSRQ */
6231 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
6233 * These functions are only useful for the IA64 MCA handling, or kdb.
6235 * They can only be called when the whole system has been
6236 * stopped - every CPU needs to be quiescent, and no scheduling
6237 * activity can take place. Using them for anything else would
6238 * be a serious bug, and as a result, they aren't even visible
6239 * under any other configuration.
6243 * curr_task - return the current task for a given CPU.
6244 * @cpu: the processor in question.
6246 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6248 * Return: The current task for @cpu.
6250 struct task_struct *curr_task(int cpu)
6252 return cpu_curr(cpu);
6255 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6259 * set_curr_task - set the current task for a given CPU.
6260 * @cpu: the processor in question.
6261 * @p: the task pointer to set.
6263 * Description: This function must only be used when non-maskable interrupts
6264 * are serviced on a separate stack. It allows the architecture to switch the
6265 * notion of the current task on a CPU in a non-blocking manner. This function
6266 * must be called with all CPU's synchronized, and interrupts disabled, the
6267 * and caller must save the original value of the current task (see
6268 * curr_task() above) and restore that value before reenabling interrupts and
6269 * re-starting the system.
6271 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6273 void ia64_set_curr_task(int cpu, struct task_struct *p)
6280 #ifdef CONFIG_CGROUP_SCHED
6281 /* task_group_lock serializes the addition/removal of task groups */
6282 static DEFINE_SPINLOCK(task_group_lock);
6284 static void sched_free_group(struct task_group *tg)
6286 free_fair_sched_group(tg);
6287 free_rt_sched_group(tg);
6289 kmem_cache_free(task_group_cache, tg);
6292 /* allocate runqueue etc for a new task group */
6293 struct task_group *sched_create_group(struct task_group *parent)
6295 struct task_group *tg;
6297 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
6299 return ERR_PTR(-ENOMEM);
6301 if (!alloc_fair_sched_group(tg, parent))
6304 if (!alloc_rt_sched_group(tg, parent))
6310 sched_free_group(tg);
6311 return ERR_PTR(-ENOMEM);
6314 void sched_online_group(struct task_group *tg, struct task_group *parent)
6316 unsigned long flags;
6318 spin_lock_irqsave(&task_group_lock, flags);
6319 list_add_rcu(&tg->list, &task_groups);
6321 /* Root should already exist: */
6324 tg->parent = parent;
6325 INIT_LIST_HEAD(&tg->children);
6326 list_add_rcu(&tg->siblings, &parent->children);
6327 spin_unlock_irqrestore(&task_group_lock, flags);
6329 online_fair_sched_group(tg);
6332 /* rcu callback to free various structures associated with a task group */
6333 static void sched_free_group_rcu(struct rcu_head *rhp)
6335 /* Now it should be safe to free those cfs_rqs: */
6336 sched_free_group(container_of(rhp, struct task_group, rcu));
6339 void sched_destroy_group(struct task_group *tg)
6341 /* Wait for possible concurrent references to cfs_rqs complete: */
6342 call_rcu(&tg->rcu, sched_free_group_rcu);
6345 void sched_offline_group(struct task_group *tg)
6347 unsigned long flags;
6349 /* End participation in shares distribution: */
6350 unregister_fair_sched_group(tg);
6352 spin_lock_irqsave(&task_group_lock, flags);
6353 list_del_rcu(&tg->list);
6354 list_del_rcu(&tg->siblings);
6355 spin_unlock_irqrestore(&task_group_lock, flags);
6358 static void sched_change_group(struct task_struct *tsk, int type)
6360 struct task_group *tg;
6363 * All callers are synchronized by task_rq_lock(); we do not use RCU
6364 * which is pointless here. Thus, we pass "true" to task_css_check()
6365 * to prevent lockdep warnings.
6367 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
6368 struct task_group, css);
6369 tg = autogroup_task_group(tsk, tg);
6370 tsk->sched_task_group = tg;
6372 #ifdef CONFIG_FAIR_GROUP_SCHED
6373 if (tsk->sched_class->task_change_group)
6374 tsk->sched_class->task_change_group(tsk, type);
6377 set_task_rq(tsk, task_cpu(tsk));
6381 * Change task's runqueue when it moves between groups.
6383 * The caller of this function should have put the task in its new group by
6384 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6387 void sched_move_task(struct task_struct *tsk)
6389 int queued, running, queue_flags =
6390 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6394 rq = task_rq_lock(tsk, &rf);
6395 update_rq_clock(rq);
6397 running = task_current(rq, tsk);
6398 queued = task_on_rq_queued(tsk);
6401 dequeue_task(rq, tsk, queue_flags);
6403 put_prev_task(rq, tsk);
6405 sched_change_group(tsk, TASK_MOVE_GROUP);
6408 enqueue_task(rq, tsk, queue_flags);
6410 set_curr_task(rq, tsk);
6412 task_rq_unlock(rq, tsk, &rf);
6415 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
6417 return css ? container_of(css, struct task_group, css) : NULL;
6420 static struct cgroup_subsys_state *
6421 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6423 struct task_group *parent = css_tg(parent_css);
6424 struct task_group *tg;
6427 /* This is early initialization for the top cgroup */
6428 return &root_task_group.css;
6431 tg = sched_create_group(parent);
6433 return ERR_PTR(-ENOMEM);
6438 /* Expose task group only after completing cgroup initialization */
6439 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6441 struct task_group *tg = css_tg(css);
6442 struct task_group *parent = css_tg(css->parent);
6445 sched_online_group(tg, parent);
6449 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
6451 struct task_group *tg = css_tg(css);
6453 sched_offline_group(tg);
6456 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
6458 struct task_group *tg = css_tg(css);
6461 * Relies on the RCU grace period between css_released() and this.
6463 sched_free_group(tg);
6467 * This is called before wake_up_new_task(), therefore we really only
6468 * have to set its group bits, all the other stuff does not apply.
6470 static void cpu_cgroup_fork(struct task_struct *task)
6475 rq = task_rq_lock(task, &rf);
6477 update_rq_clock(rq);
6478 sched_change_group(task, TASK_SET_GROUP);
6480 task_rq_unlock(rq, task, &rf);
6483 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
6485 struct task_struct *task;
6486 struct cgroup_subsys_state *css;
6489 cgroup_taskset_for_each(task, css, tset) {
6490 #ifdef CONFIG_RT_GROUP_SCHED
6491 if (!sched_rt_can_attach(css_tg(css), task))
6494 /* We don't support RT-tasks being in separate groups */
6495 if (task->sched_class != &fair_sched_class)
6499 * Serialize against wake_up_new_task() such that if its
6500 * running, we're sure to observe its full state.
6502 raw_spin_lock_irq(&task->pi_lock);
6504 * Avoid calling sched_move_task() before wake_up_new_task()
6505 * has happened. This would lead to problems with PELT, due to
6506 * move wanting to detach+attach while we're not attached yet.
6508 if (task->state == TASK_NEW)
6510 raw_spin_unlock_irq(&task->pi_lock);
6518 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
6520 struct task_struct *task;
6521 struct cgroup_subsys_state *css;
6523 cgroup_taskset_for_each(task, css, tset)
6524 sched_move_task(task);
6527 #ifdef CONFIG_FAIR_GROUP_SCHED
6528 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6529 struct cftype *cftype, u64 shareval)
6531 return sched_group_set_shares(css_tg(css), scale_load(shareval));
6534 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6537 struct task_group *tg = css_tg(css);
6539 return (u64) scale_load_down(tg->shares);
6542 #ifdef CONFIG_CFS_BANDWIDTH
6543 static DEFINE_MUTEX(cfs_constraints_mutex);
6545 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6546 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6548 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6550 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6552 int i, ret = 0, runtime_enabled, runtime_was_enabled;
6553 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6555 if (tg == &root_task_group)
6559 * Ensure we have at some amount of bandwidth every period. This is
6560 * to prevent reaching a state of large arrears when throttled via
6561 * entity_tick() resulting in prolonged exit starvation.
6563 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6567 * Likewise, bound things on the otherside by preventing insane quota
6568 * periods. This also allows us to normalize in computing quota
6571 if (period > max_cfs_quota_period)
6575 * Prevent race between setting of cfs_rq->runtime_enabled and
6576 * unthrottle_offline_cfs_rqs().
6579 mutex_lock(&cfs_constraints_mutex);
6580 ret = __cfs_schedulable(tg, period, quota);
6584 runtime_enabled = quota != RUNTIME_INF;
6585 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
6587 * If we need to toggle cfs_bandwidth_used, off->on must occur
6588 * before making related changes, and on->off must occur afterwards
6590 if (runtime_enabled && !runtime_was_enabled)
6591 cfs_bandwidth_usage_inc();
6592 raw_spin_lock_irq(&cfs_b->lock);
6593 cfs_b->period = ns_to_ktime(period);
6594 cfs_b->quota = quota;
6596 __refill_cfs_bandwidth_runtime(cfs_b);
6598 /* Restart the period timer (if active) to handle new period expiry: */
6599 if (runtime_enabled)
6600 start_cfs_bandwidth(cfs_b);
6602 raw_spin_unlock_irq(&cfs_b->lock);
6604 for_each_online_cpu(i) {
6605 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
6606 struct rq *rq = cfs_rq->rq;
6609 rq_lock_irq(rq, &rf);
6610 cfs_rq->runtime_enabled = runtime_enabled;
6611 cfs_rq->runtime_remaining = 0;
6613 if (cfs_rq->throttled)
6614 unthrottle_cfs_rq(cfs_rq);
6615 rq_unlock_irq(rq, &rf);
6617 if (runtime_was_enabled && !runtime_enabled)
6618 cfs_bandwidth_usage_dec();
6620 mutex_unlock(&cfs_constraints_mutex);
6626 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
6630 period = ktime_to_ns(tg->cfs_bandwidth.period);
6631 if (cfs_quota_us < 0)
6632 quota = RUNTIME_INF;
6634 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
6636 return tg_set_cfs_bandwidth(tg, period, quota);
6639 long tg_get_cfs_quota(struct task_group *tg)
6643 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
6646 quota_us = tg->cfs_bandwidth.quota;
6647 do_div(quota_us, NSEC_PER_USEC);
6652 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
6656 period = (u64)cfs_period_us * NSEC_PER_USEC;
6657 quota = tg->cfs_bandwidth.quota;
6659 return tg_set_cfs_bandwidth(tg, period, quota);
6662 long tg_get_cfs_period(struct task_group *tg)
6666 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
6667 do_div(cfs_period_us, NSEC_PER_USEC);
6669 return cfs_period_us;
6672 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
6675 return tg_get_cfs_quota(css_tg(css));
6678 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
6679 struct cftype *cftype, s64 cfs_quota_us)
6681 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
6684 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
6687 return tg_get_cfs_period(css_tg(css));
6690 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
6691 struct cftype *cftype, u64 cfs_period_us)
6693 return tg_set_cfs_period(css_tg(css), cfs_period_us);
6696 struct cfs_schedulable_data {
6697 struct task_group *tg;
6702 * normalize group quota/period to be quota/max_period
6703 * note: units are usecs
6705 static u64 normalize_cfs_quota(struct task_group *tg,
6706 struct cfs_schedulable_data *d)
6714 period = tg_get_cfs_period(tg);
6715 quota = tg_get_cfs_quota(tg);
6718 /* note: these should typically be equivalent */
6719 if (quota == RUNTIME_INF || quota == -1)
6722 return to_ratio(period, quota);
6725 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
6727 struct cfs_schedulable_data *d = data;
6728 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6729 s64 quota = 0, parent_quota = -1;
6732 quota = RUNTIME_INF;
6734 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
6736 quota = normalize_cfs_quota(tg, d);
6737 parent_quota = parent_b->hierarchical_quota;
6740 * Ensure max(child_quota) <= parent_quota. On cgroup2,
6741 * always take the min. On cgroup1, only inherit when no
6744 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
6745 quota = min(quota, parent_quota);
6747 if (quota == RUNTIME_INF)
6748 quota = parent_quota;
6749 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
6753 cfs_b->hierarchical_quota = quota;
6758 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
6761 struct cfs_schedulable_data data = {
6767 if (quota != RUNTIME_INF) {
6768 do_div(data.period, NSEC_PER_USEC);
6769 do_div(data.quota, NSEC_PER_USEC);
6773 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
6779 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
6781 struct task_group *tg = css_tg(seq_css(sf));
6782 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6784 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
6785 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
6786 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
6790 #endif /* CONFIG_CFS_BANDWIDTH */
6791 #endif /* CONFIG_FAIR_GROUP_SCHED */
6793 #ifdef CONFIG_RT_GROUP_SCHED
6794 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
6795 struct cftype *cft, s64 val)
6797 return sched_group_set_rt_runtime(css_tg(css), val);
6800 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
6803 return sched_group_rt_runtime(css_tg(css));
6806 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
6807 struct cftype *cftype, u64 rt_period_us)
6809 return sched_group_set_rt_period(css_tg(css), rt_period_us);
6812 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
6815 return sched_group_rt_period(css_tg(css));
6817 #endif /* CONFIG_RT_GROUP_SCHED */
6819 static struct cftype cpu_legacy_files[] = {
6820 #ifdef CONFIG_FAIR_GROUP_SCHED
6823 .read_u64 = cpu_shares_read_u64,
6824 .write_u64 = cpu_shares_write_u64,
6827 #ifdef CONFIG_CFS_BANDWIDTH
6829 .name = "cfs_quota_us",
6830 .read_s64 = cpu_cfs_quota_read_s64,
6831 .write_s64 = cpu_cfs_quota_write_s64,
6834 .name = "cfs_period_us",
6835 .read_u64 = cpu_cfs_period_read_u64,
6836 .write_u64 = cpu_cfs_period_write_u64,
6840 .seq_show = cpu_cfs_stat_show,
6843 #ifdef CONFIG_RT_GROUP_SCHED
6845 .name = "rt_runtime_us",
6846 .read_s64 = cpu_rt_runtime_read,
6847 .write_s64 = cpu_rt_runtime_write,
6850 .name = "rt_period_us",
6851 .read_u64 = cpu_rt_period_read_uint,
6852 .write_u64 = cpu_rt_period_write_uint,
6858 static int cpu_extra_stat_show(struct seq_file *sf,
6859 struct cgroup_subsys_state *css)
6861 #ifdef CONFIG_CFS_BANDWIDTH
6863 struct task_group *tg = css_tg(css);
6864 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6867 throttled_usec = cfs_b->throttled_time;
6868 do_div(throttled_usec, NSEC_PER_USEC);
6870 seq_printf(sf, "nr_periods %d\n"
6872 "throttled_usec %llu\n",
6873 cfs_b->nr_periods, cfs_b->nr_throttled,
6880 #ifdef CONFIG_FAIR_GROUP_SCHED
6881 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
6884 struct task_group *tg = css_tg(css);
6885 u64 weight = scale_load_down(tg->shares);
6887 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
6890 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
6891 struct cftype *cft, u64 weight)
6894 * cgroup weight knobs should use the common MIN, DFL and MAX
6895 * values which are 1, 100 and 10000 respectively. While it loses
6896 * a bit of range on both ends, it maps pretty well onto the shares
6897 * value used by scheduler and the round-trip conversions preserve
6898 * the original value over the entire range.
6900 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
6903 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
6905 return sched_group_set_shares(css_tg(css), scale_load(weight));
6908 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
6911 unsigned long weight = scale_load_down(css_tg(css)->shares);
6912 int last_delta = INT_MAX;
6915 /* find the closest nice value to the current weight */
6916 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
6917 delta = abs(sched_prio_to_weight[prio] - weight);
6918 if (delta >= last_delta)
6923 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
6926 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
6927 struct cftype *cft, s64 nice)
6929 unsigned long weight;
6932 if (nice < MIN_NICE || nice > MAX_NICE)
6935 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
6936 idx = array_index_nospec(idx, 40);
6937 weight = sched_prio_to_weight[idx];
6939 return sched_group_set_shares(css_tg(css), scale_load(weight));
6943 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
6944 long period, long quota)
6947 seq_puts(sf, "max");
6949 seq_printf(sf, "%ld", quota);
6951 seq_printf(sf, " %ld\n", period);
6954 /* caller should put the current value in *@periodp before calling */
6955 static int __maybe_unused cpu_period_quota_parse(char *buf,
6956 u64 *periodp, u64 *quotap)
6958 char tok[21]; /* U64_MAX */
6960 if (!sscanf(buf, "%s %llu", tok, periodp))
6963 *periodp *= NSEC_PER_USEC;
6965 if (sscanf(tok, "%llu", quotap))
6966 *quotap *= NSEC_PER_USEC;
6967 else if (!strcmp(tok, "max"))
6968 *quotap = RUNTIME_INF;
6975 #ifdef CONFIG_CFS_BANDWIDTH
6976 static int cpu_max_show(struct seq_file *sf, void *v)
6978 struct task_group *tg = css_tg(seq_css(sf));
6980 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
6984 static ssize_t cpu_max_write(struct kernfs_open_file *of,
6985 char *buf, size_t nbytes, loff_t off)
6987 struct task_group *tg = css_tg(of_css(of));
6988 u64 period = tg_get_cfs_period(tg);
6992 ret = cpu_period_quota_parse(buf, &period, "a);
6994 ret = tg_set_cfs_bandwidth(tg, period, quota);
6995 return ret ?: nbytes;
6999 static struct cftype cpu_files[] = {
7000 #ifdef CONFIG_FAIR_GROUP_SCHED
7003 .flags = CFTYPE_NOT_ON_ROOT,
7004 .read_u64 = cpu_weight_read_u64,
7005 .write_u64 = cpu_weight_write_u64,
7008 .name = "weight.nice",
7009 .flags = CFTYPE_NOT_ON_ROOT,
7010 .read_s64 = cpu_weight_nice_read_s64,
7011 .write_s64 = cpu_weight_nice_write_s64,
7014 #ifdef CONFIG_CFS_BANDWIDTH
7017 .flags = CFTYPE_NOT_ON_ROOT,
7018 .seq_show = cpu_max_show,
7019 .write = cpu_max_write,
7025 struct cgroup_subsys cpu_cgrp_subsys = {
7026 .css_alloc = cpu_cgroup_css_alloc,
7027 .css_online = cpu_cgroup_css_online,
7028 .css_released = cpu_cgroup_css_released,
7029 .css_free = cpu_cgroup_css_free,
7030 .css_extra_stat_show = cpu_extra_stat_show,
7031 .fork = cpu_cgroup_fork,
7032 .can_attach = cpu_cgroup_can_attach,
7033 .attach = cpu_cgroup_attach,
7034 .legacy_cftypes = cpu_legacy_files,
7035 .dfl_cftypes = cpu_files,
7040 #endif /* CONFIG_CGROUP_SCHED */
7042 void dump_cpu_task(int cpu)
7044 pr_info("Task dump for CPU %d:\n", cpu);
7045 sched_show_task(cpu_curr(cpu));
7049 * Nice levels are multiplicative, with a gentle 10% change for every
7050 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
7051 * nice 1, it will get ~10% less CPU time than another CPU-bound task
7052 * that remained on nice 0.
7054 * The "10% effect" is relative and cumulative: from _any_ nice level,
7055 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
7056 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
7057 * If a task goes up by ~10% and another task goes down by ~10% then
7058 * the relative distance between them is ~25%.)
7060 const int sched_prio_to_weight[40] = {
7061 /* -20 */ 88761, 71755, 56483, 46273, 36291,
7062 /* -15 */ 29154, 23254, 18705, 14949, 11916,
7063 /* -10 */ 9548, 7620, 6100, 4904, 3906,
7064 /* -5 */ 3121, 2501, 1991, 1586, 1277,
7065 /* 0 */ 1024, 820, 655, 526, 423,
7066 /* 5 */ 335, 272, 215, 172, 137,
7067 /* 10 */ 110, 87, 70, 56, 45,
7068 /* 15 */ 36, 29, 23, 18, 15,
7072 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
7074 * In cases where the weight does not change often, we can use the
7075 * precalculated inverse to speed up arithmetics by turning divisions
7076 * into multiplications:
7078 const u32 sched_prio_to_wmult[40] = {
7079 /* -20 */ 48388, 59856, 76040, 92818, 118348,
7080 /* -15 */ 147320, 184698, 229616, 287308, 360437,
7081 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
7082 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
7083 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
7084 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
7085 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
7086 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
7089 #undef CREATE_TRACE_POINTS