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>
94 DEFINE_MUTEX(sched_domains_mutex);
95 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
97 static void update_rq_clock_task(struct rq *rq, s64 delta);
99 void update_rq_clock(struct rq *rq)
103 lockdep_assert_held(&rq->lock);
105 if (rq->clock_skip_update & RQCF_ACT_SKIP)
108 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
112 update_rq_clock_task(rq, delta);
116 * Debugging: various feature bits
119 #define SCHED_FEAT(name, enabled) \
120 (1UL << __SCHED_FEAT_##name) * enabled |
122 const_debug unsigned int sysctl_sched_features =
123 #include "features.h"
129 * Number of tasks to iterate in a single balance run.
130 * Limited because this is done with IRQs disabled.
132 #ifndef CONFIG_PREEMPT_RT_FULL
133 const_debug unsigned int sysctl_sched_nr_migrate = 32;
135 const_debug unsigned int sysctl_sched_nr_migrate = 8;
139 * period over which we average the RT time consumption, measured
144 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
147 * period over which we measure -rt task cpu usage in us.
150 unsigned int sysctl_sched_rt_period = 1000000;
152 __read_mostly int scheduler_running;
155 * part of the period that we allow rt tasks to run in us.
158 int sysctl_sched_rt_runtime = 950000;
160 /* cpus with isolated domains */
161 cpumask_var_t cpu_isolated_map;
164 * this_rq_lock - lock this runqueue and disable interrupts.
166 static struct rq *this_rq_lock(void)
173 raw_spin_lock(&rq->lock);
179 * __task_rq_lock - lock the rq @p resides on.
181 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
186 lockdep_assert_held(&p->pi_lock);
190 raw_spin_lock(&rq->lock);
191 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
192 rf->cookie = lockdep_pin_lock(&rq->lock);
195 raw_spin_unlock(&rq->lock);
197 while (unlikely(task_on_rq_migrating(p)))
203 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
205 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
206 __acquires(p->pi_lock)
212 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
214 raw_spin_lock(&rq->lock);
216 * move_queued_task() task_rq_lock()
219 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
220 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
221 * [S] ->cpu = new_cpu [L] task_rq()
225 * If we observe the old cpu in task_rq_lock, the acquire of
226 * the old rq->lock will fully serialize against the stores.
228 * If we observe the new cpu in task_rq_lock, the acquire will
229 * pair with the WMB to ensure we must then also see migrating.
231 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
232 rf->cookie = lockdep_pin_lock(&rq->lock);
235 raw_spin_unlock(&rq->lock);
236 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
238 while (unlikely(task_on_rq_migrating(p)))
243 #ifdef CONFIG_SCHED_HRTICK
245 * Use HR-timers to deliver accurate preemption points.
248 static void hrtick_clear(struct rq *rq)
250 if (hrtimer_active(&rq->hrtick_timer))
251 hrtimer_cancel(&rq->hrtick_timer);
255 * High-resolution timer tick.
256 * Runs from hardirq context with interrupts disabled.
258 static enum hrtimer_restart hrtick(struct hrtimer *timer)
260 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
262 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
264 raw_spin_lock(&rq->lock);
266 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
267 raw_spin_unlock(&rq->lock);
269 return HRTIMER_NORESTART;
274 static void __hrtick_restart(struct rq *rq)
276 struct hrtimer *timer = &rq->hrtick_timer;
278 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
282 * called from hardirq (IPI) context
284 static void __hrtick_start(void *arg)
288 raw_spin_lock(&rq->lock);
289 __hrtick_restart(rq);
290 rq->hrtick_csd_pending = 0;
291 raw_spin_unlock(&rq->lock);
295 * Called to set the hrtick timer state.
297 * called with rq->lock held and irqs disabled
299 void hrtick_start(struct rq *rq, u64 delay)
301 struct hrtimer *timer = &rq->hrtick_timer;
306 * Don't schedule slices shorter than 10000ns, that just
307 * doesn't make sense and can cause timer DoS.
309 delta = max_t(s64, delay, 10000LL);
310 time = ktime_add_ns(timer->base->get_time(), delta);
312 hrtimer_set_expires(timer, time);
314 if (rq == this_rq()) {
315 __hrtick_restart(rq);
316 } else if (!rq->hrtick_csd_pending) {
317 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
318 rq->hrtick_csd_pending = 1;
324 * Called to set the hrtick timer state.
326 * called with rq->lock held and irqs disabled
328 void hrtick_start(struct rq *rq, u64 delay)
331 * Don't schedule slices shorter than 10000ns, that just
332 * doesn't make sense. Rely on vruntime for fairness.
334 delay = max_t(u64, delay, 10000LL);
335 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
336 HRTIMER_MODE_REL_PINNED);
338 #endif /* CONFIG_SMP */
340 static void init_rq_hrtick(struct rq *rq)
343 rq->hrtick_csd_pending = 0;
345 rq->hrtick_csd.flags = 0;
346 rq->hrtick_csd.func = __hrtick_start;
347 rq->hrtick_csd.info = rq;
350 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
351 rq->hrtick_timer.function = hrtick;
352 rq->hrtick_timer.irqsafe = 1;
354 #else /* CONFIG_SCHED_HRTICK */
355 static inline void hrtick_clear(struct rq *rq)
359 static inline void init_rq_hrtick(struct rq *rq)
362 #endif /* CONFIG_SCHED_HRTICK */
365 * cmpxchg based fetch_or, macro so it works for different integer types
367 #define fetch_or(ptr, mask) \
369 typeof(ptr) _ptr = (ptr); \
370 typeof(mask) _mask = (mask); \
371 typeof(*_ptr) _old, _val = *_ptr; \
374 _old = cmpxchg(_ptr, _val, _val | _mask); \
382 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
384 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
385 * this avoids any races wrt polling state changes and thereby avoids
388 static bool set_nr_and_not_polling(struct task_struct *p)
390 struct thread_info *ti = task_thread_info(p);
391 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
395 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
397 * If this returns true, then the idle task promises to call
398 * sched_ttwu_pending() and reschedule soon.
400 static bool set_nr_if_polling(struct task_struct *p)
402 struct thread_info *ti = task_thread_info(p);
403 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
406 if (!(val & _TIF_POLLING_NRFLAG))
408 if (val & _TIF_NEED_RESCHED)
410 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
419 static bool set_nr_and_not_polling(struct task_struct *p)
421 set_tsk_need_resched(p);
426 static bool set_nr_if_polling(struct task_struct *p)
433 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
435 struct wake_q_node *node = &task->wake_q;
438 * Atomically grab the task, if ->wake_q is !nil already it means
439 * its already queued (either by us or someone else) and will get the
440 * wakeup due to that.
442 * This cmpxchg() implies a full barrier, which pairs with the write
443 * barrier implied by the wakeup in wake_up_q().
445 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
448 get_task_struct(task);
451 * The head is context local, there can be no concurrency.
454 head->lastp = &node->next;
457 void __wake_up_q(struct wake_q_head *head, bool sleeper)
459 struct wake_q_node *node = head->first;
461 while (node != WAKE_Q_TAIL) {
462 struct task_struct *task;
464 task = container_of(node, struct task_struct, wake_q);
466 /* task can safely be re-inserted now */
468 task->wake_q.next = NULL;
471 * wake_up_process() implies a wmb() to pair with the queueing
472 * in wake_q_add() so as not to miss wakeups.
475 wake_up_lock_sleeper(task);
477 wake_up_process(task);
478 put_task_struct(task);
483 * resched_curr - mark rq's current task 'to be rescheduled now'.
485 * On UP this means the setting of the need_resched flag, on SMP it
486 * might also involve a cross-CPU call to trigger the scheduler on
489 void resched_curr(struct rq *rq)
491 struct task_struct *curr = rq->curr;
494 lockdep_assert_held(&rq->lock);
496 if (test_tsk_need_resched(curr))
501 if (cpu == smp_processor_id()) {
502 set_tsk_need_resched(curr);
503 set_preempt_need_resched();
507 if (set_nr_and_not_polling(curr))
508 smp_send_reschedule(cpu);
510 trace_sched_wake_idle_without_ipi(cpu);
513 #ifdef CONFIG_PREEMPT_LAZY
514 void resched_curr_lazy(struct rq *rq)
516 struct task_struct *curr = rq->curr;
519 if (!sched_feat(PREEMPT_LAZY)) {
524 lockdep_assert_held(&rq->lock);
526 if (test_tsk_need_resched(curr))
529 if (test_tsk_need_resched_lazy(curr))
532 set_tsk_need_resched_lazy(curr);
535 if (cpu == smp_processor_id())
538 /* NEED_RESCHED_LAZY must be visible before we test polling */
540 if (!tsk_is_polling(curr))
541 smp_send_reschedule(cpu);
545 void resched_cpu(int cpu)
547 struct rq *rq = cpu_rq(cpu);
550 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
553 raw_spin_unlock_irqrestore(&rq->lock, flags);
557 #ifdef CONFIG_NO_HZ_COMMON
559 * In the semi idle case, use the nearest busy cpu for migrating timers
560 * from an idle cpu. This is good for power-savings.
562 * We don't do similar optimization for completely idle system, as
563 * selecting an idle cpu will add more delays to the timers than intended
564 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
566 int get_nohz_timer_target(void)
569 struct sched_domain *sd;
571 preempt_disable_rt();
572 cpu = smp_processor_id();
574 if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
578 for_each_domain(cpu, sd) {
579 for_each_cpu(i, sched_domain_span(sd)) {
583 if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
590 if (!is_housekeeping_cpu(cpu))
591 cpu = housekeeping_any_cpu();
599 * When add_timer_on() enqueues a timer into the timer wheel of an
600 * idle CPU then this timer might expire before the next timer event
601 * which is scheduled to wake up that CPU. In case of a completely
602 * idle system the next event might even be infinite time into the
603 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
604 * leaves the inner idle loop so the newly added timer is taken into
605 * account when the CPU goes back to idle and evaluates the timer
606 * wheel for the next timer event.
608 static void wake_up_idle_cpu(int cpu)
610 struct rq *rq = cpu_rq(cpu);
612 if (cpu == smp_processor_id())
615 if (set_nr_and_not_polling(rq->idle))
616 smp_send_reschedule(cpu);
618 trace_sched_wake_idle_without_ipi(cpu);
621 static bool wake_up_full_nohz_cpu(int cpu)
624 * We just need the target to call irq_exit() and re-evaluate
625 * the next tick. The nohz full kick at least implies that.
626 * If needed we can still optimize that later with an
629 if (cpu_is_offline(cpu))
630 return true; /* Don't try to wake offline CPUs. */
631 if (tick_nohz_full_cpu(cpu)) {
632 if (cpu != smp_processor_id() ||
633 tick_nohz_tick_stopped())
634 tick_nohz_full_kick_cpu(cpu);
642 * Wake up the specified CPU. If the CPU is going offline, it is the
643 * caller's responsibility to deal with the lost wakeup, for example,
644 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
646 void wake_up_nohz_cpu(int cpu)
648 if (!wake_up_full_nohz_cpu(cpu))
649 wake_up_idle_cpu(cpu);
652 static inline bool got_nohz_idle_kick(void)
654 int cpu = smp_processor_id();
656 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
659 if (idle_cpu(cpu) && !need_resched())
663 * We can't run Idle Load Balance on this CPU for this time so we
664 * cancel it and clear NOHZ_BALANCE_KICK
666 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
670 #else /* CONFIG_NO_HZ_COMMON */
672 static inline bool got_nohz_idle_kick(void)
677 #endif /* CONFIG_NO_HZ_COMMON */
679 #ifdef CONFIG_NO_HZ_FULL
680 bool sched_can_stop_tick(struct rq *rq)
684 /* Deadline tasks, even if single, need the tick */
685 if (rq->dl.dl_nr_running)
689 * If there are more than one RR tasks, we need the tick to effect the
690 * actual RR behaviour.
692 if (rq->rt.rr_nr_running) {
693 if (rq->rt.rr_nr_running == 1)
700 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
701 * forced preemption between FIFO tasks.
703 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
708 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
709 * if there's more than one we need the tick for involuntary
712 if (rq->nr_running > 1)
717 #endif /* CONFIG_NO_HZ_FULL */
719 void sched_avg_update(struct rq *rq)
721 s64 period = sched_avg_period();
723 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
725 * Inline assembly required to prevent the compiler
726 * optimising this loop into a divmod call.
727 * See __iter_div_u64_rem() for another example of this.
729 asm("" : "+rm" (rq->age_stamp));
730 rq->age_stamp += period;
735 #endif /* CONFIG_SMP */
737 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
738 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
740 * Iterate task_group tree rooted at *from, calling @down when first entering a
741 * node and @up when leaving it for the final time.
743 * Caller must hold rcu_lock or sufficient equivalent.
745 int walk_tg_tree_from(struct task_group *from,
746 tg_visitor down, tg_visitor up, void *data)
748 struct task_group *parent, *child;
754 ret = (*down)(parent, data);
757 list_for_each_entry_rcu(child, &parent->children, siblings) {
764 ret = (*up)(parent, data);
765 if (ret || parent == from)
769 parent = parent->parent;
776 int tg_nop(struct task_group *tg, void *data)
782 static void set_load_weight(struct task_struct *p)
784 int prio = p->static_prio - MAX_RT_PRIO;
785 struct load_weight *load = &p->se.load;
788 * SCHED_IDLE tasks get minimal weight:
790 if (idle_policy(p->policy)) {
791 load->weight = scale_load(WEIGHT_IDLEPRIO);
792 load->inv_weight = WMULT_IDLEPRIO;
796 load->weight = scale_load(sched_prio_to_weight[prio]);
797 load->inv_weight = sched_prio_to_wmult[prio];
800 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
803 if (!(flags & ENQUEUE_RESTORE))
804 sched_info_queued(rq, p);
805 p->sched_class->enqueue_task(rq, p, flags);
808 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
811 if (!(flags & DEQUEUE_SAVE))
812 sched_info_dequeued(rq, p);
813 p->sched_class->dequeue_task(rq, p, flags);
816 void activate_task(struct rq *rq, struct task_struct *p, int flags)
818 if (task_contributes_to_load(p))
819 rq->nr_uninterruptible--;
821 enqueue_task(rq, p, flags);
824 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
826 if (task_contributes_to_load(p))
827 rq->nr_uninterruptible++;
829 dequeue_task(rq, p, flags);
832 static void update_rq_clock_task(struct rq *rq, s64 delta)
835 * In theory, the compile should just see 0 here, and optimize out the call
836 * to sched_rt_avg_update. But I don't trust it...
838 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
839 s64 steal = 0, irq_delta = 0;
841 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
842 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
845 * Since irq_time is only updated on {soft,}irq_exit, we might run into
846 * this case when a previous update_rq_clock() happened inside a
849 * When this happens, we stop ->clock_task and only update the
850 * prev_irq_time stamp to account for the part that fit, so that a next
851 * update will consume the rest. This ensures ->clock_task is
854 * It does however cause some slight miss-attribution of {soft,}irq
855 * time, a more accurate solution would be to update the irq_time using
856 * the current rq->clock timestamp, except that would require using
859 if (irq_delta > delta)
862 rq->prev_irq_time += irq_delta;
865 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
866 if (static_key_false((¶virt_steal_rq_enabled))) {
867 steal = paravirt_steal_clock(cpu_of(rq));
868 steal -= rq->prev_steal_time_rq;
870 if (unlikely(steal > delta))
873 rq->prev_steal_time_rq += steal;
878 rq->clock_task += delta;
880 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
881 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
882 sched_rt_avg_update(rq, irq_delta + steal);
886 void sched_set_stop_task(int cpu, struct task_struct *stop)
888 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
889 struct task_struct *old_stop = cpu_rq(cpu)->stop;
893 * Make it appear like a SCHED_FIFO task, its something
894 * userspace knows about and won't get confused about.
896 * Also, it will make PI more or less work without too
897 * much confusion -- but then, stop work should not
898 * rely on PI working anyway.
900 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
902 stop->sched_class = &stop_sched_class;
905 cpu_rq(cpu)->stop = stop;
909 * Reset it back to a normal scheduling class so that
910 * it can die in pieces.
912 old_stop->sched_class = &rt_sched_class;
917 * __normal_prio - return the priority that is based on the static prio
919 static inline int __normal_prio(struct task_struct *p)
921 return p->static_prio;
925 * Calculate the expected normal priority: i.e. priority
926 * without taking RT-inheritance into account. Might be
927 * boosted by interactivity modifiers. Changes upon fork,
928 * setprio syscalls, and whenever the interactivity
929 * estimator recalculates.
931 static inline int normal_prio(struct task_struct *p)
935 if (task_has_dl_policy(p))
936 prio = MAX_DL_PRIO-1;
937 else if (task_has_rt_policy(p))
938 prio = MAX_RT_PRIO-1 - p->rt_priority;
940 prio = __normal_prio(p);
945 * Calculate the current priority, i.e. the priority
946 * taken into account by the scheduler. This value might
947 * be boosted by RT tasks, or might be boosted by
948 * interactivity modifiers. Will be RT if the task got
949 * RT-boosted. If not then it returns p->normal_prio.
951 static int effective_prio(struct task_struct *p)
953 p->normal_prio = normal_prio(p);
955 * If we are RT tasks or we were boosted to RT priority,
956 * keep the priority unchanged. Otherwise, update priority
957 * to the normal priority:
959 if (!rt_prio(p->prio))
960 return p->normal_prio;
965 * task_curr - is this task currently executing on a CPU?
966 * @p: the task in question.
968 * Return: 1 if the task is currently executing. 0 otherwise.
970 inline int task_curr(const struct task_struct *p)
972 return cpu_curr(task_cpu(p)) == p;
976 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
977 * use the balance_callback list if you want balancing.
979 * this means any call to check_class_changed() must be followed by a call to
980 * balance_callback().
982 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
983 const struct sched_class *prev_class,
986 if (prev_class != p->sched_class) {
987 if (prev_class->switched_from)
988 prev_class->switched_from(rq, p);
990 p->sched_class->switched_to(rq, p);
991 } else if (oldprio != p->prio || dl_task(p))
992 p->sched_class->prio_changed(rq, p, oldprio);
995 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
997 const struct sched_class *class;
999 if (p->sched_class == rq->curr->sched_class) {
1000 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
1002 for_each_class(class) {
1003 if (class == rq->curr->sched_class)
1005 if (class == p->sched_class) {
1013 * A queue event has occurred, and we're going to schedule. In
1014 * this case, we can save a useless back to back clock update.
1016 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
1017 rq_clock_skip_update(rq, true);
1022 * This is how migration works:
1024 * 1) we invoke migration_cpu_stop() on the target CPU using
1026 * 2) stopper starts to run (implicitly forcing the migrated thread
1028 * 3) it checks whether the migrated task is still in the wrong runqueue.
1029 * 4) if it's in the wrong runqueue then the migration thread removes
1030 * it and puts it into the right queue.
1031 * 5) stopper completes and stop_one_cpu() returns and the migration
1036 * move_queued_task - move a queued task to new rq.
1038 * Returns (locked) new rq. Old rq's lock is released.
1040 static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
1042 lockdep_assert_held(&rq->lock);
1044 p->on_rq = TASK_ON_RQ_MIGRATING;
1045 dequeue_task(rq, p, 0);
1046 set_task_cpu(p, new_cpu);
1047 raw_spin_unlock(&rq->lock);
1049 rq = cpu_rq(new_cpu);
1051 raw_spin_lock(&rq->lock);
1052 BUG_ON(task_cpu(p) != new_cpu);
1053 enqueue_task(rq, p, 0);
1054 p->on_rq = TASK_ON_RQ_QUEUED;
1055 check_preempt_curr(rq, p, 0);
1060 struct migration_arg {
1061 struct task_struct *task;
1066 * Move (not current) task off this cpu, onto dest cpu. We're doing
1067 * this because either it can't run here any more (set_cpus_allowed()
1068 * away from this CPU, or CPU going down), or because we're
1069 * attempting to rebalance this task on exec (sched_exec).
1071 * So we race with normal scheduler movements, but that's OK, as long
1072 * as the task is no longer on this CPU.
1074 static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
1076 if (unlikely(!cpu_active(dest_cpu)))
1079 /* Affinity changed (again). */
1080 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1083 rq = move_queued_task(rq, p, dest_cpu);
1089 * migration_cpu_stop - this will be executed by a highprio stopper thread
1090 * and performs thread migration by bumping thread off CPU then
1091 * 'pushing' onto another runqueue.
1093 static int migration_cpu_stop(void *data)
1095 struct migration_arg *arg = data;
1096 struct task_struct *p = arg->task;
1097 struct rq *rq = this_rq();
1100 * The original target cpu might have gone down and we might
1101 * be on another cpu but it doesn't matter.
1103 local_irq_disable();
1105 * We need to explicitly wake pending tasks before running
1106 * __migrate_task() such that we will not miss enforcing cpus_allowed
1107 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1109 sched_ttwu_pending();
1111 raw_spin_lock(&p->pi_lock);
1112 raw_spin_lock(&rq->lock);
1114 * If task_rq(p) != rq, it cannot be migrated here, because we're
1115 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1116 * we're holding p->pi_lock.
1118 if (task_rq(p) == rq) {
1119 if (task_on_rq_queued(p))
1120 rq = __migrate_task(rq, p, arg->dest_cpu);
1122 p->wake_cpu = arg->dest_cpu;
1124 raw_spin_unlock(&rq->lock);
1125 raw_spin_unlock(&p->pi_lock);
1132 * sched_class::set_cpus_allowed must do the below, but is not required to
1133 * actually call this function.
1135 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1137 cpumask_copy(&p->cpus_allowed, new_mask);
1138 p->nr_cpus_allowed = cpumask_weight(new_mask);
1141 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1143 struct rq *rq = task_rq(p);
1144 bool queued, running;
1146 lockdep_assert_held(&p->pi_lock);
1148 if (__migrate_disabled(p)) {
1149 cpumask_copy(&p->cpus_allowed, new_mask);
1153 queued = task_on_rq_queued(p);
1154 running = task_current(rq, p);
1158 * Because __kthread_bind() calls this on blocked tasks without
1161 lockdep_assert_held(&rq->lock);
1162 dequeue_task(rq, p, DEQUEUE_SAVE);
1165 put_prev_task(rq, p);
1167 p->sched_class->set_cpus_allowed(p, new_mask);
1170 enqueue_task(rq, p, ENQUEUE_RESTORE);
1172 set_curr_task(rq, p);
1175 static DEFINE_PER_CPU(struct cpumask, sched_cpumasks);
1176 static DEFINE_MUTEX(sched_down_mutex);
1177 static cpumask_t sched_down_cpumask;
1179 void tell_sched_cpu_down_begin(int cpu)
1181 mutex_lock(&sched_down_mutex);
1182 cpumask_set_cpu(cpu, &sched_down_cpumask);
1183 mutex_unlock(&sched_down_mutex);
1186 void tell_sched_cpu_down_done(int cpu)
1188 mutex_lock(&sched_down_mutex);
1189 cpumask_clear_cpu(cpu, &sched_down_cpumask);
1190 mutex_unlock(&sched_down_mutex);
1194 * migrate_me - try to move the current task off this cpu
1196 * Used by the pin_current_cpu() code to try to get tasks
1197 * to move off the current CPU as it is going down.
1198 * It will only move the task if the task isn't pinned to
1199 * the CPU (with migrate_disable, affinity or NO_SETAFFINITY)
1200 * and the task has to be in a RUNNING state. Otherwise the
1201 * movement of the task will wake it up (change its state
1202 * to running) when the task did not expect it.
1204 * Returns 1 if it succeeded in moving the current task
1207 int migrate_me(void)
1209 struct task_struct *p = current;
1210 struct migration_arg arg;
1211 struct cpumask *cpumask;
1212 struct cpumask *mask;
1213 unsigned int dest_cpu;
1218 * We can not migrate tasks bounded to a CPU or tasks not
1219 * running. The movement of the task will wake it up.
1221 if (p->flags & PF_NO_SETAFFINITY || p->state)
1224 mutex_lock(&sched_down_mutex);
1225 rq = task_rq_lock(p, &rf);
1227 cpumask = this_cpu_ptr(&sched_cpumasks);
1228 mask = &p->cpus_allowed;
1230 cpumask_andnot(cpumask, mask, &sched_down_cpumask);
1232 if (!cpumask_weight(cpumask)) {
1233 /* It's only on this CPU? */
1234 task_rq_unlock(rq, p, &rf);
1235 mutex_unlock(&sched_down_mutex);
1239 dest_cpu = cpumask_any_and(cpu_active_mask, cpumask);
1242 arg.dest_cpu = dest_cpu;
1244 task_rq_unlock(rq, p, &rf);
1246 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1247 tlb_migrate_finish(p->mm);
1248 mutex_unlock(&sched_down_mutex);
1254 * Change a given task's CPU affinity. Migrate the thread to a
1255 * proper CPU and schedule it away if the CPU it's executing on
1256 * is removed from the allowed bitmask.
1258 * NOTE: the caller must have a valid reference to the task, the
1259 * task must not exit() & deallocate itself prematurely. The
1260 * call is not atomic; no spinlocks may be held.
1262 static int __set_cpus_allowed_ptr(struct task_struct *p,
1263 const struct cpumask *new_mask, bool check)
1265 const struct cpumask *cpu_valid_mask = cpu_active_mask;
1266 unsigned int dest_cpu;
1271 rq = task_rq_lock(p, &rf);
1273 if (p->flags & PF_KTHREAD) {
1275 * Kernel threads are allowed on online && !active CPUs
1277 cpu_valid_mask = cpu_online_mask;
1281 * Must re-check here, to close a race against __kthread_bind(),
1282 * sched_setaffinity() is not guaranteed to observe the flag.
1284 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1289 if (cpumask_equal(&p->cpus_allowed, new_mask))
1292 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1297 do_set_cpus_allowed(p, new_mask);
1299 if (p->flags & PF_KTHREAD) {
1301 * For kernel threads that do indeed end up on online &&
1302 * !active we want to ensure they are strict per-cpu threads.
1304 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1305 !cpumask_intersects(new_mask, cpu_active_mask) &&
1306 p->nr_cpus_allowed != 1);
1309 /* Can the task run on the task's current CPU? If so, we're done */
1310 if (cpumask_test_cpu(task_cpu(p), new_mask) || __migrate_disabled(p))
1313 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1314 if (task_running(rq, p) || p->state == TASK_WAKING) {
1315 struct migration_arg arg = { p, dest_cpu };
1316 /* Need help from migration thread: drop lock and wait. */
1317 task_rq_unlock(rq, p, &rf);
1318 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1319 tlb_migrate_finish(p->mm);
1321 } else if (task_on_rq_queued(p)) {
1323 * OK, since we're going to drop the lock immediately
1324 * afterwards anyway.
1326 lockdep_unpin_lock(&rq->lock, rf.cookie);
1327 rq = move_queued_task(rq, p, dest_cpu);
1328 lockdep_repin_lock(&rq->lock, rf.cookie);
1331 task_rq_unlock(rq, p, &rf);
1336 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1338 return __set_cpus_allowed_ptr(p, new_mask, false);
1340 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1342 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1344 #ifdef CONFIG_SCHED_DEBUG
1346 * We should never call set_task_cpu() on a blocked task,
1347 * ttwu() will sort out the placement.
1349 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1353 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1354 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1355 * time relying on p->on_rq.
1357 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1358 p->sched_class == &fair_sched_class &&
1359 (p->on_rq && !task_on_rq_migrating(p)));
1361 #ifdef CONFIG_LOCKDEP
1363 * The caller should hold either p->pi_lock or rq->lock, when changing
1364 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1366 * sched_move_task() holds both and thus holding either pins the cgroup,
1369 * Furthermore, all task_rq users should acquire both locks, see
1372 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1373 lockdep_is_held(&task_rq(p)->lock)));
1377 trace_sched_migrate_task(p, new_cpu);
1379 if (task_cpu(p) != new_cpu) {
1380 if (p->sched_class->migrate_task_rq)
1381 p->sched_class->migrate_task_rq(p);
1382 p->se.nr_migrations++;
1383 perf_event_task_migrate(p);
1386 __set_task_cpu(p, new_cpu);
1389 static void __migrate_swap_task(struct task_struct *p, int cpu)
1391 if (task_on_rq_queued(p)) {
1392 struct rq *src_rq, *dst_rq;
1394 src_rq = task_rq(p);
1395 dst_rq = cpu_rq(cpu);
1397 p->on_rq = TASK_ON_RQ_MIGRATING;
1398 deactivate_task(src_rq, p, 0);
1399 set_task_cpu(p, cpu);
1400 activate_task(dst_rq, p, 0);
1401 p->on_rq = TASK_ON_RQ_QUEUED;
1402 check_preempt_curr(dst_rq, p, 0);
1405 * Task isn't running anymore; make it appear like we migrated
1406 * it before it went to sleep. This means on wakeup we make the
1407 * previous cpu our target instead of where it really is.
1413 struct migration_swap_arg {
1414 struct task_struct *src_task, *dst_task;
1415 int src_cpu, dst_cpu;
1418 static int migrate_swap_stop(void *data)
1420 struct migration_swap_arg *arg = data;
1421 struct rq *src_rq, *dst_rq;
1424 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1427 src_rq = cpu_rq(arg->src_cpu);
1428 dst_rq = cpu_rq(arg->dst_cpu);
1430 double_raw_lock(&arg->src_task->pi_lock,
1431 &arg->dst_task->pi_lock);
1432 double_rq_lock(src_rq, dst_rq);
1434 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1437 if (task_cpu(arg->src_task) != arg->src_cpu)
1440 if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
1443 if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
1446 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1447 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1452 double_rq_unlock(src_rq, dst_rq);
1453 raw_spin_unlock(&arg->dst_task->pi_lock);
1454 raw_spin_unlock(&arg->src_task->pi_lock);
1460 * Cross migrate two tasks
1462 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1464 struct migration_swap_arg arg;
1467 arg = (struct migration_swap_arg){
1469 .src_cpu = task_cpu(cur),
1471 .dst_cpu = task_cpu(p),
1474 if (arg.src_cpu == arg.dst_cpu)
1478 * These three tests are all lockless; this is OK since all of them
1479 * will be re-checked with proper locks held further down the line.
1481 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1484 if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
1487 if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
1490 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1491 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1497 static bool check_task_state(struct task_struct *p, long match_state)
1501 raw_spin_lock_irq(&p->pi_lock);
1502 if (p->state == match_state || p->saved_state == match_state)
1504 raw_spin_unlock_irq(&p->pi_lock);
1510 * wait_task_inactive - wait for a thread to unschedule.
1512 * If @match_state is nonzero, it's the @p->state value just checked and
1513 * not expected to change. If it changes, i.e. @p might have woken up,
1514 * then return zero. When we succeed in waiting for @p to be off its CPU,
1515 * we return a positive number (its total switch count). If a second call
1516 * a short while later returns the same number, the caller can be sure that
1517 * @p has remained unscheduled the whole time.
1519 * The caller must ensure that the task *will* unschedule sometime soon,
1520 * else this function might spin for a *long* time. This function can't
1521 * be called with interrupts off, or it may introduce deadlock with
1522 * smp_call_function() if an IPI is sent by the same process we are
1523 * waiting to become inactive.
1525 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1527 int running, queued;
1534 * We do the initial early heuristics without holding
1535 * any task-queue locks at all. We'll only try to get
1536 * the runqueue lock when things look like they will
1542 * If the task is actively running on another CPU
1543 * still, just relax and busy-wait without holding
1546 * NOTE! Since we don't hold any locks, it's not
1547 * even sure that "rq" stays as the right runqueue!
1548 * But we don't care, since "task_running()" will
1549 * return false if the runqueue has changed and p
1550 * is actually now running somewhere else!
1552 while (task_running(rq, p)) {
1553 if (match_state && !check_task_state(p, match_state))
1559 * Ok, time to look more closely! We need the rq
1560 * lock now, to be *sure*. If we're wrong, we'll
1561 * just go back and repeat.
1563 rq = task_rq_lock(p, &rf);
1564 trace_sched_wait_task(p);
1565 running = task_running(rq, p);
1566 queued = task_on_rq_queued(p);
1568 if (!match_state || p->state == match_state ||
1569 p->saved_state == match_state)
1570 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1571 task_rq_unlock(rq, p, &rf);
1574 * If it changed from the expected state, bail out now.
1576 if (unlikely(!ncsw))
1580 * Was it really running after all now that we
1581 * checked with the proper locks actually held?
1583 * Oops. Go back and try again..
1585 if (unlikely(running)) {
1591 * It's not enough that it's not actively running,
1592 * it must be off the runqueue _entirely_, and not
1595 * So if it was still runnable (but just not actively
1596 * running right now), it's preempted, and we should
1597 * yield - it could be a while.
1599 if (unlikely(queued)) {
1600 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1602 set_current_state(TASK_UNINTERRUPTIBLE);
1603 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1608 * Ahh, all good. It wasn't running, and it wasn't
1609 * runnable, which means that it will never become
1610 * running in the future either. We're all done!
1619 * kick_process - kick a running thread to enter/exit the kernel
1620 * @p: the to-be-kicked thread
1622 * Cause a process which is running on another CPU to enter
1623 * kernel-mode, without any delay. (to get signals handled.)
1625 * NOTE: this function doesn't have to take the runqueue lock,
1626 * because all it wants to ensure is that the remote task enters
1627 * the kernel. If the IPI races and the task has been migrated
1628 * to another CPU then no harm is done and the purpose has been
1631 void kick_process(struct task_struct *p)
1637 if ((cpu != smp_processor_id()) && task_curr(p))
1638 smp_send_reschedule(cpu);
1641 EXPORT_SYMBOL_GPL(kick_process);
1644 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1646 * A few notes on cpu_active vs cpu_online:
1648 * - cpu_active must be a subset of cpu_online
1650 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1651 * see __set_cpus_allowed_ptr(). At this point the newly online
1652 * cpu isn't yet part of the sched domains, and balancing will not
1655 * - on cpu-down we clear cpu_active() to mask the sched domains and
1656 * avoid the load balancer to place new tasks on the to be removed
1657 * cpu. Existing tasks will remain running there and will be taken
1660 * This means that fallback selection must not select !active CPUs.
1661 * And can assume that any active CPU must be online. Conversely
1662 * select_task_rq() below may allow selection of !active CPUs in order
1663 * to satisfy the above rules.
1665 static int select_fallback_rq(int cpu, struct task_struct *p)
1667 int nid = cpu_to_node(cpu);
1668 const struct cpumask *nodemask = NULL;
1669 enum { cpuset, possible, fail } state = cpuset;
1673 * If the node that the cpu is on has been offlined, cpu_to_node()
1674 * will return -1. There is no cpu on the node, and we should
1675 * select the cpu on the other node.
1678 nodemask = cpumask_of_node(nid);
1680 /* Look for allowed, online CPU in same node. */
1681 for_each_cpu(dest_cpu, nodemask) {
1682 if (!cpu_active(dest_cpu))
1684 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1690 /* Any allowed, online CPU? */
1691 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1692 if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
1694 if (!cpu_online(dest_cpu))
1699 /* No more Mr. Nice Guy. */
1702 if (IS_ENABLED(CONFIG_CPUSETS)) {
1703 cpuset_cpus_allowed_fallback(p);
1709 do_set_cpus_allowed(p, cpu_possible_mask);
1720 if (state != cpuset) {
1722 * Don't tell them about moving exiting tasks or
1723 * kernel threads (both mm NULL), since they never
1726 if (p->mm && printk_ratelimit()) {
1727 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1728 task_pid_nr(p), p->comm, cpu);
1736 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1739 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1741 lockdep_assert_held(&p->pi_lock);
1743 if (tsk_nr_cpus_allowed(p) > 1)
1744 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1746 cpu = cpumask_any(tsk_cpus_allowed(p));
1749 * In order not to call set_task_cpu() on a blocking task we need
1750 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1753 * Since this is common to all placement strategies, this lives here.
1755 * [ this allows ->select_task() to simply return task_cpu(p) and
1756 * not worry about this generic constraint ]
1758 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1760 cpu = select_fallback_rq(task_cpu(p), p);
1765 static void update_avg(u64 *avg, u64 sample)
1767 s64 diff = sample - *avg;
1773 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1774 const struct cpumask *new_mask, bool check)
1776 return set_cpus_allowed_ptr(p, new_mask);
1779 #endif /* CONFIG_SMP */
1782 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1786 if (!schedstat_enabled())
1792 if (cpu == rq->cpu) {
1793 schedstat_inc(rq->ttwu_local);
1794 schedstat_inc(p->se.statistics.nr_wakeups_local);
1796 struct sched_domain *sd;
1798 schedstat_inc(p->se.statistics.nr_wakeups_remote);
1800 for_each_domain(rq->cpu, sd) {
1801 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1802 schedstat_inc(sd->ttwu_wake_remote);
1809 if (wake_flags & WF_MIGRATED)
1810 schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1811 #endif /* CONFIG_SMP */
1813 schedstat_inc(rq->ttwu_count);
1814 schedstat_inc(p->se.statistics.nr_wakeups);
1816 if (wake_flags & WF_SYNC)
1817 schedstat_inc(p->se.statistics.nr_wakeups_sync);
1820 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1822 activate_task(rq, p, en_flags);
1823 p->on_rq = TASK_ON_RQ_QUEUED;
1827 * Mark the task runnable and perform wakeup-preemption.
1829 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1830 struct pin_cookie cookie)
1832 check_preempt_curr(rq, p, wake_flags);
1833 p->state = TASK_RUNNING;
1834 trace_sched_wakeup(p);
1837 if (p->sched_class->task_woken) {
1839 * Our task @p is fully woken up and running; so its safe to
1840 * drop the rq->lock, hereafter rq is only used for statistics.
1842 lockdep_unpin_lock(&rq->lock, cookie);
1843 p->sched_class->task_woken(rq, p);
1844 lockdep_repin_lock(&rq->lock, cookie);
1847 if (rq->idle_stamp) {
1848 u64 delta = rq_clock(rq) - rq->idle_stamp;
1849 u64 max = 2*rq->max_idle_balance_cost;
1851 update_avg(&rq->avg_idle, delta);
1853 if (rq->avg_idle > max)
1862 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1863 struct pin_cookie cookie)
1865 int en_flags = ENQUEUE_WAKEUP;
1867 lockdep_assert_held(&rq->lock);
1870 if (p->sched_contributes_to_load)
1871 rq->nr_uninterruptible--;
1873 if (wake_flags & WF_MIGRATED)
1874 en_flags |= ENQUEUE_MIGRATED;
1877 ttwu_activate(rq, p, en_flags);
1878 ttwu_do_wakeup(rq, p, wake_flags, cookie);
1882 * Called in case the task @p isn't fully descheduled from its runqueue,
1883 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1884 * since all we need to do is flip p->state to TASK_RUNNING, since
1885 * the task is still ->on_rq.
1887 static int ttwu_remote(struct task_struct *p, int wake_flags)
1893 rq = __task_rq_lock(p, &rf);
1894 if (task_on_rq_queued(p)) {
1895 /* check_preempt_curr() may use rq clock */
1896 update_rq_clock(rq);
1897 ttwu_do_wakeup(rq, p, wake_flags, rf.cookie);
1900 __task_rq_unlock(rq, &rf);
1906 void sched_ttwu_pending(void)
1908 struct rq *rq = this_rq();
1909 struct llist_node *llist = llist_del_all(&rq->wake_list);
1910 struct pin_cookie cookie;
1911 struct task_struct *p;
1912 unsigned long flags;
1917 raw_spin_lock_irqsave(&rq->lock, flags);
1918 cookie = lockdep_pin_lock(&rq->lock);
1923 p = llist_entry(llist, struct task_struct, wake_entry);
1924 llist = llist_next(llist);
1926 if (p->sched_remote_wakeup)
1927 wake_flags = WF_MIGRATED;
1929 ttwu_do_activate(rq, p, wake_flags, cookie);
1932 lockdep_unpin_lock(&rq->lock, cookie);
1933 raw_spin_unlock_irqrestore(&rq->lock, flags);
1936 void scheduler_ipi(void)
1939 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1940 * TIF_NEED_RESCHED remotely (for the first time) will also send
1943 preempt_fold_need_resched();
1945 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1949 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1950 * traditionally all their work was done from the interrupt return
1951 * path. Now that we actually do some work, we need to make sure
1954 * Some archs already do call them, luckily irq_enter/exit nest
1957 * Arguably we should visit all archs and update all handlers,
1958 * however a fair share of IPIs are still resched only so this would
1959 * somewhat pessimize the simple resched case.
1962 sched_ttwu_pending();
1965 * Check if someone kicked us for doing the nohz idle load balance.
1967 if (unlikely(got_nohz_idle_kick())) {
1968 this_rq()->idle_balance = 1;
1969 raise_softirq_irqoff(SCHED_SOFTIRQ);
1974 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1976 struct rq *rq = cpu_rq(cpu);
1978 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1980 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1981 if (!set_nr_if_polling(rq->idle))
1982 smp_send_reschedule(cpu);
1984 trace_sched_wake_idle_without_ipi(cpu);
1988 void wake_up_if_idle(int cpu)
1990 struct rq *rq = cpu_rq(cpu);
1991 unsigned long flags;
1995 if (!is_idle_task(rcu_dereference(rq->curr)))
1998 if (set_nr_if_polling(rq->idle)) {
1999 trace_sched_wake_idle_without_ipi(cpu);
2001 raw_spin_lock_irqsave(&rq->lock, flags);
2002 if (is_idle_task(rq->curr))
2003 smp_send_reschedule(cpu);
2004 /* Else cpu is not in idle, do nothing here */
2005 raw_spin_unlock_irqrestore(&rq->lock, flags);
2012 bool cpus_share_cache(int this_cpu, int that_cpu)
2014 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
2016 #endif /* CONFIG_SMP */
2018 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
2020 struct rq *rq = cpu_rq(cpu);
2021 struct pin_cookie cookie;
2023 #if defined(CONFIG_SMP)
2024 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
2025 sched_clock_cpu(cpu); /* sync clocks x-cpu */
2026 ttwu_queue_remote(p, cpu, wake_flags);
2031 raw_spin_lock(&rq->lock);
2032 cookie = lockdep_pin_lock(&rq->lock);
2033 ttwu_do_activate(rq, p, wake_flags, cookie);
2034 lockdep_unpin_lock(&rq->lock, cookie);
2035 raw_spin_unlock(&rq->lock);
2039 * Notes on Program-Order guarantees on SMP systems.
2043 * The basic program-order guarantee on SMP systems is that when a task [t]
2044 * migrates, all its activity on its old cpu [c0] happens-before any subsequent
2045 * execution on its new cpu [c1].
2047 * For migration (of runnable tasks) this is provided by the following means:
2049 * A) UNLOCK of the rq(c0)->lock scheduling out task t
2050 * B) migration for t is required to synchronize *both* rq(c0)->lock and
2051 * rq(c1)->lock (if not at the same time, then in that order).
2052 * C) LOCK of the rq(c1)->lock scheduling in task
2054 * Transitivity guarantees that B happens after A and C after B.
2055 * Note: we only require RCpc transitivity.
2056 * Note: the cpu doing B need not be c0 or c1
2065 * UNLOCK rq(0)->lock
2067 * LOCK rq(0)->lock // orders against CPU0
2069 * UNLOCK rq(0)->lock
2073 * UNLOCK rq(1)->lock
2075 * LOCK rq(1)->lock // orders against CPU2
2078 * UNLOCK rq(1)->lock
2081 * BLOCKING -- aka. SLEEP + WAKEUP
2083 * For blocking we (obviously) need to provide the same guarantee as for
2084 * migration. However the means are completely different as there is no lock
2085 * chain to provide order. Instead we do:
2087 * 1) smp_store_release(X->on_cpu, 0)
2088 * 2) smp_cond_load_acquire(!X->on_cpu)
2092 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
2094 * LOCK rq(0)->lock LOCK X->pi_lock
2097 * smp_store_release(X->on_cpu, 0);
2099 * smp_cond_load_acquire(&X->on_cpu, !VAL);
2105 * X->state = RUNNING
2106 * UNLOCK rq(2)->lock
2108 * LOCK rq(2)->lock // orders against CPU1
2111 * UNLOCK rq(2)->lock
2114 * UNLOCK rq(0)->lock
2117 * However; for wakeups there is a second guarantee we must provide, namely we
2118 * must observe the state that lead to our wakeup. That is, not only must our
2119 * task observe its own prior state, it must also observe the stores prior to
2122 * This means that any means of doing remote wakeups must order the CPU doing
2123 * the wakeup against the CPU the task is going to end up running on. This,
2124 * however, is already required for the regular Program-Order guarantee above,
2125 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
2130 * try_to_wake_up - wake up a thread
2131 * @p: the thread to be awakened
2132 * @state: the mask of task states that can be woken
2133 * @wake_flags: wake modifier flags (WF_*)
2135 * Put it on the run-queue if it's not already there. The "current"
2136 * thread is always on the run-queue (except when the actual
2137 * re-schedule is in progress), and as such you're allowed to do
2138 * the simpler "current->state = TASK_RUNNING" to mark yourself
2139 * runnable without the overhead of this.
2141 * Return: %true if @p was woken up, %false if it was already running.
2142 * or @state didn't match @p's state.
2145 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
2147 unsigned long flags;
2148 int cpu, success = 0;
2151 * If we are going to wake up a thread waiting for CONDITION we
2152 * need to ensure that CONDITION=1 done by the caller can not be
2153 * reordered with p->state check below. This pairs with mb() in
2154 * set_current_state() the waiting thread does.
2156 smp_mb__before_spinlock();
2157 raw_spin_lock_irqsave(&p->pi_lock, flags);
2158 if (!(p->state & state)) {
2160 * The task might be running due to a spinlock sleeper
2161 * wakeup. Check the saved state and set it to running
2162 * if the wakeup condition is true.
2164 if (!(wake_flags & WF_LOCK_SLEEPER)) {
2165 if (p->saved_state & state) {
2166 p->saved_state = TASK_RUNNING;
2174 * If this is a regular wakeup, then we can unconditionally
2175 * clear the saved state of a "lock sleeper".
2177 if (!(wake_flags & WF_LOCK_SLEEPER))
2178 p->saved_state = TASK_RUNNING;
2180 trace_sched_waking(p);
2182 success = 1; /* we're going to change ->state */
2186 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2187 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2188 * in smp_cond_load_acquire() below.
2190 * sched_ttwu_pending() try_to_wake_up()
2191 * [S] p->on_rq = 1; [L] P->state
2192 * UNLOCK rq->lock -----.
2196 * LOCK rq->lock -----'
2200 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2202 * Pairs with the UNLOCK+LOCK on rq->lock from the
2203 * last wakeup of our task and the schedule that got our task
2207 if (p->on_rq && ttwu_remote(p, wake_flags))
2212 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2213 * possible to, falsely, observe p->on_cpu == 0.
2215 * One must be running (->on_cpu == 1) in order to remove oneself
2216 * from the runqueue.
2218 * [S] ->on_cpu = 1; [L] ->on_rq
2222 * [S] ->on_rq = 0; [L] ->on_cpu
2224 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2225 * from the consecutive calls to schedule(); the first switching to our
2226 * task, the second putting it to sleep.
2231 * If the owning (remote) cpu is still in the middle of schedule() with
2232 * this task as prev, wait until its done referencing the task.
2234 * Pairs with the smp_store_release() in finish_lock_switch().
2236 * This ensures that tasks getting woken will be fully ordered against
2237 * their previous state and preserve Program Order.
2239 smp_cond_load_acquire(&p->on_cpu, !VAL);
2241 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2242 p->state = TASK_WAKING;
2244 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2245 if (task_cpu(p) != cpu) {
2246 wake_flags |= WF_MIGRATED;
2247 set_task_cpu(p, cpu);
2249 #endif /* CONFIG_SMP */
2251 ttwu_queue(p, cpu, wake_flags);
2253 ttwu_stat(p, cpu, wake_flags);
2255 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2261 * wake_up_process - Wake up a specific process
2262 * @p: The process to be woken up.
2264 * Attempt to wake up the nominated process and move it to the set of runnable
2267 * Return: 1 if the process was woken up, 0 if it was already running.
2269 * It may be assumed that this function implies a write memory barrier before
2270 * changing the task state if and only if any tasks are woken up.
2272 int wake_up_process(struct task_struct *p)
2274 return try_to_wake_up(p, TASK_NORMAL, 0);
2276 EXPORT_SYMBOL(wake_up_process);
2279 * wake_up_lock_sleeper - Wake up a specific process blocked on a "sleeping lock"
2280 * @p: The process to be woken up.
2282 * Same as wake_up_process() above, but wake_flags=WF_LOCK_SLEEPER to indicate
2283 * the nature of the wakeup.
2285 int wake_up_lock_sleeper(struct task_struct *p)
2287 return try_to_wake_up(p, TASK_ALL, WF_LOCK_SLEEPER);
2290 int wake_up_state(struct task_struct *p, unsigned int state)
2292 return try_to_wake_up(p, state, 0);
2296 * This function clears the sched_dl_entity static params.
2298 void __dl_clear_params(struct task_struct *p)
2300 struct sched_dl_entity *dl_se = &p->dl;
2302 dl_se->dl_runtime = 0;
2303 dl_se->dl_deadline = 0;
2304 dl_se->dl_period = 0;
2308 dl_se->dl_throttled = 0;
2309 dl_se->dl_yielded = 0;
2313 * Perform scheduler related setup for a newly forked process p.
2314 * p is forked by current.
2316 * __sched_fork() is basic setup used by init_idle() too:
2318 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2323 p->se.exec_start = 0;
2324 p->se.sum_exec_runtime = 0;
2325 p->se.prev_sum_exec_runtime = 0;
2326 p->se.nr_migrations = 0;
2328 INIT_LIST_HEAD(&p->se.group_node);
2330 #ifdef CONFIG_FAIR_GROUP_SCHED
2331 p->se.cfs_rq = NULL;
2334 #ifdef CONFIG_SCHEDSTATS
2335 /* Even if schedstat is disabled, there should not be garbage */
2336 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2339 RB_CLEAR_NODE(&p->dl.rb_node);
2340 init_dl_task_timer(&p->dl);
2341 __dl_clear_params(p);
2343 INIT_LIST_HEAD(&p->rt.run_list);
2345 p->rt.time_slice = sched_rr_timeslice;
2349 #ifdef CONFIG_PREEMPT_NOTIFIERS
2350 INIT_HLIST_HEAD(&p->preempt_notifiers);
2353 #ifdef CONFIG_NUMA_BALANCING
2354 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
2355 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2356 p->mm->numa_scan_seq = 0;
2359 if (clone_flags & CLONE_VM)
2360 p->numa_preferred_nid = current->numa_preferred_nid;
2362 p->numa_preferred_nid = -1;
2364 p->node_stamp = 0ULL;
2365 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
2366 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2367 p->numa_work.next = &p->numa_work;
2368 p->numa_faults = NULL;
2369 p->last_task_numa_placement = 0;
2370 p->last_sum_exec_runtime = 0;
2372 p->numa_group = NULL;
2373 #endif /* CONFIG_NUMA_BALANCING */
2376 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2378 #ifdef CONFIG_NUMA_BALANCING
2380 void set_numabalancing_state(bool enabled)
2383 static_branch_enable(&sched_numa_balancing);
2385 static_branch_disable(&sched_numa_balancing);
2388 #ifdef CONFIG_PROC_SYSCTL
2389 int sysctl_numa_balancing(struct ctl_table *table, int write,
2390 void __user *buffer, size_t *lenp, loff_t *ppos)
2394 int state = static_branch_likely(&sched_numa_balancing);
2396 if (write && !capable(CAP_SYS_ADMIN))
2401 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2405 set_numabalancing_state(state);
2411 #ifdef CONFIG_SCHEDSTATS
2413 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2414 static bool __initdata __sched_schedstats = false;
2416 static void set_schedstats(bool enabled)
2419 static_branch_enable(&sched_schedstats);
2421 static_branch_disable(&sched_schedstats);
2424 void force_schedstat_enabled(void)
2426 if (!schedstat_enabled()) {
2427 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2428 static_branch_enable(&sched_schedstats);
2432 static int __init setup_schedstats(char *str)
2439 * This code is called before jump labels have been set up, so we can't
2440 * change the static branch directly just yet. Instead set a temporary
2441 * variable so init_schedstats() can do it later.
2443 if (!strcmp(str, "enable")) {
2444 __sched_schedstats = true;
2446 } else if (!strcmp(str, "disable")) {
2447 __sched_schedstats = false;
2452 pr_warn("Unable to parse schedstats=\n");
2456 __setup("schedstats=", setup_schedstats);
2458 static void __init init_schedstats(void)
2460 set_schedstats(__sched_schedstats);
2463 #ifdef CONFIG_PROC_SYSCTL
2464 int sysctl_schedstats(struct ctl_table *table, int write,
2465 void __user *buffer, size_t *lenp, loff_t *ppos)
2469 int state = static_branch_likely(&sched_schedstats);
2471 if (write && !capable(CAP_SYS_ADMIN))
2476 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2480 set_schedstats(state);
2483 #endif /* CONFIG_PROC_SYSCTL */
2484 #else /* !CONFIG_SCHEDSTATS */
2485 static inline void init_schedstats(void) {}
2486 #endif /* CONFIG_SCHEDSTATS */
2489 * fork()/clone()-time setup:
2491 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2493 unsigned long flags;
2494 int cpu = get_cpu();
2496 __sched_fork(clone_flags, p);
2498 * We mark the process as NEW here. This guarantees that
2499 * nobody will actually run it, and a signal or other external
2500 * event cannot wake it up and insert it on the runqueue either.
2502 p->state = TASK_NEW;
2505 * Make sure we do not leak PI boosting priority to the child.
2507 p->prio = current->normal_prio;
2510 * Revert to default priority/policy on fork if requested.
2512 if (unlikely(p->sched_reset_on_fork)) {
2513 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2514 p->policy = SCHED_NORMAL;
2515 p->static_prio = NICE_TO_PRIO(0);
2517 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2518 p->static_prio = NICE_TO_PRIO(0);
2520 p->prio = p->normal_prio = __normal_prio(p);
2524 * We don't need the reset flag anymore after the fork. It has
2525 * fulfilled its duty:
2527 p->sched_reset_on_fork = 0;
2530 if (dl_prio(p->prio)) {
2533 } else if (rt_prio(p->prio)) {
2534 p->sched_class = &rt_sched_class;
2536 p->sched_class = &fair_sched_class;
2539 init_entity_runnable_average(&p->se);
2542 * The child is not yet in the pid-hash so no cgroup attach races,
2543 * and the cgroup is pinned to this child due to cgroup_fork()
2544 * is ran before sched_fork().
2546 * Silence PROVE_RCU.
2548 raw_spin_lock_irqsave(&p->pi_lock, flags);
2550 * We're setting the cpu for the first time, we don't migrate,
2551 * so use __set_task_cpu().
2553 __set_task_cpu(p, cpu);
2554 if (p->sched_class->task_fork)
2555 p->sched_class->task_fork(p);
2556 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2558 #ifdef CONFIG_SCHED_INFO
2559 if (likely(sched_info_on()))
2560 memset(&p->sched_info, 0, sizeof(p->sched_info));
2562 #if defined(CONFIG_SMP)
2565 init_task_preempt_count(p);
2566 #ifdef CONFIG_HAVE_PREEMPT_LAZY
2567 task_thread_info(p)->preempt_lazy_count = 0;
2570 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2571 RB_CLEAR_NODE(&p->pushable_dl_tasks);
2578 unsigned long to_ratio(u64 period, u64 runtime)
2580 if (runtime == RUNTIME_INF)
2584 * Doing this here saves a lot of checks in all
2585 * the calling paths, and returning zero seems
2586 * safe for them anyway.
2591 return div64_u64(runtime << 20, period);
2595 inline struct dl_bw *dl_bw_of(int i)
2597 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2598 "sched RCU must be held");
2599 return &cpu_rq(i)->rd->dl_bw;
2602 static inline int dl_bw_cpus(int i)
2604 struct root_domain *rd = cpu_rq(i)->rd;
2607 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2608 "sched RCU must be held");
2609 for_each_cpu_and(i, rd->span, cpu_active_mask)
2615 inline struct dl_bw *dl_bw_of(int i)
2617 return &cpu_rq(i)->dl.dl_bw;
2620 static inline int dl_bw_cpus(int i)
2627 * We must be sure that accepting a new task (or allowing changing the
2628 * parameters of an existing one) is consistent with the bandwidth
2629 * constraints. If yes, this function also accordingly updates the currently
2630 * allocated bandwidth to reflect the new situation.
2632 * This function is called while holding p's rq->lock.
2634 * XXX we should delay bw change until the task's 0-lag point, see
2637 static int dl_overflow(struct task_struct *p, int policy,
2638 const struct sched_attr *attr)
2641 struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2642 u64 period = attr->sched_period ?: attr->sched_deadline;
2643 u64 runtime = attr->sched_runtime;
2644 u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2647 /* !deadline task may carry old deadline bandwidth */
2648 if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
2652 * Either if a task, enters, leave, or stays -deadline but changes
2653 * its parameters, we may need to update accordingly the total
2654 * allocated bandwidth of the container.
2656 raw_spin_lock(&dl_b->lock);
2657 cpus = dl_bw_cpus(task_cpu(p));
2658 if (dl_policy(policy) && !task_has_dl_policy(p) &&
2659 !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2660 __dl_add(dl_b, new_bw);
2662 } else if (dl_policy(policy) && task_has_dl_policy(p) &&
2663 !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2664 __dl_clear(dl_b, p->dl.dl_bw);
2665 __dl_add(dl_b, new_bw);
2667 } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2668 __dl_clear(dl_b, p->dl.dl_bw);
2671 raw_spin_unlock(&dl_b->lock);
2676 extern void init_dl_bw(struct dl_bw *dl_b);
2679 * wake_up_new_task - wake up a newly created task for the first time.
2681 * This function will do some initial scheduler statistics housekeeping
2682 * that must be done for every newly created context, then puts the task
2683 * on the runqueue and wakes it.
2685 void wake_up_new_task(struct task_struct *p)
2690 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2691 p->state = TASK_RUNNING;
2694 * Fork balancing, do it here and not earlier because:
2695 * - cpus_allowed can change in the fork path
2696 * - any previously selected cpu might disappear through hotplug
2698 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2699 * as we're not fully set-up yet.
2701 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2703 rq = __task_rq_lock(p, &rf);
2704 post_init_entity_util_avg(&p->se);
2706 activate_task(rq, p, 0);
2707 p->on_rq = TASK_ON_RQ_QUEUED;
2708 trace_sched_wakeup_new(p);
2709 check_preempt_curr(rq, p, WF_FORK);
2711 if (p->sched_class->task_woken) {
2713 * Nothing relies on rq->lock after this, so its fine to
2716 lockdep_unpin_lock(&rq->lock, rf.cookie);
2717 p->sched_class->task_woken(rq, p);
2718 lockdep_repin_lock(&rq->lock, rf.cookie);
2721 task_rq_unlock(rq, p, &rf);
2724 #ifdef CONFIG_PREEMPT_NOTIFIERS
2726 static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2728 void preempt_notifier_inc(void)
2730 static_key_slow_inc(&preempt_notifier_key);
2732 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2734 void preempt_notifier_dec(void)
2736 static_key_slow_dec(&preempt_notifier_key);
2738 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2741 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2742 * @notifier: notifier struct to register
2744 void preempt_notifier_register(struct preempt_notifier *notifier)
2746 if (!static_key_false(&preempt_notifier_key))
2747 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2749 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2751 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2754 * preempt_notifier_unregister - no longer interested in preemption notifications
2755 * @notifier: notifier struct to unregister
2757 * This is *not* safe to call from within a preemption notifier.
2759 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2761 hlist_del(¬ifier->link);
2763 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2765 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2767 struct preempt_notifier *notifier;
2769 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2770 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2773 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2775 if (static_key_false(&preempt_notifier_key))
2776 __fire_sched_in_preempt_notifiers(curr);
2780 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2781 struct task_struct *next)
2783 struct preempt_notifier *notifier;
2785 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2786 notifier->ops->sched_out(notifier, next);
2789 static __always_inline void
2790 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2791 struct task_struct *next)
2793 if (static_key_false(&preempt_notifier_key))
2794 __fire_sched_out_preempt_notifiers(curr, next);
2797 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2799 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2804 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2805 struct task_struct *next)
2809 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2812 * prepare_task_switch - prepare to switch tasks
2813 * @rq: the runqueue preparing to switch
2814 * @prev: the current task that is being switched out
2815 * @next: the task we are going to switch to.
2817 * This is called with the rq lock held and interrupts off. It must
2818 * be paired with a subsequent finish_task_switch after the context
2821 * prepare_task_switch sets up locking and calls architecture specific
2825 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2826 struct task_struct *next)
2828 sched_info_switch(rq, prev, next);
2829 perf_event_task_sched_out(prev, next);
2830 fire_sched_out_preempt_notifiers(prev, next);
2831 prepare_lock_switch(rq, next);
2832 prepare_arch_switch(next);
2836 * finish_task_switch - clean up after a task-switch
2837 * @prev: the thread we just switched away from.
2839 * finish_task_switch must be called after the context switch, paired
2840 * with a prepare_task_switch call before the context switch.
2841 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2842 * and do any other architecture-specific cleanup actions.
2844 * Note that we may have delayed dropping an mm in context_switch(). If
2845 * so, we finish that here outside of the runqueue lock. (Doing it
2846 * with the lock held can cause deadlocks; see schedule() for
2849 * The context switch have flipped the stack from under us and restored the
2850 * local variables which were saved when this task called schedule() in the
2851 * past. prev == current is still correct but we need to recalculate this_rq
2852 * because prev may have moved to another CPU.
2854 static struct rq *finish_task_switch(struct task_struct *prev)
2855 __releases(rq->lock)
2857 struct rq *rq = this_rq();
2858 struct mm_struct *mm = rq->prev_mm;
2862 * The previous task will have left us with a preempt_count of 2
2863 * because it left us after:
2866 * preempt_disable(); // 1
2868 * raw_spin_lock_irq(&rq->lock) // 2
2870 * Also, see FORK_PREEMPT_COUNT.
2872 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2873 "corrupted preempt_count: %s/%d/0x%x\n",
2874 current->comm, current->pid, preempt_count()))
2875 preempt_count_set(FORK_PREEMPT_COUNT);
2880 * A task struct has one reference for the use as "current".
2881 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2882 * schedule one last time. The schedule call will never return, and
2883 * the scheduled task must drop that reference.
2885 * We must observe prev->state before clearing prev->on_cpu (in
2886 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2887 * running on another CPU and we could rave with its RUNNING -> DEAD
2888 * transition, resulting in a double drop.
2890 prev_state = prev->state;
2891 vtime_task_switch(prev);
2892 perf_event_task_sched_in(prev, current);
2893 finish_lock_switch(rq, prev);
2894 finish_arch_post_lock_switch();
2896 fire_sched_in_preempt_notifiers(current);
2898 * We use mmdrop_delayed() here so we don't have to do the
2899 * full __mmdrop() when we are the last user.
2903 if (unlikely(prev_state == TASK_DEAD)) {
2904 if (prev->sched_class->task_dead)
2905 prev->sched_class->task_dead(prev);
2907 put_task_struct(prev);
2910 tick_nohz_task_switch();
2916 /* rq->lock is NOT held, but preemption is disabled */
2917 static void __balance_callback(struct rq *rq)
2919 struct callback_head *head, *next;
2920 void (*func)(struct rq *rq);
2921 unsigned long flags;
2923 raw_spin_lock_irqsave(&rq->lock, flags);
2924 head = rq->balance_callback;
2925 rq->balance_callback = NULL;
2927 func = (void (*)(struct rq *))head->func;
2934 raw_spin_unlock_irqrestore(&rq->lock, flags);
2937 static inline void balance_callback(struct rq *rq)
2939 if (unlikely(rq->balance_callback))
2940 __balance_callback(rq);
2945 static inline void balance_callback(struct rq *rq)
2952 * schedule_tail - first thing a freshly forked thread must call.
2953 * @prev: the thread we just switched away from.
2955 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2956 __releases(rq->lock)
2961 * New tasks start with FORK_PREEMPT_COUNT, see there and
2962 * finish_task_switch() for details.
2964 * finish_task_switch() will drop rq->lock() and lower preempt_count
2965 * and the preempt_enable() will end up enabling preemption (on
2966 * PREEMPT_COUNT kernels).
2969 rq = finish_task_switch(prev);
2970 balance_callback(rq);
2973 if (current->set_child_tid)
2974 put_user(task_pid_vnr(current), current->set_child_tid);
2978 * context_switch - switch to the new MM and the new thread's register state.
2980 static __always_inline struct rq *
2981 context_switch(struct rq *rq, struct task_struct *prev,
2982 struct task_struct *next, struct pin_cookie cookie)
2984 struct mm_struct *mm, *oldmm;
2986 prepare_task_switch(rq, prev, next);
2989 oldmm = prev->active_mm;
2991 * For paravirt, this is coupled with an exit in switch_to to
2992 * combine the page table reload and the switch backend into
2995 arch_start_context_switch(prev);
2998 next->active_mm = oldmm;
2999 atomic_inc(&oldmm->mm_count);
3000 enter_lazy_tlb(oldmm, next);
3002 switch_mm_irqs_off(oldmm, mm, next);
3005 prev->active_mm = NULL;
3006 rq->prev_mm = oldmm;
3009 * Since the runqueue lock will be released by the next
3010 * task (which is an invalid locking op but in the case
3011 * of the scheduler it's an obvious special-case), so we
3012 * do an early lockdep release here:
3014 lockdep_unpin_lock(&rq->lock, cookie);
3015 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3017 /* Here we just switch the register state and the stack. */
3018 switch_to(prev, next, prev);
3021 return finish_task_switch(prev);
3025 * nr_running and nr_context_switches:
3027 * externally visible scheduler statistics: current number of runnable
3028 * threads, total number of context switches performed since bootup.
3030 unsigned long nr_running(void)
3032 unsigned long i, sum = 0;
3034 for_each_online_cpu(i)
3035 sum += cpu_rq(i)->nr_running;
3041 * Check if only the current task is running on the cpu.
3043 * Caution: this function does not check that the caller has disabled
3044 * preemption, thus the result might have a time-of-check-to-time-of-use
3045 * race. The caller is responsible to use it correctly, for example:
3047 * - from a non-preemptable section (of course)
3049 * - from a thread that is bound to a single CPU
3051 * - in a loop with very short iterations (e.g. a polling loop)
3053 bool single_task_running(void)
3055 return raw_rq()->nr_running == 1;
3057 EXPORT_SYMBOL(single_task_running);
3059 unsigned long long nr_context_switches(void)
3062 unsigned long long sum = 0;
3064 for_each_possible_cpu(i)
3065 sum += cpu_rq(i)->nr_switches;
3070 unsigned long nr_iowait(void)
3072 unsigned long i, sum = 0;
3074 for_each_possible_cpu(i)
3075 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3080 unsigned long nr_iowait_cpu(int cpu)
3082 struct rq *this = cpu_rq(cpu);
3083 return atomic_read(&this->nr_iowait);
3086 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
3088 struct rq *rq = this_rq();
3089 *nr_waiters = atomic_read(&rq->nr_iowait);
3090 *load = rq->load.weight;
3096 * sched_exec - execve() is a valuable balancing opportunity, because at
3097 * this point the task has the smallest effective memory and cache footprint.
3099 void sched_exec(void)
3101 struct task_struct *p = current;
3102 unsigned long flags;
3105 raw_spin_lock_irqsave(&p->pi_lock, flags);
3106 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
3107 if (dest_cpu == smp_processor_id())
3110 if (likely(cpu_active(dest_cpu))) {
3111 struct migration_arg arg = { p, dest_cpu };
3113 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3114 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
3118 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3123 DEFINE_PER_CPU(struct kernel_stat, kstat);
3124 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
3126 EXPORT_PER_CPU_SYMBOL(kstat);
3127 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3130 * The function fair_sched_class.update_curr accesses the struct curr
3131 * and its field curr->exec_start; when called from task_sched_runtime(),
3132 * we observe a high rate of cache misses in practice.
3133 * Prefetching this data results in improved performance.
3135 static inline void prefetch_curr_exec_start(struct task_struct *p)
3137 #ifdef CONFIG_FAIR_GROUP_SCHED
3138 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3140 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3143 prefetch(&curr->exec_start);
3147 * Return accounted runtime for the task.
3148 * In case the task is currently running, return the runtime plus current's
3149 * pending runtime that have not been accounted yet.
3151 unsigned long long task_sched_runtime(struct task_struct *p)
3157 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3159 * 64-bit doesn't need locks to atomically read a 64bit value.
3160 * So we have a optimization chance when the task's delta_exec is 0.
3161 * Reading ->on_cpu is racy, but this is ok.
3163 * If we race with it leaving cpu, we'll take a lock. So we're correct.
3164 * If we race with it entering cpu, unaccounted time is 0. This is
3165 * indistinguishable from the read occurring a few cycles earlier.
3166 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3167 * been accounted, so we're correct here as well.
3169 if (!p->on_cpu || !task_on_rq_queued(p))
3170 return p->se.sum_exec_runtime;
3173 rq = task_rq_lock(p, &rf);
3175 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3176 * project cycles that may never be accounted to this
3177 * thread, breaking clock_gettime().
3179 if (task_current(rq, p) && task_on_rq_queued(p)) {
3180 prefetch_curr_exec_start(p);
3181 update_rq_clock(rq);
3182 p->sched_class->update_curr(rq);
3184 ns = p->se.sum_exec_runtime;
3185 task_rq_unlock(rq, p, &rf);
3191 * This function gets called by the timer code, with HZ frequency.
3192 * We call it with interrupts disabled.
3194 void scheduler_tick(void)
3196 int cpu = smp_processor_id();
3197 struct rq *rq = cpu_rq(cpu);
3198 struct task_struct *curr = rq->curr;
3202 raw_spin_lock(&rq->lock);
3203 update_rq_clock(rq);
3204 curr->sched_class->task_tick(rq, curr, 0);
3205 cpu_load_update_active(rq);
3206 calc_global_load_tick(rq);
3207 raw_spin_unlock(&rq->lock);
3209 perf_event_task_tick();
3212 rq->idle_balance = idle_cpu(cpu);
3213 trigger_load_balance(rq);
3215 rq_last_tick_reset(rq);
3218 #ifdef CONFIG_NO_HZ_FULL
3220 * scheduler_tick_max_deferment
3222 * Keep at least one tick per second when a single
3223 * active task is running because the scheduler doesn't
3224 * yet completely support full dynticks environment.
3226 * This makes sure that uptime, CFS vruntime, load
3227 * balancing, etc... continue to move forward, even
3228 * with a very low granularity.
3230 * Return: Maximum deferment in nanoseconds.
3232 u64 scheduler_tick_max_deferment(void)
3234 struct rq *rq = this_rq();
3235 unsigned long next, now = READ_ONCE(jiffies);
3237 next = rq->last_sched_tick + HZ;
3239 if (time_before_eq(next, now))
3242 return jiffies_to_nsecs(next - now);
3246 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3247 defined(CONFIG_PREEMPT_TRACER))
3249 * If the value passed in is equal to the current preempt count
3250 * then we just disabled preemption. Start timing the latency.
3252 static inline void preempt_latency_start(int val)
3254 if (preempt_count() == val) {
3255 unsigned long ip = get_lock_parent_ip();
3256 #ifdef CONFIG_DEBUG_PREEMPT
3257 current->preempt_disable_ip = ip;
3259 trace_preempt_off(CALLER_ADDR0, ip);
3263 void preempt_count_add(int val)
3265 #ifdef CONFIG_DEBUG_PREEMPT
3269 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3272 __preempt_count_add(val);
3273 #ifdef CONFIG_DEBUG_PREEMPT
3275 * Spinlock count overflowing soon?
3277 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3280 preempt_latency_start(val);
3282 EXPORT_SYMBOL(preempt_count_add);
3283 NOKPROBE_SYMBOL(preempt_count_add);
3286 * If the value passed in equals to the current preempt count
3287 * then we just enabled preemption. Stop timing the latency.
3289 static inline void preempt_latency_stop(int val)
3291 if (preempt_count() == val)
3292 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3295 void preempt_count_sub(int val)
3297 #ifdef CONFIG_DEBUG_PREEMPT
3301 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3304 * Is the spinlock portion underflowing?
3306 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3307 !(preempt_count() & PREEMPT_MASK)))
3311 preempt_latency_stop(val);
3312 __preempt_count_sub(val);
3314 EXPORT_SYMBOL(preempt_count_sub);
3315 NOKPROBE_SYMBOL(preempt_count_sub);
3318 static inline void preempt_latency_start(int val) { }
3319 static inline void preempt_latency_stop(int val) { }
3323 * Print scheduling while atomic bug:
3325 static noinline void __schedule_bug(struct task_struct *prev)
3327 /* Save this before calling printk(), since that will clobber it */
3328 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3330 if (oops_in_progress)
3333 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3334 prev->comm, prev->pid, preempt_count());
3336 debug_show_held_locks(prev);
3338 if (irqs_disabled())
3339 print_irqtrace_events(prev);
3340 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3341 && in_atomic_preempt_off()) {
3342 pr_err("Preemption disabled at:");
3343 print_ip_sym(preempt_disable_ip);
3347 panic("scheduling while atomic\n");
3350 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3354 * Various schedule()-time debugging checks and statistics:
3356 static inline void schedule_debug(struct task_struct *prev)
3358 #ifdef CONFIG_SCHED_STACK_END_CHECK
3359 if (task_stack_end_corrupted(prev))
3360 panic("corrupted stack end detected inside scheduler\n");
3363 if (unlikely(in_atomic_preempt_off())) {
3364 __schedule_bug(prev);
3365 preempt_count_set(PREEMPT_DISABLED);
3369 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3371 schedstat_inc(this_rq()->sched_count);
3374 #if defined(CONFIG_PREEMPT_RT_FULL) && defined(CONFIG_SMP)
3376 void migrate_disable(void)
3378 struct task_struct *p = current;
3380 if (in_atomic() || irqs_disabled()) {
3381 #ifdef CONFIG_SCHED_DEBUG
3382 p->migrate_disable_atomic++;
3387 #ifdef CONFIG_SCHED_DEBUG
3388 if (unlikely(p->migrate_disable_atomic)) {
3394 if (p->migrate_disable) {
3395 p->migrate_disable++;
3400 preempt_lazy_disable();
3402 p->migrate_disable = 1;
3405 EXPORT_SYMBOL(migrate_disable);
3407 void migrate_enable(void)
3409 struct task_struct *p = current;
3411 if (in_atomic() || irqs_disabled()) {
3412 #ifdef CONFIG_SCHED_DEBUG
3413 p->migrate_disable_atomic--;
3418 #ifdef CONFIG_SCHED_DEBUG
3419 if (unlikely(p->migrate_disable_atomic)) {
3424 WARN_ON_ONCE(p->migrate_disable <= 0);
3426 if (p->migrate_disable > 1) {
3427 p->migrate_disable--;
3433 * Clearing migrate_disable causes tsk_cpus_allowed to
3434 * show the tasks original cpu affinity.
3436 p->migrate_disable = 0;
3438 unpin_current_cpu();
3440 preempt_lazy_enable();
3442 EXPORT_SYMBOL(migrate_enable);
3446 * Pick up the highest-prio task:
3448 static inline struct task_struct *
3449 pick_next_task(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
3451 const struct sched_class *class = &fair_sched_class;
3452 struct task_struct *p;
3455 * Optimization: we know that if all tasks are in
3456 * the fair class we can call that function directly:
3458 if (likely(prev->sched_class == class &&
3459 rq->nr_running == rq->cfs.h_nr_running)) {
3460 p = fair_sched_class.pick_next_task(rq, prev, cookie);
3461 if (unlikely(p == RETRY_TASK))
3464 /* assumes fair_sched_class->next == idle_sched_class */
3466 p = idle_sched_class.pick_next_task(rq, prev, cookie);
3472 for_each_class(class) {
3473 p = class->pick_next_task(rq, prev, cookie);
3475 if (unlikely(p == RETRY_TASK))
3481 BUG(); /* the idle class will always have a runnable task */
3485 * __schedule() is the main scheduler function.
3487 * The main means of driving the scheduler and thus entering this function are:
3489 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3491 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3492 * paths. For example, see arch/x86/entry_64.S.
3494 * To drive preemption between tasks, the scheduler sets the flag in timer
3495 * interrupt handler scheduler_tick().
3497 * 3. Wakeups don't really cause entry into schedule(). They add a
3498 * task to the run-queue and that's it.
3500 * Now, if the new task added to the run-queue preempts the current
3501 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3502 * called on the nearest possible occasion:
3504 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3506 * - in syscall or exception context, at the next outmost
3507 * preempt_enable(). (this might be as soon as the wake_up()'s
3510 * - in IRQ context, return from interrupt-handler to
3511 * preemptible context
3513 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3516 * - cond_resched() call
3517 * - explicit schedule() call
3518 * - return from syscall or exception to user-space
3519 * - return from interrupt-handler to user-space
3521 * WARNING: must be called with preemption disabled!
3523 static void __sched notrace __schedule(bool preempt)
3525 struct task_struct *prev, *next;
3526 unsigned long *switch_count;
3527 struct pin_cookie cookie;
3531 cpu = smp_processor_id();
3535 schedule_debug(prev);
3537 if (sched_feat(HRTICK))
3540 local_irq_disable();
3541 rcu_note_context_switch();
3544 * Make sure that signal_pending_state()->signal_pending() below
3545 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3546 * done by the caller to avoid the race with signal_wake_up().
3548 smp_mb__before_spinlock();
3549 raw_spin_lock(&rq->lock);
3550 cookie = lockdep_pin_lock(&rq->lock);
3552 rq->clock_skip_update <<= 1; /* promote REQ to ACT */
3554 switch_count = &prev->nivcsw;
3555 if (!preempt && prev->state) {
3556 if (unlikely(signal_pending_state(prev->state, prev))) {
3557 prev->state = TASK_RUNNING;
3559 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3562 switch_count = &prev->nvcsw;
3565 if (task_on_rq_queued(prev))
3566 update_rq_clock(rq);
3568 next = pick_next_task(rq, prev, cookie);
3569 clear_tsk_need_resched(prev);
3570 clear_tsk_need_resched_lazy(prev);
3571 clear_preempt_need_resched();
3572 rq->clock_skip_update = 0;
3574 if (likely(prev != next)) {
3579 trace_sched_switch(preempt, prev, next);
3580 rq = context_switch(rq, prev, next, cookie); /* unlocks the rq */
3582 lockdep_unpin_lock(&rq->lock, cookie);
3583 raw_spin_unlock_irq(&rq->lock);
3586 balance_callback(rq);
3589 void __noreturn do_task_dead(void)
3592 * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
3593 * when the following two conditions become true.
3594 * - There is race condition of mmap_sem (It is acquired by
3596 * - SMI occurs before setting TASK_RUNINNG.
3597 * (or hypervisor of virtual machine switches to other guest)
3598 * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
3600 * To avoid it, we have to wait for releasing tsk->pi_lock which
3601 * is held by try_to_wake_up()
3604 raw_spin_unlock_wait(¤t->pi_lock);
3606 /* causes final put_task_struct in finish_task_switch(). */
3607 __set_current_state(TASK_DEAD);
3608 current->flags |= PF_NOFREEZE; /* tell freezer to ignore us */
3611 /* Avoid "noreturn function does return". */
3613 cpu_relax(); /* For when BUG is null */
3616 static inline void sched_submit_work(struct task_struct *tsk)
3621 * If a worker went to sleep, notify and ask workqueue whether
3622 * it wants to wake up a task to maintain concurrency.
3624 if (tsk->flags & PF_WQ_WORKER)
3625 wq_worker_sleeping(tsk);
3628 if (tsk_is_pi_blocked(tsk))
3632 * If we are going to sleep and we have plugged IO queued,
3633 * make sure to submit it to avoid deadlocks.
3635 if (blk_needs_flush_plug(tsk))
3636 blk_schedule_flush_plug(tsk);
3639 static void sched_update_worker(struct task_struct *tsk)
3641 if (tsk->flags & PF_WQ_WORKER)
3642 wq_worker_running(tsk);
3645 asmlinkage __visible void __sched schedule(void)
3647 struct task_struct *tsk = current;
3649 sched_submit_work(tsk);
3653 sched_preempt_enable_no_resched();
3654 } while (need_resched());
3655 sched_update_worker(tsk);
3657 EXPORT_SYMBOL(schedule);
3659 #ifdef CONFIG_CONTEXT_TRACKING
3660 asmlinkage __visible void __sched schedule_user(void)
3663 * If we come here after a random call to set_need_resched(),
3664 * or we have been woken up remotely but the IPI has not yet arrived,
3665 * we haven't yet exited the RCU idle mode. Do it here manually until
3666 * we find a better solution.
3668 * NB: There are buggy callers of this function. Ideally we
3669 * should warn if prev_state != CONTEXT_USER, but that will trigger
3670 * too frequently to make sense yet.
3672 enum ctx_state prev_state = exception_enter();
3674 exception_exit(prev_state);
3679 * schedule_preempt_disabled - called with preemption disabled
3681 * Returns with preemption disabled. Note: preempt_count must be 1
3683 void __sched schedule_preempt_disabled(void)
3685 sched_preempt_enable_no_resched();
3690 static void __sched notrace preempt_schedule_common(void)
3694 * Because the function tracer can trace preempt_count_sub()
3695 * and it also uses preempt_enable/disable_notrace(), if
3696 * NEED_RESCHED is set, the preempt_enable_notrace() called
3697 * by the function tracer will call this function again and
3698 * cause infinite recursion.
3700 * Preemption must be disabled here before the function
3701 * tracer can trace. Break up preempt_disable() into two
3702 * calls. One to disable preemption without fear of being
3703 * traced. The other to still record the preemption latency,
3704 * which can also be traced by the function tracer.
3706 preempt_disable_notrace();
3707 preempt_latency_start(1);
3709 preempt_latency_stop(1);
3710 preempt_enable_no_resched_notrace();
3713 * Check again in case we missed a preemption opportunity
3714 * between schedule and now.
3716 } while (need_resched());
3719 #ifdef CONFIG_PREEMPT_LAZY
3721 * If TIF_NEED_RESCHED is then we allow to be scheduled away since this is
3722 * set by a RT task. Oterwise we try to avoid beeing scheduled out as long as
3723 * preempt_lazy_count counter >0.
3725 static __always_inline int preemptible_lazy(void)
3727 if (test_thread_flag(TIF_NEED_RESCHED))
3729 if (current_thread_info()->preempt_lazy_count)
3736 static inline int preemptible_lazy(void)
3743 #ifdef CONFIG_PREEMPT
3745 * this is the entry point to schedule() from in-kernel preemption
3746 * off of preempt_enable. Kernel preemptions off return from interrupt
3747 * occur there and call schedule directly.
3749 asmlinkage __visible void __sched notrace preempt_schedule(void)
3752 * If there is a non-zero preempt_count or interrupts are disabled,
3753 * we do not want to preempt the current task. Just return..
3755 if (likely(!preemptible()))
3757 if (!preemptible_lazy())
3759 preempt_schedule_common();
3761 NOKPROBE_SYMBOL(preempt_schedule);
3762 EXPORT_SYMBOL(preempt_schedule);
3765 * preempt_schedule_notrace - preempt_schedule called by tracing
3767 * The tracing infrastructure uses preempt_enable_notrace to prevent
3768 * recursion and tracing preempt enabling caused by the tracing
3769 * infrastructure itself. But as tracing can happen in areas coming
3770 * from userspace or just about to enter userspace, a preempt enable
3771 * can occur before user_exit() is called. This will cause the scheduler
3772 * to be called when the system is still in usermode.
3774 * To prevent this, the preempt_enable_notrace will use this function
3775 * instead of preempt_schedule() to exit user context if needed before
3776 * calling the scheduler.
3778 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3780 enum ctx_state prev_ctx;
3782 if (likely(!preemptible()))
3785 if (!preemptible_lazy())
3790 * Because the function tracer can trace preempt_count_sub()
3791 * and it also uses preempt_enable/disable_notrace(), if
3792 * NEED_RESCHED is set, the preempt_enable_notrace() called
3793 * by the function tracer will call this function again and
3794 * cause infinite recursion.
3796 * Preemption must be disabled here before the function
3797 * tracer can trace. Break up preempt_disable() into two
3798 * calls. One to disable preemption without fear of being
3799 * traced. The other to still record the preemption latency,
3800 * which can also be traced by the function tracer.
3802 preempt_disable_notrace();
3803 preempt_latency_start(1);
3805 * Needs preempt disabled in case user_exit() is traced
3806 * and the tracer calls preempt_enable_notrace() causing
3807 * an infinite recursion.
3809 prev_ctx = exception_enter();
3811 * The add/subtract must not be traced by the function
3812 * tracer. But we still want to account for the
3813 * preempt off latency tracer. Since the _notrace versions
3814 * of add/subtract skip the accounting for latency tracer
3815 * we must force it manually.
3817 start_critical_timings();
3819 stop_critical_timings();
3820 exception_exit(prev_ctx);
3822 preempt_latency_stop(1);
3823 preempt_enable_no_resched_notrace();
3824 } while (need_resched());
3826 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3828 #endif /* CONFIG_PREEMPT */
3831 * this is the entry point to schedule() from kernel preemption
3832 * off of irq context.
3833 * Note, that this is called and return with irqs disabled. This will
3834 * protect us against recursive calling from irq.
3836 asmlinkage __visible void __sched preempt_schedule_irq(void)
3838 enum ctx_state prev_state;
3840 /* Catch callers which need to be fixed */
3841 BUG_ON(preempt_count() || !irqs_disabled());
3843 prev_state = exception_enter();
3849 local_irq_disable();
3850 sched_preempt_enable_no_resched();
3851 } while (need_resched());
3853 exception_exit(prev_state);
3856 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3859 return try_to_wake_up(curr->private, mode, wake_flags);
3861 EXPORT_SYMBOL(default_wake_function);
3863 #ifdef CONFIG_RT_MUTEXES
3866 * rt_mutex_setprio - set the current priority of a task
3868 * @prio: prio value (kernel-internal form)
3870 * This function changes the 'effective' priority of a task. It does
3871 * not touch ->normal_prio like __setscheduler().
3873 * Used by the rt_mutex code to implement priority inheritance
3874 * logic. Call site only calls if the priority of the task changed.
3876 void rt_mutex_setprio(struct task_struct *p, int prio)
3878 int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
3879 const struct sched_class *prev_class;
3883 BUG_ON(prio > MAX_PRIO);
3885 rq = __task_rq_lock(p, &rf);
3888 * Idle task boosting is a nono in general. There is one
3889 * exception, when PREEMPT_RT and NOHZ is active:
3891 * The idle task calls get_next_timer_interrupt() and holds
3892 * the timer wheel base->lock on the CPU and another CPU wants
3893 * to access the timer (probably to cancel it). We can safely
3894 * ignore the boosting request, as the idle CPU runs this code
3895 * with interrupts disabled and will complete the lock
3896 * protected section without being interrupted. So there is no
3897 * real need to boost.
3899 if (unlikely(p == rq->idle)) {
3900 WARN_ON(p != rq->curr);
3901 WARN_ON(p->pi_blocked_on);
3905 trace_sched_pi_setprio(p, prio);
3908 if (oldprio == prio)
3909 queue_flag &= ~DEQUEUE_MOVE;
3911 prev_class = p->sched_class;
3912 queued = task_on_rq_queued(p);
3913 running = task_current(rq, p);
3915 dequeue_task(rq, p, queue_flag);
3917 put_prev_task(rq, p);
3920 * Boosting condition are:
3921 * 1. -rt task is running and holds mutex A
3922 * --> -dl task blocks on mutex A
3924 * 2. -dl task is running and holds mutex A
3925 * --> -dl task blocks on mutex A and could preempt the
3928 if (dl_prio(prio)) {
3929 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3930 if (!dl_prio(p->normal_prio) ||
3931 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3932 p->dl.dl_boosted = 1;
3933 queue_flag |= ENQUEUE_REPLENISH;
3935 p->dl.dl_boosted = 0;
3936 p->sched_class = &dl_sched_class;
3937 } else if (rt_prio(prio)) {
3938 if (dl_prio(oldprio))
3939 p->dl.dl_boosted = 0;
3941 queue_flag |= ENQUEUE_HEAD;
3942 p->sched_class = &rt_sched_class;
3944 if (dl_prio(oldprio))
3945 p->dl.dl_boosted = 0;
3946 if (rt_prio(oldprio))
3948 p->sched_class = &fair_sched_class;
3954 enqueue_task(rq, p, queue_flag);
3956 set_curr_task(rq, p);
3958 check_class_changed(rq, p, prev_class, oldprio);
3960 preempt_disable(); /* avoid rq from going away on us */
3961 __task_rq_unlock(rq, &rf);
3963 balance_callback(rq);
3968 void set_user_nice(struct task_struct *p, long nice)
3970 bool queued, running;
3971 int old_prio, delta;
3975 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3978 * We have to be careful, if called from sys_setpriority(),
3979 * the task might be in the middle of scheduling on another CPU.
3981 rq = task_rq_lock(p, &rf);
3983 * The RT priorities are set via sched_setscheduler(), but we still
3984 * allow the 'normal' nice value to be set - but as expected
3985 * it wont have any effect on scheduling until the task is
3986 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3988 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3989 p->static_prio = NICE_TO_PRIO(nice);
3992 queued = task_on_rq_queued(p);
3993 running = task_current(rq, p);
3995 dequeue_task(rq, p, DEQUEUE_SAVE);
3997 put_prev_task(rq, p);
3999 p->static_prio = NICE_TO_PRIO(nice);
4002 p->prio = effective_prio(p);
4003 delta = p->prio - old_prio;
4006 enqueue_task(rq, p, ENQUEUE_RESTORE);
4008 * If the task increased its priority or is running and
4009 * lowered its priority, then reschedule its CPU:
4011 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4015 set_curr_task(rq, p);
4017 task_rq_unlock(rq, p, &rf);
4019 EXPORT_SYMBOL(set_user_nice);
4022 * can_nice - check if a task can reduce its nice value
4026 int can_nice(const struct task_struct *p, const int nice)
4028 /* convert nice value [19,-20] to rlimit style value [1,40] */
4029 int nice_rlim = nice_to_rlimit(nice);
4031 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4032 capable(CAP_SYS_NICE));
4035 #ifdef __ARCH_WANT_SYS_NICE
4038 * sys_nice - change the priority of the current process.
4039 * @increment: priority increment
4041 * sys_setpriority is a more generic, but much slower function that
4042 * does similar things.
4044 SYSCALL_DEFINE1(nice, int, increment)
4049 * Setpriority might change our priority at the same moment.
4050 * We don't have to worry. Conceptually one call occurs first
4051 * and we have a single winner.
4053 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
4054 nice = task_nice(current) + increment;
4056 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
4057 if (increment < 0 && !can_nice(current, nice))
4060 retval = security_task_setnice(current, nice);
4064 set_user_nice(current, nice);
4071 * task_prio - return the priority value of a given task.
4072 * @p: the task in question.
4074 * Return: The priority value as seen by users in /proc.
4075 * RT tasks are offset by -200. Normal tasks are centered
4076 * around 0, value goes from -16 to +15.
4078 int task_prio(const struct task_struct *p)
4080 return p->prio - MAX_RT_PRIO;
4084 * idle_cpu - is a given cpu idle currently?
4085 * @cpu: the processor in question.
4087 * Return: 1 if the CPU is currently idle. 0 otherwise.
4089 int idle_cpu(int cpu)
4091 struct rq *rq = cpu_rq(cpu);
4093 if (rq->curr != rq->idle)
4100 if (!llist_empty(&rq->wake_list))
4108 * idle_task - return the idle task for a given cpu.
4109 * @cpu: the processor in question.
4111 * Return: The idle task for the cpu @cpu.
4113 struct task_struct *idle_task(int cpu)
4115 return cpu_rq(cpu)->idle;
4119 * find_process_by_pid - find a process with a matching PID value.
4120 * @pid: the pid in question.
4122 * The task of @pid, if found. %NULL otherwise.
4124 static struct task_struct *find_process_by_pid(pid_t pid)
4126 return pid ? find_task_by_vpid(pid) : current;
4130 * This function initializes the sched_dl_entity of a newly becoming
4131 * SCHED_DEADLINE task.
4133 * Only the static values are considered here, the actual runtime and the
4134 * absolute deadline will be properly calculated when the task is enqueued
4135 * for the first time with its new policy.
4138 __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
4140 struct sched_dl_entity *dl_se = &p->dl;
4142 dl_se->dl_runtime = attr->sched_runtime;
4143 dl_se->dl_deadline = attr->sched_deadline;
4144 dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
4145 dl_se->flags = attr->sched_flags;
4146 dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
4149 * Changing the parameters of a task is 'tricky' and we're not doing
4150 * the correct thing -- also see task_dead_dl() and switched_from_dl().
4152 * What we SHOULD do is delay the bandwidth release until the 0-lag
4153 * point. This would include retaining the task_struct until that time
4154 * and change dl_overflow() to not immediately decrement the current
4157 * Instead we retain the current runtime/deadline and let the new
4158 * parameters take effect after the current reservation period lapses.
4159 * This is safe (albeit pessimistic) because the 0-lag point is always
4160 * before the current scheduling deadline.
4162 * We can still have temporary overloads because we do not delay the
4163 * change in bandwidth until that time; so admission control is
4164 * not on the safe side. It does however guarantee tasks will never
4165 * consume more than promised.
4170 * sched_setparam() passes in -1 for its policy, to let the functions
4171 * it calls know not to change it.
4173 #define SETPARAM_POLICY -1
4175 static void __setscheduler_params(struct task_struct *p,
4176 const struct sched_attr *attr)
4178 int policy = attr->sched_policy;
4180 if (policy == SETPARAM_POLICY)
4185 if (dl_policy(policy))
4186 __setparam_dl(p, attr);
4187 else if (fair_policy(policy))
4188 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4191 * __sched_setscheduler() ensures attr->sched_priority == 0 when
4192 * !rt_policy. Always setting this ensures that things like
4193 * getparam()/getattr() don't report silly values for !rt tasks.
4195 p->rt_priority = attr->sched_priority;
4196 p->normal_prio = normal_prio(p);
4200 /* Actually do priority change: must hold pi & rq lock. */
4201 static void __setscheduler(struct rq *rq, struct task_struct *p,
4202 const struct sched_attr *attr, bool keep_boost)
4204 __setscheduler_params(p, attr);
4207 * Keep a potential priority boosting if called from
4208 * sched_setscheduler().
4211 p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
4213 p->prio = normal_prio(p);
4215 if (dl_prio(p->prio))
4216 p->sched_class = &dl_sched_class;
4217 else if (rt_prio(p->prio))
4218 p->sched_class = &rt_sched_class;
4220 p->sched_class = &fair_sched_class;
4224 __getparam_dl(struct task_struct *p, struct sched_attr *attr)
4226 struct sched_dl_entity *dl_se = &p->dl;
4228 attr->sched_priority = p->rt_priority;
4229 attr->sched_runtime = dl_se->dl_runtime;
4230 attr->sched_deadline = dl_se->dl_deadline;
4231 attr->sched_period = dl_se->dl_period;
4232 attr->sched_flags = dl_se->flags;
4236 * This function validates the new parameters of a -deadline task.
4237 * We ask for the deadline not being zero, and greater or equal
4238 * than the runtime, as well as the period of being zero or
4239 * greater than deadline. Furthermore, we have to be sure that
4240 * user parameters are above the internal resolution of 1us (we
4241 * check sched_runtime only since it is always the smaller one) and
4242 * below 2^63 ns (we have to check both sched_deadline and
4243 * sched_period, as the latter can be zero).
4246 __checkparam_dl(const struct sched_attr *attr)
4249 if (attr->sched_deadline == 0)
4253 * Since we truncate DL_SCALE bits, make sure we're at least
4256 if (attr->sched_runtime < (1ULL << DL_SCALE))
4260 * Since we use the MSB for wrap-around and sign issues, make
4261 * sure it's not set (mind that period can be equal to zero).
4263 if (attr->sched_deadline & (1ULL << 63) ||
4264 attr->sched_period & (1ULL << 63))
4267 /* runtime <= deadline <= period (if period != 0) */
4268 if ((attr->sched_period != 0 &&
4269 attr->sched_period < attr->sched_deadline) ||
4270 attr->sched_deadline < attr->sched_runtime)
4277 * check the target process has a UID that matches the current process's
4279 static bool check_same_owner(struct task_struct *p)
4281 const struct cred *cred = current_cred(), *pcred;
4285 pcred = __task_cred(p);
4286 match = (uid_eq(cred->euid, pcred->euid) ||
4287 uid_eq(cred->euid, pcred->uid));
4292 static bool dl_param_changed(struct task_struct *p,
4293 const struct sched_attr *attr)
4295 struct sched_dl_entity *dl_se = &p->dl;
4297 if (dl_se->dl_runtime != attr->sched_runtime ||
4298 dl_se->dl_deadline != attr->sched_deadline ||
4299 dl_se->dl_period != attr->sched_period ||
4300 dl_se->flags != attr->sched_flags)
4306 static int __sched_setscheduler(struct task_struct *p,
4307 const struct sched_attr *attr,
4310 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4311 MAX_RT_PRIO - 1 - attr->sched_priority;
4312 int retval, oldprio, oldpolicy = -1, queued, running;
4313 int new_effective_prio, policy = attr->sched_policy;
4314 const struct sched_class *prev_class;
4317 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
4320 /* may grab non-irq protected spin_locks */
4321 BUG_ON(in_interrupt());
4323 /* double check policy once rq lock held */
4325 reset_on_fork = p->sched_reset_on_fork;
4326 policy = oldpolicy = p->policy;
4328 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4330 if (!valid_policy(policy))
4334 if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
4338 * Valid priorities for SCHED_FIFO and SCHED_RR are
4339 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4340 * SCHED_BATCH and SCHED_IDLE is 0.
4342 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4343 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4345 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4346 (rt_policy(policy) != (attr->sched_priority != 0)))
4350 * Allow unprivileged RT tasks to decrease priority:
4352 if (user && !capable(CAP_SYS_NICE)) {
4353 if (fair_policy(policy)) {
4354 if (attr->sched_nice < task_nice(p) &&
4355 !can_nice(p, attr->sched_nice))
4359 if (rt_policy(policy)) {
4360 unsigned long rlim_rtprio =
4361 task_rlimit(p, RLIMIT_RTPRIO);
4363 /* can't set/change the rt policy */
4364 if (policy != p->policy && !rlim_rtprio)
4367 /* can't increase priority */
4368 if (attr->sched_priority > p->rt_priority &&
4369 attr->sched_priority > rlim_rtprio)
4374 * Can't set/change SCHED_DEADLINE policy at all for now
4375 * (safest behavior); in the future we would like to allow
4376 * unprivileged DL tasks to increase their relative deadline
4377 * or reduce their runtime (both ways reducing utilization)
4379 if (dl_policy(policy))
4383 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4384 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4386 if (idle_policy(p->policy) && !idle_policy(policy)) {
4387 if (!can_nice(p, task_nice(p)))
4391 /* can't change other user's priorities */
4392 if (!check_same_owner(p))
4395 /* Normal users shall not reset the sched_reset_on_fork flag */
4396 if (p->sched_reset_on_fork && !reset_on_fork)
4401 retval = security_task_setscheduler(p);
4407 * make sure no PI-waiters arrive (or leave) while we are
4408 * changing the priority of the task:
4410 * To be able to change p->policy safely, the appropriate
4411 * runqueue lock must be held.
4413 rq = task_rq_lock(p, &rf);
4416 * Changing the policy of the stop threads its a very bad idea
4418 if (p == rq->stop) {
4419 task_rq_unlock(rq, p, &rf);
4424 * If not changing anything there's no need to proceed further,
4425 * but store a possible modification of reset_on_fork.
4427 if (unlikely(policy == p->policy)) {
4428 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4430 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4432 if (dl_policy(policy) && dl_param_changed(p, attr))
4435 p->sched_reset_on_fork = reset_on_fork;
4436 task_rq_unlock(rq, p, &rf);
4442 #ifdef CONFIG_RT_GROUP_SCHED
4444 * Do not allow realtime tasks into groups that have no runtime
4447 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4448 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4449 !task_group_is_autogroup(task_group(p))) {
4450 task_rq_unlock(rq, p, &rf);
4455 if (dl_bandwidth_enabled() && dl_policy(policy)) {
4456 cpumask_t *span = rq->rd->span;
4459 * Don't allow tasks with an affinity mask smaller than
4460 * the entire root_domain to become SCHED_DEADLINE. We
4461 * will also fail if there's no bandwidth available.
4463 if (!cpumask_subset(span, &p->cpus_allowed) ||
4464 rq->rd->dl_bw.bw == 0) {
4465 task_rq_unlock(rq, p, &rf);
4472 /* recheck policy now with rq lock held */
4473 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4474 policy = oldpolicy = -1;
4475 task_rq_unlock(rq, p, &rf);
4480 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4481 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4484 if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
4485 task_rq_unlock(rq, p, &rf);
4489 p->sched_reset_on_fork = reset_on_fork;
4494 * Take priority boosted tasks into account. If the new
4495 * effective priority is unchanged, we just store the new
4496 * normal parameters and do not touch the scheduler class and
4497 * the runqueue. This will be done when the task deboost
4500 new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
4501 if (new_effective_prio == oldprio)
4502 queue_flags &= ~DEQUEUE_MOVE;
4505 queued = task_on_rq_queued(p);
4506 running = task_current(rq, p);
4508 dequeue_task(rq, p, queue_flags);
4510 put_prev_task(rq, p);
4512 prev_class = p->sched_class;
4513 __setscheduler(rq, p, attr, pi);
4517 * We enqueue to tail when the priority of a task is
4518 * increased (user space view).
4520 if (oldprio < p->prio)
4521 queue_flags |= ENQUEUE_HEAD;
4523 enqueue_task(rq, p, queue_flags);
4526 set_curr_task(rq, p);
4528 check_class_changed(rq, p, prev_class, oldprio);
4529 preempt_disable(); /* avoid rq from going away on us */
4530 task_rq_unlock(rq, p, &rf);
4533 rt_mutex_adjust_pi(p);
4536 * Run balance callbacks after we've adjusted the PI chain.
4538 balance_callback(rq);
4544 static int _sched_setscheduler(struct task_struct *p, int policy,
4545 const struct sched_param *param, bool check)
4547 struct sched_attr attr = {
4548 .sched_policy = policy,
4549 .sched_priority = param->sched_priority,
4550 .sched_nice = PRIO_TO_NICE(p->static_prio),
4553 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4554 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4555 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4556 policy &= ~SCHED_RESET_ON_FORK;
4557 attr.sched_policy = policy;
4560 return __sched_setscheduler(p, &attr, check, true);
4563 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4564 * @p: the task in question.
4565 * @policy: new policy.
4566 * @param: structure containing the new RT priority.
4568 * Return: 0 on success. An error code otherwise.
4570 * NOTE that the task may be already dead.
4572 int sched_setscheduler(struct task_struct *p, int policy,
4573 const struct sched_param *param)
4575 return _sched_setscheduler(p, policy, param, true);
4577 EXPORT_SYMBOL_GPL(sched_setscheduler);
4579 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4581 return __sched_setscheduler(p, attr, true, true);
4583 EXPORT_SYMBOL_GPL(sched_setattr);
4586 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4587 * @p: the task in question.
4588 * @policy: new policy.
4589 * @param: structure containing the new RT priority.
4591 * Just like sched_setscheduler, only don't bother checking if the
4592 * current context has permission. For example, this is needed in
4593 * stop_machine(): we create temporary high priority worker threads,
4594 * but our caller might not have that capability.
4596 * Return: 0 on success. An error code otherwise.
4598 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4599 const struct sched_param *param)
4601 return _sched_setscheduler(p, policy, param, false);
4603 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4606 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4608 struct sched_param lparam;
4609 struct task_struct *p;
4612 if (!param || pid < 0)
4614 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4619 p = find_process_by_pid(pid);
4621 retval = sched_setscheduler(p, policy, &lparam);
4628 * Mimics kernel/events/core.c perf_copy_attr().
4630 static int sched_copy_attr(struct sched_attr __user *uattr,
4631 struct sched_attr *attr)
4636 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4640 * zero the full structure, so that a short copy will be nice.
4642 memset(attr, 0, sizeof(*attr));
4644 ret = get_user(size, &uattr->size);
4648 if (size > PAGE_SIZE) /* silly large */
4651 if (!size) /* abi compat */
4652 size = SCHED_ATTR_SIZE_VER0;
4654 if (size < SCHED_ATTR_SIZE_VER0)
4658 * If we're handed a bigger struct than we know of,
4659 * ensure all the unknown bits are 0 - i.e. new
4660 * user-space does not rely on any kernel feature
4661 * extensions we dont know about yet.
4663 if (size > sizeof(*attr)) {
4664 unsigned char __user *addr;
4665 unsigned char __user *end;
4668 addr = (void __user *)uattr + sizeof(*attr);
4669 end = (void __user *)uattr + size;
4671 for (; addr < end; addr++) {
4672 ret = get_user(val, addr);
4678 size = sizeof(*attr);
4681 ret = copy_from_user(attr, uattr, size);
4686 * XXX: do we want to be lenient like existing syscalls; or do we want
4687 * to be strict and return an error on out-of-bounds values?
4689 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4694 put_user(sizeof(*attr), &uattr->size);
4699 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4700 * @pid: the pid in question.
4701 * @policy: new policy.
4702 * @param: structure containing the new RT priority.
4704 * Return: 0 on success. An error code otherwise.
4706 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4707 struct sched_param __user *, param)
4709 /* negative values for policy are not valid */
4713 return do_sched_setscheduler(pid, policy, param);
4717 * sys_sched_setparam - set/change the RT priority of a thread
4718 * @pid: the pid in question.
4719 * @param: structure containing the new RT priority.
4721 * Return: 0 on success. An error code otherwise.
4723 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4725 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4729 * sys_sched_setattr - same as above, but with extended sched_attr
4730 * @pid: the pid in question.
4731 * @uattr: structure containing the extended parameters.
4732 * @flags: for future extension.
4734 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4735 unsigned int, flags)
4737 struct sched_attr attr;
4738 struct task_struct *p;
4741 if (!uattr || pid < 0 || flags)
4744 retval = sched_copy_attr(uattr, &attr);
4748 if ((int)attr.sched_policy < 0)
4753 p = find_process_by_pid(pid);
4755 retval = sched_setattr(p, &attr);
4762 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4763 * @pid: the pid in question.
4765 * Return: On success, the policy of the thread. Otherwise, a negative error
4768 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4770 struct task_struct *p;
4778 p = find_process_by_pid(pid);
4780 retval = security_task_getscheduler(p);
4783 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4790 * sys_sched_getparam - get the RT priority of a thread
4791 * @pid: the pid in question.
4792 * @param: structure containing the RT priority.
4794 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4797 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4799 struct sched_param lp = { .sched_priority = 0 };
4800 struct task_struct *p;
4803 if (!param || pid < 0)
4807 p = find_process_by_pid(pid);
4812 retval = security_task_getscheduler(p);
4816 if (task_has_rt_policy(p))
4817 lp.sched_priority = p->rt_priority;
4821 * This one might sleep, we cannot do it with a spinlock held ...
4823 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4832 static int sched_read_attr(struct sched_attr __user *uattr,
4833 struct sched_attr *attr,
4838 if (!access_ok(VERIFY_WRITE, uattr, usize))
4842 * If we're handed a smaller struct than we know of,
4843 * ensure all the unknown bits are 0 - i.e. old
4844 * user-space does not get uncomplete information.
4846 if (usize < sizeof(*attr)) {
4847 unsigned char *addr;
4850 addr = (void *)attr + usize;
4851 end = (void *)attr + sizeof(*attr);
4853 for (; addr < end; addr++) {
4861 ret = copy_to_user(uattr, attr, attr->size);
4869 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4870 * @pid: the pid in question.
4871 * @uattr: structure containing the extended parameters.
4872 * @size: sizeof(attr) for fwd/bwd comp.
4873 * @flags: for future extension.
4875 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4876 unsigned int, size, unsigned int, flags)
4878 struct sched_attr attr = {
4879 .size = sizeof(struct sched_attr),
4881 struct task_struct *p;
4884 if (!uattr || pid < 0 || size > PAGE_SIZE ||
4885 size < SCHED_ATTR_SIZE_VER0 || flags)
4889 p = find_process_by_pid(pid);
4894 retval = security_task_getscheduler(p);
4898 attr.sched_policy = p->policy;
4899 if (p->sched_reset_on_fork)
4900 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4901 if (task_has_dl_policy(p))
4902 __getparam_dl(p, &attr);
4903 else if (task_has_rt_policy(p))
4904 attr.sched_priority = p->rt_priority;
4906 attr.sched_nice = task_nice(p);
4910 retval = sched_read_attr(uattr, &attr, size);
4918 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4920 cpumask_var_t cpus_allowed, new_mask;
4921 struct task_struct *p;
4926 p = find_process_by_pid(pid);
4932 /* Prevent p going away */
4936 if (p->flags & PF_NO_SETAFFINITY) {
4940 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4944 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4946 goto out_free_cpus_allowed;
4949 if (!check_same_owner(p)) {
4951 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4953 goto out_free_new_mask;
4958 retval = security_task_setscheduler(p);
4960 goto out_free_new_mask;
4963 cpuset_cpus_allowed(p, cpus_allowed);
4964 cpumask_and(new_mask, in_mask, cpus_allowed);
4967 * Since bandwidth control happens on root_domain basis,
4968 * if admission test is enabled, we only admit -deadline
4969 * tasks allowed to run on all the CPUs in the task's
4973 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4975 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4978 goto out_free_new_mask;
4984 retval = __set_cpus_allowed_ptr(p, new_mask, true);
4987 cpuset_cpus_allowed(p, cpus_allowed);
4988 if (!cpumask_subset(new_mask, cpus_allowed)) {
4990 * We must have raced with a concurrent cpuset
4991 * update. Just reset the cpus_allowed to the
4992 * cpuset's cpus_allowed
4994 cpumask_copy(new_mask, cpus_allowed);
4999 free_cpumask_var(new_mask);
5000 out_free_cpus_allowed:
5001 free_cpumask_var(cpus_allowed);
5007 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5008 struct cpumask *new_mask)
5010 if (len < cpumask_size())
5011 cpumask_clear(new_mask);
5012 else if (len > cpumask_size())
5013 len = cpumask_size();
5015 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5019 * sys_sched_setaffinity - set the cpu affinity of a process
5020 * @pid: pid of the process
5021 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5022 * @user_mask_ptr: user-space pointer to the new cpu mask
5024 * Return: 0 on success. An error code otherwise.
5026 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
5027 unsigned long __user *, user_mask_ptr)
5029 cpumask_var_t new_mask;
5032 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
5035 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
5037 retval = sched_setaffinity(pid, new_mask);
5038 free_cpumask_var(new_mask);
5042 long sched_getaffinity(pid_t pid, struct cpumask *mask)
5044 struct task_struct *p;
5045 unsigned long flags;
5051 p = find_process_by_pid(pid);
5055 retval = security_task_getscheduler(p);
5059 raw_spin_lock_irqsave(&p->pi_lock, flags);
5060 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
5061 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5070 * sys_sched_getaffinity - get the cpu affinity of a process
5071 * @pid: pid of the process
5072 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5073 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5075 * Return: size of CPU mask copied to user_mask_ptr on success. An
5076 * error code otherwise.
5078 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5079 unsigned long __user *, user_mask_ptr)
5084 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5086 if (len & (sizeof(unsigned long)-1))
5089 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5092 ret = sched_getaffinity(pid, mask);
5094 size_t retlen = min_t(size_t, len, cpumask_size());
5096 if (copy_to_user(user_mask_ptr, mask, retlen))
5101 free_cpumask_var(mask);
5107 * sys_sched_yield - yield the current processor to other threads.
5109 * This function yields the current CPU to other tasks. If there are no
5110 * other threads running on this CPU then this function will return.
5114 SYSCALL_DEFINE0(sched_yield)
5116 struct rq *rq = this_rq_lock();
5118 schedstat_inc(rq->yld_count);
5119 current->sched_class->yield_task(rq);
5122 * Since we are going to call schedule() anyway, there's
5123 * no need to preempt or enable interrupts:
5125 __release(rq->lock);
5126 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5127 do_raw_spin_unlock(&rq->lock);
5128 sched_preempt_enable_no_resched();
5135 #ifndef CONFIG_PREEMPT
5136 int __sched _cond_resched(void)
5138 if (should_resched(0)) {
5139 preempt_schedule_common();
5144 EXPORT_SYMBOL(_cond_resched);
5148 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5149 * call schedule, and on return reacquire the lock.
5151 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5152 * operations here to prevent schedule() from being called twice (once via
5153 * spin_unlock(), once by hand).
5155 int __cond_resched_lock(spinlock_t *lock)
5157 int resched = should_resched(PREEMPT_LOCK_OFFSET);
5160 lockdep_assert_held(lock);
5162 if (spin_needbreak(lock) || resched) {
5165 preempt_schedule_common();
5173 EXPORT_SYMBOL(__cond_resched_lock);
5175 #ifndef CONFIG_PREEMPT_RT_FULL
5176 int __sched __cond_resched_softirq(void)
5178 BUG_ON(!in_softirq());
5180 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
5182 preempt_schedule_common();
5188 EXPORT_SYMBOL(__cond_resched_softirq);
5192 * yield - yield the current processor to other threads.
5194 * Do not ever use this function, there's a 99% chance you're doing it wrong.
5196 * The scheduler is at all times free to pick the calling task as the most
5197 * eligible task to run, if removing the yield() call from your code breaks
5198 * it, its already broken.
5200 * Typical broken usage is:
5205 * where one assumes that yield() will let 'the other' process run that will
5206 * make event true. If the current task is a SCHED_FIFO task that will never
5207 * happen. Never use yield() as a progress guarantee!!
5209 * If you want to use yield() to wait for something, use wait_event().
5210 * If you want to use yield() to be 'nice' for others, use cond_resched().
5211 * If you still want to use yield(), do not!
5213 void __sched yield(void)
5215 set_current_state(TASK_RUNNING);
5218 EXPORT_SYMBOL(yield);
5221 * yield_to - yield the current processor to another thread in
5222 * your thread group, or accelerate that thread toward the
5223 * processor it's on.
5225 * @preempt: whether task preemption is allowed or not
5227 * It's the caller's job to ensure that the target task struct
5228 * can't go away on us before we can do any checks.
5231 * true (>0) if we indeed boosted the target task.
5232 * false (0) if we failed to boost the target.
5233 * -ESRCH if there's no task to yield to.
5235 int __sched yield_to(struct task_struct *p, bool preempt)
5237 struct task_struct *curr = current;
5238 struct rq *rq, *p_rq;
5239 unsigned long flags;
5242 local_irq_save(flags);
5248 * If we're the only runnable task on the rq and target rq also
5249 * has only one task, there's absolutely no point in yielding.
5251 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5256 double_rq_lock(rq, p_rq);
5257 if (task_rq(p) != p_rq) {
5258 double_rq_unlock(rq, p_rq);
5262 if (!curr->sched_class->yield_to_task)
5265 if (curr->sched_class != p->sched_class)
5268 if (task_running(p_rq, p) || p->state)
5271 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5273 schedstat_inc(rq->yld_count);
5275 * Make p's CPU reschedule; pick_next_entity takes care of
5278 if (preempt && rq != p_rq)
5283 double_rq_unlock(rq, p_rq);
5285 local_irq_restore(flags);
5292 EXPORT_SYMBOL_GPL(yield_to);
5295 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5296 * that process accounting knows that this is a task in IO wait state.
5298 long __sched io_schedule_timeout(long timeout)
5300 int old_iowait = current->in_iowait;
5304 current->in_iowait = 1;
5305 blk_schedule_flush_plug(current);
5307 delayacct_blkio_start();
5309 atomic_inc(&rq->nr_iowait);
5310 ret = schedule_timeout(timeout);
5311 current->in_iowait = old_iowait;
5312 atomic_dec(&rq->nr_iowait);
5313 delayacct_blkio_end();
5317 EXPORT_SYMBOL(io_schedule_timeout);
5320 * sys_sched_get_priority_max - return maximum RT priority.
5321 * @policy: scheduling class.
5323 * Return: On success, this syscall returns the maximum
5324 * rt_priority that can be used by a given scheduling class.
5325 * On failure, a negative error code is returned.
5327 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5334 ret = MAX_USER_RT_PRIO-1;
5336 case SCHED_DEADLINE:
5347 * sys_sched_get_priority_min - return minimum RT priority.
5348 * @policy: scheduling class.
5350 * Return: On success, this syscall returns the minimum
5351 * rt_priority that can be used by a given scheduling class.
5352 * On failure, a negative error code is returned.
5354 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5363 case SCHED_DEADLINE:
5373 * sys_sched_rr_get_interval - return the default timeslice of a process.
5374 * @pid: pid of the process.
5375 * @interval: userspace pointer to the timeslice value.
5377 * this syscall writes the default timeslice value of a given process
5378 * into the user-space timespec buffer. A value of '0' means infinity.
5380 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5383 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5384 struct timespec __user *, interval)
5386 struct task_struct *p;
5387 unsigned int time_slice;
5398 p = find_process_by_pid(pid);
5402 retval = security_task_getscheduler(p);
5406 rq = task_rq_lock(p, &rf);
5408 if (p->sched_class->get_rr_interval)
5409 time_slice = p->sched_class->get_rr_interval(rq, p);
5410 task_rq_unlock(rq, p, &rf);
5413 jiffies_to_timespec(time_slice, &t);
5414 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5422 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5424 void sched_show_task(struct task_struct *p)
5426 unsigned long free = 0;
5428 unsigned long state = p->state;
5430 if (!try_get_task_stack(p))
5433 state = __ffs(state) + 1;
5434 printk(KERN_INFO "%-15.15s %c", p->comm,
5435 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5436 if (state == TASK_RUNNING)
5437 printk(KERN_CONT " running task ");
5438 #ifdef CONFIG_DEBUG_STACK_USAGE
5439 free = stack_not_used(p);
5444 ppid = task_pid_nr(rcu_dereference(p->real_parent));
5446 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5447 task_pid_nr(p), ppid,
5448 (unsigned long)task_thread_info(p)->flags);
5450 print_worker_info(KERN_INFO, p);
5451 show_stack(p, NULL);
5455 void show_state_filter(unsigned long state_filter)
5457 struct task_struct *g, *p;
5459 #if BITS_PER_LONG == 32
5461 " task PC stack pid father\n");
5464 " task PC stack pid father\n");
5467 for_each_process_thread(g, p) {
5469 * reset the NMI-timeout, listing all files on a slow
5470 * console might take a lot of time:
5471 * Also, reset softlockup watchdogs on all CPUs, because
5472 * another CPU might be blocked waiting for us to process
5475 touch_nmi_watchdog();
5476 touch_all_softlockup_watchdogs();
5477 if (!state_filter || (p->state & state_filter))
5481 #ifdef CONFIG_SCHED_DEBUG
5483 sysrq_sched_debug_show();
5487 * Only show locks if all tasks are dumped:
5490 debug_show_all_locks();
5493 void init_idle_bootup_task(struct task_struct *idle)
5495 idle->sched_class = &idle_sched_class;
5499 * init_idle - set up an idle thread for a given CPU
5500 * @idle: task in question
5501 * @cpu: cpu the idle task belongs to
5503 * NOTE: this function does not set the idle thread's NEED_RESCHED
5504 * flag, to make booting more robust.
5506 void init_idle(struct task_struct *idle, int cpu)
5508 struct rq *rq = cpu_rq(cpu);
5509 unsigned long flags;
5511 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5512 raw_spin_lock(&rq->lock);
5514 __sched_fork(0, idle);
5515 idle->state = TASK_RUNNING;
5516 idle->se.exec_start = sched_clock();
5518 kasan_unpoison_task_stack(idle);
5522 * Its possible that init_idle() gets called multiple times on a task,
5523 * in that case do_set_cpus_allowed() will not do the right thing.
5525 * And since this is boot we can forgo the serialization.
5527 set_cpus_allowed_common(idle, cpumask_of(cpu));
5530 * We're having a chicken and egg problem, even though we are
5531 * holding rq->lock, the cpu isn't yet set to this cpu so the
5532 * lockdep check in task_group() will fail.
5534 * Similar case to sched_fork(). / Alternatively we could
5535 * use task_rq_lock() here and obtain the other rq->lock.
5540 __set_task_cpu(idle, cpu);
5543 rq->curr = rq->idle = idle;
5544 idle->on_rq = TASK_ON_RQ_QUEUED;
5548 raw_spin_unlock(&rq->lock);
5549 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5551 /* Set the preempt count _outside_ the spinlocks! */
5552 init_idle_preempt_count(idle, cpu);
5553 #ifdef CONFIG_HAVE_PREEMPT_LAZY
5554 task_thread_info(idle)->preempt_lazy_count = 0;
5557 * The idle tasks have their own, simple scheduling class:
5559 idle->sched_class = &idle_sched_class;
5560 ftrace_graph_init_idle_task(idle, cpu);
5561 vtime_init_idle(idle, cpu);
5563 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5567 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5568 const struct cpumask *trial)
5570 int ret = 1, trial_cpus;
5571 struct dl_bw *cur_dl_b;
5572 unsigned long flags;
5574 if (!cpumask_weight(cur))
5577 rcu_read_lock_sched();
5578 cur_dl_b = dl_bw_of(cpumask_any(cur));
5579 trial_cpus = cpumask_weight(trial);
5581 raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
5582 if (cur_dl_b->bw != -1 &&
5583 cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
5585 raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
5586 rcu_read_unlock_sched();
5591 int task_can_attach(struct task_struct *p,
5592 const struct cpumask *cs_cpus_allowed)
5597 * Kthreads which disallow setaffinity shouldn't be moved
5598 * to a new cpuset; we don't want to change their cpu
5599 * affinity and isolating such threads by their set of
5600 * allowed nodes is unnecessary. Thus, cpusets are not
5601 * applicable for such threads. This prevents checking for
5602 * success of set_cpus_allowed_ptr() on all attached tasks
5603 * before cpus_allowed may be changed.
5605 if (p->flags & PF_NO_SETAFFINITY) {
5611 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5613 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
5618 unsigned long flags;
5620 rcu_read_lock_sched();
5621 dl_b = dl_bw_of(dest_cpu);
5622 raw_spin_lock_irqsave(&dl_b->lock, flags);
5623 cpus = dl_bw_cpus(dest_cpu);
5624 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
5629 * We reserve space for this task in the destination
5630 * root_domain, as we can't fail after this point.
5631 * We will free resources in the source root_domain
5632 * later on (see set_cpus_allowed_dl()).
5634 __dl_add(dl_b, p->dl.dl_bw);
5636 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5637 rcu_read_unlock_sched();
5647 static bool sched_smp_initialized __read_mostly;
5649 #ifdef CONFIG_NUMA_BALANCING
5650 /* Migrate current task p to target_cpu */
5651 int migrate_task_to(struct task_struct *p, int target_cpu)
5653 struct migration_arg arg = { p, target_cpu };
5654 int curr_cpu = task_cpu(p);
5656 if (curr_cpu == target_cpu)
5659 if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
5662 /* TODO: This is not properly updating schedstats */
5664 trace_sched_move_numa(p, curr_cpu, target_cpu);
5665 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5669 * Requeue a task on a given node and accurately track the number of NUMA
5670 * tasks on the runqueues
5672 void sched_setnuma(struct task_struct *p, int nid)
5674 bool queued, running;
5678 rq = task_rq_lock(p, &rf);
5679 queued = task_on_rq_queued(p);
5680 running = task_current(rq, p);
5683 dequeue_task(rq, p, DEQUEUE_SAVE);
5685 put_prev_task(rq, p);
5687 p->numa_preferred_nid = nid;
5690 enqueue_task(rq, p, ENQUEUE_RESTORE);
5692 set_curr_task(rq, p);
5693 task_rq_unlock(rq, p, &rf);
5695 #endif /* CONFIG_NUMA_BALANCING */
5697 #ifdef CONFIG_HOTPLUG_CPU
5698 static DEFINE_PER_CPU(struct mm_struct *, idle_last_mm);
5701 * Ensures that the idle task is using init_mm right before its cpu goes
5704 void idle_task_exit(void)
5706 struct mm_struct *mm = current->active_mm;
5708 BUG_ON(cpu_online(smp_processor_id()));
5710 if (mm != &init_mm) {
5711 switch_mm_irqs_off(mm, &init_mm, current);
5712 finish_arch_post_lock_switch();
5715 * Defer the cleanup to an alive cpu. On RT we can neither
5716 * call mmdrop() nor mmdrop_delayed() from here.
5718 per_cpu(idle_last_mm, smp_processor_id()) = mm;
5723 * Since this CPU is going 'away' for a while, fold any nr_active delta
5724 * we might have. Assumes we're called after migrate_tasks() so that the
5725 * nr_active count is stable. We need to take the teardown thread which
5726 * is calling this into account, so we hand in adjust = 1 to the load
5729 * Also see the comment "Global load-average calculations".
5731 static void calc_load_migrate(struct rq *rq)
5733 long delta = calc_load_fold_active(rq, 1);
5735 atomic_long_add(delta, &calc_load_tasks);
5738 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5742 static const struct sched_class fake_sched_class = {
5743 .put_prev_task = put_prev_task_fake,
5746 static struct task_struct fake_task = {
5748 * Avoid pull_{rt,dl}_task()
5750 .prio = MAX_PRIO + 1,
5751 .sched_class = &fake_sched_class,
5755 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5756 * try_to_wake_up()->select_task_rq().
5758 * Called with rq->lock held even though we'er in stop_machine() and
5759 * there's no concurrency possible, we hold the required locks anyway
5760 * because of lock validation efforts.
5762 static void migrate_tasks(struct rq *dead_rq)
5764 struct rq *rq = dead_rq;
5765 struct task_struct *next, *stop = rq->stop;
5766 struct pin_cookie cookie;
5770 * Fudge the rq selection such that the below task selection loop
5771 * doesn't get stuck on the currently eligible stop task.
5773 * We're currently inside stop_machine() and the rq is either stuck
5774 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5775 * either way we should never end up calling schedule() until we're
5781 * put_prev_task() and pick_next_task() sched
5782 * class method both need to have an up-to-date
5783 * value of rq->clock[_task]
5785 update_rq_clock(rq);
5789 * There's this thread running, bail when that's the only
5792 if (rq->nr_running == 1)
5796 * pick_next_task assumes pinned rq->lock.
5798 cookie = lockdep_pin_lock(&rq->lock);
5799 next = pick_next_task(rq, &fake_task, cookie);
5801 next->sched_class->put_prev_task(rq, next);
5804 * Rules for changing task_struct::cpus_allowed are holding
5805 * both pi_lock and rq->lock, such that holding either
5806 * stabilizes the mask.
5808 * Drop rq->lock is not quite as disastrous as it usually is
5809 * because !cpu_active at this point, which means load-balance
5810 * will not interfere. Also, stop-machine.
5812 lockdep_unpin_lock(&rq->lock, cookie);
5813 raw_spin_unlock(&rq->lock);
5814 raw_spin_lock(&next->pi_lock);
5815 raw_spin_lock(&rq->lock);
5818 * Since we're inside stop-machine, _nothing_ should have
5819 * changed the task, WARN if weird stuff happened, because in
5820 * that case the above rq->lock drop is a fail too.
5822 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5823 raw_spin_unlock(&next->pi_lock);
5827 /* Find suitable destination for @next, with force if needed. */
5828 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5830 rq = __migrate_task(rq, next, dest_cpu);
5831 if (rq != dead_rq) {
5832 raw_spin_unlock(&rq->lock);
5834 raw_spin_lock(&rq->lock);
5836 raw_spin_unlock(&next->pi_lock);
5841 #endif /* CONFIG_HOTPLUG_CPU */
5843 static void set_rq_online(struct rq *rq)
5846 const struct sched_class *class;
5848 cpumask_set_cpu(rq->cpu, rq->rd->online);
5851 for_each_class(class) {
5852 if (class->rq_online)
5853 class->rq_online(rq);
5858 static void set_rq_offline(struct rq *rq)
5861 const struct sched_class *class;
5863 for_each_class(class) {
5864 if (class->rq_offline)
5865 class->rq_offline(rq);
5868 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5873 static void set_cpu_rq_start_time(unsigned int cpu)
5875 struct rq *rq = cpu_rq(cpu);
5877 rq->age_stamp = sched_clock_cpu(cpu);
5880 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5882 #ifdef CONFIG_SCHED_DEBUG
5884 static __read_mostly int sched_debug_enabled;
5886 static int __init sched_debug_setup(char *str)
5888 sched_debug_enabled = 1;
5892 early_param("sched_debug", sched_debug_setup);
5894 static inline bool sched_debug(void)
5896 return sched_debug_enabled;
5899 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5900 struct cpumask *groupmask)
5902 struct sched_group *group = sd->groups;
5904 cpumask_clear(groupmask);
5906 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5908 if (!(sd->flags & SD_LOAD_BALANCE)) {
5909 printk("does not load-balance\n");
5911 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5916 printk(KERN_CONT "span %*pbl level %s\n",
5917 cpumask_pr_args(sched_domain_span(sd)), sd->name);
5919 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5920 printk(KERN_ERR "ERROR: domain->span does not contain "
5923 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5924 printk(KERN_ERR "ERROR: domain->groups does not contain"
5928 printk(KERN_DEBUG "%*s groups:", level + 1, "");
5932 printk(KERN_ERR "ERROR: group is NULL\n");
5936 if (!cpumask_weight(sched_group_cpus(group))) {
5937 printk(KERN_CONT "\n");
5938 printk(KERN_ERR "ERROR: empty group\n");
5942 if (!(sd->flags & SD_OVERLAP) &&
5943 cpumask_intersects(groupmask, sched_group_cpus(group))) {
5944 printk(KERN_CONT "\n");
5945 printk(KERN_ERR "ERROR: repeated CPUs\n");
5949 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5951 printk(KERN_CONT " %*pbl",
5952 cpumask_pr_args(sched_group_cpus(group)));
5953 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
5954 printk(KERN_CONT " (cpu_capacity = %d)",
5955 group->sgc->capacity);
5958 group = group->next;
5959 } while (group != sd->groups);
5960 printk(KERN_CONT "\n");
5962 if (!cpumask_equal(sched_domain_span(sd), groupmask))
5963 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5966 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5967 printk(KERN_ERR "ERROR: parent span is not a superset "
5968 "of domain->span\n");
5972 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5976 if (!sched_debug_enabled)
5980 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5984 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5987 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5995 #else /* !CONFIG_SCHED_DEBUG */
5997 # define sched_debug_enabled 0
5998 # define sched_domain_debug(sd, cpu) do { } while (0)
5999 static inline bool sched_debug(void)
6003 #endif /* CONFIG_SCHED_DEBUG */
6005 static int sd_degenerate(struct sched_domain *sd)
6007 if (cpumask_weight(sched_domain_span(sd)) == 1)
6010 /* Following flags need at least 2 groups */
6011 if (sd->flags & (SD_LOAD_BALANCE |
6012 SD_BALANCE_NEWIDLE |
6015 SD_SHARE_CPUCAPACITY |
6016 SD_ASYM_CPUCAPACITY |
6017 SD_SHARE_PKG_RESOURCES |
6018 SD_SHARE_POWERDOMAIN)) {
6019 if (sd->groups != sd->groups->next)
6023 /* Following flags don't use groups */
6024 if (sd->flags & (SD_WAKE_AFFINE))
6031 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6033 unsigned long cflags = sd->flags, pflags = parent->flags;
6035 if (sd_degenerate(parent))
6038 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6041 /* Flags needing groups don't count if only 1 group in parent */
6042 if (parent->groups == parent->groups->next) {
6043 pflags &= ~(SD_LOAD_BALANCE |
6044 SD_BALANCE_NEWIDLE |
6047 SD_ASYM_CPUCAPACITY |
6048 SD_SHARE_CPUCAPACITY |
6049 SD_SHARE_PKG_RESOURCES |
6051 SD_SHARE_POWERDOMAIN);
6052 if (nr_node_ids == 1)
6053 pflags &= ~SD_SERIALIZE;
6055 if (~cflags & pflags)
6061 static void free_rootdomain(struct rcu_head *rcu)
6063 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
6065 cpupri_cleanup(&rd->cpupri);
6066 cpudl_cleanup(&rd->cpudl);
6067 free_cpumask_var(rd->dlo_mask);
6068 free_cpumask_var(rd->rto_mask);
6069 free_cpumask_var(rd->online);
6070 free_cpumask_var(rd->span);
6074 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6076 struct root_domain *old_rd = NULL;
6077 unsigned long flags;
6079 raw_spin_lock_irqsave(&rq->lock, flags);
6084 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6087 cpumask_clear_cpu(rq->cpu, old_rd->span);
6090 * If we dont want to free the old_rd yet then
6091 * set old_rd to NULL to skip the freeing later
6094 if (!atomic_dec_and_test(&old_rd->refcount))
6098 atomic_inc(&rd->refcount);
6101 cpumask_set_cpu(rq->cpu, rd->span);
6102 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6105 raw_spin_unlock_irqrestore(&rq->lock, flags);
6108 call_rcu_sched(&old_rd->rcu, free_rootdomain);
6111 static int init_rootdomain(struct root_domain *rd)
6113 memset(rd, 0, sizeof(*rd));
6115 if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
6117 if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
6119 if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
6121 if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6124 init_dl_bw(&rd->dl_bw);
6125 if (cpudl_init(&rd->cpudl) != 0)
6128 if (cpupri_init(&rd->cpupri) != 0)
6133 free_cpumask_var(rd->rto_mask);
6135 free_cpumask_var(rd->dlo_mask);
6137 free_cpumask_var(rd->online);
6139 free_cpumask_var(rd->span);
6145 * By default the system creates a single root-domain with all cpus as
6146 * members (mimicking the global state we have today).
6148 struct root_domain def_root_domain;
6150 static void init_defrootdomain(void)
6152 init_rootdomain(&def_root_domain);
6154 atomic_set(&def_root_domain.refcount, 1);
6157 static struct root_domain *alloc_rootdomain(void)
6159 struct root_domain *rd;
6161 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6165 if (init_rootdomain(rd) != 0) {
6173 static void free_sched_groups(struct sched_group *sg, int free_sgc)
6175 struct sched_group *tmp, *first;
6184 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
6189 } while (sg != first);
6192 static void destroy_sched_domain(struct sched_domain *sd)
6195 * If its an overlapping domain it has private groups, iterate and
6198 if (sd->flags & SD_OVERLAP) {
6199 free_sched_groups(sd->groups, 1);
6200 } else if (atomic_dec_and_test(&sd->groups->ref)) {
6201 kfree(sd->groups->sgc);
6204 if (sd->shared && atomic_dec_and_test(&sd->shared->ref))
6209 static void destroy_sched_domains_rcu(struct rcu_head *rcu)
6211 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
6214 struct sched_domain *parent = sd->parent;
6215 destroy_sched_domain(sd);
6220 static void destroy_sched_domains(struct sched_domain *sd)
6223 call_rcu(&sd->rcu, destroy_sched_domains_rcu);
6227 * Keep a special pointer to the highest sched_domain that has
6228 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
6229 * allows us to avoid some pointer chasing select_idle_sibling().
6231 * Also keep a unique ID per domain (we use the first cpu number in
6232 * the cpumask of the domain), this allows us to quickly tell if
6233 * two cpus are in the same cache domain, see cpus_share_cache().
6235 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
6236 DEFINE_PER_CPU(int, sd_llc_size);
6237 DEFINE_PER_CPU(int, sd_llc_id);
6238 DEFINE_PER_CPU(struct sched_domain_shared *, sd_llc_shared);
6239 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
6240 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
6242 static void update_top_cache_domain(int cpu)
6244 struct sched_domain_shared *sds = NULL;
6245 struct sched_domain *sd;
6249 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
6251 id = cpumask_first(sched_domain_span(sd));
6252 size = cpumask_weight(sched_domain_span(sd));
6256 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
6257 per_cpu(sd_llc_size, cpu) = size;
6258 per_cpu(sd_llc_id, cpu) = id;
6259 rcu_assign_pointer(per_cpu(sd_llc_shared, cpu), sds);
6261 sd = lowest_flag_domain(cpu, SD_NUMA);
6262 rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
6264 sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
6265 rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
6269 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6270 * hold the hotplug lock.
6273 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6275 struct rq *rq = cpu_rq(cpu);
6276 struct sched_domain *tmp;
6278 /* Remove the sched domains which do not contribute to scheduling. */
6279 for (tmp = sd; tmp; ) {
6280 struct sched_domain *parent = tmp->parent;
6284 if (sd_parent_degenerate(tmp, parent)) {
6285 tmp->parent = parent->parent;
6287 parent->parent->child = tmp;
6289 * Transfer SD_PREFER_SIBLING down in case of a
6290 * degenerate parent; the spans match for this
6291 * so the property transfers.
6293 if (parent->flags & SD_PREFER_SIBLING)
6294 tmp->flags |= SD_PREFER_SIBLING;
6295 destroy_sched_domain(parent);
6300 if (sd && sd_degenerate(sd)) {
6303 destroy_sched_domain(tmp);
6308 sched_domain_debug(sd, cpu);
6310 rq_attach_root(rq, rd);
6312 rcu_assign_pointer(rq->sd, sd);
6313 destroy_sched_domains(tmp);
6315 update_top_cache_domain(cpu);
6318 /* Setup the mask of cpus configured for isolated domains */
6319 static int __init isolated_cpu_setup(char *str)
6323 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6324 ret = cpulist_parse(str, cpu_isolated_map);
6326 pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
6331 __setup("isolcpus=", isolated_cpu_setup);
6334 struct sched_domain ** __percpu sd;
6335 struct root_domain *rd;
6346 * Build an iteration mask that can exclude certain CPUs from the upwards
6349 * Asymmetric node setups can result in situations where the domain tree is of
6350 * unequal depth, make sure to skip domains that already cover the entire
6353 * In that case build_sched_domains() will have terminated the iteration early
6354 * and our sibling sd spans will be empty. Domains should always include the
6355 * cpu they're built on, so check that.
6358 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
6360 const struct cpumask *span = sched_domain_span(sd);
6361 struct sd_data *sdd = sd->private;
6362 struct sched_domain *sibling;
6365 for_each_cpu(i, span) {
6366 sibling = *per_cpu_ptr(sdd->sd, i);
6367 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6370 cpumask_set_cpu(i, sched_group_mask(sg));
6375 * Return the canonical balance cpu for this group, this is the first cpu
6376 * of this group that's also in the iteration mask.
6378 int group_balance_cpu(struct sched_group *sg)
6380 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
6384 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
6386 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
6387 const struct cpumask *span = sched_domain_span(sd);
6388 struct cpumask *covered = sched_domains_tmpmask;
6389 struct sd_data *sdd = sd->private;
6390 struct sched_domain *sibling;
6393 cpumask_clear(covered);
6395 for_each_cpu(i, span) {
6396 struct cpumask *sg_span;
6398 if (cpumask_test_cpu(i, covered))
6401 sibling = *per_cpu_ptr(sdd->sd, i);
6403 /* See the comment near build_group_mask(). */
6404 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
6407 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6408 GFP_KERNEL, cpu_to_node(cpu));
6413 sg_span = sched_group_cpus(sg);
6415 cpumask_copy(sg_span, sched_domain_span(sibling->child));
6417 cpumask_set_cpu(i, sg_span);
6419 cpumask_or(covered, covered, sg_span);
6421 sg->sgc = *per_cpu_ptr(sdd->sgc, i);
6422 if (atomic_inc_return(&sg->sgc->ref) == 1)
6423 build_group_mask(sd, sg);
6426 * Initialize sgc->capacity such that even if we mess up the
6427 * domains and no possible iteration will get us here, we won't
6430 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
6433 * Make sure the first group of this domain contains the
6434 * canonical balance cpu. Otherwise the sched_domain iteration
6435 * breaks. See update_sg_lb_stats().
6437 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
6438 group_balance_cpu(sg) == cpu)
6448 sd->groups = groups;
6453 free_sched_groups(first, 0);
6458 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
6460 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6461 struct sched_domain *child = sd->child;
6464 cpu = cpumask_first(sched_domain_span(child));
6467 *sg = *per_cpu_ptr(sdd->sg, cpu);
6468 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
6469 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
6476 * build_sched_groups will build a circular linked list of the groups
6477 * covered by the given span, and will set each group's ->cpumask correctly,
6478 * and ->cpu_capacity to 0.
6480 * Assumes the sched_domain tree is fully constructed
6483 build_sched_groups(struct sched_domain *sd, int cpu)
6485 struct sched_group *first = NULL, *last = NULL;
6486 struct sd_data *sdd = sd->private;
6487 const struct cpumask *span = sched_domain_span(sd);
6488 struct cpumask *covered;
6491 get_group(cpu, sdd, &sd->groups);
6492 atomic_inc(&sd->groups->ref);
6494 if (cpu != cpumask_first(span))
6497 lockdep_assert_held(&sched_domains_mutex);
6498 covered = sched_domains_tmpmask;
6500 cpumask_clear(covered);
6502 for_each_cpu(i, span) {
6503 struct sched_group *sg;
6506 if (cpumask_test_cpu(i, covered))
6509 group = get_group(i, sdd, &sg);
6510 cpumask_setall(sched_group_mask(sg));
6512 for_each_cpu(j, span) {
6513 if (get_group(j, sdd, NULL) != group)
6516 cpumask_set_cpu(j, covered);
6517 cpumask_set_cpu(j, sched_group_cpus(sg));
6532 * Initialize sched groups cpu_capacity.
6534 * cpu_capacity indicates the capacity of sched group, which is used while
6535 * distributing the load between different sched groups in a sched domain.
6536 * Typically cpu_capacity for all the groups in a sched domain will be same
6537 * unless there are asymmetries in the topology. If there are asymmetries,
6538 * group having more cpu_capacity will pickup more load compared to the
6539 * group having less cpu_capacity.
6541 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
6543 struct sched_group *sg = sd->groups;
6548 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6550 } while (sg != sd->groups);
6552 if (cpu != group_balance_cpu(sg))
6555 update_group_capacity(sd, cpu);
6559 * Initializers for schedule domains
6560 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6563 static int default_relax_domain_level = -1;
6564 int sched_domain_level_max;
6566 static int __init setup_relax_domain_level(char *str)
6568 if (kstrtoint(str, 0, &default_relax_domain_level))
6569 pr_warn("Unable to set relax_domain_level\n");
6573 __setup("relax_domain_level=", setup_relax_domain_level);
6575 static void set_domain_attribute(struct sched_domain *sd,
6576 struct sched_domain_attr *attr)
6580 if (!attr || attr->relax_domain_level < 0) {
6581 if (default_relax_domain_level < 0)
6584 request = default_relax_domain_level;
6586 request = attr->relax_domain_level;
6587 if (request < sd->level) {
6588 /* turn off idle balance on this domain */
6589 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6591 /* turn on idle balance on this domain */
6592 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6596 static void __sdt_free(const struct cpumask *cpu_map);
6597 static int __sdt_alloc(const struct cpumask *cpu_map);
6599 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6600 const struct cpumask *cpu_map)
6604 if (!atomic_read(&d->rd->refcount))
6605 free_rootdomain(&d->rd->rcu); /* fall through */
6607 free_percpu(d->sd); /* fall through */
6609 __sdt_free(cpu_map); /* fall through */
6615 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6616 const struct cpumask *cpu_map)
6618 memset(d, 0, sizeof(*d));
6620 if (__sdt_alloc(cpu_map))
6621 return sa_sd_storage;
6622 d->sd = alloc_percpu(struct sched_domain *);
6624 return sa_sd_storage;
6625 d->rd = alloc_rootdomain();
6628 return sa_rootdomain;
6632 * NULL the sd_data elements we've used to build the sched_domain and
6633 * sched_group structure so that the subsequent __free_domain_allocs()
6634 * will not free the data we're using.
6636 static void claim_allocations(int cpu, struct sched_domain *sd)
6638 struct sd_data *sdd = sd->private;
6640 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6641 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6643 if (atomic_read(&(*per_cpu_ptr(sdd->sds, cpu))->ref))
6644 *per_cpu_ptr(sdd->sds, cpu) = NULL;
6646 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6647 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6649 if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
6650 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
6654 static int sched_domains_numa_levels;
6655 enum numa_topology_type sched_numa_topology_type;
6656 static int *sched_domains_numa_distance;
6657 int sched_max_numa_distance;
6658 static struct cpumask ***sched_domains_numa_masks;
6659 static int sched_domains_curr_level;
6663 * SD_flags allowed in topology descriptions.
6665 * These flags are purely descriptive of the topology and do not prescribe
6666 * behaviour. Behaviour is artificial and mapped in the below sd_init()
6669 * SD_SHARE_CPUCAPACITY - describes SMT topologies
6670 * SD_SHARE_PKG_RESOURCES - describes shared caches
6671 * SD_NUMA - describes NUMA topologies
6672 * SD_SHARE_POWERDOMAIN - describes shared power domain
6673 * SD_ASYM_CPUCAPACITY - describes mixed capacity topologies
6675 * Odd one out, which beside describing the topology has a quirk also
6676 * prescribes the desired behaviour that goes along with it:
6678 * SD_ASYM_PACKING - describes SMT quirks
6680 #define TOPOLOGY_SD_FLAGS \
6681 (SD_SHARE_CPUCAPACITY | \
6682 SD_SHARE_PKG_RESOURCES | \
6685 SD_ASYM_CPUCAPACITY | \
6686 SD_SHARE_POWERDOMAIN)
6688 static struct sched_domain *
6689 sd_init(struct sched_domain_topology_level *tl,
6690 const struct cpumask *cpu_map,
6691 struct sched_domain *child, int cpu)
6693 struct sd_data *sdd = &tl->data;
6694 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
6695 int sd_id, sd_weight, sd_flags = 0;
6699 * Ugly hack to pass state to sd_numa_mask()...
6701 sched_domains_curr_level = tl->numa_level;
6704 sd_weight = cpumask_weight(tl->mask(cpu));
6707 sd_flags = (*tl->sd_flags)();
6708 if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
6709 "wrong sd_flags in topology description\n"))
6710 sd_flags &= ~TOPOLOGY_SD_FLAGS;
6712 *sd = (struct sched_domain){
6713 .min_interval = sd_weight,
6714 .max_interval = 2*sd_weight,
6716 .imbalance_pct = 125,
6718 .cache_nice_tries = 0,
6725 .flags = 1*SD_LOAD_BALANCE
6726 | 1*SD_BALANCE_NEWIDLE
6731 | 0*SD_SHARE_CPUCAPACITY
6732 | 0*SD_SHARE_PKG_RESOURCES
6734 | 0*SD_PREFER_SIBLING
6739 .last_balance = jiffies,
6740 .balance_interval = sd_weight,
6742 .max_newidle_lb_cost = 0,
6743 .next_decay_max_lb_cost = jiffies,
6745 #ifdef CONFIG_SCHED_DEBUG
6750 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6751 sd_id = cpumask_first(sched_domain_span(sd));
6754 * Convert topological properties into behaviour.
6757 if (sd->flags & SD_ASYM_CPUCAPACITY) {
6758 struct sched_domain *t = sd;
6760 for_each_lower_domain(t)
6761 t->flags |= SD_BALANCE_WAKE;
6764 if (sd->flags & SD_SHARE_CPUCAPACITY) {
6765 sd->flags |= SD_PREFER_SIBLING;
6766 sd->imbalance_pct = 110;
6767 sd->smt_gain = 1178; /* ~15% */
6769 } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6770 sd->imbalance_pct = 117;
6771 sd->cache_nice_tries = 1;
6775 } else if (sd->flags & SD_NUMA) {
6776 sd->cache_nice_tries = 2;
6780 sd->flags |= SD_SERIALIZE;
6781 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
6782 sd->flags &= ~(SD_BALANCE_EXEC |
6789 sd->flags |= SD_PREFER_SIBLING;
6790 sd->cache_nice_tries = 1;
6796 * For all levels sharing cache; connect a sched_domain_shared
6799 if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6800 sd->shared = *per_cpu_ptr(sdd->sds, sd_id);
6801 atomic_inc(&sd->shared->ref);
6802 atomic_set(&sd->shared->nr_busy_cpus, sd_weight);
6811 * Topology list, bottom-up.
6813 static struct sched_domain_topology_level default_topology[] = {
6814 #ifdef CONFIG_SCHED_SMT
6815 { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
6817 #ifdef CONFIG_SCHED_MC
6818 { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
6820 { cpu_cpu_mask, SD_INIT_NAME(DIE) },
6824 static struct sched_domain_topology_level *sched_domain_topology =
6827 #define for_each_sd_topology(tl) \
6828 for (tl = sched_domain_topology; tl->mask; tl++)
6830 void set_sched_topology(struct sched_domain_topology_level *tl)
6832 if (WARN_ON_ONCE(sched_smp_initialized))
6835 sched_domain_topology = tl;
6840 static const struct cpumask *sd_numa_mask(int cpu)
6842 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6845 static void sched_numa_warn(const char *str)
6847 static int done = false;
6855 printk(KERN_WARNING "ERROR: %s\n\n", str);
6857 for (i = 0; i < nr_node_ids; i++) {
6858 printk(KERN_WARNING " ");
6859 for (j = 0; j < nr_node_ids; j++)
6860 printk(KERN_CONT "%02d ", node_distance(i,j));
6861 printk(KERN_CONT "\n");
6863 printk(KERN_WARNING "\n");
6866 bool find_numa_distance(int distance)
6870 if (distance == node_distance(0, 0))
6873 for (i = 0; i < sched_domains_numa_levels; i++) {
6874 if (sched_domains_numa_distance[i] == distance)
6882 * A system can have three types of NUMA topology:
6883 * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6884 * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6885 * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6887 * The difference between a glueless mesh topology and a backplane
6888 * topology lies in whether communication between not directly
6889 * connected nodes goes through intermediary nodes (where programs
6890 * could run), or through backplane controllers. This affects
6891 * placement of programs.
6893 * The type of topology can be discerned with the following tests:
6894 * - If the maximum distance between any nodes is 1 hop, the system
6895 * is directly connected.
6896 * - If for two nodes A and B, located N > 1 hops away from each other,
6897 * there is an intermediary node C, which is < N hops away from both
6898 * nodes A and B, the system is a glueless mesh.
6900 static void init_numa_topology_type(void)
6904 n = sched_max_numa_distance;
6906 if (sched_domains_numa_levels <= 1) {
6907 sched_numa_topology_type = NUMA_DIRECT;
6911 for_each_online_node(a) {
6912 for_each_online_node(b) {
6913 /* Find two nodes furthest removed from each other. */
6914 if (node_distance(a, b) < n)
6917 /* Is there an intermediary node between a and b? */
6918 for_each_online_node(c) {
6919 if (node_distance(a, c) < n &&
6920 node_distance(b, c) < n) {
6921 sched_numa_topology_type =
6927 sched_numa_topology_type = NUMA_BACKPLANE;
6933 static void sched_init_numa(void)
6935 int next_distance, curr_distance = node_distance(0, 0);
6936 struct sched_domain_topology_level *tl;
6940 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6941 if (!sched_domains_numa_distance)
6945 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6946 * unique distances in the node_distance() table.
6948 * Assumes node_distance(0,j) includes all distances in
6949 * node_distance(i,j) in order to avoid cubic time.
6951 next_distance = curr_distance;
6952 for (i = 0; i < nr_node_ids; i++) {
6953 for (j = 0; j < nr_node_ids; j++) {
6954 for (k = 0; k < nr_node_ids; k++) {
6955 int distance = node_distance(i, k);
6957 if (distance > curr_distance &&
6958 (distance < next_distance ||
6959 next_distance == curr_distance))
6960 next_distance = distance;
6963 * While not a strong assumption it would be nice to know
6964 * about cases where if node A is connected to B, B is not
6965 * equally connected to A.
6967 if (sched_debug() && node_distance(k, i) != distance)
6968 sched_numa_warn("Node-distance not symmetric");
6970 if (sched_debug() && i && !find_numa_distance(distance))
6971 sched_numa_warn("Node-0 not representative");
6973 if (next_distance != curr_distance) {
6974 sched_domains_numa_distance[level++] = next_distance;
6975 sched_domains_numa_levels = level;
6976 curr_distance = next_distance;
6981 * In case of sched_debug() we verify the above assumption.
6991 * 'level' contains the number of unique distances, excluding the
6992 * identity distance node_distance(i,i).
6994 * The sched_domains_numa_distance[] array includes the actual distance
6999 * Here, we should temporarily reset sched_domains_numa_levels to 0.
7000 * If it fails to allocate memory for array sched_domains_numa_masks[][],
7001 * the array will contain less then 'level' members. This could be
7002 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
7003 * in other functions.
7005 * We reset it to 'level' at the end of this function.
7007 sched_domains_numa_levels = 0;
7009 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
7010 if (!sched_domains_numa_masks)
7014 * Now for each level, construct a mask per node which contains all
7015 * cpus of nodes that are that many hops away from us.
7017 for (i = 0; i < level; i++) {
7018 sched_domains_numa_masks[i] =
7019 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
7020 if (!sched_domains_numa_masks[i])
7023 for (j = 0; j < nr_node_ids; j++) {
7024 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
7028 sched_domains_numa_masks[i][j] = mask;
7031 if (node_distance(j, k) > sched_domains_numa_distance[i])
7034 cpumask_or(mask, mask, cpumask_of_node(k));
7039 /* Compute default topology size */
7040 for (i = 0; sched_domain_topology[i].mask; i++);
7042 tl = kzalloc((i + level + 1) *
7043 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
7048 * Copy the default topology bits..
7050 for (i = 0; sched_domain_topology[i].mask; i++)
7051 tl[i] = sched_domain_topology[i];
7054 * .. and append 'j' levels of NUMA goodness.
7056 for (j = 0; j < level; i++, j++) {
7057 tl[i] = (struct sched_domain_topology_level){
7058 .mask = sd_numa_mask,
7059 .sd_flags = cpu_numa_flags,
7060 .flags = SDTL_OVERLAP,
7066 sched_domain_topology = tl;
7068 sched_domains_numa_levels = level;
7069 sched_max_numa_distance = sched_domains_numa_distance[level - 1];
7071 init_numa_topology_type();
7074 static void sched_domains_numa_masks_set(unsigned int cpu)
7076 int node = cpu_to_node(cpu);
7079 for (i = 0; i < sched_domains_numa_levels; i++) {
7080 for (j = 0; j < nr_node_ids; j++) {
7081 if (node_distance(j, node) <= sched_domains_numa_distance[i])
7082 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
7087 static void sched_domains_numa_masks_clear(unsigned int cpu)
7091 for (i = 0; i < sched_domains_numa_levels; i++) {
7092 for (j = 0; j < nr_node_ids; j++)
7093 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
7098 static inline void sched_init_numa(void) { }
7099 static void sched_domains_numa_masks_set(unsigned int cpu) { }
7100 static void sched_domains_numa_masks_clear(unsigned int cpu) { }
7101 #endif /* CONFIG_NUMA */
7103 static int __sdt_alloc(const struct cpumask *cpu_map)
7105 struct sched_domain_topology_level *tl;
7108 for_each_sd_topology(tl) {
7109 struct sd_data *sdd = &tl->data;
7111 sdd->sd = alloc_percpu(struct sched_domain *);
7115 sdd->sds = alloc_percpu(struct sched_domain_shared *);
7119 sdd->sg = alloc_percpu(struct sched_group *);
7123 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
7127 for_each_cpu(j, cpu_map) {
7128 struct sched_domain *sd;
7129 struct sched_domain_shared *sds;
7130 struct sched_group *sg;
7131 struct sched_group_capacity *sgc;
7133 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
7134 GFP_KERNEL, cpu_to_node(j));
7138 *per_cpu_ptr(sdd->sd, j) = sd;
7140 sds = kzalloc_node(sizeof(struct sched_domain_shared),
7141 GFP_KERNEL, cpu_to_node(j));
7145 *per_cpu_ptr(sdd->sds, j) = sds;
7147 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
7148 GFP_KERNEL, cpu_to_node(j));
7154 *per_cpu_ptr(sdd->sg, j) = sg;
7156 sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
7157 GFP_KERNEL, cpu_to_node(j));
7161 *per_cpu_ptr(sdd->sgc, j) = sgc;
7168 static void __sdt_free(const struct cpumask *cpu_map)
7170 struct sched_domain_topology_level *tl;
7173 for_each_sd_topology(tl) {
7174 struct sd_data *sdd = &tl->data;
7176 for_each_cpu(j, cpu_map) {
7177 struct sched_domain *sd;
7180 sd = *per_cpu_ptr(sdd->sd, j);
7181 if (sd && (sd->flags & SD_OVERLAP))
7182 free_sched_groups(sd->groups, 0);
7183 kfree(*per_cpu_ptr(sdd->sd, j));
7187 kfree(*per_cpu_ptr(sdd->sds, j));
7189 kfree(*per_cpu_ptr(sdd->sg, j));
7191 kfree(*per_cpu_ptr(sdd->sgc, j));
7193 free_percpu(sdd->sd);
7195 free_percpu(sdd->sds);
7197 free_percpu(sdd->sg);
7199 free_percpu(sdd->sgc);
7204 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
7205 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7206 struct sched_domain *child, int cpu)
7208 struct sched_domain *sd = sd_init(tl, cpu_map, child, cpu);
7211 sd->level = child->level + 1;
7212 sched_domain_level_max = max(sched_domain_level_max, sd->level);
7215 if (!cpumask_subset(sched_domain_span(child),
7216 sched_domain_span(sd))) {
7217 pr_err("BUG: arch topology borken\n");
7218 #ifdef CONFIG_SCHED_DEBUG
7219 pr_err(" the %s domain not a subset of the %s domain\n",
7220 child->name, sd->name);
7222 /* Fixup, ensure @sd has at least @child cpus. */
7223 cpumask_or(sched_domain_span(sd),
7224 sched_domain_span(sd),
7225 sched_domain_span(child));
7229 set_domain_attribute(sd, attr);
7235 * Build sched domains for a given set of cpus and attach the sched domains
7236 * to the individual cpus
7238 static int build_sched_domains(const struct cpumask *cpu_map,
7239 struct sched_domain_attr *attr)
7241 enum s_alloc alloc_state;
7242 struct sched_domain *sd;
7244 struct rq *rq = NULL;
7245 int i, ret = -ENOMEM;
7247 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7248 if (alloc_state != sa_rootdomain)
7251 /* Set up domains for cpus specified by the cpu_map. */
7252 for_each_cpu(i, cpu_map) {
7253 struct sched_domain_topology_level *tl;
7256 for_each_sd_topology(tl) {
7257 sd = build_sched_domain(tl, cpu_map, attr, sd, i);
7258 if (tl == sched_domain_topology)
7259 *per_cpu_ptr(d.sd, i) = sd;
7260 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
7261 sd->flags |= SD_OVERLAP;
7262 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
7267 /* Build the groups for the domains */
7268 for_each_cpu(i, cpu_map) {
7269 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7270 sd->span_weight = cpumask_weight(sched_domain_span(sd));
7271 if (sd->flags & SD_OVERLAP) {
7272 if (build_overlap_sched_groups(sd, i))
7275 if (build_sched_groups(sd, i))
7281 /* Calculate CPU capacity for physical packages and nodes */
7282 for (i = nr_cpumask_bits-1; i >= 0; i--) {
7283 if (!cpumask_test_cpu(i, cpu_map))
7286 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7287 claim_allocations(i, sd);
7288 init_sched_groups_capacity(i, sd);
7292 /* Attach the domains */
7294 for_each_cpu(i, cpu_map) {
7296 sd = *per_cpu_ptr(d.sd, i);
7298 /* Use READ_ONCE()/WRITE_ONCE() to avoid load/store tearing: */
7299 if (rq->cpu_capacity_orig > READ_ONCE(d.rd->max_cpu_capacity))
7300 WRITE_ONCE(d.rd->max_cpu_capacity, rq->cpu_capacity_orig);
7302 cpu_attach_domain(sd, d.rd, i);
7306 if (rq && sched_debug_enabled) {
7307 pr_info("span: %*pbl (max cpu_capacity = %lu)\n",
7308 cpumask_pr_args(cpu_map), rq->rd->max_cpu_capacity);
7313 __free_domain_allocs(&d, alloc_state, cpu_map);
7317 static cpumask_var_t *doms_cur; /* current sched domains */
7318 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7319 static struct sched_domain_attr *dattr_cur;
7320 /* attribues of custom domains in 'doms_cur' */
7323 * Special case: If a kmalloc of a doms_cur partition (array of
7324 * cpumask) fails, then fallback to a single sched domain,
7325 * as determined by the single cpumask fallback_doms.
7327 static cpumask_var_t fallback_doms;
7330 * arch_update_cpu_topology lets virtualized architectures update the
7331 * cpu core maps. It is supposed to return 1 if the topology changed
7332 * or 0 if it stayed the same.
7334 int __weak arch_update_cpu_topology(void)
7339 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7342 cpumask_var_t *doms;
7344 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7347 for (i = 0; i < ndoms; i++) {
7348 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7349 free_sched_domains(doms, i);
7356 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7359 for (i = 0; i < ndoms; i++)
7360 free_cpumask_var(doms[i]);
7365 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7366 * For now this just excludes isolated cpus, but could be used to
7367 * exclude other special cases in the future.
7369 static int init_sched_domains(const struct cpumask *cpu_map)
7373 arch_update_cpu_topology();
7375 doms_cur = alloc_sched_domains(ndoms_cur);
7377 doms_cur = &fallback_doms;
7378 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7379 err = build_sched_domains(doms_cur[0], NULL);
7380 register_sched_domain_sysctl();
7386 * Detach sched domains from a group of cpus specified in cpu_map
7387 * These cpus will now be attached to the NULL domain
7389 static void detach_destroy_domains(const struct cpumask *cpu_map)
7394 for_each_cpu(i, cpu_map)
7395 cpu_attach_domain(NULL, &def_root_domain, i);
7399 /* handle null as "default" */
7400 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7401 struct sched_domain_attr *new, int idx_new)
7403 struct sched_domain_attr tmp;
7410 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7411 new ? (new + idx_new) : &tmp,
7412 sizeof(struct sched_domain_attr));
7416 * Partition sched domains as specified by the 'ndoms_new'
7417 * cpumasks in the array doms_new[] of cpumasks. This compares
7418 * doms_new[] to the current sched domain partitioning, doms_cur[].
7419 * It destroys each deleted domain and builds each new domain.
7421 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7422 * The masks don't intersect (don't overlap.) We should setup one
7423 * sched domain for each mask. CPUs not in any of the cpumasks will
7424 * not be load balanced. If the same cpumask appears both in the
7425 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7428 * The passed in 'doms_new' should be allocated using
7429 * alloc_sched_domains. This routine takes ownership of it and will
7430 * free_sched_domains it when done with it. If the caller failed the
7431 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7432 * and partition_sched_domains() will fallback to the single partition
7433 * 'fallback_doms', it also forces the domains to be rebuilt.
7435 * If doms_new == NULL it will be replaced with cpu_online_mask.
7436 * ndoms_new == 0 is a special case for destroying existing domains,
7437 * and it will not create the default domain.
7439 * Call with hotplug lock held
7441 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7442 struct sched_domain_attr *dattr_new)
7447 mutex_lock(&sched_domains_mutex);
7449 /* always unregister in case we don't destroy any domains */
7450 unregister_sched_domain_sysctl();
7452 /* Let architecture update cpu core mappings. */
7453 new_topology = arch_update_cpu_topology();
7455 n = doms_new ? ndoms_new : 0;
7457 /* Destroy deleted domains */
7458 for (i = 0; i < ndoms_cur; i++) {
7459 for (j = 0; j < n && !new_topology; j++) {
7460 if (cpumask_equal(doms_cur[i], doms_new[j])
7461 && dattrs_equal(dattr_cur, i, dattr_new, j))
7464 /* no match - a current sched domain not in new doms_new[] */
7465 detach_destroy_domains(doms_cur[i]);
7471 if (doms_new == NULL) {
7473 doms_new = &fallback_doms;
7474 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7475 WARN_ON_ONCE(dattr_new);
7478 /* Build new domains */
7479 for (i = 0; i < ndoms_new; i++) {
7480 for (j = 0; j < n && !new_topology; j++) {
7481 if (cpumask_equal(doms_new[i], doms_cur[j])
7482 && dattrs_equal(dattr_new, i, dattr_cur, j))
7485 /* no match - add a new doms_new */
7486 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7491 /* Remember the new sched domains */
7492 if (doms_cur != &fallback_doms)
7493 free_sched_domains(doms_cur, ndoms_cur);
7494 kfree(dattr_cur); /* kfree(NULL) is safe */
7495 doms_cur = doms_new;
7496 dattr_cur = dattr_new;
7497 ndoms_cur = ndoms_new;
7499 register_sched_domain_sysctl();
7501 mutex_unlock(&sched_domains_mutex);
7504 static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
7507 * Update cpusets according to cpu_active mask. If cpusets are
7508 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7509 * around partition_sched_domains().
7511 * If we come here as part of a suspend/resume, don't touch cpusets because we
7512 * want to restore it back to its original state upon resume anyway.
7514 static void cpuset_cpu_active(void)
7516 if (cpuhp_tasks_frozen) {
7518 * num_cpus_frozen tracks how many CPUs are involved in suspend
7519 * resume sequence. As long as this is not the last online
7520 * operation in the resume sequence, just build a single sched
7521 * domain, ignoring cpusets.
7524 if (likely(num_cpus_frozen)) {
7525 partition_sched_domains(1, NULL, NULL);
7529 * This is the last CPU online operation. So fall through and
7530 * restore the original sched domains by considering the
7531 * cpuset configurations.
7534 cpuset_update_active_cpus(true);
7537 static int cpuset_cpu_inactive(unsigned int cpu)
7539 unsigned long flags;
7544 if (!cpuhp_tasks_frozen) {
7545 rcu_read_lock_sched();
7546 dl_b = dl_bw_of(cpu);
7548 raw_spin_lock_irqsave(&dl_b->lock, flags);
7549 cpus = dl_bw_cpus(cpu);
7550 overflow = __dl_overflow(dl_b, cpus, 0, 0);
7551 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7553 rcu_read_unlock_sched();
7557 cpuset_update_active_cpus(false);
7560 partition_sched_domains(1, NULL, NULL);
7565 int sched_cpu_activate(unsigned int cpu)
7567 struct rq *rq = cpu_rq(cpu);
7568 unsigned long flags;
7570 set_cpu_active(cpu, true);
7572 if (sched_smp_initialized) {
7573 sched_domains_numa_masks_set(cpu);
7574 cpuset_cpu_active();
7578 * Put the rq online, if not already. This happens:
7580 * 1) In the early boot process, because we build the real domains
7581 * after all cpus have been brought up.
7583 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
7586 raw_spin_lock_irqsave(&rq->lock, flags);
7588 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7591 raw_spin_unlock_irqrestore(&rq->lock, flags);
7593 update_max_interval();
7598 int sched_cpu_deactivate(unsigned int cpu)
7602 set_cpu_active(cpu, false);
7604 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
7605 * users of this state to go away such that all new such users will
7608 * For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
7609 * not imply sync_sched(), so wait for both.
7611 * Do sync before park smpboot threads to take care the rcu boost case.
7613 if (IS_ENABLED(CONFIG_PREEMPT))
7614 synchronize_rcu_mult(call_rcu, call_rcu_sched);
7618 if (!sched_smp_initialized)
7621 ret = cpuset_cpu_inactive(cpu);
7623 set_cpu_active(cpu, true);
7626 sched_domains_numa_masks_clear(cpu);
7630 static void sched_rq_cpu_starting(unsigned int cpu)
7632 struct rq *rq = cpu_rq(cpu);
7634 rq->calc_load_update = calc_load_update;
7635 update_max_interval();
7638 int sched_cpu_starting(unsigned int cpu)
7640 set_cpu_rq_start_time(cpu);
7641 sched_rq_cpu_starting(cpu);
7645 #ifdef CONFIG_HOTPLUG_CPU
7646 int sched_cpu_dying(unsigned int cpu)
7648 struct rq *rq = cpu_rq(cpu);
7649 unsigned long flags;
7651 /* Handle pending wakeups and then migrate everything off */
7652 sched_ttwu_pending();
7653 raw_spin_lock_irqsave(&rq->lock, flags);
7655 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7659 BUG_ON(rq->nr_running != 1);
7660 raw_spin_unlock_irqrestore(&rq->lock, flags);
7661 calc_load_migrate(rq);
7662 update_max_interval();
7663 nohz_balance_exit_idle(cpu);
7665 if (per_cpu(idle_last_mm, cpu)) {
7666 mmdrop_delayed(per_cpu(idle_last_mm, cpu));
7667 per_cpu(idle_last_mm, cpu) = NULL;
7673 #ifdef CONFIG_SCHED_SMT
7674 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7676 static void sched_init_smt(void)
7679 * We've enumerated all CPUs and will assume that if any CPU
7680 * has SMT siblings, CPU0 will too.
7682 if (cpumask_weight(cpu_smt_mask(0)) > 1)
7683 static_branch_enable(&sched_smt_present);
7686 static inline void sched_init_smt(void) { }
7689 void __init sched_init_smp(void)
7691 cpumask_var_t non_isolated_cpus;
7693 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7694 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7699 * There's no userspace yet to cause hotplug operations; hence all the
7700 * cpu masks are stable and all blatant races in the below code cannot
7703 mutex_lock(&sched_domains_mutex);
7704 init_sched_domains(cpu_active_mask);
7705 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7706 if (cpumask_empty(non_isolated_cpus))
7707 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7708 mutex_unlock(&sched_domains_mutex);
7710 /* Move init over to a non-isolated CPU */
7711 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7713 sched_init_granularity();
7714 free_cpumask_var(non_isolated_cpus);
7716 init_sched_rt_class();
7717 init_sched_dl_class();
7721 sched_smp_initialized = true;
7724 static int __init migration_init(void)
7726 sched_rq_cpu_starting(smp_processor_id());
7729 early_initcall(migration_init);
7732 void __init sched_init_smp(void)
7734 sched_init_granularity();
7736 #endif /* CONFIG_SMP */
7738 int in_sched_functions(unsigned long addr)
7740 return in_lock_functions(addr) ||
7741 (addr >= (unsigned long)__sched_text_start
7742 && addr < (unsigned long)__sched_text_end);
7745 #ifdef CONFIG_CGROUP_SCHED
7747 * Default task group.
7748 * Every task in system belongs to this group at bootup.
7750 struct task_group root_task_group;
7751 LIST_HEAD(task_groups);
7753 /* Cacheline aligned slab cache for task_group */
7754 static struct kmem_cache *task_group_cache __read_mostly;
7757 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7758 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
7760 #define WAIT_TABLE_BITS 8
7761 #define WAIT_TABLE_SIZE (1 << WAIT_TABLE_BITS)
7762 static wait_queue_head_t bit_wait_table[WAIT_TABLE_SIZE] __cacheline_aligned;
7764 wait_queue_head_t *bit_waitqueue(void *word, int bit)
7766 const int shift = BITS_PER_LONG == 32 ? 5 : 6;
7767 unsigned long val = (unsigned long)word << shift | bit;
7769 return bit_wait_table + hash_long(val, WAIT_TABLE_BITS);
7771 EXPORT_SYMBOL(bit_waitqueue);
7773 void __init sched_init(void)
7776 unsigned long alloc_size = 0, ptr;
7778 for (i = 0; i < WAIT_TABLE_SIZE; i++)
7779 init_waitqueue_head(bit_wait_table + i);
7781 #ifdef CONFIG_FAIR_GROUP_SCHED
7782 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7784 #ifdef CONFIG_RT_GROUP_SCHED
7785 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7788 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7790 #ifdef CONFIG_FAIR_GROUP_SCHED
7791 root_task_group.se = (struct sched_entity **)ptr;
7792 ptr += nr_cpu_ids * sizeof(void **);
7794 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7795 ptr += nr_cpu_ids * sizeof(void **);
7797 #endif /* CONFIG_FAIR_GROUP_SCHED */
7798 #ifdef CONFIG_RT_GROUP_SCHED
7799 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7800 ptr += nr_cpu_ids * sizeof(void **);
7802 root_task_group.rt_rq = (struct rt_rq **)ptr;
7803 ptr += nr_cpu_ids * sizeof(void **);
7805 #endif /* CONFIG_RT_GROUP_SCHED */
7807 #ifdef CONFIG_CPUMASK_OFFSTACK
7808 for_each_possible_cpu(i) {
7809 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7810 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7811 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
7812 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7814 #endif /* CONFIG_CPUMASK_OFFSTACK */
7816 init_rt_bandwidth(&def_rt_bandwidth,
7817 global_rt_period(), global_rt_runtime());
7818 init_dl_bandwidth(&def_dl_bandwidth,
7819 global_rt_period(), global_rt_runtime());
7822 init_defrootdomain();
7825 #ifdef CONFIG_RT_GROUP_SCHED
7826 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7827 global_rt_period(), global_rt_runtime());
7828 #endif /* CONFIG_RT_GROUP_SCHED */
7830 #ifdef CONFIG_CGROUP_SCHED
7831 task_group_cache = KMEM_CACHE(task_group, 0);
7833 list_add(&root_task_group.list, &task_groups);
7834 INIT_LIST_HEAD(&root_task_group.children);
7835 INIT_LIST_HEAD(&root_task_group.siblings);
7836 autogroup_init(&init_task);
7837 #endif /* CONFIG_CGROUP_SCHED */
7839 for_each_possible_cpu(i) {
7843 raw_spin_lock_init(&rq->lock);
7845 rq->calc_load_active = 0;
7846 rq->calc_load_update = jiffies + LOAD_FREQ;
7847 init_cfs_rq(&rq->cfs);
7848 init_rt_rq(&rq->rt);
7849 init_dl_rq(&rq->dl);
7850 #ifdef CONFIG_FAIR_GROUP_SCHED
7851 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7852 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7854 * How much cpu bandwidth does root_task_group get?
7856 * In case of task-groups formed thr' the cgroup filesystem, it
7857 * gets 100% of the cpu resources in the system. This overall
7858 * system cpu resource is divided among the tasks of
7859 * root_task_group and its child task-groups in a fair manner,
7860 * based on each entity's (task or task-group's) weight
7861 * (se->load.weight).
7863 * In other words, if root_task_group has 10 tasks of weight
7864 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7865 * then A0's share of the cpu resource is:
7867 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7869 * We achieve this by letting root_task_group's tasks sit
7870 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7872 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7873 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7874 #endif /* CONFIG_FAIR_GROUP_SCHED */
7876 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7877 #ifdef CONFIG_RT_GROUP_SCHED
7878 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7881 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7882 rq->cpu_load[j] = 0;
7887 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7888 rq->balance_callback = NULL;
7889 rq->active_balance = 0;
7890 rq->next_balance = jiffies;
7895 rq->avg_idle = 2*sysctl_sched_migration_cost;
7896 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7898 INIT_LIST_HEAD(&rq->cfs_tasks);
7900 rq_attach_root(rq, &def_root_domain);
7901 #ifdef CONFIG_NO_HZ_COMMON
7902 rq->last_load_update_tick = jiffies;
7905 #ifdef CONFIG_NO_HZ_FULL
7906 rq->last_sched_tick = 0;
7908 #endif /* CONFIG_SMP */
7910 atomic_set(&rq->nr_iowait, 0);
7913 set_load_weight(&init_task);
7916 * The boot idle thread does lazy MMU switching as well:
7918 atomic_inc(&init_mm.mm_count);
7919 enter_lazy_tlb(&init_mm, current);
7922 * Make us the idle thread. Technically, schedule() should not be
7923 * called from this thread, however somewhere below it might be,
7924 * but because we are the idle thread, we just pick up running again
7925 * when this runqueue becomes "idle".
7927 init_idle(current, smp_processor_id());
7929 calc_load_update = jiffies + LOAD_FREQ;
7932 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7933 /* May be allocated at isolcpus cmdline parse time */
7934 if (cpu_isolated_map == NULL)
7935 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7936 idle_thread_set_boot_cpu();
7937 set_cpu_rq_start_time(smp_processor_id());
7939 init_sched_fair_class();
7943 scheduler_running = 1;
7946 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7947 static inline int preempt_count_equals(int preempt_offset)
7949 int nested = preempt_count() + sched_rcu_preempt_depth();
7951 return (nested == preempt_offset);
7954 void __might_sleep(const char *file, int line, int preempt_offset)
7957 * Blocking primitives will set (and therefore destroy) current->state,
7958 * since we will exit with TASK_RUNNING make sure we enter with it,
7959 * otherwise we will destroy state.
7961 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7962 "do not call blocking ops when !TASK_RUNNING; "
7963 "state=%lx set at [<%p>] %pS\n",
7965 (void *)current->task_state_change,
7966 (void *)current->task_state_change);
7968 ___might_sleep(file, line, preempt_offset);
7970 EXPORT_SYMBOL(__might_sleep);
7972 void ___might_sleep(const char *file, int line, int preempt_offset)
7974 static unsigned long prev_jiffy; /* ratelimiting */
7975 unsigned long preempt_disable_ip;
7977 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7978 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7979 !is_idle_task(current)) ||
7980 system_state != SYSTEM_RUNNING || oops_in_progress)
7982 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7984 prev_jiffy = jiffies;
7986 /* Save this before calling printk(), since that will clobber it */
7987 preempt_disable_ip = get_preempt_disable_ip(current);
7990 "BUG: sleeping function called from invalid context at %s:%d\n",
7993 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7994 in_atomic(), irqs_disabled(),
7995 current->pid, current->comm);
7997 if (task_stack_end_corrupted(current))
7998 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
8000 debug_show_held_locks(current);
8001 if (irqs_disabled())
8002 print_irqtrace_events(current);
8003 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
8004 && !preempt_count_equals(preempt_offset)) {
8005 pr_err("Preemption disabled at:");
8006 print_ip_sym(preempt_disable_ip);
8010 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
8012 EXPORT_SYMBOL(___might_sleep);
8015 #ifdef CONFIG_MAGIC_SYSRQ
8016 void normalize_rt_tasks(void)
8018 struct task_struct *g, *p;
8019 struct sched_attr attr = {
8020 .sched_policy = SCHED_NORMAL,
8023 read_lock(&tasklist_lock);
8024 for_each_process_thread(g, p) {
8026 * Only normalize user tasks:
8028 if (p->flags & PF_KTHREAD)
8031 p->se.exec_start = 0;
8032 schedstat_set(p->se.statistics.wait_start, 0);
8033 schedstat_set(p->se.statistics.sleep_start, 0);
8034 schedstat_set(p->se.statistics.block_start, 0);
8036 if (!dl_task(p) && !rt_task(p)) {
8038 * Renice negative nice level userspace
8041 if (task_nice(p) < 0)
8042 set_user_nice(p, 0);
8046 __sched_setscheduler(p, &attr, false, false);
8048 read_unlock(&tasklist_lock);
8051 #endif /* CONFIG_MAGIC_SYSRQ */
8053 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
8055 * These functions are only useful for the IA64 MCA handling, or kdb.
8057 * They can only be called when the whole system has been
8058 * stopped - every CPU needs to be quiescent, and no scheduling
8059 * activity can take place. Using them for anything else would
8060 * be a serious bug, and as a result, they aren't even visible
8061 * under any other configuration.
8065 * curr_task - return the current task for a given cpu.
8066 * @cpu: the processor in question.
8068 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8070 * Return: The current task for @cpu.
8072 struct task_struct *curr_task(int cpu)
8074 return cpu_curr(cpu);
8077 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8081 * set_curr_task - set the current task for a given cpu.
8082 * @cpu: the processor in question.
8083 * @p: the task pointer to set.
8085 * Description: This function must only be used when non-maskable interrupts
8086 * are serviced on a separate stack. It allows the architecture to switch the
8087 * notion of the current task on a cpu in a non-blocking manner. This function
8088 * must be called with all CPU's synchronized, and interrupts disabled, the
8089 * and caller must save the original value of the current task (see
8090 * curr_task() above) and restore that value before reenabling interrupts and
8091 * re-starting the system.
8093 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8095 void ia64_set_curr_task(int cpu, struct task_struct *p)
8102 #ifdef CONFIG_CGROUP_SCHED
8103 /* task_group_lock serializes the addition/removal of task groups */
8104 static DEFINE_SPINLOCK(task_group_lock);
8106 static void sched_free_group(struct task_group *tg)
8108 free_fair_sched_group(tg);
8109 free_rt_sched_group(tg);
8111 kmem_cache_free(task_group_cache, tg);
8114 /* allocate runqueue etc for a new task group */
8115 struct task_group *sched_create_group(struct task_group *parent)
8117 struct task_group *tg;
8119 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
8121 return ERR_PTR(-ENOMEM);
8123 if (!alloc_fair_sched_group(tg, parent))
8126 if (!alloc_rt_sched_group(tg, parent))
8132 sched_free_group(tg);
8133 return ERR_PTR(-ENOMEM);
8136 void sched_online_group(struct task_group *tg, struct task_group *parent)
8138 unsigned long flags;
8140 spin_lock_irqsave(&task_group_lock, flags);
8141 list_add_rcu(&tg->list, &task_groups);
8143 WARN_ON(!parent); /* root should already exist */
8145 tg->parent = parent;
8146 INIT_LIST_HEAD(&tg->children);
8147 list_add_rcu(&tg->siblings, &parent->children);
8148 spin_unlock_irqrestore(&task_group_lock, flags);
8150 online_fair_sched_group(tg);
8153 /* rcu callback to free various structures associated with a task group */
8154 static void sched_free_group_rcu(struct rcu_head *rhp)
8156 /* now it should be safe to free those cfs_rqs */
8157 sched_free_group(container_of(rhp, struct task_group, rcu));
8160 void sched_destroy_group(struct task_group *tg)
8162 /* wait for possible concurrent references to cfs_rqs complete */
8163 call_rcu(&tg->rcu, sched_free_group_rcu);
8166 void sched_offline_group(struct task_group *tg)
8168 unsigned long flags;
8170 /* end participation in shares distribution */
8171 unregister_fair_sched_group(tg);
8173 spin_lock_irqsave(&task_group_lock, flags);
8174 list_del_rcu(&tg->list);
8175 list_del_rcu(&tg->siblings);
8176 spin_unlock_irqrestore(&task_group_lock, flags);
8179 static void sched_change_group(struct task_struct *tsk, int type)
8181 struct task_group *tg;
8184 * All callers are synchronized by task_rq_lock(); we do not use RCU
8185 * which is pointless here. Thus, we pass "true" to task_css_check()
8186 * to prevent lockdep warnings.
8188 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8189 struct task_group, css);
8190 tg = autogroup_task_group(tsk, tg);
8191 tsk->sched_task_group = tg;
8193 #ifdef CONFIG_FAIR_GROUP_SCHED
8194 if (tsk->sched_class->task_change_group)
8195 tsk->sched_class->task_change_group(tsk, type);
8198 set_task_rq(tsk, task_cpu(tsk));
8202 * Change task's runqueue when it moves between groups.
8204 * The caller of this function should have put the task in its new group by
8205 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
8208 void sched_move_task(struct task_struct *tsk)
8210 int queued, running;
8214 rq = task_rq_lock(tsk, &rf);
8216 running = task_current(rq, tsk);
8217 queued = task_on_rq_queued(tsk);
8220 dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
8221 if (unlikely(running))
8222 put_prev_task(rq, tsk);
8224 sched_change_group(tsk, TASK_MOVE_GROUP);
8227 enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
8228 if (unlikely(running))
8229 set_curr_task(rq, tsk);
8231 task_rq_unlock(rq, tsk, &rf);
8233 #endif /* CONFIG_CGROUP_SCHED */
8235 #ifdef CONFIG_RT_GROUP_SCHED
8237 * Ensure that the real time constraints are schedulable.
8239 static DEFINE_MUTEX(rt_constraints_mutex);
8241 /* Must be called with tasklist_lock held */
8242 static inline int tg_has_rt_tasks(struct task_group *tg)
8244 struct task_struct *g, *p;
8247 * Autogroups do not have RT tasks; see autogroup_create().
8249 if (task_group_is_autogroup(tg))
8252 for_each_process_thread(g, p) {
8253 if (rt_task(p) && task_group(p) == tg)
8260 struct rt_schedulable_data {
8261 struct task_group *tg;
8266 static int tg_rt_schedulable(struct task_group *tg, void *data)
8268 struct rt_schedulable_data *d = data;
8269 struct task_group *child;
8270 unsigned long total, sum = 0;
8271 u64 period, runtime;
8273 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8274 runtime = tg->rt_bandwidth.rt_runtime;
8277 period = d->rt_period;
8278 runtime = d->rt_runtime;
8282 * Cannot have more runtime than the period.
8284 if (runtime > period && runtime != RUNTIME_INF)
8288 * Ensure we don't starve existing RT tasks.
8290 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8293 total = to_ratio(period, runtime);
8296 * Nobody can have more than the global setting allows.
8298 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8302 * The sum of our children's runtime should not exceed our own.
8304 list_for_each_entry_rcu(child, &tg->children, siblings) {
8305 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8306 runtime = child->rt_bandwidth.rt_runtime;
8308 if (child == d->tg) {
8309 period = d->rt_period;
8310 runtime = d->rt_runtime;
8313 sum += to_ratio(period, runtime);
8322 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8326 struct rt_schedulable_data data = {
8328 .rt_period = period,
8329 .rt_runtime = runtime,
8333 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
8339 static int tg_set_rt_bandwidth(struct task_group *tg,
8340 u64 rt_period, u64 rt_runtime)
8345 * Disallowing the root group RT runtime is BAD, it would disallow the
8346 * kernel creating (and or operating) RT threads.
8348 if (tg == &root_task_group && rt_runtime == 0)
8351 /* No period doesn't make any sense. */
8355 mutex_lock(&rt_constraints_mutex);
8356 read_lock(&tasklist_lock);
8357 err = __rt_schedulable(tg, rt_period, rt_runtime);
8361 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8362 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8363 tg->rt_bandwidth.rt_runtime = rt_runtime;
8365 for_each_possible_cpu(i) {
8366 struct rt_rq *rt_rq = tg->rt_rq[i];
8368 raw_spin_lock(&rt_rq->rt_runtime_lock);
8369 rt_rq->rt_runtime = rt_runtime;
8370 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8372 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8374 read_unlock(&tasklist_lock);
8375 mutex_unlock(&rt_constraints_mutex);
8380 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8382 u64 rt_runtime, rt_period;
8384 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8385 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8386 if (rt_runtime_us < 0)
8387 rt_runtime = RUNTIME_INF;
8389 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8392 static long sched_group_rt_runtime(struct task_group *tg)
8396 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8399 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8400 do_div(rt_runtime_us, NSEC_PER_USEC);
8401 return rt_runtime_us;
8404 static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
8406 u64 rt_runtime, rt_period;
8408 rt_period = rt_period_us * NSEC_PER_USEC;
8409 rt_runtime = tg->rt_bandwidth.rt_runtime;
8411 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
8414 static long sched_group_rt_period(struct task_group *tg)
8418 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8419 do_div(rt_period_us, NSEC_PER_USEC);
8420 return rt_period_us;
8422 #endif /* CONFIG_RT_GROUP_SCHED */
8424 #ifdef CONFIG_RT_GROUP_SCHED
8425 static int sched_rt_global_constraints(void)
8429 mutex_lock(&rt_constraints_mutex);
8430 read_lock(&tasklist_lock);
8431 ret = __rt_schedulable(NULL, 0, 0);
8432 read_unlock(&tasklist_lock);
8433 mutex_unlock(&rt_constraints_mutex);
8438 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8440 /* Don't accept realtime tasks when there is no way for them to run */
8441 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8447 #else /* !CONFIG_RT_GROUP_SCHED */
8448 static int sched_rt_global_constraints(void)
8450 unsigned long flags;
8453 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8454 for_each_possible_cpu(i) {
8455 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8457 raw_spin_lock(&rt_rq->rt_runtime_lock);
8458 rt_rq->rt_runtime = global_rt_runtime();
8459 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8461 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8465 #endif /* CONFIG_RT_GROUP_SCHED */
8467 static int sched_dl_global_validate(void)
8469 u64 runtime = global_rt_runtime();
8470 u64 period = global_rt_period();
8471 u64 new_bw = to_ratio(period, runtime);
8474 unsigned long flags;
8477 * Here we want to check the bandwidth not being set to some
8478 * value smaller than the currently allocated bandwidth in
8479 * any of the root_domains.
8481 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
8482 * cycling on root_domains... Discussion on different/better
8483 * solutions is welcome!
8485 for_each_possible_cpu(cpu) {
8486 rcu_read_lock_sched();
8487 dl_b = dl_bw_of(cpu);
8489 raw_spin_lock_irqsave(&dl_b->lock, flags);
8490 if (new_bw < dl_b->total_bw)
8492 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8494 rcu_read_unlock_sched();
8503 static void sched_dl_do_global(void)
8508 unsigned long flags;
8510 def_dl_bandwidth.dl_period = global_rt_period();
8511 def_dl_bandwidth.dl_runtime = global_rt_runtime();
8513 if (global_rt_runtime() != RUNTIME_INF)
8514 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
8517 * FIXME: As above...
8519 for_each_possible_cpu(cpu) {
8520 rcu_read_lock_sched();
8521 dl_b = dl_bw_of(cpu);
8523 raw_spin_lock_irqsave(&dl_b->lock, flags);
8525 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
8527 rcu_read_unlock_sched();
8531 static int sched_rt_global_validate(void)
8533 if (sysctl_sched_rt_period <= 0)
8536 if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
8537 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
8543 static void sched_rt_do_global(void)
8545 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8546 def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
8549 int sched_rt_handler(struct ctl_table *table, int write,
8550 void __user *buffer, size_t *lenp,
8553 int old_period, old_runtime;
8554 static DEFINE_MUTEX(mutex);
8558 old_period = sysctl_sched_rt_period;
8559 old_runtime = sysctl_sched_rt_runtime;
8561 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8563 if (!ret && write) {
8564 ret = sched_rt_global_validate();
8568 ret = sched_dl_global_validate();
8572 ret = sched_rt_global_constraints();
8576 sched_rt_do_global();
8577 sched_dl_do_global();
8581 sysctl_sched_rt_period = old_period;
8582 sysctl_sched_rt_runtime = old_runtime;
8584 mutex_unlock(&mutex);
8589 int sched_rr_handler(struct ctl_table *table, int write,
8590 void __user *buffer, size_t *lenp,
8594 static DEFINE_MUTEX(mutex);
8597 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8598 /* make sure that internally we keep jiffies */
8599 /* also, writing zero resets timeslice to default */
8600 if (!ret && write) {
8601 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
8602 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
8604 mutex_unlock(&mutex);
8608 #ifdef CONFIG_CGROUP_SCHED
8610 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8612 return css ? container_of(css, struct task_group, css) : NULL;
8615 static struct cgroup_subsys_state *
8616 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8618 struct task_group *parent = css_tg(parent_css);
8619 struct task_group *tg;
8622 /* This is early initialization for the top cgroup */
8623 return &root_task_group.css;
8626 tg = sched_create_group(parent);
8628 return ERR_PTR(-ENOMEM);
8630 sched_online_group(tg, parent);
8635 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
8637 struct task_group *tg = css_tg(css);
8639 sched_offline_group(tg);
8642 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8644 struct task_group *tg = css_tg(css);
8647 * Relies on the RCU grace period between css_released() and this.
8649 sched_free_group(tg);
8653 * This is called before wake_up_new_task(), therefore we really only
8654 * have to set its group bits, all the other stuff does not apply.
8656 static void cpu_cgroup_fork(struct task_struct *task)
8661 rq = task_rq_lock(task, &rf);
8663 sched_change_group(task, TASK_SET_GROUP);
8665 task_rq_unlock(rq, task, &rf);
8668 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
8670 struct task_struct *task;
8671 struct cgroup_subsys_state *css;
8674 cgroup_taskset_for_each(task, css, tset) {
8675 #ifdef CONFIG_RT_GROUP_SCHED
8676 if (!sched_rt_can_attach(css_tg(css), task))
8679 /* We don't support RT-tasks being in separate groups */
8680 if (task->sched_class != &fair_sched_class)
8684 * Serialize against wake_up_new_task() such that if its
8685 * running, we're sure to observe its full state.
8687 raw_spin_lock_irq(&task->pi_lock);
8689 * Avoid calling sched_move_task() before wake_up_new_task()
8690 * has happened. This would lead to problems with PELT, due to
8691 * move wanting to detach+attach while we're not attached yet.
8693 if (task->state == TASK_NEW)
8695 raw_spin_unlock_irq(&task->pi_lock);
8703 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
8705 struct task_struct *task;
8706 struct cgroup_subsys_state *css;
8708 cgroup_taskset_for_each(task, css, tset)
8709 sched_move_task(task);
8712 #ifdef CONFIG_FAIR_GROUP_SCHED
8713 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8714 struct cftype *cftype, u64 shareval)
8716 return sched_group_set_shares(css_tg(css), scale_load(shareval));
8719 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8722 struct task_group *tg = css_tg(css);
8724 return (u64) scale_load_down(tg->shares);
8727 #ifdef CONFIG_CFS_BANDWIDTH
8728 static DEFINE_MUTEX(cfs_constraints_mutex);
8730 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8731 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8733 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8735 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8737 int i, ret = 0, runtime_enabled, runtime_was_enabled;
8738 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8740 if (tg == &root_task_group)
8744 * Ensure we have at some amount of bandwidth every period. This is
8745 * to prevent reaching a state of large arrears when throttled via
8746 * entity_tick() resulting in prolonged exit starvation.
8748 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8752 * Likewise, bound things on the otherside by preventing insane quota
8753 * periods. This also allows us to normalize in computing quota
8756 if (period > max_cfs_quota_period)
8760 * Prevent race between setting of cfs_rq->runtime_enabled and
8761 * unthrottle_offline_cfs_rqs().
8764 mutex_lock(&cfs_constraints_mutex);
8765 ret = __cfs_schedulable(tg, period, quota);
8769 runtime_enabled = quota != RUNTIME_INF;
8770 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8772 * If we need to toggle cfs_bandwidth_used, off->on must occur
8773 * before making related changes, and on->off must occur afterwards
8775 if (runtime_enabled && !runtime_was_enabled)
8776 cfs_bandwidth_usage_inc();
8777 raw_spin_lock_irq(&cfs_b->lock);
8778 cfs_b->period = ns_to_ktime(period);
8779 cfs_b->quota = quota;
8781 __refill_cfs_bandwidth_runtime(cfs_b);
8782 /* restart the period timer (if active) to handle new period expiry */
8783 if (runtime_enabled)
8784 start_cfs_bandwidth(cfs_b);
8785 raw_spin_unlock_irq(&cfs_b->lock);
8787 for_each_online_cpu(i) {
8788 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8789 struct rq *rq = cfs_rq->rq;
8791 raw_spin_lock_irq(&rq->lock);
8792 cfs_rq->runtime_enabled = runtime_enabled;
8793 cfs_rq->runtime_remaining = 0;
8795 if (cfs_rq->throttled)
8796 unthrottle_cfs_rq(cfs_rq);
8797 raw_spin_unlock_irq(&rq->lock);
8799 if (runtime_was_enabled && !runtime_enabled)
8800 cfs_bandwidth_usage_dec();
8802 mutex_unlock(&cfs_constraints_mutex);
8808 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8812 period = ktime_to_ns(tg->cfs_bandwidth.period);
8813 if (cfs_quota_us < 0)
8814 quota = RUNTIME_INF;
8816 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8818 return tg_set_cfs_bandwidth(tg, period, quota);
8821 long tg_get_cfs_quota(struct task_group *tg)
8825 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8828 quota_us = tg->cfs_bandwidth.quota;
8829 do_div(quota_us, NSEC_PER_USEC);
8834 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8838 period = (u64)cfs_period_us * NSEC_PER_USEC;
8839 quota = tg->cfs_bandwidth.quota;
8841 return tg_set_cfs_bandwidth(tg, period, quota);
8844 long tg_get_cfs_period(struct task_group *tg)
8848 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8849 do_div(cfs_period_us, NSEC_PER_USEC);
8851 return cfs_period_us;
8854 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8857 return tg_get_cfs_quota(css_tg(css));
8860 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8861 struct cftype *cftype, s64 cfs_quota_us)
8863 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8866 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8869 return tg_get_cfs_period(css_tg(css));
8872 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8873 struct cftype *cftype, u64 cfs_period_us)
8875 return tg_set_cfs_period(css_tg(css), cfs_period_us);
8878 struct cfs_schedulable_data {
8879 struct task_group *tg;
8884 * normalize group quota/period to be quota/max_period
8885 * note: units are usecs
8887 static u64 normalize_cfs_quota(struct task_group *tg,
8888 struct cfs_schedulable_data *d)
8896 period = tg_get_cfs_period(tg);
8897 quota = tg_get_cfs_quota(tg);
8900 /* note: these should typically be equivalent */
8901 if (quota == RUNTIME_INF || quota == -1)
8904 return to_ratio(period, quota);
8907 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8909 struct cfs_schedulable_data *d = data;
8910 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8911 s64 quota = 0, parent_quota = -1;
8914 quota = RUNTIME_INF;
8916 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8918 quota = normalize_cfs_quota(tg, d);
8919 parent_quota = parent_b->hierarchical_quota;
8922 * ensure max(child_quota) <= parent_quota, inherit when no
8925 if (quota == RUNTIME_INF)
8926 quota = parent_quota;
8927 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8930 cfs_b->hierarchical_quota = quota;
8935 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8938 struct cfs_schedulable_data data = {
8944 if (quota != RUNTIME_INF) {
8945 do_div(data.period, NSEC_PER_USEC);
8946 do_div(data.quota, NSEC_PER_USEC);
8950 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8956 static int cpu_stats_show(struct seq_file *sf, void *v)
8958 struct task_group *tg = css_tg(seq_css(sf));
8959 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8961 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8962 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8963 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8967 #endif /* CONFIG_CFS_BANDWIDTH */
8968 #endif /* CONFIG_FAIR_GROUP_SCHED */
8970 #ifdef CONFIG_RT_GROUP_SCHED
8971 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8972 struct cftype *cft, s64 val)
8974 return sched_group_set_rt_runtime(css_tg(css), val);
8977 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8980 return sched_group_rt_runtime(css_tg(css));
8983 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8984 struct cftype *cftype, u64 rt_period_us)
8986 return sched_group_set_rt_period(css_tg(css), rt_period_us);
8989 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8992 return sched_group_rt_period(css_tg(css));
8994 #endif /* CONFIG_RT_GROUP_SCHED */
8996 static struct cftype cpu_files[] = {
8997 #ifdef CONFIG_FAIR_GROUP_SCHED
9000 .read_u64 = cpu_shares_read_u64,
9001 .write_u64 = cpu_shares_write_u64,
9004 #ifdef CONFIG_CFS_BANDWIDTH
9006 .name = "cfs_quota_us",
9007 .read_s64 = cpu_cfs_quota_read_s64,
9008 .write_s64 = cpu_cfs_quota_write_s64,
9011 .name = "cfs_period_us",
9012 .read_u64 = cpu_cfs_period_read_u64,
9013 .write_u64 = cpu_cfs_period_write_u64,
9017 .seq_show = cpu_stats_show,
9020 #ifdef CONFIG_RT_GROUP_SCHED
9022 .name = "rt_runtime_us",
9023 .read_s64 = cpu_rt_runtime_read,
9024 .write_s64 = cpu_rt_runtime_write,
9027 .name = "rt_period_us",
9028 .read_u64 = cpu_rt_period_read_uint,
9029 .write_u64 = cpu_rt_period_write_uint,
9035 struct cgroup_subsys cpu_cgrp_subsys = {
9036 .css_alloc = cpu_cgroup_css_alloc,
9037 .css_released = cpu_cgroup_css_released,
9038 .css_free = cpu_cgroup_css_free,
9039 .fork = cpu_cgroup_fork,
9040 .can_attach = cpu_cgroup_can_attach,
9041 .attach = cpu_cgroup_attach,
9042 .legacy_cftypes = cpu_files,
9046 #endif /* CONFIG_CGROUP_SCHED */
9048 void dump_cpu_task(int cpu)
9050 pr_info("Task dump for CPU %d:\n", cpu);
9051 sched_show_task(cpu_curr(cpu));
9055 * Nice levels are multiplicative, with a gentle 10% change for every
9056 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
9057 * nice 1, it will get ~10% less CPU time than another CPU-bound task
9058 * that remained on nice 0.
9060 * The "10% effect" is relative and cumulative: from _any_ nice level,
9061 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
9062 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
9063 * If a task goes up by ~10% and another task goes down by ~10% then
9064 * the relative distance between them is ~25%.)
9066 const int sched_prio_to_weight[40] = {
9067 /* -20 */ 88761, 71755, 56483, 46273, 36291,
9068 /* -15 */ 29154, 23254, 18705, 14949, 11916,
9069 /* -10 */ 9548, 7620, 6100, 4904, 3906,
9070 /* -5 */ 3121, 2501, 1991, 1586, 1277,
9071 /* 0 */ 1024, 820, 655, 526, 423,
9072 /* 5 */ 335, 272, 215, 172, 137,
9073 /* 10 */ 110, 87, 70, 56, 45,
9074 /* 15 */ 36, 29, 23, 18, 15,
9078 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
9080 * In cases where the weight does not change often, we can use the
9081 * precalculated inverse to speed up arithmetics by turning divisions
9082 * into multiplications:
9084 const u32 sched_prio_to_wmult[40] = {
9085 /* -20 */ 48388, 59856, 76040, 92818, 118348,
9086 /* -15 */ 147320, 184698, 229616, 287308, 360437,
9087 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
9088 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
9089 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
9090 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
9091 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
9092 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,