sched/core: Fix possible Spectre-v1 indexing for sched_prio_to_weight[]
[linux/fpc-iii.git] / kernel / sched / core.c
blob5f37ef9f6cd5030a495e868e324c887d22b04b4b
1 /*
2 * kernel/sched/core.c
4 * Core kernel scheduler code and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
7 */
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>
19 #include <linux/compat.h>
21 #include <linux/blkdev.h>
22 #include <linux/kprobes.h>
23 #include <linux/mmu_context.h>
24 #include <linux/module.h>
25 #include <linux/nmi.h>
26 #include <linux/nospec.h>
27 #include <linux/prefetch.h>
28 #include <linux/profile.h>
29 #include <linux/security.h>
30 #include <linux/syscalls.h>
31 #include <linux/sched/isolation.h>
33 #include <asm/switch_to.h>
34 #include <asm/tlb.h>
35 #ifdef CONFIG_PARAVIRT
36 #include <asm/paravirt.h>
37 #endif
39 #include "sched.h"
40 #include "../workqueue_internal.h"
41 #include "../smpboot.h"
43 #define CREATE_TRACE_POINTS
44 #include <trace/events/sched.h>
46 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
48 #if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL)
50 * Debugging: various feature bits
52 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
53 * sysctl_sched_features, defined in sched.h, to allow constants propagation
54 * at compile time and compiler optimization based on features default.
56 #define SCHED_FEAT(name, enabled) \
57 (1UL << __SCHED_FEAT_##name) * enabled |
58 const_debug unsigned int sysctl_sched_features =
59 #include "features.h"
61 #undef SCHED_FEAT
62 #endif
65 * Number of tasks to iterate in a single balance run.
66 * Limited because this is done with IRQs disabled.
68 const_debug unsigned int sysctl_sched_nr_migrate = 32;
71 * period over which we average the RT time consumption, measured
72 * in ms.
74 * default: 1s
76 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
79 * period over which we measure -rt task CPU usage in us.
80 * default: 1s
82 unsigned int sysctl_sched_rt_period = 1000000;
84 __read_mostly int scheduler_running;
87 * part of the period that we allow rt tasks to run in us.
88 * default: 0.95s
90 int sysctl_sched_rt_runtime = 950000;
93 * __task_rq_lock - lock the rq @p resides on.
95 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
96 __acquires(rq->lock)
98 struct rq *rq;
100 lockdep_assert_held(&p->pi_lock);
102 for (;;) {
103 rq = task_rq(p);
104 raw_spin_lock(&rq->lock);
105 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
106 rq_pin_lock(rq, rf);
107 return rq;
109 raw_spin_unlock(&rq->lock);
111 while (unlikely(task_on_rq_migrating(p)))
112 cpu_relax();
117 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
119 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
120 __acquires(p->pi_lock)
121 __acquires(rq->lock)
123 struct rq *rq;
125 for (;;) {
126 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
127 rq = task_rq(p);
128 raw_spin_lock(&rq->lock);
130 * move_queued_task() task_rq_lock()
132 * ACQUIRE (rq->lock)
133 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
134 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
135 * [S] ->cpu = new_cpu [L] task_rq()
136 * [L] ->on_rq
137 * RELEASE (rq->lock)
139 * If we observe the old cpu in task_rq_lock, the acquire of
140 * the old rq->lock will fully serialize against the stores.
142 * If we observe the new CPU in task_rq_lock, the acquire will
143 * pair with the WMB to ensure we must then also see migrating.
145 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
146 rq_pin_lock(rq, rf);
147 return rq;
149 raw_spin_unlock(&rq->lock);
150 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
152 while (unlikely(task_on_rq_migrating(p)))
153 cpu_relax();
158 * RQ-clock updating methods:
161 static void update_rq_clock_task(struct rq *rq, s64 delta)
164 * In theory, the compile should just see 0 here, and optimize out the call
165 * to sched_rt_avg_update. But I don't trust it...
167 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
168 s64 steal = 0, irq_delta = 0;
169 #endif
170 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
171 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
174 * Since irq_time is only updated on {soft,}irq_exit, we might run into
175 * this case when a previous update_rq_clock() happened inside a
176 * {soft,}irq region.
178 * When this happens, we stop ->clock_task and only update the
179 * prev_irq_time stamp to account for the part that fit, so that a next
180 * update will consume the rest. This ensures ->clock_task is
181 * monotonic.
183 * It does however cause some slight miss-attribution of {soft,}irq
184 * time, a more accurate solution would be to update the irq_time using
185 * the current rq->clock timestamp, except that would require using
186 * atomic ops.
188 if (irq_delta > delta)
189 irq_delta = delta;
191 rq->prev_irq_time += irq_delta;
192 delta -= irq_delta;
193 #endif
194 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
195 if (static_key_false((&paravirt_steal_rq_enabled))) {
196 steal = paravirt_steal_clock(cpu_of(rq));
197 steal -= rq->prev_steal_time_rq;
199 if (unlikely(steal > delta))
200 steal = delta;
202 rq->prev_steal_time_rq += steal;
203 delta -= steal;
205 #endif
207 rq->clock_task += delta;
209 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
210 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
211 sched_rt_avg_update(rq, irq_delta + steal);
212 #endif
215 void update_rq_clock(struct rq *rq)
217 s64 delta;
219 lockdep_assert_held(&rq->lock);
221 if (rq->clock_update_flags & RQCF_ACT_SKIP)
222 return;
224 #ifdef CONFIG_SCHED_DEBUG
225 if (sched_feat(WARN_DOUBLE_CLOCK))
226 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
227 rq->clock_update_flags |= RQCF_UPDATED;
228 #endif
230 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
231 if (delta < 0)
232 return;
233 rq->clock += delta;
234 update_rq_clock_task(rq, delta);
238 #ifdef CONFIG_SCHED_HRTICK
240 * Use HR-timers to deliver accurate preemption points.
243 static void hrtick_clear(struct rq *rq)
245 if (hrtimer_active(&rq->hrtick_timer))
246 hrtimer_cancel(&rq->hrtick_timer);
250 * High-resolution timer tick.
251 * Runs from hardirq context with interrupts disabled.
253 static enum hrtimer_restart hrtick(struct hrtimer *timer)
255 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
256 struct rq_flags rf;
258 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
260 rq_lock(rq, &rf);
261 update_rq_clock(rq);
262 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
263 rq_unlock(rq, &rf);
265 return HRTIMER_NORESTART;
268 #ifdef CONFIG_SMP
270 static void __hrtick_restart(struct rq *rq)
272 struct hrtimer *timer = &rq->hrtick_timer;
274 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
278 * called from hardirq (IPI) context
280 static void __hrtick_start(void *arg)
282 struct rq *rq = arg;
283 struct rq_flags rf;
285 rq_lock(rq, &rf);
286 __hrtick_restart(rq);
287 rq->hrtick_csd_pending = 0;
288 rq_unlock(rq, &rf);
292 * Called to set the hrtick timer state.
294 * called with rq->lock held and irqs disabled
296 void hrtick_start(struct rq *rq, u64 delay)
298 struct hrtimer *timer = &rq->hrtick_timer;
299 ktime_t time;
300 s64 delta;
303 * Don't schedule slices shorter than 10000ns, that just
304 * doesn't make sense and can cause timer DoS.
306 delta = max_t(s64, delay, 10000LL);
307 time = ktime_add_ns(timer->base->get_time(), delta);
309 hrtimer_set_expires(timer, time);
311 if (rq == this_rq()) {
312 __hrtick_restart(rq);
313 } else if (!rq->hrtick_csd_pending) {
314 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
315 rq->hrtick_csd_pending = 1;
319 #else
321 * Called to set the hrtick timer state.
323 * called with rq->lock held and irqs disabled
325 void hrtick_start(struct rq *rq, u64 delay)
328 * Don't schedule slices shorter than 10000ns, that just
329 * doesn't make sense. Rely on vruntime for fairness.
331 delay = max_t(u64, delay, 10000LL);
332 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
333 HRTIMER_MODE_REL_PINNED);
335 #endif /* CONFIG_SMP */
337 static void init_rq_hrtick(struct rq *rq)
339 #ifdef CONFIG_SMP
340 rq->hrtick_csd_pending = 0;
342 rq->hrtick_csd.flags = 0;
343 rq->hrtick_csd.func = __hrtick_start;
344 rq->hrtick_csd.info = rq;
345 #endif
347 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
348 rq->hrtick_timer.function = hrtick;
350 #else /* CONFIG_SCHED_HRTICK */
351 static inline void hrtick_clear(struct rq *rq)
355 static inline void init_rq_hrtick(struct rq *rq)
358 #endif /* CONFIG_SCHED_HRTICK */
361 * cmpxchg based fetch_or, macro so it works for different integer types
363 #define fetch_or(ptr, mask) \
364 ({ \
365 typeof(ptr) _ptr = (ptr); \
366 typeof(mask) _mask = (mask); \
367 typeof(*_ptr) _old, _val = *_ptr; \
369 for (;;) { \
370 _old = cmpxchg(_ptr, _val, _val | _mask); \
371 if (_old == _val) \
372 break; \
373 _val = _old; \
375 _old; \
378 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
380 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
381 * this avoids any races wrt polling state changes and thereby avoids
382 * spurious IPIs.
384 static bool set_nr_and_not_polling(struct task_struct *p)
386 struct thread_info *ti = task_thread_info(p);
387 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
391 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
393 * If this returns true, then the idle task promises to call
394 * sched_ttwu_pending() and reschedule soon.
396 static bool set_nr_if_polling(struct task_struct *p)
398 struct thread_info *ti = task_thread_info(p);
399 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
401 for (;;) {
402 if (!(val & _TIF_POLLING_NRFLAG))
403 return false;
404 if (val & _TIF_NEED_RESCHED)
405 return true;
406 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
407 if (old == val)
408 break;
409 val = old;
411 return true;
414 #else
415 static bool set_nr_and_not_polling(struct task_struct *p)
417 set_tsk_need_resched(p);
418 return true;
421 #ifdef CONFIG_SMP
422 static bool set_nr_if_polling(struct task_struct *p)
424 return false;
426 #endif
427 #endif
429 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
431 struct wake_q_node *node = &task->wake_q;
434 * Atomically grab the task, if ->wake_q is !nil already it means
435 * its already queued (either by us or someone else) and will get the
436 * wakeup due to that.
438 * This cmpxchg() implies a full barrier, which pairs with the write
439 * barrier implied by the wakeup in wake_up_q().
441 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
442 return;
444 get_task_struct(task);
447 * The head is context local, there can be no concurrency.
449 *head->lastp = node;
450 head->lastp = &node->next;
453 void wake_up_q(struct wake_q_head *head)
455 struct wake_q_node *node = head->first;
457 while (node != WAKE_Q_TAIL) {
458 struct task_struct *task;
460 task = container_of(node, struct task_struct, wake_q);
461 BUG_ON(!task);
462 /* Task can safely be re-inserted now: */
463 node = node->next;
464 task->wake_q.next = NULL;
467 * wake_up_process() implies a wmb() to pair with the queueing
468 * in wake_q_add() so as not to miss wakeups.
470 wake_up_process(task);
471 put_task_struct(task);
476 * resched_curr - mark rq's current task 'to be rescheduled now'.
478 * On UP this means the setting of the need_resched flag, on SMP it
479 * might also involve a cross-CPU call to trigger the scheduler on
480 * the target CPU.
482 void resched_curr(struct rq *rq)
484 struct task_struct *curr = rq->curr;
485 int cpu;
487 lockdep_assert_held(&rq->lock);
489 if (test_tsk_need_resched(curr))
490 return;
492 cpu = cpu_of(rq);
494 if (cpu == smp_processor_id()) {
495 set_tsk_need_resched(curr);
496 set_preempt_need_resched();
497 return;
500 if (set_nr_and_not_polling(curr))
501 smp_send_reschedule(cpu);
502 else
503 trace_sched_wake_idle_without_ipi(cpu);
506 void resched_cpu(int cpu)
508 struct rq *rq = cpu_rq(cpu);
509 unsigned long flags;
511 raw_spin_lock_irqsave(&rq->lock, flags);
512 if (cpu_online(cpu) || cpu == smp_processor_id())
513 resched_curr(rq);
514 raw_spin_unlock_irqrestore(&rq->lock, flags);
517 #ifdef CONFIG_SMP
518 #ifdef CONFIG_NO_HZ_COMMON
520 * In the semi idle case, use the nearest busy CPU for migrating timers
521 * from an idle CPU. This is good for power-savings.
523 * We don't do similar optimization for completely idle system, as
524 * selecting an idle CPU will add more delays to the timers than intended
525 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
527 int get_nohz_timer_target(void)
529 int i, cpu = smp_processor_id();
530 struct sched_domain *sd;
532 if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
533 return cpu;
535 rcu_read_lock();
536 for_each_domain(cpu, sd) {
537 for_each_cpu(i, sched_domain_span(sd)) {
538 if (cpu == i)
539 continue;
541 if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
542 cpu = i;
543 goto unlock;
548 if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
549 cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
550 unlock:
551 rcu_read_unlock();
552 return cpu;
556 * When add_timer_on() enqueues a timer into the timer wheel of an
557 * idle CPU then this timer might expire before the next timer event
558 * which is scheduled to wake up that CPU. In case of a completely
559 * idle system the next event might even be infinite time into the
560 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
561 * leaves the inner idle loop so the newly added timer is taken into
562 * account when the CPU goes back to idle and evaluates the timer
563 * wheel for the next timer event.
565 static void wake_up_idle_cpu(int cpu)
567 struct rq *rq = cpu_rq(cpu);
569 if (cpu == smp_processor_id())
570 return;
572 if (set_nr_and_not_polling(rq->idle))
573 smp_send_reschedule(cpu);
574 else
575 trace_sched_wake_idle_without_ipi(cpu);
578 static bool wake_up_full_nohz_cpu(int cpu)
581 * We just need the target to call irq_exit() and re-evaluate
582 * the next tick. The nohz full kick at least implies that.
583 * If needed we can still optimize that later with an
584 * empty IRQ.
586 if (cpu_is_offline(cpu))
587 return true; /* Don't try to wake offline CPUs. */
588 if (tick_nohz_full_cpu(cpu)) {
589 if (cpu != smp_processor_id() ||
590 tick_nohz_tick_stopped())
591 tick_nohz_full_kick_cpu(cpu);
592 return true;
595 return false;
599 * Wake up the specified CPU. If the CPU is going offline, it is the
600 * caller's responsibility to deal with the lost wakeup, for example,
601 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
603 void wake_up_nohz_cpu(int cpu)
605 if (!wake_up_full_nohz_cpu(cpu))
606 wake_up_idle_cpu(cpu);
609 static inline bool got_nohz_idle_kick(void)
611 int cpu = smp_processor_id();
613 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
614 return false;
616 if (idle_cpu(cpu) && !need_resched())
617 return true;
620 * We can't run Idle Load Balance on this CPU for this time so we
621 * cancel it and clear NOHZ_BALANCE_KICK
623 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
624 return false;
627 #else /* CONFIG_NO_HZ_COMMON */
629 static inline bool got_nohz_idle_kick(void)
631 return false;
634 #endif /* CONFIG_NO_HZ_COMMON */
636 #ifdef CONFIG_NO_HZ_FULL
637 bool sched_can_stop_tick(struct rq *rq)
639 int fifo_nr_running;
641 /* Deadline tasks, even if single, need the tick */
642 if (rq->dl.dl_nr_running)
643 return false;
646 * If there are more than one RR tasks, we need the tick to effect the
647 * actual RR behaviour.
649 if (rq->rt.rr_nr_running) {
650 if (rq->rt.rr_nr_running == 1)
651 return true;
652 else
653 return false;
657 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
658 * forced preemption between FIFO tasks.
660 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
661 if (fifo_nr_running)
662 return true;
665 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
666 * if there's more than one we need the tick for involuntary
667 * preemption.
669 if (rq->nr_running > 1)
670 return false;
672 return true;
674 #endif /* CONFIG_NO_HZ_FULL */
676 void sched_avg_update(struct rq *rq)
678 s64 period = sched_avg_period();
680 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
682 * Inline assembly required to prevent the compiler
683 * optimising this loop into a divmod call.
684 * See __iter_div_u64_rem() for another example of this.
686 asm("" : "+rm" (rq->age_stamp));
687 rq->age_stamp += period;
688 rq->rt_avg /= 2;
692 #endif /* CONFIG_SMP */
694 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
695 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
697 * Iterate task_group tree rooted at *from, calling @down when first entering a
698 * node and @up when leaving it for the final time.
700 * Caller must hold rcu_lock or sufficient equivalent.
702 int walk_tg_tree_from(struct task_group *from,
703 tg_visitor down, tg_visitor up, void *data)
705 struct task_group *parent, *child;
706 int ret;
708 parent = from;
710 down:
711 ret = (*down)(parent, data);
712 if (ret)
713 goto out;
714 list_for_each_entry_rcu(child, &parent->children, siblings) {
715 parent = child;
716 goto down;
719 continue;
721 ret = (*up)(parent, data);
722 if (ret || parent == from)
723 goto out;
725 child = parent;
726 parent = parent->parent;
727 if (parent)
728 goto up;
729 out:
730 return ret;
733 int tg_nop(struct task_group *tg, void *data)
735 return 0;
737 #endif
739 static void set_load_weight(struct task_struct *p, bool update_load)
741 int prio = p->static_prio - MAX_RT_PRIO;
742 struct load_weight *load = &p->se.load;
745 * SCHED_IDLE tasks get minimal weight:
747 if (idle_policy(p->policy)) {
748 load->weight = scale_load(WEIGHT_IDLEPRIO);
749 load->inv_weight = WMULT_IDLEPRIO;
750 return;
754 * SCHED_OTHER tasks have to update their load when changing their
755 * weight
757 if (update_load && p->sched_class == &fair_sched_class) {
758 reweight_task(p, prio);
759 } else {
760 load->weight = scale_load(sched_prio_to_weight[prio]);
761 load->inv_weight = sched_prio_to_wmult[prio];
765 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
767 if (!(flags & ENQUEUE_NOCLOCK))
768 update_rq_clock(rq);
770 if (!(flags & ENQUEUE_RESTORE))
771 sched_info_queued(rq, p);
773 p->sched_class->enqueue_task(rq, p, flags);
776 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
778 if (!(flags & DEQUEUE_NOCLOCK))
779 update_rq_clock(rq);
781 if (!(flags & DEQUEUE_SAVE))
782 sched_info_dequeued(rq, p);
784 p->sched_class->dequeue_task(rq, p, flags);
787 void activate_task(struct rq *rq, struct task_struct *p, int flags)
789 if (task_contributes_to_load(p))
790 rq->nr_uninterruptible--;
792 enqueue_task(rq, p, flags);
795 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
797 if (task_contributes_to_load(p))
798 rq->nr_uninterruptible++;
800 dequeue_task(rq, p, flags);
804 * __normal_prio - return the priority that is based on the static prio
806 static inline int __normal_prio(struct task_struct *p)
808 return p->static_prio;
812 * Calculate the expected normal priority: i.e. priority
813 * without taking RT-inheritance into account. Might be
814 * boosted by interactivity modifiers. Changes upon fork,
815 * setprio syscalls, and whenever the interactivity
816 * estimator recalculates.
818 static inline int normal_prio(struct task_struct *p)
820 int prio;
822 if (task_has_dl_policy(p))
823 prio = MAX_DL_PRIO-1;
824 else if (task_has_rt_policy(p))
825 prio = MAX_RT_PRIO-1 - p->rt_priority;
826 else
827 prio = __normal_prio(p);
828 return prio;
832 * Calculate the current priority, i.e. the priority
833 * taken into account by the scheduler. This value might
834 * be boosted by RT tasks, or might be boosted by
835 * interactivity modifiers. Will be RT if the task got
836 * RT-boosted. If not then it returns p->normal_prio.
838 static int effective_prio(struct task_struct *p)
840 p->normal_prio = normal_prio(p);
842 * If we are RT tasks or we were boosted to RT priority,
843 * keep the priority unchanged. Otherwise, update priority
844 * to the normal priority:
846 if (!rt_prio(p->prio))
847 return p->normal_prio;
848 return p->prio;
852 * task_curr - is this task currently executing on a CPU?
853 * @p: the task in question.
855 * Return: 1 if the task is currently executing. 0 otherwise.
857 inline int task_curr(const struct task_struct *p)
859 return cpu_curr(task_cpu(p)) == p;
863 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
864 * use the balance_callback list if you want balancing.
866 * this means any call to check_class_changed() must be followed by a call to
867 * balance_callback().
869 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
870 const struct sched_class *prev_class,
871 int oldprio)
873 if (prev_class != p->sched_class) {
874 if (prev_class->switched_from)
875 prev_class->switched_from(rq, p);
877 p->sched_class->switched_to(rq, p);
878 } else if (oldprio != p->prio || dl_task(p))
879 p->sched_class->prio_changed(rq, p, oldprio);
882 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
884 const struct sched_class *class;
886 if (p->sched_class == rq->curr->sched_class) {
887 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
888 } else {
889 for_each_class(class) {
890 if (class == rq->curr->sched_class)
891 break;
892 if (class == p->sched_class) {
893 resched_curr(rq);
894 break;
900 * A queue event has occurred, and we're going to schedule. In
901 * this case, we can save a useless back to back clock update.
903 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
904 rq_clock_skip_update(rq, true);
907 #ifdef CONFIG_SMP
909 * This is how migration works:
911 * 1) we invoke migration_cpu_stop() on the target CPU using
912 * stop_one_cpu().
913 * 2) stopper starts to run (implicitly forcing the migrated thread
914 * off the CPU)
915 * 3) it checks whether the migrated task is still in the wrong runqueue.
916 * 4) if it's in the wrong runqueue then the migration thread removes
917 * it and puts it into the right queue.
918 * 5) stopper completes and stop_one_cpu() returns and the migration
919 * is done.
923 * move_queued_task - move a queued task to new rq.
925 * Returns (locked) new rq. Old rq's lock is released.
927 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
928 struct task_struct *p, int new_cpu)
930 lockdep_assert_held(&rq->lock);
932 p->on_rq = TASK_ON_RQ_MIGRATING;
933 dequeue_task(rq, p, DEQUEUE_NOCLOCK);
934 set_task_cpu(p, new_cpu);
935 rq_unlock(rq, rf);
937 rq = cpu_rq(new_cpu);
939 rq_lock(rq, rf);
940 BUG_ON(task_cpu(p) != new_cpu);
941 enqueue_task(rq, p, 0);
942 p->on_rq = TASK_ON_RQ_QUEUED;
943 check_preempt_curr(rq, p, 0);
945 return rq;
948 struct migration_arg {
949 struct task_struct *task;
950 int dest_cpu;
954 * Move (not current) task off this CPU, onto the destination CPU. We're doing
955 * this because either it can't run here any more (set_cpus_allowed()
956 * away from this CPU, or CPU going down), or because we're
957 * attempting to rebalance this task on exec (sched_exec).
959 * So we race with normal scheduler movements, but that's OK, as long
960 * as the task is no longer on this CPU.
962 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
963 struct task_struct *p, int dest_cpu)
965 if (p->flags & PF_KTHREAD) {
966 if (unlikely(!cpu_online(dest_cpu)))
967 return rq;
968 } else {
969 if (unlikely(!cpu_active(dest_cpu)))
970 return rq;
973 /* Affinity changed (again). */
974 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
975 return rq;
977 update_rq_clock(rq);
978 rq = move_queued_task(rq, rf, p, dest_cpu);
980 return rq;
984 * migration_cpu_stop - this will be executed by a highprio stopper thread
985 * and performs thread migration by bumping thread off CPU then
986 * 'pushing' onto another runqueue.
988 static int migration_cpu_stop(void *data)
990 struct migration_arg *arg = data;
991 struct task_struct *p = arg->task;
992 struct rq *rq = this_rq();
993 struct rq_flags rf;
996 * The original target CPU might have gone down and we might
997 * be on another CPU but it doesn't matter.
999 local_irq_disable();
1001 * We need to explicitly wake pending tasks before running
1002 * __migrate_task() such that we will not miss enforcing cpus_allowed
1003 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1005 sched_ttwu_pending();
1007 raw_spin_lock(&p->pi_lock);
1008 rq_lock(rq, &rf);
1010 * If task_rq(p) != rq, it cannot be migrated here, because we're
1011 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1012 * we're holding p->pi_lock.
1014 if (task_rq(p) == rq) {
1015 if (task_on_rq_queued(p))
1016 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
1017 else
1018 p->wake_cpu = arg->dest_cpu;
1020 rq_unlock(rq, &rf);
1021 raw_spin_unlock(&p->pi_lock);
1023 local_irq_enable();
1024 return 0;
1028 * sched_class::set_cpus_allowed must do the below, but is not required to
1029 * actually call this function.
1031 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1033 cpumask_copy(&p->cpus_allowed, new_mask);
1034 p->nr_cpus_allowed = cpumask_weight(new_mask);
1037 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1039 struct rq *rq = task_rq(p);
1040 bool queued, running;
1042 lockdep_assert_held(&p->pi_lock);
1044 queued = task_on_rq_queued(p);
1045 running = task_current(rq, p);
1047 if (queued) {
1049 * Because __kthread_bind() calls this on blocked tasks without
1050 * holding rq->lock.
1052 lockdep_assert_held(&rq->lock);
1053 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
1055 if (running)
1056 put_prev_task(rq, p);
1058 p->sched_class->set_cpus_allowed(p, new_mask);
1060 if (queued)
1061 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1062 if (running)
1063 set_curr_task(rq, p);
1067 * Change a given task's CPU affinity. Migrate the thread to a
1068 * proper CPU and schedule it away if the CPU it's executing on
1069 * is removed from the allowed bitmask.
1071 * NOTE: the caller must have a valid reference to the task, the
1072 * task must not exit() & deallocate itself prematurely. The
1073 * call is not atomic; no spinlocks may be held.
1075 static int __set_cpus_allowed_ptr(struct task_struct *p,
1076 const struct cpumask *new_mask, bool check)
1078 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1079 unsigned int dest_cpu;
1080 struct rq_flags rf;
1081 struct rq *rq;
1082 int ret = 0;
1084 rq = task_rq_lock(p, &rf);
1085 update_rq_clock(rq);
1087 if (p->flags & PF_KTHREAD) {
1089 * Kernel threads are allowed on online && !active CPUs
1091 cpu_valid_mask = cpu_online_mask;
1095 * Must re-check here, to close a race against __kthread_bind(),
1096 * sched_setaffinity() is not guaranteed to observe the flag.
1098 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1099 ret = -EINVAL;
1100 goto out;
1103 if (cpumask_equal(&p->cpus_allowed, new_mask))
1104 goto out;
1106 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1107 ret = -EINVAL;
1108 goto out;
1111 do_set_cpus_allowed(p, new_mask);
1113 if (p->flags & PF_KTHREAD) {
1115 * For kernel threads that do indeed end up on online &&
1116 * !active we want to ensure they are strict per-CPU threads.
1118 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1119 !cpumask_intersects(new_mask, cpu_active_mask) &&
1120 p->nr_cpus_allowed != 1);
1123 /* Can the task run on the task's current CPU? If so, we're done */
1124 if (cpumask_test_cpu(task_cpu(p), new_mask))
1125 goto out;
1127 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1128 if (task_running(rq, p) || p->state == TASK_WAKING) {
1129 struct migration_arg arg = { p, dest_cpu };
1130 /* Need help from migration thread: drop lock and wait. */
1131 task_rq_unlock(rq, p, &rf);
1132 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1133 tlb_migrate_finish(p->mm);
1134 return 0;
1135 } else if (task_on_rq_queued(p)) {
1137 * OK, since we're going to drop the lock immediately
1138 * afterwards anyway.
1140 rq = move_queued_task(rq, &rf, p, dest_cpu);
1142 out:
1143 task_rq_unlock(rq, p, &rf);
1145 return ret;
1148 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1150 return __set_cpus_allowed_ptr(p, new_mask, false);
1152 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1154 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1156 #ifdef CONFIG_SCHED_DEBUG
1158 * We should never call set_task_cpu() on a blocked task,
1159 * ttwu() will sort out the placement.
1161 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1162 !p->on_rq);
1165 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1166 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1167 * time relying on p->on_rq.
1169 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1170 p->sched_class == &fair_sched_class &&
1171 (p->on_rq && !task_on_rq_migrating(p)));
1173 #ifdef CONFIG_LOCKDEP
1175 * The caller should hold either p->pi_lock or rq->lock, when changing
1176 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1178 * sched_move_task() holds both and thus holding either pins the cgroup,
1179 * see task_group().
1181 * Furthermore, all task_rq users should acquire both locks, see
1182 * task_rq_lock().
1184 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1185 lockdep_is_held(&task_rq(p)->lock)));
1186 #endif
1188 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1190 WARN_ON_ONCE(!cpu_online(new_cpu));
1191 #endif
1193 trace_sched_migrate_task(p, new_cpu);
1195 if (task_cpu(p) != new_cpu) {
1196 if (p->sched_class->migrate_task_rq)
1197 p->sched_class->migrate_task_rq(p);
1198 p->se.nr_migrations++;
1199 perf_event_task_migrate(p);
1202 __set_task_cpu(p, new_cpu);
1205 static void __migrate_swap_task(struct task_struct *p, int cpu)
1207 if (task_on_rq_queued(p)) {
1208 struct rq *src_rq, *dst_rq;
1209 struct rq_flags srf, drf;
1211 src_rq = task_rq(p);
1212 dst_rq = cpu_rq(cpu);
1214 rq_pin_lock(src_rq, &srf);
1215 rq_pin_lock(dst_rq, &drf);
1217 p->on_rq = TASK_ON_RQ_MIGRATING;
1218 deactivate_task(src_rq, p, 0);
1219 set_task_cpu(p, cpu);
1220 activate_task(dst_rq, p, 0);
1221 p->on_rq = TASK_ON_RQ_QUEUED;
1222 check_preempt_curr(dst_rq, p, 0);
1224 rq_unpin_lock(dst_rq, &drf);
1225 rq_unpin_lock(src_rq, &srf);
1227 } else {
1229 * Task isn't running anymore; make it appear like we migrated
1230 * it before it went to sleep. This means on wakeup we make the
1231 * previous CPU our target instead of where it really is.
1233 p->wake_cpu = cpu;
1237 struct migration_swap_arg {
1238 struct task_struct *src_task, *dst_task;
1239 int src_cpu, dst_cpu;
1242 static int migrate_swap_stop(void *data)
1244 struct migration_swap_arg *arg = data;
1245 struct rq *src_rq, *dst_rq;
1246 int ret = -EAGAIN;
1248 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1249 return -EAGAIN;
1251 src_rq = cpu_rq(arg->src_cpu);
1252 dst_rq = cpu_rq(arg->dst_cpu);
1254 double_raw_lock(&arg->src_task->pi_lock,
1255 &arg->dst_task->pi_lock);
1256 double_rq_lock(src_rq, dst_rq);
1258 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1259 goto unlock;
1261 if (task_cpu(arg->src_task) != arg->src_cpu)
1262 goto unlock;
1264 if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
1265 goto unlock;
1267 if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
1268 goto unlock;
1270 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1271 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1273 ret = 0;
1275 unlock:
1276 double_rq_unlock(src_rq, dst_rq);
1277 raw_spin_unlock(&arg->dst_task->pi_lock);
1278 raw_spin_unlock(&arg->src_task->pi_lock);
1280 return ret;
1284 * Cross migrate two tasks
1286 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1288 struct migration_swap_arg arg;
1289 int ret = -EINVAL;
1291 arg = (struct migration_swap_arg){
1292 .src_task = cur,
1293 .src_cpu = task_cpu(cur),
1294 .dst_task = p,
1295 .dst_cpu = task_cpu(p),
1298 if (arg.src_cpu == arg.dst_cpu)
1299 goto out;
1302 * These three tests are all lockless; this is OK since all of them
1303 * will be re-checked with proper locks held further down the line.
1305 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1306 goto out;
1308 if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
1309 goto out;
1311 if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
1312 goto out;
1314 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1315 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1317 out:
1318 return ret;
1322 * wait_task_inactive - wait for a thread to unschedule.
1324 * If @match_state is nonzero, it's the @p->state value just checked and
1325 * not expected to change. If it changes, i.e. @p might have woken up,
1326 * then return zero. When we succeed in waiting for @p to be off its CPU,
1327 * we return a positive number (its total switch count). If a second call
1328 * a short while later returns the same number, the caller can be sure that
1329 * @p has remained unscheduled the whole time.
1331 * The caller must ensure that the task *will* unschedule sometime soon,
1332 * else this function might spin for a *long* time. This function can't
1333 * be called with interrupts off, or it may introduce deadlock with
1334 * smp_call_function() if an IPI is sent by the same process we are
1335 * waiting to become inactive.
1337 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1339 int running, queued;
1340 struct rq_flags rf;
1341 unsigned long ncsw;
1342 struct rq *rq;
1344 for (;;) {
1346 * We do the initial early heuristics without holding
1347 * any task-queue locks at all. We'll only try to get
1348 * the runqueue lock when things look like they will
1349 * work out!
1351 rq = task_rq(p);
1354 * If the task is actively running on another CPU
1355 * still, just relax and busy-wait without holding
1356 * any locks.
1358 * NOTE! Since we don't hold any locks, it's not
1359 * even sure that "rq" stays as the right runqueue!
1360 * But we don't care, since "task_running()" will
1361 * return false if the runqueue has changed and p
1362 * is actually now running somewhere else!
1364 while (task_running(rq, p)) {
1365 if (match_state && unlikely(p->state != match_state))
1366 return 0;
1367 cpu_relax();
1371 * Ok, time to look more closely! We need the rq
1372 * lock now, to be *sure*. If we're wrong, we'll
1373 * just go back and repeat.
1375 rq = task_rq_lock(p, &rf);
1376 trace_sched_wait_task(p);
1377 running = task_running(rq, p);
1378 queued = task_on_rq_queued(p);
1379 ncsw = 0;
1380 if (!match_state || p->state == match_state)
1381 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1382 task_rq_unlock(rq, p, &rf);
1385 * If it changed from the expected state, bail out now.
1387 if (unlikely(!ncsw))
1388 break;
1391 * Was it really running after all now that we
1392 * checked with the proper locks actually held?
1394 * Oops. Go back and try again..
1396 if (unlikely(running)) {
1397 cpu_relax();
1398 continue;
1402 * It's not enough that it's not actively running,
1403 * it must be off the runqueue _entirely_, and not
1404 * preempted!
1406 * So if it was still runnable (but just not actively
1407 * running right now), it's preempted, and we should
1408 * yield - it could be a while.
1410 if (unlikely(queued)) {
1411 ktime_t to = NSEC_PER_SEC / HZ;
1413 set_current_state(TASK_UNINTERRUPTIBLE);
1414 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1415 continue;
1419 * Ahh, all good. It wasn't running, and it wasn't
1420 * runnable, which means that it will never become
1421 * running in the future either. We're all done!
1423 break;
1426 return ncsw;
1429 /***
1430 * kick_process - kick a running thread to enter/exit the kernel
1431 * @p: the to-be-kicked thread
1433 * Cause a process which is running on another CPU to enter
1434 * kernel-mode, without any delay. (to get signals handled.)
1436 * NOTE: this function doesn't have to take the runqueue lock,
1437 * because all it wants to ensure is that the remote task enters
1438 * the kernel. If the IPI races and the task has been migrated
1439 * to another CPU then no harm is done and the purpose has been
1440 * achieved as well.
1442 void kick_process(struct task_struct *p)
1444 int cpu;
1446 preempt_disable();
1447 cpu = task_cpu(p);
1448 if ((cpu != smp_processor_id()) && task_curr(p))
1449 smp_send_reschedule(cpu);
1450 preempt_enable();
1452 EXPORT_SYMBOL_GPL(kick_process);
1455 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1457 * A few notes on cpu_active vs cpu_online:
1459 * - cpu_active must be a subset of cpu_online
1461 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1462 * see __set_cpus_allowed_ptr(). At this point the newly online
1463 * CPU isn't yet part of the sched domains, and balancing will not
1464 * see it.
1466 * - on CPU-down we clear cpu_active() to mask the sched domains and
1467 * avoid the load balancer to place new tasks on the to be removed
1468 * CPU. Existing tasks will remain running there and will be taken
1469 * off.
1471 * This means that fallback selection must not select !active CPUs.
1472 * And can assume that any active CPU must be online. Conversely
1473 * select_task_rq() below may allow selection of !active CPUs in order
1474 * to satisfy the above rules.
1476 static int select_fallback_rq(int cpu, struct task_struct *p)
1478 int nid = cpu_to_node(cpu);
1479 const struct cpumask *nodemask = NULL;
1480 enum { cpuset, possible, fail } state = cpuset;
1481 int dest_cpu;
1484 * If the node that the CPU is on has been offlined, cpu_to_node()
1485 * will return -1. There is no CPU on the node, and we should
1486 * select the CPU on the other node.
1488 if (nid != -1) {
1489 nodemask = cpumask_of_node(nid);
1491 /* Look for allowed, online CPU in same node. */
1492 for_each_cpu(dest_cpu, nodemask) {
1493 if (!cpu_active(dest_cpu))
1494 continue;
1495 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
1496 return dest_cpu;
1500 for (;;) {
1501 /* Any allowed, online CPU? */
1502 for_each_cpu(dest_cpu, &p->cpus_allowed) {
1503 if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
1504 continue;
1505 if (!cpu_online(dest_cpu))
1506 continue;
1507 goto out;
1510 /* No more Mr. Nice Guy. */
1511 switch (state) {
1512 case cpuset:
1513 if (IS_ENABLED(CONFIG_CPUSETS)) {
1514 cpuset_cpus_allowed_fallback(p);
1515 state = possible;
1516 break;
1518 /* Fall-through */
1519 case possible:
1520 do_set_cpus_allowed(p, cpu_possible_mask);
1521 state = fail;
1522 break;
1524 case fail:
1525 BUG();
1526 break;
1530 out:
1531 if (state != cpuset) {
1533 * Don't tell them about moving exiting tasks or
1534 * kernel threads (both mm NULL), since they never
1535 * leave kernel.
1537 if (p->mm && printk_ratelimit()) {
1538 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1539 task_pid_nr(p), p->comm, cpu);
1543 return dest_cpu;
1547 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1549 static inline
1550 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1552 lockdep_assert_held(&p->pi_lock);
1554 if (p->nr_cpus_allowed > 1)
1555 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1556 else
1557 cpu = cpumask_any(&p->cpus_allowed);
1560 * In order not to call set_task_cpu() on a blocking task we need
1561 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1562 * CPU.
1564 * Since this is common to all placement strategies, this lives here.
1566 * [ this allows ->select_task() to simply return task_cpu(p) and
1567 * not worry about this generic constraint ]
1569 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
1570 !cpu_online(cpu)))
1571 cpu = select_fallback_rq(task_cpu(p), p);
1573 return cpu;
1576 static void update_avg(u64 *avg, u64 sample)
1578 s64 diff = sample - *avg;
1579 *avg += diff >> 3;
1582 void sched_set_stop_task(int cpu, struct task_struct *stop)
1584 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1585 struct task_struct *old_stop = cpu_rq(cpu)->stop;
1587 if (stop) {
1589 * Make it appear like a SCHED_FIFO task, its something
1590 * userspace knows about and won't get confused about.
1592 * Also, it will make PI more or less work without too
1593 * much confusion -- but then, stop work should not
1594 * rely on PI working anyway.
1596 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
1598 stop->sched_class = &stop_sched_class;
1601 cpu_rq(cpu)->stop = stop;
1603 if (old_stop) {
1605 * Reset it back to a normal scheduling class so that
1606 * it can die in pieces.
1608 old_stop->sched_class = &rt_sched_class;
1612 #else
1614 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1615 const struct cpumask *new_mask, bool check)
1617 return set_cpus_allowed_ptr(p, new_mask);
1620 #endif /* CONFIG_SMP */
1622 static void
1623 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1625 struct rq *rq;
1627 if (!schedstat_enabled())
1628 return;
1630 rq = this_rq();
1632 #ifdef CONFIG_SMP
1633 if (cpu == rq->cpu) {
1634 __schedstat_inc(rq->ttwu_local);
1635 __schedstat_inc(p->se.statistics.nr_wakeups_local);
1636 } else {
1637 struct sched_domain *sd;
1639 __schedstat_inc(p->se.statistics.nr_wakeups_remote);
1640 rcu_read_lock();
1641 for_each_domain(rq->cpu, sd) {
1642 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1643 __schedstat_inc(sd->ttwu_wake_remote);
1644 break;
1647 rcu_read_unlock();
1650 if (wake_flags & WF_MIGRATED)
1651 __schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1652 #endif /* CONFIG_SMP */
1654 __schedstat_inc(rq->ttwu_count);
1655 __schedstat_inc(p->se.statistics.nr_wakeups);
1657 if (wake_flags & WF_SYNC)
1658 __schedstat_inc(p->se.statistics.nr_wakeups_sync);
1661 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1663 activate_task(rq, p, en_flags);
1664 p->on_rq = TASK_ON_RQ_QUEUED;
1666 /* If a worker is waking up, notify the workqueue: */
1667 if (p->flags & PF_WQ_WORKER)
1668 wq_worker_waking_up(p, cpu_of(rq));
1672 * Mark the task runnable and perform wakeup-preemption.
1674 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1675 struct rq_flags *rf)
1677 check_preempt_curr(rq, p, wake_flags);
1678 p->state = TASK_RUNNING;
1679 trace_sched_wakeup(p);
1681 #ifdef CONFIG_SMP
1682 if (p->sched_class->task_woken) {
1684 * Our task @p is fully woken up and running; so its safe to
1685 * drop the rq->lock, hereafter rq is only used for statistics.
1687 rq_unpin_lock(rq, rf);
1688 p->sched_class->task_woken(rq, p);
1689 rq_repin_lock(rq, rf);
1692 if (rq->idle_stamp) {
1693 u64 delta = rq_clock(rq) - rq->idle_stamp;
1694 u64 max = 2*rq->max_idle_balance_cost;
1696 update_avg(&rq->avg_idle, delta);
1698 if (rq->avg_idle > max)
1699 rq->avg_idle = max;
1701 rq->idle_stamp = 0;
1703 #endif
1706 static void
1707 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1708 struct rq_flags *rf)
1710 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
1712 lockdep_assert_held(&rq->lock);
1714 #ifdef CONFIG_SMP
1715 if (p->sched_contributes_to_load)
1716 rq->nr_uninterruptible--;
1718 if (wake_flags & WF_MIGRATED)
1719 en_flags |= ENQUEUE_MIGRATED;
1720 #endif
1722 ttwu_activate(rq, p, en_flags);
1723 ttwu_do_wakeup(rq, p, wake_flags, rf);
1727 * Called in case the task @p isn't fully descheduled from its runqueue,
1728 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1729 * since all we need to do is flip p->state to TASK_RUNNING, since
1730 * the task is still ->on_rq.
1732 static int ttwu_remote(struct task_struct *p, int wake_flags)
1734 struct rq_flags rf;
1735 struct rq *rq;
1736 int ret = 0;
1738 rq = __task_rq_lock(p, &rf);
1739 if (task_on_rq_queued(p)) {
1740 /* check_preempt_curr() may use rq clock */
1741 update_rq_clock(rq);
1742 ttwu_do_wakeup(rq, p, wake_flags, &rf);
1743 ret = 1;
1745 __task_rq_unlock(rq, &rf);
1747 return ret;
1750 #ifdef CONFIG_SMP
1751 void sched_ttwu_pending(void)
1753 struct rq *rq = this_rq();
1754 struct llist_node *llist = llist_del_all(&rq->wake_list);
1755 struct task_struct *p, *t;
1756 struct rq_flags rf;
1758 if (!llist)
1759 return;
1761 rq_lock_irqsave(rq, &rf);
1762 update_rq_clock(rq);
1764 llist_for_each_entry_safe(p, t, llist, wake_entry)
1765 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
1767 rq_unlock_irqrestore(rq, &rf);
1770 void scheduler_ipi(void)
1773 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1774 * TIF_NEED_RESCHED remotely (for the first time) will also send
1775 * this IPI.
1777 preempt_fold_need_resched();
1779 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1780 return;
1783 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1784 * traditionally all their work was done from the interrupt return
1785 * path. Now that we actually do some work, we need to make sure
1786 * we do call them.
1788 * Some archs already do call them, luckily irq_enter/exit nest
1789 * properly.
1791 * Arguably we should visit all archs and update all handlers,
1792 * however a fair share of IPIs are still resched only so this would
1793 * somewhat pessimize the simple resched case.
1795 irq_enter();
1796 sched_ttwu_pending();
1799 * Check if someone kicked us for doing the nohz idle load balance.
1801 if (unlikely(got_nohz_idle_kick())) {
1802 this_rq()->idle_balance = 1;
1803 raise_softirq_irqoff(SCHED_SOFTIRQ);
1805 irq_exit();
1808 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1810 struct rq *rq = cpu_rq(cpu);
1812 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1814 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1815 if (!set_nr_if_polling(rq->idle))
1816 smp_send_reschedule(cpu);
1817 else
1818 trace_sched_wake_idle_without_ipi(cpu);
1822 void wake_up_if_idle(int cpu)
1824 struct rq *rq = cpu_rq(cpu);
1825 struct rq_flags rf;
1827 rcu_read_lock();
1829 if (!is_idle_task(rcu_dereference(rq->curr)))
1830 goto out;
1832 if (set_nr_if_polling(rq->idle)) {
1833 trace_sched_wake_idle_without_ipi(cpu);
1834 } else {
1835 rq_lock_irqsave(rq, &rf);
1836 if (is_idle_task(rq->curr))
1837 smp_send_reschedule(cpu);
1838 /* Else CPU is not idle, do nothing here: */
1839 rq_unlock_irqrestore(rq, &rf);
1842 out:
1843 rcu_read_unlock();
1846 bool cpus_share_cache(int this_cpu, int that_cpu)
1848 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1850 #endif /* CONFIG_SMP */
1852 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1854 struct rq *rq = cpu_rq(cpu);
1855 struct rq_flags rf;
1857 #if defined(CONFIG_SMP)
1858 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1859 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
1860 ttwu_queue_remote(p, cpu, wake_flags);
1861 return;
1863 #endif
1865 rq_lock(rq, &rf);
1866 update_rq_clock(rq);
1867 ttwu_do_activate(rq, p, wake_flags, &rf);
1868 rq_unlock(rq, &rf);
1872 * Notes on Program-Order guarantees on SMP systems.
1874 * MIGRATION
1876 * The basic program-order guarantee on SMP systems is that when a task [t]
1877 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1878 * execution on its new CPU [c1].
1880 * For migration (of runnable tasks) this is provided by the following means:
1882 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1883 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1884 * rq(c1)->lock (if not at the same time, then in that order).
1885 * C) LOCK of the rq(c1)->lock scheduling in task
1887 * Transitivity guarantees that B happens after A and C after B.
1888 * Note: we only require RCpc transitivity.
1889 * Note: the CPU doing B need not be c0 or c1
1891 * Example:
1893 * CPU0 CPU1 CPU2
1895 * LOCK rq(0)->lock
1896 * sched-out X
1897 * sched-in Y
1898 * UNLOCK rq(0)->lock
1900 * LOCK rq(0)->lock // orders against CPU0
1901 * dequeue X
1902 * UNLOCK rq(0)->lock
1904 * LOCK rq(1)->lock
1905 * enqueue X
1906 * UNLOCK rq(1)->lock
1908 * LOCK rq(1)->lock // orders against CPU2
1909 * sched-out Z
1910 * sched-in X
1911 * UNLOCK rq(1)->lock
1914 * BLOCKING -- aka. SLEEP + WAKEUP
1916 * For blocking we (obviously) need to provide the same guarantee as for
1917 * migration. However the means are completely different as there is no lock
1918 * chain to provide order. Instead we do:
1920 * 1) smp_store_release(X->on_cpu, 0)
1921 * 2) smp_cond_load_acquire(!X->on_cpu)
1923 * Example:
1925 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1927 * LOCK rq(0)->lock LOCK X->pi_lock
1928 * dequeue X
1929 * sched-out X
1930 * smp_store_release(X->on_cpu, 0);
1932 * smp_cond_load_acquire(&X->on_cpu, !VAL);
1933 * X->state = WAKING
1934 * set_task_cpu(X,2)
1936 * LOCK rq(2)->lock
1937 * enqueue X
1938 * X->state = RUNNING
1939 * UNLOCK rq(2)->lock
1941 * LOCK rq(2)->lock // orders against CPU1
1942 * sched-out Z
1943 * sched-in X
1944 * UNLOCK rq(2)->lock
1946 * UNLOCK X->pi_lock
1947 * UNLOCK rq(0)->lock
1950 * However; for wakeups there is a second guarantee we must provide, namely we
1951 * must observe the state that lead to our wakeup. That is, not only must our
1952 * task observe its own prior state, it must also observe the stores prior to
1953 * its wakeup.
1955 * This means that any means of doing remote wakeups must order the CPU doing
1956 * the wakeup against the CPU the task is going to end up running on. This,
1957 * however, is already required for the regular Program-Order guarantee above,
1958 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
1963 * try_to_wake_up - wake up a thread
1964 * @p: the thread to be awakened
1965 * @state: the mask of task states that can be woken
1966 * @wake_flags: wake modifier flags (WF_*)
1968 * If (@state & @p->state) @p->state = TASK_RUNNING.
1970 * If the task was not queued/runnable, also place it back on a runqueue.
1972 * Atomic against schedule() which would dequeue a task, also see
1973 * set_current_state().
1975 * Return: %true if @p->state changes (an actual wakeup was done),
1976 * %false otherwise.
1978 static int
1979 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1981 unsigned long flags;
1982 int cpu, success = 0;
1985 * If we are going to wake up a thread waiting for CONDITION we
1986 * need to ensure that CONDITION=1 done by the caller can not be
1987 * reordered with p->state check below. This pairs with mb() in
1988 * set_current_state() the waiting thread does.
1990 raw_spin_lock_irqsave(&p->pi_lock, flags);
1991 smp_mb__after_spinlock();
1992 if (!(p->state & state))
1993 goto out;
1995 trace_sched_waking(p);
1997 /* We're going to change ->state: */
1998 success = 1;
1999 cpu = task_cpu(p);
2002 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2003 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2004 * in smp_cond_load_acquire() below.
2006 * sched_ttwu_pending() try_to_wake_up()
2007 * [S] p->on_rq = 1; [L] P->state
2008 * UNLOCK rq->lock -----.
2010 * +--- RMB
2011 * schedule() /
2012 * LOCK rq->lock -----'
2013 * UNLOCK rq->lock
2015 * [task p]
2016 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2018 * Pairs with the UNLOCK+LOCK on rq->lock from the
2019 * last wakeup of our task and the schedule that got our task
2020 * current.
2022 smp_rmb();
2023 if (p->on_rq && ttwu_remote(p, wake_flags))
2024 goto stat;
2026 #ifdef CONFIG_SMP
2028 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2029 * possible to, falsely, observe p->on_cpu == 0.
2031 * One must be running (->on_cpu == 1) in order to remove oneself
2032 * from the runqueue.
2034 * [S] ->on_cpu = 1; [L] ->on_rq
2035 * UNLOCK rq->lock
2036 * RMB
2037 * LOCK rq->lock
2038 * [S] ->on_rq = 0; [L] ->on_cpu
2040 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2041 * from the consecutive calls to schedule(); the first switching to our
2042 * task, the second putting it to sleep.
2044 smp_rmb();
2047 * If the owning (remote) CPU is still in the middle of schedule() with
2048 * this task as prev, wait until its done referencing the task.
2050 * Pairs with the smp_store_release() in finish_task().
2052 * This ensures that tasks getting woken will be fully ordered against
2053 * their previous state and preserve Program Order.
2055 smp_cond_load_acquire(&p->on_cpu, !VAL);
2057 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2058 p->state = TASK_WAKING;
2060 if (p->in_iowait) {
2061 delayacct_blkio_end(p);
2062 atomic_dec(&task_rq(p)->nr_iowait);
2065 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2066 if (task_cpu(p) != cpu) {
2067 wake_flags |= WF_MIGRATED;
2068 set_task_cpu(p, cpu);
2071 #else /* CONFIG_SMP */
2073 if (p->in_iowait) {
2074 delayacct_blkio_end(p);
2075 atomic_dec(&task_rq(p)->nr_iowait);
2078 #endif /* CONFIG_SMP */
2080 ttwu_queue(p, cpu, wake_flags);
2081 stat:
2082 ttwu_stat(p, cpu, wake_flags);
2083 out:
2084 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2086 return success;
2090 * try_to_wake_up_local - try to wake up a local task with rq lock held
2091 * @p: the thread to be awakened
2092 * @rf: request-queue flags for pinning
2094 * Put @p on the run-queue if it's not already there. The caller must
2095 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2096 * the current task.
2098 static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
2100 struct rq *rq = task_rq(p);
2102 if (WARN_ON_ONCE(rq != this_rq()) ||
2103 WARN_ON_ONCE(p == current))
2104 return;
2106 lockdep_assert_held(&rq->lock);
2108 if (!raw_spin_trylock(&p->pi_lock)) {
2110 * This is OK, because current is on_cpu, which avoids it being
2111 * picked for load-balance and preemption/IRQs are still
2112 * disabled avoiding further scheduler activity on it and we've
2113 * not yet picked a replacement task.
2115 rq_unlock(rq, rf);
2116 raw_spin_lock(&p->pi_lock);
2117 rq_relock(rq, rf);
2120 if (!(p->state & TASK_NORMAL))
2121 goto out;
2123 trace_sched_waking(p);
2125 if (!task_on_rq_queued(p)) {
2126 if (p->in_iowait) {
2127 delayacct_blkio_end(p);
2128 atomic_dec(&rq->nr_iowait);
2130 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
2133 ttwu_do_wakeup(rq, p, 0, rf);
2134 ttwu_stat(p, smp_processor_id(), 0);
2135 out:
2136 raw_spin_unlock(&p->pi_lock);
2140 * wake_up_process - Wake up a specific process
2141 * @p: The process to be woken up.
2143 * Attempt to wake up the nominated process and move it to the set of runnable
2144 * processes.
2146 * Return: 1 if the process was woken up, 0 if it was already running.
2148 * It may be assumed that this function implies a write memory barrier before
2149 * changing the task state if and only if any tasks are woken up.
2151 int wake_up_process(struct task_struct *p)
2153 return try_to_wake_up(p, TASK_NORMAL, 0);
2155 EXPORT_SYMBOL(wake_up_process);
2157 int wake_up_state(struct task_struct *p, unsigned int state)
2159 return try_to_wake_up(p, state, 0);
2163 * Perform scheduler related setup for a newly forked process p.
2164 * p is forked by current.
2166 * __sched_fork() is basic setup used by init_idle() too:
2168 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2170 p->on_rq = 0;
2172 p->se.on_rq = 0;
2173 p->se.exec_start = 0;
2174 p->se.sum_exec_runtime = 0;
2175 p->se.prev_sum_exec_runtime = 0;
2176 p->se.nr_migrations = 0;
2177 p->se.vruntime = 0;
2178 INIT_LIST_HEAD(&p->se.group_node);
2180 #ifdef CONFIG_FAIR_GROUP_SCHED
2181 p->se.cfs_rq = NULL;
2182 #endif
2184 #ifdef CONFIG_SCHEDSTATS
2185 /* Even if schedstat is disabled, there should not be garbage */
2186 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2187 #endif
2189 RB_CLEAR_NODE(&p->dl.rb_node);
2190 init_dl_task_timer(&p->dl);
2191 init_dl_inactive_task_timer(&p->dl);
2192 __dl_clear_params(p);
2194 INIT_LIST_HEAD(&p->rt.run_list);
2195 p->rt.timeout = 0;
2196 p->rt.time_slice = sched_rr_timeslice;
2197 p->rt.on_rq = 0;
2198 p->rt.on_list = 0;
2200 #ifdef CONFIG_PREEMPT_NOTIFIERS
2201 INIT_HLIST_HEAD(&p->preempt_notifiers);
2202 #endif
2204 #ifdef CONFIG_NUMA_BALANCING
2205 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
2206 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2207 p->mm->numa_scan_seq = 0;
2210 if (clone_flags & CLONE_VM)
2211 p->numa_preferred_nid = current->numa_preferred_nid;
2212 else
2213 p->numa_preferred_nid = -1;
2215 p->node_stamp = 0ULL;
2216 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
2217 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2218 p->numa_work.next = &p->numa_work;
2219 p->numa_faults = NULL;
2220 p->last_task_numa_placement = 0;
2221 p->last_sum_exec_runtime = 0;
2223 p->numa_group = NULL;
2224 #endif /* CONFIG_NUMA_BALANCING */
2227 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2229 #ifdef CONFIG_NUMA_BALANCING
2231 void set_numabalancing_state(bool enabled)
2233 if (enabled)
2234 static_branch_enable(&sched_numa_balancing);
2235 else
2236 static_branch_disable(&sched_numa_balancing);
2239 #ifdef CONFIG_PROC_SYSCTL
2240 int sysctl_numa_balancing(struct ctl_table *table, int write,
2241 void __user *buffer, size_t *lenp, loff_t *ppos)
2243 struct ctl_table t;
2244 int err;
2245 int state = static_branch_likely(&sched_numa_balancing);
2247 if (write && !capable(CAP_SYS_ADMIN))
2248 return -EPERM;
2250 t = *table;
2251 t.data = &state;
2252 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2253 if (err < 0)
2254 return err;
2255 if (write)
2256 set_numabalancing_state(state);
2257 return err;
2259 #endif
2260 #endif
2262 #ifdef CONFIG_SCHEDSTATS
2264 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2265 static bool __initdata __sched_schedstats = false;
2267 static void set_schedstats(bool enabled)
2269 if (enabled)
2270 static_branch_enable(&sched_schedstats);
2271 else
2272 static_branch_disable(&sched_schedstats);
2275 void force_schedstat_enabled(void)
2277 if (!schedstat_enabled()) {
2278 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2279 static_branch_enable(&sched_schedstats);
2283 static int __init setup_schedstats(char *str)
2285 int ret = 0;
2286 if (!str)
2287 goto out;
2290 * This code is called before jump labels have been set up, so we can't
2291 * change the static branch directly just yet. Instead set a temporary
2292 * variable so init_schedstats() can do it later.
2294 if (!strcmp(str, "enable")) {
2295 __sched_schedstats = true;
2296 ret = 1;
2297 } else if (!strcmp(str, "disable")) {
2298 __sched_schedstats = false;
2299 ret = 1;
2301 out:
2302 if (!ret)
2303 pr_warn("Unable to parse schedstats=\n");
2305 return ret;
2307 __setup("schedstats=", setup_schedstats);
2309 static void __init init_schedstats(void)
2311 set_schedstats(__sched_schedstats);
2314 #ifdef CONFIG_PROC_SYSCTL
2315 int sysctl_schedstats(struct ctl_table *table, int write,
2316 void __user *buffer, size_t *lenp, loff_t *ppos)
2318 struct ctl_table t;
2319 int err;
2320 int state = static_branch_likely(&sched_schedstats);
2322 if (write && !capable(CAP_SYS_ADMIN))
2323 return -EPERM;
2325 t = *table;
2326 t.data = &state;
2327 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2328 if (err < 0)
2329 return err;
2330 if (write)
2331 set_schedstats(state);
2332 return err;
2334 #endif /* CONFIG_PROC_SYSCTL */
2335 #else /* !CONFIG_SCHEDSTATS */
2336 static inline void init_schedstats(void) {}
2337 #endif /* CONFIG_SCHEDSTATS */
2340 * fork()/clone()-time setup:
2342 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2344 unsigned long flags;
2345 int cpu = get_cpu();
2347 __sched_fork(clone_flags, p);
2349 * We mark the process as NEW here. This guarantees that
2350 * nobody will actually run it, and a signal or other external
2351 * event cannot wake it up and insert it on the runqueue either.
2353 p->state = TASK_NEW;
2356 * Make sure we do not leak PI boosting priority to the child.
2358 p->prio = current->normal_prio;
2361 * Revert to default priority/policy on fork if requested.
2363 if (unlikely(p->sched_reset_on_fork)) {
2364 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2365 p->policy = SCHED_NORMAL;
2366 p->static_prio = NICE_TO_PRIO(0);
2367 p->rt_priority = 0;
2368 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2369 p->static_prio = NICE_TO_PRIO(0);
2371 p->prio = p->normal_prio = __normal_prio(p);
2372 set_load_weight(p, false);
2375 * We don't need the reset flag anymore after the fork. It has
2376 * fulfilled its duty:
2378 p->sched_reset_on_fork = 0;
2381 if (dl_prio(p->prio)) {
2382 put_cpu();
2383 return -EAGAIN;
2384 } else if (rt_prio(p->prio)) {
2385 p->sched_class = &rt_sched_class;
2386 } else {
2387 p->sched_class = &fair_sched_class;
2390 init_entity_runnable_average(&p->se);
2393 * The child is not yet in the pid-hash so no cgroup attach races,
2394 * and the cgroup is pinned to this child due to cgroup_fork()
2395 * is ran before sched_fork().
2397 * Silence PROVE_RCU.
2399 raw_spin_lock_irqsave(&p->pi_lock, flags);
2401 * We're setting the CPU for the first time, we don't migrate,
2402 * so use __set_task_cpu().
2404 __set_task_cpu(p, cpu);
2405 if (p->sched_class->task_fork)
2406 p->sched_class->task_fork(p);
2407 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2409 #ifdef CONFIG_SCHED_INFO
2410 if (likely(sched_info_on()))
2411 memset(&p->sched_info, 0, sizeof(p->sched_info));
2412 #endif
2413 #if defined(CONFIG_SMP)
2414 p->on_cpu = 0;
2415 #endif
2416 init_task_preempt_count(p);
2417 #ifdef CONFIG_SMP
2418 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2419 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2420 #endif
2422 put_cpu();
2423 return 0;
2426 unsigned long to_ratio(u64 period, u64 runtime)
2428 if (runtime == RUNTIME_INF)
2429 return BW_UNIT;
2432 * Doing this here saves a lot of checks in all
2433 * the calling paths, and returning zero seems
2434 * safe for them anyway.
2436 if (period == 0)
2437 return 0;
2439 return div64_u64(runtime << BW_SHIFT, period);
2443 * wake_up_new_task - wake up a newly created task for the first time.
2445 * This function will do some initial scheduler statistics housekeeping
2446 * that must be done for every newly created context, then puts the task
2447 * on the runqueue and wakes it.
2449 void wake_up_new_task(struct task_struct *p)
2451 struct rq_flags rf;
2452 struct rq *rq;
2454 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2455 p->state = TASK_RUNNING;
2456 #ifdef CONFIG_SMP
2458 * Fork balancing, do it here and not earlier because:
2459 * - cpus_allowed can change in the fork path
2460 * - any previously selected CPU might disappear through hotplug
2462 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2463 * as we're not fully set-up yet.
2465 p->recent_used_cpu = task_cpu(p);
2466 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2467 #endif
2468 rq = __task_rq_lock(p, &rf);
2469 update_rq_clock(rq);
2470 post_init_entity_util_avg(&p->se);
2472 activate_task(rq, p, ENQUEUE_NOCLOCK);
2473 p->on_rq = TASK_ON_RQ_QUEUED;
2474 trace_sched_wakeup_new(p);
2475 check_preempt_curr(rq, p, WF_FORK);
2476 #ifdef CONFIG_SMP
2477 if (p->sched_class->task_woken) {
2479 * Nothing relies on rq->lock after this, so its fine to
2480 * drop it.
2482 rq_unpin_lock(rq, &rf);
2483 p->sched_class->task_woken(rq, p);
2484 rq_repin_lock(rq, &rf);
2486 #endif
2487 task_rq_unlock(rq, p, &rf);
2490 #ifdef CONFIG_PREEMPT_NOTIFIERS
2492 static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2494 void preempt_notifier_inc(void)
2496 static_key_slow_inc(&preempt_notifier_key);
2498 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2500 void preempt_notifier_dec(void)
2502 static_key_slow_dec(&preempt_notifier_key);
2504 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2507 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2508 * @notifier: notifier struct to register
2510 void preempt_notifier_register(struct preempt_notifier *notifier)
2512 if (!static_key_false(&preempt_notifier_key))
2513 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2515 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2517 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2520 * preempt_notifier_unregister - no longer interested in preemption notifications
2521 * @notifier: notifier struct to unregister
2523 * This is *not* safe to call from within a preemption notifier.
2525 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2527 hlist_del(&notifier->link);
2529 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2531 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2533 struct preempt_notifier *notifier;
2535 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2536 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2539 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2541 if (static_key_false(&preempt_notifier_key))
2542 __fire_sched_in_preempt_notifiers(curr);
2545 static void
2546 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2547 struct task_struct *next)
2549 struct preempt_notifier *notifier;
2551 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2552 notifier->ops->sched_out(notifier, next);
2555 static __always_inline void
2556 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2557 struct task_struct *next)
2559 if (static_key_false(&preempt_notifier_key))
2560 __fire_sched_out_preempt_notifiers(curr, next);
2563 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2565 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2569 static inline void
2570 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2571 struct task_struct *next)
2575 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2577 static inline void prepare_task(struct task_struct *next)
2579 #ifdef CONFIG_SMP
2581 * Claim the task as running, we do this before switching to it
2582 * such that any running task will have this set.
2584 next->on_cpu = 1;
2585 #endif
2588 static inline void finish_task(struct task_struct *prev)
2590 #ifdef CONFIG_SMP
2592 * After ->on_cpu is cleared, the task can be moved to a different CPU.
2593 * We must ensure this doesn't happen until the switch is completely
2594 * finished.
2596 * In particular, the load of prev->state in finish_task_switch() must
2597 * happen before this.
2599 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
2601 smp_store_release(&prev->on_cpu, 0);
2602 #endif
2605 static inline void
2606 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
2609 * Since the runqueue lock will be released by the next
2610 * task (which is an invalid locking op but in the case
2611 * of the scheduler it's an obvious special-case), so we
2612 * do an early lockdep release here:
2614 rq_unpin_lock(rq, rf);
2615 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2616 #ifdef CONFIG_DEBUG_SPINLOCK
2617 /* this is a valid case when another task releases the spinlock */
2618 rq->lock.owner = next;
2619 #endif
2622 static inline void finish_lock_switch(struct rq *rq)
2625 * If we are tracking spinlock dependencies then we have to
2626 * fix up the runqueue lock - which gets 'carried over' from
2627 * prev into current:
2629 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
2630 raw_spin_unlock_irq(&rq->lock);
2634 * prepare_task_switch - prepare to switch tasks
2635 * @rq: the runqueue preparing to switch
2636 * @prev: the current task that is being switched out
2637 * @next: the task we are going to switch to.
2639 * This is called with the rq lock held and interrupts off. It must
2640 * be paired with a subsequent finish_task_switch after the context
2641 * switch.
2643 * prepare_task_switch sets up locking and calls architecture specific
2644 * hooks.
2646 static inline void
2647 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2648 struct task_struct *next)
2650 sched_info_switch(rq, prev, next);
2651 perf_event_task_sched_out(prev, next);
2652 fire_sched_out_preempt_notifiers(prev, next);
2653 prepare_task(next);
2654 prepare_arch_switch(next);
2658 * finish_task_switch - clean up after a task-switch
2659 * @prev: the thread we just switched away from.
2661 * finish_task_switch must be called after the context switch, paired
2662 * with a prepare_task_switch call before the context switch.
2663 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2664 * and do any other architecture-specific cleanup actions.
2666 * Note that we may have delayed dropping an mm in context_switch(). If
2667 * so, we finish that here outside of the runqueue lock. (Doing it
2668 * with the lock held can cause deadlocks; see schedule() for
2669 * details.)
2671 * The context switch have flipped the stack from under us and restored the
2672 * local variables which were saved when this task called schedule() in the
2673 * past. prev == current is still correct but we need to recalculate this_rq
2674 * because prev may have moved to another CPU.
2676 static struct rq *finish_task_switch(struct task_struct *prev)
2677 __releases(rq->lock)
2679 struct rq *rq = this_rq();
2680 struct mm_struct *mm = rq->prev_mm;
2681 long prev_state;
2684 * The previous task will have left us with a preempt_count of 2
2685 * because it left us after:
2687 * schedule()
2688 * preempt_disable(); // 1
2689 * __schedule()
2690 * raw_spin_lock_irq(&rq->lock) // 2
2692 * Also, see FORK_PREEMPT_COUNT.
2694 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2695 "corrupted preempt_count: %s/%d/0x%x\n",
2696 current->comm, current->pid, preempt_count()))
2697 preempt_count_set(FORK_PREEMPT_COUNT);
2699 rq->prev_mm = NULL;
2702 * A task struct has one reference for the use as "current".
2703 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2704 * schedule one last time. The schedule call will never return, and
2705 * the scheduled task must drop that reference.
2707 * We must observe prev->state before clearing prev->on_cpu (in
2708 * finish_task), otherwise a concurrent wakeup can get prev
2709 * running on another CPU and we could rave with its RUNNING -> DEAD
2710 * transition, resulting in a double drop.
2712 prev_state = prev->state;
2713 vtime_task_switch(prev);
2714 perf_event_task_sched_in(prev, current);
2715 finish_task(prev);
2716 finish_lock_switch(rq);
2717 finish_arch_post_lock_switch();
2719 fire_sched_in_preempt_notifiers(current);
2721 * When switching through a kernel thread, the loop in
2722 * membarrier_{private,global}_expedited() may have observed that
2723 * kernel thread and not issued an IPI. It is therefore possible to
2724 * schedule between user->kernel->user threads without passing though
2725 * switch_mm(). Membarrier requires a barrier after storing to
2726 * rq->curr, before returning to userspace, so provide them here:
2728 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
2729 * provided by mmdrop(),
2730 * - a sync_core for SYNC_CORE.
2732 if (mm) {
2733 membarrier_mm_sync_core_before_usermode(mm);
2734 mmdrop(mm);
2736 if (unlikely(prev_state == TASK_DEAD)) {
2737 if (prev->sched_class->task_dead)
2738 prev->sched_class->task_dead(prev);
2741 * Remove function-return probe instances associated with this
2742 * task and put them back on the free list.
2744 kprobe_flush_task(prev);
2746 /* Task is done with its stack. */
2747 put_task_stack(prev);
2749 put_task_struct(prev);
2752 tick_nohz_task_switch();
2753 return rq;
2756 #ifdef CONFIG_SMP
2758 /* rq->lock is NOT held, but preemption is disabled */
2759 static void __balance_callback(struct rq *rq)
2761 struct callback_head *head, *next;
2762 void (*func)(struct rq *rq);
2763 unsigned long flags;
2765 raw_spin_lock_irqsave(&rq->lock, flags);
2766 head = rq->balance_callback;
2767 rq->balance_callback = NULL;
2768 while (head) {
2769 func = (void (*)(struct rq *))head->func;
2770 next = head->next;
2771 head->next = NULL;
2772 head = next;
2774 func(rq);
2776 raw_spin_unlock_irqrestore(&rq->lock, flags);
2779 static inline void balance_callback(struct rq *rq)
2781 if (unlikely(rq->balance_callback))
2782 __balance_callback(rq);
2785 #else
2787 static inline void balance_callback(struct rq *rq)
2791 #endif
2794 * schedule_tail - first thing a freshly forked thread must call.
2795 * @prev: the thread we just switched away from.
2797 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2798 __releases(rq->lock)
2800 struct rq *rq;
2803 * New tasks start with FORK_PREEMPT_COUNT, see there and
2804 * finish_task_switch() for details.
2806 * finish_task_switch() will drop rq->lock() and lower preempt_count
2807 * and the preempt_enable() will end up enabling preemption (on
2808 * PREEMPT_COUNT kernels).
2811 rq = finish_task_switch(prev);
2812 balance_callback(rq);
2813 preempt_enable();
2815 if (current->set_child_tid)
2816 put_user(task_pid_vnr(current), current->set_child_tid);
2820 * context_switch - switch to the new MM and the new thread's register state.
2822 static __always_inline struct rq *
2823 context_switch(struct rq *rq, struct task_struct *prev,
2824 struct task_struct *next, struct rq_flags *rf)
2826 struct mm_struct *mm, *oldmm;
2828 prepare_task_switch(rq, prev, next);
2830 mm = next->mm;
2831 oldmm = prev->active_mm;
2833 * For paravirt, this is coupled with an exit in switch_to to
2834 * combine the page table reload and the switch backend into
2835 * one hypercall.
2837 arch_start_context_switch(prev);
2840 * If mm is non-NULL, we pass through switch_mm(). If mm is
2841 * NULL, we will pass through mmdrop() in finish_task_switch().
2842 * Both of these contain the full memory barrier required by
2843 * membarrier after storing to rq->curr, before returning to
2844 * user-space.
2846 if (!mm) {
2847 next->active_mm = oldmm;
2848 mmgrab(oldmm);
2849 enter_lazy_tlb(oldmm, next);
2850 } else
2851 switch_mm_irqs_off(oldmm, mm, next);
2853 if (!prev->mm) {
2854 prev->active_mm = NULL;
2855 rq->prev_mm = oldmm;
2858 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
2860 prepare_lock_switch(rq, next, rf);
2862 /* Here we just switch the register state and the stack. */
2863 switch_to(prev, next, prev);
2864 barrier();
2866 return finish_task_switch(prev);
2870 * nr_running and nr_context_switches:
2872 * externally visible scheduler statistics: current number of runnable
2873 * threads, total number of context switches performed since bootup.
2875 unsigned long nr_running(void)
2877 unsigned long i, sum = 0;
2879 for_each_online_cpu(i)
2880 sum += cpu_rq(i)->nr_running;
2882 return sum;
2886 * Check if only the current task is running on the CPU.
2888 * Caution: this function does not check that the caller has disabled
2889 * preemption, thus the result might have a time-of-check-to-time-of-use
2890 * race. The caller is responsible to use it correctly, for example:
2892 * - from a non-preemptable section (of course)
2894 * - from a thread that is bound to a single CPU
2896 * - in a loop with very short iterations (e.g. a polling loop)
2898 bool single_task_running(void)
2900 return raw_rq()->nr_running == 1;
2902 EXPORT_SYMBOL(single_task_running);
2904 unsigned long long nr_context_switches(void)
2906 int i;
2907 unsigned long long sum = 0;
2909 for_each_possible_cpu(i)
2910 sum += cpu_rq(i)->nr_switches;
2912 return sum;
2916 * IO-wait accounting, and how its mostly bollocks (on SMP).
2918 * The idea behind IO-wait account is to account the idle time that we could
2919 * have spend running if it were not for IO. That is, if we were to improve the
2920 * storage performance, we'd have a proportional reduction in IO-wait time.
2922 * This all works nicely on UP, where, when a task blocks on IO, we account
2923 * idle time as IO-wait, because if the storage were faster, it could've been
2924 * running and we'd not be idle.
2926 * This has been extended to SMP, by doing the same for each CPU. This however
2927 * is broken.
2929 * Imagine for instance the case where two tasks block on one CPU, only the one
2930 * CPU will have IO-wait accounted, while the other has regular idle. Even
2931 * though, if the storage were faster, both could've ran at the same time,
2932 * utilising both CPUs.
2934 * This means, that when looking globally, the current IO-wait accounting on
2935 * SMP is a lower bound, by reason of under accounting.
2937 * Worse, since the numbers are provided per CPU, they are sometimes
2938 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2939 * associated with any one particular CPU, it can wake to another CPU than it
2940 * blocked on. This means the per CPU IO-wait number is meaningless.
2942 * Task CPU affinities can make all that even more 'interesting'.
2945 unsigned long nr_iowait(void)
2947 unsigned long i, sum = 0;
2949 for_each_possible_cpu(i)
2950 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2952 return sum;
2956 * Consumers of these two interfaces, like for example the cpufreq menu
2957 * governor are using nonsensical data. Boosting frequency for a CPU that has
2958 * IO-wait which might not even end up running the task when it does become
2959 * runnable.
2962 unsigned long nr_iowait_cpu(int cpu)
2964 struct rq *this = cpu_rq(cpu);
2965 return atomic_read(&this->nr_iowait);
2968 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2970 struct rq *rq = this_rq();
2971 *nr_waiters = atomic_read(&rq->nr_iowait);
2972 *load = rq->load.weight;
2975 #ifdef CONFIG_SMP
2978 * sched_exec - execve() is a valuable balancing opportunity, because at
2979 * this point the task has the smallest effective memory and cache footprint.
2981 void sched_exec(void)
2983 struct task_struct *p = current;
2984 unsigned long flags;
2985 int dest_cpu;
2987 raw_spin_lock_irqsave(&p->pi_lock, flags);
2988 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2989 if (dest_cpu == smp_processor_id())
2990 goto unlock;
2992 if (likely(cpu_active(dest_cpu))) {
2993 struct migration_arg arg = { p, dest_cpu };
2995 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2996 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2997 return;
2999 unlock:
3000 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3003 #endif
3005 DEFINE_PER_CPU(struct kernel_stat, kstat);
3006 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
3008 EXPORT_PER_CPU_SYMBOL(kstat);
3009 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3012 * The function fair_sched_class.update_curr accesses the struct curr
3013 * and its field curr->exec_start; when called from task_sched_runtime(),
3014 * we observe a high rate of cache misses in practice.
3015 * Prefetching this data results in improved performance.
3017 static inline void prefetch_curr_exec_start(struct task_struct *p)
3019 #ifdef CONFIG_FAIR_GROUP_SCHED
3020 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3021 #else
3022 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3023 #endif
3024 prefetch(curr);
3025 prefetch(&curr->exec_start);
3029 * Return accounted runtime for the task.
3030 * In case the task is currently running, return the runtime plus current's
3031 * pending runtime that have not been accounted yet.
3033 unsigned long long task_sched_runtime(struct task_struct *p)
3035 struct rq_flags rf;
3036 struct rq *rq;
3037 u64 ns;
3039 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3041 * 64-bit doesn't need locks to atomically read a 64bit value.
3042 * So we have a optimization chance when the task's delta_exec is 0.
3043 * Reading ->on_cpu is racy, but this is ok.
3045 * If we race with it leaving CPU, we'll take a lock. So we're correct.
3046 * If we race with it entering CPU, unaccounted time is 0. This is
3047 * indistinguishable from the read occurring a few cycles earlier.
3048 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3049 * been accounted, so we're correct here as well.
3051 if (!p->on_cpu || !task_on_rq_queued(p))
3052 return p->se.sum_exec_runtime;
3053 #endif
3055 rq = task_rq_lock(p, &rf);
3057 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3058 * project cycles that may never be accounted to this
3059 * thread, breaking clock_gettime().
3061 if (task_current(rq, p) && task_on_rq_queued(p)) {
3062 prefetch_curr_exec_start(p);
3063 update_rq_clock(rq);
3064 p->sched_class->update_curr(rq);
3066 ns = p->se.sum_exec_runtime;
3067 task_rq_unlock(rq, p, &rf);
3069 return ns;
3073 * This function gets called by the timer code, with HZ frequency.
3074 * We call it with interrupts disabled.
3076 void scheduler_tick(void)
3078 int cpu = smp_processor_id();
3079 struct rq *rq = cpu_rq(cpu);
3080 struct task_struct *curr = rq->curr;
3081 struct rq_flags rf;
3083 sched_clock_tick();
3085 rq_lock(rq, &rf);
3087 update_rq_clock(rq);
3088 curr->sched_class->task_tick(rq, curr, 0);
3089 cpu_load_update_active(rq);
3090 calc_global_load_tick(rq);
3092 rq_unlock(rq, &rf);
3094 perf_event_task_tick();
3096 #ifdef CONFIG_SMP
3097 rq->idle_balance = idle_cpu(cpu);
3098 trigger_load_balance(rq);
3099 #endif
3100 rq_last_tick_reset(rq);
3103 #ifdef CONFIG_NO_HZ_FULL
3105 * scheduler_tick_max_deferment
3107 * Keep at least one tick per second when a single
3108 * active task is running because the scheduler doesn't
3109 * yet completely support full dynticks environment.
3111 * This makes sure that uptime, CFS vruntime, load
3112 * balancing, etc... continue to move forward, even
3113 * with a very low granularity.
3115 * Return: Maximum deferment in nanoseconds.
3117 u64 scheduler_tick_max_deferment(void)
3119 struct rq *rq = this_rq();
3120 unsigned long next, now = READ_ONCE(jiffies);
3122 next = rq->last_sched_tick + HZ;
3124 if (time_before_eq(next, now))
3125 return 0;
3127 return jiffies_to_nsecs(next - now);
3129 #endif
3131 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3132 defined(CONFIG_PREEMPT_TRACER))
3134 * If the value passed in is equal to the current preempt count
3135 * then we just disabled preemption. Start timing the latency.
3137 static inline void preempt_latency_start(int val)
3139 if (preempt_count() == val) {
3140 unsigned long ip = get_lock_parent_ip();
3141 #ifdef CONFIG_DEBUG_PREEMPT
3142 current->preempt_disable_ip = ip;
3143 #endif
3144 trace_preempt_off(CALLER_ADDR0, ip);
3148 void preempt_count_add(int val)
3150 #ifdef CONFIG_DEBUG_PREEMPT
3152 * Underflow?
3154 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3155 return;
3156 #endif
3157 __preempt_count_add(val);
3158 #ifdef CONFIG_DEBUG_PREEMPT
3160 * Spinlock count overflowing soon?
3162 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3163 PREEMPT_MASK - 10);
3164 #endif
3165 preempt_latency_start(val);
3167 EXPORT_SYMBOL(preempt_count_add);
3168 NOKPROBE_SYMBOL(preempt_count_add);
3171 * If the value passed in equals to the current preempt count
3172 * then we just enabled preemption. Stop timing the latency.
3174 static inline void preempt_latency_stop(int val)
3176 if (preempt_count() == val)
3177 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3180 void preempt_count_sub(int val)
3182 #ifdef CONFIG_DEBUG_PREEMPT
3184 * Underflow?
3186 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3187 return;
3189 * Is the spinlock portion underflowing?
3191 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3192 !(preempt_count() & PREEMPT_MASK)))
3193 return;
3194 #endif
3196 preempt_latency_stop(val);
3197 __preempt_count_sub(val);
3199 EXPORT_SYMBOL(preempt_count_sub);
3200 NOKPROBE_SYMBOL(preempt_count_sub);
3202 #else
3203 static inline void preempt_latency_start(int val) { }
3204 static inline void preempt_latency_stop(int val) { }
3205 #endif
3207 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3209 #ifdef CONFIG_DEBUG_PREEMPT
3210 return p->preempt_disable_ip;
3211 #else
3212 return 0;
3213 #endif
3217 * Print scheduling while atomic bug:
3219 static noinline void __schedule_bug(struct task_struct *prev)
3221 /* Save this before calling printk(), since that will clobber it */
3222 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3224 if (oops_in_progress)
3225 return;
3227 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3228 prev->comm, prev->pid, preempt_count());
3230 debug_show_held_locks(prev);
3231 print_modules();
3232 if (irqs_disabled())
3233 print_irqtrace_events(prev);
3234 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3235 && in_atomic_preempt_off()) {
3236 pr_err("Preemption disabled at:");
3237 print_ip_sym(preempt_disable_ip);
3238 pr_cont("\n");
3240 if (panic_on_warn)
3241 panic("scheduling while atomic\n");
3243 dump_stack();
3244 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3248 * Various schedule()-time debugging checks and statistics:
3250 static inline void schedule_debug(struct task_struct *prev)
3252 #ifdef CONFIG_SCHED_STACK_END_CHECK
3253 if (task_stack_end_corrupted(prev))
3254 panic("corrupted stack end detected inside scheduler\n");
3255 #endif
3257 if (unlikely(in_atomic_preempt_off())) {
3258 __schedule_bug(prev);
3259 preempt_count_set(PREEMPT_DISABLED);
3261 rcu_sleep_check();
3263 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3265 schedstat_inc(this_rq()->sched_count);
3269 * Pick up the highest-prio task:
3271 static inline struct task_struct *
3272 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
3274 const struct sched_class *class;
3275 struct task_struct *p;
3278 * Optimization: we know that if all tasks are in the fair class we can
3279 * call that function directly, but only if the @prev task wasn't of a
3280 * higher scheduling class, because otherwise those loose the
3281 * opportunity to pull in more work from other CPUs.
3283 if (likely((prev->sched_class == &idle_sched_class ||
3284 prev->sched_class == &fair_sched_class) &&
3285 rq->nr_running == rq->cfs.h_nr_running)) {
3287 p = fair_sched_class.pick_next_task(rq, prev, rf);
3288 if (unlikely(p == RETRY_TASK))
3289 goto again;
3291 /* Assumes fair_sched_class->next == idle_sched_class */
3292 if (unlikely(!p))
3293 p = idle_sched_class.pick_next_task(rq, prev, rf);
3295 return p;
3298 again:
3299 for_each_class(class) {
3300 p = class->pick_next_task(rq, prev, rf);
3301 if (p) {
3302 if (unlikely(p == RETRY_TASK))
3303 goto again;
3304 return p;
3308 /* The idle class should always have a runnable task: */
3309 BUG();
3313 * __schedule() is the main scheduler function.
3315 * The main means of driving the scheduler and thus entering this function are:
3317 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3319 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3320 * paths. For example, see arch/x86/entry_64.S.
3322 * To drive preemption between tasks, the scheduler sets the flag in timer
3323 * interrupt handler scheduler_tick().
3325 * 3. Wakeups don't really cause entry into schedule(). They add a
3326 * task to the run-queue and that's it.
3328 * Now, if the new task added to the run-queue preempts the current
3329 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3330 * called on the nearest possible occasion:
3332 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3334 * - in syscall or exception context, at the next outmost
3335 * preempt_enable(). (this might be as soon as the wake_up()'s
3336 * spin_unlock()!)
3338 * - in IRQ context, return from interrupt-handler to
3339 * preemptible context
3341 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3342 * then at the next:
3344 * - cond_resched() call
3345 * - explicit schedule() call
3346 * - return from syscall or exception to user-space
3347 * - return from interrupt-handler to user-space
3349 * WARNING: must be called with preemption disabled!
3351 static void __sched notrace __schedule(bool preempt)
3353 struct task_struct *prev, *next;
3354 unsigned long *switch_count;
3355 struct rq_flags rf;
3356 struct rq *rq;
3357 int cpu;
3359 cpu = smp_processor_id();
3360 rq = cpu_rq(cpu);
3361 prev = rq->curr;
3363 schedule_debug(prev);
3365 if (sched_feat(HRTICK))
3366 hrtick_clear(rq);
3368 local_irq_disable();
3369 rcu_note_context_switch(preempt);
3372 * Make sure that signal_pending_state()->signal_pending() below
3373 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3374 * done by the caller to avoid the race with signal_wake_up().
3376 * The membarrier system call requires a full memory barrier
3377 * after coming from user-space, before storing to rq->curr.
3379 rq_lock(rq, &rf);
3380 smp_mb__after_spinlock();
3382 /* Promote REQ to ACT */
3383 rq->clock_update_flags <<= 1;
3384 update_rq_clock(rq);
3386 switch_count = &prev->nivcsw;
3387 if (!preempt && prev->state) {
3388 if (unlikely(signal_pending_state(prev->state, prev))) {
3389 prev->state = TASK_RUNNING;
3390 } else {
3391 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
3392 prev->on_rq = 0;
3394 if (prev->in_iowait) {
3395 atomic_inc(&rq->nr_iowait);
3396 delayacct_blkio_start();
3400 * If a worker went to sleep, notify and ask workqueue
3401 * whether it wants to wake up a task to maintain
3402 * concurrency.
3404 if (prev->flags & PF_WQ_WORKER) {
3405 struct task_struct *to_wakeup;
3407 to_wakeup = wq_worker_sleeping(prev);
3408 if (to_wakeup)
3409 try_to_wake_up_local(to_wakeup, &rf);
3412 switch_count = &prev->nvcsw;
3415 next = pick_next_task(rq, prev, &rf);
3416 clear_tsk_need_resched(prev);
3417 clear_preempt_need_resched();
3419 if (likely(prev != next)) {
3420 rq->nr_switches++;
3421 rq->curr = next;
3423 * The membarrier system call requires each architecture
3424 * to have a full memory barrier after updating
3425 * rq->curr, before returning to user-space.
3427 * Here are the schemes providing that barrier on the
3428 * various architectures:
3429 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
3430 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
3431 * - finish_lock_switch() for weakly-ordered
3432 * architectures where spin_unlock is a full barrier,
3433 * - switch_to() for arm64 (weakly-ordered, spin_unlock
3434 * is a RELEASE barrier),
3436 ++*switch_count;
3438 trace_sched_switch(preempt, prev, next);
3440 /* Also unlocks the rq: */
3441 rq = context_switch(rq, prev, next, &rf);
3442 } else {
3443 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3444 rq_unlock_irq(rq, &rf);
3447 balance_callback(rq);
3450 void __noreturn do_task_dead(void)
3453 * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
3454 * when the following two conditions become true.
3455 * - There is race condition of mmap_sem (It is acquired by
3456 * exit_mm()), and
3457 * - SMI occurs before setting TASK_RUNINNG.
3458 * (or hypervisor of virtual machine switches to other guest)
3459 * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
3461 * To avoid it, we have to wait for releasing tsk->pi_lock which
3462 * is held by try_to_wake_up()
3464 raw_spin_lock_irq(&current->pi_lock);
3465 raw_spin_unlock_irq(&current->pi_lock);
3467 /* Causes final put_task_struct in finish_task_switch(): */
3468 __set_current_state(TASK_DEAD);
3470 /* Tell freezer to ignore us: */
3471 current->flags |= PF_NOFREEZE;
3473 __schedule(false);
3474 BUG();
3476 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
3477 for (;;)
3478 cpu_relax();
3481 static inline void sched_submit_work(struct task_struct *tsk)
3483 if (!tsk->state || tsk_is_pi_blocked(tsk))
3484 return;
3486 * If we are going to sleep and we have plugged IO queued,
3487 * make sure to submit it to avoid deadlocks.
3489 if (blk_needs_flush_plug(tsk))
3490 blk_schedule_flush_plug(tsk);
3493 asmlinkage __visible void __sched schedule(void)
3495 struct task_struct *tsk = current;
3497 sched_submit_work(tsk);
3498 do {
3499 preempt_disable();
3500 __schedule(false);
3501 sched_preempt_enable_no_resched();
3502 } while (need_resched());
3504 EXPORT_SYMBOL(schedule);
3507 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3508 * state (have scheduled out non-voluntarily) by making sure that all
3509 * tasks have either left the run queue or have gone into user space.
3510 * As idle tasks do not do either, they must not ever be preempted
3511 * (schedule out non-voluntarily).
3513 * schedule_idle() is similar to schedule_preempt_disable() except that it
3514 * never enables preemption because it does not call sched_submit_work().
3516 void __sched schedule_idle(void)
3519 * As this skips calling sched_submit_work(), which the idle task does
3520 * regardless because that function is a nop when the task is in a
3521 * TASK_RUNNING state, make sure this isn't used someplace that the
3522 * current task can be in any other state. Note, idle is always in the
3523 * TASK_RUNNING state.
3525 WARN_ON_ONCE(current->state);
3526 do {
3527 __schedule(false);
3528 } while (need_resched());
3531 #ifdef CONFIG_CONTEXT_TRACKING
3532 asmlinkage __visible void __sched schedule_user(void)
3535 * If we come here after a random call to set_need_resched(),
3536 * or we have been woken up remotely but the IPI has not yet arrived,
3537 * we haven't yet exited the RCU idle mode. Do it here manually until
3538 * we find a better solution.
3540 * NB: There are buggy callers of this function. Ideally we
3541 * should warn if prev_state != CONTEXT_USER, but that will trigger
3542 * too frequently to make sense yet.
3544 enum ctx_state prev_state = exception_enter();
3545 schedule();
3546 exception_exit(prev_state);
3548 #endif
3551 * schedule_preempt_disabled - called with preemption disabled
3553 * Returns with preemption disabled. Note: preempt_count must be 1
3555 void __sched schedule_preempt_disabled(void)
3557 sched_preempt_enable_no_resched();
3558 schedule();
3559 preempt_disable();
3562 static void __sched notrace preempt_schedule_common(void)
3564 do {
3566 * Because the function tracer can trace preempt_count_sub()
3567 * and it also uses preempt_enable/disable_notrace(), if
3568 * NEED_RESCHED is set, the preempt_enable_notrace() called
3569 * by the function tracer will call this function again and
3570 * cause infinite recursion.
3572 * Preemption must be disabled here before the function
3573 * tracer can trace. Break up preempt_disable() into two
3574 * calls. One to disable preemption without fear of being
3575 * traced. The other to still record the preemption latency,
3576 * which can also be traced by the function tracer.
3578 preempt_disable_notrace();
3579 preempt_latency_start(1);
3580 __schedule(true);
3581 preempt_latency_stop(1);
3582 preempt_enable_no_resched_notrace();
3585 * Check again in case we missed a preemption opportunity
3586 * between schedule and now.
3588 } while (need_resched());
3591 #ifdef CONFIG_PREEMPT
3593 * this is the entry point to schedule() from in-kernel preemption
3594 * off of preempt_enable. Kernel preemptions off return from interrupt
3595 * occur there and call schedule directly.
3597 asmlinkage __visible void __sched notrace preempt_schedule(void)
3600 * If there is a non-zero preempt_count or interrupts are disabled,
3601 * we do not want to preempt the current task. Just return..
3603 if (likely(!preemptible()))
3604 return;
3606 preempt_schedule_common();
3608 NOKPROBE_SYMBOL(preempt_schedule);
3609 EXPORT_SYMBOL(preempt_schedule);
3612 * preempt_schedule_notrace - preempt_schedule called by tracing
3614 * The tracing infrastructure uses preempt_enable_notrace to prevent
3615 * recursion and tracing preempt enabling caused by the tracing
3616 * infrastructure itself. But as tracing can happen in areas coming
3617 * from userspace or just about to enter userspace, a preempt enable
3618 * can occur before user_exit() is called. This will cause the scheduler
3619 * to be called when the system is still in usermode.
3621 * To prevent this, the preempt_enable_notrace will use this function
3622 * instead of preempt_schedule() to exit user context if needed before
3623 * calling the scheduler.
3625 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3627 enum ctx_state prev_ctx;
3629 if (likely(!preemptible()))
3630 return;
3632 do {
3634 * Because the function tracer can trace preempt_count_sub()
3635 * and it also uses preempt_enable/disable_notrace(), if
3636 * NEED_RESCHED is set, the preempt_enable_notrace() called
3637 * by the function tracer will call this function again and
3638 * cause infinite recursion.
3640 * Preemption must be disabled here before the function
3641 * tracer can trace. Break up preempt_disable() into two
3642 * calls. One to disable preemption without fear of being
3643 * traced. The other to still record the preemption latency,
3644 * which can also be traced by the function tracer.
3646 preempt_disable_notrace();
3647 preempt_latency_start(1);
3649 * Needs preempt disabled in case user_exit() is traced
3650 * and the tracer calls preempt_enable_notrace() causing
3651 * an infinite recursion.
3653 prev_ctx = exception_enter();
3654 __schedule(true);
3655 exception_exit(prev_ctx);
3657 preempt_latency_stop(1);
3658 preempt_enable_no_resched_notrace();
3659 } while (need_resched());
3661 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3663 #endif /* CONFIG_PREEMPT */
3666 * this is the entry point to schedule() from kernel preemption
3667 * off of irq context.
3668 * Note, that this is called and return with irqs disabled. This will
3669 * protect us against recursive calling from irq.
3671 asmlinkage __visible void __sched preempt_schedule_irq(void)
3673 enum ctx_state prev_state;
3675 /* Catch callers which need to be fixed */
3676 BUG_ON(preempt_count() || !irqs_disabled());
3678 prev_state = exception_enter();
3680 do {
3681 preempt_disable();
3682 local_irq_enable();
3683 __schedule(true);
3684 local_irq_disable();
3685 sched_preempt_enable_no_resched();
3686 } while (need_resched());
3688 exception_exit(prev_state);
3691 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
3692 void *key)
3694 return try_to_wake_up(curr->private, mode, wake_flags);
3696 EXPORT_SYMBOL(default_wake_function);
3698 #ifdef CONFIG_RT_MUTEXES
3700 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
3702 if (pi_task)
3703 prio = min(prio, pi_task->prio);
3705 return prio;
3708 static inline int rt_effective_prio(struct task_struct *p, int prio)
3710 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3712 return __rt_effective_prio(pi_task, prio);
3716 * rt_mutex_setprio - set the current priority of a task
3717 * @p: task to boost
3718 * @pi_task: donor task
3720 * This function changes the 'effective' priority of a task. It does
3721 * not touch ->normal_prio like __setscheduler().
3723 * Used by the rt_mutex code to implement priority inheritance
3724 * logic. Call site only calls if the priority of the task changed.
3726 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
3728 int prio, oldprio, queued, running, queue_flag =
3729 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
3730 const struct sched_class *prev_class;
3731 struct rq_flags rf;
3732 struct rq *rq;
3734 /* XXX used to be waiter->prio, not waiter->task->prio */
3735 prio = __rt_effective_prio(pi_task, p->normal_prio);
3738 * If nothing changed; bail early.
3740 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
3741 return;
3743 rq = __task_rq_lock(p, &rf);
3744 update_rq_clock(rq);
3746 * Set under pi_lock && rq->lock, such that the value can be used under
3747 * either lock.
3749 * Note that there is loads of tricky to make this pointer cache work
3750 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3751 * ensure a task is de-boosted (pi_task is set to NULL) before the
3752 * task is allowed to run again (and can exit). This ensures the pointer
3753 * points to a blocked task -- which guaratees the task is present.
3755 p->pi_top_task = pi_task;
3758 * For FIFO/RR we only need to set prio, if that matches we're done.
3760 if (prio == p->prio && !dl_prio(prio))
3761 goto out_unlock;
3764 * Idle task boosting is a nono in general. There is one
3765 * exception, when PREEMPT_RT and NOHZ is active:
3767 * The idle task calls get_next_timer_interrupt() and holds
3768 * the timer wheel base->lock on the CPU and another CPU wants
3769 * to access the timer (probably to cancel it). We can safely
3770 * ignore the boosting request, as the idle CPU runs this code
3771 * with interrupts disabled and will complete the lock
3772 * protected section without being interrupted. So there is no
3773 * real need to boost.
3775 if (unlikely(p == rq->idle)) {
3776 WARN_ON(p != rq->curr);
3777 WARN_ON(p->pi_blocked_on);
3778 goto out_unlock;
3781 trace_sched_pi_setprio(p, pi_task);
3782 oldprio = p->prio;
3784 if (oldprio == prio)
3785 queue_flag &= ~DEQUEUE_MOVE;
3787 prev_class = p->sched_class;
3788 queued = task_on_rq_queued(p);
3789 running = task_current(rq, p);
3790 if (queued)
3791 dequeue_task(rq, p, queue_flag);
3792 if (running)
3793 put_prev_task(rq, p);
3796 * Boosting condition are:
3797 * 1. -rt task is running and holds mutex A
3798 * --> -dl task blocks on mutex A
3800 * 2. -dl task is running and holds mutex A
3801 * --> -dl task blocks on mutex A and could preempt the
3802 * running task
3804 if (dl_prio(prio)) {
3805 if (!dl_prio(p->normal_prio) ||
3806 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3807 p->dl.dl_boosted = 1;
3808 queue_flag |= ENQUEUE_REPLENISH;
3809 } else
3810 p->dl.dl_boosted = 0;
3811 p->sched_class = &dl_sched_class;
3812 } else if (rt_prio(prio)) {
3813 if (dl_prio(oldprio))
3814 p->dl.dl_boosted = 0;
3815 if (oldprio < prio)
3816 queue_flag |= ENQUEUE_HEAD;
3817 p->sched_class = &rt_sched_class;
3818 } else {
3819 if (dl_prio(oldprio))
3820 p->dl.dl_boosted = 0;
3821 if (rt_prio(oldprio))
3822 p->rt.timeout = 0;
3823 p->sched_class = &fair_sched_class;
3826 p->prio = prio;
3828 if (queued)
3829 enqueue_task(rq, p, queue_flag);
3830 if (running)
3831 set_curr_task(rq, p);
3833 check_class_changed(rq, p, prev_class, oldprio);
3834 out_unlock:
3835 /* Avoid rq from going away on us: */
3836 preempt_disable();
3837 __task_rq_unlock(rq, &rf);
3839 balance_callback(rq);
3840 preempt_enable();
3842 #else
3843 static inline int rt_effective_prio(struct task_struct *p, int prio)
3845 return prio;
3847 #endif
3849 void set_user_nice(struct task_struct *p, long nice)
3851 bool queued, running;
3852 int old_prio, delta;
3853 struct rq_flags rf;
3854 struct rq *rq;
3856 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3857 return;
3859 * We have to be careful, if called from sys_setpriority(),
3860 * the task might be in the middle of scheduling on another CPU.
3862 rq = task_rq_lock(p, &rf);
3863 update_rq_clock(rq);
3866 * The RT priorities are set via sched_setscheduler(), but we still
3867 * allow the 'normal' nice value to be set - but as expected
3868 * it wont have any effect on scheduling until the task is
3869 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3871 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3872 p->static_prio = NICE_TO_PRIO(nice);
3873 goto out_unlock;
3875 queued = task_on_rq_queued(p);
3876 running = task_current(rq, p);
3877 if (queued)
3878 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
3879 if (running)
3880 put_prev_task(rq, p);
3882 p->static_prio = NICE_TO_PRIO(nice);
3883 set_load_weight(p, true);
3884 old_prio = p->prio;
3885 p->prio = effective_prio(p);
3886 delta = p->prio - old_prio;
3888 if (queued) {
3889 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
3891 * If the task increased its priority or is running and
3892 * lowered its priority, then reschedule its CPU:
3894 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3895 resched_curr(rq);
3897 if (running)
3898 set_curr_task(rq, p);
3899 out_unlock:
3900 task_rq_unlock(rq, p, &rf);
3902 EXPORT_SYMBOL(set_user_nice);
3905 * can_nice - check if a task can reduce its nice value
3906 * @p: task
3907 * @nice: nice value
3909 int can_nice(const struct task_struct *p, const int nice)
3911 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
3912 int nice_rlim = nice_to_rlimit(nice);
3914 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3915 capable(CAP_SYS_NICE));
3918 #ifdef __ARCH_WANT_SYS_NICE
3921 * sys_nice - change the priority of the current process.
3922 * @increment: priority increment
3924 * sys_setpriority is a more generic, but much slower function that
3925 * does similar things.
3927 SYSCALL_DEFINE1(nice, int, increment)
3929 long nice, retval;
3932 * Setpriority might change our priority at the same moment.
3933 * We don't have to worry. Conceptually one call occurs first
3934 * and we have a single winner.
3936 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3937 nice = task_nice(current) + increment;
3939 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3940 if (increment < 0 && !can_nice(current, nice))
3941 return -EPERM;
3943 retval = security_task_setnice(current, nice);
3944 if (retval)
3945 return retval;
3947 set_user_nice(current, nice);
3948 return 0;
3951 #endif
3954 * task_prio - return the priority value of a given task.
3955 * @p: the task in question.
3957 * Return: The priority value as seen by users in /proc.
3958 * RT tasks are offset by -200. Normal tasks are centered
3959 * around 0, value goes from -16 to +15.
3961 int task_prio(const struct task_struct *p)
3963 return p->prio - MAX_RT_PRIO;
3967 * idle_cpu - is a given CPU idle currently?
3968 * @cpu: the processor in question.
3970 * Return: 1 if the CPU is currently idle. 0 otherwise.
3972 int idle_cpu(int cpu)
3974 struct rq *rq = cpu_rq(cpu);
3976 if (rq->curr != rq->idle)
3977 return 0;
3979 if (rq->nr_running)
3980 return 0;
3982 #ifdef CONFIG_SMP
3983 if (!llist_empty(&rq->wake_list))
3984 return 0;
3985 #endif
3987 return 1;
3991 * idle_task - return the idle task for a given CPU.
3992 * @cpu: the processor in question.
3994 * Return: The idle task for the CPU @cpu.
3996 struct task_struct *idle_task(int cpu)
3998 return cpu_rq(cpu)->idle;
4002 * find_process_by_pid - find a process with a matching PID value.
4003 * @pid: the pid in question.
4005 * The task of @pid, if found. %NULL otherwise.
4007 static struct task_struct *find_process_by_pid(pid_t pid)
4009 return pid ? find_task_by_vpid(pid) : current;
4013 * sched_setparam() passes in -1 for its policy, to let the functions
4014 * it calls know not to change it.
4016 #define SETPARAM_POLICY -1
4018 static void __setscheduler_params(struct task_struct *p,
4019 const struct sched_attr *attr)
4021 int policy = attr->sched_policy;
4023 if (policy == SETPARAM_POLICY)
4024 policy = p->policy;
4026 p->policy = policy;
4028 if (dl_policy(policy))
4029 __setparam_dl(p, attr);
4030 else if (fair_policy(policy))
4031 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4034 * __sched_setscheduler() ensures attr->sched_priority == 0 when
4035 * !rt_policy. Always setting this ensures that things like
4036 * getparam()/getattr() don't report silly values for !rt tasks.
4038 p->rt_priority = attr->sched_priority;
4039 p->normal_prio = normal_prio(p);
4040 set_load_weight(p, true);
4043 /* Actually do priority change: must hold pi & rq lock. */
4044 static void __setscheduler(struct rq *rq, struct task_struct *p,
4045 const struct sched_attr *attr, bool keep_boost)
4047 __setscheduler_params(p, attr);
4050 * Keep a potential priority boosting if called from
4051 * sched_setscheduler().
4053 p->prio = normal_prio(p);
4054 if (keep_boost)
4055 p->prio = rt_effective_prio(p, p->prio);
4057 if (dl_prio(p->prio))
4058 p->sched_class = &dl_sched_class;
4059 else if (rt_prio(p->prio))
4060 p->sched_class = &rt_sched_class;
4061 else
4062 p->sched_class = &fair_sched_class;
4066 * Check the target process has a UID that matches the current process's:
4068 static bool check_same_owner(struct task_struct *p)
4070 const struct cred *cred = current_cred(), *pcred;
4071 bool match;
4073 rcu_read_lock();
4074 pcred = __task_cred(p);
4075 match = (uid_eq(cred->euid, pcred->euid) ||
4076 uid_eq(cred->euid, pcred->uid));
4077 rcu_read_unlock();
4078 return match;
4081 static int __sched_setscheduler(struct task_struct *p,
4082 const struct sched_attr *attr,
4083 bool user, bool pi)
4085 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4086 MAX_RT_PRIO - 1 - attr->sched_priority;
4087 int retval, oldprio, oldpolicy = -1, queued, running;
4088 int new_effective_prio, policy = attr->sched_policy;
4089 const struct sched_class *prev_class;
4090 struct rq_flags rf;
4091 int reset_on_fork;
4092 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
4093 struct rq *rq;
4095 /* The pi code expects interrupts enabled */
4096 BUG_ON(pi && in_interrupt());
4097 recheck:
4098 /* Double check policy once rq lock held: */
4099 if (policy < 0) {
4100 reset_on_fork = p->sched_reset_on_fork;
4101 policy = oldpolicy = p->policy;
4102 } else {
4103 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4105 if (!valid_policy(policy))
4106 return -EINVAL;
4109 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
4110 return -EINVAL;
4113 * Valid priorities for SCHED_FIFO and SCHED_RR are
4114 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4115 * SCHED_BATCH and SCHED_IDLE is 0.
4117 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4118 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4119 return -EINVAL;
4120 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4121 (rt_policy(policy) != (attr->sched_priority != 0)))
4122 return -EINVAL;
4125 * Allow unprivileged RT tasks to decrease priority:
4127 if (user && !capable(CAP_SYS_NICE)) {
4128 if (fair_policy(policy)) {
4129 if (attr->sched_nice < task_nice(p) &&
4130 !can_nice(p, attr->sched_nice))
4131 return -EPERM;
4134 if (rt_policy(policy)) {
4135 unsigned long rlim_rtprio =
4136 task_rlimit(p, RLIMIT_RTPRIO);
4138 /* Can't set/change the rt policy: */
4139 if (policy != p->policy && !rlim_rtprio)
4140 return -EPERM;
4142 /* Can't increase priority: */
4143 if (attr->sched_priority > p->rt_priority &&
4144 attr->sched_priority > rlim_rtprio)
4145 return -EPERM;
4149 * Can't set/change SCHED_DEADLINE policy at all for now
4150 * (safest behavior); in the future we would like to allow
4151 * unprivileged DL tasks to increase their relative deadline
4152 * or reduce their runtime (both ways reducing utilization)
4154 if (dl_policy(policy))
4155 return -EPERM;
4158 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4159 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4161 if (idle_policy(p->policy) && !idle_policy(policy)) {
4162 if (!can_nice(p, task_nice(p)))
4163 return -EPERM;
4166 /* Can't change other user's priorities: */
4167 if (!check_same_owner(p))
4168 return -EPERM;
4170 /* Normal users shall not reset the sched_reset_on_fork flag: */
4171 if (p->sched_reset_on_fork && !reset_on_fork)
4172 return -EPERM;
4175 if (user) {
4176 if (attr->sched_flags & SCHED_FLAG_SUGOV)
4177 return -EINVAL;
4179 retval = security_task_setscheduler(p);
4180 if (retval)
4181 return retval;
4185 * Make sure no PI-waiters arrive (or leave) while we are
4186 * changing the priority of the task:
4188 * To be able to change p->policy safely, the appropriate
4189 * runqueue lock must be held.
4191 rq = task_rq_lock(p, &rf);
4192 update_rq_clock(rq);
4195 * Changing the policy of the stop threads its a very bad idea:
4197 if (p == rq->stop) {
4198 task_rq_unlock(rq, p, &rf);
4199 return -EINVAL;
4203 * If not changing anything there's no need to proceed further,
4204 * but store a possible modification of reset_on_fork.
4206 if (unlikely(policy == p->policy)) {
4207 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4208 goto change;
4209 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4210 goto change;
4211 if (dl_policy(policy) && dl_param_changed(p, attr))
4212 goto change;
4214 p->sched_reset_on_fork = reset_on_fork;
4215 task_rq_unlock(rq, p, &rf);
4216 return 0;
4218 change:
4220 if (user) {
4221 #ifdef CONFIG_RT_GROUP_SCHED
4223 * Do not allow realtime tasks into groups that have no runtime
4224 * assigned.
4226 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4227 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4228 !task_group_is_autogroup(task_group(p))) {
4229 task_rq_unlock(rq, p, &rf);
4230 return -EPERM;
4232 #endif
4233 #ifdef CONFIG_SMP
4234 if (dl_bandwidth_enabled() && dl_policy(policy) &&
4235 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
4236 cpumask_t *span = rq->rd->span;
4239 * Don't allow tasks with an affinity mask smaller than
4240 * the entire root_domain to become SCHED_DEADLINE. We
4241 * will also fail if there's no bandwidth available.
4243 if (!cpumask_subset(span, &p->cpus_allowed) ||
4244 rq->rd->dl_bw.bw == 0) {
4245 task_rq_unlock(rq, p, &rf);
4246 return -EPERM;
4249 #endif
4252 /* Re-check policy now with rq lock held: */
4253 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4254 policy = oldpolicy = -1;
4255 task_rq_unlock(rq, p, &rf);
4256 goto recheck;
4260 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4261 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4262 * is available.
4264 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
4265 task_rq_unlock(rq, p, &rf);
4266 return -EBUSY;
4269 p->sched_reset_on_fork = reset_on_fork;
4270 oldprio = p->prio;
4272 if (pi) {
4274 * Take priority boosted tasks into account. If the new
4275 * effective priority is unchanged, we just store the new
4276 * normal parameters and do not touch the scheduler class and
4277 * the runqueue. This will be done when the task deboost
4278 * itself.
4280 new_effective_prio = rt_effective_prio(p, newprio);
4281 if (new_effective_prio == oldprio)
4282 queue_flags &= ~DEQUEUE_MOVE;
4285 queued = task_on_rq_queued(p);
4286 running = task_current(rq, p);
4287 if (queued)
4288 dequeue_task(rq, p, queue_flags);
4289 if (running)
4290 put_prev_task(rq, p);
4292 prev_class = p->sched_class;
4293 __setscheduler(rq, p, attr, pi);
4295 if (queued) {
4297 * We enqueue to tail when the priority of a task is
4298 * increased (user space view).
4300 if (oldprio < p->prio)
4301 queue_flags |= ENQUEUE_HEAD;
4303 enqueue_task(rq, p, queue_flags);
4305 if (running)
4306 set_curr_task(rq, p);
4308 check_class_changed(rq, p, prev_class, oldprio);
4310 /* Avoid rq from going away on us: */
4311 preempt_disable();
4312 task_rq_unlock(rq, p, &rf);
4314 if (pi)
4315 rt_mutex_adjust_pi(p);
4317 /* Run balance callbacks after we've adjusted the PI chain: */
4318 balance_callback(rq);
4319 preempt_enable();
4321 return 0;
4324 static int _sched_setscheduler(struct task_struct *p, int policy,
4325 const struct sched_param *param, bool check)
4327 struct sched_attr attr = {
4328 .sched_policy = policy,
4329 .sched_priority = param->sched_priority,
4330 .sched_nice = PRIO_TO_NICE(p->static_prio),
4333 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4334 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4335 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4336 policy &= ~SCHED_RESET_ON_FORK;
4337 attr.sched_policy = policy;
4340 return __sched_setscheduler(p, &attr, check, true);
4343 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4344 * @p: the task in question.
4345 * @policy: new policy.
4346 * @param: structure containing the new RT priority.
4348 * Return: 0 on success. An error code otherwise.
4350 * NOTE that the task may be already dead.
4352 int sched_setscheduler(struct task_struct *p, int policy,
4353 const struct sched_param *param)
4355 return _sched_setscheduler(p, policy, param, true);
4357 EXPORT_SYMBOL_GPL(sched_setscheduler);
4359 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4361 return __sched_setscheduler(p, attr, true, true);
4363 EXPORT_SYMBOL_GPL(sched_setattr);
4365 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
4367 return __sched_setscheduler(p, attr, false, true);
4371 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4372 * @p: the task in question.
4373 * @policy: new policy.
4374 * @param: structure containing the new RT priority.
4376 * Just like sched_setscheduler, only don't bother checking if the
4377 * current context has permission. For example, this is needed in
4378 * stop_machine(): we create temporary high priority worker threads,
4379 * but our caller might not have that capability.
4381 * Return: 0 on success. An error code otherwise.
4383 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4384 const struct sched_param *param)
4386 return _sched_setscheduler(p, policy, param, false);
4388 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4390 static int
4391 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4393 struct sched_param lparam;
4394 struct task_struct *p;
4395 int retval;
4397 if (!param || pid < 0)
4398 return -EINVAL;
4399 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4400 return -EFAULT;
4402 rcu_read_lock();
4403 retval = -ESRCH;
4404 p = find_process_by_pid(pid);
4405 if (p != NULL)
4406 retval = sched_setscheduler(p, policy, &lparam);
4407 rcu_read_unlock();
4409 return retval;
4413 * Mimics kernel/events/core.c perf_copy_attr().
4415 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
4417 u32 size;
4418 int ret;
4420 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4421 return -EFAULT;
4423 /* Zero the full structure, so that a short copy will be nice: */
4424 memset(attr, 0, sizeof(*attr));
4426 ret = get_user(size, &uattr->size);
4427 if (ret)
4428 return ret;
4430 /* Bail out on silly large: */
4431 if (size > PAGE_SIZE)
4432 goto err_size;
4434 /* ABI compatibility quirk: */
4435 if (!size)
4436 size = SCHED_ATTR_SIZE_VER0;
4438 if (size < SCHED_ATTR_SIZE_VER0)
4439 goto err_size;
4442 * If we're handed a bigger struct than we know of,
4443 * ensure all the unknown bits are 0 - i.e. new
4444 * user-space does not rely on any kernel feature
4445 * extensions we dont know about yet.
4447 if (size > sizeof(*attr)) {
4448 unsigned char __user *addr;
4449 unsigned char __user *end;
4450 unsigned char val;
4452 addr = (void __user *)uattr + sizeof(*attr);
4453 end = (void __user *)uattr + size;
4455 for (; addr < end; addr++) {
4456 ret = get_user(val, addr);
4457 if (ret)
4458 return ret;
4459 if (val)
4460 goto err_size;
4462 size = sizeof(*attr);
4465 ret = copy_from_user(attr, uattr, size);
4466 if (ret)
4467 return -EFAULT;
4470 * XXX: Do we want to be lenient like existing syscalls; or do we want
4471 * to be strict and return an error on out-of-bounds values?
4473 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4475 return 0;
4477 err_size:
4478 put_user(sizeof(*attr), &uattr->size);
4479 return -E2BIG;
4483 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4484 * @pid: the pid in question.
4485 * @policy: new policy.
4486 * @param: structure containing the new RT priority.
4488 * Return: 0 on success. An error code otherwise.
4490 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
4492 if (policy < 0)
4493 return -EINVAL;
4495 return do_sched_setscheduler(pid, policy, param);
4499 * sys_sched_setparam - set/change the RT priority of a thread
4500 * @pid: the pid in question.
4501 * @param: structure containing the new RT priority.
4503 * Return: 0 on success. An error code otherwise.
4505 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4507 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4511 * sys_sched_setattr - same as above, but with extended sched_attr
4512 * @pid: the pid in question.
4513 * @uattr: structure containing the extended parameters.
4514 * @flags: for future extension.
4516 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4517 unsigned int, flags)
4519 struct sched_attr attr;
4520 struct task_struct *p;
4521 int retval;
4523 if (!uattr || pid < 0 || flags)
4524 return -EINVAL;
4526 retval = sched_copy_attr(uattr, &attr);
4527 if (retval)
4528 return retval;
4530 if ((int)attr.sched_policy < 0)
4531 return -EINVAL;
4533 rcu_read_lock();
4534 retval = -ESRCH;
4535 p = find_process_by_pid(pid);
4536 if (p != NULL)
4537 retval = sched_setattr(p, &attr);
4538 rcu_read_unlock();
4540 return retval;
4544 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4545 * @pid: the pid in question.
4547 * Return: On success, the policy of the thread. Otherwise, a negative error
4548 * code.
4550 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4552 struct task_struct *p;
4553 int retval;
4555 if (pid < 0)
4556 return -EINVAL;
4558 retval = -ESRCH;
4559 rcu_read_lock();
4560 p = find_process_by_pid(pid);
4561 if (p) {
4562 retval = security_task_getscheduler(p);
4563 if (!retval)
4564 retval = p->policy
4565 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4567 rcu_read_unlock();
4568 return retval;
4572 * sys_sched_getparam - get the RT priority of a thread
4573 * @pid: the pid in question.
4574 * @param: structure containing the RT priority.
4576 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4577 * code.
4579 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4581 struct sched_param lp = { .sched_priority = 0 };
4582 struct task_struct *p;
4583 int retval;
4585 if (!param || pid < 0)
4586 return -EINVAL;
4588 rcu_read_lock();
4589 p = find_process_by_pid(pid);
4590 retval = -ESRCH;
4591 if (!p)
4592 goto out_unlock;
4594 retval = security_task_getscheduler(p);
4595 if (retval)
4596 goto out_unlock;
4598 if (task_has_rt_policy(p))
4599 lp.sched_priority = p->rt_priority;
4600 rcu_read_unlock();
4603 * This one might sleep, we cannot do it with a spinlock held ...
4605 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4607 return retval;
4609 out_unlock:
4610 rcu_read_unlock();
4611 return retval;
4614 static int sched_read_attr(struct sched_attr __user *uattr,
4615 struct sched_attr *attr,
4616 unsigned int usize)
4618 int ret;
4620 if (!access_ok(VERIFY_WRITE, uattr, usize))
4621 return -EFAULT;
4624 * If we're handed a smaller struct than we know of,
4625 * ensure all the unknown bits are 0 - i.e. old
4626 * user-space does not get uncomplete information.
4628 if (usize < sizeof(*attr)) {
4629 unsigned char *addr;
4630 unsigned char *end;
4632 addr = (void *)attr + usize;
4633 end = (void *)attr + sizeof(*attr);
4635 for (; addr < end; addr++) {
4636 if (*addr)
4637 return -EFBIG;
4640 attr->size = usize;
4643 ret = copy_to_user(uattr, attr, attr->size);
4644 if (ret)
4645 return -EFAULT;
4647 return 0;
4651 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4652 * @pid: the pid in question.
4653 * @uattr: structure containing the extended parameters.
4654 * @size: sizeof(attr) for fwd/bwd comp.
4655 * @flags: for future extension.
4657 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4658 unsigned int, size, unsigned int, flags)
4660 struct sched_attr attr = {
4661 .size = sizeof(struct sched_attr),
4663 struct task_struct *p;
4664 int retval;
4666 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4667 size < SCHED_ATTR_SIZE_VER0 || flags)
4668 return -EINVAL;
4670 rcu_read_lock();
4671 p = find_process_by_pid(pid);
4672 retval = -ESRCH;
4673 if (!p)
4674 goto out_unlock;
4676 retval = security_task_getscheduler(p);
4677 if (retval)
4678 goto out_unlock;
4680 attr.sched_policy = p->policy;
4681 if (p->sched_reset_on_fork)
4682 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4683 if (task_has_dl_policy(p))
4684 __getparam_dl(p, &attr);
4685 else if (task_has_rt_policy(p))
4686 attr.sched_priority = p->rt_priority;
4687 else
4688 attr.sched_nice = task_nice(p);
4690 rcu_read_unlock();
4692 retval = sched_read_attr(uattr, &attr, size);
4693 return retval;
4695 out_unlock:
4696 rcu_read_unlock();
4697 return retval;
4700 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4702 cpumask_var_t cpus_allowed, new_mask;
4703 struct task_struct *p;
4704 int retval;
4706 rcu_read_lock();
4708 p = find_process_by_pid(pid);
4709 if (!p) {
4710 rcu_read_unlock();
4711 return -ESRCH;
4714 /* Prevent p going away */
4715 get_task_struct(p);
4716 rcu_read_unlock();
4718 if (p->flags & PF_NO_SETAFFINITY) {
4719 retval = -EINVAL;
4720 goto out_put_task;
4722 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4723 retval = -ENOMEM;
4724 goto out_put_task;
4726 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4727 retval = -ENOMEM;
4728 goto out_free_cpus_allowed;
4730 retval = -EPERM;
4731 if (!check_same_owner(p)) {
4732 rcu_read_lock();
4733 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4734 rcu_read_unlock();
4735 goto out_free_new_mask;
4737 rcu_read_unlock();
4740 retval = security_task_setscheduler(p);
4741 if (retval)
4742 goto out_free_new_mask;
4745 cpuset_cpus_allowed(p, cpus_allowed);
4746 cpumask_and(new_mask, in_mask, cpus_allowed);
4749 * Since bandwidth control happens on root_domain basis,
4750 * if admission test is enabled, we only admit -deadline
4751 * tasks allowed to run on all the CPUs in the task's
4752 * root_domain.
4754 #ifdef CONFIG_SMP
4755 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4756 rcu_read_lock();
4757 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4758 retval = -EBUSY;
4759 rcu_read_unlock();
4760 goto out_free_new_mask;
4762 rcu_read_unlock();
4764 #endif
4765 again:
4766 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4768 if (!retval) {
4769 cpuset_cpus_allowed(p, cpus_allowed);
4770 if (!cpumask_subset(new_mask, cpus_allowed)) {
4772 * We must have raced with a concurrent cpuset
4773 * update. Just reset the cpus_allowed to the
4774 * cpuset's cpus_allowed
4776 cpumask_copy(new_mask, cpus_allowed);
4777 goto again;
4780 out_free_new_mask:
4781 free_cpumask_var(new_mask);
4782 out_free_cpus_allowed:
4783 free_cpumask_var(cpus_allowed);
4784 out_put_task:
4785 put_task_struct(p);
4786 return retval;
4789 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4790 struct cpumask *new_mask)
4792 if (len < cpumask_size())
4793 cpumask_clear(new_mask);
4794 else if (len > cpumask_size())
4795 len = cpumask_size();
4797 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4801 * sys_sched_setaffinity - set the CPU affinity of a process
4802 * @pid: pid of the process
4803 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4804 * @user_mask_ptr: user-space pointer to the new CPU mask
4806 * Return: 0 on success. An error code otherwise.
4808 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4809 unsigned long __user *, user_mask_ptr)
4811 cpumask_var_t new_mask;
4812 int retval;
4814 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4815 return -ENOMEM;
4817 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4818 if (retval == 0)
4819 retval = sched_setaffinity(pid, new_mask);
4820 free_cpumask_var(new_mask);
4821 return retval;
4824 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4826 struct task_struct *p;
4827 unsigned long flags;
4828 int retval;
4830 rcu_read_lock();
4832 retval = -ESRCH;
4833 p = find_process_by_pid(pid);
4834 if (!p)
4835 goto out_unlock;
4837 retval = security_task_getscheduler(p);
4838 if (retval)
4839 goto out_unlock;
4841 raw_spin_lock_irqsave(&p->pi_lock, flags);
4842 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4843 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4845 out_unlock:
4846 rcu_read_unlock();
4848 return retval;
4852 * sys_sched_getaffinity - get the CPU affinity of a process
4853 * @pid: pid of the process
4854 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4855 * @user_mask_ptr: user-space pointer to hold the current CPU mask
4857 * Return: size of CPU mask copied to user_mask_ptr on success. An
4858 * error code otherwise.
4860 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4861 unsigned long __user *, user_mask_ptr)
4863 int ret;
4864 cpumask_var_t mask;
4866 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4867 return -EINVAL;
4868 if (len & (sizeof(unsigned long)-1))
4869 return -EINVAL;
4871 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4872 return -ENOMEM;
4874 ret = sched_getaffinity(pid, mask);
4875 if (ret == 0) {
4876 unsigned int retlen = min(len, cpumask_size());
4878 if (copy_to_user(user_mask_ptr, mask, retlen))
4879 ret = -EFAULT;
4880 else
4881 ret = retlen;
4883 free_cpumask_var(mask);
4885 return ret;
4889 * sys_sched_yield - yield the current processor to other threads.
4891 * This function yields the current CPU to other tasks. If there are no
4892 * other threads running on this CPU then this function will return.
4894 * Return: 0.
4896 SYSCALL_DEFINE0(sched_yield)
4898 struct rq_flags rf;
4899 struct rq *rq;
4901 local_irq_disable();
4902 rq = this_rq();
4903 rq_lock(rq, &rf);
4905 schedstat_inc(rq->yld_count);
4906 current->sched_class->yield_task(rq);
4909 * Since we are going to call schedule() anyway, there's
4910 * no need to preempt or enable interrupts:
4912 preempt_disable();
4913 rq_unlock(rq, &rf);
4914 sched_preempt_enable_no_resched();
4916 schedule();
4918 return 0;
4921 #ifndef CONFIG_PREEMPT
4922 int __sched _cond_resched(void)
4924 if (should_resched(0)) {
4925 preempt_schedule_common();
4926 return 1;
4928 rcu_all_qs();
4929 return 0;
4931 EXPORT_SYMBOL(_cond_resched);
4932 #endif
4935 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4936 * call schedule, and on return reacquire the lock.
4938 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4939 * operations here to prevent schedule() from being called twice (once via
4940 * spin_unlock(), once by hand).
4942 int __cond_resched_lock(spinlock_t *lock)
4944 int resched = should_resched(PREEMPT_LOCK_OFFSET);
4945 int ret = 0;
4947 lockdep_assert_held(lock);
4949 if (spin_needbreak(lock) || resched) {
4950 spin_unlock(lock);
4951 if (resched)
4952 preempt_schedule_common();
4953 else
4954 cpu_relax();
4955 ret = 1;
4956 spin_lock(lock);
4958 return ret;
4960 EXPORT_SYMBOL(__cond_resched_lock);
4962 int __sched __cond_resched_softirq(void)
4964 BUG_ON(!in_softirq());
4966 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
4967 local_bh_enable();
4968 preempt_schedule_common();
4969 local_bh_disable();
4970 return 1;
4972 return 0;
4974 EXPORT_SYMBOL(__cond_resched_softirq);
4977 * yield - yield the current processor to other threads.
4979 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4981 * The scheduler is at all times free to pick the calling task as the most
4982 * eligible task to run, if removing the yield() call from your code breaks
4983 * it, its already broken.
4985 * Typical broken usage is:
4987 * while (!event)
4988 * yield();
4990 * where one assumes that yield() will let 'the other' process run that will
4991 * make event true. If the current task is a SCHED_FIFO task that will never
4992 * happen. Never use yield() as a progress guarantee!!
4994 * If you want to use yield() to wait for something, use wait_event().
4995 * If you want to use yield() to be 'nice' for others, use cond_resched().
4996 * If you still want to use yield(), do not!
4998 void __sched yield(void)
5000 set_current_state(TASK_RUNNING);
5001 sys_sched_yield();
5003 EXPORT_SYMBOL(yield);
5006 * yield_to - yield the current processor to another thread in
5007 * your thread group, or accelerate that thread toward the
5008 * processor it's on.
5009 * @p: target task
5010 * @preempt: whether task preemption is allowed or not
5012 * It's the caller's job to ensure that the target task struct
5013 * can't go away on us before we can do any checks.
5015 * Return:
5016 * true (>0) if we indeed boosted the target task.
5017 * false (0) if we failed to boost the target.
5018 * -ESRCH if there's no task to yield to.
5020 int __sched yield_to(struct task_struct *p, bool preempt)
5022 struct task_struct *curr = current;
5023 struct rq *rq, *p_rq;
5024 unsigned long flags;
5025 int yielded = 0;
5027 local_irq_save(flags);
5028 rq = this_rq();
5030 again:
5031 p_rq = task_rq(p);
5033 * If we're the only runnable task on the rq and target rq also
5034 * has only one task, there's absolutely no point in yielding.
5036 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5037 yielded = -ESRCH;
5038 goto out_irq;
5041 double_rq_lock(rq, p_rq);
5042 if (task_rq(p) != p_rq) {
5043 double_rq_unlock(rq, p_rq);
5044 goto again;
5047 if (!curr->sched_class->yield_to_task)
5048 goto out_unlock;
5050 if (curr->sched_class != p->sched_class)
5051 goto out_unlock;
5053 if (task_running(p_rq, p) || p->state)
5054 goto out_unlock;
5056 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5057 if (yielded) {
5058 schedstat_inc(rq->yld_count);
5060 * Make p's CPU reschedule; pick_next_entity takes care of
5061 * fairness.
5063 if (preempt && rq != p_rq)
5064 resched_curr(p_rq);
5067 out_unlock:
5068 double_rq_unlock(rq, p_rq);
5069 out_irq:
5070 local_irq_restore(flags);
5072 if (yielded > 0)
5073 schedule();
5075 return yielded;
5077 EXPORT_SYMBOL_GPL(yield_to);
5079 int io_schedule_prepare(void)
5081 int old_iowait = current->in_iowait;
5083 current->in_iowait = 1;
5084 blk_schedule_flush_plug(current);
5086 return old_iowait;
5089 void io_schedule_finish(int token)
5091 current->in_iowait = token;
5095 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5096 * that process accounting knows that this is a task in IO wait state.
5098 long __sched io_schedule_timeout(long timeout)
5100 int token;
5101 long ret;
5103 token = io_schedule_prepare();
5104 ret = schedule_timeout(timeout);
5105 io_schedule_finish(token);
5107 return ret;
5109 EXPORT_SYMBOL(io_schedule_timeout);
5111 void io_schedule(void)
5113 int token;
5115 token = io_schedule_prepare();
5116 schedule();
5117 io_schedule_finish(token);
5119 EXPORT_SYMBOL(io_schedule);
5122 * sys_sched_get_priority_max - return maximum RT priority.
5123 * @policy: scheduling class.
5125 * Return: On success, this syscall returns the maximum
5126 * rt_priority that can be used by a given scheduling class.
5127 * On failure, a negative error code is returned.
5129 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5131 int ret = -EINVAL;
5133 switch (policy) {
5134 case SCHED_FIFO:
5135 case SCHED_RR:
5136 ret = MAX_USER_RT_PRIO-1;
5137 break;
5138 case SCHED_DEADLINE:
5139 case SCHED_NORMAL:
5140 case SCHED_BATCH:
5141 case SCHED_IDLE:
5142 ret = 0;
5143 break;
5145 return ret;
5149 * sys_sched_get_priority_min - return minimum RT priority.
5150 * @policy: scheduling class.
5152 * Return: On success, this syscall returns the minimum
5153 * rt_priority that can be used by a given scheduling class.
5154 * On failure, a negative error code is returned.
5156 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5158 int ret = -EINVAL;
5160 switch (policy) {
5161 case SCHED_FIFO:
5162 case SCHED_RR:
5163 ret = 1;
5164 break;
5165 case SCHED_DEADLINE:
5166 case SCHED_NORMAL:
5167 case SCHED_BATCH:
5168 case SCHED_IDLE:
5169 ret = 0;
5171 return ret;
5174 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
5176 struct task_struct *p;
5177 unsigned int time_slice;
5178 struct rq_flags rf;
5179 struct rq *rq;
5180 int retval;
5182 if (pid < 0)
5183 return -EINVAL;
5185 retval = -ESRCH;
5186 rcu_read_lock();
5187 p = find_process_by_pid(pid);
5188 if (!p)
5189 goto out_unlock;
5191 retval = security_task_getscheduler(p);
5192 if (retval)
5193 goto out_unlock;
5195 rq = task_rq_lock(p, &rf);
5196 time_slice = 0;
5197 if (p->sched_class->get_rr_interval)
5198 time_slice = p->sched_class->get_rr_interval(rq, p);
5199 task_rq_unlock(rq, p, &rf);
5201 rcu_read_unlock();
5202 jiffies_to_timespec64(time_slice, t);
5203 return 0;
5205 out_unlock:
5206 rcu_read_unlock();
5207 return retval;
5211 * sys_sched_rr_get_interval - return the default timeslice of a process.
5212 * @pid: pid of the process.
5213 * @interval: userspace pointer to the timeslice value.
5215 * this syscall writes the default timeslice value of a given process
5216 * into the user-space timespec buffer. A value of '0' means infinity.
5218 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5219 * an error code.
5221 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5222 struct timespec __user *, interval)
5224 struct timespec64 t;
5225 int retval = sched_rr_get_interval(pid, &t);
5227 if (retval == 0)
5228 retval = put_timespec64(&t, interval);
5230 return retval;
5233 #ifdef CONFIG_COMPAT
5234 COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
5235 compat_pid_t, pid,
5236 struct compat_timespec __user *, interval)
5238 struct timespec64 t;
5239 int retval = sched_rr_get_interval(pid, &t);
5241 if (retval == 0)
5242 retval = compat_put_timespec64(&t, interval);
5243 return retval;
5245 #endif
5247 void sched_show_task(struct task_struct *p)
5249 unsigned long free = 0;
5250 int ppid;
5252 if (!try_get_task_stack(p))
5253 return;
5255 printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
5257 if (p->state == TASK_RUNNING)
5258 printk(KERN_CONT " running task ");
5259 #ifdef CONFIG_DEBUG_STACK_USAGE
5260 free = stack_not_used(p);
5261 #endif
5262 ppid = 0;
5263 rcu_read_lock();
5264 if (pid_alive(p))
5265 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5266 rcu_read_unlock();
5267 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5268 task_pid_nr(p), ppid,
5269 (unsigned long)task_thread_info(p)->flags);
5271 print_worker_info(KERN_INFO, p);
5272 show_stack(p, NULL);
5273 put_task_stack(p);
5275 EXPORT_SYMBOL_GPL(sched_show_task);
5277 static inline bool
5278 state_filter_match(unsigned long state_filter, struct task_struct *p)
5280 /* no filter, everything matches */
5281 if (!state_filter)
5282 return true;
5284 /* filter, but doesn't match */
5285 if (!(p->state & state_filter))
5286 return false;
5289 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5290 * TASK_KILLABLE).
5292 if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
5293 return false;
5295 return true;
5299 void show_state_filter(unsigned long state_filter)
5301 struct task_struct *g, *p;
5303 #if BITS_PER_LONG == 32
5304 printk(KERN_INFO
5305 " task PC stack pid father\n");
5306 #else
5307 printk(KERN_INFO
5308 " task PC stack pid father\n");
5309 #endif
5310 rcu_read_lock();
5311 for_each_process_thread(g, p) {
5313 * reset the NMI-timeout, listing all files on a slow
5314 * console might take a lot of time:
5315 * Also, reset softlockup watchdogs on all CPUs, because
5316 * another CPU might be blocked waiting for us to process
5317 * an IPI.
5319 touch_nmi_watchdog();
5320 touch_all_softlockup_watchdogs();
5321 if (state_filter_match(state_filter, p))
5322 sched_show_task(p);
5325 #ifdef CONFIG_SCHED_DEBUG
5326 if (!state_filter)
5327 sysrq_sched_debug_show();
5328 #endif
5329 rcu_read_unlock();
5331 * Only show locks if all tasks are dumped:
5333 if (!state_filter)
5334 debug_show_all_locks();
5338 * init_idle - set up an idle thread for a given CPU
5339 * @idle: task in question
5340 * @cpu: CPU the idle task belongs to
5342 * NOTE: this function does not set the idle thread's NEED_RESCHED
5343 * flag, to make booting more robust.
5345 void init_idle(struct task_struct *idle, int cpu)
5347 struct rq *rq = cpu_rq(cpu);
5348 unsigned long flags;
5350 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5351 raw_spin_lock(&rq->lock);
5353 __sched_fork(0, idle);
5354 idle->state = TASK_RUNNING;
5355 idle->se.exec_start = sched_clock();
5356 idle->flags |= PF_IDLE;
5358 kasan_unpoison_task_stack(idle);
5360 #ifdef CONFIG_SMP
5362 * Its possible that init_idle() gets called multiple times on a task,
5363 * in that case do_set_cpus_allowed() will not do the right thing.
5365 * And since this is boot we can forgo the serialization.
5367 set_cpus_allowed_common(idle, cpumask_of(cpu));
5368 #endif
5370 * We're having a chicken and egg problem, even though we are
5371 * holding rq->lock, the CPU isn't yet set to this CPU so the
5372 * lockdep check in task_group() will fail.
5374 * Similar case to sched_fork(). / Alternatively we could
5375 * use task_rq_lock() here and obtain the other rq->lock.
5377 * Silence PROVE_RCU
5379 rcu_read_lock();
5380 __set_task_cpu(idle, cpu);
5381 rcu_read_unlock();
5383 rq->curr = rq->idle = idle;
5384 idle->on_rq = TASK_ON_RQ_QUEUED;
5385 #ifdef CONFIG_SMP
5386 idle->on_cpu = 1;
5387 #endif
5388 raw_spin_unlock(&rq->lock);
5389 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5391 /* Set the preempt count _outside_ the spinlocks! */
5392 init_idle_preempt_count(idle, cpu);
5395 * The idle tasks have their own, simple scheduling class:
5397 idle->sched_class = &idle_sched_class;
5398 ftrace_graph_init_idle_task(idle, cpu);
5399 vtime_init_idle(idle, cpu);
5400 #ifdef CONFIG_SMP
5401 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5402 #endif
5405 #ifdef CONFIG_SMP
5407 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5408 const struct cpumask *trial)
5410 int ret = 1;
5412 if (!cpumask_weight(cur))
5413 return ret;
5415 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
5417 return ret;
5420 int task_can_attach(struct task_struct *p,
5421 const struct cpumask *cs_cpus_allowed)
5423 int ret = 0;
5426 * Kthreads which disallow setaffinity shouldn't be moved
5427 * to a new cpuset; we don't want to change their CPU
5428 * affinity and isolating such threads by their set of
5429 * allowed nodes is unnecessary. Thus, cpusets are not
5430 * applicable for such threads. This prevents checking for
5431 * success of set_cpus_allowed_ptr() on all attached tasks
5432 * before cpus_allowed may be changed.
5434 if (p->flags & PF_NO_SETAFFINITY) {
5435 ret = -EINVAL;
5436 goto out;
5439 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5440 cs_cpus_allowed))
5441 ret = dl_task_can_attach(p, cs_cpus_allowed);
5443 out:
5444 return ret;
5447 bool sched_smp_initialized __read_mostly;
5449 #ifdef CONFIG_NUMA_BALANCING
5450 /* Migrate current task p to target_cpu */
5451 int migrate_task_to(struct task_struct *p, int target_cpu)
5453 struct migration_arg arg = { p, target_cpu };
5454 int curr_cpu = task_cpu(p);
5456 if (curr_cpu == target_cpu)
5457 return 0;
5459 if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
5460 return -EINVAL;
5462 /* TODO: This is not properly updating schedstats */
5464 trace_sched_move_numa(p, curr_cpu, target_cpu);
5465 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5469 * Requeue a task on a given node and accurately track the number of NUMA
5470 * tasks on the runqueues
5472 void sched_setnuma(struct task_struct *p, int nid)
5474 bool queued, running;
5475 struct rq_flags rf;
5476 struct rq *rq;
5478 rq = task_rq_lock(p, &rf);
5479 queued = task_on_rq_queued(p);
5480 running = task_current(rq, p);
5482 if (queued)
5483 dequeue_task(rq, p, DEQUEUE_SAVE);
5484 if (running)
5485 put_prev_task(rq, p);
5487 p->numa_preferred_nid = nid;
5489 if (queued)
5490 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
5491 if (running)
5492 set_curr_task(rq, p);
5493 task_rq_unlock(rq, p, &rf);
5495 #endif /* CONFIG_NUMA_BALANCING */
5497 #ifdef CONFIG_HOTPLUG_CPU
5499 * Ensure that the idle task is using init_mm right before its CPU goes
5500 * offline.
5502 void idle_task_exit(void)
5504 struct mm_struct *mm = current->active_mm;
5506 BUG_ON(cpu_online(smp_processor_id()));
5508 if (mm != &init_mm) {
5509 switch_mm(mm, &init_mm, current);
5510 finish_arch_post_lock_switch();
5512 mmdrop(mm);
5516 * Since this CPU is going 'away' for a while, fold any nr_active delta
5517 * we might have. Assumes we're called after migrate_tasks() so that the
5518 * nr_active count is stable. We need to take the teardown thread which
5519 * is calling this into account, so we hand in adjust = 1 to the load
5520 * calculation.
5522 * Also see the comment "Global load-average calculations".
5524 static void calc_load_migrate(struct rq *rq)
5526 long delta = calc_load_fold_active(rq, 1);
5527 if (delta)
5528 atomic_long_add(delta, &calc_load_tasks);
5531 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5535 static const struct sched_class fake_sched_class = {
5536 .put_prev_task = put_prev_task_fake,
5539 static struct task_struct fake_task = {
5541 * Avoid pull_{rt,dl}_task()
5543 .prio = MAX_PRIO + 1,
5544 .sched_class = &fake_sched_class,
5548 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5549 * try_to_wake_up()->select_task_rq().
5551 * Called with rq->lock held even though we'er in stop_machine() and
5552 * there's no concurrency possible, we hold the required locks anyway
5553 * because of lock validation efforts.
5555 static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
5557 struct rq *rq = dead_rq;
5558 struct task_struct *next, *stop = rq->stop;
5559 struct rq_flags orf = *rf;
5560 int dest_cpu;
5563 * Fudge the rq selection such that the below task selection loop
5564 * doesn't get stuck on the currently eligible stop task.
5566 * We're currently inside stop_machine() and the rq is either stuck
5567 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5568 * either way we should never end up calling schedule() until we're
5569 * done here.
5571 rq->stop = NULL;
5574 * put_prev_task() and pick_next_task() sched
5575 * class method both need to have an up-to-date
5576 * value of rq->clock[_task]
5578 update_rq_clock(rq);
5580 for (;;) {
5582 * There's this thread running, bail when that's the only
5583 * remaining thread:
5585 if (rq->nr_running == 1)
5586 break;
5589 * pick_next_task() assumes pinned rq->lock:
5591 next = pick_next_task(rq, &fake_task, rf);
5592 BUG_ON(!next);
5593 put_prev_task(rq, next);
5596 * Rules for changing task_struct::cpus_allowed are holding
5597 * both pi_lock and rq->lock, such that holding either
5598 * stabilizes the mask.
5600 * Drop rq->lock is not quite as disastrous as it usually is
5601 * because !cpu_active at this point, which means load-balance
5602 * will not interfere. Also, stop-machine.
5604 rq_unlock(rq, rf);
5605 raw_spin_lock(&next->pi_lock);
5606 rq_relock(rq, rf);
5609 * Since we're inside stop-machine, _nothing_ should have
5610 * changed the task, WARN if weird stuff happened, because in
5611 * that case the above rq->lock drop is a fail too.
5613 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5614 raw_spin_unlock(&next->pi_lock);
5615 continue;
5618 /* Find suitable destination for @next, with force if needed. */
5619 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5620 rq = __migrate_task(rq, rf, next, dest_cpu);
5621 if (rq != dead_rq) {
5622 rq_unlock(rq, rf);
5623 rq = dead_rq;
5624 *rf = orf;
5625 rq_relock(rq, rf);
5627 raw_spin_unlock(&next->pi_lock);
5630 rq->stop = stop;
5632 #endif /* CONFIG_HOTPLUG_CPU */
5634 void set_rq_online(struct rq *rq)
5636 if (!rq->online) {
5637 const struct sched_class *class;
5639 cpumask_set_cpu(rq->cpu, rq->rd->online);
5640 rq->online = 1;
5642 for_each_class(class) {
5643 if (class->rq_online)
5644 class->rq_online(rq);
5649 void set_rq_offline(struct rq *rq)
5651 if (rq->online) {
5652 const struct sched_class *class;
5654 for_each_class(class) {
5655 if (class->rq_offline)
5656 class->rq_offline(rq);
5659 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5660 rq->online = 0;
5664 static void set_cpu_rq_start_time(unsigned int cpu)
5666 struct rq *rq = cpu_rq(cpu);
5668 rq->age_stamp = sched_clock_cpu(cpu);
5672 * used to mark begin/end of suspend/resume:
5674 static int num_cpus_frozen;
5677 * Update cpusets according to cpu_active mask. If cpusets are
5678 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5679 * around partition_sched_domains().
5681 * If we come here as part of a suspend/resume, don't touch cpusets because we
5682 * want to restore it back to its original state upon resume anyway.
5684 static void cpuset_cpu_active(void)
5686 if (cpuhp_tasks_frozen) {
5688 * num_cpus_frozen tracks how many CPUs are involved in suspend
5689 * resume sequence. As long as this is not the last online
5690 * operation in the resume sequence, just build a single sched
5691 * domain, ignoring cpusets.
5693 partition_sched_domains(1, NULL, NULL);
5694 if (--num_cpus_frozen)
5695 return;
5697 * This is the last CPU online operation. So fall through and
5698 * restore the original sched domains by considering the
5699 * cpuset configurations.
5701 cpuset_force_rebuild();
5703 cpuset_update_active_cpus();
5706 static int cpuset_cpu_inactive(unsigned int cpu)
5708 if (!cpuhp_tasks_frozen) {
5709 if (dl_cpu_busy(cpu))
5710 return -EBUSY;
5711 cpuset_update_active_cpus();
5712 } else {
5713 num_cpus_frozen++;
5714 partition_sched_domains(1, NULL, NULL);
5716 return 0;
5719 int sched_cpu_activate(unsigned int cpu)
5721 struct rq *rq = cpu_rq(cpu);
5722 struct rq_flags rf;
5724 set_cpu_active(cpu, true);
5726 if (sched_smp_initialized) {
5727 sched_domains_numa_masks_set(cpu);
5728 cpuset_cpu_active();
5732 * Put the rq online, if not already. This happens:
5734 * 1) In the early boot process, because we build the real domains
5735 * after all CPUs have been brought up.
5737 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5738 * domains.
5740 rq_lock_irqsave(rq, &rf);
5741 if (rq->rd) {
5742 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5743 set_rq_online(rq);
5745 rq_unlock_irqrestore(rq, &rf);
5747 update_max_interval();
5749 return 0;
5752 int sched_cpu_deactivate(unsigned int cpu)
5754 int ret;
5756 set_cpu_active(cpu, false);
5758 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5759 * users of this state to go away such that all new such users will
5760 * observe it.
5762 * Do sync before park smpboot threads to take care the rcu boost case.
5764 synchronize_rcu_mult(call_rcu, call_rcu_sched);
5766 if (!sched_smp_initialized)
5767 return 0;
5769 ret = cpuset_cpu_inactive(cpu);
5770 if (ret) {
5771 set_cpu_active(cpu, true);
5772 return ret;
5774 sched_domains_numa_masks_clear(cpu);
5775 return 0;
5778 static void sched_rq_cpu_starting(unsigned int cpu)
5780 struct rq *rq = cpu_rq(cpu);
5782 rq->calc_load_update = calc_load_update;
5783 update_max_interval();
5786 int sched_cpu_starting(unsigned int cpu)
5788 set_cpu_rq_start_time(cpu);
5789 sched_rq_cpu_starting(cpu);
5790 return 0;
5793 #ifdef CONFIG_HOTPLUG_CPU
5794 int sched_cpu_dying(unsigned int cpu)
5796 struct rq *rq = cpu_rq(cpu);
5797 struct rq_flags rf;
5799 /* Handle pending wakeups and then migrate everything off */
5800 sched_ttwu_pending();
5802 rq_lock_irqsave(rq, &rf);
5803 if (rq->rd) {
5804 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5805 set_rq_offline(rq);
5807 migrate_tasks(rq, &rf);
5808 BUG_ON(rq->nr_running != 1);
5809 rq_unlock_irqrestore(rq, &rf);
5811 calc_load_migrate(rq);
5812 update_max_interval();
5813 nohz_balance_exit_idle(cpu);
5814 hrtick_clear(rq);
5815 return 0;
5817 #endif
5819 #ifdef CONFIG_SCHED_SMT
5820 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
5822 static void sched_init_smt(void)
5825 * We've enumerated all CPUs and will assume that if any CPU
5826 * has SMT siblings, CPU0 will too.
5828 if (cpumask_weight(cpu_smt_mask(0)) > 1)
5829 static_branch_enable(&sched_smt_present);
5831 #else
5832 static inline void sched_init_smt(void) { }
5833 #endif
5835 void __init sched_init_smp(void)
5837 sched_init_numa();
5840 * There's no userspace yet to cause hotplug operations; hence all the
5841 * CPU masks are stable and all blatant races in the below code cannot
5842 * happen.
5844 mutex_lock(&sched_domains_mutex);
5845 sched_init_domains(cpu_active_mask);
5846 mutex_unlock(&sched_domains_mutex);
5848 /* Move init over to a non-isolated CPU */
5849 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5850 BUG();
5851 sched_init_granularity();
5853 init_sched_rt_class();
5854 init_sched_dl_class();
5856 sched_init_smt();
5858 sched_smp_initialized = true;
5861 static int __init migration_init(void)
5863 sched_rq_cpu_starting(smp_processor_id());
5864 return 0;
5866 early_initcall(migration_init);
5868 #else
5869 void __init sched_init_smp(void)
5871 sched_init_granularity();
5873 #endif /* CONFIG_SMP */
5875 int in_sched_functions(unsigned long addr)
5877 return in_lock_functions(addr) ||
5878 (addr >= (unsigned long)__sched_text_start
5879 && addr < (unsigned long)__sched_text_end);
5882 #ifdef CONFIG_CGROUP_SCHED
5884 * Default task group.
5885 * Every task in system belongs to this group at bootup.
5887 struct task_group root_task_group;
5888 LIST_HEAD(task_groups);
5890 /* Cacheline aligned slab cache for task_group */
5891 static struct kmem_cache *task_group_cache __read_mostly;
5892 #endif
5894 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
5895 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
5897 void __init sched_init(void)
5899 int i, j;
5900 unsigned long alloc_size = 0, ptr;
5902 sched_clock_init();
5903 wait_bit_init();
5905 #ifdef CONFIG_FAIR_GROUP_SCHED
5906 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5907 #endif
5908 #ifdef CONFIG_RT_GROUP_SCHED
5909 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5910 #endif
5911 if (alloc_size) {
5912 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
5914 #ifdef CONFIG_FAIR_GROUP_SCHED
5915 root_task_group.se = (struct sched_entity **)ptr;
5916 ptr += nr_cpu_ids * sizeof(void **);
5918 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
5919 ptr += nr_cpu_ids * sizeof(void **);
5921 #endif /* CONFIG_FAIR_GROUP_SCHED */
5922 #ifdef CONFIG_RT_GROUP_SCHED
5923 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
5924 ptr += nr_cpu_ids * sizeof(void **);
5926 root_task_group.rt_rq = (struct rt_rq **)ptr;
5927 ptr += nr_cpu_ids * sizeof(void **);
5929 #endif /* CONFIG_RT_GROUP_SCHED */
5931 #ifdef CONFIG_CPUMASK_OFFSTACK
5932 for_each_possible_cpu(i) {
5933 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
5934 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5935 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
5936 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5938 #endif /* CONFIG_CPUMASK_OFFSTACK */
5940 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
5941 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
5943 #ifdef CONFIG_SMP
5944 init_defrootdomain();
5945 #endif
5947 #ifdef CONFIG_RT_GROUP_SCHED
5948 init_rt_bandwidth(&root_task_group.rt_bandwidth,
5949 global_rt_period(), global_rt_runtime());
5950 #endif /* CONFIG_RT_GROUP_SCHED */
5952 #ifdef CONFIG_CGROUP_SCHED
5953 task_group_cache = KMEM_CACHE(task_group, 0);
5955 list_add(&root_task_group.list, &task_groups);
5956 INIT_LIST_HEAD(&root_task_group.children);
5957 INIT_LIST_HEAD(&root_task_group.siblings);
5958 autogroup_init(&init_task);
5959 #endif /* CONFIG_CGROUP_SCHED */
5961 for_each_possible_cpu(i) {
5962 struct rq *rq;
5964 rq = cpu_rq(i);
5965 raw_spin_lock_init(&rq->lock);
5966 rq->nr_running = 0;
5967 rq->calc_load_active = 0;
5968 rq->calc_load_update = jiffies + LOAD_FREQ;
5969 init_cfs_rq(&rq->cfs);
5970 init_rt_rq(&rq->rt);
5971 init_dl_rq(&rq->dl);
5972 #ifdef CONFIG_FAIR_GROUP_SCHED
5973 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
5974 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
5975 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
5977 * How much CPU bandwidth does root_task_group get?
5979 * In case of task-groups formed thr' the cgroup filesystem, it
5980 * gets 100% of the CPU resources in the system. This overall
5981 * system CPU resource is divided among the tasks of
5982 * root_task_group and its child task-groups in a fair manner,
5983 * based on each entity's (task or task-group's) weight
5984 * (se->load.weight).
5986 * In other words, if root_task_group has 10 tasks of weight
5987 * 1024) and two child groups A0 and A1 (of weight 1024 each),
5988 * then A0's share of the CPU resource is:
5990 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
5992 * We achieve this by letting root_task_group's tasks sit
5993 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
5995 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
5996 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
5997 #endif /* CONFIG_FAIR_GROUP_SCHED */
5999 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
6000 #ifdef CONFIG_RT_GROUP_SCHED
6001 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
6002 #endif
6004 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6005 rq->cpu_load[j] = 0;
6007 #ifdef CONFIG_SMP
6008 rq->sd = NULL;
6009 rq->rd = NULL;
6010 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
6011 rq->balance_callback = NULL;
6012 rq->active_balance = 0;
6013 rq->next_balance = jiffies;
6014 rq->push_cpu = 0;
6015 rq->cpu = i;
6016 rq->online = 0;
6017 rq->idle_stamp = 0;
6018 rq->avg_idle = 2*sysctl_sched_migration_cost;
6019 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
6021 INIT_LIST_HEAD(&rq->cfs_tasks);
6023 rq_attach_root(rq, &def_root_domain);
6024 #ifdef CONFIG_NO_HZ_COMMON
6025 rq->last_load_update_tick = jiffies;
6026 rq->nohz_flags = 0;
6027 #endif
6028 #ifdef CONFIG_NO_HZ_FULL
6029 rq->last_sched_tick = 0;
6030 #endif
6031 #endif /* CONFIG_SMP */
6032 init_rq_hrtick(rq);
6033 atomic_set(&rq->nr_iowait, 0);
6036 set_load_weight(&init_task, false);
6039 * The boot idle thread does lazy MMU switching as well:
6041 mmgrab(&init_mm);
6042 enter_lazy_tlb(&init_mm, current);
6045 * Make us the idle thread. Technically, schedule() should not be
6046 * called from this thread, however somewhere below it might be,
6047 * but because we are the idle thread, we just pick up running again
6048 * when this runqueue becomes "idle".
6050 init_idle(current, smp_processor_id());
6052 calc_load_update = jiffies + LOAD_FREQ;
6054 #ifdef CONFIG_SMP
6055 idle_thread_set_boot_cpu();
6056 set_cpu_rq_start_time(smp_processor_id());
6057 #endif
6058 init_sched_fair_class();
6060 init_schedstats();
6062 scheduler_running = 1;
6065 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
6066 static inline int preempt_count_equals(int preempt_offset)
6068 int nested = preempt_count() + rcu_preempt_depth();
6070 return (nested == preempt_offset);
6073 void __might_sleep(const char *file, int line, int preempt_offset)
6076 * Blocking primitives will set (and therefore destroy) current->state,
6077 * since we will exit with TASK_RUNNING make sure we enter with it,
6078 * otherwise we will destroy state.
6080 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
6081 "do not call blocking ops when !TASK_RUNNING; "
6082 "state=%lx set at [<%p>] %pS\n",
6083 current->state,
6084 (void *)current->task_state_change,
6085 (void *)current->task_state_change);
6087 ___might_sleep(file, line, preempt_offset);
6089 EXPORT_SYMBOL(__might_sleep);
6091 void ___might_sleep(const char *file, int line, int preempt_offset)
6093 /* Ratelimiting timestamp: */
6094 static unsigned long prev_jiffy;
6096 unsigned long preempt_disable_ip;
6098 /* WARN_ON_ONCE() by default, no rate limit required: */
6099 rcu_sleep_check();
6101 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6102 !is_idle_task(current)) ||
6103 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
6104 oops_in_progress)
6105 return;
6107 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6108 return;
6109 prev_jiffy = jiffies;
6111 /* Save this before calling printk(), since that will clobber it: */
6112 preempt_disable_ip = get_preempt_disable_ip(current);
6114 printk(KERN_ERR
6115 "BUG: sleeping function called from invalid context at %s:%d\n",
6116 file, line);
6117 printk(KERN_ERR
6118 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6119 in_atomic(), irqs_disabled(),
6120 current->pid, current->comm);
6122 if (task_stack_end_corrupted(current))
6123 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6125 debug_show_held_locks(current);
6126 if (irqs_disabled())
6127 print_irqtrace_events(current);
6128 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6129 && !preempt_count_equals(preempt_offset)) {
6130 pr_err("Preemption disabled at:");
6131 print_ip_sym(preempt_disable_ip);
6132 pr_cont("\n");
6134 dump_stack();
6135 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6137 EXPORT_SYMBOL(___might_sleep);
6138 #endif
6140 #ifdef CONFIG_MAGIC_SYSRQ
6141 void normalize_rt_tasks(void)
6143 struct task_struct *g, *p;
6144 struct sched_attr attr = {
6145 .sched_policy = SCHED_NORMAL,
6148 read_lock(&tasklist_lock);
6149 for_each_process_thread(g, p) {
6151 * Only normalize user tasks:
6153 if (p->flags & PF_KTHREAD)
6154 continue;
6156 p->se.exec_start = 0;
6157 schedstat_set(p->se.statistics.wait_start, 0);
6158 schedstat_set(p->se.statistics.sleep_start, 0);
6159 schedstat_set(p->se.statistics.block_start, 0);
6161 if (!dl_task(p) && !rt_task(p)) {
6163 * Renice negative nice level userspace
6164 * tasks back to 0:
6166 if (task_nice(p) < 0)
6167 set_user_nice(p, 0);
6168 continue;
6171 __sched_setscheduler(p, &attr, false, false);
6173 read_unlock(&tasklist_lock);
6176 #endif /* CONFIG_MAGIC_SYSRQ */
6178 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
6180 * These functions are only useful for the IA64 MCA handling, or kdb.
6182 * They can only be called when the whole system has been
6183 * stopped - every CPU needs to be quiescent, and no scheduling
6184 * activity can take place. Using them for anything else would
6185 * be a serious bug, and as a result, they aren't even visible
6186 * under any other configuration.
6190 * curr_task - return the current task for a given CPU.
6191 * @cpu: the processor in question.
6193 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6195 * Return: The current task for @cpu.
6197 struct task_struct *curr_task(int cpu)
6199 return cpu_curr(cpu);
6202 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6204 #ifdef CONFIG_IA64
6206 * set_curr_task - set the current task for a given CPU.
6207 * @cpu: the processor in question.
6208 * @p: the task pointer to set.
6210 * Description: This function must only be used when non-maskable interrupts
6211 * are serviced on a separate stack. It allows the architecture to switch the
6212 * notion of the current task on a CPU in a non-blocking manner. This function
6213 * must be called with all CPU's synchronized, and interrupts disabled, the
6214 * and caller must save the original value of the current task (see
6215 * curr_task() above) and restore that value before reenabling interrupts and
6216 * re-starting the system.
6218 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6220 void ia64_set_curr_task(int cpu, struct task_struct *p)
6222 cpu_curr(cpu) = p;
6225 #endif
6227 #ifdef CONFIG_CGROUP_SCHED
6228 /* task_group_lock serializes the addition/removal of task groups */
6229 static DEFINE_SPINLOCK(task_group_lock);
6231 static void sched_free_group(struct task_group *tg)
6233 free_fair_sched_group(tg);
6234 free_rt_sched_group(tg);
6235 autogroup_free(tg);
6236 kmem_cache_free(task_group_cache, tg);
6239 /* allocate runqueue etc for a new task group */
6240 struct task_group *sched_create_group(struct task_group *parent)
6242 struct task_group *tg;
6244 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
6245 if (!tg)
6246 return ERR_PTR(-ENOMEM);
6248 if (!alloc_fair_sched_group(tg, parent))
6249 goto err;
6251 if (!alloc_rt_sched_group(tg, parent))
6252 goto err;
6254 return tg;
6256 err:
6257 sched_free_group(tg);
6258 return ERR_PTR(-ENOMEM);
6261 void sched_online_group(struct task_group *tg, struct task_group *parent)
6263 unsigned long flags;
6265 spin_lock_irqsave(&task_group_lock, flags);
6266 list_add_rcu(&tg->list, &task_groups);
6268 /* Root should already exist: */
6269 WARN_ON(!parent);
6271 tg->parent = parent;
6272 INIT_LIST_HEAD(&tg->children);
6273 list_add_rcu(&tg->siblings, &parent->children);
6274 spin_unlock_irqrestore(&task_group_lock, flags);
6276 online_fair_sched_group(tg);
6279 /* rcu callback to free various structures associated with a task group */
6280 static void sched_free_group_rcu(struct rcu_head *rhp)
6282 /* Now it should be safe to free those cfs_rqs: */
6283 sched_free_group(container_of(rhp, struct task_group, rcu));
6286 void sched_destroy_group(struct task_group *tg)
6288 /* Wait for possible concurrent references to cfs_rqs complete: */
6289 call_rcu(&tg->rcu, sched_free_group_rcu);
6292 void sched_offline_group(struct task_group *tg)
6294 unsigned long flags;
6296 /* End participation in shares distribution: */
6297 unregister_fair_sched_group(tg);
6299 spin_lock_irqsave(&task_group_lock, flags);
6300 list_del_rcu(&tg->list);
6301 list_del_rcu(&tg->siblings);
6302 spin_unlock_irqrestore(&task_group_lock, flags);
6305 static void sched_change_group(struct task_struct *tsk, int type)
6307 struct task_group *tg;
6310 * All callers are synchronized by task_rq_lock(); we do not use RCU
6311 * which is pointless here. Thus, we pass "true" to task_css_check()
6312 * to prevent lockdep warnings.
6314 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
6315 struct task_group, css);
6316 tg = autogroup_task_group(tsk, tg);
6317 tsk->sched_task_group = tg;
6319 #ifdef CONFIG_FAIR_GROUP_SCHED
6320 if (tsk->sched_class->task_change_group)
6321 tsk->sched_class->task_change_group(tsk, type);
6322 else
6323 #endif
6324 set_task_rq(tsk, task_cpu(tsk));
6328 * Change task's runqueue when it moves between groups.
6330 * The caller of this function should have put the task in its new group by
6331 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6332 * its new group.
6334 void sched_move_task(struct task_struct *tsk)
6336 int queued, running, queue_flags =
6337 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6338 struct rq_flags rf;
6339 struct rq *rq;
6341 rq = task_rq_lock(tsk, &rf);
6342 update_rq_clock(rq);
6344 running = task_current(rq, tsk);
6345 queued = task_on_rq_queued(tsk);
6347 if (queued)
6348 dequeue_task(rq, tsk, queue_flags);
6349 if (running)
6350 put_prev_task(rq, tsk);
6352 sched_change_group(tsk, TASK_MOVE_GROUP);
6354 if (queued)
6355 enqueue_task(rq, tsk, queue_flags);
6356 if (running)
6357 set_curr_task(rq, tsk);
6359 task_rq_unlock(rq, tsk, &rf);
6362 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
6364 return css ? container_of(css, struct task_group, css) : NULL;
6367 static struct cgroup_subsys_state *
6368 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6370 struct task_group *parent = css_tg(parent_css);
6371 struct task_group *tg;
6373 if (!parent) {
6374 /* This is early initialization for the top cgroup */
6375 return &root_task_group.css;
6378 tg = sched_create_group(parent);
6379 if (IS_ERR(tg))
6380 return ERR_PTR(-ENOMEM);
6382 return &tg->css;
6385 /* Expose task group only after completing cgroup initialization */
6386 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6388 struct task_group *tg = css_tg(css);
6389 struct task_group *parent = css_tg(css->parent);
6391 if (parent)
6392 sched_online_group(tg, parent);
6393 return 0;
6396 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
6398 struct task_group *tg = css_tg(css);
6400 sched_offline_group(tg);
6403 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
6405 struct task_group *tg = css_tg(css);
6408 * Relies on the RCU grace period between css_released() and this.
6410 sched_free_group(tg);
6414 * This is called before wake_up_new_task(), therefore we really only
6415 * have to set its group bits, all the other stuff does not apply.
6417 static void cpu_cgroup_fork(struct task_struct *task)
6419 struct rq_flags rf;
6420 struct rq *rq;
6422 rq = task_rq_lock(task, &rf);
6424 update_rq_clock(rq);
6425 sched_change_group(task, TASK_SET_GROUP);
6427 task_rq_unlock(rq, task, &rf);
6430 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
6432 struct task_struct *task;
6433 struct cgroup_subsys_state *css;
6434 int ret = 0;
6436 cgroup_taskset_for_each(task, css, tset) {
6437 #ifdef CONFIG_RT_GROUP_SCHED
6438 if (!sched_rt_can_attach(css_tg(css), task))
6439 return -EINVAL;
6440 #else
6441 /* We don't support RT-tasks being in separate groups */
6442 if (task->sched_class != &fair_sched_class)
6443 return -EINVAL;
6444 #endif
6446 * Serialize against wake_up_new_task() such that if its
6447 * running, we're sure to observe its full state.
6449 raw_spin_lock_irq(&task->pi_lock);
6451 * Avoid calling sched_move_task() before wake_up_new_task()
6452 * has happened. This would lead to problems with PELT, due to
6453 * move wanting to detach+attach while we're not attached yet.
6455 if (task->state == TASK_NEW)
6456 ret = -EINVAL;
6457 raw_spin_unlock_irq(&task->pi_lock);
6459 if (ret)
6460 break;
6462 return ret;
6465 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
6467 struct task_struct *task;
6468 struct cgroup_subsys_state *css;
6470 cgroup_taskset_for_each(task, css, tset)
6471 sched_move_task(task);
6474 #ifdef CONFIG_FAIR_GROUP_SCHED
6475 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6476 struct cftype *cftype, u64 shareval)
6478 return sched_group_set_shares(css_tg(css), scale_load(shareval));
6481 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6482 struct cftype *cft)
6484 struct task_group *tg = css_tg(css);
6486 return (u64) scale_load_down(tg->shares);
6489 #ifdef CONFIG_CFS_BANDWIDTH
6490 static DEFINE_MUTEX(cfs_constraints_mutex);
6492 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6493 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6495 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6497 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6499 int i, ret = 0, runtime_enabled, runtime_was_enabled;
6500 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6502 if (tg == &root_task_group)
6503 return -EINVAL;
6506 * Ensure we have at some amount of bandwidth every period. This is
6507 * to prevent reaching a state of large arrears when throttled via
6508 * entity_tick() resulting in prolonged exit starvation.
6510 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6511 return -EINVAL;
6514 * Likewise, bound things on the otherside by preventing insane quota
6515 * periods. This also allows us to normalize in computing quota
6516 * feasibility.
6518 if (period > max_cfs_quota_period)
6519 return -EINVAL;
6522 * Prevent race between setting of cfs_rq->runtime_enabled and
6523 * unthrottle_offline_cfs_rqs().
6525 get_online_cpus();
6526 mutex_lock(&cfs_constraints_mutex);
6527 ret = __cfs_schedulable(tg, period, quota);
6528 if (ret)
6529 goto out_unlock;
6531 runtime_enabled = quota != RUNTIME_INF;
6532 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
6534 * If we need to toggle cfs_bandwidth_used, off->on must occur
6535 * before making related changes, and on->off must occur afterwards
6537 if (runtime_enabled && !runtime_was_enabled)
6538 cfs_bandwidth_usage_inc();
6539 raw_spin_lock_irq(&cfs_b->lock);
6540 cfs_b->period = ns_to_ktime(period);
6541 cfs_b->quota = quota;
6543 __refill_cfs_bandwidth_runtime(cfs_b);
6545 /* Restart the period timer (if active) to handle new period expiry: */
6546 if (runtime_enabled)
6547 start_cfs_bandwidth(cfs_b);
6549 raw_spin_unlock_irq(&cfs_b->lock);
6551 for_each_online_cpu(i) {
6552 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
6553 struct rq *rq = cfs_rq->rq;
6554 struct rq_flags rf;
6556 rq_lock_irq(rq, &rf);
6557 cfs_rq->runtime_enabled = runtime_enabled;
6558 cfs_rq->runtime_remaining = 0;
6560 if (cfs_rq->throttled)
6561 unthrottle_cfs_rq(cfs_rq);
6562 rq_unlock_irq(rq, &rf);
6564 if (runtime_was_enabled && !runtime_enabled)
6565 cfs_bandwidth_usage_dec();
6566 out_unlock:
6567 mutex_unlock(&cfs_constraints_mutex);
6568 put_online_cpus();
6570 return ret;
6573 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
6575 u64 quota, period;
6577 period = ktime_to_ns(tg->cfs_bandwidth.period);
6578 if (cfs_quota_us < 0)
6579 quota = RUNTIME_INF;
6580 else
6581 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
6583 return tg_set_cfs_bandwidth(tg, period, quota);
6586 long tg_get_cfs_quota(struct task_group *tg)
6588 u64 quota_us;
6590 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
6591 return -1;
6593 quota_us = tg->cfs_bandwidth.quota;
6594 do_div(quota_us, NSEC_PER_USEC);
6596 return quota_us;
6599 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
6601 u64 quota, period;
6603 period = (u64)cfs_period_us * NSEC_PER_USEC;
6604 quota = tg->cfs_bandwidth.quota;
6606 return tg_set_cfs_bandwidth(tg, period, quota);
6609 long tg_get_cfs_period(struct task_group *tg)
6611 u64 cfs_period_us;
6613 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
6614 do_div(cfs_period_us, NSEC_PER_USEC);
6616 return cfs_period_us;
6619 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
6620 struct cftype *cft)
6622 return tg_get_cfs_quota(css_tg(css));
6625 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
6626 struct cftype *cftype, s64 cfs_quota_us)
6628 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
6631 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
6632 struct cftype *cft)
6634 return tg_get_cfs_period(css_tg(css));
6637 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
6638 struct cftype *cftype, u64 cfs_period_us)
6640 return tg_set_cfs_period(css_tg(css), cfs_period_us);
6643 struct cfs_schedulable_data {
6644 struct task_group *tg;
6645 u64 period, quota;
6649 * normalize group quota/period to be quota/max_period
6650 * note: units are usecs
6652 static u64 normalize_cfs_quota(struct task_group *tg,
6653 struct cfs_schedulable_data *d)
6655 u64 quota, period;
6657 if (tg == d->tg) {
6658 period = d->period;
6659 quota = d->quota;
6660 } else {
6661 period = tg_get_cfs_period(tg);
6662 quota = tg_get_cfs_quota(tg);
6665 /* note: these should typically be equivalent */
6666 if (quota == RUNTIME_INF || quota == -1)
6667 return RUNTIME_INF;
6669 return to_ratio(period, quota);
6672 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
6674 struct cfs_schedulable_data *d = data;
6675 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6676 s64 quota = 0, parent_quota = -1;
6678 if (!tg->parent) {
6679 quota = RUNTIME_INF;
6680 } else {
6681 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
6683 quota = normalize_cfs_quota(tg, d);
6684 parent_quota = parent_b->hierarchical_quota;
6687 * Ensure max(child_quota) <= parent_quota. On cgroup2,
6688 * always take the min. On cgroup1, only inherit when no
6689 * limit is set:
6691 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
6692 quota = min(quota, parent_quota);
6693 } else {
6694 if (quota == RUNTIME_INF)
6695 quota = parent_quota;
6696 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
6697 return -EINVAL;
6700 cfs_b->hierarchical_quota = quota;
6702 return 0;
6705 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
6707 int ret;
6708 struct cfs_schedulable_data data = {
6709 .tg = tg,
6710 .period = period,
6711 .quota = quota,
6714 if (quota != RUNTIME_INF) {
6715 do_div(data.period, NSEC_PER_USEC);
6716 do_div(data.quota, NSEC_PER_USEC);
6719 rcu_read_lock();
6720 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
6721 rcu_read_unlock();
6723 return ret;
6726 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
6728 struct task_group *tg = css_tg(seq_css(sf));
6729 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6731 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
6732 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
6733 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
6735 return 0;
6737 #endif /* CONFIG_CFS_BANDWIDTH */
6738 #endif /* CONFIG_FAIR_GROUP_SCHED */
6740 #ifdef CONFIG_RT_GROUP_SCHED
6741 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
6742 struct cftype *cft, s64 val)
6744 return sched_group_set_rt_runtime(css_tg(css), val);
6747 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
6748 struct cftype *cft)
6750 return sched_group_rt_runtime(css_tg(css));
6753 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
6754 struct cftype *cftype, u64 rt_period_us)
6756 return sched_group_set_rt_period(css_tg(css), rt_period_us);
6759 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
6760 struct cftype *cft)
6762 return sched_group_rt_period(css_tg(css));
6764 #endif /* CONFIG_RT_GROUP_SCHED */
6766 static struct cftype cpu_legacy_files[] = {
6767 #ifdef CONFIG_FAIR_GROUP_SCHED
6769 .name = "shares",
6770 .read_u64 = cpu_shares_read_u64,
6771 .write_u64 = cpu_shares_write_u64,
6773 #endif
6774 #ifdef CONFIG_CFS_BANDWIDTH
6776 .name = "cfs_quota_us",
6777 .read_s64 = cpu_cfs_quota_read_s64,
6778 .write_s64 = cpu_cfs_quota_write_s64,
6781 .name = "cfs_period_us",
6782 .read_u64 = cpu_cfs_period_read_u64,
6783 .write_u64 = cpu_cfs_period_write_u64,
6786 .name = "stat",
6787 .seq_show = cpu_cfs_stat_show,
6789 #endif
6790 #ifdef CONFIG_RT_GROUP_SCHED
6792 .name = "rt_runtime_us",
6793 .read_s64 = cpu_rt_runtime_read,
6794 .write_s64 = cpu_rt_runtime_write,
6797 .name = "rt_period_us",
6798 .read_u64 = cpu_rt_period_read_uint,
6799 .write_u64 = cpu_rt_period_write_uint,
6801 #endif
6802 { } /* Terminate */
6805 static int cpu_extra_stat_show(struct seq_file *sf,
6806 struct cgroup_subsys_state *css)
6808 #ifdef CONFIG_CFS_BANDWIDTH
6810 struct task_group *tg = css_tg(css);
6811 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6812 u64 throttled_usec;
6814 throttled_usec = cfs_b->throttled_time;
6815 do_div(throttled_usec, NSEC_PER_USEC);
6817 seq_printf(sf, "nr_periods %d\n"
6818 "nr_throttled %d\n"
6819 "throttled_usec %llu\n",
6820 cfs_b->nr_periods, cfs_b->nr_throttled,
6821 throttled_usec);
6823 #endif
6824 return 0;
6827 #ifdef CONFIG_FAIR_GROUP_SCHED
6828 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
6829 struct cftype *cft)
6831 struct task_group *tg = css_tg(css);
6832 u64 weight = scale_load_down(tg->shares);
6834 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
6837 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
6838 struct cftype *cft, u64 weight)
6841 * cgroup weight knobs should use the common MIN, DFL and MAX
6842 * values which are 1, 100 and 10000 respectively. While it loses
6843 * a bit of range on both ends, it maps pretty well onto the shares
6844 * value used by scheduler and the round-trip conversions preserve
6845 * the original value over the entire range.
6847 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
6848 return -ERANGE;
6850 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
6852 return sched_group_set_shares(css_tg(css), scale_load(weight));
6855 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
6856 struct cftype *cft)
6858 unsigned long weight = scale_load_down(css_tg(css)->shares);
6859 int last_delta = INT_MAX;
6860 int prio, delta;
6862 /* find the closest nice value to the current weight */
6863 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
6864 delta = abs(sched_prio_to_weight[prio] - weight);
6865 if (delta >= last_delta)
6866 break;
6867 last_delta = delta;
6870 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
6873 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
6874 struct cftype *cft, s64 nice)
6876 unsigned long weight;
6877 int idx;
6879 if (nice < MIN_NICE || nice > MAX_NICE)
6880 return -ERANGE;
6882 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
6883 idx = array_index_nospec(idx, 40);
6884 weight = sched_prio_to_weight[idx];
6886 return sched_group_set_shares(css_tg(css), scale_load(weight));
6888 #endif
6890 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
6891 long period, long quota)
6893 if (quota < 0)
6894 seq_puts(sf, "max");
6895 else
6896 seq_printf(sf, "%ld", quota);
6898 seq_printf(sf, " %ld\n", period);
6901 /* caller should put the current value in *@periodp before calling */
6902 static int __maybe_unused cpu_period_quota_parse(char *buf,
6903 u64 *periodp, u64 *quotap)
6905 char tok[21]; /* U64_MAX */
6907 if (!sscanf(buf, "%s %llu", tok, periodp))
6908 return -EINVAL;
6910 *periodp *= NSEC_PER_USEC;
6912 if (sscanf(tok, "%llu", quotap))
6913 *quotap *= NSEC_PER_USEC;
6914 else if (!strcmp(tok, "max"))
6915 *quotap = RUNTIME_INF;
6916 else
6917 return -EINVAL;
6919 return 0;
6922 #ifdef CONFIG_CFS_BANDWIDTH
6923 static int cpu_max_show(struct seq_file *sf, void *v)
6925 struct task_group *tg = css_tg(seq_css(sf));
6927 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
6928 return 0;
6931 static ssize_t cpu_max_write(struct kernfs_open_file *of,
6932 char *buf, size_t nbytes, loff_t off)
6934 struct task_group *tg = css_tg(of_css(of));
6935 u64 period = tg_get_cfs_period(tg);
6936 u64 quota;
6937 int ret;
6939 ret = cpu_period_quota_parse(buf, &period, &quota);
6940 if (!ret)
6941 ret = tg_set_cfs_bandwidth(tg, period, quota);
6942 return ret ?: nbytes;
6944 #endif
6946 static struct cftype cpu_files[] = {
6947 #ifdef CONFIG_FAIR_GROUP_SCHED
6949 .name = "weight",
6950 .flags = CFTYPE_NOT_ON_ROOT,
6951 .read_u64 = cpu_weight_read_u64,
6952 .write_u64 = cpu_weight_write_u64,
6955 .name = "weight.nice",
6956 .flags = CFTYPE_NOT_ON_ROOT,
6957 .read_s64 = cpu_weight_nice_read_s64,
6958 .write_s64 = cpu_weight_nice_write_s64,
6960 #endif
6961 #ifdef CONFIG_CFS_BANDWIDTH
6963 .name = "max",
6964 .flags = CFTYPE_NOT_ON_ROOT,
6965 .seq_show = cpu_max_show,
6966 .write = cpu_max_write,
6968 #endif
6969 { } /* terminate */
6972 struct cgroup_subsys cpu_cgrp_subsys = {
6973 .css_alloc = cpu_cgroup_css_alloc,
6974 .css_online = cpu_cgroup_css_online,
6975 .css_released = cpu_cgroup_css_released,
6976 .css_free = cpu_cgroup_css_free,
6977 .css_extra_stat_show = cpu_extra_stat_show,
6978 .fork = cpu_cgroup_fork,
6979 .can_attach = cpu_cgroup_can_attach,
6980 .attach = cpu_cgroup_attach,
6981 .legacy_cftypes = cpu_legacy_files,
6982 .dfl_cftypes = cpu_files,
6983 .early_init = true,
6984 .threaded = true,
6987 #endif /* CONFIG_CGROUP_SCHED */
6989 void dump_cpu_task(int cpu)
6991 pr_info("Task dump for CPU %d:\n", cpu);
6992 sched_show_task(cpu_curr(cpu));
6996 * Nice levels are multiplicative, with a gentle 10% change for every
6997 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
6998 * nice 1, it will get ~10% less CPU time than another CPU-bound task
6999 * that remained on nice 0.
7001 * The "10% effect" is relative and cumulative: from _any_ nice level,
7002 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
7003 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
7004 * If a task goes up by ~10% and another task goes down by ~10% then
7005 * the relative distance between them is ~25%.)
7007 const int sched_prio_to_weight[40] = {
7008 /* -20 */ 88761, 71755, 56483, 46273, 36291,
7009 /* -15 */ 29154, 23254, 18705, 14949, 11916,
7010 /* -10 */ 9548, 7620, 6100, 4904, 3906,
7011 /* -5 */ 3121, 2501, 1991, 1586, 1277,
7012 /* 0 */ 1024, 820, 655, 526, 423,
7013 /* 5 */ 335, 272, 215, 172, 137,
7014 /* 10 */ 110, 87, 70, 56, 45,
7015 /* 15 */ 36, 29, 23, 18, 15,
7019 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
7021 * In cases where the weight does not change often, we can use the
7022 * precalculated inverse to speed up arithmetics by turning divisions
7023 * into multiplications:
7025 const u32 sched_prio_to_wmult[40] = {
7026 /* -20 */ 48388, 59856, 76040, 92818, 118348,
7027 /* -15 */ 147320, 184698, 229616, 287308, 360437,
7028 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
7029 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
7030 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
7031 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
7032 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
7033 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,