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 <asm/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>
78 #include <asm/switch_to.h>
80 #include <asm/irq_regs.h>
81 #include <asm/mutex.h>
82 #ifdef CONFIG_PARAVIRT
83 #include <asm/paravirt.h>
87 #include "../workqueue_internal.h"
88 #include "../smpboot.h"
90 #define CREATE_TRACE_POINTS
91 #include <trace/events/sched.h>
93 DEFINE_MUTEX(sched_domains_mutex);
94 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
96 static void update_rq_clock_task(struct rq *rq, s64 delta);
98 void update_rq_clock(struct rq *rq)
102 lockdep_assert_held(&rq->lock);
104 if (rq->clock_skip_update & RQCF_ACT_SKIP)
107 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
111 update_rq_clock_task(rq, delta);
115 * Debugging: various feature bits
118 #define SCHED_FEAT(name, enabled) \
119 (1UL << __SCHED_FEAT_##name) * enabled |
121 const_debug unsigned int sysctl_sched_features =
122 #include "features.h"
128 * Number of tasks to iterate in a single balance run.
129 * Limited because this is done with IRQs disabled.
131 const_debug unsigned int sysctl_sched_nr_migrate = 32;
134 * period over which we average the RT time consumption, measured
139 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
142 * period over which we measure -rt task cpu usage in us.
145 unsigned int sysctl_sched_rt_period = 1000000;
147 __read_mostly int scheduler_running;
150 * part of the period that we allow rt tasks to run in us.
153 int sysctl_sched_rt_runtime = 950000;
155 /* cpus with isolated domains */
156 cpumask_var_t cpu_isolated_map;
159 * this_rq_lock - lock this runqueue and disable interrupts.
161 static struct rq *this_rq_lock(void)
168 raw_spin_lock(&rq->lock);
173 #ifdef CONFIG_SCHED_HRTICK
175 * Use HR-timers to deliver accurate preemption points.
178 static void hrtick_clear(struct rq *rq)
180 if (hrtimer_active(&rq->hrtick_timer))
181 hrtimer_cancel(&rq->hrtick_timer);
185 * High-resolution timer tick.
186 * Runs from hardirq context with interrupts disabled.
188 static enum hrtimer_restart hrtick(struct hrtimer *timer)
190 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
192 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
194 raw_spin_lock(&rq->lock);
196 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
197 raw_spin_unlock(&rq->lock);
199 return HRTIMER_NORESTART;
204 static void __hrtick_restart(struct rq *rq)
206 struct hrtimer *timer = &rq->hrtick_timer;
208 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
212 * called from hardirq (IPI) context
214 static void __hrtick_start(void *arg)
218 raw_spin_lock(&rq->lock);
219 __hrtick_restart(rq);
220 rq->hrtick_csd_pending = 0;
221 raw_spin_unlock(&rq->lock);
225 * Called to set the hrtick timer state.
227 * called with rq->lock held and irqs disabled
229 void hrtick_start(struct rq *rq, u64 delay)
231 struct hrtimer *timer = &rq->hrtick_timer;
236 * Don't schedule slices shorter than 10000ns, that just
237 * doesn't make sense and can cause timer DoS.
239 delta = max_t(s64, delay, 10000LL);
240 time = ktime_add_ns(timer->base->get_time(), delta);
242 hrtimer_set_expires(timer, time);
244 if (rq == this_rq()) {
245 __hrtick_restart(rq);
246 } else if (!rq->hrtick_csd_pending) {
247 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
248 rq->hrtick_csd_pending = 1;
253 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
255 int cpu = (int)(long)hcpu;
258 case CPU_UP_CANCELED:
259 case CPU_UP_CANCELED_FROZEN:
260 case CPU_DOWN_PREPARE:
261 case CPU_DOWN_PREPARE_FROZEN:
263 case CPU_DEAD_FROZEN:
264 hrtick_clear(cpu_rq(cpu));
271 static __init void init_hrtick(void)
273 hotcpu_notifier(hotplug_hrtick, 0);
277 * Called to set the hrtick timer state.
279 * called with rq->lock held and irqs disabled
281 void hrtick_start(struct rq *rq, u64 delay)
284 * Don't schedule slices shorter than 10000ns, that just
285 * doesn't make sense. Rely on vruntime for fairness.
287 delay = max_t(u64, delay, 10000LL);
288 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
289 HRTIMER_MODE_REL_PINNED);
292 static inline void init_hrtick(void)
295 #endif /* CONFIG_SMP */
297 static void init_rq_hrtick(struct rq *rq)
300 rq->hrtick_csd_pending = 0;
302 rq->hrtick_csd.flags = 0;
303 rq->hrtick_csd.func = __hrtick_start;
304 rq->hrtick_csd.info = rq;
307 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
308 rq->hrtick_timer.function = hrtick;
310 #else /* CONFIG_SCHED_HRTICK */
311 static inline void hrtick_clear(struct rq *rq)
315 static inline void init_rq_hrtick(struct rq *rq)
319 static inline void init_hrtick(void)
322 #endif /* CONFIG_SCHED_HRTICK */
324 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
326 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
327 * this avoids any races wrt polling state changes and thereby avoids
330 static bool set_nr_and_not_polling(struct task_struct *p)
332 struct thread_info *ti = task_thread_info(p);
333 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
337 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
339 * If this returns true, then the idle task promises to call
340 * sched_ttwu_pending() and reschedule soon.
342 static bool set_nr_if_polling(struct task_struct *p)
344 struct thread_info *ti = task_thread_info(p);
345 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
348 if (!(val & _TIF_POLLING_NRFLAG))
350 if (val & _TIF_NEED_RESCHED)
352 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
361 static bool set_nr_and_not_polling(struct task_struct *p)
363 set_tsk_need_resched(p);
368 static bool set_nr_if_polling(struct task_struct *p)
375 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
377 struct wake_q_node *node = &task->wake_q;
380 * Atomically grab the task, if ->wake_q is !nil already it means
381 * its already queued (either by us or someone else) and will get the
382 * wakeup due to that.
384 * This cmpxchg() implies a full barrier, which pairs with the write
385 * barrier implied by the wakeup in wake_up_list().
387 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
390 get_task_struct(task);
393 * The head is context local, there can be no concurrency.
396 head->lastp = &node->next;
399 void wake_up_q(struct wake_q_head *head)
401 struct wake_q_node *node = head->first;
403 while (node != WAKE_Q_TAIL) {
404 struct task_struct *task;
406 task = container_of(node, struct task_struct, wake_q);
408 /* task can safely be re-inserted now */
410 task->wake_q.next = NULL;
413 * wake_up_process() implies a wmb() to pair with the queueing
414 * in wake_q_add() so as not to miss wakeups.
416 wake_up_process(task);
417 put_task_struct(task);
422 * resched_curr - mark rq's current task 'to be rescheduled now'.
424 * On UP this means the setting of the need_resched flag, on SMP it
425 * might also involve a cross-CPU call to trigger the scheduler on
428 void resched_curr(struct rq *rq)
430 struct task_struct *curr = rq->curr;
433 lockdep_assert_held(&rq->lock);
435 if (test_tsk_need_resched(curr))
440 if (cpu == smp_processor_id()) {
441 set_tsk_need_resched(curr);
442 set_preempt_need_resched();
446 if (set_nr_and_not_polling(curr))
447 smp_send_reschedule(cpu);
449 trace_sched_wake_idle_without_ipi(cpu);
452 void resched_cpu(int cpu)
454 struct rq *rq = cpu_rq(cpu);
457 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
460 raw_spin_unlock_irqrestore(&rq->lock, flags);
464 #ifdef CONFIG_NO_HZ_COMMON
466 * In the semi idle case, use the nearest busy cpu for migrating timers
467 * from an idle cpu. This is good for power-savings.
469 * We don't do similar optimization for completely idle system, as
470 * selecting an idle cpu will add more delays to the timers than intended
471 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
473 int get_nohz_timer_target(void)
475 int i, cpu = smp_processor_id();
476 struct sched_domain *sd;
478 if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
482 for_each_domain(cpu, sd) {
483 for_each_cpu(i, sched_domain_span(sd)) {
484 if (!idle_cpu(i) && is_housekeeping_cpu(cpu)) {
491 if (!is_housekeeping_cpu(cpu))
492 cpu = housekeeping_any_cpu();
498 * When add_timer_on() enqueues a timer into the timer wheel of an
499 * idle CPU then this timer might expire before the next timer event
500 * which is scheduled to wake up that CPU. In case of a completely
501 * idle system the next event might even be infinite time into the
502 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
503 * leaves the inner idle loop so the newly added timer is taken into
504 * account when the CPU goes back to idle and evaluates the timer
505 * wheel for the next timer event.
507 static void wake_up_idle_cpu(int cpu)
509 struct rq *rq = cpu_rq(cpu);
511 if (cpu == smp_processor_id())
514 if (set_nr_and_not_polling(rq->idle))
515 smp_send_reschedule(cpu);
517 trace_sched_wake_idle_without_ipi(cpu);
520 static bool wake_up_full_nohz_cpu(int cpu)
523 * We just need the target to call irq_exit() and re-evaluate
524 * the next tick. The nohz full kick at least implies that.
525 * If needed we can still optimize that later with an
528 if (tick_nohz_full_cpu(cpu)) {
529 if (cpu != smp_processor_id() ||
530 tick_nohz_tick_stopped())
531 tick_nohz_full_kick_cpu(cpu);
538 void wake_up_nohz_cpu(int cpu)
540 if (!wake_up_full_nohz_cpu(cpu))
541 wake_up_idle_cpu(cpu);
544 static inline bool got_nohz_idle_kick(void)
546 int cpu = smp_processor_id();
548 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
551 if (idle_cpu(cpu) && !need_resched())
555 * We can't run Idle Load Balance on this CPU for this time so we
556 * cancel it and clear NOHZ_BALANCE_KICK
558 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
562 #else /* CONFIG_NO_HZ_COMMON */
564 static inline bool got_nohz_idle_kick(void)
569 #endif /* CONFIG_NO_HZ_COMMON */
571 #ifdef CONFIG_NO_HZ_FULL
572 bool sched_can_stop_tick(struct rq *rq)
576 /* Deadline tasks, even if single, need the tick */
577 if (rq->dl.dl_nr_running)
581 * FIFO realtime policy runs the highest priority task (after DEADLINE).
582 * Other runnable tasks are of a lower priority. The scheduler tick
585 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
590 * Round-robin realtime tasks time slice with other tasks at the same
593 if (rq->rt.rr_nr_running) {
594 if (rq->rt.rr_nr_running == 1)
600 /* Normal multitasking need periodic preemption checks */
601 if (rq->cfs.nr_running > 1)
606 #endif /* CONFIG_NO_HZ_FULL */
608 void sched_avg_update(struct rq *rq)
610 s64 period = sched_avg_period();
612 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
614 * Inline assembly required to prevent the compiler
615 * optimising this loop into a divmod call.
616 * See __iter_div_u64_rem() for another example of this.
618 asm("" : "+rm" (rq->age_stamp));
619 rq->age_stamp += period;
624 #endif /* CONFIG_SMP */
626 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
627 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
629 * Iterate task_group tree rooted at *from, calling @down when first entering a
630 * node and @up when leaving it for the final time.
632 * Caller must hold rcu_lock or sufficient equivalent.
634 int walk_tg_tree_from(struct task_group *from,
635 tg_visitor down, tg_visitor up, void *data)
637 struct task_group *parent, *child;
643 ret = (*down)(parent, data);
646 list_for_each_entry_rcu(child, &parent->children, siblings) {
653 ret = (*up)(parent, data);
654 if (ret || parent == from)
658 parent = parent->parent;
665 int tg_nop(struct task_group *tg, void *data)
671 static void set_load_weight(struct task_struct *p)
673 int prio = p->static_prio - MAX_RT_PRIO;
674 struct load_weight *load = &p->se.load;
677 * SCHED_IDLE tasks get minimal weight:
679 if (idle_policy(p->policy)) {
680 load->weight = scale_load(WEIGHT_IDLEPRIO);
681 load->inv_weight = WMULT_IDLEPRIO;
685 load->weight = scale_load(sched_prio_to_weight[prio]);
686 load->inv_weight = sched_prio_to_wmult[prio];
689 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
692 if (!(flags & ENQUEUE_RESTORE))
693 sched_info_queued(rq, p);
694 p->sched_class->enqueue_task(rq, p, flags);
697 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
700 if (!(flags & DEQUEUE_SAVE))
701 sched_info_dequeued(rq, p);
702 p->sched_class->dequeue_task(rq, p, flags);
705 void activate_task(struct rq *rq, struct task_struct *p, int flags)
707 if (task_contributes_to_load(p))
708 rq->nr_uninterruptible--;
710 enqueue_task(rq, p, flags);
713 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
715 if (task_contributes_to_load(p))
716 rq->nr_uninterruptible++;
718 dequeue_task(rq, p, flags);
721 static void update_rq_clock_task(struct rq *rq, s64 delta)
724 * In theory, the compile should just see 0 here, and optimize out the call
725 * to sched_rt_avg_update. But I don't trust it...
727 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
728 s64 steal = 0, irq_delta = 0;
730 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
731 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
734 * Since irq_time is only updated on {soft,}irq_exit, we might run into
735 * this case when a previous update_rq_clock() happened inside a
738 * When this happens, we stop ->clock_task and only update the
739 * prev_irq_time stamp to account for the part that fit, so that a next
740 * update will consume the rest. This ensures ->clock_task is
743 * It does however cause some slight miss-attribution of {soft,}irq
744 * time, a more accurate solution would be to update the irq_time using
745 * the current rq->clock timestamp, except that would require using
748 if (irq_delta > delta)
751 rq->prev_irq_time += irq_delta;
754 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
755 if (static_key_false((¶virt_steal_rq_enabled))) {
756 steal = paravirt_steal_clock(cpu_of(rq));
757 steal -= rq->prev_steal_time_rq;
759 if (unlikely(steal > delta))
762 rq->prev_steal_time_rq += steal;
767 rq->clock_task += delta;
769 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
770 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
771 sched_rt_avg_update(rq, irq_delta + steal);
775 void sched_set_stop_task(int cpu, struct task_struct *stop)
777 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
778 struct task_struct *old_stop = cpu_rq(cpu)->stop;
782 * Make it appear like a SCHED_FIFO task, its something
783 * userspace knows about and won't get confused about.
785 * Also, it will make PI more or less work without too
786 * much confusion -- but then, stop work should not
787 * rely on PI working anyway.
789 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
791 stop->sched_class = &stop_sched_class;
794 cpu_rq(cpu)->stop = stop;
798 * Reset it back to a normal scheduling class so that
799 * it can die in pieces.
801 old_stop->sched_class = &rt_sched_class;
806 * __normal_prio - return the priority that is based on the static prio
808 static inline int __normal_prio(struct task_struct *p)
810 return p->static_prio;
814 * Calculate the expected normal priority: i.e. priority
815 * without taking RT-inheritance into account. Might be
816 * boosted by interactivity modifiers. Changes upon fork,
817 * setprio syscalls, and whenever the interactivity
818 * estimator recalculates.
820 static inline int normal_prio(struct task_struct *p)
824 if (task_has_dl_policy(p))
825 prio = MAX_DL_PRIO-1;
826 else if (task_has_rt_policy(p))
827 prio = MAX_RT_PRIO-1 - p->rt_priority;
829 prio = __normal_prio(p);
834 * Calculate the current priority, i.e. the priority
835 * taken into account by the scheduler. This value might
836 * be boosted by RT tasks, or might be boosted by
837 * interactivity modifiers. Will be RT if the task got
838 * RT-boosted. If not then it returns p->normal_prio.
840 static int effective_prio(struct task_struct *p)
842 p->normal_prio = normal_prio(p);
844 * If we are RT tasks or we were boosted to RT priority,
845 * keep the priority unchanged. Otherwise, update priority
846 * to the normal priority:
848 if (!rt_prio(p->prio))
849 return p->normal_prio;
854 * task_curr - is this task currently executing on a CPU?
855 * @p: the task in question.
857 * Return: 1 if the task is currently executing. 0 otherwise.
859 inline int task_curr(const struct task_struct *p)
861 return cpu_curr(task_cpu(p)) == p;
865 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
866 * use the balance_callback list if you want balancing.
868 * this means any call to check_class_changed() must be followed by a call to
869 * balance_callback().
871 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
872 const struct sched_class *prev_class,
875 if (prev_class != p->sched_class) {
876 if (prev_class->switched_from)
877 prev_class->switched_from(rq, p);
879 p->sched_class->switched_to(rq, p);
880 } else if (oldprio != p->prio || dl_task(p))
881 p->sched_class->prio_changed(rq, p, oldprio);
884 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
886 const struct sched_class *class;
888 if (p->sched_class == rq->curr->sched_class) {
889 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
891 for_each_class(class) {
892 if (class == rq->curr->sched_class)
894 if (class == p->sched_class) {
902 * A queue event has occurred, and we're going to schedule. In
903 * this case, we can save a useless back to back clock update.
905 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
906 rq_clock_skip_update(rq, true);
911 * This is how migration works:
913 * 1) we invoke migration_cpu_stop() on the target CPU using
915 * 2) stopper starts to run (implicitly forcing the migrated thread
917 * 3) it checks whether the migrated task is still in the wrong runqueue.
918 * 4) if it's in the wrong runqueue then the migration thread removes
919 * it and puts it into the right queue.
920 * 5) stopper completes and stop_one_cpu() returns and the migration
925 * move_queued_task - move a queued task to new rq.
927 * Returns (locked) new rq. Old rq's lock is released.
929 static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
931 lockdep_assert_held(&rq->lock);
933 p->on_rq = TASK_ON_RQ_MIGRATING;
934 dequeue_task(rq, p, 0);
935 set_task_cpu(p, new_cpu);
936 raw_spin_unlock(&rq->lock);
938 rq = cpu_rq(new_cpu);
940 raw_spin_lock(&rq->lock);
941 BUG_ON(task_cpu(p) != new_cpu);
942 enqueue_task(rq, p, 0);
943 p->on_rq = TASK_ON_RQ_QUEUED;
944 check_preempt_curr(rq, p, 0);
949 struct migration_arg {
950 struct task_struct *task;
955 * Move (not current) task off this cpu, onto dest cpu. We're doing
956 * this because either it can't run here any more (set_cpus_allowed()
957 * away from this CPU, or CPU going down), or because we're
958 * attempting to rebalance this task on exec (sched_exec).
960 * So we race with normal scheduler movements, but that's OK, as long
961 * as the task is no longer on this CPU.
963 static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
965 if (unlikely(!cpu_active(dest_cpu)))
968 /* Affinity changed (again). */
969 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
972 rq = move_queued_task(rq, p, dest_cpu);
978 * migration_cpu_stop - this will be executed by a highprio stopper thread
979 * and performs thread migration by bumping thread off CPU then
980 * 'pushing' onto another runqueue.
982 static int migration_cpu_stop(void *data)
984 struct migration_arg *arg = data;
985 struct task_struct *p = arg->task;
986 struct rq *rq = this_rq();
989 * The original target cpu might have gone down and we might
990 * be on another cpu but it doesn't matter.
994 * We need to explicitly wake pending tasks before running
995 * __migrate_task() such that we will not miss enforcing cpus_allowed
996 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
998 sched_ttwu_pending();
1000 raw_spin_lock(&p->pi_lock);
1001 raw_spin_lock(&rq->lock);
1003 * If task_rq(p) != rq, it cannot be migrated here, because we're
1004 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1005 * we're holding p->pi_lock.
1007 if (task_rq(p) == rq && task_on_rq_queued(p))
1008 rq = __migrate_task(rq, p, arg->dest_cpu);
1009 raw_spin_unlock(&rq->lock);
1010 raw_spin_unlock(&p->pi_lock);
1017 * sched_class::set_cpus_allowed must do the below, but is not required to
1018 * actually call this function.
1020 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1022 cpumask_copy(&p->cpus_allowed, new_mask);
1023 p->nr_cpus_allowed = cpumask_weight(new_mask);
1026 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1028 struct rq *rq = task_rq(p);
1029 bool queued, running;
1031 lockdep_assert_held(&p->pi_lock);
1033 queued = task_on_rq_queued(p);
1034 running = task_current(rq, p);
1038 * Because __kthread_bind() calls this on blocked tasks without
1041 lockdep_assert_held(&rq->lock);
1042 dequeue_task(rq, p, DEQUEUE_SAVE);
1045 put_prev_task(rq, p);
1047 p->sched_class->set_cpus_allowed(p, new_mask);
1050 p->sched_class->set_curr_task(rq);
1052 enqueue_task(rq, p, ENQUEUE_RESTORE);
1056 * Change a given task's CPU affinity. Migrate the thread to a
1057 * proper CPU and schedule it away if the CPU it's executing on
1058 * is removed from the allowed bitmask.
1060 * NOTE: the caller must have a valid reference to the task, the
1061 * task must not exit() & deallocate itself prematurely. The
1062 * call is not atomic; no spinlocks may be held.
1064 static int __set_cpus_allowed_ptr(struct task_struct *p,
1065 const struct cpumask *new_mask, bool check)
1067 unsigned long flags;
1069 unsigned int dest_cpu;
1072 rq = task_rq_lock(p, &flags);
1075 * Must re-check here, to close a race against __kthread_bind(),
1076 * sched_setaffinity() is not guaranteed to observe the flag.
1078 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1083 if (cpumask_equal(&p->cpus_allowed, new_mask))
1086 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
1091 do_set_cpus_allowed(p, new_mask);
1093 /* Can the task run on the task's current CPU? If so, we're done */
1094 if (cpumask_test_cpu(task_cpu(p), new_mask))
1097 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
1098 if (task_running(rq, p) || p->state == TASK_WAKING) {
1099 struct migration_arg arg = { p, dest_cpu };
1100 /* Need help from migration thread: drop lock and wait. */
1101 task_rq_unlock(rq, p, &flags);
1102 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1103 tlb_migrate_finish(p->mm);
1105 } else if (task_on_rq_queued(p)) {
1107 * OK, since we're going to drop the lock immediately
1108 * afterwards anyway.
1110 lockdep_unpin_lock(&rq->lock);
1111 rq = move_queued_task(rq, p, dest_cpu);
1112 lockdep_pin_lock(&rq->lock);
1115 task_rq_unlock(rq, p, &flags);
1120 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1122 return __set_cpus_allowed_ptr(p, new_mask, false);
1124 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1126 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1128 #ifdef CONFIG_SCHED_DEBUG
1130 * We should never call set_task_cpu() on a blocked task,
1131 * ttwu() will sort out the placement.
1133 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1137 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1138 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1139 * time relying on p->on_rq.
1141 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1142 p->sched_class == &fair_sched_class &&
1143 (p->on_rq && !task_on_rq_migrating(p)));
1145 #ifdef CONFIG_LOCKDEP
1147 * The caller should hold either p->pi_lock or rq->lock, when changing
1148 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1150 * sched_move_task() holds both and thus holding either pins the cgroup,
1153 * Furthermore, all task_rq users should acquire both locks, see
1156 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1157 lockdep_is_held(&task_rq(p)->lock)));
1161 trace_sched_migrate_task(p, new_cpu);
1163 if (task_cpu(p) != new_cpu) {
1164 if (p->sched_class->migrate_task_rq)
1165 p->sched_class->migrate_task_rq(p);
1166 p->se.nr_migrations++;
1167 perf_event_task_migrate(p);
1170 __set_task_cpu(p, new_cpu);
1173 static void __migrate_swap_task(struct task_struct *p, int cpu)
1175 if (task_on_rq_queued(p)) {
1176 struct rq *src_rq, *dst_rq;
1178 src_rq = task_rq(p);
1179 dst_rq = cpu_rq(cpu);
1181 p->on_rq = TASK_ON_RQ_MIGRATING;
1182 deactivate_task(src_rq, p, 0);
1183 set_task_cpu(p, cpu);
1184 activate_task(dst_rq, p, 0);
1185 p->on_rq = TASK_ON_RQ_QUEUED;
1186 check_preempt_curr(dst_rq, p, 0);
1189 * Task isn't running anymore; make it appear like we migrated
1190 * it before it went to sleep. This means on wakeup we make the
1191 * previous cpu our targer instead of where it really is.
1197 struct migration_swap_arg {
1198 struct task_struct *src_task, *dst_task;
1199 int src_cpu, dst_cpu;
1202 static int migrate_swap_stop(void *data)
1204 struct migration_swap_arg *arg = data;
1205 struct rq *src_rq, *dst_rq;
1208 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1211 src_rq = cpu_rq(arg->src_cpu);
1212 dst_rq = cpu_rq(arg->dst_cpu);
1214 double_raw_lock(&arg->src_task->pi_lock,
1215 &arg->dst_task->pi_lock);
1216 double_rq_lock(src_rq, dst_rq);
1218 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1221 if (task_cpu(arg->src_task) != arg->src_cpu)
1224 if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
1227 if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
1230 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1231 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1236 double_rq_unlock(src_rq, dst_rq);
1237 raw_spin_unlock(&arg->dst_task->pi_lock);
1238 raw_spin_unlock(&arg->src_task->pi_lock);
1244 * Cross migrate two tasks
1246 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1248 struct migration_swap_arg arg;
1251 arg = (struct migration_swap_arg){
1253 .src_cpu = task_cpu(cur),
1255 .dst_cpu = task_cpu(p),
1258 if (arg.src_cpu == arg.dst_cpu)
1262 * These three tests are all lockless; this is OK since all of them
1263 * will be re-checked with proper locks held further down the line.
1265 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1268 if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
1271 if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
1274 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1275 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1282 * wait_task_inactive - wait for a thread to unschedule.
1284 * If @match_state is nonzero, it's the @p->state value just checked and
1285 * not expected to change. If it changes, i.e. @p might have woken up,
1286 * then return zero. When we succeed in waiting for @p to be off its CPU,
1287 * we return a positive number (its total switch count). If a second call
1288 * a short while later returns the same number, the caller can be sure that
1289 * @p has remained unscheduled the whole time.
1291 * The caller must ensure that the task *will* unschedule sometime soon,
1292 * else this function might spin for a *long* time. This function can't
1293 * be called with interrupts off, or it may introduce deadlock with
1294 * smp_call_function() if an IPI is sent by the same process we are
1295 * waiting to become inactive.
1297 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1299 unsigned long flags;
1300 int running, queued;
1306 * We do the initial early heuristics without holding
1307 * any task-queue locks at all. We'll only try to get
1308 * the runqueue lock when things look like they will
1314 * If the task is actively running on another CPU
1315 * still, just relax and busy-wait without holding
1318 * NOTE! Since we don't hold any locks, it's not
1319 * even sure that "rq" stays as the right runqueue!
1320 * But we don't care, since "task_running()" will
1321 * return false if the runqueue has changed and p
1322 * is actually now running somewhere else!
1324 while (task_running(rq, p)) {
1325 if (match_state && unlikely(p->state != match_state))
1331 * Ok, time to look more closely! We need the rq
1332 * lock now, to be *sure*. If we're wrong, we'll
1333 * just go back and repeat.
1335 rq = task_rq_lock(p, &flags);
1336 trace_sched_wait_task(p);
1337 running = task_running(rq, p);
1338 queued = task_on_rq_queued(p);
1340 if (!match_state || p->state == match_state)
1341 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1342 task_rq_unlock(rq, p, &flags);
1345 * If it changed from the expected state, bail out now.
1347 if (unlikely(!ncsw))
1351 * Was it really running after all now that we
1352 * checked with the proper locks actually held?
1354 * Oops. Go back and try again..
1356 if (unlikely(running)) {
1362 * It's not enough that it's not actively running,
1363 * it must be off the runqueue _entirely_, and not
1366 * So if it was still runnable (but just not actively
1367 * running right now), it's preempted, and we should
1368 * yield - it could be a while.
1370 if (unlikely(queued)) {
1371 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1373 set_current_state(TASK_UNINTERRUPTIBLE);
1374 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1379 * Ahh, all good. It wasn't running, and it wasn't
1380 * runnable, which means that it will never become
1381 * running in the future either. We're all done!
1390 * kick_process - kick a running thread to enter/exit the kernel
1391 * @p: the to-be-kicked thread
1393 * Cause a process which is running on another CPU to enter
1394 * kernel-mode, without any delay. (to get signals handled.)
1396 * NOTE: this function doesn't have to take the runqueue lock,
1397 * because all it wants to ensure is that the remote task enters
1398 * the kernel. If the IPI races and the task has been migrated
1399 * to another CPU then no harm is done and the purpose has been
1402 void kick_process(struct task_struct *p)
1408 if ((cpu != smp_processor_id()) && task_curr(p))
1409 smp_send_reschedule(cpu);
1412 EXPORT_SYMBOL_GPL(kick_process);
1415 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1417 static int select_fallback_rq(int cpu, struct task_struct *p)
1419 int nid = cpu_to_node(cpu);
1420 const struct cpumask *nodemask = NULL;
1421 enum { cpuset, possible, fail } state = cpuset;
1425 * If the node that the cpu is on has been offlined, cpu_to_node()
1426 * will return -1. There is no cpu on the node, and we should
1427 * select the cpu on the other node.
1430 nodemask = cpumask_of_node(nid);
1432 /* Look for allowed, online CPU in same node. */
1433 for_each_cpu(dest_cpu, nodemask) {
1434 if (!cpu_online(dest_cpu))
1436 if (!cpu_active(dest_cpu))
1438 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1444 /* Any allowed, online CPU? */
1445 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1446 if (!cpu_online(dest_cpu))
1448 if (!cpu_active(dest_cpu))
1453 /* No more Mr. Nice Guy. */
1456 if (IS_ENABLED(CONFIG_CPUSETS)) {
1457 cpuset_cpus_allowed_fallback(p);
1463 do_set_cpus_allowed(p, cpu_possible_mask);
1474 if (state != cpuset) {
1476 * Don't tell them about moving exiting tasks or
1477 * kernel threads (both mm NULL), since they never
1480 if (p->mm && printk_ratelimit()) {
1481 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1482 task_pid_nr(p), p->comm, cpu);
1490 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1493 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1495 lockdep_assert_held(&p->pi_lock);
1497 if (p->nr_cpus_allowed > 1)
1498 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1501 * In order not to call set_task_cpu() on a blocking task we need
1502 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1505 * Since this is common to all placement strategies, this lives here.
1507 * [ this allows ->select_task() to simply return task_cpu(p) and
1508 * not worry about this generic constraint ]
1510 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1512 cpu = select_fallback_rq(task_cpu(p), p);
1517 static void update_avg(u64 *avg, u64 sample)
1519 s64 diff = sample - *avg;
1525 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1526 const struct cpumask *new_mask, bool check)
1528 return set_cpus_allowed_ptr(p, new_mask);
1531 #endif /* CONFIG_SMP */
1534 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1536 #ifdef CONFIG_SCHEDSTATS
1537 struct rq *rq = this_rq();
1540 int this_cpu = smp_processor_id();
1542 if (cpu == this_cpu) {
1543 schedstat_inc(rq, ttwu_local);
1544 schedstat_inc(p, se.statistics.nr_wakeups_local);
1546 struct sched_domain *sd;
1548 schedstat_inc(p, se.statistics.nr_wakeups_remote);
1550 for_each_domain(this_cpu, sd) {
1551 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1552 schedstat_inc(sd, ttwu_wake_remote);
1559 if (wake_flags & WF_MIGRATED)
1560 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
1562 #endif /* CONFIG_SMP */
1564 schedstat_inc(rq, ttwu_count);
1565 schedstat_inc(p, se.statistics.nr_wakeups);
1567 if (wake_flags & WF_SYNC)
1568 schedstat_inc(p, se.statistics.nr_wakeups_sync);
1570 #endif /* CONFIG_SCHEDSTATS */
1573 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1575 activate_task(rq, p, en_flags);
1576 p->on_rq = TASK_ON_RQ_QUEUED;
1578 /* if a worker is waking up, notify workqueue */
1579 if (p->flags & PF_WQ_WORKER)
1580 wq_worker_waking_up(p, cpu_of(rq));
1584 * Mark the task runnable and perform wakeup-preemption.
1587 ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
1589 check_preempt_curr(rq, p, wake_flags);
1590 p->state = TASK_RUNNING;
1591 trace_sched_wakeup(p);
1594 if (p->sched_class->task_woken) {
1596 * Our task @p is fully woken up and running; so its safe to
1597 * drop the rq->lock, hereafter rq is only used for statistics.
1599 lockdep_unpin_lock(&rq->lock);
1600 p->sched_class->task_woken(rq, p);
1601 lockdep_pin_lock(&rq->lock);
1604 if (rq->idle_stamp) {
1605 u64 delta = rq_clock(rq) - rq->idle_stamp;
1606 u64 max = 2*rq->max_idle_balance_cost;
1608 update_avg(&rq->avg_idle, delta);
1610 if (rq->avg_idle > max)
1619 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
1621 lockdep_assert_held(&rq->lock);
1624 if (p->sched_contributes_to_load)
1625 rq->nr_uninterruptible--;
1628 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
1629 ttwu_do_wakeup(rq, p, wake_flags);
1633 * Called in case the task @p isn't fully descheduled from its runqueue,
1634 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1635 * since all we need to do is flip p->state to TASK_RUNNING, since
1636 * the task is still ->on_rq.
1638 static int ttwu_remote(struct task_struct *p, int wake_flags)
1643 rq = __task_rq_lock(p);
1644 if (task_on_rq_queued(p)) {
1645 /* check_preempt_curr() may use rq clock */
1646 update_rq_clock(rq);
1647 ttwu_do_wakeup(rq, p, wake_flags);
1650 __task_rq_unlock(rq);
1656 void sched_ttwu_pending(void)
1658 struct rq *rq = this_rq();
1659 struct llist_node *llist = llist_del_all(&rq->wake_list);
1660 struct task_struct *p;
1661 unsigned long flags;
1666 raw_spin_lock_irqsave(&rq->lock, flags);
1667 lockdep_pin_lock(&rq->lock);
1670 p = llist_entry(llist, struct task_struct, wake_entry);
1671 llist = llist_next(llist);
1672 ttwu_do_activate(rq, p, 0);
1675 lockdep_unpin_lock(&rq->lock);
1676 raw_spin_unlock_irqrestore(&rq->lock, flags);
1679 void scheduler_ipi(void)
1682 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1683 * TIF_NEED_RESCHED remotely (for the first time) will also send
1686 preempt_fold_need_resched();
1688 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1692 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1693 * traditionally all their work was done from the interrupt return
1694 * path. Now that we actually do some work, we need to make sure
1697 * Some archs already do call them, luckily irq_enter/exit nest
1700 * Arguably we should visit all archs and update all handlers,
1701 * however a fair share of IPIs are still resched only so this would
1702 * somewhat pessimize the simple resched case.
1705 sched_ttwu_pending();
1708 * Check if someone kicked us for doing the nohz idle load balance.
1710 if (unlikely(got_nohz_idle_kick())) {
1711 this_rq()->idle_balance = 1;
1712 raise_softirq_irqoff(SCHED_SOFTIRQ);
1717 static void ttwu_queue_remote(struct task_struct *p, int cpu)
1719 struct rq *rq = cpu_rq(cpu);
1721 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1722 if (!set_nr_if_polling(rq->idle))
1723 smp_send_reschedule(cpu);
1725 trace_sched_wake_idle_without_ipi(cpu);
1729 void wake_up_if_idle(int cpu)
1731 struct rq *rq = cpu_rq(cpu);
1732 unsigned long flags;
1736 if (!is_idle_task(rcu_dereference(rq->curr)))
1739 if (set_nr_if_polling(rq->idle)) {
1740 trace_sched_wake_idle_without_ipi(cpu);
1742 raw_spin_lock_irqsave(&rq->lock, flags);
1743 if (is_idle_task(rq->curr))
1744 smp_send_reschedule(cpu);
1745 /* Else cpu is not in idle, do nothing here */
1746 raw_spin_unlock_irqrestore(&rq->lock, flags);
1753 bool cpus_share_cache(int this_cpu, int that_cpu)
1755 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1757 #endif /* CONFIG_SMP */
1759 static void ttwu_queue(struct task_struct *p, int cpu)
1761 struct rq *rq = cpu_rq(cpu);
1763 #if defined(CONFIG_SMP)
1764 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1765 sched_clock_cpu(cpu); /* sync clocks x-cpu */
1766 ttwu_queue_remote(p, cpu);
1771 raw_spin_lock(&rq->lock);
1772 lockdep_pin_lock(&rq->lock);
1773 ttwu_do_activate(rq, p, 0);
1774 lockdep_unpin_lock(&rq->lock);
1775 raw_spin_unlock(&rq->lock);
1779 * Notes on Program-Order guarantees on SMP systems.
1783 * The basic program-order guarantee on SMP systems is that when a task [t]
1784 * migrates, all its activity on its old cpu [c0] happens-before any subsequent
1785 * execution on its new cpu [c1].
1787 * For migration (of runnable tasks) this is provided by the following means:
1789 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1790 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1791 * rq(c1)->lock (if not at the same time, then in that order).
1792 * C) LOCK of the rq(c1)->lock scheduling in task
1794 * Transitivity guarantees that B happens after A and C after B.
1795 * Note: we only require RCpc transitivity.
1796 * Note: the cpu doing B need not be c0 or c1
1805 * UNLOCK rq(0)->lock
1807 * LOCK rq(0)->lock // orders against CPU0
1809 * UNLOCK rq(0)->lock
1813 * UNLOCK rq(1)->lock
1815 * LOCK rq(1)->lock // orders against CPU2
1818 * UNLOCK rq(1)->lock
1821 * BLOCKING -- aka. SLEEP + WAKEUP
1823 * For blocking we (obviously) need to provide the same guarantee as for
1824 * migration. However the means are completely different as there is no lock
1825 * chain to provide order. Instead we do:
1827 * 1) smp_store_release(X->on_cpu, 0)
1828 * 2) smp_cond_acquire(!X->on_cpu)
1832 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1834 * LOCK rq(0)->lock LOCK X->pi_lock
1837 * smp_store_release(X->on_cpu, 0);
1839 * smp_cond_acquire(!X->on_cpu);
1845 * X->state = RUNNING
1846 * UNLOCK rq(2)->lock
1848 * LOCK rq(2)->lock // orders against CPU1
1851 * UNLOCK rq(2)->lock
1854 * UNLOCK rq(0)->lock
1857 * However; for wakeups there is a second guarantee we must provide, namely we
1858 * must observe the state that lead to our wakeup. That is, not only must our
1859 * task observe its own prior state, it must also observe the stores prior to
1862 * This means that any means of doing remote wakeups must order the CPU doing
1863 * the wakeup against the CPU the task is going to end up running on. This,
1864 * however, is already required for the regular Program-Order guarantee above,
1865 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_acquire).
1870 * try_to_wake_up - wake up a thread
1871 * @p: the thread to be awakened
1872 * @state: the mask of task states that can be woken
1873 * @wake_flags: wake modifier flags (WF_*)
1875 * Put it on the run-queue if it's not already there. The "current"
1876 * thread is always on the run-queue (except when the actual
1877 * re-schedule is in progress), and as such you're allowed to do
1878 * the simpler "current->state = TASK_RUNNING" to mark yourself
1879 * runnable without the overhead of this.
1881 * Return: %true if @p was woken up, %false if it was already running.
1882 * or @state didn't match @p's state.
1885 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1887 unsigned long flags;
1888 int cpu, success = 0;
1891 * If we are going to wake up a thread waiting for CONDITION we
1892 * need to ensure that CONDITION=1 done by the caller can not be
1893 * reordered with p->state check below. This pairs with mb() in
1894 * set_current_state() the waiting thread does.
1896 smp_mb__before_spinlock();
1897 raw_spin_lock_irqsave(&p->pi_lock, flags);
1898 if (!(p->state & state))
1901 trace_sched_waking(p);
1903 success = 1; /* we're going to change ->state */
1906 if (p->on_rq && ttwu_remote(p, wake_flags))
1911 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
1912 * possible to, falsely, observe p->on_cpu == 0.
1914 * One must be running (->on_cpu == 1) in order to remove oneself
1915 * from the runqueue.
1917 * [S] ->on_cpu = 1; [L] ->on_rq
1921 * [S] ->on_rq = 0; [L] ->on_cpu
1923 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
1924 * from the consecutive calls to schedule(); the first switching to our
1925 * task, the second putting it to sleep.
1930 * If the owning (remote) cpu is still in the middle of schedule() with
1931 * this task as prev, wait until its done referencing the task.
1933 * Pairs with the smp_store_release() in finish_lock_switch().
1935 * This ensures that tasks getting woken will be fully ordered against
1936 * their previous state and preserve Program Order.
1938 smp_cond_acquire(!p->on_cpu);
1940 p->sched_contributes_to_load = !!task_contributes_to_load(p);
1941 p->state = TASK_WAKING;
1943 if (p->sched_class->task_waking)
1944 p->sched_class->task_waking(p);
1946 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
1947 if (task_cpu(p) != cpu) {
1948 wake_flags |= WF_MIGRATED;
1949 set_task_cpu(p, cpu);
1951 #endif /* CONFIG_SMP */
1955 if (schedstat_enabled())
1956 ttwu_stat(p, cpu, wake_flags);
1958 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1964 * try_to_wake_up_local - try to wake up a local task with rq lock held
1965 * @p: the thread to be awakened
1967 * Put @p on the run-queue if it's not already there. The caller must
1968 * ensure that this_rq() is locked, @p is bound to this_rq() and not
1971 static void try_to_wake_up_local(struct task_struct *p)
1973 struct rq *rq = task_rq(p);
1975 if (WARN_ON_ONCE(rq != this_rq()) ||
1976 WARN_ON_ONCE(p == current))
1979 lockdep_assert_held(&rq->lock);
1981 if (!raw_spin_trylock(&p->pi_lock)) {
1983 * This is OK, because current is on_cpu, which avoids it being
1984 * picked for load-balance and preemption/IRQs are still
1985 * disabled avoiding further scheduler activity on it and we've
1986 * not yet picked a replacement task.
1988 lockdep_unpin_lock(&rq->lock);
1989 raw_spin_unlock(&rq->lock);
1990 raw_spin_lock(&p->pi_lock);
1991 raw_spin_lock(&rq->lock);
1992 lockdep_pin_lock(&rq->lock);
1995 if (!(p->state & TASK_NORMAL))
1998 trace_sched_waking(p);
2000 if (!task_on_rq_queued(p))
2001 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2003 ttwu_do_wakeup(rq, p, 0);
2004 if (schedstat_enabled())
2005 ttwu_stat(p, smp_processor_id(), 0);
2007 raw_spin_unlock(&p->pi_lock);
2011 * wake_up_process - Wake up a specific process
2012 * @p: The process to be woken up.
2014 * Attempt to wake up the nominated process and move it to the set of runnable
2017 * Return: 1 if the process was woken up, 0 if it was already running.
2019 * It may be assumed that this function implies a write memory barrier before
2020 * changing the task state if and only if any tasks are woken up.
2022 int wake_up_process(struct task_struct *p)
2024 return try_to_wake_up(p, TASK_NORMAL, 0);
2026 EXPORT_SYMBOL(wake_up_process);
2028 int wake_up_state(struct task_struct *p, unsigned int state)
2030 return try_to_wake_up(p, state, 0);
2034 * This function clears the sched_dl_entity static params.
2036 void __dl_clear_params(struct task_struct *p)
2038 struct sched_dl_entity *dl_se = &p->dl;
2040 dl_se->dl_runtime = 0;
2041 dl_se->dl_deadline = 0;
2042 dl_se->dl_period = 0;
2046 dl_se->dl_throttled = 0;
2047 dl_se->dl_yielded = 0;
2051 * Perform scheduler related setup for a newly forked process p.
2052 * p is forked by current.
2054 * __sched_fork() is basic setup used by init_idle() too:
2056 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2061 p->se.exec_start = 0;
2062 p->se.sum_exec_runtime = 0;
2063 p->se.prev_sum_exec_runtime = 0;
2064 p->se.nr_migrations = 0;
2066 INIT_LIST_HEAD(&p->se.group_node);
2068 #ifdef CONFIG_FAIR_GROUP_SCHED
2069 p->se.cfs_rq = NULL;
2072 #ifdef CONFIG_SCHEDSTATS
2073 /* Even if schedstat is disabled, there should not be garbage */
2074 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2077 RB_CLEAR_NODE(&p->dl.rb_node);
2078 init_dl_task_timer(&p->dl);
2079 __dl_clear_params(p);
2081 INIT_LIST_HEAD(&p->rt.run_list);
2083 p->rt.time_slice = sched_rr_timeslice;
2087 #ifdef CONFIG_PREEMPT_NOTIFIERS
2088 INIT_HLIST_HEAD(&p->preempt_notifiers);
2091 #ifdef CONFIG_NUMA_BALANCING
2092 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
2093 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2094 p->mm->numa_scan_seq = 0;
2097 if (clone_flags & CLONE_VM)
2098 p->numa_preferred_nid = current->numa_preferred_nid;
2100 p->numa_preferred_nid = -1;
2102 p->node_stamp = 0ULL;
2103 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
2104 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2105 p->numa_work.next = &p->numa_work;
2106 p->numa_faults = NULL;
2107 p->last_task_numa_placement = 0;
2108 p->last_sum_exec_runtime = 0;
2110 p->numa_group = NULL;
2111 #endif /* CONFIG_NUMA_BALANCING */
2114 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2116 #ifdef CONFIG_NUMA_BALANCING
2118 void set_numabalancing_state(bool enabled)
2121 static_branch_enable(&sched_numa_balancing);
2123 static_branch_disable(&sched_numa_balancing);
2126 #ifdef CONFIG_PROC_SYSCTL
2127 int sysctl_numa_balancing(struct ctl_table *table, int write,
2128 void __user *buffer, size_t *lenp, loff_t *ppos)
2132 int state = static_branch_likely(&sched_numa_balancing);
2134 if (write && !capable(CAP_SYS_ADMIN))
2139 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2143 set_numabalancing_state(state);
2149 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2151 #ifdef CONFIG_SCHEDSTATS
2152 static void set_schedstats(bool enabled)
2155 static_branch_enable(&sched_schedstats);
2157 static_branch_disable(&sched_schedstats);
2160 void force_schedstat_enabled(void)
2162 if (!schedstat_enabled()) {
2163 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2164 static_branch_enable(&sched_schedstats);
2168 static int __init setup_schedstats(char *str)
2174 if (!strcmp(str, "enable")) {
2175 set_schedstats(true);
2177 } else if (!strcmp(str, "disable")) {
2178 set_schedstats(false);
2183 pr_warn("Unable to parse schedstats=\n");
2187 __setup("schedstats=", setup_schedstats);
2189 #ifdef CONFIG_PROC_SYSCTL
2190 int sysctl_schedstats(struct ctl_table *table, int write,
2191 void __user *buffer, size_t *lenp, loff_t *ppos)
2195 int state = static_branch_likely(&sched_schedstats);
2197 if (write && !capable(CAP_SYS_ADMIN))
2202 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2206 set_schedstats(state);
2213 * fork()/clone()-time setup:
2215 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2217 unsigned long flags;
2218 int cpu = get_cpu();
2220 __sched_fork(clone_flags, p);
2222 * We mark the process as running here. This guarantees that
2223 * nobody will actually run it, and a signal or other external
2224 * event cannot wake it up and insert it on the runqueue either.
2226 p->state = TASK_RUNNING;
2229 * Make sure we do not leak PI boosting priority to the child.
2231 p->prio = current->normal_prio;
2234 * Revert to default priority/policy on fork if requested.
2236 if (unlikely(p->sched_reset_on_fork)) {
2237 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2238 p->policy = SCHED_NORMAL;
2239 p->static_prio = NICE_TO_PRIO(0);
2241 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2242 p->static_prio = NICE_TO_PRIO(0);
2244 p->prio = p->normal_prio = __normal_prio(p);
2248 * We don't need the reset flag anymore after the fork. It has
2249 * fulfilled its duty:
2251 p->sched_reset_on_fork = 0;
2254 if (dl_prio(p->prio)) {
2257 } else if (rt_prio(p->prio)) {
2258 p->sched_class = &rt_sched_class;
2260 p->sched_class = &fair_sched_class;
2263 if (p->sched_class->task_fork)
2264 p->sched_class->task_fork(p);
2267 * The child is not yet in the pid-hash so no cgroup attach races,
2268 * and the cgroup is pinned to this child due to cgroup_fork()
2269 * is ran before sched_fork().
2271 * Silence PROVE_RCU.
2273 raw_spin_lock_irqsave(&p->pi_lock, flags);
2274 set_task_cpu(p, cpu);
2275 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2277 #ifdef CONFIG_SCHED_INFO
2278 if (likely(sched_info_on()))
2279 memset(&p->sched_info, 0, sizeof(p->sched_info));
2281 #if defined(CONFIG_SMP)
2284 init_task_preempt_count(p);
2286 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2287 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2294 unsigned long to_ratio(u64 period, u64 runtime)
2296 if (runtime == RUNTIME_INF)
2300 * Doing this here saves a lot of checks in all
2301 * the calling paths, and returning zero seems
2302 * safe for them anyway.
2307 return div64_u64(runtime << 20, period);
2311 inline struct dl_bw *dl_bw_of(int i)
2313 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2314 "sched RCU must be held");
2315 return &cpu_rq(i)->rd->dl_bw;
2318 static inline int dl_bw_cpus(int i)
2320 struct root_domain *rd = cpu_rq(i)->rd;
2323 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2324 "sched RCU must be held");
2325 for_each_cpu_and(i, rd->span, cpu_active_mask)
2331 inline struct dl_bw *dl_bw_of(int i)
2333 return &cpu_rq(i)->dl.dl_bw;
2336 static inline int dl_bw_cpus(int i)
2343 * We must be sure that accepting a new task (or allowing changing the
2344 * parameters of an existing one) is consistent with the bandwidth
2345 * constraints. If yes, this function also accordingly updates the currently
2346 * allocated bandwidth to reflect the new situation.
2348 * This function is called while holding p's rq->lock.
2350 * XXX we should delay bw change until the task's 0-lag point, see
2353 static int dl_overflow(struct task_struct *p, int policy,
2354 const struct sched_attr *attr)
2357 struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2358 u64 period = attr->sched_period ?: attr->sched_deadline;
2359 u64 runtime = attr->sched_runtime;
2360 u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2363 if (new_bw == p->dl.dl_bw)
2367 * Either if a task, enters, leave, or stays -deadline but changes
2368 * its parameters, we may need to update accordingly the total
2369 * allocated bandwidth of the container.
2371 raw_spin_lock(&dl_b->lock);
2372 cpus = dl_bw_cpus(task_cpu(p));
2373 if (dl_policy(policy) && !task_has_dl_policy(p) &&
2374 !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2375 __dl_add(dl_b, new_bw);
2377 } else if (dl_policy(policy) && task_has_dl_policy(p) &&
2378 !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2379 __dl_clear(dl_b, p->dl.dl_bw);
2380 __dl_add(dl_b, new_bw);
2382 } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2383 __dl_clear(dl_b, p->dl.dl_bw);
2386 raw_spin_unlock(&dl_b->lock);
2391 extern void init_dl_bw(struct dl_bw *dl_b);
2394 * wake_up_new_task - wake up a newly created task for the first time.
2396 * This function will do some initial scheduler statistics housekeeping
2397 * that must be done for every newly created context, then puts the task
2398 * on the runqueue and wakes it.
2400 void wake_up_new_task(struct task_struct *p)
2402 unsigned long flags;
2405 raw_spin_lock_irqsave(&p->pi_lock, flags);
2406 /* Initialize new task's runnable average */
2407 init_entity_runnable_average(&p->se);
2410 * Fork balancing, do it here and not earlier because:
2411 * - cpus_allowed can change in the fork path
2412 * - any previously selected cpu might disappear through hotplug
2414 set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2417 rq = __task_rq_lock(p);
2418 activate_task(rq, p, 0);
2419 p->on_rq = TASK_ON_RQ_QUEUED;
2420 trace_sched_wakeup_new(p);
2421 check_preempt_curr(rq, p, WF_FORK);
2423 if (p->sched_class->task_woken) {
2425 * Nothing relies on rq->lock after this, so its fine to
2428 lockdep_unpin_lock(&rq->lock);
2429 p->sched_class->task_woken(rq, p);
2430 lockdep_pin_lock(&rq->lock);
2433 task_rq_unlock(rq, p, &flags);
2436 #ifdef CONFIG_PREEMPT_NOTIFIERS
2438 static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2440 void preempt_notifier_inc(void)
2442 static_key_slow_inc(&preempt_notifier_key);
2444 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2446 void preempt_notifier_dec(void)
2448 static_key_slow_dec(&preempt_notifier_key);
2450 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2453 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2454 * @notifier: notifier struct to register
2456 void preempt_notifier_register(struct preempt_notifier *notifier)
2458 if (!static_key_false(&preempt_notifier_key))
2459 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2461 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2463 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2466 * preempt_notifier_unregister - no longer interested in preemption notifications
2467 * @notifier: notifier struct to unregister
2469 * This is *not* safe to call from within a preemption notifier.
2471 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2473 hlist_del(¬ifier->link);
2475 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2477 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2479 struct preempt_notifier *notifier;
2481 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2482 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2485 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2487 if (static_key_false(&preempt_notifier_key))
2488 __fire_sched_in_preempt_notifiers(curr);
2492 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2493 struct task_struct *next)
2495 struct preempt_notifier *notifier;
2497 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2498 notifier->ops->sched_out(notifier, next);
2501 static __always_inline void
2502 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2503 struct task_struct *next)
2505 if (static_key_false(&preempt_notifier_key))
2506 __fire_sched_out_preempt_notifiers(curr, next);
2509 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2511 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2516 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2517 struct task_struct *next)
2521 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2524 * prepare_task_switch - prepare to switch tasks
2525 * @rq: the runqueue preparing to switch
2526 * @prev: the current task that is being switched out
2527 * @next: the task we are going to switch to.
2529 * This is called with the rq lock held and interrupts off. It must
2530 * be paired with a subsequent finish_task_switch after the context
2533 * prepare_task_switch sets up locking and calls architecture specific
2537 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2538 struct task_struct *next)
2540 sched_info_switch(rq, prev, next);
2541 perf_event_task_sched_out(prev, next);
2542 fire_sched_out_preempt_notifiers(prev, next);
2543 prepare_lock_switch(rq, next);
2544 prepare_arch_switch(next);
2548 * finish_task_switch - clean up after a task-switch
2549 * @prev: the thread we just switched away from.
2551 * finish_task_switch must be called after the context switch, paired
2552 * with a prepare_task_switch call before the context switch.
2553 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2554 * and do any other architecture-specific cleanup actions.
2556 * Note that we may have delayed dropping an mm in context_switch(). If
2557 * so, we finish that here outside of the runqueue lock. (Doing it
2558 * with the lock held can cause deadlocks; see schedule() for
2561 * The context switch have flipped the stack from under us and restored the
2562 * local variables which were saved when this task called schedule() in the
2563 * past. prev == current is still correct but we need to recalculate this_rq
2564 * because prev may have moved to another CPU.
2566 static struct rq *finish_task_switch(struct task_struct *prev)
2567 __releases(rq->lock)
2569 struct rq *rq = this_rq();
2570 struct mm_struct *mm = rq->prev_mm;
2574 * The previous task will have left us with a preempt_count of 2
2575 * because it left us after:
2578 * preempt_disable(); // 1
2580 * raw_spin_lock_irq(&rq->lock) // 2
2582 * Also, see FORK_PREEMPT_COUNT.
2584 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2585 "corrupted preempt_count: %s/%d/0x%x\n",
2586 current->comm, current->pid, preempt_count()))
2587 preempt_count_set(FORK_PREEMPT_COUNT);
2592 * A task struct has one reference for the use as "current".
2593 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2594 * schedule one last time. The schedule call will never return, and
2595 * the scheduled task must drop that reference.
2597 * We must observe prev->state before clearing prev->on_cpu (in
2598 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2599 * running on another CPU and we could rave with its RUNNING -> DEAD
2600 * transition, resulting in a double drop.
2602 prev_state = prev->state;
2603 vtime_task_switch(prev);
2604 perf_event_task_sched_in(prev, current);
2605 finish_lock_switch(rq, prev);
2606 finish_arch_post_lock_switch();
2608 fire_sched_in_preempt_notifiers(current);
2611 if (unlikely(prev_state == TASK_DEAD)) {
2612 if (prev->sched_class->task_dead)
2613 prev->sched_class->task_dead(prev);
2616 * Remove function-return probe instances associated with this
2617 * task and put them back on the free list.
2619 kprobe_flush_task(prev);
2620 put_task_struct(prev);
2623 tick_nohz_task_switch();
2629 /* rq->lock is NOT held, but preemption is disabled */
2630 static void __balance_callback(struct rq *rq)
2632 struct callback_head *head, *next;
2633 void (*func)(struct rq *rq);
2634 unsigned long flags;
2636 raw_spin_lock_irqsave(&rq->lock, flags);
2637 head = rq->balance_callback;
2638 rq->balance_callback = NULL;
2640 func = (void (*)(struct rq *))head->func;
2647 raw_spin_unlock_irqrestore(&rq->lock, flags);
2650 static inline void balance_callback(struct rq *rq)
2652 if (unlikely(rq->balance_callback))
2653 __balance_callback(rq);
2658 static inline void balance_callback(struct rq *rq)
2665 * schedule_tail - first thing a freshly forked thread must call.
2666 * @prev: the thread we just switched away from.
2668 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2669 __releases(rq->lock)
2674 * New tasks start with FORK_PREEMPT_COUNT, see there and
2675 * finish_task_switch() for details.
2677 * finish_task_switch() will drop rq->lock() and lower preempt_count
2678 * and the preempt_enable() will end up enabling preemption (on
2679 * PREEMPT_COUNT kernels).
2682 rq = finish_task_switch(prev);
2683 balance_callback(rq);
2686 if (current->set_child_tid)
2687 put_user(task_pid_vnr(current), current->set_child_tid);
2691 * context_switch - switch to the new MM and the new thread's register state.
2693 static __always_inline struct rq *
2694 context_switch(struct rq *rq, struct task_struct *prev,
2695 struct task_struct *next)
2697 struct mm_struct *mm, *oldmm;
2699 prepare_task_switch(rq, prev, next);
2702 oldmm = prev->active_mm;
2704 * For paravirt, this is coupled with an exit in switch_to to
2705 * combine the page table reload and the switch backend into
2708 arch_start_context_switch(prev);
2711 next->active_mm = oldmm;
2712 atomic_inc(&oldmm->mm_count);
2713 enter_lazy_tlb(oldmm, next);
2715 switch_mm(oldmm, mm, next);
2718 prev->active_mm = NULL;
2719 rq->prev_mm = oldmm;
2722 * Since the runqueue lock will be released by the next
2723 * task (which is an invalid locking op but in the case
2724 * of the scheduler it's an obvious special-case), so we
2725 * do an early lockdep release here:
2727 lockdep_unpin_lock(&rq->lock);
2728 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2730 /* Here we just switch the register state and the stack. */
2731 switch_to(prev, next, prev);
2734 return finish_task_switch(prev);
2738 * nr_running and nr_context_switches:
2740 * externally visible scheduler statistics: current number of runnable
2741 * threads, total number of context switches performed since bootup.
2743 unsigned long nr_running(void)
2745 unsigned long i, sum = 0;
2747 for_each_online_cpu(i)
2748 sum += cpu_rq(i)->nr_running;
2754 * Check if only the current task is running on the cpu.
2756 * Caution: this function does not check that the caller has disabled
2757 * preemption, thus the result might have a time-of-check-to-time-of-use
2758 * race. The caller is responsible to use it correctly, for example:
2760 * - from a non-preemptable section (of course)
2762 * - from a thread that is bound to a single CPU
2764 * - in a loop with very short iterations (e.g. a polling loop)
2766 bool single_task_running(void)
2768 return raw_rq()->nr_running == 1;
2770 EXPORT_SYMBOL(single_task_running);
2772 unsigned long long nr_context_switches(void)
2775 unsigned long long sum = 0;
2777 for_each_possible_cpu(i)
2778 sum += cpu_rq(i)->nr_switches;
2783 unsigned long nr_iowait(void)
2785 unsigned long i, sum = 0;
2787 for_each_possible_cpu(i)
2788 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2793 unsigned long nr_iowait_cpu(int cpu)
2795 struct rq *this = cpu_rq(cpu);
2796 return atomic_read(&this->nr_iowait);
2799 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2801 struct rq *rq = this_rq();
2802 *nr_waiters = atomic_read(&rq->nr_iowait);
2803 *load = rq->load.weight;
2809 * sched_exec - execve() is a valuable balancing opportunity, because at
2810 * this point the task has the smallest effective memory and cache footprint.
2812 void sched_exec(void)
2814 struct task_struct *p = current;
2815 unsigned long flags;
2818 raw_spin_lock_irqsave(&p->pi_lock, flags);
2819 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2820 if (dest_cpu == smp_processor_id())
2823 if (likely(cpu_active(dest_cpu))) {
2824 struct migration_arg arg = { p, dest_cpu };
2826 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2827 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2831 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2836 DEFINE_PER_CPU(struct kernel_stat, kstat);
2837 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2839 EXPORT_PER_CPU_SYMBOL(kstat);
2840 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
2843 * Return accounted runtime for the task.
2844 * In case the task is currently running, return the runtime plus current's
2845 * pending runtime that have not been accounted yet.
2847 unsigned long long task_sched_runtime(struct task_struct *p)
2849 unsigned long flags;
2853 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
2855 * 64-bit doesn't need locks to atomically read a 64bit value.
2856 * So we have a optimization chance when the task's delta_exec is 0.
2857 * Reading ->on_cpu is racy, but this is ok.
2859 * If we race with it leaving cpu, we'll take a lock. So we're correct.
2860 * If we race with it entering cpu, unaccounted time is 0. This is
2861 * indistinguishable from the read occurring a few cycles earlier.
2862 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
2863 * been accounted, so we're correct here as well.
2865 if (!p->on_cpu || !task_on_rq_queued(p))
2866 return p->se.sum_exec_runtime;
2869 rq = task_rq_lock(p, &flags);
2871 * Must be ->curr _and_ ->on_rq. If dequeued, we would
2872 * project cycles that may never be accounted to this
2873 * thread, breaking clock_gettime().
2875 if (task_current(rq, p) && task_on_rq_queued(p)) {
2876 update_rq_clock(rq);
2877 p->sched_class->update_curr(rq);
2879 ns = p->se.sum_exec_runtime;
2880 task_rq_unlock(rq, p, &flags);
2886 * This function gets called by the timer code, with HZ frequency.
2887 * We call it with interrupts disabled.
2889 void scheduler_tick(void)
2891 int cpu = smp_processor_id();
2892 struct rq *rq = cpu_rq(cpu);
2893 struct task_struct *curr = rq->curr;
2897 raw_spin_lock(&rq->lock);
2898 update_rq_clock(rq);
2899 curr->sched_class->task_tick(rq, curr, 0);
2900 update_cpu_load_active(rq);
2901 calc_global_load_tick(rq);
2902 raw_spin_unlock(&rq->lock);
2904 perf_event_task_tick();
2907 rq->idle_balance = idle_cpu(cpu);
2908 trigger_load_balance(rq);
2910 rq_last_tick_reset(rq);
2913 #ifdef CONFIG_NO_HZ_FULL
2915 * scheduler_tick_max_deferment
2917 * Keep at least one tick per second when a single
2918 * active task is running because the scheduler doesn't
2919 * yet completely support full dynticks environment.
2921 * This makes sure that uptime, CFS vruntime, load
2922 * balancing, etc... continue to move forward, even
2923 * with a very low granularity.
2925 * Return: Maximum deferment in nanoseconds.
2927 u64 scheduler_tick_max_deferment(void)
2929 struct rq *rq = this_rq();
2930 unsigned long next, now = READ_ONCE(jiffies);
2932 next = rq->last_sched_tick + HZ;
2934 if (time_before_eq(next, now))
2937 return jiffies_to_nsecs(next - now);
2941 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
2942 defined(CONFIG_PREEMPT_TRACER))
2944 void preempt_count_add(int val)
2946 #ifdef CONFIG_DEBUG_PREEMPT
2950 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
2953 __preempt_count_add(val);
2954 #ifdef CONFIG_DEBUG_PREEMPT
2956 * Spinlock count overflowing soon?
2958 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
2961 if (preempt_count() == val) {
2962 unsigned long ip = get_lock_parent_ip();
2963 #ifdef CONFIG_DEBUG_PREEMPT
2964 current->preempt_disable_ip = ip;
2966 trace_preempt_off(CALLER_ADDR0, ip);
2969 EXPORT_SYMBOL(preempt_count_add);
2970 NOKPROBE_SYMBOL(preempt_count_add);
2972 void preempt_count_sub(int val)
2974 #ifdef CONFIG_DEBUG_PREEMPT
2978 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
2981 * Is the spinlock portion underflowing?
2983 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
2984 !(preempt_count() & PREEMPT_MASK)))
2988 if (preempt_count() == val)
2989 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
2990 __preempt_count_sub(val);
2992 EXPORT_SYMBOL(preempt_count_sub);
2993 NOKPROBE_SYMBOL(preempt_count_sub);
2998 * Print scheduling while atomic bug:
3000 static noinline void __schedule_bug(struct task_struct *prev)
3002 if (oops_in_progress)
3005 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3006 prev->comm, prev->pid, preempt_count());
3008 debug_show_held_locks(prev);
3010 if (irqs_disabled())
3011 print_irqtrace_events(prev);
3012 #ifdef CONFIG_DEBUG_PREEMPT
3013 if (in_atomic_preempt_off()) {
3014 pr_err("Preemption disabled at:");
3015 print_ip_sym(current->preempt_disable_ip);
3020 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3024 * Various schedule()-time debugging checks and statistics:
3026 static inline void schedule_debug(struct task_struct *prev)
3028 #ifdef CONFIG_SCHED_STACK_END_CHECK
3029 BUG_ON(task_stack_end_corrupted(prev));
3032 if (unlikely(in_atomic_preempt_off())) {
3033 __schedule_bug(prev);
3034 preempt_count_set(PREEMPT_DISABLED);
3038 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3040 schedstat_inc(this_rq(), sched_count);
3044 * Pick up the highest-prio task:
3046 static inline struct task_struct *
3047 pick_next_task(struct rq *rq, struct task_struct *prev)
3049 const struct sched_class *class = &fair_sched_class;
3050 struct task_struct *p;
3053 * Optimization: we know that if all tasks are in
3054 * the fair class we can call that function directly:
3056 if (likely(prev->sched_class == class &&
3057 rq->nr_running == rq->cfs.h_nr_running)) {
3058 p = fair_sched_class.pick_next_task(rq, prev);
3059 if (unlikely(p == RETRY_TASK))
3062 /* assumes fair_sched_class->next == idle_sched_class */
3064 p = idle_sched_class.pick_next_task(rq, prev);
3070 for_each_class(class) {
3071 p = class->pick_next_task(rq, prev);
3073 if (unlikely(p == RETRY_TASK))
3079 BUG(); /* the idle class will always have a runnable task */
3083 * __schedule() is the main scheduler function.
3085 * The main means of driving the scheduler and thus entering this function are:
3087 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3089 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3090 * paths. For example, see arch/x86/entry_64.S.
3092 * To drive preemption between tasks, the scheduler sets the flag in timer
3093 * interrupt handler scheduler_tick().
3095 * 3. Wakeups don't really cause entry into schedule(). They add a
3096 * task to the run-queue and that's it.
3098 * Now, if the new task added to the run-queue preempts the current
3099 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3100 * called on the nearest possible occasion:
3102 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3104 * - in syscall or exception context, at the next outmost
3105 * preempt_enable(). (this might be as soon as the wake_up()'s
3108 * - in IRQ context, return from interrupt-handler to
3109 * preemptible context
3111 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3114 * - cond_resched() call
3115 * - explicit schedule() call
3116 * - return from syscall or exception to user-space
3117 * - return from interrupt-handler to user-space
3119 * WARNING: must be called with preemption disabled!
3121 static void __sched notrace __schedule(bool preempt)
3123 struct task_struct *prev, *next;
3124 unsigned long *switch_count;
3128 cpu = smp_processor_id();
3133 * do_exit() calls schedule() with preemption disabled as an exception;
3134 * however we must fix that up, otherwise the next task will see an
3135 * inconsistent (higher) preempt count.
3137 * It also avoids the below schedule_debug() test from complaining
3140 if (unlikely(prev->state == TASK_DEAD))
3141 preempt_enable_no_resched_notrace();
3143 schedule_debug(prev);
3145 if (sched_feat(HRTICK))
3148 local_irq_disable();
3149 rcu_note_context_switch();
3152 * Make sure that signal_pending_state()->signal_pending() below
3153 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3154 * done by the caller to avoid the race with signal_wake_up().
3156 smp_mb__before_spinlock();
3157 raw_spin_lock(&rq->lock);
3158 lockdep_pin_lock(&rq->lock);
3160 rq->clock_skip_update <<= 1; /* promote REQ to ACT */
3162 switch_count = &prev->nivcsw;
3163 if (!preempt && prev->state) {
3164 if (unlikely(signal_pending_state(prev->state, prev))) {
3165 prev->state = TASK_RUNNING;
3167 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3171 * If a worker went to sleep, notify and ask workqueue
3172 * whether it wants to wake up a task to maintain
3175 if (prev->flags & PF_WQ_WORKER) {
3176 struct task_struct *to_wakeup;
3178 to_wakeup = wq_worker_sleeping(prev);
3180 try_to_wake_up_local(to_wakeup);
3183 switch_count = &prev->nvcsw;
3186 if (task_on_rq_queued(prev))
3187 update_rq_clock(rq);
3189 next = pick_next_task(rq, prev);
3190 clear_tsk_need_resched(prev);
3191 clear_preempt_need_resched();
3192 rq->clock_skip_update = 0;
3194 if (likely(prev != next)) {
3199 trace_sched_switch(preempt, prev, next);
3200 rq = context_switch(rq, prev, next); /* unlocks the rq */
3202 lockdep_unpin_lock(&rq->lock);
3203 raw_spin_unlock_irq(&rq->lock);
3206 balance_callback(rq);
3208 STACK_FRAME_NON_STANDARD(__schedule); /* switch_to() */
3210 static inline void sched_submit_work(struct task_struct *tsk)
3212 if (!tsk->state || tsk_is_pi_blocked(tsk))
3215 * If we are going to sleep and we have plugged IO queued,
3216 * make sure to submit it to avoid deadlocks.
3218 if (blk_needs_flush_plug(tsk))
3219 blk_schedule_flush_plug(tsk);
3222 asmlinkage __visible void __sched schedule(void)
3224 struct task_struct *tsk = current;
3226 sched_submit_work(tsk);
3230 sched_preempt_enable_no_resched();
3231 } while (need_resched());
3233 EXPORT_SYMBOL(schedule);
3235 #ifdef CONFIG_CONTEXT_TRACKING
3236 asmlinkage __visible void __sched schedule_user(void)
3239 * If we come here after a random call to set_need_resched(),
3240 * or we have been woken up remotely but the IPI has not yet arrived,
3241 * we haven't yet exited the RCU idle mode. Do it here manually until
3242 * we find a better solution.
3244 * NB: There are buggy callers of this function. Ideally we
3245 * should warn if prev_state != CONTEXT_USER, but that will trigger
3246 * too frequently to make sense yet.
3248 enum ctx_state prev_state = exception_enter();
3250 exception_exit(prev_state);
3255 * schedule_preempt_disabled - called with preemption disabled
3257 * Returns with preemption disabled. Note: preempt_count must be 1
3259 void __sched schedule_preempt_disabled(void)
3261 sched_preempt_enable_no_resched();
3266 static void __sched notrace preempt_schedule_common(void)
3269 preempt_disable_notrace();
3271 preempt_enable_no_resched_notrace();
3274 * Check again in case we missed a preemption opportunity
3275 * between schedule and now.
3277 } while (need_resched());
3280 #ifdef CONFIG_PREEMPT
3282 * this is the entry point to schedule() from in-kernel preemption
3283 * off of preempt_enable. Kernel preemptions off return from interrupt
3284 * occur there and call schedule directly.
3286 asmlinkage __visible void __sched notrace preempt_schedule(void)
3289 * If there is a non-zero preempt_count or interrupts are disabled,
3290 * we do not want to preempt the current task. Just return..
3292 if (likely(!preemptible()))
3295 preempt_schedule_common();
3297 NOKPROBE_SYMBOL(preempt_schedule);
3298 EXPORT_SYMBOL(preempt_schedule);
3301 * preempt_schedule_notrace - preempt_schedule called by tracing
3303 * The tracing infrastructure uses preempt_enable_notrace to prevent
3304 * recursion and tracing preempt enabling caused by the tracing
3305 * infrastructure itself. But as tracing can happen in areas coming
3306 * from userspace or just about to enter userspace, a preempt enable
3307 * can occur before user_exit() is called. This will cause the scheduler
3308 * to be called when the system is still in usermode.
3310 * To prevent this, the preempt_enable_notrace will use this function
3311 * instead of preempt_schedule() to exit user context if needed before
3312 * calling the scheduler.
3314 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3316 enum ctx_state prev_ctx;
3318 if (likely(!preemptible()))
3322 preempt_disable_notrace();
3324 * Needs preempt disabled in case user_exit() is traced
3325 * and the tracer calls preempt_enable_notrace() causing
3326 * an infinite recursion.
3328 prev_ctx = exception_enter();
3330 exception_exit(prev_ctx);
3332 preempt_enable_no_resched_notrace();
3333 } while (need_resched());
3335 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3337 #endif /* CONFIG_PREEMPT */
3340 * this is the entry point to schedule() from kernel preemption
3341 * off of irq context.
3342 * Note, that this is called and return with irqs disabled. This will
3343 * protect us against recursive calling from irq.
3345 asmlinkage __visible void __sched preempt_schedule_irq(void)
3347 enum ctx_state prev_state;
3349 /* Catch callers which need to be fixed */
3350 BUG_ON(preempt_count() || !irqs_disabled());
3352 prev_state = exception_enter();
3358 local_irq_disable();
3359 sched_preempt_enable_no_resched();
3360 } while (need_resched());
3362 exception_exit(prev_state);
3365 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3368 return try_to_wake_up(curr->private, mode, wake_flags);
3370 EXPORT_SYMBOL(default_wake_function);
3372 #ifdef CONFIG_RT_MUTEXES
3375 * rt_mutex_setprio - set the current priority of a task
3377 * @prio: prio value (kernel-internal form)
3379 * This function changes the 'effective' priority of a task. It does
3380 * not touch ->normal_prio like __setscheduler().
3382 * Used by the rt_mutex code to implement priority inheritance
3383 * logic. Call site only calls if the priority of the task changed.
3385 void rt_mutex_setprio(struct task_struct *p, int prio)
3387 int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
3389 const struct sched_class *prev_class;
3391 BUG_ON(prio > MAX_PRIO);
3393 rq = __task_rq_lock(p);
3396 * Idle task boosting is a nono in general. There is one
3397 * exception, when PREEMPT_RT and NOHZ is active:
3399 * The idle task calls get_next_timer_interrupt() and holds
3400 * the timer wheel base->lock on the CPU and another CPU wants
3401 * to access the timer (probably to cancel it). We can safely
3402 * ignore the boosting request, as the idle CPU runs this code
3403 * with interrupts disabled and will complete the lock
3404 * protected section without being interrupted. So there is no
3405 * real need to boost.
3407 if (unlikely(p == rq->idle)) {
3408 WARN_ON(p != rq->curr);
3409 WARN_ON(p->pi_blocked_on);
3413 trace_sched_pi_setprio(p, prio);
3416 if (oldprio == prio)
3417 queue_flag &= ~DEQUEUE_MOVE;
3419 prev_class = p->sched_class;
3420 queued = task_on_rq_queued(p);
3421 running = task_current(rq, p);
3423 dequeue_task(rq, p, queue_flag);
3425 put_prev_task(rq, p);
3428 * Boosting condition are:
3429 * 1. -rt task is running and holds mutex A
3430 * --> -dl task blocks on mutex A
3432 * 2. -dl task is running and holds mutex A
3433 * --> -dl task blocks on mutex A and could preempt the
3436 if (dl_prio(prio)) {
3437 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3438 if (!dl_prio(p->normal_prio) ||
3439 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3440 p->dl.dl_boosted = 1;
3441 queue_flag |= ENQUEUE_REPLENISH;
3443 p->dl.dl_boosted = 0;
3444 p->sched_class = &dl_sched_class;
3445 } else if (rt_prio(prio)) {
3446 if (dl_prio(oldprio))
3447 p->dl.dl_boosted = 0;
3449 queue_flag |= ENQUEUE_HEAD;
3450 p->sched_class = &rt_sched_class;
3452 if (dl_prio(oldprio))
3453 p->dl.dl_boosted = 0;
3454 if (rt_prio(oldprio))
3456 p->sched_class = &fair_sched_class;
3462 p->sched_class->set_curr_task(rq);
3464 enqueue_task(rq, p, queue_flag);
3466 check_class_changed(rq, p, prev_class, oldprio);
3468 preempt_disable(); /* avoid rq from going away on us */
3469 __task_rq_unlock(rq);
3471 balance_callback(rq);
3476 void set_user_nice(struct task_struct *p, long nice)
3478 int old_prio, delta, queued;
3479 unsigned long flags;
3482 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3485 * We have to be careful, if called from sys_setpriority(),
3486 * the task might be in the middle of scheduling on another CPU.
3488 rq = task_rq_lock(p, &flags);
3490 * The RT priorities are set via sched_setscheduler(), but we still
3491 * allow the 'normal' nice value to be set - but as expected
3492 * it wont have any effect on scheduling until the task is
3493 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3495 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3496 p->static_prio = NICE_TO_PRIO(nice);
3499 queued = task_on_rq_queued(p);
3501 dequeue_task(rq, p, DEQUEUE_SAVE);
3503 p->static_prio = NICE_TO_PRIO(nice);
3506 p->prio = effective_prio(p);
3507 delta = p->prio - old_prio;
3510 enqueue_task(rq, p, ENQUEUE_RESTORE);
3512 * If the task increased its priority or is running and
3513 * lowered its priority, then reschedule its CPU:
3515 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3519 task_rq_unlock(rq, p, &flags);
3521 EXPORT_SYMBOL(set_user_nice);
3524 * can_nice - check if a task can reduce its nice value
3528 int can_nice(const struct task_struct *p, const int nice)
3530 /* convert nice value [19,-20] to rlimit style value [1,40] */
3531 int nice_rlim = nice_to_rlimit(nice);
3533 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3534 capable(CAP_SYS_NICE));
3537 #ifdef __ARCH_WANT_SYS_NICE
3540 * sys_nice - change the priority of the current process.
3541 * @increment: priority increment
3543 * sys_setpriority is a more generic, but much slower function that
3544 * does similar things.
3546 SYSCALL_DEFINE1(nice, int, increment)
3551 * Setpriority might change our priority at the same moment.
3552 * We don't have to worry. Conceptually one call occurs first
3553 * and we have a single winner.
3555 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3556 nice = task_nice(current) + increment;
3558 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3559 if (increment < 0 && !can_nice(current, nice))
3562 retval = security_task_setnice(current, nice);
3566 set_user_nice(current, nice);
3573 * task_prio - return the priority value of a given task.
3574 * @p: the task in question.
3576 * Return: The priority value as seen by users in /proc.
3577 * RT tasks are offset by -200. Normal tasks are centered
3578 * around 0, value goes from -16 to +15.
3580 int task_prio(const struct task_struct *p)
3582 return p->prio - MAX_RT_PRIO;
3586 * idle_cpu - is a given cpu idle currently?
3587 * @cpu: the processor in question.
3589 * Return: 1 if the CPU is currently idle. 0 otherwise.
3591 int idle_cpu(int cpu)
3593 struct rq *rq = cpu_rq(cpu);
3595 if (rq->curr != rq->idle)
3602 if (!llist_empty(&rq->wake_list))
3610 * idle_task - return the idle task for a given cpu.
3611 * @cpu: the processor in question.
3613 * Return: The idle task for the cpu @cpu.
3615 struct task_struct *idle_task(int cpu)
3617 return cpu_rq(cpu)->idle;
3621 * find_process_by_pid - find a process with a matching PID value.
3622 * @pid: the pid in question.
3624 * The task of @pid, if found. %NULL otherwise.
3626 static struct task_struct *find_process_by_pid(pid_t pid)
3628 return pid ? find_task_by_vpid(pid) : current;
3632 * This function initializes the sched_dl_entity of a newly becoming
3633 * SCHED_DEADLINE task.
3635 * Only the static values are considered here, the actual runtime and the
3636 * absolute deadline will be properly calculated when the task is enqueued
3637 * for the first time with its new policy.
3640 __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
3642 struct sched_dl_entity *dl_se = &p->dl;
3644 dl_se->dl_runtime = attr->sched_runtime;
3645 dl_se->dl_deadline = attr->sched_deadline;
3646 dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
3647 dl_se->flags = attr->sched_flags;
3648 dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
3651 * Changing the parameters of a task is 'tricky' and we're not doing
3652 * the correct thing -- also see task_dead_dl() and switched_from_dl().
3654 * What we SHOULD do is delay the bandwidth release until the 0-lag
3655 * point. This would include retaining the task_struct until that time
3656 * and change dl_overflow() to not immediately decrement the current
3659 * Instead we retain the current runtime/deadline and let the new
3660 * parameters take effect after the current reservation period lapses.
3661 * This is safe (albeit pessimistic) because the 0-lag point is always
3662 * before the current scheduling deadline.
3664 * We can still have temporary overloads because we do not delay the
3665 * change in bandwidth until that time; so admission control is
3666 * not on the safe side. It does however guarantee tasks will never
3667 * consume more than promised.
3672 * sched_setparam() passes in -1 for its policy, to let the functions
3673 * it calls know not to change it.
3675 #define SETPARAM_POLICY -1
3677 static void __setscheduler_params(struct task_struct *p,
3678 const struct sched_attr *attr)
3680 int policy = attr->sched_policy;
3682 if (policy == SETPARAM_POLICY)
3687 if (dl_policy(policy))
3688 __setparam_dl(p, attr);
3689 else if (fair_policy(policy))
3690 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
3693 * __sched_setscheduler() ensures attr->sched_priority == 0 when
3694 * !rt_policy. Always setting this ensures that things like
3695 * getparam()/getattr() don't report silly values for !rt tasks.
3697 p->rt_priority = attr->sched_priority;
3698 p->normal_prio = normal_prio(p);
3702 /* Actually do priority change: must hold pi & rq lock. */
3703 static void __setscheduler(struct rq *rq, struct task_struct *p,
3704 const struct sched_attr *attr, bool keep_boost)
3706 __setscheduler_params(p, attr);
3709 * Keep a potential priority boosting if called from
3710 * sched_setscheduler().
3713 p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
3715 p->prio = normal_prio(p);
3717 if (dl_prio(p->prio))
3718 p->sched_class = &dl_sched_class;
3719 else if (rt_prio(p->prio))
3720 p->sched_class = &rt_sched_class;
3722 p->sched_class = &fair_sched_class;
3726 __getparam_dl(struct task_struct *p, struct sched_attr *attr)
3728 struct sched_dl_entity *dl_se = &p->dl;
3730 attr->sched_priority = p->rt_priority;
3731 attr->sched_runtime = dl_se->dl_runtime;
3732 attr->sched_deadline = dl_se->dl_deadline;
3733 attr->sched_period = dl_se->dl_period;
3734 attr->sched_flags = dl_se->flags;
3738 * This function validates the new parameters of a -deadline task.
3739 * We ask for the deadline not being zero, and greater or equal
3740 * than the runtime, as well as the period of being zero or
3741 * greater than deadline. Furthermore, we have to be sure that
3742 * user parameters are above the internal resolution of 1us (we
3743 * check sched_runtime only since it is always the smaller one) and
3744 * below 2^63 ns (we have to check both sched_deadline and
3745 * sched_period, as the latter can be zero).
3748 __checkparam_dl(const struct sched_attr *attr)
3751 if (attr->sched_deadline == 0)
3755 * Since we truncate DL_SCALE bits, make sure we're at least
3758 if (attr->sched_runtime < (1ULL << DL_SCALE))
3762 * Since we use the MSB for wrap-around and sign issues, make
3763 * sure it's not set (mind that period can be equal to zero).
3765 if (attr->sched_deadline & (1ULL << 63) ||
3766 attr->sched_period & (1ULL << 63))
3769 /* runtime <= deadline <= period (if period != 0) */
3770 if ((attr->sched_period != 0 &&
3771 attr->sched_period < attr->sched_deadline) ||
3772 attr->sched_deadline < attr->sched_runtime)
3779 * check the target process has a UID that matches the current process's
3781 static bool check_same_owner(struct task_struct *p)
3783 const struct cred *cred = current_cred(), *pcred;
3787 pcred = __task_cred(p);
3788 match = (uid_eq(cred->euid, pcred->euid) ||
3789 uid_eq(cred->euid, pcred->uid));
3794 static bool dl_param_changed(struct task_struct *p,
3795 const struct sched_attr *attr)
3797 struct sched_dl_entity *dl_se = &p->dl;
3799 if (dl_se->dl_runtime != attr->sched_runtime ||
3800 dl_se->dl_deadline != attr->sched_deadline ||
3801 dl_se->dl_period != attr->sched_period ||
3802 dl_se->flags != attr->sched_flags)
3808 static int __sched_setscheduler(struct task_struct *p,
3809 const struct sched_attr *attr,
3812 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
3813 MAX_RT_PRIO - 1 - attr->sched_priority;
3814 int retval, oldprio, oldpolicy = -1, queued, running;
3815 int new_effective_prio, policy = attr->sched_policy;
3816 unsigned long flags;
3817 const struct sched_class *prev_class;
3820 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
3822 /* may grab non-irq protected spin_locks */
3823 BUG_ON(in_interrupt());
3825 /* double check policy once rq lock held */
3827 reset_on_fork = p->sched_reset_on_fork;
3828 policy = oldpolicy = p->policy;
3830 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
3832 if (!valid_policy(policy))
3836 if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
3840 * Valid priorities for SCHED_FIFO and SCHED_RR are
3841 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
3842 * SCHED_BATCH and SCHED_IDLE is 0.
3844 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
3845 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
3847 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
3848 (rt_policy(policy) != (attr->sched_priority != 0)))
3852 * Allow unprivileged RT tasks to decrease priority:
3854 if (user && !capable(CAP_SYS_NICE)) {
3855 if (fair_policy(policy)) {
3856 if (attr->sched_nice < task_nice(p) &&
3857 !can_nice(p, attr->sched_nice))
3861 if (rt_policy(policy)) {
3862 unsigned long rlim_rtprio =
3863 task_rlimit(p, RLIMIT_RTPRIO);
3865 /* can't set/change the rt policy */
3866 if (policy != p->policy && !rlim_rtprio)
3869 /* can't increase priority */
3870 if (attr->sched_priority > p->rt_priority &&
3871 attr->sched_priority > rlim_rtprio)
3876 * Can't set/change SCHED_DEADLINE policy at all for now
3877 * (safest behavior); in the future we would like to allow
3878 * unprivileged DL tasks to increase their relative deadline
3879 * or reduce their runtime (both ways reducing utilization)
3881 if (dl_policy(policy))
3885 * Treat SCHED_IDLE as nice 20. Only allow a switch to
3886 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
3888 if (idle_policy(p->policy) && !idle_policy(policy)) {
3889 if (!can_nice(p, task_nice(p)))
3893 /* can't change other user's priorities */
3894 if (!check_same_owner(p))
3897 /* Normal users shall not reset the sched_reset_on_fork flag */
3898 if (p->sched_reset_on_fork && !reset_on_fork)
3903 retval = security_task_setscheduler(p);
3909 * make sure no PI-waiters arrive (or leave) while we are
3910 * changing the priority of the task:
3912 * To be able to change p->policy safely, the appropriate
3913 * runqueue lock must be held.
3915 rq = task_rq_lock(p, &flags);
3918 * Changing the policy of the stop threads its a very bad idea
3920 if (p == rq->stop) {
3921 task_rq_unlock(rq, p, &flags);
3926 * If not changing anything there's no need to proceed further,
3927 * but store a possible modification of reset_on_fork.
3929 if (unlikely(policy == p->policy)) {
3930 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
3932 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
3934 if (dl_policy(policy) && dl_param_changed(p, attr))
3937 p->sched_reset_on_fork = reset_on_fork;
3938 task_rq_unlock(rq, p, &flags);
3944 #ifdef CONFIG_RT_GROUP_SCHED
3946 * Do not allow realtime tasks into groups that have no runtime
3949 if (rt_bandwidth_enabled() && rt_policy(policy) &&
3950 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
3951 !task_group_is_autogroup(task_group(p))) {
3952 task_rq_unlock(rq, p, &flags);
3957 if (dl_bandwidth_enabled() && dl_policy(policy)) {
3958 cpumask_t *span = rq->rd->span;
3961 * Don't allow tasks with an affinity mask smaller than
3962 * the entire root_domain to become SCHED_DEADLINE. We
3963 * will also fail if there's no bandwidth available.
3965 if (!cpumask_subset(span, &p->cpus_allowed) ||
3966 rq->rd->dl_bw.bw == 0) {
3967 task_rq_unlock(rq, p, &flags);
3974 /* recheck policy now with rq lock held */
3975 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3976 policy = oldpolicy = -1;
3977 task_rq_unlock(rq, p, &flags);
3982 * If setscheduling to SCHED_DEADLINE (or changing the parameters
3983 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
3986 if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
3987 task_rq_unlock(rq, p, &flags);
3991 p->sched_reset_on_fork = reset_on_fork;
3996 * Take priority boosted tasks into account. If the new
3997 * effective priority is unchanged, we just store the new
3998 * normal parameters and do not touch the scheduler class and
3999 * the runqueue. This will be done when the task deboost
4002 new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
4003 if (new_effective_prio == oldprio)
4004 queue_flags &= ~DEQUEUE_MOVE;
4007 queued = task_on_rq_queued(p);
4008 running = task_current(rq, p);
4010 dequeue_task(rq, p, queue_flags);
4012 put_prev_task(rq, p);
4014 prev_class = p->sched_class;
4015 __setscheduler(rq, p, attr, pi);
4018 p->sched_class->set_curr_task(rq);
4021 * We enqueue to tail when the priority of a task is
4022 * increased (user space view).
4024 if (oldprio < p->prio)
4025 queue_flags |= ENQUEUE_HEAD;
4027 enqueue_task(rq, p, queue_flags);
4030 check_class_changed(rq, p, prev_class, oldprio);
4031 preempt_disable(); /* avoid rq from going away on us */
4032 task_rq_unlock(rq, p, &flags);
4035 rt_mutex_adjust_pi(p);
4038 * Run balance callbacks after we've adjusted the PI chain.
4040 balance_callback(rq);
4046 static int _sched_setscheduler(struct task_struct *p, int policy,
4047 const struct sched_param *param, bool check)
4049 struct sched_attr attr = {
4050 .sched_policy = policy,
4051 .sched_priority = param->sched_priority,
4052 .sched_nice = PRIO_TO_NICE(p->static_prio),
4055 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4056 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4057 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4058 policy &= ~SCHED_RESET_ON_FORK;
4059 attr.sched_policy = policy;
4062 return __sched_setscheduler(p, &attr, check, true);
4065 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4066 * @p: the task in question.
4067 * @policy: new policy.
4068 * @param: structure containing the new RT priority.
4070 * Return: 0 on success. An error code otherwise.
4072 * NOTE that the task may be already dead.
4074 int sched_setscheduler(struct task_struct *p, int policy,
4075 const struct sched_param *param)
4077 return _sched_setscheduler(p, policy, param, true);
4079 EXPORT_SYMBOL_GPL(sched_setscheduler);
4081 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4083 return __sched_setscheduler(p, attr, true, true);
4085 EXPORT_SYMBOL_GPL(sched_setattr);
4088 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4089 * @p: the task in question.
4090 * @policy: new policy.
4091 * @param: structure containing the new RT priority.
4093 * Just like sched_setscheduler, only don't bother checking if the
4094 * current context has permission. For example, this is needed in
4095 * stop_machine(): we create temporary high priority worker threads,
4096 * but our caller might not have that capability.
4098 * Return: 0 on success. An error code otherwise.
4100 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4101 const struct sched_param *param)
4103 return _sched_setscheduler(p, policy, param, false);
4105 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4108 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4110 struct sched_param lparam;
4111 struct task_struct *p;
4114 if (!param || pid < 0)
4116 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4121 p = find_process_by_pid(pid);
4123 retval = sched_setscheduler(p, policy, &lparam);
4130 * Mimics kernel/events/core.c perf_copy_attr().
4132 static int sched_copy_attr(struct sched_attr __user *uattr,
4133 struct sched_attr *attr)
4138 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4142 * zero the full structure, so that a short copy will be nice.
4144 memset(attr, 0, sizeof(*attr));
4146 ret = get_user(size, &uattr->size);
4150 if (size > PAGE_SIZE) /* silly large */
4153 if (!size) /* abi compat */
4154 size = SCHED_ATTR_SIZE_VER0;
4156 if (size < SCHED_ATTR_SIZE_VER0)
4160 * If we're handed a bigger struct than we know of,
4161 * ensure all the unknown bits are 0 - i.e. new
4162 * user-space does not rely on any kernel feature
4163 * extensions we dont know about yet.
4165 if (size > sizeof(*attr)) {
4166 unsigned char __user *addr;
4167 unsigned char __user *end;
4170 addr = (void __user *)uattr + sizeof(*attr);
4171 end = (void __user *)uattr + size;
4173 for (; addr < end; addr++) {
4174 ret = get_user(val, addr);
4180 size = sizeof(*attr);
4183 ret = copy_from_user(attr, uattr, size);
4188 * XXX: do we want to be lenient like existing syscalls; or do we want
4189 * to be strict and return an error on out-of-bounds values?
4191 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4196 put_user(sizeof(*attr), &uattr->size);
4201 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4202 * @pid: the pid in question.
4203 * @policy: new policy.
4204 * @param: structure containing the new RT priority.
4206 * Return: 0 on success. An error code otherwise.
4208 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4209 struct sched_param __user *, param)
4211 /* negative values for policy are not valid */
4215 return do_sched_setscheduler(pid, policy, param);
4219 * sys_sched_setparam - set/change the RT priority of a thread
4220 * @pid: the pid in question.
4221 * @param: structure containing the new RT priority.
4223 * Return: 0 on success. An error code otherwise.
4225 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4227 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4231 * sys_sched_setattr - same as above, but with extended sched_attr
4232 * @pid: the pid in question.
4233 * @uattr: structure containing the extended parameters.
4234 * @flags: for future extension.
4236 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4237 unsigned int, flags)
4239 struct sched_attr attr;
4240 struct task_struct *p;
4243 if (!uattr || pid < 0 || flags)
4246 retval = sched_copy_attr(uattr, &attr);
4250 if ((int)attr.sched_policy < 0)
4255 p = find_process_by_pid(pid);
4257 retval = sched_setattr(p, &attr);
4264 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4265 * @pid: the pid in question.
4267 * Return: On success, the policy of the thread. Otherwise, a negative error
4270 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4272 struct task_struct *p;
4280 p = find_process_by_pid(pid);
4282 retval = security_task_getscheduler(p);
4285 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4292 * sys_sched_getparam - get the RT priority of a thread
4293 * @pid: the pid in question.
4294 * @param: structure containing the RT priority.
4296 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4299 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4301 struct sched_param lp = { .sched_priority = 0 };
4302 struct task_struct *p;
4305 if (!param || pid < 0)
4309 p = find_process_by_pid(pid);
4314 retval = security_task_getscheduler(p);
4318 if (task_has_rt_policy(p))
4319 lp.sched_priority = p->rt_priority;
4323 * This one might sleep, we cannot do it with a spinlock held ...
4325 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4334 static int sched_read_attr(struct sched_attr __user *uattr,
4335 struct sched_attr *attr,
4340 if (!access_ok(VERIFY_WRITE, uattr, usize))
4344 * If we're handed a smaller struct than we know of,
4345 * ensure all the unknown bits are 0 - i.e. old
4346 * user-space does not get uncomplete information.
4348 if (usize < sizeof(*attr)) {
4349 unsigned char *addr;
4352 addr = (void *)attr + usize;
4353 end = (void *)attr + sizeof(*attr);
4355 for (; addr < end; addr++) {
4363 ret = copy_to_user(uattr, attr, attr->size);
4371 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4372 * @pid: the pid in question.
4373 * @uattr: structure containing the extended parameters.
4374 * @size: sizeof(attr) for fwd/bwd comp.
4375 * @flags: for future extension.
4377 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4378 unsigned int, size, unsigned int, flags)
4380 struct sched_attr attr = {
4381 .size = sizeof(struct sched_attr),
4383 struct task_struct *p;
4386 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4387 size < SCHED_ATTR_SIZE_VER0 || flags)
4391 p = find_process_by_pid(pid);
4396 retval = security_task_getscheduler(p);
4400 attr.sched_policy = p->policy;
4401 if (p->sched_reset_on_fork)
4402 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4403 if (task_has_dl_policy(p))
4404 __getparam_dl(p, &attr);
4405 else if (task_has_rt_policy(p))
4406 attr.sched_priority = p->rt_priority;
4408 attr.sched_nice = task_nice(p);
4412 retval = sched_read_attr(uattr, &attr, size);
4420 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4422 cpumask_var_t cpus_allowed, new_mask;
4423 struct task_struct *p;
4428 p = find_process_by_pid(pid);
4434 /* Prevent p going away */
4438 if (p->flags & PF_NO_SETAFFINITY) {
4442 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4446 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4448 goto out_free_cpus_allowed;
4451 if (!check_same_owner(p)) {
4453 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4455 goto out_free_new_mask;
4460 retval = security_task_setscheduler(p);
4462 goto out_free_new_mask;
4465 cpuset_cpus_allowed(p, cpus_allowed);
4466 cpumask_and(new_mask, in_mask, cpus_allowed);
4469 * Since bandwidth control happens on root_domain basis,
4470 * if admission test is enabled, we only admit -deadline
4471 * tasks allowed to run on all the CPUs in the task's
4475 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4477 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4480 goto out_free_new_mask;
4486 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4489 cpuset_cpus_allowed(p, cpus_allowed);
4490 if (!cpumask_subset(new_mask, cpus_allowed)) {
4492 * We must have raced with a concurrent cpuset
4493 * update. Just reset the cpus_allowed to the
4494 * cpuset's cpus_allowed
4496 cpumask_copy(new_mask, cpus_allowed);
4501 free_cpumask_var(new_mask);
4502 out_free_cpus_allowed:
4503 free_cpumask_var(cpus_allowed);
4509 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4510 struct cpumask *new_mask)
4512 if (len < cpumask_size())
4513 cpumask_clear(new_mask);
4514 else if (len > cpumask_size())
4515 len = cpumask_size();
4517 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4521 * sys_sched_setaffinity - set the cpu affinity of a process
4522 * @pid: pid of the process
4523 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4524 * @user_mask_ptr: user-space pointer to the new cpu mask
4526 * Return: 0 on success. An error code otherwise.
4528 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4529 unsigned long __user *, user_mask_ptr)
4531 cpumask_var_t new_mask;
4534 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4537 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4539 retval = sched_setaffinity(pid, new_mask);
4540 free_cpumask_var(new_mask);
4544 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4546 struct task_struct *p;
4547 unsigned long flags;
4553 p = find_process_by_pid(pid);
4557 retval = security_task_getscheduler(p);
4561 raw_spin_lock_irqsave(&p->pi_lock, flags);
4562 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4563 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4572 * sys_sched_getaffinity - get the cpu affinity of a process
4573 * @pid: pid of the process
4574 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4575 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4577 * Return: 0 on success. An error code otherwise.
4579 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4580 unsigned long __user *, user_mask_ptr)
4585 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4587 if (len & (sizeof(unsigned long)-1))
4590 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4593 ret = sched_getaffinity(pid, mask);
4595 size_t retlen = min_t(size_t, len, cpumask_size());
4597 if (copy_to_user(user_mask_ptr, mask, retlen))
4602 free_cpumask_var(mask);
4608 * sys_sched_yield - yield the current processor to other threads.
4610 * This function yields the current CPU to other tasks. If there are no
4611 * other threads running on this CPU then this function will return.
4615 SYSCALL_DEFINE0(sched_yield)
4617 struct rq *rq = this_rq_lock();
4619 schedstat_inc(rq, yld_count);
4620 current->sched_class->yield_task(rq);
4623 * Since we are going to call schedule() anyway, there's
4624 * no need to preempt or enable interrupts:
4626 __release(rq->lock);
4627 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4628 do_raw_spin_unlock(&rq->lock);
4629 sched_preempt_enable_no_resched();
4636 int __sched _cond_resched(void)
4638 if (should_resched(0)) {
4639 preempt_schedule_common();
4644 EXPORT_SYMBOL(_cond_resched);
4647 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4648 * call schedule, and on return reacquire the lock.
4650 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4651 * operations here to prevent schedule() from being called twice (once via
4652 * spin_unlock(), once by hand).
4654 int __cond_resched_lock(spinlock_t *lock)
4656 int resched = should_resched(PREEMPT_LOCK_OFFSET);
4659 lockdep_assert_held(lock);
4661 if (spin_needbreak(lock) || resched) {
4664 preempt_schedule_common();
4672 EXPORT_SYMBOL(__cond_resched_lock);
4674 int __sched __cond_resched_softirq(void)
4676 BUG_ON(!in_softirq());
4678 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
4680 preempt_schedule_common();
4686 EXPORT_SYMBOL(__cond_resched_softirq);
4689 * yield - yield the current processor to other threads.
4691 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4693 * The scheduler is at all times free to pick the calling task as the most
4694 * eligible task to run, if removing the yield() call from your code breaks
4695 * it, its already broken.
4697 * Typical broken usage is:
4702 * where one assumes that yield() will let 'the other' process run that will
4703 * make event true. If the current task is a SCHED_FIFO task that will never
4704 * happen. Never use yield() as a progress guarantee!!
4706 * If you want to use yield() to wait for something, use wait_event().
4707 * If you want to use yield() to be 'nice' for others, use cond_resched().
4708 * If you still want to use yield(), do not!
4710 void __sched yield(void)
4712 set_current_state(TASK_RUNNING);
4715 EXPORT_SYMBOL(yield);
4718 * yield_to - yield the current processor to another thread in
4719 * your thread group, or accelerate that thread toward the
4720 * processor it's on.
4722 * @preempt: whether task preemption is allowed or not
4724 * It's the caller's job to ensure that the target task struct
4725 * can't go away on us before we can do any checks.
4728 * true (>0) if we indeed boosted the target task.
4729 * false (0) if we failed to boost the target.
4730 * -ESRCH if there's no task to yield to.
4732 int __sched yield_to(struct task_struct *p, bool preempt)
4734 struct task_struct *curr = current;
4735 struct rq *rq, *p_rq;
4736 unsigned long flags;
4739 local_irq_save(flags);
4745 * If we're the only runnable task on the rq and target rq also
4746 * has only one task, there's absolutely no point in yielding.
4748 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4753 double_rq_lock(rq, p_rq);
4754 if (task_rq(p) != p_rq) {
4755 double_rq_unlock(rq, p_rq);
4759 if (!curr->sched_class->yield_to_task)
4762 if (curr->sched_class != p->sched_class)
4765 if (task_running(p_rq, p) || p->state)
4768 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
4770 schedstat_inc(rq, yld_count);
4772 * Make p's CPU reschedule; pick_next_entity takes care of
4775 if (preempt && rq != p_rq)
4780 double_rq_unlock(rq, p_rq);
4782 local_irq_restore(flags);
4789 EXPORT_SYMBOL_GPL(yield_to);
4792 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4793 * that process accounting knows that this is a task in IO wait state.
4795 long __sched io_schedule_timeout(long timeout)
4797 int old_iowait = current->in_iowait;
4801 current->in_iowait = 1;
4802 blk_schedule_flush_plug(current);
4804 delayacct_blkio_start();
4806 atomic_inc(&rq->nr_iowait);
4807 ret = schedule_timeout(timeout);
4808 current->in_iowait = old_iowait;
4809 atomic_dec(&rq->nr_iowait);
4810 delayacct_blkio_end();
4814 EXPORT_SYMBOL(io_schedule_timeout);
4817 * sys_sched_get_priority_max - return maximum RT priority.
4818 * @policy: scheduling class.
4820 * Return: On success, this syscall returns the maximum
4821 * rt_priority that can be used by a given scheduling class.
4822 * On failure, a negative error code is returned.
4824 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
4831 ret = MAX_USER_RT_PRIO-1;
4833 case SCHED_DEADLINE:
4844 * sys_sched_get_priority_min - return minimum RT priority.
4845 * @policy: scheduling class.
4847 * Return: On success, this syscall returns the minimum
4848 * rt_priority that can be used by a given scheduling class.
4849 * On failure, a negative error code is returned.
4851 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
4860 case SCHED_DEADLINE:
4870 * sys_sched_rr_get_interval - return the default timeslice of a process.
4871 * @pid: pid of the process.
4872 * @interval: userspace pointer to the timeslice value.
4874 * this syscall writes the default timeslice value of a given process
4875 * into the user-space timespec buffer. A value of '0' means infinity.
4877 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
4880 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
4881 struct timespec __user *, interval)
4883 struct task_struct *p;
4884 unsigned int time_slice;
4885 unsigned long flags;
4895 p = find_process_by_pid(pid);
4899 retval = security_task_getscheduler(p);
4903 rq = task_rq_lock(p, &flags);
4905 if (p->sched_class->get_rr_interval)
4906 time_slice = p->sched_class->get_rr_interval(rq, p);
4907 task_rq_unlock(rq, p, &flags);
4910 jiffies_to_timespec(time_slice, &t);
4911 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4919 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
4921 void sched_show_task(struct task_struct *p)
4923 unsigned long free = 0;
4925 unsigned long state = p->state;
4928 state = __ffs(state) + 1;
4929 printk(KERN_INFO "%-15.15s %c", p->comm,
4930 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4931 #if BITS_PER_LONG == 32
4932 if (state == TASK_RUNNING)
4933 printk(KERN_CONT " running ");
4935 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
4937 if (state == TASK_RUNNING)
4938 printk(KERN_CONT " running task ");
4940 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
4942 #ifdef CONFIG_DEBUG_STACK_USAGE
4943 free = stack_not_used(p);
4948 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4950 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4951 task_pid_nr(p), ppid,
4952 (unsigned long)task_thread_info(p)->flags);
4954 print_worker_info(KERN_INFO, p);
4955 show_stack(p, NULL);
4958 void show_state_filter(unsigned long state_filter)
4960 struct task_struct *g, *p;
4962 #if BITS_PER_LONG == 32
4964 " task PC stack pid father\n");
4967 " task PC stack pid father\n");
4970 for_each_process_thread(g, p) {
4972 * reset the NMI-timeout, listing all files on a slow
4973 * console might take a lot of time:
4975 touch_nmi_watchdog();
4976 if (!state_filter || (p->state & state_filter))
4980 touch_all_softlockup_watchdogs();
4982 #ifdef CONFIG_SCHED_DEBUG
4983 sysrq_sched_debug_show();
4987 * Only show locks if all tasks are dumped:
4990 debug_show_all_locks();
4993 void init_idle_bootup_task(struct task_struct *idle)
4995 idle->sched_class = &idle_sched_class;
4999 * init_idle - set up an idle thread for a given CPU
5000 * @idle: task in question
5001 * @cpu: cpu the idle task belongs to
5003 * NOTE: this function does not set the idle thread's NEED_RESCHED
5004 * flag, to make booting more robust.
5006 void init_idle(struct task_struct *idle, int cpu)
5008 struct rq *rq = cpu_rq(cpu);
5009 unsigned long flags;
5011 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5012 raw_spin_lock(&rq->lock);
5014 __sched_fork(0, idle);
5015 idle->state = TASK_RUNNING;
5016 idle->se.exec_start = sched_clock();
5018 kasan_unpoison_task_stack(idle);
5022 * Its possible that init_idle() gets called multiple times on a task,
5023 * in that case do_set_cpus_allowed() will not do the right thing.
5025 * And since this is boot we can forgo the serialization.
5027 set_cpus_allowed_common(idle, cpumask_of(cpu));
5030 * We're having a chicken and egg problem, even though we are
5031 * holding rq->lock, the cpu isn't yet set to this cpu so the
5032 * lockdep check in task_group() will fail.
5034 * Similar case to sched_fork(). / Alternatively we could
5035 * use task_rq_lock() here and obtain the other rq->lock.
5040 __set_task_cpu(idle, cpu);
5043 rq->curr = rq->idle = idle;
5044 idle->on_rq = TASK_ON_RQ_QUEUED;
5048 raw_spin_unlock(&rq->lock);
5049 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5051 /* Set the preempt count _outside_ the spinlocks! */
5052 init_idle_preempt_count(idle, cpu);
5055 * The idle tasks have their own, simple scheduling class:
5057 idle->sched_class = &idle_sched_class;
5058 ftrace_graph_init_idle_task(idle, cpu);
5059 vtime_init_idle(idle, cpu);
5061 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5065 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5066 const struct cpumask *trial)
5068 int ret = 1, trial_cpus;
5069 struct dl_bw *cur_dl_b;
5070 unsigned long flags;
5072 if (!cpumask_weight(cur))
5075 rcu_read_lock_sched();
5076 cur_dl_b = dl_bw_of(cpumask_any(cur));
5077 trial_cpus = cpumask_weight(trial);
5079 raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
5080 if (cur_dl_b->bw != -1 &&
5081 cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
5083 raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
5084 rcu_read_unlock_sched();
5089 int task_can_attach(struct task_struct *p,
5090 const struct cpumask *cs_cpus_allowed)
5095 * Kthreads which disallow setaffinity shouldn't be moved
5096 * to a new cpuset; we don't want to change their cpu
5097 * affinity and isolating such threads by their set of
5098 * allowed nodes is unnecessary. Thus, cpusets are not
5099 * applicable for such threads. This prevents checking for
5100 * success of set_cpus_allowed_ptr() on all attached tasks
5101 * before cpus_allowed may be changed.
5103 if (p->flags & PF_NO_SETAFFINITY) {
5109 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5111 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
5116 unsigned long flags;
5118 rcu_read_lock_sched();
5119 dl_b = dl_bw_of(dest_cpu);
5120 raw_spin_lock_irqsave(&dl_b->lock, flags);
5121 cpus = dl_bw_cpus(dest_cpu);
5122 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
5127 * We reserve space for this task in the destination
5128 * root_domain, as we can't fail after this point.
5129 * We will free resources in the source root_domain
5130 * later on (see set_cpus_allowed_dl()).
5132 __dl_add(dl_b, p->dl.dl_bw);
5134 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5135 rcu_read_unlock_sched();
5145 #ifdef CONFIG_NUMA_BALANCING
5146 /* Migrate current task p to target_cpu */
5147 int migrate_task_to(struct task_struct *p, int target_cpu)
5149 struct migration_arg arg = { p, target_cpu };
5150 int curr_cpu = task_cpu(p);
5152 if (curr_cpu == target_cpu)
5155 if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
5158 /* TODO: This is not properly updating schedstats */
5160 trace_sched_move_numa(p, curr_cpu, target_cpu);
5161 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5165 * Requeue a task on a given node and accurately track the number of NUMA
5166 * tasks on the runqueues
5168 void sched_setnuma(struct task_struct *p, int nid)
5171 unsigned long flags;
5172 bool queued, running;
5174 rq = task_rq_lock(p, &flags);
5175 queued = task_on_rq_queued(p);
5176 running = task_current(rq, p);
5179 dequeue_task(rq, p, DEQUEUE_SAVE);
5181 put_prev_task(rq, p);
5183 p->numa_preferred_nid = nid;
5186 p->sched_class->set_curr_task(rq);
5188 enqueue_task(rq, p, ENQUEUE_RESTORE);
5189 task_rq_unlock(rq, p, &flags);
5191 #endif /* CONFIG_NUMA_BALANCING */
5193 #ifdef CONFIG_HOTPLUG_CPU
5195 * Ensures that the idle task is using init_mm right before its cpu goes
5198 void idle_task_exit(void)
5200 struct mm_struct *mm = current->active_mm;
5202 BUG_ON(cpu_online(smp_processor_id()));
5204 if (mm != &init_mm) {
5205 switch_mm(mm, &init_mm, current);
5206 finish_arch_post_lock_switch();
5212 * Since this CPU is going 'away' for a while, fold any nr_active delta
5213 * we might have. Assumes we're called after migrate_tasks() so that the
5214 * nr_active count is stable.
5216 * Also see the comment "Global load-average calculations".
5218 static void calc_load_migrate(struct rq *rq)
5220 long delta = calc_load_fold_active(rq);
5222 atomic_long_add(delta, &calc_load_tasks);
5225 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5229 static const struct sched_class fake_sched_class = {
5230 .put_prev_task = put_prev_task_fake,
5233 static struct task_struct fake_task = {
5235 * Avoid pull_{rt,dl}_task()
5237 .prio = MAX_PRIO + 1,
5238 .sched_class = &fake_sched_class,
5242 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5243 * try_to_wake_up()->select_task_rq().
5245 * Called with rq->lock held even though we'er in stop_machine() and
5246 * there's no concurrency possible, we hold the required locks anyway
5247 * because of lock validation efforts.
5249 static void migrate_tasks(struct rq *dead_rq)
5251 struct rq *rq = dead_rq;
5252 struct task_struct *next, *stop = rq->stop;
5256 * Fudge the rq selection such that the below task selection loop
5257 * doesn't get stuck on the currently eligible stop task.
5259 * We're currently inside stop_machine() and the rq is either stuck
5260 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5261 * either way we should never end up calling schedule() until we're
5267 * put_prev_task() and pick_next_task() sched
5268 * class method both need to have an up-to-date
5269 * value of rq->clock[_task]
5271 update_rq_clock(rq);
5275 * There's this thread running, bail when that's the only
5278 if (rq->nr_running == 1)
5282 * pick_next_task assumes pinned rq->lock.
5284 lockdep_pin_lock(&rq->lock);
5285 next = pick_next_task(rq, &fake_task);
5287 next->sched_class->put_prev_task(rq, next);
5290 * Rules for changing task_struct::cpus_allowed are holding
5291 * both pi_lock and rq->lock, such that holding either
5292 * stabilizes the mask.
5294 * Drop rq->lock is not quite as disastrous as it usually is
5295 * because !cpu_active at this point, which means load-balance
5296 * will not interfere. Also, stop-machine.
5298 lockdep_unpin_lock(&rq->lock);
5299 raw_spin_unlock(&rq->lock);
5300 raw_spin_lock(&next->pi_lock);
5301 raw_spin_lock(&rq->lock);
5304 * Since we're inside stop-machine, _nothing_ should have
5305 * changed the task, WARN if weird stuff happened, because in
5306 * that case the above rq->lock drop is a fail too.
5308 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5309 raw_spin_unlock(&next->pi_lock);
5313 /* Find suitable destination for @next, with force if needed. */
5314 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5316 rq = __migrate_task(rq, next, dest_cpu);
5317 if (rq != dead_rq) {
5318 raw_spin_unlock(&rq->lock);
5320 raw_spin_lock(&rq->lock);
5322 raw_spin_unlock(&next->pi_lock);
5327 #endif /* CONFIG_HOTPLUG_CPU */
5329 static void set_rq_online(struct rq *rq)
5332 const struct sched_class *class;
5334 cpumask_set_cpu(rq->cpu, rq->rd->online);
5337 for_each_class(class) {
5338 if (class->rq_online)
5339 class->rq_online(rq);
5344 static void set_rq_offline(struct rq *rq)
5347 const struct sched_class *class;
5349 for_each_class(class) {
5350 if (class->rq_offline)
5351 class->rq_offline(rq);
5354 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5360 * migration_call - callback that gets triggered when a CPU is added.
5361 * Here we can start up the necessary migration thread for the new CPU.
5364 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5366 int cpu = (long)hcpu;
5367 unsigned long flags;
5368 struct rq *rq = cpu_rq(cpu);
5370 switch (action & ~CPU_TASKS_FROZEN) {
5372 case CPU_UP_PREPARE:
5373 rq->calc_load_update = calc_load_update;
5377 /* Update our root-domain */
5378 raw_spin_lock_irqsave(&rq->lock, flags);
5380 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5384 raw_spin_unlock_irqrestore(&rq->lock, flags);
5387 #ifdef CONFIG_HOTPLUG_CPU
5389 sched_ttwu_pending();
5390 /* Update our root-domain */
5391 raw_spin_lock_irqsave(&rq->lock, flags);
5393 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5397 BUG_ON(rq->nr_running != 1); /* the migration thread */
5398 raw_spin_unlock_irqrestore(&rq->lock, flags);
5402 calc_load_migrate(rq);
5407 update_max_interval();
5413 * Register at high priority so that task migration (migrate_all_tasks)
5414 * happens before everything else. This has to be lower priority than
5415 * the notifier in the perf_event subsystem, though.
5417 static struct notifier_block migration_notifier = {
5418 .notifier_call = migration_call,
5419 .priority = CPU_PRI_MIGRATION,
5422 static void set_cpu_rq_start_time(void)
5424 int cpu = smp_processor_id();
5425 struct rq *rq = cpu_rq(cpu);
5426 rq->age_stamp = sched_clock_cpu(cpu);
5429 static int sched_cpu_active(struct notifier_block *nfb,
5430 unsigned long action, void *hcpu)
5432 int cpu = (long)hcpu;
5434 switch (action & ~CPU_TASKS_FROZEN) {
5436 set_cpu_rq_start_time();
5439 case CPU_DOWN_FAILED:
5440 set_cpu_active(cpu, true);
5448 static int sched_cpu_inactive(struct notifier_block *nfb,
5449 unsigned long action, void *hcpu)
5451 switch (action & ~CPU_TASKS_FROZEN) {
5452 case CPU_DOWN_PREPARE:
5453 set_cpu_active((long)hcpu, false);
5460 static int __init migration_init(void)
5462 void *cpu = (void *)(long)smp_processor_id();
5465 /* Initialize migration for the boot CPU */
5466 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5467 BUG_ON(err == NOTIFY_BAD);
5468 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5469 register_cpu_notifier(&migration_notifier);
5471 /* Register cpu active notifiers */
5472 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5473 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5477 early_initcall(migration_init);
5479 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5481 #ifdef CONFIG_SCHED_DEBUG
5483 static __read_mostly int sched_debug_enabled;
5485 static int __init sched_debug_setup(char *str)
5487 sched_debug_enabled = 1;
5491 early_param("sched_debug", sched_debug_setup);
5493 static inline bool sched_debug(void)
5495 return sched_debug_enabled;
5498 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5499 struct cpumask *groupmask)
5501 struct sched_group *group = sd->groups;
5503 cpumask_clear(groupmask);
5505 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5507 if (!(sd->flags & SD_LOAD_BALANCE)) {
5508 printk("does not load-balance\n");
5510 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5515 printk(KERN_CONT "span %*pbl level %s\n",
5516 cpumask_pr_args(sched_domain_span(sd)), sd->name);
5518 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5519 printk(KERN_ERR "ERROR: domain->span does not contain "
5522 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5523 printk(KERN_ERR "ERROR: domain->groups does not contain"
5527 printk(KERN_DEBUG "%*s groups:", level + 1, "");
5531 printk(KERN_ERR "ERROR: group is NULL\n");
5535 if (!cpumask_weight(sched_group_cpus(group))) {
5536 printk(KERN_CONT "\n");
5537 printk(KERN_ERR "ERROR: empty group\n");
5541 if (!(sd->flags & SD_OVERLAP) &&
5542 cpumask_intersects(groupmask, sched_group_cpus(group))) {
5543 printk(KERN_CONT "\n");
5544 printk(KERN_ERR "ERROR: repeated CPUs\n");
5548 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5550 printk(KERN_CONT " %*pbl",
5551 cpumask_pr_args(sched_group_cpus(group)));
5552 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
5553 printk(KERN_CONT " (cpu_capacity = %d)",
5554 group->sgc->capacity);
5557 group = group->next;
5558 } while (group != sd->groups);
5559 printk(KERN_CONT "\n");
5561 if (!cpumask_equal(sched_domain_span(sd), groupmask))
5562 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5565 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5566 printk(KERN_ERR "ERROR: parent span is not a superset "
5567 "of domain->span\n");
5571 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5575 if (!sched_debug_enabled)
5579 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5583 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5586 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5594 #else /* !CONFIG_SCHED_DEBUG */
5595 # define sched_domain_debug(sd, cpu) do { } while (0)
5596 static inline bool sched_debug(void)
5600 #endif /* CONFIG_SCHED_DEBUG */
5602 static int sd_degenerate(struct sched_domain *sd)
5604 if (cpumask_weight(sched_domain_span(sd)) == 1)
5607 /* Following flags need at least 2 groups */
5608 if (sd->flags & (SD_LOAD_BALANCE |
5609 SD_BALANCE_NEWIDLE |
5612 SD_SHARE_CPUCAPACITY |
5613 SD_SHARE_PKG_RESOURCES |
5614 SD_SHARE_POWERDOMAIN)) {
5615 if (sd->groups != sd->groups->next)
5619 /* Following flags don't use groups */
5620 if (sd->flags & (SD_WAKE_AFFINE))
5627 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5629 unsigned long cflags = sd->flags, pflags = parent->flags;
5631 if (sd_degenerate(parent))
5634 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5637 /* Flags needing groups don't count if only 1 group in parent */
5638 if (parent->groups == parent->groups->next) {
5639 pflags &= ~(SD_LOAD_BALANCE |
5640 SD_BALANCE_NEWIDLE |
5643 SD_SHARE_CPUCAPACITY |
5644 SD_SHARE_PKG_RESOURCES |
5646 SD_SHARE_POWERDOMAIN);
5647 if (nr_node_ids == 1)
5648 pflags &= ~SD_SERIALIZE;
5650 if (~cflags & pflags)
5656 static void free_rootdomain(struct rcu_head *rcu)
5658 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5660 cpupri_cleanup(&rd->cpupri);
5661 cpudl_cleanup(&rd->cpudl);
5662 free_cpumask_var(rd->dlo_mask);
5663 free_cpumask_var(rd->rto_mask);
5664 free_cpumask_var(rd->online);
5665 free_cpumask_var(rd->span);
5669 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5671 struct root_domain *old_rd = NULL;
5672 unsigned long flags;
5674 raw_spin_lock_irqsave(&rq->lock, flags);
5679 if (cpumask_test_cpu(rq->cpu, old_rd->online))
5682 cpumask_clear_cpu(rq->cpu, old_rd->span);
5685 * If we dont want to free the old_rd yet then
5686 * set old_rd to NULL to skip the freeing later
5689 if (!atomic_dec_and_test(&old_rd->refcount))
5693 atomic_inc(&rd->refcount);
5696 cpumask_set_cpu(rq->cpu, rd->span);
5697 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
5700 raw_spin_unlock_irqrestore(&rq->lock, flags);
5703 call_rcu_sched(&old_rd->rcu, free_rootdomain);
5706 static int init_rootdomain(struct root_domain *rd)
5708 memset(rd, 0, sizeof(*rd));
5710 if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
5712 if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
5714 if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
5716 if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
5719 init_dl_bw(&rd->dl_bw);
5720 if (cpudl_init(&rd->cpudl) != 0)
5723 if (cpupri_init(&rd->cpupri) != 0)
5728 free_cpumask_var(rd->rto_mask);
5730 free_cpumask_var(rd->dlo_mask);
5732 free_cpumask_var(rd->online);
5734 free_cpumask_var(rd->span);
5740 * By default the system creates a single root-domain with all cpus as
5741 * members (mimicking the global state we have today).
5743 struct root_domain def_root_domain;
5745 static void init_defrootdomain(void)
5747 init_rootdomain(&def_root_domain);
5749 atomic_set(&def_root_domain.refcount, 1);
5752 static struct root_domain *alloc_rootdomain(void)
5754 struct root_domain *rd;
5756 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5760 if (init_rootdomain(rd) != 0) {
5768 static void free_sched_groups(struct sched_group *sg, int free_sgc)
5770 struct sched_group *tmp, *first;
5779 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
5784 } while (sg != first);
5787 static void free_sched_domain(struct rcu_head *rcu)
5789 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
5792 * If its an overlapping domain it has private groups, iterate and
5795 if (sd->flags & SD_OVERLAP) {
5796 free_sched_groups(sd->groups, 1);
5797 } else if (atomic_dec_and_test(&sd->groups->ref)) {
5798 kfree(sd->groups->sgc);
5804 static void destroy_sched_domain(struct sched_domain *sd, int cpu)
5806 call_rcu(&sd->rcu, free_sched_domain);
5809 static void destroy_sched_domains(struct sched_domain *sd, int cpu)
5811 for (; sd; sd = sd->parent)
5812 destroy_sched_domain(sd, cpu);
5816 * Keep a special pointer to the highest sched_domain that has
5817 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
5818 * allows us to avoid some pointer chasing select_idle_sibling().
5820 * Also keep a unique ID per domain (we use the first cpu number in
5821 * the cpumask of the domain), this allows us to quickly tell if
5822 * two cpus are in the same cache domain, see cpus_share_cache().
5824 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
5825 DEFINE_PER_CPU(int, sd_llc_size);
5826 DEFINE_PER_CPU(int, sd_llc_id);
5827 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
5828 DEFINE_PER_CPU(struct sched_domain *, sd_busy);
5829 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
5831 static void update_top_cache_domain(int cpu)
5833 struct sched_domain *sd;
5834 struct sched_domain *busy_sd = NULL;
5838 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
5840 id = cpumask_first(sched_domain_span(sd));
5841 size = cpumask_weight(sched_domain_span(sd));
5842 busy_sd = sd->parent; /* sd_busy */
5844 rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
5846 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
5847 per_cpu(sd_llc_size, cpu) = size;
5848 per_cpu(sd_llc_id, cpu) = id;
5850 sd = lowest_flag_domain(cpu, SD_NUMA);
5851 rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
5853 sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
5854 rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
5858 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5859 * hold the hotplug lock.
5862 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
5864 struct rq *rq = cpu_rq(cpu);
5865 struct sched_domain *tmp;
5867 /* Remove the sched domains which do not contribute to scheduling. */
5868 for (tmp = sd; tmp; ) {
5869 struct sched_domain *parent = tmp->parent;
5873 if (sd_parent_degenerate(tmp, parent)) {
5874 tmp->parent = parent->parent;
5876 parent->parent->child = tmp;
5878 * Transfer SD_PREFER_SIBLING down in case of a
5879 * degenerate parent; the spans match for this
5880 * so the property transfers.
5882 if (parent->flags & SD_PREFER_SIBLING)
5883 tmp->flags |= SD_PREFER_SIBLING;
5884 destroy_sched_domain(parent, cpu);
5889 if (sd && sd_degenerate(sd)) {
5892 destroy_sched_domain(tmp, cpu);
5897 sched_domain_debug(sd, cpu);
5899 rq_attach_root(rq, rd);
5901 rcu_assign_pointer(rq->sd, sd);
5902 destroy_sched_domains(tmp, cpu);
5904 update_top_cache_domain(cpu);
5907 /* Setup the mask of cpus configured for isolated domains */
5908 static int __init isolated_cpu_setup(char *str)
5912 alloc_bootmem_cpumask_var(&cpu_isolated_map);
5913 ret = cpulist_parse(str, cpu_isolated_map);
5915 pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
5920 __setup("isolcpus=", isolated_cpu_setup);
5923 struct sched_domain ** __percpu sd;
5924 struct root_domain *rd;
5935 * Build an iteration mask that can exclude certain CPUs from the upwards
5938 * Asymmetric node setups can result in situations where the domain tree is of
5939 * unequal depth, make sure to skip domains that already cover the entire
5942 * In that case build_sched_domains() will have terminated the iteration early
5943 * and our sibling sd spans will be empty. Domains should always include the
5944 * cpu they're built on, so check that.
5947 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
5949 const struct cpumask *span = sched_domain_span(sd);
5950 struct sd_data *sdd = sd->private;
5951 struct sched_domain *sibling;
5954 for_each_cpu(i, span) {
5955 sibling = *per_cpu_ptr(sdd->sd, i);
5956 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
5959 cpumask_set_cpu(i, sched_group_mask(sg));
5964 * Return the canonical balance cpu for this group, this is the first cpu
5965 * of this group that's also in the iteration mask.
5967 int group_balance_cpu(struct sched_group *sg)
5969 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
5973 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
5975 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
5976 const struct cpumask *span = sched_domain_span(sd);
5977 struct cpumask *covered = sched_domains_tmpmask;
5978 struct sd_data *sdd = sd->private;
5979 struct sched_domain *sibling;
5982 cpumask_clear(covered);
5984 for_each_cpu(i, span) {
5985 struct cpumask *sg_span;
5987 if (cpumask_test_cpu(i, covered))
5990 sibling = *per_cpu_ptr(sdd->sd, i);
5992 /* See the comment near build_group_mask(). */
5993 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
5996 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
5997 GFP_KERNEL, cpu_to_node(cpu));
6002 sg_span = sched_group_cpus(sg);
6004 cpumask_copy(sg_span, sched_domain_span(sibling->child));
6006 cpumask_set_cpu(i, sg_span);
6008 cpumask_or(covered, covered, sg_span);
6010 sg->sgc = *per_cpu_ptr(sdd->sgc, i);
6011 if (atomic_inc_return(&sg->sgc->ref) == 1)
6012 build_group_mask(sd, sg);
6015 * Initialize sgc->capacity such that even if we mess up the
6016 * domains and no possible iteration will get us here, we won't
6019 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
6022 * Make sure the first group of this domain contains the
6023 * canonical balance cpu. Otherwise the sched_domain iteration
6024 * breaks. See update_sg_lb_stats().
6026 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
6027 group_balance_cpu(sg) == cpu)
6037 sd->groups = groups;
6042 free_sched_groups(first, 0);
6047 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
6049 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6050 struct sched_domain *child = sd->child;
6053 cpu = cpumask_first(sched_domain_span(child));
6056 *sg = *per_cpu_ptr(sdd->sg, cpu);
6057 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
6058 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
6065 * build_sched_groups will build a circular linked list of the groups
6066 * covered by the given span, and will set each group's ->cpumask correctly,
6067 * and ->cpu_capacity to 0.
6069 * Assumes the sched_domain tree is fully constructed
6072 build_sched_groups(struct sched_domain *sd, int cpu)
6074 struct sched_group *first = NULL, *last = NULL;
6075 struct sd_data *sdd = sd->private;
6076 const struct cpumask *span = sched_domain_span(sd);
6077 struct cpumask *covered;
6080 get_group(cpu, sdd, &sd->groups);
6081 atomic_inc(&sd->groups->ref);
6083 if (cpu != cpumask_first(span))
6086 lockdep_assert_held(&sched_domains_mutex);
6087 covered = sched_domains_tmpmask;
6089 cpumask_clear(covered);
6091 for_each_cpu(i, span) {
6092 struct sched_group *sg;
6095 if (cpumask_test_cpu(i, covered))
6098 group = get_group(i, sdd, &sg);
6099 cpumask_setall(sched_group_mask(sg));
6101 for_each_cpu(j, span) {
6102 if (get_group(j, sdd, NULL) != group)
6105 cpumask_set_cpu(j, covered);
6106 cpumask_set_cpu(j, sched_group_cpus(sg));
6121 * Initialize sched groups cpu_capacity.
6123 * cpu_capacity indicates the capacity of sched group, which is used while
6124 * distributing the load between different sched groups in a sched domain.
6125 * Typically cpu_capacity for all the groups in a sched domain will be same
6126 * unless there are asymmetries in the topology. If there are asymmetries,
6127 * group having more cpu_capacity will pickup more load compared to the
6128 * group having less cpu_capacity.
6130 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
6132 struct sched_group *sg = sd->groups;
6137 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6139 } while (sg != sd->groups);
6141 if (cpu != group_balance_cpu(sg))
6144 update_group_capacity(sd, cpu);
6145 atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
6149 * Initializers for schedule domains
6150 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6153 static int default_relax_domain_level = -1;
6154 int sched_domain_level_max;
6156 static int __init setup_relax_domain_level(char *str)
6158 if (kstrtoint(str, 0, &default_relax_domain_level))
6159 pr_warn("Unable to set relax_domain_level\n");
6163 __setup("relax_domain_level=", setup_relax_domain_level);
6165 static void set_domain_attribute(struct sched_domain *sd,
6166 struct sched_domain_attr *attr)
6170 if (!attr || attr->relax_domain_level < 0) {
6171 if (default_relax_domain_level < 0)
6174 request = default_relax_domain_level;
6176 request = attr->relax_domain_level;
6177 if (request < sd->level) {
6178 /* turn off idle balance on this domain */
6179 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6181 /* turn on idle balance on this domain */
6182 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6186 static void __sdt_free(const struct cpumask *cpu_map);
6187 static int __sdt_alloc(const struct cpumask *cpu_map);
6189 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6190 const struct cpumask *cpu_map)
6194 if (!atomic_read(&d->rd->refcount))
6195 free_rootdomain(&d->rd->rcu); /* fall through */
6197 free_percpu(d->sd); /* fall through */
6199 __sdt_free(cpu_map); /* fall through */
6205 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6206 const struct cpumask *cpu_map)
6208 memset(d, 0, sizeof(*d));
6210 if (__sdt_alloc(cpu_map))
6211 return sa_sd_storage;
6212 d->sd = alloc_percpu(struct sched_domain *);
6214 return sa_sd_storage;
6215 d->rd = alloc_rootdomain();
6218 return sa_rootdomain;
6222 * NULL the sd_data elements we've used to build the sched_domain and
6223 * sched_group structure so that the subsequent __free_domain_allocs()
6224 * will not free the data we're using.
6226 static void claim_allocations(int cpu, struct sched_domain *sd)
6228 struct sd_data *sdd = sd->private;
6230 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6231 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6233 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6234 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6236 if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
6237 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
6241 static int sched_domains_numa_levels;
6242 enum numa_topology_type sched_numa_topology_type;
6243 static int *sched_domains_numa_distance;
6244 int sched_max_numa_distance;
6245 static struct cpumask ***sched_domains_numa_masks;
6246 static int sched_domains_curr_level;
6250 * SD_flags allowed in topology descriptions.
6252 * SD_SHARE_CPUCAPACITY - describes SMT topologies
6253 * SD_SHARE_PKG_RESOURCES - describes shared caches
6254 * SD_NUMA - describes NUMA topologies
6255 * SD_SHARE_POWERDOMAIN - describes shared power domain
6258 * SD_ASYM_PACKING - describes SMT quirks
6260 #define TOPOLOGY_SD_FLAGS \
6261 (SD_SHARE_CPUCAPACITY | \
6262 SD_SHARE_PKG_RESOURCES | \
6265 SD_SHARE_POWERDOMAIN)
6267 static struct sched_domain *
6268 sd_init(struct sched_domain_topology_level *tl, int cpu)
6270 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6271 int sd_weight, sd_flags = 0;
6275 * Ugly hack to pass state to sd_numa_mask()...
6277 sched_domains_curr_level = tl->numa_level;
6280 sd_weight = cpumask_weight(tl->mask(cpu));
6283 sd_flags = (*tl->sd_flags)();
6284 if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
6285 "wrong sd_flags in topology description\n"))
6286 sd_flags &= ~TOPOLOGY_SD_FLAGS;
6288 *sd = (struct sched_domain){
6289 .min_interval = sd_weight,
6290 .max_interval = 2*sd_weight,
6292 .imbalance_pct = 125,
6294 .cache_nice_tries = 0,
6301 .flags = 1*SD_LOAD_BALANCE
6302 | 1*SD_BALANCE_NEWIDLE
6307 | 0*SD_SHARE_CPUCAPACITY
6308 | 0*SD_SHARE_PKG_RESOURCES
6310 | 0*SD_PREFER_SIBLING
6315 .last_balance = jiffies,
6316 .balance_interval = sd_weight,
6318 .max_newidle_lb_cost = 0,
6319 .next_decay_max_lb_cost = jiffies,
6320 #ifdef CONFIG_SCHED_DEBUG
6326 * Convert topological properties into behaviour.
6329 if (sd->flags & SD_SHARE_CPUCAPACITY) {
6330 sd->flags |= SD_PREFER_SIBLING;
6331 sd->imbalance_pct = 110;
6332 sd->smt_gain = 1178; /* ~15% */
6334 } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6335 sd->imbalance_pct = 117;
6336 sd->cache_nice_tries = 1;
6340 } else if (sd->flags & SD_NUMA) {
6341 sd->cache_nice_tries = 2;
6345 sd->flags |= SD_SERIALIZE;
6346 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
6347 sd->flags &= ~(SD_BALANCE_EXEC |
6354 sd->flags |= SD_PREFER_SIBLING;
6355 sd->cache_nice_tries = 1;
6360 sd->private = &tl->data;
6366 * Topology list, bottom-up.
6368 static struct sched_domain_topology_level default_topology[] = {
6369 #ifdef CONFIG_SCHED_SMT
6370 { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
6372 #ifdef CONFIG_SCHED_MC
6373 { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
6375 { cpu_cpu_mask, SD_INIT_NAME(DIE) },
6379 static struct sched_domain_topology_level *sched_domain_topology =
6382 #define for_each_sd_topology(tl) \
6383 for (tl = sched_domain_topology; tl->mask; tl++)
6385 void set_sched_topology(struct sched_domain_topology_level *tl)
6387 sched_domain_topology = tl;
6392 static const struct cpumask *sd_numa_mask(int cpu)
6394 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6397 static void sched_numa_warn(const char *str)
6399 static int done = false;
6407 printk(KERN_WARNING "ERROR: %s\n\n", str);
6409 for (i = 0; i < nr_node_ids; i++) {
6410 printk(KERN_WARNING " ");
6411 for (j = 0; j < nr_node_ids; j++)
6412 printk(KERN_CONT "%02d ", node_distance(i,j));
6413 printk(KERN_CONT "\n");
6415 printk(KERN_WARNING "\n");
6418 bool find_numa_distance(int distance)
6422 if (distance == node_distance(0, 0))
6425 for (i = 0; i < sched_domains_numa_levels; i++) {
6426 if (sched_domains_numa_distance[i] == distance)
6434 * A system can have three types of NUMA topology:
6435 * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6436 * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6437 * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6439 * The difference between a glueless mesh topology and a backplane
6440 * topology lies in whether communication between not directly
6441 * connected nodes goes through intermediary nodes (where programs
6442 * could run), or through backplane controllers. This affects
6443 * placement of programs.
6445 * The type of topology can be discerned with the following tests:
6446 * - If the maximum distance between any nodes is 1 hop, the system
6447 * is directly connected.
6448 * - If for two nodes A and B, located N > 1 hops away from each other,
6449 * there is an intermediary node C, which is < N hops away from both
6450 * nodes A and B, the system is a glueless mesh.
6452 static void init_numa_topology_type(void)
6456 n = sched_max_numa_distance;
6458 if (sched_domains_numa_levels <= 1) {
6459 sched_numa_topology_type = NUMA_DIRECT;
6463 for_each_online_node(a) {
6464 for_each_online_node(b) {
6465 /* Find two nodes furthest removed from each other. */
6466 if (node_distance(a, b) < n)
6469 /* Is there an intermediary node between a and b? */
6470 for_each_online_node(c) {
6471 if (node_distance(a, c) < n &&
6472 node_distance(b, c) < n) {
6473 sched_numa_topology_type =
6479 sched_numa_topology_type = NUMA_BACKPLANE;
6485 static void sched_init_numa(void)
6487 int next_distance, curr_distance = node_distance(0, 0);
6488 struct sched_domain_topology_level *tl;
6492 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6493 if (!sched_domains_numa_distance)
6497 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6498 * unique distances in the node_distance() table.
6500 * Assumes node_distance(0,j) includes all distances in
6501 * node_distance(i,j) in order to avoid cubic time.
6503 next_distance = curr_distance;
6504 for (i = 0; i < nr_node_ids; i++) {
6505 for (j = 0; j < nr_node_ids; j++) {
6506 for (k = 0; k < nr_node_ids; k++) {
6507 int distance = node_distance(i, k);
6509 if (distance > curr_distance &&
6510 (distance < next_distance ||
6511 next_distance == curr_distance))
6512 next_distance = distance;
6515 * While not a strong assumption it would be nice to know
6516 * about cases where if node A is connected to B, B is not
6517 * equally connected to A.
6519 if (sched_debug() && node_distance(k, i) != distance)
6520 sched_numa_warn("Node-distance not symmetric");
6522 if (sched_debug() && i && !find_numa_distance(distance))
6523 sched_numa_warn("Node-0 not representative");
6525 if (next_distance != curr_distance) {
6526 sched_domains_numa_distance[level++] = next_distance;
6527 sched_domains_numa_levels = level;
6528 curr_distance = next_distance;
6533 * In case of sched_debug() we verify the above assumption.
6543 * 'level' contains the number of unique distances, excluding the
6544 * identity distance node_distance(i,i).
6546 * The sched_domains_numa_distance[] array includes the actual distance
6551 * Here, we should temporarily reset sched_domains_numa_levels to 0.
6552 * If it fails to allocate memory for array sched_domains_numa_masks[][],
6553 * the array will contain less then 'level' members. This could be
6554 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6555 * in other functions.
6557 * We reset it to 'level' at the end of this function.
6559 sched_domains_numa_levels = 0;
6561 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6562 if (!sched_domains_numa_masks)
6566 * Now for each level, construct a mask per node which contains all
6567 * cpus of nodes that are that many hops away from us.
6569 for (i = 0; i < level; i++) {
6570 sched_domains_numa_masks[i] =
6571 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6572 if (!sched_domains_numa_masks[i])
6575 for (j = 0; j < nr_node_ids; j++) {
6576 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
6580 sched_domains_numa_masks[i][j] = mask;
6583 if (node_distance(j, k) > sched_domains_numa_distance[i])
6586 cpumask_or(mask, mask, cpumask_of_node(k));
6591 /* Compute default topology size */
6592 for (i = 0; sched_domain_topology[i].mask; i++);
6594 tl = kzalloc((i + level + 1) *
6595 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6600 * Copy the default topology bits..
6602 for (i = 0; sched_domain_topology[i].mask; i++)
6603 tl[i] = sched_domain_topology[i];
6606 * .. and append 'j' levels of NUMA goodness.
6608 for (j = 0; j < level; i++, j++) {
6609 tl[i] = (struct sched_domain_topology_level){
6610 .mask = sd_numa_mask,
6611 .sd_flags = cpu_numa_flags,
6612 .flags = SDTL_OVERLAP,
6618 sched_domain_topology = tl;
6620 sched_domains_numa_levels = level;
6621 sched_max_numa_distance = sched_domains_numa_distance[level - 1];
6623 init_numa_topology_type();
6626 static void sched_domains_numa_masks_set(int cpu)
6629 int node = cpu_to_node(cpu);
6631 for (i = 0; i < sched_domains_numa_levels; i++) {
6632 for (j = 0; j < nr_node_ids; j++) {
6633 if (node_distance(j, node) <= sched_domains_numa_distance[i])
6634 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6639 static void sched_domains_numa_masks_clear(int cpu)
6642 for (i = 0; i < sched_domains_numa_levels; i++) {
6643 for (j = 0; j < nr_node_ids; j++)
6644 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6649 * Update sched_domains_numa_masks[level][node] array when new cpus
6652 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6653 unsigned long action,
6656 int cpu = (long)hcpu;
6658 switch (action & ~CPU_TASKS_FROZEN) {
6660 sched_domains_numa_masks_set(cpu);
6664 sched_domains_numa_masks_clear(cpu);
6674 static inline void sched_init_numa(void)
6678 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6679 unsigned long action,
6684 #endif /* CONFIG_NUMA */
6686 static int __sdt_alloc(const struct cpumask *cpu_map)
6688 struct sched_domain_topology_level *tl;
6691 for_each_sd_topology(tl) {
6692 struct sd_data *sdd = &tl->data;
6694 sdd->sd = alloc_percpu(struct sched_domain *);
6698 sdd->sg = alloc_percpu(struct sched_group *);
6702 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
6706 for_each_cpu(j, cpu_map) {
6707 struct sched_domain *sd;
6708 struct sched_group *sg;
6709 struct sched_group_capacity *sgc;
6711 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6712 GFP_KERNEL, cpu_to_node(j));
6716 *per_cpu_ptr(sdd->sd, j) = sd;
6718 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6719 GFP_KERNEL, cpu_to_node(j));
6725 *per_cpu_ptr(sdd->sg, j) = sg;
6727 sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
6728 GFP_KERNEL, cpu_to_node(j));
6732 *per_cpu_ptr(sdd->sgc, j) = sgc;
6739 static void __sdt_free(const struct cpumask *cpu_map)
6741 struct sched_domain_topology_level *tl;
6744 for_each_sd_topology(tl) {
6745 struct sd_data *sdd = &tl->data;
6747 for_each_cpu(j, cpu_map) {
6748 struct sched_domain *sd;
6751 sd = *per_cpu_ptr(sdd->sd, j);
6752 if (sd && (sd->flags & SD_OVERLAP))
6753 free_sched_groups(sd->groups, 0);
6754 kfree(*per_cpu_ptr(sdd->sd, j));
6758 kfree(*per_cpu_ptr(sdd->sg, j));
6760 kfree(*per_cpu_ptr(sdd->sgc, j));
6762 free_percpu(sdd->sd);
6764 free_percpu(sdd->sg);
6766 free_percpu(sdd->sgc);
6771 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6772 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6773 struct sched_domain *child, int cpu)
6775 struct sched_domain *sd = sd_init(tl, cpu);
6779 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6781 sd->level = child->level + 1;
6782 sched_domain_level_max = max(sched_domain_level_max, sd->level);
6786 if (!cpumask_subset(sched_domain_span(child),
6787 sched_domain_span(sd))) {
6788 pr_err("BUG: arch topology borken\n");
6789 #ifdef CONFIG_SCHED_DEBUG
6790 pr_err(" the %s domain not a subset of the %s domain\n",
6791 child->name, sd->name);
6793 /* Fixup, ensure @sd has at least @child cpus. */
6794 cpumask_or(sched_domain_span(sd),
6795 sched_domain_span(sd),
6796 sched_domain_span(child));
6800 set_domain_attribute(sd, attr);
6806 * Build sched domains for a given set of cpus and attach the sched domains
6807 * to the individual cpus
6809 static int build_sched_domains(const struct cpumask *cpu_map,
6810 struct sched_domain_attr *attr)
6812 enum s_alloc alloc_state;
6813 struct sched_domain *sd;
6815 int i, ret = -ENOMEM;
6817 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
6818 if (alloc_state != sa_rootdomain)
6821 /* Set up domains for cpus specified by the cpu_map. */
6822 for_each_cpu(i, cpu_map) {
6823 struct sched_domain_topology_level *tl;
6826 for_each_sd_topology(tl) {
6827 sd = build_sched_domain(tl, cpu_map, attr, sd, i);
6828 if (tl == sched_domain_topology)
6829 *per_cpu_ptr(d.sd, i) = sd;
6830 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
6831 sd->flags |= SD_OVERLAP;
6832 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
6837 /* Build the groups for the domains */
6838 for_each_cpu(i, cpu_map) {
6839 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6840 sd->span_weight = cpumask_weight(sched_domain_span(sd));
6841 if (sd->flags & SD_OVERLAP) {
6842 if (build_overlap_sched_groups(sd, i))
6845 if (build_sched_groups(sd, i))
6851 /* Calculate CPU capacity for physical packages and nodes */
6852 for (i = nr_cpumask_bits-1; i >= 0; i--) {
6853 if (!cpumask_test_cpu(i, cpu_map))
6856 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6857 claim_allocations(i, sd);
6858 init_sched_groups_capacity(i, sd);
6862 /* Attach the domains */
6864 for_each_cpu(i, cpu_map) {
6865 sd = *per_cpu_ptr(d.sd, i);
6866 cpu_attach_domain(sd, d.rd, i);
6872 __free_domain_allocs(&d, alloc_state, cpu_map);
6876 static cpumask_var_t *doms_cur; /* current sched domains */
6877 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
6878 static struct sched_domain_attr *dattr_cur;
6879 /* attribues of custom domains in 'doms_cur' */
6882 * Special case: If a kmalloc of a doms_cur partition (array of
6883 * cpumask) fails, then fallback to a single sched domain,
6884 * as determined by the single cpumask fallback_doms.
6886 static cpumask_var_t fallback_doms;
6889 * arch_update_cpu_topology lets virtualized architectures update the
6890 * cpu core maps. It is supposed to return 1 if the topology changed
6891 * or 0 if it stayed the same.
6893 int __weak arch_update_cpu_topology(void)
6898 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
6901 cpumask_var_t *doms;
6903 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
6906 for (i = 0; i < ndoms; i++) {
6907 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
6908 free_sched_domains(doms, i);
6915 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
6918 for (i = 0; i < ndoms; i++)
6919 free_cpumask_var(doms[i]);
6924 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6925 * For now this just excludes isolated cpus, but could be used to
6926 * exclude other special cases in the future.
6928 static int init_sched_domains(const struct cpumask *cpu_map)
6932 arch_update_cpu_topology();
6934 doms_cur = alloc_sched_domains(ndoms_cur);
6936 doms_cur = &fallback_doms;
6937 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
6938 err = build_sched_domains(doms_cur[0], NULL);
6939 register_sched_domain_sysctl();
6945 * Detach sched domains from a group of cpus specified in cpu_map
6946 * These cpus will now be attached to the NULL domain
6948 static void detach_destroy_domains(const struct cpumask *cpu_map)
6953 for_each_cpu(i, cpu_map)
6954 cpu_attach_domain(NULL, &def_root_domain, i);
6958 /* handle null as "default" */
6959 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
6960 struct sched_domain_attr *new, int idx_new)
6962 struct sched_domain_attr tmp;
6969 return !memcmp(cur ? (cur + idx_cur) : &tmp,
6970 new ? (new + idx_new) : &tmp,
6971 sizeof(struct sched_domain_attr));
6975 * Partition sched domains as specified by the 'ndoms_new'
6976 * cpumasks in the array doms_new[] of cpumasks. This compares
6977 * doms_new[] to the current sched domain partitioning, doms_cur[].
6978 * It destroys each deleted domain and builds each new domain.
6980 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
6981 * The masks don't intersect (don't overlap.) We should setup one
6982 * sched domain for each mask. CPUs not in any of the cpumasks will
6983 * not be load balanced. If the same cpumask appears both in the
6984 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6987 * The passed in 'doms_new' should be allocated using
6988 * alloc_sched_domains. This routine takes ownership of it and will
6989 * free_sched_domains it when done with it. If the caller failed the
6990 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
6991 * and partition_sched_domains() will fallback to the single partition
6992 * 'fallback_doms', it also forces the domains to be rebuilt.
6994 * If doms_new == NULL it will be replaced with cpu_online_mask.
6995 * ndoms_new == 0 is a special case for destroying existing domains,
6996 * and it will not create the default domain.
6998 * Call with hotplug lock held
7000 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7001 struct sched_domain_attr *dattr_new)
7006 mutex_lock(&sched_domains_mutex);
7008 /* always unregister in case we don't destroy any domains */
7009 unregister_sched_domain_sysctl();
7011 /* Let architecture update cpu core mappings. */
7012 new_topology = arch_update_cpu_topology();
7014 n = doms_new ? ndoms_new : 0;
7016 /* Destroy deleted domains */
7017 for (i = 0; i < ndoms_cur; i++) {
7018 for (j = 0; j < n && !new_topology; j++) {
7019 if (cpumask_equal(doms_cur[i], doms_new[j])
7020 && dattrs_equal(dattr_cur, i, dattr_new, j))
7023 /* no match - a current sched domain not in new doms_new[] */
7024 detach_destroy_domains(doms_cur[i]);
7030 if (doms_new == NULL) {
7032 doms_new = &fallback_doms;
7033 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7034 WARN_ON_ONCE(dattr_new);
7037 /* Build new domains */
7038 for (i = 0; i < ndoms_new; i++) {
7039 for (j = 0; j < n && !new_topology; j++) {
7040 if (cpumask_equal(doms_new[i], doms_cur[j])
7041 && dattrs_equal(dattr_new, i, dattr_cur, j))
7044 /* no match - add a new doms_new */
7045 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7050 /* Remember the new sched domains */
7051 if (doms_cur != &fallback_doms)
7052 free_sched_domains(doms_cur, ndoms_cur);
7053 kfree(dattr_cur); /* kfree(NULL) is safe */
7054 doms_cur = doms_new;
7055 dattr_cur = dattr_new;
7056 ndoms_cur = ndoms_new;
7058 register_sched_domain_sysctl();
7060 mutex_unlock(&sched_domains_mutex);
7063 static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
7066 * Update cpusets according to cpu_active mask. If cpusets are
7067 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7068 * around partition_sched_domains().
7070 * If we come here as part of a suspend/resume, don't touch cpusets because we
7071 * want to restore it back to its original state upon resume anyway.
7073 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7077 case CPU_ONLINE_FROZEN:
7078 case CPU_DOWN_FAILED_FROZEN:
7081 * num_cpus_frozen tracks how many CPUs are involved in suspend
7082 * resume sequence. As long as this is not the last online
7083 * operation in the resume sequence, just build a single sched
7084 * domain, ignoring cpusets.
7087 if (likely(num_cpus_frozen)) {
7088 partition_sched_domains(1, NULL, NULL);
7093 * This is the last CPU online operation. So fall through and
7094 * restore the original sched domains by considering the
7095 * cpuset configurations.
7099 cpuset_update_active_cpus(true);
7107 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7110 unsigned long flags;
7111 long cpu = (long)hcpu;
7117 case CPU_DOWN_PREPARE:
7118 rcu_read_lock_sched();
7119 dl_b = dl_bw_of(cpu);
7121 raw_spin_lock_irqsave(&dl_b->lock, flags);
7122 cpus = dl_bw_cpus(cpu);
7123 overflow = __dl_overflow(dl_b, cpus, 0, 0);
7124 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7126 rcu_read_unlock_sched();
7129 return notifier_from_errno(-EBUSY);
7130 cpuset_update_active_cpus(false);
7132 case CPU_DOWN_PREPARE_FROZEN:
7134 partition_sched_domains(1, NULL, NULL);
7142 void __init sched_init_smp(void)
7144 cpumask_var_t non_isolated_cpus;
7146 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7147 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7152 * There's no userspace yet to cause hotplug operations; hence all the
7153 * cpu masks are stable and all blatant races in the below code cannot
7156 mutex_lock(&sched_domains_mutex);
7157 init_sched_domains(cpu_active_mask);
7158 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7159 if (cpumask_empty(non_isolated_cpus))
7160 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7161 mutex_unlock(&sched_domains_mutex);
7163 hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
7164 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7165 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7169 /* Move init over to a non-isolated CPU */
7170 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7172 sched_init_granularity();
7173 free_cpumask_var(non_isolated_cpus);
7175 init_sched_rt_class();
7176 init_sched_dl_class();
7179 void __init sched_init_smp(void)
7181 sched_init_granularity();
7183 #endif /* CONFIG_SMP */
7185 int in_sched_functions(unsigned long addr)
7187 return in_lock_functions(addr) ||
7188 (addr >= (unsigned long)__sched_text_start
7189 && addr < (unsigned long)__sched_text_end);
7192 #ifdef CONFIG_CGROUP_SCHED
7194 * Default task group.
7195 * Every task in system belongs to this group at bootup.
7197 struct task_group root_task_group;
7198 LIST_HEAD(task_groups);
7200 /* Cacheline aligned slab cache for task_group */
7201 static struct kmem_cache *task_group_cache __read_mostly;
7204 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7206 void __init sched_init(void)
7209 unsigned long alloc_size = 0, ptr;
7211 #ifdef CONFIG_FAIR_GROUP_SCHED
7212 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7214 #ifdef CONFIG_RT_GROUP_SCHED
7215 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7218 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7220 #ifdef CONFIG_FAIR_GROUP_SCHED
7221 root_task_group.se = (struct sched_entity **)ptr;
7222 ptr += nr_cpu_ids * sizeof(void **);
7224 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7225 ptr += nr_cpu_ids * sizeof(void **);
7227 #endif /* CONFIG_FAIR_GROUP_SCHED */
7228 #ifdef CONFIG_RT_GROUP_SCHED
7229 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7230 ptr += nr_cpu_ids * sizeof(void **);
7232 root_task_group.rt_rq = (struct rt_rq **)ptr;
7233 ptr += nr_cpu_ids * sizeof(void **);
7235 #endif /* CONFIG_RT_GROUP_SCHED */
7237 #ifdef CONFIG_CPUMASK_OFFSTACK
7238 for_each_possible_cpu(i) {
7239 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7240 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7242 #endif /* CONFIG_CPUMASK_OFFSTACK */
7244 init_rt_bandwidth(&def_rt_bandwidth,
7245 global_rt_period(), global_rt_runtime());
7246 init_dl_bandwidth(&def_dl_bandwidth,
7247 global_rt_period(), global_rt_runtime());
7250 init_defrootdomain();
7253 #ifdef CONFIG_RT_GROUP_SCHED
7254 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7255 global_rt_period(), global_rt_runtime());
7256 #endif /* CONFIG_RT_GROUP_SCHED */
7258 #ifdef CONFIG_CGROUP_SCHED
7259 task_group_cache = KMEM_CACHE(task_group, 0);
7261 list_add(&root_task_group.list, &task_groups);
7262 INIT_LIST_HEAD(&root_task_group.children);
7263 INIT_LIST_HEAD(&root_task_group.siblings);
7264 autogroup_init(&init_task);
7265 #endif /* CONFIG_CGROUP_SCHED */
7267 for_each_possible_cpu(i) {
7271 raw_spin_lock_init(&rq->lock);
7273 rq->calc_load_active = 0;
7274 rq->calc_load_update = jiffies + LOAD_FREQ;
7275 init_cfs_rq(&rq->cfs);
7276 init_rt_rq(&rq->rt);
7277 init_dl_rq(&rq->dl);
7278 #ifdef CONFIG_FAIR_GROUP_SCHED
7279 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7280 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7282 * How much cpu bandwidth does root_task_group get?
7284 * In case of task-groups formed thr' the cgroup filesystem, it
7285 * gets 100% of the cpu resources in the system. This overall
7286 * system cpu resource is divided among the tasks of
7287 * root_task_group and its child task-groups in a fair manner,
7288 * based on each entity's (task or task-group's) weight
7289 * (se->load.weight).
7291 * In other words, if root_task_group has 10 tasks of weight
7292 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7293 * then A0's share of the cpu resource is:
7295 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7297 * We achieve this by letting root_task_group's tasks sit
7298 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7300 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7301 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7302 #endif /* CONFIG_FAIR_GROUP_SCHED */
7304 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7305 #ifdef CONFIG_RT_GROUP_SCHED
7306 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7309 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7310 rq->cpu_load[j] = 0;
7312 rq->last_load_update_tick = jiffies;
7317 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7318 rq->balance_callback = NULL;
7319 rq->active_balance = 0;
7320 rq->next_balance = jiffies;
7325 rq->avg_idle = 2*sysctl_sched_migration_cost;
7326 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7328 INIT_LIST_HEAD(&rq->cfs_tasks);
7330 rq_attach_root(rq, &def_root_domain);
7331 #ifdef CONFIG_NO_HZ_COMMON
7334 #ifdef CONFIG_NO_HZ_FULL
7335 rq->last_sched_tick = 0;
7339 atomic_set(&rq->nr_iowait, 0);
7342 set_load_weight(&init_task);
7344 #ifdef CONFIG_PREEMPT_NOTIFIERS
7345 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7349 * The boot idle thread does lazy MMU switching as well:
7351 atomic_inc(&init_mm.mm_count);
7352 enter_lazy_tlb(&init_mm, current);
7355 * During early bootup we pretend to be a normal task:
7357 current->sched_class = &fair_sched_class;
7360 * Make us the idle thread. Technically, schedule() should not be
7361 * called from this thread, however somewhere below it might be,
7362 * but because we are the idle thread, we just pick up running again
7363 * when this runqueue becomes "idle".
7365 init_idle(current, smp_processor_id());
7367 calc_load_update = jiffies + LOAD_FREQ;
7370 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7371 /* May be allocated at isolcpus cmdline parse time */
7372 if (cpu_isolated_map == NULL)
7373 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7374 idle_thread_set_boot_cpu();
7375 set_cpu_rq_start_time();
7377 init_sched_fair_class();
7379 scheduler_running = 1;
7382 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7383 static inline int preempt_count_equals(int preempt_offset)
7385 int nested = preempt_count() + rcu_preempt_depth();
7387 return (nested == preempt_offset);
7390 void __might_sleep(const char *file, int line, int preempt_offset)
7393 * Blocking primitives will set (and therefore destroy) current->state,
7394 * since we will exit with TASK_RUNNING make sure we enter with it,
7395 * otherwise we will destroy state.
7397 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7398 "do not call blocking ops when !TASK_RUNNING; "
7399 "state=%lx set at [<%p>] %pS\n",
7401 (void *)current->task_state_change,
7402 (void *)current->task_state_change);
7404 ___might_sleep(file, line, preempt_offset);
7406 EXPORT_SYMBOL(__might_sleep);
7408 void ___might_sleep(const char *file, int line, int preempt_offset)
7410 static unsigned long prev_jiffy; /* ratelimiting */
7412 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7413 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7414 !is_idle_task(current)) ||
7415 system_state != SYSTEM_RUNNING || oops_in_progress)
7417 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7419 prev_jiffy = jiffies;
7422 "BUG: sleeping function called from invalid context at %s:%d\n",
7425 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7426 in_atomic(), irqs_disabled(),
7427 current->pid, current->comm);
7429 if (task_stack_end_corrupted(current))
7430 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
7432 debug_show_held_locks(current);
7433 if (irqs_disabled())
7434 print_irqtrace_events(current);
7435 #ifdef CONFIG_DEBUG_PREEMPT
7436 if (!preempt_count_equals(preempt_offset)) {
7437 pr_err("Preemption disabled at:");
7438 print_ip_sym(current->preempt_disable_ip);
7444 EXPORT_SYMBOL(___might_sleep);
7447 #ifdef CONFIG_MAGIC_SYSRQ
7448 void normalize_rt_tasks(void)
7450 struct task_struct *g, *p;
7451 struct sched_attr attr = {
7452 .sched_policy = SCHED_NORMAL,
7455 read_lock(&tasklist_lock);
7456 for_each_process_thread(g, p) {
7458 * Only normalize user tasks:
7460 if (p->flags & PF_KTHREAD)
7463 p->se.exec_start = 0;
7464 #ifdef CONFIG_SCHEDSTATS
7465 p->se.statistics.wait_start = 0;
7466 p->se.statistics.sleep_start = 0;
7467 p->se.statistics.block_start = 0;
7470 if (!dl_task(p) && !rt_task(p)) {
7472 * Renice negative nice level userspace
7475 if (task_nice(p) < 0)
7476 set_user_nice(p, 0);
7480 __sched_setscheduler(p, &attr, false, false);
7482 read_unlock(&tasklist_lock);
7485 #endif /* CONFIG_MAGIC_SYSRQ */
7487 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7489 * These functions are only useful for the IA64 MCA handling, or kdb.
7491 * They can only be called when the whole system has been
7492 * stopped - every CPU needs to be quiescent, and no scheduling
7493 * activity can take place. Using them for anything else would
7494 * be a serious bug, and as a result, they aren't even visible
7495 * under any other configuration.
7499 * curr_task - return the current task for a given cpu.
7500 * @cpu: the processor in question.
7502 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7504 * Return: The current task for @cpu.
7506 struct task_struct *curr_task(int cpu)
7508 return cpu_curr(cpu);
7511 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7515 * set_curr_task - set the current task for a given cpu.
7516 * @cpu: the processor in question.
7517 * @p: the task pointer to set.
7519 * Description: This function must only be used when non-maskable interrupts
7520 * are serviced on a separate stack. It allows the architecture to switch the
7521 * notion of the current task on a cpu in a non-blocking manner. This function
7522 * must be called with all CPU's synchronized, and interrupts disabled, the
7523 * and caller must save the original value of the current task (see
7524 * curr_task() above) and restore that value before reenabling interrupts and
7525 * re-starting the system.
7527 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7529 void set_curr_task(int cpu, struct task_struct *p)
7536 #ifdef CONFIG_CGROUP_SCHED
7537 /* task_group_lock serializes the addition/removal of task groups */
7538 static DEFINE_SPINLOCK(task_group_lock);
7540 static void free_sched_group(struct task_group *tg)
7542 free_fair_sched_group(tg);
7543 free_rt_sched_group(tg);
7545 kmem_cache_free(task_group_cache, tg);
7548 /* allocate runqueue etc for a new task group */
7549 struct task_group *sched_create_group(struct task_group *parent)
7551 struct task_group *tg;
7553 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
7555 return ERR_PTR(-ENOMEM);
7557 if (!alloc_fair_sched_group(tg, parent))
7560 if (!alloc_rt_sched_group(tg, parent))
7566 free_sched_group(tg);
7567 return ERR_PTR(-ENOMEM);
7570 void sched_online_group(struct task_group *tg, struct task_group *parent)
7572 unsigned long flags;
7574 spin_lock_irqsave(&task_group_lock, flags);
7575 list_add_rcu(&tg->list, &task_groups);
7577 WARN_ON(!parent); /* root should already exist */
7579 tg->parent = parent;
7580 INIT_LIST_HEAD(&tg->children);
7581 list_add_rcu(&tg->siblings, &parent->children);
7582 spin_unlock_irqrestore(&task_group_lock, flags);
7585 /* rcu callback to free various structures associated with a task group */
7586 static void free_sched_group_rcu(struct rcu_head *rhp)
7588 /* now it should be safe to free those cfs_rqs */
7589 free_sched_group(container_of(rhp, struct task_group, rcu));
7592 /* Destroy runqueue etc associated with a task group */
7593 void sched_destroy_group(struct task_group *tg)
7595 /* wait for possible concurrent references to cfs_rqs complete */
7596 call_rcu(&tg->rcu, free_sched_group_rcu);
7599 void sched_offline_group(struct task_group *tg)
7601 unsigned long flags;
7603 /* end participation in shares distribution */
7604 unregister_fair_sched_group(tg);
7606 spin_lock_irqsave(&task_group_lock, flags);
7607 list_del_rcu(&tg->list);
7608 list_del_rcu(&tg->siblings);
7609 spin_unlock_irqrestore(&task_group_lock, flags);
7612 /* change task's runqueue when it moves between groups.
7613 * The caller of this function should have put the task in its new group
7614 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7615 * reflect its new group.
7617 void sched_move_task(struct task_struct *tsk)
7619 struct task_group *tg;
7620 int queued, running;
7621 unsigned long flags;
7624 rq = task_rq_lock(tsk, &flags);
7626 running = task_current(rq, tsk);
7627 queued = task_on_rq_queued(tsk);
7630 dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
7631 if (unlikely(running))
7632 put_prev_task(rq, tsk);
7635 * All callers are synchronized by task_rq_lock(); we do not use RCU
7636 * which is pointless here. Thus, we pass "true" to task_css_check()
7637 * to prevent lockdep warnings.
7639 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
7640 struct task_group, css);
7641 tg = autogroup_task_group(tsk, tg);
7642 tsk->sched_task_group = tg;
7644 #ifdef CONFIG_FAIR_GROUP_SCHED
7645 if (tsk->sched_class->task_move_group)
7646 tsk->sched_class->task_move_group(tsk);
7649 set_task_rq(tsk, task_cpu(tsk));
7651 if (unlikely(running))
7652 tsk->sched_class->set_curr_task(rq);
7654 enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
7656 task_rq_unlock(rq, tsk, &flags);
7658 #endif /* CONFIG_CGROUP_SCHED */
7660 #ifdef CONFIG_RT_GROUP_SCHED
7662 * Ensure that the real time constraints are schedulable.
7664 static DEFINE_MUTEX(rt_constraints_mutex);
7666 /* Must be called with tasklist_lock held */
7667 static inline int tg_has_rt_tasks(struct task_group *tg)
7669 struct task_struct *g, *p;
7672 * Autogroups do not have RT tasks; see autogroup_create().
7674 if (task_group_is_autogroup(tg))
7677 for_each_process_thread(g, p) {
7678 if (rt_task(p) && task_group(p) == tg)
7685 struct rt_schedulable_data {
7686 struct task_group *tg;
7691 static int tg_rt_schedulable(struct task_group *tg, void *data)
7693 struct rt_schedulable_data *d = data;
7694 struct task_group *child;
7695 unsigned long total, sum = 0;
7696 u64 period, runtime;
7698 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7699 runtime = tg->rt_bandwidth.rt_runtime;
7702 period = d->rt_period;
7703 runtime = d->rt_runtime;
7707 * Cannot have more runtime than the period.
7709 if (runtime > period && runtime != RUNTIME_INF)
7713 * Ensure we don't starve existing RT tasks.
7715 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7718 total = to_ratio(period, runtime);
7721 * Nobody can have more than the global setting allows.
7723 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7727 * The sum of our children's runtime should not exceed our own.
7729 list_for_each_entry_rcu(child, &tg->children, siblings) {
7730 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7731 runtime = child->rt_bandwidth.rt_runtime;
7733 if (child == d->tg) {
7734 period = d->rt_period;
7735 runtime = d->rt_runtime;
7738 sum += to_ratio(period, runtime);
7747 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7751 struct rt_schedulable_data data = {
7753 .rt_period = period,
7754 .rt_runtime = runtime,
7758 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
7764 static int tg_set_rt_bandwidth(struct task_group *tg,
7765 u64 rt_period, u64 rt_runtime)
7770 * Disallowing the root group RT runtime is BAD, it would disallow the
7771 * kernel creating (and or operating) RT threads.
7773 if (tg == &root_task_group && rt_runtime == 0)
7776 /* No period doesn't make any sense. */
7780 mutex_lock(&rt_constraints_mutex);
7781 read_lock(&tasklist_lock);
7782 err = __rt_schedulable(tg, rt_period, rt_runtime);
7786 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7787 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7788 tg->rt_bandwidth.rt_runtime = rt_runtime;
7790 for_each_possible_cpu(i) {
7791 struct rt_rq *rt_rq = tg->rt_rq[i];
7793 raw_spin_lock(&rt_rq->rt_runtime_lock);
7794 rt_rq->rt_runtime = rt_runtime;
7795 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7797 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7799 read_unlock(&tasklist_lock);
7800 mutex_unlock(&rt_constraints_mutex);
7805 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
7807 u64 rt_runtime, rt_period;
7809 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7810 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7811 if (rt_runtime_us < 0)
7812 rt_runtime = RUNTIME_INF;
7814 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7817 static long sched_group_rt_runtime(struct task_group *tg)
7821 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
7824 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
7825 do_div(rt_runtime_us, NSEC_PER_USEC);
7826 return rt_runtime_us;
7829 static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
7831 u64 rt_runtime, rt_period;
7833 rt_period = rt_period_us * NSEC_PER_USEC;
7834 rt_runtime = tg->rt_bandwidth.rt_runtime;
7836 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7839 static long sched_group_rt_period(struct task_group *tg)
7843 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
7844 do_div(rt_period_us, NSEC_PER_USEC);
7845 return rt_period_us;
7847 #endif /* CONFIG_RT_GROUP_SCHED */
7849 #ifdef CONFIG_RT_GROUP_SCHED
7850 static int sched_rt_global_constraints(void)
7854 mutex_lock(&rt_constraints_mutex);
7855 read_lock(&tasklist_lock);
7856 ret = __rt_schedulable(NULL, 0, 0);
7857 read_unlock(&tasklist_lock);
7858 mutex_unlock(&rt_constraints_mutex);
7863 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
7865 /* Don't accept realtime tasks when there is no way for them to run */
7866 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
7872 #else /* !CONFIG_RT_GROUP_SCHED */
7873 static int sched_rt_global_constraints(void)
7875 unsigned long flags;
7878 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
7879 for_each_possible_cpu(i) {
7880 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
7882 raw_spin_lock(&rt_rq->rt_runtime_lock);
7883 rt_rq->rt_runtime = global_rt_runtime();
7884 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7886 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
7890 #endif /* CONFIG_RT_GROUP_SCHED */
7892 static int sched_dl_global_validate(void)
7894 u64 runtime = global_rt_runtime();
7895 u64 period = global_rt_period();
7896 u64 new_bw = to_ratio(period, runtime);
7899 unsigned long flags;
7902 * Here we want to check the bandwidth not being set to some
7903 * value smaller than the currently allocated bandwidth in
7904 * any of the root_domains.
7906 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
7907 * cycling on root_domains... Discussion on different/better
7908 * solutions is welcome!
7910 for_each_possible_cpu(cpu) {
7911 rcu_read_lock_sched();
7912 dl_b = dl_bw_of(cpu);
7914 raw_spin_lock_irqsave(&dl_b->lock, flags);
7915 if (new_bw < dl_b->total_bw)
7917 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7919 rcu_read_unlock_sched();
7928 static void sched_dl_do_global(void)
7933 unsigned long flags;
7935 def_dl_bandwidth.dl_period = global_rt_period();
7936 def_dl_bandwidth.dl_runtime = global_rt_runtime();
7938 if (global_rt_runtime() != RUNTIME_INF)
7939 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
7942 * FIXME: As above...
7944 for_each_possible_cpu(cpu) {
7945 rcu_read_lock_sched();
7946 dl_b = dl_bw_of(cpu);
7948 raw_spin_lock_irqsave(&dl_b->lock, flags);
7950 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7952 rcu_read_unlock_sched();
7956 static int sched_rt_global_validate(void)
7958 if (sysctl_sched_rt_period <= 0)
7961 if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
7962 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
7968 static void sched_rt_do_global(void)
7970 def_rt_bandwidth.rt_runtime = global_rt_runtime();
7971 def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
7974 int sched_rt_handler(struct ctl_table *table, int write,
7975 void __user *buffer, size_t *lenp,
7978 int old_period, old_runtime;
7979 static DEFINE_MUTEX(mutex);
7983 old_period = sysctl_sched_rt_period;
7984 old_runtime = sysctl_sched_rt_runtime;
7986 ret = proc_dointvec(table, write, buffer, lenp, ppos);
7988 if (!ret && write) {
7989 ret = sched_rt_global_validate();
7993 ret = sched_dl_global_validate();
7997 ret = sched_rt_global_constraints();
8001 sched_rt_do_global();
8002 sched_dl_do_global();
8006 sysctl_sched_rt_period = old_period;
8007 sysctl_sched_rt_runtime = old_runtime;
8009 mutex_unlock(&mutex);
8014 int sched_rr_handler(struct ctl_table *table, int write,
8015 void __user *buffer, size_t *lenp,
8019 static DEFINE_MUTEX(mutex);
8022 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8023 /* make sure that internally we keep jiffies */
8024 /* also, writing zero resets timeslice to default */
8025 if (!ret && write) {
8026 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
8027 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
8029 mutex_unlock(&mutex);
8033 #ifdef CONFIG_CGROUP_SCHED
8035 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8037 return css ? container_of(css, struct task_group, css) : NULL;
8040 static struct cgroup_subsys_state *
8041 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8043 struct task_group *parent = css_tg(parent_css);
8044 struct task_group *tg;
8047 /* This is early initialization for the top cgroup */
8048 return &root_task_group.css;
8051 tg = sched_create_group(parent);
8053 return ERR_PTR(-ENOMEM);
8058 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
8060 struct task_group *tg = css_tg(css);
8061 struct task_group *parent = css_tg(css->parent);
8064 sched_online_group(tg, parent);
8068 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8070 struct task_group *tg = css_tg(css);
8072 sched_destroy_group(tg);
8075 static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css)
8077 struct task_group *tg = css_tg(css);
8079 sched_offline_group(tg);
8082 static void cpu_cgroup_fork(struct task_struct *task)
8084 sched_move_task(task);
8087 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
8089 struct task_struct *task;
8090 struct cgroup_subsys_state *css;
8092 cgroup_taskset_for_each(task, css, tset) {
8093 #ifdef CONFIG_RT_GROUP_SCHED
8094 if (!sched_rt_can_attach(css_tg(css), task))
8097 /* We don't support RT-tasks being in separate groups */
8098 if (task->sched_class != &fair_sched_class)
8105 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
8107 struct task_struct *task;
8108 struct cgroup_subsys_state *css;
8110 cgroup_taskset_for_each(task, css, tset)
8111 sched_move_task(task);
8114 #ifdef CONFIG_FAIR_GROUP_SCHED
8115 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8116 struct cftype *cftype, u64 shareval)
8118 return sched_group_set_shares(css_tg(css), scale_load(shareval));
8121 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8124 struct task_group *tg = css_tg(css);
8126 return (u64) scale_load_down(tg->shares);
8129 #ifdef CONFIG_CFS_BANDWIDTH
8130 static DEFINE_MUTEX(cfs_constraints_mutex);
8132 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8133 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8135 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8137 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8139 int i, ret = 0, runtime_enabled, runtime_was_enabled;
8140 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8142 if (tg == &root_task_group)
8146 * Ensure we have at some amount of bandwidth every period. This is
8147 * to prevent reaching a state of large arrears when throttled via
8148 * entity_tick() resulting in prolonged exit starvation.
8150 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8154 * Likewise, bound things on the otherside by preventing insane quota
8155 * periods. This also allows us to normalize in computing quota
8158 if (period > max_cfs_quota_period)
8162 * Prevent race between setting of cfs_rq->runtime_enabled and
8163 * unthrottle_offline_cfs_rqs().
8166 mutex_lock(&cfs_constraints_mutex);
8167 ret = __cfs_schedulable(tg, period, quota);
8171 runtime_enabled = quota != RUNTIME_INF;
8172 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8174 * If we need to toggle cfs_bandwidth_used, off->on must occur
8175 * before making related changes, and on->off must occur afterwards
8177 if (runtime_enabled && !runtime_was_enabled)
8178 cfs_bandwidth_usage_inc();
8179 raw_spin_lock_irq(&cfs_b->lock);
8180 cfs_b->period = ns_to_ktime(period);
8181 cfs_b->quota = quota;
8183 __refill_cfs_bandwidth_runtime(cfs_b);
8184 /* restart the period timer (if active) to handle new period expiry */
8185 if (runtime_enabled)
8186 start_cfs_bandwidth(cfs_b);
8187 raw_spin_unlock_irq(&cfs_b->lock);
8189 for_each_online_cpu(i) {
8190 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8191 struct rq *rq = cfs_rq->rq;
8193 raw_spin_lock_irq(&rq->lock);
8194 cfs_rq->runtime_enabled = runtime_enabled;
8195 cfs_rq->runtime_remaining = 0;
8197 if (cfs_rq->throttled)
8198 unthrottle_cfs_rq(cfs_rq);
8199 raw_spin_unlock_irq(&rq->lock);
8201 if (runtime_was_enabled && !runtime_enabled)
8202 cfs_bandwidth_usage_dec();
8204 mutex_unlock(&cfs_constraints_mutex);
8210 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8214 period = ktime_to_ns(tg->cfs_bandwidth.period);
8215 if (cfs_quota_us < 0)
8216 quota = RUNTIME_INF;
8218 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8220 return tg_set_cfs_bandwidth(tg, period, quota);
8223 long tg_get_cfs_quota(struct task_group *tg)
8227 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8230 quota_us = tg->cfs_bandwidth.quota;
8231 do_div(quota_us, NSEC_PER_USEC);
8236 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8240 period = (u64)cfs_period_us * NSEC_PER_USEC;
8241 quota = tg->cfs_bandwidth.quota;
8243 return tg_set_cfs_bandwidth(tg, period, quota);
8246 long tg_get_cfs_period(struct task_group *tg)
8250 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8251 do_div(cfs_period_us, NSEC_PER_USEC);
8253 return cfs_period_us;
8256 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8259 return tg_get_cfs_quota(css_tg(css));
8262 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8263 struct cftype *cftype, s64 cfs_quota_us)
8265 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8268 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8271 return tg_get_cfs_period(css_tg(css));
8274 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8275 struct cftype *cftype, u64 cfs_period_us)
8277 return tg_set_cfs_period(css_tg(css), cfs_period_us);
8280 struct cfs_schedulable_data {
8281 struct task_group *tg;
8286 * normalize group quota/period to be quota/max_period
8287 * note: units are usecs
8289 static u64 normalize_cfs_quota(struct task_group *tg,
8290 struct cfs_schedulable_data *d)
8298 period = tg_get_cfs_period(tg);
8299 quota = tg_get_cfs_quota(tg);
8302 /* note: these should typically be equivalent */
8303 if (quota == RUNTIME_INF || quota == -1)
8306 return to_ratio(period, quota);
8309 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8311 struct cfs_schedulable_data *d = data;
8312 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8313 s64 quota = 0, parent_quota = -1;
8316 quota = RUNTIME_INF;
8318 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8320 quota = normalize_cfs_quota(tg, d);
8321 parent_quota = parent_b->hierarchical_quota;
8324 * ensure max(child_quota) <= parent_quota, inherit when no
8327 if (quota == RUNTIME_INF)
8328 quota = parent_quota;
8329 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8332 cfs_b->hierarchical_quota = quota;
8337 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8340 struct cfs_schedulable_data data = {
8346 if (quota != RUNTIME_INF) {
8347 do_div(data.period, NSEC_PER_USEC);
8348 do_div(data.quota, NSEC_PER_USEC);
8352 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8358 static int cpu_stats_show(struct seq_file *sf, void *v)
8360 struct task_group *tg = css_tg(seq_css(sf));
8361 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8363 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8364 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8365 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8369 #endif /* CONFIG_CFS_BANDWIDTH */
8370 #endif /* CONFIG_FAIR_GROUP_SCHED */
8372 #ifdef CONFIG_RT_GROUP_SCHED
8373 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8374 struct cftype *cft, s64 val)
8376 return sched_group_set_rt_runtime(css_tg(css), val);
8379 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8382 return sched_group_rt_runtime(css_tg(css));
8385 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8386 struct cftype *cftype, u64 rt_period_us)
8388 return sched_group_set_rt_period(css_tg(css), rt_period_us);
8391 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8394 return sched_group_rt_period(css_tg(css));
8396 #endif /* CONFIG_RT_GROUP_SCHED */
8398 static struct cftype cpu_files[] = {
8399 #ifdef CONFIG_FAIR_GROUP_SCHED
8402 .read_u64 = cpu_shares_read_u64,
8403 .write_u64 = cpu_shares_write_u64,
8406 #ifdef CONFIG_CFS_BANDWIDTH
8408 .name = "cfs_quota_us",
8409 .read_s64 = cpu_cfs_quota_read_s64,
8410 .write_s64 = cpu_cfs_quota_write_s64,
8413 .name = "cfs_period_us",
8414 .read_u64 = cpu_cfs_period_read_u64,
8415 .write_u64 = cpu_cfs_period_write_u64,
8419 .seq_show = cpu_stats_show,
8422 #ifdef CONFIG_RT_GROUP_SCHED
8424 .name = "rt_runtime_us",
8425 .read_s64 = cpu_rt_runtime_read,
8426 .write_s64 = cpu_rt_runtime_write,
8429 .name = "rt_period_us",
8430 .read_u64 = cpu_rt_period_read_uint,
8431 .write_u64 = cpu_rt_period_write_uint,
8437 struct cgroup_subsys cpu_cgrp_subsys = {
8438 .css_alloc = cpu_cgroup_css_alloc,
8439 .css_free = cpu_cgroup_css_free,
8440 .css_online = cpu_cgroup_css_online,
8441 .css_offline = cpu_cgroup_css_offline,
8442 .fork = cpu_cgroup_fork,
8443 .can_attach = cpu_cgroup_can_attach,
8444 .attach = cpu_cgroup_attach,
8445 .legacy_cftypes = cpu_files,
8449 #endif /* CONFIG_CGROUP_SCHED */
8451 void dump_cpu_task(int cpu)
8453 pr_info("Task dump for CPU %d:\n", cpu);
8454 sched_show_task(cpu_curr(cpu));
8458 * Nice levels are multiplicative, with a gentle 10% change for every
8459 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
8460 * nice 1, it will get ~10% less CPU time than another CPU-bound task
8461 * that remained on nice 0.
8463 * The "10% effect" is relative and cumulative: from _any_ nice level,
8464 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
8465 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
8466 * If a task goes up by ~10% and another task goes down by ~10% then
8467 * the relative distance between them is ~25%.)
8469 const int sched_prio_to_weight[40] = {
8470 /* -20 */ 88761, 71755, 56483, 46273, 36291,
8471 /* -15 */ 29154, 23254, 18705, 14949, 11916,
8472 /* -10 */ 9548, 7620, 6100, 4904, 3906,
8473 /* -5 */ 3121, 2501, 1991, 1586, 1277,
8474 /* 0 */ 1024, 820, 655, 526, 423,
8475 /* 5 */ 335, 272, 215, 172, 137,
8476 /* 10 */ 110, 87, 70, 56, 45,
8477 /* 15 */ 36, 29, 23, 18, 15,
8481 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
8483 * In cases where the weight does not change often, we can use the
8484 * precalculated inverse to speed up arithmetics by turning divisions
8485 * into multiplications:
8487 const u32 sched_prio_to_wmult[40] = {
8488 /* -20 */ 48388, 59856, 76040, 92818, 118348,
8489 /* -15 */ 147320, 184698, 229616, 287308, 360437,
8490 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
8491 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
8492 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
8493 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
8494 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
8495 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,