4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
29 #include <linux/kasan.h>
31 #include <linux/module.h>
32 #include <linux/nmi.h>
33 #include <linux/init.h>
34 #include <linux/uaccess.h>
35 #include <linux/highmem.h>
36 #include <linux/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/perf_event.h>
43 #include <linux/security.h>
44 #include <linux/notifier.h>
45 #include <linux/profile.h>
46 #include <linux/freezer.h>
47 #include <linux/vmalloc.h>
48 #include <linux/blkdev.h>
49 #include <linux/delay.h>
50 #include <linux/pid_namespace.h>
51 #include <linux/smp.h>
52 #include <linux/threads.h>
53 #include <linux/timer.h>
54 #include <linux/rcupdate.h>
55 #include <linux/cpu.h>
56 #include <linux/cpuset.h>
57 #include <linux/percpu.h>
58 #include <linux/proc_fs.h>
59 #include <linux/seq_file.h>
60 #include <linux/sysctl.h>
61 #include <linux/syscalls.h>
62 #include <linux/times.h>
63 #include <linux/tsacct_kern.h>
64 #include <linux/kprobes.h>
65 #include <linux/delayacct.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/ctype.h>
71 #include <linux/ftrace.h>
72 #include <linux/slab.h>
73 #include <linux/init_task.h>
74 #include <linux/context_tracking.h>
75 #include <linux/compiler.h>
76 #include <linux/frame.h>
77 #include <linux/prefetch.h>
79 #include <asm/switch_to.h>
81 #include <asm/irq_regs.h>
82 #include <asm/mutex.h>
83 #ifdef CONFIG_PARAVIRT
84 #include <asm/paravirt.h>
88 #include "../workqueue_internal.h"
89 #include "../smpboot.h"
91 #define CREATE_TRACE_POINTS
92 #include <trace/events/sched.h>
95 DEFINE_MUTEX(sched_domains_mutex);
96 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
98 static void update_rq_clock_task(struct rq *rq, s64 delta);
100 void update_rq_clock(struct rq *rq)
104 lockdep_assert_held(&rq->lock);
106 if (rq->clock_skip_update & RQCF_ACT_SKIP)
109 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
113 update_rq_clock_task(rq, delta);
117 * Debugging: various feature bits
120 #define SCHED_FEAT(name, enabled) \
121 (1UL << __SCHED_FEAT_##name) * enabled |
123 const_debug unsigned int sysctl_sched_features =
124 #include "features.h"
130 * Number of tasks to iterate in a single balance run.
131 * Limited because this is done with IRQs disabled.
133 const_debug unsigned int sysctl_sched_nr_migrate = 32;
136 * period over which we average the RT time consumption, measured
141 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
144 * period over which we measure -rt task cpu usage in us.
147 unsigned int sysctl_sched_rt_period = 1000000;
149 __read_mostly int scheduler_running;
152 * part of the period that we allow rt tasks to run in us.
155 int sysctl_sched_rt_runtime = 950000;
157 /* cpus with isolated domains */
158 cpumask_var_t cpu_isolated_map;
161 lock_rq_of(struct task_struct *p, struct rq_flags *flags)
163 return task_rq_lock(p, flags);
167 unlock_rq_of(struct rq *rq, struct task_struct *p, struct rq_flags *flags)
169 task_rq_unlock(rq, p, flags);
173 * this_rq_lock - lock this runqueue and disable interrupts.
175 static struct rq *this_rq_lock(void)
182 raw_spin_lock(&rq->lock);
188 * __task_rq_lock - lock the rq @p resides on.
190 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
195 lockdep_assert_held(&p->pi_lock);
199 raw_spin_lock(&rq->lock);
200 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
201 rf->cookie = lockdep_pin_lock(&rq->lock);
204 raw_spin_unlock(&rq->lock);
206 while (unlikely(task_on_rq_migrating(p)))
212 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
214 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
215 __acquires(p->pi_lock)
221 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
223 raw_spin_lock(&rq->lock);
225 * move_queued_task() task_rq_lock()
228 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
229 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
230 * [S] ->cpu = new_cpu [L] task_rq()
234 * If we observe the old cpu in task_rq_lock, the acquire of
235 * the old rq->lock will fully serialize against the stores.
237 * If we observe the new cpu in task_rq_lock, the acquire will
238 * pair with the WMB to ensure we must then also see migrating.
240 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
241 rf->cookie = lockdep_pin_lock(&rq->lock);
244 raw_spin_unlock(&rq->lock);
245 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
247 while (unlikely(task_on_rq_migrating(p)))
252 #ifdef CONFIG_SCHED_HRTICK
254 * Use HR-timers to deliver accurate preemption points.
257 static void hrtick_clear(struct rq *rq)
259 if (hrtimer_active(&rq->hrtick_timer))
260 hrtimer_cancel(&rq->hrtick_timer);
264 * High-resolution timer tick.
265 * Runs from hardirq context with interrupts disabled.
267 static enum hrtimer_restart hrtick(struct hrtimer *timer)
269 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
271 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
273 raw_spin_lock(&rq->lock);
275 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
276 raw_spin_unlock(&rq->lock);
278 return HRTIMER_NORESTART;
283 static void __hrtick_restart(struct rq *rq)
285 struct hrtimer *timer = &rq->hrtick_timer;
287 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
291 * called from hardirq (IPI) context
293 static void __hrtick_start(void *arg)
297 raw_spin_lock(&rq->lock);
298 __hrtick_restart(rq);
299 rq->hrtick_csd_pending = 0;
300 raw_spin_unlock(&rq->lock);
304 * Called to set the hrtick timer state.
306 * called with rq->lock held and irqs disabled
308 void hrtick_start(struct rq *rq, u64 delay)
310 struct hrtimer *timer = &rq->hrtick_timer;
315 * Don't schedule slices shorter than 10000ns, that just
316 * doesn't make sense and can cause timer DoS.
318 delta = max_t(s64, delay, 10000LL);
319 time = ktime_add_ns(timer->base->get_time(), delta);
321 hrtimer_set_expires(timer, time);
323 if (rq == this_rq()) {
324 __hrtick_restart(rq);
325 } else if (!rq->hrtick_csd_pending) {
326 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
327 rq->hrtick_csd_pending = 1;
333 * Called to set the hrtick timer state.
335 * called with rq->lock held and irqs disabled
337 void hrtick_start(struct rq *rq, u64 delay)
340 * Don't schedule slices shorter than 10000ns, that just
341 * doesn't make sense. Rely on vruntime for fairness.
343 delay = max_t(u64, delay, 10000LL);
344 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
345 HRTIMER_MODE_REL_PINNED);
347 #endif /* CONFIG_SMP */
349 static void init_rq_hrtick(struct rq *rq)
352 rq->hrtick_csd_pending = 0;
354 rq->hrtick_csd.flags = 0;
355 rq->hrtick_csd.func = __hrtick_start;
356 rq->hrtick_csd.info = rq;
359 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
360 rq->hrtick_timer.function = hrtick;
362 #else /* CONFIG_SCHED_HRTICK */
363 static inline void hrtick_clear(struct rq *rq)
367 static inline void init_rq_hrtick(struct rq *rq)
370 #endif /* CONFIG_SCHED_HRTICK */
373 * cmpxchg based fetch_or, macro so it works for different integer types
375 #define fetch_or(ptr, mask) \
377 typeof(ptr) _ptr = (ptr); \
378 typeof(mask) _mask = (mask); \
379 typeof(*_ptr) _old, _val = *_ptr; \
382 _old = cmpxchg(_ptr, _val, _val | _mask); \
390 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
392 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
393 * this avoids any races wrt polling state changes and thereby avoids
396 static bool set_nr_and_not_polling(struct task_struct *p)
398 struct thread_info *ti = task_thread_info(p);
399 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
403 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
405 * If this returns true, then the idle task promises to call
406 * sched_ttwu_pending() and reschedule soon.
408 static bool set_nr_if_polling(struct task_struct *p)
410 struct thread_info *ti = task_thread_info(p);
411 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
414 if (!(val & _TIF_POLLING_NRFLAG))
416 if (val & _TIF_NEED_RESCHED)
418 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
427 static bool set_nr_and_not_polling(struct task_struct *p)
429 set_tsk_need_resched(p);
434 static bool set_nr_if_polling(struct task_struct *p)
441 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
443 struct wake_q_node *node = &task->wake_q;
446 * Atomically grab the task, if ->wake_q is !nil already it means
447 * its already queued (either by us or someone else) and will get the
448 * wakeup due to that.
450 * This cmpxchg() implies a full barrier, which pairs with the write
451 * barrier implied by the wakeup in wake_up_q().
453 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
456 get_task_struct(task);
459 * The head is context local, there can be no concurrency.
462 head->lastp = &node->next;
465 void wake_up_q(struct wake_q_head *head)
467 struct wake_q_node *node = head->first;
469 while (node != WAKE_Q_TAIL) {
470 struct task_struct *task;
472 task = container_of(node, struct task_struct, wake_q);
474 /* task can safely be re-inserted now */
476 task->wake_q.next = NULL;
479 * wake_up_process() implies a wmb() to pair with the queueing
480 * in wake_q_add() so as not to miss wakeups.
482 wake_up_process(task);
483 put_task_struct(task);
488 * resched_curr - mark rq's current task 'to be rescheduled now'.
490 * On UP this means the setting of the need_resched flag, on SMP it
491 * might also involve a cross-CPU call to trigger the scheduler on
494 void resched_curr(struct rq *rq)
496 struct task_struct *curr = rq->curr;
499 lockdep_assert_held(&rq->lock);
501 if (test_tsk_need_resched(curr))
506 if (cpu == smp_processor_id()) {
507 set_tsk_need_resched(curr);
508 set_preempt_need_resched();
512 if (set_nr_and_not_polling(curr))
513 smp_send_reschedule(cpu);
515 trace_sched_wake_idle_without_ipi(cpu);
518 void resched_cpu(int cpu)
520 struct rq *rq = cpu_rq(cpu);
523 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
526 raw_spin_unlock_irqrestore(&rq->lock, flags);
530 #ifdef CONFIG_NO_HZ_COMMON
532 * In the semi idle case, use the nearest busy cpu for migrating timers
533 * from an idle cpu. This is good for power-savings.
535 * We don't do similar optimization for completely idle system, as
536 * selecting an idle cpu will add more delays to the timers than intended
537 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
539 int get_nohz_timer_target(void)
541 int i, cpu = smp_processor_id();
542 struct sched_domain *sd;
544 if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
548 for_each_domain(cpu, sd) {
549 for_each_cpu(i, sched_domain_span(sd)) {
553 if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
560 if (!is_housekeeping_cpu(cpu))
561 cpu = housekeeping_any_cpu();
567 * When add_timer_on() enqueues a timer into the timer wheel of an
568 * idle CPU then this timer might expire before the next timer event
569 * which is scheduled to wake up that CPU. In case of a completely
570 * idle system the next event might even be infinite time into the
571 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
572 * leaves the inner idle loop so the newly added timer is taken into
573 * account when the CPU goes back to idle and evaluates the timer
574 * wheel for the next timer event.
576 static void wake_up_idle_cpu(int cpu)
578 struct rq *rq = cpu_rq(cpu);
580 if (cpu == smp_processor_id())
583 if (set_nr_and_not_polling(rq->idle))
584 smp_send_reschedule(cpu);
586 trace_sched_wake_idle_without_ipi(cpu);
589 static bool wake_up_full_nohz_cpu(int cpu)
592 * We just need the target to call irq_exit() and re-evaluate
593 * the next tick. The nohz full kick at least implies that.
594 * If needed we can still optimize that later with an
597 if (cpu_is_offline(cpu))
598 return true; /* Don't try to wake offline CPUs. */
599 if (tick_nohz_full_cpu(cpu)) {
600 if (cpu != smp_processor_id() ||
601 tick_nohz_tick_stopped())
602 tick_nohz_full_kick_cpu(cpu);
610 * Wake up the specified CPU. If the CPU is going offline, it is the
611 * caller's responsibility to deal with the lost wakeup, for example,
612 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
614 void wake_up_nohz_cpu(int cpu)
616 if (!wake_up_full_nohz_cpu(cpu))
617 wake_up_idle_cpu(cpu);
620 static inline bool got_nohz_idle_kick(void)
622 int cpu = smp_processor_id();
624 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
627 if (idle_cpu(cpu) && !need_resched())
631 * We can't run Idle Load Balance on this CPU for this time so we
632 * cancel it and clear NOHZ_BALANCE_KICK
634 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
638 #else /* CONFIG_NO_HZ_COMMON */
640 static inline bool got_nohz_idle_kick(void)
645 #endif /* CONFIG_NO_HZ_COMMON */
647 #ifdef CONFIG_NO_HZ_FULL
648 bool sched_can_stop_tick(struct rq *rq)
652 /* Deadline tasks, even if single, need the tick */
653 if (rq->dl.dl_nr_running)
657 * If there are more than one RR tasks, we need the tick to effect the
658 * actual RR behaviour.
660 if (rq->rt.rr_nr_running) {
661 if (rq->rt.rr_nr_running == 1)
668 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
669 * forced preemption between FIFO tasks.
671 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
676 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
677 * if there's more than one we need the tick for involuntary
680 if (rq->nr_running > 1)
685 #endif /* CONFIG_NO_HZ_FULL */
687 void sched_avg_update(struct rq *rq)
689 s64 period = sched_avg_period();
691 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
693 * Inline assembly required to prevent the compiler
694 * optimising this loop into a divmod call.
695 * See __iter_div_u64_rem() for another example of this.
697 asm("" : "+rm" (rq->age_stamp));
698 rq->age_stamp += period;
703 #endif /* CONFIG_SMP */
705 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
706 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
708 * Iterate task_group tree rooted at *from, calling @down when first entering a
709 * node and @up when leaving it for the final time.
711 * Caller must hold rcu_lock or sufficient equivalent.
713 int walk_tg_tree_from(struct task_group *from,
714 tg_visitor down, tg_visitor up, void *data)
716 struct task_group *parent, *child;
722 ret = (*down)(parent, data);
725 list_for_each_entry_rcu(child, &parent->children, siblings) {
732 ret = (*up)(parent, data);
733 if (ret || parent == from)
737 parent = parent->parent;
744 int tg_nop(struct task_group *tg, void *data)
750 static void set_load_weight(struct task_struct *p)
752 int prio = p->static_prio - MAX_RT_PRIO;
753 struct load_weight *load = &p->se.load;
756 * SCHED_IDLE tasks get minimal weight:
758 if (idle_policy(p->policy)) {
759 load->weight = scale_load(WEIGHT_IDLEPRIO);
760 load->inv_weight = WMULT_IDLEPRIO;
764 load->weight = scale_load(sched_prio_to_weight[prio]);
765 load->inv_weight = sched_prio_to_wmult[prio];
768 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
771 if (!(flags & ENQUEUE_RESTORE))
772 sched_info_queued(rq, p);
773 p->sched_class->enqueue_task(rq, p, flags);
776 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
779 if (!(flags & DEQUEUE_SAVE))
780 sched_info_dequeued(rq, p);
781 p->sched_class->dequeue_task(rq, p, flags);
784 void activate_task(struct rq *rq, struct task_struct *p, int flags)
786 if (task_contributes_to_load(p))
787 rq->nr_uninterruptible--;
789 enqueue_task(rq, p, flags);
792 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
794 if (task_contributes_to_load(p))
795 rq->nr_uninterruptible++;
797 dequeue_task(rq, p, flags);
800 static void update_rq_clock_task(struct rq *rq, s64 delta)
803 * In theory, the compile should just see 0 here, and optimize out the call
804 * to sched_rt_avg_update. But I don't trust it...
806 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
807 s64 steal = 0, irq_delta = 0;
809 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
810 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
813 * Since irq_time is only updated on {soft,}irq_exit, we might run into
814 * this case when a previous update_rq_clock() happened inside a
817 * When this happens, we stop ->clock_task and only update the
818 * prev_irq_time stamp to account for the part that fit, so that a next
819 * update will consume the rest. This ensures ->clock_task is
822 * It does however cause some slight miss-attribution of {soft,}irq
823 * time, a more accurate solution would be to update the irq_time using
824 * the current rq->clock timestamp, except that would require using
827 if (irq_delta > delta)
830 rq->prev_irq_time += irq_delta;
833 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
834 if (static_key_false((¶virt_steal_rq_enabled))) {
835 steal = paravirt_steal_clock(cpu_of(rq));
836 steal -= rq->prev_steal_time_rq;
838 if (unlikely(steal > delta))
841 rq->prev_steal_time_rq += steal;
846 rq->clock_task += delta;
848 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
849 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
850 sched_rt_avg_update(rq, irq_delta + steal);
854 void sched_set_stop_task(int cpu, struct task_struct *stop)
856 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
857 struct task_struct *old_stop = cpu_rq(cpu)->stop;
861 * Make it appear like a SCHED_FIFO task, its something
862 * userspace knows about and won't get confused about.
864 * Also, it will make PI more or less work without too
865 * much confusion -- but then, stop work should not
866 * rely on PI working anyway.
868 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
870 stop->sched_class = &stop_sched_class;
873 cpu_rq(cpu)->stop = stop;
877 * Reset it back to a normal scheduling class so that
878 * it can die in pieces.
880 old_stop->sched_class = &rt_sched_class;
885 * __normal_prio - return the priority that is based on the static prio
887 static inline int __normal_prio(struct task_struct *p)
889 return p->static_prio;
893 * Calculate the expected normal priority: i.e. priority
894 * without taking RT-inheritance into account. Might be
895 * boosted by interactivity modifiers. Changes upon fork,
896 * setprio syscalls, and whenever the interactivity
897 * estimator recalculates.
899 static inline int normal_prio(struct task_struct *p)
903 if (task_has_dl_policy(p))
904 prio = MAX_DL_PRIO-1;
905 else if (task_has_rt_policy(p))
906 prio = MAX_RT_PRIO-1 - p->rt_priority;
908 prio = __normal_prio(p);
913 * Calculate the current priority, i.e. the priority
914 * taken into account by the scheduler. This value might
915 * be boosted by RT tasks, or might be boosted by
916 * interactivity modifiers. Will be RT if the task got
917 * RT-boosted. If not then it returns p->normal_prio.
919 static int effective_prio(struct task_struct *p)
921 p->normal_prio = normal_prio(p);
923 * If we are RT tasks or we were boosted to RT priority,
924 * keep the priority unchanged. Otherwise, update priority
925 * to the normal priority:
927 if (!rt_prio(p->prio))
928 return p->normal_prio;
933 * task_curr - is this task currently executing on a CPU?
934 * @p: the task in question.
936 * Return: 1 if the task is currently executing. 0 otherwise.
938 inline int task_curr(const struct task_struct *p)
940 return cpu_curr(task_cpu(p)) == p;
944 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
945 * use the balance_callback list if you want balancing.
947 * this means any call to check_class_changed() must be followed by a call to
948 * balance_callback().
950 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
951 const struct sched_class *prev_class,
954 if (prev_class != p->sched_class) {
955 if (prev_class->switched_from)
956 prev_class->switched_from(rq, p);
958 p->sched_class->switched_to(rq, p);
959 } else if (oldprio != p->prio || dl_task(p))
960 p->sched_class->prio_changed(rq, p, oldprio);
963 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
965 const struct sched_class *class;
967 if (p->sched_class == rq->curr->sched_class) {
968 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
970 for_each_class(class) {
971 if (class == rq->curr->sched_class)
973 if (class == p->sched_class) {
981 * A queue event has occurred, and we're going to schedule. In
982 * this case, we can save a useless back to back clock update.
984 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
985 rq_clock_skip_update(rq, true);
990 * This is how migration works:
992 * 1) we invoke migration_cpu_stop() on the target CPU using
994 * 2) stopper starts to run (implicitly forcing the migrated thread
996 * 3) it checks whether the migrated task is still in the wrong runqueue.
997 * 4) if it's in the wrong runqueue then the migration thread removes
998 * it and puts it into the right queue.
999 * 5) stopper completes and stop_one_cpu() returns and the migration
1004 * move_queued_task - move a queued task to new rq.
1006 * Returns (locked) new rq. Old rq's lock is released.
1008 static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
1010 lockdep_assert_held(&rq->lock);
1012 p->on_rq = TASK_ON_RQ_MIGRATING;
1013 dequeue_task(rq, p, 0);
1014 double_lock_balance(rq, cpu_rq(new_cpu));
1015 set_task_cpu(p, new_cpu);
1016 double_unlock_balance(rq, cpu_rq(new_cpu));
1017 raw_spin_unlock(&rq->lock);
1019 rq = cpu_rq(new_cpu);
1021 raw_spin_lock(&rq->lock);
1022 BUG_ON(task_cpu(p) != new_cpu);
1023 enqueue_task(rq, p, 0);
1024 p->on_rq = TASK_ON_RQ_QUEUED;
1025 check_preempt_curr(rq, p, 0);
1030 struct migration_arg {
1031 struct task_struct *task;
1036 * Move (not current) task off this cpu, onto dest cpu. We're doing
1037 * this because either it can't run here any more (set_cpus_allowed()
1038 * away from this CPU, or CPU going down), or because we're
1039 * attempting to rebalance this task on exec (sched_exec).
1041 * So we race with normal scheduler movements, but that's OK, as long
1042 * as the task is no longer on this CPU.
1044 static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
1046 if (unlikely(!cpu_active(dest_cpu)))
1049 /* Affinity changed (again). */
1050 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1053 rq = move_queued_task(rq, p, dest_cpu);
1059 * migration_cpu_stop - this will be executed by a highprio stopper thread
1060 * and performs thread migration by bumping thread off CPU then
1061 * 'pushing' onto another runqueue.
1063 static int migration_cpu_stop(void *data)
1065 struct migration_arg *arg = data;
1066 struct task_struct *p = arg->task;
1067 struct rq *rq = this_rq();
1070 * The original target cpu might have gone down and we might
1071 * be on another cpu but it doesn't matter.
1073 local_irq_disable();
1075 * We need to explicitly wake pending tasks before running
1076 * __migrate_task() such that we will not miss enforcing cpus_allowed
1077 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1079 sched_ttwu_pending();
1081 raw_spin_lock(&p->pi_lock);
1082 raw_spin_lock(&rq->lock);
1084 * If task_rq(p) != rq, it cannot be migrated here, because we're
1085 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1086 * we're holding p->pi_lock.
1088 if (task_rq(p) == rq) {
1089 if (task_on_rq_queued(p))
1090 rq = __migrate_task(rq, p, arg->dest_cpu);
1092 p->wake_cpu = arg->dest_cpu;
1094 raw_spin_unlock(&rq->lock);
1095 raw_spin_unlock(&p->pi_lock);
1102 * sched_class::set_cpus_allowed must do the below, but is not required to
1103 * actually call this function.
1105 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1107 cpumask_copy(&p->cpus_allowed, new_mask);
1108 p->nr_cpus_allowed = cpumask_weight(new_mask);
1111 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1113 struct rq *rq = task_rq(p);
1114 bool queued, running;
1116 lockdep_assert_held(&p->pi_lock);
1118 queued = task_on_rq_queued(p);
1119 running = task_current(rq, p);
1123 * Because __kthread_bind() calls this on blocked tasks without
1126 lockdep_assert_held(&rq->lock);
1127 dequeue_task(rq, p, DEQUEUE_SAVE);
1130 put_prev_task(rq, p);
1132 p->sched_class->set_cpus_allowed(p, new_mask);
1135 enqueue_task(rq, p, ENQUEUE_RESTORE);
1137 set_curr_task(rq, p);
1141 * Change a given task's CPU affinity. Migrate the thread to a
1142 * proper CPU and schedule it away if the CPU it's executing on
1143 * is removed from the allowed bitmask.
1145 * NOTE: the caller must have a valid reference to the task, the
1146 * task must not exit() & deallocate itself prematurely. The
1147 * call is not atomic; no spinlocks may be held.
1149 static int __set_cpus_allowed_ptr(struct task_struct *p,
1150 const struct cpumask *new_mask, bool check)
1152 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1153 unsigned int dest_cpu;
1158 rq = task_rq_lock(p, &rf);
1160 if (p->flags & PF_KTHREAD) {
1162 * Kernel threads are allowed on online && !active CPUs
1164 cpu_valid_mask = cpu_online_mask;
1168 * Must re-check here, to close a race against __kthread_bind(),
1169 * sched_setaffinity() is not guaranteed to observe the flag.
1171 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1176 if (cpumask_equal(&p->cpus_allowed, new_mask))
1179 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1184 do_set_cpus_allowed(p, new_mask);
1186 if (p->flags & PF_KTHREAD) {
1188 * For kernel threads that do indeed end up on online &&
1189 * !active we want to ensure they are strict per-cpu threads.
1191 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1192 !cpumask_intersects(new_mask, cpu_active_mask) &&
1193 p->nr_cpus_allowed != 1);
1196 /* Can the task run on the task's current CPU? If so, we're done */
1197 if (cpumask_test_cpu(task_cpu(p), new_mask))
1200 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1201 if (task_running(rq, p) || p->state == TASK_WAKING) {
1202 struct migration_arg arg = { p, dest_cpu };
1203 /* Need help from migration thread: drop lock and wait. */
1204 task_rq_unlock(rq, p, &rf);
1205 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1206 tlb_migrate_finish(p->mm);
1208 } else if (task_on_rq_queued(p)) {
1210 * OK, since we're going to drop the lock immediately
1211 * afterwards anyway.
1213 lockdep_unpin_lock(&rq->lock, rf.cookie);
1214 rq = move_queued_task(rq, p, dest_cpu);
1215 lockdep_repin_lock(&rq->lock, rf.cookie);
1218 task_rq_unlock(rq, p, &rf);
1223 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1225 return __set_cpus_allowed_ptr(p, new_mask, false);
1227 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1229 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1231 #ifdef CONFIG_SCHED_DEBUG
1233 * We should never call set_task_cpu() on a blocked task,
1234 * ttwu() will sort out the placement.
1236 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1240 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1241 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1242 * time relying on p->on_rq.
1244 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1245 p->sched_class == &fair_sched_class &&
1246 (p->on_rq && !task_on_rq_migrating(p)));
1248 #ifdef CONFIG_LOCKDEP
1250 * The caller should hold either p->pi_lock or rq->lock, when changing
1251 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1253 * sched_move_task() holds both and thus holding either pins the cgroup,
1256 * Furthermore, all task_rq users should acquire both locks, see
1259 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1260 lockdep_is_held(&task_rq(p)->lock)));
1264 trace_sched_migrate_task(p, new_cpu);
1266 if (task_cpu(p) != new_cpu) {
1267 if (p->sched_class->migrate_task_rq)
1268 p->sched_class->migrate_task_rq(p);
1269 p->se.nr_migrations++;
1270 perf_event_task_migrate(p);
1272 walt_fixup_busy_time(p, new_cpu);
1275 __set_task_cpu(p, new_cpu);
1278 static void __migrate_swap_task(struct task_struct *p, int cpu)
1280 if (task_on_rq_queued(p)) {
1281 struct rq *src_rq, *dst_rq;
1283 src_rq = task_rq(p);
1284 dst_rq = cpu_rq(cpu);
1286 p->on_rq = TASK_ON_RQ_MIGRATING;
1287 deactivate_task(src_rq, p, 0);
1288 set_task_cpu(p, cpu);
1289 activate_task(dst_rq, p, 0);
1290 p->on_rq = TASK_ON_RQ_QUEUED;
1291 check_preempt_curr(dst_rq, p, 0);
1294 * Task isn't running anymore; make it appear like we migrated
1295 * it before it went to sleep. This means on wakeup we make the
1296 * previous cpu our target instead of where it really is.
1302 struct migration_swap_arg {
1303 struct task_struct *src_task, *dst_task;
1304 int src_cpu, dst_cpu;
1307 static int migrate_swap_stop(void *data)
1309 struct migration_swap_arg *arg = data;
1310 struct rq *src_rq, *dst_rq;
1313 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1316 src_rq = cpu_rq(arg->src_cpu);
1317 dst_rq = cpu_rq(arg->dst_cpu);
1319 double_raw_lock(&arg->src_task->pi_lock,
1320 &arg->dst_task->pi_lock);
1321 double_rq_lock(src_rq, dst_rq);
1323 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1326 if (task_cpu(arg->src_task) != arg->src_cpu)
1329 if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
1332 if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
1335 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1336 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1341 double_rq_unlock(src_rq, dst_rq);
1342 raw_spin_unlock(&arg->dst_task->pi_lock);
1343 raw_spin_unlock(&arg->src_task->pi_lock);
1349 * Cross migrate two tasks
1351 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1353 struct migration_swap_arg arg;
1356 arg = (struct migration_swap_arg){
1358 .src_cpu = task_cpu(cur),
1360 .dst_cpu = task_cpu(p),
1363 if (arg.src_cpu == arg.dst_cpu)
1367 * These three tests are all lockless; this is OK since all of them
1368 * will be re-checked with proper locks held further down the line.
1370 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1373 if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
1376 if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
1379 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1380 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1387 * wait_task_inactive - wait for a thread to unschedule.
1389 * If @match_state is nonzero, it's the @p->state value just checked and
1390 * not expected to change. If it changes, i.e. @p might have woken up,
1391 * then return zero. When we succeed in waiting for @p to be off its CPU,
1392 * we return a positive number (its total switch count). If a second call
1393 * a short while later returns the same number, the caller can be sure that
1394 * @p has remained unscheduled the whole time.
1396 * The caller must ensure that the task *will* unschedule sometime soon,
1397 * else this function might spin for a *long* time. This function can't
1398 * be called with interrupts off, or it may introduce deadlock with
1399 * smp_call_function() if an IPI is sent by the same process we are
1400 * waiting to become inactive.
1402 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1404 int running, queued;
1411 * We do the initial early heuristics without holding
1412 * any task-queue locks at all. We'll only try to get
1413 * the runqueue lock when things look like they will
1419 * If the task is actively running on another CPU
1420 * still, just relax and busy-wait without holding
1423 * NOTE! Since we don't hold any locks, it's not
1424 * even sure that "rq" stays as the right runqueue!
1425 * But we don't care, since "task_running()" will
1426 * return false if the runqueue has changed and p
1427 * is actually now running somewhere else!
1429 while (task_running(rq, p)) {
1430 if (match_state && unlikely(p->state != match_state))
1436 * Ok, time to look more closely! We need the rq
1437 * lock now, to be *sure*. If we're wrong, we'll
1438 * just go back and repeat.
1440 rq = task_rq_lock(p, &rf);
1441 trace_sched_wait_task(p);
1442 running = task_running(rq, p);
1443 queued = task_on_rq_queued(p);
1445 if (!match_state || p->state == match_state)
1446 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1447 task_rq_unlock(rq, p, &rf);
1450 * If it changed from the expected state, bail out now.
1452 if (unlikely(!ncsw))
1456 * Was it really running after all now that we
1457 * checked with the proper locks actually held?
1459 * Oops. Go back and try again..
1461 if (unlikely(running)) {
1467 * It's not enough that it's not actively running,
1468 * it must be off the runqueue _entirely_, and not
1471 * So if it was still runnable (but just not actively
1472 * running right now), it's preempted, and we should
1473 * yield - it could be a while.
1475 if (unlikely(queued)) {
1476 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1478 set_current_state(TASK_UNINTERRUPTIBLE);
1479 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1484 * Ahh, all good. It wasn't running, and it wasn't
1485 * runnable, which means that it will never become
1486 * running in the future either. We're all done!
1495 * kick_process - kick a running thread to enter/exit the kernel
1496 * @p: the to-be-kicked thread
1498 * Cause a process which is running on another CPU to enter
1499 * kernel-mode, without any delay. (to get signals handled.)
1501 * NOTE: this function doesn't have to take the runqueue lock,
1502 * because all it wants to ensure is that the remote task enters
1503 * the kernel. If the IPI races and the task has been migrated
1504 * to another CPU then no harm is done and the purpose has been
1507 void kick_process(struct task_struct *p)
1513 if ((cpu != smp_processor_id()) && task_curr(p))
1514 smp_send_reschedule(cpu);
1517 EXPORT_SYMBOL_GPL(kick_process);
1520 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1522 * A few notes on cpu_active vs cpu_online:
1524 * - cpu_active must be a subset of cpu_online
1526 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1527 * see __set_cpus_allowed_ptr(). At this point the newly online
1528 * cpu isn't yet part of the sched domains, and balancing will not
1531 * - on cpu-down we clear cpu_active() to mask the sched domains and
1532 * avoid the load balancer to place new tasks on the to be removed
1533 * cpu. Existing tasks will remain running there and will be taken
1536 * This means that fallback selection must not select !active CPUs.
1537 * And can assume that any active CPU must be online. Conversely
1538 * select_task_rq() below may allow selection of !active CPUs in order
1539 * to satisfy the above rules.
1541 static int select_fallback_rq(int cpu, struct task_struct *p)
1543 int nid = cpu_to_node(cpu);
1544 const struct cpumask *nodemask = NULL;
1545 enum { cpuset, possible, fail } state = cpuset;
1549 * If the node that the cpu is on has been offlined, cpu_to_node()
1550 * will return -1. There is no cpu on the node, and we should
1551 * select the cpu on the other node.
1554 nodemask = cpumask_of_node(nid);
1556 /* Look for allowed, online CPU in same node. */
1557 for_each_cpu(dest_cpu, nodemask) {
1558 if (!cpu_active(dest_cpu))
1560 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1566 /* Any allowed, online CPU? */
1567 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1568 if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
1570 if (!cpu_online(dest_cpu))
1575 /* No more Mr. Nice Guy. */
1578 if (IS_ENABLED(CONFIG_CPUSETS)) {
1579 cpuset_cpus_allowed_fallback(p);
1585 do_set_cpus_allowed(p, cpu_possible_mask);
1596 if (state != cpuset) {
1598 * Don't tell them about moving exiting tasks or
1599 * kernel threads (both mm NULL), since they never
1602 if (p->mm && printk_ratelimit()) {
1603 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1604 task_pid_nr(p), p->comm, cpu);
1612 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1615 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1617 lockdep_assert_held(&p->pi_lock);
1619 if (tsk_nr_cpus_allowed(p) > 1)
1620 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1622 cpu = cpumask_any(tsk_cpus_allowed(p));
1625 * In order not to call set_task_cpu() on a blocking task we need
1626 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1629 * Since this is common to all placement strategies, this lives here.
1631 * [ this allows ->select_task() to simply return task_cpu(p) and
1632 * not worry about this generic constraint ]
1634 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1636 cpu = select_fallback_rq(task_cpu(p), p);
1641 static void update_avg(u64 *avg, u64 sample)
1643 s64 diff = sample - *avg;
1649 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1650 const struct cpumask *new_mask, bool check)
1652 return set_cpus_allowed_ptr(p, new_mask);
1655 #endif /* CONFIG_SMP */
1658 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1662 if (!schedstat_enabled())
1668 if (cpu == rq->cpu) {
1669 schedstat_inc(rq->ttwu_local);
1670 schedstat_inc(p->se.statistics.nr_wakeups_local);
1672 struct sched_domain *sd;
1674 schedstat_inc(p->se.statistics.nr_wakeups_remote);
1676 for_each_domain(rq->cpu, sd) {
1677 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1678 schedstat_inc(sd->ttwu_wake_remote);
1685 if (wake_flags & WF_MIGRATED)
1686 schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1687 #endif /* CONFIG_SMP */
1689 schedstat_inc(rq->ttwu_count);
1690 schedstat_inc(p->se.statistics.nr_wakeups);
1692 if (wake_flags & WF_SYNC)
1693 schedstat_inc(p->se.statistics.nr_wakeups_sync);
1696 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1698 activate_task(rq, p, en_flags);
1699 p->on_rq = TASK_ON_RQ_QUEUED;
1701 /* if a worker is waking up, notify workqueue */
1702 if (p->flags & PF_WQ_WORKER)
1703 wq_worker_waking_up(p, cpu_of(rq));
1707 * Mark the task runnable and perform wakeup-preemption.
1709 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1710 struct pin_cookie cookie)
1712 check_preempt_curr(rq, p, wake_flags);
1713 p->state = TASK_RUNNING;
1714 trace_sched_wakeup(p);
1717 if (p->sched_class->task_woken) {
1719 * Our task @p is fully woken up and running; so its safe to
1720 * drop the rq->lock, hereafter rq is only used for statistics.
1722 lockdep_unpin_lock(&rq->lock, cookie);
1723 p->sched_class->task_woken(rq, p);
1724 lockdep_repin_lock(&rq->lock, cookie);
1727 if (rq->idle_stamp) {
1728 u64 delta = rq_clock(rq) - rq->idle_stamp;
1729 u64 max = 2*rq->max_idle_balance_cost;
1731 update_avg(&rq->avg_idle, delta);
1733 if (rq->avg_idle > max)
1742 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1743 struct pin_cookie cookie)
1745 int en_flags = ENQUEUE_WAKEUP;
1747 lockdep_assert_held(&rq->lock);
1750 if (p->sched_contributes_to_load)
1751 rq->nr_uninterruptible--;
1753 if (wake_flags & WF_MIGRATED)
1754 en_flags |= ENQUEUE_MIGRATED;
1757 ttwu_activate(rq, p, en_flags);
1758 ttwu_do_wakeup(rq, p, wake_flags, cookie);
1762 * Called in case the task @p isn't fully descheduled from its runqueue,
1763 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1764 * since all we need to do is flip p->state to TASK_RUNNING, since
1765 * the task is still ->on_rq.
1767 static int ttwu_remote(struct task_struct *p, int wake_flags)
1773 rq = __task_rq_lock(p, &rf);
1774 if (task_on_rq_queued(p)) {
1775 /* check_preempt_curr() may use rq clock */
1776 update_rq_clock(rq);
1777 ttwu_do_wakeup(rq, p, wake_flags, rf.cookie);
1780 __task_rq_unlock(rq, &rf);
1786 void sched_ttwu_pending(void)
1788 struct rq *rq = this_rq();
1789 struct llist_node *llist = llist_del_all(&rq->wake_list);
1790 struct pin_cookie cookie;
1791 struct task_struct *p;
1792 unsigned long flags;
1797 raw_spin_lock_irqsave(&rq->lock, flags);
1798 cookie = lockdep_pin_lock(&rq->lock);
1803 p = llist_entry(llist, struct task_struct, wake_entry);
1804 llist = llist_next(llist);
1806 if (p->sched_remote_wakeup)
1807 wake_flags = WF_MIGRATED;
1809 ttwu_do_activate(rq, p, wake_flags, cookie);
1812 lockdep_unpin_lock(&rq->lock, cookie);
1813 raw_spin_unlock_irqrestore(&rq->lock, flags);
1816 void scheduler_ipi(void)
1819 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1820 * TIF_NEED_RESCHED remotely (for the first time) will also send
1823 preempt_fold_need_resched();
1825 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1829 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1830 * traditionally all their work was done from the interrupt return
1831 * path. Now that we actually do some work, we need to make sure
1834 * Some archs already do call them, luckily irq_enter/exit nest
1837 * Arguably we should visit all archs and update all handlers,
1838 * however a fair share of IPIs are still resched only so this would
1839 * somewhat pessimize the simple resched case.
1842 sched_ttwu_pending();
1845 * Check if someone kicked us for doing the nohz idle load balance.
1847 if (unlikely(got_nohz_idle_kick())) {
1848 this_rq()->idle_balance = 1;
1849 raise_softirq_irqoff(SCHED_SOFTIRQ);
1854 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1856 struct rq *rq = cpu_rq(cpu);
1858 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1860 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1861 if (!set_nr_if_polling(rq->idle))
1862 smp_send_reschedule(cpu);
1864 trace_sched_wake_idle_without_ipi(cpu);
1868 void wake_up_if_idle(int cpu)
1870 struct rq *rq = cpu_rq(cpu);
1871 unsigned long flags;
1875 if (!is_idle_task(rcu_dereference(rq->curr)))
1878 if (set_nr_if_polling(rq->idle)) {
1879 trace_sched_wake_idle_without_ipi(cpu);
1881 raw_spin_lock_irqsave(&rq->lock, flags);
1882 if (is_idle_task(rq->curr))
1883 smp_send_reschedule(cpu);
1884 /* Else cpu is not in idle, do nothing here */
1885 raw_spin_unlock_irqrestore(&rq->lock, flags);
1892 bool cpus_share_cache(int this_cpu, int that_cpu)
1894 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1896 #endif /* CONFIG_SMP */
1898 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1900 struct rq *rq = cpu_rq(cpu);
1901 struct pin_cookie cookie;
1903 #if defined(CONFIG_SMP)
1904 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1905 sched_clock_cpu(cpu); /* sync clocks x-cpu */
1906 ttwu_queue_remote(p, cpu, wake_flags);
1911 raw_spin_lock(&rq->lock);
1912 cookie = lockdep_pin_lock(&rq->lock);
1913 ttwu_do_activate(rq, p, wake_flags, cookie);
1914 lockdep_unpin_lock(&rq->lock, cookie);
1915 raw_spin_unlock(&rq->lock);
1919 * Notes on Program-Order guarantees on SMP systems.
1923 * The basic program-order guarantee on SMP systems is that when a task [t]
1924 * migrates, all its activity on its old cpu [c0] happens-before any subsequent
1925 * execution on its new cpu [c1].
1927 * For migration (of runnable tasks) this is provided by the following means:
1929 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1930 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1931 * rq(c1)->lock (if not at the same time, then in that order).
1932 * C) LOCK of the rq(c1)->lock scheduling in task
1934 * Transitivity guarantees that B happens after A and C after B.
1935 * Note: we only require RCpc transitivity.
1936 * Note: the cpu doing B need not be c0 or c1
1945 * UNLOCK rq(0)->lock
1947 * LOCK rq(0)->lock // orders against CPU0
1949 * UNLOCK rq(0)->lock
1953 * UNLOCK rq(1)->lock
1955 * LOCK rq(1)->lock // orders against CPU2
1958 * UNLOCK rq(1)->lock
1961 * BLOCKING -- aka. SLEEP + WAKEUP
1963 * For blocking we (obviously) need to provide the same guarantee as for
1964 * migration. However the means are completely different as there is no lock
1965 * chain to provide order. Instead we do:
1967 * 1) smp_store_release(X->on_cpu, 0)
1968 * 2) smp_cond_load_acquire(!X->on_cpu)
1972 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1974 * LOCK rq(0)->lock LOCK X->pi_lock
1977 * smp_store_release(X->on_cpu, 0);
1979 * smp_cond_load_acquire(&X->on_cpu, !VAL);
1985 * X->state = RUNNING
1986 * UNLOCK rq(2)->lock
1988 * LOCK rq(2)->lock // orders against CPU1
1991 * UNLOCK rq(2)->lock
1994 * UNLOCK rq(0)->lock
1997 * However; for wakeups there is a second guarantee we must provide, namely we
1998 * must observe the state that lead to our wakeup. That is, not only must our
1999 * task observe its own prior state, it must also observe the stores prior to
2002 * This means that any means of doing remote wakeups must order the CPU doing
2003 * the wakeup against the CPU the task is going to end up running on. This,
2004 * however, is already required for the regular Program-Order guarantee above,
2005 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
2010 * try_to_wake_up - wake up a thread
2011 * @p: the thread to be awakened
2012 * @state: the mask of task states that can be woken
2013 * @wake_flags: wake modifier flags (WF_*)
2015 * Put it on the run-queue if it's not already there. The "current"
2016 * thread is always on the run-queue (except when the actual
2017 * re-schedule is in progress), and as such you're allowed to do
2018 * the simpler "current->state = TASK_RUNNING" to mark yourself
2019 * runnable without the overhead of this.
2021 * Return: %true if @p was woken up, %false if it was already running.
2022 * or @state didn't match @p's state.
2025 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
2027 unsigned long flags;
2028 int cpu, success = 0;
2035 * If we are going to wake up a thread waiting for CONDITION we
2036 * need to ensure that CONDITION=1 done by the caller can not be
2037 * reordered with p->state check below. This pairs with mb() in
2038 * set_current_state() the waiting thread does.
2040 smp_mb__before_spinlock();
2041 raw_spin_lock_irqsave(&p->pi_lock, flags);
2042 if (!(p->state & state))
2045 trace_sched_waking(p);
2047 success = 1; /* we're going to change ->state */
2051 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2052 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2053 * in smp_cond_load_acquire() below.
2055 * sched_ttwu_pending() try_to_wake_up()
2056 * [S] p->on_rq = 1; [L] P->state
2057 * UNLOCK rq->lock -----.
2061 * LOCK rq->lock -----'
2065 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2067 * Pairs with the UNLOCK+LOCK on rq->lock from the
2068 * last wakeup of our task and the schedule that got our task
2072 if (p->on_rq && ttwu_remote(p, wake_flags))
2077 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2078 * possible to, falsely, observe p->on_cpu == 0.
2080 * One must be running (->on_cpu == 1) in order to remove oneself
2081 * from the runqueue.
2083 * [S] ->on_cpu = 1; [L] ->on_rq
2087 * [S] ->on_rq = 0; [L] ->on_cpu
2089 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2090 * from the consecutive calls to schedule(); the first switching to our
2091 * task, the second putting it to sleep.
2096 * If the owning (remote) cpu is still in the middle of schedule() with
2097 * this task as prev, wait until its done referencing the task.
2099 * Pairs with the smp_store_release() in finish_lock_switch().
2101 * This ensures that tasks getting woken will be fully ordered against
2102 * their previous state and preserve Program Order.
2104 smp_cond_load_acquire(&p->on_cpu, !VAL);
2106 rq = cpu_rq(task_cpu(p));
2108 raw_spin_lock(&rq->lock);
2109 wallclock = walt_ktime_clock();
2110 walt_update_task_ravg(rq->curr, rq, TASK_UPDATE, wallclock, 0);
2111 walt_update_task_ravg(p, rq, TASK_WAKE, wallclock, 0);
2112 raw_spin_unlock(&rq->lock);
2114 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2115 p->state = TASK_WAKING;
2117 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2119 if (task_cpu(p) != cpu) {
2120 wake_flags |= WF_MIGRATED;
2121 set_task_cpu(p, cpu);
2124 #endif /* CONFIG_SMP */
2126 ttwu_queue(p, cpu, wake_flags);
2128 ttwu_stat(p, cpu, wake_flags);
2130 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2136 * try_to_wake_up_local - try to wake up a local task with rq lock held
2137 * @p: the thread to be awakened
2138 * @cookie: context's cookie for pinning
2140 * Put @p on the run-queue if it's not already there. The caller must
2141 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2144 static void try_to_wake_up_local(struct task_struct *p, struct pin_cookie cookie)
2146 struct rq *rq = task_rq(p);
2148 if (WARN_ON_ONCE(rq != this_rq()) ||
2149 WARN_ON_ONCE(p == current))
2152 lockdep_assert_held(&rq->lock);
2154 if (!raw_spin_trylock(&p->pi_lock)) {
2156 * This is OK, because current is on_cpu, which avoids it being
2157 * picked for load-balance and preemption/IRQs are still
2158 * disabled avoiding further scheduler activity on it and we've
2159 * not yet picked a replacement task.
2161 lockdep_unpin_lock(&rq->lock, cookie);
2162 raw_spin_unlock(&rq->lock);
2163 raw_spin_lock(&p->pi_lock);
2164 raw_spin_lock(&rq->lock);
2165 lockdep_repin_lock(&rq->lock, cookie);
2168 if (!(p->state & TASK_NORMAL))
2171 trace_sched_waking(p);
2173 if (!task_on_rq_queued(p)) {
2174 u64 wallclock = walt_ktime_clock();
2176 walt_update_task_ravg(rq->curr, rq, TASK_UPDATE, wallclock, 0);
2177 walt_update_task_ravg(p, rq, TASK_WAKE, wallclock, 0);
2178 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2181 ttwu_do_wakeup(rq, p, 0, cookie);
2182 ttwu_stat(p, smp_processor_id(), 0);
2184 raw_spin_unlock(&p->pi_lock);
2188 * wake_up_process - Wake up a specific process
2189 * @p: The process to be woken up.
2191 * Attempt to wake up the nominated process and move it to the set of runnable
2194 * Return: 1 if the process was woken up, 0 if it was already running.
2196 * It may be assumed that this function implies a write memory barrier before
2197 * changing the task state if and only if any tasks are woken up.
2199 int wake_up_process(struct task_struct *p)
2201 return try_to_wake_up(p, TASK_NORMAL, 0);
2203 EXPORT_SYMBOL(wake_up_process);
2205 int wake_up_state(struct task_struct *p, unsigned int state)
2207 return try_to_wake_up(p, state, 0);
2211 * This function clears the sched_dl_entity static params.
2213 void __dl_clear_params(struct task_struct *p)
2215 struct sched_dl_entity *dl_se = &p->dl;
2217 dl_se->dl_runtime = 0;
2218 dl_se->dl_deadline = 0;
2219 dl_se->dl_period = 0;
2223 dl_se->dl_throttled = 0;
2224 dl_se->dl_yielded = 0;
2228 * Perform scheduler related setup for a newly forked process p.
2229 * p is forked by current.
2231 * __sched_fork() is basic setup used by init_idle() too:
2233 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2238 p->se.exec_start = 0;
2239 p->se.sum_exec_runtime = 0;
2240 p->se.prev_sum_exec_runtime = 0;
2241 p->se.nr_migrations = 0;
2243 INIT_LIST_HEAD(&p->se.group_node);
2244 walt_init_new_task_load(p);
2246 #ifdef CONFIG_FAIR_GROUP_SCHED
2247 p->se.cfs_rq = NULL;
2250 #ifdef CONFIG_SCHEDSTATS
2251 /* Even if schedstat is disabled, there should not be garbage */
2252 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2255 RB_CLEAR_NODE(&p->dl.rb_node);
2256 init_dl_task_timer(&p->dl);
2257 __dl_clear_params(p);
2259 INIT_LIST_HEAD(&p->rt.run_list);
2261 p->rt.time_slice = sched_rr_timeslice;
2265 #ifdef CONFIG_PREEMPT_NOTIFIERS
2266 INIT_HLIST_HEAD(&p->preempt_notifiers);
2269 #ifdef CONFIG_NUMA_BALANCING
2270 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
2271 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2272 p->mm->numa_scan_seq = 0;
2275 if (clone_flags & CLONE_VM)
2276 p->numa_preferred_nid = current->numa_preferred_nid;
2278 p->numa_preferred_nid = -1;
2280 p->node_stamp = 0ULL;
2281 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
2282 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2283 p->numa_work.next = &p->numa_work;
2284 p->numa_faults = NULL;
2285 p->last_task_numa_placement = 0;
2286 p->last_sum_exec_runtime = 0;
2288 p->numa_group = NULL;
2289 #endif /* CONFIG_NUMA_BALANCING */
2292 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2294 #ifdef CONFIG_NUMA_BALANCING
2296 void set_numabalancing_state(bool enabled)
2299 static_branch_enable(&sched_numa_balancing);
2301 static_branch_disable(&sched_numa_balancing);
2304 #ifdef CONFIG_PROC_SYSCTL
2305 int sysctl_numa_balancing(struct ctl_table *table, int write,
2306 void __user *buffer, size_t *lenp, loff_t *ppos)
2310 int state = static_branch_likely(&sched_numa_balancing);
2312 if (write && !capable(CAP_SYS_ADMIN))
2317 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2321 set_numabalancing_state(state);
2327 #ifdef CONFIG_SCHEDSTATS
2329 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2330 static bool __initdata __sched_schedstats = false;
2332 static void set_schedstats(bool enabled)
2335 static_branch_enable(&sched_schedstats);
2337 static_branch_disable(&sched_schedstats);
2340 void force_schedstat_enabled(void)
2342 if (!schedstat_enabled()) {
2343 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2344 static_branch_enable(&sched_schedstats);
2348 static int __init setup_schedstats(char *str)
2355 * This code is called before jump labels have been set up, so we can't
2356 * change the static branch directly just yet. Instead set a temporary
2357 * variable so init_schedstats() can do it later.
2359 if (!strcmp(str, "enable")) {
2360 __sched_schedstats = true;
2362 } else if (!strcmp(str, "disable")) {
2363 __sched_schedstats = false;
2368 pr_warn("Unable to parse schedstats=\n");
2372 __setup("schedstats=", setup_schedstats);
2374 static void __init init_schedstats(void)
2376 set_schedstats(__sched_schedstats);
2379 #ifdef CONFIG_PROC_SYSCTL
2380 int sysctl_schedstats(struct ctl_table *table, int write,
2381 void __user *buffer, size_t *lenp, loff_t *ppos)
2385 int state = static_branch_likely(&sched_schedstats);
2387 if (write && !capable(CAP_SYS_ADMIN))
2392 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2396 set_schedstats(state);
2399 #endif /* CONFIG_PROC_SYSCTL */
2400 #else /* !CONFIG_SCHEDSTATS */
2401 static inline void init_schedstats(void) {}
2402 #endif /* CONFIG_SCHEDSTATS */
2405 * fork()/clone()-time setup:
2407 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2409 unsigned long flags;
2410 int cpu = get_cpu();
2412 __sched_fork(clone_flags, p);
2414 * We mark the process as NEW here. This guarantees that
2415 * nobody will actually run it, and a signal or other external
2416 * event cannot wake it up and insert it on the runqueue either.
2418 p->state = TASK_NEW;
2421 * Make sure we do not leak PI boosting priority to the child.
2423 p->prio = current->normal_prio;
2426 * Revert to default priority/policy on fork if requested.
2428 if (unlikely(p->sched_reset_on_fork)) {
2429 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2430 p->policy = SCHED_NORMAL;
2431 p->static_prio = NICE_TO_PRIO(0);
2433 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2434 p->static_prio = NICE_TO_PRIO(0);
2436 p->prio = p->normal_prio = __normal_prio(p);
2440 * We don't need the reset flag anymore after the fork. It has
2441 * fulfilled its duty:
2443 p->sched_reset_on_fork = 0;
2446 if (dl_prio(p->prio)) {
2449 } else if (rt_prio(p->prio)) {
2450 p->sched_class = &rt_sched_class;
2452 p->sched_class = &fair_sched_class;
2455 init_entity_runnable_average(&p->se);
2458 * The child is not yet in the pid-hash so no cgroup attach races,
2459 * and the cgroup is pinned to this child due to cgroup_fork()
2460 * is ran before sched_fork().
2462 * Silence PROVE_RCU.
2464 raw_spin_lock_irqsave(&p->pi_lock, flags);
2466 * We're setting the cpu for the first time, we don't migrate,
2467 * so use __set_task_cpu().
2469 __set_task_cpu(p, cpu);
2470 if (p->sched_class->task_fork)
2471 p->sched_class->task_fork(p);
2472 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2474 #ifdef CONFIG_SCHED_INFO
2475 if (likely(sched_info_on()))
2476 memset(&p->sched_info, 0, sizeof(p->sched_info));
2478 #if defined(CONFIG_SMP)
2481 init_task_preempt_count(p);
2483 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2484 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2491 unsigned long to_ratio(u64 period, u64 runtime)
2493 if (runtime == RUNTIME_INF)
2497 * Doing this here saves a lot of checks in all
2498 * the calling paths, and returning zero seems
2499 * safe for them anyway.
2504 return div64_u64(runtime << 20, period);
2508 inline struct dl_bw *dl_bw_of(int i)
2510 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2511 "sched RCU must be held");
2512 return &cpu_rq(i)->rd->dl_bw;
2515 static inline int dl_bw_cpus(int i)
2517 struct root_domain *rd = cpu_rq(i)->rd;
2520 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2521 "sched RCU must be held");
2522 for_each_cpu_and(i, rd->span, cpu_active_mask)
2528 inline struct dl_bw *dl_bw_of(int i)
2530 return &cpu_rq(i)->dl.dl_bw;
2533 static inline int dl_bw_cpus(int i)
2540 * We must be sure that accepting a new task (or allowing changing the
2541 * parameters of an existing one) is consistent with the bandwidth
2542 * constraints. If yes, this function also accordingly updates the currently
2543 * allocated bandwidth to reflect the new situation.
2545 * This function is called while holding p's rq->lock.
2547 * XXX we should delay bw change until the task's 0-lag point, see
2550 static int dl_overflow(struct task_struct *p, int policy,
2551 const struct sched_attr *attr)
2554 struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2555 u64 period = attr->sched_period ?: attr->sched_deadline;
2556 u64 runtime = attr->sched_runtime;
2557 u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2560 /* !deadline task may carry old deadline bandwidth */
2561 if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
2565 * Either if a task, enters, leave, or stays -deadline but changes
2566 * its parameters, we may need to update accordingly the total
2567 * allocated bandwidth of the container.
2569 raw_spin_lock(&dl_b->lock);
2570 cpus = dl_bw_cpus(task_cpu(p));
2571 if (dl_policy(policy) && !task_has_dl_policy(p) &&
2572 !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2573 __dl_add(dl_b, new_bw);
2575 } else if (dl_policy(policy) && task_has_dl_policy(p) &&
2576 !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2577 __dl_clear(dl_b, p->dl.dl_bw);
2578 __dl_add(dl_b, new_bw);
2580 } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2581 __dl_clear(dl_b, p->dl.dl_bw);
2584 raw_spin_unlock(&dl_b->lock);
2589 extern void init_dl_bw(struct dl_bw *dl_b);
2592 * wake_up_new_task - wake up a newly created task for the first time.
2594 * This function will do some initial scheduler statistics housekeeping
2595 * that must be done for every newly created context, then puts the task
2596 * on the runqueue and wakes it.
2598 void wake_up_new_task(struct task_struct *p)
2603 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2605 walt_init_new_task_load(p);
2607 p->state = TASK_RUNNING;
2610 * Fork balancing, do it here and not earlier because:
2611 * - cpus_allowed can change in the fork path
2612 * - any previously selected cpu might disappear through hotplug
2614 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2615 * as we're not fully set-up yet.
2617 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2619 rq = __task_rq_lock(p, &rf);
2620 post_init_entity_util_avg(&p->se);
2622 walt_mark_task_starting(p);
2624 activate_task(rq, p, ENQUEUE_WAKEUP_NEW);
2625 p->on_rq = TASK_ON_RQ_QUEUED;
2626 trace_sched_wakeup_new(p);
2627 check_preempt_curr(rq, p, WF_FORK);
2629 if (p->sched_class->task_woken) {
2631 * Nothing relies on rq->lock after this, so its fine to
2634 lockdep_unpin_lock(&rq->lock, rf.cookie);
2635 p->sched_class->task_woken(rq, p);
2636 lockdep_repin_lock(&rq->lock, rf.cookie);
2639 task_rq_unlock(rq, p, &rf);
2642 #ifdef CONFIG_PREEMPT_NOTIFIERS
2644 static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2646 void preempt_notifier_inc(void)
2648 static_key_slow_inc(&preempt_notifier_key);
2650 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2652 void preempt_notifier_dec(void)
2654 static_key_slow_dec(&preempt_notifier_key);
2656 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2659 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2660 * @notifier: notifier struct to register
2662 void preempt_notifier_register(struct preempt_notifier *notifier)
2664 if (!static_key_false(&preempt_notifier_key))
2665 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2667 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2669 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2672 * preempt_notifier_unregister - no longer interested in preemption notifications
2673 * @notifier: notifier struct to unregister
2675 * This is *not* safe to call from within a preemption notifier.
2677 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2679 hlist_del(¬ifier->link);
2681 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2683 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2685 struct preempt_notifier *notifier;
2687 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2688 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2691 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2693 if (static_key_false(&preempt_notifier_key))
2694 __fire_sched_in_preempt_notifiers(curr);
2698 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2699 struct task_struct *next)
2701 struct preempt_notifier *notifier;
2703 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2704 notifier->ops->sched_out(notifier, next);
2707 static __always_inline void
2708 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2709 struct task_struct *next)
2711 if (static_key_false(&preempt_notifier_key))
2712 __fire_sched_out_preempt_notifiers(curr, next);
2715 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2717 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2722 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2723 struct task_struct *next)
2727 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2730 * prepare_task_switch - prepare to switch tasks
2731 * @rq: the runqueue preparing to switch
2732 * @prev: the current task that is being switched out
2733 * @next: the task we are going to switch to.
2735 * This is called with the rq lock held and interrupts off. It must
2736 * be paired with a subsequent finish_task_switch after the context
2739 * prepare_task_switch sets up locking and calls architecture specific
2743 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2744 struct task_struct *next)
2746 sched_info_switch(rq, prev, next);
2747 perf_event_task_sched_out(prev, next);
2748 fire_sched_out_preempt_notifiers(prev, next);
2749 prepare_lock_switch(rq, next);
2750 prepare_arch_switch(next);
2754 * finish_task_switch - clean up after a task-switch
2755 * @prev: the thread we just switched away from.
2757 * finish_task_switch must be called after the context switch, paired
2758 * with a prepare_task_switch call before the context switch.
2759 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2760 * and do any other architecture-specific cleanup actions.
2762 * Note that we may have delayed dropping an mm in context_switch(). If
2763 * so, we finish that here outside of the runqueue lock. (Doing it
2764 * with the lock held can cause deadlocks; see schedule() for
2767 * The context switch have flipped the stack from under us and restored the
2768 * local variables which were saved when this task called schedule() in the
2769 * past. prev == current is still correct but we need to recalculate this_rq
2770 * because prev may have moved to another CPU.
2772 static struct rq *finish_task_switch(struct task_struct *prev)
2773 __releases(rq->lock)
2775 struct rq *rq = this_rq();
2776 struct mm_struct *mm = rq->prev_mm;
2780 * The previous task will have left us with a preempt_count of 2
2781 * because it left us after:
2784 * preempt_disable(); // 1
2786 * raw_spin_lock_irq(&rq->lock) // 2
2788 * Also, see FORK_PREEMPT_COUNT.
2790 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2791 "corrupted preempt_count: %s/%d/0x%x\n",
2792 current->comm, current->pid, preempt_count()))
2793 preempt_count_set(FORK_PREEMPT_COUNT);
2798 * A task struct has one reference for the use as "current".
2799 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2800 * schedule one last time. The schedule call will never return, and
2801 * the scheduled task must drop that reference.
2803 * We must observe prev->state before clearing prev->on_cpu (in
2804 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2805 * running on another CPU and we could rave with its RUNNING -> DEAD
2806 * transition, resulting in a double drop.
2808 prev_state = prev->state;
2809 vtime_task_switch(prev);
2810 perf_event_task_sched_in(prev, current);
2811 finish_lock_switch(rq, prev);
2812 finish_arch_post_lock_switch();
2814 fire_sched_in_preempt_notifiers(current);
2817 if (unlikely(prev_state == TASK_DEAD)) {
2818 if (prev->sched_class->task_dead)
2819 prev->sched_class->task_dead(prev);
2822 * Remove function-return probe instances associated with this
2823 * task and put them back on the free list.
2825 kprobe_flush_task(prev);
2827 /* Task is done with its stack. */
2828 put_task_stack(prev);
2830 put_task_struct(prev);
2833 tick_nohz_task_switch();
2839 /* rq->lock is NOT held, but preemption is disabled */
2840 static void __balance_callback(struct rq *rq)
2842 struct callback_head *head, *next;
2843 void (*func)(struct rq *rq);
2844 unsigned long flags;
2846 raw_spin_lock_irqsave(&rq->lock, flags);
2847 head = rq->balance_callback;
2848 rq->balance_callback = NULL;
2850 func = (void (*)(struct rq *))head->func;
2857 raw_spin_unlock_irqrestore(&rq->lock, flags);
2860 static inline void balance_callback(struct rq *rq)
2862 if (unlikely(rq->balance_callback))
2863 __balance_callback(rq);
2868 static inline void balance_callback(struct rq *rq)
2875 * schedule_tail - first thing a freshly forked thread must call.
2876 * @prev: the thread we just switched away from.
2878 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2879 __releases(rq->lock)
2884 * New tasks start with FORK_PREEMPT_COUNT, see there and
2885 * finish_task_switch() for details.
2887 * finish_task_switch() will drop rq->lock() and lower preempt_count
2888 * and the preempt_enable() will end up enabling preemption (on
2889 * PREEMPT_COUNT kernels).
2892 rq = finish_task_switch(prev);
2893 balance_callback(rq);
2896 if (current->set_child_tid)
2897 put_user(task_pid_vnr(current), current->set_child_tid);
2901 * context_switch - switch to the new MM and the new thread's register state.
2903 static __always_inline struct rq *
2904 context_switch(struct rq *rq, struct task_struct *prev,
2905 struct task_struct *next, struct pin_cookie cookie)
2907 struct mm_struct *mm, *oldmm;
2909 prepare_task_switch(rq, prev, next);
2912 oldmm = prev->active_mm;
2914 * For paravirt, this is coupled with an exit in switch_to to
2915 * combine the page table reload and the switch backend into
2918 arch_start_context_switch(prev);
2921 next->active_mm = oldmm;
2922 atomic_inc(&oldmm->mm_count);
2923 enter_lazy_tlb(oldmm, next);
2925 switch_mm_irqs_off(oldmm, mm, next);
2928 prev->active_mm = NULL;
2929 rq->prev_mm = oldmm;
2932 * Since the runqueue lock will be released by the next
2933 * task (which is an invalid locking op but in the case
2934 * of the scheduler it's an obvious special-case), so we
2935 * do an early lockdep release here:
2937 lockdep_unpin_lock(&rq->lock, cookie);
2938 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2940 /* Here we just switch the register state and the stack. */
2941 switch_to(prev, next, prev);
2944 return finish_task_switch(prev);
2948 * nr_running and nr_context_switches:
2950 * externally visible scheduler statistics: current number of runnable
2951 * threads, total number of context switches performed since bootup.
2953 unsigned long nr_running(void)
2955 unsigned long i, sum = 0;
2957 for_each_online_cpu(i)
2958 sum += cpu_rq(i)->nr_running;
2964 * Check if only the current task is running on the cpu.
2966 * Caution: this function does not check that the caller has disabled
2967 * preemption, thus the result might have a time-of-check-to-time-of-use
2968 * race. The caller is responsible to use it correctly, for example:
2970 * - from a non-preemptable section (of course)
2972 * - from a thread that is bound to a single CPU
2974 * - in a loop with very short iterations (e.g. a polling loop)
2976 bool single_task_running(void)
2978 return raw_rq()->nr_running == 1;
2980 EXPORT_SYMBOL(single_task_running);
2982 unsigned long long nr_context_switches(void)
2985 unsigned long long sum = 0;
2987 for_each_possible_cpu(i)
2988 sum += cpu_rq(i)->nr_switches;
2993 unsigned long nr_iowait(void)
2995 unsigned long i, sum = 0;
2997 for_each_possible_cpu(i)
2998 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3003 unsigned long nr_iowait_cpu(int cpu)
3005 struct rq *this = cpu_rq(cpu);
3006 return atomic_read(&this->nr_iowait);
3009 #ifdef CONFIG_CPU_QUIET
3010 u64 nr_running_integral(unsigned int cpu)
3012 unsigned int seqcnt;
3016 if (cpu >= nr_cpu_ids)
3022 * Update average to avoid reading stalled value if there were
3023 * no run-queue changes for a long time. On the other hand if
3024 * the changes are happening right now, just read current value
3028 seqcnt = read_seqcount_begin(&q->ave_seqcnt);
3029 integral = do_nr_running_integral(q);
3030 if (read_seqcount_retry(&q->ave_seqcnt, seqcnt)) {
3031 read_seqcount_begin(&q->ave_seqcnt);
3032 integral = q->nr_running_integral;
3039 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
3041 struct rq *rq = this_rq();
3042 *nr_waiters = atomic_read(&rq->nr_iowait);
3043 *load = rq->load.weight;
3049 * sched_exec - execve() is a valuable balancing opportunity, because at
3050 * this point the task has the smallest effective memory and cache footprint.
3052 void sched_exec(void)
3054 struct task_struct *p = current;
3055 unsigned long flags;
3058 raw_spin_lock_irqsave(&p->pi_lock, flags);
3059 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
3060 if (dest_cpu == smp_processor_id())
3063 if (likely(cpu_active(dest_cpu))) {
3064 struct migration_arg arg = { p, dest_cpu };
3066 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3067 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
3071 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3076 DEFINE_PER_CPU(struct kernel_stat, kstat);
3077 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
3079 EXPORT_PER_CPU_SYMBOL(kstat);
3080 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3083 * The function fair_sched_class.update_curr accesses the struct curr
3084 * and its field curr->exec_start; when called from task_sched_runtime(),
3085 * we observe a high rate of cache misses in practice.
3086 * Prefetching this data results in improved performance.
3088 static inline void prefetch_curr_exec_start(struct task_struct *p)
3090 #ifdef CONFIG_FAIR_GROUP_SCHED
3091 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3093 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3096 prefetch(&curr->exec_start);
3100 * Return accounted runtime for the task.
3101 * In case the task is currently running, return the runtime plus current's
3102 * pending runtime that have not been accounted yet.
3104 unsigned long long task_sched_runtime(struct task_struct *p)
3110 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3112 * 64-bit doesn't need locks to atomically read a 64bit value.
3113 * So we have a optimization chance when the task's delta_exec is 0.
3114 * Reading ->on_cpu is racy, but this is ok.
3116 * If we race with it leaving cpu, we'll take a lock. So we're correct.
3117 * If we race with it entering cpu, unaccounted time is 0. This is
3118 * indistinguishable from the read occurring a few cycles earlier.
3119 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3120 * been accounted, so we're correct here as well.
3122 if (!p->on_cpu || !task_on_rq_queued(p))
3123 return p->se.sum_exec_runtime;
3126 rq = task_rq_lock(p, &rf);
3128 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3129 * project cycles that may never be accounted to this
3130 * thread, breaking clock_gettime().
3132 if (task_current(rq, p) && task_on_rq_queued(p)) {
3133 prefetch_curr_exec_start(p);
3134 update_rq_clock(rq);
3135 p->sched_class->update_curr(rq);
3137 ns = p->se.sum_exec_runtime;
3138 task_rq_unlock(rq, p, &rf);
3143 #ifdef CONFIG_CPU_FREQ_GOV_SCHED
3146 unsigned long add_capacity_margin(unsigned long cpu_capacity)
3148 cpu_capacity = cpu_capacity * capacity_margin;
3149 cpu_capacity /= SCHED_CAPACITY_SCALE;
3150 return cpu_capacity;
3154 unsigned long sum_capacity_reqs(unsigned long cfs_cap,
3155 struct sched_capacity_reqs *scr)
3157 unsigned long total = add_capacity_margin(cfs_cap + scr->rt);
3158 return total += scr->dl;
3161 static void sched_freq_tick_pelt(int cpu)
3163 unsigned long cpu_utilization = capacity_max;
3164 unsigned long capacity_curr = capacity_curr_of(cpu);
3165 struct sched_capacity_reqs *scr;
3167 scr = &per_cpu(cpu_sched_capacity_reqs, cpu);
3168 if (sum_capacity_reqs(cpu_utilization, scr) < capacity_curr)
3172 * To make free room for a task that is building up its "real"
3173 * utilization and to harm its performance the least, request
3174 * a jump to a higher OPP as soon as the margin of free capacity
3175 * is impacted (specified by capacity_margin).
3177 set_cfs_cpu_capacity(cpu, true, cpu_utilization);
3180 #ifdef CONFIG_SCHED_WALT
3181 static void sched_freq_tick_walt(int cpu)
3183 unsigned long cpu_utilization = cpu_util(cpu);
3184 unsigned long capacity_curr = capacity_curr_of(cpu);
3186 if (walt_disabled || !sysctl_sched_use_walt_cpu_util)
3187 return sched_freq_tick_pelt(cpu);
3190 * Add a margin to the WALT utilization.
3191 * NOTE: WALT tracks a single CPU signal for all the scheduling
3192 * classes, thus this margin is going to be added to the DL class as
3193 * well, which is something we do not do in sched_freq_tick_pelt case.
3195 cpu_utilization = add_capacity_margin(cpu_utilization);
3196 if (cpu_utilization <= capacity_curr)
3200 * It is likely that the load is growing so we
3201 * keep the added margin in our request as an
3204 set_cfs_cpu_capacity(cpu, true, cpu_utilization);
3207 #define _sched_freq_tick(cpu) sched_freq_tick_walt(cpu)
3209 #define _sched_freq_tick(cpu) sched_freq_tick_pelt(cpu)
3210 #endif /* CONFIG_SCHED_WALT */
3212 static void sched_freq_tick(int cpu)
3214 unsigned long capacity_orig, capacity_curr;
3219 capacity_orig = capacity_orig_of(cpu);
3220 capacity_curr = capacity_curr_of(cpu);
3221 if (capacity_curr == capacity_orig)
3224 _sched_freq_tick(cpu);
3227 static inline void sched_freq_tick(int cpu) { }
3228 #endif /* CONFIG_CPU_FREQ_GOV_SCHED */
3231 * This function gets called by the timer code, with HZ frequency.
3232 * We call it with interrupts disabled.
3234 void scheduler_tick(void)
3236 int cpu = smp_processor_id();
3237 struct rq *rq = cpu_rq(cpu);
3238 struct task_struct *curr = rq->curr;
3242 raw_spin_lock(&rq->lock);
3243 walt_set_window_start(rq);
3244 update_rq_clock(rq);
3245 curr->sched_class->task_tick(rq, curr, 0);
3246 cpu_load_update_active(rq);
3247 walt_update_task_ravg(rq->curr, rq, TASK_UPDATE,
3248 walt_ktime_clock(), 0);
3249 calc_global_load_tick(rq);
3250 sched_freq_tick(cpu);
3251 raw_spin_unlock(&rq->lock);
3253 perf_event_task_tick();
3256 rq->idle_balance = idle_cpu(cpu);
3257 trigger_load_balance(rq);
3259 rq_last_tick_reset(rq);
3262 #ifdef CONFIG_NO_HZ_FULL
3264 * scheduler_tick_max_deferment
3266 * Keep at least one tick per second when a single
3267 * active task is running because the scheduler doesn't
3268 * yet completely support full dynticks environment.
3270 * This makes sure that uptime, CFS vruntime, load
3271 * balancing, etc... continue to move forward, even
3272 * with a very low granularity.
3274 * Return: Maximum deferment in nanoseconds.
3276 u64 scheduler_tick_max_deferment(void)
3278 struct rq *rq = this_rq();
3279 unsigned long next, now = READ_ONCE(jiffies);
3281 next = rq->last_sched_tick + HZ;
3283 if (time_before_eq(next, now))
3286 return jiffies_to_nsecs(next - now);
3290 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3291 defined(CONFIG_PREEMPT_TRACER))
3293 * If the value passed in is equal to the current preempt count
3294 * then we just disabled preemption. Start timing the latency.
3296 static inline void preempt_latency_start(int val)
3298 if (preempt_count() == val) {
3299 unsigned long ip = get_lock_parent_ip();
3300 #ifdef CONFIG_DEBUG_PREEMPT
3301 current->preempt_disable_ip = ip;
3303 trace_preempt_off(CALLER_ADDR0, ip);
3307 void preempt_count_add(int val)
3309 #ifdef CONFIG_DEBUG_PREEMPT
3313 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3316 __preempt_count_add(val);
3317 #ifdef CONFIG_DEBUG_PREEMPT
3319 * Spinlock count overflowing soon?
3321 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3324 preempt_latency_start(val);
3326 EXPORT_SYMBOL(preempt_count_add);
3327 NOKPROBE_SYMBOL(preempt_count_add);
3330 * If the value passed in equals to the current preempt count
3331 * then we just enabled preemption. Stop timing the latency.
3333 static inline void preempt_latency_stop(int val)
3335 if (preempt_count() == val)
3336 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3339 void preempt_count_sub(int val)
3341 #ifdef CONFIG_DEBUG_PREEMPT
3345 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3348 * Is the spinlock portion underflowing?
3350 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3351 !(preempt_count() & PREEMPT_MASK)))
3355 preempt_latency_stop(val);
3356 __preempt_count_sub(val);
3358 EXPORT_SYMBOL(preempt_count_sub);
3359 NOKPROBE_SYMBOL(preempt_count_sub);
3362 static inline void preempt_latency_start(int val) { }
3363 static inline void preempt_latency_stop(int val) { }
3367 * Print scheduling while atomic bug:
3369 static noinline void __schedule_bug(struct task_struct *prev)
3371 /* Save this before calling printk(), since that will clobber it */
3372 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3374 if (oops_in_progress)
3377 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3378 prev->comm, prev->pid, preempt_count());
3380 debug_show_held_locks(prev);
3382 if (irqs_disabled())
3383 print_irqtrace_events(prev);
3384 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3385 && in_atomic_preempt_off()) {
3386 pr_err("Preemption disabled at:");
3387 print_ip_sym(preempt_disable_ip);
3391 panic("scheduling while atomic\n");
3394 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3398 * Various schedule()-time debugging checks and statistics:
3400 static inline void schedule_debug(struct task_struct *prev)
3402 #ifdef CONFIG_SCHED_STACK_END_CHECK
3403 if (task_stack_end_corrupted(prev))
3404 panic("corrupted stack end detected inside scheduler\n");
3407 if (unlikely(in_atomic_preempt_off())) {
3408 __schedule_bug(prev);
3409 preempt_count_set(PREEMPT_DISABLED);
3413 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3415 schedstat_inc(this_rq()->sched_count);
3419 * Pick up the highest-prio task:
3421 static inline struct task_struct *
3422 pick_next_task(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
3424 const struct sched_class *class = &fair_sched_class;
3425 struct task_struct *p;
3428 * Optimization: we know that if all tasks are in
3429 * the fair class we can call that function directly:
3431 if (likely(prev->sched_class == class &&
3432 rq->nr_running == rq->cfs.h_nr_running)) {
3433 p = fair_sched_class.pick_next_task(rq, prev, cookie);
3434 if (unlikely(p == RETRY_TASK))
3437 /* assumes fair_sched_class->next == idle_sched_class */
3439 p = idle_sched_class.pick_next_task(rq, prev, cookie);
3445 for_each_class(class) {
3446 p = class->pick_next_task(rq, prev, cookie);
3448 if (unlikely(p == RETRY_TASK))
3454 BUG(); /* the idle class will always have a runnable task */
3458 * __schedule() is the main scheduler function.
3460 * The main means of driving the scheduler and thus entering this function are:
3462 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3464 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3465 * paths. For example, see arch/x86/entry_64.S.
3467 * To drive preemption between tasks, the scheduler sets the flag in timer
3468 * interrupt handler scheduler_tick().
3470 * 3. Wakeups don't really cause entry into schedule(). They add a
3471 * task to the run-queue and that's it.
3473 * Now, if the new task added to the run-queue preempts the current
3474 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3475 * called on the nearest possible occasion:
3477 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3479 * - in syscall or exception context, at the next outmost
3480 * preempt_enable(). (this might be as soon as the wake_up()'s
3483 * - in IRQ context, return from interrupt-handler to
3484 * preemptible context
3486 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3489 * - cond_resched() call
3490 * - explicit schedule() call
3491 * - return from syscall or exception to user-space
3492 * - return from interrupt-handler to user-space
3494 * WARNING: must be called with preemption disabled!
3496 static void __sched notrace __schedule(bool preempt)
3498 struct task_struct *prev, *next;
3499 unsigned long *switch_count;
3500 struct pin_cookie cookie;
3505 cpu = smp_processor_id();
3509 schedule_debug(prev);
3511 if (sched_feat(HRTICK))
3514 local_irq_disable();
3515 rcu_note_context_switch();
3518 * Make sure that signal_pending_state()->signal_pending() below
3519 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3520 * done by the caller to avoid the race with signal_wake_up().
3522 smp_mb__before_spinlock();
3523 raw_spin_lock(&rq->lock);
3524 cookie = lockdep_pin_lock(&rq->lock);
3526 rq->clock_skip_update <<= 1; /* promote REQ to ACT */
3528 switch_count = &prev->nivcsw;
3529 if (!preempt && prev->state) {
3530 if (unlikely(signal_pending_state(prev->state, prev))) {
3531 prev->state = TASK_RUNNING;
3533 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3537 * If a worker went to sleep, notify and ask workqueue
3538 * whether it wants to wake up a task to maintain
3541 if (prev->flags & PF_WQ_WORKER) {
3542 struct task_struct *to_wakeup;
3544 to_wakeup = wq_worker_sleeping(prev);
3546 try_to_wake_up_local(to_wakeup, cookie);
3549 switch_count = &prev->nvcsw;
3552 if (task_on_rq_queued(prev))
3553 update_rq_clock(rq);
3555 next = pick_next_task(rq, prev, cookie);
3556 wallclock = walt_ktime_clock();
3557 walt_update_task_ravg(prev, rq, PUT_PREV_TASK, wallclock, 0);
3558 walt_update_task_ravg(next, rq, PICK_NEXT_TASK, wallclock, 0);
3559 clear_tsk_need_resched(prev);
3560 clear_preempt_need_resched();
3561 rq->clock_skip_update = 0;
3563 if (likely(prev != next)) {
3568 trace_sched_switch(preempt, prev, next);
3569 rq = context_switch(rq, prev, next, cookie); /* unlocks the rq */
3571 lockdep_unpin_lock(&rq->lock, cookie);
3572 raw_spin_unlock_irq(&rq->lock);
3575 balance_callback(rq);
3578 void __noreturn do_task_dead(void)
3581 * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
3582 * when the following two conditions become true.
3583 * - There is race condition of mmap_sem (It is acquired by
3585 * - SMI occurs before setting TASK_RUNINNG.
3586 * (or hypervisor of virtual machine switches to other guest)
3587 * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
3589 * To avoid it, we have to wait for releasing tsk->pi_lock which
3590 * is held by try_to_wake_up()
3593 raw_spin_unlock_wait(¤t->pi_lock);
3595 /* causes final put_task_struct in finish_task_switch(). */
3596 __set_current_state(TASK_DEAD);
3597 current->flags |= PF_NOFREEZE; /* tell freezer to ignore us */
3600 /* Avoid "noreturn function does return". */
3602 cpu_relax(); /* For when BUG is null */
3605 static inline void sched_submit_work(struct task_struct *tsk)
3607 if (!tsk->state || tsk_is_pi_blocked(tsk))
3610 * If we are going to sleep and we have plugged IO queued,
3611 * make sure to submit it to avoid deadlocks.
3613 if (blk_needs_flush_plug(tsk))
3614 blk_schedule_flush_plug(tsk);
3617 asmlinkage __visible void __sched schedule(void)
3619 struct task_struct *tsk = current;
3621 sched_submit_work(tsk);
3625 sched_preempt_enable_no_resched();
3626 } while (need_resched());
3628 EXPORT_SYMBOL(schedule);
3630 #ifdef CONFIG_CONTEXT_TRACKING
3631 asmlinkage __visible void __sched schedule_user(void)
3634 * If we come here after a random call to set_need_resched(),
3635 * or we have been woken up remotely but the IPI has not yet arrived,
3636 * we haven't yet exited the RCU idle mode. Do it here manually until
3637 * we find a better solution.
3639 * NB: There are buggy callers of this function. Ideally we
3640 * should warn if prev_state != CONTEXT_USER, but that will trigger
3641 * too frequently to make sense yet.
3643 enum ctx_state prev_state = exception_enter();
3645 exception_exit(prev_state);
3650 * schedule_preempt_disabled - called with preemption disabled
3652 * Returns with preemption disabled. Note: preempt_count must be 1
3654 void __sched schedule_preempt_disabled(void)
3656 sched_preempt_enable_no_resched();
3661 static void __sched notrace preempt_schedule_common(void)
3665 * Because the function tracer can trace preempt_count_sub()
3666 * and it also uses preempt_enable/disable_notrace(), if
3667 * NEED_RESCHED is set, the preempt_enable_notrace() called
3668 * by the function tracer will call this function again and
3669 * cause infinite recursion.
3671 * Preemption must be disabled here before the function
3672 * tracer can trace. Break up preempt_disable() into two
3673 * calls. One to disable preemption without fear of being
3674 * traced. The other to still record the preemption latency,
3675 * which can also be traced by the function tracer.
3677 preempt_disable_notrace();
3678 preempt_latency_start(1);
3680 preempt_latency_stop(1);
3681 preempt_enable_no_resched_notrace();
3684 * Check again in case we missed a preemption opportunity
3685 * between schedule and now.
3687 } while (need_resched());
3690 #ifdef CONFIG_PREEMPT
3692 * this is the entry point to schedule() from in-kernel preemption
3693 * off of preempt_enable. Kernel preemptions off return from interrupt
3694 * occur there and call schedule directly.
3696 asmlinkage __visible void __sched notrace preempt_schedule(void)
3699 * If there is a non-zero preempt_count or interrupts are disabled,
3700 * we do not want to preempt the current task. Just return..
3702 if (likely(!preemptible()))
3705 preempt_schedule_common();
3707 NOKPROBE_SYMBOL(preempt_schedule);
3708 EXPORT_SYMBOL(preempt_schedule);
3711 * preempt_schedule_notrace - preempt_schedule called by tracing
3713 * The tracing infrastructure uses preempt_enable_notrace to prevent
3714 * recursion and tracing preempt enabling caused by the tracing
3715 * infrastructure itself. But as tracing can happen in areas coming
3716 * from userspace or just about to enter userspace, a preempt enable
3717 * can occur before user_exit() is called. This will cause the scheduler
3718 * to be called when the system is still in usermode.
3720 * To prevent this, the preempt_enable_notrace will use this function
3721 * instead of preempt_schedule() to exit user context if needed before
3722 * calling the scheduler.
3724 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3726 enum ctx_state prev_ctx;
3728 if (likely(!preemptible()))
3733 * Because the function tracer can trace preempt_count_sub()
3734 * and it also uses preempt_enable/disable_notrace(), if
3735 * NEED_RESCHED is set, the preempt_enable_notrace() called
3736 * by the function tracer will call this function again and
3737 * cause infinite recursion.
3739 * Preemption must be disabled here before the function
3740 * tracer can trace. Break up preempt_disable() into two
3741 * calls. One to disable preemption without fear of being
3742 * traced. The other to still record the preemption latency,
3743 * which can also be traced by the function tracer.
3745 preempt_disable_notrace();
3746 preempt_latency_start(1);
3748 * Needs preempt disabled in case user_exit() is traced
3749 * and the tracer calls preempt_enable_notrace() causing
3750 * an infinite recursion.
3752 prev_ctx = exception_enter();
3754 exception_exit(prev_ctx);
3756 preempt_latency_stop(1);
3757 preempt_enable_no_resched_notrace();
3758 } while (need_resched());
3760 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3762 #endif /* CONFIG_PREEMPT */
3765 * this is the entry point to schedule() from kernel preemption
3766 * off of irq context.
3767 * Note, that this is called and return with irqs disabled. This will
3768 * protect us against recursive calling from irq.
3770 asmlinkage __visible void __sched preempt_schedule_irq(void)
3772 enum ctx_state prev_state;
3774 /* Catch callers which need to be fixed */
3775 BUG_ON(preempt_count() || !irqs_disabled());
3777 prev_state = exception_enter();
3783 local_irq_disable();
3784 sched_preempt_enable_no_resched();
3785 } while (need_resched());
3787 exception_exit(prev_state);
3790 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3793 return try_to_wake_up(curr->private, mode, wake_flags);
3795 EXPORT_SYMBOL(default_wake_function);
3797 #ifdef CONFIG_RT_MUTEXES
3800 * rt_mutex_setprio - set the current priority of a task
3802 * @prio: prio value (kernel-internal form)
3804 * This function changes the 'effective' priority of a task. It does
3805 * not touch ->normal_prio like __setscheduler().
3807 * Used by the rt_mutex code to implement priority inheritance
3808 * logic. Call site only calls if the priority of the task changed.
3810 void rt_mutex_setprio(struct task_struct *p, int prio)
3812 int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
3813 const struct sched_class *prev_class;
3817 BUG_ON(prio > MAX_PRIO);
3819 rq = __task_rq_lock(p, &rf);
3822 * Idle task boosting is a nono in general. There is one
3823 * exception, when PREEMPT_RT and NOHZ is active:
3825 * The idle task calls get_next_timer_interrupt() and holds
3826 * the timer wheel base->lock on the CPU and another CPU wants
3827 * to access the timer (probably to cancel it). We can safely
3828 * ignore the boosting request, as the idle CPU runs this code
3829 * with interrupts disabled and will complete the lock
3830 * protected section without being interrupted. So there is no
3831 * real need to boost.
3833 if (unlikely(p == rq->idle)) {
3834 WARN_ON(p != rq->curr);
3835 WARN_ON(p->pi_blocked_on);
3839 trace_sched_pi_setprio(p, prio);
3842 if (oldprio == prio)
3843 queue_flag &= ~DEQUEUE_MOVE;
3845 prev_class = p->sched_class;
3846 queued = task_on_rq_queued(p);
3847 running = task_current(rq, p);
3849 dequeue_task(rq, p, queue_flag);
3851 put_prev_task(rq, p);
3854 * Boosting condition are:
3855 * 1. -rt task is running and holds mutex A
3856 * --> -dl task blocks on mutex A
3858 * 2. -dl task is running and holds mutex A
3859 * --> -dl task blocks on mutex A and could preempt the
3862 if (dl_prio(prio)) {
3863 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3864 if (!dl_prio(p->normal_prio) ||
3865 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3866 p->dl.dl_boosted = 1;
3867 queue_flag |= ENQUEUE_REPLENISH;
3869 p->dl.dl_boosted = 0;
3870 p->sched_class = &dl_sched_class;
3871 } else if (rt_prio(prio)) {
3872 if (dl_prio(oldprio))
3873 p->dl.dl_boosted = 0;
3875 queue_flag |= ENQUEUE_HEAD;
3876 p->sched_class = &rt_sched_class;
3878 if (dl_prio(oldprio))
3879 p->dl.dl_boosted = 0;
3880 if (rt_prio(oldprio))
3882 p->sched_class = &fair_sched_class;
3888 enqueue_task(rq, p, queue_flag);
3890 set_curr_task(rq, p);
3892 check_class_changed(rq, p, prev_class, oldprio);
3894 preempt_disable(); /* avoid rq from going away on us */
3895 __task_rq_unlock(rq, &rf);
3897 balance_callback(rq);
3902 void set_user_nice(struct task_struct *p, long nice)
3904 bool queued, running;
3905 int old_prio, delta;
3909 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3912 * We have to be careful, if called from sys_setpriority(),
3913 * the task might be in the middle of scheduling on another CPU.
3915 rq = task_rq_lock(p, &rf);
3917 * The RT priorities are set via sched_setscheduler(), but we still
3918 * allow the 'normal' nice value to be set - but as expected
3919 * it wont have any effect on scheduling until the task is
3920 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3922 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3923 p->static_prio = NICE_TO_PRIO(nice);
3926 queued = task_on_rq_queued(p);
3927 running = task_current(rq, p);
3929 dequeue_task(rq, p, DEQUEUE_SAVE);
3931 put_prev_task(rq, p);
3933 p->static_prio = NICE_TO_PRIO(nice);
3936 p->prio = effective_prio(p);
3937 delta = p->prio - old_prio;
3940 enqueue_task(rq, p, ENQUEUE_RESTORE);
3942 * If the task increased its priority or is running and
3943 * lowered its priority, then reschedule its CPU:
3945 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3949 set_curr_task(rq, p);
3951 task_rq_unlock(rq, p, &rf);
3953 EXPORT_SYMBOL(set_user_nice);
3956 * can_nice - check if a task can reduce its nice value
3960 int can_nice(const struct task_struct *p, const int nice)
3962 /* convert nice value [19,-20] to rlimit style value [1,40] */
3963 int nice_rlim = nice_to_rlimit(nice);
3965 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3966 capable(CAP_SYS_NICE));
3969 #ifdef __ARCH_WANT_SYS_NICE
3972 * sys_nice - change the priority of the current process.
3973 * @increment: priority increment
3975 * sys_setpriority is a more generic, but much slower function that
3976 * does similar things.
3978 SYSCALL_DEFINE1(nice, int, increment)
3983 * Setpriority might change our priority at the same moment.
3984 * We don't have to worry. Conceptually one call occurs first
3985 * and we have a single winner.
3987 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3988 nice = task_nice(current) + increment;
3990 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3991 if (increment < 0 && !can_nice(current, nice))
3994 retval = security_task_setnice(current, nice);
3998 set_user_nice(current, nice);
4005 * task_prio - return the priority value of a given task.
4006 * @p: the task in question.
4008 * Return: The priority value as seen by users in /proc.
4009 * RT tasks are offset by -200. Normal tasks are centered
4010 * around 0, value goes from -16 to +15.
4012 int task_prio(const struct task_struct *p)
4014 return p->prio - MAX_RT_PRIO;
4018 * idle_cpu - is a given cpu idle currently?
4019 * @cpu: the processor in question.
4021 * Return: 1 if the CPU is currently idle. 0 otherwise.
4023 int idle_cpu(int cpu)
4025 struct rq *rq = cpu_rq(cpu);
4027 if (rq->curr != rq->idle)
4034 if (!llist_empty(&rq->wake_list))
4042 * idle_task - return the idle task for a given cpu.
4043 * @cpu: the processor in question.
4045 * Return: The idle task for the cpu @cpu.
4047 struct task_struct *idle_task(int cpu)
4049 return cpu_rq(cpu)->idle;
4053 * find_process_by_pid - find a process with a matching PID value.
4054 * @pid: the pid in question.
4056 * The task of @pid, if found. %NULL otherwise.
4058 static struct task_struct *find_process_by_pid(pid_t pid)
4060 return pid ? find_task_by_vpid(pid) : current;
4064 * This function initializes the sched_dl_entity of a newly becoming
4065 * SCHED_DEADLINE task.
4067 * Only the static values are considered here, the actual runtime and the
4068 * absolute deadline will be properly calculated when the task is enqueued
4069 * for the first time with its new policy.
4072 __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
4074 struct sched_dl_entity *dl_se = &p->dl;
4076 dl_se->dl_runtime = attr->sched_runtime;
4077 dl_se->dl_deadline = attr->sched_deadline;
4078 dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
4079 dl_se->flags = attr->sched_flags;
4080 dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
4083 * Changing the parameters of a task is 'tricky' and we're not doing
4084 * the correct thing -- also see task_dead_dl() and switched_from_dl().
4086 * What we SHOULD do is delay the bandwidth release until the 0-lag
4087 * point. This would include retaining the task_struct until that time
4088 * and change dl_overflow() to not immediately decrement the current
4091 * Instead we retain the current runtime/deadline and let the new
4092 * parameters take effect after the current reservation period lapses.
4093 * This is safe (albeit pessimistic) because the 0-lag point is always
4094 * before the current scheduling deadline.
4096 * We can still have temporary overloads because we do not delay the
4097 * change in bandwidth until that time; so admission control is
4098 * not on the safe side. It does however guarantee tasks will never
4099 * consume more than promised.
4104 * sched_setparam() passes in -1 for its policy, to let the functions
4105 * it calls know not to change it.
4107 #define SETPARAM_POLICY -1
4109 static void __setscheduler_params(struct task_struct *p,
4110 const struct sched_attr *attr)
4112 int policy = attr->sched_policy;
4114 if (policy == SETPARAM_POLICY)
4119 if (dl_policy(policy))
4120 __setparam_dl(p, attr);
4121 else if (fair_policy(policy))
4122 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4125 * __sched_setscheduler() ensures attr->sched_priority == 0 when
4126 * !rt_policy. Always setting this ensures that things like
4127 * getparam()/getattr() don't report silly values for !rt tasks.
4129 p->rt_priority = attr->sched_priority;
4130 p->normal_prio = normal_prio(p);
4134 /* Actually do priority change: must hold pi & rq lock. */
4135 static void __setscheduler(struct rq *rq, struct task_struct *p,
4136 const struct sched_attr *attr, bool keep_boost)
4138 __setscheduler_params(p, attr);
4141 * Keep a potential priority boosting if called from
4142 * sched_setscheduler().
4145 p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
4147 p->prio = normal_prio(p);
4149 if (dl_prio(p->prio))
4150 p->sched_class = &dl_sched_class;
4151 else if (rt_prio(p->prio))
4152 p->sched_class = &rt_sched_class;
4154 p->sched_class = &fair_sched_class;
4158 __getparam_dl(struct task_struct *p, struct sched_attr *attr)
4160 struct sched_dl_entity *dl_se = &p->dl;
4162 attr->sched_priority = p->rt_priority;
4163 attr->sched_runtime = dl_se->dl_runtime;
4164 attr->sched_deadline = dl_se->dl_deadline;
4165 attr->sched_period = dl_se->dl_period;
4166 attr->sched_flags = dl_se->flags;
4170 * This function validates the new parameters of a -deadline task.
4171 * We ask for the deadline not being zero, and greater or equal
4172 * than the runtime, as well as the period of being zero or
4173 * greater than deadline. Furthermore, we have to be sure that
4174 * user parameters are above the internal resolution of 1us (we
4175 * check sched_runtime only since it is always the smaller one) and
4176 * below 2^63 ns (we have to check both sched_deadline and
4177 * sched_period, as the latter can be zero).
4180 __checkparam_dl(const struct sched_attr *attr)
4183 if (attr->sched_deadline == 0)
4187 * Since we truncate DL_SCALE bits, make sure we're at least
4190 if (attr->sched_runtime < (1ULL << DL_SCALE))
4194 * Since we use the MSB for wrap-around and sign issues, make
4195 * sure it's not set (mind that period can be equal to zero).
4197 if (attr->sched_deadline & (1ULL << 63) ||
4198 attr->sched_period & (1ULL << 63))
4201 /* runtime <= deadline <= period (if period != 0) */
4202 if ((attr->sched_period != 0 &&
4203 attr->sched_period < attr->sched_deadline) ||
4204 attr->sched_deadline < attr->sched_runtime)
4211 * check the target process has a UID that matches the current process's
4213 static bool check_same_owner(struct task_struct *p)
4215 const struct cred *cred = current_cred(), *pcred;
4219 pcred = __task_cred(p);
4220 match = (uid_eq(cred->euid, pcred->euid) ||
4221 uid_eq(cred->euid, pcred->uid));
4226 static bool dl_param_changed(struct task_struct *p,
4227 const struct sched_attr *attr)
4229 struct sched_dl_entity *dl_se = &p->dl;
4231 if (dl_se->dl_runtime != attr->sched_runtime ||
4232 dl_se->dl_deadline != attr->sched_deadline ||
4233 dl_se->dl_period != attr->sched_period ||
4234 dl_se->flags != attr->sched_flags)
4240 static int __sched_setscheduler(struct task_struct *p,
4241 const struct sched_attr *attr,
4244 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4245 MAX_RT_PRIO - 1 - attr->sched_priority;
4246 int retval, oldprio, oldpolicy = -1, queued, running;
4247 int new_effective_prio, policy = attr->sched_policy;
4248 const struct sched_class *prev_class;
4251 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
4254 /* may grab non-irq protected spin_locks */
4255 BUG_ON(in_interrupt());
4257 /* double check policy once rq lock held */
4259 reset_on_fork = p->sched_reset_on_fork;
4260 policy = oldpolicy = p->policy;
4262 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4264 if (!valid_policy(policy))
4268 if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
4272 * Valid priorities for SCHED_FIFO and SCHED_RR are
4273 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4274 * SCHED_BATCH and SCHED_IDLE is 0.
4276 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4277 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4279 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4280 (rt_policy(policy) != (attr->sched_priority != 0)))
4284 * Allow unprivileged RT tasks to decrease priority:
4286 if (user && !capable(CAP_SYS_NICE)) {
4287 if (fair_policy(policy)) {
4288 if (attr->sched_nice < task_nice(p) &&
4289 !can_nice(p, attr->sched_nice))
4293 if (rt_policy(policy)) {
4294 unsigned long rlim_rtprio =
4295 task_rlimit(p, RLIMIT_RTPRIO);
4297 /* can't set/change the rt policy */
4298 if (policy != p->policy && !rlim_rtprio)
4301 /* can't increase priority */
4302 if (attr->sched_priority > p->rt_priority &&
4303 attr->sched_priority > rlim_rtprio)
4308 * Can't set/change SCHED_DEADLINE policy at all for now
4309 * (safest behavior); in the future we would like to allow
4310 * unprivileged DL tasks to increase their relative deadline
4311 * or reduce their runtime (both ways reducing utilization)
4313 if (dl_policy(policy))
4317 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4318 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4320 if (idle_policy(p->policy) && !idle_policy(policy)) {
4321 if (!can_nice(p, task_nice(p)))
4325 /* can't change other user's priorities */
4326 if (!check_same_owner(p))
4329 /* Normal users shall not reset the sched_reset_on_fork flag */
4330 if (p->sched_reset_on_fork && !reset_on_fork)
4335 retval = security_task_setscheduler(p);
4341 * make sure no PI-waiters arrive (or leave) while we are
4342 * changing the priority of the task:
4344 * To be able to change p->policy safely, the appropriate
4345 * runqueue lock must be held.
4347 rq = task_rq_lock(p, &rf);
4350 * Changing the policy of the stop threads its a very bad idea
4352 if (p == rq->stop) {
4353 task_rq_unlock(rq, p, &rf);
4358 * If not changing anything there's no need to proceed further,
4359 * but store a possible modification of reset_on_fork.
4361 if (unlikely(policy == p->policy)) {
4362 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4364 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4366 if (dl_policy(policy) && dl_param_changed(p, attr))
4369 p->sched_reset_on_fork = reset_on_fork;
4370 task_rq_unlock(rq, p, &rf);
4376 #ifdef CONFIG_RT_GROUP_SCHED
4378 * Do not allow realtime tasks into groups that have no runtime
4381 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4382 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4383 !task_group_is_autogroup(task_group(p))) {
4384 task_rq_unlock(rq, p, &rf);
4389 if (dl_bandwidth_enabled() && dl_policy(policy)) {
4390 cpumask_t *span = rq->rd->span;
4393 * Don't allow tasks with an affinity mask smaller than
4394 * the entire root_domain to become SCHED_DEADLINE. We
4395 * will also fail if there's no bandwidth available.
4397 if (!cpumask_subset(span, &p->cpus_allowed) ||
4398 rq->rd->dl_bw.bw == 0) {
4399 task_rq_unlock(rq, p, &rf);
4406 /* recheck policy now with rq lock held */
4407 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4408 policy = oldpolicy = -1;
4409 task_rq_unlock(rq, p, &rf);
4414 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4415 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4418 if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
4419 task_rq_unlock(rq, p, &rf);
4423 p->sched_reset_on_fork = reset_on_fork;
4428 * Take priority boosted tasks into account. If the new
4429 * effective priority is unchanged, we just store the new
4430 * normal parameters and do not touch the scheduler class and
4431 * the runqueue. This will be done when the task deboost
4434 new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
4435 if (new_effective_prio == oldprio)
4436 queue_flags &= ~DEQUEUE_MOVE;
4439 queued = task_on_rq_queued(p);
4440 running = task_current(rq, p);
4442 dequeue_task(rq, p, queue_flags);
4444 put_prev_task(rq, p);
4446 prev_class = p->sched_class;
4447 __setscheduler(rq, p, attr, pi);
4451 * We enqueue to tail when the priority of a task is
4452 * increased (user space view).
4454 if (oldprio < p->prio)
4455 queue_flags |= ENQUEUE_HEAD;
4457 enqueue_task(rq, p, queue_flags);
4460 set_curr_task(rq, p);
4462 check_class_changed(rq, p, prev_class, oldprio);
4463 preempt_disable(); /* avoid rq from going away on us */
4464 task_rq_unlock(rq, p, &rf);
4467 rt_mutex_adjust_pi(p);
4470 * Run balance callbacks after we've adjusted the PI chain.
4472 balance_callback(rq);
4478 static int _sched_setscheduler(struct task_struct *p, int policy,
4479 const struct sched_param *param, bool check)
4481 struct sched_attr attr = {
4482 .sched_policy = policy,
4483 .sched_priority = param->sched_priority,
4484 .sched_nice = PRIO_TO_NICE(p->static_prio),
4487 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4488 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4489 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4490 policy &= ~SCHED_RESET_ON_FORK;
4491 attr.sched_policy = policy;
4494 return __sched_setscheduler(p, &attr, check, true);
4497 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4498 * @p: the task in question.
4499 * @policy: new policy.
4500 * @param: structure containing the new RT priority.
4502 * Return: 0 on success. An error code otherwise.
4504 * NOTE that the task may be already dead.
4506 int sched_setscheduler(struct task_struct *p, int policy,
4507 const struct sched_param *param)
4509 return _sched_setscheduler(p, policy, param, true);
4511 EXPORT_SYMBOL_GPL(sched_setscheduler);
4513 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4515 return __sched_setscheduler(p, attr, true, true);
4517 EXPORT_SYMBOL_GPL(sched_setattr);
4520 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4521 * @p: the task in question.
4522 * @policy: new policy.
4523 * @param: structure containing the new RT priority.
4525 * Just like sched_setscheduler, only don't bother checking if the
4526 * current context has permission. For example, this is needed in
4527 * stop_machine(): we create temporary high priority worker threads,
4528 * but our caller might not have that capability.
4530 * Return: 0 on success. An error code otherwise.
4532 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4533 const struct sched_param *param)
4535 return _sched_setscheduler(p, policy, param, false);
4537 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4540 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4542 struct sched_param lparam;
4543 struct task_struct *p;
4546 if (!param || pid < 0)
4548 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4553 p = find_process_by_pid(pid);
4555 retval = sched_setscheduler(p, policy, &lparam);
4562 * Mimics kernel/events/core.c perf_copy_attr().
4564 static int sched_copy_attr(struct sched_attr __user *uattr,
4565 struct sched_attr *attr)
4570 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4574 * zero the full structure, so that a short copy will be nice.
4576 memset(attr, 0, sizeof(*attr));
4578 ret = get_user(size, &uattr->size);
4582 if (size > PAGE_SIZE) /* silly large */
4585 if (!size) /* abi compat */
4586 size = SCHED_ATTR_SIZE_VER0;
4588 if (size < SCHED_ATTR_SIZE_VER0)
4592 * If we're handed a bigger struct than we know of,
4593 * ensure all the unknown bits are 0 - i.e. new
4594 * user-space does not rely on any kernel feature
4595 * extensions we dont know about yet.
4597 if (size > sizeof(*attr)) {
4598 unsigned char __user *addr;
4599 unsigned char __user *end;
4602 addr = (void __user *)uattr + sizeof(*attr);
4603 end = (void __user *)uattr + size;
4605 for (; addr < end; addr++) {
4606 ret = get_user(val, addr);
4612 size = sizeof(*attr);
4615 ret = copy_from_user(attr, uattr, size);
4620 * XXX: do we want to be lenient like existing syscalls; or do we want
4621 * to be strict and return an error on out-of-bounds values?
4623 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4628 put_user(sizeof(*attr), &uattr->size);
4633 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4634 * @pid: the pid in question.
4635 * @policy: new policy.
4636 * @param: structure containing the new RT priority.
4638 * Return: 0 on success. An error code otherwise.
4640 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4641 struct sched_param __user *, param)
4643 /* negative values for policy are not valid */
4647 return do_sched_setscheduler(pid, policy, param);
4651 * sys_sched_setparam - set/change the RT priority of a thread
4652 * @pid: the pid in question.
4653 * @param: structure containing the new RT priority.
4655 * Return: 0 on success. An error code otherwise.
4657 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4659 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4663 * sys_sched_setattr - same as above, but with extended sched_attr
4664 * @pid: the pid in question.
4665 * @uattr: structure containing the extended parameters.
4666 * @flags: for future extension.
4668 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4669 unsigned int, flags)
4671 struct sched_attr attr;
4672 struct task_struct *p;
4675 if (!uattr || pid < 0 || flags)
4678 retval = sched_copy_attr(uattr, &attr);
4682 if ((int)attr.sched_policy < 0)
4687 p = find_process_by_pid(pid);
4689 retval = sched_setattr(p, &attr);
4696 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4697 * @pid: the pid in question.
4699 * Return: On success, the policy of the thread. Otherwise, a negative error
4702 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4704 struct task_struct *p;
4712 p = find_process_by_pid(pid);
4714 retval = security_task_getscheduler(p);
4717 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4724 * sys_sched_getparam - get the RT priority of a thread
4725 * @pid: the pid in question.
4726 * @param: structure containing the RT priority.
4728 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4731 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4733 struct sched_param lp = { .sched_priority = 0 };
4734 struct task_struct *p;
4737 if (!param || pid < 0)
4741 p = find_process_by_pid(pid);
4746 retval = security_task_getscheduler(p);
4750 if (task_has_rt_policy(p))
4751 lp.sched_priority = p->rt_priority;
4755 * This one might sleep, we cannot do it with a spinlock held ...
4757 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4766 static int sched_read_attr(struct sched_attr __user *uattr,
4767 struct sched_attr *attr,
4772 if (!access_ok(VERIFY_WRITE, uattr, usize))
4776 * If we're handed a smaller struct than we know of,
4777 * ensure all the unknown bits are 0 - i.e. old
4778 * user-space does not get uncomplete information.
4780 if (usize < sizeof(*attr)) {
4781 unsigned char *addr;
4784 addr = (void *)attr + usize;
4785 end = (void *)attr + sizeof(*attr);
4787 for (; addr < end; addr++) {
4795 ret = copy_to_user(uattr, attr, attr->size);
4803 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4804 * @pid: the pid in question.
4805 * @uattr: structure containing the extended parameters.
4806 * @size: sizeof(attr) for fwd/bwd comp.
4807 * @flags: for future extension.
4809 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4810 unsigned int, size, unsigned int, flags)
4812 struct sched_attr attr = {
4813 .size = sizeof(struct sched_attr),
4815 struct task_struct *p;
4818 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4819 size < SCHED_ATTR_SIZE_VER0 || flags)
4823 p = find_process_by_pid(pid);
4828 retval = security_task_getscheduler(p);
4832 attr.sched_policy = p->policy;
4833 if (p->sched_reset_on_fork)
4834 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4835 if (task_has_dl_policy(p))
4836 __getparam_dl(p, &attr);
4837 else if (task_has_rt_policy(p))
4838 attr.sched_priority = p->rt_priority;
4840 attr.sched_nice = task_nice(p);
4844 retval = sched_read_attr(uattr, &attr, size);
4852 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4854 cpumask_var_t cpus_allowed, new_mask;
4855 struct task_struct *p;
4860 p = find_process_by_pid(pid);
4866 /* Prevent p going away */
4870 if (p->flags & PF_NO_SETAFFINITY) {
4874 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4878 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4880 goto out_free_cpus_allowed;
4883 if (!check_same_owner(p)) {
4885 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4887 goto out_free_new_mask;
4892 retval = security_task_setscheduler(p);
4894 goto out_free_new_mask;
4897 cpuset_cpus_allowed(p, cpus_allowed);
4898 cpumask_and(new_mask, in_mask, cpus_allowed);
4901 * Since bandwidth control happens on root_domain basis,
4902 * if admission test is enabled, we only admit -deadline
4903 * tasks allowed to run on all the CPUs in the task's
4907 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4909 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4912 goto out_free_new_mask;
4918 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4921 cpuset_cpus_allowed(p, cpus_allowed);
4922 if (!cpumask_subset(new_mask, cpus_allowed)) {
4924 * We must have raced with a concurrent cpuset
4925 * update. Just reset the cpus_allowed to the
4926 * cpuset's cpus_allowed
4928 cpumask_copy(new_mask, cpus_allowed);
4933 free_cpumask_var(new_mask);
4934 out_free_cpus_allowed:
4935 free_cpumask_var(cpus_allowed);
4941 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4942 struct cpumask *new_mask)
4944 if (len < cpumask_size())
4945 cpumask_clear(new_mask);
4946 else if (len > cpumask_size())
4947 len = cpumask_size();
4949 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4953 * sys_sched_setaffinity - set the cpu affinity of a process
4954 * @pid: pid of the process
4955 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4956 * @user_mask_ptr: user-space pointer to the new cpu mask
4958 * Return: 0 on success. An error code otherwise.
4960 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4961 unsigned long __user *, user_mask_ptr)
4963 cpumask_var_t new_mask;
4966 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4969 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4971 retval = sched_setaffinity(pid, new_mask);
4972 free_cpumask_var(new_mask);
4976 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4978 struct task_struct *p;
4979 unsigned long flags;
4985 p = find_process_by_pid(pid);
4989 retval = security_task_getscheduler(p);
4993 raw_spin_lock_irqsave(&p->pi_lock, flags);
4994 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4995 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5004 * sys_sched_getaffinity - get the cpu affinity of a process
5005 * @pid: pid of the process
5006 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5007 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5009 * Return: size of CPU mask copied to user_mask_ptr on success. An
5010 * error code otherwise.
5012 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5013 unsigned long __user *, user_mask_ptr)
5018 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5020 if (len & (sizeof(unsigned long)-1))
5023 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5026 ret = sched_getaffinity(pid, mask);
5028 size_t retlen = min_t(size_t, len, cpumask_size());
5030 if (copy_to_user(user_mask_ptr, mask, retlen))
5035 free_cpumask_var(mask);
5041 * sys_sched_yield - yield the current processor to other threads.
5043 * This function yields the current CPU to other tasks. If there are no
5044 * other threads running on this CPU then this function will return.
5048 SYSCALL_DEFINE0(sched_yield)
5050 struct rq *rq = this_rq_lock();
5052 schedstat_inc(rq->yld_count);
5053 current->sched_class->yield_task(rq);
5056 * Since we are going to call schedule() anyway, there's
5057 * no need to preempt or enable interrupts:
5059 __release(rq->lock);
5060 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5061 do_raw_spin_unlock(&rq->lock);
5062 sched_preempt_enable_no_resched();
5069 #ifndef CONFIG_PREEMPT
5070 int __sched _cond_resched(void)
5072 if (should_resched(0)) {
5073 preempt_schedule_common();
5078 EXPORT_SYMBOL(_cond_resched);
5082 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5083 * call schedule, and on return reacquire the lock.
5085 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5086 * operations here to prevent schedule() from being called twice (once via
5087 * spin_unlock(), once by hand).
5089 int __cond_resched_lock(spinlock_t *lock)
5091 int resched = should_resched(PREEMPT_LOCK_OFFSET);
5094 lockdep_assert_held(lock);
5096 if (spin_needbreak(lock) || resched) {
5099 preempt_schedule_common();
5107 EXPORT_SYMBOL(__cond_resched_lock);
5109 int __sched __cond_resched_softirq(void)
5111 BUG_ON(!in_softirq());
5113 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
5115 preempt_schedule_common();
5121 EXPORT_SYMBOL(__cond_resched_softirq);
5124 * yield - yield the current processor to other threads.
5126 * Do not ever use this function, there's a 99% chance you're doing it wrong.
5128 * The scheduler is at all times free to pick the calling task as the most
5129 * eligible task to run, if removing the yield() call from your code breaks
5130 * it, its already broken.
5132 * Typical broken usage is:
5137 * where one assumes that yield() will let 'the other' process run that will
5138 * make event true. If the current task is a SCHED_FIFO task that will never
5139 * happen. Never use yield() as a progress guarantee!!
5141 * If you want to use yield() to wait for something, use wait_event().
5142 * If you want to use yield() to be 'nice' for others, use cond_resched().
5143 * If you still want to use yield(), do not!
5145 void __sched yield(void)
5147 set_current_state(TASK_RUNNING);
5150 EXPORT_SYMBOL(yield);
5153 * yield_to - yield the current processor to another thread in
5154 * your thread group, or accelerate that thread toward the
5155 * processor it's on.
5157 * @preempt: whether task preemption is allowed or not
5159 * It's the caller's job to ensure that the target task struct
5160 * can't go away on us before we can do any checks.
5163 * true (>0) if we indeed boosted the target task.
5164 * false (0) if we failed to boost the target.
5165 * -ESRCH if there's no task to yield to.
5167 int __sched yield_to(struct task_struct *p, bool preempt)
5169 struct task_struct *curr = current;
5170 struct rq *rq, *p_rq;
5171 unsigned long flags;
5174 local_irq_save(flags);
5180 * If we're the only runnable task on the rq and target rq also
5181 * has only one task, there's absolutely no point in yielding.
5183 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5188 double_rq_lock(rq, p_rq);
5189 if (task_rq(p) != p_rq) {
5190 double_rq_unlock(rq, p_rq);
5194 if (!curr->sched_class->yield_to_task)
5197 if (curr->sched_class != p->sched_class)
5200 if (task_running(p_rq, p) || p->state)
5203 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5205 schedstat_inc(rq->yld_count);
5207 * Make p's CPU reschedule; pick_next_entity takes care of
5210 if (preempt && rq != p_rq)
5215 double_rq_unlock(rq, p_rq);
5217 local_irq_restore(flags);
5224 EXPORT_SYMBOL_GPL(yield_to);
5227 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5228 * that process accounting knows that this is a task in IO wait state.
5230 long __sched io_schedule_timeout(long timeout)
5232 int old_iowait = current->in_iowait;
5236 current->in_iowait = 1;
5237 blk_schedule_flush_plug(current);
5239 delayacct_blkio_start();
5241 atomic_inc(&rq->nr_iowait);
5242 ret = schedule_timeout(timeout);
5243 current->in_iowait = old_iowait;
5244 atomic_dec(&rq->nr_iowait);
5245 delayacct_blkio_end();
5249 EXPORT_SYMBOL(io_schedule_timeout);
5252 * sys_sched_get_priority_max - return maximum RT priority.
5253 * @policy: scheduling class.
5255 * Return: On success, this syscall returns the maximum
5256 * rt_priority that can be used by a given scheduling class.
5257 * On failure, a negative error code is returned.
5259 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5266 ret = MAX_USER_RT_PRIO-1;
5268 case SCHED_DEADLINE:
5279 * sys_sched_get_priority_min - return minimum RT priority.
5280 * @policy: scheduling class.
5282 * Return: On success, this syscall returns the minimum
5283 * rt_priority that can be used by a given scheduling class.
5284 * On failure, a negative error code is returned.
5286 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5295 case SCHED_DEADLINE:
5305 * sys_sched_rr_get_interval - return the default timeslice of a process.
5306 * @pid: pid of the process.
5307 * @interval: userspace pointer to the timeslice value.
5309 * this syscall writes the default timeslice value of a given process
5310 * into the user-space timespec buffer. A value of '0' means infinity.
5312 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5315 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5316 struct timespec __user *, interval)
5318 struct task_struct *p;
5319 unsigned int time_slice;
5330 p = find_process_by_pid(pid);
5334 retval = security_task_getscheduler(p);
5338 rq = task_rq_lock(p, &rf);
5340 if (p->sched_class->get_rr_interval)
5341 time_slice = p->sched_class->get_rr_interval(rq, p);
5342 task_rq_unlock(rq, p, &rf);
5345 jiffies_to_timespec(time_slice, &t);
5346 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5354 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5356 void sched_show_task(struct task_struct *p)
5358 unsigned long free = 0;
5360 unsigned long state = p->state;
5362 if (!try_get_task_stack(p))
5365 state = __ffs(state) + 1;
5366 printk(KERN_INFO "%-15.15s %c", p->comm,
5367 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5368 if (state == TASK_RUNNING)
5369 printk(KERN_CONT " running task ");
5370 #ifdef CONFIG_DEBUG_STACK_USAGE
5371 free = stack_not_used(p);
5376 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5378 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5379 task_pid_nr(p), ppid,
5380 (unsigned long)task_thread_info(p)->flags);
5382 print_worker_info(KERN_INFO, p);
5383 show_stack(p, NULL);
5387 void show_state_filter(unsigned long state_filter)
5389 struct task_struct *g, *p;
5391 #if BITS_PER_LONG == 32
5393 " task PC stack pid father\n");
5396 " task PC stack pid father\n");
5399 for_each_process_thread(g, p) {
5401 * reset the NMI-timeout, listing all files on a slow
5402 * console might take a lot of time:
5403 * Also, reset softlockup watchdogs on all CPUs, because
5404 * another CPU might be blocked waiting for us to process
5407 touch_nmi_watchdog();
5408 touch_all_softlockup_watchdogs();
5409 if (!state_filter || (p->state & state_filter))
5413 #ifdef CONFIG_SCHED_DEBUG
5415 sysrq_sched_debug_show();
5419 * Only show locks if all tasks are dumped:
5422 debug_show_all_locks();
5425 void init_idle_bootup_task(struct task_struct *idle)
5427 idle->sched_class = &idle_sched_class;
5431 * init_idle - set up an idle thread for a given CPU
5432 * @idle: task in question
5433 * @cpu: cpu the idle task belongs to
5435 * NOTE: this function does not set the idle thread's NEED_RESCHED
5436 * flag, to make booting more robust.
5438 void init_idle(struct task_struct *idle, int cpu)
5440 struct rq *rq = cpu_rq(cpu);
5441 unsigned long flags;
5443 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5444 raw_spin_lock(&rq->lock);
5446 __sched_fork(0, idle);
5447 idle->state = TASK_RUNNING;
5448 idle->se.exec_start = sched_clock();
5450 kasan_unpoison_task_stack(idle);
5454 * Its possible that init_idle() gets called multiple times on a task,
5455 * in that case do_set_cpus_allowed() will not do the right thing.
5457 * And since this is boot we can forgo the serialization.
5459 set_cpus_allowed_common(idle, cpumask_of(cpu));
5462 * We're having a chicken and egg problem, even though we are
5463 * holding rq->lock, the cpu isn't yet set to this cpu so the
5464 * lockdep check in task_group() will fail.
5466 * Similar case to sched_fork(). / Alternatively we could
5467 * use task_rq_lock() here and obtain the other rq->lock.
5472 __set_task_cpu(idle, cpu);
5475 rq->curr = rq->idle = idle;
5476 idle->on_rq = TASK_ON_RQ_QUEUED;
5480 raw_spin_unlock(&rq->lock);
5481 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5483 /* Set the preempt count _outside_ the spinlocks! */
5484 init_idle_preempt_count(idle, cpu);
5487 * The idle tasks have their own, simple scheduling class:
5489 idle->sched_class = &idle_sched_class;
5490 ftrace_graph_init_idle_task(idle, cpu);
5491 vtime_init_idle(idle, cpu);
5493 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5497 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5498 const struct cpumask *trial)
5500 int ret = 1, trial_cpus;
5501 struct dl_bw *cur_dl_b;
5502 unsigned long flags;
5504 if (!cpumask_weight(cur))
5507 rcu_read_lock_sched();
5508 cur_dl_b = dl_bw_of(cpumask_any(cur));
5509 trial_cpus = cpumask_weight(trial);
5511 raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
5512 if (cur_dl_b->bw != -1 &&
5513 cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
5515 raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
5516 rcu_read_unlock_sched();
5521 int task_can_attach(struct task_struct *p,
5522 const struct cpumask *cs_cpus_allowed)
5527 * Kthreads which disallow setaffinity shouldn't be moved
5528 * to a new cpuset; we don't want to change their cpu
5529 * affinity and isolating such threads by their set of
5530 * allowed nodes is unnecessary. Thus, cpusets are not
5531 * applicable for such threads. This prevents checking for
5532 * success of set_cpus_allowed_ptr() on all attached tasks
5533 * before cpus_allowed may be changed.
5535 if (p->flags & PF_NO_SETAFFINITY) {
5541 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5543 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
5548 unsigned long flags;
5550 rcu_read_lock_sched();
5551 dl_b = dl_bw_of(dest_cpu);
5552 raw_spin_lock_irqsave(&dl_b->lock, flags);
5553 cpus = dl_bw_cpus(dest_cpu);
5554 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
5559 * We reserve space for this task in the destination
5560 * root_domain, as we can't fail after this point.
5561 * We will free resources in the source root_domain
5562 * later on (see set_cpus_allowed_dl()).
5564 __dl_add(dl_b, p->dl.dl_bw);
5566 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5567 rcu_read_unlock_sched();
5577 static bool sched_smp_initialized __read_mostly;
5579 #ifdef CONFIG_NUMA_BALANCING
5580 /* Migrate current task p to target_cpu */
5581 int migrate_task_to(struct task_struct *p, int target_cpu)
5583 struct migration_arg arg = { p, target_cpu };
5584 int curr_cpu = task_cpu(p);
5586 if (curr_cpu == target_cpu)
5589 if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
5592 /* TODO: This is not properly updating schedstats */
5594 trace_sched_move_numa(p, curr_cpu, target_cpu);
5595 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5599 * Requeue a task on a given node and accurately track the number of NUMA
5600 * tasks on the runqueues
5602 void sched_setnuma(struct task_struct *p, int nid)
5604 bool queued, running;
5608 rq = task_rq_lock(p, &rf);
5609 queued = task_on_rq_queued(p);
5610 running = task_current(rq, p);
5613 dequeue_task(rq, p, DEQUEUE_SAVE);
5615 put_prev_task(rq, p);
5617 p->numa_preferred_nid = nid;
5620 enqueue_task(rq, p, ENQUEUE_RESTORE);
5622 set_curr_task(rq, p);
5623 task_rq_unlock(rq, p, &rf);
5625 #endif /* CONFIG_NUMA_BALANCING */
5627 #ifdef CONFIG_HOTPLUG_CPU
5629 * Ensures that the idle task is using init_mm right before its cpu goes
5632 void idle_task_exit(void)
5634 struct mm_struct *mm = current->active_mm;
5636 BUG_ON(cpu_online(smp_processor_id()));
5638 if (mm != &init_mm) {
5639 switch_mm(mm, &init_mm, current);
5640 finish_arch_post_lock_switch();
5646 * Since this CPU is going 'away' for a while, fold any nr_active delta
5647 * we might have. Assumes we're called after migrate_tasks() so that the
5648 * nr_active count is stable. We need to take the teardown thread which
5649 * is calling this into account, so we hand in adjust = 1 to the load
5652 * Also see the comment "Global load-average calculations".
5654 static void calc_load_migrate(struct rq *rq)
5656 long delta = calc_load_fold_active(rq, 1);
5658 atomic_long_add(delta, &calc_load_tasks);
5661 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5665 static const struct sched_class fake_sched_class = {
5666 .put_prev_task = put_prev_task_fake,
5669 static struct task_struct fake_task = {
5671 * Avoid pull_{rt,dl}_task()
5673 .prio = MAX_PRIO + 1,
5674 .sched_class = &fake_sched_class,
5678 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5679 * try_to_wake_up()->select_task_rq().
5681 * Called with rq->lock held even though we'er in stop_machine() and
5682 * there's no concurrency possible, we hold the required locks anyway
5683 * because of lock validation efforts.
5685 static void migrate_tasks(struct rq *dead_rq)
5687 struct rq *rq = dead_rq;
5688 struct task_struct *next, *stop = rq->stop;
5689 struct pin_cookie cookie;
5693 * Fudge the rq selection such that the below task selection loop
5694 * doesn't get stuck on the currently eligible stop task.
5696 * We're currently inside stop_machine() and the rq is either stuck
5697 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5698 * either way we should never end up calling schedule() until we're
5704 * put_prev_task() and pick_next_task() sched
5705 * class method both need to have an up-to-date
5706 * value of rq->clock[_task]
5708 update_rq_clock(rq);
5712 * There's this thread running, bail when that's the only
5715 if (rq->nr_running == 1)
5719 * pick_next_task assumes pinned rq->lock.
5721 cookie = lockdep_pin_lock(&rq->lock);
5722 next = pick_next_task(rq, &fake_task, cookie);
5724 next->sched_class->put_prev_task(rq, next);
5727 * Rules for changing task_struct::cpus_allowed are holding
5728 * both pi_lock and rq->lock, such that holding either
5729 * stabilizes the mask.
5731 * Drop rq->lock is not quite as disastrous as it usually is
5732 * because !cpu_active at this point, which means load-balance
5733 * will not interfere. Also, stop-machine.
5735 lockdep_unpin_lock(&rq->lock, cookie);
5736 raw_spin_unlock(&rq->lock);
5737 raw_spin_lock(&next->pi_lock);
5738 raw_spin_lock(&rq->lock);
5741 * Since we're inside stop-machine, _nothing_ should have
5742 * changed the task, WARN if weird stuff happened, because in
5743 * that case the above rq->lock drop is a fail too.
5745 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5746 raw_spin_unlock(&next->pi_lock);
5750 /* Find suitable destination for @next, with force if needed. */
5751 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5753 rq = __migrate_task(rq, next, dest_cpu);
5754 if (rq != dead_rq) {
5755 raw_spin_unlock(&rq->lock);
5757 raw_spin_lock(&rq->lock);
5759 raw_spin_unlock(&next->pi_lock);
5764 #endif /* CONFIG_HOTPLUG_CPU */
5766 static void set_rq_online(struct rq *rq)
5769 const struct sched_class *class;
5771 cpumask_set_cpu(rq->cpu, rq->rd->online);
5774 for_each_class(class) {
5775 if (class->rq_online)
5776 class->rq_online(rq);
5781 static void set_rq_offline(struct rq *rq)
5784 const struct sched_class *class;
5786 for_each_class(class) {
5787 if (class->rq_offline)
5788 class->rq_offline(rq);
5791 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5796 static void set_cpu_rq_start_time(unsigned int cpu)
5798 struct rq *rq = cpu_rq(cpu);
5800 rq->age_stamp = sched_clock_cpu(cpu);
5803 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5805 #ifdef CONFIG_SCHED_DEBUG
5807 static __read_mostly int sched_debug_enabled;
5809 static int __init sched_debug_setup(char *str)
5811 sched_debug_enabled = 1;
5815 early_param("sched_debug", sched_debug_setup);
5817 static inline bool sched_debug(void)
5819 return sched_debug_enabled;
5822 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5823 struct cpumask *groupmask)
5825 struct sched_group *group = sd->groups;
5827 cpumask_clear(groupmask);
5829 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5831 if (!(sd->flags & SD_LOAD_BALANCE)) {
5832 printk("does not load-balance\n");
5834 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5839 printk(KERN_CONT "span %*pbl level %s\n",
5840 cpumask_pr_args(sched_domain_span(sd)), sd->name);
5842 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5843 printk(KERN_ERR "ERROR: domain->span does not contain "
5846 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5847 printk(KERN_ERR "ERROR: domain->groups does not contain"
5851 printk(KERN_DEBUG "%*s groups:", level + 1, "");
5855 printk(KERN_ERR "ERROR: group is NULL\n");
5859 if (!cpumask_weight(sched_group_cpus(group))) {
5860 printk(KERN_CONT "\n");
5861 printk(KERN_ERR "ERROR: empty group\n");
5865 if (!(sd->flags & SD_OVERLAP) &&
5866 cpumask_intersects(groupmask, sched_group_cpus(group))) {
5867 printk(KERN_CONT "\n");
5868 printk(KERN_ERR "ERROR: repeated CPUs\n");
5872 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5874 printk(KERN_CONT " %*pbl",
5875 cpumask_pr_args(sched_group_cpus(group)));
5876 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
5877 printk(KERN_CONT " (cpu_capacity = %lu)",
5878 group->sgc->capacity);
5881 group = group->next;
5882 } while (group != sd->groups);
5883 printk(KERN_CONT "\n");
5885 if (!cpumask_equal(sched_domain_span(sd), groupmask))
5886 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5889 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5890 printk(KERN_ERR "ERROR: parent span is not a superset "
5891 "of domain->span\n");
5895 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5899 if (!sched_debug_enabled)
5903 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5907 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5910 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5918 #else /* !CONFIG_SCHED_DEBUG */
5920 # define sched_debug_enabled 0
5921 # define sched_domain_debug(sd, cpu) do { } while (0)
5922 static inline bool sched_debug(void)
5926 #endif /* CONFIG_SCHED_DEBUG */
5928 static int sd_degenerate(struct sched_domain *sd)
5930 if (cpumask_weight(sched_domain_span(sd)) == 1)
5933 /* Following flags need at least 2 groups */
5934 if (sd->flags & (SD_LOAD_BALANCE |
5935 SD_BALANCE_NEWIDLE |
5938 SD_SHARE_CPUCAPACITY |
5939 SD_ASYM_CPUCAPACITY |
5940 SD_SHARE_PKG_RESOURCES |
5941 SD_SHARE_POWERDOMAIN |
5942 SD_SHARE_CAP_STATES)) {
5943 if (sd->groups != sd->groups->next)
5947 /* Following flags don't use groups */
5948 if (sd->flags & (SD_WAKE_AFFINE))
5955 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5957 unsigned long cflags = sd->flags, pflags = parent->flags;
5959 if (sd_degenerate(parent))
5962 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5965 /* Flags needing groups don't count if only 1 group in parent */
5966 if (parent->groups == parent->groups->next) {
5967 pflags &= ~(SD_LOAD_BALANCE |
5968 SD_BALANCE_NEWIDLE |
5971 SD_ASYM_CPUCAPACITY |
5972 SD_SHARE_CPUCAPACITY |
5973 SD_SHARE_PKG_RESOURCES |
5975 SD_SHARE_POWERDOMAIN |
5976 SD_SHARE_CAP_STATES);
5977 if (nr_node_ids == 1)
5978 pflags &= ~SD_SERIALIZE;
5980 if (~cflags & pflags)
5986 static void free_rootdomain(struct rcu_head *rcu)
5988 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5990 cpupri_cleanup(&rd->cpupri);
5991 cpudl_cleanup(&rd->cpudl);
5992 free_cpumask_var(rd->dlo_mask);
5993 free_cpumask_var(rd->rto_mask);
5994 free_cpumask_var(rd->online);
5995 free_cpumask_var(rd->span);
5999 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6001 struct root_domain *old_rd = NULL;
6002 unsigned long flags;
6004 raw_spin_lock_irqsave(&rq->lock, flags);
6009 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6012 cpumask_clear_cpu(rq->cpu, old_rd->span);
6015 * If we dont want to free the old_rd yet then
6016 * set old_rd to NULL to skip the freeing later
6019 if (!atomic_dec_and_test(&old_rd->refcount))
6023 atomic_inc(&rd->refcount);
6026 cpumask_set_cpu(rq->cpu, rd->span);
6027 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6030 raw_spin_unlock_irqrestore(&rq->lock, flags);
6033 call_rcu_sched(&old_rd->rcu, free_rootdomain);
6036 static int init_rootdomain(struct root_domain *rd)
6038 memset(rd, 0, sizeof(*rd));
6040 if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
6042 if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
6044 if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
6046 if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6049 init_dl_bw(&rd->dl_bw);
6050 if (cpudl_init(&rd->cpudl) != 0)
6053 if (cpupri_init(&rd->cpupri) != 0)
6056 init_max_cpu_capacity(&rd->max_cpu_capacity);
6058 rd->max_cap_orig_cpu = rd->min_cap_orig_cpu = -1;
6063 free_cpumask_var(rd->rto_mask);
6065 free_cpumask_var(rd->dlo_mask);
6067 free_cpumask_var(rd->online);
6069 free_cpumask_var(rd->span);
6075 * By default the system creates a single root-domain with all cpus as
6076 * members (mimicking the global state we have today).
6078 struct root_domain def_root_domain;
6080 static void init_defrootdomain(void)
6082 init_rootdomain(&def_root_domain);
6084 atomic_set(&def_root_domain.refcount, 1);
6087 static struct root_domain *alloc_rootdomain(void)
6089 struct root_domain *rd;
6091 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6095 if (init_rootdomain(rd) != 0) {
6103 static void free_sched_groups(struct sched_group *sg, int free_sgc)
6105 struct sched_group *tmp, *first;
6114 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
6119 } while (sg != first);
6122 static void destroy_sched_domain(struct sched_domain *sd)
6125 * If its an overlapping domain it has private groups, iterate and
6128 if (sd->flags & SD_OVERLAP) {
6129 free_sched_groups(sd->groups, 1);
6130 } else if (atomic_dec_and_test(&sd->groups->ref)) {
6131 kfree(sd->groups->sgc);
6134 if (sd->shared && atomic_dec_and_test(&sd->shared->ref))
6139 static void destroy_sched_domains_rcu(struct rcu_head *rcu)
6141 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
6144 struct sched_domain *parent = sd->parent;
6145 destroy_sched_domain(sd);
6150 static void destroy_sched_domains(struct sched_domain *sd)
6153 call_rcu(&sd->rcu, destroy_sched_domains_rcu);
6157 * Keep a special pointer to the highest sched_domain that has
6158 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
6159 * allows us to avoid some pointer chasing select_idle_sibling().
6161 * Also keep a unique ID per domain (we use the first cpu number in
6162 * the cpumask of the domain), this allows us to quickly tell if
6163 * two cpus are in the same cache domain, see cpus_share_cache().
6165 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
6166 DEFINE_PER_CPU(int, sd_llc_size);
6167 DEFINE_PER_CPU(int, sd_llc_id);
6168 DEFINE_PER_CPU(struct sched_domain_shared *, sd_llc_shared);
6169 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
6170 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
6171 DEFINE_PER_CPU(struct sched_domain *, sd_ea);
6172 DEFINE_PER_CPU(struct sched_domain *, sd_scs);
6174 static void update_top_cache_domain(int cpu)
6176 struct sched_domain_shared *sds = NULL;
6177 struct sched_domain *sd;
6178 struct sched_domain *ea_sd = NULL;
6182 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
6184 id = cpumask_first(sched_domain_span(sd));
6185 size = cpumask_weight(sched_domain_span(sd));
6189 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
6190 per_cpu(sd_llc_size, cpu) = size;
6191 per_cpu(sd_llc_id, cpu) = id;
6192 rcu_assign_pointer(per_cpu(sd_llc_shared, cpu), sds);
6194 sd = lowest_flag_domain(cpu, SD_NUMA);
6195 rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
6197 sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
6198 rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
6200 for_each_domain(cpu, sd) {
6201 if (sd->groups->sge)
6206 rcu_assign_pointer(per_cpu(sd_ea, cpu), ea_sd);
6208 sd = highest_flag_domain(cpu, SD_SHARE_CAP_STATES);
6209 rcu_assign_pointer(per_cpu(sd_scs, cpu), sd);
6213 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6214 * hold the hotplug lock.
6217 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6219 struct rq *rq = cpu_rq(cpu);
6220 struct sched_domain *tmp;
6222 /* Remove the sched domains which do not contribute to scheduling. */
6223 for (tmp = sd; tmp; ) {
6224 struct sched_domain *parent = tmp->parent;
6228 if (sd_parent_degenerate(tmp, parent)) {
6229 tmp->parent = parent->parent;
6231 parent->parent->child = tmp;
6233 * Transfer SD_PREFER_SIBLING down in case of a
6234 * degenerate parent; the spans match for this
6235 * so the property transfers.
6237 if (parent->flags & SD_PREFER_SIBLING)
6238 tmp->flags |= SD_PREFER_SIBLING;
6239 destroy_sched_domain(parent);
6244 if (sd && sd_degenerate(sd)) {
6247 destroy_sched_domain(tmp);
6252 sched_domain_debug(sd, cpu);
6254 rq_attach_root(rq, rd);
6256 rcu_assign_pointer(rq->sd, sd);
6257 destroy_sched_domains(tmp);
6259 update_top_cache_domain(cpu);
6262 /* Setup the mask of cpus configured for isolated domains */
6263 static int __init isolated_cpu_setup(char *str)
6267 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6268 ret = cpulist_parse(str, cpu_isolated_map);
6270 pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
6275 __setup("isolcpus=", isolated_cpu_setup);
6278 struct sched_domain ** __percpu sd;
6279 struct root_domain *rd;
6290 * Build an iteration mask that can exclude certain CPUs from the upwards
6293 * Only CPUs that can arrive at this group should be considered to continue
6296 * Asymmetric node setups can result in situations where the domain tree is of
6297 * unequal depth, make sure to skip domains that already cover the entire
6300 * In that case build_sched_domains() will have terminated the iteration early
6301 * and our sibling sd spans will be empty. Domains should always include the
6302 * cpu they're built on, so check that.
6305 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
6307 const struct cpumask *sg_span = sched_group_cpus(sg);
6308 struct sd_data *sdd = sd->private;
6309 struct sched_domain *sibling;
6312 for_each_cpu(i, sg_span) {
6313 sibling = *per_cpu_ptr(sdd->sd, i);
6316 * Can happen in the asymmetric case, where these siblings are
6317 * unused. The mask will not be empty because those CPUs that
6318 * do have the top domain _should_ span the domain.
6320 if (!sibling->child)
6323 /* If we would not end up here, we can't continue from here */
6324 if (!cpumask_equal(sg_span, sched_domain_span(sibling->child)))
6327 cpumask_set_cpu(i, sched_group_mask(sg));
6330 /* We must not have empty masks here */
6331 WARN_ON_ONCE(cpumask_empty(sched_group_mask(sg)));
6335 * Return the canonical balance cpu for this group, this is the first cpu
6336 * of this group that's also in the iteration mask.
6338 int group_balance_cpu(struct sched_group *sg)
6340 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
6344 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
6346 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
6347 const struct cpumask *span = sched_domain_span(sd);
6348 struct cpumask *covered = sched_domains_tmpmask;
6349 struct sd_data *sdd = sd->private;
6350 struct sched_domain *sibling;
6353 cpumask_clear(covered);
6355 for_each_cpu_wrap(i, span, cpu) {
6356 struct cpumask *sg_span;
6358 if (cpumask_test_cpu(i, covered))
6361 sibling = *per_cpu_ptr(sdd->sd, i);
6363 /* See the comment near build_group_mask(). */
6364 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6367 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6368 GFP_KERNEL, cpu_to_node(cpu));
6373 sg_span = sched_group_cpus(sg);
6375 cpumask_copy(sg_span, sched_domain_span(sibling->child));
6377 cpumask_set_cpu(i, sg_span);
6379 cpumask_or(covered, covered, sg_span);
6381 sg->sgc = *per_cpu_ptr(sdd->sgc, i);
6382 if (atomic_inc_return(&sg->sgc->ref) == 1)
6383 build_group_mask(sd, sg);
6386 * Initialize sgc->capacity such that even if we mess up the
6387 * domains and no possible iteration will get us here, we won't
6390 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
6391 sg->sgc->max_capacity = SCHED_CAPACITY_SCALE;
6392 sg->sgc->min_capacity = SCHED_CAPACITY_SCALE;
6395 * Make sure the first group of this domain contains the
6396 * canonical balance cpu. Otherwise the sched_domain iteration
6397 * breaks. See update_sg_lb_stats().
6399 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
6400 group_balance_cpu(sg) == cpu)
6410 sd->groups = groups;
6415 free_sched_groups(first, 0);
6420 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
6422 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6423 struct sched_domain *child = sd->child;
6426 cpu = cpumask_first(sched_domain_span(child));
6429 *sg = *per_cpu_ptr(sdd->sg, cpu);
6430 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
6431 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
6438 * build_sched_groups will build a circular linked list of the groups
6439 * covered by the given span, and will set each group's ->cpumask correctly,
6440 * and ->cpu_capacity to 0.
6442 * Assumes the sched_domain tree is fully constructed
6445 build_sched_groups(struct sched_domain *sd, int cpu)
6447 struct sched_group *first = NULL, *last = NULL;
6448 struct sd_data *sdd = sd->private;
6449 const struct cpumask *span = sched_domain_span(sd);
6450 struct cpumask *covered;
6453 get_group(cpu, sdd, &sd->groups);
6454 atomic_inc(&sd->groups->ref);
6456 if (cpu != cpumask_first(span))
6459 lockdep_assert_held(&sched_domains_mutex);
6460 covered = sched_domains_tmpmask;
6462 cpumask_clear(covered);
6464 for_each_cpu(i, span) {
6465 struct sched_group *sg;
6468 if (cpumask_test_cpu(i, covered))
6471 group = get_group(i, sdd, &sg);
6472 cpumask_setall(sched_group_mask(sg));
6474 for_each_cpu(j, span) {
6475 if (get_group(j, sdd, NULL) != group)
6478 cpumask_set_cpu(j, covered);
6479 cpumask_set_cpu(j, sched_group_cpus(sg));
6494 * Initialize sched groups cpu_capacity.
6496 * cpu_capacity indicates the capacity of sched group, which is used while
6497 * distributing the load between different sched groups in a sched domain.
6498 * Typically cpu_capacity for all the groups in a sched domain will be same
6499 * unless there are asymmetries in the topology. If there are asymmetries,
6500 * group having more cpu_capacity will pickup more load compared to the
6501 * group having less cpu_capacity.
6503 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
6505 struct sched_group *sg = sd->groups;
6510 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6512 } while (sg != sd->groups);
6514 if (cpu != group_balance_cpu(sg))
6517 update_group_capacity(sd, cpu);
6521 * Check that the per-cpu provided sd energy data is consistent for all cpus
6524 static inline void check_sched_energy_data(int cpu, sched_domain_energy_f fn,
6525 const struct cpumask *cpumask)
6527 const struct sched_group_energy * const sge = fn(cpu);
6528 struct cpumask mask;
6531 if (cpumask_weight(cpumask) <= 1)
6534 cpumask_xor(&mask, cpumask, get_cpu_mask(cpu));
6536 for_each_cpu(i, &mask) {
6537 const struct sched_group_energy * const e = fn(i);
6540 BUG_ON(e->nr_idle_states != sge->nr_idle_states);
6542 for (y = 0; y < (e->nr_idle_states); y++) {
6543 BUG_ON(e->idle_states[y].power !=
6544 sge->idle_states[y].power);
6547 BUG_ON(e->nr_cap_states != sge->nr_cap_states);
6549 for (y = 0; y < (e->nr_cap_states); y++) {
6550 BUG_ON(e->cap_states[y].cap != sge->cap_states[y].cap);
6551 BUG_ON(e->cap_states[y].power !=
6552 sge->cap_states[y].power);
6557 static void init_sched_energy(int cpu, struct sched_domain *sd,
6558 sched_domain_energy_f fn)
6560 if (!(fn && fn(cpu)))
6563 if (cpu != group_balance_cpu(sd->groups))
6566 if (sd->child && !sd->child->groups->sge) {
6567 pr_err("BUG: EAS setup broken for CPU%d\n", cpu);
6568 #ifdef CONFIG_SCHED_DEBUG
6569 pr_err(" energy data on %s but not on %s domain\n",
6570 sd->name, sd->child->name);
6575 check_sched_energy_data(cpu, fn, sched_group_cpus(sd->groups));
6577 sd->groups->sge = fn(cpu);
6581 * Initializers for schedule domains
6582 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6585 static int default_relax_domain_level = -1;
6586 int sched_domain_level_max;
6588 static int __init setup_relax_domain_level(char *str)
6590 if (kstrtoint(str, 0, &default_relax_domain_level))
6591 pr_warn("Unable to set relax_domain_level\n");
6595 __setup("relax_domain_level=", setup_relax_domain_level);
6597 static void set_domain_attribute(struct sched_domain *sd,
6598 struct sched_domain_attr *attr)
6602 if (!attr || attr->relax_domain_level < 0) {
6603 if (default_relax_domain_level < 0)
6606 request = default_relax_domain_level;
6608 request = attr->relax_domain_level;
6609 if (request < sd->level) {
6610 /* turn off idle balance on this domain */
6611 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6613 /* turn on idle balance on this domain */
6614 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6618 static void __sdt_free(const struct cpumask *cpu_map);
6619 static int __sdt_alloc(const struct cpumask *cpu_map);
6621 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6622 const struct cpumask *cpu_map)
6626 if (!atomic_read(&d->rd->refcount))
6627 free_rootdomain(&d->rd->rcu); /* fall through */
6629 free_percpu(d->sd); /* fall through */
6631 __sdt_free(cpu_map); /* fall through */
6637 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6638 const struct cpumask *cpu_map)
6640 memset(d, 0, sizeof(*d));
6642 if (__sdt_alloc(cpu_map))
6643 return sa_sd_storage;
6644 d->sd = alloc_percpu(struct sched_domain *);
6646 return sa_sd_storage;
6647 d->rd = alloc_rootdomain();
6650 return sa_rootdomain;
6654 * NULL the sd_data elements we've used to build the sched_domain and
6655 * sched_group structure so that the subsequent __free_domain_allocs()
6656 * will not free the data we're using.
6658 static void claim_allocations(int cpu, struct sched_domain *sd)
6660 struct sd_data *sdd = sd->private;
6662 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6663 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6665 if (atomic_read(&(*per_cpu_ptr(sdd->sds, cpu))->ref))
6666 *per_cpu_ptr(sdd->sds, cpu) = NULL;
6668 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6669 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6671 if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
6672 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
6676 static int sched_domains_numa_levels;
6677 enum numa_topology_type sched_numa_topology_type;
6678 static int *sched_domains_numa_distance;
6679 int sched_max_numa_distance;
6680 static struct cpumask ***sched_domains_numa_masks;
6681 static int sched_domains_curr_level;
6685 * SD_flags allowed in topology descriptions.
6687 * These flags are purely descriptive of the topology and do not prescribe
6688 * behaviour. Behaviour is artificial and mapped in the below sd_init()
6691 * SD_SHARE_CPUCAPACITY - describes SMT topologies
6692 * SD_SHARE_PKG_RESOURCES - describes shared caches
6693 * SD_NUMA - describes NUMA topologies
6694 * SD_SHARE_POWERDOMAIN - describes shared power domain
6695 * SD_ASYM_CPUCAPACITY - describes mixed capacity topologies
6696 * SD_SHARE_CAP_STATES - describes shared capacity states
6698 * Odd one out, which beside describing the topology has a quirk also
6699 * prescribes the desired behaviour that goes along with it:
6701 * SD_ASYM_PACKING - describes SMT quirks
6703 #define TOPOLOGY_SD_FLAGS \
6704 (SD_SHARE_CPUCAPACITY | \
6705 SD_SHARE_PKG_RESOURCES | \
6708 SD_ASYM_CPUCAPACITY | \
6709 SD_SHARE_POWERDOMAIN | \
6710 SD_SHARE_CAP_STATES)
6712 static struct sched_domain *
6713 sd_init(struct sched_domain_topology_level *tl,
6714 const struct cpumask *cpu_map,
6715 struct sched_domain *child, int cpu)
6717 struct sd_data *sdd = &tl->data;
6718 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6719 int sd_id, sd_weight, sd_flags = 0;
6723 * Ugly hack to pass state to sd_numa_mask()...
6725 sched_domains_curr_level = tl->numa_level;
6728 sd_weight = cpumask_weight(tl->mask(cpu));
6731 sd_flags = (*tl->sd_flags)();
6732 if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
6733 "wrong sd_flags in topology description\n"))
6734 sd_flags &= ~TOPOLOGY_SD_FLAGS;
6736 *sd = (struct sched_domain){
6737 .min_interval = sd_weight,
6738 .max_interval = 2*sd_weight,
6740 .imbalance_pct = 125,
6742 .cache_nice_tries = 0,
6749 .flags = 1*SD_LOAD_BALANCE
6750 | 1*SD_BALANCE_NEWIDLE
6755 | 0*SD_SHARE_CPUCAPACITY
6756 | 0*SD_SHARE_PKG_RESOURCES
6758 | 0*SD_PREFER_SIBLING
6763 .last_balance = jiffies,
6764 .balance_interval = sd_weight,
6766 .max_newidle_lb_cost = 0,
6767 .next_decay_max_lb_cost = jiffies,
6769 #ifdef CONFIG_SCHED_DEBUG
6774 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6775 sd_id = cpumask_first(sched_domain_span(sd));
6778 * Convert topological properties into behaviour.
6781 if (sd->flags & SD_ASYM_CPUCAPACITY) {
6782 struct sched_domain *t = sd;
6784 for_each_lower_domain(t)
6785 t->flags |= SD_BALANCE_WAKE;
6788 if (sd->flags & SD_SHARE_CPUCAPACITY) {
6789 sd->flags |= SD_PREFER_SIBLING;
6790 sd->imbalance_pct = 110;
6791 sd->smt_gain = 1178; /* ~15% */
6793 } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6794 sd->imbalance_pct = 117;
6795 sd->cache_nice_tries = 1;
6799 } else if (sd->flags & SD_NUMA) {
6800 sd->cache_nice_tries = 2;
6804 sd->flags |= SD_SERIALIZE;
6805 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
6806 sd->flags &= ~(SD_BALANCE_EXEC |
6813 sd->flags |= SD_PREFER_SIBLING;
6814 sd->cache_nice_tries = 1;
6820 * For all levels sharing cache; connect a sched_domain_shared
6823 if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6824 sd->shared = *per_cpu_ptr(sdd->sds, sd_id);
6825 atomic_inc(&sd->shared->ref);
6826 atomic_set(&sd->shared->nr_busy_cpus, sd_weight);
6835 * Topology list, bottom-up.
6837 static struct sched_domain_topology_level default_topology[] = {
6838 #ifdef CONFIG_SCHED_SMT
6839 { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
6841 #ifdef CONFIG_SCHED_MC
6842 { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
6844 { cpu_cpu_mask, SD_INIT_NAME(DIE) },
6848 static struct sched_domain_topology_level *sched_domain_topology =
6851 #define for_each_sd_topology(tl) \
6852 for (tl = sched_domain_topology; tl->mask; tl++)
6854 void set_sched_topology(struct sched_domain_topology_level *tl)
6856 if (WARN_ON_ONCE(sched_smp_initialized))
6859 sched_domain_topology = tl;
6864 static const struct cpumask *sd_numa_mask(int cpu)
6866 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6869 static void sched_numa_warn(const char *str)
6871 static int done = false;
6879 printk(KERN_WARNING "ERROR: %s\n\n", str);
6881 for (i = 0; i < nr_node_ids; i++) {
6882 printk(KERN_WARNING " ");
6883 for (j = 0; j < nr_node_ids; j++)
6884 printk(KERN_CONT "%02d ", node_distance(i,j));
6885 printk(KERN_CONT "\n");
6887 printk(KERN_WARNING "\n");
6890 bool find_numa_distance(int distance)
6894 if (distance == node_distance(0, 0))
6897 for (i = 0; i < sched_domains_numa_levels; i++) {
6898 if (sched_domains_numa_distance[i] == distance)
6906 * A system can have three types of NUMA topology:
6907 * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6908 * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6909 * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6911 * The difference between a glueless mesh topology and a backplane
6912 * topology lies in whether communication between not directly
6913 * connected nodes goes through intermediary nodes (where programs
6914 * could run), or through backplane controllers. This affects
6915 * placement of programs.
6917 * The type of topology can be discerned with the following tests:
6918 * - If the maximum distance between any nodes is 1 hop, the system
6919 * is directly connected.
6920 * - If for two nodes A and B, located N > 1 hops away from each other,
6921 * there is an intermediary node C, which is < N hops away from both
6922 * nodes A and B, the system is a glueless mesh.
6924 static void init_numa_topology_type(void)
6928 n = sched_max_numa_distance;
6930 if (sched_domains_numa_levels <= 1) {
6931 sched_numa_topology_type = NUMA_DIRECT;
6935 for_each_online_node(a) {
6936 for_each_online_node(b) {
6937 /* Find two nodes furthest removed from each other. */
6938 if (node_distance(a, b) < n)
6941 /* Is there an intermediary node between a and b? */
6942 for_each_online_node(c) {
6943 if (node_distance(a, c) < n &&
6944 node_distance(b, c) < n) {
6945 sched_numa_topology_type =
6951 sched_numa_topology_type = NUMA_BACKPLANE;
6957 static void sched_init_numa(void)
6959 int next_distance, curr_distance = node_distance(0, 0);
6960 struct sched_domain_topology_level *tl;
6964 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6965 if (!sched_domains_numa_distance)
6969 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6970 * unique distances in the node_distance() table.
6972 * Assumes node_distance(0,j) includes all distances in
6973 * node_distance(i,j) in order to avoid cubic time.
6975 next_distance = curr_distance;
6976 for (i = 0; i < nr_node_ids; i++) {
6977 for (j = 0; j < nr_node_ids; j++) {
6978 for (k = 0; k < nr_node_ids; k++) {
6979 int distance = node_distance(i, k);
6981 if (distance > curr_distance &&
6982 (distance < next_distance ||
6983 next_distance == curr_distance))
6984 next_distance = distance;
6987 * While not a strong assumption it would be nice to know
6988 * about cases where if node A is connected to B, B is not
6989 * equally connected to A.
6991 if (sched_debug() && node_distance(k, i) != distance)
6992 sched_numa_warn("Node-distance not symmetric");
6994 if (sched_debug() && i && !find_numa_distance(distance))
6995 sched_numa_warn("Node-0 not representative");
6997 if (next_distance != curr_distance) {
6998 sched_domains_numa_distance[level++] = next_distance;
6999 sched_domains_numa_levels = level;
7000 curr_distance = next_distance;
7005 * In case of sched_debug() we verify the above assumption.
7015 * 'level' contains the number of unique distances, excluding the
7016 * identity distance node_distance(i,i).
7018 * The sched_domains_numa_distance[] array includes the actual distance
7023 * Here, we should temporarily reset sched_domains_numa_levels to 0.
7024 * If it fails to allocate memory for array sched_domains_numa_masks[][],
7025 * the array will contain less then 'level' members. This could be
7026 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
7027 * in other functions.
7029 * We reset it to 'level' at the end of this function.
7031 sched_domains_numa_levels = 0;
7033 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
7034 if (!sched_domains_numa_masks)
7038 * Now for each level, construct a mask per node which contains all
7039 * cpus of nodes that are that many hops away from us.
7041 for (i = 0; i < level; i++) {
7042 sched_domains_numa_masks[i] =
7043 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
7044 if (!sched_domains_numa_masks[i])
7047 for (j = 0; j < nr_node_ids; j++) {
7048 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
7052 sched_domains_numa_masks[i][j] = mask;
7055 if (node_distance(j, k) > sched_domains_numa_distance[i])
7058 cpumask_or(mask, mask, cpumask_of_node(k));
7063 /* Compute default topology size */
7064 for (i = 0; sched_domain_topology[i].mask; i++);
7066 tl = kzalloc((i + level + 1) *
7067 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
7072 * Copy the default topology bits..
7074 for (i = 0; sched_domain_topology[i].mask; i++)
7075 tl[i] = sched_domain_topology[i];
7078 * .. and append 'j' levels of NUMA goodness.
7080 for (j = 0; j < level; i++, j++) {
7081 tl[i] = (struct sched_domain_topology_level){
7082 .mask = sd_numa_mask,
7083 .sd_flags = cpu_numa_flags,
7084 .flags = SDTL_OVERLAP,
7090 sched_domain_topology = tl;
7092 sched_domains_numa_levels = level;
7093 sched_max_numa_distance = sched_domains_numa_distance[level - 1];
7095 init_numa_topology_type();
7098 static void sched_domains_numa_masks_set(unsigned int cpu)
7100 int node = cpu_to_node(cpu);
7103 for (i = 0; i < sched_domains_numa_levels; i++) {
7104 for (j = 0; j < nr_node_ids; j++) {
7105 if (node_distance(j, node) <= sched_domains_numa_distance[i])
7106 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
7111 static void sched_domains_numa_masks_clear(unsigned int cpu)
7115 for (i = 0; i < sched_domains_numa_levels; i++) {
7116 for (j = 0; j < nr_node_ids; j++)
7117 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
7122 static inline void sched_init_numa(void) { }
7123 static void sched_domains_numa_masks_set(unsigned int cpu) { }
7124 static void sched_domains_numa_masks_clear(unsigned int cpu) { }
7125 #endif /* CONFIG_NUMA */
7127 static int __sdt_alloc(const struct cpumask *cpu_map)
7129 struct sched_domain_topology_level *tl;
7132 for_each_sd_topology(tl) {
7133 struct sd_data *sdd = &tl->data;
7135 sdd->sd = alloc_percpu(struct sched_domain *);
7139 sdd->sds = alloc_percpu(struct sched_domain_shared *);
7143 sdd->sg = alloc_percpu(struct sched_group *);
7147 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
7151 for_each_cpu(j, cpu_map) {
7152 struct sched_domain *sd;
7153 struct sched_domain_shared *sds;
7154 struct sched_group *sg;
7155 struct sched_group_capacity *sgc;
7157 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
7158 GFP_KERNEL, cpu_to_node(j));
7162 *per_cpu_ptr(sdd->sd, j) = sd;
7164 sds = kzalloc_node(sizeof(struct sched_domain_shared),
7165 GFP_KERNEL, cpu_to_node(j));
7169 *per_cpu_ptr(sdd->sds, j) = sds;
7171 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
7172 GFP_KERNEL, cpu_to_node(j));
7178 *per_cpu_ptr(sdd->sg, j) = sg;
7180 sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
7181 GFP_KERNEL, cpu_to_node(j));
7185 *per_cpu_ptr(sdd->sgc, j) = sgc;
7192 static void __sdt_free(const struct cpumask *cpu_map)
7194 struct sched_domain_topology_level *tl;
7197 for_each_sd_topology(tl) {
7198 struct sd_data *sdd = &tl->data;
7200 for_each_cpu(j, cpu_map) {
7201 struct sched_domain *sd;
7204 sd = *per_cpu_ptr(sdd->sd, j);
7205 if (sd && (sd->flags & SD_OVERLAP))
7206 free_sched_groups(sd->groups, 0);
7207 kfree(*per_cpu_ptr(sdd->sd, j));
7211 kfree(*per_cpu_ptr(sdd->sds, j));
7213 kfree(*per_cpu_ptr(sdd->sg, j));
7215 kfree(*per_cpu_ptr(sdd->sgc, j));
7217 free_percpu(sdd->sd);
7219 free_percpu(sdd->sds);
7221 free_percpu(sdd->sg);
7223 free_percpu(sdd->sgc);
7228 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
7229 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7230 struct sched_domain *child, int cpu)
7232 struct sched_domain *sd = sd_init(tl, cpu_map, child, cpu);
7235 sd->level = child->level + 1;
7236 sched_domain_level_max = max(sched_domain_level_max, sd->level);
7239 if (!cpumask_subset(sched_domain_span(child),
7240 sched_domain_span(sd))) {
7241 pr_err("BUG: arch topology borken\n");
7242 #ifdef CONFIG_SCHED_DEBUG
7243 pr_err(" the %s domain not a subset of the %s domain\n",
7244 child->name, sd->name);
7246 /* Fixup, ensure @sd has at least @child cpus. */
7247 cpumask_or(sched_domain_span(sd),
7248 sched_domain_span(sd),
7249 sched_domain_span(child));
7253 set_domain_attribute(sd, attr);
7259 * Build sched domains for a given set of cpus and attach the sched domains
7260 * to the individual cpus
7262 static int build_sched_domains(const struct cpumask *cpu_map,
7263 struct sched_domain_attr *attr)
7265 enum s_alloc alloc_state;
7266 struct sched_domain *sd;
7268 int i, ret = -ENOMEM;
7270 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7271 if (alloc_state != sa_rootdomain)
7274 /* Set up domains for cpus specified by the cpu_map. */
7275 for_each_cpu(i, cpu_map) {
7276 struct sched_domain_topology_level *tl;
7279 for_each_sd_topology(tl) {
7280 sd = build_sched_domain(tl, cpu_map, attr, sd, i);
7281 if (tl == sched_domain_topology)
7282 *per_cpu_ptr(d.sd, i) = sd;
7283 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
7284 sd->flags |= SD_OVERLAP;
7285 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
7290 /* Build the groups for the domains */
7291 for_each_cpu(i, cpu_map) {
7292 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7293 sd->span_weight = cpumask_weight(sched_domain_span(sd));
7294 if (sd->flags & SD_OVERLAP) {
7295 if (build_overlap_sched_groups(sd, i))
7298 if (build_sched_groups(sd, i))
7304 /* Calculate CPU capacity for physical packages and nodes */
7305 for (i = nr_cpumask_bits-1; i >= 0; i--) {
7306 struct sched_domain_topology_level *tl = sched_domain_topology;
7308 if (!cpumask_test_cpu(i, cpu_map))
7311 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent, tl++) {
7312 init_sched_energy(i, sd, tl->energy);
7313 claim_allocations(i, sd);
7314 init_sched_groups_capacity(i, sd);
7318 /* Attach the domains */
7320 for_each_cpu(i, cpu_map) {
7321 int max_cpu = READ_ONCE(d.rd->max_cap_orig_cpu);
7322 int min_cpu = READ_ONCE(d.rd->min_cap_orig_cpu);
7324 if ((max_cpu < 0) || (cpu_rq(i)->cpu_capacity_orig >
7325 cpu_rq(max_cpu)->cpu_capacity_orig))
7326 WRITE_ONCE(d.rd->max_cap_orig_cpu, i);
7328 if ((min_cpu < 0) || (cpu_rq(i)->cpu_capacity_orig <
7329 cpu_rq(min_cpu)->cpu_capacity_orig))
7330 WRITE_ONCE(d.rd->min_cap_orig_cpu, i);
7332 sd = *per_cpu_ptr(d.sd, i);
7334 cpu_attach_domain(sd, d.rd, i);
7340 __free_domain_allocs(&d, alloc_state, cpu_map);
7344 static cpumask_var_t *doms_cur; /* current sched domains */
7345 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7346 static struct sched_domain_attr *dattr_cur;
7347 /* attribues of custom domains in 'doms_cur' */
7350 * Special case: If a kmalloc of a doms_cur partition (array of
7351 * cpumask) fails, then fallback to a single sched domain,
7352 * as determined by the single cpumask fallback_doms.
7354 static cpumask_var_t fallback_doms;
7357 * arch_update_cpu_topology lets virtualized architectures update the
7358 * cpu core maps. It is supposed to return 1 if the topology changed
7359 * or 0 if it stayed the same.
7361 int __weak arch_update_cpu_topology(void)
7366 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7369 cpumask_var_t *doms;
7371 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7374 for (i = 0; i < ndoms; i++) {
7375 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7376 free_sched_domains(doms, i);
7383 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7386 for (i = 0; i < ndoms; i++)
7387 free_cpumask_var(doms[i]);
7392 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7393 * For now this just excludes isolated cpus, but could be used to
7394 * exclude other special cases in the future.
7396 static int init_sched_domains(const struct cpumask *cpu_map)
7400 arch_update_cpu_topology();
7402 doms_cur = alloc_sched_domains(ndoms_cur);
7404 doms_cur = &fallback_doms;
7405 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7406 err = build_sched_domains(doms_cur[0], NULL);
7407 register_sched_domain_sysctl();
7413 * Detach sched domains from a group of cpus specified in cpu_map
7414 * These cpus will now be attached to the NULL domain
7416 static void detach_destroy_domains(const struct cpumask *cpu_map)
7421 for_each_cpu(i, cpu_map)
7422 cpu_attach_domain(NULL, &def_root_domain, i);
7426 /* handle null as "default" */
7427 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7428 struct sched_domain_attr *new, int idx_new)
7430 struct sched_domain_attr tmp;
7437 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7438 new ? (new + idx_new) : &tmp,
7439 sizeof(struct sched_domain_attr));
7443 * Partition sched domains as specified by the 'ndoms_new'
7444 * cpumasks in the array doms_new[] of cpumasks. This compares
7445 * doms_new[] to the current sched domain partitioning, doms_cur[].
7446 * It destroys each deleted domain and builds each new domain.
7448 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7449 * The masks don't intersect (don't overlap.) We should setup one
7450 * sched domain for each mask. CPUs not in any of the cpumasks will
7451 * not be load balanced. If the same cpumask appears both in the
7452 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7455 * The passed in 'doms_new' should be allocated using
7456 * alloc_sched_domains. This routine takes ownership of it and will
7457 * free_sched_domains it when done with it. If the caller failed the
7458 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7459 * and partition_sched_domains() will fallback to the single partition
7460 * 'fallback_doms', it also forces the domains to be rebuilt.
7462 * If doms_new == NULL it will be replaced with cpu_online_mask.
7463 * ndoms_new == 0 is a special case for destroying existing domains,
7464 * and it will not create the default domain.
7466 * Call with hotplug lock held
7468 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7469 struct sched_domain_attr *dattr_new)
7474 mutex_lock(&sched_domains_mutex);
7476 /* always unregister in case we don't destroy any domains */
7477 unregister_sched_domain_sysctl();
7479 /* Let architecture update cpu core mappings. */
7480 new_topology = arch_update_cpu_topology();
7482 n = doms_new ? ndoms_new : 0;
7484 /* Destroy deleted domains */
7485 for (i = 0; i < ndoms_cur; i++) {
7486 for (j = 0; j < n && !new_topology; j++) {
7487 if (cpumask_equal(doms_cur[i], doms_new[j])
7488 && dattrs_equal(dattr_cur, i, dattr_new, j))
7491 /* no match - a current sched domain not in new doms_new[] */
7492 detach_destroy_domains(doms_cur[i]);
7498 if (doms_new == NULL) {
7500 doms_new = &fallback_doms;
7501 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7502 WARN_ON_ONCE(dattr_new);
7505 /* Build new domains */
7506 for (i = 0; i < ndoms_new; i++) {
7507 for (j = 0; j < n && !new_topology; j++) {
7508 if (cpumask_equal(doms_new[i], doms_cur[j])
7509 && dattrs_equal(dattr_new, i, dattr_cur, j))
7512 /* no match - add a new doms_new */
7513 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7518 /* Remember the new sched domains */
7519 if (doms_cur != &fallback_doms)
7520 free_sched_domains(doms_cur, ndoms_cur);
7521 kfree(dattr_cur); /* kfree(NULL) is safe */
7522 doms_cur = doms_new;
7523 dattr_cur = dattr_new;
7524 ndoms_cur = ndoms_new;
7526 register_sched_domain_sysctl();
7528 mutex_unlock(&sched_domains_mutex);
7531 static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
7534 * Update cpusets according to cpu_active mask. If cpusets are
7535 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7536 * around partition_sched_domains().
7538 * If we come here as part of a suspend/resume, don't touch cpusets because we
7539 * want to restore it back to its original state upon resume anyway.
7541 static void cpuset_cpu_active(void)
7543 if (cpuhp_tasks_frozen) {
7545 * num_cpus_frozen tracks how many CPUs are involved in suspend
7546 * resume sequence. As long as this is not the last online
7547 * operation in the resume sequence, just build a single sched
7548 * domain, ignoring cpusets.
7551 if (likely(num_cpus_frozen)) {
7552 partition_sched_domains(1, NULL, NULL);
7556 * This is the last CPU online operation. So fall through and
7557 * restore the original sched domains by considering the
7558 * cpuset configurations.
7561 cpuset_update_active_cpus(true);
7564 static int cpuset_cpu_inactive(unsigned int cpu)
7566 unsigned long flags;
7571 if (!cpuhp_tasks_frozen) {
7572 rcu_read_lock_sched();
7573 dl_b = dl_bw_of(cpu);
7575 raw_spin_lock_irqsave(&dl_b->lock, flags);
7576 cpus = dl_bw_cpus(cpu);
7577 overflow = __dl_overflow(dl_b, cpus, 0, 0);
7578 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7580 rcu_read_unlock_sched();
7584 cpuset_update_active_cpus(false);
7587 partition_sched_domains(1, NULL, NULL);
7592 int sched_cpu_activate(unsigned int cpu)
7594 struct rq *rq = cpu_rq(cpu);
7595 unsigned long flags;
7597 set_cpu_active(cpu, true);
7599 if (sched_smp_initialized) {
7600 sched_domains_numa_masks_set(cpu);
7601 cpuset_cpu_active();
7605 * Put the rq online, if not already. This happens:
7607 * 1) In the early boot process, because we build the real domains
7608 * after all cpus have been brought up.
7610 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
7613 raw_spin_lock_irqsave(&rq->lock, flags);
7615 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7618 raw_spin_unlock_irqrestore(&rq->lock, flags);
7620 update_max_interval();
7625 int sched_cpu_deactivate(unsigned int cpu)
7629 set_cpu_active(cpu, false);
7631 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
7632 * users of this state to go away such that all new such users will
7635 * For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
7636 * not imply sync_sched(), so wait for both.
7638 * Do sync before park smpboot threads to take care the rcu boost case.
7640 if (IS_ENABLED(CONFIG_PREEMPT))
7641 synchronize_rcu_mult(call_rcu, call_rcu_sched);
7645 if (!sched_smp_initialized)
7648 ret = cpuset_cpu_inactive(cpu);
7650 set_cpu_active(cpu, true);
7653 sched_domains_numa_masks_clear(cpu);
7657 static void sched_rq_cpu_starting(unsigned int cpu)
7659 struct rq *rq = cpu_rq(cpu);
7661 rq->calc_load_update = calc_load_update;
7662 update_max_interval();
7665 int sched_cpu_starting(unsigned int cpu)
7667 set_cpu_rq_start_time(cpu);
7668 sched_rq_cpu_starting(cpu);
7672 #ifdef CONFIG_HOTPLUG_CPU
7673 int sched_cpu_dying(unsigned int cpu)
7675 struct rq *rq = cpu_rq(cpu);
7676 unsigned long flags;
7678 /* Handle pending wakeups and then migrate everything off */
7679 sched_ttwu_pending();
7680 raw_spin_lock_irqsave(&rq->lock, flags);
7682 walt_migrate_sync_cpu(cpu);
7685 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7689 BUG_ON(rq->nr_running != 1);
7690 raw_spin_unlock_irqrestore(&rq->lock, flags);
7691 calc_load_migrate(rq);
7692 update_max_interval();
7693 nohz_balance_exit_idle(cpu);
7699 void __init sched_init_smp(void)
7701 cpumask_var_t non_isolated_cpus;
7703 walt_init_cpu_efficiency();
7704 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7705 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7710 * There's no userspace yet to cause hotplug operations; hence all the
7711 * cpu masks are stable and all blatant races in the below code cannot
7714 mutex_lock(&sched_domains_mutex);
7715 init_sched_domains(cpu_active_mask);
7716 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7717 if (cpumask_empty(non_isolated_cpus))
7718 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7719 mutex_unlock(&sched_domains_mutex);
7721 /* Move init over to a non-isolated CPU */
7722 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7724 sched_init_granularity();
7725 free_cpumask_var(non_isolated_cpus);
7727 init_sched_rt_class();
7728 init_sched_dl_class();
7729 sched_smp_initialized = true;
7732 static int __init migration_init(void)
7734 sched_rq_cpu_starting(smp_processor_id());
7737 early_initcall(migration_init);
7740 void __init sched_init_smp(void)
7742 sched_init_granularity();
7744 #endif /* CONFIG_SMP */
7746 int in_sched_functions(unsigned long addr)
7748 return in_lock_functions(addr) ||
7749 (addr >= (unsigned long)__sched_text_start
7750 && addr < (unsigned long)__sched_text_end);
7753 #ifdef CONFIG_CGROUP_SCHED
7755 * Default task group.
7756 * Every task in system belongs to this group at bootup.
7758 struct task_group root_task_group;
7759 LIST_HEAD(task_groups);
7761 /* Cacheline aligned slab cache for task_group */
7762 static struct kmem_cache *task_group_cache __read_mostly;
7765 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7766 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
7768 #define WAIT_TABLE_BITS 8
7769 #define WAIT_TABLE_SIZE (1 << WAIT_TABLE_BITS)
7770 static wait_queue_head_t bit_wait_table[WAIT_TABLE_SIZE] __cacheline_aligned;
7772 wait_queue_head_t *bit_waitqueue(void *word, int bit)
7774 const int shift = BITS_PER_LONG == 32 ? 5 : 6;
7775 unsigned long val = (unsigned long)word << shift | bit;
7777 return bit_wait_table + hash_long(val, WAIT_TABLE_BITS);
7779 EXPORT_SYMBOL(bit_waitqueue);
7781 void __init sched_init(void)
7784 unsigned long alloc_size = 0, ptr;
7786 for (i = 0; i < WAIT_TABLE_SIZE; i++)
7787 init_waitqueue_head(bit_wait_table + i);
7789 #ifdef CONFIG_FAIR_GROUP_SCHED
7790 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7792 #ifdef CONFIG_RT_GROUP_SCHED
7793 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7796 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7798 #ifdef CONFIG_FAIR_GROUP_SCHED
7799 root_task_group.se = (struct sched_entity **)ptr;
7800 ptr += nr_cpu_ids * sizeof(void **);
7802 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7803 ptr += nr_cpu_ids * sizeof(void **);
7805 #endif /* CONFIG_FAIR_GROUP_SCHED */
7806 #ifdef CONFIG_RT_GROUP_SCHED
7807 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7808 ptr += nr_cpu_ids * sizeof(void **);
7810 root_task_group.rt_rq = (struct rt_rq **)ptr;
7811 ptr += nr_cpu_ids * sizeof(void **);
7813 #endif /* CONFIG_RT_GROUP_SCHED */
7815 #ifdef CONFIG_CPUMASK_OFFSTACK
7816 for_each_possible_cpu(i) {
7817 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7818 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7819 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
7820 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7822 #endif /* CONFIG_CPUMASK_OFFSTACK */
7824 init_rt_bandwidth(&def_rt_bandwidth,
7825 global_rt_period(), global_rt_runtime());
7826 init_dl_bandwidth(&def_dl_bandwidth,
7827 global_rt_period(), global_rt_runtime());
7830 init_defrootdomain();
7833 #ifdef CONFIG_RT_GROUP_SCHED
7834 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7835 global_rt_period(), global_rt_runtime());
7836 #endif /* CONFIG_RT_GROUP_SCHED */
7838 #ifdef CONFIG_CGROUP_SCHED
7839 task_group_cache = KMEM_CACHE(task_group, 0);
7841 list_add(&root_task_group.list, &task_groups);
7842 INIT_LIST_HEAD(&root_task_group.children);
7843 INIT_LIST_HEAD(&root_task_group.siblings);
7844 autogroup_init(&init_task);
7845 #endif /* CONFIG_CGROUP_SCHED */
7847 for_each_possible_cpu(i) {
7851 raw_spin_lock_init(&rq->lock);
7853 rq->calc_load_active = 0;
7854 rq->calc_load_update = jiffies + LOAD_FREQ;
7855 init_cfs_rq(&rq->cfs);
7856 init_rt_rq(&rq->rt);
7857 init_dl_rq(&rq->dl);
7858 #ifdef CONFIG_FAIR_GROUP_SCHED
7859 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7860 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7862 * How much cpu bandwidth does root_task_group get?
7864 * In case of task-groups formed thr' the cgroup filesystem, it
7865 * gets 100% of the cpu resources in the system. This overall
7866 * system cpu resource is divided among the tasks of
7867 * root_task_group and its child task-groups in a fair manner,
7868 * based on each entity's (task or task-group's) weight
7869 * (se->load.weight).
7871 * In other words, if root_task_group has 10 tasks of weight
7872 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7873 * then A0's share of the cpu resource is:
7875 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7877 * We achieve this by letting root_task_group's tasks sit
7878 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7880 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7881 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7882 #endif /* CONFIG_FAIR_GROUP_SCHED */
7884 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7885 #ifdef CONFIG_RT_GROUP_SCHED
7886 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7889 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7890 rq->cpu_load[j] = 0;
7895 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7896 rq->balance_callback = NULL;
7897 rq->active_balance = 0;
7898 rq->next_balance = jiffies;
7903 rq->avg_idle = 2*sysctl_sched_migration_cost;
7904 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7905 #ifdef CONFIG_SCHED_WALT
7906 rq->cur_irqload = 0;
7907 rq->avg_irqload = 0;
7911 INIT_LIST_HEAD(&rq->cfs_tasks);
7913 rq_attach_root(rq, &def_root_domain);
7914 #ifdef CONFIG_NO_HZ_COMMON
7915 rq->last_load_update_tick = jiffies;
7918 #ifdef CONFIG_NO_HZ_FULL
7919 rq->last_sched_tick = 0;
7921 #endif /* CONFIG_SMP */
7923 atomic_set(&rq->nr_iowait, 0);
7926 set_load_weight(&init_task);
7929 * The boot idle thread does lazy MMU switching as well:
7931 atomic_inc(&init_mm.mm_count);
7932 enter_lazy_tlb(&init_mm, current);
7935 * Make us the idle thread. Technically, schedule() should not be
7936 * called from this thread, however somewhere below it might be,
7937 * but because we are the idle thread, we just pick up running again
7938 * when this runqueue becomes "idle".
7940 init_idle(current, smp_processor_id());
7942 calc_load_update = jiffies + LOAD_FREQ;
7945 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7946 /* May be allocated at isolcpus cmdline parse time */
7947 if (cpu_isolated_map == NULL)
7948 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7949 idle_thread_set_boot_cpu();
7950 set_cpu_rq_start_time(smp_processor_id());
7952 init_sched_fair_class();
7956 scheduler_running = 1;
7959 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7960 static inline int preempt_count_equals(int preempt_offset)
7962 int nested = preempt_count() + rcu_preempt_depth();
7964 return (nested == preempt_offset);
7967 static int __might_sleep_init_called;
7968 int __init __might_sleep_init(void)
7970 __might_sleep_init_called = 1;
7973 early_initcall(__might_sleep_init);
7975 void __might_sleep(const char *file, int line, int preempt_offset)
7978 * Blocking primitives will set (and therefore destroy) current->state,
7979 * since we will exit with TASK_RUNNING make sure we enter with it,
7980 * otherwise we will destroy state.
7982 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7983 "do not call blocking ops when !TASK_RUNNING; "
7984 "state=%lx set at [<%p>] %pS\n",
7986 (void *)current->task_state_change,
7987 (void *)current->task_state_change);
7989 ___might_sleep(file, line, preempt_offset);
7991 EXPORT_SYMBOL(__might_sleep);
7993 void ___might_sleep(const char *file, int line, int preempt_offset)
7995 static unsigned long prev_jiffy; /* ratelimiting */
7996 unsigned long preempt_disable_ip;
7998 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7999 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
8000 !is_idle_task(current)) || oops_in_progress)
8002 if (system_state != SYSTEM_RUNNING &&
8003 (!__might_sleep_init_called || system_state != SYSTEM_BOOTING))
8005 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8007 prev_jiffy = jiffies;
8009 /* Save this before calling printk(), since that will clobber it */
8010 preempt_disable_ip = get_preempt_disable_ip(current);
8013 "BUG: sleeping function called from invalid context at %s:%d\n",
8016 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8017 in_atomic(), irqs_disabled(),
8018 current->pid, current->comm);
8020 if (task_stack_end_corrupted(current))
8021 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
8023 debug_show_held_locks(current);
8024 if (irqs_disabled())
8025 print_irqtrace_events(current);
8026 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
8027 && !preempt_count_equals(preempt_offset)) {
8028 pr_err("Preemption disabled at:");
8029 print_ip_sym(preempt_disable_ip);
8033 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
8035 EXPORT_SYMBOL(___might_sleep);
8038 #ifdef CONFIG_MAGIC_SYSRQ
8039 void normalize_rt_tasks(void)
8041 struct task_struct *g, *p;
8042 struct sched_attr attr = {
8043 .sched_policy = SCHED_NORMAL,
8046 read_lock(&tasklist_lock);
8047 for_each_process_thread(g, p) {
8049 * Only normalize user tasks:
8051 if (p->flags & PF_KTHREAD)
8054 p->se.exec_start = 0;
8055 schedstat_set(p->se.statistics.wait_start, 0);
8056 schedstat_set(p->se.statistics.sleep_start, 0);
8057 schedstat_set(p->se.statistics.block_start, 0);
8059 if (!dl_task(p) && !rt_task(p)) {
8061 * Renice negative nice level userspace
8064 if (task_nice(p) < 0)
8065 set_user_nice(p, 0);
8069 __sched_setscheduler(p, &attr, false, false);
8071 read_unlock(&tasklist_lock);
8074 #endif /* CONFIG_MAGIC_SYSRQ */
8076 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
8078 * These functions are only useful for the IA64 MCA handling, or kdb.
8080 * They can only be called when the whole system has been
8081 * stopped - every CPU needs to be quiescent, and no scheduling
8082 * activity can take place. Using them for anything else would
8083 * be a serious bug, and as a result, they aren't even visible
8084 * under any other configuration.
8088 * curr_task - return the current task for a given cpu.
8089 * @cpu: the processor in question.
8091 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8093 * Return: The current task for @cpu.
8095 struct task_struct *curr_task(int cpu)
8097 return cpu_curr(cpu);
8100 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8104 * set_curr_task - set the current task for a given cpu.
8105 * @cpu: the processor in question.
8106 * @p: the task pointer to set.
8108 * Description: This function must only be used when non-maskable interrupts
8109 * are serviced on a separate stack. It allows the architecture to switch the
8110 * notion of the current task on a cpu in a non-blocking manner. This function
8111 * must be called with all CPU's synchronized, and interrupts disabled, the
8112 * and caller must save the original value of the current task (see
8113 * curr_task() above) and restore that value before reenabling interrupts and
8114 * re-starting the system.
8116 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8118 void ia64_set_curr_task(int cpu, struct task_struct *p)
8125 #ifdef CONFIG_CGROUP_SCHED
8126 /* task_group_lock serializes the addition/removal of task groups */
8127 static DEFINE_SPINLOCK(task_group_lock);
8129 static void sched_free_group(struct task_group *tg)
8131 free_fair_sched_group(tg);
8132 free_rt_sched_group(tg);
8134 kmem_cache_free(task_group_cache, tg);
8137 /* allocate runqueue etc for a new task group */
8138 struct task_group *sched_create_group(struct task_group *parent)
8140 struct task_group *tg;
8142 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
8144 return ERR_PTR(-ENOMEM);
8146 if (!alloc_fair_sched_group(tg, parent))
8149 if (!alloc_rt_sched_group(tg, parent))
8155 sched_free_group(tg);
8156 return ERR_PTR(-ENOMEM);
8159 void sched_online_group(struct task_group *tg, struct task_group *parent)
8161 unsigned long flags;
8163 spin_lock_irqsave(&task_group_lock, flags);
8164 list_add_rcu(&tg->list, &task_groups);
8166 WARN_ON(!parent); /* root should already exist */
8168 tg->parent = parent;
8169 INIT_LIST_HEAD(&tg->children);
8170 list_add_rcu(&tg->siblings, &parent->children);
8171 spin_unlock_irqrestore(&task_group_lock, flags);
8173 online_fair_sched_group(tg);
8176 /* rcu callback to free various structures associated with a task group */
8177 static void sched_free_group_rcu(struct rcu_head *rhp)
8179 /* now it should be safe to free those cfs_rqs */
8180 sched_free_group(container_of(rhp, struct task_group, rcu));
8183 void sched_destroy_group(struct task_group *tg)
8185 /* wait for possible concurrent references to cfs_rqs complete */
8186 call_rcu(&tg->rcu, sched_free_group_rcu);
8189 void sched_offline_group(struct task_group *tg)
8191 unsigned long flags;
8193 /* end participation in shares distribution */
8194 unregister_fair_sched_group(tg);
8196 spin_lock_irqsave(&task_group_lock, flags);
8197 list_del_rcu(&tg->list);
8198 list_del_rcu(&tg->siblings);
8199 spin_unlock_irqrestore(&task_group_lock, flags);
8202 static void sched_change_group(struct task_struct *tsk, int type)
8204 struct task_group *tg;
8207 * All callers are synchronized by task_rq_lock(); we do not use RCU
8208 * which is pointless here. Thus, we pass "true" to task_css_check()
8209 * to prevent lockdep warnings.
8211 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8212 struct task_group, css);
8213 tg = autogroup_task_group(tsk, tg);
8214 tsk->sched_task_group = tg;
8216 #ifdef CONFIG_FAIR_GROUP_SCHED
8217 if (tsk->sched_class->task_change_group)
8218 tsk->sched_class->task_change_group(tsk, type);
8221 set_task_rq(tsk, task_cpu(tsk));
8225 * Change task's runqueue when it moves between groups.
8227 * The caller of this function should have put the task in its new group by
8228 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
8231 void sched_move_task(struct task_struct *tsk)
8233 int queued, running;
8237 rq = task_rq_lock(tsk, &rf);
8239 running = task_current(rq, tsk);
8240 queued = task_on_rq_queued(tsk);
8243 dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
8244 if (unlikely(running))
8245 put_prev_task(rq, tsk);
8247 sched_change_group(tsk, TASK_MOVE_GROUP);
8250 enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
8251 if (unlikely(running))
8252 set_curr_task(rq, tsk);
8254 task_rq_unlock(rq, tsk, &rf);
8256 #endif /* CONFIG_CGROUP_SCHED */
8258 #ifdef CONFIG_RT_GROUP_SCHED
8260 * Ensure that the real time constraints are schedulable.
8262 static DEFINE_MUTEX(rt_constraints_mutex);
8264 /* Must be called with tasklist_lock held */
8265 static inline int tg_has_rt_tasks(struct task_group *tg)
8267 struct task_struct *g, *p;
8270 * Autogroups do not have RT tasks; see autogroup_create().
8272 if (task_group_is_autogroup(tg))
8275 for_each_process_thread(g, p) {
8276 if (rt_task(p) && task_group(p) == tg)
8283 struct rt_schedulable_data {
8284 struct task_group *tg;
8289 static int tg_rt_schedulable(struct task_group *tg, void *data)
8291 struct rt_schedulable_data *d = data;
8292 struct task_group *child;
8293 unsigned long total, sum = 0;
8294 u64 period, runtime;
8296 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8297 runtime = tg->rt_bandwidth.rt_runtime;
8300 period = d->rt_period;
8301 runtime = d->rt_runtime;
8305 * Cannot have more runtime than the period.
8307 if (runtime > period && runtime != RUNTIME_INF)
8311 * Ensure we don't starve existing RT tasks.
8313 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8316 total = to_ratio(period, runtime);
8319 * Nobody can have more than the global setting allows.
8321 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8325 * The sum of our children's runtime should not exceed our own.
8327 list_for_each_entry_rcu(child, &tg->children, siblings) {
8328 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8329 runtime = child->rt_bandwidth.rt_runtime;
8331 if (child == d->tg) {
8332 period = d->rt_period;
8333 runtime = d->rt_runtime;
8336 sum += to_ratio(period, runtime);
8345 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8349 struct rt_schedulable_data data = {
8351 .rt_period = period,
8352 .rt_runtime = runtime,
8356 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
8362 static int tg_set_rt_bandwidth(struct task_group *tg,
8363 u64 rt_period, u64 rt_runtime)
8368 * Disallowing the root group RT runtime is BAD, it would disallow the
8369 * kernel creating (and or operating) RT threads.
8371 if (tg == &root_task_group && rt_runtime == 0)
8374 /* No period doesn't make any sense. */
8378 mutex_lock(&rt_constraints_mutex);
8379 read_lock(&tasklist_lock);
8380 err = __rt_schedulable(tg, rt_period, rt_runtime);
8384 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8385 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8386 tg->rt_bandwidth.rt_runtime = rt_runtime;
8388 for_each_possible_cpu(i) {
8389 struct rt_rq *rt_rq = tg->rt_rq[i];
8391 raw_spin_lock(&rt_rq->rt_runtime_lock);
8392 rt_rq->rt_runtime = rt_runtime;
8393 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8395 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8397 read_unlock(&tasklist_lock);
8398 mutex_unlock(&rt_constraints_mutex);
8403 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8405 u64 rt_runtime, rt_period;
8407 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8408 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8409 if (rt_runtime_us < 0)
8410 rt_runtime = RUNTIME_INF;
8412 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8415 static long sched_group_rt_runtime(struct task_group *tg)
8419 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8422 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8423 do_div(rt_runtime_us, NSEC_PER_USEC);
8424 return rt_runtime_us;
8427 static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
8429 u64 rt_runtime, rt_period;
8431 rt_period = rt_period_us * NSEC_PER_USEC;
8432 rt_runtime = tg->rt_bandwidth.rt_runtime;
8434 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8437 static long sched_group_rt_period(struct task_group *tg)
8441 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8442 do_div(rt_period_us, NSEC_PER_USEC);
8443 return rt_period_us;
8445 #endif /* CONFIG_RT_GROUP_SCHED */
8447 #ifdef CONFIG_RT_GROUP_SCHED
8448 static int sched_rt_global_constraints(void)
8452 mutex_lock(&rt_constraints_mutex);
8453 read_lock(&tasklist_lock);
8454 ret = __rt_schedulable(NULL, 0, 0);
8455 read_unlock(&tasklist_lock);
8456 mutex_unlock(&rt_constraints_mutex);
8461 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8463 /* Don't accept realtime tasks when there is no way for them to run */
8464 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8470 #else /* !CONFIG_RT_GROUP_SCHED */
8471 static int sched_rt_global_constraints(void)
8473 unsigned long flags;
8476 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8477 for_each_possible_cpu(i) {
8478 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8480 raw_spin_lock(&rt_rq->rt_runtime_lock);
8481 rt_rq->rt_runtime = global_rt_runtime();
8482 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8484 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8488 #endif /* CONFIG_RT_GROUP_SCHED */
8490 static int sched_dl_global_validate(void)
8492 u64 runtime = global_rt_runtime();
8493 u64 period = global_rt_period();
8494 u64 new_bw = to_ratio(period, runtime);
8497 unsigned long flags;
8500 * Here we want to check the bandwidth not being set to some
8501 * value smaller than the currently allocated bandwidth in
8502 * any of the root_domains.
8504 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
8505 * cycling on root_domains... Discussion on different/better
8506 * solutions is welcome!
8508 for_each_possible_cpu(cpu) {
8509 rcu_read_lock_sched();
8510 dl_b = dl_bw_of(cpu);
8512 raw_spin_lock_irqsave(&dl_b->lock, flags);
8513 if (new_bw < dl_b->total_bw)
8515 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8517 rcu_read_unlock_sched();
8526 static void sched_dl_do_global(void)
8531 unsigned long flags;
8533 def_dl_bandwidth.dl_period = global_rt_period();
8534 def_dl_bandwidth.dl_runtime = global_rt_runtime();
8536 if (global_rt_runtime() != RUNTIME_INF)
8537 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
8540 * FIXME: As above...
8542 for_each_possible_cpu(cpu) {
8543 rcu_read_lock_sched();
8544 dl_b = dl_bw_of(cpu);
8546 raw_spin_lock_irqsave(&dl_b->lock, flags);
8548 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8550 rcu_read_unlock_sched();
8554 static int sched_rt_global_validate(void)
8556 if (sysctl_sched_rt_period <= 0)
8559 if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
8560 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
8566 static void sched_rt_do_global(void)
8568 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8569 def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
8572 int sched_rt_handler(struct ctl_table *table, int write,
8573 void __user *buffer, size_t *lenp,
8576 int old_period, old_runtime;
8577 static DEFINE_MUTEX(mutex);
8581 old_period = sysctl_sched_rt_period;
8582 old_runtime = sysctl_sched_rt_runtime;
8584 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8586 if (!ret && write) {
8587 ret = sched_rt_global_validate();
8591 ret = sched_dl_global_validate();
8595 ret = sched_rt_global_constraints();
8599 sched_rt_do_global();
8600 sched_dl_do_global();
8604 sysctl_sched_rt_period = old_period;
8605 sysctl_sched_rt_runtime = old_runtime;
8607 mutex_unlock(&mutex);
8612 int sched_rr_handler(struct ctl_table *table, int write,
8613 void __user *buffer, size_t *lenp,
8617 static DEFINE_MUTEX(mutex);
8620 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8621 /* make sure that internally we keep jiffies */
8622 /* also, writing zero resets timeslice to default */
8623 if (!ret && write) {
8624 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
8625 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
8627 mutex_unlock(&mutex);
8631 #ifdef CONFIG_CGROUP_SCHED
8633 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8635 return css ? container_of(css, struct task_group, css) : NULL;
8638 static struct cgroup_subsys_state *
8639 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8641 struct task_group *parent = css_tg(parent_css);
8642 struct task_group *tg;
8645 /* This is early initialization for the top cgroup */
8646 return &root_task_group.css;
8649 tg = sched_create_group(parent);
8651 return ERR_PTR(-ENOMEM);
8653 sched_online_group(tg, parent);
8658 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
8660 struct task_group *tg = css_tg(css);
8662 sched_offline_group(tg);
8665 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8667 struct task_group *tg = css_tg(css);
8670 * Relies on the RCU grace period between css_released() and this.
8672 sched_free_group(tg);
8676 * This is called before wake_up_new_task(), therefore we really only
8677 * have to set its group bits, all the other stuff does not apply.
8679 static void cpu_cgroup_fork(struct task_struct *task)
8684 rq = task_rq_lock(task, &rf);
8686 sched_change_group(task, TASK_SET_GROUP);
8688 task_rq_unlock(rq, task, &rf);
8691 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
8693 struct task_struct *task;
8694 struct cgroup_subsys_state *css;
8697 cgroup_taskset_for_each(task, css, tset) {
8698 #ifdef CONFIG_RT_GROUP_SCHED
8699 if (!sched_rt_can_attach(css_tg(css), task))
8702 /* We don't support RT-tasks being in separate groups */
8703 if (task->sched_class != &fair_sched_class)
8707 * Serialize against wake_up_new_task() such that if its
8708 * running, we're sure to observe its full state.
8710 raw_spin_lock_irq(&task->pi_lock);
8712 * Avoid calling sched_move_task() before wake_up_new_task()
8713 * has happened. This would lead to problems with PELT, due to
8714 * move wanting to detach+attach while we're not attached yet.
8716 if (task->state == TASK_NEW)
8718 raw_spin_unlock_irq(&task->pi_lock);
8726 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
8728 struct task_struct *task;
8729 struct cgroup_subsys_state *css;
8731 cgroup_taskset_for_each(task, css, tset)
8732 sched_move_task(task);
8735 #ifdef CONFIG_FAIR_GROUP_SCHED
8736 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8737 struct cftype *cftype, u64 shareval)
8739 return sched_group_set_shares(css_tg(css), scale_load(shareval));
8742 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8745 struct task_group *tg = css_tg(css);
8747 return (u64) scale_load_down(tg->shares);
8750 #ifdef CONFIG_CFS_BANDWIDTH
8751 static DEFINE_MUTEX(cfs_constraints_mutex);
8753 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8754 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8756 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8758 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8760 int i, ret = 0, runtime_enabled, runtime_was_enabled;
8761 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8763 if (tg == &root_task_group)
8767 * Ensure we have at some amount of bandwidth every period. This is
8768 * to prevent reaching a state of large arrears when throttled via
8769 * entity_tick() resulting in prolonged exit starvation.
8771 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8775 * Likewise, bound things on the otherside by preventing insane quota
8776 * periods. This also allows us to normalize in computing quota
8779 if (period > max_cfs_quota_period)
8783 * Prevent race between setting of cfs_rq->runtime_enabled and
8784 * unthrottle_offline_cfs_rqs().
8787 mutex_lock(&cfs_constraints_mutex);
8788 ret = __cfs_schedulable(tg, period, quota);
8792 runtime_enabled = quota != RUNTIME_INF;
8793 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8795 * If we need to toggle cfs_bandwidth_used, off->on must occur
8796 * before making related changes, and on->off must occur afterwards
8798 if (runtime_enabled && !runtime_was_enabled)
8799 cfs_bandwidth_usage_inc();
8800 raw_spin_lock_irq(&cfs_b->lock);
8801 cfs_b->period = ns_to_ktime(period);
8802 cfs_b->quota = quota;
8804 __refill_cfs_bandwidth_runtime(cfs_b);
8805 /* restart the period timer (if active) to handle new period expiry */
8806 if (runtime_enabled)
8807 start_cfs_bandwidth(cfs_b);
8808 raw_spin_unlock_irq(&cfs_b->lock);
8810 for_each_online_cpu(i) {
8811 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8812 struct rq *rq = cfs_rq->rq;
8814 raw_spin_lock_irq(&rq->lock);
8815 cfs_rq->runtime_enabled = runtime_enabled;
8816 cfs_rq->runtime_remaining = 0;
8818 if (cfs_rq->throttled)
8819 unthrottle_cfs_rq(cfs_rq);
8820 raw_spin_unlock_irq(&rq->lock);
8822 if (runtime_was_enabled && !runtime_enabled)
8823 cfs_bandwidth_usage_dec();
8825 mutex_unlock(&cfs_constraints_mutex);
8831 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8835 period = ktime_to_ns(tg->cfs_bandwidth.period);
8836 if (cfs_quota_us < 0)
8837 quota = RUNTIME_INF;
8839 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8841 return tg_set_cfs_bandwidth(tg, period, quota);
8844 long tg_get_cfs_quota(struct task_group *tg)
8848 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8851 quota_us = tg->cfs_bandwidth.quota;
8852 do_div(quota_us, NSEC_PER_USEC);
8857 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8861 period = (u64)cfs_period_us * NSEC_PER_USEC;
8862 quota = tg->cfs_bandwidth.quota;
8864 return tg_set_cfs_bandwidth(tg, period, quota);
8867 long tg_get_cfs_period(struct task_group *tg)
8871 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8872 do_div(cfs_period_us, NSEC_PER_USEC);
8874 return cfs_period_us;
8877 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8880 return tg_get_cfs_quota(css_tg(css));
8883 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8884 struct cftype *cftype, s64 cfs_quota_us)
8886 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8889 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8892 return tg_get_cfs_period(css_tg(css));
8895 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8896 struct cftype *cftype, u64 cfs_period_us)
8898 return tg_set_cfs_period(css_tg(css), cfs_period_us);
8901 struct cfs_schedulable_data {
8902 struct task_group *tg;
8907 * normalize group quota/period to be quota/max_period
8908 * note: units are usecs
8910 static u64 normalize_cfs_quota(struct task_group *tg,
8911 struct cfs_schedulable_data *d)
8919 period = tg_get_cfs_period(tg);
8920 quota = tg_get_cfs_quota(tg);
8923 /* note: these should typically be equivalent */
8924 if (quota == RUNTIME_INF || quota == -1)
8927 return to_ratio(period, quota);
8930 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8932 struct cfs_schedulable_data *d = data;
8933 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8934 s64 quota = 0, parent_quota = -1;
8937 quota = RUNTIME_INF;
8939 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8941 quota = normalize_cfs_quota(tg, d);
8942 parent_quota = parent_b->hierarchical_quota;
8945 * ensure max(child_quota) <= parent_quota, inherit when no
8948 if (quota == RUNTIME_INF)
8949 quota = parent_quota;
8950 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8953 cfs_b->hierarchical_quota = quota;
8958 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8961 struct cfs_schedulable_data data = {
8967 if (quota != RUNTIME_INF) {
8968 do_div(data.period, NSEC_PER_USEC);
8969 do_div(data.quota, NSEC_PER_USEC);
8973 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8979 static int cpu_stats_show(struct seq_file *sf, void *v)
8981 struct task_group *tg = css_tg(seq_css(sf));
8982 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8984 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8985 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8986 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8990 #endif /* CONFIG_CFS_BANDWIDTH */
8991 #endif /* CONFIG_FAIR_GROUP_SCHED */
8993 #ifdef CONFIG_RT_GROUP_SCHED
8994 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8995 struct cftype *cft, s64 val)
8997 return sched_group_set_rt_runtime(css_tg(css), val);
9000 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
9003 return sched_group_rt_runtime(css_tg(css));
9006 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
9007 struct cftype *cftype, u64 rt_period_us)
9009 return sched_group_set_rt_period(css_tg(css), rt_period_us);
9012 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
9015 return sched_group_rt_period(css_tg(css));
9017 #endif /* CONFIG_RT_GROUP_SCHED */
9019 static struct cftype cpu_files[] = {
9020 #ifdef CONFIG_FAIR_GROUP_SCHED
9023 .read_u64 = cpu_shares_read_u64,
9024 .write_u64 = cpu_shares_write_u64,
9027 #ifdef CONFIG_CFS_BANDWIDTH
9029 .name = "cfs_quota_us",
9030 .read_s64 = cpu_cfs_quota_read_s64,
9031 .write_s64 = cpu_cfs_quota_write_s64,
9034 .name = "cfs_period_us",
9035 .read_u64 = cpu_cfs_period_read_u64,
9036 .write_u64 = cpu_cfs_period_write_u64,
9040 .seq_show = cpu_stats_show,
9043 #ifdef CONFIG_RT_GROUP_SCHED
9045 .name = "rt_runtime_us",
9046 .read_s64 = cpu_rt_runtime_read,
9047 .write_s64 = cpu_rt_runtime_write,
9050 .name = "rt_period_us",
9051 .read_u64 = cpu_rt_period_read_uint,
9052 .write_u64 = cpu_rt_period_write_uint,
9058 struct cgroup_subsys cpu_cgrp_subsys = {
9059 .css_alloc = cpu_cgroup_css_alloc,
9060 .css_released = cpu_cgroup_css_released,
9061 .css_free = cpu_cgroup_css_free,
9062 .fork = cpu_cgroup_fork,
9063 .can_attach = cpu_cgroup_can_attach,
9064 .attach = cpu_cgroup_attach,
9065 .legacy_cftypes = cpu_files,
9069 #endif /* CONFIG_CGROUP_SCHED */
9071 void dump_cpu_task(int cpu)
9073 pr_info("Task dump for CPU %d:\n", cpu);
9074 sched_show_task(cpu_curr(cpu));
9078 * Nice levels are multiplicative, with a gentle 10% change for every
9079 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
9080 * nice 1, it will get ~10% less CPU time than another CPU-bound task
9081 * that remained on nice 0.
9083 * The "10% effect" is relative and cumulative: from _any_ nice level,
9084 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
9085 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
9086 * If a task goes up by ~10% and another task goes down by ~10% then
9087 * the relative distance between them is ~25%.)
9089 const int sched_prio_to_weight[40] = {
9090 /* -20 */ 88761, 71755, 56483, 46273, 36291,
9091 /* -15 */ 29154, 23254, 18705, 14949, 11916,
9092 /* -10 */ 9548, 7620, 6100, 4904, 3906,
9093 /* -5 */ 3121, 2501, 1991, 1586, 1277,
9094 /* 0 */ 1024, 820, 655, 526, 423,
9095 /* 5 */ 335, 272, 215, 172, 137,
9096 /* 10 */ 110, 87, 70, 56, 45,
9097 /* 15 */ 36, 29, 23, 18, 15,
9101 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
9103 * In cases where the weight does not change often, we can use the
9104 * precalculated inverse to speed up arithmetics by turning divisions
9105 * into multiplications:
9107 const u32 sched_prio_to_wmult[40] = {
9108 /* -20 */ 48388, 59856, 76040, 92818, 118348,
9109 /* -15 */ 147320, 184698, 229616, 287308, 360437,
9110 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
9111 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
9112 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
9113 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
9114 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
9115 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,