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/wait_bit.h>
14 #include <linux/cpuset.h>
15 #include <linux/delayacct.h>
16 #include <linux/init_task.h>
17 #include <linux/context_tracking.h>
18 #include <linux/rcupdate_wait.h>
20 #include <linux/blkdev.h>
21 #include <linux/kprobes.h>
22 #include <linux/mmu_context.h>
23 #include <linux/module.h>
24 #include <linux/nmi.h>
25 #include <linux/prefetch.h>
26 #include <linux/profile.h>
27 #include <linux/security.h>
28 #include <linux/syscalls.h>
29 #include <linux/sched/isolation.h>
31 #include <asm/switch_to.h>
33 #ifdef CONFIG_PARAVIRT
34 #include <asm/paravirt.h>
38 #include "../workqueue_internal.h"
39 #include "../smpboot.h"
41 #define CREATE_TRACE_POINTS
42 #include <trace/events/sched.h>
44 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
46 #if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL)
48 * Debugging: various feature bits
50 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
51 * sysctl_sched_features, defined in sched.h, to allow constants propagation
52 * at compile time and compiler optimization based on features default.
54 #define SCHED_FEAT(name, enabled) \
55 (1UL << __SCHED_FEAT_##name) * enabled |
56 const_debug
unsigned int sysctl_sched_features
=
63 * Number of tasks to iterate in a single balance run.
64 * Limited because this is done with IRQs disabled.
66 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
69 * period over which we average the RT time consumption, measured
74 const_debug
unsigned int sysctl_sched_time_avg
= MSEC_PER_SEC
;
77 * period over which we measure -rt task CPU usage in us.
80 unsigned int sysctl_sched_rt_period
= 1000000;
82 __read_mostly
int scheduler_running
;
85 * part of the period that we allow rt tasks to run in us.
88 int sysctl_sched_rt_runtime
= 950000;
91 * __task_rq_lock - lock the rq @p resides on.
93 struct rq
*__task_rq_lock(struct task_struct
*p
, struct rq_flags
*rf
)
98 lockdep_assert_held(&p
->pi_lock
);
102 raw_spin_lock(&rq
->lock
);
103 if (likely(rq
== task_rq(p
) && !task_on_rq_migrating(p
))) {
107 raw_spin_unlock(&rq
->lock
);
109 while (unlikely(task_on_rq_migrating(p
)))
115 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
117 struct rq
*task_rq_lock(struct task_struct
*p
, struct rq_flags
*rf
)
118 __acquires(p
->pi_lock
)
124 raw_spin_lock_irqsave(&p
->pi_lock
, rf
->flags
);
126 raw_spin_lock(&rq
->lock
);
128 * move_queued_task() task_rq_lock()
131 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
132 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
133 * [S] ->cpu = new_cpu [L] task_rq()
137 * If we observe the old cpu in task_rq_lock, the acquire of
138 * the old rq->lock will fully serialize against the stores.
140 * If we observe the new CPU in task_rq_lock, the acquire will
141 * pair with the WMB to ensure we must then also see migrating.
143 if (likely(rq
== task_rq(p
) && !task_on_rq_migrating(p
))) {
147 raw_spin_unlock(&rq
->lock
);
148 raw_spin_unlock_irqrestore(&p
->pi_lock
, rf
->flags
);
150 while (unlikely(task_on_rq_migrating(p
)))
156 * RQ-clock updating methods:
159 static void update_rq_clock_task(struct rq
*rq
, s64 delta
)
162 * In theory, the compile should just see 0 here, and optimize out the call
163 * to sched_rt_avg_update. But I don't trust it...
165 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
166 s64 steal
= 0, irq_delta
= 0;
168 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
169 irq_delta
= irq_time_read(cpu_of(rq
)) - rq
->prev_irq_time
;
172 * Since irq_time is only updated on {soft,}irq_exit, we might run into
173 * this case when a previous update_rq_clock() happened inside a
176 * When this happens, we stop ->clock_task and only update the
177 * prev_irq_time stamp to account for the part that fit, so that a next
178 * update will consume the rest. This ensures ->clock_task is
181 * It does however cause some slight miss-attribution of {soft,}irq
182 * time, a more accurate solution would be to update the irq_time using
183 * the current rq->clock timestamp, except that would require using
186 if (irq_delta
> delta
)
189 rq
->prev_irq_time
+= irq_delta
;
192 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
193 if (static_key_false((¶virt_steal_rq_enabled
))) {
194 steal
= paravirt_steal_clock(cpu_of(rq
));
195 steal
-= rq
->prev_steal_time_rq
;
197 if (unlikely(steal
> delta
))
200 rq
->prev_steal_time_rq
+= steal
;
205 rq
->clock_task
+= delta
;
207 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
208 if ((irq_delta
+ steal
) && sched_feat(NONTASK_CAPACITY
))
209 sched_rt_avg_update(rq
, irq_delta
+ steal
);
213 void update_rq_clock(struct rq
*rq
)
217 lockdep_assert_held(&rq
->lock
);
219 if (rq
->clock_update_flags
& RQCF_ACT_SKIP
)
222 #ifdef CONFIG_SCHED_DEBUG
223 if (sched_feat(WARN_DOUBLE_CLOCK
))
224 SCHED_WARN_ON(rq
->clock_update_flags
& RQCF_UPDATED
);
225 rq
->clock_update_flags
|= RQCF_UPDATED
;
228 delta
= sched_clock_cpu(cpu_of(rq
)) - rq
->clock
;
232 update_rq_clock_task(rq
, delta
);
236 #ifdef CONFIG_SCHED_HRTICK
238 * Use HR-timers to deliver accurate preemption points.
241 static void hrtick_clear(struct rq
*rq
)
243 if (hrtimer_active(&rq
->hrtick_timer
))
244 hrtimer_cancel(&rq
->hrtick_timer
);
248 * High-resolution timer tick.
249 * Runs from hardirq context with interrupts disabled.
251 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
253 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
256 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
260 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
263 return HRTIMER_NORESTART
;
268 static void __hrtick_restart(struct rq
*rq
)
270 struct hrtimer
*timer
= &rq
->hrtick_timer
;
272 hrtimer_start_expires(timer
, HRTIMER_MODE_ABS_PINNED
);
276 * called from hardirq (IPI) context
278 static void __hrtick_start(void *arg
)
284 __hrtick_restart(rq
);
285 rq
->hrtick_csd_pending
= 0;
290 * Called to set the hrtick timer state.
292 * called with rq->lock held and irqs disabled
294 void hrtick_start(struct rq
*rq
, u64 delay
)
296 struct hrtimer
*timer
= &rq
->hrtick_timer
;
301 * Don't schedule slices shorter than 10000ns, that just
302 * doesn't make sense and can cause timer DoS.
304 delta
= max_t(s64
, delay
, 10000LL);
305 time
= ktime_add_ns(timer
->base
->get_time(), delta
);
307 hrtimer_set_expires(timer
, time
);
309 if (rq
== this_rq()) {
310 __hrtick_restart(rq
);
311 } else if (!rq
->hrtick_csd_pending
) {
312 smp_call_function_single_async(cpu_of(rq
), &rq
->hrtick_csd
);
313 rq
->hrtick_csd_pending
= 1;
319 * Called to set the hrtick timer state.
321 * called with rq->lock held and irqs disabled
323 void hrtick_start(struct rq
*rq
, u64 delay
)
326 * Don't schedule slices shorter than 10000ns, that just
327 * doesn't make sense. Rely on vruntime for fairness.
329 delay
= max_t(u64
, delay
, 10000LL);
330 hrtimer_start(&rq
->hrtick_timer
, ns_to_ktime(delay
),
331 HRTIMER_MODE_REL_PINNED
);
333 #endif /* CONFIG_SMP */
335 static void init_rq_hrtick(struct rq
*rq
)
338 rq
->hrtick_csd_pending
= 0;
340 rq
->hrtick_csd
.flags
= 0;
341 rq
->hrtick_csd
.func
= __hrtick_start
;
342 rq
->hrtick_csd
.info
= rq
;
345 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
346 rq
->hrtick_timer
.function
= hrtick
;
348 #else /* CONFIG_SCHED_HRTICK */
349 static inline void hrtick_clear(struct rq
*rq
)
353 static inline void init_rq_hrtick(struct rq
*rq
)
356 #endif /* CONFIG_SCHED_HRTICK */
359 * cmpxchg based fetch_or, macro so it works for different integer types
361 #define fetch_or(ptr, mask) \
363 typeof(ptr) _ptr = (ptr); \
364 typeof(mask) _mask = (mask); \
365 typeof(*_ptr) _old, _val = *_ptr; \
368 _old = cmpxchg(_ptr, _val, _val | _mask); \
376 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
378 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
379 * this avoids any races wrt polling state changes and thereby avoids
382 static bool set_nr_and_not_polling(struct task_struct
*p
)
384 struct thread_info
*ti
= task_thread_info(p
);
385 return !(fetch_or(&ti
->flags
, _TIF_NEED_RESCHED
) & _TIF_POLLING_NRFLAG
);
389 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
391 * If this returns true, then the idle task promises to call
392 * sched_ttwu_pending() and reschedule soon.
394 static bool set_nr_if_polling(struct task_struct
*p
)
396 struct thread_info
*ti
= task_thread_info(p
);
397 typeof(ti
->flags
) old
, val
= READ_ONCE(ti
->flags
);
400 if (!(val
& _TIF_POLLING_NRFLAG
))
402 if (val
& _TIF_NEED_RESCHED
)
404 old
= cmpxchg(&ti
->flags
, val
, val
| _TIF_NEED_RESCHED
);
413 static bool set_nr_and_not_polling(struct task_struct
*p
)
415 set_tsk_need_resched(p
);
420 static bool set_nr_if_polling(struct task_struct
*p
)
427 void wake_q_add(struct wake_q_head
*head
, struct task_struct
*task
)
429 struct wake_q_node
*node
= &task
->wake_q
;
432 * Atomically grab the task, if ->wake_q is !nil already it means
433 * its already queued (either by us or someone else) and will get the
434 * wakeup due to that.
436 * This cmpxchg() implies a full barrier, which pairs with the write
437 * barrier implied by the wakeup in wake_up_q().
439 if (cmpxchg(&node
->next
, NULL
, WAKE_Q_TAIL
))
442 get_task_struct(task
);
445 * The head is context local, there can be no concurrency.
448 head
->lastp
= &node
->next
;
451 void wake_up_q(struct wake_q_head
*head
)
453 struct wake_q_node
*node
= head
->first
;
455 while (node
!= WAKE_Q_TAIL
) {
456 struct task_struct
*task
;
458 task
= container_of(node
, struct task_struct
, wake_q
);
460 /* Task can safely be re-inserted now: */
462 task
->wake_q
.next
= NULL
;
465 * wake_up_process() implies a wmb() to pair with the queueing
466 * in wake_q_add() so as not to miss wakeups.
468 wake_up_process(task
);
469 put_task_struct(task
);
474 * resched_curr - mark rq's current task 'to be rescheduled now'.
476 * On UP this means the setting of the need_resched flag, on SMP it
477 * might also involve a cross-CPU call to trigger the scheduler on
480 void resched_curr(struct rq
*rq
)
482 struct task_struct
*curr
= rq
->curr
;
485 lockdep_assert_held(&rq
->lock
);
487 if (test_tsk_need_resched(curr
))
492 if (cpu
== smp_processor_id()) {
493 set_tsk_need_resched(curr
);
494 set_preempt_need_resched();
498 if (set_nr_and_not_polling(curr
))
499 smp_send_reschedule(cpu
);
501 trace_sched_wake_idle_without_ipi(cpu
);
504 void resched_cpu(int cpu
)
506 struct rq
*rq
= cpu_rq(cpu
);
509 raw_spin_lock_irqsave(&rq
->lock
, flags
);
511 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
515 #ifdef CONFIG_NO_HZ_COMMON
517 * In the semi idle case, use the nearest busy CPU for migrating timers
518 * from an idle CPU. This is good for power-savings.
520 * We don't do similar optimization for completely idle system, as
521 * selecting an idle CPU will add more delays to the timers than intended
522 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
524 int get_nohz_timer_target(void)
526 int i
, cpu
= smp_processor_id();
527 struct sched_domain
*sd
;
529 if (!idle_cpu(cpu
) && housekeeping_cpu(cpu
, HK_FLAG_TIMER
))
533 for_each_domain(cpu
, sd
) {
534 for_each_cpu(i
, sched_domain_span(sd
)) {
538 if (!idle_cpu(i
) && housekeeping_cpu(i
, HK_FLAG_TIMER
)) {
545 if (!housekeeping_cpu(cpu
, HK_FLAG_TIMER
))
546 cpu
= housekeeping_any_cpu(HK_FLAG_TIMER
);
553 * When add_timer_on() enqueues a timer into the timer wheel of an
554 * idle CPU then this timer might expire before the next timer event
555 * which is scheduled to wake up that CPU. In case of a completely
556 * idle system the next event might even be infinite time into the
557 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
558 * leaves the inner idle loop so the newly added timer is taken into
559 * account when the CPU goes back to idle and evaluates the timer
560 * wheel for the next timer event.
562 static void wake_up_idle_cpu(int cpu
)
564 struct rq
*rq
= cpu_rq(cpu
);
566 if (cpu
== smp_processor_id())
569 if (set_nr_and_not_polling(rq
->idle
))
570 smp_send_reschedule(cpu
);
572 trace_sched_wake_idle_without_ipi(cpu
);
575 static bool wake_up_full_nohz_cpu(int cpu
)
578 * We just need the target to call irq_exit() and re-evaluate
579 * the next tick. The nohz full kick at least implies that.
580 * If needed we can still optimize that later with an
583 if (cpu_is_offline(cpu
))
584 return true; /* Don't try to wake offline CPUs. */
585 if (tick_nohz_full_cpu(cpu
)) {
586 if (cpu
!= smp_processor_id() ||
587 tick_nohz_tick_stopped())
588 tick_nohz_full_kick_cpu(cpu
);
596 * Wake up the specified CPU. If the CPU is going offline, it is the
597 * caller's responsibility to deal with the lost wakeup, for example,
598 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
600 void wake_up_nohz_cpu(int cpu
)
602 if (!wake_up_full_nohz_cpu(cpu
))
603 wake_up_idle_cpu(cpu
);
606 static inline bool got_nohz_idle_kick(void)
608 int cpu
= smp_processor_id();
610 if (!test_bit(NOHZ_BALANCE_KICK
, nohz_flags(cpu
)))
613 if (idle_cpu(cpu
) && !need_resched())
617 * We can't run Idle Load Balance on this CPU for this time so we
618 * cancel it and clear NOHZ_BALANCE_KICK
620 clear_bit(NOHZ_BALANCE_KICK
, nohz_flags(cpu
));
624 #else /* CONFIG_NO_HZ_COMMON */
626 static inline bool got_nohz_idle_kick(void)
631 #endif /* CONFIG_NO_HZ_COMMON */
633 #ifdef CONFIG_NO_HZ_FULL
634 bool sched_can_stop_tick(struct rq
*rq
)
638 /* Deadline tasks, even if single, need the tick */
639 if (rq
->dl
.dl_nr_running
)
643 * If there are more than one RR tasks, we need the tick to effect the
644 * actual RR behaviour.
646 if (rq
->rt
.rr_nr_running
) {
647 if (rq
->rt
.rr_nr_running
== 1)
654 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
655 * forced preemption between FIFO tasks.
657 fifo_nr_running
= rq
->rt
.rt_nr_running
- rq
->rt
.rr_nr_running
;
662 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
663 * if there's more than one we need the tick for involuntary
666 if (rq
->nr_running
> 1)
671 #endif /* CONFIG_NO_HZ_FULL */
673 void sched_avg_update(struct rq
*rq
)
675 s64 period
= sched_avg_period();
677 while ((s64
)(rq_clock(rq
) - rq
->age_stamp
) > period
) {
679 * Inline assembly required to prevent the compiler
680 * optimising this loop into a divmod call.
681 * See __iter_div_u64_rem() for another example of this.
683 asm("" : "+rm" (rq
->age_stamp
));
684 rq
->age_stamp
+= period
;
689 #endif /* CONFIG_SMP */
691 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
692 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
694 * Iterate task_group tree rooted at *from, calling @down when first entering a
695 * node and @up when leaving it for the final time.
697 * Caller must hold rcu_lock or sufficient equivalent.
699 int walk_tg_tree_from(struct task_group
*from
,
700 tg_visitor down
, tg_visitor up
, void *data
)
702 struct task_group
*parent
, *child
;
708 ret
= (*down
)(parent
, data
);
711 list_for_each_entry_rcu(child
, &parent
->children
, siblings
) {
718 ret
= (*up
)(parent
, data
);
719 if (ret
|| parent
== from
)
723 parent
= parent
->parent
;
730 int tg_nop(struct task_group
*tg
, void *data
)
736 static void set_load_weight(struct task_struct
*p
, bool update_load
)
738 int prio
= p
->static_prio
- MAX_RT_PRIO
;
739 struct load_weight
*load
= &p
->se
.load
;
742 * SCHED_IDLE tasks get minimal weight:
744 if (idle_policy(p
->policy
)) {
745 load
->weight
= scale_load(WEIGHT_IDLEPRIO
);
746 load
->inv_weight
= WMULT_IDLEPRIO
;
751 * SCHED_OTHER tasks have to update their load when changing their
754 if (update_load
&& p
->sched_class
== &fair_sched_class
) {
755 reweight_task(p
, prio
);
757 load
->weight
= scale_load(sched_prio_to_weight
[prio
]);
758 load
->inv_weight
= sched_prio_to_wmult
[prio
];
762 static inline void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
764 if (!(flags
& ENQUEUE_NOCLOCK
))
767 if (!(flags
& ENQUEUE_RESTORE
))
768 sched_info_queued(rq
, p
);
770 p
->sched_class
->enqueue_task(rq
, p
, flags
);
773 static inline void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
775 if (!(flags
& DEQUEUE_NOCLOCK
))
778 if (!(flags
& DEQUEUE_SAVE
))
779 sched_info_dequeued(rq
, p
);
781 p
->sched_class
->dequeue_task(rq
, p
, flags
);
784 void activate_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
786 if (task_contributes_to_load(p
))
787 rq
->nr_uninterruptible
--;
789 enqueue_task(rq
, p
, flags
);
792 void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
794 if (task_contributes_to_load(p
))
795 rq
->nr_uninterruptible
++;
797 dequeue_task(rq
, p
, flags
);
801 * __normal_prio - return the priority that is based on the static prio
803 static inline int __normal_prio(struct task_struct
*p
)
805 return p
->static_prio
;
809 * Calculate the expected normal priority: i.e. priority
810 * without taking RT-inheritance into account. Might be
811 * boosted by interactivity modifiers. Changes upon fork,
812 * setprio syscalls, and whenever the interactivity
813 * estimator recalculates.
815 static inline int normal_prio(struct task_struct
*p
)
819 if (task_has_dl_policy(p
))
820 prio
= MAX_DL_PRIO
-1;
821 else if (task_has_rt_policy(p
))
822 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
824 prio
= __normal_prio(p
);
829 * Calculate the current priority, i.e. the priority
830 * taken into account by the scheduler. This value might
831 * be boosted by RT tasks, or might be boosted by
832 * interactivity modifiers. Will be RT if the task got
833 * RT-boosted. If not then it returns p->normal_prio.
835 static int effective_prio(struct task_struct
*p
)
837 p
->normal_prio
= normal_prio(p
);
839 * If we are RT tasks or we were boosted to RT priority,
840 * keep the priority unchanged. Otherwise, update priority
841 * to the normal priority:
843 if (!rt_prio(p
->prio
))
844 return p
->normal_prio
;
849 * task_curr - is this task currently executing on a CPU?
850 * @p: the task in question.
852 * Return: 1 if the task is currently executing. 0 otherwise.
854 inline int task_curr(const struct task_struct
*p
)
856 return cpu_curr(task_cpu(p
)) == p
;
860 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
861 * use the balance_callback list if you want balancing.
863 * this means any call to check_class_changed() must be followed by a call to
864 * balance_callback().
866 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
867 const struct sched_class
*prev_class
,
870 if (prev_class
!= p
->sched_class
) {
871 if (prev_class
->switched_from
)
872 prev_class
->switched_from(rq
, p
);
874 p
->sched_class
->switched_to(rq
, p
);
875 } else if (oldprio
!= p
->prio
|| dl_task(p
))
876 p
->sched_class
->prio_changed(rq
, p
, oldprio
);
879 void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
, int flags
)
881 const struct sched_class
*class;
883 if (p
->sched_class
== rq
->curr
->sched_class
) {
884 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
, flags
);
886 for_each_class(class) {
887 if (class == rq
->curr
->sched_class
)
889 if (class == p
->sched_class
) {
897 * A queue event has occurred, and we're going to schedule. In
898 * this case, we can save a useless back to back clock update.
900 if (task_on_rq_queued(rq
->curr
) && test_tsk_need_resched(rq
->curr
))
901 rq_clock_skip_update(rq
, true);
906 * This is how migration works:
908 * 1) we invoke migration_cpu_stop() on the target CPU using
910 * 2) stopper starts to run (implicitly forcing the migrated thread
912 * 3) it checks whether the migrated task is still in the wrong runqueue.
913 * 4) if it's in the wrong runqueue then the migration thread removes
914 * it and puts it into the right queue.
915 * 5) stopper completes and stop_one_cpu() returns and the migration
920 * move_queued_task - move a queued task to new rq.
922 * Returns (locked) new rq. Old rq's lock is released.
924 static struct rq
*move_queued_task(struct rq
*rq
, struct rq_flags
*rf
,
925 struct task_struct
*p
, int new_cpu
)
927 lockdep_assert_held(&rq
->lock
);
929 p
->on_rq
= TASK_ON_RQ_MIGRATING
;
930 dequeue_task(rq
, p
, DEQUEUE_NOCLOCK
);
931 set_task_cpu(p
, new_cpu
);
934 rq
= cpu_rq(new_cpu
);
937 BUG_ON(task_cpu(p
) != new_cpu
);
938 enqueue_task(rq
, p
, 0);
939 p
->on_rq
= TASK_ON_RQ_QUEUED
;
940 check_preempt_curr(rq
, p
, 0);
945 struct migration_arg
{
946 struct task_struct
*task
;
951 * Move (not current) task off this CPU, onto the destination CPU. We're doing
952 * this because either it can't run here any more (set_cpus_allowed()
953 * away from this CPU, or CPU going down), or because we're
954 * attempting to rebalance this task on exec (sched_exec).
956 * So we race with normal scheduler movements, but that's OK, as long
957 * as the task is no longer on this CPU.
959 static struct rq
*__migrate_task(struct rq
*rq
, struct rq_flags
*rf
,
960 struct task_struct
*p
, int dest_cpu
)
962 if (p
->flags
& PF_KTHREAD
) {
963 if (unlikely(!cpu_online(dest_cpu
)))
966 if (unlikely(!cpu_active(dest_cpu
)))
970 /* Affinity changed (again). */
971 if (!cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
))
975 rq
= move_queued_task(rq
, rf
, p
, dest_cpu
);
981 * migration_cpu_stop - this will be executed by a highprio stopper thread
982 * and performs thread migration by bumping thread off CPU then
983 * 'pushing' onto another runqueue.
985 static int migration_cpu_stop(void *data
)
987 struct migration_arg
*arg
= data
;
988 struct task_struct
*p
= arg
->task
;
989 struct rq
*rq
= this_rq();
993 * The original target CPU might have gone down and we might
994 * be on another CPU but it doesn't matter.
998 * We need to explicitly wake pending tasks before running
999 * __migrate_task() such that we will not miss enforcing cpus_allowed
1000 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1002 sched_ttwu_pending();
1004 raw_spin_lock(&p
->pi_lock
);
1007 * If task_rq(p) != rq, it cannot be migrated here, because we're
1008 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1009 * we're holding p->pi_lock.
1011 if (task_rq(p
) == rq
) {
1012 if (task_on_rq_queued(p
))
1013 rq
= __migrate_task(rq
, &rf
, p
, arg
->dest_cpu
);
1015 p
->wake_cpu
= arg
->dest_cpu
;
1018 raw_spin_unlock(&p
->pi_lock
);
1025 * sched_class::set_cpus_allowed must do the below, but is not required to
1026 * actually call this function.
1028 void set_cpus_allowed_common(struct task_struct
*p
, const struct cpumask
*new_mask
)
1030 cpumask_copy(&p
->cpus_allowed
, new_mask
);
1031 p
->nr_cpus_allowed
= cpumask_weight(new_mask
);
1034 void do_set_cpus_allowed(struct task_struct
*p
, const struct cpumask
*new_mask
)
1036 struct rq
*rq
= task_rq(p
);
1037 bool queued
, running
;
1039 lockdep_assert_held(&p
->pi_lock
);
1041 queued
= task_on_rq_queued(p
);
1042 running
= task_current(rq
, p
);
1046 * Because __kthread_bind() calls this on blocked tasks without
1049 lockdep_assert_held(&rq
->lock
);
1050 dequeue_task(rq
, p
, DEQUEUE_SAVE
| DEQUEUE_NOCLOCK
);
1053 put_prev_task(rq
, p
);
1055 p
->sched_class
->set_cpus_allowed(p
, new_mask
);
1058 enqueue_task(rq
, p
, ENQUEUE_RESTORE
| ENQUEUE_NOCLOCK
);
1060 set_curr_task(rq
, p
);
1064 * Change a given task's CPU affinity. Migrate the thread to a
1065 * proper CPU and schedule it away if the CPU it's executing on
1066 * is removed from the allowed bitmask.
1068 * NOTE: the caller must have a valid reference to the task, the
1069 * task must not exit() & deallocate itself prematurely. The
1070 * call is not atomic; no spinlocks may be held.
1072 static int __set_cpus_allowed_ptr(struct task_struct
*p
,
1073 const struct cpumask
*new_mask
, bool check
)
1075 const struct cpumask
*cpu_valid_mask
= cpu_active_mask
;
1076 unsigned int dest_cpu
;
1081 rq
= task_rq_lock(p
, &rf
);
1082 update_rq_clock(rq
);
1084 if (p
->flags
& PF_KTHREAD
) {
1086 * Kernel threads are allowed on online && !active CPUs
1088 cpu_valid_mask
= cpu_online_mask
;
1092 * Must re-check here, to close a race against __kthread_bind(),
1093 * sched_setaffinity() is not guaranteed to observe the flag.
1095 if (check
&& (p
->flags
& PF_NO_SETAFFINITY
)) {
1100 if (cpumask_equal(&p
->cpus_allowed
, new_mask
))
1103 if (!cpumask_intersects(new_mask
, cpu_valid_mask
)) {
1108 do_set_cpus_allowed(p
, new_mask
);
1110 if (p
->flags
& PF_KTHREAD
) {
1112 * For kernel threads that do indeed end up on online &&
1113 * !active we want to ensure they are strict per-CPU threads.
1115 WARN_ON(cpumask_intersects(new_mask
, cpu_online_mask
) &&
1116 !cpumask_intersects(new_mask
, cpu_active_mask
) &&
1117 p
->nr_cpus_allowed
!= 1);
1120 /* Can the task run on the task's current CPU? If so, we're done */
1121 if (cpumask_test_cpu(task_cpu(p
), new_mask
))
1124 dest_cpu
= cpumask_any_and(cpu_valid_mask
, new_mask
);
1125 if (task_running(rq
, p
) || p
->state
== TASK_WAKING
) {
1126 struct migration_arg arg
= { p
, dest_cpu
};
1127 /* Need help from migration thread: drop lock and wait. */
1128 task_rq_unlock(rq
, p
, &rf
);
1129 stop_one_cpu(cpu_of(rq
), migration_cpu_stop
, &arg
);
1130 tlb_migrate_finish(p
->mm
);
1132 } else if (task_on_rq_queued(p
)) {
1134 * OK, since we're going to drop the lock immediately
1135 * afterwards anyway.
1137 rq
= move_queued_task(rq
, &rf
, p
, dest_cpu
);
1140 task_rq_unlock(rq
, p
, &rf
);
1145 int set_cpus_allowed_ptr(struct task_struct
*p
, const struct cpumask
*new_mask
)
1147 return __set_cpus_allowed_ptr(p
, new_mask
, false);
1149 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr
);
1151 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1153 #ifdef CONFIG_SCHED_DEBUG
1155 * We should never call set_task_cpu() on a blocked task,
1156 * ttwu() will sort out the placement.
1158 WARN_ON_ONCE(p
->state
!= TASK_RUNNING
&& p
->state
!= TASK_WAKING
&&
1162 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1163 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1164 * time relying on p->on_rq.
1166 WARN_ON_ONCE(p
->state
== TASK_RUNNING
&&
1167 p
->sched_class
== &fair_sched_class
&&
1168 (p
->on_rq
&& !task_on_rq_migrating(p
)));
1170 #ifdef CONFIG_LOCKDEP
1172 * The caller should hold either p->pi_lock or rq->lock, when changing
1173 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1175 * sched_move_task() holds both and thus holding either pins the cgroup,
1178 * Furthermore, all task_rq users should acquire both locks, see
1181 WARN_ON_ONCE(debug_locks
&& !(lockdep_is_held(&p
->pi_lock
) ||
1182 lockdep_is_held(&task_rq(p
)->lock
)));
1185 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1187 WARN_ON_ONCE(!cpu_online(new_cpu
));
1190 trace_sched_migrate_task(p
, new_cpu
);
1192 if (task_cpu(p
) != new_cpu
) {
1193 if (p
->sched_class
->migrate_task_rq
)
1194 p
->sched_class
->migrate_task_rq(p
);
1195 p
->se
.nr_migrations
++;
1196 perf_event_task_migrate(p
);
1199 __set_task_cpu(p
, new_cpu
);
1202 static void __migrate_swap_task(struct task_struct
*p
, int cpu
)
1204 if (task_on_rq_queued(p
)) {
1205 struct rq
*src_rq
, *dst_rq
;
1206 struct rq_flags srf
, drf
;
1208 src_rq
= task_rq(p
);
1209 dst_rq
= cpu_rq(cpu
);
1211 rq_pin_lock(src_rq
, &srf
);
1212 rq_pin_lock(dst_rq
, &drf
);
1214 p
->on_rq
= TASK_ON_RQ_MIGRATING
;
1215 deactivate_task(src_rq
, p
, 0);
1216 set_task_cpu(p
, cpu
);
1217 activate_task(dst_rq
, p
, 0);
1218 p
->on_rq
= TASK_ON_RQ_QUEUED
;
1219 check_preempt_curr(dst_rq
, p
, 0);
1221 rq_unpin_lock(dst_rq
, &drf
);
1222 rq_unpin_lock(src_rq
, &srf
);
1226 * Task isn't running anymore; make it appear like we migrated
1227 * it before it went to sleep. This means on wakeup we make the
1228 * previous CPU our target instead of where it really is.
1234 struct migration_swap_arg
{
1235 struct task_struct
*src_task
, *dst_task
;
1236 int src_cpu
, dst_cpu
;
1239 static int migrate_swap_stop(void *data
)
1241 struct migration_swap_arg
*arg
= data
;
1242 struct rq
*src_rq
, *dst_rq
;
1245 if (!cpu_active(arg
->src_cpu
) || !cpu_active(arg
->dst_cpu
))
1248 src_rq
= cpu_rq(arg
->src_cpu
);
1249 dst_rq
= cpu_rq(arg
->dst_cpu
);
1251 double_raw_lock(&arg
->src_task
->pi_lock
,
1252 &arg
->dst_task
->pi_lock
);
1253 double_rq_lock(src_rq
, dst_rq
);
1255 if (task_cpu(arg
->dst_task
) != arg
->dst_cpu
)
1258 if (task_cpu(arg
->src_task
) != arg
->src_cpu
)
1261 if (!cpumask_test_cpu(arg
->dst_cpu
, &arg
->src_task
->cpus_allowed
))
1264 if (!cpumask_test_cpu(arg
->src_cpu
, &arg
->dst_task
->cpus_allowed
))
1267 __migrate_swap_task(arg
->src_task
, arg
->dst_cpu
);
1268 __migrate_swap_task(arg
->dst_task
, arg
->src_cpu
);
1273 double_rq_unlock(src_rq
, dst_rq
);
1274 raw_spin_unlock(&arg
->dst_task
->pi_lock
);
1275 raw_spin_unlock(&arg
->src_task
->pi_lock
);
1281 * Cross migrate two tasks
1283 int migrate_swap(struct task_struct
*cur
, struct task_struct
*p
)
1285 struct migration_swap_arg arg
;
1288 arg
= (struct migration_swap_arg
){
1290 .src_cpu
= task_cpu(cur
),
1292 .dst_cpu
= task_cpu(p
),
1295 if (arg
.src_cpu
== arg
.dst_cpu
)
1299 * These three tests are all lockless; this is OK since all of them
1300 * will be re-checked with proper locks held further down the line.
1302 if (!cpu_active(arg
.src_cpu
) || !cpu_active(arg
.dst_cpu
))
1305 if (!cpumask_test_cpu(arg
.dst_cpu
, &arg
.src_task
->cpus_allowed
))
1308 if (!cpumask_test_cpu(arg
.src_cpu
, &arg
.dst_task
->cpus_allowed
))
1311 trace_sched_swap_numa(cur
, arg
.src_cpu
, p
, arg
.dst_cpu
);
1312 ret
= stop_two_cpus(arg
.dst_cpu
, arg
.src_cpu
, migrate_swap_stop
, &arg
);
1319 * wait_task_inactive - wait for a thread to unschedule.
1321 * If @match_state is nonzero, it's the @p->state value just checked and
1322 * not expected to change. If it changes, i.e. @p might have woken up,
1323 * then return zero. When we succeed in waiting for @p to be off its CPU,
1324 * we return a positive number (its total switch count). If a second call
1325 * a short while later returns the same number, the caller can be sure that
1326 * @p has remained unscheduled the whole time.
1328 * The caller must ensure that the task *will* unschedule sometime soon,
1329 * else this function might spin for a *long* time. This function can't
1330 * be called with interrupts off, or it may introduce deadlock with
1331 * smp_call_function() if an IPI is sent by the same process we are
1332 * waiting to become inactive.
1334 unsigned long wait_task_inactive(struct task_struct
*p
, long match_state
)
1336 int running
, queued
;
1343 * We do the initial early heuristics without holding
1344 * any task-queue locks at all. We'll only try to get
1345 * the runqueue lock when things look like they will
1351 * If the task is actively running on another CPU
1352 * still, just relax and busy-wait without holding
1355 * NOTE! Since we don't hold any locks, it's not
1356 * even sure that "rq" stays as the right runqueue!
1357 * But we don't care, since "task_running()" will
1358 * return false if the runqueue has changed and p
1359 * is actually now running somewhere else!
1361 while (task_running(rq
, p
)) {
1362 if (match_state
&& unlikely(p
->state
!= match_state
))
1368 * Ok, time to look more closely! We need the rq
1369 * lock now, to be *sure*. If we're wrong, we'll
1370 * just go back and repeat.
1372 rq
= task_rq_lock(p
, &rf
);
1373 trace_sched_wait_task(p
);
1374 running
= task_running(rq
, p
);
1375 queued
= task_on_rq_queued(p
);
1377 if (!match_state
|| p
->state
== match_state
)
1378 ncsw
= p
->nvcsw
| LONG_MIN
; /* sets MSB */
1379 task_rq_unlock(rq
, p
, &rf
);
1382 * If it changed from the expected state, bail out now.
1384 if (unlikely(!ncsw
))
1388 * Was it really running after all now that we
1389 * checked with the proper locks actually held?
1391 * Oops. Go back and try again..
1393 if (unlikely(running
)) {
1399 * It's not enough that it's not actively running,
1400 * it must be off the runqueue _entirely_, and not
1403 * So if it was still runnable (but just not actively
1404 * running right now), it's preempted, and we should
1405 * yield - it could be a while.
1407 if (unlikely(queued
)) {
1408 ktime_t to
= NSEC_PER_SEC
/ HZ
;
1410 set_current_state(TASK_UNINTERRUPTIBLE
);
1411 schedule_hrtimeout(&to
, HRTIMER_MODE_REL
);
1416 * Ahh, all good. It wasn't running, and it wasn't
1417 * runnable, which means that it will never become
1418 * running in the future either. We're all done!
1427 * kick_process - kick a running thread to enter/exit the kernel
1428 * @p: the to-be-kicked thread
1430 * Cause a process which is running on another CPU to enter
1431 * kernel-mode, without any delay. (to get signals handled.)
1433 * NOTE: this function doesn't have to take the runqueue lock,
1434 * because all it wants to ensure is that the remote task enters
1435 * the kernel. If the IPI races and the task has been migrated
1436 * to another CPU then no harm is done and the purpose has been
1439 void kick_process(struct task_struct
*p
)
1445 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1446 smp_send_reschedule(cpu
);
1449 EXPORT_SYMBOL_GPL(kick_process
);
1452 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1454 * A few notes on cpu_active vs cpu_online:
1456 * - cpu_active must be a subset of cpu_online
1458 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1459 * see __set_cpus_allowed_ptr(). At this point the newly online
1460 * CPU isn't yet part of the sched domains, and balancing will not
1463 * - on CPU-down we clear cpu_active() to mask the sched domains and
1464 * avoid the load balancer to place new tasks on the to be removed
1465 * CPU. Existing tasks will remain running there and will be taken
1468 * This means that fallback selection must not select !active CPUs.
1469 * And can assume that any active CPU must be online. Conversely
1470 * select_task_rq() below may allow selection of !active CPUs in order
1471 * to satisfy the above rules.
1473 static int select_fallback_rq(int cpu
, struct task_struct
*p
)
1475 int nid
= cpu_to_node(cpu
);
1476 const struct cpumask
*nodemask
= NULL
;
1477 enum { cpuset
, possible
, fail
} state
= cpuset
;
1481 * If the node that the CPU is on has been offlined, cpu_to_node()
1482 * will return -1. There is no CPU on the node, and we should
1483 * select the CPU on the other node.
1486 nodemask
= cpumask_of_node(nid
);
1488 /* Look for allowed, online CPU in same node. */
1489 for_each_cpu(dest_cpu
, nodemask
) {
1490 if (!cpu_active(dest_cpu
))
1492 if (cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
))
1498 /* Any allowed, online CPU? */
1499 for_each_cpu(dest_cpu
, &p
->cpus_allowed
) {
1500 if (!(p
->flags
& PF_KTHREAD
) && !cpu_active(dest_cpu
))
1502 if (!cpu_online(dest_cpu
))
1507 /* No more Mr. Nice Guy. */
1510 if (IS_ENABLED(CONFIG_CPUSETS
)) {
1511 cpuset_cpus_allowed_fallback(p
);
1517 do_set_cpus_allowed(p
, cpu_possible_mask
);
1528 if (state
!= cpuset
) {
1530 * Don't tell them about moving exiting tasks or
1531 * kernel threads (both mm NULL), since they never
1534 if (p
->mm
&& printk_ratelimit()) {
1535 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1536 task_pid_nr(p
), p
->comm
, cpu
);
1544 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1547 int select_task_rq(struct task_struct
*p
, int cpu
, int sd_flags
, int wake_flags
)
1549 lockdep_assert_held(&p
->pi_lock
);
1551 if (p
->nr_cpus_allowed
> 1)
1552 cpu
= p
->sched_class
->select_task_rq(p
, cpu
, sd_flags
, wake_flags
);
1554 cpu
= cpumask_any(&p
->cpus_allowed
);
1557 * In order not to call set_task_cpu() on a blocking task we need
1558 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1561 * Since this is common to all placement strategies, this lives here.
1563 * [ this allows ->select_task() to simply return task_cpu(p) and
1564 * not worry about this generic constraint ]
1566 if (unlikely(!cpumask_test_cpu(cpu
, &p
->cpus_allowed
) ||
1568 cpu
= select_fallback_rq(task_cpu(p
), p
);
1573 static void update_avg(u64
*avg
, u64 sample
)
1575 s64 diff
= sample
- *avg
;
1579 void sched_set_stop_task(int cpu
, struct task_struct
*stop
)
1581 struct sched_param param
= { .sched_priority
= MAX_RT_PRIO
- 1 };
1582 struct task_struct
*old_stop
= cpu_rq(cpu
)->stop
;
1586 * Make it appear like a SCHED_FIFO task, its something
1587 * userspace knows about and won't get confused about.
1589 * Also, it will make PI more or less work without too
1590 * much confusion -- but then, stop work should not
1591 * rely on PI working anyway.
1593 sched_setscheduler_nocheck(stop
, SCHED_FIFO
, ¶m
);
1595 stop
->sched_class
= &stop_sched_class
;
1598 cpu_rq(cpu
)->stop
= stop
;
1602 * Reset it back to a normal scheduling class so that
1603 * it can die in pieces.
1605 old_stop
->sched_class
= &rt_sched_class
;
1611 static inline int __set_cpus_allowed_ptr(struct task_struct
*p
,
1612 const struct cpumask
*new_mask
, bool check
)
1614 return set_cpus_allowed_ptr(p
, new_mask
);
1617 #endif /* CONFIG_SMP */
1620 ttwu_stat(struct task_struct
*p
, int cpu
, int wake_flags
)
1624 if (!schedstat_enabled())
1630 if (cpu
== rq
->cpu
) {
1631 schedstat_inc(rq
->ttwu_local
);
1632 schedstat_inc(p
->se
.statistics
.nr_wakeups_local
);
1634 struct sched_domain
*sd
;
1636 schedstat_inc(p
->se
.statistics
.nr_wakeups_remote
);
1638 for_each_domain(rq
->cpu
, sd
) {
1639 if (cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
1640 schedstat_inc(sd
->ttwu_wake_remote
);
1647 if (wake_flags
& WF_MIGRATED
)
1648 schedstat_inc(p
->se
.statistics
.nr_wakeups_migrate
);
1649 #endif /* CONFIG_SMP */
1651 schedstat_inc(rq
->ttwu_count
);
1652 schedstat_inc(p
->se
.statistics
.nr_wakeups
);
1654 if (wake_flags
& WF_SYNC
)
1655 schedstat_inc(p
->se
.statistics
.nr_wakeups_sync
);
1658 static inline void ttwu_activate(struct rq
*rq
, struct task_struct
*p
, int en_flags
)
1660 activate_task(rq
, p
, en_flags
);
1661 p
->on_rq
= TASK_ON_RQ_QUEUED
;
1663 /* If a worker is waking up, notify the workqueue: */
1664 if (p
->flags
& PF_WQ_WORKER
)
1665 wq_worker_waking_up(p
, cpu_of(rq
));
1669 * Mark the task runnable and perform wakeup-preemption.
1671 static void ttwu_do_wakeup(struct rq
*rq
, struct task_struct
*p
, int wake_flags
,
1672 struct rq_flags
*rf
)
1674 check_preempt_curr(rq
, p
, wake_flags
);
1675 p
->state
= TASK_RUNNING
;
1676 trace_sched_wakeup(p
);
1679 if (p
->sched_class
->task_woken
) {
1681 * Our task @p is fully woken up and running; so its safe to
1682 * drop the rq->lock, hereafter rq is only used for statistics.
1684 rq_unpin_lock(rq
, rf
);
1685 p
->sched_class
->task_woken(rq
, p
);
1686 rq_repin_lock(rq
, rf
);
1689 if (rq
->idle_stamp
) {
1690 u64 delta
= rq_clock(rq
) - rq
->idle_stamp
;
1691 u64 max
= 2*rq
->max_idle_balance_cost
;
1693 update_avg(&rq
->avg_idle
, delta
);
1695 if (rq
->avg_idle
> max
)
1704 ttwu_do_activate(struct rq
*rq
, struct task_struct
*p
, int wake_flags
,
1705 struct rq_flags
*rf
)
1707 int en_flags
= ENQUEUE_WAKEUP
| ENQUEUE_NOCLOCK
;
1709 lockdep_assert_held(&rq
->lock
);
1712 if (p
->sched_contributes_to_load
)
1713 rq
->nr_uninterruptible
--;
1715 if (wake_flags
& WF_MIGRATED
)
1716 en_flags
|= ENQUEUE_MIGRATED
;
1719 ttwu_activate(rq
, p
, en_flags
);
1720 ttwu_do_wakeup(rq
, p
, wake_flags
, rf
);
1724 * Called in case the task @p isn't fully descheduled from its runqueue,
1725 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1726 * since all we need to do is flip p->state to TASK_RUNNING, since
1727 * the task is still ->on_rq.
1729 static int ttwu_remote(struct task_struct
*p
, int wake_flags
)
1735 rq
= __task_rq_lock(p
, &rf
);
1736 if (task_on_rq_queued(p
)) {
1737 /* check_preempt_curr() may use rq clock */
1738 update_rq_clock(rq
);
1739 ttwu_do_wakeup(rq
, p
, wake_flags
, &rf
);
1742 __task_rq_unlock(rq
, &rf
);
1748 void sched_ttwu_pending(void)
1750 struct rq
*rq
= this_rq();
1751 struct llist_node
*llist
= llist_del_all(&rq
->wake_list
);
1752 struct task_struct
*p
, *t
;
1758 rq_lock_irqsave(rq
, &rf
);
1759 update_rq_clock(rq
);
1761 llist_for_each_entry_safe(p
, t
, llist
, wake_entry
)
1762 ttwu_do_activate(rq
, p
, p
->sched_remote_wakeup
? WF_MIGRATED
: 0, &rf
);
1764 rq_unlock_irqrestore(rq
, &rf
);
1767 void scheduler_ipi(void)
1770 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1771 * TIF_NEED_RESCHED remotely (for the first time) will also send
1774 preempt_fold_need_resched();
1776 if (llist_empty(&this_rq()->wake_list
) && !got_nohz_idle_kick())
1780 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1781 * traditionally all their work was done from the interrupt return
1782 * path. Now that we actually do some work, we need to make sure
1785 * Some archs already do call them, luckily irq_enter/exit nest
1788 * Arguably we should visit all archs and update all handlers,
1789 * however a fair share of IPIs are still resched only so this would
1790 * somewhat pessimize the simple resched case.
1793 sched_ttwu_pending();
1796 * Check if someone kicked us for doing the nohz idle load balance.
1798 if (unlikely(got_nohz_idle_kick())) {
1799 this_rq()->idle_balance
= 1;
1800 raise_softirq_irqoff(SCHED_SOFTIRQ
);
1805 static void ttwu_queue_remote(struct task_struct
*p
, int cpu
, int wake_flags
)
1807 struct rq
*rq
= cpu_rq(cpu
);
1809 p
->sched_remote_wakeup
= !!(wake_flags
& WF_MIGRATED
);
1811 if (llist_add(&p
->wake_entry
, &cpu_rq(cpu
)->wake_list
)) {
1812 if (!set_nr_if_polling(rq
->idle
))
1813 smp_send_reschedule(cpu
);
1815 trace_sched_wake_idle_without_ipi(cpu
);
1819 void wake_up_if_idle(int cpu
)
1821 struct rq
*rq
= cpu_rq(cpu
);
1826 if (!is_idle_task(rcu_dereference(rq
->curr
)))
1829 if (set_nr_if_polling(rq
->idle
)) {
1830 trace_sched_wake_idle_without_ipi(cpu
);
1832 rq_lock_irqsave(rq
, &rf
);
1833 if (is_idle_task(rq
->curr
))
1834 smp_send_reschedule(cpu
);
1835 /* Else CPU is not idle, do nothing here: */
1836 rq_unlock_irqrestore(rq
, &rf
);
1843 bool cpus_share_cache(int this_cpu
, int that_cpu
)
1845 return per_cpu(sd_llc_id
, this_cpu
) == per_cpu(sd_llc_id
, that_cpu
);
1847 #endif /* CONFIG_SMP */
1849 static void ttwu_queue(struct task_struct
*p
, int cpu
, int wake_flags
)
1851 struct rq
*rq
= cpu_rq(cpu
);
1854 #if defined(CONFIG_SMP)
1855 if (sched_feat(TTWU_QUEUE
) && !cpus_share_cache(smp_processor_id(), cpu
)) {
1856 sched_clock_cpu(cpu
); /* Sync clocks across CPUs */
1857 ttwu_queue_remote(p
, cpu
, wake_flags
);
1863 update_rq_clock(rq
);
1864 ttwu_do_activate(rq
, p
, wake_flags
, &rf
);
1869 * Notes on Program-Order guarantees on SMP systems.
1873 * The basic program-order guarantee on SMP systems is that when a task [t]
1874 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1875 * execution on its new CPU [c1].
1877 * For migration (of runnable tasks) this is provided by the following means:
1879 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1880 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1881 * rq(c1)->lock (if not at the same time, then in that order).
1882 * C) LOCK of the rq(c1)->lock scheduling in task
1884 * Transitivity guarantees that B happens after A and C after B.
1885 * Note: we only require RCpc transitivity.
1886 * Note: the CPU doing B need not be c0 or c1
1895 * UNLOCK rq(0)->lock
1897 * LOCK rq(0)->lock // orders against CPU0
1899 * UNLOCK rq(0)->lock
1903 * UNLOCK rq(1)->lock
1905 * LOCK rq(1)->lock // orders against CPU2
1908 * UNLOCK rq(1)->lock
1911 * BLOCKING -- aka. SLEEP + WAKEUP
1913 * For blocking we (obviously) need to provide the same guarantee as for
1914 * migration. However the means are completely different as there is no lock
1915 * chain to provide order. Instead we do:
1917 * 1) smp_store_release(X->on_cpu, 0)
1918 * 2) smp_cond_load_acquire(!X->on_cpu)
1922 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1924 * LOCK rq(0)->lock LOCK X->pi_lock
1927 * smp_store_release(X->on_cpu, 0);
1929 * smp_cond_load_acquire(&X->on_cpu, !VAL);
1935 * X->state = RUNNING
1936 * UNLOCK rq(2)->lock
1938 * LOCK rq(2)->lock // orders against CPU1
1941 * UNLOCK rq(2)->lock
1944 * UNLOCK rq(0)->lock
1947 * However; for wakeups there is a second guarantee we must provide, namely we
1948 * must observe the state that lead to our wakeup. That is, not only must our
1949 * task observe its own prior state, it must also observe the stores prior to
1952 * This means that any means of doing remote wakeups must order the CPU doing
1953 * the wakeup against the CPU the task is going to end up running on. This,
1954 * however, is already required for the regular Program-Order guarantee above,
1955 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
1960 * try_to_wake_up - wake up a thread
1961 * @p: the thread to be awakened
1962 * @state: the mask of task states that can be woken
1963 * @wake_flags: wake modifier flags (WF_*)
1965 * If (@state & @p->state) @p->state = TASK_RUNNING.
1967 * If the task was not queued/runnable, also place it back on a runqueue.
1969 * Atomic against schedule() which would dequeue a task, also see
1970 * set_current_state().
1972 * Return: %true if @p->state changes (an actual wakeup was done),
1976 try_to_wake_up(struct task_struct
*p
, unsigned int state
, int wake_flags
)
1978 unsigned long flags
;
1979 int cpu
, success
= 0;
1982 * If we are going to wake up a thread waiting for CONDITION we
1983 * need to ensure that CONDITION=1 done by the caller can not be
1984 * reordered with p->state check below. This pairs with mb() in
1985 * set_current_state() the waiting thread does.
1987 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
1988 smp_mb__after_spinlock();
1989 if (!(p
->state
& state
))
1992 trace_sched_waking(p
);
1994 /* We're going to change ->state: */
1999 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2000 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2001 * in smp_cond_load_acquire() below.
2003 * sched_ttwu_pending() try_to_wake_up()
2004 * [S] p->on_rq = 1; [L] P->state
2005 * UNLOCK rq->lock -----.
2009 * LOCK rq->lock -----'
2013 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2015 * Pairs with the UNLOCK+LOCK on rq->lock from the
2016 * last wakeup of our task and the schedule that got our task
2020 if (p
->on_rq
&& ttwu_remote(p
, wake_flags
))
2025 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2026 * possible to, falsely, observe p->on_cpu == 0.
2028 * One must be running (->on_cpu == 1) in order to remove oneself
2029 * from the runqueue.
2031 * [S] ->on_cpu = 1; [L] ->on_rq
2035 * [S] ->on_rq = 0; [L] ->on_cpu
2037 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2038 * from the consecutive calls to schedule(); the first switching to our
2039 * task, the second putting it to sleep.
2044 * If the owning (remote) CPU is still in the middle of schedule() with
2045 * this task as prev, wait until its done referencing the task.
2047 * Pairs with the smp_store_release() in finish_lock_switch().
2049 * This ensures that tasks getting woken will be fully ordered against
2050 * their previous state and preserve Program Order.
2052 smp_cond_load_acquire(&p
->on_cpu
, !VAL
);
2054 p
->sched_contributes_to_load
= !!task_contributes_to_load(p
);
2055 p
->state
= TASK_WAKING
;
2058 delayacct_blkio_end();
2059 atomic_dec(&task_rq(p
)->nr_iowait
);
2062 cpu
= select_task_rq(p
, p
->wake_cpu
, SD_BALANCE_WAKE
, wake_flags
);
2063 if (task_cpu(p
) != cpu
) {
2064 wake_flags
|= WF_MIGRATED
;
2065 set_task_cpu(p
, cpu
);
2068 #else /* CONFIG_SMP */
2071 delayacct_blkio_end();
2072 atomic_dec(&task_rq(p
)->nr_iowait
);
2075 #endif /* CONFIG_SMP */
2077 ttwu_queue(p
, cpu
, wake_flags
);
2079 ttwu_stat(p
, cpu
, wake_flags
);
2081 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2087 * try_to_wake_up_local - try to wake up a local task with rq lock held
2088 * @p: the thread to be awakened
2089 * @rf: request-queue flags for pinning
2091 * Put @p on the run-queue if it's not already there. The caller must
2092 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2095 static void try_to_wake_up_local(struct task_struct
*p
, struct rq_flags
*rf
)
2097 struct rq
*rq
= task_rq(p
);
2099 if (WARN_ON_ONCE(rq
!= this_rq()) ||
2100 WARN_ON_ONCE(p
== current
))
2103 lockdep_assert_held(&rq
->lock
);
2105 if (!raw_spin_trylock(&p
->pi_lock
)) {
2107 * This is OK, because current is on_cpu, which avoids it being
2108 * picked for load-balance and preemption/IRQs are still
2109 * disabled avoiding further scheduler activity on it and we've
2110 * not yet picked a replacement task.
2113 raw_spin_lock(&p
->pi_lock
);
2117 if (!(p
->state
& TASK_NORMAL
))
2120 trace_sched_waking(p
);
2122 if (!task_on_rq_queued(p
)) {
2124 delayacct_blkio_end();
2125 atomic_dec(&rq
->nr_iowait
);
2127 ttwu_activate(rq
, p
, ENQUEUE_WAKEUP
| ENQUEUE_NOCLOCK
);
2130 ttwu_do_wakeup(rq
, p
, 0, rf
);
2131 ttwu_stat(p
, smp_processor_id(), 0);
2133 raw_spin_unlock(&p
->pi_lock
);
2137 * wake_up_process - Wake up a specific process
2138 * @p: The process to be woken up.
2140 * Attempt to wake up the nominated process and move it to the set of runnable
2143 * Return: 1 if the process was woken up, 0 if it was already running.
2145 * It may be assumed that this function implies a write memory barrier before
2146 * changing the task state if and only if any tasks are woken up.
2148 int wake_up_process(struct task_struct
*p
)
2150 return try_to_wake_up(p
, TASK_NORMAL
, 0);
2152 EXPORT_SYMBOL(wake_up_process
);
2154 int wake_up_state(struct task_struct
*p
, unsigned int state
)
2156 return try_to_wake_up(p
, state
, 0);
2160 * Perform scheduler related setup for a newly forked process p.
2161 * p is forked by current.
2163 * __sched_fork() is basic setup used by init_idle() too:
2165 static void __sched_fork(unsigned long clone_flags
, struct task_struct
*p
)
2170 p
->se
.exec_start
= 0;
2171 p
->se
.sum_exec_runtime
= 0;
2172 p
->se
.prev_sum_exec_runtime
= 0;
2173 p
->se
.nr_migrations
= 0;
2175 INIT_LIST_HEAD(&p
->se
.group_node
);
2177 #ifdef CONFIG_FAIR_GROUP_SCHED
2178 p
->se
.cfs_rq
= NULL
;
2181 #ifdef CONFIG_SCHEDSTATS
2182 /* Even if schedstat is disabled, there should not be garbage */
2183 memset(&p
->se
.statistics
, 0, sizeof(p
->se
.statistics
));
2186 RB_CLEAR_NODE(&p
->dl
.rb_node
);
2187 init_dl_task_timer(&p
->dl
);
2188 init_dl_inactive_task_timer(&p
->dl
);
2189 __dl_clear_params(p
);
2191 INIT_LIST_HEAD(&p
->rt
.run_list
);
2193 p
->rt
.time_slice
= sched_rr_timeslice
;
2197 #ifdef CONFIG_PREEMPT_NOTIFIERS
2198 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
2201 #ifdef CONFIG_NUMA_BALANCING
2202 if (p
->mm
&& atomic_read(&p
->mm
->mm_users
) == 1) {
2203 p
->mm
->numa_next_scan
= jiffies
+ msecs_to_jiffies(sysctl_numa_balancing_scan_delay
);
2204 p
->mm
->numa_scan_seq
= 0;
2207 if (clone_flags
& CLONE_VM
)
2208 p
->numa_preferred_nid
= current
->numa_preferred_nid
;
2210 p
->numa_preferred_nid
= -1;
2212 p
->node_stamp
= 0ULL;
2213 p
->numa_scan_seq
= p
->mm
? p
->mm
->numa_scan_seq
: 0;
2214 p
->numa_scan_period
= sysctl_numa_balancing_scan_delay
;
2215 p
->numa_work
.next
= &p
->numa_work
;
2216 p
->numa_faults
= NULL
;
2217 p
->last_task_numa_placement
= 0;
2218 p
->last_sum_exec_runtime
= 0;
2220 p
->numa_group
= NULL
;
2221 #endif /* CONFIG_NUMA_BALANCING */
2224 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing
);
2226 #ifdef CONFIG_NUMA_BALANCING
2228 void set_numabalancing_state(bool enabled
)
2231 static_branch_enable(&sched_numa_balancing
);
2233 static_branch_disable(&sched_numa_balancing
);
2236 #ifdef CONFIG_PROC_SYSCTL
2237 int sysctl_numa_balancing(struct ctl_table
*table
, int write
,
2238 void __user
*buffer
, size_t *lenp
, loff_t
*ppos
)
2242 int state
= static_branch_likely(&sched_numa_balancing
);
2244 if (write
&& !capable(CAP_SYS_ADMIN
))
2249 err
= proc_dointvec_minmax(&t
, write
, buffer
, lenp
, ppos
);
2253 set_numabalancing_state(state
);
2259 #ifdef CONFIG_SCHEDSTATS
2261 DEFINE_STATIC_KEY_FALSE(sched_schedstats
);
2262 static bool __initdata __sched_schedstats
= false;
2264 static void set_schedstats(bool enabled
)
2267 static_branch_enable(&sched_schedstats
);
2269 static_branch_disable(&sched_schedstats
);
2272 void force_schedstat_enabled(void)
2274 if (!schedstat_enabled()) {
2275 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2276 static_branch_enable(&sched_schedstats
);
2280 static int __init
setup_schedstats(char *str
)
2287 * This code is called before jump labels have been set up, so we can't
2288 * change the static branch directly just yet. Instead set a temporary
2289 * variable so init_schedstats() can do it later.
2291 if (!strcmp(str
, "enable")) {
2292 __sched_schedstats
= true;
2294 } else if (!strcmp(str
, "disable")) {
2295 __sched_schedstats
= false;
2300 pr_warn("Unable to parse schedstats=\n");
2304 __setup("schedstats=", setup_schedstats
);
2306 static void __init
init_schedstats(void)
2308 set_schedstats(__sched_schedstats
);
2311 #ifdef CONFIG_PROC_SYSCTL
2312 int sysctl_schedstats(struct ctl_table
*table
, int write
,
2313 void __user
*buffer
, size_t *lenp
, loff_t
*ppos
)
2317 int state
= static_branch_likely(&sched_schedstats
);
2319 if (write
&& !capable(CAP_SYS_ADMIN
))
2324 err
= proc_dointvec_minmax(&t
, write
, buffer
, lenp
, ppos
);
2328 set_schedstats(state
);
2331 #endif /* CONFIG_PROC_SYSCTL */
2332 #else /* !CONFIG_SCHEDSTATS */
2333 static inline void init_schedstats(void) {}
2334 #endif /* CONFIG_SCHEDSTATS */
2337 * fork()/clone()-time setup:
2339 int sched_fork(unsigned long clone_flags
, struct task_struct
*p
)
2341 unsigned long flags
;
2342 int cpu
= get_cpu();
2344 __sched_fork(clone_flags
, p
);
2346 * We mark the process as NEW here. This guarantees that
2347 * nobody will actually run it, and a signal or other external
2348 * event cannot wake it up and insert it on the runqueue either.
2350 p
->state
= TASK_NEW
;
2353 * Make sure we do not leak PI boosting priority to the child.
2355 p
->prio
= current
->normal_prio
;
2358 * Revert to default priority/policy on fork if requested.
2360 if (unlikely(p
->sched_reset_on_fork
)) {
2361 if (task_has_dl_policy(p
) || task_has_rt_policy(p
)) {
2362 p
->policy
= SCHED_NORMAL
;
2363 p
->static_prio
= NICE_TO_PRIO(0);
2365 } else if (PRIO_TO_NICE(p
->static_prio
) < 0)
2366 p
->static_prio
= NICE_TO_PRIO(0);
2368 p
->prio
= p
->normal_prio
= __normal_prio(p
);
2369 set_load_weight(p
, false);
2372 * We don't need the reset flag anymore after the fork. It has
2373 * fulfilled its duty:
2375 p
->sched_reset_on_fork
= 0;
2378 if (dl_prio(p
->prio
)) {
2381 } else if (rt_prio(p
->prio
)) {
2382 p
->sched_class
= &rt_sched_class
;
2384 p
->sched_class
= &fair_sched_class
;
2387 init_entity_runnable_average(&p
->se
);
2390 * The child is not yet in the pid-hash so no cgroup attach races,
2391 * and the cgroup is pinned to this child due to cgroup_fork()
2392 * is ran before sched_fork().
2394 * Silence PROVE_RCU.
2396 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
2398 * We're setting the CPU for the first time, we don't migrate,
2399 * so use __set_task_cpu().
2401 __set_task_cpu(p
, cpu
);
2402 if (p
->sched_class
->task_fork
)
2403 p
->sched_class
->task_fork(p
);
2404 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2406 #ifdef CONFIG_SCHED_INFO
2407 if (likely(sched_info_on()))
2408 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
2410 #if defined(CONFIG_SMP)
2413 init_task_preempt_count(p
);
2415 plist_node_init(&p
->pushable_tasks
, MAX_PRIO
);
2416 RB_CLEAR_NODE(&p
->pushable_dl_tasks
);
2423 unsigned long to_ratio(u64 period
, u64 runtime
)
2425 if (runtime
== RUNTIME_INF
)
2429 * Doing this here saves a lot of checks in all
2430 * the calling paths, and returning zero seems
2431 * safe for them anyway.
2436 return div64_u64(runtime
<< BW_SHIFT
, period
);
2440 * wake_up_new_task - wake up a newly created task for the first time.
2442 * This function will do some initial scheduler statistics housekeeping
2443 * that must be done for every newly created context, then puts the task
2444 * on the runqueue and wakes it.
2446 void wake_up_new_task(struct task_struct
*p
)
2451 raw_spin_lock_irqsave(&p
->pi_lock
, rf
.flags
);
2452 p
->state
= TASK_RUNNING
;
2455 * Fork balancing, do it here and not earlier because:
2456 * - cpus_allowed can change in the fork path
2457 * - any previously selected CPU might disappear through hotplug
2459 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2460 * as we're not fully set-up yet.
2462 __set_task_cpu(p
, select_task_rq(p
, task_cpu(p
), SD_BALANCE_FORK
, 0));
2464 rq
= __task_rq_lock(p
, &rf
);
2465 update_rq_clock(rq
);
2466 post_init_entity_util_avg(&p
->se
);
2468 activate_task(rq
, p
, ENQUEUE_NOCLOCK
);
2469 p
->on_rq
= TASK_ON_RQ_QUEUED
;
2470 trace_sched_wakeup_new(p
);
2471 check_preempt_curr(rq
, p
, WF_FORK
);
2473 if (p
->sched_class
->task_woken
) {
2475 * Nothing relies on rq->lock after this, so its fine to
2478 rq_unpin_lock(rq
, &rf
);
2479 p
->sched_class
->task_woken(rq
, p
);
2480 rq_repin_lock(rq
, &rf
);
2483 task_rq_unlock(rq
, p
, &rf
);
2486 #ifdef CONFIG_PREEMPT_NOTIFIERS
2488 static struct static_key preempt_notifier_key
= STATIC_KEY_INIT_FALSE
;
2490 void preempt_notifier_inc(void)
2492 static_key_slow_inc(&preempt_notifier_key
);
2494 EXPORT_SYMBOL_GPL(preempt_notifier_inc
);
2496 void preempt_notifier_dec(void)
2498 static_key_slow_dec(&preempt_notifier_key
);
2500 EXPORT_SYMBOL_GPL(preempt_notifier_dec
);
2503 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2504 * @notifier: notifier struct to register
2506 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2508 if (!static_key_false(&preempt_notifier_key
))
2509 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2511 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2513 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2516 * preempt_notifier_unregister - no longer interested in preemption notifications
2517 * @notifier: notifier struct to unregister
2519 * This is *not* safe to call from within a preemption notifier.
2521 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2523 hlist_del(¬ifier
->link
);
2525 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2527 static void __fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2529 struct preempt_notifier
*notifier
;
2531 hlist_for_each_entry(notifier
, &curr
->preempt_notifiers
, link
)
2532 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2535 static __always_inline
void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2537 if (static_key_false(&preempt_notifier_key
))
2538 __fire_sched_in_preempt_notifiers(curr
);
2542 __fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2543 struct task_struct
*next
)
2545 struct preempt_notifier
*notifier
;
2547 hlist_for_each_entry(notifier
, &curr
->preempt_notifiers
, link
)
2548 notifier
->ops
->sched_out(notifier
, next
);
2551 static __always_inline
void
2552 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2553 struct task_struct
*next
)
2555 if (static_key_false(&preempt_notifier_key
))
2556 __fire_sched_out_preempt_notifiers(curr
, next
);
2559 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2561 static inline void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2566 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2567 struct task_struct
*next
)
2571 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2574 * prepare_task_switch - prepare to switch tasks
2575 * @rq: the runqueue preparing to switch
2576 * @prev: the current task that is being switched out
2577 * @next: the task we are going to switch to.
2579 * This is called with the rq lock held and interrupts off. It must
2580 * be paired with a subsequent finish_task_switch after the context
2583 * prepare_task_switch sets up locking and calls architecture specific
2587 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2588 struct task_struct
*next
)
2590 sched_info_switch(rq
, prev
, next
);
2591 perf_event_task_sched_out(prev
, next
);
2592 fire_sched_out_preempt_notifiers(prev
, next
);
2593 prepare_lock_switch(rq
, next
);
2594 prepare_arch_switch(next
);
2598 * finish_task_switch - clean up after a task-switch
2599 * @prev: the thread we just switched away from.
2601 * finish_task_switch must be called after the context switch, paired
2602 * with a prepare_task_switch call before the context switch.
2603 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2604 * and do any other architecture-specific cleanup actions.
2606 * Note that we may have delayed dropping an mm in context_switch(). If
2607 * so, we finish that here outside of the runqueue lock. (Doing it
2608 * with the lock held can cause deadlocks; see schedule() for
2611 * The context switch have flipped the stack from under us and restored the
2612 * local variables which were saved when this task called schedule() in the
2613 * past. prev == current is still correct but we need to recalculate this_rq
2614 * because prev may have moved to another CPU.
2616 static struct rq
*finish_task_switch(struct task_struct
*prev
)
2617 __releases(rq
->lock
)
2619 struct rq
*rq
= this_rq();
2620 struct mm_struct
*mm
= rq
->prev_mm
;
2624 * The previous task will have left us with a preempt_count of 2
2625 * because it left us after:
2628 * preempt_disable(); // 1
2630 * raw_spin_lock_irq(&rq->lock) // 2
2632 * Also, see FORK_PREEMPT_COUNT.
2634 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET
,
2635 "corrupted preempt_count: %s/%d/0x%x\n",
2636 current
->comm
, current
->pid
, preempt_count()))
2637 preempt_count_set(FORK_PREEMPT_COUNT
);
2642 * A task struct has one reference for the use as "current".
2643 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2644 * schedule one last time. The schedule call will never return, and
2645 * the scheduled task must drop that reference.
2647 * We must observe prev->state before clearing prev->on_cpu (in
2648 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2649 * running on another CPU and we could rave with its RUNNING -> DEAD
2650 * transition, resulting in a double drop.
2652 prev_state
= prev
->state
;
2653 vtime_task_switch(prev
);
2654 perf_event_task_sched_in(prev
, current
);
2656 * The membarrier system call requires a full memory barrier
2657 * after storing to rq->curr, before going back to user-space.
2659 * TODO: This smp_mb__after_unlock_lock can go away if PPC end
2660 * up adding a full barrier to switch_mm(), or we should figure
2661 * out if a smp_mb__after_unlock_lock is really the proper API
2664 smp_mb__after_unlock_lock();
2665 finish_lock_switch(rq
, prev
);
2666 finish_arch_post_lock_switch();
2668 fire_sched_in_preempt_notifiers(current
);
2671 if (unlikely(prev_state
== TASK_DEAD
)) {
2672 if (prev
->sched_class
->task_dead
)
2673 prev
->sched_class
->task_dead(prev
);
2676 * Remove function-return probe instances associated with this
2677 * task and put them back on the free list.
2679 kprobe_flush_task(prev
);
2681 /* Task is done with its stack. */
2682 put_task_stack(prev
);
2684 put_task_struct(prev
);
2687 tick_nohz_task_switch();
2693 /* rq->lock is NOT held, but preemption is disabled */
2694 static void __balance_callback(struct rq
*rq
)
2696 struct callback_head
*head
, *next
;
2697 void (*func
)(struct rq
*rq
);
2698 unsigned long flags
;
2700 raw_spin_lock_irqsave(&rq
->lock
, flags
);
2701 head
= rq
->balance_callback
;
2702 rq
->balance_callback
= NULL
;
2704 func
= (void (*)(struct rq
*))head
->func
;
2711 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
2714 static inline void balance_callback(struct rq
*rq
)
2716 if (unlikely(rq
->balance_callback
))
2717 __balance_callback(rq
);
2722 static inline void balance_callback(struct rq
*rq
)
2729 * schedule_tail - first thing a freshly forked thread must call.
2730 * @prev: the thread we just switched away from.
2732 asmlinkage __visible
void schedule_tail(struct task_struct
*prev
)
2733 __releases(rq
->lock
)
2738 * New tasks start with FORK_PREEMPT_COUNT, see there and
2739 * finish_task_switch() for details.
2741 * finish_task_switch() will drop rq->lock() and lower preempt_count
2742 * and the preempt_enable() will end up enabling preemption (on
2743 * PREEMPT_COUNT kernels).
2746 rq
= finish_task_switch(prev
);
2747 balance_callback(rq
);
2750 if (current
->set_child_tid
)
2751 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2755 * context_switch - switch to the new MM and the new thread's register state.
2757 static __always_inline
struct rq
*
2758 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2759 struct task_struct
*next
, struct rq_flags
*rf
)
2761 struct mm_struct
*mm
, *oldmm
;
2763 prepare_task_switch(rq
, prev
, next
);
2766 oldmm
= prev
->active_mm
;
2768 * For paravirt, this is coupled with an exit in switch_to to
2769 * combine the page table reload and the switch backend into
2772 arch_start_context_switch(prev
);
2775 next
->active_mm
= oldmm
;
2777 enter_lazy_tlb(oldmm
, next
);
2779 switch_mm_irqs_off(oldmm
, mm
, next
);
2782 prev
->active_mm
= NULL
;
2783 rq
->prev_mm
= oldmm
;
2786 rq
->clock_update_flags
&= ~(RQCF_ACT_SKIP
|RQCF_REQ_SKIP
);
2789 * Since the runqueue lock will be released by the next
2790 * task (which is an invalid locking op but in the case
2791 * of the scheduler it's an obvious special-case), so we
2792 * do an early lockdep release here:
2794 rq_unpin_lock(rq
, rf
);
2795 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2797 /* Here we just switch the register state and the stack. */
2798 switch_to(prev
, next
, prev
);
2801 return finish_task_switch(prev
);
2805 * nr_running and nr_context_switches:
2807 * externally visible scheduler statistics: current number of runnable
2808 * threads, total number of context switches performed since bootup.
2810 unsigned long nr_running(void)
2812 unsigned long i
, sum
= 0;
2814 for_each_online_cpu(i
)
2815 sum
+= cpu_rq(i
)->nr_running
;
2821 * Check if only the current task is running on the CPU.
2823 * Caution: this function does not check that the caller has disabled
2824 * preemption, thus the result might have a time-of-check-to-time-of-use
2825 * race. The caller is responsible to use it correctly, for example:
2827 * - from a non-preemptable section (of course)
2829 * - from a thread that is bound to a single CPU
2831 * - in a loop with very short iterations (e.g. a polling loop)
2833 bool single_task_running(void)
2835 return raw_rq()->nr_running
== 1;
2837 EXPORT_SYMBOL(single_task_running
);
2839 unsigned long long nr_context_switches(void)
2842 unsigned long long sum
= 0;
2844 for_each_possible_cpu(i
)
2845 sum
+= cpu_rq(i
)->nr_switches
;
2851 * IO-wait accounting, and how its mostly bollocks (on SMP).
2853 * The idea behind IO-wait account is to account the idle time that we could
2854 * have spend running if it were not for IO. That is, if we were to improve the
2855 * storage performance, we'd have a proportional reduction in IO-wait time.
2857 * This all works nicely on UP, where, when a task blocks on IO, we account
2858 * idle time as IO-wait, because if the storage were faster, it could've been
2859 * running and we'd not be idle.
2861 * This has been extended to SMP, by doing the same for each CPU. This however
2864 * Imagine for instance the case where two tasks block on one CPU, only the one
2865 * CPU will have IO-wait accounted, while the other has regular idle. Even
2866 * though, if the storage were faster, both could've ran at the same time,
2867 * utilising both CPUs.
2869 * This means, that when looking globally, the current IO-wait accounting on
2870 * SMP is a lower bound, by reason of under accounting.
2872 * Worse, since the numbers are provided per CPU, they are sometimes
2873 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2874 * associated with any one particular CPU, it can wake to another CPU than it
2875 * blocked on. This means the per CPU IO-wait number is meaningless.
2877 * Task CPU affinities can make all that even more 'interesting'.
2880 unsigned long nr_iowait(void)
2882 unsigned long i
, sum
= 0;
2884 for_each_possible_cpu(i
)
2885 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2891 * Consumers of these two interfaces, like for example the cpufreq menu
2892 * governor are using nonsensical data. Boosting frequency for a CPU that has
2893 * IO-wait which might not even end up running the task when it does become
2897 unsigned long nr_iowait_cpu(int cpu
)
2899 struct rq
*this = cpu_rq(cpu
);
2900 return atomic_read(&this->nr_iowait
);
2903 void get_iowait_load(unsigned long *nr_waiters
, unsigned long *load
)
2905 struct rq
*rq
= this_rq();
2906 *nr_waiters
= atomic_read(&rq
->nr_iowait
);
2907 *load
= rq
->load
.weight
;
2913 * sched_exec - execve() is a valuable balancing opportunity, because at
2914 * this point the task has the smallest effective memory and cache footprint.
2916 void sched_exec(void)
2918 struct task_struct
*p
= current
;
2919 unsigned long flags
;
2922 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
2923 dest_cpu
= p
->sched_class
->select_task_rq(p
, task_cpu(p
), SD_BALANCE_EXEC
, 0);
2924 if (dest_cpu
== smp_processor_id())
2927 if (likely(cpu_active(dest_cpu
))) {
2928 struct migration_arg arg
= { p
, dest_cpu
};
2930 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2931 stop_one_cpu(task_cpu(p
), migration_cpu_stop
, &arg
);
2935 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2940 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
2941 DEFINE_PER_CPU(struct kernel_cpustat
, kernel_cpustat
);
2943 EXPORT_PER_CPU_SYMBOL(kstat
);
2944 EXPORT_PER_CPU_SYMBOL(kernel_cpustat
);
2947 * The function fair_sched_class.update_curr accesses the struct curr
2948 * and its field curr->exec_start; when called from task_sched_runtime(),
2949 * we observe a high rate of cache misses in practice.
2950 * Prefetching this data results in improved performance.
2952 static inline void prefetch_curr_exec_start(struct task_struct
*p
)
2954 #ifdef CONFIG_FAIR_GROUP_SCHED
2955 struct sched_entity
*curr
= (&p
->se
)->cfs_rq
->curr
;
2957 struct sched_entity
*curr
= (&task_rq(p
)->cfs
)->curr
;
2960 prefetch(&curr
->exec_start
);
2964 * Return accounted runtime for the task.
2965 * In case the task is currently running, return the runtime plus current's
2966 * pending runtime that have not been accounted yet.
2968 unsigned long long task_sched_runtime(struct task_struct
*p
)
2974 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
2976 * 64-bit doesn't need locks to atomically read a 64bit value.
2977 * So we have a optimization chance when the task's delta_exec is 0.
2978 * Reading ->on_cpu is racy, but this is ok.
2980 * If we race with it leaving CPU, we'll take a lock. So we're correct.
2981 * If we race with it entering CPU, unaccounted time is 0. This is
2982 * indistinguishable from the read occurring a few cycles earlier.
2983 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
2984 * been accounted, so we're correct here as well.
2986 if (!p
->on_cpu
|| !task_on_rq_queued(p
))
2987 return p
->se
.sum_exec_runtime
;
2990 rq
= task_rq_lock(p
, &rf
);
2992 * Must be ->curr _and_ ->on_rq. If dequeued, we would
2993 * project cycles that may never be accounted to this
2994 * thread, breaking clock_gettime().
2996 if (task_current(rq
, p
) && task_on_rq_queued(p
)) {
2997 prefetch_curr_exec_start(p
);
2998 update_rq_clock(rq
);
2999 p
->sched_class
->update_curr(rq
);
3001 ns
= p
->se
.sum_exec_runtime
;
3002 task_rq_unlock(rq
, p
, &rf
);
3008 * This function gets called by the timer code, with HZ frequency.
3009 * We call it with interrupts disabled.
3011 void scheduler_tick(void)
3013 int cpu
= smp_processor_id();
3014 struct rq
*rq
= cpu_rq(cpu
);
3015 struct task_struct
*curr
= rq
->curr
;
3022 update_rq_clock(rq
);
3023 curr
->sched_class
->task_tick(rq
, curr
, 0);
3024 cpu_load_update_active(rq
);
3025 calc_global_load_tick(rq
);
3029 perf_event_task_tick();
3032 rq
->idle_balance
= idle_cpu(cpu
);
3033 trigger_load_balance(rq
);
3035 rq_last_tick_reset(rq
);
3038 #ifdef CONFIG_NO_HZ_FULL
3040 * scheduler_tick_max_deferment
3042 * Keep at least one tick per second when a single
3043 * active task is running because the scheduler doesn't
3044 * yet completely support full dynticks environment.
3046 * This makes sure that uptime, CFS vruntime, load
3047 * balancing, etc... continue to move forward, even
3048 * with a very low granularity.
3050 * Return: Maximum deferment in nanoseconds.
3052 u64
scheduler_tick_max_deferment(void)
3054 struct rq
*rq
= this_rq();
3055 unsigned long next
, now
= READ_ONCE(jiffies
);
3057 next
= rq
->last_sched_tick
+ HZ
;
3059 if (time_before_eq(next
, now
))
3062 return jiffies_to_nsecs(next
- now
);
3066 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3067 defined(CONFIG_PREEMPT_TRACER))
3069 * If the value passed in is equal to the current preempt count
3070 * then we just disabled preemption. Start timing the latency.
3072 static inline void preempt_latency_start(int val
)
3074 if (preempt_count() == val
) {
3075 unsigned long ip
= get_lock_parent_ip();
3076 #ifdef CONFIG_DEBUG_PREEMPT
3077 current
->preempt_disable_ip
= ip
;
3079 trace_preempt_off(CALLER_ADDR0
, ip
);
3083 void preempt_count_add(int val
)
3085 #ifdef CONFIG_DEBUG_PREEMPT
3089 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3092 __preempt_count_add(val
);
3093 #ifdef CONFIG_DEBUG_PREEMPT
3095 * Spinlock count overflowing soon?
3097 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
3100 preempt_latency_start(val
);
3102 EXPORT_SYMBOL(preempt_count_add
);
3103 NOKPROBE_SYMBOL(preempt_count_add
);
3106 * If the value passed in equals to the current preempt count
3107 * then we just enabled preemption. Stop timing the latency.
3109 static inline void preempt_latency_stop(int val
)
3111 if (preempt_count() == val
)
3112 trace_preempt_on(CALLER_ADDR0
, get_lock_parent_ip());
3115 void preempt_count_sub(int val
)
3117 #ifdef CONFIG_DEBUG_PREEMPT
3121 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3124 * Is the spinlock portion underflowing?
3126 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3127 !(preempt_count() & PREEMPT_MASK
)))
3131 preempt_latency_stop(val
);
3132 __preempt_count_sub(val
);
3134 EXPORT_SYMBOL(preempt_count_sub
);
3135 NOKPROBE_SYMBOL(preempt_count_sub
);
3138 static inline void preempt_latency_start(int val
) { }
3139 static inline void preempt_latency_stop(int val
) { }
3142 static inline unsigned long get_preempt_disable_ip(struct task_struct
*p
)
3144 #ifdef CONFIG_DEBUG_PREEMPT
3145 return p
->preempt_disable_ip
;
3152 * Print scheduling while atomic bug:
3154 static noinline
void __schedule_bug(struct task_struct
*prev
)
3156 /* Save this before calling printk(), since that will clobber it */
3157 unsigned long preempt_disable_ip
= get_preempt_disable_ip(current
);
3159 if (oops_in_progress
)
3162 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
3163 prev
->comm
, prev
->pid
, preempt_count());
3165 debug_show_held_locks(prev
);
3167 if (irqs_disabled())
3168 print_irqtrace_events(prev
);
3169 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT
)
3170 && in_atomic_preempt_off()) {
3171 pr_err("Preemption disabled at:");
3172 print_ip_sym(preempt_disable_ip
);
3176 panic("scheduling while atomic\n");
3179 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
3183 * Various schedule()-time debugging checks and statistics:
3185 static inline void schedule_debug(struct task_struct
*prev
)
3187 #ifdef CONFIG_SCHED_STACK_END_CHECK
3188 if (task_stack_end_corrupted(prev
))
3189 panic("corrupted stack end detected inside scheduler\n");
3192 if (unlikely(in_atomic_preempt_off())) {
3193 __schedule_bug(prev
);
3194 preempt_count_set(PREEMPT_DISABLED
);
3198 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3200 schedstat_inc(this_rq()->sched_count
);
3204 * Pick up the highest-prio task:
3206 static inline struct task_struct
*
3207 pick_next_task(struct rq
*rq
, struct task_struct
*prev
, struct rq_flags
*rf
)
3209 const struct sched_class
*class;
3210 struct task_struct
*p
;
3213 * Optimization: we know that if all tasks are in the fair class we can
3214 * call that function directly, but only if the @prev task wasn't of a
3215 * higher scheduling class, because otherwise those loose the
3216 * opportunity to pull in more work from other CPUs.
3218 if (likely((prev
->sched_class
== &idle_sched_class
||
3219 prev
->sched_class
== &fair_sched_class
) &&
3220 rq
->nr_running
== rq
->cfs
.h_nr_running
)) {
3222 p
= fair_sched_class
.pick_next_task(rq
, prev
, rf
);
3223 if (unlikely(p
== RETRY_TASK
))
3226 /* Assumes fair_sched_class->next == idle_sched_class */
3228 p
= idle_sched_class
.pick_next_task(rq
, prev
, rf
);
3234 for_each_class(class) {
3235 p
= class->pick_next_task(rq
, prev
, rf
);
3237 if (unlikely(p
== RETRY_TASK
))
3243 /* The idle class should always have a runnable task: */
3248 * __schedule() is the main scheduler function.
3250 * The main means of driving the scheduler and thus entering this function are:
3252 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3254 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3255 * paths. For example, see arch/x86/entry_64.S.
3257 * To drive preemption between tasks, the scheduler sets the flag in timer
3258 * interrupt handler scheduler_tick().
3260 * 3. Wakeups don't really cause entry into schedule(). They add a
3261 * task to the run-queue and that's it.
3263 * Now, if the new task added to the run-queue preempts the current
3264 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3265 * called on the nearest possible occasion:
3267 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3269 * - in syscall or exception context, at the next outmost
3270 * preempt_enable(). (this might be as soon as the wake_up()'s
3273 * - in IRQ context, return from interrupt-handler to
3274 * preemptible context
3276 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3279 * - cond_resched() call
3280 * - explicit schedule() call
3281 * - return from syscall or exception to user-space
3282 * - return from interrupt-handler to user-space
3284 * WARNING: must be called with preemption disabled!
3286 static void __sched notrace
__schedule(bool preempt
)
3288 struct task_struct
*prev
, *next
;
3289 unsigned long *switch_count
;
3294 cpu
= smp_processor_id();
3298 schedule_debug(prev
);
3300 if (sched_feat(HRTICK
))
3303 local_irq_disable();
3304 rcu_note_context_switch(preempt
);
3307 * Make sure that signal_pending_state()->signal_pending() below
3308 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3309 * done by the caller to avoid the race with signal_wake_up().
3312 smp_mb__after_spinlock();
3314 /* Promote REQ to ACT */
3315 rq
->clock_update_flags
<<= 1;
3316 update_rq_clock(rq
);
3318 switch_count
= &prev
->nivcsw
;
3319 if (!preempt
&& prev
->state
) {
3320 if (unlikely(signal_pending_state(prev
->state
, prev
))) {
3321 prev
->state
= TASK_RUNNING
;
3323 deactivate_task(rq
, prev
, DEQUEUE_SLEEP
| DEQUEUE_NOCLOCK
);
3326 if (prev
->in_iowait
) {
3327 atomic_inc(&rq
->nr_iowait
);
3328 delayacct_blkio_start();
3332 * If a worker went to sleep, notify and ask workqueue
3333 * whether it wants to wake up a task to maintain
3336 if (prev
->flags
& PF_WQ_WORKER
) {
3337 struct task_struct
*to_wakeup
;
3339 to_wakeup
= wq_worker_sleeping(prev
);
3341 try_to_wake_up_local(to_wakeup
, &rf
);
3344 switch_count
= &prev
->nvcsw
;
3347 next
= pick_next_task(rq
, prev
, &rf
);
3348 clear_tsk_need_resched(prev
);
3349 clear_preempt_need_resched();
3351 if (likely(prev
!= next
)) {
3355 * The membarrier system call requires each architecture
3356 * to have a full memory barrier after updating
3357 * rq->curr, before returning to user-space. For TSO
3358 * (e.g. x86), the architecture must provide its own
3359 * barrier in switch_mm(). For weakly ordered machines
3360 * for which spin_unlock() acts as a full memory
3361 * barrier, finish_lock_switch() in common code takes
3362 * care of this barrier. For weakly ordered machines for
3363 * which spin_unlock() acts as a RELEASE barrier (only
3364 * arm64 and PowerPC), arm64 has a full barrier in
3365 * switch_to(), and PowerPC has
3366 * smp_mb__after_unlock_lock() before
3367 * finish_lock_switch().
3371 trace_sched_switch(preempt
, prev
, next
);
3373 /* Also unlocks the rq: */
3374 rq
= context_switch(rq
, prev
, next
, &rf
);
3376 rq
->clock_update_flags
&= ~(RQCF_ACT_SKIP
|RQCF_REQ_SKIP
);
3377 rq_unlock_irq(rq
, &rf
);
3380 balance_callback(rq
);
3383 void __noreturn
do_task_dead(void)
3386 * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
3387 * when the following two conditions become true.
3388 * - There is race condition of mmap_sem (It is acquired by
3390 * - SMI occurs before setting TASK_RUNINNG.
3391 * (or hypervisor of virtual machine switches to other guest)
3392 * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
3394 * To avoid it, we have to wait for releasing tsk->pi_lock which
3395 * is held by try_to_wake_up()
3397 raw_spin_lock_irq(¤t
->pi_lock
);
3398 raw_spin_unlock_irq(¤t
->pi_lock
);
3400 /* Causes final put_task_struct in finish_task_switch(): */
3401 __set_current_state(TASK_DEAD
);
3403 /* Tell freezer to ignore us: */
3404 current
->flags
|= PF_NOFREEZE
;
3409 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
3414 static inline void sched_submit_work(struct task_struct
*tsk
)
3416 if (!tsk
->state
|| tsk_is_pi_blocked(tsk
))
3419 * If we are going to sleep and we have plugged IO queued,
3420 * make sure to submit it to avoid deadlocks.
3422 if (blk_needs_flush_plug(tsk
))
3423 blk_schedule_flush_plug(tsk
);
3426 asmlinkage __visible
void __sched
schedule(void)
3428 struct task_struct
*tsk
= current
;
3430 sched_submit_work(tsk
);
3434 sched_preempt_enable_no_resched();
3435 } while (need_resched());
3437 EXPORT_SYMBOL(schedule
);
3440 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3441 * state (have scheduled out non-voluntarily) by making sure that all
3442 * tasks have either left the run queue or have gone into user space.
3443 * As idle tasks do not do either, they must not ever be preempted
3444 * (schedule out non-voluntarily).
3446 * schedule_idle() is similar to schedule_preempt_disable() except that it
3447 * never enables preemption because it does not call sched_submit_work().
3449 void __sched
schedule_idle(void)
3452 * As this skips calling sched_submit_work(), which the idle task does
3453 * regardless because that function is a nop when the task is in a
3454 * TASK_RUNNING state, make sure this isn't used someplace that the
3455 * current task can be in any other state. Note, idle is always in the
3456 * TASK_RUNNING state.
3458 WARN_ON_ONCE(current
->state
);
3461 } while (need_resched());
3464 #ifdef CONFIG_CONTEXT_TRACKING
3465 asmlinkage __visible
void __sched
schedule_user(void)
3468 * If we come here after a random call to set_need_resched(),
3469 * or we have been woken up remotely but the IPI has not yet arrived,
3470 * we haven't yet exited the RCU idle mode. Do it here manually until
3471 * we find a better solution.
3473 * NB: There are buggy callers of this function. Ideally we
3474 * should warn if prev_state != CONTEXT_USER, but that will trigger
3475 * too frequently to make sense yet.
3477 enum ctx_state prev_state
= exception_enter();
3479 exception_exit(prev_state
);
3484 * schedule_preempt_disabled - called with preemption disabled
3486 * Returns with preemption disabled. Note: preempt_count must be 1
3488 void __sched
schedule_preempt_disabled(void)
3490 sched_preempt_enable_no_resched();
3495 static void __sched notrace
preempt_schedule_common(void)
3499 * Because the function tracer can trace preempt_count_sub()
3500 * and it also uses preempt_enable/disable_notrace(), if
3501 * NEED_RESCHED is set, the preempt_enable_notrace() called
3502 * by the function tracer will call this function again and
3503 * cause infinite recursion.
3505 * Preemption must be disabled here before the function
3506 * tracer can trace. Break up preempt_disable() into two
3507 * calls. One to disable preemption without fear of being
3508 * traced. The other to still record the preemption latency,
3509 * which can also be traced by the function tracer.
3511 preempt_disable_notrace();
3512 preempt_latency_start(1);
3514 preempt_latency_stop(1);
3515 preempt_enable_no_resched_notrace();
3518 * Check again in case we missed a preemption opportunity
3519 * between schedule and now.
3521 } while (need_resched());
3524 #ifdef CONFIG_PREEMPT
3526 * this is the entry point to schedule() from in-kernel preemption
3527 * off of preempt_enable. Kernel preemptions off return from interrupt
3528 * occur there and call schedule directly.
3530 asmlinkage __visible
void __sched notrace
preempt_schedule(void)
3533 * If there is a non-zero preempt_count or interrupts are disabled,
3534 * we do not want to preempt the current task. Just return..
3536 if (likely(!preemptible()))
3539 preempt_schedule_common();
3541 NOKPROBE_SYMBOL(preempt_schedule
);
3542 EXPORT_SYMBOL(preempt_schedule
);
3545 * preempt_schedule_notrace - preempt_schedule called by tracing
3547 * The tracing infrastructure uses preempt_enable_notrace to prevent
3548 * recursion and tracing preempt enabling caused by the tracing
3549 * infrastructure itself. But as tracing can happen in areas coming
3550 * from userspace or just about to enter userspace, a preempt enable
3551 * can occur before user_exit() is called. This will cause the scheduler
3552 * to be called when the system is still in usermode.
3554 * To prevent this, the preempt_enable_notrace will use this function
3555 * instead of preempt_schedule() to exit user context if needed before
3556 * calling the scheduler.
3558 asmlinkage __visible
void __sched notrace
preempt_schedule_notrace(void)
3560 enum ctx_state prev_ctx
;
3562 if (likely(!preemptible()))
3567 * Because the function tracer can trace preempt_count_sub()
3568 * and it also uses preempt_enable/disable_notrace(), if
3569 * NEED_RESCHED is set, the preempt_enable_notrace() called
3570 * by the function tracer will call this function again and
3571 * cause infinite recursion.
3573 * Preemption must be disabled here before the function
3574 * tracer can trace. Break up preempt_disable() into two
3575 * calls. One to disable preemption without fear of being
3576 * traced. The other to still record the preemption latency,
3577 * which can also be traced by the function tracer.
3579 preempt_disable_notrace();
3580 preempt_latency_start(1);
3582 * Needs preempt disabled in case user_exit() is traced
3583 * and the tracer calls preempt_enable_notrace() causing
3584 * an infinite recursion.
3586 prev_ctx
= exception_enter();
3588 exception_exit(prev_ctx
);
3590 preempt_latency_stop(1);
3591 preempt_enable_no_resched_notrace();
3592 } while (need_resched());
3594 EXPORT_SYMBOL_GPL(preempt_schedule_notrace
);
3596 #endif /* CONFIG_PREEMPT */
3599 * this is the entry point to schedule() from kernel preemption
3600 * off of irq context.
3601 * Note, that this is called and return with irqs disabled. This will
3602 * protect us against recursive calling from irq.
3604 asmlinkage __visible
void __sched
preempt_schedule_irq(void)
3606 enum ctx_state prev_state
;
3608 /* Catch callers which need to be fixed */
3609 BUG_ON(preempt_count() || !irqs_disabled());
3611 prev_state
= exception_enter();
3617 local_irq_disable();
3618 sched_preempt_enable_no_resched();
3619 } while (need_resched());
3621 exception_exit(prev_state
);
3624 int default_wake_function(wait_queue_entry_t
*curr
, unsigned mode
, int wake_flags
,
3627 return try_to_wake_up(curr
->private, mode
, wake_flags
);
3629 EXPORT_SYMBOL(default_wake_function
);
3631 #ifdef CONFIG_RT_MUTEXES
3633 static inline int __rt_effective_prio(struct task_struct
*pi_task
, int prio
)
3636 prio
= min(prio
, pi_task
->prio
);
3641 static inline int rt_effective_prio(struct task_struct
*p
, int prio
)
3643 struct task_struct
*pi_task
= rt_mutex_get_top_task(p
);
3645 return __rt_effective_prio(pi_task
, prio
);
3649 * rt_mutex_setprio - set the current priority of a task
3651 * @pi_task: donor task
3653 * This function changes the 'effective' priority of a task. It does
3654 * not touch ->normal_prio like __setscheduler().
3656 * Used by the rt_mutex code to implement priority inheritance
3657 * logic. Call site only calls if the priority of the task changed.
3659 void rt_mutex_setprio(struct task_struct
*p
, struct task_struct
*pi_task
)
3661 int prio
, oldprio
, queued
, running
, queue_flag
=
3662 DEQUEUE_SAVE
| DEQUEUE_MOVE
| DEQUEUE_NOCLOCK
;
3663 const struct sched_class
*prev_class
;
3667 /* XXX used to be waiter->prio, not waiter->task->prio */
3668 prio
= __rt_effective_prio(pi_task
, p
->normal_prio
);
3671 * If nothing changed; bail early.
3673 if (p
->pi_top_task
== pi_task
&& prio
== p
->prio
&& !dl_prio(prio
))
3676 rq
= __task_rq_lock(p
, &rf
);
3677 update_rq_clock(rq
);
3679 * Set under pi_lock && rq->lock, such that the value can be used under
3682 * Note that there is loads of tricky to make this pointer cache work
3683 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3684 * ensure a task is de-boosted (pi_task is set to NULL) before the
3685 * task is allowed to run again (and can exit). This ensures the pointer
3686 * points to a blocked task -- which guaratees the task is present.
3688 p
->pi_top_task
= pi_task
;
3691 * For FIFO/RR we only need to set prio, if that matches we're done.
3693 if (prio
== p
->prio
&& !dl_prio(prio
))
3697 * Idle task boosting is a nono in general. There is one
3698 * exception, when PREEMPT_RT and NOHZ is active:
3700 * The idle task calls get_next_timer_interrupt() and holds
3701 * the timer wheel base->lock on the CPU and another CPU wants
3702 * to access the timer (probably to cancel it). We can safely
3703 * ignore the boosting request, as the idle CPU runs this code
3704 * with interrupts disabled and will complete the lock
3705 * protected section without being interrupted. So there is no
3706 * real need to boost.
3708 if (unlikely(p
== rq
->idle
)) {
3709 WARN_ON(p
!= rq
->curr
);
3710 WARN_ON(p
->pi_blocked_on
);
3714 trace_sched_pi_setprio(p
, pi_task
);
3717 if (oldprio
== prio
)
3718 queue_flag
&= ~DEQUEUE_MOVE
;
3720 prev_class
= p
->sched_class
;
3721 queued
= task_on_rq_queued(p
);
3722 running
= task_current(rq
, p
);
3724 dequeue_task(rq
, p
, queue_flag
);
3726 put_prev_task(rq
, p
);
3729 * Boosting condition are:
3730 * 1. -rt task is running and holds mutex A
3731 * --> -dl task blocks on mutex A
3733 * 2. -dl task is running and holds mutex A
3734 * --> -dl task blocks on mutex A and could preempt the
3737 if (dl_prio(prio
)) {
3738 if (!dl_prio(p
->normal_prio
) ||
3739 (pi_task
&& dl_entity_preempt(&pi_task
->dl
, &p
->dl
))) {
3740 p
->dl
.dl_boosted
= 1;
3741 queue_flag
|= ENQUEUE_REPLENISH
;
3743 p
->dl
.dl_boosted
= 0;
3744 p
->sched_class
= &dl_sched_class
;
3745 } else if (rt_prio(prio
)) {
3746 if (dl_prio(oldprio
))
3747 p
->dl
.dl_boosted
= 0;
3749 queue_flag
|= ENQUEUE_HEAD
;
3750 p
->sched_class
= &rt_sched_class
;
3752 if (dl_prio(oldprio
))
3753 p
->dl
.dl_boosted
= 0;
3754 if (rt_prio(oldprio
))
3756 p
->sched_class
= &fair_sched_class
;
3762 enqueue_task(rq
, p
, queue_flag
);
3764 set_curr_task(rq
, p
);
3766 check_class_changed(rq
, p
, prev_class
, oldprio
);
3768 /* Avoid rq from going away on us: */
3770 __task_rq_unlock(rq
, &rf
);
3772 balance_callback(rq
);
3776 static inline int rt_effective_prio(struct task_struct
*p
, int prio
)
3782 void set_user_nice(struct task_struct
*p
, long nice
)
3784 bool queued
, running
;
3785 int old_prio
, delta
;
3789 if (task_nice(p
) == nice
|| nice
< MIN_NICE
|| nice
> MAX_NICE
)
3792 * We have to be careful, if called from sys_setpriority(),
3793 * the task might be in the middle of scheduling on another CPU.
3795 rq
= task_rq_lock(p
, &rf
);
3796 update_rq_clock(rq
);
3799 * The RT priorities are set via sched_setscheduler(), but we still
3800 * allow the 'normal' nice value to be set - but as expected
3801 * it wont have any effect on scheduling until the task is
3802 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3804 if (task_has_dl_policy(p
) || task_has_rt_policy(p
)) {
3805 p
->static_prio
= NICE_TO_PRIO(nice
);
3808 queued
= task_on_rq_queued(p
);
3809 running
= task_current(rq
, p
);
3811 dequeue_task(rq
, p
, DEQUEUE_SAVE
| DEQUEUE_NOCLOCK
);
3813 put_prev_task(rq
, p
);
3815 p
->static_prio
= NICE_TO_PRIO(nice
);
3816 set_load_weight(p
, true);
3818 p
->prio
= effective_prio(p
);
3819 delta
= p
->prio
- old_prio
;
3822 enqueue_task(rq
, p
, ENQUEUE_RESTORE
| ENQUEUE_NOCLOCK
);
3824 * If the task increased its priority or is running and
3825 * lowered its priority, then reschedule its CPU:
3827 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
3831 set_curr_task(rq
, p
);
3833 task_rq_unlock(rq
, p
, &rf
);
3835 EXPORT_SYMBOL(set_user_nice
);
3838 * can_nice - check if a task can reduce its nice value
3842 int can_nice(const struct task_struct
*p
, const int nice
)
3844 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
3845 int nice_rlim
= nice_to_rlimit(nice
);
3847 return (nice_rlim
<= task_rlimit(p
, RLIMIT_NICE
) ||
3848 capable(CAP_SYS_NICE
));
3851 #ifdef __ARCH_WANT_SYS_NICE
3854 * sys_nice - change the priority of the current process.
3855 * @increment: priority increment
3857 * sys_setpriority is a more generic, but much slower function that
3858 * does similar things.
3860 SYSCALL_DEFINE1(nice
, int, increment
)
3865 * Setpriority might change our priority at the same moment.
3866 * We don't have to worry. Conceptually one call occurs first
3867 * and we have a single winner.
3869 increment
= clamp(increment
, -NICE_WIDTH
, NICE_WIDTH
);
3870 nice
= task_nice(current
) + increment
;
3872 nice
= clamp_val(nice
, MIN_NICE
, MAX_NICE
);
3873 if (increment
< 0 && !can_nice(current
, nice
))
3876 retval
= security_task_setnice(current
, nice
);
3880 set_user_nice(current
, nice
);
3887 * task_prio - return the priority value of a given task.
3888 * @p: the task in question.
3890 * Return: The priority value as seen by users in /proc.
3891 * RT tasks are offset by -200. Normal tasks are centered
3892 * around 0, value goes from -16 to +15.
3894 int task_prio(const struct task_struct
*p
)
3896 return p
->prio
- MAX_RT_PRIO
;
3900 * idle_cpu - is a given CPU idle currently?
3901 * @cpu: the processor in question.
3903 * Return: 1 if the CPU is currently idle. 0 otherwise.
3905 int idle_cpu(int cpu
)
3907 struct rq
*rq
= cpu_rq(cpu
);
3909 if (rq
->curr
!= rq
->idle
)
3916 if (!llist_empty(&rq
->wake_list
))
3924 * idle_task - return the idle task for a given CPU.
3925 * @cpu: the processor in question.
3927 * Return: The idle task for the CPU @cpu.
3929 struct task_struct
*idle_task(int cpu
)
3931 return cpu_rq(cpu
)->idle
;
3935 * find_process_by_pid - find a process with a matching PID value.
3936 * @pid: the pid in question.
3938 * The task of @pid, if found. %NULL otherwise.
3940 static struct task_struct
*find_process_by_pid(pid_t pid
)
3942 return pid
? find_task_by_vpid(pid
) : current
;
3946 * sched_setparam() passes in -1 for its policy, to let the functions
3947 * it calls know not to change it.
3949 #define SETPARAM_POLICY -1
3951 static void __setscheduler_params(struct task_struct
*p
,
3952 const struct sched_attr
*attr
)
3954 int policy
= attr
->sched_policy
;
3956 if (policy
== SETPARAM_POLICY
)
3961 if (dl_policy(policy
))
3962 __setparam_dl(p
, attr
);
3963 else if (fair_policy(policy
))
3964 p
->static_prio
= NICE_TO_PRIO(attr
->sched_nice
);
3967 * __sched_setscheduler() ensures attr->sched_priority == 0 when
3968 * !rt_policy. Always setting this ensures that things like
3969 * getparam()/getattr() don't report silly values for !rt tasks.
3971 p
->rt_priority
= attr
->sched_priority
;
3972 p
->normal_prio
= normal_prio(p
);
3973 set_load_weight(p
, true);
3976 /* Actually do priority change: must hold pi & rq lock. */
3977 static void __setscheduler(struct rq
*rq
, struct task_struct
*p
,
3978 const struct sched_attr
*attr
, bool keep_boost
)
3980 __setscheduler_params(p
, attr
);
3983 * Keep a potential priority boosting if called from
3984 * sched_setscheduler().
3986 p
->prio
= normal_prio(p
);
3988 p
->prio
= rt_effective_prio(p
, p
->prio
);
3990 if (dl_prio(p
->prio
))
3991 p
->sched_class
= &dl_sched_class
;
3992 else if (rt_prio(p
->prio
))
3993 p
->sched_class
= &rt_sched_class
;
3995 p
->sched_class
= &fair_sched_class
;
3999 * Check the target process has a UID that matches the current process's:
4001 static bool check_same_owner(struct task_struct
*p
)
4003 const struct cred
*cred
= current_cred(), *pcred
;
4007 pcred
= __task_cred(p
);
4008 match
= (uid_eq(cred
->euid
, pcred
->euid
) ||
4009 uid_eq(cred
->euid
, pcred
->uid
));
4014 static int __sched_setscheduler(struct task_struct
*p
,
4015 const struct sched_attr
*attr
,
4018 int newprio
= dl_policy(attr
->sched_policy
) ? MAX_DL_PRIO
- 1 :
4019 MAX_RT_PRIO
- 1 - attr
->sched_priority
;
4020 int retval
, oldprio
, oldpolicy
= -1, queued
, running
;
4021 int new_effective_prio
, policy
= attr
->sched_policy
;
4022 const struct sched_class
*prev_class
;
4025 int queue_flags
= DEQUEUE_SAVE
| DEQUEUE_MOVE
| DEQUEUE_NOCLOCK
;
4028 /* The pi code expects interrupts enabled */
4029 BUG_ON(pi
&& in_interrupt());
4031 /* Double check policy once rq lock held: */
4033 reset_on_fork
= p
->sched_reset_on_fork
;
4034 policy
= oldpolicy
= p
->policy
;
4036 reset_on_fork
= !!(attr
->sched_flags
& SCHED_FLAG_RESET_ON_FORK
);
4038 if (!valid_policy(policy
))
4042 if (attr
->sched_flags
&
4043 ~(SCHED_FLAG_RESET_ON_FORK
| SCHED_FLAG_RECLAIM
))
4047 * Valid priorities for SCHED_FIFO and SCHED_RR are
4048 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4049 * SCHED_BATCH and SCHED_IDLE is 0.
4051 if ((p
->mm
&& attr
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4052 (!p
->mm
&& attr
->sched_priority
> MAX_RT_PRIO
-1))
4054 if ((dl_policy(policy
) && !__checkparam_dl(attr
)) ||
4055 (rt_policy(policy
) != (attr
->sched_priority
!= 0)))
4059 * Allow unprivileged RT tasks to decrease priority:
4061 if (user
&& !capable(CAP_SYS_NICE
)) {
4062 if (fair_policy(policy
)) {
4063 if (attr
->sched_nice
< task_nice(p
) &&
4064 !can_nice(p
, attr
->sched_nice
))
4068 if (rt_policy(policy
)) {
4069 unsigned long rlim_rtprio
=
4070 task_rlimit(p
, RLIMIT_RTPRIO
);
4072 /* Can't set/change the rt policy: */
4073 if (policy
!= p
->policy
&& !rlim_rtprio
)
4076 /* Can't increase priority: */
4077 if (attr
->sched_priority
> p
->rt_priority
&&
4078 attr
->sched_priority
> rlim_rtprio
)
4083 * Can't set/change SCHED_DEADLINE policy at all for now
4084 * (safest behavior); in the future we would like to allow
4085 * unprivileged DL tasks to increase their relative deadline
4086 * or reduce their runtime (both ways reducing utilization)
4088 if (dl_policy(policy
))
4092 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4093 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4095 if (idle_policy(p
->policy
) && !idle_policy(policy
)) {
4096 if (!can_nice(p
, task_nice(p
)))
4100 /* Can't change other user's priorities: */
4101 if (!check_same_owner(p
))
4104 /* Normal users shall not reset the sched_reset_on_fork flag: */
4105 if (p
->sched_reset_on_fork
&& !reset_on_fork
)
4110 retval
= security_task_setscheduler(p
);
4116 * Make sure no PI-waiters arrive (or leave) while we are
4117 * changing the priority of the task:
4119 * To be able to change p->policy safely, the appropriate
4120 * runqueue lock must be held.
4122 rq
= task_rq_lock(p
, &rf
);
4123 update_rq_clock(rq
);
4126 * Changing the policy of the stop threads its a very bad idea:
4128 if (p
== rq
->stop
) {
4129 task_rq_unlock(rq
, p
, &rf
);
4134 * If not changing anything there's no need to proceed further,
4135 * but store a possible modification of reset_on_fork.
4137 if (unlikely(policy
== p
->policy
)) {
4138 if (fair_policy(policy
) && attr
->sched_nice
!= task_nice(p
))
4140 if (rt_policy(policy
) && attr
->sched_priority
!= p
->rt_priority
)
4142 if (dl_policy(policy
) && dl_param_changed(p
, attr
))
4145 p
->sched_reset_on_fork
= reset_on_fork
;
4146 task_rq_unlock(rq
, p
, &rf
);
4152 #ifdef CONFIG_RT_GROUP_SCHED
4154 * Do not allow realtime tasks into groups that have no runtime
4157 if (rt_bandwidth_enabled() && rt_policy(policy
) &&
4158 task_group(p
)->rt_bandwidth
.rt_runtime
== 0 &&
4159 !task_group_is_autogroup(task_group(p
))) {
4160 task_rq_unlock(rq
, p
, &rf
);
4165 if (dl_bandwidth_enabled() && dl_policy(policy
)) {
4166 cpumask_t
*span
= rq
->rd
->span
;
4169 * Don't allow tasks with an affinity mask smaller than
4170 * the entire root_domain to become SCHED_DEADLINE. We
4171 * will also fail if there's no bandwidth available.
4173 if (!cpumask_subset(span
, &p
->cpus_allowed
) ||
4174 rq
->rd
->dl_bw
.bw
== 0) {
4175 task_rq_unlock(rq
, p
, &rf
);
4182 /* Re-check policy now with rq lock held: */
4183 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4184 policy
= oldpolicy
= -1;
4185 task_rq_unlock(rq
, p
, &rf
);
4190 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4191 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4194 if ((dl_policy(policy
) || dl_task(p
)) && sched_dl_overflow(p
, policy
, attr
)) {
4195 task_rq_unlock(rq
, p
, &rf
);
4199 p
->sched_reset_on_fork
= reset_on_fork
;
4204 * Take priority boosted tasks into account. If the new
4205 * effective priority is unchanged, we just store the new
4206 * normal parameters and do not touch the scheduler class and
4207 * the runqueue. This will be done when the task deboost
4210 new_effective_prio
= rt_effective_prio(p
, newprio
);
4211 if (new_effective_prio
== oldprio
)
4212 queue_flags
&= ~DEQUEUE_MOVE
;
4215 queued
= task_on_rq_queued(p
);
4216 running
= task_current(rq
, p
);
4218 dequeue_task(rq
, p
, queue_flags
);
4220 put_prev_task(rq
, p
);
4222 prev_class
= p
->sched_class
;
4223 __setscheduler(rq
, p
, attr
, pi
);
4227 * We enqueue to tail when the priority of a task is
4228 * increased (user space view).
4230 if (oldprio
< p
->prio
)
4231 queue_flags
|= ENQUEUE_HEAD
;
4233 enqueue_task(rq
, p
, queue_flags
);
4236 set_curr_task(rq
, p
);
4238 check_class_changed(rq
, p
, prev_class
, oldprio
);
4240 /* Avoid rq from going away on us: */
4242 task_rq_unlock(rq
, p
, &rf
);
4245 rt_mutex_adjust_pi(p
);
4247 /* Run balance callbacks after we've adjusted the PI chain: */
4248 balance_callback(rq
);
4254 static int _sched_setscheduler(struct task_struct
*p
, int policy
,
4255 const struct sched_param
*param
, bool check
)
4257 struct sched_attr attr
= {
4258 .sched_policy
= policy
,
4259 .sched_priority
= param
->sched_priority
,
4260 .sched_nice
= PRIO_TO_NICE(p
->static_prio
),
4263 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4264 if ((policy
!= SETPARAM_POLICY
) && (policy
& SCHED_RESET_ON_FORK
)) {
4265 attr
.sched_flags
|= SCHED_FLAG_RESET_ON_FORK
;
4266 policy
&= ~SCHED_RESET_ON_FORK
;
4267 attr
.sched_policy
= policy
;
4270 return __sched_setscheduler(p
, &attr
, check
, true);
4273 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4274 * @p: the task in question.
4275 * @policy: new policy.
4276 * @param: structure containing the new RT priority.
4278 * Return: 0 on success. An error code otherwise.
4280 * NOTE that the task may be already dead.
4282 int sched_setscheduler(struct task_struct
*p
, int policy
,
4283 const struct sched_param
*param
)
4285 return _sched_setscheduler(p
, policy
, param
, true);
4287 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4289 int sched_setattr(struct task_struct
*p
, const struct sched_attr
*attr
)
4291 return __sched_setscheduler(p
, attr
, true, true);
4293 EXPORT_SYMBOL_GPL(sched_setattr
);
4296 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4297 * @p: the task in question.
4298 * @policy: new policy.
4299 * @param: structure containing the new RT priority.
4301 * Just like sched_setscheduler, only don't bother checking if the
4302 * current context has permission. For example, this is needed in
4303 * stop_machine(): we create temporary high priority worker threads,
4304 * but our caller might not have that capability.
4306 * Return: 0 on success. An error code otherwise.
4308 int sched_setscheduler_nocheck(struct task_struct
*p
, int policy
,
4309 const struct sched_param
*param
)
4311 return _sched_setscheduler(p
, policy
, param
, false);
4313 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck
);
4316 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4318 struct sched_param lparam
;
4319 struct task_struct
*p
;
4322 if (!param
|| pid
< 0)
4324 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4329 p
= find_process_by_pid(pid
);
4331 retval
= sched_setscheduler(p
, policy
, &lparam
);
4338 * Mimics kernel/events/core.c perf_copy_attr().
4340 static int sched_copy_attr(struct sched_attr __user
*uattr
, struct sched_attr
*attr
)
4345 if (!access_ok(VERIFY_WRITE
, uattr
, SCHED_ATTR_SIZE_VER0
))
4348 /* Zero the full structure, so that a short copy will be nice: */
4349 memset(attr
, 0, sizeof(*attr
));
4351 ret
= get_user(size
, &uattr
->size
);
4355 /* Bail out on silly large: */
4356 if (size
> PAGE_SIZE
)
4359 /* ABI compatibility quirk: */
4361 size
= SCHED_ATTR_SIZE_VER0
;
4363 if (size
< SCHED_ATTR_SIZE_VER0
)
4367 * If we're handed a bigger struct than we know of,
4368 * ensure all the unknown bits are 0 - i.e. new
4369 * user-space does not rely on any kernel feature
4370 * extensions we dont know about yet.
4372 if (size
> sizeof(*attr
)) {
4373 unsigned char __user
*addr
;
4374 unsigned char __user
*end
;
4377 addr
= (void __user
*)uattr
+ sizeof(*attr
);
4378 end
= (void __user
*)uattr
+ size
;
4380 for (; addr
< end
; addr
++) {
4381 ret
= get_user(val
, addr
);
4387 size
= sizeof(*attr
);
4390 ret
= copy_from_user(attr
, uattr
, size
);
4395 * XXX: Do we want to be lenient like existing syscalls; or do we want
4396 * to be strict and return an error on out-of-bounds values?
4398 attr
->sched_nice
= clamp(attr
->sched_nice
, MIN_NICE
, MAX_NICE
);
4403 put_user(sizeof(*attr
), &uattr
->size
);
4408 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4409 * @pid: the pid in question.
4410 * @policy: new policy.
4411 * @param: structure containing the new RT priority.
4413 * Return: 0 on success. An error code otherwise.
4415 SYSCALL_DEFINE3(sched_setscheduler
, pid_t
, pid
, int, policy
, struct sched_param __user
*, param
)
4420 return do_sched_setscheduler(pid
, policy
, param
);
4424 * sys_sched_setparam - set/change the RT priority of a thread
4425 * @pid: the pid in question.
4426 * @param: structure containing the new RT priority.
4428 * Return: 0 on success. An error code otherwise.
4430 SYSCALL_DEFINE2(sched_setparam
, pid_t
, pid
, struct sched_param __user
*, param
)
4432 return do_sched_setscheduler(pid
, SETPARAM_POLICY
, param
);
4436 * sys_sched_setattr - same as above, but with extended sched_attr
4437 * @pid: the pid in question.
4438 * @uattr: structure containing the extended parameters.
4439 * @flags: for future extension.
4441 SYSCALL_DEFINE3(sched_setattr
, pid_t
, pid
, struct sched_attr __user
*, uattr
,
4442 unsigned int, flags
)
4444 struct sched_attr attr
;
4445 struct task_struct
*p
;
4448 if (!uattr
|| pid
< 0 || flags
)
4451 retval
= sched_copy_attr(uattr
, &attr
);
4455 if ((int)attr
.sched_policy
< 0)
4460 p
= find_process_by_pid(pid
);
4462 retval
= sched_setattr(p
, &attr
);
4469 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4470 * @pid: the pid in question.
4472 * Return: On success, the policy of the thread. Otherwise, a negative error
4475 SYSCALL_DEFINE1(sched_getscheduler
, pid_t
, pid
)
4477 struct task_struct
*p
;
4485 p
= find_process_by_pid(pid
);
4487 retval
= security_task_getscheduler(p
);
4490 | (p
->sched_reset_on_fork
? SCHED_RESET_ON_FORK
: 0);
4497 * sys_sched_getparam - get the RT priority of a thread
4498 * @pid: the pid in question.
4499 * @param: structure containing the RT priority.
4501 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4504 SYSCALL_DEFINE2(sched_getparam
, pid_t
, pid
, struct sched_param __user
*, param
)
4506 struct sched_param lp
= { .sched_priority
= 0 };
4507 struct task_struct
*p
;
4510 if (!param
|| pid
< 0)
4514 p
= find_process_by_pid(pid
);
4519 retval
= security_task_getscheduler(p
);
4523 if (task_has_rt_policy(p
))
4524 lp
.sched_priority
= p
->rt_priority
;
4528 * This one might sleep, we cannot do it with a spinlock held ...
4530 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4539 static int sched_read_attr(struct sched_attr __user
*uattr
,
4540 struct sched_attr
*attr
,
4545 if (!access_ok(VERIFY_WRITE
, uattr
, usize
))
4549 * If we're handed a smaller struct than we know of,
4550 * ensure all the unknown bits are 0 - i.e. old
4551 * user-space does not get uncomplete information.
4553 if (usize
< sizeof(*attr
)) {
4554 unsigned char *addr
;
4557 addr
= (void *)attr
+ usize
;
4558 end
= (void *)attr
+ sizeof(*attr
);
4560 for (; addr
< end
; addr
++) {
4568 ret
= copy_to_user(uattr
, attr
, attr
->size
);
4576 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4577 * @pid: the pid in question.
4578 * @uattr: structure containing the extended parameters.
4579 * @size: sizeof(attr) for fwd/bwd comp.
4580 * @flags: for future extension.
4582 SYSCALL_DEFINE4(sched_getattr
, pid_t
, pid
, struct sched_attr __user
*, uattr
,
4583 unsigned int, size
, unsigned int, flags
)
4585 struct sched_attr attr
= {
4586 .size
= sizeof(struct sched_attr
),
4588 struct task_struct
*p
;
4591 if (!uattr
|| pid
< 0 || size
> PAGE_SIZE
||
4592 size
< SCHED_ATTR_SIZE_VER0
|| flags
)
4596 p
= find_process_by_pid(pid
);
4601 retval
= security_task_getscheduler(p
);
4605 attr
.sched_policy
= p
->policy
;
4606 if (p
->sched_reset_on_fork
)
4607 attr
.sched_flags
|= SCHED_FLAG_RESET_ON_FORK
;
4608 if (task_has_dl_policy(p
))
4609 __getparam_dl(p
, &attr
);
4610 else if (task_has_rt_policy(p
))
4611 attr
.sched_priority
= p
->rt_priority
;
4613 attr
.sched_nice
= task_nice(p
);
4617 retval
= sched_read_attr(uattr
, &attr
, size
);
4625 long sched_setaffinity(pid_t pid
, const struct cpumask
*in_mask
)
4627 cpumask_var_t cpus_allowed
, new_mask
;
4628 struct task_struct
*p
;
4633 p
= find_process_by_pid(pid
);
4639 /* Prevent p going away */
4643 if (p
->flags
& PF_NO_SETAFFINITY
) {
4647 if (!alloc_cpumask_var(&cpus_allowed
, GFP_KERNEL
)) {
4651 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
)) {
4653 goto out_free_cpus_allowed
;
4656 if (!check_same_owner(p
)) {
4658 if (!ns_capable(__task_cred(p
)->user_ns
, CAP_SYS_NICE
)) {
4660 goto out_free_new_mask
;
4665 retval
= security_task_setscheduler(p
);
4667 goto out_free_new_mask
;
4670 cpuset_cpus_allowed(p
, cpus_allowed
);
4671 cpumask_and(new_mask
, in_mask
, cpus_allowed
);
4674 * Since bandwidth control happens on root_domain basis,
4675 * if admission test is enabled, we only admit -deadline
4676 * tasks allowed to run on all the CPUs in the task's
4680 if (task_has_dl_policy(p
) && dl_bandwidth_enabled()) {
4682 if (!cpumask_subset(task_rq(p
)->rd
->span
, new_mask
)) {
4685 goto out_free_new_mask
;
4691 retval
= __set_cpus_allowed_ptr(p
, new_mask
, true);
4694 cpuset_cpus_allowed(p
, cpus_allowed
);
4695 if (!cpumask_subset(new_mask
, cpus_allowed
)) {
4697 * We must have raced with a concurrent cpuset
4698 * update. Just reset the cpus_allowed to the
4699 * cpuset's cpus_allowed
4701 cpumask_copy(new_mask
, cpus_allowed
);
4706 free_cpumask_var(new_mask
);
4707 out_free_cpus_allowed
:
4708 free_cpumask_var(cpus_allowed
);
4714 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4715 struct cpumask
*new_mask
)
4717 if (len
< cpumask_size())
4718 cpumask_clear(new_mask
);
4719 else if (len
> cpumask_size())
4720 len
= cpumask_size();
4722 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4726 * sys_sched_setaffinity - set the CPU affinity of a process
4727 * @pid: pid of the process
4728 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4729 * @user_mask_ptr: user-space pointer to the new CPU mask
4731 * Return: 0 on success. An error code otherwise.
4733 SYSCALL_DEFINE3(sched_setaffinity
, pid_t
, pid
, unsigned int, len
,
4734 unsigned long __user
*, user_mask_ptr
)
4736 cpumask_var_t new_mask
;
4739 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
))
4742 retval
= get_user_cpu_mask(user_mask_ptr
, len
, new_mask
);
4744 retval
= sched_setaffinity(pid
, new_mask
);
4745 free_cpumask_var(new_mask
);
4749 long sched_getaffinity(pid_t pid
, struct cpumask
*mask
)
4751 struct task_struct
*p
;
4752 unsigned long flags
;
4758 p
= find_process_by_pid(pid
);
4762 retval
= security_task_getscheduler(p
);
4766 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
4767 cpumask_and(mask
, &p
->cpus_allowed
, cpu_active_mask
);
4768 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4777 * sys_sched_getaffinity - get the CPU affinity of a process
4778 * @pid: pid of the process
4779 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4780 * @user_mask_ptr: user-space pointer to hold the current CPU mask
4782 * Return: size of CPU mask copied to user_mask_ptr on success. An
4783 * error code otherwise.
4785 SYSCALL_DEFINE3(sched_getaffinity
, pid_t
, pid
, unsigned int, len
,
4786 unsigned long __user
*, user_mask_ptr
)
4791 if ((len
* BITS_PER_BYTE
) < nr_cpu_ids
)
4793 if (len
& (sizeof(unsigned long)-1))
4796 if (!alloc_cpumask_var(&mask
, GFP_KERNEL
))
4799 ret
= sched_getaffinity(pid
, mask
);
4801 size_t retlen
= min_t(size_t, len
, cpumask_size());
4803 if (copy_to_user(user_mask_ptr
, mask
, retlen
))
4808 free_cpumask_var(mask
);
4814 * sys_sched_yield - yield the current processor to other threads.
4816 * This function yields the current CPU to other tasks. If there are no
4817 * other threads running on this CPU then this function will return.
4821 SYSCALL_DEFINE0(sched_yield
)
4826 local_irq_disable();
4830 schedstat_inc(rq
->yld_count
);
4831 current
->sched_class
->yield_task(rq
);
4834 * Since we are going to call schedule() anyway, there's
4835 * no need to preempt or enable interrupts:
4839 sched_preempt_enable_no_resched();
4846 #ifndef CONFIG_PREEMPT
4847 int __sched
_cond_resched(void)
4849 if (should_resched(0)) {
4850 preempt_schedule_common();
4856 EXPORT_SYMBOL(_cond_resched
);
4860 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4861 * call schedule, and on return reacquire the lock.
4863 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4864 * operations here to prevent schedule() from being called twice (once via
4865 * spin_unlock(), once by hand).
4867 int __cond_resched_lock(spinlock_t
*lock
)
4869 int resched
= should_resched(PREEMPT_LOCK_OFFSET
);
4872 lockdep_assert_held(lock
);
4874 if (spin_needbreak(lock
) || resched
) {
4877 preempt_schedule_common();
4885 EXPORT_SYMBOL(__cond_resched_lock
);
4887 int __sched
__cond_resched_softirq(void)
4889 BUG_ON(!in_softirq());
4891 if (should_resched(SOFTIRQ_DISABLE_OFFSET
)) {
4893 preempt_schedule_common();
4899 EXPORT_SYMBOL(__cond_resched_softirq
);
4902 * yield - yield the current processor to other threads.
4904 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4906 * The scheduler is at all times free to pick the calling task as the most
4907 * eligible task to run, if removing the yield() call from your code breaks
4908 * it, its already broken.
4910 * Typical broken usage is:
4915 * where one assumes that yield() will let 'the other' process run that will
4916 * make event true. If the current task is a SCHED_FIFO task that will never
4917 * happen. Never use yield() as a progress guarantee!!
4919 * If you want to use yield() to wait for something, use wait_event().
4920 * If you want to use yield() to be 'nice' for others, use cond_resched().
4921 * If you still want to use yield(), do not!
4923 void __sched
yield(void)
4925 set_current_state(TASK_RUNNING
);
4928 EXPORT_SYMBOL(yield
);
4931 * yield_to - yield the current processor to another thread in
4932 * your thread group, or accelerate that thread toward the
4933 * processor it's on.
4935 * @preempt: whether task preemption is allowed or not
4937 * It's the caller's job to ensure that the target task struct
4938 * can't go away on us before we can do any checks.
4941 * true (>0) if we indeed boosted the target task.
4942 * false (0) if we failed to boost the target.
4943 * -ESRCH if there's no task to yield to.
4945 int __sched
yield_to(struct task_struct
*p
, bool preempt
)
4947 struct task_struct
*curr
= current
;
4948 struct rq
*rq
, *p_rq
;
4949 unsigned long flags
;
4952 local_irq_save(flags
);
4958 * If we're the only runnable task on the rq and target rq also
4959 * has only one task, there's absolutely no point in yielding.
4961 if (rq
->nr_running
== 1 && p_rq
->nr_running
== 1) {
4966 double_rq_lock(rq
, p_rq
);
4967 if (task_rq(p
) != p_rq
) {
4968 double_rq_unlock(rq
, p_rq
);
4972 if (!curr
->sched_class
->yield_to_task
)
4975 if (curr
->sched_class
!= p
->sched_class
)
4978 if (task_running(p_rq
, p
) || p
->state
)
4981 yielded
= curr
->sched_class
->yield_to_task(rq
, p
, preempt
);
4983 schedstat_inc(rq
->yld_count
);
4985 * Make p's CPU reschedule; pick_next_entity takes care of
4988 if (preempt
&& rq
!= p_rq
)
4993 double_rq_unlock(rq
, p_rq
);
4995 local_irq_restore(flags
);
5002 EXPORT_SYMBOL_GPL(yield_to
);
5004 int io_schedule_prepare(void)
5006 int old_iowait
= current
->in_iowait
;
5008 current
->in_iowait
= 1;
5009 blk_schedule_flush_plug(current
);
5014 void io_schedule_finish(int token
)
5016 current
->in_iowait
= token
;
5020 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5021 * that process accounting knows that this is a task in IO wait state.
5023 long __sched
io_schedule_timeout(long timeout
)
5028 token
= io_schedule_prepare();
5029 ret
= schedule_timeout(timeout
);
5030 io_schedule_finish(token
);
5034 EXPORT_SYMBOL(io_schedule_timeout
);
5036 void io_schedule(void)
5040 token
= io_schedule_prepare();
5042 io_schedule_finish(token
);
5044 EXPORT_SYMBOL(io_schedule
);
5047 * sys_sched_get_priority_max - return maximum RT priority.
5048 * @policy: scheduling class.
5050 * Return: On success, this syscall returns the maximum
5051 * rt_priority that can be used by a given scheduling class.
5052 * On failure, a negative error code is returned.
5054 SYSCALL_DEFINE1(sched_get_priority_max
, int, policy
)
5061 ret
= MAX_USER_RT_PRIO
-1;
5063 case SCHED_DEADLINE
:
5074 * sys_sched_get_priority_min - return minimum RT priority.
5075 * @policy: scheduling class.
5077 * Return: On success, this syscall returns the minimum
5078 * rt_priority that can be used by a given scheduling class.
5079 * On failure, a negative error code is returned.
5081 SYSCALL_DEFINE1(sched_get_priority_min
, int, policy
)
5090 case SCHED_DEADLINE
:
5100 * sys_sched_rr_get_interval - return the default timeslice of a process.
5101 * @pid: pid of the process.
5102 * @interval: userspace pointer to the timeslice value.
5104 * this syscall writes the default timeslice value of a given process
5105 * into the user-space timespec buffer. A value of '0' means infinity.
5107 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5110 SYSCALL_DEFINE2(sched_rr_get_interval
, pid_t
, pid
,
5111 struct timespec __user
*, interval
)
5113 struct task_struct
*p
;
5114 unsigned int time_slice
;
5125 p
= find_process_by_pid(pid
);
5129 retval
= security_task_getscheduler(p
);
5133 rq
= task_rq_lock(p
, &rf
);
5135 if (p
->sched_class
->get_rr_interval
)
5136 time_slice
= p
->sched_class
->get_rr_interval(rq
, p
);
5137 task_rq_unlock(rq
, p
, &rf
);
5140 jiffies_to_timespec(time_slice
, &t
);
5141 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5149 void sched_show_task(struct task_struct
*p
)
5151 unsigned long free
= 0;
5154 if (!try_get_task_stack(p
))
5157 printk(KERN_INFO
"%-15.15s %c", p
->comm
, task_state_to_char(p
));
5159 if (p
->state
== TASK_RUNNING
)
5160 printk(KERN_CONT
" running task ");
5161 #ifdef CONFIG_DEBUG_STACK_USAGE
5162 free
= stack_not_used(p
);
5167 ppid
= task_pid_nr(rcu_dereference(p
->real_parent
));
5169 printk(KERN_CONT
"%5lu %5d %6d 0x%08lx\n", free
,
5170 task_pid_nr(p
), ppid
,
5171 (unsigned long)task_thread_info(p
)->flags
);
5173 print_worker_info(KERN_INFO
, p
);
5174 show_stack(p
, NULL
);
5177 EXPORT_SYMBOL_GPL(sched_show_task
);
5180 state_filter_match(unsigned long state_filter
, struct task_struct
*p
)
5182 /* no filter, everything matches */
5186 /* filter, but doesn't match */
5187 if (!(p
->state
& state_filter
))
5191 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5194 if (state_filter
== TASK_UNINTERRUPTIBLE
&& p
->state
== TASK_IDLE
)
5201 void show_state_filter(unsigned long state_filter
)
5203 struct task_struct
*g
, *p
;
5205 #if BITS_PER_LONG == 32
5207 " task PC stack pid father\n");
5210 " task PC stack pid father\n");
5213 for_each_process_thread(g
, p
) {
5215 * reset the NMI-timeout, listing all files on a slow
5216 * console might take a lot of time:
5217 * Also, reset softlockup watchdogs on all CPUs, because
5218 * another CPU might be blocked waiting for us to process
5221 touch_nmi_watchdog();
5222 touch_all_softlockup_watchdogs();
5223 if (state_filter_match(state_filter
, p
))
5227 #ifdef CONFIG_SCHED_DEBUG
5229 sysrq_sched_debug_show();
5233 * Only show locks if all tasks are dumped:
5236 debug_show_all_locks();
5240 * init_idle - set up an idle thread for a given CPU
5241 * @idle: task in question
5242 * @cpu: CPU the idle task belongs to
5244 * NOTE: this function does not set the idle thread's NEED_RESCHED
5245 * flag, to make booting more robust.
5247 void init_idle(struct task_struct
*idle
, int cpu
)
5249 struct rq
*rq
= cpu_rq(cpu
);
5250 unsigned long flags
;
5252 raw_spin_lock_irqsave(&idle
->pi_lock
, flags
);
5253 raw_spin_lock(&rq
->lock
);
5255 __sched_fork(0, idle
);
5256 idle
->state
= TASK_RUNNING
;
5257 idle
->se
.exec_start
= sched_clock();
5258 idle
->flags
|= PF_IDLE
;
5260 kasan_unpoison_task_stack(idle
);
5264 * Its possible that init_idle() gets called multiple times on a task,
5265 * in that case do_set_cpus_allowed() will not do the right thing.
5267 * And since this is boot we can forgo the serialization.
5269 set_cpus_allowed_common(idle
, cpumask_of(cpu
));
5272 * We're having a chicken and egg problem, even though we are
5273 * holding rq->lock, the CPU isn't yet set to this CPU so the
5274 * lockdep check in task_group() will fail.
5276 * Similar case to sched_fork(). / Alternatively we could
5277 * use task_rq_lock() here and obtain the other rq->lock.
5282 __set_task_cpu(idle
, cpu
);
5285 rq
->curr
= rq
->idle
= idle
;
5286 idle
->on_rq
= TASK_ON_RQ_QUEUED
;
5290 raw_spin_unlock(&rq
->lock
);
5291 raw_spin_unlock_irqrestore(&idle
->pi_lock
, flags
);
5293 /* Set the preempt count _outside_ the spinlocks! */
5294 init_idle_preempt_count(idle
, cpu
);
5297 * The idle tasks have their own, simple scheduling class:
5299 idle
->sched_class
= &idle_sched_class
;
5300 ftrace_graph_init_idle_task(idle
, cpu
);
5301 vtime_init_idle(idle
, cpu
);
5303 sprintf(idle
->comm
, "%s/%d", INIT_TASK_COMM
, cpu
);
5309 int cpuset_cpumask_can_shrink(const struct cpumask
*cur
,
5310 const struct cpumask
*trial
)
5314 if (!cpumask_weight(cur
))
5317 ret
= dl_cpuset_cpumask_can_shrink(cur
, trial
);
5322 int task_can_attach(struct task_struct
*p
,
5323 const struct cpumask
*cs_cpus_allowed
)
5328 * Kthreads which disallow setaffinity shouldn't be moved
5329 * to a new cpuset; we don't want to change their CPU
5330 * affinity and isolating such threads by their set of
5331 * allowed nodes is unnecessary. Thus, cpusets are not
5332 * applicable for such threads. This prevents checking for
5333 * success of set_cpus_allowed_ptr() on all attached tasks
5334 * before cpus_allowed may be changed.
5336 if (p
->flags
& PF_NO_SETAFFINITY
) {
5341 if (dl_task(p
) && !cpumask_intersects(task_rq(p
)->rd
->span
,
5343 ret
= dl_task_can_attach(p
, cs_cpus_allowed
);
5349 bool sched_smp_initialized __read_mostly
;
5351 #ifdef CONFIG_NUMA_BALANCING
5352 /* Migrate current task p to target_cpu */
5353 int migrate_task_to(struct task_struct
*p
, int target_cpu
)
5355 struct migration_arg arg
= { p
, target_cpu
};
5356 int curr_cpu
= task_cpu(p
);
5358 if (curr_cpu
== target_cpu
)
5361 if (!cpumask_test_cpu(target_cpu
, &p
->cpus_allowed
))
5364 /* TODO: This is not properly updating schedstats */
5366 trace_sched_move_numa(p
, curr_cpu
, target_cpu
);
5367 return stop_one_cpu(curr_cpu
, migration_cpu_stop
, &arg
);
5371 * Requeue a task on a given node and accurately track the number of NUMA
5372 * tasks on the runqueues
5374 void sched_setnuma(struct task_struct
*p
, int nid
)
5376 bool queued
, running
;
5380 rq
= task_rq_lock(p
, &rf
);
5381 queued
= task_on_rq_queued(p
);
5382 running
= task_current(rq
, p
);
5385 dequeue_task(rq
, p
, DEQUEUE_SAVE
);
5387 put_prev_task(rq
, p
);
5389 p
->numa_preferred_nid
= nid
;
5392 enqueue_task(rq
, p
, ENQUEUE_RESTORE
| ENQUEUE_NOCLOCK
);
5394 set_curr_task(rq
, p
);
5395 task_rq_unlock(rq
, p
, &rf
);
5397 #endif /* CONFIG_NUMA_BALANCING */
5399 #ifdef CONFIG_HOTPLUG_CPU
5401 * Ensure that the idle task is using init_mm right before its CPU goes
5404 void idle_task_exit(void)
5406 struct mm_struct
*mm
= current
->active_mm
;
5408 BUG_ON(cpu_online(smp_processor_id()));
5410 if (mm
!= &init_mm
) {
5411 switch_mm(mm
, &init_mm
, current
);
5412 finish_arch_post_lock_switch();
5418 * Since this CPU is going 'away' for a while, fold any nr_active delta
5419 * we might have. Assumes we're called after migrate_tasks() so that the
5420 * nr_active count is stable. We need to take the teardown thread which
5421 * is calling this into account, so we hand in adjust = 1 to the load
5424 * Also see the comment "Global load-average calculations".
5426 static void calc_load_migrate(struct rq
*rq
)
5428 long delta
= calc_load_fold_active(rq
, 1);
5430 atomic_long_add(delta
, &calc_load_tasks
);
5433 static void put_prev_task_fake(struct rq
*rq
, struct task_struct
*prev
)
5437 static const struct sched_class fake_sched_class
= {
5438 .put_prev_task
= put_prev_task_fake
,
5441 static struct task_struct fake_task
= {
5443 * Avoid pull_{rt,dl}_task()
5445 .prio
= MAX_PRIO
+ 1,
5446 .sched_class
= &fake_sched_class
,
5450 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5451 * try_to_wake_up()->select_task_rq().
5453 * Called with rq->lock held even though we'er in stop_machine() and
5454 * there's no concurrency possible, we hold the required locks anyway
5455 * because of lock validation efforts.
5457 static void migrate_tasks(struct rq
*dead_rq
, struct rq_flags
*rf
)
5459 struct rq
*rq
= dead_rq
;
5460 struct task_struct
*next
, *stop
= rq
->stop
;
5461 struct rq_flags orf
= *rf
;
5465 * Fudge the rq selection such that the below task selection loop
5466 * doesn't get stuck on the currently eligible stop task.
5468 * We're currently inside stop_machine() and the rq is either stuck
5469 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5470 * either way we should never end up calling schedule() until we're
5476 * put_prev_task() and pick_next_task() sched
5477 * class method both need to have an up-to-date
5478 * value of rq->clock[_task]
5480 update_rq_clock(rq
);
5484 * There's this thread running, bail when that's the only
5487 if (rq
->nr_running
== 1)
5491 * pick_next_task() assumes pinned rq->lock:
5493 next
= pick_next_task(rq
, &fake_task
, rf
);
5495 put_prev_task(rq
, next
);
5498 * Rules for changing task_struct::cpus_allowed are holding
5499 * both pi_lock and rq->lock, such that holding either
5500 * stabilizes the mask.
5502 * Drop rq->lock is not quite as disastrous as it usually is
5503 * because !cpu_active at this point, which means load-balance
5504 * will not interfere. Also, stop-machine.
5507 raw_spin_lock(&next
->pi_lock
);
5511 * Since we're inside stop-machine, _nothing_ should have
5512 * changed the task, WARN if weird stuff happened, because in
5513 * that case the above rq->lock drop is a fail too.
5515 if (WARN_ON(task_rq(next
) != rq
|| !task_on_rq_queued(next
))) {
5516 raw_spin_unlock(&next
->pi_lock
);
5520 /* Find suitable destination for @next, with force if needed. */
5521 dest_cpu
= select_fallback_rq(dead_rq
->cpu
, next
);
5522 rq
= __migrate_task(rq
, rf
, next
, dest_cpu
);
5523 if (rq
!= dead_rq
) {
5529 raw_spin_unlock(&next
->pi_lock
);
5534 #endif /* CONFIG_HOTPLUG_CPU */
5536 void set_rq_online(struct rq
*rq
)
5539 const struct sched_class
*class;
5541 cpumask_set_cpu(rq
->cpu
, rq
->rd
->online
);
5544 for_each_class(class) {
5545 if (class->rq_online
)
5546 class->rq_online(rq
);
5551 void set_rq_offline(struct rq
*rq
)
5554 const struct sched_class
*class;
5556 for_each_class(class) {
5557 if (class->rq_offline
)
5558 class->rq_offline(rq
);
5561 cpumask_clear_cpu(rq
->cpu
, rq
->rd
->online
);
5566 static void set_cpu_rq_start_time(unsigned int cpu
)
5568 struct rq
*rq
= cpu_rq(cpu
);
5570 rq
->age_stamp
= sched_clock_cpu(cpu
);
5574 * used to mark begin/end of suspend/resume:
5576 static int num_cpus_frozen
;
5579 * Update cpusets according to cpu_active mask. If cpusets are
5580 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5581 * around partition_sched_domains().
5583 * If we come here as part of a suspend/resume, don't touch cpusets because we
5584 * want to restore it back to its original state upon resume anyway.
5586 static void cpuset_cpu_active(void)
5588 if (cpuhp_tasks_frozen
) {
5590 * num_cpus_frozen tracks how many CPUs are involved in suspend
5591 * resume sequence. As long as this is not the last online
5592 * operation in the resume sequence, just build a single sched
5593 * domain, ignoring cpusets.
5595 partition_sched_domains(1, NULL
, NULL
);
5596 if (--num_cpus_frozen
)
5599 * This is the last CPU online operation. So fall through and
5600 * restore the original sched domains by considering the
5601 * cpuset configurations.
5603 cpuset_force_rebuild();
5605 cpuset_update_active_cpus();
5608 static int cpuset_cpu_inactive(unsigned int cpu
)
5610 if (!cpuhp_tasks_frozen
) {
5611 if (dl_cpu_busy(cpu
))
5613 cpuset_update_active_cpus();
5616 partition_sched_domains(1, NULL
, NULL
);
5621 int sched_cpu_activate(unsigned int cpu
)
5623 struct rq
*rq
= cpu_rq(cpu
);
5626 set_cpu_active(cpu
, true);
5628 if (sched_smp_initialized
) {
5629 sched_domains_numa_masks_set(cpu
);
5630 cpuset_cpu_active();
5634 * Put the rq online, if not already. This happens:
5636 * 1) In the early boot process, because we build the real domains
5637 * after all CPUs have been brought up.
5639 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5642 rq_lock_irqsave(rq
, &rf
);
5644 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
5647 rq_unlock_irqrestore(rq
, &rf
);
5649 update_max_interval();
5654 int sched_cpu_deactivate(unsigned int cpu
)
5658 set_cpu_active(cpu
, false);
5660 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5661 * users of this state to go away such that all new such users will
5664 * Do sync before park smpboot threads to take care the rcu boost case.
5666 synchronize_rcu_mult(call_rcu
, call_rcu_sched
);
5668 if (!sched_smp_initialized
)
5671 ret
= cpuset_cpu_inactive(cpu
);
5673 set_cpu_active(cpu
, true);
5676 sched_domains_numa_masks_clear(cpu
);
5680 static void sched_rq_cpu_starting(unsigned int cpu
)
5682 struct rq
*rq
= cpu_rq(cpu
);
5684 rq
->calc_load_update
= calc_load_update
;
5685 update_max_interval();
5688 int sched_cpu_starting(unsigned int cpu
)
5690 set_cpu_rq_start_time(cpu
);
5691 sched_rq_cpu_starting(cpu
);
5695 #ifdef CONFIG_HOTPLUG_CPU
5696 int sched_cpu_dying(unsigned int cpu
)
5698 struct rq
*rq
= cpu_rq(cpu
);
5701 /* Handle pending wakeups and then migrate everything off */
5702 sched_ttwu_pending();
5704 rq_lock_irqsave(rq
, &rf
);
5706 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
5709 migrate_tasks(rq
, &rf
);
5710 BUG_ON(rq
->nr_running
!= 1);
5711 rq_unlock_irqrestore(rq
, &rf
);
5713 calc_load_migrate(rq
);
5714 update_max_interval();
5715 nohz_balance_exit_idle(cpu
);
5721 #ifdef CONFIG_SCHED_SMT
5722 DEFINE_STATIC_KEY_FALSE(sched_smt_present
);
5724 static void sched_init_smt(void)
5727 * We've enumerated all CPUs and will assume that if any CPU
5728 * has SMT siblings, CPU0 will too.
5730 if (cpumask_weight(cpu_smt_mask(0)) > 1)
5731 static_branch_enable(&sched_smt_present
);
5734 static inline void sched_init_smt(void) { }
5737 void __init
sched_init_smp(void)
5742 * There's no userspace yet to cause hotplug operations; hence all the
5743 * CPU masks are stable and all blatant races in the below code cannot
5746 mutex_lock(&sched_domains_mutex
);
5747 sched_init_domains(cpu_active_mask
);
5748 mutex_unlock(&sched_domains_mutex
);
5750 /* Move init over to a non-isolated CPU */
5751 if (set_cpus_allowed_ptr(current
, housekeeping_cpumask(HK_FLAG_DOMAIN
)) < 0)
5753 sched_init_granularity();
5755 init_sched_rt_class();
5756 init_sched_dl_class();
5760 sched_smp_initialized
= true;
5763 static int __init
migration_init(void)
5765 sched_rq_cpu_starting(smp_processor_id());
5768 early_initcall(migration_init
);
5771 void __init
sched_init_smp(void)
5773 sched_init_granularity();
5775 #endif /* CONFIG_SMP */
5777 int in_sched_functions(unsigned long addr
)
5779 return in_lock_functions(addr
) ||
5780 (addr
>= (unsigned long)__sched_text_start
5781 && addr
< (unsigned long)__sched_text_end
);
5784 #ifdef CONFIG_CGROUP_SCHED
5786 * Default task group.
5787 * Every task in system belongs to this group at bootup.
5789 struct task_group root_task_group
;
5790 LIST_HEAD(task_groups
);
5792 /* Cacheline aligned slab cache for task_group */
5793 static struct kmem_cache
*task_group_cache __read_mostly
;
5796 DECLARE_PER_CPU(cpumask_var_t
, load_balance_mask
);
5797 DECLARE_PER_CPU(cpumask_var_t
, select_idle_mask
);
5799 void __init
sched_init(void)
5802 unsigned long alloc_size
= 0, ptr
;
5807 #ifdef CONFIG_FAIR_GROUP_SCHED
5808 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
5810 #ifdef CONFIG_RT_GROUP_SCHED
5811 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
5814 ptr
= (unsigned long)kzalloc(alloc_size
, GFP_NOWAIT
);
5816 #ifdef CONFIG_FAIR_GROUP_SCHED
5817 root_task_group
.se
= (struct sched_entity
**)ptr
;
5818 ptr
+= nr_cpu_ids
* sizeof(void **);
5820 root_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
5821 ptr
+= nr_cpu_ids
* sizeof(void **);
5823 #endif /* CONFIG_FAIR_GROUP_SCHED */
5824 #ifdef CONFIG_RT_GROUP_SCHED
5825 root_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
5826 ptr
+= nr_cpu_ids
* sizeof(void **);
5828 root_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
5829 ptr
+= nr_cpu_ids
* sizeof(void **);
5831 #endif /* CONFIG_RT_GROUP_SCHED */
5833 #ifdef CONFIG_CPUMASK_OFFSTACK
5834 for_each_possible_cpu(i
) {
5835 per_cpu(load_balance_mask
, i
) = (cpumask_var_t
)kzalloc_node(
5836 cpumask_size(), GFP_KERNEL
, cpu_to_node(i
));
5837 per_cpu(select_idle_mask
, i
) = (cpumask_var_t
)kzalloc_node(
5838 cpumask_size(), GFP_KERNEL
, cpu_to_node(i
));
5840 #endif /* CONFIG_CPUMASK_OFFSTACK */
5842 init_rt_bandwidth(&def_rt_bandwidth
, global_rt_period(), global_rt_runtime());
5843 init_dl_bandwidth(&def_dl_bandwidth
, global_rt_period(), global_rt_runtime());
5846 init_defrootdomain();
5849 #ifdef CONFIG_RT_GROUP_SCHED
5850 init_rt_bandwidth(&root_task_group
.rt_bandwidth
,
5851 global_rt_period(), global_rt_runtime());
5852 #endif /* CONFIG_RT_GROUP_SCHED */
5854 #ifdef CONFIG_CGROUP_SCHED
5855 task_group_cache
= KMEM_CACHE(task_group
, 0);
5857 list_add(&root_task_group
.list
, &task_groups
);
5858 INIT_LIST_HEAD(&root_task_group
.children
);
5859 INIT_LIST_HEAD(&root_task_group
.siblings
);
5860 autogroup_init(&init_task
);
5861 #endif /* CONFIG_CGROUP_SCHED */
5863 for_each_possible_cpu(i
) {
5867 raw_spin_lock_init(&rq
->lock
);
5869 rq
->calc_load_active
= 0;
5870 rq
->calc_load_update
= jiffies
+ LOAD_FREQ
;
5871 init_cfs_rq(&rq
->cfs
);
5872 init_rt_rq(&rq
->rt
);
5873 init_dl_rq(&rq
->dl
);
5874 #ifdef CONFIG_FAIR_GROUP_SCHED
5875 root_task_group
.shares
= ROOT_TASK_GROUP_LOAD
;
5876 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
5877 rq
->tmp_alone_branch
= &rq
->leaf_cfs_rq_list
;
5879 * How much CPU bandwidth does root_task_group get?
5881 * In case of task-groups formed thr' the cgroup filesystem, it
5882 * gets 100% of the CPU resources in the system. This overall
5883 * system CPU resource is divided among the tasks of
5884 * root_task_group and its child task-groups in a fair manner,
5885 * based on each entity's (task or task-group's) weight
5886 * (se->load.weight).
5888 * In other words, if root_task_group has 10 tasks of weight
5889 * 1024) and two child groups A0 and A1 (of weight 1024 each),
5890 * then A0's share of the CPU resource is:
5892 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
5894 * We achieve this by letting root_task_group's tasks sit
5895 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
5897 init_cfs_bandwidth(&root_task_group
.cfs_bandwidth
);
5898 init_tg_cfs_entry(&root_task_group
, &rq
->cfs
, NULL
, i
, NULL
);
5899 #endif /* CONFIG_FAIR_GROUP_SCHED */
5901 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
5902 #ifdef CONFIG_RT_GROUP_SCHED
5903 init_tg_rt_entry(&root_task_group
, &rq
->rt
, NULL
, i
, NULL
);
5906 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
5907 rq
->cpu_load
[j
] = 0;
5912 rq
->cpu_capacity
= rq
->cpu_capacity_orig
= SCHED_CAPACITY_SCALE
;
5913 rq
->balance_callback
= NULL
;
5914 rq
->active_balance
= 0;
5915 rq
->next_balance
= jiffies
;
5920 rq
->avg_idle
= 2*sysctl_sched_migration_cost
;
5921 rq
->max_idle_balance_cost
= sysctl_sched_migration_cost
;
5923 INIT_LIST_HEAD(&rq
->cfs_tasks
);
5925 rq_attach_root(rq
, &def_root_domain
);
5926 #ifdef CONFIG_NO_HZ_COMMON
5927 rq
->last_load_update_tick
= jiffies
;
5930 #ifdef CONFIG_NO_HZ_FULL
5931 rq
->last_sched_tick
= 0;
5933 #endif /* CONFIG_SMP */
5935 atomic_set(&rq
->nr_iowait
, 0);
5938 set_load_weight(&init_task
, false);
5941 * The boot idle thread does lazy MMU switching as well:
5944 enter_lazy_tlb(&init_mm
, current
);
5947 * Make us the idle thread. Technically, schedule() should not be
5948 * called from this thread, however somewhere below it might be,
5949 * but because we are the idle thread, we just pick up running again
5950 * when this runqueue becomes "idle".
5952 init_idle(current
, smp_processor_id());
5954 calc_load_update
= jiffies
+ LOAD_FREQ
;
5957 idle_thread_set_boot_cpu();
5958 set_cpu_rq_start_time(smp_processor_id());
5960 init_sched_fair_class();
5964 scheduler_running
= 1;
5967 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
5968 static inline int preempt_count_equals(int preempt_offset
)
5970 int nested
= preempt_count() + rcu_preempt_depth();
5972 return (nested
== preempt_offset
);
5975 void __might_sleep(const char *file
, int line
, int preempt_offset
)
5978 * Blocking primitives will set (and therefore destroy) current->state,
5979 * since we will exit with TASK_RUNNING make sure we enter with it,
5980 * otherwise we will destroy state.
5982 WARN_ONCE(current
->state
!= TASK_RUNNING
&& current
->task_state_change
,
5983 "do not call blocking ops when !TASK_RUNNING; "
5984 "state=%lx set at [<%p>] %pS\n",
5986 (void *)current
->task_state_change
,
5987 (void *)current
->task_state_change
);
5989 ___might_sleep(file
, line
, preempt_offset
);
5991 EXPORT_SYMBOL(__might_sleep
);
5993 void ___might_sleep(const char *file
, int line
, int preempt_offset
)
5995 /* Ratelimiting timestamp: */
5996 static unsigned long prev_jiffy
;
5998 unsigned long preempt_disable_ip
;
6000 /* WARN_ON_ONCE() by default, no rate limit required: */
6003 if ((preempt_count_equals(preempt_offset
) && !irqs_disabled() &&
6004 !is_idle_task(current
)) ||
6005 system_state
== SYSTEM_BOOTING
|| system_state
> SYSTEM_RUNNING
||
6009 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
6011 prev_jiffy
= jiffies
;
6013 /* Save this before calling printk(), since that will clobber it: */
6014 preempt_disable_ip
= get_preempt_disable_ip(current
);
6017 "BUG: sleeping function called from invalid context at %s:%d\n",
6020 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6021 in_atomic(), irqs_disabled(),
6022 current
->pid
, current
->comm
);
6024 if (task_stack_end_corrupted(current
))
6025 printk(KERN_EMERG
"Thread overran stack, or stack corrupted\n");
6027 debug_show_held_locks(current
);
6028 if (irqs_disabled())
6029 print_irqtrace_events(current
);
6030 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT
)
6031 && !preempt_count_equals(preempt_offset
)) {
6032 pr_err("Preemption disabled at:");
6033 print_ip_sym(preempt_disable_ip
);
6037 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
6039 EXPORT_SYMBOL(___might_sleep
);
6042 #ifdef CONFIG_MAGIC_SYSRQ
6043 void normalize_rt_tasks(void)
6045 struct task_struct
*g
, *p
;
6046 struct sched_attr attr
= {
6047 .sched_policy
= SCHED_NORMAL
,
6050 read_lock(&tasklist_lock
);
6051 for_each_process_thread(g
, p
) {
6053 * Only normalize user tasks:
6055 if (p
->flags
& PF_KTHREAD
)
6058 p
->se
.exec_start
= 0;
6059 schedstat_set(p
->se
.statistics
.wait_start
, 0);
6060 schedstat_set(p
->se
.statistics
.sleep_start
, 0);
6061 schedstat_set(p
->se
.statistics
.block_start
, 0);
6063 if (!dl_task(p
) && !rt_task(p
)) {
6065 * Renice negative nice level userspace
6068 if (task_nice(p
) < 0)
6069 set_user_nice(p
, 0);
6073 __sched_setscheduler(p
, &attr
, false, false);
6075 read_unlock(&tasklist_lock
);
6078 #endif /* CONFIG_MAGIC_SYSRQ */
6080 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
6082 * These functions are only useful for the IA64 MCA handling, or kdb.
6084 * They can only be called when the whole system has been
6085 * stopped - every CPU needs to be quiescent, and no scheduling
6086 * activity can take place. Using them for anything else would
6087 * be a serious bug, and as a result, they aren't even visible
6088 * under any other configuration.
6092 * curr_task - return the current task for a given CPU.
6093 * @cpu: the processor in question.
6095 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6097 * Return: The current task for @cpu.
6099 struct task_struct
*curr_task(int cpu
)
6101 return cpu_curr(cpu
);
6104 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6108 * set_curr_task - set the current task for a given CPU.
6109 * @cpu: the processor in question.
6110 * @p: the task pointer to set.
6112 * Description: This function must only be used when non-maskable interrupts
6113 * are serviced on a separate stack. It allows the architecture to switch the
6114 * notion of the current task on a CPU in a non-blocking manner. This function
6115 * must be called with all CPU's synchronized, and interrupts disabled, the
6116 * and caller must save the original value of the current task (see
6117 * curr_task() above) and restore that value before reenabling interrupts and
6118 * re-starting the system.
6120 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6122 void ia64_set_curr_task(int cpu
, struct task_struct
*p
)
6129 #ifdef CONFIG_CGROUP_SCHED
6130 /* task_group_lock serializes the addition/removal of task groups */
6131 static DEFINE_SPINLOCK(task_group_lock
);
6133 static void sched_free_group(struct task_group
*tg
)
6135 free_fair_sched_group(tg
);
6136 free_rt_sched_group(tg
);
6138 kmem_cache_free(task_group_cache
, tg
);
6141 /* allocate runqueue etc for a new task group */
6142 struct task_group
*sched_create_group(struct task_group
*parent
)
6144 struct task_group
*tg
;
6146 tg
= kmem_cache_alloc(task_group_cache
, GFP_KERNEL
| __GFP_ZERO
);
6148 return ERR_PTR(-ENOMEM
);
6150 if (!alloc_fair_sched_group(tg
, parent
))
6153 if (!alloc_rt_sched_group(tg
, parent
))
6159 sched_free_group(tg
);
6160 return ERR_PTR(-ENOMEM
);
6163 void sched_online_group(struct task_group
*tg
, struct task_group
*parent
)
6165 unsigned long flags
;
6167 spin_lock_irqsave(&task_group_lock
, flags
);
6168 list_add_rcu(&tg
->list
, &task_groups
);
6170 /* Root should already exist: */
6173 tg
->parent
= parent
;
6174 INIT_LIST_HEAD(&tg
->children
);
6175 list_add_rcu(&tg
->siblings
, &parent
->children
);
6176 spin_unlock_irqrestore(&task_group_lock
, flags
);
6178 online_fair_sched_group(tg
);
6181 /* rcu callback to free various structures associated with a task group */
6182 static void sched_free_group_rcu(struct rcu_head
*rhp
)
6184 /* Now it should be safe to free those cfs_rqs: */
6185 sched_free_group(container_of(rhp
, struct task_group
, rcu
));
6188 void sched_destroy_group(struct task_group
*tg
)
6190 /* Wait for possible concurrent references to cfs_rqs complete: */
6191 call_rcu(&tg
->rcu
, sched_free_group_rcu
);
6194 void sched_offline_group(struct task_group
*tg
)
6196 unsigned long flags
;
6198 /* End participation in shares distribution: */
6199 unregister_fair_sched_group(tg
);
6201 spin_lock_irqsave(&task_group_lock
, flags
);
6202 list_del_rcu(&tg
->list
);
6203 list_del_rcu(&tg
->siblings
);
6204 spin_unlock_irqrestore(&task_group_lock
, flags
);
6207 static void sched_change_group(struct task_struct
*tsk
, int type
)
6209 struct task_group
*tg
;
6212 * All callers are synchronized by task_rq_lock(); we do not use RCU
6213 * which is pointless here. Thus, we pass "true" to task_css_check()
6214 * to prevent lockdep warnings.
6216 tg
= container_of(task_css_check(tsk
, cpu_cgrp_id
, true),
6217 struct task_group
, css
);
6218 tg
= autogroup_task_group(tsk
, tg
);
6219 tsk
->sched_task_group
= tg
;
6221 #ifdef CONFIG_FAIR_GROUP_SCHED
6222 if (tsk
->sched_class
->task_change_group
)
6223 tsk
->sched_class
->task_change_group(tsk
, type
);
6226 set_task_rq(tsk
, task_cpu(tsk
));
6230 * Change task's runqueue when it moves between groups.
6232 * The caller of this function should have put the task in its new group by
6233 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6236 void sched_move_task(struct task_struct
*tsk
)
6238 int queued
, running
, queue_flags
=
6239 DEQUEUE_SAVE
| DEQUEUE_MOVE
| DEQUEUE_NOCLOCK
;
6243 rq
= task_rq_lock(tsk
, &rf
);
6244 update_rq_clock(rq
);
6246 running
= task_current(rq
, tsk
);
6247 queued
= task_on_rq_queued(tsk
);
6250 dequeue_task(rq
, tsk
, queue_flags
);
6252 put_prev_task(rq
, tsk
);
6254 sched_change_group(tsk
, TASK_MOVE_GROUP
);
6257 enqueue_task(rq
, tsk
, queue_flags
);
6259 set_curr_task(rq
, tsk
);
6261 task_rq_unlock(rq
, tsk
, &rf
);
6264 static inline struct task_group
*css_tg(struct cgroup_subsys_state
*css
)
6266 return css
? container_of(css
, struct task_group
, css
) : NULL
;
6269 static struct cgroup_subsys_state
*
6270 cpu_cgroup_css_alloc(struct cgroup_subsys_state
*parent_css
)
6272 struct task_group
*parent
= css_tg(parent_css
);
6273 struct task_group
*tg
;
6276 /* This is early initialization for the top cgroup */
6277 return &root_task_group
.css
;
6280 tg
= sched_create_group(parent
);
6282 return ERR_PTR(-ENOMEM
);
6287 /* Expose task group only after completing cgroup initialization */
6288 static int cpu_cgroup_css_online(struct cgroup_subsys_state
*css
)
6290 struct task_group
*tg
= css_tg(css
);
6291 struct task_group
*parent
= css_tg(css
->parent
);
6294 sched_online_group(tg
, parent
);
6298 static void cpu_cgroup_css_released(struct cgroup_subsys_state
*css
)
6300 struct task_group
*tg
= css_tg(css
);
6302 sched_offline_group(tg
);
6305 static void cpu_cgroup_css_free(struct cgroup_subsys_state
*css
)
6307 struct task_group
*tg
= css_tg(css
);
6310 * Relies on the RCU grace period between css_released() and this.
6312 sched_free_group(tg
);
6316 * This is called before wake_up_new_task(), therefore we really only
6317 * have to set its group bits, all the other stuff does not apply.
6319 static void cpu_cgroup_fork(struct task_struct
*task
)
6324 rq
= task_rq_lock(task
, &rf
);
6326 update_rq_clock(rq
);
6327 sched_change_group(task
, TASK_SET_GROUP
);
6329 task_rq_unlock(rq
, task
, &rf
);
6332 static int cpu_cgroup_can_attach(struct cgroup_taskset
*tset
)
6334 struct task_struct
*task
;
6335 struct cgroup_subsys_state
*css
;
6338 cgroup_taskset_for_each(task
, css
, tset
) {
6339 #ifdef CONFIG_RT_GROUP_SCHED
6340 if (!sched_rt_can_attach(css_tg(css
), task
))
6343 /* We don't support RT-tasks being in separate groups */
6344 if (task
->sched_class
!= &fair_sched_class
)
6348 * Serialize against wake_up_new_task() such that if its
6349 * running, we're sure to observe its full state.
6351 raw_spin_lock_irq(&task
->pi_lock
);
6353 * Avoid calling sched_move_task() before wake_up_new_task()
6354 * has happened. This would lead to problems with PELT, due to
6355 * move wanting to detach+attach while we're not attached yet.
6357 if (task
->state
== TASK_NEW
)
6359 raw_spin_unlock_irq(&task
->pi_lock
);
6367 static void cpu_cgroup_attach(struct cgroup_taskset
*tset
)
6369 struct task_struct
*task
;
6370 struct cgroup_subsys_state
*css
;
6372 cgroup_taskset_for_each(task
, css
, tset
)
6373 sched_move_task(task
);
6376 #ifdef CONFIG_FAIR_GROUP_SCHED
6377 static int cpu_shares_write_u64(struct cgroup_subsys_state
*css
,
6378 struct cftype
*cftype
, u64 shareval
)
6380 return sched_group_set_shares(css_tg(css
), scale_load(shareval
));
6383 static u64
cpu_shares_read_u64(struct cgroup_subsys_state
*css
,
6386 struct task_group
*tg
= css_tg(css
);
6388 return (u64
) scale_load_down(tg
->shares
);
6391 #ifdef CONFIG_CFS_BANDWIDTH
6392 static DEFINE_MUTEX(cfs_constraints_mutex
);
6394 const u64 max_cfs_quota_period
= 1 * NSEC_PER_SEC
; /* 1s */
6395 const u64 min_cfs_quota_period
= 1 * NSEC_PER_MSEC
; /* 1ms */
6397 static int __cfs_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
);
6399 static int tg_set_cfs_bandwidth(struct task_group
*tg
, u64 period
, u64 quota
)
6401 int i
, ret
= 0, runtime_enabled
, runtime_was_enabled
;
6402 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
6404 if (tg
== &root_task_group
)
6408 * Ensure we have at some amount of bandwidth every period. This is
6409 * to prevent reaching a state of large arrears when throttled via
6410 * entity_tick() resulting in prolonged exit starvation.
6412 if (quota
< min_cfs_quota_period
|| period
< min_cfs_quota_period
)
6416 * Likewise, bound things on the otherside by preventing insane quota
6417 * periods. This also allows us to normalize in computing quota
6420 if (period
> max_cfs_quota_period
)
6424 * Prevent race between setting of cfs_rq->runtime_enabled and
6425 * unthrottle_offline_cfs_rqs().
6428 mutex_lock(&cfs_constraints_mutex
);
6429 ret
= __cfs_schedulable(tg
, period
, quota
);
6433 runtime_enabled
= quota
!= RUNTIME_INF
;
6434 runtime_was_enabled
= cfs_b
->quota
!= RUNTIME_INF
;
6436 * If we need to toggle cfs_bandwidth_used, off->on must occur
6437 * before making related changes, and on->off must occur afterwards
6439 if (runtime_enabled
&& !runtime_was_enabled
)
6440 cfs_bandwidth_usage_inc();
6441 raw_spin_lock_irq(&cfs_b
->lock
);
6442 cfs_b
->period
= ns_to_ktime(period
);
6443 cfs_b
->quota
= quota
;
6445 __refill_cfs_bandwidth_runtime(cfs_b
);
6447 /* Restart the period timer (if active) to handle new period expiry: */
6448 if (runtime_enabled
)
6449 start_cfs_bandwidth(cfs_b
);
6451 raw_spin_unlock_irq(&cfs_b
->lock
);
6453 for_each_online_cpu(i
) {
6454 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[i
];
6455 struct rq
*rq
= cfs_rq
->rq
;
6458 rq_lock_irq(rq
, &rf
);
6459 cfs_rq
->runtime_enabled
= runtime_enabled
;
6460 cfs_rq
->runtime_remaining
= 0;
6462 if (cfs_rq
->throttled
)
6463 unthrottle_cfs_rq(cfs_rq
);
6464 rq_unlock_irq(rq
, &rf
);
6466 if (runtime_was_enabled
&& !runtime_enabled
)
6467 cfs_bandwidth_usage_dec();
6469 mutex_unlock(&cfs_constraints_mutex
);
6475 int tg_set_cfs_quota(struct task_group
*tg
, long cfs_quota_us
)
6479 period
= ktime_to_ns(tg
->cfs_bandwidth
.period
);
6480 if (cfs_quota_us
< 0)
6481 quota
= RUNTIME_INF
;
6483 quota
= (u64
)cfs_quota_us
* NSEC_PER_USEC
;
6485 return tg_set_cfs_bandwidth(tg
, period
, quota
);
6488 long tg_get_cfs_quota(struct task_group
*tg
)
6492 if (tg
->cfs_bandwidth
.quota
== RUNTIME_INF
)
6495 quota_us
= tg
->cfs_bandwidth
.quota
;
6496 do_div(quota_us
, NSEC_PER_USEC
);
6501 int tg_set_cfs_period(struct task_group
*tg
, long cfs_period_us
)
6505 period
= (u64
)cfs_period_us
* NSEC_PER_USEC
;
6506 quota
= tg
->cfs_bandwidth
.quota
;
6508 return tg_set_cfs_bandwidth(tg
, period
, quota
);
6511 long tg_get_cfs_period(struct task_group
*tg
)
6515 cfs_period_us
= ktime_to_ns(tg
->cfs_bandwidth
.period
);
6516 do_div(cfs_period_us
, NSEC_PER_USEC
);
6518 return cfs_period_us
;
6521 static s64
cpu_cfs_quota_read_s64(struct cgroup_subsys_state
*css
,
6524 return tg_get_cfs_quota(css_tg(css
));
6527 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state
*css
,
6528 struct cftype
*cftype
, s64 cfs_quota_us
)
6530 return tg_set_cfs_quota(css_tg(css
), cfs_quota_us
);
6533 static u64
cpu_cfs_period_read_u64(struct cgroup_subsys_state
*css
,
6536 return tg_get_cfs_period(css_tg(css
));
6539 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state
*css
,
6540 struct cftype
*cftype
, u64 cfs_period_us
)
6542 return tg_set_cfs_period(css_tg(css
), cfs_period_us
);
6545 struct cfs_schedulable_data
{
6546 struct task_group
*tg
;
6551 * normalize group quota/period to be quota/max_period
6552 * note: units are usecs
6554 static u64
normalize_cfs_quota(struct task_group
*tg
,
6555 struct cfs_schedulable_data
*d
)
6563 period
= tg_get_cfs_period(tg
);
6564 quota
= tg_get_cfs_quota(tg
);
6567 /* note: these should typically be equivalent */
6568 if (quota
== RUNTIME_INF
|| quota
== -1)
6571 return to_ratio(period
, quota
);
6574 static int tg_cfs_schedulable_down(struct task_group
*tg
, void *data
)
6576 struct cfs_schedulable_data
*d
= data
;
6577 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
6578 s64 quota
= 0, parent_quota
= -1;
6581 quota
= RUNTIME_INF
;
6583 struct cfs_bandwidth
*parent_b
= &tg
->parent
->cfs_bandwidth
;
6585 quota
= normalize_cfs_quota(tg
, d
);
6586 parent_quota
= parent_b
->hierarchical_quota
;
6589 * Ensure max(child_quota) <= parent_quota, inherit when no
6592 if (quota
== RUNTIME_INF
)
6593 quota
= parent_quota
;
6594 else if (parent_quota
!= RUNTIME_INF
&& quota
> parent_quota
)
6597 cfs_b
->hierarchical_quota
= quota
;
6602 static int __cfs_schedulable(struct task_group
*tg
, u64 period
, u64 quota
)
6605 struct cfs_schedulable_data data
= {
6611 if (quota
!= RUNTIME_INF
) {
6612 do_div(data
.period
, NSEC_PER_USEC
);
6613 do_div(data
.quota
, NSEC_PER_USEC
);
6617 ret
= walk_tg_tree(tg_cfs_schedulable_down
, tg_nop
, &data
);
6623 static int cpu_stats_show(struct seq_file
*sf
, void *v
)
6625 struct task_group
*tg
= css_tg(seq_css(sf
));
6626 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
6628 seq_printf(sf
, "nr_periods %d\n", cfs_b
->nr_periods
);
6629 seq_printf(sf
, "nr_throttled %d\n", cfs_b
->nr_throttled
);
6630 seq_printf(sf
, "throttled_time %llu\n", cfs_b
->throttled_time
);
6634 #endif /* CONFIG_CFS_BANDWIDTH */
6635 #endif /* CONFIG_FAIR_GROUP_SCHED */
6637 #ifdef CONFIG_RT_GROUP_SCHED
6638 static int cpu_rt_runtime_write(struct cgroup_subsys_state
*css
,
6639 struct cftype
*cft
, s64 val
)
6641 return sched_group_set_rt_runtime(css_tg(css
), val
);
6644 static s64
cpu_rt_runtime_read(struct cgroup_subsys_state
*css
,
6647 return sched_group_rt_runtime(css_tg(css
));
6650 static int cpu_rt_period_write_uint(struct cgroup_subsys_state
*css
,
6651 struct cftype
*cftype
, u64 rt_period_us
)
6653 return sched_group_set_rt_period(css_tg(css
), rt_period_us
);
6656 static u64
cpu_rt_period_read_uint(struct cgroup_subsys_state
*css
,
6659 return sched_group_rt_period(css_tg(css
));
6661 #endif /* CONFIG_RT_GROUP_SCHED */
6663 static struct cftype cpu_files
[] = {
6664 #ifdef CONFIG_FAIR_GROUP_SCHED
6667 .read_u64
= cpu_shares_read_u64
,
6668 .write_u64
= cpu_shares_write_u64
,
6671 #ifdef CONFIG_CFS_BANDWIDTH
6673 .name
= "cfs_quota_us",
6674 .read_s64
= cpu_cfs_quota_read_s64
,
6675 .write_s64
= cpu_cfs_quota_write_s64
,
6678 .name
= "cfs_period_us",
6679 .read_u64
= cpu_cfs_period_read_u64
,
6680 .write_u64
= cpu_cfs_period_write_u64
,
6684 .seq_show
= cpu_stats_show
,
6687 #ifdef CONFIG_RT_GROUP_SCHED
6689 .name
= "rt_runtime_us",
6690 .read_s64
= cpu_rt_runtime_read
,
6691 .write_s64
= cpu_rt_runtime_write
,
6694 .name
= "rt_period_us",
6695 .read_u64
= cpu_rt_period_read_uint
,
6696 .write_u64
= cpu_rt_period_write_uint
,
6702 struct cgroup_subsys cpu_cgrp_subsys
= {
6703 .css_alloc
= cpu_cgroup_css_alloc
,
6704 .css_online
= cpu_cgroup_css_online
,
6705 .css_released
= cpu_cgroup_css_released
,
6706 .css_free
= cpu_cgroup_css_free
,
6707 .fork
= cpu_cgroup_fork
,
6708 .can_attach
= cpu_cgroup_can_attach
,
6709 .attach
= cpu_cgroup_attach
,
6710 .legacy_cftypes
= cpu_files
,
6714 #endif /* CONFIG_CGROUP_SCHED */
6716 void dump_cpu_task(int cpu
)
6718 pr_info("Task dump for CPU %d:\n", cpu
);
6719 sched_show_task(cpu_curr(cpu
));
6723 * Nice levels are multiplicative, with a gentle 10% change for every
6724 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
6725 * nice 1, it will get ~10% less CPU time than another CPU-bound task
6726 * that remained on nice 0.
6728 * The "10% effect" is relative and cumulative: from _any_ nice level,
6729 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
6730 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
6731 * If a task goes up by ~10% and another task goes down by ~10% then
6732 * the relative distance between them is ~25%.)
6734 const int sched_prio_to_weight
[40] = {
6735 /* -20 */ 88761, 71755, 56483, 46273, 36291,
6736 /* -15 */ 29154, 23254, 18705, 14949, 11916,
6737 /* -10 */ 9548, 7620, 6100, 4904, 3906,
6738 /* -5 */ 3121, 2501, 1991, 1586, 1277,
6739 /* 0 */ 1024, 820, 655, 526, 423,
6740 /* 5 */ 335, 272, 215, 172, 137,
6741 /* 10 */ 110, 87, 70, 56, 45,
6742 /* 15 */ 36, 29, 23, 18, 15,
6746 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
6748 * In cases where the weight does not change often, we can use the
6749 * precalculated inverse to speed up arithmetics by turning divisions
6750 * into multiplications:
6752 const u32 sched_prio_to_wmult
[40] = {
6753 /* -20 */ 48388, 59856, 76040, 92818, 118348,
6754 /* -15 */ 147320, 184698, 229616, 287308, 360437,
6755 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
6756 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
6757 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
6758 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
6759 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
6760 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,