4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
29 #include <linux/kasan.h>
31 #include <linux/module.h>
32 #include <linux/nmi.h>
33 #include <linux/init.h>
34 #include <linux/uaccess.h>
35 #include <linux/highmem.h>
36 #include <linux/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/perf_event.h>
43 #include <linux/security.h>
44 #include <linux/notifier.h>
45 #include <linux/profile.h>
46 #include <linux/freezer.h>
47 #include <linux/vmalloc.h>
48 #include <linux/blkdev.h>
49 #include <linux/delay.h>
50 #include <linux/pid_namespace.h>
51 #include <linux/smp.h>
52 #include <linux/threads.h>
53 #include <linux/timer.h>
54 #include <linux/rcupdate.h>
55 #include <linux/cpu.h>
56 #include <linux/cpuset.h>
57 #include <linux/percpu.h>
58 #include <linux/proc_fs.h>
59 #include <linux/seq_file.h>
60 #include <linux/sysctl.h>
61 #include <linux/syscalls.h>
62 #include <linux/times.h>
63 #include <linux/tsacct_kern.h>
64 #include <linux/kprobes.h>
65 #include <linux/delayacct.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/ctype.h>
71 #include <linux/ftrace.h>
72 #include <linux/slab.h>
73 #include <linux/init_task.h>
74 #include <linux/context_tracking.h>
75 #include <linux/compiler.h>
76 #include <linux/frame.h>
77 #include <linux/prefetch.h>
78 #include <linux/mutex.h>
80 #include <asm/switch_to.h>
82 #include <asm/irq_regs.h>
83 #ifdef CONFIG_PARAVIRT
84 #include <asm/paravirt.h>
88 #include "../workqueue_internal.h"
89 #include "../smpboot.h"
91 #define CREATE_TRACE_POINTS
92 #include <trace/events/sched.h>
94 DEFINE_MUTEX(sched_domains_mutex);
95 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
97 static void update_rq_clock_task(struct rq *rq, s64 delta);
99 void update_rq_clock(struct rq *rq)
103 lockdep_assert_held(&rq->lock);
105 if (rq->clock_update_flags & RQCF_ACT_SKIP)
108 #ifdef CONFIG_SCHED_DEBUG
109 rq->clock_update_flags |= RQCF_UPDATED;
111 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
115 update_rq_clock_task(rq, delta);
119 * Debugging: various feature bits
122 #define SCHED_FEAT(name, enabled) \
123 (1UL << __SCHED_FEAT_##name) * enabled |
125 const_debug unsigned int sysctl_sched_features =
126 #include "features.h"
132 * Number of tasks to iterate in a single balance run.
133 * Limited because this is done with IRQs disabled.
135 const_debug unsigned int sysctl_sched_nr_migrate = 32;
138 * period over which we average the RT time consumption, measured
143 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
146 * period over which we measure -rt task cpu usage in us.
149 unsigned int sysctl_sched_rt_period = 1000000;
151 __read_mostly int scheduler_running;
154 * part of the period that we allow rt tasks to run in us.
157 int sysctl_sched_rt_runtime = 950000;
159 /* cpus with isolated domains */
160 cpumask_var_t cpu_isolated_map;
163 * this_rq_lock - lock this runqueue and disable interrupts.
165 static struct rq *this_rq_lock(void)
172 raw_spin_lock(&rq->lock);
178 * __task_rq_lock - lock the rq @p resides on.
180 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
185 lockdep_assert_held(&p->pi_lock);
189 raw_spin_lock(&rq->lock);
190 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
194 raw_spin_unlock(&rq->lock);
196 while (unlikely(task_on_rq_migrating(p)))
202 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
204 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
205 __acquires(p->pi_lock)
211 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
213 raw_spin_lock(&rq->lock);
215 * move_queued_task() task_rq_lock()
218 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
219 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
220 * [S] ->cpu = new_cpu [L] task_rq()
224 * If we observe the old cpu in task_rq_lock, the acquire of
225 * the old rq->lock will fully serialize against the stores.
227 * If we observe the new cpu in task_rq_lock, the acquire will
228 * pair with the WMB to ensure we must then also see migrating.
230 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
234 raw_spin_unlock(&rq->lock);
235 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
237 while (unlikely(task_on_rq_migrating(p)))
242 #ifdef CONFIG_SCHED_HRTICK
244 * Use HR-timers to deliver accurate preemption points.
247 static void hrtick_clear(struct rq *rq)
249 if (hrtimer_active(&rq->hrtick_timer))
250 hrtimer_cancel(&rq->hrtick_timer);
254 * High-resolution timer tick.
255 * Runs from hardirq context with interrupts disabled.
257 static enum hrtimer_restart hrtick(struct hrtimer *timer)
259 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
261 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
263 raw_spin_lock(&rq->lock);
265 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
266 raw_spin_unlock(&rq->lock);
268 return HRTIMER_NORESTART;
273 static void __hrtick_restart(struct rq *rq)
275 struct hrtimer *timer = &rq->hrtick_timer;
277 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
281 * called from hardirq (IPI) context
283 static void __hrtick_start(void *arg)
287 raw_spin_lock(&rq->lock);
288 __hrtick_restart(rq);
289 rq->hrtick_csd_pending = 0;
290 raw_spin_unlock(&rq->lock);
294 * Called to set the hrtick timer state.
296 * called with rq->lock held and irqs disabled
298 void hrtick_start(struct rq *rq, u64 delay)
300 struct hrtimer *timer = &rq->hrtick_timer;
305 * Don't schedule slices shorter than 10000ns, that just
306 * doesn't make sense and can cause timer DoS.
308 delta = max_t(s64, delay, 10000LL);
309 time = ktime_add_ns(timer->base->get_time(), delta);
311 hrtimer_set_expires(timer, time);
313 if (rq == this_rq()) {
314 __hrtick_restart(rq);
315 } else if (!rq->hrtick_csd_pending) {
316 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
317 rq->hrtick_csd_pending = 1;
323 * Called to set the hrtick timer state.
325 * called with rq->lock held and irqs disabled
327 void hrtick_start(struct rq *rq, u64 delay)
330 * Don't schedule slices shorter than 10000ns, that just
331 * doesn't make sense. Rely on vruntime for fairness.
333 delay = max_t(u64, delay, 10000LL);
334 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
335 HRTIMER_MODE_REL_PINNED);
337 #endif /* CONFIG_SMP */
339 static void init_rq_hrtick(struct rq *rq)
342 rq->hrtick_csd_pending = 0;
344 rq->hrtick_csd.flags = 0;
345 rq->hrtick_csd.func = __hrtick_start;
346 rq->hrtick_csd.info = rq;
349 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
350 rq->hrtick_timer.function = hrtick;
352 #else /* CONFIG_SCHED_HRTICK */
353 static inline void hrtick_clear(struct rq *rq)
357 static inline void init_rq_hrtick(struct rq *rq)
360 #endif /* CONFIG_SCHED_HRTICK */
363 * cmpxchg based fetch_or, macro so it works for different integer types
365 #define fetch_or(ptr, mask) \
367 typeof(ptr) _ptr = (ptr); \
368 typeof(mask) _mask = (mask); \
369 typeof(*_ptr) _old, _val = *_ptr; \
372 _old = cmpxchg(_ptr, _val, _val | _mask); \
380 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
382 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
383 * this avoids any races wrt polling state changes and thereby avoids
386 static bool set_nr_and_not_polling(struct task_struct *p)
388 struct thread_info *ti = task_thread_info(p);
389 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
393 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
395 * If this returns true, then the idle task promises to call
396 * sched_ttwu_pending() and reschedule soon.
398 static bool set_nr_if_polling(struct task_struct *p)
400 struct thread_info *ti = task_thread_info(p);
401 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
404 if (!(val & _TIF_POLLING_NRFLAG))
406 if (val & _TIF_NEED_RESCHED)
408 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
417 static bool set_nr_and_not_polling(struct task_struct *p)
419 set_tsk_need_resched(p);
424 static bool set_nr_if_polling(struct task_struct *p)
431 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
433 struct wake_q_node *node = &task->wake_q;
436 * Atomically grab the task, if ->wake_q is !nil already it means
437 * its already queued (either by us or someone else) and will get the
438 * wakeup due to that.
440 * This cmpxchg() implies a full barrier, which pairs with the write
441 * barrier implied by the wakeup in wake_up_q().
443 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
446 get_task_struct(task);
449 * The head is context local, there can be no concurrency.
452 head->lastp = &node->next;
455 void wake_up_q(struct wake_q_head *head)
457 struct wake_q_node *node = head->first;
459 while (node != WAKE_Q_TAIL) {
460 struct task_struct *task;
462 task = container_of(node, struct task_struct, wake_q);
464 /* task can safely be re-inserted now */
466 task->wake_q.next = NULL;
469 * wake_up_process() implies a wmb() to pair with the queueing
470 * in wake_q_add() so as not to miss wakeups.
472 wake_up_process(task);
473 put_task_struct(task);
478 * resched_curr - mark rq's current task 'to be rescheduled now'.
480 * On UP this means the setting of the need_resched flag, on SMP it
481 * might also involve a cross-CPU call to trigger the scheduler on
484 void resched_curr(struct rq *rq)
486 struct task_struct *curr = rq->curr;
489 lockdep_assert_held(&rq->lock);
491 if (test_tsk_need_resched(curr))
496 if (cpu == smp_processor_id()) {
497 set_tsk_need_resched(curr);
498 set_preempt_need_resched();
502 if (set_nr_and_not_polling(curr))
503 smp_send_reschedule(cpu);
505 trace_sched_wake_idle_without_ipi(cpu);
508 void resched_cpu(int cpu)
510 struct rq *rq = cpu_rq(cpu);
513 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
516 raw_spin_unlock_irqrestore(&rq->lock, flags);
520 #ifdef CONFIG_NO_HZ_COMMON
522 * In the semi idle case, use the nearest busy cpu for migrating timers
523 * from an idle cpu. This is good for power-savings.
525 * We don't do similar optimization for completely idle system, as
526 * selecting an idle cpu will add more delays to the timers than intended
527 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
529 int get_nohz_timer_target(void)
531 int i, cpu = smp_processor_id();
532 struct sched_domain *sd;
534 if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
538 for_each_domain(cpu, sd) {
539 for_each_cpu(i, sched_domain_span(sd)) {
543 if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
550 if (!is_housekeeping_cpu(cpu))
551 cpu = housekeeping_any_cpu();
557 * When add_timer_on() enqueues a timer into the timer wheel of an
558 * idle CPU then this timer might expire before the next timer event
559 * which is scheduled to wake up that CPU. In case of a completely
560 * idle system the next event might even be infinite time into the
561 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
562 * leaves the inner idle loop so the newly added timer is taken into
563 * account when the CPU goes back to idle and evaluates the timer
564 * wheel for the next timer event.
566 static void wake_up_idle_cpu(int cpu)
568 struct rq *rq = cpu_rq(cpu);
570 if (cpu == smp_processor_id())
573 if (set_nr_and_not_polling(rq->idle))
574 smp_send_reschedule(cpu);
576 trace_sched_wake_idle_without_ipi(cpu);
579 static bool wake_up_full_nohz_cpu(int cpu)
582 * We just need the target to call irq_exit() and re-evaluate
583 * the next tick. The nohz full kick at least implies that.
584 * If needed we can still optimize that later with an
587 if (cpu_is_offline(cpu))
588 return true; /* Don't try to wake offline CPUs. */
589 if (tick_nohz_full_cpu(cpu)) {
590 if (cpu != smp_processor_id() ||
591 tick_nohz_tick_stopped())
592 tick_nohz_full_kick_cpu(cpu);
600 * Wake up the specified CPU. If the CPU is going offline, it is the
601 * caller's responsibility to deal with the lost wakeup, for example,
602 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
604 void wake_up_nohz_cpu(int cpu)
606 if (!wake_up_full_nohz_cpu(cpu))
607 wake_up_idle_cpu(cpu);
610 static inline bool got_nohz_idle_kick(void)
612 int cpu = smp_processor_id();
614 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
617 if (idle_cpu(cpu) && !need_resched())
621 * We can't run Idle Load Balance on this CPU for this time so we
622 * cancel it and clear NOHZ_BALANCE_KICK
624 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
628 #else /* CONFIG_NO_HZ_COMMON */
630 static inline bool got_nohz_idle_kick(void)
635 #endif /* CONFIG_NO_HZ_COMMON */
637 #ifdef CONFIG_NO_HZ_FULL
638 bool sched_can_stop_tick(struct rq *rq)
642 /* Deadline tasks, even if single, need the tick */
643 if (rq->dl.dl_nr_running)
647 * If there are more than one RR tasks, we need the tick to effect the
648 * actual RR behaviour.
650 if (rq->rt.rr_nr_running) {
651 if (rq->rt.rr_nr_running == 1)
658 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
659 * forced preemption between FIFO tasks.
661 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
666 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
667 * if there's more than one we need the tick for involuntary
670 if (rq->nr_running > 1)
675 #endif /* CONFIG_NO_HZ_FULL */
677 void sched_avg_update(struct rq *rq)
679 s64 period = sched_avg_period();
681 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
683 * Inline assembly required to prevent the compiler
684 * optimising this loop into a divmod call.
685 * See __iter_div_u64_rem() for another example of this.
687 asm("" : "+rm" (rq->age_stamp));
688 rq->age_stamp += period;
693 #endif /* CONFIG_SMP */
695 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
696 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
698 * Iterate task_group tree rooted at *from, calling @down when first entering a
699 * node and @up when leaving it for the final time.
701 * Caller must hold rcu_lock or sufficient equivalent.
703 int walk_tg_tree_from(struct task_group *from,
704 tg_visitor down, tg_visitor up, void *data)
706 struct task_group *parent, *child;
712 ret = (*down)(parent, data);
715 list_for_each_entry_rcu(child, &parent->children, siblings) {
722 ret = (*up)(parent, data);
723 if (ret || parent == from)
727 parent = parent->parent;
734 int tg_nop(struct task_group *tg, void *data)
740 static void set_load_weight(struct task_struct *p)
742 int prio = p->static_prio - MAX_RT_PRIO;
743 struct load_weight *load = &p->se.load;
746 * SCHED_IDLE tasks get minimal weight:
748 if (idle_policy(p->policy)) {
749 load->weight = scale_load(WEIGHT_IDLEPRIO);
750 load->inv_weight = WMULT_IDLEPRIO;
754 load->weight = scale_load(sched_prio_to_weight[prio]);
755 load->inv_weight = sched_prio_to_wmult[prio];
758 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
761 if (!(flags & ENQUEUE_RESTORE))
762 sched_info_queued(rq, p);
763 p->sched_class->enqueue_task(rq, p, flags);
766 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
769 if (!(flags & DEQUEUE_SAVE))
770 sched_info_dequeued(rq, p);
771 p->sched_class->dequeue_task(rq, p, flags);
774 void activate_task(struct rq *rq, struct task_struct *p, int flags)
776 if (task_contributes_to_load(p))
777 rq->nr_uninterruptible--;
779 enqueue_task(rq, p, flags);
782 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
784 if (task_contributes_to_load(p))
785 rq->nr_uninterruptible++;
787 dequeue_task(rq, p, flags);
790 static void update_rq_clock_task(struct rq *rq, s64 delta)
793 * In theory, the compile should just see 0 here, and optimize out the call
794 * to sched_rt_avg_update. But I don't trust it...
796 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
797 s64 steal = 0, irq_delta = 0;
799 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
800 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
803 * Since irq_time is only updated on {soft,}irq_exit, we might run into
804 * this case when a previous update_rq_clock() happened inside a
807 * When this happens, we stop ->clock_task and only update the
808 * prev_irq_time stamp to account for the part that fit, so that a next
809 * update will consume the rest. This ensures ->clock_task is
812 * It does however cause some slight miss-attribution of {soft,}irq
813 * time, a more accurate solution would be to update the irq_time using
814 * the current rq->clock timestamp, except that would require using
817 if (irq_delta > delta)
820 rq->prev_irq_time += irq_delta;
823 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
824 if (static_key_false((¶virt_steal_rq_enabled))) {
825 steal = paravirt_steal_clock(cpu_of(rq));
826 steal -= rq->prev_steal_time_rq;
828 if (unlikely(steal > delta))
831 rq->prev_steal_time_rq += steal;
836 rq->clock_task += delta;
838 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
839 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
840 sched_rt_avg_update(rq, irq_delta + steal);
844 void sched_set_stop_task(int cpu, struct task_struct *stop)
846 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
847 struct task_struct *old_stop = cpu_rq(cpu)->stop;
851 * Make it appear like a SCHED_FIFO task, its something
852 * userspace knows about and won't get confused about.
854 * Also, it will make PI more or less work without too
855 * much confusion -- but then, stop work should not
856 * rely on PI working anyway.
858 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
860 stop->sched_class = &stop_sched_class;
863 cpu_rq(cpu)->stop = stop;
867 * Reset it back to a normal scheduling class so that
868 * it can die in pieces.
870 old_stop->sched_class = &rt_sched_class;
875 * __normal_prio - return the priority that is based on the static prio
877 static inline int __normal_prio(struct task_struct *p)
879 return p->static_prio;
883 * Calculate the expected normal priority: i.e. priority
884 * without taking RT-inheritance into account. Might be
885 * boosted by interactivity modifiers. Changes upon fork,
886 * setprio syscalls, and whenever the interactivity
887 * estimator recalculates.
889 static inline int normal_prio(struct task_struct *p)
893 if (task_has_dl_policy(p))
894 prio = MAX_DL_PRIO-1;
895 else if (task_has_rt_policy(p))
896 prio = MAX_RT_PRIO-1 - p->rt_priority;
898 prio = __normal_prio(p);
903 * Calculate the current priority, i.e. the priority
904 * taken into account by the scheduler. This value might
905 * be boosted by RT tasks, or might be boosted by
906 * interactivity modifiers. Will be RT if the task got
907 * RT-boosted. If not then it returns p->normal_prio.
909 static int effective_prio(struct task_struct *p)
911 p->normal_prio = normal_prio(p);
913 * If we are RT tasks or we were boosted to RT priority,
914 * keep the priority unchanged. Otherwise, update priority
915 * to the normal priority:
917 if (!rt_prio(p->prio))
918 return p->normal_prio;
923 * task_curr - is this task currently executing on a CPU?
924 * @p: the task in question.
926 * Return: 1 if the task is currently executing. 0 otherwise.
928 inline int task_curr(const struct task_struct *p)
930 return cpu_curr(task_cpu(p)) == p;
934 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
935 * use the balance_callback list if you want balancing.
937 * this means any call to check_class_changed() must be followed by a call to
938 * balance_callback().
940 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
941 const struct sched_class *prev_class,
944 if (prev_class != p->sched_class) {
945 if (prev_class->switched_from)
946 prev_class->switched_from(rq, p);
948 p->sched_class->switched_to(rq, p);
949 } else if (oldprio != p->prio || dl_task(p))
950 p->sched_class->prio_changed(rq, p, oldprio);
953 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
955 const struct sched_class *class;
957 if (p->sched_class == rq->curr->sched_class) {
958 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
960 for_each_class(class) {
961 if (class == rq->curr->sched_class)
963 if (class == p->sched_class) {
971 * A queue event has occurred, and we're going to schedule. In
972 * this case, we can save a useless back to back clock update.
974 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
975 rq_clock_skip_update(rq, true);
980 * This is how migration works:
982 * 1) we invoke migration_cpu_stop() on the target CPU using
984 * 2) stopper starts to run (implicitly forcing the migrated thread
986 * 3) it checks whether the migrated task is still in the wrong runqueue.
987 * 4) if it's in the wrong runqueue then the migration thread removes
988 * it and puts it into the right queue.
989 * 5) stopper completes and stop_one_cpu() returns and the migration
994 * move_queued_task - move a queued task to new rq.
996 * Returns (locked) new rq. Old rq's lock is released.
998 static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
1000 lockdep_assert_held(&rq->lock);
1002 p->on_rq = TASK_ON_RQ_MIGRATING;
1003 dequeue_task(rq, p, 0);
1004 set_task_cpu(p, new_cpu);
1005 raw_spin_unlock(&rq->lock);
1007 rq = cpu_rq(new_cpu);
1009 raw_spin_lock(&rq->lock);
1010 BUG_ON(task_cpu(p) != new_cpu);
1011 enqueue_task(rq, p, 0);
1012 p->on_rq = TASK_ON_RQ_QUEUED;
1013 check_preempt_curr(rq, p, 0);
1018 struct migration_arg {
1019 struct task_struct *task;
1024 * Move (not current) task off this cpu, onto dest cpu. We're doing
1025 * this because either it can't run here any more (set_cpus_allowed()
1026 * away from this CPU, or CPU going down), or because we're
1027 * attempting to rebalance this task on exec (sched_exec).
1029 * So we race with normal scheduler movements, but that's OK, as long
1030 * as the task is no longer on this CPU.
1032 static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
1034 if (unlikely(!cpu_active(dest_cpu)))
1037 /* Affinity changed (again). */
1038 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1041 rq = move_queued_task(rq, p, dest_cpu);
1047 * migration_cpu_stop - this will be executed by a highprio stopper thread
1048 * and performs thread migration by bumping thread off CPU then
1049 * 'pushing' onto another runqueue.
1051 static int migration_cpu_stop(void *data)
1053 struct migration_arg *arg = data;
1054 struct task_struct *p = arg->task;
1055 struct rq *rq = this_rq();
1058 * The original target cpu might have gone down and we might
1059 * be on another cpu but it doesn't matter.
1061 local_irq_disable();
1063 * We need to explicitly wake pending tasks before running
1064 * __migrate_task() such that we will not miss enforcing cpus_allowed
1065 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1067 sched_ttwu_pending();
1069 raw_spin_lock(&p->pi_lock);
1070 raw_spin_lock(&rq->lock);
1072 * If task_rq(p) != rq, it cannot be migrated here, because we're
1073 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1074 * we're holding p->pi_lock.
1076 if (task_rq(p) == rq) {
1077 if (task_on_rq_queued(p))
1078 rq = __migrate_task(rq, p, arg->dest_cpu);
1080 p->wake_cpu = arg->dest_cpu;
1082 raw_spin_unlock(&rq->lock);
1083 raw_spin_unlock(&p->pi_lock);
1090 * sched_class::set_cpus_allowed must do the below, but is not required to
1091 * actually call this function.
1093 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1095 cpumask_copy(&p->cpus_allowed, new_mask);
1096 p->nr_cpus_allowed = cpumask_weight(new_mask);
1099 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1101 struct rq *rq = task_rq(p);
1102 bool queued, running;
1104 lockdep_assert_held(&p->pi_lock);
1106 queued = task_on_rq_queued(p);
1107 running = task_current(rq, p);
1111 * Because __kthread_bind() calls this on blocked tasks without
1114 lockdep_assert_held(&rq->lock);
1115 dequeue_task(rq, p, DEQUEUE_SAVE);
1118 put_prev_task(rq, p);
1120 p->sched_class->set_cpus_allowed(p, new_mask);
1123 enqueue_task(rq, p, ENQUEUE_RESTORE);
1125 set_curr_task(rq, p);
1129 * Change a given task's CPU affinity. Migrate the thread to a
1130 * proper CPU and schedule it away if the CPU it's executing on
1131 * is removed from the allowed bitmask.
1133 * NOTE: the caller must have a valid reference to the task, the
1134 * task must not exit() & deallocate itself prematurely. The
1135 * call is not atomic; no spinlocks may be held.
1137 static int __set_cpus_allowed_ptr(struct task_struct *p,
1138 const struct cpumask *new_mask, bool check)
1140 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1141 unsigned int dest_cpu;
1146 rq = task_rq_lock(p, &rf);
1148 if (p->flags & PF_KTHREAD) {
1150 * Kernel threads are allowed on online && !active CPUs
1152 cpu_valid_mask = cpu_online_mask;
1156 * Must re-check here, to close a race against __kthread_bind(),
1157 * sched_setaffinity() is not guaranteed to observe the flag.
1159 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1164 if (cpumask_equal(&p->cpus_allowed, new_mask))
1167 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1172 do_set_cpus_allowed(p, new_mask);
1174 if (p->flags & PF_KTHREAD) {
1176 * For kernel threads that do indeed end up on online &&
1177 * !active we want to ensure they are strict per-cpu threads.
1179 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1180 !cpumask_intersects(new_mask, cpu_active_mask) &&
1181 p->nr_cpus_allowed != 1);
1184 /* Can the task run on the task's current CPU? If so, we're done */
1185 if (cpumask_test_cpu(task_cpu(p), new_mask))
1188 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1189 if (task_running(rq, p) || p->state == TASK_WAKING) {
1190 struct migration_arg arg = { p, dest_cpu };
1191 /* Need help from migration thread: drop lock and wait. */
1192 task_rq_unlock(rq, p, &rf);
1193 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1194 tlb_migrate_finish(p->mm);
1196 } else if (task_on_rq_queued(p)) {
1198 * OK, since we're going to drop the lock immediately
1199 * afterwards anyway.
1201 rq_unpin_lock(rq, &rf);
1202 rq = move_queued_task(rq, p, dest_cpu);
1203 rq_repin_lock(rq, &rf);
1206 task_rq_unlock(rq, p, &rf);
1211 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1213 return __set_cpus_allowed_ptr(p, new_mask, false);
1215 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1217 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1219 #ifdef CONFIG_SCHED_DEBUG
1221 * We should never call set_task_cpu() on a blocked task,
1222 * ttwu() will sort out the placement.
1224 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1228 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1229 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1230 * time relying on p->on_rq.
1232 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1233 p->sched_class == &fair_sched_class &&
1234 (p->on_rq && !task_on_rq_migrating(p)));
1236 #ifdef CONFIG_LOCKDEP
1238 * The caller should hold either p->pi_lock or rq->lock, when changing
1239 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1241 * sched_move_task() holds both and thus holding either pins the cgroup,
1244 * Furthermore, all task_rq users should acquire both locks, see
1247 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1248 lockdep_is_held(&task_rq(p)->lock)));
1252 trace_sched_migrate_task(p, new_cpu);
1254 if (task_cpu(p) != new_cpu) {
1255 if (p->sched_class->migrate_task_rq)
1256 p->sched_class->migrate_task_rq(p);
1257 p->se.nr_migrations++;
1258 perf_event_task_migrate(p);
1261 __set_task_cpu(p, new_cpu);
1264 static void __migrate_swap_task(struct task_struct *p, int cpu)
1266 if (task_on_rq_queued(p)) {
1267 struct rq *src_rq, *dst_rq;
1269 src_rq = task_rq(p);
1270 dst_rq = cpu_rq(cpu);
1272 p->on_rq = TASK_ON_RQ_MIGRATING;
1273 deactivate_task(src_rq, p, 0);
1274 set_task_cpu(p, cpu);
1275 activate_task(dst_rq, p, 0);
1276 p->on_rq = TASK_ON_RQ_QUEUED;
1277 check_preempt_curr(dst_rq, p, 0);
1280 * Task isn't running anymore; make it appear like we migrated
1281 * it before it went to sleep. This means on wakeup we make the
1282 * previous cpu our target instead of where it really is.
1288 struct migration_swap_arg {
1289 struct task_struct *src_task, *dst_task;
1290 int src_cpu, dst_cpu;
1293 static int migrate_swap_stop(void *data)
1295 struct migration_swap_arg *arg = data;
1296 struct rq *src_rq, *dst_rq;
1299 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1302 src_rq = cpu_rq(arg->src_cpu);
1303 dst_rq = cpu_rq(arg->dst_cpu);
1305 double_raw_lock(&arg->src_task->pi_lock,
1306 &arg->dst_task->pi_lock);
1307 double_rq_lock(src_rq, dst_rq);
1309 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1312 if (task_cpu(arg->src_task) != arg->src_cpu)
1315 if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
1318 if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
1321 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1322 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1327 double_rq_unlock(src_rq, dst_rq);
1328 raw_spin_unlock(&arg->dst_task->pi_lock);
1329 raw_spin_unlock(&arg->src_task->pi_lock);
1335 * Cross migrate two tasks
1337 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1339 struct migration_swap_arg arg;
1342 arg = (struct migration_swap_arg){
1344 .src_cpu = task_cpu(cur),
1346 .dst_cpu = task_cpu(p),
1349 if (arg.src_cpu == arg.dst_cpu)
1353 * These three tests are all lockless; this is OK since all of them
1354 * will be re-checked with proper locks held further down the line.
1356 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1359 if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
1362 if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
1365 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1366 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1373 * wait_task_inactive - wait for a thread to unschedule.
1375 * If @match_state is nonzero, it's the @p->state value just checked and
1376 * not expected to change. If it changes, i.e. @p might have woken up,
1377 * then return zero. When we succeed in waiting for @p to be off its CPU,
1378 * we return a positive number (its total switch count). If a second call
1379 * a short while later returns the same number, the caller can be sure that
1380 * @p has remained unscheduled the whole time.
1382 * The caller must ensure that the task *will* unschedule sometime soon,
1383 * else this function might spin for a *long* time. This function can't
1384 * be called with interrupts off, or it may introduce deadlock with
1385 * smp_call_function() if an IPI is sent by the same process we are
1386 * waiting to become inactive.
1388 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1390 int running, queued;
1397 * We do the initial early heuristics without holding
1398 * any task-queue locks at all. We'll only try to get
1399 * the runqueue lock when things look like they will
1405 * If the task is actively running on another CPU
1406 * still, just relax and busy-wait without holding
1409 * NOTE! Since we don't hold any locks, it's not
1410 * even sure that "rq" stays as the right runqueue!
1411 * But we don't care, since "task_running()" will
1412 * return false if the runqueue has changed and p
1413 * is actually now running somewhere else!
1415 while (task_running(rq, p)) {
1416 if (match_state && unlikely(p->state != match_state))
1422 * Ok, time to look more closely! We need the rq
1423 * lock now, to be *sure*. If we're wrong, we'll
1424 * just go back and repeat.
1426 rq = task_rq_lock(p, &rf);
1427 trace_sched_wait_task(p);
1428 running = task_running(rq, p);
1429 queued = task_on_rq_queued(p);
1431 if (!match_state || p->state == match_state)
1432 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1433 task_rq_unlock(rq, p, &rf);
1436 * If it changed from the expected state, bail out now.
1438 if (unlikely(!ncsw))
1442 * Was it really running after all now that we
1443 * checked with the proper locks actually held?
1445 * Oops. Go back and try again..
1447 if (unlikely(running)) {
1453 * It's not enough that it's not actively running,
1454 * it must be off the runqueue _entirely_, and not
1457 * So if it was still runnable (but just not actively
1458 * running right now), it's preempted, and we should
1459 * yield - it could be a while.
1461 if (unlikely(queued)) {
1462 ktime_t to = NSEC_PER_SEC / HZ;
1464 set_current_state(TASK_UNINTERRUPTIBLE);
1465 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1470 * Ahh, all good. It wasn't running, and it wasn't
1471 * runnable, which means that it will never become
1472 * running in the future either. We're all done!
1481 * kick_process - kick a running thread to enter/exit the kernel
1482 * @p: the to-be-kicked thread
1484 * Cause a process which is running on another CPU to enter
1485 * kernel-mode, without any delay. (to get signals handled.)
1487 * NOTE: this function doesn't have to take the runqueue lock,
1488 * because all it wants to ensure is that the remote task enters
1489 * the kernel. If the IPI races and the task has been migrated
1490 * to another CPU then no harm is done and the purpose has been
1493 void kick_process(struct task_struct *p)
1499 if ((cpu != smp_processor_id()) && task_curr(p))
1500 smp_send_reschedule(cpu);
1503 EXPORT_SYMBOL_GPL(kick_process);
1506 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1508 * A few notes on cpu_active vs cpu_online:
1510 * - cpu_active must be a subset of cpu_online
1512 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1513 * see __set_cpus_allowed_ptr(). At this point the newly online
1514 * cpu isn't yet part of the sched domains, and balancing will not
1517 * - on cpu-down we clear cpu_active() to mask the sched domains and
1518 * avoid the load balancer to place new tasks on the to be removed
1519 * cpu. Existing tasks will remain running there and will be taken
1522 * This means that fallback selection must not select !active CPUs.
1523 * And can assume that any active CPU must be online. Conversely
1524 * select_task_rq() below may allow selection of !active CPUs in order
1525 * to satisfy the above rules.
1527 static int select_fallback_rq(int cpu, struct task_struct *p)
1529 int nid = cpu_to_node(cpu);
1530 const struct cpumask *nodemask = NULL;
1531 enum { cpuset, possible, fail } state = cpuset;
1535 * If the node that the cpu is on has been offlined, cpu_to_node()
1536 * will return -1. There is no cpu on the node, and we should
1537 * select the cpu on the other node.
1540 nodemask = cpumask_of_node(nid);
1542 /* Look for allowed, online CPU in same node. */
1543 for_each_cpu(dest_cpu, nodemask) {
1544 if (!cpu_active(dest_cpu))
1546 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1552 /* Any allowed, online CPU? */
1553 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1554 if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
1556 if (!cpu_online(dest_cpu))
1561 /* No more Mr. Nice Guy. */
1564 if (IS_ENABLED(CONFIG_CPUSETS)) {
1565 cpuset_cpus_allowed_fallback(p);
1571 do_set_cpus_allowed(p, cpu_possible_mask);
1582 if (state != cpuset) {
1584 * Don't tell them about moving exiting tasks or
1585 * kernel threads (both mm NULL), since they never
1588 if (p->mm && printk_ratelimit()) {
1589 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1590 task_pid_nr(p), p->comm, cpu);
1598 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1601 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1603 lockdep_assert_held(&p->pi_lock);
1605 if (tsk_nr_cpus_allowed(p) > 1)
1606 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1608 cpu = cpumask_any(tsk_cpus_allowed(p));
1611 * In order not to call set_task_cpu() on a blocking task we need
1612 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1615 * Since this is common to all placement strategies, this lives here.
1617 * [ this allows ->select_task() to simply return task_cpu(p) and
1618 * not worry about this generic constraint ]
1620 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1622 cpu = select_fallback_rq(task_cpu(p), p);
1627 static void update_avg(u64 *avg, u64 sample)
1629 s64 diff = sample - *avg;
1635 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1636 const struct cpumask *new_mask, bool check)
1638 return set_cpus_allowed_ptr(p, new_mask);
1641 #endif /* CONFIG_SMP */
1644 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1648 if (!schedstat_enabled())
1654 if (cpu == rq->cpu) {
1655 schedstat_inc(rq->ttwu_local);
1656 schedstat_inc(p->se.statistics.nr_wakeups_local);
1658 struct sched_domain *sd;
1660 schedstat_inc(p->se.statistics.nr_wakeups_remote);
1662 for_each_domain(rq->cpu, sd) {
1663 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1664 schedstat_inc(sd->ttwu_wake_remote);
1671 if (wake_flags & WF_MIGRATED)
1672 schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1673 #endif /* CONFIG_SMP */
1675 schedstat_inc(rq->ttwu_count);
1676 schedstat_inc(p->se.statistics.nr_wakeups);
1678 if (wake_flags & WF_SYNC)
1679 schedstat_inc(p->se.statistics.nr_wakeups_sync);
1682 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1684 activate_task(rq, p, en_flags);
1685 p->on_rq = TASK_ON_RQ_QUEUED;
1687 /* if a worker is waking up, notify workqueue */
1688 if (p->flags & PF_WQ_WORKER)
1689 wq_worker_waking_up(p, cpu_of(rq));
1693 * Mark the task runnable and perform wakeup-preemption.
1695 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1696 struct rq_flags *rf)
1698 check_preempt_curr(rq, p, wake_flags);
1699 p->state = TASK_RUNNING;
1700 trace_sched_wakeup(p);
1703 if (p->sched_class->task_woken) {
1705 * Our task @p is fully woken up and running; so its safe to
1706 * drop the rq->lock, hereafter rq is only used for statistics.
1708 rq_unpin_lock(rq, rf);
1709 p->sched_class->task_woken(rq, p);
1710 rq_repin_lock(rq, rf);
1713 if (rq->idle_stamp) {
1714 u64 delta = rq_clock(rq) - rq->idle_stamp;
1715 u64 max = 2*rq->max_idle_balance_cost;
1717 update_avg(&rq->avg_idle, delta);
1719 if (rq->avg_idle > max)
1728 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1729 struct rq_flags *rf)
1731 int en_flags = ENQUEUE_WAKEUP;
1733 lockdep_assert_held(&rq->lock);
1736 if (p->sched_contributes_to_load)
1737 rq->nr_uninterruptible--;
1739 if (wake_flags & WF_MIGRATED)
1740 en_flags |= ENQUEUE_MIGRATED;
1743 ttwu_activate(rq, p, en_flags);
1744 ttwu_do_wakeup(rq, p, wake_flags, rf);
1748 * Called in case the task @p isn't fully descheduled from its runqueue,
1749 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1750 * since all we need to do is flip p->state to TASK_RUNNING, since
1751 * the task is still ->on_rq.
1753 static int ttwu_remote(struct task_struct *p, int wake_flags)
1759 rq = __task_rq_lock(p, &rf);
1760 if (task_on_rq_queued(p)) {
1761 /* check_preempt_curr() may use rq clock */
1762 update_rq_clock(rq);
1763 ttwu_do_wakeup(rq, p, wake_flags, &rf);
1766 __task_rq_unlock(rq, &rf);
1772 void sched_ttwu_pending(void)
1774 struct rq *rq = this_rq();
1775 struct llist_node *llist = llist_del_all(&rq->wake_list);
1776 struct task_struct *p;
1777 unsigned long flags;
1783 raw_spin_lock_irqsave(&rq->lock, flags);
1784 rq_pin_lock(rq, &rf);
1789 p = llist_entry(llist, struct task_struct, wake_entry);
1790 llist = llist_next(llist);
1792 if (p->sched_remote_wakeup)
1793 wake_flags = WF_MIGRATED;
1795 ttwu_do_activate(rq, p, wake_flags, &rf);
1798 rq_unpin_lock(rq, &rf);
1799 raw_spin_unlock_irqrestore(&rq->lock, flags);
1802 void scheduler_ipi(void)
1805 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1806 * TIF_NEED_RESCHED remotely (for the first time) will also send
1809 preempt_fold_need_resched();
1811 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1815 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1816 * traditionally all their work was done from the interrupt return
1817 * path. Now that we actually do some work, we need to make sure
1820 * Some archs already do call them, luckily irq_enter/exit nest
1823 * Arguably we should visit all archs and update all handlers,
1824 * however a fair share of IPIs are still resched only so this would
1825 * somewhat pessimize the simple resched case.
1828 sched_ttwu_pending();
1831 * Check if someone kicked us for doing the nohz idle load balance.
1833 if (unlikely(got_nohz_idle_kick())) {
1834 this_rq()->idle_balance = 1;
1835 raise_softirq_irqoff(SCHED_SOFTIRQ);
1840 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1842 struct rq *rq = cpu_rq(cpu);
1844 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1846 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1847 if (!set_nr_if_polling(rq->idle))
1848 smp_send_reschedule(cpu);
1850 trace_sched_wake_idle_without_ipi(cpu);
1854 void wake_up_if_idle(int cpu)
1856 struct rq *rq = cpu_rq(cpu);
1857 unsigned long flags;
1861 if (!is_idle_task(rcu_dereference(rq->curr)))
1864 if (set_nr_if_polling(rq->idle)) {
1865 trace_sched_wake_idle_without_ipi(cpu);
1867 raw_spin_lock_irqsave(&rq->lock, flags);
1868 if (is_idle_task(rq->curr))
1869 smp_send_reschedule(cpu);
1870 /* Else cpu is not in idle, do nothing here */
1871 raw_spin_unlock_irqrestore(&rq->lock, flags);
1878 bool cpus_share_cache(int this_cpu, int that_cpu)
1880 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1882 #endif /* CONFIG_SMP */
1884 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1886 struct rq *rq = cpu_rq(cpu);
1889 #if defined(CONFIG_SMP)
1890 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1891 sched_clock_cpu(cpu); /* sync clocks x-cpu */
1892 ttwu_queue_remote(p, cpu, wake_flags);
1897 raw_spin_lock(&rq->lock);
1898 rq_pin_lock(rq, &rf);
1899 ttwu_do_activate(rq, p, wake_flags, &rf);
1900 rq_unpin_lock(rq, &rf);
1901 raw_spin_unlock(&rq->lock);
1905 * Notes on Program-Order guarantees on SMP systems.
1909 * The basic program-order guarantee on SMP systems is that when a task [t]
1910 * migrates, all its activity on its old cpu [c0] happens-before any subsequent
1911 * execution on its new cpu [c1].
1913 * For migration (of runnable tasks) this is provided by the following means:
1915 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1916 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1917 * rq(c1)->lock (if not at the same time, then in that order).
1918 * C) LOCK of the rq(c1)->lock scheduling in task
1920 * Transitivity guarantees that B happens after A and C after B.
1921 * Note: we only require RCpc transitivity.
1922 * Note: the cpu doing B need not be c0 or c1
1931 * UNLOCK rq(0)->lock
1933 * LOCK rq(0)->lock // orders against CPU0
1935 * UNLOCK rq(0)->lock
1939 * UNLOCK rq(1)->lock
1941 * LOCK rq(1)->lock // orders against CPU2
1944 * UNLOCK rq(1)->lock
1947 * BLOCKING -- aka. SLEEP + WAKEUP
1949 * For blocking we (obviously) need to provide the same guarantee as for
1950 * migration. However the means are completely different as there is no lock
1951 * chain to provide order. Instead we do:
1953 * 1) smp_store_release(X->on_cpu, 0)
1954 * 2) smp_cond_load_acquire(!X->on_cpu)
1958 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1960 * LOCK rq(0)->lock LOCK X->pi_lock
1963 * smp_store_release(X->on_cpu, 0);
1965 * smp_cond_load_acquire(&X->on_cpu, !VAL);
1971 * X->state = RUNNING
1972 * UNLOCK rq(2)->lock
1974 * LOCK rq(2)->lock // orders against CPU1
1977 * UNLOCK rq(2)->lock
1980 * UNLOCK rq(0)->lock
1983 * However; for wakeups there is a second guarantee we must provide, namely we
1984 * must observe the state that lead to our wakeup. That is, not only must our
1985 * task observe its own prior state, it must also observe the stores prior to
1988 * This means that any means of doing remote wakeups must order the CPU doing
1989 * the wakeup against the CPU the task is going to end up running on. This,
1990 * however, is already required for the regular Program-Order guarantee above,
1991 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
1996 * try_to_wake_up - wake up a thread
1997 * @p: the thread to be awakened
1998 * @state: the mask of task states that can be woken
1999 * @wake_flags: wake modifier flags (WF_*)
2001 * If (@state & @p->state) @p->state = TASK_RUNNING.
2003 * If the task was not queued/runnable, also place it back on a runqueue.
2005 * Atomic against schedule() which would dequeue a task, also see
2006 * set_current_state().
2008 * Return: %true if @p->state changes (an actual wakeup was done),
2012 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
2014 unsigned long flags;
2015 int cpu, success = 0;
2018 * If we are going to wake up a thread waiting for CONDITION we
2019 * need to ensure that CONDITION=1 done by the caller can not be
2020 * reordered with p->state check below. This pairs with mb() in
2021 * set_current_state() the waiting thread does.
2023 smp_mb__before_spinlock();
2024 raw_spin_lock_irqsave(&p->pi_lock, flags);
2025 if (!(p->state & state))
2028 trace_sched_waking(p);
2030 success = 1; /* we're going to change ->state */
2034 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2035 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2036 * in smp_cond_load_acquire() below.
2038 * sched_ttwu_pending() try_to_wake_up()
2039 * [S] p->on_rq = 1; [L] P->state
2040 * UNLOCK rq->lock -----.
2044 * LOCK rq->lock -----'
2048 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2050 * Pairs with the UNLOCK+LOCK on rq->lock from the
2051 * last wakeup of our task and the schedule that got our task
2055 if (p->on_rq && ttwu_remote(p, wake_flags))
2060 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2061 * possible to, falsely, observe p->on_cpu == 0.
2063 * One must be running (->on_cpu == 1) in order to remove oneself
2064 * from the runqueue.
2066 * [S] ->on_cpu = 1; [L] ->on_rq
2070 * [S] ->on_rq = 0; [L] ->on_cpu
2072 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2073 * from the consecutive calls to schedule(); the first switching to our
2074 * task, the second putting it to sleep.
2079 * If the owning (remote) cpu is still in the middle of schedule() with
2080 * this task as prev, wait until its done referencing the task.
2082 * Pairs with the smp_store_release() in finish_lock_switch().
2084 * This ensures that tasks getting woken will be fully ordered against
2085 * their previous state and preserve Program Order.
2087 smp_cond_load_acquire(&p->on_cpu, !VAL);
2089 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2090 p->state = TASK_WAKING;
2092 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2093 if (task_cpu(p) != cpu) {
2094 wake_flags |= WF_MIGRATED;
2095 set_task_cpu(p, cpu);
2097 #endif /* CONFIG_SMP */
2099 ttwu_queue(p, cpu, wake_flags);
2101 ttwu_stat(p, cpu, wake_flags);
2103 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2109 * try_to_wake_up_local - try to wake up a local task with rq lock held
2110 * @p: the thread to be awakened
2111 * @cookie: context's cookie for pinning
2113 * Put @p on the run-queue if it's not already there. The caller must
2114 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2117 static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
2119 struct rq *rq = task_rq(p);
2121 if (WARN_ON_ONCE(rq != this_rq()) ||
2122 WARN_ON_ONCE(p == current))
2125 lockdep_assert_held(&rq->lock);
2127 if (!raw_spin_trylock(&p->pi_lock)) {
2129 * This is OK, because current is on_cpu, which avoids it being
2130 * picked for load-balance and preemption/IRQs are still
2131 * disabled avoiding further scheduler activity on it and we've
2132 * not yet picked a replacement task.
2134 rq_unpin_lock(rq, rf);
2135 raw_spin_unlock(&rq->lock);
2136 raw_spin_lock(&p->pi_lock);
2137 raw_spin_lock(&rq->lock);
2138 rq_repin_lock(rq, rf);
2141 if (!(p->state & TASK_NORMAL))
2144 trace_sched_waking(p);
2146 if (!task_on_rq_queued(p))
2147 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2149 ttwu_do_wakeup(rq, p, 0, rf);
2150 ttwu_stat(p, smp_processor_id(), 0);
2152 raw_spin_unlock(&p->pi_lock);
2156 * wake_up_process - Wake up a specific process
2157 * @p: The process to be woken up.
2159 * Attempt to wake up the nominated process and move it to the set of runnable
2162 * Return: 1 if the process was woken up, 0 if it was already running.
2164 * It may be assumed that this function implies a write memory barrier before
2165 * changing the task state if and only if any tasks are woken up.
2167 int wake_up_process(struct task_struct *p)
2169 return try_to_wake_up(p, TASK_NORMAL, 0);
2171 EXPORT_SYMBOL(wake_up_process);
2173 int wake_up_state(struct task_struct *p, unsigned int state)
2175 return try_to_wake_up(p, state, 0);
2179 * This function clears the sched_dl_entity static params.
2181 void __dl_clear_params(struct task_struct *p)
2183 struct sched_dl_entity *dl_se = &p->dl;
2185 dl_se->dl_runtime = 0;
2186 dl_se->dl_deadline = 0;
2187 dl_se->dl_period = 0;
2191 dl_se->dl_throttled = 0;
2192 dl_se->dl_yielded = 0;
2196 * Perform scheduler related setup for a newly forked process p.
2197 * p is forked by current.
2199 * __sched_fork() is basic setup used by init_idle() too:
2201 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2206 p->se.exec_start = 0;
2207 p->se.sum_exec_runtime = 0;
2208 p->se.prev_sum_exec_runtime = 0;
2209 p->se.nr_migrations = 0;
2211 INIT_LIST_HEAD(&p->se.group_node);
2213 #ifdef CONFIG_FAIR_GROUP_SCHED
2214 p->se.cfs_rq = NULL;
2217 #ifdef CONFIG_SCHEDSTATS
2218 /* Even if schedstat is disabled, there should not be garbage */
2219 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2222 RB_CLEAR_NODE(&p->dl.rb_node);
2223 init_dl_task_timer(&p->dl);
2224 __dl_clear_params(p);
2226 INIT_LIST_HEAD(&p->rt.run_list);
2228 p->rt.time_slice = sched_rr_timeslice;
2232 #ifdef CONFIG_PREEMPT_NOTIFIERS
2233 INIT_HLIST_HEAD(&p->preempt_notifiers);
2236 #ifdef CONFIG_NUMA_BALANCING
2237 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
2238 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2239 p->mm->numa_scan_seq = 0;
2242 if (clone_flags & CLONE_VM)
2243 p->numa_preferred_nid = current->numa_preferred_nid;
2245 p->numa_preferred_nid = -1;
2247 p->node_stamp = 0ULL;
2248 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
2249 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2250 p->numa_work.next = &p->numa_work;
2251 p->numa_faults = NULL;
2252 p->last_task_numa_placement = 0;
2253 p->last_sum_exec_runtime = 0;
2255 p->numa_group = NULL;
2256 #endif /* CONFIG_NUMA_BALANCING */
2259 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2261 #ifdef CONFIG_NUMA_BALANCING
2263 void set_numabalancing_state(bool enabled)
2266 static_branch_enable(&sched_numa_balancing);
2268 static_branch_disable(&sched_numa_balancing);
2271 #ifdef CONFIG_PROC_SYSCTL
2272 int sysctl_numa_balancing(struct ctl_table *table, int write,
2273 void __user *buffer, size_t *lenp, loff_t *ppos)
2277 int state = static_branch_likely(&sched_numa_balancing);
2279 if (write && !capable(CAP_SYS_ADMIN))
2284 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2288 set_numabalancing_state(state);
2294 #ifdef CONFIG_SCHEDSTATS
2296 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2297 static bool __initdata __sched_schedstats = false;
2299 static void set_schedstats(bool enabled)
2302 static_branch_enable(&sched_schedstats);
2304 static_branch_disable(&sched_schedstats);
2307 void force_schedstat_enabled(void)
2309 if (!schedstat_enabled()) {
2310 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2311 static_branch_enable(&sched_schedstats);
2315 static int __init setup_schedstats(char *str)
2322 * This code is called before jump labels have been set up, so we can't
2323 * change the static branch directly just yet. Instead set a temporary
2324 * variable so init_schedstats() can do it later.
2326 if (!strcmp(str, "enable")) {
2327 __sched_schedstats = true;
2329 } else if (!strcmp(str, "disable")) {
2330 __sched_schedstats = false;
2335 pr_warn("Unable to parse schedstats=\n");
2339 __setup("schedstats=", setup_schedstats);
2341 static void __init init_schedstats(void)
2343 set_schedstats(__sched_schedstats);
2346 #ifdef CONFIG_PROC_SYSCTL
2347 int sysctl_schedstats(struct ctl_table *table, int write,
2348 void __user *buffer, size_t *lenp, loff_t *ppos)
2352 int state = static_branch_likely(&sched_schedstats);
2354 if (write && !capable(CAP_SYS_ADMIN))
2359 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2363 set_schedstats(state);
2366 #endif /* CONFIG_PROC_SYSCTL */
2367 #else /* !CONFIG_SCHEDSTATS */
2368 static inline void init_schedstats(void) {}
2369 #endif /* CONFIG_SCHEDSTATS */
2372 * fork()/clone()-time setup:
2374 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2376 unsigned long flags;
2377 int cpu = get_cpu();
2379 __sched_fork(clone_flags, p);
2381 * We mark the process as NEW here. This guarantees that
2382 * nobody will actually run it, and a signal or other external
2383 * event cannot wake it up and insert it on the runqueue either.
2385 p->state = TASK_NEW;
2388 * Make sure we do not leak PI boosting priority to the child.
2390 p->prio = current->normal_prio;
2393 * Revert to default priority/policy on fork if requested.
2395 if (unlikely(p->sched_reset_on_fork)) {
2396 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2397 p->policy = SCHED_NORMAL;
2398 p->static_prio = NICE_TO_PRIO(0);
2400 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2401 p->static_prio = NICE_TO_PRIO(0);
2403 p->prio = p->normal_prio = __normal_prio(p);
2407 * We don't need the reset flag anymore after the fork. It has
2408 * fulfilled its duty:
2410 p->sched_reset_on_fork = 0;
2413 if (dl_prio(p->prio)) {
2416 } else if (rt_prio(p->prio)) {
2417 p->sched_class = &rt_sched_class;
2419 p->sched_class = &fair_sched_class;
2422 init_entity_runnable_average(&p->se);
2425 * The child is not yet in the pid-hash so no cgroup attach races,
2426 * and the cgroup is pinned to this child due to cgroup_fork()
2427 * is ran before sched_fork().
2429 * Silence PROVE_RCU.
2431 raw_spin_lock_irqsave(&p->pi_lock, flags);
2433 * We're setting the cpu for the first time, we don't migrate,
2434 * so use __set_task_cpu().
2436 __set_task_cpu(p, cpu);
2437 if (p->sched_class->task_fork)
2438 p->sched_class->task_fork(p);
2439 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2441 #ifdef CONFIG_SCHED_INFO
2442 if (likely(sched_info_on()))
2443 memset(&p->sched_info, 0, sizeof(p->sched_info));
2445 #if defined(CONFIG_SMP)
2448 init_task_preempt_count(p);
2450 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2451 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2458 unsigned long to_ratio(u64 period, u64 runtime)
2460 if (runtime == RUNTIME_INF)
2464 * Doing this here saves a lot of checks in all
2465 * the calling paths, and returning zero seems
2466 * safe for them anyway.
2471 return div64_u64(runtime << 20, period);
2475 inline struct dl_bw *dl_bw_of(int i)
2477 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2478 "sched RCU must be held");
2479 return &cpu_rq(i)->rd->dl_bw;
2482 static inline int dl_bw_cpus(int i)
2484 struct root_domain *rd = cpu_rq(i)->rd;
2487 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2488 "sched RCU must be held");
2489 for_each_cpu_and(i, rd->span, cpu_active_mask)
2495 inline struct dl_bw *dl_bw_of(int i)
2497 return &cpu_rq(i)->dl.dl_bw;
2500 static inline int dl_bw_cpus(int i)
2507 * We must be sure that accepting a new task (or allowing changing the
2508 * parameters of an existing one) is consistent with the bandwidth
2509 * constraints. If yes, this function also accordingly updates the currently
2510 * allocated bandwidth to reflect the new situation.
2512 * This function is called while holding p's rq->lock.
2514 * XXX we should delay bw change until the task's 0-lag point, see
2517 static int dl_overflow(struct task_struct *p, int policy,
2518 const struct sched_attr *attr)
2521 struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2522 u64 period = attr->sched_period ?: attr->sched_deadline;
2523 u64 runtime = attr->sched_runtime;
2524 u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2527 /* !deadline task may carry old deadline bandwidth */
2528 if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
2532 * Either if a task, enters, leave, or stays -deadline but changes
2533 * its parameters, we may need to update accordingly the total
2534 * allocated bandwidth of the container.
2536 raw_spin_lock(&dl_b->lock);
2537 cpus = dl_bw_cpus(task_cpu(p));
2538 if (dl_policy(policy) && !task_has_dl_policy(p) &&
2539 !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2540 __dl_add(dl_b, new_bw);
2542 } else if (dl_policy(policy) && task_has_dl_policy(p) &&
2543 !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2544 __dl_clear(dl_b, p->dl.dl_bw);
2545 __dl_add(dl_b, new_bw);
2547 } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2548 __dl_clear(dl_b, p->dl.dl_bw);
2551 raw_spin_unlock(&dl_b->lock);
2556 extern void init_dl_bw(struct dl_bw *dl_b);
2559 * wake_up_new_task - wake up a newly created task for the first time.
2561 * This function will do some initial scheduler statistics housekeeping
2562 * that must be done for every newly created context, then puts the task
2563 * on the runqueue and wakes it.
2565 void wake_up_new_task(struct task_struct *p)
2570 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2571 p->state = TASK_RUNNING;
2574 * Fork balancing, do it here and not earlier because:
2575 * - cpus_allowed can change in the fork path
2576 * - any previously selected cpu might disappear through hotplug
2578 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2579 * as we're not fully set-up yet.
2581 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2583 rq = __task_rq_lock(p, &rf);
2584 update_rq_clock(rq);
2585 post_init_entity_util_avg(&p->se);
2587 activate_task(rq, p, 0);
2588 p->on_rq = TASK_ON_RQ_QUEUED;
2589 trace_sched_wakeup_new(p);
2590 check_preempt_curr(rq, p, WF_FORK);
2592 if (p->sched_class->task_woken) {
2594 * Nothing relies on rq->lock after this, so its fine to
2597 rq_unpin_lock(rq, &rf);
2598 p->sched_class->task_woken(rq, p);
2599 rq_repin_lock(rq, &rf);
2602 task_rq_unlock(rq, p, &rf);
2605 #ifdef CONFIG_PREEMPT_NOTIFIERS
2607 static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2609 void preempt_notifier_inc(void)
2611 static_key_slow_inc(&preempt_notifier_key);
2613 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2615 void preempt_notifier_dec(void)
2617 static_key_slow_dec(&preempt_notifier_key);
2619 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2622 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2623 * @notifier: notifier struct to register
2625 void preempt_notifier_register(struct preempt_notifier *notifier)
2627 if (!static_key_false(&preempt_notifier_key))
2628 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2630 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2632 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2635 * preempt_notifier_unregister - no longer interested in preemption notifications
2636 * @notifier: notifier struct to unregister
2638 * This is *not* safe to call from within a preemption notifier.
2640 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2642 hlist_del(¬ifier->link);
2644 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2646 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2648 struct preempt_notifier *notifier;
2650 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2651 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2654 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2656 if (static_key_false(&preempt_notifier_key))
2657 __fire_sched_in_preempt_notifiers(curr);
2661 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2662 struct task_struct *next)
2664 struct preempt_notifier *notifier;
2666 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2667 notifier->ops->sched_out(notifier, next);
2670 static __always_inline void
2671 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2672 struct task_struct *next)
2674 if (static_key_false(&preempt_notifier_key))
2675 __fire_sched_out_preempt_notifiers(curr, next);
2678 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2680 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2685 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2686 struct task_struct *next)
2690 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2693 * prepare_task_switch - prepare to switch tasks
2694 * @rq: the runqueue preparing to switch
2695 * @prev: the current task that is being switched out
2696 * @next: the task we are going to switch to.
2698 * This is called with the rq lock held and interrupts off. It must
2699 * be paired with a subsequent finish_task_switch after the context
2702 * prepare_task_switch sets up locking and calls architecture specific
2706 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2707 struct task_struct *next)
2709 sched_info_switch(rq, prev, next);
2710 perf_event_task_sched_out(prev, next);
2711 fire_sched_out_preempt_notifiers(prev, next);
2712 prepare_lock_switch(rq, next);
2713 prepare_arch_switch(next);
2717 * finish_task_switch - clean up after a task-switch
2718 * @prev: the thread we just switched away from.
2720 * finish_task_switch must be called after the context switch, paired
2721 * with a prepare_task_switch call before the context switch.
2722 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2723 * and do any other architecture-specific cleanup actions.
2725 * Note that we may have delayed dropping an mm in context_switch(). If
2726 * so, we finish that here outside of the runqueue lock. (Doing it
2727 * with the lock held can cause deadlocks; see schedule() for
2730 * The context switch have flipped the stack from under us and restored the
2731 * local variables which were saved when this task called schedule() in the
2732 * past. prev == current is still correct but we need to recalculate this_rq
2733 * because prev may have moved to another CPU.
2735 static struct rq *finish_task_switch(struct task_struct *prev)
2736 __releases(rq->lock)
2738 struct rq *rq = this_rq();
2739 struct mm_struct *mm = rq->prev_mm;
2743 * The previous task will have left us with a preempt_count of 2
2744 * because it left us after:
2747 * preempt_disable(); // 1
2749 * raw_spin_lock_irq(&rq->lock) // 2
2751 * Also, see FORK_PREEMPT_COUNT.
2753 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2754 "corrupted preempt_count: %s/%d/0x%x\n",
2755 current->comm, current->pid, preempt_count()))
2756 preempt_count_set(FORK_PREEMPT_COUNT);
2761 * A task struct has one reference for the use as "current".
2762 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2763 * schedule one last time. The schedule call will never return, and
2764 * the scheduled task must drop that reference.
2766 * We must observe prev->state before clearing prev->on_cpu (in
2767 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2768 * running on another CPU and we could rave with its RUNNING -> DEAD
2769 * transition, resulting in a double drop.
2771 prev_state = prev->state;
2772 vtime_task_switch(prev);
2773 perf_event_task_sched_in(prev, current);
2774 finish_lock_switch(rq, prev);
2775 finish_arch_post_lock_switch();
2777 fire_sched_in_preempt_notifiers(current);
2780 if (unlikely(prev_state == TASK_DEAD)) {
2781 if (prev->sched_class->task_dead)
2782 prev->sched_class->task_dead(prev);
2785 * Remove function-return probe instances associated with this
2786 * task and put them back on the free list.
2788 kprobe_flush_task(prev);
2790 /* Task is done with its stack. */
2791 put_task_stack(prev);
2793 put_task_struct(prev);
2796 tick_nohz_task_switch();
2802 /* rq->lock is NOT held, but preemption is disabled */
2803 static void __balance_callback(struct rq *rq)
2805 struct callback_head *head, *next;
2806 void (*func)(struct rq *rq);
2807 unsigned long flags;
2809 raw_spin_lock_irqsave(&rq->lock, flags);
2810 head = rq->balance_callback;
2811 rq->balance_callback = NULL;
2813 func = (void (*)(struct rq *))head->func;
2820 raw_spin_unlock_irqrestore(&rq->lock, flags);
2823 static inline void balance_callback(struct rq *rq)
2825 if (unlikely(rq->balance_callback))
2826 __balance_callback(rq);
2831 static inline void balance_callback(struct rq *rq)
2838 * schedule_tail - first thing a freshly forked thread must call.
2839 * @prev: the thread we just switched away from.
2841 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2842 __releases(rq->lock)
2847 * New tasks start with FORK_PREEMPT_COUNT, see there and
2848 * finish_task_switch() for details.
2850 * finish_task_switch() will drop rq->lock() and lower preempt_count
2851 * and the preempt_enable() will end up enabling preemption (on
2852 * PREEMPT_COUNT kernels).
2855 rq = finish_task_switch(prev);
2856 balance_callback(rq);
2859 if (current->set_child_tid)
2860 put_user(task_pid_vnr(current), current->set_child_tid);
2864 * context_switch - switch to the new MM and the new thread's register state.
2866 static __always_inline struct rq *
2867 context_switch(struct rq *rq, struct task_struct *prev,
2868 struct task_struct *next, struct rq_flags *rf)
2870 struct mm_struct *mm, *oldmm;
2872 prepare_task_switch(rq, prev, next);
2875 oldmm = prev->active_mm;
2877 * For paravirt, this is coupled with an exit in switch_to to
2878 * combine the page table reload and the switch backend into
2881 arch_start_context_switch(prev);
2884 next->active_mm = oldmm;
2885 atomic_inc(&oldmm->mm_count);
2886 enter_lazy_tlb(oldmm, next);
2888 switch_mm_irqs_off(oldmm, mm, next);
2891 prev->active_mm = NULL;
2892 rq->prev_mm = oldmm;
2895 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
2898 * Since the runqueue lock will be released by the next
2899 * task (which is an invalid locking op but in the case
2900 * of the scheduler it's an obvious special-case), so we
2901 * do an early lockdep release here:
2903 rq_unpin_lock(rq, rf);
2904 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2906 /* Here we just switch the register state and the stack. */
2907 switch_to(prev, next, prev);
2910 return finish_task_switch(prev);
2914 * nr_running and nr_context_switches:
2916 * externally visible scheduler statistics: current number of runnable
2917 * threads, total number of context switches performed since bootup.
2919 unsigned long nr_running(void)
2921 unsigned long i, sum = 0;
2923 for_each_online_cpu(i)
2924 sum += cpu_rq(i)->nr_running;
2930 * Check if only the current task is running on the cpu.
2932 * Caution: this function does not check that the caller has disabled
2933 * preemption, thus the result might have a time-of-check-to-time-of-use
2934 * race. The caller is responsible to use it correctly, for example:
2936 * - from a non-preemptable section (of course)
2938 * - from a thread that is bound to a single CPU
2940 * - in a loop with very short iterations (e.g. a polling loop)
2942 bool single_task_running(void)
2944 return raw_rq()->nr_running == 1;
2946 EXPORT_SYMBOL(single_task_running);
2948 unsigned long long nr_context_switches(void)
2951 unsigned long long sum = 0;
2953 for_each_possible_cpu(i)
2954 sum += cpu_rq(i)->nr_switches;
2959 unsigned long nr_iowait(void)
2961 unsigned long i, sum = 0;
2963 for_each_possible_cpu(i)
2964 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2969 unsigned long nr_iowait_cpu(int cpu)
2971 struct rq *this = cpu_rq(cpu);
2972 return atomic_read(&this->nr_iowait);
2975 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2977 struct rq *rq = this_rq();
2978 *nr_waiters = atomic_read(&rq->nr_iowait);
2979 *load = rq->load.weight;
2985 * sched_exec - execve() is a valuable balancing opportunity, because at
2986 * this point the task has the smallest effective memory and cache footprint.
2988 void sched_exec(void)
2990 struct task_struct *p = current;
2991 unsigned long flags;
2994 raw_spin_lock_irqsave(&p->pi_lock, flags);
2995 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2996 if (dest_cpu == smp_processor_id())
2999 if (likely(cpu_active(dest_cpu))) {
3000 struct migration_arg arg = { p, dest_cpu };
3002 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3003 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
3007 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3012 DEFINE_PER_CPU(struct kernel_stat, kstat);
3013 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
3015 EXPORT_PER_CPU_SYMBOL(kstat);
3016 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3019 * The function fair_sched_class.update_curr accesses the struct curr
3020 * and its field curr->exec_start; when called from task_sched_runtime(),
3021 * we observe a high rate of cache misses in practice.
3022 * Prefetching this data results in improved performance.
3024 static inline void prefetch_curr_exec_start(struct task_struct *p)
3026 #ifdef CONFIG_FAIR_GROUP_SCHED
3027 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3029 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3032 prefetch(&curr->exec_start);
3036 * Return accounted runtime for the task.
3037 * In case the task is currently running, return the runtime plus current's
3038 * pending runtime that have not been accounted yet.
3040 unsigned long long task_sched_runtime(struct task_struct *p)
3046 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3048 * 64-bit doesn't need locks to atomically read a 64bit value.
3049 * So we have a optimization chance when the task's delta_exec is 0.
3050 * Reading ->on_cpu is racy, but this is ok.
3052 * If we race with it leaving cpu, we'll take a lock. So we're correct.
3053 * If we race with it entering cpu, unaccounted time is 0. This is
3054 * indistinguishable from the read occurring a few cycles earlier.
3055 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3056 * been accounted, so we're correct here as well.
3058 if (!p->on_cpu || !task_on_rq_queued(p))
3059 return p->se.sum_exec_runtime;
3062 rq = task_rq_lock(p, &rf);
3064 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3065 * project cycles that may never be accounted to this
3066 * thread, breaking clock_gettime().
3068 if (task_current(rq, p) && task_on_rq_queued(p)) {
3069 prefetch_curr_exec_start(p);
3070 update_rq_clock(rq);
3071 p->sched_class->update_curr(rq);
3073 ns = p->se.sum_exec_runtime;
3074 task_rq_unlock(rq, p, &rf);
3080 * This function gets called by the timer code, with HZ frequency.
3081 * We call it with interrupts disabled.
3083 void scheduler_tick(void)
3085 int cpu = smp_processor_id();
3086 struct rq *rq = cpu_rq(cpu);
3087 struct task_struct *curr = rq->curr;
3091 raw_spin_lock(&rq->lock);
3092 update_rq_clock(rq);
3093 curr->sched_class->task_tick(rq, curr, 0);
3094 cpu_load_update_active(rq);
3095 calc_global_load_tick(rq);
3096 raw_spin_unlock(&rq->lock);
3098 perf_event_task_tick();
3101 rq->idle_balance = idle_cpu(cpu);
3102 trigger_load_balance(rq);
3104 rq_last_tick_reset(rq);
3107 #ifdef CONFIG_NO_HZ_FULL
3109 * scheduler_tick_max_deferment
3111 * Keep at least one tick per second when a single
3112 * active task is running because the scheduler doesn't
3113 * yet completely support full dynticks environment.
3115 * This makes sure that uptime, CFS vruntime, load
3116 * balancing, etc... continue to move forward, even
3117 * with a very low granularity.
3119 * Return: Maximum deferment in nanoseconds.
3121 u64 scheduler_tick_max_deferment(void)
3123 struct rq *rq = this_rq();
3124 unsigned long next, now = READ_ONCE(jiffies);
3126 next = rq->last_sched_tick + HZ;
3128 if (time_before_eq(next, now))
3131 return jiffies_to_nsecs(next - now);
3135 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3136 defined(CONFIG_PREEMPT_TRACER))
3138 * If the value passed in is equal to the current preempt count
3139 * then we just disabled preemption. Start timing the latency.
3141 static inline void preempt_latency_start(int val)
3143 if (preempt_count() == val) {
3144 unsigned long ip = get_lock_parent_ip();
3145 #ifdef CONFIG_DEBUG_PREEMPT
3146 current->preempt_disable_ip = ip;
3148 trace_preempt_off(CALLER_ADDR0, ip);
3152 void preempt_count_add(int val)
3154 #ifdef CONFIG_DEBUG_PREEMPT
3158 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3161 __preempt_count_add(val);
3162 #ifdef CONFIG_DEBUG_PREEMPT
3164 * Spinlock count overflowing soon?
3166 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3169 preempt_latency_start(val);
3171 EXPORT_SYMBOL(preempt_count_add);
3172 NOKPROBE_SYMBOL(preempt_count_add);
3175 * If the value passed in equals to the current preempt count
3176 * then we just enabled preemption. Stop timing the latency.
3178 static inline void preempt_latency_stop(int val)
3180 if (preempt_count() == val)
3181 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3184 void preempt_count_sub(int val)
3186 #ifdef CONFIG_DEBUG_PREEMPT
3190 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3193 * Is the spinlock portion underflowing?
3195 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3196 !(preempt_count() & PREEMPT_MASK)))
3200 preempt_latency_stop(val);
3201 __preempt_count_sub(val);
3203 EXPORT_SYMBOL(preempt_count_sub);
3204 NOKPROBE_SYMBOL(preempt_count_sub);
3207 static inline void preempt_latency_start(int val) { }
3208 static inline void preempt_latency_stop(int val) { }
3212 * Print scheduling while atomic bug:
3214 static noinline void __schedule_bug(struct task_struct *prev)
3216 /* Save this before calling printk(), since that will clobber it */
3217 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3219 if (oops_in_progress)
3222 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3223 prev->comm, prev->pid, preempt_count());
3225 debug_show_held_locks(prev);
3227 if (irqs_disabled())
3228 print_irqtrace_events(prev);
3229 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3230 && in_atomic_preempt_off()) {
3231 pr_err("Preemption disabled at:");
3232 print_ip_sym(preempt_disable_ip);
3236 panic("scheduling while atomic\n");
3239 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3243 * Various schedule()-time debugging checks and statistics:
3245 static inline void schedule_debug(struct task_struct *prev)
3247 #ifdef CONFIG_SCHED_STACK_END_CHECK
3248 if (task_stack_end_corrupted(prev))
3249 panic("corrupted stack end detected inside scheduler\n");
3252 if (unlikely(in_atomic_preempt_off())) {
3253 __schedule_bug(prev);
3254 preempt_count_set(PREEMPT_DISABLED);
3258 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3260 schedstat_inc(this_rq()->sched_count);
3264 * Pick up the highest-prio task:
3266 static inline struct task_struct *
3267 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
3269 const struct sched_class *class = &fair_sched_class;
3270 struct task_struct *p;
3273 * Optimization: we know that if all tasks are in
3274 * the fair class we can call that function directly:
3276 if (likely(prev->sched_class == class &&
3277 rq->nr_running == rq->cfs.h_nr_running)) {
3278 p = fair_sched_class.pick_next_task(rq, prev, rf);
3279 if (unlikely(p == RETRY_TASK))
3282 /* assumes fair_sched_class->next == idle_sched_class */
3284 p = idle_sched_class.pick_next_task(rq, prev, rf);
3290 for_each_class(class) {
3291 p = class->pick_next_task(rq, prev, rf);
3293 if (unlikely(p == RETRY_TASK))
3299 BUG(); /* the idle class will always have a runnable task */
3303 * __schedule() is the main scheduler function.
3305 * The main means of driving the scheduler and thus entering this function are:
3307 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3309 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3310 * paths. For example, see arch/x86/entry_64.S.
3312 * To drive preemption between tasks, the scheduler sets the flag in timer
3313 * interrupt handler scheduler_tick().
3315 * 3. Wakeups don't really cause entry into schedule(). They add a
3316 * task to the run-queue and that's it.
3318 * Now, if the new task added to the run-queue preempts the current
3319 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3320 * called on the nearest possible occasion:
3322 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3324 * - in syscall or exception context, at the next outmost
3325 * preempt_enable(). (this might be as soon as the wake_up()'s
3328 * - in IRQ context, return from interrupt-handler to
3329 * preemptible context
3331 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3334 * - cond_resched() call
3335 * - explicit schedule() call
3336 * - return from syscall or exception to user-space
3337 * - return from interrupt-handler to user-space
3339 * WARNING: must be called with preemption disabled!
3341 static void __sched notrace __schedule(bool preempt)
3343 struct task_struct *prev, *next;
3344 unsigned long *switch_count;
3349 cpu = smp_processor_id();
3353 schedule_debug(prev);
3355 if (sched_feat(HRTICK))
3358 local_irq_disable();
3359 rcu_note_context_switch();
3362 * Make sure that signal_pending_state()->signal_pending() below
3363 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3364 * done by the caller to avoid the race with signal_wake_up().
3366 smp_mb__before_spinlock();
3367 raw_spin_lock(&rq->lock);
3368 rq_pin_lock(rq, &rf);
3370 rq->clock_update_flags <<= 1; /* promote REQ to ACT */
3372 switch_count = &prev->nivcsw;
3373 if (!preempt && prev->state) {
3374 if (unlikely(signal_pending_state(prev->state, prev))) {
3375 prev->state = TASK_RUNNING;
3377 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3381 * If a worker went to sleep, notify and ask workqueue
3382 * whether it wants to wake up a task to maintain
3385 if (prev->flags & PF_WQ_WORKER) {
3386 struct task_struct *to_wakeup;
3388 to_wakeup = wq_worker_sleeping(prev);
3390 try_to_wake_up_local(to_wakeup, &rf);
3393 switch_count = &prev->nvcsw;
3396 if (task_on_rq_queued(prev))
3397 update_rq_clock(rq);
3399 next = pick_next_task(rq, prev, &rf);
3400 clear_tsk_need_resched(prev);
3401 clear_preempt_need_resched();
3403 if (likely(prev != next)) {
3408 trace_sched_switch(preempt, prev, next);
3409 rq = context_switch(rq, prev, next, &rf); /* unlocks the rq */
3411 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3412 rq_unpin_lock(rq, &rf);
3413 raw_spin_unlock_irq(&rq->lock);
3416 balance_callback(rq);
3419 void __noreturn do_task_dead(void)
3422 * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
3423 * when the following two conditions become true.
3424 * - There is race condition of mmap_sem (It is acquired by
3426 * - SMI occurs before setting TASK_RUNINNG.
3427 * (or hypervisor of virtual machine switches to other guest)
3428 * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
3430 * To avoid it, we have to wait for releasing tsk->pi_lock which
3431 * is held by try_to_wake_up()
3434 raw_spin_unlock_wait(¤t->pi_lock);
3436 /* causes final put_task_struct in finish_task_switch(). */
3437 __set_current_state(TASK_DEAD);
3438 current->flags |= PF_NOFREEZE; /* tell freezer to ignore us */
3441 /* Avoid "noreturn function does return". */
3443 cpu_relax(); /* For when BUG is null */
3446 static inline void sched_submit_work(struct task_struct *tsk)
3448 if (!tsk->state || tsk_is_pi_blocked(tsk))
3451 * If we are going to sleep and we have plugged IO queued,
3452 * make sure to submit it to avoid deadlocks.
3454 if (blk_needs_flush_plug(tsk))
3455 blk_schedule_flush_plug(tsk);
3458 asmlinkage __visible void __sched schedule(void)
3460 struct task_struct *tsk = current;
3462 sched_submit_work(tsk);
3466 sched_preempt_enable_no_resched();
3467 } while (need_resched());
3469 EXPORT_SYMBOL(schedule);
3471 #ifdef CONFIG_CONTEXT_TRACKING
3472 asmlinkage __visible void __sched schedule_user(void)
3475 * If we come here after a random call to set_need_resched(),
3476 * or we have been woken up remotely but the IPI has not yet arrived,
3477 * we haven't yet exited the RCU idle mode. Do it here manually until
3478 * we find a better solution.
3480 * NB: There are buggy callers of this function. Ideally we
3481 * should warn if prev_state != CONTEXT_USER, but that will trigger
3482 * too frequently to make sense yet.
3484 enum ctx_state prev_state = exception_enter();
3486 exception_exit(prev_state);
3491 * schedule_preempt_disabled - called with preemption disabled
3493 * Returns with preemption disabled. Note: preempt_count must be 1
3495 void __sched schedule_preempt_disabled(void)
3497 sched_preempt_enable_no_resched();
3502 static void __sched notrace preempt_schedule_common(void)
3506 * Because the function tracer can trace preempt_count_sub()
3507 * and it also uses preempt_enable/disable_notrace(), if
3508 * NEED_RESCHED is set, the preempt_enable_notrace() called
3509 * by the function tracer will call this function again and
3510 * cause infinite recursion.
3512 * Preemption must be disabled here before the function
3513 * tracer can trace. Break up preempt_disable() into two
3514 * calls. One to disable preemption without fear of being
3515 * traced. The other to still record the preemption latency,
3516 * which can also be traced by the function tracer.
3518 preempt_disable_notrace();
3519 preempt_latency_start(1);
3521 preempt_latency_stop(1);
3522 preempt_enable_no_resched_notrace();
3525 * Check again in case we missed a preemption opportunity
3526 * between schedule and now.
3528 } while (need_resched());
3531 #ifdef CONFIG_PREEMPT
3533 * this is the entry point to schedule() from in-kernel preemption
3534 * off of preempt_enable. Kernel preemptions off return from interrupt
3535 * occur there and call schedule directly.
3537 asmlinkage __visible void __sched notrace preempt_schedule(void)
3540 * If there is a non-zero preempt_count or interrupts are disabled,
3541 * we do not want to preempt the current task. Just return..
3543 if (likely(!preemptible()))
3546 preempt_schedule_common();
3548 NOKPROBE_SYMBOL(preempt_schedule);
3549 EXPORT_SYMBOL(preempt_schedule);
3552 * preempt_schedule_notrace - preempt_schedule called by tracing
3554 * The tracing infrastructure uses preempt_enable_notrace to prevent
3555 * recursion and tracing preempt enabling caused by the tracing
3556 * infrastructure itself. But as tracing can happen in areas coming
3557 * from userspace or just about to enter userspace, a preempt enable
3558 * can occur before user_exit() is called. This will cause the scheduler
3559 * to be called when the system is still in usermode.
3561 * To prevent this, the preempt_enable_notrace will use this function
3562 * instead of preempt_schedule() to exit user context if needed before
3563 * calling the scheduler.
3565 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3567 enum ctx_state prev_ctx;
3569 if (likely(!preemptible()))
3574 * Because the function tracer can trace preempt_count_sub()
3575 * and it also uses preempt_enable/disable_notrace(), if
3576 * NEED_RESCHED is set, the preempt_enable_notrace() called
3577 * by the function tracer will call this function again and
3578 * cause infinite recursion.
3580 * Preemption must be disabled here before the function
3581 * tracer can trace. Break up preempt_disable() into two
3582 * calls. One to disable preemption without fear of being
3583 * traced. The other to still record the preemption latency,
3584 * which can also be traced by the function tracer.
3586 preempt_disable_notrace();
3587 preempt_latency_start(1);
3589 * Needs preempt disabled in case user_exit() is traced
3590 * and the tracer calls preempt_enable_notrace() causing
3591 * an infinite recursion.
3593 prev_ctx = exception_enter();
3595 exception_exit(prev_ctx);
3597 preempt_latency_stop(1);
3598 preempt_enable_no_resched_notrace();
3599 } while (need_resched());
3601 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3603 #endif /* CONFIG_PREEMPT */
3606 * this is the entry point to schedule() from kernel preemption
3607 * off of irq context.
3608 * Note, that this is called and return with irqs disabled. This will
3609 * protect us against recursive calling from irq.
3611 asmlinkage __visible void __sched preempt_schedule_irq(void)
3613 enum ctx_state prev_state;
3615 /* Catch callers which need to be fixed */
3616 BUG_ON(preempt_count() || !irqs_disabled());
3618 prev_state = exception_enter();
3624 local_irq_disable();
3625 sched_preempt_enable_no_resched();
3626 } while (need_resched());
3628 exception_exit(prev_state);
3631 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3634 return try_to_wake_up(curr->private, mode, wake_flags);
3636 EXPORT_SYMBOL(default_wake_function);
3638 #ifdef CONFIG_RT_MUTEXES
3641 * rt_mutex_setprio - set the current priority of a task
3643 * @prio: prio value (kernel-internal form)
3645 * This function changes the 'effective' priority of a task. It does
3646 * not touch ->normal_prio like __setscheduler().
3648 * Used by the rt_mutex code to implement priority inheritance
3649 * logic. Call site only calls if the priority of the task changed.
3651 void rt_mutex_setprio(struct task_struct *p, int prio)
3653 int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
3654 const struct sched_class *prev_class;
3658 BUG_ON(prio > MAX_PRIO);
3660 rq = __task_rq_lock(p, &rf);
3661 update_rq_clock(rq);
3664 * Idle task boosting is a nono in general. There is one
3665 * exception, when PREEMPT_RT and NOHZ is active:
3667 * The idle task calls get_next_timer_interrupt() and holds
3668 * the timer wheel base->lock on the CPU and another CPU wants
3669 * to access the timer (probably to cancel it). We can safely
3670 * ignore the boosting request, as the idle CPU runs this code
3671 * with interrupts disabled and will complete the lock
3672 * protected section without being interrupted. So there is no
3673 * real need to boost.
3675 if (unlikely(p == rq->idle)) {
3676 WARN_ON(p != rq->curr);
3677 WARN_ON(p->pi_blocked_on);
3681 trace_sched_pi_setprio(p, prio);
3684 if (oldprio == prio)
3685 queue_flag &= ~DEQUEUE_MOVE;
3687 prev_class = p->sched_class;
3688 queued = task_on_rq_queued(p);
3689 running = task_current(rq, p);
3691 dequeue_task(rq, p, queue_flag);
3693 put_prev_task(rq, p);
3696 * Boosting condition are:
3697 * 1. -rt task is running and holds mutex A
3698 * --> -dl task blocks on mutex A
3700 * 2. -dl task is running and holds mutex A
3701 * --> -dl task blocks on mutex A and could preempt the
3704 if (dl_prio(prio)) {
3705 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3706 if (!dl_prio(p->normal_prio) ||
3707 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3708 p->dl.dl_boosted = 1;
3709 queue_flag |= ENQUEUE_REPLENISH;
3711 p->dl.dl_boosted = 0;
3712 p->sched_class = &dl_sched_class;
3713 } else if (rt_prio(prio)) {
3714 if (dl_prio(oldprio))
3715 p->dl.dl_boosted = 0;
3717 queue_flag |= ENQUEUE_HEAD;
3718 p->sched_class = &rt_sched_class;
3720 if (dl_prio(oldprio))
3721 p->dl.dl_boosted = 0;
3722 if (rt_prio(oldprio))
3724 p->sched_class = &fair_sched_class;
3730 enqueue_task(rq, p, queue_flag);
3732 set_curr_task(rq, p);
3734 check_class_changed(rq, p, prev_class, oldprio);
3736 preempt_disable(); /* avoid rq from going away on us */
3737 __task_rq_unlock(rq, &rf);
3739 balance_callback(rq);
3744 void set_user_nice(struct task_struct *p, long nice)
3746 bool queued, running;
3747 int old_prio, delta;
3751 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3754 * We have to be careful, if called from sys_setpriority(),
3755 * the task might be in the middle of scheduling on another CPU.
3757 rq = task_rq_lock(p, &rf);
3758 update_rq_clock(rq);
3761 * The RT priorities are set via sched_setscheduler(), but we still
3762 * allow the 'normal' nice value to be set - but as expected
3763 * it wont have any effect on scheduling until the task is
3764 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3766 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3767 p->static_prio = NICE_TO_PRIO(nice);
3770 queued = task_on_rq_queued(p);
3771 running = task_current(rq, p);
3773 dequeue_task(rq, p, DEQUEUE_SAVE);
3775 put_prev_task(rq, p);
3777 p->static_prio = NICE_TO_PRIO(nice);
3780 p->prio = effective_prio(p);
3781 delta = p->prio - old_prio;
3784 enqueue_task(rq, p, ENQUEUE_RESTORE);
3786 * If the task increased its priority or is running and
3787 * lowered its priority, then reschedule its CPU:
3789 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3793 set_curr_task(rq, p);
3795 task_rq_unlock(rq, p, &rf);
3797 EXPORT_SYMBOL(set_user_nice);
3800 * can_nice - check if a task can reduce its nice value
3804 int can_nice(const struct task_struct *p, const int nice)
3806 /* convert nice value [19,-20] to rlimit style value [1,40] */
3807 int nice_rlim = nice_to_rlimit(nice);
3809 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3810 capable(CAP_SYS_NICE));
3813 #ifdef __ARCH_WANT_SYS_NICE
3816 * sys_nice - change the priority of the current process.
3817 * @increment: priority increment
3819 * sys_setpriority is a more generic, but much slower function that
3820 * does similar things.
3822 SYSCALL_DEFINE1(nice, int, increment)
3827 * Setpriority might change our priority at the same moment.
3828 * We don't have to worry. Conceptually one call occurs first
3829 * and we have a single winner.
3831 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3832 nice = task_nice(current) + increment;
3834 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3835 if (increment < 0 && !can_nice(current, nice))
3838 retval = security_task_setnice(current, nice);
3842 set_user_nice(current, nice);
3849 * task_prio - return the priority value of a given task.
3850 * @p: the task in question.
3852 * Return: The priority value as seen by users in /proc.
3853 * RT tasks are offset by -200. Normal tasks are centered
3854 * around 0, value goes from -16 to +15.
3856 int task_prio(const struct task_struct *p)
3858 return p->prio - MAX_RT_PRIO;
3862 * idle_cpu - is a given cpu idle currently?
3863 * @cpu: the processor in question.
3865 * Return: 1 if the CPU is currently idle. 0 otherwise.
3867 int idle_cpu(int cpu)
3869 struct rq *rq = cpu_rq(cpu);
3871 if (rq->curr != rq->idle)
3878 if (!llist_empty(&rq->wake_list))
3886 * idle_task - return the idle task for a given cpu.
3887 * @cpu: the processor in question.
3889 * Return: The idle task for the cpu @cpu.
3891 struct task_struct *idle_task(int cpu)
3893 return cpu_rq(cpu)->idle;
3897 * find_process_by_pid - find a process with a matching PID value.
3898 * @pid: the pid in question.
3900 * The task of @pid, if found. %NULL otherwise.
3902 static struct task_struct *find_process_by_pid(pid_t pid)
3904 return pid ? find_task_by_vpid(pid) : current;
3908 * This function initializes the sched_dl_entity of a newly becoming
3909 * SCHED_DEADLINE task.
3911 * Only the static values are considered here, the actual runtime and the
3912 * absolute deadline will be properly calculated when the task is enqueued
3913 * for the first time with its new policy.
3916 __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
3918 struct sched_dl_entity *dl_se = &p->dl;
3920 dl_se->dl_runtime = attr->sched_runtime;
3921 dl_se->dl_deadline = attr->sched_deadline;
3922 dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
3923 dl_se->flags = attr->sched_flags;
3924 dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
3927 * Changing the parameters of a task is 'tricky' and we're not doing
3928 * the correct thing -- also see task_dead_dl() and switched_from_dl().
3930 * What we SHOULD do is delay the bandwidth release until the 0-lag
3931 * point. This would include retaining the task_struct until that time
3932 * and change dl_overflow() to not immediately decrement the current
3935 * Instead we retain the current runtime/deadline and let the new
3936 * parameters take effect after the current reservation period lapses.
3937 * This is safe (albeit pessimistic) because the 0-lag point is always
3938 * before the current scheduling deadline.
3940 * We can still have temporary overloads because we do not delay the
3941 * change in bandwidth until that time; so admission control is
3942 * not on the safe side. It does however guarantee tasks will never
3943 * consume more than promised.
3948 * sched_setparam() passes in -1 for its policy, to let the functions
3949 * it calls know not to change it.
3951 #define SETPARAM_POLICY -1
3953 static void __setscheduler_params(struct task_struct *p,
3954 const struct sched_attr *attr)
3956 int policy = attr->sched_policy;
3958 if (policy == SETPARAM_POLICY)
3963 if (dl_policy(policy))
3964 __setparam_dl(p, attr);
3965 else if (fair_policy(policy))
3966 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
3969 * __sched_setscheduler() ensures attr->sched_priority == 0 when
3970 * !rt_policy. Always setting this ensures that things like
3971 * getparam()/getattr() don't report silly values for !rt tasks.
3973 p->rt_priority = attr->sched_priority;
3974 p->normal_prio = normal_prio(p);
3978 /* Actually do priority change: must hold pi & rq lock. */
3979 static void __setscheduler(struct rq *rq, struct task_struct *p,
3980 const struct sched_attr *attr, bool keep_boost)
3982 __setscheduler_params(p, attr);
3985 * Keep a potential priority boosting if called from
3986 * sched_setscheduler().
3989 p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
3991 p->prio = normal_prio(p);
3993 if (dl_prio(p->prio))
3994 p->sched_class = &dl_sched_class;
3995 else if (rt_prio(p->prio))
3996 p->sched_class = &rt_sched_class;
3998 p->sched_class = &fair_sched_class;
4002 __getparam_dl(struct task_struct *p, struct sched_attr *attr)
4004 struct sched_dl_entity *dl_se = &p->dl;
4006 attr->sched_priority = p->rt_priority;
4007 attr->sched_runtime = dl_se->dl_runtime;
4008 attr->sched_deadline = dl_se->dl_deadline;
4009 attr->sched_period = dl_se->dl_period;
4010 attr->sched_flags = dl_se->flags;
4014 * This function validates the new parameters of a -deadline task.
4015 * We ask for the deadline not being zero, and greater or equal
4016 * than the runtime, as well as the period of being zero or
4017 * greater than deadline. Furthermore, we have to be sure that
4018 * user parameters are above the internal resolution of 1us (we
4019 * check sched_runtime only since it is always the smaller one) and
4020 * below 2^63 ns (we have to check both sched_deadline and
4021 * sched_period, as the latter can be zero).
4024 __checkparam_dl(const struct sched_attr *attr)
4027 if (attr->sched_deadline == 0)
4031 * Since we truncate DL_SCALE bits, make sure we're at least
4034 if (attr->sched_runtime < (1ULL << DL_SCALE))
4038 * Since we use the MSB for wrap-around and sign issues, make
4039 * sure it's not set (mind that period can be equal to zero).
4041 if (attr->sched_deadline & (1ULL << 63) ||
4042 attr->sched_period & (1ULL << 63))
4045 /* runtime <= deadline <= period (if period != 0) */
4046 if ((attr->sched_period != 0 &&
4047 attr->sched_period < attr->sched_deadline) ||
4048 attr->sched_deadline < attr->sched_runtime)
4055 * check the target process has a UID that matches the current process's
4057 static bool check_same_owner(struct task_struct *p)
4059 const struct cred *cred = current_cred(), *pcred;
4063 pcred = __task_cred(p);
4064 match = (uid_eq(cred->euid, pcred->euid) ||
4065 uid_eq(cred->euid, pcred->uid));
4070 static bool dl_param_changed(struct task_struct *p,
4071 const struct sched_attr *attr)
4073 struct sched_dl_entity *dl_se = &p->dl;
4075 if (dl_se->dl_runtime != attr->sched_runtime ||
4076 dl_se->dl_deadline != attr->sched_deadline ||
4077 dl_se->dl_period != attr->sched_period ||
4078 dl_se->flags != attr->sched_flags)
4084 static int __sched_setscheduler(struct task_struct *p,
4085 const struct sched_attr *attr,
4088 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4089 MAX_RT_PRIO - 1 - attr->sched_priority;
4090 int retval, oldprio, oldpolicy = -1, queued, running;
4091 int new_effective_prio, policy = attr->sched_policy;
4092 const struct sched_class *prev_class;
4095 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
4098 /* may grab non-irq protected spin_locks */
4099 BUG_ON(in_interrupt());
4101 /* double check policy once rq lock held */
4103 reset_on_fork = p->sched_reset_on_fork;
4104 policy = oldpolicy = p->policy;
4106 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4108 if (!valid_policy(policy))
4112 if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
4116 * Valid priorities for SCHED_FIFO and SCHED_RR are
4117 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4118 * SCHED_BATCH and SCHED_IDLE is 0.
4120 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4121 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4123 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4124 (rt_policy(policy) != (attr->sched_priority != 0)))
4128 * Allow unprivileged RT tasks to decrease priority:
4130 if (user && !capable(CAP_SYS_NICE)) {
4131 if (fair_policy(policy)) {
4132 if (attr->sched_nice < task_nice(p) &&
4133 !can_nice(p, attr->sched_nice))
4137 if (rt_policy(policy)) {
4138 unsigned long rlim_rtprio =
4139 task_rlimit(p, RLIMIT_RTPRIO);
4141 /* can't set/change the rt policy */
4142 if (policy != p->policy && !rlim_rtprio)
4145 /* can't increase priority */
4146 if (attr->sched_priority > p->rt_priority &&
4147 attr->sched_priority > rlim_rtprio)
4152 * Can't set/change SCHED_DEADLINE policy at all for now
4153 * (safest behavior); in the future we would like to allow
4154 * unprivileged DL tasks to increase their relative deadline
4155 * or reduce their runtime (both ways reducing utilization)
4157 if (dl_policy(policy))
4161 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4162 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4164 if (idle_policy(p->policy) && !idle_policy(policy)) {
4165 if (!can_nice(p, task_nice(p)))
4169 /* can't change other user's priorities */
4170 if (!check_same_owner(p))
4173 /* Normal users shall not reset the sched_reset_on_fork flag */
4174 if (p->sched_reset_on_fork && !reset_on_fork)
4179 retval = security_task_setscheduler(p);
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);
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))
4209 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4211 if (dl_policy(policy) && dl_param_changed(p, attr))
4214 p->sched_reset_on_fork = reset_on_fork;
4215 task_rq_unlock(rq, p, &rf);
4221 #ifdef CONFIG_RT_GROUP_SCHED
4223 * Do not allow realtime tasks into groups that have no runtime
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);
4234 if (dl_bandwidth_enabled() && dl_policy(policy)) {
4235 cpumask_t *span = rq->rd->span;
4238 * Don't allow tasks with an affinity mask smaller than
4239 * the entire root_domain to become SCHED_DEADLINE. We
4240 * will also fail if there's no bandwidth available.
4242 if (!cpumask_subset(span, &p->cpus_allowed) ||
4243 rq->rd->dl_bw.bw == 0) {
4244 task_rq_unlock(rq, p, &rf);
4251 /* recheck policy now with rq lock held */
4252 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4253 policy = oldpolicy = -1;
4254 task_rq_unlock(rq, p, &rf);
4259 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4260 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4263 if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
4264 task_rq_unlock(rq, p, &rf);
4268 p->sched_reset_on_fork = reset_on_fork;
4273 * Take priority boosted tasks into account. If the new
4274 * effective priority is unchanged, we just store the new
4275 * normal parameters and do not touch the scheduler class and
4276 * the runqueue. This will be done when the task deboost
4279 new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
4280 if (new_effective_prio == oldprio)
4281 queue_flags &= ~DEQUEUE_MOVE;
4284 queued = task_on_rq_queued(p);
4285 running = task_current(rq, p);
4287 dequeue_task(rq, p, queue_flags);
4289 put_prev_task(rq, p);
4291 prev_class = p->sched_class;
4292 __setscheduler(rq, p, attr, pi);
4296 * We enqueue to tail when the priority of a task is
4297 * increased (user space view).
4299 if (oldprio < p->prio)
4300 queue_flags |= ENQUEUE_HEAD;
4302 enqueue_task(rq, p, queue_flags);
4305 set_curr_task(rq, p);
4307 check_class_changed(rq, p, prev_class, oldprio);
4308 preempt_disable(); /* avoid rq from going away on us */
4309 task_rq_unlock(rq, p, &rf);
4312 rt_mutex_adjust_pi(p);
4315 * Run balance callbacks after we've adjusted the PI chain.
4317 balance_callback(rq);
4323 static int _sched_setscheduler(struct task_struct *p, int policy,
4324 const struct sched_param *param, bool check)
4326 struct sched_attr attr = {
4327 .sched_policy = policy,
4328 .sched_priority = param->sched_priority,
4329 .sched_nice = PRIO_TO_NICE(p->static_prio),
4332 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4333 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4334 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4335 policy &= ~SCHED_RESET_ON_FORK;
4336 attr.sched_policy = policy;
4339 return __sched_setscheduler(p, &attr, check, true);
4342 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4343 * @p: the task in question.
4344 * @policy: new policy.
4345 * @param: structure containing the new RT priority.
4347 * Return: 0 on success. An error code otherwise.
4349 * NOTE that the task may be already dead.
4351 int sched_setscheduler(struct task_struct *p, int policy,
4352 const struct sched_param *param)
4354 return _sched_setscheduler(p, policy, param, true);
4356 EXPORT_SYMBOL_GPL(sched_setscheduler);
4358 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4360 return __sched_setscheduler(p, attr, true, true);
4362 EXPORT_SYMBOL_GPL(sched_setattr);
4365 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4366 * @p: the task in question.
4367 * @policy: new policy.
4368 * @param: structure containing the new RT priority.
4370 * Just like sched_setscheduler, only don't bother checking if the
4371 * current context has permission. For example, this is needed in
4372 * stop_machine(): we create temporary high priority worker threads,
4373 * but our caller might not have that capability.
4375 * Return: 0 on success. An error code otherwise.
4377 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4378 const struct sched_param *param)
4380 return _sched_setscheduler(p, policy, param, false);
4382 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4385 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4387 struct sched_param lparam;
4388 struct task_struct *p;
4391 if (!param || pid < 0)
4393 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4398 p = find_process_by_pid(pid);
4400 retval = sched_setscheduler(p, policy, &lparam);
4407 * Mimics kernel/events/core.c perf_copy_attr().
4409 static int sched_copy_attr(struct sched_attr __user *uattr,
4410 struct sched_attr *attr)
4415 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4419 * zero the full structure, so that a short copy will be nice.
4421 memset(attr, 0, sizeof(*attr));
4423 ret = get_user(size, &uattr->size);
4427 if (size > PAGE_SIZE) /* silly large */
4430 if (!size) /* abi compat */
4431 size = SCHED_ATTR_SIZE_VER0;
4433 if (size < SCHED_ATTR_SIZE_VER0)
4437 * If we're handed a bigger struct than we know of,
4438 * ensure all the unknown bits are 0 - i.e. new
4439 * user-space does not rely on any kernel feature
4440 * extensions we dont know about yet.
4442 if (size > sizeof(*attr)) {
4443 unsigned char __user *addr;
4444 unsigned char __user *end;
4447 addr = (void __user *)uattr + sizeof(*attr);
4448 end = (void __user *)uattr + size;
4450 for (; addr < end; addr++) {
4451 ret = get_user(val, addr);
4457 size = sizeof(*attr);
4460 ret = copy_from_user(attr, uattr, size);
4465 * XXX: do we want to be lenient like existing syscalls; or do we want
4466 * to be strict and return an error on out-of-bounds values?
4468 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4473 put_user(sizeof(*attr), &uattr->size);
4478 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4479 * @pid: the pid in question.
4480 * @policy: new policy.
4481 * @param: structure containing the new RT priority.
4483 * Return: 0 on success. An error code otherwise.
4485 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4486 struct sched_param __user *, param)
4488 /* negative values for policy are not valid */
4492 return do_sched_setscheduler(pid, policy, param);
4496 * sys_sched_setparam - set/change the RT priority of a thread
4497 * @pid: the pid in question.
4498 * @param: structure containing the new RT priority.
4500 * Return: 0 on success. An error code otherwise.
4502 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4504 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4508 * sys_sched_setattr - same as above, but with extended sched_attr
4509 * @pid: the pid in question.
4510 * @uattr: structure containing the extended parameters.
4511 * @flags: for future extension.
4513 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4514 unsigned int, flags)
4516 struct sched_attr attr;
4517 struct task_struct *p;
4520 if (!uattr || pid < 0 || flags)
4523 retval = sched_copy_attr(uattr, &attr);
4527 if ((int)attr.sched_policy < 0)
4532 p = find_process_by_pid(pid);
4534 retval = sched_setattr(p, &attr);
4541 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4542 * @pid: the pid in question.
4544 * Return: On success, the policy of the thread. Otherwise, a negative error
4547 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4549 struct task_struct *p;
4557 p = find_process_by_pid(pid);
4559 retval = security_task_getscheduler(p);
4562 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4569 * sys_sched_getparam - get the RT priority of a thread
4570 * @pid: the pid in question.
4571 * @param: structure containing the RT priority.
4573 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4576 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4578 struct sched_param lp = { .sched_priority = 0 };
4579 struct task_struct *p;
4582 if (!param || pid < 0)
4586 p = find_process_by_pid(pid);
4591 retval = security_task_getscheduler(p);
4595 if (task_has_rt_policy(p))
4596 lp.sched_priority = p->rt_priority;
4600 * This one might sleep, we cannot do it with a spinlock held ...
4602 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4611 static int sched_read_attr(struct sched_attr __user *uattr,
4612 struct sched_attr *attr,
4617 if (!access_ok(VERIFY_WRITE, uattr, usize))
4621 * If we're handed a smaller struct than we know of,
4622 * ensure all the unknown bits are 0 - i.e. old
4623 * user-space does not get uncomplete information.
4625 if (usize < sizeof(*attr)) {
4626 unsigned char *addr;
4629 addr = (void *)attr + usize;
4630 end = (void *)attr + sizeof(*attr);
4632 for (; addr < end; addr++) {
4640 ret = copy_to_user(uattr, attr, attr->size);
4648 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4649 * @pid: the pid in question.
4650 * @uattr: structure containing the extended parameters.
4651 * @size: sizeof(attr) for fwd/bwd comp.
4652 * @flags: for future extension.
4654 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4655 unsigned int, size, unsigned int, flags)
4657 struct sched_attr attr = {
4658 .size = sizeof(struct sched_attr),
4660 struct task_struct *p;
4663 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4664 size < SCHED_ATTR_SIZE_VER0 || flags)
4668 p = find_process_by_pid(pid);
4673 retval = security_task_getscheduler(p);
4677 attr.sched_policy = p->policy;
4678 if (p->sched_reset_on_fork)
4679 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4680 if (task_has_dl_policy(p))
4681 __getparam_dl(p, &attr);
4682 else if (task_has_rt_policy(p))
4683 attr.sched_priority = p->rt_priority;
4685 attr.sched_nice = task_nice(p);
4689 retval = sched_read_attr(uattr, &attr, size);
4697 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4699 cpumask_var_t cpus_allowed, new_mask;
4700 struct task_struct *p;
4705 p = find_process_by_pid(pid);
4711 /* Prevent p going away */
4715 if (p->flags & PF_NO_SETAFFINITY) {
4719 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4723 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4725 goto out_free_cpus_allowed;
4728 if (!check_same_owner(p)) {
4730 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4732 goto out_free_new_mask;
4737 retval = security_task_setscheduler(p);
4739 goto out_free_new_mask;
4742 cpuset_cpus_allowed(p, cpus_allowed);
4743 cpumask_and(new_mask, in_mask, cpus_allowed);
4746 * Since bandwidth control happens on root_domain basis,
4747 * if admission test is enabled, we only admit -deadline
4748 * tasks allowed to run on all the CPUs in the task's
4752 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4754 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4757 goto out_free_new_mask;
4763 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4766 cpuset_cpus_allowed(p, cpus_allowed);
4767 if (!cpumask_subset(new_mask, cpus_allowed)) {
4769 * We must have raced with a concurrent cpuset
4770 * update. Just reset the cpus_allowed to the
4771 * cpuset's cpus_allowed
4773 cpumask_copy(new_mask, cpus_allowed);
4778 free_cpumask_var(new_mask);
4779 out_free_cpus_allowed:
4780 free_cpumask_var(cpus_allowed);
4786 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4787 struct cpumask *new_mask)
4789 if (len < cpumask_size())
4790 cpumask_clear(new_mask);
4791 else if (len > cpumask_size())
4792 len = cpumask_size();
4794 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4798 * sys_sched_setaffinity - set the cpu affinity of a process
4799 * @pid: pid of the process
4800 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4801 * @user_mask_ptr: user-space pointer to the new cpu mask
4803 * Return: 0 on success. An error code otherwise.
4805 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4806 unsigned long __user *, user_mask_ptr)
4808 cpumask_var_t new_mask;
4811 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4814 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4816 retval = sched_setaffinity(pid, new_mask);
4817 free_cpumask_var(new_mask);
4821 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4823 struct task_struct *p;
4824 unsigned long flags;
4830 p = find_process_by_pid(pid);
4834 retval = security_task_getscheduler(p);
4838 raw_spin_lock_irqsave(&p->pi_lock, flags);
4839 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4840 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4849 * sys_sched_getaffinity - get the cpu affinity of a process
4850 * @pid: pid of the process
4851 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4852 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4854 * Return: size of CPU mask copied to user_mask_ptr on success. An
4855 * error code otherwise.
4857 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4858 unsigned long __user *, user_mask_ptr)
4863 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4865 if (len & (sizeof(unsigned long)-1))
4868 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4871 ret = sched_getaffinity(pid, mask);
4873 size_t retlen = min_t(size_t, len, cpumask_size());
4875 if (copy_to_user(user_mask_ptr, mask, retlen))
4880 free_cpumask_var(mask);
4886 * sys_sched_yield - yield the current processor to other threads.
4888 * This function yields the current CPU to other tasks. If there are no
4889 * other threads running on this CPU then this function will return.
4893 SYSCALL_DEFINE0(sched_yield)
4895 struct rq *rq = this_rq_lock();
4897 schedstat_inc(rq->yld_count);
4898 current->sched_class->yield_task(rq);
4901 * Since we are going to call schedule() anyway, there's
4902 * no need to preempt or enable interrupts:
4904 __release(rq->lock);
4905 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4906 do_raw_spin_unlock(&rq->lock);
4907 sched_preempt_enable_no_resched();
4914 #ifndef CONFIG_PREEMPT
4915 int __sched _cond_resched(void)
4917 if (should_resched(0)) {
4918 preempt_schedule_common();
4923 EXPORT_SYMBOL(_cond_resched);
4927 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4928 * call schedule, and on return reacquire the lock.
4930 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4931 * operations here to prevent schedule() from being called twice (once via
4932 * spin_unlock(), once by hand).
4934 int __cond_resched_lock(spinlock_t *lock)
4936 int resched = should_resched(PREEMPT_LOCK_OFFSET);
4939 lockdep_assert_held(lock);
4941 if (spin_needbreak(lock) || resched) {
4944 preempt_schedule_common();
4952 EXPORT_SYMBOL(__cond_resched_lock);
4954 int __sched __cond_resched_softirq(void)
4956 BUG_ON(!in_softirq());
4958 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
4960 preempt_schedule_common();
4966 EXPORT_SYMBOL(__cond_resched_softirq);
4969 * yield - yield the current processor to other threads.
4971 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4973 * The scheduler is at all times free to pick the calling task as the most
4974 * eligible task to run, if removing the yield() call from your code breaks
4975 * it, its already broken.
4977 * Typical broken usage is:
4982 * where one assumes that yield() will let 'the other' process run that will
4983 * make event true. If the current task is a SCHED_FIFO task that will never
4984 * happen. Never use yield() as a progress guarantee!!
4986 * If you want to use yield() to wait for something, use wait_event().
4987 * If you want to use yield() to be 'nice' for others, use cond_resched().
4988 * If you still want to use yield(), do not!
4990 void __sched yield(void)
4992 set_current_state(TASK_RUNNING);
4995 EXPORT_SYMBOL(yield);
4998 * yield_to - yield the current processor to another thread in
4999 * your thread group, or accelerate that thread toward the
5000 * processor it's on.
5002 * @preempt: whether task preemption is allowed or not
5004 * It's the caller's job to ensure that the target task struct
5005 * can't go away on us before we can do any checks.
5008 * true (>0) if we indeed boosted the target task.
5009 * false (0) if we failed to boost the target.
5010 * -ESRCH if there's no task to yield to.
5012 int __sched yield_to(struct task_struct *p, bool preempt)
5014 struct task_struct *curr = current;
5015 struct rq *rq, *p_rq;
5016 unsigned long flags;
5019 local_irq_save(flags);
5025 * If we're the only runnable task on the rq and target rq also
5026 * has only one task, there's absolutely no point in yielding.
5028 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5033 double_rq_lock(rq, p_rq);
5034 if (task_rq(p) != p_rq) {
5035 double_rq_unlock(rq, p_rq);
5039 if (!curr->sched_class->yield_to_task)
5042 if (curr->sched_class != p->sched_class)
5045 if (task_running(p_rq, p) || p->state)
5048 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5050 schedstat_inc(rq->yld_count);
5052 * Make p's CPU reschedule; pick_next_entity takes care of
5055 if (preempt && rq != p_rq)
5060 double_rq_unlock(rq, p_rq);
5062 local_irq_restore(flags);
5069 EXPORT_SYMBOL_GPL(yield_to);
5072 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5073 * that process accounting knows that this is a task in IO wait state.
5075 long __sched io_schedule_timeout(long timeout)
5077 int old_iowait = current->in_iowait;
5081 current->in_iowait = 1;
5082 blk_schedule_flush_plug(current);
5084 delayacct_blkio_start();
5086 atomic_inc(&rq->nr_iowait);
5087 ret = schedule_timeout(timeout);
5088 current->in_iowait = old_iowait;
5089 atomic_dec(&rq->nr_iowait);
5090 delayacct_blkio_end();
5094 EXPORT_SYMBOL(io_schedule_timeout);
5097 * sys_sched_get_priority_max - return maximum RT priority.
5098 * @policy: scheduling class.
5100 * Return: On success, this syscall returns the maximum
5101 * rt_priority that can be used by a given scheduling class.
5102 * On failure, a negative error code is returned.
5104 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5111 ret = MAX_USER_RT_PRIO-1;
5113 case SCHED_DEADLINE:
5124 * sys_sched_get_priority_min - return minimum RT priority.
5125 * @policy: scheduling class.
5127 * Return: On success, this syscall returns the minimum
5128 * rt_priority that can be used by a given scheduling class.
5129 * On failure, a negative error code is returned.
5131 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5140 case SCHED_DEADLINE:
5150 * sys_sched_rr_get_interval - return the default timeslice of a process.
5151 * @pid: pid of the process.
5152 * @interval: userspace pointer to the timeslice value.
5154 * this syscall writes the default timeslice value of a given process
5155 * into the user-space timespec buffer. A value of '0' means infinity.
5157 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5160 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5161 struct timespec __user *, interval)
5163 struct task_struct *p;
5164 unsigned int time_slice;
5175 p = find_process_by_pid(pid);
5179 retval = security_task_getscheduler(p);
5183 rq = task_rq_lock(p, &rf);
5185 if (p->sched_class->get_rr_interval)
5186 time_slice = p->sched_class->get_rr_interval(rq, p);
5187 task_rq_unlock(rq, p, &rf);
5190 jiffies_to_timespec(time_slice, &t);
5191 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5199 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5201 void sched_show_task(struct task_struct *p)
5203 unsigned long free = 0;
5205 unsigned long state = p->state;
5207 if (!try_get_task_stack(p))
5210 state = __ffs(state) + 1;
5211 printk(KERN_INFO "%-15.15s %c", p->comm,
5212 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5213 if (state == TASK_RUNNING)
5214 printk(KERN_CONT " running task ");
5215 #ifdef CONFIG_DEBUG_STACK_USAGE
5216 free = stack_not_used(p);
5221 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5223 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5224 task_pid_nr(p), ppid,
5225 (unsigned long)task_thread_info(p)->flags);
5227 print_worker_info(KERN_INFO, p);
5228 show_stack(p, NULL);
5232 void show_state_filter(unsigned long state_filter)
5234 struct task_struct *g, *p;
5236 #if BITS_PER_LONG == 32
5238 " task PC stack pid father\n");
5241 " task PC stack pid father\n");
5244 for_each_process_thread(g, p) {
5246 * reset the NMI-timeout, listing all files on a slow
5247 * console might take a lot of time:
5248 * Also, reset softlockup watchdogs on all CPUs, because
5249 * another CPU might be blocked waiting for us to process
5252 touch_nmi_watchdog();
5253 touch_all_softlockup_watchdogs();
5254 if (!state_filter || (p->state & state_filter))
5258 #ifdef CONFIG_SCHED_DEBUG
5260 sysrq_sched_debug_show();
5264 * Only show locks if all tasks are dumped:
5267 debug_show_all_locks();
5270 void init_idle_bootup_task(struct task_struct *idle)
5272 idle->sched_class = &idle_sched_class;
5276 * init_idle - set up an idle thread for a given CPU
5277 * @idle: task in question
5278 * @cpu: cpu the idle task belongs to
5280 * NOTE: this function does not set the idle thread's NEED_RESCHED
5281 * flag, to make booting more robust.
5283 void init_idle(struct task_struct *idle, int cpu)
5285 struct rq *rq = cpu_rq(cpu);
5286 unsigned long flags;
5288 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5289 raw_spin_lock(&rq->lock);
5291 __sched_fork(0, idle);
5292 idle->state = TASK_RUNNING;
5293 idle->se.exec_start = sched_clock();
5294 idle->flags |= PF_IDLE;
5296 kasan_unpoison_task_stack(idle);
5300 * Its possible that init_idle() gets called multiple times on a task,
5301 * in that case do_set_cpus_allowed() will not do the right thing.
5303 * And since this is boot we can forgo the serialization.
5305 set_cpus_allowed_common(idle, cpumask_of(cpu));
5308 * We're having a chicken and egg problem, even though we are
5309 * holding rq->lock, the cpu isn't yet set to this cpu so the
5310 * lockdep check in task_group() will fail.
5312 * Similar case to sched_fork(). / Alternatively we could
5313 * use task_rq_lock() here and obtain the other rq->lock.
5318 __set_task_cpu(idle, cpu);
5321 rq->curr = rq->idle = idle;
5322 idle->on_rq = TASK_ON_RQ_QUEUED;
5326 raw_spin_unlock(&rq->lock);
5327 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5329 /* Set the preempt count _outside_ the spinlocks! */
5330 init_idle_preempt_count(idle, cpu);
5333 * The idle tasks have their own, simple scheduling class:
5335 idle->sched_class = &idle_sched_class;
5336 ftrace_graph_init_idle_task(idle, cpu);
5337 vtime_init_idle(idle, cpu);
5339 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5343 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5344 const struct cpumask *trial)
5346 int ret = 1, trial_cpus;
5347 struct dl_bw *cur_dl_b;
5348 unsigned long flags;
5350 if (!cpumask_weight(cur))
5353 rcu_read_lock_sched();
5354 cur_dl_b = dl_bw_of(cpumask_any(cur));
5355 trial_cpus = cpumask_weight(trial);
5357 raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
5358 if (cur_dl_b->bw != -1 &&
5359 cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
5361 raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
5362 rcu_read_unlock_sched();
5367 int task_can_attach(struct task_struct *p,
5368 const struct cpumask *cs_cpus_allowed)
5373 * Kthreads which disallow setaffinity shouldn't be moved
5374 * to a new cpuset; we don't want to change their cpu
5375 * affinity and isolating such threads by their set of
5376 * allowed nodes is unnecessary. Thus, cpusets are not
5377 * applicable for such threads. This prevents checking for
5378 * success of set_cpus_allowed_ptr() on all attached tasks
5379 * before cpus_allowed may be changed.
5381 if (p->flags & PF_NO_SETAFFINITY) {
5387 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5389 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
5394 unsigned long flags;
5396 rcu_read_lock_sched();
5397 dl_b = dl_bw_of(dest_cpu);
5398 raw_spin_lock_irqsave(&dl_b->lock, flags);
5399 cpus = dl_bw_cpus(dest_cpu);
5400 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
5405 * We reserve space for this task in the destination
5406 * root_domain, as we can't fail after this point.
5407 * We will free resources in the source root_domain
5408 * later on (see set_cpus_allowed_dl()).
5410 __dl_add(dl_b, p->dl.dl_bw);
5412 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5413 rcu_read_unlock_sched();
5423 static bool sched_smp_initialized __read_mostly;
5425 #ifdef CONFIG_NUMA_BALANCING
5426 /* Migrate current task p to target_cpu */
5427 int migrate_task_to(struct task_struct *p, int target_cpu)
5429 struct migration_arg arg = { p, target_cpu };
5430 int curr_cpu = task_cpu(p);
5432 if (curr_cpu == target_cpu)
5435 if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
5438 /* TODO: This is not properly updating schedstats */
5440 trace_sched_move_numa(p, curr_cpu, target_cpu);
5441 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5445 * Requeue a task on a given node and accurately track the number of NUMA
5446 * tasks on the runqueues
5448 void sched_setnuma(struct task_struct *p, int nid)
5450 bool queued, running;
5454 rq = task_rq_lock(p, &rf);
5455 queued = task_on_rq_queued(p);
5456 running = task_current(rq, p);
5459 dequeue_task(rq, p, DEQUEUE_SAVE);
5461 put_prev_task(rq, p);
5463 p->numa_preferred_nid = nid;
5466 enqueue_task(rq, p, ENQUEUE_RESTORE);
5468 set_curr_task(rq, p);
5469 task_rq_unlock(rq, p, &rf);
5471 #endif /* CONFIG_NUMA_BALANCING */
5473 #ifdef CONFIG_HOTPLUG_CPU
5475 * Ensures that the idle task is using init_mm right before its cpu goes
5478 void idle_task_exit(void)
5480 struct mm_struct *mm = current->active_mm;
5482 BUG_ON(cpu_online(smp_processor_id()));
5484 if (mm != &init_mm) {
5485 switch_mm_irqs_off(mm, &init_mm, current);
5486 finish_arch_post_lock_switch();
5492 * Since this CPU is going 'away' for a while, fold any nr_active delta
5493 * we might have. Assumes we're called after migrate_tasks() so that the
5494 * nr_active count is stable. We need to take the teardown thread which
5495 * is calling this into account, so we hand in adjust = 1 to the load
5498 * Also see the comment "Global load-average calculations".
5500 static void calc_load_migrate(struct rq *rq)
5502 long delta = calc_load_fold_active(rq, 1);
5504 atomic_long_add(delta, &calc_load_tasks);
5507 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5511 static const struct sched_class fake_sched_class = {
5512 .put_prev_task = put_prev_task_fake,
5515 static struct task_struct fake_task = {
5517 * Avoid pull_{rt,dl}_task()
5519 .prio = MAX_PRIO + 1,
5520 .sched_class = &fake_sched_class,
5524 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5525 * try_to_wake_up()->select_task_rq().
5527 * Called with rq->lock held even though we'er in stop_machine() and
5528 * there's no concurrency possible, we hold the required locks anyway
5529 * because of lock validation efforts.
5531 static void migrate_tasks(struct rq *dead_rq)
5533 struct rq *rq = dead_rq;
5534 struct task_struct *next, *stop = rq->stop;
5539 * Fudge the rq selection such that the below task selection loop
5540 * doesn't get stuck on the currently eligible stop task.
5542 * We're currently inside stop_machine() and the rq is either stuck
5543 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5544 * either way we should never end up calling schedule() until we're
5550 * put_prev_task() and pick_next_task() sched
5551 * class method both need to have an up-to-date
5552 * value of rq->clock[_task]
5554 update_rq_clock(rq);
5558 * There's this thread running, bail when that's the only
5561 if (rq->nr_running == 1)
5565 * pick_next_task assumes pinned rq->lock.
5567 rq_pin_lock(rq, &rf);
5568 next = pick_next_task(rq, &fake_task, &rf);
5570 next->sched_class->put_prev_task(rq, next);
5573 * Rules for changing task_struct::cpus_allowed are holding
5574 * both pi_lock and rq->lock, such that holding either
5575 * stabilizes the mask.
5577 * Drop rq->lock is not quite as disastrous as it usually is
5578 * because !cpu_active at this point, which means load-balance
5579 * will not interfere. Also, stop-machine.
5581 rq_unpin_lock(rq, &rf);
5582 raw_spin_unlock(&rq->lock);
5583 raw_spin_lock(&next->pi_lock);
5584 raw_spin_lock(&rq->lock);
5587 * Since we're inside stop-machine, _nothing_ should have
5588 * changed the task, WARN if weird stuff happened, because in
5589 * that case the above rq->lock drop is a fail too.
5591 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5592 raw_spin_unlock(&next->pi_lock);
5596 /* Find suitable destination for @next, with force if needed. */
5597 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5599 rq = __migrate_task(rq, next, dest_cpu);
5600 if (rq != dead_rq) {
5601 raw_spin_unlock(&rq->lock);
5603 raw_spin_lock(&rq->lock);
5605 raw_spin_unlock(&next->pi_lock);
5610 #endif /* CONFIG_HOTPLUG_CPU */
5612 static void set_rq_online(struct rq *rq)
5615 const struct sched_class *class;
5617 cpumask_set_cpu(rq->cpu, rq->rd->online);
5620 for_each_class(class) {
5621 if (class->rq_online)
5622 class->rq_online(rq);
5627 static void set_rq_offline(struct rq *rq)
5630 const struct sched_class *class;
5632 for_each_class(class) {
5633 if (class->rq_offline)
5634 class->rq_offline(rq);
5637 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5642 static void set_cpu_rq_start_time(unsigned int cpu)
5644 struct rq *rq = cpu_rq(cpu);
5646 rq->age_stamp = sched_clock_cpu(cpu);
5649 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5651 #ifdef CONFIG_SCHED_DEBUG
5653 static __read_mostly int sched_debug_enabled;
5655 static int __init sched_debug_setup(char *str)
5657 sched_debug_enabled = 1;
5661 early_param("sched_debug", sched_debug_setup);
5663 static inline bool sched_debug(void)
5665 return sched_debug_enabled;
5668 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5669 struct cpumask *groupmask)
5671 struct sched_group *group = sd->groups;
5673 cpumask_clear(groupmask);
5675 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5677 if (!(sd->flags & SD_LOAD_BALANCE)) {
5678 printk("does not load-balance\n");
5680 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5685 printk(KERN_CONT "span %*pbl level %s\n",
5686 cpumask_pr_args(sched_domain_span(sd)), sd->name);
5688 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5689 printk(KERN_ERR "ERROR: domain->span does not contain "
5692 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5693 printk(KERN_ERR "ERROR: domain->groups does not contain"
5697 printk(KERN_DEBUG "%*s groups:", level + 1, "");
5701 printk(KERN_ERR "ERROR: group is NULL\n");
5705 if (!cpumask_weight(sched_group_cpus(group))) {
5706 printk(KERN_CONT "\n");
5707 printk(KERN_ERR "ERROR: empty group\n");
5711 if (!(sd->flags & SD_OVERLAP) &&
5712 cpumask_intersects(groupmask, sched_group_cpus(group))) {
5713 printk(KERN_CONT "\n");
5714 printk(KERN_ERR "ERROR: repeated CPUs\n");
5718 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5720 printk(KERN_CONT " %*pbl",
5721 cpumask_pr_args(sched_group_cpus(group)));
5722 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
5723 printk(KERN_CONT " (cpu_capacity = %lu)",
5724 group->sgc->capacity);
5727 group = group->next;
5728 } while (group != sd->groups);
5729 printk(KERN_CONT "\n");
5731 if (!cpumask_equal(sched_domain_span(sd), groupmask))
5732 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5735 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5736 printk(KERN_ERR "ERROR: parent span is not a superset "
5737 "of domain->span\n");
5741 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5745 if (!sched_debug_enabled)
5749 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5753 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5756 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5764 #else /* !CONFIG_SCHED_DEBUG */
5766 # define sched_debug_enabled 0
5767 # define sched_domain_debug(sd, cpu) do { } while (0)
5768 static inline bool sched_debug(void)
5772 #endif /* CONFIG_SCHED_DEBUG */
5774 static int sd_degenerate(struct sched_domain *sd)
5776 if (cpumask_weight(sched_domain_span(sd)) == 1)
5779 /* Following flags need at least 2 groups */
5780 if (sd->flags & (SD_LOAD_BALANCE |
5781 SD_BALANCE_NEWIDLE |
5784 SD_SHARE_CPUCAPACITY |
5785 SD_ASYM_CPUCAPACITY |
5786 SD_SHARE_PKG_RESOURCES |
5787 SD_SHARE_POWERDOMAIN)) {
5788 if (sd->groups != sd->groups->next)
5792 /* Following flags don't use groups */
5793 if (sd->flags & (SD_WAKE_AFFINE))
5800 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5802 unsigned long cflags = sd->flags, pflags = parent->flags;
5804 if (sd_degenerate(parent))
5807 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5810 /* Flags needing groups don't count if only 1 group in parent */
5811 if (parent->groups == parent->groups->next) {
5812 pflags &= ~(SD_LOAD_BALANCE |
5813 SD_BALANCE_NEWIDLE |
5816 SD_ASYM_CPUCAPACITY |
5817 SD_SHARE_CPUCAPACITY |
5818 SD_SHARE_PKG_RESOURCES |
5820 SD_SHARE_POWERDOMAIN);
5821 if (nr_node_ids == 1)
5822 pflags &= ~SD_SERIALIZE;
5824 if (~cflags & pflags)
5830 static void free_rootdomain(struct rcu_head *rcu)
5832 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5834 cpupri_cleanup(&rd->cpupri);
5835 cpudl_cleanup(&rd->cpudl);
5836 free_cpumask_var(rd->dlo_mask);
5837 free_cpumask_var(rd->rto_mask);
5838 free_cpumask_var(rd->online);
5839 free_cpumask_var(rd->span);
5843 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5845 struct root_domain *old_rd = NULL;
5846 unsigned long flags;
5848 raw_spin_lock_irqsave(&rq->lock, flags);
5853 if (cpumask_test_cpu(rq->cpu, old_rd->online))
5856 cpumask_clear_cpu(rq->cpu, old_rd->span);
5859 * If we dont want to free the old_rd yet then
5860 * set old_rd to NULL to skip the freeing later
5863 if (!atomic_dec_and_test(&old_rd->refcount))
5867 atomic_inc(&rd->refcount);
5870 cpumask_set_cpu(rq->cpu, rd->span);
5871 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
5874 raw_spin_unlock_irqrestore(&rq->lock, flags);
5877 call_rcu_sched(&old_rd->rcu, free_rootdomain);
5880 static int init_rootdomain(struct root_domain *rd)
5882 memset(rd, 0, sizeof(*rd));
5884 if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
5886 if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
5888 if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
5890 if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
5893 init_dl_bw(&rd->dl_bw);
5894 if (cpudl_init(&rd->cpudl) != 0)
5897 if (cpupri_init(&rd->cpupri) != 0)
5902 free_cpumask_var(rd->rto_mask);
5904 free_cpumask_var(rd->dlo_mask);
5906 free_cpumask_var(rd->online);
5908 free_cpumask_var(rd->span);
5914 * By default the system creates a single root-domain with all cpus as
5915 * members (mimicking the global state we have today).
5917 struct root_domain def_root_domain;
5919 static void init_defrootdomain(void)
5921 init_rootdomain(&def_root_domain);
5923 atomic_set(&def_root_domain.refcount, 1);
5926 static struct root_domain *alloc_rootdomain(void)
5928 struct root_domain *rd;
5930 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5934 if (init_rootdomain(rd) != 0) {
5942 static void free_sched_groups(struct sched_group *sg, int free_sgc)
5944 struct sched_group *tmp, *first;
5953 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
5958 } while (sg != first);
5961 static void destroy_sched_domain(struct sched_domain *sd)
5964 * If its an overlapping domain it has private groups, iterate and
5967 if (sd->flags & SD_OVERLAP) {
5968 free_sched_groups(sd->groups, 1);
5969 } else if (atomic_dec_and_test(&sd->groups->ref)) {
5970 kfree(sd->groups->sgc);
5973 if (sd->shared && atomic_dec_and_test(&sd->shared->ref))
5978 static void destroy_sched_domains_rcu(struct rcu_head *rcu)
5980 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
5983 struct sched_domain *parent = sd->parent;
5984 destroy_sched_domain(sd);
5989 static void destroy_sched_domains(struct sched_domain *sd)
5992 call_rcu(&sd->rcu, destroy_sched_domains_rcu);
5996 * Keep a special pointer to the highest sched_domain that has
5997 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
5998 * allows us to avoid some pointer chasing select_idle_sibling().
6000 * Also keep a unique ID per domain (we use the first cpu number in
6001 * the cpumask of the domain), this allows us to quickly tell if
6002 * two cpus are in the same cache domain, see cpus_share_cache().
6004 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
6005 DEFINE_PER_CPU(int, sd_llc_size);
6006 DEFINE_PER_CPU(int, sd_llc_id);
6007 DEFINE_PER_CPU(struct sched_domain_shared *, sd_llc_shared);
6008 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
6009 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
6011 static void update_top_cache_domain(int cpu)
6013 struct sched_domain_shared *sds = NULL;
6014 struct sched_domain *sd;
6018 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
6020 id = cpumask_first(sched_domain_span(sd));
6021 size = cpumask_weight(sched_domain_span(sd));
6025 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
6026 per_cpu(sd_llc_size, cpu) = size;
6027 per_cpu(sd_llc_id, cpu) = id;
6028 rcu_assign_pointer(per_cpu(sd_llc_shared, cpu), sds);
6030 sd = lowest_flag_domain(cpu, SD_NUMA);
6031 rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
6033 sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
6034 rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
6038 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6039 * hold the hotplug lock.
6042 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6044 struct rq *rq = cpu_rq(cpu);
6045 struct sched_domain *tmp;
6047 /* Remove the sched domains which do not contribute to scheduling. */
6048 for (tmp = sd; tmp; ) {
6049 struct sched_domain *parent = tmp->parent;
6053 if (sd_parent_degenerate(tmp, parent)) {
6054 tmp->parent = parent->parent;
6056 parent->parent->child = tmp;
6058 * Transfer SD_PREFER_SIBLING down in case of a
6059 * degenerate parent; the spans match for this
6060 * so the property transfers.
6062 if (parent->flags & SD_PREFER_SIBLING)
6063 tmp->flags |= SD_PREFER_SIBLING;
6064 destroy_sched_domain(parent);
6069 if (sd && sd_degenerate(sd)) {
6072 destroy_sched_domain(tmp);
6077 sched_domain_debug(sd, cpu);
6079 rq_attach_root(rq, rd);
6081 rcu_assign_pointer(rq->sd, sd);
6082 destroy_sched_domains(tmp);
6084 update_top_cache_domain(cpu);
6087 /* Setup the mask of cpus configured for isolated domains */
6088 static int __init isolated_cpu_setup(char *str)
6092 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6093 ret = cpulist_parse(str, cpu_isolated_map);
6095 pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
6100 __setup("isolcpus=", isolated_cpu_setup);
6103 struct sched_domain ** __percpu sd;
6104 struct root_domain *rd;
6115 * Build an iteration mask that can exclude certain CPUs from the upwards
6118 * Asymmetric node setups can result in situations where the domain tree is of
6119 * unequal depth, make sure to skip domains that already cover the entire
6122 * In that case build_sched_domains() will have terminated the iteration early
6123 * and our sibling sd spans will be empty. Domains should always include the
6124 * cpu they're built on, so check that.
6127 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
6129 const struct cpumask *span = sched_domain_span(sd);
6130 struct sd_data *sdd = sd->private;
6131 struct sched_domain *sibling;
6134 for_each_cpu(i, span) {
6135 sibling = *per_cpu_ptr(sdd->sd, i);
6136 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6139 cpumask_set_cpu(i, sched_group_mask(sg));
6144 * Return the canonical balance cpu for this group, this is the first cpu
6145 * of this group that's also in the iteration mask.
6147 int group_balance_cpu(struct sched_group *sg)
6149 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
6153 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
6155 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
6156 const struct cpumask *span = sched_domain_span(sd);
6157 struct cpumask *covered = sched_domains_tmpmask;
6158 struct sd_data *sdd = sd->private;
6159 struct sched_domain *sibling;
6162 cpumask_clear(covered);
6164 for_each_cpu(i, span) {
6165 struct cpumask *sg_span;
6167 if (cpumask_test_cpu(i, covered))
6170 sibling = *per_cpu_ptr(sdd->sd, i);
6172 /* See the comment near build_group_mask(). */
6173 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6176 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6177 GFP_KERNEL, cpu_to_node(cpu));
6182 sg_span = sched_group_cpus(sg);
6184 cpumask_copy(sg_span, sched_domain_span(sibling->child));
6186 cpumask_set_cpu(i, sg_span);
6188 cpumask_or(covered, covered, sg_span);
6190 sg->sgc = *per_cpu_ptr(sdd->sgc, i);
6191 if (atomic_inc_return(&sg->sgc->ref) == 1)
6192 build_group_mask(sd, sg);
6195 * Initialize sgc->capacity such that even if we mess up the
6196 * domains and no possible iteration will get us here, we won't
6199 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
6200 sg->sgc->min_capacity = SCHED_CAPACITY_SCALE;
6203 * Make sure the first group of this domain contains the
6204 * canonical balance cpu. Otherwise the sched_domain iteration
6205 * breaks. See update_sg_lb_stats().
6207 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
6208 group_balance_cpu(sg) == cpu)
6218 sd->groups = groups;
6223 free_sched_groups(first, 0);
6228 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
6230 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6231 struct sched_domain *child = sd->child;
6234 cpu = cpumask_first(sched_domain_span(child));
6237 *sg = *per_cpu_ptr(sdd->sg, cpu);
6238 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
6239 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
6246 * build_sched_groups will build a circular linked list of the groups
6247 * covered by the given span, and will set each group's ->cpumask correctly,
6248 * and ->cpu_capacity to 0.
6250 * Assumes the sched_domain tree is fully constructed
6253 build_sched_groups(struct sched_domain *sd, int cpu)
6255 struct sched_group *first = NULL, *last = NULL;
6256 struct sd_data *sdd = sd->private;
6257 const struct cpumask *span = sched_domain_span(sd);
6258 struct cpumask *covered;
6261 get_group(cpu, sdd, &sd->groups);
6262 atomic_inc(&sd->groups->ref);
6264 if (cpu != cpumask_first(span))
6267 lockdep_assert_held(&sched_domains_mutex);
6268 covered = sched_domains_tmpmask;
6270 cpumask_clear(covered);
6272 for_each_cpu(i, span) {
6273 struct sched_group *sg;
6276 if (cpumask_test_cpu(i, covered))
6279 group = get_group(i, sdd, &sg);
6280 cpumask_setall(sched_group_mask(sg));
6282 for_each_cpu(j, span) {
6283 if (get_group(j, sdd, NULL) != group)
6286 cpumask_set_cpu(j, covered);
6287 cpumask_set_cpu(j, sched_group_cpus(sg));
6302 * Initialize sched groups cpu_capacity.
6304 * cpu_capacity indicates the capacity of sched group, which is used while
6305 * distributing the load between different sched groups in a sched domain.
6306 * Typically cpu_capacity for all the groups in a sched domain will be same
6307 * unless there are asymmetries in the topology. If there are asymmetries,
6308 * group having more cpu_capacity will pickup more load compared to the
6309 * group having less cpu_capacity.
6311 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
6313 struct sched_group *sg = sd->groups;
6318 int cpu, max_cpu = -1;
6320 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6322 if (!(sd->flags & SD_ASYM_PACKING))
6325 for_each_cpu(cpu, sched_group_cpus(sg)) {
6328 else if (sched_asym_prefer(cpu, max_cpu))
6331 sg->asym_prefer_cpu = max_cpu;
6335 } while (sg != sd->groups);
6337 if (cpu != group_balance_cpu(sg))
6340 update_group_capacity(sd, cpu);
6344 * Initializers for schedule domains
6345 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6348 static int default_relax_domain_level = -1;
6349 int sched_domain_level_max;
6351 static int __init setup_relax_domain_level(char *str)
6353 if (kstrtoint(str, 0, &default_relax_domain_level))
6354 pr_warn("Unable to set relax_domain_level\n");
6358 __setup("relax_domain_level=", setup_relax_domain_level);
6360 static void set_domain_attribute(struct sched_domain *sd,
6361 struct sched_domain_attr *attr)
6365 if (!attr || attr->relax_domain_level < 0) {
6366 if (default_relax_domain_level < 0)
6369 request = default_relax_domain_level;
6371 request = attr->relax_domain_level;
6372 if (request < sd->level) {
6373 /* turn off idle balance on this domain */
6374 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6376 /* turn on idle balance on this domain */
6377 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6381 static void __sdt_free(const struct cpumask *cpu_map);
6382 static int __sdt_alloc(const struct cpumask *cpu_map);
6384 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6385 const struct cpumask *cpu_map)
6389 if (!atomic_read(&d->rd->refcount))
6390 free_rootdomain(&d->rd->rcu); /* fall through */
6392 free_percpu(d->sd); /* fall through */
6394 __sdt_free(cpu_map); /* fall through */
6400 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6401 const struct cpumask *cpu_map)
6403 memset(d, 0, sizeof(*d));
6405 if (__sdt_alloc(cpu_map))
6406 return sa_sd_storage;
6407 d->sd = alloc_percpu(struct sched_domain *);
6409 return sa_sd_storage;
6410 d->rd = alloc_rootdomain();
6413 return sa_rootdomain;
6417 * NULL the sd_data elements we've used to build the sched_domain and
6418 * sched_group structure so that the subsequent __free_domain_allocs()
6419 * will not free the data we're using.
6421 static void claim_allocations(int cpu, struct sched_domain *sd)
6423 struct sd_data *sdd = sd->private;
6425 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6426 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6428 if (atomic_read(&(*per_cpu_ptr(sdd->sds, cpu))->ref))
6429 *per_cpu_ptr(sdd->sds, cpu) = NULL;
6431 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6432 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6434 if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
6435 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
6439 static int sched_domains_numa_levels;
6440 enum numa_topology_type sched_numa_topology_type;
6441 static int *sched_domains_numa_distance;
6442 int sched_max_numa_distance;
6443 static struct cpumask ***sched_domains_numa_masks;
6444 static int sched_domains_curr_level;
6448 * SD_flags allowed in topology descriptions.
6450 * These flags are purely descriptive of the topology and do not prescribe
6451 * behaviour. Behaviour is artificial and mapped in the below sd_init()
6454 * SD_SHARE_CPUCAPACITY - describes SMT topologies
6455 * SD_SHARE_PKG_RESOURCES - describes shared caches
6456 * SD_NUMA - describes NUMA topologies
6457 * SD_SHARE_POWERDOMAIN - describes shared power domain
6458 * SD_ASYM_CPUCAPACITY - describes mixed capacity topologies
6460 * Odd one out, which beside describing the topology has a quirk also
6461 * prescribes the desired behaviour that goes along with it:
6463 * SD_ASYM_PACKING - describes SMT quirks
6465 #define TOPOLOGY_SD_FLAGS \
6466 (SD_SHARE_CPUCAPACITY | \
6467 SD_SHARE_PKG_RESOURCES | \
6470 SD_ASYM_CPUCAPACITY | \
6471 SD_SHARE_POWERDOMAIN)
6473 static struct sched_domain *
6474 sd_init(struct sched_domain_topology_level *tl,
6475 const struct cpumask *cpu_map,
6476 struct sched_domain *child, int cpu)
6478 struct sd_data *sdd = &tl->data;
6479 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6480 int sd_id, sd_weight, sd_flags = 0;
6484 * Ugly hack to pass state to sd_numa_mask()...
6486 sched_domains_curr_level = tl->numa_level;
6489 sd_weight = cpumask_weight(tl->mask(cpu));
6492 sd_flags = (*tl->sd_flags)();
6493 if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
6494 "wrong sd_flags in topology description\n"))
6495 sd_flags &= ~TOPOLOGY_SD_FLAGS;
6497 *sd = (struct sched_domain){
6498 .min_interval = sd_weight,
6499 .max_interval = 2*sd_weight,
6501 .imbalance_pct = 125,
6503 .cache_nice_tries = 0,
6510 .flags = 1*SD_LOAD_BALANCE
6511 | 1*SD_BALANCE_NEWIDLE
6516 | 0*SD_SHARE_CPUCAPACITY
6517 | 0*SD_SHARE_PKG_RESOURCES
6519 | 0*SD_PREFER_SIBLING
6524 .last_balance = jiffies,
6525 .balance_interval = sd_weight,
6527 .max_newidle_lb_cost = 0,
6528 .next_decay_max_lb_cost = jiffies,
6530 #ifdef CONFIG_SCHED_DEBUG
6535 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6536 sd_id = cpumask_first(sched_domain_span(sd));
6539 * Convert topological properties into behaviour.
6542 if (sd->flags & SD_ASYM_CPUCAPACITY) {
6543 struct sched_domain *t = sd;
6545 for_each_lower_domain(t)
6546 t->flags |= SD_BALANCE_WAKE;
6549 if (sd->flags & SD_SHARE_CPUCAPACITY) {
6550 sd->flags |= SD_PREFER_SIBLING;
6551 sd->imbalance_pct = 110;
6552 sd->smt_gain = 1178; /* ~15% */
6554 } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6555 sd->imbalance_pct = 117;
6556 sd->cache_nice_tries = 1;
6560 } else if (sd->flags & SD_NUMA) {
6561 sd->cache_nice_tries = 2;
6565 sd->flags |= SD_SERIALIZE;
6566 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
6567 sd->flags &= ~(SD_BALANCE_EXEC |
6574 sd->flags |= SD_PREFER_SIBLING;
6575 sd->cache_nice_tries = 1;
6581 * For all levels sharing cache; connect a sched_domain_shared
6584 if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6585 sd->shared = *per_cpu_ptr(sdd->sds, sd_id);
6586 atomic_inc(&sd->shared->ref);
6587 atomic_set(&sd->shared->nr_busy_cpus, sd_weight);
6596 * Topology list, bottom-up.
6598 static struct sched_domain_topology_level default_topology[] = {
6599 #ifdef CONFIG_SCHED_SMT
6600 { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
6602 #ifdef CONFIG_SCHED_MC
6603 { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
6605 { cpu_cpu_mask, SD_INIT_NAME(DIE) },
6609 static struct sched_domain_topology_level *sched_domain_topology =
6612 #define for_each_sd_topology(tl) \
6613 for (tl = sched_domain_topology; tl->mask; tl++)
6615 void set_sched_topology(struct sched_domain_topology_level *tl)
6617 if (WARN_ON_ONCE(sched_smp_initialized))
6620 sched_domain_topology = tl;
6625 static const struct cpumask *sd_numa_mask(int cpu)
6627 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6630 static void sched_numa_warn(const char *str)
6632 static int done = false;
6640 printk(KERN_WARNING "ERROR: %s\n\n", str);
6642 for (i = 0; i < nr_node_ids; i++) {
6643 printk(KERN_WARNING " ");
6644 for (j = 0; j < nr_node_ids; j++)
6645 printk(KERN_CONT "%02d ", node_distance(i,j));
6646 printk(KERN_CONT "\n");
6648 printk(KERN_WARNING "\n");
6651 bool find_numa_distance(int distance)
6655 if (distance == node_distance(0, 0))
6658 for (i = 0; i < sched_domains_numa_levels; i++) {
6659 if (sched_domains_numa_distance[i] == distance)
6667 * A system can have three types of NUMA topology:
6668 * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6669 * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6670 * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6672 * The difference between a glueless mesh topology and a backplane
6673 * topology lies in whether communication between not directly
6674 * connected nodes goes through intermediary nodes (where programs
6675 * could run), or through backplane controllers. This affects
6676 * placement of programs.
6678 * The type of topology can be discerned with the following tests:
6679 * - If the maximum distance between any nodes is 1 hop, the system
6680 * is directly connected.
6681 * - If for two nodes A and B, located N > 1 hops away from each other,
6682 * there is an intermediary node C, which is < N hops away from both
6683 * nodes A and B, the system is a glueless mesh.
6685 static void init_numa_topology_type(void)
6689 n = sched_max_numa_distance;
6691 if (sched_domains_numa_levels <= 1) {
6692 sched_numa_topology_type = NUMA_DIRECT;
6696 for_each_online_node(a) {
6697 for_each_online_node(b) {
6698 /* Find two nodes furthest removed from each other. */
6699 if (node_distance(a, b) < n)
6702 /* Is there an intermediary node between a and b? */
6703 for_each_online_node(c) {
6704 if (node_distance(a, c) < n &&
6705 node_distance(b, c) < n) {
6706 sched_numa_topology_type =
6712 sched_numa_topology_type = NUMA_BACKPLANE;
6718 static void sched_init_numa(void)
6720 int next_distance, curr_distance = node_distance(0, 0);
6721 struct sched_domain_topology_level *tl;
6725 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6726 if (!sched_domains_numa_distance)
6730 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6731 * unique distances in the node_distance() table.
6733 * Assumes node_distance(0,j) includes all distances in
6734 * node_distance(i,j) in order to avoid cubic time.
6736 next_distance = curr_distance;
6737 for (i = 0; i < nr_node_ids; i++) {
6738 for (j = 0; j < nr_node_ids; j++) {
6739 for (k = 0; k < nr_node_ids; k++) {
6740 int distance = node_distance(i, k);
6742 if (distance > curr_distance &&
6743 (distance < next_distance ||
6744 next_distance == curr_distance))
6745 next_distance = distance;
6748 * While not a strong assumption it would be nice to know
6749 * about cases where if node A is connected to B, B is not
6750 * equally connected to A.
6752 if (sched_debug() && node_distance(k, i) != distance)
6753 sched_numa_warn("Node-distance not symmetric");
6755 if (sched_debug() && i && !find_numa_distance(distance))
6756 sched_numa_warn("Node-0 not representative");
6758 if (next_distance != curr_distance) {
6759 sched_domains_numa_distance[level++] = next_distance;
6760 sched_domains_numa_levels = level;
6761 curr_distance = next_distance;
6766 * In case of sched_debug() we verify the above assumption.
6776 * 'level' contains the number of unique distances, excluding the
6777 * identity distance node_distance(i,i).
6779 * The sched_domains_numa_distance[] array includes the actual distance
6784 * Here, we should temporarily reset sched_domains_numa_levels to 0.
6785 * If it fails to allocate memory for array sched_domains_numa_masks[][],
6786 * the array will contain less then 'level' members. This could be
6787 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6788 * in other functions.
6790 * We reset it to 'level' at the end of this function.
6792 sched_domains_numa_levels = 0;
6794 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6795 if (!sched_domains_numa_masks)
6799 * Now for each level, construct a mask per node which contains all
6800 * cpus of nodes that are that many hops away from us.
6802 for (i = 0; i < level; i++) {
6803 sched_domains_numa_masks[i] =
6804 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6805 if (!sched_domains_numa_masks[i])
6808 for (j = 0; j < nr_node_ids; j++) {
6809 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
6813 sched_domains_numa_masks[i][j] = mask;
6816 if (node_distance(j, k) > sched_domains_numa_distance[i])
6819 cpumask_or(mask, mask, cpumask_of_node(k));
6824 /* Compute default topology size */
6825 for (i = 0; sched_domain_topology[i].mask; i++);
6827 tl = kzalloc((i + level + 1) *
6828 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6833 * Copy the default topology bits..
6835 for (i = 0; sched_domain_topology[i].mask; i++)
6836 tl[i] = sched_domain_topology[i];
6839 * .. and append 'j' levels of NUMA goodness.
6841 for (j = 0; j < level; i++, j++) {
6842 tl[i] = (struct sched_domain_topology_level){
6843 .mask = sd_numa_mask,
6844 .sd_flags = cpu_numa_flags,
6845 .flags = SDTL_OVERLAP,
6851 sched_domain_topology = tl;
6853 sched_domains_numa_levels = level;
6854 sched_max_numa_distance = sched_domains_numa_distance[level - 1];
6856 init_numa_topology_type();
6859 static void sched_domains_numa_masks_set(unsigned int cpu)
6861 int node = cpu_to_node(cpu);
6864 for (i = 0; i < sched_domains_numa_levels; i++) {
6865 for (j = 0; j < nr_node_ids; j++) {
6866 if (node_distance(j, node) <= sched_domains_numa_distance[i])
6867 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6872 static void sched_domains_numa_masks_clear(unsigned int cpu)
6876 for (i = 0; i < sched_domains_numa_levels; i++) {
6877 for (j = 0; j < nr_node_ids; j++)
6878 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6883 static inline void sched_init_numa(void) { }
6884 static void sched_domains_numa_masks_set(unsigned int cpu) { }
6885 static void sched_domains_numa_masks_clear(unsigned int cpu) { }
6886 #endif /* CONFIG_NUMA */
6888 static int __sdt_alloc(const struct cpumask *cpu_map)
6890 struct sched_domain_topology_level *tl;
6893 for_each_sd_topology(tl) {
6894 struct sd_data *sdd = &tl->data;
6896 sdd->sd = alloc_percpu(struct sched_domain *);
6900 sdd->sds = alloc_percpu(struct sched_domain_shared *);
6904 sdd->sg = alloc_percpu(struct sched_group *);
6908 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
6912 for_each_cpu(j, cpu_map) {
6913 struct sched_domain *sd;
6914 struct sched_domain_shared *sds;
6915 struct sched_group *sg;
6916 struct sched_group_capacity *sgc;
6918 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6919 GFP_KERNEL, cpu_to_node(j));
6923 *per_cpu_ptr(sdd->sd, j) = sd;
6925 sds = kzalloc_node(sizeof(struct sched_domain_shared),
6926 GFP_KERNEL, cpu_to_node(j));
6930 *per_cpu_ptr(sdd->sds, j) = sds;
6932 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6933 GFP_KERNEL, cpu_to_node(j));
6939 *per_cpu_ptr(sdd->sg, j) = sg;
6941 sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
6942 GFP_KERNEL, cpu_to_node(j));
6946 *per_cpu_ptr(sdd->sgc, j) = sgc;
6953 static void __sdt_free(const struct cpumask *cpu_map)
6955 struct sched_domain_topology_level *tl;
6958 for_each_sd_topology(tl) {
6959 struct sd_data *sdd = &tl->data;
6961 for_each_cpu(j, cpu_map) {
6962 struct sched_domain *sd;
6965 sd = *per_cpu_ptr(sdd->sd, j);
6966 if (sd && (sd->flags & SD_OVERLAP))
6967 free_sched_groups(sd->groups, 0);
6968 kfree(*per_cpu_ptr(sdd->sd, j));
6972 kfree(*per_cpu_ptr(sdd->sds, j));
6974 kfree(*per_cpu_ptr(sdd->sg, j));
6976 kfree(*per_cpu_ptr(sdd->sgc, j));
6978 free_percpu(sdd->sd);
6980 free_percpu(sdd->sds);
6982 free_percpu(sdd->sg);
6984 free_percpu(sdd->sgc);
6989 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6990 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6991 struct sched_domain *child, int cpu)
6993 struct sched_domain *sd = sd_init(tl, cpu_map, child, cpu);
6996 sd->level = child->level + 1;
6997 sched_domain_level_max = max(sched_domain_level_max, sd->level);
7000 if (!cpumask_subset(sched_domain_span(child),
7001 sched_domain_span(sd))) {
7002 pr_err("BUG: arch topology borken\n");
7003 #ifdef CONFIG_SCHED_DEBUG
7004 pr_err(" the %s domain not a subset of the %s domain\n",
7005 child->name, sd->name);
7007 /* Fixup, ensure @sd has at least @child cpus. */
7008 cpumask_or(sched_domain_span(sd),
7009 sched_domain_span(sd),
7010 sched_domain_span(child));
7014 set_domain_attribute(sd, attr);
7020 * Build sched domains for a given set of cpus and attach the sched domains
7021 * to the individual cpus
7023 static int build_sched_domains(const struct cpumask *cpu_map,
7024 struct sched_domain_attr *attr)
7026 enum s_alloc alloc_state;
7027 struct sched_domain *sd;
7029 struct rq *rq = NULL;
7030 int i, ret = -ENOMEM;
7032 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7033 if (alloc_state != sa_rootdomain)
7036 /* Set up domains for cpus specified by the cpu_map. */
7037 for_each_cpu(i, cpu_map) {
7038 struct sched_domain_topology_level *tl;
7041 for_each_sd_topology(tl) {
7042 sd = build_sched_domain(tl, cpu_map, attr, sd, i);
7043 if (tl == sched_domain_topology)
7044 *per_cpu_ptr(d.sd, i) = sd;
7045 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
7046 sd->flags |= SD_OVERLAP;
7047 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
7052 /* Build the groups for the domains */
7053 for_each_cpu(i, cpu_map) {
7054 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7055 sd->span_weight = cpumask_weight(sched_domain_span(sd));
7056 if (sd->flags & SD_OVERLAP) {
7057 if (build_overlap_sched_groups(sd, i))
7060 if (build_sched_groups(sd, i))
7066 /* Calculate CPU capacity for physical packages and nodes */
7067 for (i = nr_cpumask_bits-1; i >= 0; i--) {
7068 if (!cpumask_test_cpu(i, cpu_map))
7071 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7072 claim_allocations(i, sd);
7073 init_sched_groups_capacity(i, sd);
7077 /* Attach the domains */
7079 for_each_cpu(i, cpu_map) {
7081 sd = *per_cpu_ptr(d.sd, i);
7083 /* Use READ_ONCE()/WRITE_ONCE() to avoid load/store tearing: */
7084 if (rq->cpu_capacity_orig > READ_ONCE(d.rd->max_cpu_capacity))
7085 WRITE_ONCE(d.rd->max_cpu_capacity, rq->cpu_capacity_orig);
7087 cpu_attach_domain(sd, d.rd, i);
7091 if (rq && sched_debug_enabled) {
7092 pr_info("span: %*pbl (max cpu_capacity = %lu)\n",
7093 cpumask_pr_args(cpu_map), rq->rd->max_cpu_capacity);
7098 __free_domain_allocs(&d, alloc_state, cpu_map);
7102 static cpumask_var_t *doms_cur; /* current sched domains */
7103 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7104 static struct sched_domain_attr *dattr_cur;
7105 /* attribues of custom domains in 'doms_cur' */
7108 * Special case: If a kmalloc of a doms_cur partition (array of
7109 * cpumask) fails, then fallback to a single sched domain,
7110 * as determined by the single cpumask fallback_doms.
7112 static cpumask_var_t fallback_doms;
7115 * arch_update_cpu_topology lets virtualized architectures update the
7116 * cpu core maps. It is supposed to return 1 if the topology changed
7117 * or 0 if it stayed the same.
7119 int __weak arch_update_cpu_topology(void)
7124 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7127 cpumask_var_t *doms;
7129 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7132 for (i = 0; i < ndoms; i++) {
7133 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7134 free_sched_domains(doms, i);
7141 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7144 for (i = 0; i < ndoms; i++)
7145 free_cpumask_var(doms[i]);
7150 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7151 * For now this just excludes isolated cpus, but could be used to
7152 * exclude other special cases in the future.
7154 static int init_sched_domains(const struct cpumask *cpu_map)
7158 arch_update_cpu_topology();
7160 doms_cur = alloc_sched_domains(ndoms_cur);
7162 doms_cur = &fallback_doms;
7163 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7164 err = build_sched_domains(doms_cur[0], NULL);
7165 register_sched_domain_sysctl();
7171 * Detach sched domains from a group of cpus specified in cpu_map
7172 * These cpus will now be attached to the NULL domain
7174 static void detach_destroy_domains(const struct cpumask *cpu_map)
7179 for_each_cpu(i, cpu_map)
7180 cpu_attach_domain(NULL, &def_root_domain, i);
7184 /* handle null as "default" */
7185 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7186 struct sched_domain_attr *new, int idx_new)
7188 struct sched_domain_attr tmp;
7195 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7196 new ? (new + idx_new) : &tmp,
7197 sizeof(struct sched_domain_attr));
7201 * Partition sched domains as specified by the 'ndoms_new'
7202 * cpumasks in the array doms_new[] of cpumasks. This compares
7203 * doms_new[] to the current sched domain partitioning, doms_cur[].
7204 * It destroys each deleted domain and builds each new domain.
7206 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7207 * The masks don't intersect (don't overlap.) We should setup one
7208 * sched domain for each mask. CPUs not in any of the cpumasks will
7209 * not be load balanced. If the same cpumask appears both in the
7210 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7213 * The passed in 'doms_new' should be allocated using
7214 * alloc_sched_domains. This routine takes ownership of it and will
7215 * free_sched_domains it when done with it. If the caller failed the
7216 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7217 * and partition_sched_domains() will fallback to the single partition
7218 * 'fallback_doms', it also forces the domains to be rebuilt.
7220 * If doms_new == NULL it will be replaced with cpu_online_mask.
7221 * ndoms_new == 0 is a special case for destroying existing domains,
7222 * and it will not create the default domain.
7224 * Call with hotplug lock held
7226 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7227 struct sched_domain_attr *dattr_new)
7232 mutex_lock(&sched_domains_mutex);
7234 /* always unregister in case we don't destroy any domains */
7235 unregister_sched_domain_sysctl();
7237 /* Let architecture update cpu core mappings. */
7238 new_topology = arch_update_cpu_topology();
7240 n = doms_new ? ndoms_new : 0;
7242 /* Destroy deleted domains */
7243 for (i = 0; i < ndoms_cur; i++) {
7244 for (j = 0; j < n && !new_topology; j++) {
7245 if (cpumask_equal(doms_cur[i], doms_new[j])
7246 && dattrs_equal(dattr_cur, i, dattr_new, j))
7249 /* no match - a current sched domain not in new doms_new[] */
7250 detach_destroy_domains(doms_cur[i]);
7256 if (doms_new == NULL) {
7258 doms_new = &fallback_doms;
7259 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7260 WARN_ON_ONCE(dattr_new);
7263 /* Build new domains */
7264 for (i = 0; i < ndoms_new; i++) {
7265 for (j = 0; j < n && !new_topology; j++) {
7266 if (cpumask_equal(doms_new[i], doms_cur[j])
7267 && dattrs_equal(dattr_new, i, dattr_cur, j))
7270 /* no match - add a new doms_new */
7271 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7276 /* Remember the new sched domains */
7277 if (doms_cur != &fallback_doms)
7278 free_sched_domains(doms_cur, ndoms_cur);
7279 kfree(dattr_cur); /* kfree(NULL) is safe */
7280 doms_cur = doms_new;
7281 dattr_cur = dattr_new;
7282 ndoms_cur = ndoms_new;
7284 register_sched_domain_sysctl();
7286 mutex_unlock(&sched_domains_mutex);
7289 static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
7292 * Update cpusets according to cpu_active mask. If cpusets are
7293 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7294 * around partition_sched_domains().
7296 * If we come here as part of a suspend/resume, don't touch cpusets because we
7297 * want to restore it back to its original state upon resume anyway.
7299 static void cpuset_cpu_active(void)
7301 if (cpuhp_tasks_frozen) {
7303 * num_cpus_frozen tracks how many CPUs are involved in suspend
7304 * resume sequence. As long as this is not the last online
7305 * operation in the resume sequence, just build a single sched
7306 * domain, ignoring cpusets.
7309 if (likely(num_cpus_frozen)) {
7310 partition_sched_domains(1, NULL, NULL);
7314 * This is the last CPU online operation. So fall through and
7315 * restore the original sched domains by considering the
7316 * cpuset configurations.
7319 cpuset_update_active_cpus(true);
7322 static int cpuset_cpu_inactive(unsigned int cpu)
7324 unsigned long flags;
7329 if (!cpuhp_tasks_frozen) {
7330 rcu_read_lock_sched();
7331 dl_b = dl_bw_of(cpu);
7333 raw_spin_lock_irqsave(&dl_b->lock, flags);
7334 cpus = dl_bw_cpus(cpu);
7335 overflow = __dl_overflow(dl_b, cpus, 0, 0);
7336 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7338 rcu_read_unlock_sched();
7342 cpuset_update_active_cpus(false);
7345 partition_sched_domains(1, NULL, NULL);
7350 int sched_cpu_activate(unsigned int cpu)
7352 struct rq *rq = cpu_rq(cpu);
7353 unsigned long flags;
7355 set_cpu_active(cpu, true);
7357 if (sched_smp_initialized) {
7358 sched_domains_numa_masks_set(cpu);
7359 cpuset_cpu_active();
7363 * Put the rq online, if not already. This happens:
7365 * 1) In the early boot process, because we build the real domains
7366 * after all cpus have been brought up.
7368 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
7371 raw_spin_lock_irqsave(&rq->lock, flags);
7373 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7376 raw_spin_unlock_irqrestore(&rq->lock, flags);
7378 update_max_interval();
7383 int sched_cpu_deactivate(unsigned int cpu)
7387 set_cpu_active(cpu, false);
7389 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
7390 * users of this state to go away such that all new such users will
7393 * For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
7394 * not imply sync_sched(), so wait for both.
7396 * Do sync before park smpboot threads to take care the rcu boost case.
7398 if (IS_ENABLED(CONFIG_PREEMPT))
7399 synchronize_rcu_mult(call_rcu, call_rcu_sched);
7403 if (!sched_smp_initialized)
7406 ret = cpuset_cpu_inactive(cpu);
7408 set_cpu_active(cpu, true);
7411 sched_domains_numa_masks_clear(cpu);
7415 static void sched_rq_cpu_starting(unsigned int cpu)
7417 struct rq *rq = cpu_rq(cpu);
7419 rq->calc_load_update = calc_load_update;
7420 update_max_interval();
7423 int sched_cpu_starting(unsigned int cpu)
7425 set_cpu_rq_start_time(cpu);
7426 sched_rq_cpu_starting(cpu);
7430 #ifdef CONFIG_HOTPLUG_CPU
7431 int sched_cpu_dying(unsigned int cpu)
7433 struct rq *rq = cpu_rq(cpu);
7434 unsigned long flags;
7436 /* Handle pending wakeups and then migrate everything off */
7437 sched_ttwu_pending();
7438 raw_spin_lock_irqsave(&rq->lock, flags);
7440 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7444 BUG_ON(rq->nr_running != 1);
7445 raw_spin_unlock_irqrestore(&rq->lock, flags);
7446 calc_load_migrate(rq);
7447 update_max_interval();
7448 nohz_balance_exit_idle(cpu);
7454 #ifdef CONFIG_SCHED_SMT
7455 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7457 static void sched_init_smt(void)
7460 * We've enumerated all CPUs and will assume that if any CPU
7461 * has SMT siblings, CPU0 will too.
7463 if (cpumask_weight(cpu_smt_mask(0)) > 1)
7464 static_branch_enable(&sched_smt_present);
7467 static inline void sched_init_smt(void) { }
7470 void __init sched_init_smp(void)
7472 cpumask_var_t non_isolated_cpus;
7474 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7475 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7480 * There's no userspace yet to cause hotplug operations; hence all the
7481 * cpu masks are stable and all blatant races in the below code cannot
7484 mutex_lock(&sched_domains_mutex);
7485 init_sched_domains(cpu_active_mask);
7486 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7487 if (cpumask_empty(non_isolated_cpus))
7488 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7489 mutex_unlock(&sched_domains_mutex);
7491 /* Move init over to a non-isolated CPU */
7492 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7494 sched_init_granularity();
7495 free_cpumask_var(non_isolated_cpus);
7497 init_sched_rt_class();
7498 init_sched_dl_class();
7502 sched_smp_initialized = true;
7505 static int __init migration_init(void)
7507 sched_rq_cpu_starting(smp_processor_id());
7510 early_initcall(migration_init);
7513 void __init sched_init_smp(void)
7515 sched_init_granularity();
7517 #endif /* CONFIG_SMP */
7519 int in_sched_functions(unsigned long addr)
7521 return in_lock_functions(addr) ||
7522 (addr >= (unsigned long)__sched_text_start
7523 && addr < (unsigned long)__sched_text_end);
7526 #ifdef CONFIG_CGROUP_SCHED
7528 * Default task group.
7529 * Every task in system belongs to this group at bootup.
7531 struct task_group root_task_group;
7532 LIST_HEAD(task_groups);
7534 /* Cacheline aligned slab cache for task_group */
7535 static struct kmem_cache *task_group_cache __read_mostly;
7538 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7539 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
7541 #define WAIT_TABLE_BITS 8
7542 #define WAIT_TABLE_SIZE (1 << WAIT_TABLE_BITS)
7543 static wait_queue_head_t bit_wait_table[WAIT_TABLE_SIZE] __cacheline_aligned;
7545 wait_queue_head_t *bit_waitqueue(void *word, int bit)
7547 const int shift = BITS_PER_LONG == 32 ? 5 : 6;
7548 unsigned long val = (unsigned long)word << shift | bit;
7550 return bit_wait_table + hash_long(val, WAIT_TABLE_BITS);
7552 EXPORT_SYMBOL(bit_waitqueue);
7554 void __init sched_init(void)
7557 unsigned long alloc_size = 0, ptr;
7559 for (i = 0; i < WAIT_TABLE_SIZE; i++)
7560 init_waitqueue_head(bit_wait_table + i);
7562 #ifdef CONFIG_FAIR_GROUP_SCHED
7563 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7565 #ifdef CONFIG_RT_GROUP_SCHED
7566 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7569 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7571 #ifdef CONFIG_FAIR_GROUP_SCHED
7572 root_task_group.se = (struct sched_entity **)ptr;
7573 ptr += nr_cpu_ids * sizeof(void **);
7575 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7576 ptr += nr_cpu_ids * sizeof(void **);
7578 #endif /* CONFIG_FAIR_GROUP_SCHED */
7579 #ifdef CONFIG_RT_GROUP_SCHED
7580 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7581 ptr += nr_cpu_ids * sizeof(void **);
7583 root_task_group.rt_rq = (struct rt_rq **)ptr;
7584 ptr += nr_cpu_ids * sizeof(void **);
7586 #endif /* CONFIG_RT_GROUP_SCHED */
7588 #ifdef CONFIG_CPUMASK_OFFSTACK
7589 for_each_possible_cpu(i) {
7590 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7591 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7592 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
7593 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7595 #endif /* CONFIG_CPUMASK_OFFSTACK */
7597 init_rt_bandwidth(&def_rt_bandwidth,
7598 global_rt_period(), global_rt_runtime());
7599 init_dl_bandwidth(&def_dl_bandwidth,
7600 global_rt_period(), global_rt_runtime());
7603 init_defrootdomain();
7606 #ifdef CONFIG_RT_GROUP_SCHED
7607 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7608 global_rt_period(), global_rt_runtime());
7609 #endif /* CONFIG_RT_GROUP_SCHED */
7611 #ifdef CONFIG_CGROUP_SCHED
7612 task_group_cache = KMEM_CACHE(task_group, 0);
7614 list_add(&root_task_group.list, &task_groups);
7615 INIT_LIST_HEAD(&root_task_group.children);
7616 INIT_LIST_HEAD(&root_task_group.siblings);
7617 autogroup_init(&init_task);
7618 #endif /* CONFIG_CGROUP_SCHED */
7620 for_each_possible_cpu(i) {
7624 raw_spin_lock_init(&rq->lock);
7626 rq->calc_load_active = 0;
7627 rq->calc_load_update = jiffies + LOAD_FREQ;
7628 init_cfs_rq(&rq->cfs);
7629 init_rt_rq(&rq->rt);
7630 init_dl_rq(&rq->dl);
7631 #ifdef CONFIG_FAIR_GROUP_SCHED
7632 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7633 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7634 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
7636 * How much cpu bandwidth does root_task_group get?
7638 * In case of task-groups formed thr' the cgroup filesystem, it
7639 * gets 100% of the cpu resources in the system. This overall
7640 * system cpu resource is divided among the tasks of
7641 * root_task_group and its child task-groups in a fair manner,
7642 * based on each entity's (task or task-group's) weight
7643 * (se->load.weight).
7645 * In other words, if root_task_group has 10 tasks of weight
7646 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7647 * then A0's share of the cpu resource is:
7649 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7651 * We achieve this by letting root_task_group's tasks sit
7652 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7654 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7655 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7656 #endif /* CONFIG_FAIR_GROUP_SCHED */
7658 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7659 #ifdef CONFIG_RT_GROUP_SCHED
7660 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7663 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7664 rq->cpu_load[j] = 0;
7669 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7670 rq->balance_callback = NULL;
7671 rq->active_balance = 0;
7672 rq->next_balance = jiffies;
7677 rq->avg_idle = 2*sysctl_sched_migration_cost;
7678 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7680 INIT_LIST_HEAD(&rq->cfs_tasks);
7682 rq_attach_root(rq, &def_root_domain);
7683 #ifdef CONFIG_NO_HZ_COMMON
7684 rq->last_load_update_tick = jiffies;
7687 #ifdef CONFIG_NO_HZ_FULL
7688 rq->last_sched_tick = 0;
7690 #endif /* CONFIG_SMP */
7692 atomic_set(&rq->nr_iowait, 0);
7695 set_load_weight(&init_task);
7698 * The boot idle thread does lazy MMU switching as well:
7700 atomic_inc(&init_mm.mm_count);
7701 enter_lazy_tlb(&init_mm, current);
7704 * Make us the idle thread. Technically, schedule() should not be
7705 * called from this thread, however somewhere below it might be,
7706 * but because we are the idle thread, we just pick up running again
7707 * when this runqueue becomes "idle".
7709 init_idle(current, smp_processor_id());
7711 calc_load_update = jiffies + LOAD_FREQ;
7714 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7715 /* May be allocated at isolcpus cmdline parse time */
7716 if (cpu_isolated_map == NULL)
7717 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7718 idle_thread_set_boot_cpu();
7719 set_cpu_rq_start_time(smp_processor_id());
7721 init_sched_fair_class();
7725 scheduler_running = 1;
7728 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7729 static inline int preempt_count_equals(int preempt_offset)
7731 int nested = preempt_count() + rcu_preempt_depth();
7733 return (nested == preempt_offset);
7736 void __might_sleep(const char *file, int line, int preempt_offset)
7739 * Blocking primitives will set (and therefore destroy) current->state,
7740 * since we will exit with TASK_RUNNING make sure we enter with it,
7741 * otherwise we will destroy state.
7743 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7744 "do not call blocking ops when !TASK_RUNNING; "
7745 "state=%lx set at [<%p>] %pS\n",
7747 (void *)current->task_state_change,
7748 (void *)current->task_state_change);
7750 ___might_sleep(file, line, preempt_offset);
7752 EXPORT_SYMBOL(__might_sleep);
7754 void ___might_sleep(const char *file, int line, int preempt_offset)
7756 static unsigned long prev_jiffy; /* ratelimiting */
7757 unsigned long preempt_disable_ip;
7759 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7760 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7761 !is_idle_task(current)) ||
7762 system_state != SYSTEM_RUNNING || oops_in_progress)
7764 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7766 prev_jiffy = jiffies;
7768 /* Save this before calling printk(), since that will clobber it */
7769 preempt_disable_ip = get_preempt_disable_ip(current);
7772 "BUG: sleeping function called from invalid context at %s:%d\n",
7775 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7776 in_atomic(), irqs_disabled(),
7777 current->pid, current->comm);
7779 if (task_stack_end_corrupted(current))
7780 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
7782 debug_show_held_locks(current);
7783 if (irqs_disabled())
7784 print_irqtrace_events(current);
7785 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
7786 && !preempt_count_equals(preempt_offset)) {
7787 pr_err("Preemption disabled at:");
7788 print_ip_sym(preempt_disable_ip);
7792 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
7794 EXPORT_SYMBOL(___might_sleep);
7797 #ifdef CONFIG_MAGIC_SYSRQ
7798 void normalize_rt_tasks(void)
7800 struct task_struct *g, *p;
7801 struct sched_attr attr = {
7802 .sched_policy = SCHED_NORMAL,
7805 read_lock(&tasklist_lock);
7806 for_each_process_thread(g, p) {
7808 * Only normalize user tasks:
7810 if (p->flags & PF_KTHREAD)
7813 p->se.exec_start = 0;
7814 schedstat_set(p->se.statistics.wait_start, 0);
7815 schedstat_set(p->se.statistics.sleep_start, 0);
7816 schedstat_set(p->se.statistics.block_start, 0);
7818 if (!dl_task(p) && !rt_task(p)) {
7820 * Renice negative nice level userspace
7823 if (task_nice(p) < 0)
7824 set_user_nice(p, 0);
7828 __sched_setscheduler(p, &attr, false, false);
7830 read_unlock(&tasklist_lock);
7833 #endif /* CONFIG_MAGIC_SYSRQ */
7835 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7837 * These functions are only useful for the IA64 MCA handling, or kdb.
7839 * They can only be called when the whole system has been
7840 * stopped - every CPU needs to be quiescent, and no scheduling
7841 * activity can take place. Using them for anything else would
7842 * be a serious bug, and as a result, they aren't even visible
7843 * under any other configuration.
7847 * curr_task - return the current task for a given cpu.
7848 * @cpu: the processor in question.
7850 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7852 * Return: The current task for @cpu.
7854 struct task_struct *curr_task(int cpu)
7856 return cpu_curr(cpu);
7859 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7863 * set_curr_task - set the current task for a given cpu.
7864 * @cpu: the processor in question.
7865 * @p: the task pointer to set.
7867 * Description: This function must only be used when non-maskable interrupts
7868 * are serviced on a separate stack. It allows the architecture to switch the
7869 * notion of the current task on a cpu in a non-blocking manner. This function
7870 * must be called with all CPU's synchronized, and interrupts disabled, the
7871 * and caller must save the original value of the current task (see
7872 * curr_task() above) and restore that value before reenabling interrupts and
7873 * re-starting the system.
7875 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7877 void ia64_set_curr_task(int cpu, struct task_struct *p)
7884 #ifdef CONFIG_CGROUP_SCHED
7885 /* task_group_lock serializes the addition/removal of task groups */
7886 static DEFINE_SPINLOCK(task_group_lock);
7888 static void sched_free_group(struct task_group *tg)
7890 free_fair_sched_group(tg);
7891 free_rt_sched_group(tg);
7893 kmem_cache_free(task_group_cache, tg);
7896 /* allocate runqueue etc for a new task group */
7897 struct task_group *sched_create_group(struct task_group *parent)
7899 struct task_group *tg;
7901 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
7903 return ERR_PTR(-ENOMEM);
7905 if (!alloc_fair_sched_group(tg, parent))
7908 if (!alloc_rt_sched_group(tg, parent))
7914 sched_free_group(tg);
7915 return ERR_PTR(-ENOMEM);
7918 void sched_online_group(struct task_group *tg, struct task_group *parent)
7920 unsigned long flags;
7922 spin_lock_irqsave(&task_group_lock, flags);
7923 list_add_rcu(&tg->list, &task_groups);
7925 WARN_ON(!parent); /* root should already exist */
7927 tg->parent = parent;
7928 INIT_LIST_HEAD(&tg->children);
7929 list_add_rcu(&tg->siblings, &parent->children);
7930 spin_unlock_irqrestore(&task_group_lock, flags);
7932 online_fair_sched_group(tg);
7935 /* rcu callback to free various structures associated with a task group */
7936 static void sched_free_group_rcu(struct rcu_head *rhp)
7938 /* now it should be safe to free those cfs_rqs */
7939 sched_free_group(container_of(rhp, struct task_group, rcu));
7942 void sched_destroy_group(struct task_group *tg)
7944 /* wait for possible concurrent references to cfs_rqs complete */
7945 call_rcu(&tg->rcu, sched_free_group_rcu);
7948 void sched_offline_group(struct task_group *tg)
7950 unsigned long flags;
7952 /* end participation in shares distribution */
7953 unregister_fair_sched_group(tg);
7955 spin_lock_irqsave(&task_group_lock, flags);
7956 list_del_rcu(&tg->list);
7957 list_del_rcu(&tg->siblings);
7958 spin_unlock_irqrestore(&task_group_lock, flags);
7961 static void sched_change_group(struct task_struct *tsk, int type)
7963 struct task_group *tg;
7966 * All callers are synchronized by task_rq_lock(); we do not use RCU
7967 * which is pointless here. Thus, we pass "true" to task_css_check()
7968 * to prevent lockdep warnings.
7970 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
7971 struct task_group, css);
7972 tg = autogroup_task_group(tsk, tg);
7973 tsk->sched_task_group = tg;
7975 #ifdef CONFIG_FAIR_GROUP_SCHED
7976 if (tsk->sched_class->task_change_group)
7977 tsk->sched_class->task_change_group(tsk, type);
7980 set_task_rq(tsk, task_cpu(tsk));
7984 * Change task's runqueue when it moves between groups.
7986 * The caller of this function should have put the task in its new group by
7987 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
7990 void sched_move_task(struct task_struct *tsk)
7992 int queued, running;
7996 rq = task_rq_lock(tsk, &rf);
7998 running = task_current(rq, tsk);
7999 queued = task_on_rq_queued(tsk);
8002 dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
8003 if (unlikely(running))
8004 put_prev_task(rq, tsk);
8006 sched_change_group(tsk, TASK_MOVE_GROUP);
8009 enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
8010 if (unlikely(running))
8011 set_curr_task(rq, tsk);
8013 task_rq_unlock(rq, tsk, &rf);
8015 #endif /* CONFIG_CGROUP_SCHED */
8017 #ifdef CONFIG_RT_GROUP_SCHED
8019 * Ensure that the real time constraints are schedulable.
8021 static DEFINE_MUTEX(rt_constraints_mutex);
8023 /* Must be called with tasklist_lock held */
8024 static inline int tg_has_rt_tasks(struct task_group *tg)
8026 struct task_struct *g, *p;
8029 * Autogroups do not have RT tasks; see autogroup_create().
8031 if (task_group_is_autogroup(tg))
8034 for_each_process_thread(g, p) {
8035 if (rt_task(p) && task_group(p) == tg)
8042 struct rt_schedulable_data {
8043 struct task_group *tg;
8048 static int tg_rt_schedulable(struct task_group *tg, void *data)
8050 struct rt_schedulable_data *d = data;
8051 struct task_group *child;
8052 unsigned long total, sum = 0;
8053 u64 period, runtime;
8055 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8056 runtime = tg->rt_bandwidth.rt_runtime;
8059 period = d->rt_period;
8060 runtime = d->rt_runtime;
8064 * Cannot have more runtime than the period.
8066 if (runtime > period && runtime != RUNTIME_INF)
8070 * Ensure we don't starve existing RT tasks.
8072 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8075 total = to_ratio(period, runtime);
8078 * Nobody can have more than the global setting allows.
8080 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8084 * The sum of our children's runtime should not exceed our own.
8086 list_for_each_entry_rcu(child, &tg->children, siblings) {
8087 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8088 runtime = child->rt_bandwidth.rt_runtime;
8090 if (child == d->tg) {
8091 period = d->rt_period;
8092 runtime = d->rt_runtime;
8095 sum += to_ratio(period, runtime);
8104 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8108 struct rt_schedulable_data data = {
8110 .rt_period = period,
8111 .rt_runtime = runtime,
8115 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
8121 static int tg_set_rt_bandwidth(struct task_group *tg,
8122 u64 rt_period, u64 rt_runtime)
8127 * Disallowing the root group RT runtime is BAD, it would disallow the
8128 * kernel creating (and or operating) RT threads.
8130 if (tg == &root_task_group && rt_runtime == 0)
8133 /* No period doesn't make any sense. */
8137 mutex_lock(&rt_constraints_mutex);
8138 read_lock(&tasklist_lock);
8139 err = __rt_schedulable(tg, rt_period, rt_runtime);
8143 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8144 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8145 tg->rt_bandwidth.rt_runtime = rt_runtime;
8147 for_each_possible_cpu(i) {
8148 struct rt_rq *rt_rq = tg->rt_rq[i];
8150 raw_spin_lock(&rt_rq->rt_runtime_lock);
8151 rt_rq->rt_runtime = rt_runtime;
8152 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8154 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8156 read_unlock(&tasklist_lock);
8157 mutex_unlock(&rt_constraints_mutex);
8162 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8164 u64 rt_runtime, rt_period;
8166 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8167 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8168 if (rt_runtime_us < 0)
8169 rt_runtime = RUNTIME_INF;
8171 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8174 static long sched_group_rt_runtime(struct task_group *tg)
8178 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8181 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8182 do_div(rt_runtime_us, NSEC_PER_USEC);
8183 return rt_runtime_us;
8186 static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
8188 u64 rt_runtime, rt_period;
8190 rt_period = rt_period_us * NSEC_PER_USEC;
8191 rt_runtime = tg->rt_bandwidth.rt_runtime;
8193 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8196 static long sched_group_rt_period(struct task_group *tg)
8200 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8201 do_div(rt_period_us, NSEC_PER_USEC);
8202 return rt_period_us;
8204 #endif /* CONFIG_RT_GROUP_SCHED */
8206 #ifdef CONFIG_RT_GROUP_SCHED
8207 static int sched_rt_global_constraints(void)
8211 mutex_lock(&rt_constraints_mutex);
8212 read_lock(&tasklist_lock);
8213 ret = __rt_schedulable(NULL, 0, 0);
8214 read_unlock(&tasklist_lock);
8215 mutex_unlock(&rt_constraints_mutex);
8220 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8222 /* Don't accept realtime tasks when there is no way for them to run */
8223 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8229 #else /* !CONFIG_RT_GROUP_SCHED */
8230 static int sched_rt_global_constraints(void)
8232 unsigned long flags;
8235 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8236 for_each_possible_cpu(i) {
8237 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8239 raw_spin_lock(&rt_rq->rt_runtime_lock);
8240 rt_rq->rt_runtime = global_rt_runtime();
8241 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8243 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8247 #endif /* CONFIG_RT_GROUP_SCHED */
8249 static int sched_dl_global_validate(void)
8251 u64 runtime = global_rt_runtime();
8252 u64 period = global_rt_period();
8253 u64 new_bw = to_ratio(period, runtime);
8256 unsigned long flags;
8259 * Here we want to check the bandwidth not being set to some
8260 * value smaller than the currently allocated bandwidth in
8261 * any of the root_domains.
8263 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
8264 * cycling on root_domains... Discussion on different/better
8265 * solutions is welcome!
8267 for_each_possible_cpu(cpu) {
8268 rcu_read_lock_sched();
8269 dl_b = dl_bw_of(cpu);
8271 raw_spin_lock_irqsave(&dl_b->lock, flags);
8272 if (new_bw < dl_b->total_bw)
8274 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8276 rcu_read_unlock_sched();
8285 static void sched_dl_do_global(void)
8290 unsigned long flags;
8292 def_dl_bandwidth.dl_period = global_rt_period();
8293 def_dl_bandwidth.dl_runtime = global_rt_runtime();
8295 if (global_rt_runtime() != RUNTIME_INF)
8296 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
8299 * FIXME: As above...
8301 for_each_possible_cpu(cpu) {
8302 rcu_read_lock_sched();
8303 dl_b = dl_bw_of(cpu);
8305 raw_spin_lock_irqsave(&dl_b->lock, flags);
8307 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8309 rcu_read_unlock_sched();
8313 static int sched_rt_global_validate(void)
8315 if (sysctl_sched_rt_period <= 0)
8318 if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
8319 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
8325 static void sched_rt_do_global(void)
8327 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8328 def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
8331 int sched_rt_handler(struct ctl_table *table, int write,
8332 void __user *buffer, size_t *lenp,
8335 int old_period, old_runtime;
8336 static DEFINE_MUTEX(mutex);
8340 old_period = sysctl_sched_rt_period;
8341 old_runtime = sysctl_sched_rt_runtime;
8343 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8345 if (!ret && write) {
8346 ret = sched_rt_global_validate();
8350 ret = sched_dl_global_validate();
8354 ret = sched_rt_global_constraints();
8358 sched_rt_do_global();
8359 sched_dl_do_global();
8363 sysctl_sched_rt_period = old_period;
8364 sysctl_sched_rt_runtime = old_runtime;
8366 mutex_unlock(&mutex);
8371 int sched_rr_handler(struct ctl_table *table, int write,
8372 void __user *buffer, size_t *lenp,
8376 static DEFINE_MUTEX(mutex);
8379 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8380 /* make sure that internally we keep jiffies */
8381 /* also, writing zero resets timeslice to default */
8382 if (!ret && write) {
8383 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
8384 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
8386 mutex_unlock(&mutex);
8390 #ifdef CONFIG_CGROUP_SCHED
8392 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8394 return css ? container_of(css, struct task_group, css) : NULL;
8397 static struct cgroup_subsys_state *
8398 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8400 struct task_group *parent = css_tg(parent_css);
8401 struct task_group *tg;
8404 /* This is early initialization for the top cgroup */
8405 return &root_task_group.css;
8408 tg = sched_create_group(parent);
8410 return ERR_PTR(-ENOMEM);
8412 sched_online_group(tg, parent);
8417 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
8419 struct task_group *tg = css_tg(css);
8421 sched_offline_group(tg);
8424 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8426 struct task_group *tg = css_tg(css);
8429 * Relies on the RCU grace period between css_released() and this.
8431 sched_free_group(tg);
8435 * This is called before wake_up_new_task(), therefore we really only
8436 * have to set its group bits, all the other stuff does not apply.
8438 static void cpu_cgroup_fork(struct task_struct *task)
8443 rq = task_rq_lock(task, &rf);
8445 update_rq_clock(rq);
8446 sched_change_group(task, TASK_SET_GROUP);
8448 task_rq_unlock(rq, task, &rf);
8451 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
8453 struct task_struct *task;
8454 struct cgroup_subsys_state *css;
8457 cgroup_taskset_for_each(task, css, tset) {
8458 #ifdef CONFIG_RT_GROUP_SCHED
8459 if (!sched_rt_can_attach(css_tg(css), task))
8462 /* We don't support RT-tasks being in separate groups */
8463 if (task->sched_class != &fair_sched_class)
8467 * Serialize against wake_up_new_task() such that if its
8468 * running, we're sure to observe its full state.
8470 raw_spin_lock_irq(&task->pi_lock);
8472 * Avoid calling sched_move_task() before wake_up_new_task()
8473 * has happened. This would lead to problems with PELT, due to
8474 * move wanting to detach+attach while we're not attached yet.
8476 if (task->state == TASK_NEW)
8478 raw_spin_unlock_irq(&task->pi_lock);
8486 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
8488 struct task_struct *task;
8489 struct cgroup_subsys_state *css;
8491 cgroup_taskset_for_each(task, css, tset)
8492 sched_move_task(task);
8495 #ifdef CONFIG_FAIR_GROUP_SCHED
8496 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8497 struct cftype *cftype, u64 shareval)
8499 return sched_group_set_shares(css_tg(css), scale_load(shareval));
8502 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8505 struct task_group *tg = css_tg(css);
8507 return (u64) scale_load_down(tg->shares);
8510 #ifdef CONFIG_CFS_BANDWIDTH
8511 static DEFINE_MUTEX(cfs_constraints_mutex);
8513 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8514 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8516 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8518 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8520 int i, ret = 0, runtime_enabled, runtime_was_enabled;
8521 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8523 if (tg == &root_task_group)
8527 * Ensure we have at some amount of bandwidth every period. This is
8528 * to prevent reaching a state of large arrears when throttled via
8529 * entity_tick() resulting in prolonged exit starvation.
8531 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8535 * Likewise, bound things on the otherside by preventing insane quota
8536 * periods. This also allows us to normalize in computing quota
8539 if (period > max_cfs_quota_period)
8543 * Prevent race between setting of cfs_rq->runtime_enabled and
8544 * unthrottle_offline_cfs_rqs().
8547 mutex_lock(&cfs_constraints_mutex);
8548 ret = __cfs_schedulable(tg, period, quota);
8552 runtime_enabled = quota != RUNTIME_INF;
8553 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8555 * If we need to toggle cfs_bandwidth_used, off->on must occur
8556 * before making related changes, and on->off must occur afterwards
8558 if (runtime_enabled && !runtime_was_enabled)
8559 cfs_bandwidth_usage_inc();
8560 raw_spin_lock_irq(&cfs_b->lock);
8561 cfs_b->period = ns_to_ktime(period);
8562 cfs_b->quota = quota;
8564 __refill_cfs_bandwidth_runtime(cfs_b);
8565 /* restart the period timer (if active) to handle new period expiry */
8566 if (runtime_enabled)
8567 start_cfs_bandwidth(cfs_b);
8568 raw_spin_unlock_irq(&cfs_b->lock);
8570 for_each_online_cpu(i) {
8571 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8572 struct rq *rq = cfs_rq->rq;
8574 raw_spin_lock_irq(&rq->lock);
8575 cfs_rq->runtime_enabled = runtime_enabled;
8576 cfs_rq->runtime_remaining = 0;
8578 if (cfs_rq->throttled)
8579 unthrottle_cfs_rq(cfs_rq);
8580 raw_spin_unlock_irq(&rq->lock);
8582 if (runtime_was_enabled && !runtime_enabled)
8583 cfs_bandwidth_usage_dec();
8585 mutex_unlock(&cfs_constraints_mutex);
8591 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8595 period = ktime_to_ns(tg->cfs_bandwidth.period);
8596 if (cfs_quota_us < 0)
8597 quota = RUNTIME_INF;
8599 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8601 return tg_set_cfs_bandwidth(tg, period, quota);
8604 long tg_get_cfs_quota(struct task_group *tg)
8608 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8611 quota_us = tg->cfs_bandwidth.quota;
8612 do_div(quota_us, NSEC_PER_USEC);
8617 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8621 period = (u64)cfs_period_us * NSEC_PER_USEC;
8622 quota = tg->cfs_bandwidth.quota;
8624 return tg_set_cfs_bandwidth(tg, period, quota);
8627 long tg_get_cfs_period(struct task_group *tg)
8631 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8632 do_div(cfs_period_us, NSEC_PER_USEC);
8634 return cfs_period_us;
8637 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8640 return tg_get_cfs_quota(css_tg(css));
8643 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8644 struct cftype *cftype, s64 cfs_quota_us)
8646 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8649 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8652 return tg_get_cfs_period(css_tg(css));
8655 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8656 struct cftype *cftype, u64 cfs_period_us)
8658 return tg_set_cfs_period(css_tg(css), cfs_period_us);
8661 struct cfs_schedulable_data {
8662 struct task_group *tg;
8667 * normalize group quota/period to be quota/max_period
8668 * note: units are usecs
8670 static u64 normalize_cfs_quota(struct task_group *tg,
8671 struct cfs_schedulable_data *d)
8679 period = tg_get_cfs_period(tg);
8680 quota = tg_get_cfs_quota(tg);
8683 /* note: these should typically be equivalent */
8684 if (quota == RUNTIME_INF || quota == -1)
8687 return to_ratio(period, quota);
8690 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8692 struct cfs_schedulable_data *d = data;
8693 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8694 s64 quota = 0, parent_quota = -1;
8697 quota = RUNTIME_INF;
8699 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8701 quota = normalize_cfs_quota(tg, d);
8702 parent_quota = parent_b->hierarchical_quota;
8705 * ensure max(child_quota) <= parent_quota, inherit when no
8708 if (quota == RUNTIME_INF)
8709 quota = parent_quota;
8710 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8713 cfs_b->hierarchical_quota = quota;
8718 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8721 struct cfs_schedulable_data data = {
8727 if (quota != RUNTIME_INF) {
8728 do_div(data.period, NSEC_PER_USEC);
8729 do_div(data.quota, NSEC_PER_USEC);
8733 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8739 static int cpu_stats_show(struct seq_file *sf, void *v)
8741 struct task_group *tg = css_tg(seq_css(sf));
8742 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8744 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8745 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8746 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8750 #endif /* CONFIG_CFS_BANDWIDTH */
8751 #endif /* CONFIG_FAIR_GROUP_SCHED */
8753 #ifdef CONFIG_RT_GROUP_SCHED
8754 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8755 struct cftype *cft, s64 val)
8757 return sched_group_set_rt_runtime(css_tg(css), val);
8760 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8763 return sched_group_rt_runtime(css_tg(css));
8766 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8767 struct cftype *cftype, u64 rt_period_us)
8769 return sched_group_set_rt_period(css_tg(css), rt_period_us);
8772 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8775 return sched_group_rt_period(css_tg(css));
8777 #endif /* CONFIG_RT_GROUP_SCHED */
8779 static struct cftype cpu_files[] = {
8780 #ifdef CONFIG_FAIR_GROUP_SCHED
8783 .read_u64 = cpu_shares_read_u64,
8784 .write_u64 = cpu_shares_write_u64,
8787 #ifdef CONFIG_CFS_BANDWIDTH
8789 .name = "cfs_quota_us",
8790 .read_s64 = cpu_cfs_quota_read_s64,
8791 .write_s64 = cpu_cfs_quota_write_s64,
8794 .name = "cfs_period_us",
8795 .read_u64 = cpu_cfs_period_read_u64,
8796 .write_u64 = cpu_cfs_period_write_u64,
8800 .seq_show = cpu_stats_show,
8803 #ifdef CONFIG_RT_GROUP_SCHED
8805 .name = "rt_runtime_us",
8806 .read_s64 = cpu_rt_runtime_read,
8807 .write_s64 = cpu_rt_runtime_write,
8810 .name = "rt_period_us",
8811 .read_u64 = cpu_rt_period_read_uint,
8812 .write_u64 = cpu_rt_period_write_uint,
8818 struct cgroup_subsys cpu_cgrp_subsys = {
8819 .css_alloc = cpu_cgroup_css_alloc,
8820 .css_released = cpu_cgroup_css_released,
8821 .css_free = cpu_cgroup_css_free,
8822 .fork = cpu_cgroup_fork,
8823 .can_attach = cpu_cgroup_can_attach,
8824 .attach = cpu_cgroup_attach,
8825 .legacy_cftypes = cpu_files,
8829 #endif /* CONFIG_CGROUP_SCHED */
8831 void dump_cpu_task(int cpu)
8833 pr_info("Task dump for CPU %d:\n", cpu);
8834 sched_show_task(cpu_curr(cpu));
8838 * Nice levels are multiplicative, with a gentle 10% change for every
8839 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
8840 * nice 1, it will get ~10% less CPU time than another CPU-bound task
8841 * that remained on nice 0.
8843 * The "10% effect" is relative and cumulative: from _any_ nice level,
8844 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
8845 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
8846 * If a task goes up by ~10% and another task goes down by ~10% then
8847 * the relative distance between them is ~25%.)
8849 const int sched_prio_to_weight[40] = {
8850 /* -20 */ 88761, 71755, 56483, 46273, 36291,
8851 /* -15 */ 29154, 23254, 18705, 14949, 11916,
8852 /* -10 */ 9548, 7620, 6100, 4904, 3906,
8853 /* -5 */ 3121, 2501, 1991, 1586, 1277,
8854 /* 0 */ 1024, 820, 655, 526, 423,
8855 /* 5 */ 335, 272, 215, 172, 137,
8856 /* 10 */ 110, 87, 70, 56, 45,
8857 /* 15 */ 36, 29, 23, 18, 15,
8861 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
8863 * In cases where the weight does not change often, we can use the
8864 * precalculated inverse to speed up arithmetics by turning divisions
8865 * into multiplications:
8867 const u32 sched_prio_to_wmult[40] = {
8868 /* -20 */ 48388, 59856, 76040, 92818, 118348,
8869 /* -15 */ 147320, 184698, 229616, 287308, 360437,
8870 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
8871 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
8872 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
8873 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
8874 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
8875 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,