4 * Core kernel scheduler code and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 #include <linux/sched.h>
9 #include <linux/sched/clock.h>
10 #include <uapi/linux/sched/types.h>
11 #include <linux/sched/loadavg.h>
12 #include <linux/sched/hotplug.h>
13 #include <linux/cpuset.h>
14 #include <linux/delayacct.h>
15 #include <linux/init_task.h>
16 #include <linux/context_tracking.h>
17 #include <linux/rcupdate_wait.h>
19 #include <linux/blkdev.h>
20 #include <linux/kprobes.h>
21 #include <linux/mmu_context.h>
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/prefetch.h>
25 #include <linux/profile.h>
26 #include <linux/security.h>
27 #include <linux/syscalls.h>
29 #include <asm/switch_to.h>
31 #ifdef CONFIG_PARAVIRT
32 #include <asm/paravirt.h>
36 #include "../workqueue_internal.h"
37 #include "../smpboot.h"
39 #define CREATE_TRACE_POINTS
40 #include <trace/events/sched.h>
42 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
45 * Debugging: various feature bits
48 #define SCHED_FEAT(name, enabled) \
49 (1UL << __SCHED_FEAT_##name) * enabled |
51 const_debug unsigned int sysctl_sched_features =
58 * Number of tasks to iterate in a single balance run.
59 * Limited because this is done with IRQs disabled.
61 const_debug unsigned int sysctl_sched_nr_migrate = 32;
64 * period over which we average the RT time consumption, measured
69 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
72 * period over which we measure -rt task CPU usage in us.
75 unsigned int sysctl_sched_rt_period = 1000000;
77 __read_mostly int scheduler_running;
80 * part of the period that we allow rt tasks to run in us.
83 int sysctl_sched_rt_runtime = 950000;
85 /* CPUs with isolated domains */
86 cpumask_var_t cpu_isolated_map;
89 * this_rq_lock - lock this runqueue and disable interrupts.
91 static struct rq *this_rq_lock(void)
98 raw_spin_lock(&rq->lock);
104 * __task_rq_lock - lock the rq @p resides on.
106 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
111 lockdep_assert_held(&p->pi_lock);
115 raw_spin_lock(&rq->lock);
116 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
120 raw_spin_unlock(&rq->lock);
122 while (unlikely(task_on_rq_migrating(p)))
128 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
130 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
131 __acquires(p->pi_lock)
137 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
139 raw_spin_lock(&rq->lock);
141 * move_queued_task() task_rq_lock()
144 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
145 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
146 * [S] ->cpu = new_cpu [L] task_rq()
150 * If we observe the old cpu in task_rq_lock, the acquire of
151 * the old rq->lock will fully serialize against the stores.
153 * If we observe the new CPU in task_rq_lock, the acquire will
154 * pair with the WMB to ensure we must then also see migrating.
156 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
160 raw_spin_unlock(&rq->lock);
161 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
163 while (unlikely(task_on_rq_migrating(p)))
169 * RQ-clock updating methods:
172 static void update_rq_clock_task(struct rq *rq, s64 delta)
175 * In theory, the compile should just see 0 here, and optimize out the call
176 * to sched_rt_avg_update. But I don't trust it...
178 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
179 s64 steal = 0, irq_delta = 0;
181 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
182 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
185 * Since irq_time is only updated on {soft,}irq_exit, we might run into
186 * this case when a previous update_rq_clock() happened inside a
189 * When this happens, we stop ->clock_task and only update the
190 * prev_irq_time stamp to account for the part that fit, so that a next
191 * update will consume the rest. This ensures ->clock_task is
194 * It does however cause some slight miss-attribution of {soft,}irq
195 * time, a more accurate solution would be to update the irq_time using
196 * the current rq->clock timestamp, except that would require using
199 if (irq_delta > delta)
202 rq->prev_irq_time += irq_delta;
205 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
206 if (static_key_false((¶virt_steal_rq_enabled))) {
207 steal = paravirt_steal_clock(cpu_of(rq));
208 steal -= rq->prev_steal_time_rq;
210 if (unlikely(steal > delta))
213 rq->prev_steal_time_rq += steal;
218 rq->clock_task += delta;
220 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
221 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
222 sched_rt_avg_update(rq, irq_delta + steal);
226 void update_rq_clock(struct rq *rq)
230 lockdep_assert_held(&rq->lock);
232 if (rq->clock_update_flags & RQCF_ACT_SKIP)
235 #ifdef CONFIG_SCHED_DEBUG
236 rq->clock_update_flags |= RQCF_UPDATED;
238 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
242 update_rq_clock_task(rq, delta);
246 #ifdef CONFIG_SCHED_HRTICK
248 * Use HR-timers to deliver accurate preemption points.
251 static void hrtick_clear(struct rq *rq)
253 if (hrtimer_active(&rq->hrtick_timer))
254 hrtimer_cancel(&rq->hrtick_timer);
258 * High-resolution timer tick.
259 * Runs from hardirq context with interrupts disabled.
261 static enum hrtimer_restart hrtick(struct hrtimer *timer)
263 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
265 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
267 raw_spin_lock(&rq->lock);
269 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
270 raw_spin_unlock(&rq->lock);
272 return HRTIMER_NORESTART;
277 static void __hrtick_restart(struct rq *rq)
279 struct hrtimer *timer = &rq->hrtick_timer;
281 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
285 * called from hardirq (IPI) context
287 static void __hrtick_start(void *arg)
291 raw_spin_lock(&rq->lock);
292 __hrtick_restart(rq);
293 rq->hrtick_csd_pending = 0;
294 raw_spin_unlock(&rq->lock);
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)
304 struct hrtimer *timer = &rq->hrtick_timer;
309 * Don't schedule slices shorter than 10000ns, that just
310 * doesn't make sense and can cause timer DoS.
312 delta = max_t(s64, delay, 10000LL);
313 time = ktime_add_ns(timer->base->get_time(), delta);
315 hrtimer_set_expires(timer, time);
317 if (rq == this_rq()) {
318 __hrtick_restart(rq);
319 } else if (!rq->hrtick_csd_pending) {
320 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
321 rq->hrtick_csd_pending = 1;
327 * Called to set the hrtick timer state.
329 * called with rq->lock held and irqs disabled
331 void hrtick_start(struct rq *rq, u64 delay)
334 * Don't schedule slices shorter than 10000ns, that just
335 * doesn't make sense. Rely on vruntime for fairness.
337 delay = max_t(u64, delay, 10000LL);
338 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
339 HRTIMER_MODE_REL_PINNED);
341 #endif /* CONFIG_SMP */
343 static void init_rq_hrtick(struct rq *rq)
346 rq->hrtick_csd_pending = 0;
348 rq->hrtick_csd.flags = 0;
349 rq->hrtick_csd.func = __hrtick_start;
350 rq->hrtick_csd.info = rq;
353 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
354 rq->hrtick_timer.function = hrtick;
356 #else /* CONFIG_SCHED_HRTICK */
357 static inline void hrtick_clear(struct rq *rq)
361 static inline void init_rq_hrtick(struct rq *rq)
364 #endif /* CONFIG_SCHED_HRTICK */
367 * cmpxchg based fetch_or, macro so it works for different integer types
369 #define fetch_or(ptr, mask) \
371 typeof(ptr) _ptr = (ptr); \
372 typeof(mask) _mask = (mask); \
373 typeof(*_ptr) _old, _val = *_ptr; \
376 _old = cmpxchg(_ptr, _val, _val | _mask); \
384 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
386 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
387 * this avoids any races wrt polling state changes and thereby avoids
390 static bool set_nr_and_not_polling(struct task_struct *p)
392 struct thread_info *ti = task_thread_info(p);
393 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
397 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
399 * If this returns true, then the idle task promises to call
400 * sched_ttwu_pending() and reschedule soon.
402 static bool set_nr_if_polling(struct task_struct *p)
404 struct thread_info *ti = task_thread_info(p);
405 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
408 if (!(val & _TIF_POLLING_NRFLAG))
410 if (val & _TIF_NEED_RESCHED)
412 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
421 static bool set_nr_and_not_polling(struct task_struct *p)
423 set_tsk_need_resched(p);
428 static bool set_nr_if_polling(struct task_struct *p)
435 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
437 struct wake_q_node *node = &task->wake_q;
440 * Atomically grab the task, if ->wake_q is !nil already it means
441 * its already queued (either by us or someone else) and will get the
442 * wakeup due to that.
444 * This cmpxchg() implies a full barrier, which pairs with the write
445 * barrier implied by the wakeup in wake_up_q().
447 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
450 get_task_struct(task);
453 * The head is context local, there can be no concurrency.
456 head->lastp = &node->next;
459 void wake_up_q(struct wake_q_head *head)
461 struct wake_q_node *node = head->first;
463 while (node != WAKE_Q_TAIL) {
464 struct task_struct *task;
466 task = container_of(node, struct task_struct, wake_q);
468 /* Task can safely be re-inserted now: */
470 task->wake_q.next = NULL;
473 * wake_up_process() implies a wmb() to pair with the queueing
474 * in wake_q_add() so as not to miss wakeups.
476 wake_up_process(task);
477 put_task_struct(task);
482 * resched_curr - mark rq's current task 'to be rescheduled now'.
484 * On UP this means the setting of the need_resched flag, on SMP it
485 * might also involve a cross-CPU call to trigger the scheduler on
488 void resched_curr(struct rq *rq)
490 struct task_struct *curr = rq->curr;
493 lockdep_assert_held(&rq->lock);
495 if (test_tsk_need_resched(curr))
500 if (cpu == smp_processor_id()) {
501 set_tsk_need_resched(curr);
502 set_preempt_need_resched();
506 if (set_nr_and_not_polling(curr))
507 smp_send_reschedule(cpu);
509 trace_sched_wake_idle_without_ipi(cpu);
512 void resched_cpu(int cpu)
514 struct rq *rq = cpu_rq(cpu);
517 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
520 raw_spin_unlock_irqrestore(&rq->lock, flags);
524 #ifdef CONFIG_NO_HZ_COMMON
526 * In the semi idle case, use the nearest busy CPU for migrating timers
527 * from an idle CPU. This is good for power-savings.
529 * We don't do similar optimization for completely idle system, as
530 * selecting an idle CPU will add more delays to the timers than intended
531 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
533 int get_nohz_timer_target(void)
535 int i, cpu = smp_processor_id();
536 struct sched_domain *sd;
538 if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
542 for_each_domain(cpu, sd) {
543 for_each_cpu(i, sched_domain_span(sd)) {
547 if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
554 if (!is_housekeeping_cpu(cpu))
555 cpu = housekeeping_any_cpu();
562 * When add_timer_on() enqueues a timer into the timer wheel of an
563 * idle CPU then this timer might expire before the next timer event
564 * which is scheduled to wake up that CPU. In case of a completely
565 * idle system the next event might even be infinite time into the
566 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
567 * leaves the inner idle loop so the newly added timer is taken into
568 * account when the CPU goes back to idle and evaluates the timer
569 * wheel for the next timer event.
571 static void wake_up_idle_cpu(int cpu)
573 struct rq *rq = cpu_rq(cpu);
575 if (cpu == smp_processor_id())
578 if (set_nr_and_not_polling(rq->idle))
579 smp_send_reschedule(cpu);
581 trace_sched_wake_idle_without_ipi(cpu);
584 static bool wake_up_full_nohz_cpu(int cpu)
587 * We just need the target to call irq_exit() and re-evaluate
588 * the next tick. The nohz full kick at least implies that.
589 * If needed we can still optimize that later with an
592 if (cpu_is_offline(cpu))
593 return true; /* Don't try to wake offline CPUs. */
594 if (tick_nohz_full_cpu(cpu)) {
595 if (cpu != smp_processor_id() ||
596 tick_nohz_tick_stopped())
597 tick_nohz_full_kick_cpu(cpu);
605 * Wake up the specified CPU. If the CPU is going offline, it is the
606 * caller's responsibility to deal with the lost wakeup, for example,
607 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
609 void wake_up_nohz_cpu(int cpu)
611 if (!wake_up_full_nohz_cpu(cpu))
612 wake_up_idle_cpu(cpu);
615 static inline bool got_nohz_idle_kick(void)
617 int cpu = smp_processor_id();
619 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
622 if (idle_cpu(cpu) && !need_resched())
626 * We can't run Idle Load Balance on this CPU for this time so we
627 * cancel it and clear NOHZ_BALANCE_KICK
629 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
633 #else /* CONFIG_NO_HZ_COMMON */
635 static inline bool got_nohz_idle_kick(void)
640 #endif /* CONFIG_NO_HZ_COMMON */
642 #ifdef CONFIG_NO_HZ_FULL
643 bool sched_can_stop_tick(struct rq *rq)
647 /* Deadline tasks, even if single, need the tick */
648 if (rq->dl.dl_nr_running)
652 * If there are more than one RR tasks, we need the tick to effect the
653 * actual RR behaviour.
655 if (rq->rt.rr_nr_running) {
656 if (rq->rt.rr_nr_running == 1)
663 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
664 * forced preemption between FIFO tasks.
666 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
671 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
672 * if there's more than one we need the tick for involuntary
675 if (rq->nr_running > 1)
680 #endif /* CONFIG_NO_HZ_FULL */
682 void sched_avg_update(struct rq *rq)
684 s64 period = sched_avg_period();
686 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
688 * Inline assembly required to prevent the compiler
689 * optimising this loop into a divmod call.
690 * See __iter_div_u64_rem() for another example of this.
692 asm("" : "+rm" (rq->age_stamp));
693 rq->age_stamp += period;
698 #endif /* CONFIG_SMP */
700 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
701 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
703 * Iterate task_group tree rooted at *from, calling @down when first entering a
704 * node and @up when leaving it for the final time.
706 * Caller must hold rcu_lock or sufficient equivalent.
708 int walk_tg_tree_from(struct task_group *from,
709 tg_visitor down, tg_visitor up, void *data)
711 struct task_group *parent, *child;
717 ret = (*down)(parent, data);
720 list_for_each_entry_rcu(child, &parent->children, siblings) {
727 ret = (*up)(parent, data);
728 if (ret || parent == from)
732 parent = parent->parent;
739 int tg_nop(struct task_group *tg, void *data)
745 static void set_load_weight(struct task_struct *p)
747 int prio = p->static_prio - MAX_RT_PRIO;
748 struct load_weight *load = &p->se.load;
751 * SCHED_IDLE tasks get minimal weight:
753 if (idle_policy(p->policy)) {
754 load->weight = scale_load(WEIGHT_IDLEPRIO);
755 load->inv_weight = WMULT_IDLEPRIO;
759 load->weight = scale_load(sched_prio_to_weight[prio]);
760 load->inv_weight = sched_prio_to_wmult[prio];
763 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
766 if (!(flags & ENQUEUE_RESTORE))
767 sched_info_queued(rq, p);
768 p->sched_class->enqueue_task(rq, p, flags);
771 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
774 if (!(flags & DEQUEUE_SAVE))
775 sched_info_dequeued(rq, p);
776 p->sched_class->dequeue_task(rq, p, flags);
779 void activate_task(struct rq *rq, struct task_struct *p, int flags)
781 if (task_contributes_to_load(p))
782 rq->nr_uninterruptible--;
784 enqueue_task(rq, p, flags);
787 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
789 if (task_contributes_to_load(p))
790 rq->nr_uninterruptible++;
792 dequeue_task(rq, p, flags);
795 void sched_set_stop_task(int cpu, struct task_struct *stop)
797 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
798 struct task_struct *old_stop = cpu_rq(cpu)->stop;
802 * Make it appear like a SCHED_FIFO task, its something
803 * userspace knows about and won't get confused about.
805 * Also, it will make PI more or less work without too
806 * much confusion -- but then, stop work should not
807 * rely on PI working anyway.
809 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
811 stop->sched_class = &stop_sched_class;
814 cpu_rq(cpu)->stop = stop;
818 * Reset it back to a normal scheduling class so that
819 * it can die in pieces.
821 old_stop->sched_class = &rt_sched_class;
826 * __normal_prio - return the priority that is based on the static prio
828 static inline int __normal_prio(struct task_struct *p)
830 return p->static_prio;
834 * Calculate the expected normal priority: i.e. priority
835 * without taking RT-inheritance into account. Might be
836 * boosted by interactivity modifiers. Changes upon fork,
837 * setprio syscalls, and whenever the interactivity
838 * estimator recalculates.
840 static inline int normal_prio(struct task_struct *p)
844 if (task_has_dl_policy(p))
845 prio = MAX_DL_PRIO-1;
846 else if (task_has_rt_policy(p))
847 prio = MAX_RT_PRIO-1 - p->rt_priority;
849 prio = __normal_prio(p);
854 * Calculate the current priority, i.e. the priority
855 * taken into account by the scheduler. This value might
856 * be boosted by RT tasks, or might be boosted by
857 * interactivity modifiers. Will be RT if the task got
858 * RT-boosted. If not then it returns p->normal_prio.
860 static int effective_prio(struct task_struct *p)
862 p->normal_prio = normal_prio(p);
864 * If we are RT tasks or we were boosted to RT priority,
865 * keep the priority unchanged. Otherwise, update priority
866 * to the normal priority:
868 if (!rt_prio(p->prio))
869 return p->normal_prio;
874 * task_curr - is this task currently executing on a CPU?
875 * @p: the task in question.
877 * Return: 1 if the task is currently executing. 0 otherwise.
879 inline int task_curr(const struct task_struct *p)
881 return cpu_curr(task_cpu(p)) == p;
885 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
886 * use the balance_callback list if you want balancing.
888 * this means any call to check_class_changed() must be followed by a call to
889 * balance_callback().
891 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
892 const struct sched_class *prev_class,
895 if (prev_class != p->sched_class) {
896 if (prev_class->switched_from)
897 prev_class->switched_from(rq, p);
899 p->sched_class->switched_to(rq, p);
900 } else if (oldprio != p->prio || dl_task(p))
901 p->sched_class->prio_changed(rq, p, oldprio);
904 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
906 const struct sched_class *class;
908 if (p->sched_class == rq->curr->sched_class) {
909 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
911 for_each_class(class) {
912 if (class == rq->curr->sched_class)
914 if (class == p->sched_class) {
922 * A queue event has occurred, and we're going to schedule. In
923 * this case, we can save a useless back to back clock update.
925 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
926 rq_clock_skip_update(rq, true);
931 * This is how migration works:
933 * 1) we invoke migration_cpu_stop() on the target CPU using
935 * 2) stopper starts to run (implicitly forcing the migrated thread
937 * 3) it checks whether the migrated task is still in the wrong runqueue.
938 * 4) if it's in the wrong runqueue then the migration thread removes
939 * it and puts it into the right queue.
940 * 5) stopper completes and stop_one_cpu() returns and the migration
945 * move_queued_task - move a queued task to new rq.
947 * Returns (locked) new rq. Old rq's lock is released.
949 static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
951 lockdep_assert_held(&rq->lock);
953 p->on_rq = TASK_ON_RQ_MIGRATING;
954 dequeue_task(rq, p, 0);
955 set_task_cpu(p, new_cpu);
956 raw_spin_unlock(&rq->lock);
958 rq = cpu_rq(new_cpu);
960 raw_spin_lock(&rq->lock);
961 BUG_ON(task_cpu(p) != new_cpu);
962 enqueue_task(rq, p, 0);
963 p->on_rq = TASK_ON_RQ_QUEUED;
964 check_preempt_curr(rq, p, 0);
969 struct migration_arg {
970 struct task_struct *task;
975 * Move (not current) task off this CPU, onto the destination CPU. We're doing
976 * this because either it can't run here any more (set_cpus_allowed()
977 * away from this CPU, or CPU going down), or because we're
978 * attempting to rebalance this task on exec (sched_exec).
980 * So we race with normal scheduler movements, but that's OK, as long
981 * as the task is no longer on this CPU.
983 static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
985 if (unlikely(!cpu_active(dest_cpu)))
988 /* Affinity changed (again). */
989 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
992 rq = move_queued_task(rq, p, dest_cpu);
998 * migration_cpu_stop - this will be executed by a highprio stopper thread
999 * and performs thread migration by bumping thread off CPU then
1000 * 'pushing' onto another runqueue.
1002 static int migration_cpu_stop(void *data)
1004 struct migration_arg *arg = data;
1005 struct task_struct *p = arg->task;
1006 struct rq *rq = this_rq();
1009 * The original target CPU might have gone down and we might
1010 * be on another CPU but it doesn't matter.
1012 local_irq_disable();
1014 * We need to explicitly wake pending tasks before running
1015 * __migrate_task() such that we will not miss enforcing cpus_allowed
1016 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1018 sched_ttwu_pending();
1020 raw_spin_lock(&p->pi_lock);
1021 raw_spin_lock(&rq->lock);
1023 * If task_rq(p) != rq, it cannot be migrated here, because we're
1024 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1025 * we're holding p->pi_lock.
1027 if (task_rq(p) == rq) {
1028 if (task_on_rq_queued(p))
1029 rq = __migrate_task(rq, p, arg->dest_cpu);
1031 p->wake_cpu = arg->dest_cpu;
1033 raw_spin_unlock(&rq->lock);
1034 raw_spin_unlock(&p->pi_lock);
1041 * sched_class::set_cpus_allowed must do the below, but is not required to
1042 * actually call this function.
1044 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1046 cpumask_copy(&p->cpus_allowed, new_mask);
1047 p->nr_cpus_allowed = cpumask_weight(new_mask);
1050 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1052 struct rq *rq = task_rq(p);
1053 bool queued, running;
1055 lockdep_assert_held(&p->pi_lock);
1057 queued = task_on_rq_queued(p);
1058 running = task_current(rq, p);
1062 * Because __kthread_bind() calls this on blocked tasks without
1065 lockdep_assert_held(&rq->lock);
1066 dequeue_task(rq, p, DEQUEUE_SAVE);
1069 put_prev_task(rq, p);
1071 p->sched_class->set_cpus_allowed(p, new_mask);
1074 enqueue_task(rq, p, ENQUEUE_RESTORE);
1076 set_curr_task(rq, p);
1080 * Change a given task's CPU affinity. Migrate the thread to a
1081 * proper CPU and schedule it away if the CPU it's executing on
1082 * is removed from the allowed bitmask.
1084 * NOTE: the caller must have a valid reference to the task, the
1085 * task must not exit() & deallocate itself prematurely. The
1086 * call is not atomic; no spinlocks may be held.
1088 static int __set_cpus_allowed_ptr(struct task_struct *p,
1089 const struct cpumask *new_mask, bool check)
1091 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1092 unsigned int dest_cpu;
1097 rq = task_rq_lock(p, &rf);
1098 update_rq_clock(rq);
1100 if (p->flags & PF_KTHREAD) {
1102 * Kernel threads are allowed on online && !active CPUs
1104 cpu_valid_mask = cpu_online_mask;
1108 * Must re-check here, to close a race against __kthread_bind(),
1109 * sched_setaffinity() is not guaranteed to observe the flag.
1111 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1116 if (cpumask_equal(&p->cpus_allowed, new_mask))
1119 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1124 do_set_cpus_allowed(p, new_mask);
1126 if (p->flags & PF_KTHREAD) {
1128 * For kernel threads that do indeed end up on online &&
1129 * !active we want to ensure they are strict per-CPU threads.
1131 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1132 !cpumask_intersects(new_mask, cpu_active_mask) &&
1133 p->nr_cpus_allowed != 1);
1136 /* Can the task run on the task's current CPU? If so, we're done */
1137 if (cpumask_test_cpu(task_cpu(p), new_mask))
1140 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1141 if (task_running(rq, p) || p->state == TASK_WAKING) {
1142 struct migration_arg arg = { p, dest_cpu };
1143 /* Need help from migration thread: drop lock and wait. */
1144 task_rq_unlock(rq, p, &rf);
1145 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1146 tlb_migrate_finish(p->mm);
1148 } else if (task_on_rq_queued(p)) {
1150 * OK, since we're going to drop the lock immediately
1151 * afterwards anyway.
1153 rq_unpin_lock(rq, &rf);
1154 rq = move_queued_task(rq, p, dest_cpu);
1155 rq_repin_lock(rq, &rf);
1158 task_rq_unlock(rq, p, &rf);
1163 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1165 return __set_cpus_allowed_ptr(p, new_mask, false);
1167 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1169 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1171 #ifdef CONFIG_SCHED_DEBUG
1173 * We should never call set_task_cpu() on a blocked task,
1174 * ttwu() will sort out the placement.
1176 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1180 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1181 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1182 * time relying on p->on_rq.
1184 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1185 p->sched_class == &fair_sched_class &&
1186 (p->on_rq && !task_on_rq_migrating(p)));
1188 #ifdef CONFIG_LOCKDEP
1190 * The caller should hold either p->pi_lock or rq->lock, when changing
1191 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1193 * sched_move_task() holds both and thus holding either pins the cgroup,
1196 * Furthermore, all task_rq users should acquire both locks, see
1199 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1200 lockdep_is_held(&task_rq(p)->lock)));
1204 trace_sched_migrate_task(p, new_cpu);
1206 if (task_cpu(p) != new_cpu) {
1207 if (p->sched_class->migrate_task_rq)
1208 p->sched_class->migrate_task_rq(p);
1209 p->se.nr_migrations++;
1210 perf_event_task_migrate(p);
1213 __set_task_cpu(p, new_cpu);
1216 static void __migrate_swap_task(struct task_struct *p, int cpu)
1218 if (task_on_rq_queued(p)) {
1219 struct rq *src_rq, *dst_rq;
1221 src_rq = task_rq(p);
1222 dst_rq = cpu_rq(cpu);
1224 p->on_rq = TASK_ON_RQ_MIGRATING;
1225 deactivate_task(src_rq, p, 0);
1226 set_task_cpu(p, cpu);
1227 activate_task(dst_rq, p, 0);
1228 p->on_rq = TASK_ON_RQ_QUEUED;
1229 check_preempt_curr(dst_rq, p, 0);
1232 * Task isn't running anymore; make it appear like we migrated
1233 * it before it went to sleep. This means on wakeup we make the
1234 * previous CPU our target instead of where it really is.
1240 struct migration_swap_arg {
1241 struct task_struct *src_task, *dst_task;
1242 int src_cpu, dst_cpu;
1245 static int migrate_swap_stop(void *data)
1247 struct migration_swap_arg *arg = data;
1248 struct rq *src_rq, *dst_rq;
1251 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1254 src_rq = cpu_rq(arg->src_cpu);
1255 dst_rq = cpu_rq(arg->dst_cpu);
1257 double_raw_lock(&arg->src_task->pi_lock,
1258 &arg->dst_task->pi_lock);
1259 double_rq_lock(src_rq, dst_rq);
1261 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1264 if (task_cpu(arg->src_task) != arg->src_cpu)
1267 if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
1270 if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
1273 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1274 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1279 double_rq_unlock(src_rq, dst_rq);
1280 raw_spin_unlock(&arg->dst_task->pi_lock);
1281 raw_spin_unlock(&arg->src_task->pi_lock);
1287 * Cross migrate two tasks
1289 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1291 struct migration_swap_arg arg;
1294 arg = (struct migration_swap_arg){
1296 .src_cpu = task_cpu(cur),
1298 .dst_cpu = task_cpu(p),
1301 if (arg.src_cpu == arg.dst_cpu)
1305 * These three tests are all lockless; this is OK since all of them
1306 * will be re-checked with proper locks held further down the line.
1308 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1311 if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
1314 if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
1317 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1318 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1325 * wait_task_inactive - wait for a thread to unschedule.
1327 * If @match_state is nonzero, it's the @p->state value just checked and
1328 * not expected to change. If it changes, i.e. @p might have woken up,
1329 * then return zero. When we succeed in waiting for @p to be off its CPU,
1330 * we return a positive number (its total switch count). If a second call
1331 * a short while later returns the same number, the caller can be sure that
1332 * @p has remained unscheduled the whole time.
1334 * The caller must ensure that the task *will* unschedule sometime soon,
1335 * else this function might spin for a *long* time. This function can't
1336 * be called with interrupts off, or it may introduce deadlock with
1337 * smp_call_function() if an IPI is sent by the same process we are
1338 * waiting to become inactive.
1340 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1342 int running, queued;
1349 * We do the initial early heuristics without holding
1350 * any task-queue locks at all. We'll only try to get
1351 * the runqueue lock when things look like they will
1357 * If the task is actively running on another CPU
1358 * still, just relax and busy-wait without holding
1361 * NOTE! Since we don't hold any locks, it's not
1362 * even sure that "rq" stays as the right runqueue!
1363 * But we don't care, since "task_running()" will
1364 * return false if the runqueue has changed and p
1365 * is actually now running somewhere else!
1367 while (task_running(rq, p)) {
1368 if (match_state && unlikely(p->state != match_state))
1374 * Ok, time to look more closely! We need the rq
1375 * lock now, to be *sure*. If we're wrong, we'll
1376 * just go back and repeat.
1378 rq = task_rq_lock(p, &rf);
1379 trace_sched_wait_task(p);
1380 running = task_running(rq, p);
1381 queued = task_on_rq_queued(p);
1383 if (!match_state || p->state == match_state)
1384 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1385 task_rq_unlock(rq, p, &rf);
1388 * If it changed from the expected state, bail out now.
1390 if (unlikely(!ncsw))
1394 * Was it really running after all now that we
1395 * checked with the proper locks actually held?
1397 * Oops. Go back and try again..
1399 if (unlikely(running)) {
1405 * It's not enough that it's not actively running,
1406 * it must be off the runqueue _entirely_, and not
1409 * So if it was still runnable (but just not actively
1410 * running right now), it's preempted, and we should
1411 * yield - it could be a while.
1413 if (unlikely(queued)) {
1414 ktime_t to = NSEC_PER_SEC / HZ;
1416 set_current_state(TASK_UNINTERRUPTIBLE);
1417 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1422 * Ahh, all good. It wasn't running, and it wasn't
1423 * runnable, which means that it will never become
1424 * running in the future either. We're all done!
1433 * kick_process - kick a running thread to enter/exit the kernel
1434 * @p: the to-be-kicked thread
1436 * Cause a process which is running on another CPU to enter
1437 * kernel-mode, without any delay. (to get signals handled.)
1439 * NOTE: this function doesn't have to take the runqueue lock,
1440 * because all it wants to ensure is that the remote task enters
1441 * the kernel. If the IPI races and the task has been migrated
1442 * to another CPU then no harm is done and the purpose has been
1445 void kick_process(struct task_struct *p)
1451 if ((cpu != smp_processor_id()) && task_curr(p))
1452 smp_send_reschedule(cpu);
1455 EXPORT_SYMBOL_GPL(kick_process);
1458 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1460 * A few notes on cpu_active vs cpu_online:
1462 * - cpu_active must be a subset of cpu_online
1464 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1465 * see __set_cpus_allowed_ptr(). At this point the newly online
1466 * CPU isn't yet part of the sched domains, and balancing will not
1469 * - on CPU-down we clear cpu_active() to mask the sched domains and
1470 * avoid the load balancer to place new tasks on the to be removed
1471 * CPU. Existing tasks will remain running there and will be taken
1474 * This means that fallback selection must not select !active CPUs.
1475 * And can assume that any active CPU must be online. Conversely
1476 * select_task_rq() below may allow selection of !active CPUs in order
1477 * to satisfy the above rules.
1479 static int select_fallback_rq(int cpu, struct task_struct *p)
1481 int nid = cpu_to_node(cpu);
1482 const struct cpumask *nodemask = NULL;
1483 enum { cpuset, possible, fail } state = cpuset;
1487 * If the node that the CPU is on has been offlined, cpu_to_node()
1488 * will return -1. There is no CPU on the node, and we should
1489 * select the CPU on the other node.
1492 nodemask = cpumask_of_node(nid);
1494 /* Look for allowed, online CPU in same node. */
1495 for_each_cpu(dest_cpu, nodemask) {
1496 if (!cpu_active(dest_cpu))
1498 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
1504 /* Any allowed, online CPU? */
1505 for_each_cpu(dest_cpu, &p->cpus_allowed) {
1506 if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
1508 if (!cpu_online(dest_cpu))
1513 /* No more Mr. Nice Guy. */
1516 if (IS_ENABLED(CONFIG_CPUSETS)) {
1517 cpuset_cpus_allowed_fallback(p);
1523 do_set_cpus_allowed(p, cpu_possible_mask);
1534 if (state != cpuset) {
1536 * Don't tell them about moving exiting tasks or
1537 * kernel threads (both mm NULL), since they never
1540 if (p->mm && printk_ratelimit()) {
1541 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1542 task_pid_nr(p), p->comm, cpu);
1550 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1553 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1555 lockdep_assert_held(&p->pi_lock);
1557 if (p->nr_cpus_allowed > 1)
1558 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1560 cpu = cpumask_any(&p->cpus_allowed);
1563 * In order not to call set_task_cpu() on a blocking task we need
1564 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1567 * Since this is common to all placement strategies, this lives here.
1569 * [ this allows ->select_task() to simply return task_cpu(p) and
1570 * not worry about this generic constraint ]
1572 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
1574 cpu = select_fallback_rq(task_cpu(p), p);
1579 static void update_avg(u64 *avg, u64 sample)
1581 s64 diff = sample - *avg;
1587 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1588 const struct cpumask *new_mask, bool check)
1590 return set_cpus_allowed_ptr(p, new_mask);
1593 #endif /* CONFIG_SMP */
1596 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1600 if (!schedstat_enabled())
1606 if (cpu == rq->cpu) {
1607 schedstat_inc(rq->ttwu_local);
1608 schedstat_inc(p->se.statistics.nr_wakeups_local);
1610 struct sched_domain *sd;
1612 schedstat_inc(p->se.statistics.nr_wakeups_remote);
1614 for_each_domain(rq->cpu, sd) {
1615 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1616 schedstat_inc(sd->ttwu_wake_remote);
1623 if (wake_flags & WF_MIGRATED)
1624 schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1625 #endif /* CONFIG_SMP */
1627 schedstat_inc(rq->ttwu_count);
1628 schedstat_inc(p->se.statistics.nr_wakeups);
1630 if (wake_flags & WF_SYNC)
1631 schedstat_inc(p->se.statistics.nr_wakeups_sync);
1634 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1636 activate_task(rq, p, en_flags);
1637 p->on_rq = TASK_ON_RQ_QUEUED;
1639 /* If a worker is waking up, notify the workqueue: */
1640 if (p->flags & PF_WQ_WORKER)
1641 wq_worker_waking_up(p, cpu_of(rq));
1645 * Mark the task runnable and perform wakeup-preemption.
1647 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1648 struct rq_flags *rf)
1650 check_preempt_curr(rq, p, wake_flags);
1651 p->state = TASK_RUNNING;
1652 trace_sched_wakeup(p);
1655 if (p->sched_class->task_woken) {
1657 * Our task @p is fully woken up and running; so its safe to
1658 * drop the rq->lock, hereafter rq is only used for statistics.
1660 rq_unpin_lock(rq, rf);
1661 p->sched_class->task_woken(rq, p);
1662 rq_repin_lock(rq, rf);
1665 if (rq->idle_stamp) {
1666 u64 delta = rq_clock(rq) - rq->idle_stamp;
1667 u64 max = 2*rq->max_idle_balance_cost;
1669 update_avg(&rq->avg_idle, delta);
1671 if (rq->avg_idle > max)
1680 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1681 struct rq_flags *rf)
1683 int en_flags = ENQUEUE_WAKEUP;
1685 lockdep_assert_held(&rq->lock);
1688 if (p->sched_contributes_to_load)
1689 rq->nr_uninterruptible--;
1691 if (wake_flags & WF_MIGRATED)
1692 en_flags |= ENQUEUE_MIGRATED;
1695 ttwu_activate(rq, p, en_flags);
1696 ttwu_do_wakeup(rq, p, wake_flags, rf);
1700 * Called in case the task @p isn't fully descheduled from its runqueue,
1701 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1702 * since all we need to do is flip p->state to TASK_RUNNING, since
1703 * the task is still ->on_rq.
1705 static int ttwu_remote(struct task_struct *p, int wake_flags)
1711 rq = __task_rq_lock(p, &rf);
1712 if (task_on_rq_queued(p)) {
1713 /* check_preempt_curr() may use rq clock */
1714 update_rq_clock(rq);
1715 ttwu_do_wakeup(rq, p, wake_flags, &rf);
1718 __task_rq_unlock(rq, &rf);
1724 void sched_ttwu_pending(void)
1726 struct rq *rq = this_rq();
1727 struct llist_node *llist = llist_del_all(&rq->wake_list);
1728 struct task_struct *p;
1729 unsigned long flags;
1735 raw_spin_lock_irqsave(&rq->lock, flags);
1736 rq_pin_lock(rq, &rf);
1741 p = llist_entry(llist, struct task_struct, wake_entry);
1742 llist = llist_next(llist);
1744 if (p->sched_remote_wakeup)
1745 wake_flags = WF_MIGRATED;
1747 ttwu_do_activate(rq, p, wake_flags, &rf);
1750 rq_unpin_lock(rq, &rf);
1751 raw_spin_unlock_irqrestore(&rq->lock, flags);
1754 void scheduler_ipi(void)
1757 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1758 * TIF_NEED_RESCHED remotely (for the first time) will also send
1761 preempt_fold_need_resched();
1763 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1767 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1768 * traditionally all their work was done from the interrupt return
1769 * path. Now that we actually do some work, we need to make sure
1772 * Some archs already do call them, luckily irq_enter/exit nest
1775 * Arguably we should visit all archs and update all handlers,
1776 * however a fair share of IPIs are still resched only so this would
1777 * somewhat pessimize the simple resched case.
1780 sched_ttwu_pending();
1783 * Check if someone kicked us for doing the nohz idle load balance.
1785 if (unlikely(got_nohz_idle_kick())) {
1786 this_rq()->idle_balance = 1;
1787 raise_softirq_irqoff(SCHED_SOFTIRQ);
1792 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1794 struct rq *rq = cpu_rq(cpu);
1796 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1798 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1799 if (!set_nr_if_polling(rq->idle))
1800 smp_send_reschedule(cpu);
1802 trace_sched_wake_idle_without_ipi(cpu);
1806 void wake_up_if_idle(int cpu)
1808 struct rq *rq = cpu_rq(cpu);
1809 unsigned long flags;
1813 if (!is_idle_task(rcu_dereference(rq->curr)))
1816 if (set_nr_if_polling(rq->idle)) {
1817 trace_sched_wake_idle_without_ipi(cpu);
1819 raw_spin_lock_irqsave(&rq->lock, flags);
1820 if (is_idle_task(rq->curr))
1821 smp_send_reschedule(cpu);
1822 /* Else CPU is not idle, do nothing here: */
1823 raw_spin_unlock_irqrestore(&rq->lock, flags);
1830 bool cpus_share_cache(int this_cpu, int that_cpu)
1832 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1834 #endif /* CONFIG_SMP */
1836 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1838 struct rq *rq = cpu_rq(cpu);
1841 #if defined(CONFIG_SMP)
1842 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1843 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
1844 ttwu_queue_remote(p, cpu, wake_flags);
1849 raw_spin_lock(&rq->lock);
1850 rq_pin_lock(rq, &rf);
1851 ttwu_do_activate(rq, p, wake_flags, &rf);
1852 rq_unpin_lock(rq, &rf);
1853 raw_spin_unlock(&rq->lock);
1857 * Notes on Program-Order guarantees on SMP systems.
1861 * The basic program-order guarantee on SMP systems is that when a task [t]
1862 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1863 * execution on its new CPU [c1].
1865 * For migration (of runnable tasks) this is provided by the following means:
1867 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1868 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1869 * rq(c1)->lock (if not at the same time, then in that order).
1870 * C) LOCK of the rq(c1)->lock scheduling in task
1872 * Transitivity guarantees that B happens after A and C after B.
1873 * Note: we only require RCpc transitivity.
1874 * Note: the CPU doing B need not be c0 or c1
1883 * UNLOCK rq(0)->lock
1885 * LOCK rq(0)->lock // orders against CPU0
1887 * UNLOCK rq(0)->lock
1891 * UNLOCK rq(1)->lock
1893 * LOCK rq(1)->lock // orders against CPU2
1896 * UNLOCK rq(1)->lock
1899 * BLOCKING -- aka. SLEEP + WAKEUP
1901 * For blocking we (obviously) need to provide the same guarantee as for
1902 * migration. However the means are completely different as there is no lock
1903 * chain to provide order. Instead we do:
1905 * 1) smp_store_release(X->on_cpu, 0)
1906 * 2) smp_cond_load_acquire(!X->on_cpu)
1910 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1912 * LOCK rq(0)->lock LOCK X->pi_lock
1915 * smp_store_release(X->on_cpu, 0);
1917 * smp_cond_load_acquire(&X->on_cpu, !VAL);
1923 * X->state = RUNNING
1924 * UNLOCK rq(2)->lock
1926 * LOCK rq(2)->lock // orders against CPU1
1929 * UNLOCK rq(2)->lock
1932 * UNLOCK rq(0)->lock
1935 * However; for wakeups there is a second guarantee we must provide, namely we
1936 * must observe the state that lead to our wakeup. That is, not only must our
1937 * task observe its own prior state, it must also observe the stores prior to
1940 * This means that any means of doing remote wakeups must order the CPU doing
1941 * the wakeup against the CPU the task is going to end up running on. This,
1942 * however, is already required for the regular Program-Order guarantee above,
1943 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
1948 * try_to_wake_up - wake up a thread
1949 * @p: the thread to be awakened
1950 * @state: the mask of task states that can be woken
1951 * @wake_flags: wake modifier flags (WF_*)
1953 * If (@state & @p->state) @p->state = TASK_RUNNING.
1955 * If the task was not queued/runnable, also place it back on a runqueue.
1957 * Atomic against schedule() which would dequeue a task, also see
1958 * set_current_state().
1960 * Return: %true if @p->state changes (an actual wakeup was done),
1964 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1966 unsigned long flags;
1967 int cpu, success = 0;
1970 * If we are going to wake up a thread waiting for CONDITION we
1971 * need to ensure that CONDITION=1 done by the caller can not be
1972 * reordered with p->state check below. This pairs with mb() in
1973 * set_current_state() the waiting thread does.
1975 smp_mb__before_spinlock();
1976 raw_spin_lock_irqsave(&p->pi_lock, flags);
1977 if (!(p->state & state))
1980 trace_sched_waking(p);
1982 /* We're going to change ->state: */
1987 * Ensure we load p->on_rq _after_ p->state, otherwise it would
1988 * be possible to, falsely, observe p->on_rq == 0 and get stuck
1989 * in smp_cond_load_acquire() below.
1991 * sched_ttwu_pending() try_to_wake_up()
1992 * [S] p->on_rq = 1; [L] P->state
1993 * UNLOCK rq->lock -----.
1997 * LOCK rq->lock -----'
2001 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2003 * Pairs with the UNLOCK+LOCK on rq->lock from the
2004 * last wakeup of our task and the schedule that got our task
2008 if (p->on_rq && ttwu_remote(p, wake_flags))
2013 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2014 * possible to, falsely, observe p->on_cpu == 0.
2016 * One must be running (->on_cpu == 1) in order to remove oneself
2017 * from the runqueue.
2019 * [S] ->on_cpu = 1; [L] ->on_rq
2023 * [S] ->on_rq = 0; [L] ->on_cpu
2025 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2026 * from the consecutive calls to schedule(); the first switching to our
2027 * task, the second putting it to sleep.
2032 * If the owning (remote) CPU is still in the middle of schedule() with
2033 * this task as prev, wait until its done referencing the task.
2035 * Pairs with the smp_store_release() in finish_lock_switch().
2037 * This ensures that tasks getting woken will be fully ordered against
2038 * their previous state and preserve Program Order.
2040 smp_cond_load_acquire(&p->on_cpu, !VAL);
2042 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2043 p->state = TASK_WAKING;
2046 delayacct_blkio_end();
2047 atomic_dec(&task_rq(p)->nr_iowait);
2050 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2051 if (task_cpu(p) != cpu) {
2052 wake_flags |= WF_MIGRATED;
2053 set_task_cpu(p, cpu);
2056 #else /* CONFIG_SMP */
2059 delayacct_blkio_end();
2060 atomic_dec(&task_rq(p)->nr_iowait);
2063 #endif /* CONFIG_SMP */
2065 ttwu_queue(p, cpu, wake_flags);
2067 ttwu_stat(p, cpu, wake_flags);
2069 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2075 * try_to_wake_up_local - try to wake up a local task with rq lock held
2076 * @p: the thread to be awakened
2077 * @cookie: context's cookie for pinning
2079 * Put @p on the run-queue if it's not already there. The caller must
2080 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2083 static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
2085 struct rq *rq = task_rq(p);
2087 if (WARN_ON_ONCE(rq != this_rq()) ||
2088 WARN_ON_ONCE(p == current))
2091 lockdep_assert_held(&rq->lock);
2093 if (!raw_spin_trylock(&p->pi_lock)) {
2095 * This is OK, because current is on_cpu, which avoids it being
2096 * picked for load-balance and preemption/IRQs are still
2097 * disabled avoiding further scheduler activity on it and we've
2098 * not yet picked a replacement task.
2100 rq_unpin_lock(rq, rf);
2101 raw_spin_unlock(&rq->lock);
2102 raw_spin_lock(&p->pi_lock);
2103 raw_spin_lock(&rq->lock);
2104 rq_repin_lock(rq, rf);
2107 if (!(p->state & TASK_NORMAL))
2110 trace_sched_waking(p);
2112 if (!task_on_rq_queued(p)) {
2114 delayacct_blkio_end();
2115 atomic_dec(&rq->nr_iowait);
2117 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2120 ttwu_do_wakeup(rq, p, 0, rf);
2121 ttwu_stat(p, smp_processor_id(), 0);
2123 raw_spin_unlock(&p->pi_lock);
2127 * wake_up_process - Wake up a specific process
2128 * @p: The process to be woken up.
2130 * Attempt to wake up the nominated process and move it to the set of runnable
2133 * Return: 1 if the process was woken up, 0 if it was already running.
2135 * It may be assumed that this function implies a write memory barrier before
2136 * changing the task state if and only if any tasks are woken up.
2138 int wake_up_process(struct task_struct *p)
2140 return try_to_wake_up(p, TASK_NORMAL, 0);
2142 EXPORT_SYMBOL(wake_up_process);
2144 int wake_up_state(struct task_struct *p, unsigned int state)
2146 return try_to_wake_up(p, state, 0);
2150 * This function clears the sched_dl_entity static params.
2152 void __dl_clear_params(struct task_struct *p)
2154 struct sched_dl_entity *dl_se = &p->dl;
2156 dl_se->dl_runtime = 0;
2157 dl_se->dl_deadline = 0;
2158 dl_se->dl_period = 0;
2162 dl_se->dl_throttled = 0;
2163 dl_se->dl_yielded = 0;
2167 * Perform scheduler related setup for a newly forked process p.
2168 * p is forked by current.
2170 * __sched_fork() is basic setup used by init_idle() too:
2172 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2177 p->se.exec_start = 0;
2178 p->se.sum_exec_runtime = 0;
2179 p->se.prev_sum_exec_runtime = 0;
2180 p->se.nr_migrations = 0;
2182 INIT_LIST_HEAD(&p->se.group_node);
2184 #ifdef CONFIG_FAIR_GROUP_SCHED
2185 p->se.cfs_rq = NULL;
2188 #ifdef CONFIG_SCHEDSTATS
2189 /* Even if schedstat is disabled, there should not be garbage */
2190 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2193 RB_CLEAR_NODE(&p->dl.rb_node);
2194 init_dl_task_timer(&p->dl);
2195 __dl_clear_params(p);
2197 INIT_LIST_HEAD(&p->rt.run_list);
2199 p->rt.time_slice = sched_rr_timeslice;
2203 #ifdef CONFIG_PREEMPT_NOTIFIERS
2204 INIT_HLIST_HEAD(&p->preempt_notifiers);
2207 #ifdef CONFIG_NUMA_BALANCING
2208 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
2209 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2210 p->mm->numa_scan_seq = 0;
2213 if (clone_flags & CLONE_VM)
2214 p->numa_preferred_nid = current->numa_preferred_nid;
2216 p->numa_preferred_nid = -1;
2218 p->node_stamp = 0ULL;
2219 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
2220 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2221 p->numa_work.next = &p->numa_work;
2222 p->numa_faults = NULL;
2223 p->last_task_numa_placement = 0;
2224 p->last_sum_exec_runtime = 0;
2226 p->numa_group = NULL;
2227 #endif /* CONFIG_NUMA_BALANCING */
2230 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2232 #ifdef CONFIG_NUMA_BALANCING
2234 void set_numabalancing_state(bool enabled)
2237 static_branch_enable(&sched_numa_balancing);
2239 static_branch_disable(&sched_numa_balancing);
2242 #ifdef CONFIG_PROC_SYSCTL
2243 int sysctl_numa_balancing(struct ctl_table *table, int write,
2244 void __user *buffer, size_t *lenp, loff_t *ppos)
2248 int state = static_branch_likely(&sched_numa_balancing);
2250 if (write && !capable(CAP_SYS_ADMIN))
2255 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2259 set_numabalancing_state(state);
2265 #ifdef CONFIG_SCHEDSTATS
2267 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2268 static bool __initdata __sched_schedstats = false;
2270 static void set_schedstats(bool enabled)
2273 static_branch_enable(&sched_schedstats);
2275 static_branch_disable(&sched_schedstats);
2278 void force_schedstat_enabled(void)
2280 if (!schedstat_enabled()) {
2281 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2282 static_branch_enable(&sched_schedstats);
2286 static int __init setup_schedstats(char *str)
2293 * This code is called before jump labels have been set up, so we can't
2294 * change the static branch directly just yet. Instead set a temporary
2295 * variable so init_schedstats() can do it later.
2297 if (!strcmp(str, "enable")) {
2298 __sched_schedstats = true;
2300 } else if (!strcmp(str, "disable")) {
2301 __sched_schedstats = false;
2306 pr_warn("Unable to parse schedstats=\n");
2310 __setup("schedstats=", setup_schedstats);
2312 static void __init init_schedstats(void)
2314 set_schedstats(__sched_schedstats);
2317 #ifdef CONFIG_PROC_SYSCTL
2318 int sysctl_schedstats(struct ctl_table *table, int write,
2319 void __user *buffer, size_t *lenp, loff_t *ppos)
2323 int state = static_branch_likely(&sched_schedstats);
2325 if (write && !capable(CAP_SYS_ADMIN))
2330 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2334 set_schedstats(state);
2337 #endif /* CONFIG_PROC_SYSCTL */
2338 #else /* !CONFIG_SCHEDSTATS */
2339 static inline void init_schedstats(void) {}
2340 #endif /* CONFIG_SCHEDSTATS */
2343 * fork()/clone()-time setup:
2345 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2347 unsigned long flags;
2348 int cpu = get_cpu();
2350 __sched_fork(clone_flags, p);
2352 * We mark the process as NEW here. This guarantees that
2353 * nobody will actually run it, and a signal or other external
2354 * event cannot wake it up and insert it on the runqueue either.
2356 p->state = TASK_NEW;
2359 * Make sure we do not leak PI boosting priority to the child.
2361 p->prio = current->normal_prio;
2364 * Revert to default priority/policy on fork if requested.
2366 if (unlikely(p->sched_reset_on_fork)) {
2367 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2368 p->policy = SCHED_NORMAL;
2369 p->static_prio = NICE_TO_PRIO(0);
2371 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2372 p->static_prio = NICE_TO_PRIO(0);
2374 p->prio = p->normal_prio = __normal_prio(p);
2378 * We don't need the reset flag anymore after the fork. It has
2379 * fulfilled its duty:
2381 p->sched_reset_on_fork = 0;
2384 if (dl_prio(p->prio)) {
2387 } else if (rt_prio(p->prio)) {
2388 p->sched_class = &rt_sched_class;
2390 p->sched_class = &fair_sched_class;
2393 init_entity_runnable_average(&p->se);
2396 * The child is not yet in the pid-hash so no cgroup attach races,
2397 * and the cgroup is pinned to this child due to cgroup_fork()
2398 * is ran before sched_fork().
2400 * Silence PROVE_RCU.
2402 raw_spin_lock_irqsave(&p->pi_lock, flags);
2404 * We're setting the CPU for the first time, we don't migrate,
2405 * so use __set_task_cpu().
2407 __set_task_cpu(p, cpu);
2408 if (p->sched_class->task_fork)
2409 p->sched_class->task_fork(p);
2410 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2412 #ifdef CONFIG_SCHED_INFO
2413 if (likely(sched_info_on()))
2414 memset(&p->sched_info, 0, sizeof(p->sched_info));
2416 #if defined(CONFIG_SMP)
2419 init_task_preempt_count(p);
2421 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2422 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2429 unsigned long to_ratio(u64 period, u64 runtime)
2431 if (runtime == RUNTIME_INF)
2435 * Doing this here saves a lot of checks in all
2436 * the calling paths, and returning zero seems
2437 * safe for them anyway.
2442 return div64_u64(runtime << 20, period);
2446 inline struct dl_bw *dl_bw_of(int i)
2448 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2449 "sched RCU must be held");
2450 return &cpu_rq(i)->rd->dl_bw;
2453 static inline int dl_bw_cpus(int i)
2455 struct root_domain *rd = cpu_rq(i)->rd;
2458 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2459 "sched RCU must be held");
2460 for_each_cpu_and(i, rd->span, cpu_active_mask)
2466 inline struct dl_bw *dl_bw_of(int i)
2468 return &cpu_rq(i)->dl.dl_bw;
2471 static inline int dl_bw_cpus(int i)
2478 * We must be sure that accepting a new task (or allowing changing the
2479 * parameters of an existing one) is consistent with the bandwidth
2480 * constraints. If yes, this function also accordingly updates the currently
2481 * allocated bandwidth to reflect the new situation.
2483 * This function is called while holding p's rq->lock.
2485 * XXX we should delay bw change until the task's 0-lag point, see
2488 static int dl_overflow(struct task_struct *p, int policy,
2489 const struct sched_attr *attr)
2492 struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2493 u64 period = attr->sched_period ?: attr->sched_deadline;
2494 u64 runtime = attr->sched_runtime;
2495 u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2498 /* !deadline task may carry old deadline bandwidth */
2499 if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
2503 * Either if a task, enters, leave, or stays -deadline but changes
2504 * its parameters, we may need to update accordingly the total
2505 * allocated bandwidth of the container.
2507 raw_spin_lock(&dl_b->lock);
2508 cpus = dl_bw_cpus(task_cpu(p));
2509 if (dl_policy(policy) && !task_has_dl_policy(p) &&
2510 !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2511 __dl_add(dl_b, new_bw);
2513 } else if (dl_policy(policy) && task_has_dl_policy(p) &&
2514 !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2515 __dl_clear(dl_b, p->dl.dl_bw);
2516 __dl_add(dl_b, new_bw);
2518 } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2519 __dl_clear(dl_b, p->dl.dl_bw);
2522 raw_spin_unlock(&dl_b->lock);
2527 extern void init_dl_bw(struct dl_bw *dl_b);
2530 * wake_up_new_task - wake up a newly created task for the first time.
2532 * This function will do some initial scheduler statistics housekeeping
2533 * that must be done for every newly created context, then puts the task
2534 * on the runqueue and wakes it.
2536 void wake_up_new_task(struct task_struct *p)
2541 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2542 p->state = TASK_RUNNING;
2545 * Fork balancing, do it here and not earlier because:
2546 * - cpus_allowed can change in the fork path
2547 * - any previously selected CPU might disappear through hotplug
2549 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2550 * as we're not fully set-up yet.
2552 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2554 rq = __task_rq_lock(p, &rf);
2555 update_rq_clock(rq);
2556 post_init_entity_util_avg(&p->se);
2558 activate_task(rq, p, 0);
2559 p->on_rq = TASK_ON_RQ_QUEUED;
2560 trace_sched_wakeup_new(p);
2561 check_preempt_curr(rq, p, WF_FORK);
2563 if (p->sched_class->task_woken) {
2565 * Nothing relies on rq->lock after this, so its fine to
2568 rq_unpin_lock(rq, &rf);
2569 p->sched_class->task_woken(rq, p);
2570 rq_repin_lock(rq, &rf);
2573 task_rq_unlock(rq, p, &rf);
2576 #ifdef CONFIG_PREEMPT_NOTIFIERS
2578 static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2580 void preempt_notifier_inc(void)
2582 static_key_slow_inc(&preempt_notifier_key);
2584 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2586 void preempt_notifier_dec(void)
2588 static_key_slow_dec(&preempt_notifier_key);
2590 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2593 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2594 * @notifier: notifier struct to register
2596 void preempt_notifier_register(struct preempt_notifier *notifier)
2598 if (!static_key_false(&preempt_notifier_key))
2599 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2601 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2603 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2606 * preempt_notifier_unregister - no longer interested in preemption notifications
2607 * @notifier: notifier struct to unregister
2609 * This is *not* safe to call from within a preemption notifier.
2611 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2613 hlist_del(¬ifier->link);
2615 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2617 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2619 struct preempt_notifier *notifier;
2621 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2622 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2625 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2627 if (static_key_false(&preempt_notifier_key))
2628 __fire_sched_in_preempt_notifiers(curr);
2632 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2633 struct task_struct *next)
2635 struct preempt_notifier *notifier;
2637 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2638 notifier->ops->sched_out(notifier, next);
2641 static __always_inline void
2642 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2643 struct task_struct *next)
2645 if (static_key_false(&preempt_notifier_key))
2646 __fire_sched_out_preempt_notifiers(curr, next);
2649 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2651 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2656 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2657 struct task_struct *next)
2661 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2664 * prepare_task_switch - prepare to switch tasks
2665 * @rq: the runqueue preparing to switch
2666 * @prev: the current task that is being switched out
2667 * @next: the task we are going to switch to.
2669 * This is called with the rq lock held and interrupts off. It must
2670 * be paired with a subsequent finish_task_switch after the context
2673 * prepare_task_switch sets up locking and calls architecture specific
2677 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2678 struct task_struct *next)
2680 sched_info_switch(rq, prev, next);
2681 perf_event_task_sched_out(prev, next);
2682 fire_sched_out_preempt_notifiers(prev, next);
2683 prepare_lock_switch(rq, next);
2684 prepare_arch_switch(next);
2688 * finish_task_switch - clean up after a task-switch
2689 * @prev: the thread we just switched away from.
2691 * finish_task_switch must be called after the context switch, paired
2692 * with a prepare_task_switch call before the context switch.
2693 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2694 * and do any other architecture-specific cleanup actions.
2696 * Note that we may have delayed dropping an mm in context_switch(). If
2697 * so, we finish that here outside of the runqueue lock. (Doing it
2698 * with the lock held can cause deadlocks; see schedule() for
2701 * The context switch have flipped the stack from under us and restored the
2702 * local variables which were saved when this task called schedule() in the
2703 * past. prev == current is still correct but we need to recalculate this_rq
2704 * because prev may have moved to another CPU.
2706 static struct rq *finish_task_switch(struct task_struct *prev)
2707 __releases(rq->lock)
2709 struct rq *rq = this_rq();
2710 struct mm_struct *mm = rq->prev_mm;
2714 * The previous task will have left us with a preempt_count of 2
2715 * because it left us after:
2718 * preempt_disable(); // 1
2720 * raw_spin_lock_irq(&rq->lock) // 2
2722 * Also, see FORK_PREEMPT_COUNT.
2724 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2725 "corrupted preempt_count: %s/%d/0x%x\n",
2726 current->comm, current->pid, preempt_count()))
2727 preempt_count_set(FORK_PREEMPT_COUNT);
2732 * A task struct has one reference for the use as "current".
2733 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2734 * schedule one last time. The schedule call will never return, and
2735 * the scheduled task must drop that reference.
2737 * We must observe prev->state before clearing prev->on_cpu (in
2738 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2739 * running on another CPU and we could rave with its RUNNING -> DEAD
2740 * transition, resulting in a double drop.
2742 prev_state = prev->state;
2743 vtime_task_switch(prev);
2744 perf_event_task_sched_in(prev, current);
2745 finish_lock_switch(rq, prev);
2746 finish_arch_post_lock_switch();
2748 fire_sched_in_preempt_notifiers(current);
2751 if (unlikely(prev_state == TASK_DEAD)) {
2752 if (prev->sched_class->task_dead)
2753 prev->sched_class->task_dead(prev);
2756 * Remove function-return probe instances associated with this
2757 * task and put them back on the free list.
2759 kprobe_flush_task(prev);
2761 /* Task is done with its stack. */
2762 put_task_stack(prev);
2764 put_task_struct(prev);
2767 tick_nohz_task_switch();
2773 /* rq->lock is NOT held, but preemption is disabled */
2774 static void __balance_callback(struct rq *rq)
2776 struct callback_head *head, *next;
2777 void (*func)(struct rq *rq);
2778 unsigned long flags;
2780 raw_spin_lock_irqsave(&rq->lock, flags);
2781 head = rq->balance_callback;
2782 rq->balance_callback = NULL;
2784 func = (void (*)(struct rq *))head->func;
2791 raw_spin_unlock_irqrestore(&rq->lock, flags);
2794 static inline void balance_callback(struct rq *rq)
2796 if (unlikely(rq->balance_callback))
2797 __balance_callback(rq);
2802 static inline void balance_callback(struct rq *rq)
2809 * schedule_tail - first thing a freshly forked thread must call.
2810 * @prev: the thread we just switched away from.
2812 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2813 __releases(rq->lock)
2818 * New tasks start with FORK_PREEMPT_COUNT, see there and
2819 * finish_task_switch() for details.
2821 * finish_task_switch() will drop rq->lock() and lower preempt_count
2822 * and the preempt_enable() will end up enabling preemption (on
2823 * PREEMPT_COUNT kernels).
2826 rq = finish_task_switch(prev);
2827 balance_callback(rq);
2830 if (current->set_child_tid)
2831 put_user(task_pid_vnr(current), current->set_child_tid);
2835 * context_switch - switch to the new MM and the new thread's register state.
2837 static __always_inline struct rq *
2838 context_switch(struct rq *rq, struct task_struct *prev,
2839 struct task_struct *next, struct rq_flags *rf)
2841 struct mm_struct *mm, *oldmm;
2843 prepare_task_switch(rq, prev, next);
2846 oldmm = prev->active_mm;
2848 * For paravirt, this is coupled with an exit in switch_to to
2849 * combine the page table reload and the switch backend into
2852 arch_start_context_switch(prev);
2855 next->active_mm = oldmm;
2857 enter_lazy_tlb(oldmm, next);
2859 switch_mm_irqs_off(oldmm, mm, next);
2862 prev->active_mm = NULL;
2863 rq->prev_mm = oldmm;
2866 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
2869 * Since the runqueue lock will be released by the next
2870 * task (which is an invalid locking op but in the case
2871 * of the scheduler it's an obvious special-case), so we
2872 * do an early lockdep release here:
2874 rq_unpin_lock(rq, rf);
2875 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2877 /* Here we just switch the register state and the stack. */
2878 switch_to(prev, next, prev);
2881 return finish_task_switch(prev);
2885 * nr_running and nr_context_switches:
2887 * externally visible scheduler statistics: current number of runnable
2888 * threads, total number of context switches performed since bootup.
2890 unsigned long nr_running(void)
2892 unsigned long i, sum = 0;
2894 for_each_online_cpu(i)
2895 sum += cpu_rq(i)->nr_running;
2901 * Check if only the current task is running on the CPU.
2903 * Caution: this function does not check that the caller has disabled
2904 * preemption, thus the result might have a time-of-check-to-time-of-use
2905 * race. The caller is responsible to use it correctly, for example:
2907 * - from a non-preemptable section (of course)
2909 * - from a thread that is bound to a single CPU
2911 * - in a loop with very short iterations (e.g. a polling loop)
2913 bool single_task_running(void)
2915 return raw_rq()->nr_running == 1;
2917 EXPORT_SYMBOL(single_task_running);
2919 unsigned long long nr_context_switches(void)
2922 unsigned long long sum = 0;
2924 for_each_possible_cpu(i)
2925 sum += cpu_rq(i)->nr_switches;
2931 * IO-wait accounting, and how its mostly bollocks (on SMP).
2933 * The idea behind IO-wait account is to account the idle time that we could
2934 * have spend running if it were not for IO. That is, if we were to improve the
2935 * storage performance, we'd have a proportional reduction in IO-wait time.
2937 * This all works nicely on UP, where, when a task blocks on IO, we account
2938 * idle time as IO-wait, because if the storage were faster, it could've been
2939 * running and we'd not be idle.
2941 * This has been extended to SMP, by doing the same for each CPU. This however
2944 * Imagine for instance the case where two tasks block on one CPU, only the one
2945 * CPU will have IO-wait accounted, while the other has regular idle. Even
2946 * though, if the storage were faster, both could've ran at the same time,
2947 * utilising both CPUs.
2949 * This means, that when looking globally, the current IO-wait accounting on
2950 * SMP is a lower bound, by reason of under accounting.
2952 * Worse, since the numbers are provided per CPU, they are sometimes
2953 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2954 * associated with any one particular CPU, it can wake to another CPU than it
2955 * blocked on. This means the per CPU IO-wait number is meaningless.
2957 * Task CPU affinities can make all that even more 'interesting'.
2960 unsigned long nr_iowait(void)
2962 unsigned long i, sum = 0;
2964 for_each_possible_cpu(i)
2965 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2971 * Consumers of these two interfaces, like for example the cpufreq menu
2972 * governor are using nonsensical data. Boosting frequency for a CPU that has
2973 * IO-wait which might not even end up running the task when it does become
2977 unsigned long nr_iowait_cpu(int cpu)
2979 struct rq *this = cpu_rq(cpu);
2980 return atomic_read(&this->nr_iowait);
2983 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2985 struct rq *rq = this_rq();
2986 *nr_waiters = atomic_read(&rq->nr_iowait);
2987 *load = rq->load.weight;
2993 * sched_exec - execve() is a valuable balancing opportunity, because at
2994 * this point the task has the smallest effective memory and cache footprint.
2996 void sched_exec(void)
2998 struct task_struct *p = current;
2999 unsigned long flags;
3002 raw_spin_lock_irqsave(&p->pi_lock, flags);
3003 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
3004 if (dest_cpu == smp_processor_id())
3007 if (likely(cpu_active(dest_cpu))) {
3008 struct migration_arg arg = { p, dest_cpu };
3010 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3011 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
3015 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3020 DEFINE_PER_CPU(struct kernel_stat, kstat);
3021 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
3023 EXPORT_PER_CPU_SYMBOL(kstat);
3024 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3027 * The function fair_sched_class.update_curr accesses the struct curr
3028 * and its field curr->exec_start; when called from task_sched_runtime(),
3029 * we observe a high rate of cache misses in practice.
3030 * Prefetching this data results in improved performance.
3032 static inline void prefetch_curr_exec_start(struct task_struct *p)
3034 #ifdef CONFIG_FAIR_GROUP_SCHED
3035 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3037 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3040 prefetch(&curr->exec_start);
3044 * Return accounted runtime for the task.
3045 * In case the task is currently running, return the runtime plus current's
3046 * pending runtime that have not been accounted yet.
3048 unsigned long long task_sched_runtime(struct task_struct *p)
3054 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3056 * 64-bit doesn't need locks to atomically read a 64bit value.
3057 * So we have a optimization chance when the task's delta_exec is 0.
3058 * Reading ->on_cpu is racy, but this is ok.
3060 * If we race with it leaving CPU, we'll take a lock. So we're correct.
3061 * If we race with it entering CPU, unaccounted time is 0. This is
3062 * indistinguishable from the read occurring a few cycles earlier.
3063 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3064 * been accounted, so we're correct here as well.
3066 if (!p->on_cpu || !task_on_rq_queued(p))
3067 return p->se.sum_exec_runtime;
3070 rq = task_rq_lock(p, &rf);
3072 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3073 * project cycles that may never be accounted to this
3074 * thread, breaking clock_gettime().
3076 if (task_current(rq, p) && task_on_rq_queued(p)) {
3077 prefetch_curr_exec_start(p);
3078 update_rq_clock(rq);
3079 p->sched_class->update_curr(rq);
3081 ns = p->se.sum_exec_runtime;
3082 task_rq_unlock(rq, p, &rf);
3088 * This function gets called by the timer code, with HZ frequency.
3089 * We call it with interrupts disabled.
3091 void scheduler_tick(void)
3093 int cpu = smp_processor_id();
3094 struct rq *rq = cpu_rq(cpu);
3095 struct task_struct *curr = rq->curr;
3099 raw_spin_lock(&rq->lock);
3100 update_rq_clock(rq);
3101 curr->sched_class->task_tick(rq, curr, 0);
3102 cpu_load_update_active(rq);
3103 calc_global_load_tick(rq);
3104 raw_spin_unlock(&rq->lock);
3106 perf_event_task_tick();
3109 rq->idle_balance = idle_cpu(cpu);
3110 trigger_load_balance(rq);
3112 rq_last_tick_reset(rq);
3115 #ifdef CONFIG_NO_HZ_FULL
3117 * scheduler_tick_max_deferment
3119 * Keep at least one tick per second when a single
3120 * active task is running because the scheduler doesn't
3121 * yet completely support full dynticks environment.
3123 * This makes sure that uptime, CFS vruntime, load
3124 * balancing, etc... continue to move forward, even
3125 * with a very low granularity.
3127 * Return: Maximum deferment in nanoseconds.
3129 u64 scheduler_tick_max_deferment(void)
3131 struct rq *rq = this_rq();
3132 unsigned long next, now = READ_ONCE(jiffies);
3134 next = rq->last_sched_tick + HZ;
3136 if (time_before_eq(next, now))
3139 return jiffies_to_nsecs(next - now);
3143 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3144 defined(CONFIG_PREEMPT_TRACER))
3146 * If the value passed in is equal to the current preempt count
3147 * then we just disabled preemption. Start timing the latency.
3149 static inline void preempt_latency_start(int val)
3151 if (preempt_count() == val) {
3152 unsigned long ip = get_lock_parent_ip();
3153 #ifdef CONFIG_DEBUG_PREEMPT
3154 current->preempt_disable_ip = ip;
3156 trace_preempt_off(CALLER_ADDR0, ip);
3160 void preempt_count_add(int val)
3162 #ifdef CONFIG_DEBUG_PREEMPT
3166 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3169 __preempt_count_add(val);
3170 #ifdef CONFIG_DEBUG_PREEMPT
3172 * Spinlock count overflowing soon?
3174 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3177 preempt_latency_start(val);
3179 EXPORT_SYMBOL(preempt_count_add);
3180 NOKPROBE_SYMBOL(preempt_count_add);
3183 * If the value passed in equals to the current preempt count
3184 * then we just enabled preemption. Stop timing the latency.
3186 static inline void preempt_latency_stop(int val)
3188 if (preempt_count() == val)
3189 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3192 void preempt_count_sub(int val)
3194 #ifdef CONFIG_DEBUG_PREEMPT
3198 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3201 * Is the spinlock portion underflowing?
3203 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3204 !(preempt_count() & PREEMPT_MASK)))
3208 preempt_latency_stop(val);
3209 __preempt_count_sub(val);
3211 EXPORT_SYMBOL(preempt_count_sub);
3212 NOKPROBE_SYMBOL(preempt_count_sub);
3215 static inline void preempt_latency_start(int val) { }
3216 static inline void preempt_latency_stop(int val) { }
3219 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3221 #ifdef CONFIG_DEBUG_PREEMPT
3222 return p->preempt_disable_ip;
3229 * Print scheduling while atomic bug:
3231 static noinline void __schedule_bug(struct task_struct *prev)
3233 /* Save this before calling printk(), since that will clobber it */
3234 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3236 if (oops_in_progress)
3239 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3240 prev->comm, prev->pid, preempt_count());
3242 debug_show_held_locks(prev);
3244 if (irqs_disabled())
3245 print_irqtrace_events(prev);
3246 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3247 && in_atomic_preempt_off()) {
3248 pr_err("Preemption disabled at:");
3249 print_ip_sym(preempt_disable_ip);
3253 panic("scheduling while atomic\n");
3256 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3260 * Various schedule()-time debugging checks and statistics:
3262 static inline void schedule_debug(struct task_struct *prev)
3264 #ifdef CONFIG_SCHED_STACK_END_CHECK
3265 if (task_stack_end_corrupted(prev))
3266 panic("corrupted stack end detected inside scheduler\n");
3269 if (unlikely(in_atomic_preempt_off())) {
3270 __schedule_bug(prev);
3271 preempt_count_set(PREEMPT_DISABLED);
3275 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3277 schedstat_inc(this_rq()->sched_count);
3281 * Pick up the highest-prio task:
3283 static inline struct task_struct *
3284 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
3286 const struct sched_class *class;
3287 struct task_struct *p;
3290 * Optimization: we know that if all tasks are in the fair class we can
3291 * call that function directly, but only if the @prev task wasn't of a
3292 * higher scheduling class, because otherwise those loose the
3293 * opportunity to pull in more work from other CPUs.
3295 if (likely((prev->sched_class == &idle_sched_class ||
3296 prev->sched_class == &fair_sched_class) &&
3297 rq->nr_running == rq->cfs.h_nr_running)) {
3299 p = fair_sched_class.pick_next_task(rq, prev, rf);
3300 if (unlikely(p == RETRY_TASK))
3303 /* Assumes fair_sched_class->next == idle_sched_class */
3305 p = idle_sched_class.pick_next_task(rq, prev, rf);
3311 for_each_class(class) {
3312 p = class->pick_next_task(rq, prev, rf);
3314 if (unlikely(p == RETRY_TASK))
3320 /* The idle class should always have a runnable task: */
3325 * __schedule() is the main scheduler function.
3327 * The main means of driving the scheduler and thus entering this function are:
3329 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3331 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3332 * paths. For example, see arch/x86/entry_64.S.
3334 * To drive preemption between tasks, the scheduler sets the flag in timer
3335 * interrupt handler scheduler_tick().
3337 * 3. Wakeups don't really cause entry into schedule(). They add a
3338 * task to the run-queue and that's it.
3340 * Now, if the new task added to the run-queue preempts the current
3341 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3342 * called on the nearest possible occasion:
3344 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3346 * - in syscall or exception context, at the next outmost
3347 * preempt_enable(). (this might be as soon as the wake_up()'s
3350 * - in IRQ context, return from interrupt-handler to
3351 * preemptible context
3353 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3356 * - cond_resched() call
3357 * - explicit schedule() call
3358 * - return from syscall or exception to user-space
3359 * - return from interrupt-handler to user-space
3361 * WARNING: must be called with preemption disabled!
3363 static void __sched notrace __schedule(bool preempt)
3365 struct task_struct *prev, *next;
3366 unsigned long *switch_count;
3371 cpu = smp_processor_id();
3375 schedule_debug(prev);
3377 if (sched_feat(HRTICK))
3380 local_irq_disable();
3381 rcu_note_context_switch();
3384 * Make sure that signal_pending_state()->signal_pending() below
3385 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3386 * done by the caller to avoid the race with signal_wake_up().
3388 smp_mb__before_spinlock();
3389 raw_spin_lock(&rq->lock);
3390 rq_pin_lock(rq, &rf);
3392 /* Promote REQ to ACT */
3393 rq->clock_update_flags <<= 1;
3395 switch_count = &prev->nivcsw;
3396 if (!preempt && prev->state) {
3397 if (unlikely(signal_pending_state(prev->state, prev))) {
3398 prev->state = TASK_RUNNING;
3400 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3403 if (prev->in_iowait) {
3404 atomic_inc(&rq->nr_iowait);
3405 delayacct_blkio_start();
3409 * If a worker went to sleep, notify and ask workqueue
3410 * whether it wants to wake up a task to maintain
3413 if (prev->flags & PF_WQ_WORKER) {
3414 struct task_struct *to_wakeup;
3416 to_wakeup = wq_worker_sleeping(prev);
3418 try_to_wake_up_local(to_wakeup, &rf);
3421 switch_count = &prev->nvcsw;
3424 if (task_on_rq_queued(prev))
3425 update_rq_clock(rq);
3427 next = pick_next_task(rq, prev, &rf);
3428 clear_tsk_need_resched(prev);
3429 clear_preempt_need_resched();
3431 if (likely(prev != next)) {
3436 trace_sched_switch(preempt, prev, next);
3438 /* Also unlocks the rq: */
3439 rq = context_switch(rq, prev, next, &rf);
3441 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3442 rq_unpin_lock(rq, &rf);
3443 raw_spin_unlock_irq(&rq->lock);
3446 balance_callback(rq);
3449 void __noreturn do_task_dead(void)
3452 * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
3453 * when the following two conditions become true.
3454 * - There is race condition of mmap_sem (It is acquired by
3456 * - SMI occurs before setting TASK_RUNINNG.
3457 * (or hypervisor of virtual machine switches to other guest)
3458 * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
3460 * To avoid it, we have to wait for releasing tsk->pi_lock which
3461 * is held by try_to_wake_up()
3464 raw_spin_unlock_wait(¤t->pi_lock);
3466 /* Causes final put_task_struct in finish_task_switch(): */
3467 __set_current_state(TASK_DEAD);
3469 /* Tell freezer to ignore us: */
3470 current->flags |= PF_NOFREEZE;
3475 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
3480 static inline void sched_submit_work(struct task_struct *tsk)
3482 if (!tsk->state || tsk_is_pi_blocked(tsk))
3485 * If we are going to sleep and we have plugged IO queued,
3486 * make sure to submit it to avoid deadlocks.
3488 if (blk_needs_flush_plug(tsk))
3489 blk_schedule_flush_plug(tsk);
3492 asmlinkage __visible void __sched schedule(void)
3494 struct task_struct *tsk = current;
3496 sched_submit_work(tsk);
3500 sched_preempt_enable_no_resched();
3501 } while (need_resched());
3503 EXPORT_SYMBOL(schedule);
3505 #ifdef CONFIG_CONTEXT_TRACKING
3506 asmlinkage __visible void __sched schedule_user(void)
3509 * If we come here after a random call to set_need_resched(),
3510 * or we have been woken up remotely but the IPI has not yet arrived,
3511 * we haven't yet exited the RCU idle mode. Do it here manually until
3512 * we find a better solution.
3514 * NB: There are buggy callers of this function. Ideally we
3515 * should warn if prev_state != CONTEXT_USER, but that will trigger
3516 * too frequently to make sense yet.
3518 enum ctx_state prev_state = exception_enter();
3520 exception_exit(prev_state);
3525 * schedule_preempt_disabled - called with preemption disabled
3527 * Returns with preemption disabled. Note: preempt_count must be 1
3529 void __sched schedule_preempt_disabled(void)
3531 sched_preempt_enable_no_resched();
3536 static void __sched notrace preempt_schedule_common(void)
3540 * Because the function tracer can trace preempt_count_sub()
3541 * and it also uses preempt_enable/disable_notrace(), if
3542 * NEED_RESCHED is set, the preempt_enable_notrace() called
3543 * by the function tracer will call this function again and
3544 * cause infinite recursion.
3546 * Preemption must be disabled here before the function
3547 * tracer can trace. Break up preempt_disable() into two
3548 * calls. One to disable preemption without fear of being
3549 * traced. The other to still record the preemption latency,
3550 * which can also be traced by the function tracer.
3552 preempt_disable_notrace();
3553 preempt_latency_start(1);
3555 preempt_latency_stop(1);
3556 preempt_enable_no_resched_notrace();
3559 * Check again in case we missed a preemption opportunity
3560 * between schedule and now.
3562 } while (need_resched());
3565 #ifdef CONFIG_PREEMPT
3567 * this is the entry point to schedule() from in-kernel preemption
3568 * off of preempt_enable. Kernel preemptions off return from interrupt
3569 * occur there and call schedule directly.
3571 asmlinkage __visible void __sched notrace preempt_schedule(void)
3574 * If there is a non-zero preempt_count or interrupts are disabled,
3575 * we do not want to preempt the current task. Just return..
3577 if (likely(!preemptible()))
3580 preempt_schedule_common();
3582 NOKPROBE_SYMBOL(preempt_schedule);
3583 EXPORT_SYMBOL(preempt_schedule);
3586 * preempt_schedule_notrace - preempt_schedule called by tracing
3588 * The tracing infrastructure uses preempt_enable_notrace to prevent
3589 * recursion and tracing preempt enabling caused by the tracing
3590 * infrastructure itself. But as tracing can happen in areas coming
3591 * from userspace or just about to enter userspace, a preempt enable
3592 * can occur before user_exit() is called. This will cause the scheduler
3593 * to be called when the system is still in usermode.
3595 * To prevent this, the preempt_enable_notrace will use this function
3596 * instead of preempt_schedule() to exit user context if needed before
3597 * calling the scheduler.
3599 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3601 enum ctx_state prev_ctx;
3603 if (likely(!preemptible()))
3608 * Because the function tracer can trace preempt_count_sub()
3609 * and it also uses preempt_enable/disable_notrace(), if
3610 * NEED_RESCHED is set, the preempt_enable_notrace() called
3611 * by the function tracer will call this function again and
3612 * cause infinite recursion.
3614 * Preemption must be disabled here before the function
3615 * tracer can trace. Break up preempt_disable() into two
3616 * calls. One to disable preemption without fear of being
3617 * traced. The other to still record the preemption latency,
3618 * which can also be traced by the function tracer.
3620 preempt_disable_notrace();
3621 preempt_latency_start(1);
3623 * Needs preempt disabled in case user_exit() is traced
3624 * and the tracer calls preempt_enable_notrace() causing
3625 * an infinite recursion.
3627 prev_ctx = exception_enter();
3629 exception_exit(prev_ctx);
3631 preempt_latency_stop(1);
3632 preempt_enable_no_resched_notrace();
3633 } while (need_resched());
3635 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3637 #endif /* CONFIG_PREEMPT */
3640 * this is the entry point to schedule() from kernel preemption
3641 * off of irq context.
3642 * Note, that this is called and return with irqs disabled. This will
3643 * protect us against recursive calling from irq.
3645 asmlinkage __visible void __sched preempt_schedule_irq(void)
3647 enum ctx_state prev_state;
3649 /* Catch callers which need to be fixed */
3650 BUG_ON(preempt_count() || !irqs_disabled());
3652 prev_state = exception_enter();
3658 local_irq_disable();
3659 sched_preempt_enable_no_resched();
3660 } while (need_resched());
3662 exception_exit(prev_state);
3665 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3668 return try_to_wake_up(curr->private, mode, wake_flags);
3670 EXPORT_SYMBOL(default_wake_function);
3672 #ifdef CONFIG_RT_MUTEXES
3675 * rt_mutex_setprio - set the current priority of a task
3677 * @prio: prio value (kernel-internal form)
3679 * This function changes the 'effective' priority of a task. It does
3680 * not touch ->normal_prio like __setscheduler().
3682 * Used by the rt_mutex code to implement priority inheritance
3683 * logic. Call site only calls if the priority of the task changed.
3685 void rt_mutex_setprio(struct task_struct *p, int prio)
3687 int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
3688 const struct sched_class *prev_class;
3692 BUG_ON(prio > MAX_PRIO);
3694 rq = __task_rq_lock(p, &rf);
3695 update_rq_clock(rq);
3698 * Idle task boosting is a nono in general. There is one
3699 * exception, when PREEMPT_RT and NOHZ is active:
3701 * The idle task calls get_next_timer_interrupt() and holds
3702 * the timer wheel base->lock on the CPU and another CPU wants
3703 * to access the timer (probably to cancel it). We can safely
3704 * ignore the boosting request, as the idle CPU runs this code
3705 * with interrupts disabled and will complete the lock
3706 * protected section without being interrupted. So there is no
3707 * real need to boost.
3709 if (unlikely(p == rq->idle)) {
3710 WARN_ON(p != rq->curr);
3711 WARN_ON(p->pi_blocked_on);
3715 trace_sched_pi_setprio(p, prio);
3718 if (oldprio == prio)
3719 queue_flag &= ~DEQUEUE_MOVE;
3721 prev_class = p->sched_class;
3722 queued = task_on_rq_queued(p);
3723 running = task_current(rq, p);
3725 dequeue_task(rq, p, queue_flag);
3727 put_prev_task(rq, p);
3730 * Boosting condition are:
3731 * 1. -rt task is running and holds mutex A
3732 * --> -dl task blocks on mutex A
3734 * 2. -dl task is running and holds mutex A
3735 * --> -dl task blocks on mutex A and could preempt the
3738 if (dl_prio(prio)) {
3739 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3740 if (!dl_prio(p->normal_prio) ||
3741 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3742 p->dl.dl_boosted = 1;
3743 queue_flag |= ENQUEUE_REPLENISH;
3745 p->dl.dl_boosted = 0;
3746 p->sched_class = &dl_sched_class;
3747 } else if (rt_prio(prio)) {
3748 if (dl_prio(oldprio))
3749 p->dl.dl_boosted = 0;
3751 queue_flag |= ENQUEUE_HEAD;
3752 p->sched_class = &rt_sched_class;
3754 if (dl_prio(oldprio))
3755 p->dl.dl_boosted = 0;
3756 if (rt_prio(oldprio))
3758 p->sched_class = &fair_sched_class;
3764 enqueue_task(rq, p, queue_flag);
3766 set_curr_task(rq, p);
3768 check_class_changed(rq, p, prev_class, oldprio);
3770 /* Avoid rq from going away on us: */
3772 __task_rq_unlock(rq, &rf);
3774 balance_callback(rq);
3779 void set_user_nice(struct task_struct *p, long nice)
3781 bool queued, running;
3782 int old_prio, delta;
3786 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3789 * We have to be careful, if called from sys_setpriority(),
3790 * the task might be in the middle of scheduling on another CPU.
3792 rq = task_rq_lock(p, &rf);
3793 update_rq_clock(rq);
3796 * The RT priorities are set via sched_setscheduler(), but we still
3797 * allow the 'normal' nice value to be set - but as expected
3798 * it wont have any effect on scheduling until the task is
3799 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3801 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3802 p->static_prio = NICE_TO_PRIO(nice);
3805 queued = task_on_rq_queued(p);
3806 running = task_current(rq, p);
3808 dequeue_task(rq, p, DEQUEUE_SAVE);
3810 put_prev_task(rq, p);
3812 p->static_prio = NICE_TO_PRIO(nice);
3815 p->prio = effective_prio(p);
3816 delta = p->prio - old_prio;
3819 enqueue_task(rq, p, ENQUEUE_RESTORE);
3821 * If the task increased its priority or is running and
3822 * lowered its priority, then reschedule its CPU:
3824 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3828 set_curr_task(rq, p);
3830 task_rq_unlock(rq, p, &rf);
3832 EXPORT_SYMBOL(set_user_nice);
3835 * can_nice - check if a task can reduce its nice value
3839 int can_nice(const struct task_struct *p, const int nice)
3841 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
3842 int nice_rlim = nice_to_rlimit(nice);
3844 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3845 capable(CAP_SYS_NICE));
3848 #ifdef __ARCH_WANT_SYS_NICE
3851 * sys_nice - change the priority of the current process.
3852 * @increment: priority increment
3854 * sys_setpriority is a more generic, but much slower function that
3855 * does similar things.
3857 SYSCALL_DEFINE1(nice, int, increment)
3862 * Setpriority might change our priority at the same moment.
3863 * We don't have to worry. Conceptually one call occurs first
3864 * and we have a single winner.
3866 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3867 nice = task_nice(current) + increment;
3869 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3870 if (increment < 0 && !can_nice(current, nice))
3873 retval = security_task_setnice(current, nice);
3877 set_user_nice(current, nice);
3884 * task_prio - return the priority value of a given task.
3885 * @p: the task in question.
3887 * Return: The priority value as seen by users in /proc.
3888 * RT tasks are offset by -200. Normal tasks are centered
3889 * around 0, value goes from -16 to +15.
3891 int task_prio(const struct task_struct *p)
3893 return p->prio - MAX_RT_PRIO;
3897 * idle_cpu - is a given CPU idle currently?
3898 * @cpu: the processor in question.
3900 * Return: 1 if the CPU is currently idle. 0 otherwise.
3902 int idle_cpu(int cpu)
3904 struct rq *rq = cpu_rq(cpu);
3906 if (rq->curr != rq->idle)
3913 if (!llist_empty(&rq->wake_list))
3921 * idle_task - return the idle task for a given CPU.
3922 * @cpu: the processor in question.
3924 * Return: The idle task for the CPU @cpu.
3926 struct task_struct *idle_task(int cpu)
3928 return cpu_rq(cpu)->idle;
3932 * find_process_by_pid - find a process with a matching PID value.
3933 * @pid: the pid in question.
3935 * The task of @pid, if found. %NULL otherwise.
3937 static struct task_struct *find_process_by_pid(pid_t pid)
3939 return pid ? find_task_by_vpid(pid) : current;
3943 * This function initializes the sched_dl_entity of a newly becoming
3944 * SCHED_DEADLINE task.
3946 * Only the static values are considered here, the actual runtime and the
3947 * absolute deadline will be properly calculated when the task is enqueued
3948 * for the first time with its new policy.
3951 __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
3953 struct sched_dl_entity *dl_se = &p->dl;
3955 dl_se->dl_runtime = attr->sched_runtime;
3956 dl_se->dl_deadline = attr->sched_deadline;
3957 dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
3958 dl_se->flags = attr->sched_flags;
3959 dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
3962 * Changing the parameters of a task is 'tricky' and we're not doing
3963 * the correct thing -- also see task_dead_dl() and switched_from_dl().
3965 * What we SHOULD do is delay the bandwidth release until the 0-lag
3966 * point. This would include retaining the task_struct until that time
3967 * and change dl_overflow() to not immediately decrement the current
3970 * Instead we retain the current runtime/deadline and let the new
3971 * parameters take effect after the current reservation period lapses.
3972 * This is safe (albeit pessimistic) because the 0-lag point is always
3973 * before the current scheduling deadline.
3975 * We can still have temporary overloads because we do not delay the
3976 * change in bandwidth until that time; so admission control is
3977 * not on the safe side. It does however guarantee tasks will never
3978 * consume more than promised.
3983 * sched_setparam() passes in -1 for its policy, to let the functions
3984 * it calls know not to change it.
3986 #define SETPARAM_POLICY -1
3988 static void __setscheduler_params(struct task_struct *p,
3989 const struct sched_attr *attr)
3991 int policy = attr->sched_policy;
3993 if (policy == SETPARAM_POLICY)
3998 if (dl_policy(policy))
3999 __setparam_dl(p, attr);
4000 else if (fair_policy(policy))
4001 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4004 * __sched_setscheduler() ensures attr->sched_priority == 0 when
4005 * !rt_policy. Always setting this ensures that things like
4006 * getparam()/getattr() don't report silly values for !rt tasks.
4008 p->rt_priority = attr->sched_priority;
4009 p->normal_prio = normal_prio(p);
4013 /* Actually do priority change: must hold pi & rq lock. */
4014 static void __setscheduler(struct rq *rq, struct task_struct *p,
4015 const struct sched_attr *attr, bool keep_boost)
4017 __setscheduler_params(p, attr);
4020 * Keep a potential priority boosting if called from
4021 * sched_setscheduler().
4024 p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
4026 p->prio = normal_prio(p);
4028 if (dl_prio(p->prio))
4029 p->sched_class = &dl_sched_class;
4030 else if (rt_prio(p->prio))
4031 p->sched_class = &rt_sched_class;
4033 p->sched_class = &fair_sched_class;
4037 __getparam_dl(struct task_struct *p, struct sched_attr *attr)
4039 struct sched_dl_entity *dl_se = &p->dl;
4041 attr->sched_priority = p->rt_priority;
4042 attr->sched_runtime = dl_se->dl_runtime;
4043 attr->sched_deadline = dl_se->dl_deadline;
4044 attr->sched_period = dl_se->dl_period;
4045 attr->sched_flags = dl_se->flags;
4049 * This function validates the new parameters of a -deadline task.
4050 * We ask for the deadline not being zero, and greater or equal
4051 * than the runtime, as well as the period of being zero or
4052 * greater than deadline. Furthermore, we have to be sure that
4053 * user parameters are above the internal resolution of 1us (we
4054 * check sched_runtime only since it is always the smaller one) and
4055 * below 2^63 ns (we have to check both sched_deadline and
4056 * sched_period, as the latter can be zero).
4059 __checkparam_dl(const struct sched_attr *attr)
4062 if (attr->sched_deadline == 0)
4066 * Since we truncate DL_SCALE bits, make sure we're at least
4069 if (attr->sched_runtime < (1ULL << DL_SCALE))
4073 * Since we use the MSB for wrap-around and sign issues, make
4074 * sure it's not set (mind that period can be equal to zero).
4076 if (attr->sched_deadline & (1ULL << 63) ||
4077 attr->sched_period & (1ULL << 63))
4080 /* runtime <= deadline <= period (if period != 0) */
4081 if ((attr->sched_period != 0 &&
4082 attr->sched_period < attr->sched_deadline) ||
4083 attr->sched_deadline < attr->sched_runtime)
4090 * Check the target process has a UID that matches the current process's:
4092 static bool check_same_owner(struct task_struct *p)
4094 const struct cred *cred = current_cred(), *pcred;
4098 pcred = __task_cred(p);
4099 match = (uid_eq(cred->euid, pcred->euid) ||
4100 uid_eq(cred->euid, pcred->uid));
4105 static bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr)
4107 struct sched_dl_entity *dl_se = &p->dl;
4109 if (dl_se->dl_runtime != attr->sched_runtime ||
4110 dl_se->dl_deadline != attr->sched_deadline ||
4111 dl_se->dl_period != attr->sched_period ||
4112 dl_se->flags != attr->sched_flags)
4118 static int __sched_setscheduler(struct task_struct *p,
4119 const struct sched_attr *attr,
4122 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4123 MAX_RT_PRIO - 1 - attr->sched_priority;
4124 int retval, oldprio, oldpolicy = -1, queued, running;
4125 int new_effective_prio, policy = attr->sched_policy;
4126 const struct sched_class *prev_class;
4129 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
4132 /* May grab non-irq protected spin_locks: */
4133 BUG_ON(in_interrupt());
4135 /* Double check policy once rq lock held: */
4137 reset_on_fork = p->sched_reset_on_fork;
4138 policy = oldpolicy = p->policy;
4140 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4142 if (!valid_policy(policy))
4146 if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
4150 * Valid priorities for SCHED_FIFO and SCHED_RR are
4151 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4152 * SCHED_BATCH and SCHED_IDLE is 0.
4154 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4155 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4157 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4158 (rt_policy(policy) != (attr->sched_priority != 0)))
4162 * Allow unprivileged RT tasks to decrease priority:
4164 if (user && !capable(CAP_SYS_NICE)) {
4165 if (fair_policy(policy)) {
4166 if (attr->sched_nice < task_nice(p) &&
4167 !can_nice(p, attr->sched_nice))
4171 if (rt_policy(policy)) {
4172 unsigned long rlim_rtprio =
4173 task_rlimit(p, RLIMIT_RTPRIO);
4175 /* Can't set/change the rt policy: */
4176 if (policy != p->policy && !rlim_rtprio)
4179 /* Can't increase priority: */
4180 if (attr->sched_priority > p->rt_priority &&
4181 attr->sched_priority > rlim_rtprio)
4186 * Can't set/change SCHED_DEADLINE policy at all for now
4187 * (safest behavior); in the future we would like to allow
4188 * unprivileged DL tasks to increase their relative deadline
4189 * or reduce their runtime (both ways reducing utilization)
4191 if (dl_policy(policy))
4195 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4196 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4198 if (idle_policy(p->policy) && !idle_policy(policy)) {
4199 if (!can_nice(p, task_nice(p)))
4203 /* Can't change other user's priorities: */
4204 if (!check_same_owner(p))
4207 /* Normal users shall not reset the sched_reset_on_fork flag: */
4208 if (p->sched_reset_on_fork && !reset_on_fork)
4213 retval = security_task_setscheduler(p);
4219 * Make sure no PI-waiters arrive (or leave) while we are
4220 * changing the priority of the task:
4222 * To be able to change p->policy safely, the appropriate
4223 * runqueue lock must be held.
4225 rq = task_rq_lock(p, &rf);
4226 update_rq_clock(rq);
4229 * Changing the policy of the stop threads its a very bad idea:
4231 if (p == rq->stop) {
4232 task_rq_unlock(rq, p, &rf);
4237 * If not changing anything there's no need to proceed further,
4238 * but store a possible modification of reset_on_fork.
4240 if (unlikely(policy == p->policy)) {
4241 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4243 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4245 if (dl_policy(policy) && dl_param_changed(p, attr))
4248 p->sched_reset_on_fork = reset_on_fork;
4249 task_rq_unlock(rq, p, &rf);
4255 #ifdef CONFIG_RT_GROUP_SCHED
4257 * Do not allow realtime tasks into groups that have no runtime
4260 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4261 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4262 !task_group_is_autogroup(task_group(p))) {
4263 task_rq_unlock(rq, p, &rf);
4268 if (dl_bandwidth_enabled() && dl_policy(policy)) {
4269 cpumask_t *span = rq->rd->span;
4272 * Don't allow tasks with an affinity mask smaller than
4273 * the entire root_domain to become SCHED_DEADLINE. We
4274 * will also fail if there's no bandwidth available.
4276 if (!cpumask_subset(span, &p->cpus_allowed) ||
4277 rq->rd->dl_bw.bw == 0) {
4278 task_rq_unlock(rq, p, &rf);
4285 /* Re-check policy now with rq lock held: */
4286 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4287 policy = oldpolicy = -1;
4288 task_rq_unlock(rq, p, &rf);
4293 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4294 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4297 if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
4298 task_rq_unlock(rq, p, &rf);
4302 p->sched_reset_on_fork = reset_on_fork;
4307 * Take priority boosted tasks into account. If the new
4308 * effective priority is unchanged, we just store the new
4309 * normal parameters and do not touch the scheduler class and
4310 * the runqueue. This will be done when the task deboost
4313 new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
4314 if (new_effective_prio == oldprio)
4315 queue_flags &= ~DEQUEUE_MOVE;
4318 queued = task_on_rq_queued(p);
4319 running = task_current(rq, p);
4321 dequeue_task(rq, p, queue_flags);
4323 put_prev_task(rq, p);
4325 prev_class = p->sched_class;
4326 __setscheduler(rq, p, attr, pi);
4330 * We enqueue to tail when the priority of a task is
4331 * increased (user space view).
4333 if (oldprio < p->prio)
4334 queue_flags |= ENQUEUE_HEAD;
4336 enqueue_task(rq, p, queue_flags);
4339 set_curr_task(rq, p);
4341 check_class_changed(rq, p, prev_class, oldprio);
4343 /* Avoid rq from going away on us: */
4345 task_rq_unlock(rq, p, &rf);
4348 rt_mutex_adjust_pi(p);
4350 /* Run balance callbacks after we've adjusted the PI chain: */
4351 balance_callback(rq);
4357 static int _sched_setscheduler(struct task_struct *p, int policy,
4358 const struct sched_param *param, bool check)
4360 struct sched_attr attr = {
4361 .sched_policy = policy,
4362 .sched_priority = param->sched_priority,
4363 .sched_nice = PRIO_TO_NICE(p->static_prio),
4366 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4367 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4368 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4369 policy &= ~SCHED_RESET_ON_FORK;
4370 attr.sched_policy = policy;
4373 return __sched_setscheduler(p, &attr, check, true);
4376 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4377 * @p: the task in question.
4378 * @policy: new policy.
4379 * @param: structure containing the new RT priority.
4381 * Return: 0 on success. An error code otherwise.
4383 * NOTE that the task may be already dead.
4385 int sched_setscheduler(struct task_struct *p, int policy,
4386 const struct sched_param *param)
4388 return _sched_setscheduler(p, policy, param, true);
4390 EXPORT_SYMBOL_GPL(sched_setscheduler);
4392 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4394 return __sched_setscheduler(p, attr, true, true);
4396 EXPORT_SYMBOL_GPL(sched_setattr);
4399 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4400 * @p: the task in question.
4401 * @policy: new policy.
4402 * @param: structure containing the new RT priority.
4404 * Just like sched_setscheduler, only don't bother checking if the
4405 * current context has permission. For example, this is needed in
4406 * stop_machine(): we create temporary high priority worker threads,
4407 * but our caller might not have that capability.
4409 * Return: 0 on success. An error code otherwise.
4411 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4412 const struct sched_param *param)
4414 return _sched_setscheduler(p, policy, param, false);
4416 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4419 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4421 struct sched_param lparam;
4422 struct task_struct *p;
4425 if (!param || pid < 0)
4427 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4432 p = find_process_by_pid(pid);
4434 retval = sched_setscheduler(p, policy, &lparam);
4441 * Mimics kernel/events/core.c perf_copy_attr().
4443 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
4448 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4451 /* Zero the full structure, so that a short copy will be nice: */
4452 memset(attr, 0, sizeof(*attr));
4454 ret = get_user(size, &uattr->size);
4458 /* Bail out on silly large: */
4459 if (size > PAGE_SIZE)
4462 /* ABI compatibility quirk: */
4464 size = SCHED_ATTR_SIZE_VER0;
4466 if (size < SCHED_ATTR_SIZE_VER0)
4470 * If we're handed a bigger struct than we know of,
4471 * ensure all the unknown bits are 0 - i.e. new
4472 * user-space does not rely on any kernel feature
4473 * extensions we dont know about yet.
4475 if (size > sizeof(*attr)) {
4476 unsigned char __user *addr;
4477 unsigned char __user *end;
4480 addr = (void __user *)uattr + sizeof(*attr);
4481 end = (void __user *)uattr + size;
4483 for (; addr < end; addr++) {
4484 ret = get_user(val, addr);
4490 size = sizeof(*attr);
4493 ret = copy_from_user(attr, uattr, size);
4498 * XXX: Do we want to be lenient like existing syscalls; or do we want
4499 * to be strict and return an error on out-of-bounds values?
4501 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4506 put_user(sizeof(*attr), &uattr->size);
4511 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4512 * @pid: the pid in question.
4513 * @policy: new policy.
4514 * @param: structure containing the new RT priority.
4516 * Return: 0 on success. An error code otherwise.
4518 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
4523 return do_sched_setscheduler(pid, policy, param);
4527 * sys_sched_setparam - set/change the RT priority of a thread
4528 * @pid: the pid in question.
4529 * @param: structure containing the new RT priority.
4531 * Return: 0 on success. An error code otherwise.
4533 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4535 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4539 * sys_sched_setattr - same as above, but with extended sched_attr
4540 * @pid: the pid in question.
4541 * @uattr: structure containing the extended parameters.
4542 * @flags: for future extension.
4544 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4545 unsigned int, flags)
4547 struct sched_attr attr;
4548 struct task_struct *p;
4551 if (!uattr || pid < 0 || flags)
4554 retval = sched_copy_attr(uattr, &attr);
4558 if ((int)attr.sched_policy < 0)
4563 p = find_process_by_pid(pid);
4565 retval = sched_setattr(p, &attr);
4572 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4573 * @pid: the pid in question.
4575 * Return: On success, the policy of the thread. Otherwise, a negative error
4578 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4580 struct task_struct *p;
4588 p = find_process_by_pid(pid);
4590 retval = security_task_getscheduler(p);
4593 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4600 * sys_sched_getparam - get the RT priority of a thread
4601 * @pid: the pid in question.
4602 * @param: structure containing the RT priority.
4604 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4607 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4609 struct sched_param lp = { .sched_priority = 0 };
4610 struct task_struct *p;
4613 if (!param || pid < 0)
4617 p = find_process_by_pid(pid);
4622 retval = security_task_getscheduler(p);
4626 if (task_has_rt_policy(p))
4627 lp.sched_priority = p->rt_priority;
4631 * This one might sleep, we cannot do it with a spinlock held ...
4633 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4642 static int sched_read_attr(struct sched_attr __user *uattr,
4643 struct sched_attr *attr,
4648 if (!access_ok(VERIFY_WRITE, uattr, usize))
4652 * If we're handed a smaller struct than we know of,
4653 * ensure all the unknown bits are 0 - i.e. old
4654 * user-space does not get uncomplete information.
4656 if (usize < sizeof(*attr)) {
4657 unsigned char *addr;
4660 addr = (void *)attr + usize;
4661 end = (void *)attr + sizeof(*attr);
4663 for (; addr < end; addr++) {
4671 ret = copy_to_user(uattr, attr, attr->size);
4679 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4680 * @pid: the pid in question.
4681 * @uattr: structure containing the extended parameters.
4682 * @size: sizeof(attr) for fwd/bwd comp.
4683 * @flags: for future extension.
4685 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4686 unsigned int, size, unsigned int, flags)
4688 struct sched_attr attr = {
4689 .size = sizeof(struct sched_attr),
4691 struct task_struct *p;
4694 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4695 size < SCHED_ATTR_SIZE_VER0 || flags)
4699 p = find_process_by_pid(pid);
4704 retval = security_task_getscheduler(p);
4708 attr.sched_policy = p->policy;
4709 if (p->sched_reset_on_fork)
4710 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4711 if (task_has_dl_policy(p))
4712 __getparam_dl(p, &attr);
4713 else if (task_has_rt_policy(p))
4714 attr.sched_priority = p->rt_priority;
4716 attr.sched_nice = task_nice(p);
4720 retval = sched_read_attr(uattr, &attr, size);
4728 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4730 cpumask_var_t cpus_allowed, new_mask;
4731 struct task_struct *p;
4736 p = find_process_by_pid(pid);
4742 /* Prevent p going away */
4746 if (p->flags & PF_NO_SETAFFINITY) {
4750 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4754 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4756 goto out_free_cpus_allowed;
4759 if (!check_same_owner(p)) {
4761 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4763 goto out_free_new_mask;
4768 retval = security_task_setscheduler(p);
4770 goto out_free_new_mask;
4773 cpuset_cpus_allowed(p, cpus_allowed);
4774 cpumask_and(new_mask, in_mask, cpus_allowed);
4777 * Since bandwidth control happens on root_domain basis,
4778 * if admission test is enabled, we only admit -deadline
4779 * tasks allowed to run on all the CPUs in the task's
4783 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4785 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4788 goto out_free_new_mask;
4794 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4797 cpuset_cpus_allowed(p, cpus_allowed);
4798 if (!cpumask_subset(new_mask, cpus_allowed)) {
4800 * We must have raced with a concurrent cpuset
4801 * update. Just reset the cpus_allowed to the
4802 * cpuset's cpus_allowed
4804 cpumask_copy(new_mask, cpus_allowed);
4809 free_cpumask_var(new_mask);
4810 out_free_cpus_allowed:
4811 free_cpumask_var(cpus_allowed);
4817 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4818 struct cpumask *new_mask)
4820 if (len < cpumask_size())
4821 cpumask_clear(new_mask);
4822 else if (len > cpumask_size())
4823 len = cpumask_size();
4825 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4829 * sys_sched_setaffinity - set the CPU affinity of a process
4830 * @pid: pid of the process
4831 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4832 * @user_mask_ptr: user-space pointer to the new CPU mask
4834 * Return: 0 on success. An error code otherwise.
4836 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4837 unsigned long __user *, user_mask_ptr)
4839 cpumask_var_t new_mask;
4842 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4845 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4847 retval = sched_setaffinity(pid, new_mask);
4848 free_cpumask_var(new_mask);
4852 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4854 struct task_struct *p;
4855 unsigned long flags;
4861 p = find_process_by_pid(pid);
4865 retval = security_task_getscheduler(p);
4869 raw_spin_lock_irqsave(&p->pi_lock, flags);
4870 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4871 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4880 * sys_sched_getaffinity - get the CPU affinity of a process
4881 * @pid: pid of the process
4882 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4883 * @user_mask_ptr: user-space pointer to hold the current CPU mask
4885 * Return: size of CPU mask copied to user_mask_ptr on success. An
4886 * error code otherwise.
4888 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4889 unsigned long __user *, user_mask_ptr)
4894 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4896 if (len & (sizeof(unsigned long)-1))
4899 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4902 ret = sched_getaffinity(pid, mask);
4904 size_t retlen = min_t(size_t, len, cpumask_size());
4906 if (copy_to_user(user_mask_ptr, mask, retlen))
4911 free_cpumask_var(mask);
4917 * sys_sched_yield - yield the current processor to other threads.
4919 * This function yields the current CPU to other tasks. If there are no
4920 * other threads running on this CPU then this function will return.
4924 SYSCALL_DEFINE0(sched_yield)
4926 struct rq *rq = this_rq_lock();
4928 schedstat_inc(rq->yld_count);
4929 current->sched_class->yield_task(rq);
4932 * Since we are going to call schedule() anyway, there's
4933 * no need to preempt or enable interrupts:
4935 __release(rq->lock);
4936 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4937 do_raw_spin_unlock(&rq->lock);
4938 sched_preempt_enable_no_resched();
4945 #ifndef CONFIG_PREEMPT
4946 int __sched _cond_resched(void)
4948 if (should_resched(0)) {
4949 preempt_schedule_common();
4954 EXPORT_SYMBOL(_cond_resched);
4958 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4959 * call schedule, and on return reacquire the lock.
4961 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4962 * operations here to prevent schedule() from being called twice (once via
4963 * spin_unlock(), once by hand).
4965 int __cond_resched_lock(spinlock_t *lock)
4967 int resched = should_resched(PREEMPT_LOCK_OFFSET);
4970 lockdep_assert_held(lock);
4972 if (spin_needbreak(lock) || resched) {
4975 preempt_schedule_common();
4983 EXPORT_SYMBOL(__cond_resched_lock);
4985 int __sched __cond_resched_softirq(void)
4987 BUG_ON(!in_softirq());
4989 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
4991 preempt_schedule_common();
4997 EXPORT_SYMBOL(__cond_resched_softirq);
5000 * yield - yield the current processor to other threads.
5002 * Do not ever use this function, there's a 99% chance you're doing it wrong.
5004 * The scheduler is at all times free to pick the calling task as the most
5005 * eligible task to run, if removing the yield() call from your code breaks
5006 * it, its already broken.
5008 * Typical broken usage is:
5013 * where one assumes that yield() will let 'the other' process run that will
5014 * make event true. If the current task is a SCHED_FIFO task that will never
5015 * happen. Never use yield() as a progress guarantee!!
5017 * If you want to use yield() to wait for something, use wait_event().
5018 * If you want to use yield() to be 'nice' for others, use cond_resched().
5019 * If you still want to use yield(), do not!
5021 void __sched yield(void)
5023 set_current_state(TASK_RUNNING);
5026 EXPORT_SYMBOL(yield);
5029 * yield_to - yield the current processor to another thread in
5030 * your thread group, or accelerate that thread toward the
5031 * processor it's on.
5033 * @preempt: whether task preemption is allowed or not
5035 * It's the caller's job to ensure that the target task struct
5036 * can't go away on us before we can do any checks.
5039 * true (>0) if we indeed boosted the target task.
5040 * false (0) if we failed to boost the target.
5041 * -ESRCH if there's no task to yield to.
5043 int __sched yield_to(struct task_struct *p, bool preempt)
5045 struct task_struct *curr = current;
5046 struct rq *rq, *p_rq;
5047 unsigned long flags;
5050 local_irq_save(flags);
5056 * If we're the only runnable task on the rq and target rq also
5057 * has only one task, there's absolutely no point in yielding.
5059 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5064 double_rq_lock(rq, p_rq);
5065 if (task_rq(p) != p_rq) {
5066 double_rq_unlock(rq, p_rq);
5070 if (!curr->sched_class->yield_to_task)
5073 if (curr->sched_class != p->sched_class)
5076 if (task_running(p_rq, p) || p->state)
5079 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5081 schedstat_inc(rq->yld_count);
5083 * Make p's CPU reschedule; pick_next_entity takes care of
5086 if (preempt && rq != p_rq)
5091 double_rq_unlock(rq, p_rq);
5093 local_irq_restore(flags);
5100 EXPORT_SYMBOL_GPL(yield_to);
5102 int io_schedule_prepare(void)
5104 int old_iowait = current->in_iowait;
5106 current->in_iowait = 1;
5107 blk_schedule_flush_plug(current);
5112 void io_schedule_finish(int token)
5114 current->in_iowait = token;
5118 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5119 * that process accounting knows that this is a task in IO wait state.
5121 long __sched io_schedule_timeout(long timeout)
5126 token = io_schedule_prepare();
5127 ret = schedule_timeout(timeout);
5128 io_schedule_finish(token);
5132 EXPORT_SYMBOL(io_schedule_timeout);
5134 void io_schedule(void)
5138 token = io_schedule_prepare();
5140 io_schedule_finish(token);
5142 EXPORT_SYMBOL(io_schedule);
5145 * sys_sched_get_priority_max - return maximum RT priority.
5146 * @policy: scheduling class.
5148 * Return: On success, this syscall returns the maximum
5149 * rt_priority that can be used by a given scheduling class.
5150 * On failure, a negative error code is returned.
5152 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5159 ret = MAX_USER_RT_PRIO-1;
5161 case SCHED_DEADLINE:
5172 * sys_sched_get_priority_min - return minimum RT priority.
5173 * @policy: scheduling class.
5175 * Return: On success, this syscall returns the minimum
5176 * rt_priority that can be used by a given scheduling class.
5177 * On failure, a negative error code is returned.
5179 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5188 case SCHED_DEADLINE:
5198 * sys_sched_rr_get_interval - return the default timeslice of a process.
5199 * @pid: pid of the process.
5200 * @interval: userspace pointer to the timeslice value.
5202 * this syscall writes the default timeslice value of a given process
5203 * into the user-space timespec buffer. A value of '0' means infinity.
5205 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5208 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5209 struct timespec __user *, interval)
5211 struct task_struct *p;
5212 unsigned int time_slice;
5223 p = find_process_by_pid(pid);
5227 retval = security_task_getscheduler(p);
5231 rq = task_rq_lock(p, &rf);
5233 if (p->sched_class->get_rr_interval)
5234 time_slice = p->sched_class->get_rr_interval(rq, p);
5235 task_rq_unlock(rq, p, &rf);
5238 jiffies_to_timespec(time_slice, &t);
5239 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5247 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5249 void sched_show_task(struct task_struct *p)
5251 unsigned long free = 0;
5253 unsigned long state = p->state;
5255 /* Make sure the string lines up properly with the number of task states: */
5256 BUILD_BUG_ON(sizeof(TASK_STATE_TO_CHAR_STR)-1 != ilog2(TASK_STATE_MAX)+1);
5258 if (!try_get_task_stack(p))
5261 state = __ffs(state) + 1;
5262 printk(KERN_INFO "%-15.15s %c", p->comm,
5263 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5264 if (state == TASK_RUNNING)
5265 printk(KERN_CONT " running task ");
5266 #ifdef CONFIG_DEBUG_STACK_USAGE
5267 free = stack_not_used(p);
5272 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5274 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5275 task_pid_nr(p), ppid,
5276 (unsigned long)task_thread_info(p)->flags);
5278 print_worker_info(KERN_INFO, p);
5279 show_stack(p, NULL);
5283 void show_state_filter(unsigned long state_filter)
5285 struct task_struct *g, *p;
5287 #if BITS_PER_LONG == 32
5289 " task PC stack pid father\n");
5292 " task PC stack pid father\n");
5295 for_each_process_thread(g, p) {
5297 * reset the NMI-timeout, listing all files on a slow
5298 * console might take a lot of time:
5299 * Also, reset softlockup watchdogs on all CPUs, because
5300 * another CPU might be blocked waiting for us to process
5303 touch_nmi_watchdog();
5304 touch_all_softlockup_watchdogs();
5305 if (!state_filter || (p->state & state_filter))
5309 #ifdef CONFIG_SCHED_DEBUG
5311 sysrq_sched_debug_show();
5315 * Only show locks if all tasks are dumped:
5318 debug_show_all_locks();
5321 void init_idle_bootup_task(struct task_struct *idle)
5323 idle->sched_class = &idle_sched_class;
5327 * init_idle - set up an idle thread for a given CPU
5328 * @idle: task in question
5329 * @cpu: CPU the idle task belongs to
5331 * NOTE: this function does not set the idle thread's NEED_RESCHED
5332 * flag, to make booting more robust.
5334 void init_idle(struct task_struct *idle, int cpu)
5336 struct rq *rq = cpu_rq(cpu);
5337 unsigned long flags;
5339 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5340 raw_spin_lock(&rq->lock);
5342 __sched_fork(0, idle);
5343 idle->state = TASK_RUNNING;
5344 idle->se.exec_start = sched_clock();
5345 idle->flags |= PF_IDLE;
5347 kasan_unpoison_task_stack(idle);
5351 * Its possible that init_idle() gets called multiple times on a task,
5352 * in that case do_set_cpus_allowed() will not do the right thing.
5354 * And since this is boot we can forgo the serialization.
5356 set_cpus_allowed_common(idle, cpumask_of(cpu));
5359 * We're having a chicken and egg problem, even though we are
5360 * holding rq->lock, the CPU isn't yet set to this CPU so the
5361 * lockdep check in task_group() will fail.
5363 * Similar case to sched_fork(). / Alternatively we could
5364 * use task_rq_lock() here and obtain the other rq->lock.
5369 __set_task_cpu(idle, cpu);
5372 rq->curr = rq->idle = idle;
5373 idle->on_rq = TASK_ON_RQ_QUEUED;
5377 raw_spin_unlock(&rq->lock);
5378 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5380 /* Set the preempt count _outside_ the spinlocks! */
5381 init_idle_preempt_count(idle, cpu);
5384 * The idle tasks have their own, simple scheduling class:
5386 idle->sched_class = &idle_sched_class;
5387 ftrace_graph_init_idle_task(idle, cpu);
5388 vtime_init_idle(idle, cpu);
5390 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5394 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5395 const struct cpumask *trial)
5397 int ret = 1, trial_cpus;
5398 struct dl_bw *cur_dl_b;
5399 unsigned long flags;
5401 if (!cpumask_weight(cur))
5404 rcu_read_lock_sched();
5405 cur_dl_b = dl_bw_of(cpumask_any(cur));
5406 trial_cpus = cpumask_weight(trial);
5408 raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
5409 if (cur_dl_b->bw != -1 &&
5410 cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
5412 raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
5413 rcu_read_unlock_sched();
5418 int task_can_attach(struct task_struct *p,
5419 const struct cpumask *cs_cpus_allowed)
5424 * Kthreads which disallow setaffinity shouldn't be moved
5425 * to a new cpuset; we don't want to change their CPU
5426 * affinity and isolating such threads by their set of
5427 * allowed nodes is unnecessary. Thus, cpusets are not
5428 * applicable for such threads. This prevents checking for
5429 * success of set_cpus_allowed_ptr() on all attached tasks
5430 * before cpus_allowed may be changed.
5432 if (p->flags & PF_NO_SETAFFINITY) {
5438 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5440 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
5445 unsigned long flags;
5447 rcu_read_lock_sched();
5448 dl_b = dl_bw_of(dest_cpu);
5449 raw_spin_lock_irqsave(&dl_b->lock, flags);
5450 cpus = dl_bw_cpus(dest_cpu);
5451 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
5456 * We reserve space for this task in the destination
5457 * root_domain, as we can't fail after this point.
5458 * We will free resources in the source root_domain
5459 * later on (see set_cpus_allowed_dl()).
5461 __dl_add(dl_b, p->dl.dl_bw);
5463 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5464 rcu_read_unlock_sched();
5474 bool sched_smp_initialized __read_mostly;
5476 #ifdef CONFIG_NUMA_BALANCING
5477 /* Migrate current task p to target_cpu */
5478 int migrate_task_to(struct task_struct *p, int target_cpu)
5480 struct migration_arg arg = { p, target_cpu };
5481 int curr_cpu = task_cpu(p);
5483 if (curr_cpu == target_cpu)
5486 if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
5489 /* TODO: This is not properly updating schedstats */
5491 trace_sched_move_numa(p, curr_cpu, target_cpu);
5492 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5496 * Requeue a task on a given node and accurately track the number of NUMA
5497 * tasks on the runqueues
5499 void sched_setnuma(struct task_struct *p, int nid)
5501 bool queued, running;
5505 rq = task_rq_lock(p, &rf);
5506 queued = task_on_rq_queued(p);
5507 running = task_current(rq, p);
5510 dequeue_task(rq, p, DEQUEUE_SAVE);
5512 put_prev_task(rq, p);
5514 p->numa_preferred_nid = nid;
5517 enqueue_task(rq, p, ENQUEUE_RESTORE);
5519 set_curr_task(rq, p);
5520 task_rq_unlock(rq, p, &rf);
5522 #endif /* CONFIG_NUMA_BALANCING */
5524 #ifdef CONFIG_HOTPLUG_CPU
5526 * Ensure that the idle task is using init_mm right before its CPU goes
5529 void idle_task_exit(void)
5531 struct mm_struct *mm = current->active_mm;
5533 BUG_ON(cpu_online(smp_processor_id()));
5535 if (mm != &init_mm) {
5536 switch_mm_irqs_off(mm, &init_mm, current);
5537 finish_arch_post_lock_switch();
5543 * Since this CPU is going 'away' for a while, fold any nr_active delta
5544 * we might have. Assumes we're called after migrate_tasks() so that the
5545 * nr_active count is stable. We need to take the teardown thread which
5546 * is calling this into account, so we hand in adjust = 1 to the load
5549 * Also see the comment "Global load-average calculations".
5551 static void calc_load_migrate(struct rq *rq)
5553 long delta = calc_load_fold_active(rq, 1);
5555 atomic_long_add(delta, &calc_load_tasks);
5558 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5562 static const struct sched_class fake_sched_class = {
5563 .put_prev_task = put_prev_task_fake,
5566 static struct task_struct fake_task = {
5568 * Avoid pull_{rt,dl}_task()
5570 .prio = MAX_PRIO + 1,
5571 .sched_class = &fake_sched_class,
5575 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5576 * try_to_wake_up()->select_task_rq().
5578 * Called with rq->lock held even though we'er in stop_machine() and
5579 * there's no concurrency possible, we hold the required locks anyway
5580 * because of lock validation efforts.
5582 static void migrate_tasks(struct rq *dead_rq)
5584 struct rq *rq = dead_rq;
5585 struct task_struct *next, *stop = rq->stop;
5590 * Fudge the rq selection such that the below task selection loop
5591 * doesn't get stuck on the currently eligible stop task.
5593 * We're currently inside stop_machine() and the rq is either stuck
5594 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5595 * either way we should never end up calling schedule() until we're
5601 * put_prev_task() and pick_next_task() sched
5602 * class method both need to have an up-to-date
5603 * value of rq->clock[_task]
5605 rq_pin_lock(rq, &rf);
5606 update_rq_clock(rq);
5607 rq_unpin_lock(rq, &rf);
5611 * There's this thread running, bail when that's the only
5614 if (rq->nr_running == 1)
5618 * pick_next_task() assumes pinned rq->lock:
5620 rq_repin_lock(rq, &rf);
5621 next = pick_next_task(rq, &fake_task, &rf);
5623 next->sched_class->put_prev_task(rq, next);
5626 * Rules for changing task_struct::cpus_allowed are holding
5627 * both pi_lock and rq->lock, such that holding either
5628 * stabilizes the mask.
5630 * Drop rq->lock is not quite as disastrous as it usually is
5631 * because !cpu_active at this point, which means load-balance
5632 * will not interfere. Also, stop-machine.
5634 rq_unpin_lock(rq, &rf);
5635 raw_spin_unlock(&rq->lock);
5636 raw_spin_lock(&next->pi_lock);
5637 raw_spin_lock(&rq->lock);
5640 * Since we're inside stop-machine, _nothing_ should have
5641 * changed the task, WARN if weird stuff happened, because in
5642 * that case the above rq->lock drop is a fail too.
5644 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5645 raw_spin_unlock(&next->pi_lock);
5649 /* Find suitable destination for @next, with force if needed. */
5650 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5652 rq = __migrate_task(rq, next, dest_cpu);
5653 if (rq != dead_rq) {
5654 raw_spin_unlock(&rq->lock);
5656 raw_spin_lock(&rq->lock);
5658 raw_spin_unlock(&next->pi_lock);
5663 #endif /* CONFIG_HOTPLUG_CPU */
5665 void set_rq_online(struct rq *rq)
5668 const struct sched_class *class;
5670 cpumask_set_cpu(rq->cpu, rq->rd->online);
5673 for_each_class(class) {
5674 if (class->rq_online)
5675 class->rq_online(rq);
5680 void set_rq_offline(struct rq *rq)
5683 const struct sched_class *class;
5685 for_each_class(class) {
5686 if (class->rq_offline)
5687 class->rq_offline(rq);
5690 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5695 static void set_cpu_rq_start_time(unsigned int cpu)
5697 struct rq *rq = cpu_rq(cpu);
5699 rq->age_stamp = sched_clock_cpu(cpu);
5703 * used to mark begin/end of suspend/resume:
5705 static int num_cpus_frozen;
5708 * Update cpusets according to cpu_active mask. If cpusets are
5709 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5710 * around partition_sched_domains().
5712 * If we come here as part of a suspend/resume, don't touch cpusets because we
5713 * want to restore it back to its original state upon resume anyway.
5715 static void cpuset_cpu_active(void)
5717 if (cpuhp_tasks_frozen) {
5719 * num_cpus_frozen tracks how many CPUs are involved in suspend
5720 * resume sequence. As long as this is not the last online
5721 * operation in the resume sequence, just build a single sched
5722 * domain, ignoring cpusets.
5725 if (likely(num_cpus_frozen)) {
5726 partition_sched_domains(1, NULL, NULL);
5730 * This is the last CPU online operation. So fall through and
5731 * restore the original sched domains by considering the
5732 * cpuset configurations.
5735 cpuset_update_active_cpus(true);
5738 static int cpuset_cpu_inactive(unsigned int cpu)
5740 unsigned long flags;
5745 if (!cpuhp_tasks_frozen) {
5746 rcu_read_lock_sched();
5747 dl_b = dl_bw_of(cpu);
5749 raw_spin_lock_irqsave(&dl_b->lock, flags);
5750 cpus = dl_bw_cpus(cpu);
5751 overflow = __dl_overflow(dl_b, cpus, 0, 0);
5752 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5754 rcu_read_unlock_sched();
5758 cpuset_update_active_cpus(false);
5761 partition_sched_domains(1, NULL, NULL);
5766 int sched_cpu_activate(unsigned int cpu)
5768 struct rq *rq = cpu_rq(cpu);
5769 unsigned long flags;
5771 set_cpu_active(cpu, true);
5773 if (sched_smp_initialized) {
5774 sched_domains_numa_masks_set(cpu);
5775 cpuset_cpu_active();
5779 * Put the rq online, if not already. This happens:
5781 * 1) In the early boot process, because we build the real domains
5782 * after all CPUs have been brought up.
5784 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5787 raw_spin_lock_irqsave(&rq->lock, flags);
5789 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5792 raw_spin_unlock_irqrestore(&rq->lock, flags);
5794 update_max_interval();
5799 int sched_cpu_deactivate(unsigned int cpu)
5803 set_cpu_active(cpu, false);
5805 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5806 * users of this state to go away such that all new such users will
5809 * For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
5810 * not imply sync_sched(), so wait for both.
5812 * Do sync before park smpboot threads to take care the rcu boost case.
5814 if (IS_ENABLED(CONFIG_PREEMPT))
5815 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);
5846 #ifdef CONFIG_HOTPLUG_CPU
5847 int sched_cpu_dying(unsigned int cpu)
5849 struct rq *rq = cpu_rq(cpu);
5850 unsigned long flags;
5852 /* Handle pending wakeups and then migrate everything off */
5853 sched_ttwu_pending();
5854 raw_spin_lock_irqsave(&rq->lock, flags);
5856 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5860 BUG_ON(rq->nr_running != 1);
5861 raw_spin_unlock_irqrestore(&rq->lock, flags);
5862 calc_load_migrate(rq);
5863 update_max_interval();
5864 nohz_balance_exit_idle(cpu);
5870 #ifdef CONFIG_SCHED_SMT
5871 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
5873 static void sched_init_smt(void)
5876 * We've enumerated all CPUs and will assume that if any CPU
5877 * has SMT siblings, CPU0 will too.
5879 if (cpumask_weight(cpu_smt_mask(0)) > 1)
5880 static_branch_enable(&sched_smt_present);
5883 static inline void sched_init_smt(void) { }
5886 void __init sched_init_smp(void)
5888 cpumask_var_t non_isolated_cpus;
5890 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
5891 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
5896 * There's no userspace yet to cause hotplug operations; hence all the
5897 * CPU masks are stable and all blatant races in the below code cannot
5900 mutex_lock(&sched_domains_mutex);
5901 init_sched_domains(cpu_active_mask);
5902 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
5903 if (cpumask_empty(non_isolated_cpus))
5904 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
5905 mutex_unlock(&sched_domains_mutex);
5907 /* Move init over to a non-isolated CPU */
5908 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
5910 sched_init_granularity();
5911 free_cpumask_var(non_isolated_cpus);
5913 init_sched_rt_class();
5914 init_sched_dl_class();
5917 sched_clock_init_late();
5919 sched_smp_initialized = true;
5922 static int __init migration_init(void)
5924 sched_rq_cpu_starting(smp_processor_id());
5927 early_initcall(migration_init);
5930 void __init sched_init_smp(void)
5932 sched_init_granularity();
5933 sched_clock_init_late();
5935 #endif /* CONFIG_SMP */
5937 int in_sched_functions(unsigned long addr)
5939 return in_lock_functions(addr) ||
5940 (addr >= (unsigned long)__sched_text_start
5941 && addr < (unsigned long)__sched_text_end);
5944 #ifdef CONFIG_CGROUP_SCHED
5946 * Default task group.
5947 * Every task in system belongs to this group at bootup.
5949 struct task_group root_task_group;
5950 LIST_HEAD(task_groups);
5952 /* Cacheline aligned slab cache for task_group */
5953 static struct kmem_cache *task_group_cache __read_mostly;
5956 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
5957 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
5959 #define WAIT_TABLE_BITS 8
5960 #define WAIT_TABLE_SIZE (1 << WAIT_TABLE_BITS)
5961 static wait_queue_head_t bit_wait_table[WAIT_TABLE_SIZE] __cacheline_aligned;
5963 wait_queue_head_t *bit_waitqueue(void *word, int bit)
5965 const int shift = BITS_PER_LONG == 32 ? 5 : 6;
5966 unsigned long val = (unsigned long)word << shift | bit;
5968 return bit_wait_table + hash_long(val, WAIT_TABLE_BITS);
5970 EXPORT_SYMBOL(bit_waitqueue);
5972 void __init sched_init(void)
5975 unsigned long alloc_size = 0, ptr;
5979 for (i = 0; i < WAIT_TABLE_SIZE; i++)
5980 init_waitqueue_head(bit_wait_table + i);
5982 #ifdef CONFIG_FAIR_GROUP_SCHED
5983 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5985 #ifdef CONFIG_RT_GROUP_SCHED
5986 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5989 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
5991 #ifdef CONFIG_FAIR_GROUP_SCHED
5992 root_task_group.se = (struct sched_entity **)ptr;
5993 ptr += nr_cpu_ids * sizeof(void **);
5995 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
5996 ptr += nr_cpu_ids * sizeof(void **);
5998 #endif /* CONFIG_FAIR_GROUP_SCHED */
5999 #ifdef CONFIG_RT_GROUP_SCHED
6000 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
6001 ptr += nr_cpu_ids * sizeof(void **);
6003 root_task_group.rt_rq = (struct rt_rq **)ptr;
6004 ptr += nr_cpu_ids * sizeof(void **);
6006 #endif /* CONFIG_RT_GROUP_SCHED */
6008 #ifdef CONFIG_CPUMASK_OFFSTACK
6009 for_each_possible_cpu(i) {
6010 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
6011 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
6012 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
6013 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
6015 #endif /* CONFIG_CPUMASK_OFFSTACK */
6017 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
6018 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
6021 init_defrootdomain();
6024 #ifdef CONFIG_RT_GROUP_SCHED
6025 init_rt_bandwidth(&root_task_group.rt_bandwidth,
6026 global_rt_period(), global_rt_runtime());
6027 #endif /* CONFIG_RT_GROUP_SCHED */
6029 #ifdef CONFIG_CGROUP_SCHED
6030 task_group_cache = KMEM_CACHE(task_group, 0);
6032 list_add(&root_task_group.list, &task_groups);
6033 INIT_LIST_HEAD(&root_task_group.children);
6034 INIT_LIST_HEAD(&root_task_group.siblings);
6035 autogroup_init(&init_task);
6036 #endif /* CONFIG_CGROUP_SCHED */
6038 for_each_possible_cpu(i) {
6042 raw_spin_lock_init(&rq->lock);
6044 rq->calc_load_active = 0;
6045 rq->calc_load_update = jiffies + LOAD_FREQ;
6046 init_cfs_rq(&rq->cfs);
6047 init_rt_rq(&rq->rt);
6048 init_dl_rq(&rq->dl);
6049 #ifdef CONFIG_FAIR_GROUP_SCHED
6050 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6051 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6052 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
6054 * How much CPU bandwidth does root_task_group get?
6056 * In case of task-groups formed thr' the cgroup filesystem, it
6057 * gets 100% of the CPU resources in the system. This overall
6058 * system CPU resource is divided among the tasks of
6059 * root_task_group and its child task-groups in a fair manner,
6060 * based on each entity's (task or task-group's) weight
6061 * (se->load.weight).
6063 * In other words, if root_task_group has 10 tasks of weight
6064 * 1024) and two child groups A0 and A1 (of weight 1024 each),
6065 * then A0's share of the CPU resource is:
6067 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
6069 * We achieve this by letting root_task_group's tasks sit
6070 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
6072 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
6073 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
6074 #endif /* CONFIG_FAIR_GROUP_SCHED */
6076 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
6077 #ifdef CONFIG_RT_GROUP_SCHED
6078 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
6081 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6082 rq->cpu_load[j] = 0;
6087 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
6088 rq->balance_callback = NULL;
6089 rq->active_balance = 0;
6090 rq->next_balance = jiffies;
6095 rq->avg_idle = 2*sysctl_sched_migration_cost;
6096 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
6098 INIT_LIST_HEAD(&rq->cfs_tasks);
6100 rq_attach_root(rq, &def_root_domain);
6101 #ifdef CONFIG_NO_HZ_COMMON
6102 rq->last_load_update_tick = jiffies;
6105 #ifdef CONFIG_NO_HZ_FULL
6106 rq->last_sched_tick = 0;
6108 #endif /* CONFIG_SMP */
6110 atomic_set(&rq->nr_iowait, 0);
6113 set_load_weight(&init_task);
6116 * The boot idle thread does lazy MMU switching as well:
6119 enter_lazy_tlb(&init_mm, current);
6122 * Make us the idle thread. Technically, schedule() should not be
6123 * called from this thread, however somewhere below it might be,
6124 * but because we are the idle thread, we just pick up running again
6125 * when this runqueue becomes "idle".
6127 init_idle(current, smp_processor_id());
6129 calc_load_update = jiffies + LOAD_FREQ;
6132 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
6133 /* May be allocated at isolcpus cmdline parse time */
6134 if (cpu_isolated_map == NULL)
6135 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
6136 idle_thread_set_boot_cpu();
6137 set_cpu_rq_start_time(smp_processor_id());
6139 init_sched_fair_class();
6143 scheduler_running = 1;
6146 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
6147 static inline int preempt_count_equals(int preempt_offset)
6149 int nested = preempt_count() + rcu_preempt_depth();
6151 return (nested == preempt_offset);
6154 void __might_sleep(const char *file, int line, int preempt_offset)
6157 * Blocking primitives will set (and therefore destroy) current->state,
6158 * since we will exit with TASK_RUNNING make sure we enter with it,
6159 * otherwise we will destroy state.
6161 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
6162 "do not call blocking ops when !TASK_RUNNING; "
6163 "state=%lx set at [<%p>] %pS\n",
6165 (void *)current->task_state_change,
6166 (void *)current->task_state_change);
6168 ___might_sleep(file, line, preempt_offset);
6170 EXPORT_SYMBOL(__might_sleep);
6172 void ___might_sleep(const char *file, int line, int preempt_offset)
6174 /* Ratelimiting timestamp: */
6175 static unsigned long prev_jiffy;
6177 unsigned long preempt_disable_ip;
6179 /* WARN_ON_ONCE() by default, no rate limit required: */
6182 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6183 !is_idle_task(current)) ||
6184 system_state != SYSTEM_RUNNING || oops_in_progress)
6186 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6188 prev_jiffy = jiffies;
6190 /* Save this before calling printk(), since that will clobber it: */
6191 preempt_disable_ip = get_preempt_disable_ip(current);
6194 "BUG: sleeping function called from invalid context at %s:%d\n",
6197 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6198 in_atomic(), irqs_disabled(),
6199 current->pid, current->comm);
6201 if (task_stack_end_corrupted(current))
6202 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6204 debug_show_held_locks(current);
6205 if (irqs_disabled())
6206 print_irqtrace_events(current);
6207 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6208 && !preempt_count_equals(preempt_offset)) {
6209 pr_err("Preemption disabled at:");
6210 print_ip_sym(preempt_disable_ip);
6214 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6216 EXPORT_SYMBOL(___might_sleep);
6219 #ifdef CONFIG_MAGIC_SYSRQ
6220 void normalize_rt_tasks(void)
6222 struct task_struct *g, *p;
6223 struct sched_attr attr = {
6224 .sched_policy = SCHED_NORMAL,
6227 read_lock(&tasklist_lock);
6228 for_each_process_thread(g, p) {
6230 * Only normalize user tasks:
6232 if (p->flags & PF_KTHREAD)
6235 p->se.exec_start = 0;
6236 schedstat_set(p->se.statistics.wait_start, 0);
6237 schedstat_set(p->se.statistics.sleep_start, 0);
6238 schedstat_set(p->se.statistics.block_start, 0);
6240 if (!dl_task(p) && !rt_task(p)) {
6242 * Renice negative nice level userspace
6245 if (task_nice(p) < 0)
6246 set_user_nice(p, 0);
6250 __sched_setscheduler(p, &attr, false, false);
6252 read_unlock(&tasklist_lock);
6255 #endif /* CONFIG_MAGIC_SYSRQ */
6257 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
6259 * These functions are only useful for the IA64 MCA handling, or kdb.
6261 * They can only be called when the whole system has been
6262 * stopped - every CPU needs to be quiescent, and no scheduling
6263 * activity can take place. Using them for anything else would
6264 * be a serious bug, and as a result, they aren't even visible
6265 * under any other configuration.
6269 * curr_task - return the current task for a given CPU.
6270 * @cpu: the processor in question.
6272 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6274 * Return: The current task for @cpu.
6276 struct task_struct *curr_task(int cpu)
6278 return cpu_curr(cpu);
6281 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6285 * set_curr_task - set the current task for a given CPU.
6286 * @cpu: the processor in question.
6287 * @p: the task pointer to set.
6289 * Description: This function must only be used when non-maskable interrupts
6290 * are serviced on a separate stack. It allows the architecture to switch the
6291 * notion of the current task on a CPU in a non-blocking manner. This function
6292 * must be called with all CPU's synchronized, and interrupts disabled, the
6293 * and caller must save the original value of the current task (see
6294 * curr_task() above) and restore that value before reenabling interrupts and
6295 * re-starting the system.
6297 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6299 void ia64_set_curr_task(int cpu, struct task_struct *p)
6306 #ifdef CONFIG_CGROUP_SCHED
6307 /* task_group_lock serializes the addition/removal of task groups */
6308 static DEFINE_SPINLOCK(task_group_lock);
6310 static void sched_free_group(struct task_group *tg)
6312 free_fair_sched_group(tg);
6313 free_rt_sched_group(tg);
6315 kmem_cache_free(task_group_cache, tg);
6318 /* allocate runqueue etc for a new task group */
6319 struct task_group *sched_create_group(struct task_group *parent)
6321 struct task_group *tg;
6323 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
6325 return ERR_PTR(-ENOMEM);
6327 if (!alloc_fair_sched_group(tg, parent))
6330 if (!alloc_rt_sched_group(tg, parent))
6336 sched_free_group(tg);
6337 return ERR_PTR(-ENOMEM);
6340 void sched_online_group(struct task_group *tg, struct task_group *parent)
6342 unsigned long flags;
6344 spin_lock_irqsave(&task_group_lock, flags);
6345 list_add_rcu(&tg->list, &task_groups);
6347 /* Root should already exist: */
6350 tg->parent = parent;
6351 INIT_LIST_HEAD(&tg->children);
6352 list_add_rcu(&tg->siblings, &parent->children);
6353 spin_unlock_irqrestore(&task_group_lock, flags);
6355 online_fair_sched_group(tg);
6358 /* rcu callback to free various structures associated with a task group */
6359 static void sched_free_group_rcu(struct rcu_head *rhp)
6361 /* Now it should be safe to free those cfs_rqs: */
6362 sched_free_group(container_of(rhp, struct task_group, rcu));
6365 void sched_destroy_group(struct task_group *tg)
6367 /* Wait for possible concurrent references to cfs_rqs complete: */
6368 call_rcu(&tg->rcu, sched_free_group_rcu);
6371 void sched_offline_group(struct task_group *tg)
6373 unsigned long flags;
6375 /* End participation in shares distribution: */
6376 unregister_fair_sched_group(tg);
6378 spin_lock_irqsave(&task_group_lock, flags);
6379 list_del_rcu(&tg->list);
6380 list_del_rcu(&tg->siblings);
6381 spin_unlock_irqrestore(&task_group_lock, flags);
6384 static void sched_change_group(struct task_struct *tsk, int type)
6386 struct task_group *tg;
6389 * All callers are synchronized by task_rq_lock(); we do not use RCU
6390 * which is pointless here. Thus, we pass "true" to task_css_check()
6391 * to prevent lockdep warnings.
6393 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
6394 struct task_group, css);
6395 tg = autogroup_task_group(tsk, tg);
6396 tsk->sched_task_group = tg;
6398 #ifdef CONFIG_FAIR_GROUP_SCHED
6399 if (tsk->sched_class->task_change_group)
6400 tsk->sched_class->task_change_group(tsk, type);
6403 set_task_rq(tsk, task_cpu(tsk));
6407 * Change task's runqueue when it moves between groups.
6409 * The caller of this function should have put the task in its new group by
6410 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6413 void sched_move_task(struct task_struct *tsk)
6415 int queued, running;
6419 rq = task_rq_lock(tsk, &rf);
6420 update_rq_clock(rq);
6422 running = task_current(rq, tsk);
6423 queued = task_on_rq_queued(tsk);
6426 dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
6428 put_prev_task(rq, tsk);
6430 sched_change_group(tsk, TASK_MOVE_GROUP);
6433 enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
6435 set_curr_task(rq, tsk);
6437 task_rq_unlock(rq, tsk, &rf);
6439 #endif /* CONFIG_CGROUP_SCHED */
6441 #ifdef CONFIG_RT_GROUP_SCHED
6443 * Ensure that the real time constraints are schedulable.
6445 static DEFINE_MUTEX(rt_constraints_mutex);
6447 /* Must be called with tasklist_lock held */
6448 static inline int tg_has_rt_tasks(struct task_group *tg)
6450 struct task_struct *g, *p;
6453 * Autogroups do not have RT tasks; see autogroup_create().
6455 if (task_group_is_autogroup(tg))
6458 for_each_process_thread(g, p) {
6459 if (rt_task(p) && task_group(p) == tg)
6466 struct rt_schedulable_data {
6467 struct task_group *tg;
6472 static int tg_rt_schedulable(struct task_group *tg, void *data)
6474 struct rt_schedulable_data *d = data;
6475 struct task_group *child;
6476 unsigned long total, sum = 0;
6477 u64 period, runtime;
6479 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
6480 runtime = tg->rt_bandwidth.rt_runtime;
6483 period = d->rt_period;
6484 runtime = d->rt_runtime;
6488 * Cannot have more runtime than the period.
6490 if (runtime > period && runtime != RUNTIME_INF)
6494 * Ensure we don't starve existing RT tasks.
6496 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
6499 total = to_ratio(period, runtime);
6502 * Nobody can have more than the global setting allows.
6504 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
6508 * The sum of our children's runtime should not exceed our own.
6510 list_for_each_entry_rcu(child, &tg->children, siblings) {
6511 period = ktime_to_ns(child->rt_bandwidth.rt_period);
6512 runtime = child->rt_bandwidth.rt_runtime;
6514 if (child == d->tg) {
6515 period = d->rt_period;
6516 runtime = d->rt_runtime;
6519 sum += to_ratio(period, runtime);
6528 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
6532 struct rt_schedulable_data data = {
6534 .rt_period = period,
6535 .rt_runtime = runtime,
6539 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
6545 static int tg_set_rt_bandwidth(struct task_group *tg,
6546 u64 rt_period, u64 rt_runtime)
6551 * Disallowing the root group RT runtime is BAD, it would disallow the
6552 * kernel creating (and or operating) RT threads.
6554 if (tg == &root_task_group && rt_runtime == 0)
6557 /* No period doesn't make any sense. */
6561 mutex_lock(&rt_constraints_mutex);
6562 read_lock(&tasklist_lock);
6563 err = __rt_schedulable(tg, rt_period, rt_runtime);
6567 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
6568 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
6569 tg->rt_bandwidth.rt_runtime = rt_runtime;
6571 for_each_possible_cpu(i) {
6572 struct rt_rq *rt_rq = tg->rt_rq[i];
6574 raw_spin_lock(&rt_rq->rt_runtime_lock);
6575 rt_rq->rt_runtime = rt_runtime;
6576 raw_spin_unlock(&rt_rq->rt_runtime_lock);
6578 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
6580 read_unlock(&tasklist_lock);
6581 mutex_unlock(&rt_constraints_mutex);
6586 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
6588 u64 rt_runtime, rt_period;
6590 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
6591 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
6592 if (rt_runtime_us < 0)
6593 rt_runtime = RUNTIME_INF;
6595 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
6598 static long sched_group_rt_runtime(struct task_group *tg)
6602 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
6605 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
6606 do_div(rt_runtime_us, NSEC_PER_USEC);
6607 return rt_runtime_us;
6610 static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
6612 u64 rt_runtime, rt_period;
6614 rt_period = rt_period_us * NSEC_PER_USEC;
6615 rt_runtime = tg->rt_bandwidth.rt_runtime;
6617 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
6620 static long sched_group_rt_period(struct task_group *tg)
6624 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
6625 do_div(rt_period_us, NSEC_PER_USEC);
6626 return rt_period_us;
6628 #endif /* CONFIG_RT_GROUP_SCHED */
6630 #ifdef CONFIG_RT_GROUP_SCHED
6631 static int sched_rt_global_constraints(void)
6635 mutex_lock(&rt_constraints_mutex);
6636 read_lock(&tasklist_lock);
6637 ret = __rt_schedulable(NULL, 0, 0);
6638 read_unlock(&tasklist_lock);
6639 mutex_unlock(&rt_constraints_mutex);
6644 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
6646 /* Don't accept realtime tasks when there is no way for them to run */
6647 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
6653 #else /* !CONFIG_RT_GROUP_SCHED */
6654 static int sched_rt_global_constraints(void)
6656 unsigned long flags;
6659 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
6660 for_each_possible_cpu(i) {
6661 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
6663 raw_spin_lock(&rt_rq->rt_runtime_lock);
6664 rt_rq->rt_runtime = global_rt_runtime();
6665 raw_spin_unlock(&rt_rq->rt_runtime_lock);
6667 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
6671 #endif /* CONFIG_RT_GROUP_SCHED */
6673 static int sched_dl_global_validate(void)
6675 u64 runtime = global_rt_runtime();
6676 u64 period = global_rt_period();
6677 u64 new_bw = to_ratio(period, runtime);
6680 unsigned long flags;
6683 * Here we want to check the bandwidth not being set to some
6684 * value smaller than the currently allocated bandwidth in
6685 * any of the root_domains.
6687 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
6688 * cycling on root_domains... Discussion on different/better
6689 * solutions is welcome!
6691 for_each_possible_cpu(cpu) {
6692 rcu_read_lock_sched();
6693 dl_b = dl_bw_of(cpu);
6695 raw_spin_lock_irqsave(&dl_b->lock, flags);
6696 if (new_bw < dl_b->total_bw)
6698 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
6700 rcu_read_unlock_sched();
6709 static void sched_dl_do_global(void)
6714 unsigned long flags;
6716 def_dl_bandwidth.dl_period = global_rt_period();
6717 def_dl_bandwidth.dl_runtime = global_rt_runtime();
6719 if (global_rt_runtime() != RUNTIME_INF)
6720 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
6723 * FIXME: As above...
6725 for_each_possible_cpu(cpu) {
6726 rcu_read_lock_sched();
6727 dl_b = dl_bw_of(cpu);
6729 raw_spin_lock_irqsave(&dl_b->lock, flags);
6731 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
6733 rcu_read_unlock_sched();
6737 static int sched_rt_global_validate(void)
6739 if (sysctl_sched_rt_period <= 0)
6742 if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
6743 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
6749 static void sched_rt_do_global(void)
6751 def_rt_bandwidth.rt_runtime = global_rt_runtime();
6752 def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
6755 int sched_rt_handler(struct ctl_table *table, int write,
6756 void __user *buffer, size_t *lenp,
6759 int old_period, old_runtime;
6760 static DEFINE_MUTEX(mutex);
6764 old_period = sysctl_sched_rt_period;
6765 old_runtime = sysctl_sched_rt_runtime;
6767 ret = proc_dointvec(table, write, buffer, lenp, ppos);
6769 if (!ret && write) {
6770 ret = sched_rt_global_validate();
6774 ret = sched_dl_global_validate();
6778 ret = sched_rt_global_constraints();
6782 sched_rt_do_global();
6783 sched_dl_do_global();
6787 sysctl_sched_rt_period = old_period;
6788 sysctl_sched_rt_runtime = old_runtime;
6790 mutex_unlock(&mutex);
6795 int sched_rr_handler(struct ctl_table *table, int write,
6796 void __user *buffer, size_t *lenp,
6800 static DEFINE_MUTEX(mutex);
6803 ret = proc_dointvec(table, write, buffer, lenp, ppos);
6805 * Make sure that internally we keep jiffies.
6806 * Also, writing zero resets the timeslice to default:
6808 if (!ret && write) {
6809 sched_rr_timeslice =
6810 sysctl_sched_rr_timeslice <= 0 ? RR_TIMESLICE :
6811 msecs_to_jiffies(sysctl_sched_rr_timeslice);
6813 mutex_unlock(&mutex);
6817 #ifdef CONFIG_CGROUP_SCHED
6819 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
6821 return css ? container_of(css, struct task_group, css) : NULL;
6824 static struct cgroup_subsys_state *
6825 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6827 struct task_group *parent = css_tg(parent_css);
6828 struct task_group *tg;
6831 /* This is early initialization for the top cgroup */
6832 return &root_task_group.css;
6835 tg = sched_create_group(parent);
6837 return ERR_PTR(-ENOMEM);
6842 /* Expose task group only after completing cgroup initialization */
6843 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6845 struct task_group *tg = css_tg(css);
6846 struct task_group *parent = css_tg(css->parent);
6849 sched_online_group(tg, parent);
6853 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
6855 struct task_group *tg = css_tg(css);
6857 sched_offline_group(tg);
6860 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
6862 struct task_group *tg = css_tg(css);
6865 * Relies on the RCU grace period between css_released() and this.
6867 sched_free_group(tg);
6871 * This is called before wake_up_new_task(), therefore we really only
6872 * have to set its group bits, all the other stuff does not apply.
6874 static void cpu_cgroup_fork(struct task_struct *task)
6879 rq = task_rq_lock(task, &rf);
6881 update_rq_clock(rq);
6882 sched_change_group(task, TASK_SET_GROUP);
6884 task_rq_unlock(rq, task, &rf);
6887 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
6889 struct task_struct *task;
6890 struct cgroup_subsys_state *css;
6893 cgroup_taskset_for_each(task, css, tset) {
6894 #ifdef CONFIG_RT_GROUP_SCHED
6895 if (!sched_rt_can_attach(css_tg(css), task))
6898 /* We don't support RT-tasks being in separate groups */
6899 if (task->sched_class != &fair_sched_class)
6903 * Serialize against wake_up_new_task() such that if its
6904 * running, we're sure to observe its full state.
6906 raw_spin_lock_irq(&task->pi_lock);
6908 * Avoid calling sched_move_task() before wake_up_new_task()
6909 * has happened. This would lead to problems with PELT, due to
6910 * move wanting to detach+attach while we're not attached yet.
6912 if (task->state == TASK_NEW)
6914 raw_spin_unlock_irq(&task->pi_lock);
6922 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
6924 struct task_struct *task;
6925 struct cgroup_subsys_state *css;
6927 cgroup_taskset_for_each(task, css, tset)
6928 sched_move_task(task);
6931 #ifdef CONFIG_FAIR_GROUP_SCHED
6932 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6933 struct cftype *cftype, u64 shareval)
6935 return sched_group_set_shares(css_tg(css), scale_load(shareval));
6938 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6941 struct task_group *tg = css_tg(css);
6943 return (u64) scale_load_down(tg->shares);
6946 #ifdef CONFIG_CFS_BANDWIDTH
6947 static DEFINE_MUTEX(cfs_constraints_mutex);
6949 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6950 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6952 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6954 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6956 int i, ret = 0, runtime_enabled, runtime_was_enabled;
6957 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6959 if (tg == &root_task_group)
6963 * Ensure we have at some amount of bandwidth every period. This is
6964 * to prevent reaching a state of large arrears when throttled via
6965 * entity_tick() resulting in prolonged exit starvation.
6967 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6971 * Likewise, bound things on the otherside by preventing insane quota
6972 * periods. This also allows us to normalize in computing quota
6975 if (period > max_cfs_quota_period)
6979 * Prevent race between setting of cfs_rq->runtime_enabled and
6980 * unthrottle_offline_cfs_rqs().
6983 mutex_lock(&cfs_constraints_mutex);
6984 ret = __cfs_schedulable(tg, period, quota);
6988 runtime_enabled = quota != RUNTIME_INF;
6989 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
6991 * If we need to toggle cfs_bandwidth_used, off->on must occur
6992 * before making related changes, and on->off must occur afterwards
6994 if (runtime_enabled && !runtime_was_enabled)
6995 cfs_bandwidth_usage_inc();
6996 raw_spin_lock_irq(&cfs_b->lock);
6997 cfs_b->period = ns_to_ktime(period);
6998 cfs_b->quota = quota;
7000 __refill_cfs_bandwidth_runtime(cfs_b);
7002 /* Restart the period timer (if active) to handle new period expiry: */
7003 if (runtime_enabled)
7004 start_cfs_bandwidth(cfs_b);
7006 raw_spin_unlock_irq(&cfs_b->lock);
7008 for_each_online_cpu(i) {
7009 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
7010 struct rq *rq = cfs_rq->rq;
7012 raw_spin_lock_irq(&rq->lock);
7013 cfs_rq->runtime_enabled = runtime_enabled;
7014 cfs_rq->runtime_remaining = 0;
7016 if (cfs_rq->throttled)
7017 unthrottle_cfs_rq(cfs_rq);
7018 raw_spin_unlock_irq(&rq->lock);
7020 if (runtime_was_enabled && !runtime_enabled)
7021 cfs_bandwidth_usage_dec();
7023 mutex_unlock(&cfs_constraints_mutex);
7029 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
7033 period = ktime_to_ns(tg->cfs_bandwidth.period);
7034 if (cfs_quota_us < 0)
7035 quota = RUNTIME_INF;
7037 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
7039 return tg_set_cfs_bandwidth(tg, period, quota);
7042 long tg_get_cfs_quota(struct task_group *tg)
7046 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
7049 quota_us = tg->cfs_bandwidth.quota;
7050 do_div(quota_us, NSEC_PER_USEC);
7055 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
7059 period = (u64)cfs_period_us * NSEC_PER_USEC;
7060 quota = tg->cfs_bandwidth.quota;
7062 return tg_set_cfs_bandwidth(tg, period, quota);
7065 long tg_get_cfs_period(struct task_group *tg)
7069 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
7070 do_div(cfs_period_us, NSEC_PER_USEC);
7072 return cfs_period_us;
7075 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
7078 return tg_get_cfs_quota(css_tg(css));
7081 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
7082 struct cftype *cftype, s64 cfs_quota_us)
7084 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
7087 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
7090 return tg_get_cfs_period(css_tg(css));
7093 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
7094 struct cftype *cftype, u64 cfs_period_us)
7096 return tg_set_cfs_period(css_tg(css), cfs_period_us);
7099 struct cfs_schedulable_data {
7100 struct task_group *tg;
7105 * normalize group quota/period to be quota/max_period
7106 * note: units are usecs
7108 static u64 normalize_cfs_quota(struct task_group *tg,
7109 struct cfs_schedulable_data *d)
7117 period = tg_get_cfs_period(tg);
7118 quota = tg_get_cfs_quota(tg);
7121 /* note: these should typically be equivalent */
7122 if (quota == RUNTIME_INF || quota == -1)
7125 return to_ratio(period, quota);
7128 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
7130 struct cfs_schedulable_data *d = data;
7131 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7132 s64 quota = 0, parent_quota = -1;
7135 quota = RUNTIME_INF;
7137 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
7139 quota = normalize_cfs_quota(tg, d);
7140 parent_quota = parent_b->hierarchical_quota;
7143 * Ensure max(child_quota) <= parent_quota, inherit when no
7146 if (quota == RUNTIME_INF)
7147 quota = parent_quota;
7148 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
7151 cfs_b->hierarchical_quota = quota;
7156 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
7159 struct cfs_schedulable_data data = {
7165 if (quota != RUNTIME_INF) {
7166 do_div(data.period, NSEC_PER_USEC);
7167 do_div(data.quota, NSEC_PER_USEC);
7171 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
7177 static int cpu_stats_show(struct seq_file *sf, void *v)
7179 struct task_group *tg = css_tg(seq_css(sf));
7180 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7182 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
7183 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
7184 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
7188 #endif /* CONFIG_CFS_BANDWIDTH */
7189 #endif /* CONFIG_FAIR_GROUP_SCHED */
7191 #ifdef CONFIG_RT_GROUP_SCHED
7192 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
7193 struct cftype *cft, s64 val)
7195 return sched_group_set_rt_runtime(css_tg(css), val);
7198 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
7201 return sched_group_rt_runtime(css_tg(css));
7204 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
7205 struct cftype *cftype, u64 rt_period_us)
7207 return sched_group_set_rt_period(css_tg(css), rt_period_us);
7210 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
7213 return sched_group_rt_period(css_tg(css));
7215 #endif /* CONFIG_RT_GROUP_SCHED */
7217 static struct cftype cpu_files[] = {
7218 #ifdef CONFIG_FAIR_GROUP_SCHED
7221 .read_u64 = cpu_shares_read_u64,
7222 .write_u64 = cpu_shares_write_u64,
7225 #ifdef CONFIG_CFS_BANDWIDTH
7227 .name = "cfs_quota_us",
7228 .read_s64 = cpu_cfs_quota_read_s64,
7229 .write_s64 = cpu_cfs_quota_write_s64,
7232 .name = "cfs_period_us",
7233 .read_u64 = cpu_cfs_period_read_u64,
7234 .write_u64 = cpu_cfs_period_write_u64,
7238 .seq_show = cpu_stats_show,
7241 #ifdef CONFIG_RT_GROUP_SCHED
7243 .name = "rt_runtime_us",
7244 .read_s64 = cpu_rt_runtime_read,
7245 .write_s64 = cpu_rt_runtime_write,
7248 .name = "rt_period_us",
7249 .read_u64 = cpu_rt_period_read_uint,
7250 .write_u64 = cpu_rt_period_write_uint,
7256 struct cgroup_subsys cpu_cgrp_subsys = {
7257 .css_alloc = cpu_cgroup_css_alloc,
7258 .css_online = cpu_cgroup_css_online,
7259 .css_released = cpu_cgroup_css_released,
7260 .css_free = cpu_cgroup_css_free,
7261 .fork = cpu_cgroup_fork,
7262 .can_attach = cpu_cgroup_can_attach,
7263 .attach = cpu_cgroup_attach,
7264 .legacy_cftypes = cpu_files,
7268 #endif /* CONFIG_CGROUP_SCHED */
7270 void dump_cpu_task(int cpu)
7272 pr_info("Task dump for CPU %d:\n", cpu);
7273 sched_show_task(cpu_curr(cpu));
7277 * Nice levels are multiplicative, with a gentle 10% change for every
7278 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
7279 * nice 1, it will get ~10% less CPU time than another CPU-bound task
7280 * that remained on nice 0.
7282 * The "10% effect" is relative and cumulative: from _any_ nice level,
7283 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
7284 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
7285 * If a task goes up by ~10% and another task goes down by ~10% then
7286 * the relative distance between them is ~25%.)
7288 const int sched_prio_to_weight[40] = {
7289 /* -20 */ 88761, 71755, 56483, 46273, 36291,
7290 /* -15 */ 29154, 23254, 18705, 14949, 11916,
7291 /* -10 */ 9548, 7620, 6100, 4904, 3906,
7292 /* -5 */ 3121, 2501, 1991, 1586, 1277,
7293 /* 0 */ 1024, 820, 655, 526, 423,
7294 /* 5 */ 335, 272, 215, 172, 137,
7295 /* 10 */ 110, 87, 70, 56, 45,
7296 /* 15 */ 36, 29, 23, 18, 15,
7300 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
7302 * In cases where the weight does not change often, we can use the
7303 * precalculated inverse to speed up arithmetics by turning divisions
7304 * into multiplications:
7306 const u32 sched_prio_to_wmult[40] = {
7307 /* -20 */ 48388, 59856, 76040, 92818, 118348,
7308 /* -15 */ 147320, 184698, 229616, 287308, 360437,
7309 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
7310 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
7311 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
7312 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
7313 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
7314 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,