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
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <asm/mmu_context.h>
36 #include <linux/interrupt.h>
37 #include <linux/capability.h>
38 #include <linux/completion.h>
39 #include <linux/kernel_stat.h>
40 #include <linux/debug_locks.h>
41 #include <linux/perf_event.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/proc_fs.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/unistd.h>
66 #include <linux/pagemap.h>
67 #include <linux/hrtimer.h>
68 #include <linux/tick.h>
69 #include <linux/debugfs.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/binfmts.h>
75 #include <linux/context_tracking.h>
76 #include <linux/compiler.h>
78 #include <asm/switch_to.h>
80 #include <asm/irq_regs.h>
81 #include <asm/mutex.h>
82 #ifdef CONFIG_PARAVIRT
83 #include <asm/paravirt.h>
87 #include "../workqueue_internal.h"
88 #include "../smpboot.h"
90 #define CREATE_TRACE_POINTS
91 #include <trace/events/sched.h>
93 DEFINE_MUTEX(sched_domains_mutex
);
94 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
96 static void update_rq_clock_task(struct rq
*rq
, s64 delta
);
98 void update_rq_clock(struct rq
*rq
)
102 lockdep_assert_held(&rq
->lock
);
104 if (rq
->clock_skip_update
& RQCF_ACT_SKIP
)
107 delta
= sched_clock_cpu(cpu_of(rq
)) - rq
->clock
;
111 update_rq_clock_task(rq
, delta
);
115 * Debugging: various feature bits
118 #define SCHED_FEAT(name, enabled) \
119 (1UL << __SCHED_FEAT_##name) * enabled |
121 const_debug
unsigned int sysctl_sched_features
=
122 #include "features.h"
127 #ifdef CONFIG_SCHED_DEBUG
128 #define SCHED_FEAT(name, enabled) \
131 static const char * const sched_feat_names
[] = {
132 #include "features.h"
137 static int sched_feat_show(struct seq_file
*m
, void *v
)
141 for (i
= 0; i
< __SCHED_FEAT_NR
; i
++) {
142 if (!(sysctl_sched_features
& (1UL << i
)))
144 seq_printf(m
, "%s ", sched_feat_names
[i
]);
151 #ifdef HAVE_JUMP_LABEL
153 #define jump_label_key__true STATIC_KEY_INIT_TRUE
154 #define jump_label_key__false STATIC_KEY_INIT_FALSE
156 #define SCHED_FEAT(name, enabled) \
157 jump_label_key__##enabled ,
159 struct static_key sched_feat_keys
[__SCHED_FEAT_NR
] = {
160 #include "features.h"
165 static void sched_feat_disable(int i
)
167 static_key_disable(&sched_feat_keys
[i
]);
170 static void sched_feat_enable(int i
)
172 static_key_enable(&sched_feat_keys
[i
]);
175 static void sched_feat_disable(int i
) { };
176 static void sched_feat_enable(int i
) { };
177 #endif /* HAVE_JUMP_LABEL */
179 static int sched_feat_set(char *cmp
)
184 if (strncmp(cmp
, "NO_", 3) == 0) {
189 for (i
= 0; i
< __SCHED_FEAT_NR
; i
++) {
190 if (strcmp(cmp
, sched_feat_names
[i
]) == 0) {
192 sysctl_sched_features
&= ~(1UL << i
);
193 sched_feat_disable(i
);
195 sysctl_sched_features
|= (1UL << i
);
196 sched_feat_enable(i
);
206 sched_feat_write(struct file
*filp
, const char __user
*ubuf
,
207 size_t cnt
, loff_t
*ppos
)
217 if (copy_from_user(&buf
, ubuf
, cnt
))
223 /* Ensure the static_key remains in a consistent state */
224 inode
= file_inode(filp
);
226 i
= sched_feat_set(cmp
);
228 if (i
== __SCHED_FEAT_NR
)
236 static int sched_feat_open(struct inode
*inode
, struct file
*filp
)
238 return single_open(filp
, sched_feat_show
, NULL
);
241 static const struct file_operations sched_feat_fops
= {
242 .open
= sched_feat_open
,
243 .write
= sched_feat_write
,
246 .release
= single_release
,
249 static __init
int sched_init_debug(void)
251 debugfs_create_file("sched_features", 0644, NULL
, NULL
,
256 late_initcall(sched_init_debug
);
257 #endif /* CONFIG_SCHED_DEBUG */
260 * Number of tasks to iterate in a single balance run.
261 * Limited because this is done with IRQs disabled.
263 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
266 * period over which we average the RT time consumption, measured
271 const_debug
unsigned int sysctl_sched_time_avg
= MSEC_PER_SEC
;
274 * period over which we measure -rt task cpu usage in us.
277 unsigned int sysctl_sched_rt_period
= 1000000;
279 __read_mostly
int scheduler_running
;
282 * part of the period that we allow rt tasks to run in us.
285 int sysctl_sched_rt_runtime
= 950000;
287 /* cpus with isolated domains */
288 cpumask_var_t cpu_isolated_map
;
291 * this_rq_lock - lock this runqueue and disable interrupts.
293 static struct rq
*this_rq_lock(void)
300 raw_spin_lock(&rq
->lock
);
305 #ifdef CONFIG_SCHED_HRTICK
307 * Use HR-timers to deliver accurate preemption points.
310 static void hrtick_clear(struct rq
*rq
)
312 if (hrtimer_active(&rq
->hrtick_timer
))
313 hrtimer_cancel(&rq
->hrtick_timer
);
317 * High-resolution timer tick.
318 * Runs from hardirq context with interrupts disabled.
320 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
322 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
324 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
326 raw_spin_lock(&rq
->lock
);
328 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
329 raw_spin_unlock(&rq
->lock
);
331 return HRTIMER_NORESTART
;
336 static void __hrtick_restart(struct rq
*rq
)
338 struct hrtimer
*timer
= &rq
->hrtick_timer
;
340 hrtimer_start_expires(timer
, HRTIMER_MODE_ABS_PINNED
);
344 * called from hardirq (IPI) context
346 static void __hrtick_start(void *arg
)
350 raw_spin_lock(&rq
->lock
);
351 __hrtick_restart(rq
);
352 rq
->hrtick_csd_pending
= 0;
353 raw_spin_unlock(&rq
->lock
);
357 * Called to set the hrtick timer state.
359 * called with rq->lock held and irqs disabled
361 void hrtick_start(struct rq
*rq
, u64 delay
)
363 struct hrtimer
*timer
= &rq
->hrtick_timer
;
368 * Don't schedule slices shorter than 10000ns, that just
369 * doesn't make sense and can cause timer DoS.
371 delta
= max_t(s64
, delay
, 10000LL);
372 time
= ktime_add_ns(timer
->base
->get_time(), delta
);
374 hrtimer_set_expires(timer
, time
);
376 if (rq
== this_rq()) {
377 __hrtick_restart(rq
);
378 } else if (!rq
->hrtick_csd_pending
) {
379 smp_call_function_single_async(cpu_of(rq
), &rq
->hrtick_csd
);
380 rq
->hrtick_csd_pending
= 1;
385 hotplug_hrtick(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
387 int cpu
= (int)(long)hcpu
;
390 case CPU_UP_CANCELED
:
391 case CPU_UP_CANCELED_FROZEN
:
392 case CPU_DOWN_PREPARE
:
393 case CPU_DOWN_PREPARE_FROZEN
:
395 case CPU_DEAD_FROZEN
:
396 hrtick_clear(cpu_rq(cpu
));
403 static __init
void init_hrtick(void)
405 hotcpu_notifier(hotplug_hrtick
, 0);
409 * Called to set the hrtick timer state.
411 * called with rq->lock held and irqs disabled
413 void hrtick_start(struct rq
*rq
, u64 delay
)
416 * Don't schedule slices shorter than 10000ns, that just
417 * doesn't make sense. Rely on vruntime for fairness.
419 delay
= max_t(u64
, delay
, 10000LL);
420 hrtimer_start(&rq
->hrtick_timer
, ns_to_ktime(delay
),
421 HRTIMER_MODE_REL_PINNED
);
424 static inline void init_hrtick(void)
427 #endif /* CONFIG_SMP */
429 static void init_rq_hrtick(struct rq
*rq
)
432 rq
->hrtick_csd_pending
= 0;
434 rq
->hrtick_csd
.flags
= 0;
435 rq
->hrtick_csd
.func
= __hrtick_start
;
436 rq
->hrtick_csd
.info
= rq
;
439 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
440 rq
->hrtick_timer
.function
= hrtick
;
442 #else /* CONFIG_SCHED_HRTICK */
443 static inline void hrtick_clear(struct rq
*rq
)
447 static inline void init_rq_hrtick(struct rq
*rq
)
451 static inline void init_hrtick(void)
454 #endif /* CONFIG_SCHED_HRTICK */
457 * cmpxchg based fetch_or, macro so it works for different integer types
459 #define fetch_or(ptr, val) \
460 ({ typeof(*(ptr)) __old, __val = *(ptr); \
462 __old = cmpxchg((ptr), __val, __val | (val)); \
463 if (__old == __val) \
470 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
472 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
473 * this avoids any races wrt polling state changes and thereby avoids
476 static bool set_nr_and_not_polling(struct task_struct
*p
)
478 struct thread_info
*ti
= task_thread_info(p
);
479 return !(fetch_or(&ti
->flags
, _TIF_NEED_RESCHED
) & _TIF_POLLING_NRFLAG
);
483 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
485 * If this returns true, then the idle task promises to call
486 * sched_ttwu_pending() and reschedule soon.
488 static bool set_nr_if_polling(struct task_struct
*p
)
490 struct thread_info
*ti
= task_thread_info(p
);
491 typeof(ti
->flags
) old
, val
= READ_ONCE(ti
->flags
);
494 if (!(val
& _TIF_POLLING_NRFLAG
))
496 if (val
& _TIF_NEED_RESCHED
)
498 old
= cmpxchg(&ti
->flags
, val
, val
| _TIF_NEED_RESCHED
);
507 static bool set_nr_and_not_polling(struct task_struct
*p
)
509 set_tsk_need_resched(p
);
514 static bool set_nr_if_polling(struct task_struct
*p
)
521 void wake_q_add(struct wake_q_head
*head
, struct task_struct
*task
)
523 struct wake_q_node
*node
= &task
->wake_q
;
526 * Atomically grab the task, if ->wake_q is !nil already it means
527 * its already queued (either by us or someone else) and will get the
528 * wakeup due to that.
530 * This cmpxchg() implies a full barrier, which pairs with the write
531 * barrier implied by the wakeup in wake_up_list().
533 if (cmpxchg(&node
->next
, NULL
, WAKE_Q_TAIL
))
536 get_task_struct(task
);
539 * The head is context local, there can be no concurrency.
542 head
->lastp
= &node
->next
;
545 void wake_up_q(struct wake_q_head
*head
)
547 struct wake_q_node
*node
= head
->first
;
549 while (node
!= WAKE_Q_TAIL
) {
550 struct task_struct
*task
;
552 task
= container_of(node
, struct task_struct
, wake_q
);
554 /* task can safely be re-inserted now */
556 task
->wake_q
.next
= NULL
;
559 * wake_up_process() implies a wmb() to pair with the queueing
560 * in wake_q_add() so as not to miss wakeups.
562 wake_up_process(task
);
563 put_task_struct(task
);
568 * resched_curr - mark rq's current task 'to be rescheduled now'.
570 * On UP this means the setting of the need_resched flag, on SMP it
571 * might also involve a cross-CPU call to trigger the scheduler on
574 void resched_curr(struct rq
*rq
)
576 struct task_struct
*curr
= rq
->curr
;
579 lockdep_assert_held(&rq
->lock
);
581 if (test_tsk_need_resched(curr
))
586 if (cpu
== smp_processor_id()) {
587 set_tsk_need_resched(curr
);
588 set_preempt_need_resched();
592 if (set_nr_and_not_polling(curr
))
593 smp_send_reschedule(cpu
);
595 trace_sched_wake_idle_without_ipi(cpu
);
598 void resched_cpu(int cpu
)
600 struct rq
*rq
= cpu_rq(cpu
);
603 if (!raw_spin_trylock_irqsave(&rq
->lock
, flags
))
606 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
610 #ifdef CONFIG_NO_HZ_COMMON
612 * In the semi idle case, use the nearest busy cpu for migrating timers
613 * from an idle cpu. This is good for power-savings.
615 * We don't do similar optimization for completely idle system, as
616 * selecting an idle cpu will add more delays to the timers than intended
617 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
619 int get_nohz_timer_target(void)
621 int i
, cpu
= smp_processor_id();
622 struct sched_domain
*sd
;
624 if (!idle_cpu(cpu
) && is_housekeeping_cpu(cpu
))
628 for_each_domain(cpu
, sd
) {
629 for_each_cpu(i
, sched_domain_span(sd
)) {
630 if (!idle_cpu(i
) && is_housekeeping_cpu(cpu
)) {
637 if (!is_housekeeping_cpu(cpu
))
638 cpu
= housekeeping_any_cpu();
644 * When add_timer_on() enqueues a timer into the timer wheel of an
645 * idle CPU then this timer might expire before the next timer event
646 * which is scheduled to wake up that CPU. In case of a completely
647 * idle system the next event might even be infinite time into the
648 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
649 * leaves the inner idle loop so the newly added timer is taken into
650 * account when the CPU goes back to idle and evaluates the timer
651 * wheel for the next timer event.
653 static void wake_up_idle_cpu(int cpu
)
655 struct rq
*rq
= cpu_rq(cpu
);
657 if (cpu
== smp_processor_id())
660 if (set_nr_and_not_polling(rq
->idle
))
661 smp_send_reschedule(cpu
);
663 trace_sched_wake_idle_without_ipi(cpu
);
666 static bool wake_up_full_nohz_cpu(int cpu
)
669 * We just need the target to call irq_exit() and re-evaluate
670 * the next tick. The nohz full kick at least implies that.
671 * If needed we can still optimize that later with an
674 if (tick_nohz_full_cpu(cpu
)) {
675 if (cpu
!= smp_processor_id() ||
676 tick_nohz_tick_stopped())
677 tick_nohz_full_kick_cpu(cpu
);
684 void wake_up_nohz_cpu(int cpu
)
686 if (!wake_up_full_nohz_cpu(cpu
))
687 wake_up_idle_cpu(cpu
);
690 static inline bool got_nohz_idle_kick(void)
692 int cpu
= smp_processor_id();
694 if (!test_bit(NOHZ_BALANCE_KICK
, nohz_flags(cpu
)))
697 if (idle_cpu(cpu
) && !need_resched())
701 * We can't run Idle Load Balance on this CPU for this time so we
702 * cancel it and clear NOHZ_BALANCE_KICK
704 clear_bit(NOHZ_BALANCE_KICK
, nohz_flags(cpu
));
708 #else /* CONFIG_NO_HZ_COMMON */
710 static inline bool got_nohz_idle_kick(void)
715 #endif /* CONFIG_NO_HZ_COMMON */
717 #ifdef CONFIG_NO_HZ_FULL
718 bool sched_can_stop_tick(void)
721 * FIFO realtime policy runs the highest priority task. Other runnable
722 * tasks are of a lower priority. The scheduler tick does nothing.
724 if (current
->policy
== SCHED_FIFO
)
728 * Round-robin realtime tasks time slice with other tasks at the same
729 * realtime priority. Is this task the only one at this priority?
731 if (current
->policy
== SCHED_RR
) {
732 struct sched_rt_entity
*rt_se
= ¤t
->rt
;
734 return list_is_singular(&rt_se
->run_list
);
738 * More than one running task need preemption.
739 * nr_running update is assumed to be visible
740 * after IPI is sent from wakers.
742 if (this_rq()->nr_running
> 1)
747 #endif /* CONFIG_NO_HZ_FULL */
749 void sched_avg_update(struct rq
*rq
)
751 s64 period
= sched_avg_period();
753 while ((s64
)(rq_clock(rq
) - rq
->age_stamp
) > period
) {
755 * Inline assembly required to prevent the compiler
756 * optimising this loop into a divmod call.
757 * See __iter_div_u64_rem() for another example of this.
759 asm("" : "+rm" (rq
->age_stamp
));
760 rq
->age_stamp
+= period
;
765 #endif /* CONFIG_SMP */
767 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
768 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
770 * Iterate task_group tree rooted at *from, calling @down when first entering a
771 * node and @up when leaving it for the final time.
773 * Caller must hold rcu_lock or sufficient equivalent.
775 int walk_tg_tree_from(struct task_group
*from
,
776 tg_visitor down
, tg_visitor up
, void *data
)
778 struct task_group
*parent
, *child
;
784 ret
= (*down
)(parent
, data
);
787 list_for_each_entry_rcu(child
, &parent
->children
, siblings
) {
794 ret
= (*up
)(parent
, data
);
795 if (ret
|| parent
== from
)
799 parent
= parent
->parent
;
806 int tg_nop(struct task_group
*tg
, void *data
)
812 static void set_load_weight(struct task_struct
*p
)
814 int prio
= p
->static_prio
- MAX_RT_PRIO
;
815 struct load_weight
*load
= &p
->se
.load
;
818 * SCHED_IDLE tasks get minimal weight:
820 if (idle_policy(p
->policy
)) {
821 load
->weight
= scale_load(WEIGHT_IDLEPRIO
);
822 load
->inv_weight
= WMULT_IDLEPRIO
;
826 load
->weight
= scale_load(sched_prio_to_weight
[prio
]);
827 load
->inv_weight
= sched_prio_to_wmult
[prio
];
830 static inline void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
833 if (!(flags
& ENQUEUE_RESTORE
))
834 sched_info_queued(rq
, p
);
835 p
->sched_class
->enqueue_task(rq
, p
, flags
);
838 static inline void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
841 if (!(flags
& DEQUEUE_SAVE
))
842 sched_info_dequeued(rq
, p
);
843 p
->sched_class
->dequeue_task(rq
, p
, flags
);
846 void activate_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
848 if (task_contributes_to_load(p
))
849 rq
->nr_uninterruptible
--;
851 enqueue_task(rq
, p
, flags
);
854 void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int flags
)
856 if (task_contributes_to_load(p
))
857 rq
->nr_uninterruptible
++;
859 dequeue_task(rq
, p
, flags
);
862 static void update_rq_clock_task(struct rq
*rq
, s64 delta
)
865 * In theory, the compile should just see 0 here, and optimize out the call
866 * to sched_rt_avg_update. But I don't trust it...
868 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
869 s64 steal
= 0, irq_delta
= 0;
871 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
872 irq_delta
= irq_time_read(cpu_of(rq
)) - rq
->prev_irq_time
;
875 * Since irq_time is only updated on {soft,}irq_exit, we might run into
876 * this case when a previous update_rq_clock() happened inside a
879 * When this happens, we stop ->clock_task and only update the
880 * prev_irq_time stamp to account for the part that fit, so that a next
881 * update will consume the rest. This ensures ->clock_task is
884 * It does however cause some slight miss-attribution of {soft,}irq
885 * time, a more accurate solution would be to update the irq_time using
886 * the current rq->clock timestamp, except that would require using
889 if (irq_delta
> delta
)
892 rq
->prev_irq_time
+= irq_delta
;
895 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
896 if (static_key_false((¶virt_steal_rq_enabled
))) {
897 steal
= paravirt_steal_clock(cpu_of(rq
));
898 steal
-= rq
->prev_steal_time_rq
;
900 if (unlikely(steal
> delta
))
903 rq
->prev_steal_time_rq
+= steal
;
908 rq
->clock_task
+= delta
;
910 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
911 if ((irq_delta
+ steal
) && sched_feat(NONTASK_CAPACITY
))
912 sched_rt_avg_update(rq
, irq_delta
+ steal
);
916 void sched_set_stop_task(int cpu
, struct task_struct
*stop
)
918 struct sched_param param
= { .sched_priority
= MAX_RT_PRIO
- 1 };
919 struct task_struct
*old_stop
= cpu_rq(cpu
)->stop
;
923 * Make it appear like a SCHED_FIFO task, its something
924 * userspace knows about and won't get confused about.
926 * Also, it will make PI more or less work without too
927 * much confusion -- but then, stop work should not
928 * rely on PI working anyway.
930 sched_setscheduler_nocheck(stop
, SCHED_FIFO
, ¶m
);
932 stop
->sched_class
= &stop_sched_class
;
935 cpu_rq(cpu
)->stop
= stop
;
939 * Reset it back to a normal scheduling class so that
940 * it can die in pieces.
942 old_stop
->sched_class
= &rt_sched_class
;
947 * __normal_prio - return the priority that is based on the static prio
949 static inline int __normal_prio(struct task_struct
*p
)
951 return p
->static_prio
;
955 * Calculate the expected normal priority: i.e. priority
956 * without taking RT-inheritance into account. Might be
957 * boosted by interactivity modifiers. Changes upon fork,
958 * setprio syscalls, and whenever the interactivity
959 * estimator recalculates.
961 static inline int normal_prio(struct task_struct
*p
)
965 if (task_has_dl_policy(p
))
966 prio
= MAX_DL_PRIO
-1;
967 else if (task_has_rt_policy(p
))
968 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
970 prio
= __normal_prio(p
);
975 * Calculate the current priority, i.e. the priority
976 * taken into account by the scheduler. This value might
977 * be boosted by RT tasks, or might be boosted by
978 * interactivity modifiers. Will be RT if the task got
979 * RT-boosted. If not then it returns p->normal_prio.
981 static int effective_prio(struct task_struct
*p
)
983 p
->normal_prio
= normal_prio(p
);
985 * If we are RT tasks or we were boosted to RT priority,
986 * keep the priority unchanged. Otherwise, update priority
987 * to the normal priority:
989 if (!rt_prio(p
->prio
))
990 return p
->normal_prio
;
995 * task_curr - is this task currently executing on a CPU?
996 * @p: the task in question.
998 * Return: 1 if the task is currently executing. 0 otherwise.
1000 inline int task_curr(const struct task_struct
*p
)
1002 return cpu_curr(task_cpu(p
)) == p
;
1006 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
1007 * use the balance_callback list if you want balancing.
1009 * this means any call to check_class_changed() must be followed by a call to
1010 * balance_callback().
1012 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1013 const struct sched_class
*prev_class
,
1016 if (prev_class
!= p
->sched_class
) {
1017 if (prev_class
->switched_from
)
1018 prev_class
->switched_from(rq
, p
);
1020 p
->sched_class
->switched_to(rq
, p
);
1021 } else if (oldprio
!= p
->prio
|| dl_task(p
))
1022 p
->sched_class
->prio_changed(rq
, p
, oldprio
);
1025 void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
, int flags
)
1027 const struct sched_class
*class;
1029 if (p
->sched_class
== rq
->curr
->sched_class
) {
1030 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
, flags
);
1032 for_each_class(class) {
1033 if (class == rq
->curr
->sched_class
)
1035 if (class == p
->sched_class
) {
1043 * A queue event has occurred, and we're going to schedule. In
1044 * this case, we can save a useless back to back clock update.
1046 if (task_on_rq_queued(rq
->curr
) && test_tsk_need_resched(rq
->curr
))
1047 rq_clock_skip_update(rq
, true);
1052 * This is how migration works:
1054 * 1) we invoke migration_cpu_stop() on the target CPU using
1056 * 2) stopper starts to run (implicitly forcing the migrated thread
1058 * 3) it checks whether the migrated task is still in the wrong runqueue.
1059 * 4) if it's in the wrong runqueue then the migration thread removes
1060 * it and puts it into the right queue.
1061 * 5) stopper completes and stop_one_cpu() returns and the migration
1066 * move_queued_task - move a queued task to new rq.
1068 * Returns (locked) new rq. Old rq's lock is released.
1070 static struct rq
*move_queued_task(struct rq
*rq
, struct task_struct
*p
, int new_cpu
)
1072 lockdep_assert_held(&rq
->lock
);
1074 p
->on_rq
= TASK_ON_RQ_MIGRATING
;
1075 dequeue_task(rq
, p
, 0);
1076 set_task_cpu(p
, new_cpu
);
1077 raw_spin_unlock(&rq
->lock
);
1079 rq
= cpu_rq(new_cpu
);
1081 raw_spin_lock(&rq
->lock
);
1082 BUG_ON(task_cpu(p
) != new_cpu
);
1083 enqueue_task(rq
, p
, 0);
1084 p
->on_rq
= TASK_ON_RQ_QUEUED
;
1085 check_preempt_curr(rq
, p
, 0);
1090 struct migration_arg
{
1091 struct task_struct
*task
;
1096 * Move (not current) task off this cpu, onto dest cpu. We're doing
1097 * this because either it can't run here any more (set_cpus_allowed()
1098 * away from this CPU, or CPU going down), or because we're
1099 * attempting to rebalance this task on exec (sched_exec).
1101 * So we race with normal scheduler movements, but that's OK, as long
1102 * as the task is no longer on this CPU.
1104 static struct rq
*__migrate_task(struct rq
*rq
, struct task_struct
*p
, int dest_cpu
)
1106 if (unlikely(!cpu_active(dest_cpu
)))
1109 /* Affinity changed (again). */
1110 if (!cpumask_test_cpu(dest_cpu
, tsk_cpus_allowed(p
)))
1113 rq
= move_queued_task(rq
, p
, dest_cpu
);
1119 * migration_cpu_stop - this will be executed by a highprio stopper thread
1120 * and performs thread migration by bumping thread off CPU then
1121 * 'pushing' onto another runqueue.
1123 static int migration_cpu_stop(void *data
)
1125 struct migration_arg
*arg
= data
;
1126 struct task_struct
*p
= arg
->task
;
1127 struct rq
*rq
= this_rq();
1130 * The original target cpu might have gone down and we might
1131 * be on another cpu but it doesn't matter.
1133 local_irq_disable();
1135 * We need to explicitly wake pending tasks before running
1136 * __migrate_task() such that we will not miss enforcing cpus_allowed
1137 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1139 sched_ttwu_pending();
1141 raw_spin_lock(&p
->pi_lock
);
1142 raw_spin_lock(&rq
->lock
);
1144 * If task_rq(p) != rq, it cannot be migrated here, because we're
1145 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1146 * we're holding p->pi_lock.
1148 if (task_rq(p
) == rq
&& task_on_rq_queued(p
))
1149 rq
= __migrate_task(rq
, p
, arg
->dest_cpu
);
1150 raw_spin_unlock(&rq
->lock
);
1151 raw_spin_unlock(&p
->pi_lock
);
1158 * sched_class::set_cpus_allowed must do the below, but is not required to
1159 * actually call this function.
1161 void set_cpus_allowed_common(struct task_struct
*p
, const struct cpumask
*new_mask
)
1163 cpumask_copy(&p
->cpus_allowed
, new_mask
);
1164 p
->nr_cpus_allowed
= cpumask_weight(new_mask
);
1167 void do_set_cpus_allowed(struct task_struct
*p
, const struct cpumask
*new_mask
)
1169 struct rq
*rq
= task_rq(p
);
1170 bool queued
, running
;
1172 lockdep_assert_held(&p
->pi_lock
);
1174 queued
= task_on_rq_queued(p
);
1175 running
= task_current(rq
, p
);
1179 * Because __kthread_bind() calls this on blocked tasks without
1182 lockdep_assert_held(&rq
->lock
);
1183 dequeue_task(rq
, p
, DEQUEUE_SAVE
);
1186 put_prev_task(rq
, p
);
1188 p
->sched_class
->set_cpus_allowed(p
, new_mask
);
1191 p
->sched_class
->set_curr_task(rq
);
1193 enqueue_task(rq
, p
, ENQUEUE_RESTORE
);
1197 * Change a given task's CPU affinity. Migrate the thread to a
1198 * proper CPU and schedule it away if the CPU it's executing on
1199 * is removed from the allowed bitmask.
1201 * NOTE: the caller must have a valid reference to the task, the
1202 * task must not exit() & deallocate itself prematurely. The
1203 * call is not atomic; no spinlocks may be held.
1205 static int __set_cpus_allowed_ptr(struct task_struct
*p
,
1206 const struct cpumask
*new_mask
, bool check
)
1208 unsigned long flags
;
1210 unsigned int dest_cpu
;
1213 rq
= task_rq_lock(p
, &flags
);
1216 * Must re-check here, to close a race against __kthread_bind(),
1217 * sched_setaffinity() is not guaranteed to observe the flag.
1219 if (check
&& (p
->flags
& PF_NO_SETAFFINITY
)) {
1224 if (cpumask_equal(&p
->cpus_allowed
, new_mask
))
1227 if (!cpumask_intersects(new_mask
, cpu_active_mask
)) {
1232 do_set_cpus_allowed(p
, new_mask
);
1234 /* Can the task run on the task's current CPU? If so, we're done */
1235 if (cpumask_test_cpu(task_cpu(p
), new_mask
))
1238 dest_cpu
= cpumask_any_and(cpu_active_mask
, new_mask
);
1239 if (task_running(rq
, p
) || p
->state
== TASK_WAKING
) {
1240 struct migration_arg arg
= { p
, dest_cpu
};
1241 /* Need help from migration thread: drop lock and wait. */
1242 task_rq_unlock(rq
, p
, &flags
);
1243 stop_one_cpu(cpu_of(rq
), migration_cpu_stop
, &arg
);
1244 tlb_migrate_finish(p
->mm
);
1246 } else if (task_on_rq_queued(p
)) {
1248 * OK, since we're going to drop the lock immediately
1249 * afterwards anyway.
1251 lockdep_unpin_lock(&rq
->lock
);
1252 rq
= move_queued_task(rq
, p
, dest_cpu
);
1253 lockdep_pin_lock(&rq
->lock
);
1256 task_rq_unlock(rq
, p
, &flags
);
1261 int set_cpus_allowed_ptr(struct task_struct
*p
, const struct cpumask
*new_mask
)
1263 return __set_cpus_allowed_ptr(p
, new_mask
, false);
1265 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr
);
1267 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1269 #ifdef CONFIG_SCHED_DEBUG
1271 * We should never call set_task_cpu() on a blocked task,
1272 * ttwu() will sort out the placement.
1274 WARN_ON_ONCE(p
->state
!= TASK_RUNNING
&& p
->state
!= TASK_WAKING
&&
1278 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1279 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1280 * time relying on p->on_rq.
1282 WARN_ON_ONCE(p
->state
== TASK_RUNNING
&&
1283 p
->sched_class
== &fair_sched_class
&&
1284 (p
->on_rq
&& !task_on_rq_migrating(p
)));
1286 #ifdef CONFIG_LOCKDEP
1288 * The caller should hold either p->pi_lock or rq->lock, when changing
1289 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1291 * sched_move_task() holds both and thus holding either pins the cgroup,
1294 * Furthermore, all task_rq users should acquire both locks, see
1297 WARN_ON_ONCE(debug_locks
&& !(lockdep_is_held(&p
->pi_lock
) ||
1298 lockdep_is_held(&task_rq(p
)->lock
)));
1302 trace_sched_migrate_task(p
, new_cpu
);
1304 if (task_cpu(p
) != new_cpu
) {
1305 if (p
->sched_class
->migrate_task_rq
)
1306 p
->sched_class
->migrate_task_rq(p
);
1307 p
->se
.nr_migrations
++;
1308 perf_event_task_migrate(p
);
1311 __set_task_cpu(p
, new_cpu
);
1314 static void __migrate_swap_task(struct task_struct
*p
, int cpu
)
1316 if (task_on_rq_queued(p
)) {
1317 struct rq
*src_rq
, *dst_rq
;
1319 src_rq
= task_rq(p
);
1320 dst_rq
= cpu_rq(cpu
);
1322 p
->on_rq
= TASK_ON_RQ_MIGRATING
;
1323 deactivate_task(src_rq
, p
, 0);
1324 set_task_cpu(p
, cpu
);
1325 activate_task(dst_rq
, p
, 0);
1326 p
->on_rq
= TASK_ON_RQ_QUEUED
;
1327 check_preempt_curr(dst_rq
, p
, 0);
1330 * Task isn't running anymore; make it appear like we migrated
1331 * it before it went to sleep. This means on wakeup we make the
1332 * previous cpu our targer instead of where it really is.
1338 struct migration_swap_arg
{
1339 struct task_struct
*src_task
, *dst_task
;
1340 int src_cpu
, dst_cpu
;
1343 static int migrate_swap_stop(void *data
)
1345 struct migration_swap_arg
*arg
= data
;
1346 struct rq
*src_rq
, *dst_rq
;
1349 if (!cpu_active(arg
->src_cpu
) || !cpu_active(arg
->dst_cpu
))
1352 src_rq
= cpu_rq(arg
->src_cpu
);
1353 dst_rq
= cpu_rq(arg
->dst_cpu
);
1355 double_raw_lock(&arg
->src_task
->pi_lock
,
1356 &arg
->dst_task
->pi_lock
);
1357 double_rq_lock(src_rq
, dst_rq
);
1359 if (task_cpu(arg
->dst_task
) != arg
->dst_cpu
)
1362 if (task_cpu(arg
->src_task
) != arg
->src_cpu
)
1365 if (!cpumask_test_cpu(arg
->dst_cpu
, tsk_cpus_allowed(arg
->src_task
)))
1368 if (!cpumask_test_cpu(arg
->src_cpu
, tsk_cpus_allowed(arg
->dst_task
)))
1371 __migrate_swap_task(arg
->src_task
, arg
->dst_cpu
);
1372 __migrate_swap_task(arg
->dst_task
, arg
->src_cpu
);
1377 double_rq_unlock(src_rq
, dst_rq
);
1378 raw_spin_unlock(&arg
->dst_task
->pi_lock
);
1379 raw_spin_unlock(&arg
->src_task
->pi_lock
);
1385 * Cross migrate two tasks
1387 int migrate_swap(struct task_struct
*cur
, struct task_struct
*p
)
1389 struct migration_swap_arg arg
;
1392 arg
= (struct migration_swap_arg
){
1394 .src_cpu
= task_cpu(cur
),
1396 .dst_cpu
= task_cpu(p
),
1399 if (arg
.src_cpu
== arg
.dst_cpu
)
1403 * These three tests are all lockless; this is OK since all of them
1404 * will be re-checked with proper locks held further down the line.
1406 if (!cpu_active(arg
.src_cpu
) || !cpu_active(arg
.dst_cpu
))
1409 if (!cpumask_test_cpu(arg
.dst_cpu
, tsk_cpus_allowed(arg
.src_task
)))
1412 if (!cpumask_test_cpu(arg
.src_cpu
, tsk_cpus_allowed(arg
.dst_task
)))
1415 trace_sched_swap_numa(cur
, arg
.src_cpu
, p
, arg
.dst_cpu
);
1416 ret
= stop_two_cpus(arg
.dst_cpu
, arg
.src_cpu
, migrate_swap_stop
, &arg
);
1423 * wait_task_inactive - wait for a thread to unschedule.
1425 * If @match_state is nonzero, it's the @p->state value just checked and
1426 * not expected to change. If it changes, i.e. @p might have woken up,
1427 * then return zero. When we succeed in waiting for @p to be off its CPU,
1428 * we return a positive number (its total switch count). If a second call
1429 * a short while later returns the same number, the caller can be sure that
1430 * @p has remained unscheduled the whole time.
1432 * The caller must ensure that the task *will* unschedule sometime soon,
1433 * else this function might spin for a *long* time. This function can't
1434 * be called with interrupts off, or it may introduce deadlock with
1435 * smp_call_function() if an IPI is sent by the same process we are
1436 * waiting to become inactive.
1438 unsigned long wait_task_inactive(struct task_struct
*p
, long match_state
)
1440 unsigned long flags
;
1441 int running
, queued
;
1447 * We do the initial early heuristics without holding
1448 * any task-queue locks at all. We'll only try to get
1449 * the runqueue lock when things look like they will
1455 * If the task is actively running on another CPU
1456 * still, just relax and busy-wait without holding
1459 * NOTE! Since we don't hold any locks, it's not
1460 * even sure that "rq" stays as the right runqueue!
1461 * But we don't care, since "task_running()" will
1462 * return false if the runqueue has changed and p
1463 * is actually now running somewhere else!
1465 while (task_running(rq
, p
)) {
1466 if (match_state
&& unlikely(p
->state
!= match_state
))
1472 * Ok, time to look more closely! We need the rq
1473 * lock now, to be *sure*. If we're wrong, we'll
1474 * just go back and repeat.
1476 rq
= task_rq_lock(p
, &flags
);
1477 trace_sched_wait_task(p
);
1478 running
= task_running(rq
, p
);
1479 queued
= task_on_rq_queued(p
);
1481 if (!match_state
|| p
->state
== match_state
)
1482 ncsw
= p
->nvcsw
| LONG_MIN
; /* sets MSB */
1483 task_rq_unlock(rq
, p
, &flags
);
1486 * If it changed from the expected state, bail out now.
1488 if (unlikely(!ncsw
))
1492 * Was it really running after all now that we
1493 * checked with the proper locks actually held?
1495 * Oops. Go back and try again..
1497 if (unlikely(running
)) {
1503 * It's not enough that it's not actively running,
1504 * it must be off the runqueue _entirely_, and not
1507 * So if it was still runnable (but just not actively
1508 * running right now), it's preempted, and we should
1509 * yield - it could be a while.
1511 if (unlikely(queued
)) {
1512 ktime_t to
= ktime_set(0, NSEC_PER_SEC
/HZ
);
1514 set_current_state(TASK_UNINTERRUPTIBLE
);
1515 schedule_hrtimeout(&to
, HRTIMER_MODE_REL
);
1520 * Ahh, all good. It wasn't running, and it wasn't
1521 * runnable, which means that it will never become
1522 * running in the future either. We're all done!
1531 * kick_process - kick a running thread to enter/exit the kernel
1532 * @p: the to-be-kicked thread
1534 * Cause a process which is running on another CPU to enter
1535 * kernel-mode, without any delay. (to get signals handled.)
1537 * NOTE: this function doesn't have to take the runqueue lock,
1538 * because all it wants to ensure is that the remote task enters
1539 * the kernel. If the IPI races and the task has been migrated
1540 * to another CPU then no harm is done and the purpose has been
1543 void kick_process(struct task_struct
*p
)
1549 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1550 smp_send_reschedule(cpu
);
1553 EXPORT_SYMBOL_GPL(kick_process
);
1556 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1558 static int select_fallback_rq(int cpu
, struct task_struct
*p
)
1560 int nid
= cpu_to_node(cpu
);
1561 const struct cpumask
*nodemask
= NULL
;
1562 enum { cpuset
, possible
, fail
} state
= cpuset
;
1566 * If the node that the cpu is on has been offlined, cpu_to_node()
1567 * will return -1. There is no cpu on the node, and we should
1568 * select the cpu on the other node.
1571 nodemask
= cpumask_of_node(nid
);
1573 /* Look for allowed, online CPU in same node. */
1574 for_each_cpu(dest_cpu
, nodemask
) {
1575 if (!cpu_online(dest_cpu
))
1577 if (!cpu_active(dest_cpu
))
1579 if (cpumask_test_cpu(dest_cpu
, tsk_cpus_allowed(p
)))
1585 /* Any allowed, online CPU? */
1586 for_each_cpu(dest_cpu
, tsk_cpus_allowed(p
)) {
1587 if (!cpu_online(dest_cpu
))
1589 if (!cpu_active(dest_cpu
))
1594 /* No more Mr. Nice Guy. */
1597 if (IS_ENABLED(CONFIG_CPUSETS
)) {
1598 cpuset_cpus_allowed_fallback(p
);
1604 do_set_cpus_allowed(p
, cpu_possible_mask
);
1615 if (state
!= cpuset
) {
1617 * Don't tell them about moving exiting tasks or
1618 * kernel threads (both mm NULL), since they never
1621 if (p
->mm
&& printk_ratelimit()) {
1622 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1623 task_pid_nr(p
), p
->comm
, cpu
);
1631 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1634 int select_task_rq(struct task_struct
*p
, int cpu
, int sd_flags
, int wake_flags
)
1636 lockdep_assert_held(&p
->pi_lock
);
1638 if (p
->nr_cpus_allowed
> 1)
1639 cpu
= p
->sched_class
->select_task_rq(p
, cpu
, sd_flags
, wake_flags
);
1642 * In order not to call set_task_cpu() on a blocking task we need
1643 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1646 * Since this is common to all placement strategies, this lives here.
1648 * [ this allows ->select_task() to simply return task_cpu(p) and
1649 * not worry about this generic constraint ]
1651 if (unlikely(!cpumask_test_cpu(cpu
, tsk_cpus_allowed(p
)) ||
1653 cpu
= select_fallback_rq(task_cpu(p
), p
);
1658 static void update_avg(u64
*avg
, u64 sample
)
1660 s64 diff
= sample
- *avg
;
1666 static inline int __set_cpus_allowed_ptr(struct task_struct
*p
,
1667 const struct cpumask
*new_mask
, bool check
)
1669 return set_cpus_allowed_ptr(p
, new_mask
);
1672 #endif /* CONFIG_SMP */
1675 ttwu_stat(struct task_struct
*p
, int cpu
, int wake_flags
)
1677 #ifdef CONFIG_SCHEDSTATS
1678 struct rq
*rq
= this_rq();
1681 int this_cpu
= smp_processor_id();
1683 if (cpu
== this_cpu
) {
1684 schedstat_inc(rq
, ttwu_local
);
1685 schedstat_inc(p
, se
.statistics
.nr_wakeups_local
);
1687 struct sched_domain
*sd
;
1689 schedstat_inc(p
, se
.statistics
.nr_wakeups_remote
);
1691 for_each_domain(this_cpu
, sd
) {
1692 if (cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
1693 schedstat_inc(sd
, ttwu_wake_remote
);
1700 if (wake_flags
& WF_MIGRATED
)
1701 schedstat_inc(p
, se
.statistics
.nr_wakeups_migrate
);
1703 #endif /* CONFIG_SMP */
1705 schedstat_inc(rq
, ttwu_count
);
1706 schedstat_inc(p
, se
.statistics
.nr_wakeups
);
1708 if (wake_flags
& WF_SYNC
)
1709 schedstat_inc(p
, se
.statistics
.nr_wakeups_sync
);
1711 #endif /* CONFIG_SCHEDSTATS */
1714 static inline void ttwu_activate(struct rq
*rq
, struct task_struct
*p
, int en_flags
)
1716 activate_task(rq
, p
, en_flags
);
1717 p
->on_rq
= TASK_ON_RQ_QUEUED
;
1719 /* if a worker is waking up, notify workqueue */
1720 if (p
->flags
& PF_WQ_WORKER
)
1721 wq_worker_waking_up(p
, cpu_of(rq
));
1725 * Mark the task runnable and perform wakeup-preemption.
1728 ttwu_do_wakeup(struct rq
*rq
, struct task_struct
*p
, int wake_flags
)
1730 check_preempt_curr(rq
, p
, wake_flags
);
1731 p
->state
= TASK_RUNNING
;
1732 trace_sched_wakeup(p
);
1735 if (p
->sched_class
->task_woken
) {
1737 * Our task @p is fully woken up and running; so its safe to
1738 * drop the rq->lock, hereafter rq is only used for statistics.
1740 lockdep_unpin_lock(&rq
->lock
);
1741 p
->sched_class
->task_woken(rq
, p
);
1742 lockdep_pin_lock(&rq
->lock
);
1745 if (rq
->idle_stamp
) {
1746 u64 delta
= rq_clock(rq
) - rq
->idle_stamp
;
1747 u64 max
= 2*rq
->max_idle_balance_cost
;
1749 update_avg(&rq
->avg_idle
, delta
);
1751 if (rq
->avg_idle
> max
)
1760 ttwu_do_activate(struct rq
*rq
, struct task_struct
*p
, int wake_flags
)
1762 lockdep_assert_held(&rq
->lock
);
1765 if (p
->sched_contributes_to_load
)
1766 rq
->nr_uninterruptible
--;
1769 ttwu_activate(rq
, p
, ENQUEUE_WAKEUP
| ENQUEUE_WAKING
);
1770 ttwu_do_wakeup(rq
, p
, wake_flags
);
1774 * Called in case the task @p isn't fully descheduled from its runqueue,
1775 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1776 * since all we need to do is flip p->state to TASK_RUNNING, since
1777 * the task is still ->on_rq.
1779 static int ttwu_remote(struct task_struct
*p
, int wake_flags
)
1784 rq
= __task_rq_lock(p
);
1785 if (task_on_rq_queued(p
)) {
1786 /* check_preempt_curr() may use rq clock */
1787 update_rq_clock(rq
);
1788 ttwu_do_wakeup(rq
, p
, wake_flags
);
1791 __task_rq_unlock(rq
);
1797 void sched_ttwu_pending(void)
1799 struct rq
*rq
= this_rq();
1800 struct llist_node
*llist
= llist_del_all(&rq
->wake_list
);
1801 struct task_struct
*p
;
1802 unsigned long flags
;
1807 raw_spin_lock_irqsave(&rq
->lock
, flags
);
1808 lockdep_pin_lock(&rq
->lock
);
1811 p
= llist_entry(llist
, struct task_struct
, wake_entry
);
1812 llist
= llist_next(llist
);
1813 ttwu_do_activate(rq
, p
, 0);
1816 lockdep_unpin_lock(&rq
->lock
);
1817 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
1820 void scheduler_ipi(void)
1823 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1824 * TIF_NEED_RESCHED remotely (for the first time) will also send
1827 preempt_fold_need_resched();
1829 if (llist_empty(&this_rq()->wake_list
) && !got_nohz_idle_kick())
1833 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1834 * traditionally all their work was done from the interrupt return
1835 * path. Now that we actually do some work, we need to make sure
1838 * Some archs already do call them, luckily irq_enter/exit nest
1841 * Arguably we should visit all archs and update all handlers,
1842 * however a fair share of IPIs are still resched only so this would
1843 * somewhat pessimize the simple resched case.
1846 sched_ttwu_pending();
1849 * Check if someone kicked us for doing the nohz idle load balance.
1851 if (unlikely(got_nohz_idle_kick())) {
1852 this_rq()->idle_balance
= 1;
1853 raise_softirq_irqoff(SCHED_SOFTIRQ
);
1858 static void ttwu_queue_remote(struct task_struct
*p
, int cpu
)
1860 struct rq
*rq
= cpu_rq(cpu
);
1862 if (llist_add(&p
->wake_entry
, &cpu_rq(cpu
)->wake_list
)) {
1863 if (!set_nr_if_polling(rq
->idle
))
1864 smp_send_reschedule(cpu
);
1866 trace_sched_wake_idle_without_ipi(cpu
);
1870 void wake_up_if_idle(int cpu
)
1872 struct rq
*rq
= cpu_rq(cpu
);
1873 unsigned long flags
;
1877 if (!is_idle_task(rcu_dereference(rq
->curr
)))
1880 if (set_nr_if_polling(rq
->idle
)) {
1881 trace_sched_wake_idle_without_ipi(cpu
);
1883 raw_spin_lock_irqsave(&rq
->lock
, flags
);
1884 if (is_idle_task(rq
->curr
))
1885 smp_send_reschedule(cpu
);
1886 /* Else cpu is not in idle, do nothing here */
1887 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
1894 bool cpus_share_cache(int this_cpu
, int that_cpu
)
1896 return per_cpu(sd_llc_id
, this_cpu
) == per_cpu(sd_llc_id
, that_cpu
);
1898 #endif /* CONFIG_SMP */
1900 static void ttwu_queue(struct task_struct
*p
, int cpu
)
1902 struct rq
*rq
= cpu_rq(cpu
);
1904 #if defined(CONFIG_SMP)
1905 if (sched_feat(TTWU_QUEUE
) && !cpus_share_cache(smp_processor_id(), cpu
)) {
1906 sched_clock_cpu(cpu
); /* sync clocks x-cpu */
1907 ttwu_queue_remote(p
, cpu
);
1912 raw_spin_lock(&rq
->lock
);
1913 lockdep_pin_lock(&rq
->lock
);
1914 ttwu_do_activate(rq
, p
, 0);
1915 lockdep_unpin_lock(&rq
->lock
);
1916 raw_spin_unlock(&rq
->lock
);
1920 * Notes on Program-Order guarantees on SMP systems.
1924 * The basic program-order guarantee on SMP systems is that when a task [t]
1925 * migrates, all its activity on its old cpu [c0] happens-before any subsequent
1926 * execution on its new cpu [c1].
1928 * For migration (of runnable tasks) this is provided by the following means:
1930 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1931 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1932 * rq(c1)->lock (if not at the same time, then in that order).
1933 * C) LOCK of the rq(c1)->lock scheduling in task
1935 * Transitivity guarantees that B happens after A and C after B.
1936 * Note: we only require RCpc transitivity.
1937 * Note: the cpu doing B need not be c0 or c1
1946 * UNLOCK rq(0)->lock
1948 * LOCK rq(0)->lock // orders against CPU0
1950 * UNLOCK rq(0)->lock
1954 * UNLOCK rq(1)->lock
1956 * LOCK rq(1)->lock // orders against CPU2
1959 * UNLOCK rq(1)->lock
1962 * BLOCKING -- aka. SLEEP + WAKEUP
1964 * For blocking we (obviously) need to provide the same guarantee as for
1965 * migration. However the means are completely different as there is no lock
1966 * chain to provide order. Instead we do:
1968 * 1) smp_store_release(X->on_cpu, 0)
1969 * 2) smp_cond_acquire(!X->on_cpu)
1973 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1975 * LOCK rq(0)->lock LOCK X->pi_lock
1978 * smp_store_release(X->on_cpu, 0);
1980 * smp_cond_acquire(!X->on_cpu);
1986 * X->state = RUNNING
1987 * UNLOCK rq(2)->lock
1989 * LOCK rq(2)->lock // orders against CPU1
1992 * UNLOCK rq(2)->lock
1995 * UNLOCK rq(0)->lock
1998 * However; for wakeups there is a second guarantee we must provide, namely we
1999 * must observe the state that lead to our wakeup. That is, not only must our
2000 * task observe its own prior state, it must also observe the stores prior to
2003 * This means that any means of doing remote wakeups must order the CPU doing
2004 * the wakeup against the CPU the task is going to end up running on. This,
2005 * however, is already required for the regular Program-Order guarantee above,
2006 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_acquire).
2011 * try_to_wake_up - wake up a thread
2012 * @p: the thread to be awakened
2013 * @state: the mask of task states that can be woken
2014 * @wake_flags: wake modifier flags (WF_*)
2016 * Put it on the run-queue if it's not already there. The "current"
2017 * thread is always on the run-queue (except when the actual
2018 * re-schedule is in progress), and as such you're allowed to do
2019 * the simpler "current->state = TASK_RUNNING" to mark yourself
2020 * runnable without the overhead of this.
2022 * Return: %true if @p was woken up, %false if it was already running.
2023 * or @state didn't match @p's state.
2026 try_to_wake_up(struct task_struct
*p
, unsigned int state
, int wake_flags
)
2028 unsigned long flags
;
2029 int cpu
, success
= 0;
2032 * If we are going to wake up a thread waiting for CONDITION we
2033 * need to ensure that CONDITION=1 done by the caller can not be
2034 * reordered with p->state check below. This pairs with mb() in
2035 * set_current_state() the waiting thread does.
2037 smp_mb__before_spinlock();
2038 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
2039 if (!(p
->state
& state
))
2042 trace_sched_waking(p
);
2044 success
= 1; /* we're going to change ->state */
2047 if (p
->on_rq
&& ttwu_remote(p
, wake_flags
))
2052 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2053 * possible to, falsely, observe p->on_cpu == 0.
2055 * One must be running (->on_cpu == 1) in order to remove oneself
2056 * from the runqueue.
2058 * [S] ->on_cpu = 1; [L] ->on_rq
2062 * [S] ->on_rq = 0; [L] ->on_cpu
2064 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2065 * from the consecutive calls to schedule(); the first switching to our
2066 * task, the second putting it to sleep.
2071 * If the owning (remote) cpu is still in the middle of schedule() with
2072 * this task as prev, wait until its done referencing the task.
2074 * Pairs with the smp_store_release() in finish_lock_switch().
2076 * This ensures that tasks getting woken will be fully ordered against
2077 * their previous state and preserve Program Order.
2079 smp_cond_acquire(!p
->on_cpu
);
2081 p
->sched_contributes_to_load
= !!task_contributes_to_load(p
);
2082 p
->state
= TASK_WAKING
;
2084 if (p
->sched_class
->task_waking
)
2085 p
->sched_class
->task_waking(p
);
2087 cpu
= select_task_rq(p
, p
->wake_cpu
, SD_BALANCE_WAKE
, wake_flags
);
2088 if (task_cpu(p
) != cpu
) {
2089 wake_flags
|= WF_MIGRATED
;
2090 set_task_cpu(p
, cpu
);
2092 #endif /* CONFIG_SMP */
2096 if (schedstat_enabled())
2097 ttwu_stat(p
, cpu
, wake_flags
);
2099 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2105 * try_to_wake_up_local - try to wake up a local task with rq lock held
2106 * @p: the thread to be awakened
2108 * Put @p on the run-queue if it's not already there. The caller must
2109 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2112 static void try_to_wake_up_local(struct task_struct
*p
)
2114 struct rq
*rq
= task_rq(p
);
2116 if (WARN_ON_ONCE(rq
!= this_rq()) ||
2117 WARN_ON_ONCE(p
== current
))
2120 lockdep_assert_held(&rq
->lock
);
2122 if (!raw_spin_trylock(&p
->pi_lock
)) {
2124 * This is OK, because current is on_cpu, which avoids it being
2125 * picked for load-balance and preemption/IRQs are still
2126 * disabled avoiding further scheduler activity on it and we've
2127 * not yet picked a replacement task.
2129 lockdep_unpin_lock(&rq
->lock
);
2130 raw_spin_unlock(&rq
->lock
);
2131 raw_spin_lock(&p
->pi_lock
);
2132 raw_spin_lock(&rq
->lock
);
2133 lockdep_pin_lock(&rq
->lock
);
2136 if (!(p
->state
& TASK_NORMAL
))
2139 trace_sched_waking(p
);
2141 if (!task_on_rq_queued(p
))
2142 ttwu_activate(rq
, p
, ENQUEUE_WAKEUP
);
2144 ttwu_do_wakeup(rq
, p
, 0);
2145 if (schedstat_enabled())
2146 ttwu_stat(p
, smp_processor_id(), 0);
2148 raw_spin_unlock(&p
->pi_lock
);
2152 * wake_up_process - Wake up a specific process
2153 * @p: The process to be woken up.
2155 * Attempt to wake up the nominated process and move it to the set of runnable
2158 * Return: 1 if the process was woken up, 0 if it was already running.
2160 * It may be assumed that this function implies a write memory barrier before
2161 * changing the task state if and only if any tasks are woken up.
2163 int wake_up_process(struct task_struct
*p
)
2165 return try_to_wake_up(p
, TASK_NORMAL
, 0);
2167 EXPORT_SYMBOL(wake_up_process
);
2169 int wake_up_state(struct task_struct
*p
, unsigned int state
)
2171 return try_to_wake_up(p
, state
, 0);
2175 * This function clears the sched_dl_entity static params.
2177 void __dl_clear_params(struct task_struct
*p
)
2179 struct sched_dl_entity
*dl_se
= &p
->dl
;
2181 dl_se
->dl_runtime
= 0;
2182 dl_se
->dl_deadline
= 0;
2183 dl_se
->dl_period
= 0;
2187 dl_se
->dl_throttled
= 0;
2189 dl_se
->dl_yielded
= 0;
2193 * Perform scheduler related setup for a newly forked process p.
2194 * p is forked by current.
2196 * __sched_fork() is basic setup used by init_idle() too:
2198 static void __sched_fork(unsigned long clone_flags
, struct task_struct
*p
)
2203 p
->se
.exec_start
= 0;
2204 p
->se
.sum_exec_runtime
= 0;
2205 p
->se
.prev_sum_exec_runtime
= 0;
2206 p
->se
.nr_migrations
= 0;
2208 INIT_LIST_HEAD(&p
->se
.group_node
);
2210 #ifdef CONFIG_FAIR_GROUP_SCHED
2211 p
->se
.cfs_rq
= NULL
;
2214 #ifdef CONFIG_SCHEDSTATS
2215 /* Even if schedstat is disabled, there should not be garbage */
2216 memset(&p
->se
.statistics
, 0, sizeof(p
->se
.statistics
));
2219 RB_CLEAR_NODE(&p
->dl
.rb_node
);
2220 init_dl_task_timer(&p
->dl
);
2221 __dl_clear_params(p
);
2223 INIT_LIST_HEAD(&p
->rt
.run_list
);
2225 #ifdef CONFIG_PREEMPT_NOTIFIERS
2226 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
2229 #ifdef CONFIG_NUMA_BALANCING
2230 if (p
->mm
&& atomic_read(&p
->mm
->mm_users
) == 1) {
2231 p
->mm
->numa_next_scan
= jiffies
+ msecs_to_jiffies(sysctl_numa_balancing_scan_delay
);
2232 p
->mm
->numa_scan_seq
= 0;
2235 if (clone_flags
& CLONE_VM
)
2236 p
->numa_preferred_nid
= current
->numa_preferred_nid
;
2238 p
->numa_preferred_nid
= -1;
2240 p
->node_stamp
= 0ULL;
2241 p
->numa_scan_seq
= p
->mm
? p
->mm
->numa_scan_seq
: 0;
2242 p
->numa_scan_period
= sysctl_numa_balancing_scan_delay
;
2243 p
->numa_work
.next
= &p
->numa_work
;
2244 p
->numa_faults
= NULL
;
2245 p
->last_task_numa_placement
= 0;
2246 p
->last_sum_exec_runtime
= 0;
2248 p
->numa_group
= NULL
;
2249 #endif /* CONFIG_NUMA_BALANCING */
2252 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing
);
2254 #ifdef CONFIG_NUMA_BALANCING
2256 void set_numabalancing_state(bool enabled
)
2259 static_branch_enable(&sched_numa_balancing
);
2261 static_branch_disable(&sched_numa_balancing
);
2264 #ifdef CONFIG_PROC_SYSCTL
2265 int sysctl_numa_balancing(struct ctl_table
*table
, int write
,
2266 void __user
*buffer
, size_t *lenp
, loff_t
*ppos
)
2270 int state
= static_branch_likely(&sched_numa_balancing
);
2272 if (write
&& !capable(CAP_SYS_ADMIN
))
2277 err
= proc_dointvec_minmax(&t
, write
, buffer
, lenp
, ppos
);
2281 set_numabalancing_state(state
);
2287 DEFINE_STATIC_KEY_FALSE(sched_schedstats
);
2289 #ifdef CONFIG_SCHEDSTATS
2290 static void set_schedstats(bool enabled
)
2293 static_branch_enable(&sched_schedstats
);
2295 static_branch_disable(&sched_schedstats
);
2298 void force_schedstat_enabled(void)
2300 if (!schedstat_enabled()) {
2301 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2302 static_branch_enable(&sched_schedstats
);
2306 static int __init
setup_schedstats(char *str
)
2312 if (!strcmp(str
, "enable")) {
2313 set_schedstats(true);
2315 } else if (!strcmp(str
, "disable")) {
2316 set_schedstats(false);
2321 pr_warn("Unable to parse schedstats=\n");
2325 __setup("schedstats=", setup_schedstats
);
2327 #ifdef CONFIG_PROC_SYSCTL
2328 int sysctl_schedstats(struct ctl_table
*table
, int write
,
2329 void __user
*buffer
, size_t *lenp
, loff_t
*ppos
)
2333 int state
= static_branch_likely(&sched_schedstats
);
2335 if (write
&& !capable(CAP_SYS_ADMIN
))
2340 err
= proc_dointvec_minmax(&t
, write
, buffer
, lenp
, ppos
);
2344 set_schedstats(state
);
2351 * fork()/clone()-time setup:
2353 int sched_fork(unsigned long clone_flags
, struct task_struct
*p
)
2355 unsigned long flags
;
2356 int cpu
= get_cpu();
2358 __sched_fork(clone_flags
, p
);
2360 * We mark the process as running here. This guarantees that
2361 * nobody will actually run it, and a signal or other external
2362 * event cannot wake it up and insert it on the runqueue either.
2364 p
->state
= TASK_RUNNING
;
2367 * Make sure we do not leak PI boosting priority to the child.
2369 p
->prio
= current
->normal_prio
;
2372 * Revert to default priority/policy on fork if requested.
2374 if (unlikely(p
->sched_reset_on_fork
)) {
2375 if (task_has_dl_policy(p
) || task_has_rt_policy(p
)) {
2376 p
->policy
= SCHED_NORMAL
;
2377 p
->static_prio
= NICE_TO_PRIO(0);
2379 } else if (PRIO_TO_NICE(p
->static_prio
) < 0)
2380 p
->static_prio
= NICE_TO_PRIO(0);
2382 p
->prio
= p
->normal_prio
= __normal_prio(p
);
2386 * We don't need the reset flag anymore after the fork. It has
2387 * fulfilled its duty:
2389 p
->sched_reset_on_fork
= 0;
2392 if (dl_prio(p
->prio
)) {
2395 } else if (rt_prio(p
->prio
)) {
2396 p
->sched_class
= &rt_sched_class
;
2398 p
->sched_class
= &fair_sched_class
;
2401 if (p
->sched_class
->task_fork
)
2402 p
->sched_class
->task_fork(p
);
2405 * The child is not yet in the pid-hash so no cgroup attach races,
2406 * and the cgroup is pinned to this child due to cgroup_fork()
2407 * is ran before sched_fork().
2409 * Silence PROVE_RCU.
2411 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
2412 set_task_cpu(p
, cpu
);
2413 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2415 #ifdef CONFIG_SCHED_INFO
2416 if (likely(sched_info_on()))
2417 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
2419 #if defined(CONFIG_SMP)
2422 init_task_preempt_count(p
);
2424 plist_node_init(&p
->pushable_tasks
, MAX_PRIO
);
2425 RB_CLEAR_NODE(&p
->pushable_dl_tasks
);
2432 unsigned long to_ratio(u64 period
, u64 runtime
)
2434 if (runtime
== RUNTIME_INF
)
2438 * Doing this here saves a lot of checks in all
2439 * the calling paths, and returning zero seems
2440 * safe for them anyway.
2445 return div64_u64(runtime
<< 20, period
);
2449 inline struct dl_bw
*dl_bw_of(int i
)
2451 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2452 "sched RCU must be held");
2453 return &cpu_rq(i
)->rd
->dl_bw
;
2456 static inline int dl_bw_cpus(int i
)
2458 struct root_domain
*rd
= cpu_rq(i
)->rd
;
2461 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
2462 "sched RCU must be held");
2463 for_each_cpu_and(i
, rd
->span
, cpu_active_mask
)
2469 inline struct dl_bw
*dl_bw_of(int i
)
2471 return &cpu_rq(i
)->dl
.dl_bw
;
2474 static inline int dl_bw_cpus(int i
)
2481 * We must be sure that accepting a new task (or allowing changing the
2482 * parameters of an existing one) is consistent with the bandwidth
2483 * constraints. If yes, this function also accordingly updates the currently
2484 * allocated bandwidth to reflect the new situation.
2486 * This function is called while holding p's rq->lock.
2488 * XXX we should delay bw change until the task's 0-lag point, see
2491 static int dl_overflow(struct task_struct
*p
, int policy
,
2492 const struct sched_attr
*attr
)
2495 struct dl_bw
*dl_b
= dl_bw_of(task_cpu(p
));
2496 u64 period
= attr
->sched_period
?: attr
->sched_deadline
;
2497 u64 runtime
= attr
->sched_runtime
;
2498 u64 new_bw
= dl_policy(policy
) ? to_ratio(period
, runtime
) : 0;
2501 if (new_bw
== p
->dl
.dl_bw
)
2505 * Either if a task, enters, leave, or stays -deadline but changes
2506 * its parameters, we may need to update accordingly the total
2507 * allocated bandwidth of the container.
2509 raw_spin_lock(&dl_b
->lock
);
2510 cpus
= dl_bw_cpus(task_cpu(p
));
2511 if (dl_policy(policy
) && !task_has_dl_policy(p
) &&
2512 !__dl_overflow(dl_b
, cpus
, 0, new_bw
)) {
2513 __dl_add(dl_b
, new_bw
);
2515 } else if (dl_policy(policy
) && task_has_dl_policy(p
) &&
2516 !__dl_overflow(dl_b
, cpus
, p
->dl
.dl_bw
, new_bw
)) {
2517 __dl_clear(dl_b
, p
->dl
.dl_bw
);
2518 __dl_add(dl_b
, new_bw
);
2520 } else if (!dl_policy(policy
) && task_has_dl_policy(p
)) {
2521 __dl_clear(dl_b
, p
->dl
.dl_bw
);
2524 raw_spin_unlock(&dl_b
->lock
);
2529 extern void init_dl_bw(struct dl_bw
*dl_b
);
2532 * wake_up_new_task - wake up a newly created task for the first time.
2534 * This function will do some initial scheduler statistics housekeeping
2535 * that must be done for every newly created context, then puts the task
2536 * on the runqueue and wakes it.
2538 void wake_up_new_task(struct task_struct
*p
)
2540 unsigned long flags
;
2543 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
2544 /* Initialize new task's runnable average */
2545 init_entity_runnable_average(&p
->se
);
2548 * Fork balancing, do it here and not earlier because:
2549 * - cpus_allowed can change in the fork path
2550 * - any previously selected cpu might disappear through hotplug
2552 set_task_cpu(p
, select_task_rq(p
, task_cpu(p
), SD_BALANCE_FORK
, 0));
2555 rq
= __task_rq_lock(p
);
2556 activate_task(rq
, p
, 0);
2557 p
->on_rq
= TASK_ON_RQ_QUEUED
;
2558 trace_sched_wakeup_new(p
);
2559 check_preempt_curr(rq
, p
, WF_FORK
);
2561 if (p
->sched_class
->task_woken
) {
2563 * Nothing relies on rq->lock after this, so its fine to
2566 lockdep_unpin_lock(&rq
->lock
);
2567 p
->sched_class
->task_woken(rq
, p
);
2568 lockdep_pin_lock(&rq
->lock
);
2571 task_rq_unlock(rq
, p
, &flags
);
2574 #ifdef CONFIG_PREEMPT_NOTIFIERS
2576 static struct static_key preempt_notifier_key
= STATIC_KEY_INIT_FALSE
;
2578 void preempt_notifier_inc(void)
2580 static_key_slow_inc(&preempt_notifier_key
);
2582 EXPORT_SYMBOL_GPL(preempt_notifier_inc
);
2584 void preempt_notifier_dec(void)
2586 static_key_slow_dec(&preempt_notifier_key
);
2588 EXPORT_SYMBOL_GPL(preempt_notifier_dec
);
2591 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2592 * @notifier: notifier struct to register
2594 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2596 if (!static_key_false(&preempt_notifier_key
))
2597 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2599 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2601 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2604 * preempt_notifier_unregister - no longer interested in preemption notifications
2605 * @notifier: notifier struct to unregister
2607 * This is *not* safe to call from within a preemption notifier.
2609 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2611 hlist_del(¬ifier
->link
);
2613 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2615 static void __fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2617 struct preempt_notifier
*notifier
;
2619 hlist_for_each_entry(notifier
, &curr
->preempt_notifiers
, link
)
2620 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2623 static __always_inline
void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2625 if (static_key_false(&preempt_notifier_key
))
2626 __fire_sched_in_preempt_notifiers(curr
);
2630 __fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2631 struct task_struct
*next
)
2633 struct preempt_notifier
*notifier
;
2635 hlist_for_each_entry(notifier
, &curr
->preempt_notifiers
, link
)
2636 notifier
->ops
->sched_out(notifier
, next
);
2639 static __always_inline
void
2640 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2641 struct task_struct
*next
)
2643 if (static_key_false(&preempt_notifier_key
))
2644 __fire_sched_out_preempt_notifiers(curr
, next
);
2647 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2649 static inline void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2654 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2655 struct task_struct
*next
)
2659 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2662 * prepare_task_switch - prepare to switch tasks
2663 * @rq: the runqueue preparing to switch
2664 * @prev: the current task that is being switched out
2665 * @next: the task we are going to switch to.
2667 * This is called with the rq lock held and interrupts off. It must
2668 * be paired with a subsequent finish_task_switch after the context
2671 * prepare_task_switch sets up locking and calls architecture specific
2675 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2676 struct task_struct
*next
)
2678 sched_info_switch(rq
, prev
, next
);
2679 perf_event_task_sched_out(prev
, next
);
2680 fire_sched_out_preempt_notifiers(prev
, next
);
2681 prepare_lock_switch(rq
, next
);
2682 prepare_arch_switch(next
);
2686 * finish_task_switch - clean up after a task-switch
2687 * @prev: the thread we just switched away from.
2689 * finish_task_switch must be called after the context switch, paired
2690 * with a prepare_task_switch call before the context switch.
2691 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2692 * and do any other architecture-specific cleanup actions.
2694 * Note that we may have delayed dropping an mm in context_switch(). If
2695 * so, we finish that here outside of the runqueue lock. (Doing it
2696 * with the lock held can cause deadlocks; see schedule() for
2699 * The context switch have flipped the stack from under us and restored the
2700 * local variables which were saved when this task called schedule() in the
2701 * past. prev == current is still correct but we need to recalculate this_rq
2702 * because prev may have moved to another CPU.
2704 static struct rq
*finish_task_switch(struct task_struct
*prev
)
2705 __releases(rq
->lock
)
2707 struct rq
*rq
= this_rq();
2708 struct mm_struct
*mm
= rq
->prev_mm
;
2712 * The previous task will have left us with a preempt_count of 2
2713 * because it left us after:
2716 * preempt_disable(); // 1
2718 * raw_spin_lock_irq(&rq->lock) // 2
2720 * Also, see FORK_PREEMPT_COUNT.
2722 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET
,
2723 "corrupted preempt_count: %s/%d/0x%x\n",
2724 current
->comm
, current
->pid
, preempt_count()))
2725 preempt_count_set(FORK_PREEMPT_COUNT
);
2730 * A task struct has one reference for the use as "current".
2731 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2732 * schedule one last time. The schedule call will never return, and
2733 * the scheduled task must drop that reference.
2735 * We must observe prev->state before clearing prev->on_cpu (in
2736 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2737 * running on another CPU and we could rave with its RUNNING -> DEAD
2738 * transition, resulting in a double drop.
2740 prev_state
= prev
->state
;
2741 vtime_task_switch(prev
);
2742 perf_event_task_sched_in(prev
, current
);
2743 finish_lock_switch(rq
, prev
);
2744 finish_arch_post_lock_switch();
2746 fire_sched_in_preempt_notifiers(current
);
2749 if (unlikely(prev_state
== TASK_DEAD
)) {
2750 if (prev
->sched_class
->task_dead
)
2751 prev
->sched_class
->task_dead(prev
);
2754 * Remove function-return probe instances associated with this
2755 * task and put them back on the free list.
2757 kprobe_flush_task(prev
);
2758 put_task_struct(prev
);
2761 tick_nohz_task_switch();
2767 /* rq->lock is NOT held, but preemption is disabled */
2768 static void __balance_callback(struct rq
*rq
)
2770 struct callback_head
*head
, *next
;
2771 void (*func
)(struct rq
*rq
);
2772 unsigned long flags
;
2774 raw_spin_lock_irqsave(&rq
->lock
, flags
);
2775 head
= rq
->balance_callback
;
2776 rq
->balance_callback
= NULL
;
2778 func
= (void (*)(struct rq
*))head
->func
;
2785 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
2788 static inline void balance_callback(struct rq
*rq
)
2790 if (unlikely(rq
->balance_callback
))
2791 __balance_callback(rq
);
2796 static inline void balance_callback(struct rq
*rq
)
2803 * schedule_tail - first thing a freshly forked thread must call.
2804 * @prev: the thread we just switched away from.
2806 asmlinkage __visible
void schedule_tail(struct task_struct
*prev
)
2807 __releases(rq
->lock
)
2812 * New tasks start with FORK_PREEMPT_COUNT, see there and
2813 * finish_task_switch() for details.
2815 * finish_task_switch() will drop rq->lock() and lower preempt_count
2816 * and the preempt_enable() will end up enabling preemption (on
2817 * PREEMPT_COUNT kernels).
2820 rq
= finish_task_switch(prev
);
2821 balance_callback(rq
);
2824 if (current
->set_child_tid
)
2825 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2829 * context_switch - switch to the new MM and the new thread's register state.
2831 static inline struct rq
*
2832 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2833 struct task_struct
*next
)
2835 struct mm_struct
*mm
, *oldmm
;
2837 prepare_task_switch(rq
, prev
, next
);
2840 oldmm
= prev
->active_mm
;
2842 * For paravirt, this is coupled with an exit in switch_to to
2843 * combine the page table reload and the switch backend into
2846 arch_start_context_switch(prev
);
2849 next
->active_mm
= oldmm
;
2850 atomic_inc(&oldmm
->mm_count
);
2851 enter_lazy_tlb(oldmm
, next
);
2853 switch_mm(oldmm
, mm
, next
);
2856 prev
->active_mm
= NULL
;
2857 rq
->prev_mm
= oldmm
;
2860 * Since the runqueue lock will be released by the next
2861 * task (which is an invalid locking op but in the case
2862 * of the scheduler it's an obvious special-case), so we
2863 * do an early lockdep release here:
2865 lockdep_unpin_lock(&rq
->lock
);
2866 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2868 /* Here we just switch the register state and the stack. */
2869 switch_to(prev
, next
, prev
);
2872 return finish_task_switch(prev
);
2876 * nr_running and nr_context_switches:
2878 * externally visible scheduler statistics: current number of runnable
2879 * threads, total number of context switches performed since bootup.
2881 unsigned long nr_running(void)
2883 unsigned long i
, sum
= 0;
2885 for_each_online_cpu(i
)
2886 sum
+= cpu_rq(i
)->nr_running
;
2892 * Check if only the current task is running on the cpu.
2894 * Caution: this function does not check that the caller has disabled
2895 * preemption, thus the result might have a time-of-check-to-time-of-use
2896 * race. The caller is responsible to use it correctly, for example:
2898 * - from a non-preemptable section (of course)
2900 * - from a thread that is bound to a single CPU
2902 * - in a loop with very short iterations (e.g. a polling loop)
2904 bool single_task_running(void)
2906 return raw_rq()->nr_running
== 1;
2908 EXPORT_SYMBOL(single_task_running
);
2910 unsigned long long nr_context_switches(void)
2913 unsigned long long sum
= 0;
2915 for_each_possible_cpu(i
)
2916 sum
+= cpu_rq(i
)->nr_switches
;
2921 unsigned long nr_iowait(void)
2923 unsigned long i
, sum
= 0;
2925 for_each_possible_cpu(i
)
2926 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2931 unsigned long nr_iowait_cpu(int cpu
)
2933 struct rq
*this = cpu_rq(cpu
);
2934 return atomic_read(&this->nr_iowait
);
2937 void get_iowait_load(unsigned long *nr_waiters
, unsigned long *load
)
2939 struct rq
*rq
= this_rq();
2940 *nr_waiters
= atomic_read(&rq
->nr_iowait
);
2941 *load
= rq
->load
.weight
;
2947 * sched_exec - execve() is a valuable balancing opportunity, because at
2948 * this point the task has the smallest effective memory and cache footprint.
2950 void sched_exec(void)
2952 struct task_struct
*p
= current
;
2953 unsigned long flags
;
2956 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
2957 dest_cpu
= p
->sched_class
->select_task_rq(p
, task_cpu(p
), SD_BALANCE_EXEC
, 0);
2958 if (dest_cpu
== smp_processor_id())
2961 if (likely(cpu_active(dest_cpu
))) {
2962 struct migration_arg arg
= { p
, dest_cpu
};
2964 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2965 stop_one_cpu(task_cpu(p
), migration_cpu_stop
, &arg
);
2969 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
2974 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
2975 DEFINE_PER_CPU(struct kernel_cpustat
, kernel_cpustat
);
2977 EXPORT_PER_CPU_SYMBOL(kstat
);
2978 EXPORT_PER_CPU_SYMBOL(kernel_cpustat
);
2981 * Return accounted runtime for the task.
2982 * In case the task is currently running, return the runtime plus current's
2983 * pending runtime that have not been accounted yet.
2985 unsigned long long task_sched_runtime(struct task_struct
*p
)
2987 unsigned long flags
;
2991 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
2993 * 64-bit doesn't need locks to atomically read a 64bit value.
2994 * So we have a optimization chance when the task's delta_exec is 0.
2995 * Reading ->on_cpu is racy, but this is ok.
2997 * If we race with it leaving cpu, we'll take a lock. So we're correct.
2998 * If we race with it entering cpu, unaccounted time is 0. This is
2999 * indistinguishable from the read occurring a few cycles earlier.
3000 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3001 * been accounted, so we're correct here as well.
3003 if (!p
->on_cpu
|| !task_on_rq_queued(p
))
3004 return p
->se
.sum_exec_runtime
;
3007 rq
= task_rq_lock(p
, &flags
);
3009 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3010 * project cycles that may never be accounted to this
3011 * thread, breaking clock_gettime().
3013 if (task_current(rq
, p
) && task_on_rq_queued(p
)) {
3014 update_rq_clock(rq
);
3015 p
->sched_class
->update_curr(rq
);
3017 ns
= p
->se
.sum_exec_runtime
;
3018 task_rq_unlock(rq
, p
, &flags
);
3024 * This function gets called by the timer code, with HZ frequency.
3025 * We call it with interrupts disabled.
3027 void scheduler_tick(void)
3029 int cpu
= smp_processor_id();
3030 struct rq
*rq
= cpu_rq(cpu
);
3031 struct task_struct
*curr
= rq
->curr
;
3035 raw_spin_lock(&rq
->lock
);
3036 update_rq_clock(rq
);
3037 curr
->sched_class
->task_tick(rq
, curr
, 0);
3038 update_cpu_load_active(rq
);
3039 calc_global_load_tick(rq
);
3040 raw_spin_unlock(&rq
->lock
);
3042 perf_event_task_tick();
3045 rq
->idle_balance
= idle_cpu(cpu
);
3046 trigger_load_balance(rq
);
3048 rq_last_tick_reset(rq
);
3051 #ifdef CONFIG_NO_HZ_FULL
3053 * scheduler_tick_max_deferment
3055 * Keep at least one tick per second when a single
3056 * active task is running because the scheduler doesn't
3057 * yet completely support full dynticks environment.
3059 * This makes sure that uptime, CFS vruntime, load
3060 * balancing, etc... continue to move forward, even
3061 * with a very low granularity.
3063 * Return: Maximum deferment in nanoseconds.
3065 u64
scheduler_tick_max_deferment(void)
3067 struct rq
*rq
= this_rq();
3068 unsigned long next
, now
= READ_ONCE(jiffies
);
3070 next
= rq
->last_sched_tick
+ HZ
;
3072 if (time_before_eq(next
, now
))
3075 return jiffies_to_nsecs(next
- now
);
3079 notrace
unsigned long get_parent_ip(unsigned long addr
)
3081 if (in_lock_functions(addr
)) {
3082 addr
= CALLER_ADDR2
;
3083 if (in_lock_functions(addr
))
3084 addr
= CALLER_ADDR3
;
3089 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3090 defined(CONFIG_PREEMPT_TRACER))
3092 void preempt_count_add(int val
)
3094 #ifdef CONFIG_DEBUG_PREEMPT
3098 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3101 __preempt_count_add(val
);
3102 #ifdef CONFIG_DEBUG_PREEMPT
3104 * Spinlock count overflowing soon?
3106 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
3109 if (preempt_count() == val
) {
3110 unsigned long ip
= get_parent_ip(CALLER_ADDR1
);
3111 #ifdef CONFIG_DEBUG_PREEMPT
3112 current
->preempt_disable_ip
= ip
;
3114 trace_preempt_off(CALLER_ADDR0
, ip
);
3117 EXPORT_SYMBOL(preempt_count_add
);
3118 NOKPROBE_SYMBOL(preempt_count_add
);
3120 void preempt_count_sub(int val
)
3122 #ifdef CONFIG_DEBUG_PREEMPT
3126 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3129 * Is the spinlock portion underflowing?
3131 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3132 !(preempt_count() & PREEMPT_MASK
)))
3136 if (preempt_count() == val
)
3137 trace_preempt_on(CALLER_ADDR0
, get_parent_ip(CALLER_ADDR1
));
3138 __preempt_count_sub(val
);
3140 EXPORT_SYMBOL(preempt_count_sub
);
3141 NOKPROBE_SYMBOL(preempt_count_sub
);
3146 * Print scheduling while atomic bug:
3148 static noinline
void __schedule_bug(struct task_struct
*prev
)
3150 if (oops_in_progress
)
3153 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
3154 prev
->comm
, prev
->pid
, preempt_count());
3156 debug_show_held_locks(prev
);
3158 if (irqs_disabled())
3159 print_irqtrace_events(prev
);
3160 #ifdef CONFIG_DEBUG_PREEMPT
3161 if (in_atomic_preempt_off()) {
3162 pr_err("Preemption disabled at:");
3163 print_ip_sym(current
->preempt_disable_ip
);
3168 add_taint(TAINT_WARN
, LOCKDEP_STILL_OK
);
3172 * Various schedule()-time debugging checks and statistics:
3174 static inline void schedule_debug(struct task_struct
*prev
)
3176 #ifdef CONFIG_SCHED_STACK_END_CHECK
3177 BUG_ON(task_stack_end_corrupted(prev
));
3180 if (unlikely(in_atomic_preempt_off())) {
3181 __schedule_bug(prev
);
3182 preempt_count_set(PREEMPT_DISABLED
);
3186 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3188 schedstat_inc(this_rq(), sched_count
);
3192 * Pick up the highest-prio task:
3194 static inline struct task_struct
*
3195 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
3197 const struct sched_class
*class = &fair_sched_class
;
3198 struct task_struct
*p
;
3201 * Optimization: we know that if all tasks are in
3202 * the fair class we can call that function directly:
3204 if (likely(prev
->sched_class
== class &&
3205 rq
->nr_running
== rq
->cfs
.h_nr_running
)) {
3206 p
= fair_sched_class
.pick_next_task(rq
, prev
);
3207 if (unlikely(p
== RETRY_TASK
))
3210 /* assumes fair_sched_class->next == idle_sched_class */
3212 p
= idle_sched_class
.pick_next_task(rq
, prev
);
3218 for_each_class(class) {
3219 p
= class->pick_next_task(rq
, prev
);
3221 if (unlikely(p
== RETRY_TASK
))
3227 BUG(); /* the idle class will always have a runnable task */
3231 * __schedule() is the main scheduler function.
3233 * The main means of driving the scheduler and thus entering this function are:
3235 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3237 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3238 * paths. For example, see arch/x86/entry_64.S.
3240 * To drive preemption between tasks, the scheduler sets the flag in timer
3241 * interrupt handler scheduler_tick().
3243 * 3. Wakeups don't really cause entry into schedule(). They add a
3244 * task to the run-queue and that's it.
3246 * Now, if the new task added to the run-queue preempts the current
3247 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3248 * called on the nearest possible occasion:
3250 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3252 * - in syscall or exception context, at the next outmost
3253 * preempt_enable(). (this might be as soon as the wake_up()'s
3256 * - in IRQ context, return from interrupt-handler to
3257 * preemptible context
3259 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3262 * - cond_resched() call
3263 * - explicit schedule() call
3264 * - return from syscall or exception to user-space
3265 * - return from interrupt-handler to user-space
3267 * WARNING: must be called with preemption disabled!
3269 static void __sched notrace
__schedule(bool preempt
)
3271 struct task_struct
*prev
, *next
;
3272 unsigned long *switch_count
;
3276 cpu
= smp_processor_id();
3281 * do_exit() calls schedule() with preemption disabled as an exception;
3282 * however we must fix that up, otherwise the next task will see an
3283 * inconsistent (higher) preempt count.
3285 * It also avoids the below schedule_debug() test from complaining
3288 if (unlikely(prev
->state
== TASK_DEAD
))
3289 preempt_enable_no_resched_notrace();
3291 schedule_debug(prev
);
3293 if (sched_feat(HRTICK
))
3296 local_irq_disable();
3297 rcu_note_context_switch();
3300 * Make sure that signal_pending_state()->signal_pending() below
3301 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3302 * done by the caller to avoid the race with signal_wake_up().
3304 smp_mb__before_spinlock();
3305 raw_spin_lock(&rq
->lock
);
3306 lockdep_pin_lock(&rq
->lock
);
3308 rq
->clock_skip_update
<<= 1; /* promote REQ to ACT */
3310 switch_count
= &prev
->nivcsw
;
3311 if (!preempt
&& prev
->state
) {
3312 if (unlikely(signal_pending_state(prev
->state
, prev
))) {
3313 prev
->state
= TASK_RUNNING
;
3315 deactivate_task(rq
, prev
, DEQUEUE_SLEEP
);
3319 * If a worker went to sleep, notify and ask workqueue
3320 * whether it wants to wake up a task to maintain
3323 if (prev
->flags
& PF_WQ_WORKER
) {
3324 struct task_struct
*to_wakeup
;
3326 to_wakeup
= wq_worker_sleeping(prev
, cpu
);
3328 try_to_wake_up_local(to_wakeup
);
3331 switch_count
= &prev
->nvcsw
;
3334 if (task_on_rq_queued(prev
))
3335 update_rq_clock(rq
);
3337 next
= pick_next_task(rq
, prev
);
3338 clear_tsk_need_resched(prev
);
3339 clear_preempt_need_resched();
3340 rq
->clock_skip_update
= 0;
3342 if (likely(prev
!= next
)) {
3347 trace_sched_switch(preempt
, prev
, next
);
3348 rq
= context_switch(rq
, prev
, next
); /* unlocks the rq */
3351 lockdep_unpin_lock(&rq
->lock
);
3352 raw_spin_unlock_irq(&rq
->lock
);
3355 balance_callback(rq
);
3358 static inline void sched_submit_work(struct task_struct
*tsk
)
3360 if (!tsk
->state
|| tsk_is_pi_blocked(tsk
))
3363 * If we are going to sleep and we have plugged IO queued,
3364 * make sure to submit it to avoid deadlocks.
3366 if (blk_needs_flush_plug(tsk
))
3367 blk_schedule_flush_plug(tsk
);
3370 asmlinkage __visible
void __sched
schedule(void)
3372 struct task_struct
*tsk
= current
;
3374 sched_submit_work(tsk
);
3378 sched_preempt_enable_no_resched();
3379 } while (need_resched());
3381 EXPORT_SYMBOL(schedule
);
3383 #ifdef CONFIG_CONTEXT_TRACKING
3384 asmlinkage __visible
void __sched
schedule_user(void)
3387 * If we come here after a random call to set_need_resched(),
3388 * or we have been woken up remotely but the IPI has not yet arrived,
3389 * we haven't yet exited the RCU idle mode. Do it here manually until
3390 * we find a better solution.
3392 * NB: There are buggy callers of this function. Ideally we
3393 * should warn if prev_state != CONTEXT_USER, but that will trigger
3394 * too frequently to make sense yet.
3396 enum ctx_state prev_state
= exception_enter();
3398 exception_exit(prev_state
);
3403 * schedule_preempt_disabled - called with preemption disabled
3405 * Returns with preemption disabled. Note: preempt_count must be 1
3407 void __sched
schedule_preempt_disabled(void)
3409 sched_preempt_enable_no_resched();
3414 static void __sched notrace
preempt_schedule_common(void)
3417 preempt_disable_notrace();
3419 preempt_enable_no_resched_notrace();
3422 * Check again in case we missed a preemption opportunity
3423 * between schedule and now.
3425 } while (need_resched());
3428 #ifdef CONFIG_PREEMPT
3430 * this is the entry point to schedule() from in-kernel preemption
3431 * off of preempt_enable. Kernel preemptions off return from interrupt
3432 * occur there and call schedule directly.
3434 asmlinkage __visible
void __sched notrace
preempt_schedule(void)
3437 * If there is a non-zero preempt_count or interrupts are disabled,
3438 * we do not want to preempt the current task. Just return..
3440 if (likely(!preemptible()))
3443 preempt_schedule_common();
3445 NOKPROBE_SYMBOL(preempt_schedule
);
3446 EXPORT_SYMBOL(preempt_schedule
);
3449 * preempt_schedule_notrace - preempt_schedule called by tracing
3451 * The tracing infrastructure uses preempt_enable_notrace to prevent
3452 * recursion and tracing preempt enabling caused by the tracing
3453 * infrastructure itself. But as tracing can happen in areas coming
3454 * from userspace or just about to enter userspace, a preempt enable
3455 * can occur before user_exit() is called. This will cause the scheduler
3456 * to be called when the system is still in usermode.
3458 * To prevent this, the preempt_enable_notrace will use this function
3459 * instead of preempt_schedule() to exit user context if needed before
3460 * calling the scheduler.
3462 asmlinkage __visible
void __sched notrace
preempt_schedule_notrace(void)
3464 enum ctx_state prev_ctx
;
3466 if (likely(!preemptible()))
3470 preempt_disable_notrace();
3472 * Needs preempt disabled in case user_exit() is traced
3473 * and the tracer calls preempt_enable_notrace() causing
3474 * an infinite recursion.
3476 prev_ctx
= exception_enter();
3478 exception_exit(prev_ctx
);
3480 preempt_enable_no_resched_notrace();
3481 } while (need_resched());
3483 EXPORT_SYMBOL_GPL(preempt_schedule_notrace
);
3485 #endif /* CONFIG_PREEMPT */
3488 * this is the entry point to schedule() from kernel preemption
3489 * off of irq context.
3490 * Note, that this is called and return with irqs disabled. This will
3491 * protect us against recursive calling from irq.
3493 asmlinkage __visible
void __sched
preempt_schedule_irq(void)
3495 enum ctx_state prev_state
;
3497 /* Catch callers which need to be fixed */
3498 BUG_ON(preempt_count() || !irqs_disabled());
3500 prev_state
= exception_enter();
3506 local_irq_disable();
3507 sched_preempt_enable_no_resched();
3508 } while (need_resched());
3510 exception_exit(prev_state
);
3513 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int wake_flags
,
3516 return try_to_wake_up(curr
->private, mode
, wake_flags
);
3518 EXPORT_SYMBOL(default_wake_function
);
3520 #ifdef CONFIG_RT_MUTEXES
3523 * rt_mutex_setprio - set the current priority of a task
3525 * @prio: prio value (kernel-internal form)
3527 * This function changes the 'effective' priority of a task. It does
3528 * not touch ->normal_prio like __setscheduler().
3530 * Used by the rt_mutex code to implement priority inheritance
3531 * logic. Call site only calls if the priority of the task changed.
3533 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
3535 int oldprio
, queued
, running
, enqueue_flag
= ENQUEUE_RESTORE
;
3537 const struct sched_class
*prev_class
;
3539 BUG_ON(prio
> MAX_PRIO
);
3541 rq
= __task_rq_lock(p
);
3544 * Idle task boosting is a nono in general. There is one
3545 * exception, when PREEMPT_RT and NOHZ is active:
3547 * The idle task calls get_next_timer_interrupt() and holds
3548 * the timer wheel base->lock on the CPU and another CPU wants
3549 * to access the timer (probably to cancel it). We can safely
3550 * ignore the boosting request, as the idle CPU runs this code
3551 * with interrupts disabled and will complete the lock
3552 * protected section without being interrupted. So there is no
3553 * real need to boost.
3555 if (unlikely(p
== rq
->idle
)) {
3556 WARN_ON(p
!= rq
->curr
);
3557 WARN_ON(p
->pi_blocked_on
);
3561 trace_sched_pi_setprio(p
, prio
);
3563 prev_class
= p
->sched_class
;
3564 queued
= task_on_rq_queued(p
);
3565 running
= task_current(rq
, p
);
3567 dequeue_task(rq
, p
, DEQUEUE_SAVE
);
3569 put_prev_task(rq
, p
);
3572 * Boosting condition are:
3573 * 1. -rt task is running and holds mutex A
3574 * --> -dl task blocks on mutex A
3576 * 2. -dl task is running and holds mutex A
3577 * --> -dl task blocks on mutex A and could preempt the
3580 if (dl_prio(prio
)) {
3581 struct task_struct
*pi_task
= rt_mutex_get_top_task(p
);
3582 if (!dl_prio(p
->normal_prio
) ||
3583 (pi_task
&& dl_entity_preempt(&pi_task
->dl
, &p
->dl
))) {
3584 p
->dl
.dl_boosted
= 1;
3585 enqueue_flag
|= ENQUEUE_REPLENISH
;
3587 p
->dl
.dl_boosted
= 0;
3588 p
->sched_class
= &dl_sched_class
;
3589 } else if (rt_prio(prio
)) {
3590 if (dl_prio(oldprio
))
3591 p
->dl
.dl_boosted
= 0;
3593 enqueue_flag
|= ENQUEUE_HEAD
;
3594 p
->sched_class
= &rt_sched_class
;
3596 if (dl_prio(oldprio
))
3597 p
->dl
.dl_boosted
= 0;
3598 if (rt_prio(oldprio
))
3600 p
->sched_class
= &fair_sched_class
;
3606 p
->sched_class
->set_curr_task(rq
);
3608 enqueue_task(rq
, p
, enqueue_flag
);
3610 check_class_changed(rq
, p
, prev_class
, oldprio
);
3612 preempt_disable(); /* avoid rq from going away on us */
3613 __task_rq_unlock(rq
);
3615 balance_callback(rq
);
3620 void set_user_nice(struct task_struct
*p
, long nice
)
3622 int old_prio
, delta
, queued
;
3623 unsigned long flags
;
3626 if (task_nice(p
) == nice
|| nice
< MIN_NICE
|| nice
> MAX_NICE
)
3629 * We have to be careful, if called from sys_setpriority(),
3630 * the task might be in the middle of scheduling on another CPU.
3632 rq
= task_rq_lock(p
, &flags
);
3634 * The RT priorities are set via sched_setscheduler(), but we still
3635 * allow the 'normal' nice value to be set - but as expected
3636 * it wont have any effect on scheduling until the task is
3637 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3639 if (task_has_dl_policy(p
) || task_has_rt_policy(p
)) {
3640 p
->static_prio
= NICE_TO_PRIO(nice
);
3643 queued
= task_on_rq_queued(p
);
3645 dequeue_task(rq
, p
, DEQUEUE_SAVE
);
3647 p
->static_prio
= NICE_TO_PRIO(nice
);
3650 p
->prio
= effective_prio(p
);
3651 delta
= p
->prio
- old_prio
;
3654 enqueue_task(rq
, p
, ENQUEUE_RESTORE
);
3656 * If the task increased its priority or is running and
3657 * lowered its priority, then reschedule its CPU:
3659 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
3663 task_rq_unlock(rq
, p
, &flags
);
3665 EXPORT_SYMBOL(set_user_nice
);
3668 * can_nice - check if a task can reduce its nice value
3672 int can_nice(const struct task_struct
*p
, const int nice
)
3674 /* convert nice value [19,-20] to rlimit style value [1,40] */
3675 int nice_rlim
= nice_to_rlimit(nice
);
3677 return (nice_rlim
<= task_rlimit(p
, RLIMIT_NICE
) ||
3678 capable(CAP_SYS_NICE
));
3681 #ifdef __ARCH_WANT_SYS_NICE
3684 * sys_nice - change the priority of the current process.
3685 * @increment: priority increment
3687 * sys_setpriority is a more generic, but much slower function that
3688 * does similar things.
3690 SYSCALL_DEFINE1(nice
, int, increment
)
3695 * Setpriority might change our priority at the same moment.
3696 * We don't have to worry. Conceptually one call occurs first
3697 * and we have a single winner.
3699 increment
= clamp(increment
, -NICE_WIDTH
, NICE_WIDTH
);
3700 nice
= task_nice(current
) + increment
;
3702 nice
= clamp_val(nice
, MIN_NICE
, MAX_NICE
);
3703 if (increment
< 0 && !can_nice(current
, nice
))
3706 retval
= security_task_setnice(current
, nice
);
3710 set_user_nice(current
, nice
);
3717 * task_prio - return the priority value of a given task.
3718 * @p: the task in question.
3720 * Return: The priority value as seen by users in /proc.
3721 * RT tasks are offset by -200. Normal tasks are centered
3722 * around 0, value goes from -16 to +15.
3724 int task_prio(const struct task_struct
*p
)
3726 return p
->prio
- MAX_RT_PRIO
;
3730 * idle_cpu - is a given cpu idle currently?
3731 * @cpu: the processor in question.
3733 * Return: 1 if the CPU is currently idle. 0 otherwise.
3735 int idle_cpu(int cpu
)
3737 struct rq
*rq
= cpu_rq(cpu
);
3739 if (rq
->curr
!= rq
->idle
)
3746 if (!llist_empty(&rq
->wake_list
))
3754 * idle_task - return the idle task for a given cpu.
3755 * @cpu: the processor in question.
3757 * Return: The idle task for the cpu @cpu.
3759 struct task_struct
*idle_task(int cpu
)
3761 return cpu_rq(cpu
)->idle
;
3765 * find_process_by_pid - find a process with a matching PID value.
3766 * @pid: the pid in question.
3768 * The task of @pid, if found. %NULL otherwise.
3770 static struct task_struct
*find_process_by_pid(pid_t pid
)
3772 return pid
? find_task_by_vpid(pid
) : current
;
3776 * This function initializes the sched_dl_entity of a newly becoming
3777 * SCHED_DEADLINE task.
3779 * Only the static values are considered here, the actual runtime and the
3780 * absolute deadline will be properly calculated when the task is enqueued
3781 * for the first time with its new policy.
3784 __setparam_dl(struct task_struct
*p
, const struct sched_attr
*attr
)
3786 struct sched_dl_entity
*dl_se
= &p
->dl
;
3788 dl_se
->dl_runtime
= attr
->sched_runtime
;
3789 dl_se
->dl_deadline
= attr
->sched_deadline
;
3790 dl_se
->dl_period
= attr
->sched_period
?: dl_se
->dl_deadline
;
3791 dl_se
->flags
= attr
->sched_flags
;
3792 dl_se
->dl_bw
= to_ratio(dl_se
->dl_period
, dl_se
->dl_runtime
);
3795 * Changing the parameters of a task is 'tricky' and we're not doing
3796 * the correct thing -- also see task_dead_dl() and switched_from_dl().
3798 * What we SHOULD do is delay the bandwidth release until the 0-lag
3799 * point. This would include retaining the task_struct until that time
3800 * and change dl_overflow() to not immediately decrement the current
3803 * Instead we retain the current runtime/deadline and let the new
3804 * parameters take effect after the current reservation period lapses.
3805 * This is safe (albeit pessimistic) because the 0-lag point is always
3806 * before the current scheduling deadline.
3808 * We can still have temporary overloads because we do not delay the
3809 * change in bandwidth until that time; so admission control is
3810 * not on the safe side. It does however guarantee tasks will never
3811 * consume more than promised.
3816 * sched_setparam() passes in -1 for its policy, to let the functions
3817 * it calls know not to change it.
3819 #define SETPARAM_POLICY -1
3821 static void __setscheduler_params(struct task_struct
*p
,
3822 const struct sched_attr
*attr
)
3824 int policy
= attr
->sched_policy
;
3826 if (policy
== SETPARAM_POLICY
)
3831 if (dl_policy(policy
))
3832 __setparam_dl(p
, attr
);
3833 else if (fair_policy(policy
))
3834 p
->static_prio
= NICE_TO_PRIO(attr
->sched_nice
);
3837 * __sched_setscheduler() ensures attr->sched_priority == 0 when
3838 * !rt_policy. Always setting this ensures that things like
3839 * getparam()/getattr() don't report silly values for !rt tasks.
3841 p
->rt_priority
= attr
->sched_priority
;
3842 p
->normal_prio
= normal_prio(p
);
3846 /* Actually do priority change: must hold pi & rq lock. */
3847 static void __setscheduler(struct rq
*rq
, struct task_struct
*p
,
3848 const struct sched_attr
*attr
, bool keep_boost
)
3850 __setscheduler_params(p
, attr
);
3853 * Keep a potential priority boosting if called from
3854 * sched_setscheduler().
3857 p
->prio
= rt_mutex_get_effective_prio(p
, normal_prio(p
));
3859 p
->prio
= normal_prio(p
);
3861 if (dl_prio(p
->prio
))
3862 p
->sched_class
= &dl_sched_class
;
3863 else if (rt_prio(p
->prio
))
3864 p
->sched_class
= &rt_sched_class
;
3866 p
->sched_class
= &fair_sched_class
;
3870 __getparam_dl(struct task_struct
*p
, struct sched_attr
*attr
)
3872 struct sched_dl_entity
*dl_se
= &p
->dl
;
3874 attr
->sched_priority
= p
->rt_priority
;
3875 attr
->sched_runtime
= dl_se
->dl_runtime
;
3876 attr
->sched_deadline
= dl_se
->dl_deadline
;
3877 attr
->sched_period
= dl_se
->dl_period
;
3878 attr
->sched_flags
= dl_se
->flags
;
3882 * This function validates the new parameters of a -deadline task.
3883 * We ask for the deadline not being zero, and greater or equal
3884 * than the runtime, as well as the period of being zero or
3885 * greater than deadline. Furthermore, we have to be sure that
3886 * user parameters are above the internal resolution of 1us (we
3887 * check sched_runtime only since it is always the smaller one) and
3888 * below 2^63 ns (we have to check both sched_deadline and
3889 * sched_period, as the latter can be zero).
3892 __checkparam_dl(const struct sched_attr
*attr
)
3895 if (attr
->sched_deadline
== 0)
3899 * Since we truncate DL_SCALE bits, make sure we're at least
3902 if (attr
->sched_runtime
< (1ULL << DL_SCALE
))
3906 * Since we use the MSB for wrap-around and sign issues, make
3907 * sure it's not set (mind that period can be equal to zero).
3909 if (attr
->sched_deadline
& (1ULL << 63) ||
3910 attr
->sched_period
& (1ULL << 63))
3913 /* runtime <= deadline <= period (if period != 0) */
3914 if ((attr
->sched_period
!= 0 &&
3915 attr
->sched_period
< attr
->sched_deadline
) ||
3916 attr
->sched_deadline
< attr
->sched_runtime
)
3923 * check the target process has a UID that matches the current process's
3925 static bool check_same_owner(struct task_struct
*p
)
3927 const struct cred
*cred
= current_cred(), *pcred
;
3931 pcred
= __task_cred(p
);
3932 match
= (uid_eq(cred
->euid
, pcred
->euid
) ||
3933 uid_eq(cred
->euid
, pcred
->uid
));
3938 static bool dl_param_changed(struct task_struct
*p
,
3939 const struct sched_attr
*attr
)
3941 struct sched_dl_entity
*dl_se
= &p
->dl
;
3943 if (dl_se
->dl_runtime
!= attr
->sched_runtime
||
3944 dl_se
->dl_deadline
!= attr
->sched_deadline
||
3945 dl_se
->dl_period
!= attr
->sched_period
||
3946 dl_se
->flags
!= attr
->sched_flags
)
3952 static int __sched_setscheduler(struct task_struct
*p
,
3953 const struct sched_attr
*attr
,
3956 int newprio
= dl_policy(attr
->sched_policy
) ? MAX_DL_PRIO
- 1 :
3957 MAX_RT_PRIO
- 1 - attr
->sched_priority
;
3958 int retval
, oldprio
, oldpolicy
= -1, queued
, running
;
3959 int new_effective_prio
, policy
= attr
->sched_policy
;
3960 unsigned long flags
;
3961 const struct sched_class
*prev_class
;
3965 /* may grab non-irq protected spin_locks */
3966 BUG_ON(in_interrupt());
3968 /* double check policy once rq lock held */
3970 reset_on_fork
= p
->sched_reset_on_fork
;
3971 policy
= oldpolicy
= p
->policy
;
3973 reset_on_fork
= !!(attr
->sched_flags
& SCHED_FLAG_RESET_ON_FORK
);
3975 if (!valid_policy(policy
))
3979 if (attr
->sched_flags
& ~(SCHED_FLAG_RESET_ON_FORK
))
3983 * Valid priorities for SCHED_FIFO and SCHED_RR are
3984 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
3985 * SCHED_BATCH and SCHED_IDLE is 0.
3987 if ((p
->mm
&& attr
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
3988 (!p
->mm
&& attr
->sched_priority
> MAX_RT_PRIO
-1))
3990 if ((dl_policy(policy
) && !__checkparam_dl(attr
)) ||
3991 (rt_policy(policy
) != (attr
->sched_priority
!= 0)))
3995 * Allow unprivileged RT tasks to decrease priority:
3997 if (user
&& !capable(CAP_SYS_NICE
)) {
3998 if (fair_policy(policy
)) {
3999 if (attr
->sched_nice
< task_nice(p
) &&
4000 !can_nice(p
, attr
->sched_nice
))
4004 if (rt_policy(policy
)) {
4005 unsigned long rlim_rtprio
=
4006 task_rlimit(p
, RLIMIT_RTPRIO
);
4008 /* can't set/change the rt policy */
4009 if (policy
!= p
->policy
&& !rlim_rtprio
)
4012 /* can't increase priority */
4013 if (attr
->sched_priority
> p
->rt_priority
&&
4014 attr
->sched_priority
> rlim_rtprio
)
4019 * Can't set/change SCHED_DEADLINE policy at all for now
4020 * (safest behavior); in the future we would like to allow
4021 * unprivileged DL tasks to increase their relative deadline
4022 * or reduce their runtime (both ways reducing utilization)
4024 if (dl_policy(policy
))
4028 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4029 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4031 if (idle_policy(p
->policy
) && !idle_policy(policy
)) {
4032 if (!can_nice(p
, task_nice(p
)))
4036 /* can't change other user's priorities */
4037 if (!check_same_owner(p
))
4040 /* Normal users shall not reset the sched_reset_on_fork flag */
4041 if (p
->sched_reset_on_fork
&& !reset_on_fork
)
4046 retval
= security_task_setscheduler(p
);
4052 * make sure no PI-waiters arrive (or leave) while we are
4053 * changing the priority of the task:
4055 * To be able to change p->policy safely, the appropriate
4056 * runqueue lock must be held.
4058 rq
= task_rq_lock(p
, &flags
);
4061 * Changing the policy of the stop threads its a very bad idea
4063 if (p
== rq
->stop
) {
4064 task_rq_unlock(rq
, p
, &flags
);
4069 * If not changing anything there's no need to proceed further,
4070 * but store a possible modification of reset_on_fork.
4072 if (unlikely(policy
== p
->policy
)) {
4073 if (fair_policy(policy
) && attr
->sched_nice
!= task_nice(p
))
4075 if (rt_policy(policy
) && attr
->sched_priority
!= p
->rt_priority
)
4077 if (dl_policy(policy
) && dl_param_changed(p
, attr
))
4080 p
->sched_reset_on_fork
= reset_on_fork
;
4081 task_rq_unlock(rq
, p
, &flags
);
4087 #ifdef CONFIG_RT_GROUP_SCHED
4089 * Do not allow realtime tasks into groups that have no runtime
4092 if (rt_bandwidth_enabled() && rt_policy(policy
) &&
4093 task_group(p
)->rt_bandwidth
.rt_runtime
== 0 &&
4094 !task_group_is_autogroup(task_group(p
))) {
4095 task_rq_unlock(rq
, p
, &flags
);
4100 if (dl_bandwidth_enabled() && dl_policy(policy
)) {
4101 cpumask_t
*span
= rq
->rd
->span
;
4104 * Don't allow tasks with an affinity mask smaller than
4105 * the entire root_domain to become SCHED_DEADLINE. We
4106 * will also fail if there's no bandwidth available.
4108 if (!cpumask_subset(span
, &p
->cpus_allowed
) ||
4109 rq
->rd
->dl_bw
.bw
== 0) {
4110 task_rq_unlock(rq
, p
, &flags
);
4117 /* recheck policy now with rq lock held */
4118 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4119 policy
= oldpolicy
= -1;
4120 task_rq_unlock(rq
, p
, &flags
);
4125 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4126 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4129 if ((dl_policy(policy
) || dl_task(p
)) && dl_overflow(p
, policy
, attr
)) {
4130 task_rq_unlock(rq
, p
, &flags
);
4134 p
->sched_reset_on_fork
= reset_on_fork
;
4139 * Take priority boosted tasks into account. If the new
4140 * effective priority is unchanged, we just store the new
4141 * normal parameters and do not touch the scheduler class and
4142 * the runqueue. This will be done when the task deboost
4145 new_effective_prio
= rt_mutex_get_effective_prio(p
, newprio
);
4146 if (new_effective_prio
== oldprio
) {
4147 __setscheduler_params(p
, attr
);
4148 task_rq_unlock(rq
, p
, &flags
);
4153 queued
= task_on_rq_queued(p
);
4154 running
= task_current(rq
, p
);
4156 dequeue_task(rq
, p
, DEQUEUE_SAVE
);
4158 put_prev_task(rq
, p
);
4160 prev_class
= p
->sched_class
;
4161 __setscheduler(rq
, p
, attr
, pi
);
4164 p
->sched_class
->set_curr_task(rq
);
4166 int enqueue_flags
= ENQUEUE_RESTORE
;
4168 * We enqueue to tail when the priority of a task is
4169 * increased (user space view).
4171 if (oldprio
<= p
->prio
)
4172 enqueue_flags
|= ENQUEUE_HEAD
;
4174 enqueue_task(rq
, p
, enqueue_flags
);
4177 check_class_changed(rq
, p
, prev_class
, oldprio
);
4178 preempt_disable(); /* avoid rq from going away on us */
4179 task_rq_unlock(rq
, p
, &flags
);
4182 rt_mutex_adjust_pi(p
);
4185 * Run balance callbacks after we've adjusted the PI chain.
4187 balance_callback(rq
);
4193 static int _sched_setscheduler(struct task_struct
*p
, int policy
,
4194 const struct sched_param
*param
, bool check
)
4196 struct sched_attr attr
= {
4197 .sched_policy
= policy
,
4198 .sched_priority
= param
->sched_priority
,
4199 .sched_nice
= PRIO_TO_NICE(p
->static_prio
),
4202 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4203 if ((policy
!= SETPARAM_POLICY
) && (policy
& SCHED_RESET_ON_FORK
)) {
4204 attr
.sched_flags
|= SCHED_FLAG_RESET_ON_FORK
;
4205 policy
&= ~SCHED_RESET_ON_FORK
;
4206 attr
.sched_policy
= policy
;
4209 return __sched_setscheduler(p
, &attr
, check
, true);
4212 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4213 * @p: the task in question.
4214 * @policy: new policy.
4215 * @param: structure containing the new RT priority.
4217 * Return: 0 on success. An error code otherwise.
4219 * NOTE that the task may be already dead.
4221 int sched_setscheduler(struct task_struct
*p
, int policy
,
4222 const struct sched_param
*param
)
4224 return _sched_setscheduler(p
, policy
, param
, true);
4226 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4228 int sched_setattr(struct task_struct
*p
, const struct sched_attr
*attr
)
4230 return __sched_setscheduler(p
, attr
, true, true);
4232 EXPORT_SYMBOL_GPL(sched_setattr
);
4235 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4236 * @p: the task in question.
4237 * @policy: new policy.
4238 * @param: structure containing the new RT priority.
4240 * Just like sched_setscheduler, only don't bother checking if the
4241 * current context has permission. For example, this is needed in
4242 * stop_machine(): we create temporary high priority worker threads,
4243 * but our caller might not have that capability.
4245 * Return: 0 on success. An error code otherwise.
4247 int sched_setscheduler_nocheck(struct task_struct
*p
, int policy
,
4248 const struct sched_param
*param
)
4250 return _sched_setscheduler(p
, policy
, param
, false);
4252 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck
);
4255 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4257 struct sched_param lparam
;
4258 struct task_struct
*p
;
4261 if (!param
|| pid
< 0)
4263 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4268 p
= find_process_by_pid(pid
);
4270 retval
= sched_setscheduler(p
, policy
, &lparam
);
4277 * Mimics kernel/events/core.c perf_copy_attr().
4279 static int sched_copy_attr(struct sched_attr __user
*uattr
,
4280 struct sched_attr
*attr
)
4285 if (!access_ok(VERIFY_WRITE
, uattr
, SCHED_ATTR_SIZE_VER0
))
4289 * zero the full structure, so that a short copy will be nice.
4291 memset(attr
, 0, sizeof(*attr
));
4293 ret
= get_user(size
, &uattr
->size
);
4297 if (size
> PAGE_SIZE
) /* silly large */
4300 if (!size
) /* abi compat */
4301 size
= SCHED_ATTR_SIZE_VER0
;
4303 if (size
< SCHED_ATTR_SIZE_VER0
)
4307 * If we're handed a bigger struct than we know of,
4308 * ensure all the unknown bits are 0 - i.e. new
4309 * user-space does not rely on any kernel feature
4310 * extensions we dont know about yet.
4312 if (size
> sizeof(*attr
)) {
4313 unsigned char __user
*addr
;
4314 unsigned char __user
*end
;
4317 addr
= (void __user
*)uattr
+ sizeof(*attr
);
4318 end
= (void __user
*)uattr
+ size
;
4320 for (; addr
< end
; addr
++) {
4321 ret
= get_user(val
, addr
);
4327 size
= sizeof(*attr
);
4330 ret
= copy_from_user(attr
, uattr
, size
);
4335 * XXX: do we want to be lenient like existing syscalls; or do we want
4336 * to be strict and return an error on out-of-bounds values?
4338 attr
->sched_nice
= clamp(attr
->sched_nice
, MIN_NICE
, MAX_NICE
);
4343 put_user(sizeof(*attr
), &uattr
->size
);
4348 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4349 * @pid: the pid in question.
4350 * @policy: new policy.
4351 * @param: structure containing the new RT priority.
4353 * Return: 0 on success. An error code otherwise.
4355 SYSCALL_DEFINE3(sched_setscheduler
, pid_t
, pid
, int, policy
,
4356 struct sched_param __user
*, param
)
4358 /* negative values for policy are not valid */
4362 return do_sched_setscheduler(pid
, policy
, param
);
4366 * sys_sched_setparam - set/change the RT priority of a thread
4367 * @pid: the pid in question.
4368 * @param: structure containing the new RT priority.
4370 * Return: 0 on success. An error code otherwise.
4372 SYSCALL_DEFINE2(sched_setparam
, pid_t
, pid
, struct sched_param __user
*, param
)
4374 return do_sched_setscheduler(pid
, SETPARAM_POLICY
, param
);
4378 * sys_sched_setattr - same as above, but with extended sched_attr
4379 * @pid: the pid in question.
4380 * @uattr: structure containing the extended parameters.
4381 * @flags: for future extension.
4383 SYSCALL_DEFINE3(sched_setattr
, pid_t
, pid
, struct sched_attr __user
*, uattr
,
4384 unsigned int, flags
)
4386 struct sched_attr attr
;
4387 struct task_struct
*p
;
4390 if (!uattr
|| pid
< 0 || flags
)
4393 retval
= sched_copy_attr(uattr
, &attr
);
4397 if ((int)attr
.sched_policy
< 0)
4402 p
= find_process_by_pid(pid
);
4404 retval
= sched_setattr(p
, &attr
);
4411 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4412 * @pid: the pid in question.
4414 * Return: On success, the policy of the thread. Otherwise, a negative error
4417 SYSCALL_DEFINE1(sched_getscheduler
, pid_t
, pid
)
4419 struct task_struct
*p
;
4427 p
= find_process_by_pid(pid
);
4429 retval
= security_task_getscheduler(p
);
4432 | (p
->sched_reset_on_fork
? SCHED_RESET_ON_FORK
: 0);
4439 * sys_sched_getparam - get the RT priority of a thread
4440 * @pid: the pid in question.
4441 * @param: structure containing the RT priority.
4443 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4446 SYSCALL_DEFINE2(sched_getparam
, pid_t
, pid
, struct sched_param __user
*, param
)
4448 struct sched_param lp
= { .sched_priority
= 0 };
4449 struct task_struct
*p
;
4452 if (!param
|| pid
< 0)
4456 p
= find_process_by_pid(pid
);
4461 retval
= security_task_getscheduler(p
);
4465 if (task_has_rt_policy(p
))
4466 lp
.sched_priority
= p
->rt_priority
;
4470 * This one might sleep, we cannot do it with a spinlock held ...
4472 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4481 static int sched_read_attr(struct sched_attr __user
*uattr
,
4482 struct sched_attr
*attr
,
4487 if (!access_ok(VERIFY_WRITE
, uattr
, usize
))
4491 * If we're handed a smaller struct than we know of,
4492 * ensure all the unknown bits are 0 - i.e. old
4493 * user-space does not get uncomplete information.
4495 if (usize
< sizeof(*attr
)) {
4496 unsigned char *addr
;
4499 addr
= (void *)attr
+ usize
;
4500 end
= (void *)attr
+ sizeof(*attr
);
4502 for (; addr
< end
; addr
++) {
4510 ret
= copy_to_user(uattr
, attr
, attr
->size
);
4518 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4519 * @pid: the pid in question.
4520 * @uattr: structure containing the extended parameters.
4521 * @size: sizeof(attr) for fwd/bwd comp.
4522 * @flags: for future extension.
4524 SYSCALL_DEFINE4(sched_getattr
, pid_t
, pid
, struct sched_attr __user
*, uattr
,
4525 unsigned int, size
, unsigned int, flags
)
4527 struct sched_attr attr
= {
4528 .size
= sizeof(struct sched_attr
),
4530 struct task_struct
*p
;
4533 if (!uattr
|| pid
< 0 || size
> PAGE_SIZE
||
4534 size
< SCHED_ATTR_SIZE_VER0
|| flags
)
4538 p
= find_process_by_pid(pid
);
4543 retval
= security_task_getscheduler(p
);
4547 attr
.sched_policy
= p
->policy
;
4548 if (p
->sched_reset_on_fork
)
4549 attr
.sched_flags
|= SCHED_FLAG_RESET_ON_FORK
;
4550 if (task_has_dl_policy(p
))
4551 __getparam_dl(p
, &attr
);
4552 else if (task_has_rt_policy(p
))
4553 attr
.sched_priority
= p
->rt_priority
;
4555 attr
.sched_nice
= task_nice(p
);
4559 retval
= sched_read_attr(uattr
, &attr
, size
);
4567 long sched_setaffinity(pid_t pid
, const struct cpumask
*in_mask
)
4569 cpumask_var_t cpus_allowed
, new_mask
;
4570 struct task_struct
*p
;
4575 p
= find_process_by_pid(pid
);
4581 /* Prevent p going away */
4585 if (p
->flags
& PF_NO_SETAFFINITY
) {
4589 if (!alloc_cpumask_var(&cpus_allowed
, GFP_KERNEL
)) {
4593 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
)) {
4595 goto out_free_cpus_allowed
;
4598 if (!check_same_owner(p
)) {
4600 if (!ns_capable(__task_cred(p
)->user_ns
, CAP_SYS_NICE
)) {
4602 goto out_free_new_mask
;
4607 retval
= security_task_setscheduler(p
);
4609 goto out_free_new_mask
;
4612 cpuset_cpus_allowed(p
, cpus_allowed
);
4613 cpumask_and(new_mask
, in_mask
, cpus_allowed
);
4616 * Since bandwidth control happens on root_domain basis,
4617 * if admission test is enabled, we only admit -deadline
4618 * tasks allowed to run on all the CPUs in the task's
4622 if (task_has_dl_policy(p
) && dl_bandwidth_enabled()) {
4624 if (!cpumask_subset(task_rq(p
)->rd
->span
, new_mask
)) {
4627 goto out_free_new_mask
;
4633 retval
= __set_cpus_allowed_ptr(p
, new_mask
, true);
4636 cpuset_cpus_allowed(p
, cpus_allowed
);
4637 if (!cpumask_subset(new_mask
, cpus_allowed
)) {
4639 * We must have raced with a concurrent cpuset
4640 * update. Just reset the cpus_allowed to the
4641 * cpuset's cpus_allowed
4643 cpumask_copy(new_mask
, cpus_allowed
);
4648 free_cpumask_var(new_mask
);
4649 out_free_cpus_allowed
:
4650 free_cpumask_var(cpus_allowed
);
4656 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4657 struct cpumask
*new_mask
)
4659 if (len
< cpumask_size())
4660 cpumask_clear(new_mask
);
4661 else if (len
> cpumask_size())
4662 len
= cpumask_size();
4664 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4668 * sys_sched_setaffinity - set the cpu affinity of a process
4669 * @pid: pid of the process
4670 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4671 * @user_mask_ptr: user-space pointer to the new cpu mask
4673 * Return: 0 on success. An error code otherwise.
4675 SYSCALL_DEFINE3(sched_setaffinity
, pid_t
, pid
, unsigned int, len
,
4676 unsigned long __user
*, user_mask_ptr
)
4678 cpumask_var_t new_mask
;
4681 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
))
4684 retval
= get_user_cpu_mask(user_mask_ptr
, len
, new_mask
);
4686 retval
= sched_setaffinity(pid
, new_mask
);
4687 free_cpumask_var(new_mask
);
4691 long sched_getaffinity(pid_t pid
, struct cpumask
*mask
)
4693 struct task_struct
*p
;
4694 unsigned long flags
;
4700 p
= find_process_by_pid(pid
);
4704 retval
= security_task_getscheduler(p
);
4708 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
4709 cpumask_and(mask
, &p
->cpus_allowed
, cpu_active_mask
);
4710 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4719 * sys_sched_getaffinity - get the cpu affinity of a process
4720 * @pid: pid of the process
4721 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4722 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4724 * Return: 0 on success. An error code otherwise.
4726 SYSCALL_DEFINE3(sched_getaffinity
, pid_t
, pid
, unsigned int, len
,
4727 unsigned long __user
*, user_mask_ptr
)
4732 if ((len
* BITS_PER_BYTE
) < nr_cpu_ids
)
4734 if (len
& (sizeof(unsigned long)-1))
4737 if (!alloc_cpumask_var(&mask
, GFP_KERNEL
))
4740 ret
= sched_getaffinity(pid
, mask
);
4742 size_t retlen
= min_t(size_t, len
, cpumask_size());
4744 if (copy_to_user(user_mask_ptr
, mask
, retlen
))
4749 free_cpumask_var(mask
);
4755 * sys_sched_yield - yield the current processor to other threads.
4757 * This function yields the current CPU to other tasks. If there are no
4758 * other threads running on this CPU then this function will return.
4762 SYSCALL_DEFINE0(sched_yield
)
4764 struct rq
*rq
= this_rq_lock();
4766 schedstat_inc(rq
, yld_count
);
4767 current
->sched_class
->yield_task(rq
);
4770 * Since we are going to call schedule() anyway, there's
4771 * no need to preempt or enable interrupts:
4773 __release(rq
->lock
);
4774 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
4775 do_raw_spin_unlock(&rq
->lock
);
4776 sched_preempt_enable_no_resched();
4783 int __sched
_cond_resched(void)
4785 if (should_resched(0)) {
4786 preempt_schedule_common();
4791 EXPORT_SYMBOL(_cond_resched
);
4794 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4795 * call schedule, and on return reacquire the lock.
4797 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4798 * operations here to prevent schedule() from being called twice (once via
4799 * spin_unlock(), once by hand).
4801 int __cond_resched_lock(spinlock_t
*lock
)
4803 int resched
= should_resched(PREEMPT_LOCK_OFFSET
);
4806 lockdep_assert_held(lock
);
4808 if (spin_needbreak(lock
) || resched
) {
4811 preempt_schedule_common();
4819 EXPORT_SYMBOL(__cond_resched_lock
);
4821 int __sched
__cond_resched_softirq(void)
4823 BUG_ON(!in_softirq());
4825 if (should_resched(SOFTIRQ_DISABLE_OFFSET
)) {
4827 preempt_schedule_common();
4833 EXPORT_SYMBOL(__cond_resched_softirq
);
4836 * yield - yield the current processor to other threads.
4838 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4840 * The scheduler is at all times free to pick the calling task as the most
4841 * eligible task to run, if removing the yield() call from your code breaks
4842 * it, its already broken.
4844 * Typical broken usage is:
4849 * where one assumes that yield() will let 'the other' process run that will
4850 * make event true. If the current task is a SCHED_FIFO task that will never
4851 * happen. Never use yield() as a progress guarantee!!
4853 * If you want to use yield() to wait for something, use wait_event().
4854 * If you want to use yield() to be 'nice' for others, use cond_resched().
4855 * If you still want to use yield(), do not!
4857 void __sched
yield(void)
4859 set_current_state(TASK_RUNNING
);
4862 EXPORT_SYMBOL(yield
);
4865 * yield_to - yield the current processor to another thread in
4866 * your thread group, or accelerate that thread toward the
4867 * processor it's on.
4869 * @preempt: whether task preemption is allowed or not
4871 * It's the caller's job to ensure that the target task struct
4872 * can't go away on us before we can do any checks.
4875 * true (>0) if we indeed boosted the target task.
4876 * false (0) if we failed to boost the target.
4877 * -ESRCH if there's no task to yield to.
4879 int __sched
yield_to(struct task_struct
*p
, bool preempt
)
4881 struct task_struct
*curr
= current
;
4882 struct rq
*rq
, *p_rq
;
4883 unsigned long flags
;
4886 local_irq_save(flags
);
4892 * If we're the only runnable task on the rq and target rq also
4893 * has only one task, there's absolutely no point in yielding.
4895 if (rq
->nr_running
== 1 && p_rq
->nr_running
== 1) {
4900 double_rq_lock(rq
, p_rq
);
4901 if (task_rq(p
) != p_rq
) {
4902 double_rq_unlock(rq
, p_rq
);
4906 if (!curr
->sched_class
->yield_to_task
)
4909 if (curr
->sched_class
!= p
->sched_class
)
4912 if (task_running(p_rq
, p
) || p
->state
)
4915 yielded
= curr
->sched_class
->yield_to_task(rq
, p
, preempt
);
4917 schedstat_inc(rq
, yld_count
);
4919 * Make p's CPU reschedule; pick_next_entity takes care of
4922 if (preempt
&& rq
!= p_rq
)
4927 double_rq_unlock(rq
, p_rq
);
4929 local_irq_restore(flags
);
4936 EXPORT_SYMBOL_GPL(yield_to
);
4939 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4940 * that process accounting knows that this is a task in IO wait state.
4942 long __sched
io_schedule_timeout(long timeout
)
4944 int old_iowait
= current
->in_iowait
;
4948 current
->in_iowait
= 1;
4949 blk_schedule_flush_plug(current
);
4951 delayacct_blkio_start();
4953 atomic_inc(&rq
->nr_iowait
);
4954 ret
= schedule_timeout(timeout
);
4955 current
->in_iowait
= old_iowait
;
4956 atomic_dec(&rq
->nr_iowait
);
4957 delayacct_blkio_end();
4961 EXPORT_SYMBOL(io_schedule_timeout
);
4964 * sys_sched_get_priority_max - return maximum RT priority.
4965 * @policy: scheduling class.
4967 * Return: On success, this syscall returns the maximum
4968 * rt_priority that can be used by a given scheduling class.
4969 * On failure, a negative error code is returned.
4971 SYSCALL_DEFINE1(sched_get_priority_max
, int, policy
)
4978 ret
= MAX_USER_RT_PRIO
-1;
4980 case SCHED_DEADLINE
:
4991 * sys_sched_get_priority_min - return minimum RT priority.
4992 * @policy: scheduling class.
4994 * Return: On success, this syscall returns the minimum
4995 * rt_priority that can be used by a given scheduling class.
4996 * On failure, a negative error code is returned.
4998 SYSCALL_DEFINE1(sched_get_priority_min
, int, policy
)
5007 case SCHED_DEADLINE
:
5017 * sys_sched_rr_get_interval - return the default timeslice of a process.
5018 * @pid: pid of the process.
5019 * @interval: userspace pointer to the timeslice value.
5021 * this syscall writes the default timeslice value of a given process
5022 * into the user-space timespec buffer. A value of '0' means infinity.
5024 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5027 SYSCALL_DEFINE2(sched_rr_get_interval
, pid_t
, pid
,
5028 struct timespec __user
*, interval
)
5030 struct task_struct
*p
;
5031 unsigned int time_slice
;
5032 unsigned long flags
;
5042 p
= find_process_by_pid(pid
);
5046 retval
= security_task_getscheduler(p
);
5050 rq
= task_rq_lock(p
, &flags
);
5052 if (p
->sched_class
->get_rr_interval
)
5053 time_slice
= p
->sched_class
->get_rr_interval(rq
, p
);
5054 task_rq_unlock(rq
, p
, &flags
);
5057 jiffies_to_timespec(time_slice
, &t
);
5058 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5066 static const char stat_nam
[] = TASK_STATE_TO_CHAR_STR
;
5068 void sched_show_task(struct task_struct
*p
)
5070 unsigned long free
= 0;
5072 unsigned long state
= p
->state
;
5075 state
= __ffs(state
) + 1;
5076 printk(KERN_INFO
"%-15.15s %c", p
->comm
,
5077 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5078 #if BITS_PER_LONG == 32
5079 if (state
== TASK_RUNNING
)
5080 printk(KERN_CONT
" running ");
5082 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5084 if (state
== TASK_RUNNING
)
5085 printk(KERN_CONT
" running task ");
5087 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5089 #ifdef CONFIG_DEBUG_STACK_USAGE
5090 free
= stack_not_used(p
);
5095 ppid
= task_pid_nr(rcu_dereference(p
->real_parent
));
5097 printk(KERN_CONT
"%5lu %5d %6d 0x%08lx\n", free
,
5098 task_pid_nr(p
), ppid
,
5099 (unsigned long)task_thread_info(p
)->flags
);
5101 print_worker_info(KERN_INFO
, p
);
5102 show_stack(p
, NULL
);
5105 void show_state_filter(unsigned long state_filter
)
5107 struct task_struct
*g
, *p
;
5109 #if BITS_PER_LONG == 32
5111 " task PC stack pid father\n");
5114 " task PC stack pid father\n");
5117 for_each_process_thread(g
, p
) {
5119 * reset the NMI-timeout, listing all files on a slow
5120 * console might take a lot of time:
5122 touch_nmi_watchdog();
5123 if (!state_filter
|| (p
->state
& state_filter
))
5127 touch_all_softlockup_watchdogs();
5129 #ifdef CONFIG_SCHED_DEBUG
5130 sysrq_sched_debug_show();
5134 * Only show locks if all tasks are dumped:
5137 debug_show_all_locks();
5140 void init_idle_bootup_task(struct task_struct
*idle
)
5142 idle
->sched_class
= &idle_sched_class
;
5146 * init_idle - set up an idle thread for a given CPU
5147 * @idle: task in question
5148 * @cpu: cpu the idle task belongs to
5150 * NOTE: this function does not set the idle thread's NEED_RESCHED
5151 * flag, to make booting more robust.
5153 void init_idle(struct task_struct
*idle
, int cpu
)
5155 struct rq
*rq
= cpu_rq(cpu
);
5156 unsigned long flags
;
5158 raw_spin_lock_irqsave(&idle
->pi_lock
, flags
);
5159 raw_spin_lock(&rq
->lock
);
5161 __sched_fork(0, idle
);
5162 idle
->state
= TASK_RUNNING
;
5163 idle
->se
.exec_start
= sched_clock();
5167 * Its possible that init_idle() gets called multiple times on a task,
5168 * in that case do_set_cpus_allowed() will not do the right thing.
5170 * And since this is boot we can forgo the serialization.
5172 set_cpus_allowed_common(idle
, cpumask_of(cpu
));
5175 * We're having a chicken and egg problem, even though we are
5176 * holding rq->lock, the cpu isn't yet set to this cpu so the
5177 * lockdep check in task_group() will fail.
5179 * Similar case to sched_fork(). / Alternatively we could
5180 * use task_rq_lock() here and obtain the other rq->lock.
5185 __set_task_cpu(idle
, cpu
);
5188 rq
->curr
= rq
->idle
= idle
;
5189 idle
->on_rq
= TASK_ON_RQ_QUEUED
;
5193 raw_spin_unlock(&rq
->lock
);
5194 raw_spin_unlock_irqrestore(&idle
->pi_lock
, flags
);
5196 /* Set the preempt count _outside_ the spinlocks! */
5197 init_idle_preempt_count(idle
, cpu
);
5200 * The idle tasks have their own, simple scheduling class:
5202 idle
->sched_class
= &idle_sched_class
;
5203 ftrace_graph_init_idle_task(idle
, cpu
);
5204 vtime_init_idle(idle
, cpu
);
5206 sprintf(idle
->comm
, "%s/%d", INIT_TASK_COMM
, cpu
);
5210 int cpuset_cpumask_can_shrink(const struct cpumask
*cur
,
5211 const struct cpumask
*trial
)
5213 int ret
= 1, trial_cpus
;
5214 struct dl_bw
*cur_dl_b
;
5215 unsigned long flags
;
5217 if (!cpumask_weight(cur
))
5220 rcu_read_lock_sched();
5221 cur_dl_b
= dl_bw_of(cpumask_any(cur
));
5222 trial_cpus
= cpumask_weight(trial
);
5224 raw_spin_lock_irqsave(&cur_dl_b
->lock
, flags
);
5225 if (cur_dl_b
->bw
!= -1 &&
5226 cur_dl_b
->bw
* trial_cpus
< cur_dl_b
->total_bw
)
5228 raw_spin_unlock_irqrestore(&cur_dl_b
->lock
, flags
);
5229 rcu_read_unlock_sched();
5234 int task_can_attach(struct task_struct
*p
,
5235 const struct cpumask
*cs_cpus_allowed
)
5240 * Kthreads which disallow setaffinity shouldn't be moved
5241 * to a new cpuset; we don't want to change their cpu
5242 * affinity and isolating such threads by their set of
5243 * allowed nodes is unnecessary. Thus, cpusets are not
5244 * applicable for such threads. This prevents checking for
5245 * success of set_cpus_allowed_ptr() on all attached tasks
5246 * before cpus_allowed may be changed.
5248 if (p
->flags
& PF_NO_SETAFFINITY
) {
5254 if (dl_task(p
) && !cpumask_intersects(task_rq(p
)->rd
->span
,
5256 unsigned int dest_cpu
= cpumask_any_and(cpu_active_mask
,
5261 unsigned long flags
;
5263 rcu_read_lock_sched();
5264 dl_b
= dl_bw_of(dest_cpu
);
5265 raw_spin_lock_irqsave(&dl_b
->lock
, flags
);
5266 cpus
= dl_bw_cpus(dest_cpu
);
5267 overflow
= __dl_overflow(dl_b
, cpus
, 0, p
->dl
.dl_bw
);
5272 * We reserve space for this task in the destination
5273 * root_domain, as we can't fail after this point.
5274 * We will free resources in the source root_domain
5275 * later on (see set_cpus_allowed_dl()).
5277 __dl_add(dl_b
, p
->dl
.dl_bw
);
5279 raw_spin_unlock_irqrestore(&dl_b
->lock
, flags
);
5280 rcu_read_unlock_sched();
5290 #ifdef CONFIG_NUMA_BALANCING
5291 /* Migrate current task p to target_cpu */
5292 int migrate_task_to(struct task_struct
*p
, int target_cpu
)
5294 struct migration_arg arg
= { p
, target_cpu
};
5295 int curr_cpu
= task_cpu(p
);
5297 if (curr_cpu
== target_cpu
)
5300 if (!cpumask_test_cpu(target_cpu
, tsk_cpus_allowed(p
)))
5303 /* TODO: This is not properly updating schedstats */
5305 trace_sched_move_numa(p
, curr_cpu
, target_cpu
);
5306 return stop_one_cpu(curr_cpu
, migration_cpu_stop
, &arg
);
5310 * Requeue a task on a given node and accurately track the number of NUMA
5311 * tasks on the runqueues
5313 void sched_setnuma(struct task_struct
*p
, int nid
)
5316 unsigned long flags
;
5317 bool queued
, running
;
5319 rq
= task_rq_lock(p
, &flags
);
5320 queued
= task_on_rq_queued(p
);
5321 running
= task_current(rq
, p
);
5324 dequeue_task(rq
, p
, DEQUEUE_SAVE
);
5326 put_prev_task(rq
, p
);
5328 p
->numa_preferred_nid
= nid
;
5331 p
->sched_class
->set_curr_task(rq
);
5333 enqueue_task(rq
, p
, ENQUEUE_RESTORE
);
5334 task_rq_unlock(rq
, p
, &flags
);
5336 #endif /* CONFIG_NUMA_BALANCING */
5338 #ifdef CONFIG_HOTPLUG_CPU
5340 * Ensures that the idle task is using init_mm right before its cpu goes
5343 void idle_task_exit(void)
5345 struct mm_struct
*mm
= current
->active_mm
;
5347 BUG_ON(cpu_online(smp_processor_id()));
5349 if (mm
!= &init_mm
) {
5350 switch_mm(mm
, &init_mm
, current
);
5351 finish_arch_post_lock_switch();
5357 * Since this CPU is going 'away' for a while, fold any nr_active delta
5358 * we might have. Assumes we're called after migrate_tasks() so that the
5359 * nr_active count is stable.
5361 * Also see the comment "Global load-average calculations".
5363 static void calc_load_migrate(struct rq
*rq
)
5365 long delta
= calc_load_fold_active(rq
);
5367 atomic_long_add(delta
, &calc_load_tasks
);
5370 static void put_prev_task_fake(struct rq
*rq
, struct task_struct
*prev
)
5374 static const struct sched_class fake_sched_class
= {
5375 .put_prev_task
= put_prev_task_fake
,
5378 static struct task_struct fake_task
= {
5380 * Avoid pull_{rt,dl}_task()
5382 .prio
= MAX_PRIO
+ 1,
5383 .sched_class
= &fake_sched_class
,
5387 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5388 * try_to_wake_up()->select_task_rq().
5390 * Called with rq->lock held even though we'er in stop_machine() and
5391 * there's no concurrency possible, we hold the required locks anyway
5392 * because of lock validation efforts.
5394 static void migrate_tasks(struct rq
*dead_rq
)
5396 struct rq
*rq
= dead_rq
;
5397 struct task_struct
*next
, *stop
= rq
->stop
;
5401 * Fudge the rq selection such that the below task selection loop
5402 * doesn't get stuck on the currently eligible stop task.
5404 * We're currently inside stop_machine() and the rq is either stuck
5405 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5406 * either way we should never end up calling schedule() until we're
5412 * put_prev_task() and pick_next_task() sched
5413 * class method both need to have an up-to-date
5414 * value of rq->clock[_task]
5416 update_rq_clock(rq
);
5420 * There's this thread running, bail when that's the only
5423 if (rq
->nr_running
== 1)
5427 * pick_next_task assumes pinned rq->lock.
5429 lockdep_pin_lock(&rq
->lock
);
5430 next
= pick_next_task(rq
, &fake_task
);
5432 next
->sched_class
->put_prev_task(rq
, next
);
5435 * Rules for changing task_struct::cpus_allowed are holding
5436 * both pi_lock and rq->lock, such that holding either
5437 * stabilizes the mask.
5439 * Drop rq->lock is not quite as disastrous as it usually is
5440 * because !cpu_active at this point, which means load-balance
5441 * will not interfere. Also, stop-machine.
5443 lockdep_unpin_lock(&rq
->lock
);
5444 raw_spin_unlock(&rq
->lock
);
5445 raw_spin_lock(&next
->pi_lock
);
5446 raw_spin_lock(&rq
->lock
);
5449 * Since we're inside stop-machine, _nothing_ should have
5450 * changed the task, WARN if weird stuff happened, because in
5451 * that case the above rq->lock drop is a fail too.
5453 if (WARN_ON(task_rq(next
) != rq
|| !task_on_rq_queued(next
))) {
5454 raw_spin_unlock(&next
->pi_lock
);
5458 /* Find suitable destination for @next, with force if needed. */
5459 dest_cpu
= select_fallback_rq(dead_rq
->cpu
, next
);
5461 rq
= __migrate_task(rq
, next
, dest_cpu
);
5462 if (rq
!= dead_rq
) {
5463 raw_spin_unlock(&rq
->lock
);
5465 raw_spin_lock(&rq
->lock
);
5467 raw_spin_unlock(&next
->pi_lock
);
5472 #endif /* CONFIG_HOTPLUG_CPU */
5474 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5476 static struct ctl_table sd_ctl_dir
[] = {
5478 .procname
= "sched_domain",
5484 static struct ctl_table sd_ctl_root
[] = {
5486 .procname
= "kernel",
5488 .child
= sd_ctl_dir
,
5493 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
5495 struct ctl_table
*entry
=
5496 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
5501 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
5503 struct ctl_table
*entry
;
5506 * In the intermediate directories, both the child directory and
5507 * procname are dynamically allocated and could fail but the mode
5508 * will always be set. In the lowest directory the names are
5509 * static strings and all have proc handlers.
5511 for (entry
= *tablep
; entry
->mode
; entry
++) {
5513 sd_free_ctl_entry(&entry
->child
);
5514 if (entry
->proc_handler
== NULL
)
5515 kfree(entry
->procname
);
5522 static int min_load_idx
= 0;
5523 static int max_load_idx
= CPU_LOAD_IDX_MAX
-1;
5526 set_table_entry(struct ctl_table
*entry
,
5527 const char *procname
, void *data
, int maxlen
,
5528 umode_t mode
, proc_handler
*proc_handler
,
5531 entry
->procname
= procname
;
5533 entry
->maxlen
= maxlen
;
5535 entry
->proc_handler
= proc_handler
;
5538 entry
->extra1
= &min_load_idx
;
5539 entry
->extra2
= &max_load_idx
;
5543 static struct ctl_table
*
5544 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
5546 struct ctl_table
*table
= sd_alloc_ctl_entry(14);
5551 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
5552 sizeof(long), 0644, proc_doulongvec_minmax
, false);
5553 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
5554 sizeof(long), 0644, proc_doulongvec_minmax
, false);
5555 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
5556 sizeof(int), 0644, proc_dointvec_minmax
, true);
5557 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
5558 sizeof(int), 0644, proc_dointvec_minmax
, true);
5559 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
5560 sizeof(int), 0644, proc_dointvec_minmax
, true);
5561 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
5562 sizeof(int), 0644, proc_dointvec_minmax
, true);
5563 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
5564 sizeof(int), 0644, proc_dointvec_minmax
, true);
5565 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
5566 sizeof(int), 0644, proc_dointvec_minmax
, false);
5567 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
5568 sizeof(int), 0644, proc_dointvec_minmax
, false);
5569 set_table_entry(&table
[9], "cache_nice_tries",
5570 &sd
->cache_nice_tries
,
5571 sizeof(int), 0644, proc_dointvec_minmax
, false);
5572 set_table_entry(&table
[10], "flags", &sd
->flags
,
5573 sizeof(int), 0644, proc_dointvec_minmax
, false);
5574 set_table_entry(&table
[11], "max_newidle_lb_cost",
5575 &sd
->max_newidle_lb_cost
,
5576 sizeof(long), 0644, proc_doulongvec_minmax
, false);
5577 set_table_entry(&table
[12], "name", sd
->name
,
5578 CORENAME_MAX_SIZE
, 0444, proc_dostring
, false);
5579 /* &table[13] is terminator */
5584 static struct ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
5586 struct ctl_table
*entry
, *table
;
5587 struct sched_domain
*sd
;
5588 int domain_num
= 0, i
;
5591 for_each_domain(cpu
, sd
)
5593 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
5598 for_each_domain(cpu
, sd
) {
5599 snprintf(buf
, 32, "domain%d", i
);
5600 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5602 entry
->child
= sd_alloc_ctl_domain_table(sd
);
5609 static struct ctl_table_header
*sd_sysctl_header
;
5610 static void register_sched_domain_sysctl(void)
5612 int i
, cpu_num
= num_possible_cpus();
5613 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
5616 WARN_ON(sd_ctl_dir
[0].child
);
5617 sd_ctl_dir
[0].child
= entry
;
5622 for_each_possible_cpu(i
) {
5623 snprintf(buf
, 32, "cpu%d", i
);
5624 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5626 entry
->child
= sd_alloc_ctl_cpu_table(i
);
5630 WARN_ON(sd_sysctl_header
);
5631 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
5634 /* may be called multiple times per register */
5635 static void unregister_sched_domain_sysctl(void)
5637 unregister_sysctl_table(sd_sysctl_header
);
5638 sd_sysctl_header
= NULL
;
5639 if (sd_ctl_dir
[0].child
)
5640 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
5643 static void register_sched_domain_sysctl(void)
5646 static void unregister_sched_domain_sysctl(void)
5649 #endif /* CONFIG_SCHED_DEBUG && CONFIG_SYSCTL */
5651 static void set_rq_online(struct rq
*rq
)
5654 const struct sched_class
*class;
5656 cpumask_set_cpu(rq
->cpu
, rq
->rd
->online
);
5659 for_each_class(class) {
5660 if (class->rq_online
)
5661 class->rq_online(rq
);
5666 static void set_rq_offline(struct rq
*rq
)
5669 const struct sched_class
*class;
5671 for_each_class(class) {
5672 if (class->rq_offline
)
5673 class->rq_offline(rq
);
5676 cpumask_clear_cpu(rq
->cpu
, rq
->rd
->online
);
5682 * migration_call - callback that gets triggered when a CPU is added.
5683 * Here we can start up the necessary migration thread for the new CPU.
5686 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
5688 int cpu
= (long)hcpu
;
5689 unsigned long flags
;
5690 struct rq
*rq
= cpu_rq(cpu
);
5692 switch (action
& ~CPU_TASKS_FROZEN
) {
5694 case CPU_UP_PREPARE
:
5695 rq
->calc_load_update
= calc_load_update
;
5699 /* Update our root-domain */
5700 raw_spin_lock_irqsave(&rq
->lock
, flags
);
5702 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
5706 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
5709 #ifdef CONFIG_HOTPLUG_CPU
5711 sched_ttwu_pending();
5712 /* Update our root-domain */
5713 raw_spin_lock_irqsave(&rq
->lock
, flags
);
5715 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
5719 BUG_ON(rq
->nr_running
!= 1); /* the migration thread */
5720 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
5724 calc_load_migrate(rq
);
5729 update_max_interval();
5735 * Register at high priority so that task migration (migrate_all_tasks)
5736 * happens before everything else. This has to be lower priority than
5737 * the notifier in the perf_event subsystem, though.
5739 static struct notifier_block migration_notifier
= {
5740 .notifier_call
= migration_call
,
5741 .priority
= CPU_PRI_MIGRATION
,
5744 static void set_cpu_rq_start_time(void)
5746 int cpu
= smp_processor_id();
5747 struct rq
*rq
= cpu_rq(cpu
);
5748 rq
->age_stamp
= sched_clock_cpu(cpu
);
5751 static int sched_cpu_active(struct notifier_block
*nfb
,
5752 unsigned long action
, void *hcpu
)
5754 int cpu
= (long)hcpu
;
5756 switch (action
& ~CPU_TASKS_FROZEN
) {
5758 set_cpu_rq_start_time();
5763 * At this point a starting CPU has marked itself as online via
5764 * set_cpu_online(). But it might not yet have marked itself
5765 * as active, which is essential from here on.
5767 set_cpu_active(cpu
, true);
5768 stop_machine_unpark(cpu
);
5771 case CPU_DOWN_FAILED
:
5772 set_cpu_active(cpu
, true);
5780 static int sched_cpu_inactive(struct notifier_block
*nfb
,
5781 unsigned long action
, void *hcpu
)
5783 switch (action
& ~CPU_TASKS_FROZEN
) {
5784 case CPU_DOWN_PREPARE
:
5785 set_cpu_active((long)hcpu
, false);
5792 static int __init
migration_init(void)
5794 void *cpu
= (void *)(long)smp_processor_id();
5797 /* Initialize migration for the boot CPU */
5798 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
5799 BUG_ON(err
== NOTIFY_BAD
);
5800 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
5801 register_cpu_notifier(&migration_notifier
);
5803 /* Register cpu active notifiers */
5804 cpu_notifier(sched_cpu_active
, CPU_PRI_SCHED_ACTIVE
);
5805 cpu_notifier(sched_cpu_inactive
, CPU_PRI_SCHED_INACTIVE
);
5809 early_initcall(migration_init
);
5811 static cpumask_var_t sched_domains_tmpmask
; /* sched_domains_mutex */
5813 #ifdef CONFIG_SCHED_DEBUG
5815 static __read_mostly
int sched_debug_enabled
;
5817 static int __init
sched_debug_setup(char *str
)
5819 sched_debug_enabled
= 1;
5823 early_param("sched_debug", sched_debug_setup
);
5825 static inline bool sched_debug(void)
5827 return sched_debug_enabled
;
5830 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
,
5831 struct cpumask
*groupmask
)
5833 struct sched_group
*group
= sd
->groups
;
5835 cpumask_clear(groupmask
);
5837 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
5839 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
5840 printk("does not load-balance\n");
5842 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
5847 printk(KERN_CONT
"span %*pbl level %s\n",
5848 cpumask_pr_args(sched_domain_span(sd
)), sd
->name
);
5850 if (!cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
5851 printk(KERN_ERR
"ERROR: domain->span does not contain "
5854 if (!cpumask_test_cpu(cpu
, sched_group_cpus(group
))) {
5855 printk(KERN_ERR
"ERROR: domain->groups does not contain"
5859 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
5863 printk(KERN_ERR
"ERROR: group is NULL\n");
5867 if (!cpumask_weight(sched_group_cpus(group
))) {
5868 printk(KERN_CONT
"\n");
5869 printk(KERN_ERR
"ERROR: empty group\n");
5873 if (!(sd
->flags
& SD_OVERLAP
) &&
5874 cpumask_intersects(groupmask
, sched_group_cpus(group
))) {
5875 printk(KERN_CONT
"\n");
5876 printk(KERN_ERR
"ERROR: repeated CPUs\n");
5880 cpumask_or(groupmask
, groupmask
, sched_group_cpus(group
));
5882 printk(KERN_CONT
" %*pbl",
5883 cpumask_pr_args(sched_group_cpus(group
)));
5884 if (group
->sgc
->capacity
!= SCHED_CAPACITY_SCALE
) {
5885 printk(KERN_CONT
" (cpu_capacity = %d)",
5886 group
->sgc
->capacity
);
5889 group
= group
->next
;
5890 } while (group
!= sd
->groups
);
5891 printk(KERN_CONT
"\n");
5893 if (!cpumask_equal(sched_domain_span(sd
), groupmask
))
5894 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
5897 !cpumask_subset(groupmask
, sched_domain_span(sd
->parent
)))
5898 printk(KERN_ERR
"ERROR: parent span is not a superset "
5899 "of domain->span\n");
5903 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
5907 if (!sched_debug_enabled
)
5911 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
5915 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
5918 if (sched_domain_debug_one(sd
, cpu
, level
, sched_domains_tmpmask
))
5926 #else /* !CONFIG_SCHED_DEBUG */
5927 # define sched_domain_debug(sd, cpu) do { } while (0)
5928 static inline bool sched_debug(void)
5932 #endif /* CONFIG_SCHED_DEBUG */
5934 static int sd_degenerate(struct sched_domain
*sd
)
5936 if (cpumask_weight(sched_domain_span(sd
)) == 1)
5939 /* Following flags need at least 2 groups */
5940 if (sd
->flags
& (SD_LOAD_BALANCE
|
5941 SD_BALANCE_NEWIDLE
|
5944 SD_SHARE_CPUCAPACITY
|
5945 SD_SHARE_PKG_RESOURCES
|
5946 SD_SHARE_POWERDOMAIN
)) {
5947 if (sd
->groups
!= sd
->groups
->next
)
5951 /* Following flags don't use groups */
5952 if (sd
->flags
& (SD_WAKE_AFFINE
))
5959 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
5961 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
5963 if (sd_degenerate(parent
))
5966 if (!cpumask_equal(sched_domain_span(sd
), sched_domain_span(parent
)))
5969 /* Flags needing groups don't count if only 1 group in parent */
5970 if (parent
->groups
== parent
->groups
->next
) {
5971 pflags
&= ~(SD_LOAD_BALANCE
|
5972 SD_BALANCE_NEWIDLE
|
5975 SD_SHARE_CPUCAPACITY
|
5976 SD_SHARE_PKG_RESOURCES
|
5978 SD_SHARE_POWERDOMAIN
);
5979 if (nr_node_ids
== 1)
5980 pflags
&= ~SD_SERIALIZE
;
5982 if (~cflags
& pflags
)
5988 static void free_rootdomain(struct rcu_head
*rcu
)
5990 struct root_domain
*rd
= container_of(rcu
, struct root_domain
, rcu
);
5992 cpupri_cleanup(&rd
->cpupri
);
5993 cpudl_cleanup(&rd
->cpudl
);
5994 free_cpumask_var(rd
->dlo_mask
);
5995 free_cpumask_var(rd
->rto_mask
);
5996 free_cpumask_var(rd
->online
);
5997 free_cpumask_var(rd
->span
);
6001 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6003 struct root_domain
*old_rd
= NULL
;
6004 unsigned long flags
;
6006 raw_spin_lock_irqsave(&rq
->lock
, flags
);
6011 if (cpumask_test_cpu(rq
->cpu
, old_rd
->online
))
6014 cpumask_clear_cpu(rq
->cpu
, old_rd
->span
);
6017 * If we dont want to free the old_rd yet then
6018 * set old_rd to NULL to skip the freeing later
6021 if (!atomic_dec_and_test(&old_rd
->refcount
))
6025 atomic_inc(&rd
->refcount
);
6028 cpumask_set_cpu(rq
->cpu
, rd
->span
);
6029 if (cpumask_test_cpu(rq
->cpu
, cpu_active_mask
))
6032 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
6035 call_rcu_sched(&old_rd
->rcu
, free_rootdomain
);
6038 static int init_rootdomain(struct root_domain
*rd
)
6040 memset(rd
, 0, sizeof(*rd
));
6042 if (!zalloc_cpumask_var(&rd
->span
, GFP_KERNEL
))
6044 if (!zalloc_cpumask_var(&rd
->online
, GFP_KERNEL
))
6046 if (!zalloc_cpumask_var(&rd
->dlo_mask
, GFP_KERNEL
))
6048 if (!zalloc_cpumask_var(&rd
->rto_mask
, GFP_KERNEL
))
6051 init_dl_bw(&rd
->dl_bw
);
6052 if (cpudl_init(&rd
->cpudl
) != 0)
6055 if (cpupri_init(&rd
->cpupri
) != 0)
6060 free_cpumask_var(rd
->rto_mask
);
6062 free_cpumask_var(rd
->dlo_mask
);
6064 free_cpumask_var(rd
->online
);
6066 free_cpumask_var(rd
->span
);
6072 * By default the system creates a single root-domain with all cpus as
6073 * members (mimicking the global state we have today).
6075 struct root_domain def_root_domain
;
6077 static void init_defrootdomain(void)
6079 init_rootdomain(&def_root_domain
);
6081 atomic_set(&def_root_domain
.refcount
, 1);
6084 static struct root_domain
*alloc_rootdomain(void)
6086 struct root_domain
*rd
;
6088 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6092 if (init_rootdomain(rd
) != 0) {
6100 static void free_sched_groups(struct sched_group
*sg
, int free_sgc
)
6102 struct sched_group
*tmp
, *first
;
6111 if (free_sgc
&& atomic_dec_and_test(&sg
->sgc
->ref
))
6116 } while (sg
!= first
);
6119 static void free_sched_domain(struct rcu_head
*rcu
)
6121 struct sched_domain
*sd
= container_of(rcu
, struct sched_domain
, rcu
);
6124 * If its an overlapping domain it has private groups, iterate and
6127 if (sd
->flags
& SD_OVERLAP
) {
6128 free_sched_groups(sd
->groups
, 1);
6129 } else if (atomic_dec_and_test(&sd
->groups
->ref
)) {
6130 kfree(sd
->groups
->sgc
);
6136 static void destroy_sched_domain(struct sched_domain
*sd
, int cpu
)
6138 call_rcu(&sd
->rcu
, free_sched_domain
);
6141 static void destroy_sched_domains(struct sched_domain
*sd
, int cpu
)
6143 for (; sd
; sd
= sd
->parent
)
6144 destroy_sched_domain(sd
, cpu
);
6148 * Keep a special pointer to the highest sched_domain that has
6149 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
6150 * allows us to avoid some pointer chasing select_idle_sibling().
6152 * Also keep a unique ID per domain (we use the first cpu number in
6153 * the cpumask of the domain), this allows us to quickly tell if
6154 * two cpus are in the same cache domain, see cpus_share_cache().
6156 DEFINE_PER_CPU(struct sched_domain
*, sd_llc
);
6157 DEFINE_PER_CPU(int, sd_llc_size
);
6158 DEFINE_PER_CPU(int, sd_llc_id
);
6159 DEFINE_PER_CPU(struct sched_domain
*, sd_numa
);
6160 DEFINE_PER_CPU(struct sched_domain
*, sd_busy
);
6161 DEFINE_PER_CPU(struct sched_domain
*, sd_asym
);
6163 static void update_top_cache_domain(int cpu
)
6165 struct sched_domain
*sd
;
6166 struct sched_domain
*busy_sd
= NULL
;
6170 sd
= highest_flag_domain(cpu
, SD_SHARE_PKG_RESOURCES
);
6172 id
= cpumask_first(sched_domain_span(sd
));
6173 size
= cpumask_weight(sched_domain_span(sd
));
6174 busy_sd
= sd
->parent
; /* sd_busy */
6176 rcu_assign_pointer(per_cpu(sd_busy
, cpu
), busy_sd
);
6178 rcu_assign_pointer(per_cpu(sd_llc
, cpu
), sd
);
6179 per_cpu(sd_llc_size
, cpu
) = size
;
6180 per_cpu(sd_llc_id
, cpu
) = id
;
6182 sd
= lowest_flag_domain(cpu
, SD_NUMA
);
6183 rcu_assign_pointer(per_cpu(sd_numa
, cpu
), sd
);
6185 sd
= highest_flag_domain(cpu
, SD_ASYM_PACKING
);
6186 rcu_assign_pointer(per_cpu(sd_asym
, cpu
), sd
);
6190 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6191 * hold the hotplug lock.
6194 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6196 struct rq
*rq
= cpu_rq(cpu
);
6197 struct sched_domain
*tmp
;
6199 /* Remove the sched domains which do not contribute to scheduling. */
6200 for (tmp
= sd
; tmp
; ) {
6201 struct sched_domain
*parent
= tmp
->parent
;
6205 if (sd_parent_degenerate(tmp
, parent
)) {
6206 tmp
->parent
= parent
->parent
;
6208 parent
->parent
->child
= tmp
;
6210 * Transfer SD_PREFER_SIBLING down in case of a
6211 * degenerate parent; the spans match for this
6212 * so the property transfers.
6214 if (parent
->flags
& SD_PREFER_SIBLING
)
6215 tmp
->flags
|= SD_PREFER_SIBLING
;
6216 destroy_sched_domain(parent
, cpu
);
6221 if (sd
&& sd_degenerate(sd
)) {
6224 destroy_sched_domain(tmp
, cpu
);
6229 sched_domain_debug(sd
, cpu
);
6231 rq_attach_root(rq
, rd
);
6233 rcu_assign_pointer(rq
->sd
, sd
);
6234 destroy_sched_domains(tmp
, cpu
);
6236 update_top_cache_domain(cpu
);
6239 /* Setup the mask of cpus configured for isolated domains */
6240 static int __init
isolated_cpu_setup(char *str
)
6244 alloc_bootmem_cpumask_var(&cpu_isolated_map
);
6245 ret
= cpulist_parse(str
, cpu_isolated_map
);
6247 pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids
);
6252 __setup("isolcpus=", isolated_cpu_setup
);
6255 struct sched_domain
** __percpu sd
;
6256 struct root_domain
*rd
;
6267 * Build an iteration mask that can exclude certain CPUs from the upwards
6270 * Asymmetric node setups can result in situations where the domain tree is of
6271 * unequal depth, make sure to skip domains that already cover the entire
6274 * In that case build_sched_domains() will have terminated the iteration early
6275 * and our sibling sd spans will be empty. Domains should always include the
6276 * cpu they're built on, so check that.
6279 static void build_group_mask(struct sched_domain
*sd
, struct sched_group
*sg
)
6281 const struct cpumask
*span
= sched_domain_span(sd
);
6282 struct sd_data
*sdd
= sd
->private;
6283 struct sched_domain
*sibling
;
6286 for_each_cpu(i
, span
) {
6287 sibling
= *per_cpu_ptr(sdd
->sd
, i
);
6288 if (!cpumask_test_cpu(i
, sched_domain_span(sibling
)))
6291 cpumask_set_cpu(i
, sched_group_mask(sg
));
6296 * Return the canonical balance cpu for this group, this is the first cpu
6297 * of this group that's also in the iteration mask.
6299 int group_balance_cpu(struct sched_group
*sg
)
6301 return cpumask_first_and(sched_group_cpus(sg
), sched_group_mask(sg
));
6305 build_overlap_sched_groups(struct sched_domain
*sd
, int cpu
)
6307 struct sched_group
*first
= NULL
, *last
= NULL
, *groups
= NULL
, *sg
;
6308 const struct cpumask
*span
= sched_domain_span(sd
);
6309 struct cpumask
*covered
= sched_domains_tmpmask
;
6310 struct sd_data
*sdd
= sd
->private;
6311 struct sched_domain
*sibling
;
6314 cpumask_clear(covered
);
6316 for_each_cpu(i
, span
) {
6317 struct cpumask
*sg_span
;
6319 if (cpumask_test_cpu(i
, covered
))
6322 sibling
= *per_cpu_ptr(sdd
->sd
, i
);
6324 /* See the comment near build_group_mask(). */
6325 if (!cpumask_test_cpu(i
, sched_domain_span(sibling
)))
6328 sg
= kzalloc_node(sizeof(struct sched_group
) + cpumask_size(),
6329 GFP_KERNEL
, cpu_to_node(cpu
));
6334 sg_span
= sched_group_cpus(sg
);
6336 cpumask_copy(sg_span
, sched_domain_span(sibling
->child
));
6338 cpumask_set_cpu(i
, sg_span
);
6340 cpumask_or(covered
, covered
, sg_span
);
6342 sg
->sgc
= *per_cpu_ptr(sdd
->sgc
, i
);
6343 if (atomic_inc_return(&sg
->sgc
->ref
) == 1)
6344 build_group_mask(sd
, sg
);
6347 * Initialize sgc->capacity such that even if we mess up the
6348 * domains and no possible iteration will get us here, we won't
6351 sg
->sgc
->capacity
= SCHED_CAPACITY_SCALE
* cpumask_weight(sg_span
);
6354 * Make sure the first group of this domain contains the
6355 * canonical balance cpu. Otherwise the sched_domain iteration
6356 * breaks. See update_sg_lb_stats().
6358 if ((!groups
&& cpumask_test_cpu(cpu
, sg_span
)) ||
6359 group_balance_cpu(sg
) == cpu
)
6369 sd
->groups
= groups
;
6374 free_sched_groups(first
, 0);
6379 static int get_group(int cpu
, struct sd_data
*sdd
, struct sched_group
**sg
)
6381 struct sched_domain
*sd
= *per_cpu_ptr(sdd
->sd
, cpu
);
6382 struct sched_domain
*child
= sd
->child
;
6385 cpu
= cpumask_first(sched_domain_span(child
));
6388 *sg
= *per_cpu_ptr(sdd
->sg
, cpu
);
6389 (*sg
)->sgc
= *per_cpu_ptr(sdd
->sgc
, cpu
);
6390 atomic_set(&(*sg
)->sgc
->ref
, 1); /* for claim_allocations */
6397 * build_sched_groups will build a circular linked list of the groups
6398 * covered by the given span, and will set each group's ->cpumask correctly,
6399 * and ->cpu_capacity to 0.
6401 * Assumes the sched_domain tree is fully constructed
6404 build_sched_groups(struct sched_domain
*sd
, int cpu
)
6406 struct sched_group
*first
= NULL
, *last
= NULL
;
6407 struct sd_data
*sdd
= sd
->private;
6408 const struct cpumask
*span
= sched_domain_span(sd
);
6409 struct cpumask
*covered
;
6412 get_group(cpu
, sdd
, &sd
->groups
);
6413 atomic_inc(&sd
->groups
->ref
);
6415 if (cpu
!= cpumask_first(span
))
6418 lockdep_assert_held(&sched_domains_mutex
);
6419 covered
= sched_domains_tmpmask
;
6421 cpumask_clear(covered
);
6423 for_each_cpu(i
, span
) {
6424 struct sched_group
*sg
;
6427 if (cpumask_test_cpu(i
, covered
))
6430 group
= get_group(i
, sdd
, &sg
);
6431 cpumask_setall(sched_group_mask(sg
));
6433 for_each_cpu(j
, span
) {
6434 if (get_group(j
, sdd
, NULL
) != group
)
6437 cpumask_set_cpu(j
, covered
);
6438 cpumask_set_cpu(j
, sched_group_cpus(sg
));
6453 * Initialize sched groups cpu_capacity.
6455 * cpu_capacity indicates the capacity of sched group, which is used while
6456 * distributing the load between different sched groups in a sched domain.
6457 * Typically cpu_capacity for all the groups in a sched domain will be same
6458 * unless there are asymmetries in the topology. If there are asymmetries,
6459 * group having more cpu_capacity will pickup more load compared to the
6460 * group having less cpu_capacity.
6462 static void init_sched_groups_capacity(int cpu
, struct sched_domain
*sd
)
6464 struct sched_group
*sg
= sd
->groups
;
6469 sg
->group_weight
= cpumask_weight(sched_group_cpus(sg
));
6471 } while (sg
!= sd
->groups
);
6473 if (cpu
!= group_balance_cpu(sg
))
6476 update_group_capacity(sd
, cpu
);
6477 atomic_set(&sg
->sgc
->nr_busy_cpus
, sg
->group_weight
);
6481 * Initializers for schedule domains
6482 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6485 static int default_relax_domain_level
= -1;
6486 int sched_domain_level_max
;
6488 static int __init
setup_relax_domain_level(char *str
)
6490 if (kstrtoint(str
, 0, &default_relax_domain_level
))
6491 pr_warn("Unable to set relax_domain_level\n");
6495 __setup("relax_domain_level=", setup_relax_domain_level
);
6497 static void set_domain_attribute(struct sched_domain
*sd
,
6498 struct sched_domain_attr
*attr
)
6502 if (!attr
|| attr
->relax_domain_level
< 0) {
6503 if (default_relax_domain_level
< 0)
6506 request
= default_relax_domain_level
;
6508 request
= attr
->relax_domain_level
;
6509 if (request
< sd
->level
) {
6510 /* turn off idle balance on this domain */
6511 sd
->flags
&= ~(SD_BALANCE_WAKE
|SD_BALANCE_NEWIDLE
);
6513 /* turn on idle balance on this domain */
6514 sd
->flags
|= (SD_BALANCE_WAKE
|SD_BALANCE_NEWIDLE
);
6518 static void __sdt_free(const struct cpumask
*cpu_map
);
6519 static int __sdt_alloc(const struct cpumask
*cpu_map
);
6521 static void __free_domain_allocs(struct s_data
*d
, enum s_alloc what
,
6522 const struct cpumask
*cpu_map
)
6526 if (!atomic_read(&d
->rd
->refcount
))
6527 free_rootdomain(&d
->rd
->rcu
); /* fall through */
6529 free_percpu(d
->sd
); /* fall through */
6531 __sdt_free(cpu_map
); /* fall through */
6537 static enum s_alloc
__visit_domain_allocation_hell(struct s_data
*d
,
6538 const struct cpumask
*cpu_map
)
6540 memset(d
, 0, sizeof(*d
));
6542 if (__sdt_alloc(cpu_map
))
6543 return sa_sd_storage
;
6544 d
->sd
= alloc_percpu(struct sched_domain
*);
6546 return sa_sd_storage
;
6547 d
->rd
= alloc_rootdomain();
6550 return sa_rootdomain
;
6554 * NULL the sd_data elements we've used to build the sched_domain and
6555 * sched_group structure so that the subsequent __free_domain_allocs()
6556 * will not free the data we're using.
6558 static void claim_allocations(int cpu
, struct sched_domain
*sd
)
6560 struct sd_data
*sdd
= sd
->private;
6562 WARN_ON_ONCE(*per_cpu_ptr(sdd
->sd
, cpu
) != sd
);
6563 *per_cpu_ptr(sdd
->sd
, cpu
) = NULL
;
6565 if (atomic_read(&(*per_cpu_ptr(sdd
->sg
, cpu
))->ref
))
6566 *per_cpu_ptr(sdd
->sg
, cpu
) = NULL
;
6568 if (atomic_read(&(*per_cpu_ptr(sdd
->sgc
, cpu
))->ref
))
6569 *per_cpu_ptr(sdd
->sgc
, cpu
) = NULL
;
6573 static int sched_domains_numa_levels
;
6574 enum numa_topology_type sched_numa_topology_type
;
6575 static int *sched_domains_numa_distance
;
6576 int sched_max_numa_distance
;
6577 static struct cpumask
***sched_domains_numa_masks
;
6578 static int sched_domains_curr_level
;
6582 * SD_flags allowed in topology descriptions.
6584 * SD_SHARE_CPUCAPACITY - describes SMT topologies
6585 * SD_SHARE_PKG_RESOURCES - describes shared caches
6586 * SD_NUMA - describes NUMA topologies
6587 * SD_SHARE_POWERDOMAIN - describes shared power domain
6590 * SD_ASYM_PACKING - describes SMT quirks
6592 #define TOPOLOGY_SD_FLAGS \
6593 (SD_SHARE_CPUCAPACITY | \
6594 SD_SHARE_PKG_RESOURCES | \
6597 SD_SHARE_POWERDOMAIN)
6599 static struct sched_domain
*
6600 sd_init(struct sched_domain_topology_level
*tl
, int cpu
)
6602 struct sched_domain
*sd
= *per_cpu_ptr(tl
->data
.sd
, cpu
);
6603 int sd_weight
, sd_flags
= 0;
6607 * Ugly hack to pass state to sd_numa_mask()...
6609 sched_domains_curr_level
= tl
->numa_level
;
6612 sd_weight
= cpumask_weight(tl
->mask(cpu
));
6615 sd_flags
= (*tl
->sd_flags
)();
6616 if (WARN_ONCE(sd_flags
& ~TOPOLOGY_SD_FLAGS
,
6617 "wrong sd_flags in topology description\n"))
6618 sd_flags
&= ~TOPOLOGY_SD_FLAGS
;
6620 *sd
= (struct sched_domain
){
6621 .min_interval
= sd_weight
,
6622 .max_interval
= 2*sd_weight
,
6624 .imbalance_pct
= 125,
6626 .cache_nice_tries
= 0,
6633 .flags
= 1*SD_LOAD_BALANCE
6634 | 1*SD_BALANCE_NEWIDLE
6639 | 0*SD_SHARE_CPUCAPACITY
6640 | 0*SD_SHARE_PKG_RESOURCES
6642 | 0*SD_PREFER_SIBLING
6647 .last_balance
= jiffies
,
6648 .balance_interval
= sd_weight
,
6650 .max_newidle_lb_cost
= 0,
6651 .next_decay_max_lb_cost
= jiffies
,
6652 #ifdef CONFIG_SCHED_DEBUG
6658 * Convert topological properties into behaviour.
6661 if (sd
->flags
& SD_SHARE_CPUCAPACITY
) {
6662 sd
->flags
|= SD_PREFER_SIBLING
;
6663 sd
->imbalance_pct
= 110;
6664 sd
->smt_gain
= 1178; /* ~15% */
6666 } else if (sd
->flags
& SD_SHARE_PKG_RESOURCES
) {
6667 sd
->imbalance_pct
= 117;
6668 sd
->cache_nice_tries
= 1;
6672 } else if (sd
->flags
& SD_NUMA
) {
6673 sd
->cache_nice_tries
= 2;
6677 sd
->flags
|= SD_SERIALIZE
;
6678 if (sched_domains_numa_distance
[tl
->numa_level
] > RECLAIM_DISTANCE
) {
6679 sd
->flags
&= ~(SD_BALANCE_EXEC
|
6686 sd
->flags
|= SD_PREFER_SIBLING
;
6687 sd
->cache_nice_tries
= 1;
6692 sd
->private = &tl
->data
;
6698 * Topology list, bottom-up.
6700 static struct sched_domain_topology_level default_topology
[] = {
6701 #ifdef CONFIG_SCHED_SMT
6702 { cpu_smt_mask
, cpu_smt_flags
, SD_INIT_NAME(SMT
) },
6704 #ifdef CONFIG_SCHED_MC
6705 { cpu_coregroup_mask
, cpu_core_flags
, SD_INIT_NAME(MC
) },
6707 { cpu_cpu_mask
, SD_INIT_NAME(DIE
) },
6711 static struct sched_domain_topology_level
*sched_domain_topology
=
6714 #define for_each_sd_topology(tl) \
6715 for (tl = sched_domain_topology; tl->mask; tl++)
6717 void set_sched_topology(struct sched_domain_topology_level
*tl
)
6719 sched_domain_topology
= tl
;
6724 static const struct cpumask
*sd_numa_mask(int cpu
)
6726 return sched_domains_numa_masks
[sched_domains_curr_level
][cpu_to_node(cpu
)];
6729 static void sched_numa_warn(const char *str
)
6731 static int done
= false;
6739 printk(KERN_WARNING
"ERROR: %s\n\n", str
);
6741 for (i
= 0; i
< nr_node_ids
; i
++) {
6742 printk(KERN_WARNING
" ");
6743 for (j
= 0; j
< nr_node_ids
; j
++)
6744 printk(KERN_CONT
"%02d ", node_distance(i
,j
));
6745 printk(KERN_CONT
"\n");
6747 printk(KERN_WARNING
"\n");
6750 bool find_numa_distance(int distance
)
6754 if (distance
== node_distance(0, 0))
6757 for (i
= 0; i
< sched_domains_numa_levels
; i
++) {
6758 if (sched_domains_numa_distance
[i
] == distance
)
6766 * A system can have three types of NUMA topology:
6767 * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6768 * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6769 * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6771 * The difference between a glueless mesh topology and a backplane
6772 * topology lies in whether communication between not directly
6773 * connected nodes goes through intermediary nodes (where programs
6774 * could run), or through backplane controllers. This affects
6775 * placement of programs.
6777 * The type of topology can be discerned with the following tests:
6778 * - If the maximum distance between any nodes is 1 hop, the system
6779 * is directly connected.
6780 * - If for two nodes A and B, located N > 1 hops away from each other,
6781 * there is an intermediary node C, which is < N hops away from both
6782 * nodes A and B, the system is a glueless mesh.
6784 static void init_numa_topology_type(void)
6788 n
= sched_max_numa_distance
;
6790 if (sched_domains_numa_levels
<= 1) {
6791 sched_numa_topology_type
= NUMA_DIRECT
;
6795 for_each_online_node(a
) {
6796 for_each_online_node(b
) {
6797 /* Find two nodes furthest removed from each other. */
6798 if (node_distance(a
, b
) < n
)
6801 /* Is there an intermediary node between a and b? */
6802 for_each_online_node(c
) {
6803 if (node_distance(a
, c
) < n
&&
6804 node_distance(b
, c
) < n
) {
6805 sched_numa_topology_type
=
6811 sched_numa_topology_type
= NUMA_BACKPLANE
;
6817 static void sched_init_numa(void)
6819 int next_distance
, curr_distance
= node_distance(0, 0);
6820 struct sched_domain_topology_level
*tl
;
6824 sched_domains_numa_distance
= kzalloc(sizeof(int) * nr_node_ids
, GFP_KERNEL
);
6825 if (!sched_domains_numa_distance
)
6829 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6830 * unique distances in the node_distance() table.
6832 * Assumes node_distance(0,j) includes all distances in
6833 * node_distance(i,j) in order to avoid cubic time.
6835 next_distance
= curr_distance
;
6836 for (i
= 0; i
< nr_node_ids
; i
++) {
6837 for (j
= 0; j
< nr_node_ids
; j
++) {
6838 for (k
= 0; k
< nr_node_ids
; k
++) {
6839 int distance
= node_distance(i
, k
);
6841 if (distance
> curr_distance
&&
6842 (distance
< next_distance
||
6843 next_distance
== curr_distance
))
6844 next_distance
= distance
;
6847 * While not a strong assumption it would be nice to know
6848 * about cases where if node A is connected to B, B is not
6849 * equally connected to A.
6851 if (sched_debug() && node_distance(k
, i
) != distance
)
6852 sched_numa_warn("Node-distance not symmetric");
6854 if (sched_debug() && i
&& !find_numa_distance(distance
))
6855 sched_numa_warn("Node-0 not representative");
6857 if (next_distance
!= curr_distance
) {
6858 sched_domains_numa_distance
[level
++] = next_distance
;
6859 sched_domains_numa_levels
= level
;
6860 curr_distance
= next_distance
;
6865 * In case of sched_debug() we verify the above assumption.
6875 * 'level' contains the number of unique distances, excluding the
6876 * identity distance node_distance(i,i).
6878 * The sched_domains_numa_distance[] array includes the actual distance
6883 * Here, we should temporarily reset sched_domains_numa_levels to 0.
6884 * If it fails to allocate memory for array sched_domains_numa_masks[][],
6885 * the array will contain less then 'level' members. This could be
6886 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6887 * in other functions.
6889 * We reset it to 'level' at the end of this function.
6891 sched_domains_numa_levels
= 0;
6893 sched_domains_numa_masks
= kzalloc(sizeof(void *) * level
, GFP_KERNEL
);
6894 if (!sched_domains_numa_masks
)
6898 * Now for each level, construct a mask per node which contains all
6899 * cpus of nodes that are that many hops away from us.
6901 for (i
= 0; i
< level
; i
++) {
6902 sched_domains_numa_masks
[i
] =
6903 kzalloc(nr_node_ids
* sizeof(void *), GFP_KERNEL
);
6904 if (!sched_domains_numa_masks
[i
])
6907 for (j
= 0; j
< nr_node_ids
; j
++) {
6908 struct cpumask
*mask
= kzalloc(cpumask_size(), GFP_KERNEL
);
6912 sched_domains_numa_masks
[i
][j
] = mask
;
6915 if (node_distance(j
, k
) > sched_domains_numa_distance
[i
])
6918 cpumask_or(mask
, mask
, cpumask_of_node(k
));
6923 /* Compute default topology size */
6924 for (i
= 0; sched_domain_topology
[i
].mask
; i
++);
6926 tl
= kzalloc((i
+ level
+ 1) *
6927 sizeof(struct sched_domain_topology_level
), GFP_KERNEL
);
6932 * Copy the default topology bits..
6934 for (i
= 0; sched_domain_topology
[i
].mask
; i
++)
6935 tl
[i
] = sched_domain_topology
[i
];
6938 * .. and append 'j' levels of NUMA goodness.
6940 for (j
= 0; j
< level
; i
++, j
++) {
6941 tl
[i
] = (struct sched_domain_topology_level
){
6942 .mask
= sd_numa_mask
,
6943 .sd_flags
= cpu_numa_flags
,
6944 .flags
= SDTL_OVERLAP
,
6950 sched_domain_topology
= tl
;
6952 sched_domains_numa_levels
= level
;
6953 sched_max_numa_distance
= sched_domains_numa_distance
[level
- 1];
6955 init_numa_topology_type();
6958 static void sched_domains_numa_masks_set(int cpu
)
6961 int node
= cpu_to_node(cpu
);
6963 for (i
= 0; i
< sched_domains_numa_levels
; i
++) {
6964 for (j
= 0; j
< nr_node_ids
; j
++) {
6965 if (node_distance(j
, node
) <= sched_domains_numa_distance
[i
])
6966 cpumask_set_cpu(cpu
, sched_domains_numa_masks
[i
][j
]);
6971 static void sched_domains_numa_masks_clear(int cpu
)
6974 for (i
= 0; i
< sched_domains_numa_levels
; i
++) {
6975 for (j
= 0; j
< nr_node_ids
; j
++)
6976 cpumask_clear_cpu(cpu
, sched_domains_numa_masks
[i
][j
]);
6981 * Update sched_domains_numa_masks[level][node] array when new cpus
6984 static int sched_domains_numa_masks_update(struct notifier_block
*nfb
,
6985 unsigned long action
,
6988 int cpu
= (long)hcpu
;
6990 switch (action
& ~CPU_TASKS_FROZEN
) {
6992 sched_domains_numa_masks_set(cpu
);
6996 sched_domains_numa_masks_clear(cpu
);
7006 static inline void sched_init_numa(void)
7010 static int sched_domains_numa_masks_update(struct notifier_block
*nfb
,
7011 unsigned long action
,
7016 #endif /* CONFIG_NUMA */
7018 static int __sdt_alloc(const struct cpumask
*cpu_map
)
7020 struct sched_domain_topology_level
*tl
;
7023 for_each_sd_topology(tl
) {
7024 struct sd_data
*sdd
= &tl
->data
;
7026 sdd
->sd
= alloc_percpu(struct sched_domain
*);
7030 sdd
->sg
= alloc_percpu(struct sched_group
*);
7034 sdd
->sgc
= alloc_percpu(struct sched_group_capacity
*);
7038 for_each_cpu(j
, cpu_map
) {
7039 struct sched_domain
*sd
;
7040 struct sched_group
*sg
;
7041 struct sched_group_capacity
*sgc
;
7043 sd
= kzalloc_node(sizeof(struct sched_domain
) + cpumask_size(),
7044 GFP_KERNEL
, cpu_to_node(j
));
7048 *per_cpu_ptr(sdd
->sd
, j
) = sd
;
7050 sg
= kzalloc_node(sizeof(struct sched_group
) + cpumask_size(),
7051 GFP_KERNEL
, cpu_to_node(j
));
7057 *per_cpu_ptr(sdd
->sg
, j
) = sg
;
7059 sgc
= kzalloc_node(sizeof(struct sched_group_capacity
) + cpumask_size(),
7060 GFP_KERNEL
, cpu_to_node(j
));
7064 *per_cpu_ptr(sdd
->sgc
, j
) = sgc
;
7071 static void __sdt_free(const struct cpumask
*cpu_map
)
7073 struct sched_domain_topology_level
*tl
;
7076 for_each_sd_topology(tl
) {
7077 struct sd_data
*sdd
= &tl
->data
;
7079 for_each_cpu(j
, cpu_map
) {
7080 struct sched_domain
*sd
;
7083 sd
= *per_cpu_ptr(sdd
->sd
, j
);
7084 if (sd
&& (sd
->flags
& SD_OVERLAP
))
7085 free_sched_groups(sd
->groups
, 0);
7086 kfree(*per_cpu_ptr(sdd
->sd
, j
));
7090 kfree(*per_cpu_ptr(sdd
->sg
, j
));
7092 kfree(*per_cpu_ptr(sdd
->sgc
, j
));
7094 free_percpu(sdd
->sd
);
7096 free_percpu(sdd
->sg
);
7098 free_percpu(sdd
->sgc
);
7103 struct sched_domain
*build_sched_domain(struct sched_domain_topology_level
*tl
,
7104 const struct cpumask
*cpu_map
, struct sched_domain_attr
*attr
,
7105 struct sched_domain
*child
, int cpu
)
7107 struct sched_domain
*sd
= sd_init(tl
, cpu
);
7111 cpumask_and(sched_domain_span(sd
), cpu_map
, tl
->mask(cpu
));
7113 sd
->level
= child
->level
+ 1;
7114 sched_domain_level_max
= max(sched_domain_level_max
, sd
->level
);
7118 if (!cpumask_subset(sched_domain_span(child
),
7119 sched_domain_span(sd
))) {
7120 pr_err("BUG: arch topology borken\n");
7121 #ifdef CONFIG_SCHED_DEBUG
7122 pr_err(" the %s domain not a subset of the %s domain\n",
7123 child
->name
, sd
->name
);
7125 /* Fixup, ensure @sd has at least @child cpus. */
7126 cpumask_or(sched_domain_span(sd
),
7127 sched_domain_span(sd
),
7128 sched_domain_span(child
));
7132 set_domain_attribute(sd
, attr
);
7138 * Build sched domains for a given set of cpus and attach the sched domains
7139 * to the individual cpus
7141 static int build_sched_domains(const struct cpumask
*cpu_map
,
7142 struct sched_domain_attr
*attr
)
7144 enum s_alloc alloc_state
;
7145 struct sched_domain
*sd
;
7147 int i
, ret
= -ENOMEM
;
7149 alloc_state
= __visit_domain_allocation_hell(&d
, cpu_map
);
7150 if (alloc_state
!= sa_rootdomain
)
7153 /* Set up domains for cpus specified by the cpu_map. */
7154 for_each_cpu(i
, cpu_map
) {
7155 struct sched_domain_topology_level
*tl
;
7158 for_each_sd_topology(tl
) {
7159 sd
= build_sched_domain(tl
, cpu_map
, attr
, sd
, i
);
7160 if (tl
== sched_domain_topology
)
7161 *per_cpu_ptr(d
.sd
, i
) = sd
;
7162 if (tl
->flags
& SDTL_OVERLAP
|| sched_feat(FORCE_SD_OVERLAP
))
7163 sd
->flags
|= SD_OVERLAP
;
7164 if (cpumask_equal(cpu_map
, sched_domain_span(sd
)))
7169 /* Build the groups for the domains */
7170 for_each_cpu(i
, cpu_map
) {
7171 for (sd
= *per_cpu_ptr(d
.sd
, i
); sd
; sd
= sd
->parent
) {
7172 sd
->span_weight
= cpumask_weight(sched_domain_span(sd
));
7173 if (sd
->flags
& SD_OVERLAP
) {
7174 if (build_overlap_sched_groups(sd
, i
))
7177 if (build_sched_groups(sd
, i
))
7183 /* Calculate CPU capacity for physical packages and nodes */
7184 for (i
= nr_cpumask_bits
-1; i
>= 0; i
--) {
7185 if (!cpumask_test_cpu(i
, cpu_map
))
7188 for (sd
= *per_cpu_ptr(d
.sd
, i
); sd
; sd
= sd
->parent
) {
7189 claim_allocations(i
, sd
);
7190 init_sched_groups_capacity(i
, sd
);
7194 /* Attach the domains */
7196 for_each_cpu(i
, cpu_map
) {
7197 sd
= *per_cpu_ptr(d
.sd
, i
);
7198 cpu_attach_domain(sd
, d
.rd
, i
);
7204 __free_domain_allocs(&d
, alloc_state
, cpu_map
);
7208 static cpumask_var_t
*doms_cur
; /* current sched domains */
7209 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
7210 static struct sched_domain_attr
*dattr_cur
;
7211 /* attribues of custom domains in 'doms_cur' */
7214 * Special case: If a kmalloc of a doms_cur partition (array of
7215 * cpumask) fails, then fallback to a single sched domain,
7216 * as determined by the single cpumask fallback_doms.
7218 static cpumask_var_t fallback_doms
;
7221 * arch_update_cpu_topology lets virtualized architectures update the
7222 * cpu core maps. It is supposed to return 1 if the topology changed
7223 * or 0 if it stayed the same.
7225 int __weak
arch_update_cpu_topology(void)
7230 cpumask_var_t
*alloc_sched_domains(unsigned int ndoms
)
7233 cpumask_var_t
*doms
;
7235 doms
= kmalloc(sizeof(*doms
) * ndoms
, GFP_KERNEL
);
7238 for (i
= 0; i
< ndoms
; i
++) {
7239 if (!alloc_cpumask_var(&doms
[i
], GFP_KERNEL
)) {
7240 free_sched_domains(doms
, i
);
7247 void free_sched_domains(cpumask_var_t doms
[], unsigned int ndoms
)
7250 for (i
= 0; i
< ndoms
; i
++)
7251 free_cpumask_var(doms
[i
]);
7256 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7257 * For now this just excludes isolated cpus, but could be used to
7258 * exclude other special cases in the future.
7260 static int init_sched_domains(const struct cpumask
*cpu_map
)
7264 arch_update_cpu_topology();
7266 doms_cur
= alloc_sched_domains(ndoms_cur
);
7268 doms_cur
= &fallback_doms
;
7269 cpumask_andnot(doms_cur
[0], cpu_map
, cpu_isolated_map
);
7270 err
= build_sched_domains(doms_cur
[0], NULL
);
7271 register_sched_domain_sysctl();
7277 * Detach sched domains from a group of cpus specified in cpu_map
7278 * These cpus will now be attached to the NULL domain
7280 static void detach_destroy_domains(const struct cpumask
*cpu_map
)
7285 for_each_cpu(i
, cpu_map
)
7286 cpu_attach_domain(NULL
, &def_root_domain
, i
);
7290 /* handle null as "default" */
7291 static int dattrs_equal(struct sched_domain_attr
*cur
, int idx_cur
,
7292 struct sched_domain_attr
*new, int idx_new
)
7294 struct sched_domain_attr tmp
;
7301 return !memcmp(cur
? (cur
+ idx_cur
) : &tmp
,
7302 new ? (new + idx_new
) : &tmp
,
7303 sizeof(struct sched_domain_attr
));
7307 * Partition sched domains as specified by the 'ndoms_new'
7308 * cpumasks in the array doms_new[] of cpumasks. This compares
7309 * doms_new[] to the current sched domain partitioning, doms_cur[].
7310 * It destroys each deleted domain and builds each new domain.
7312 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7313 * The masks don't intersect (don't overlap.) We should setup one
7314 * sched domain for each mask. CPUs not in any of the cpumasks will
7315 * not be load balanced. If the same cpumask appears both in the
7316 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7319 * The passed in 'doms_new' should be allocated using
7320 * alloc_sched_domains. This routine takes ownership of it and will
7321 * free_sched_domains it when done with it. If the caller failed the
7322 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7323 * and partition_sched_domains() will fallback to the single partition
7324 * 'fallback_doms', it also forces the domains to be rebuilt.
7326 * If doms_new == NULL it will be replaced with cpu_online_mask.
7327 * ndoms_new == 0 is a special case for destroying existing domains,
7328 * and it will not create the default domain.
7330 * Call with hotplug lock held
7332 void partition_sched_domains(int ndoms_new
, cpumask_var_t doms_new
[],
7333 struct sched_domain_attr
*dattr_new
)
7338 mutex_lock(&sched_domains_mutex
);
7340 /* always unregister in case we don't destroy any domains */
7341 unregister_sched_domain_sysctl();
7343 /* Let architecture update cpu core mappings. */
7344 new_topology
= arch_update_cpu_topology();
7346 n
= doms_new
? ndoms_new
: 0;
7348 /* Destroy deleted domains */
7349 for (i
= 0; i
< ndoms_cur
; i
++) {
7350 for (j
= 0; j
< n
&& !new_topology
; j
++) {
7351 if (cpumask_equal(doms_cur
[i
], doms_new
[j
])
7352 && dattrs_equal(dattr_cur
, i
, dattr_new
, j
))
7355 /* no match - a current sched domain not in new doms_new[] */
7356 detach_destroy_domains(doms_cur
[i
]);
7362 if (doms_new
== NULL
) {
7364 doms_new
= &fallback_doms
;
7365 cpumask_andnot(doms_new
[0], cpu_active_mask
, cpu_isolated_map
);
7366 WARN_ON_ONCE(dattr_new
);
7369 /* Build new domains */
7370 for (i
= 0; i
< ndoms_new
; i
++) {
7371 for (j
= 0; j
< n
&& !new_topology
; j
++) {
7372 if (cpumask_equal(doms_new
[i
], doms_cur
[j
])
7373 && dattrs_equal(dattr_new
, i
, dattr_cur
, j
))
7376 /* no match - add a new doms_new */
7377 build_sched_domains(doms_new
[i
], dattr_new
? dattr_new
+ i
: NULL
);
7382 /* Remember the new sched domains */
7383 if (doms_cur
!= &fallback_doms
)
7384 free_sched_domains(doms_cur
, ndoms_cur
);
7385 kfree(dattr_cur
); /* kfree(NULL) is safe */
7386 doms_cur
= doms_new
;
7387 dattr_cur
= dattr_new
;
7388 ndoms_cur
= ndoms_new
;
7390 register_sched_domain_sysctl();
7392 mutex_unlock(&sched_domains_mutex
);
7395 static int num_cpus_frozen
; /* used to mark begin/end of suspend/resume */
7398 * Update cpusets according to cpu_active mask. If cpusets are
7399 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7400 * around partition_sched_domains().
7402 * If we come here as part of a suspend/resume, don't touch cpusets because we
7403 * want to restore it back to its original state upon resume anyway.
7405 static int cpuset_cpu_active(struct notifier_block
*nfb
, unsigned long action
,
7409 case CPU_ONLINE_FROZEN
:
7410 case CPU_DOWN_FAILED_FROZEN
:
7413 * num_cpus_frozen tracks how many CPUs are involved in suspend
7414 * resume sequence. As long as this is not the last online
7415 * operation in the resume sequence, just build a single sched
7416 * domain, ignoring cpusets.
7419 if (likely(num_cpus_frozen
)) {
7420 partition_sched_domains(1, NULL
, NULL
);
7425 * This is the last CPU online operation. So fall through and
7426 * restore the original sched domains by considering the
7427 * cpuset configurations.
7431 cpuset_update_active_cpus(true);
7439 static int cpuset_cpu_inactive(struct notifier_block
*nfb
, unsigned long action
,
7442 unsigned long flags
;
7443 long cpu
= (long)hcpu
;
7449 case CPU_DOWN_PREPARE
:
7450 rcu_read_lock_sched();
7451 dl_b
= dl_bw_of(cpu
);
7453 raw_spin_lock_irqsave(&dl_b
->lock
, flags
);
7454 cpus
= dl_bw_cpus(cpu
);
7455 overflow
= __dl_overflow(dl_b
, cpus
, 0, 0);
7456 raw_spin_unlock_irqrestore(&dl_b
->lock
, flags
);
7458 rcu_read_unlock_sched();
7461 return notifier_from_errno(-EBUSY
);
7462 cpuset_update_active_cpus(false);
7464 case CPU_DOWN_PREPARE_FROZEN
:
7466 partition_sched_domains(1, NULL
, NULL
);
7474 void __init
sched_init_smp(void)
7476 cpumask_var_t non_isolated_cpus
;
7478 alloc_cpumask_var(&non_isolated_cpus
, GFP_KERNEL
);
7479 alloc_cpumask_var(&fallback_doms
, GFP_KERNEL
);
7484 * There's no userspace yet to cause hotplug operations; hence all the
7485 * cpu masks are stable and all blatant races in the below code cannot
7488 mutex_lock(&sched_domains_mutex
);
7489 init_sched_domains(cpu_active_mask
);
7490 cpumask_andnot(non_isolated_cpus
, cpu_possible_mask
, cpu_isolated_map
);
7491 if (cpumask_empty(non_isolated_cpus
))
7492 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus
);
7493 mutex_unlock(&sched_domains_mutex
);
7495 hotcpu_notifier(sched_domains_numa_masks_update
, CPU_PRI_SCHED_ACTIVE
);
7496 hotcpu_notifier(cpuset_cpu_active
, CPU_PRI_CPUSET_ACTIVE
);
7497 hotcpu_notifier(cpuset_cpu_inactive
, CPU_PRI_CPUSET_INACTIVE
);
7501 /* Move init over to a non-isolated CPU */
7502 if (set_cpus_allowed_ptr(current
, non_isolated_cpus
) < 0)
7504 sched_init_granularity();
7505 free_cpumask_var(non_isolated_cpus
);
7507 init_sched_rt_class();
7508 init_sched_dl_class();
7511 void __init
sched_init_smp(void)
7513 sched_init_granularity();
7515 #endif /* CONFIG_SMP */
7517 int in_sched_functions(unsigned long addr
)
7519 return in_lock_functions(addr
) ||
7520 (addr
>= (unsigned long)__sched_text_start
7521 && addr
< (unsigned long)__sched_text_end
);
7524 #ifdef CONFIG_CGROUP_SCHED
7526 * Default task group.
7527 * Every task in system belongs to this group at bootup.
7529 struct task_group root_task_group
;
7530 LIST_HEAD(task_groups
);
7532 /* Cacheline aligned slab cache for task_group */
7533 static struct kmem_cache
*task_group_cache __read_mostly
;
7536 DECLARE_PER_CPU(cpumask_var_t
, load_balance_mask
);
7538 void __init
sched_init(void)
7541 unsigned long alloc_size
= 0, ptr
;
7543 #ifdef CONFIG_FAIR_GROUP_SCHED
7544 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
7546 #ifdef CONFIG_RT_GROUP_SCHED
7547 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
7550 ptr
= (unsigned long)kzalloc(alloc_size
, GFP_NOWAIT
);
7552 #ifdef CONFIG_FAIR_GROUP_SCHED
7553 root_task_group
.se
= (struct sched_entity
**)ptr
;
7554 ptr
+= nr_cpu_ids
* sizeof(void **);
7556 root_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
7557 ptr
+= nr_cpu_ids
* sizeof(void **);
7559 #endif /* CONFIG_FAIR_GROUP_SCHED */
7560 #ifdef CONFIG_RT_GROUP_SCHED
7561 root_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
7562 ptr
+= nr_cpu_ids
* sizeof(void **);
7564 root_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
7565 ptr
+= nr_cpu_ids
* sizeof(void **);
7567 #endif /* CONFIG_RT_GROUP_SCHED */
7569 #ifdef CONFIG_CPUMASK_OFFSTACK
7570 for_each_possible_cpu(i
) {
7571 per_cpu(load_balance_mask
, i
) = (cpumask_var_t
)kzalloc_node(
7572 cpumask_size(), GFP_KERNEL
, cpu_to_node(i
));
7574 #endif /* CONFIG_CPUMASK_OFFSTACK */
7576 init_rt_bandwidth(&def_rt_bandwidth
,
7577 global_rt_period(), global_rt_runtime());
7578 init_dl_bandwidth(&def_dl_bandwidth
,
7579 global_rt_period(), global_rt_runtime());
7582 init_defrootdomain();
7585 #ifdef CONFIG_RT_GROUP_SCHED
7586 init_rt_bandwidth(&root_task_group
.rt_bandwidth
,
7587 global_rt_period(), global_rt_runtime());
7588 #endif /* CONFIG_RT_GROUP_SCHED */
7590 #ifdef CONFIG_CGROUP_SCHED
7591 task_group_cache
= KMEM_CACHE(task_group
, 0);
7593 list_add(&root_task_group
.list
, &task_groups
);
7594 INIT_LIST_HEAD(&root_task_group
.children
);
7595 INIT_LIST_HEAD(&root_task_group
.siblings
);
7596 autogroup_init(&init_task
);
7597 #endif /* CONFIG_CGROUP_SCHED */
7599 for_each_possible_cpu(i
) {
7603 raw_spin_lock_init(&rq
->lock
);
7605 rq
->calc_load_active
= 0;
7606 rq
->calc_load_update
= jiffies
+ LOAD_FREQ
;
7607 init_cfs_rq(&rq
->cfs
);
7608 init_rt_rq(&rq
->rt
);
7609 init_dl_rq(&rq
->dl
);
7610 #ifdef CONFIG_FAIR_GROUP_SCHED
7611 root_task_group
.shares
= ROOT_TASK_GROUP_LOAD
;
7612 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
7614 * How much cpu bandwidth does root_task_group get?
7616 * In case of task-groups formed thr' the cgroup filesystem, it
7617 * gets 100% of the cpu resources in the system. This overall
7618 * system cpu resource is divided among the tasks of
7619 * root_task_group and its child task-groups in a fair manner,
7620 * based on each entity's (task or task-group's) weight
7621 * (se->load.weight).
7623 * In other words, if root_task_group has 10 tasks of weight
7624 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7625 * then A0's share of the cpu resource is:
7627 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7629 * We achieve this by letting root_task_group's tasks sit
7630 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7632 init_cfs_bandwidth(&root_task_group
.cfs_bandwidth
);
7633 init_tg_cfs_entry(&root_task_group
, &rq
->cfs
, NULL
, i
, NULL
);
7634 #endif /* CONFIG_FAIR_GROUP_SCHED */
7636 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
7637 #ifdef CONFIG_RT_GROUP_SCHED
7638 init_tg_rt_entry(&root_task_group
, &rq
->rt
, NULL
, i
, NULL
);
7641 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
7642 rq
->cpu_load
[j
] = 0;
7644 rq
->last_load_update_tick
= jiffies
;
7649 rq
->cpu_capacity
= rq
->cpu_capacity_orig
= SCHED_CAPACITY_SCALE
;
7650 rq
->balance_callback
= NULL
;
7651 rq
->active_balance
= 0;
7652 rq
->next_balance
= jiffies
;
7657 rq
->avg_idle
= 2*sysctl_sched_migration_cost
;
7658 rq
->max_idle_balance_cost
= sysctl_sched_migration_cost
;
7660 INIT_LIST_HEAD(&rq
->cfs_tasks
);
7662 rq_attach_root(rq
, &def_root_domain
);
7663 #ifdef CONFIG_NO_HZ_COMMON
7666 #ifdef CONFIG_NO_HZ_FULL
7667 rq
->last_sched_tick
= 0;
7671 atomic_set(&rq
->nr_iowait
, 0);
7674 set_load_weight(&init_task
);
7676 #ifdef CONFIG_PREEMPT_NOTIFIERS
7677 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
7681 * The boot idle thread does lazy MMU switching as well:
7683 atomic_inc(&init_mm
.mm_count
);
7684 enter_lazy_tlb(&init_mm
, current
);
7687 * During early bootup we pretend to be a normal task:
7689 current
->sched_class
= &fair_sched_class
;
7692 * Make us the idle thread. Technically, schedule() should not be
7693 * called from this thread, however somewhere below it might be,
7694 * but because we are the idle thread, we just pick up running again
7695 * when this runqueue becomes "idle".
7697 init_idle(current
, smp_processor_id());
7699 calc_load_update
= jiffies
+ LOAD_FREQ
;
7702 zalloc_cpumask_var(&sched_domains_tmpmask
, GFP_NOWAIT
);
7703 /* May be allocated at isolcpus cmdline parse time */
7704 if (cpu_isolated_map
== NULL
)
7705 zalloc_cpumask_var(&cpu_isolated_map
, GFP_NOWAIT
);
7706 idle_thread_set_boot_cpu();
7707 set_cpu_rq_start_time();
7709 init_sched_fair_class();
7711 scheduler_running
= 1;
7714 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7715 static inline int preempt_count_equals(int preempt_offset
)
7717 int nested
= preempt_count() + rcu_preempt_depth();
7719 return (nested
== preempt_offset
);
7722 void __might_sleep(const char *file
, int line
, int preempt_offset
)
7725 * Blocking primitives will set (and therefore destroy) current->state,
7726 * since we will exit with TASK_RUNNING make sure we enter with it,
7727 * otherwise we will destroy state.
7729 WARN_ONCE(current
->state
!= TASK_RUNNING
&& current
->task_state_change
,
7730 "do not call blocking ops when !TASK_RUNNING; "
7731 "state=%lx set at [<%p>] %pS\n",
7733 (void *)current
->task_state_change
,
7734 (void *)current
->task_state_change
);
7736 ___might_sleep(file
, line
, preempt_offset
);
7738 EXPORT_SYMBOL(__might_sleep
);
7740 void ___might_sleep(const char *file
, int line
, int preempt_offset
)
7742 static unsigned long prev_jiffy
; /* ratelimiting */
7744 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7745 if ((preempt_count_equals(preempt_offset
) && !irqs_disabled() &&
7746 !is_idle_task(current
)) ||
7747 system_state
!= SYSTEM_RUNNING
|| oops_in_progress
)
7749 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
7751 prev_jiffy
= jiffies
;
7754 "BUG: sleeping function called from invalid context at %s:%d\n",
7757 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7758 in_atomic(), irqs_disabled(),
7759 current
->pid
, current
->comm
);
7761 if (task_stack_end_corrupted(current
))
7762 printk(KERN_EMERG
"Thread overran stack, or stack corrupted\n");
7764 debug_show_held_locks(current
);
7765 if (irqs_disabled())
7766 print_irqtrace_events(current
);
7767 #ifdef CONFIG_DEBUG_PREEMPT
7768 if (!preempt_count_equals(preempt_offset
)) {
7769 pr_err("Preemption disabled at:");
7770 print_ip_sym(current
->preempt_disable_ip
);
7776 EXPORT_SYMBOL(___might_sleep
);
7779 #ifdef CONFIG_MAGIC_SYSRQ
7780 void normalize_rt_tasks(void)
7782 struct task_struct
*g
, *p
;
7783 struct sched_attr attr
= {
7784 .sched_policy
= SCHED_NORMAL
,
7787 read_lock(&tasklist_lock
);
7788 for_each_process_thread(g
, p
) {
7790 * Only normalize user tasks:
7792 if (p
->flags
& PF_KTHREAD
)
7795 p
->se
.exec_start
= 0;
7796 #ifdef CONFIG_SCHEDSTATS
7797 p
->se
.statistics
.wait_start
= 0;
7798 p
->se
.statistics
.sleep_start
= 0;
7799 p
->se
.statistics
.block_start
= 0;
7802 if (!dl_task(p
) && !rt_task(p
)) {
7804 * Renice negative nice level userspace
7807 if (task_nice(p
) < 0)
7808 set_user_nice(p
, 0);
7812 __sched_setscheduler(p
, &attr
, false, false);
7814 read_unlock(&tasklist_lock
);
7817 #endif /* CONFIG_MAGIC_SYSRQ */
7819 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7821 * These functions are only useful for the IA64 MCA handling, or kdb.
7823 * They can only be called when the whole system has been
7824 * stopped - every CPU needs to be quiescent, and no scheduling
7825 * activity can take place. Using them for anything else would
7826 * be a serious bug, and as a result, they aren't even visible
7827 * under any other configuration.
7831 * curr_task - return the current task for a given cpu.
7832 * @cpu: the processor in question.
7834 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7836 * Return: The current task for @cpu.
7838 struct task_struct
*curr_task(int cpu
)
7840 return cpu_curr(cpu
);
7843 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7847 * set_curr_task - set the current task for a given cpu.
7848 * @cpu: the processor in question.
7849 * @p: the task pointer to set.
7851 * Description: This function must only be used when non-maskable interrupts
7852 * are serviced on a separate stack. It allows the architecture to switch the
7853 * notion of the current task on a cpu in a non-blocking manner. This function
7854 * must be called with all CPU's synchronized, and interrupts disabled, the
7855 * and caller must save the original value of the current task (see
7856 * curr_task() above) and restore that value before reenabling interrupts and
7857 * re-starting the system.
7859 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7861 void set_curr_task(int cpu
, struct task_struct
*p
)
7868 #ifdef CONFIG_CGROUP_SCHED
7869 /* task_group_lock serializes the addition/removal of task groups */
7870 static DEFINE_SPINLOCK(task_group_lock
);
7872 static void free_sched_group(struct task_group
*tg
)
7874 free_fair_sched_group(tg
);
7875 free_rt_sched_group(tg
);
7877 kmem_cache_free(task_group_cache
, tg
);
7880 /* allocate runqueue etc for a new task group */
7881 struct task_group
*sched_create_group(struct task_group
*parent
)
7883 struct task_group
*tg
;
7885 tg
= kmem_cache_alloc(task_group_cache
, GFP_KERNEL
| __GFP_ZERO
);
7887 return ERR_PTR(-ENOMEM
);
7889 if (!alloc_fair_sched_group(tg
, parent
))
7892 if (!alloc_rt_sched_group(tg
, parent
))
7898 free_sched_group(tg
);
7899 return ERR_PTR(-ENOMEM
);
7902 void sched_online_group(struct task_group
*tg
, struct task_group
*parent
)
7904 unsigned long flags
;
7906 spin_lock_irqsave(&task_group_lock
, flags
);
7907 list_add_rcu(&tg
->list
, &task_groups
);
7909 WARN_ON(!parent
); /* root should already exist */
7911 tg
->parent
= parent
;
7912 INIT_LIST_HEAD(&tg
->children
);
7913 list_add_rcu(&tg
->siblings
, &parent
->children
);
7914 spin_unlock_irqrestore(&task_group_lock
, flags
);
7917 /* rcu callback to free various structures associated with a task group */
7918 static void free_sched_group_rcu(struct rcu_head
*rhp
)
7920 /* now it should be safe to free those cfs_rqs */
7921 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
7924 /* Destroy runqueue etc associated with a task group */
7925 void sched_destroy_group(struct task_group
*tg
)
7927 /* wait for possible concurrent references to cfs_rqs complete */
7928 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
7931 void sched_offline_group(struct task_group
*tg
)
7933 unsigned long flags
;
7936 /* end participation in shares distribution */
7937 for_each_possible_cpu(i
)
7938 unregister_fair_sched_group(tg
, i
);
7940 spin_lock_irqsave(&task_group_lock
, flags
);
7941 list_del_rcu(&tg
->list
);
7942 list_del_rcu(&tg
->siblings
);
7943 spin_unlock_irqrestore(&task_group_lock
, flags
);
7946 /* change task's runqueue when it moves between groups.
7947 * The caller of this function should have put the task in its new group
7948 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7949 * reflect its new group.
7951 void sched_move_task(struct task_struct
*tsk
)
7953 struct task_group
*tg
;
7954 int queued
, running
;
7955 unsigned long flags
;
7958 rq
= task_rq_lock(tsk
, &flags
);
7960 running
= task_current(rq
, tsk
);
7961 queued
= task_on_rq_queued(tsk
);
7964 dequeue_task(rq
, tsk
, DEQUEUE_SAVE
);
7965 if (unlikely(running
))
7966 put_prev_task(rq
, tsk
);
7969 * All callers are synchronized by task_rq_lock(); we do not use RCU
7970 * which is pointless here. Thus, we pass "true" to task_css_check()
7971 * to prevent lockdep warnings.
7973 tg
= container_of(task_css_check(tsk
, cpu_cgrp_id
, true),
7974 struct task_group
, css
);
7975 tg
= autogroup_task_group(tsk
, tg
);
7976 tsk
->sched_task_group
= tg
;
7978 #ifdef CONFIG_FAIR_GROUP_SCHED
7979 if (tsk
->sched_class
->task_move_group
)
7980 tsk
->sched_class
->task_move_group(tsk
);
7983 set_task_rq(tsk
, task_cpu(tsk
));
7985 if (unlikely(running
))
7986 tsk
->sched_class
->set_curr_task(rq
);
7988 enqueue_task(rq
, tsk
, ENQUEUE_RESTORE
);
7990 task_rq_unlock(rq
, tsk
, &flags
);
7992 #endif /* CONFIG_CGROUP_SCHED */
7994 #ifdef CONFIG_RT_GROUP_SCHED
7996 * Ensure that the real time constraints are schedulable.
7998 static DEFINE_MUTEX(rt_constraints_mutex
);
8000 /* Must be called with tasklist_lock held */
8001 static inline int tg_has_rt_tasks(struct task_group
*tg
)
8003 struct task_struct
*g
, *p
;
8006 * Autogroups do not have RT tasks; see autogroup_create().
8008 if (task_group_is_autogroup(tg
))
8011 for_each_process_thread(g
, p
) {
8012 if (rt_task(p
) && task_group(p
) == tg
)
8019 struct rt_schedulable_data
{
8020 struct task_group
*tg
;
8025 static int tg_rt_schedulable(struct task_group
*tg
, void *data
)
8027 struct rt_schedulable_data
*d
= data
;
8028 struct task_group
*child
;
8029 unsigned long total
, sum
= 0;
8030 u64 period
, runtime
;
8032 period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8033 runtime
= tg
->rt_bandwidth
.rt_runtime
;
8036 period
= d
->rt_period
;
8037 runtime
= d
->rt_runtime
;
8041 * Cannot have more runtime than the period.
8043 if (runtime
> period
&& runtime
!= RUNTIME_INF
)
8047 * Ensure we don't starve existing RT tasks.
8049 if (rt_bandwidth_enabled() && !runtime
&& tg_has_rt_tasks(tg
))
8052 total
= to_ratio(period
, runtime
);
8055 * Nobody can have more than the global setting allows.
8057 if (total
> to_ratio(global_rt_period(), global_rt_runtime()))
8061 * The sum of our children's runtime should not exceed our own.
8063 list_for_each_entry_rcu(child
, &tg
->children
, siblings
) {
8064 period
= ktime_to_ns(child
->rt_bandwidth
.rt_period
);
8065 runtime
= child
->rt_bandwidth
.rt_runtime
;
8067 if (child
== d
->tg
) {
8068 period
= d
->rt_period
;
8069 runtime
= d
->rt_runtime
;
8072 sum
+= to_ratio(period
, runtime
);
8081 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
8085 struct rt_schedulable_data data
= {
8087 .rt_period
= period
,
8088 .rt_runtime
= runtime
,
8092 ret
= walk_tg_tree(tg_rt_schedulable
, tg_nop
, &data
);
8098 static int tg_set_rt_bandwidth(struct task_group
*tg
,
8099 u64 rt_period
, u64 rt_runtime
)
8104 * Disallowing the root group RT runtime is BAD, it would disallow the
8105 * kernel creating (and or operating) RT threads.
8107 if (tg
== &root_task_group
&& rt_runtime
== 0)
8110 /* No period doesn't make any sense. */
8114 mutex_lock(&rt_constraints_mutex
);
8115 read_lock(&tasklist_lock
);
8116 err
= __rt_schedulable(tg
, rt_period
, rt_runtime
);
8120 raw_spin_lock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8121 tg
->rt_bandwidth
.rt_period
= ns_to_ktime(rt_period
);
8122 tg
->rt_bandwidth
.rt_runtime
= rt_runtime
;
8124 for_each_possible_cpu(i
) {
8125 struct rt_rq
*rt_rq
= tg
->rt_rq
[i
];
8127 raw_spin_lock(&rt_rq
->rt_runtime_lock
);
8128 rt_rq
->rt_runtime
= rt_runtime
;
8129 raw_spin_unlock(&rt_rq
->rt_runtime_lock
);
8131 raw_spin_unlock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8133 read_unlock(&tasklist_lock
);
8134 mutex_unlock(&rt_constraints_mutex
);
8139 static int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
8141 u64 rt_runtime
, rt_period
;
8143 rt_period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8144 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
8145 if (rt_runtime_us
< 0)
8146 rt_runtime
= RUNTIME_INF
;
8148 return tg_set_rt_bandwidth(tg
, rt_period
, rt_runtime
);
8151 static long sched_group_rt_runtime(struct task_group
*tg
)
8155 if (tg
->rt_bandwidth
.rt_runtime
== RUNTIME_INF
)
8158 rt_runtime_us
= tg
->rt_bandwidth
.rt_runtime
;
8159 do_div(rt_runtime_us
, NSEC_PER_USEC
);
8160 return rt_runtime_us
;
8163 static int sched_group_set_rt_period(struct task_group
*tg
, u64 rt_period_us
)
8165 u64 rt_runtime
, rt_period
;
8167 rt_period
= rt_period_us
* NSEC_PER_USEC
;
8168 rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
8170 return tg_set_rt_bandwidth(tg
, rt_period
, rt_runtime
);
8173 static long sched_group_rt_period(struct task_group
*tg
)
8177 rt_period_us
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8178 do_div(rt_period_us
, NSEC_PER_USEC
);
8179 return rt_period_us
;
8181 #endif /* CONFIG_RT_GROUP_SCHED */
8183 #ifdef CONFIG_RT_GROUP_SCHED
8184 static int sched_rt_global_constraints(void)
8188 mutex_lock(&rt_constraints_mutex
);
8189 read_lock(&tasklist_lock
);
8190 ret
= __rt_schedulable(NULL
, 0, 0);
8191 read_unlock(&tasklist_lock
);
8192 mutex_unlock(&rt_constraints_mutex
);
8197 static int sched_rt_can_attach(struct task_group
*tg
, struct task_struct
*tsk
)
8199 /* Don't accept realtime tasks when there is no way for them to run */
8200 if (rt_task(tsk
) && tg
->rt_bandwidth
.rt_runtime
== 0)
8206 #else /* !CONFIG_RT_GROUP_SCHED */
8207 static int sched_rt_global_constraints(void)
8209 unsigned long flags
;
8212 raw_spin_lock_irqsave(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8213 for_each_possible_cpu(i
) {
8214 struct rt_rq
*rt_rq
= &cpu_rq(i
)->rt
;
8216 raw_spin_lock(&rt_rq
->rt_runtime_lock
);
8217 rt_rq
->rt_runtime
= global_rt_runtime();
8218 raw_spin_unlock(&rt_rq
->rt_runtime_lock
);
8220 raw_spin_unlock_irqrestore(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8224 #endif /* CONFIG_RT_GROUP_SCHED */
8226 static int sched_dl_global_validate(void)
8228 u64 runtime
= global_rt_runtime();
8229 u64 period
= global_rt_period();
8230 u64 new_bw
= to_ratio(period
, runtime
);
8233 unsigned long flags
;
8236 * Here we want to check the bandwidth not being set to some
8237 * value smaller than the currently allocated bandwidth in
8238 * any of the root_domains.
8240 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
8241 * cycling on root_domains... Discussion on different/better
8242 * solutions is welcome!
8244 for_each_possible_cpu(cpu
) {
8245 rcu_read_lock_sched();
8246 dl_b
= dl_bw_of(cpu
);
8248 raw_spin_lock_irqsave(&dl_b
->lock
, flags
);
8249 if (new_bw
< dl_b
->total_bw
)
8251 raw_spin_unlock_irqrestore(&dl_b
->lock
, flags
);
8253 rcu_read_unlock_sched();
8262 static void sched_dl_do_global(void)
8267 unsigned long flags
;
8269 def_dl_bandwidth
.dl_period
= global_rt_period();
8270 def_dl_bandwidth
.dl_runtime
= global_rt_runtime();
8272 if (global_rt_runtime() != RUNTIME_INF
)
8273 new_bw
= to_ratio(global_rt_period(), global_rt_runtime());
8276 * FIXME: As above...
8278 for_each_possible_cpu(cpu
) {
8279 rcu_read_lock_sched();
8280 dl_b
= dl_bw_of(cpu
);
8282 raw_spin_lock_irqsave(&dl_b
->lock
, flags
);
8284 raw_spin_unlock_irqrestore(&dl_b
->lock
, flags
);
8286 rcu_read_unlock_sched();
8290 static int sched_rt_global_validate(void)
8292 if (sysctl_sched_rt_period
<= 0)
8295 if ((sysctl_sched_rt_runtime
!= RUNTIME_INF
) &&
8296 (sysctl_sched_rt_runtime
> sysctl_sched_rt_period
))
8302 static void sched_rt_do_global(void)
8304 def_rt_bandwidth
.rt_runtime
= global_rt_runtime();
8305 def_rt_bandwidth
.rt_period
= ns_to_ktime(global_rt_period());
8308 int sched_rt_handler(struct ctl_table
*table
, int write
,
8309 void __user
*buffer
, size_t *lenp
,
8312 int old_period
, old_runtime
;
8313 static DEFINE_MUTEX(mutex
);
8317 old_period
= sysctl_sched_rt_period
;
8318 old_runtime
= sysctl_sched_rt_runtime
;
8320 ret
= proc_dointvec(table
, write
, buffer
, lenp
, ppos
);
8322 if (!ret
&& write
) {
8323 ret
= sched_rt_global_validate();
8327 ret
= sched_dl_global_validate();
8331 ret
= sched_rt_global_constraints();
8335 sched_rt_do_global();
8336 sched_dl_do_global();
8340 sysctl_sched_rt_period
= old_period
;
8341 sysctl_sched_rt_runtime
= old_runtime
;
8343 mutex_unlock(&mutex
);
8348 int sched_rr_handler(struct ctl_table
*table
, int write
,
8349 void __user
*buffer
, size_t *lenp
,
8353 static DEFINE_MUTEX(mutex
);
8356 ret
= proc_dointvec(table
, write
, buffer
, lenp
, ppos
);
8357 /* make sure that internally we keep jiffies */
8358 /* also, writing zero resets timeslice to default */
8359 if (!ret
&& write
) {
8360 sched_rr_timeslice
= sched_rr_timeslice
<= 0 ?
8361 RR_TIMESLICE
: msecs_to_jiffies(sched_rr_timeslice
);
8363 mutex_unlock(&mutex
);
8367 #ifdef CONFIG_CGROUP_SCHED
8369 static inline struct task_group
*css_tg(struct cgroup_subsys_state
*css
)
8371 return css
? container_of(css
, struct task_group
, css
) : NULL
;
8374 static struct cgroup_subsys_state
*
8375 cpu_cgroup_css_alloc(struct cgroup_subsys_state
*parent_css
)
8377 struct task_group
*parent
= css_tg(parent_css
);
8378 struct task_group
*tg
;
8381 /* This is early initialization for the top cgroup */
8382 return &root_task_group
.css
;
8385 tg
= sched_create_group(parent
);
8387 return ERR_PTR(-ENOMEM
);
8392 static int cpu_cgroup_css_online(struct cgroup_subsys_state
*css
)
8394 struct task_group
*tg
= css_tg(css
);
8395 struct task_group
*parent
= css_tg(css
->parent
);
8398 sched_online_group(tg
, parent
);
8402 static void cpu_cgroup_css_free(struct cgroup_subsys_state
*css
)
8404 struct task_group
*tg
= css_tg(css
);
8406 sched_destroy_group(tg
);
8409 static void cpu_cgroup_css_offline(struct cgroup_subsys_state
*css
)
8411 struct task_group
*tg
= css_tg(css
);
8413 sched_offline_group(tg
);
8416 static void cpu_cgroup_fork(struct task_struct
*task
)
8418 sched_move_task(task
);
8421 static int cpu_cgroup_can_attach(struct cgroup_taskset
*tset
)
8423 struct task_struct
*task
;
8424 struct cgroup_subsys_state
*css
;
8426 cgroup_taskset_for_each(task
, css
, tset
) {
8427 #ifdef CONFIG_RT_GROUP_SCHED
8428 if (!sched_rt_can_attach(css_tg(css
), task
))
8431 /* We don't support RT-tasks being in separate groups */
8432 if (task
->sched_class
!= &fair_sched_class
)
8439 static void cpu_cgroup_attach(struct cgroup_taskset
*tset
)
8441 struct task_struct
*task
;
8442 struct cgroup_subsys_state
*css
;
8444 cgroup_taskset_for_each(task
, css
, tset
)
8445 sched_move_task(task
);
8448 #ifdef CONFIG_FAIR_GROUP_SCHED
8449 static int cpu_shares_write_u64(struct cgroup_subsys_state
*css
,
8450 struct cftype
*cftype
, u64 shareval
)
8452 return sched_group_set_shares(css_tg(css
), scale_load(shareval
));
8455 static u64
cpu_shares_read_u64(struct cgroup_subsys_state
*css
,
8458 struct task_group
*tg
= css_tg(css
);
8460 return (u64
) scale_load_down(tg
->shares
);
8463 #ifdef CONFIG_CFS_BANDWIDTH
8464 static DEFINE_MUTEX(cfs_constraints_mutex
);
8466 const u64 max_cfs_quota_period
= 1 * NSEC_PER_SEC
; /* 1s */
8467 const u64 min_cfs_quota_period
= 1 * NSEC_PER_MSEC
; /* 1ms */
8469 static int __cfs_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
);
8471 static int tg_set_cfs_bandwidth(struct task_group
*tg
, u64 period
, u64 quota
)
8473 int i
, ret
= 0, runtime_enabled
, runtime_was_enabled
;
8474 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
8476 if (tg
== &root_task_group
)
8480 * Ensure we have at some amount of bandwidth every period. This is
8481 * to prevent reaching a state of large arrears when throttled via
8482 * entity_tick() resulting in prolonged exit starvation.
8484 if (quota
< min_cfs_quota_period
|| period
< min_cfs_quota_period
)
8488 * Likewise, bound things on the otherside by preventing insane quota
8489 * periods. This also allows us to normalize in computing quota
8492 if (period
> max_cfs_quota_period
)
8496 * Prevent race between setting of cfs_rq->runtime_enabled and
8497 * unthrottle_offline_cfs_rqs().
8500 mutex_lock(&cfs_constraints_mutex
);
8501 ret
= __cfs_schedulable(tg
, period
, quota
);
8505 runtime_enabled
= quota
!= RUNTIME_INF
;
8506 runtime_was_enabled
= cfs_b
->quota
!= RUNTIME_INF
;
8508 * If we need to toggle cfs_bandwidth_used, off->on must occur
8509 * before making related changes, and on->off must occur afterwards
8511 if (runtime_enabled
&& !runtime_was_enabled
)
8512 cfs_bandwidth_usage_inc();
8513 raw_spin_lock_irq(&cfs_b
->lock
);
8514 cfs_b
->period
= ns_to_ktime(period
);
8515 cfs_b
->quota
= quota
;
8517 __refill_cfs_bandwidth_runtime(cfs_b
);
8518 /* restart the period timer (if active) to handle new period expiry */
8519 if (runtime_enabled
)
8520 start_cfs_bandwidth(cfs_b
);
8521 raw_spin_unlock_irq(&cfs_b
->lock
);
8523 for_each_online_cpu(i
) {
8524 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[i
];
8525 struct rq
*rq
= cfs_rq
->rq
;
8527 raw_spin_lock_irq(&rq
->lock
);
8528 cfs_rq
->runtime_enabled
= runtime_enabled
;
8529 cfs_rq
->runtime_remaining
= 0;
8531 if (cfs_rq
->throttled
)
8532 unthrottle_cfs_rq(cfs_rq
);
8533 raw_spin_unlock_irq(&rq
->lock
);
8535 if (runtime_was_enabled
&& !runtime_enabled
)
8536 cfs_bandwidth_usage_dec();
8538 mutex_unlock(&cfs_constraints_mutex
);
8544 int tg_set_cfs_quota(struct task_group
*tg
, long cfs_quota_us
)
8548 period
= ktime_to_ns(tg
->cfs_bandwidth
.period
);
8549 if (cfs_quota_us
< 0)
8550 quota
= RUNTIME_INF
;
8552 quota
= (u64
)cfs_quota_us
* NSEC_PER_USEC
;
8554 return tg_set_cfs_bandwidth(tg
, period
, quota
);
8557 long tg_get_cfs_quota(struct task_group
*tg
)
8561 if (tg
->cfs_bandwidth
.quota
== RUNTIME_INF
)
8564 quota_us
= tg
->cfs_bandwidth
.quota
;
8565 do_div(quota_us
, NSEC_PER_USEC
);
8570 int tg_set_cfs_period(struct task_group
*tg
, long cfs_period_us
)
8574 period
= (u64
)cfs_period_us
* NSEC_PER_USEC
;
8575 quota
= tg
->cfs_bandwidth
.quota
;
8577 return tg_set_cfs_bandwidth(tg
, period
, quota
);
8580 long tg_get_cfs_period(struct task_group
*tg
)
8584 cfs_period_us
= ktime_to_ns(tg
->cfs_bandwidth
.period
);
8585 do_div(cfs_period_us
, NSEC_PER_USEC
);
8587 return cfs_period_us
;
8590 static s64
cpu_cfs_quota_read_s64(struct cgroup_subsys_state
*css
,
8593 return tg_get_cfs_quota(css_tg(css
));
8596 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state
*css
,
8597 struct cftype
*cftype
, s64 cfs_quota_us
)
8599 return tg_set_cfs_quota(css_tg(css
), cfs_quota_us
);
8602 static u64
cpu_cfs_period_read_u64(struct cgroup_subsys_state
*css
,
8605 return tg_get_cfs_period(css_tg(css
));
8608 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state
*css
,
8609 struct cftype
*cftype
, u64 cfs_period_us
)
8611 return tg_set_cfs_period(css_tg(css
), cfs_period_us
);
8614 struct cfs_schedulable_data
{
8615 struct task_group
*tg
;
8620 * normalize group quota/period to be quota/max_period
8621 * note: units are usecs
8623 static u64
normalize_cfs_quota(struct task_group
*tg
,
8624 struct cfs_schedulable_data
*d
)
8632 period
= tg_get_cfs_period(tg
);
8633 quota
= tg_get_cfs_quota(tg
);
8636 /* note: these should typically be equivalent */
8637 if (quota
== RUNTIME_INF
|| quota
== -1)
8640 return to_ratio(period
, quota
);
8643 static int tg_cfs_schedulable_down(struct task_group
*tg
, void *data
)
8645 struct cfs_schedulable_data
*d
= data
;
8646 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
8647 s64 quota
= 0, parent_quota
= -1;
8650 quota
= RUNTIME_INF
;
8652 struct cfs_bandwidth
*parent_b
= &tg
->parent
->cfs_bandwidth
;
8654 quota
= normalize_cfs_quota(tg
, d
);
8655 parent_quota
= parent_b
->hierarchical_quota
;
8658 * ensure max(child_quota) <= parent_quota, inherit when no
8661 if (quota
== RUNTIME_INF
)
8662 quota
= parent_quota
;
8663 else if (parent_quota
!= RUNTIME_INF
&& quota
> parent_quota
)
8666 cfs_b
->hierarchical_quota
= quota
;
8671 static int __cfs_schedulable(struct task_group
*tg
, u64 period
, u64 quota
)
8674 struct cfs_schedulable_data data
= {
8680 if (quota
!= RUNTIME_INF
) {
8681 do_div(data
.period
, NSEC_PER_USEC
);
8682 do_div(data
.quota
, NSEC_PER_USEC
);
8686 ret
= walk_tg_tree(tg_cfs_schedulable_down
, tg_nop
, &data
);
8692 static int cpu_stats_show(struct seq_file
*sf
, void *v
)
8694 struct task_group
*tg
= css_tg(seq_css(sf
));
8695 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
8697 seq_printf(sf
, "nr_periods %d\n", cfs_b
->nr_periods
);
8698 seq_printf(sf
, "nr_throttled %d\n", cfs_b
->nr_throttled
);
8699 seq_printf(sf
, "throttled_time %llu\n", cfs_b
->throttled_time
);
8703 #endif /* CONFIG_CFS_BANDWIDTH */
8704 #endif /* CONFIG_FAIR_GROUP_SCHED */
8706 #ifdef CONFIG_RT_GROUP_SCHED
8707 static int cpu_rt_runtime_write(struct cgroup_subsys_state
*css
,
8708 struct cftype
*cft
, s64 val
)
8710 return sched_group_set_rt_runtime(css_tg(css
), val
);
8713 static s64
cpu_rt_runtime_read(struct cgroup_subsys_state
*css
,
8716 return sched_group_rt_runtime(css_tg(css
));
8719 static int cpu_rt_period_write_uint(struct cgroup_subsys_state
*css
,
8720 struct cftype
*cftype
, u64 rt_period_us
)
8722 return sched_group_set_rt_period(css_tg(css
), rt_period_us
);
8725 static u64
cpu_rt_period_read_uint(struct cgroup_subsys_state
*css
,
8728 return sched_group_rt_period(css_tg(css
));
8730 #endif /* CONFIG_RT_GROUP_SCHED */
8732 static struct cftype cpu_files
[] = {
8733 #ifdef CONFIG_FAIR_GROUP_SCHED
8736 .read_u64
= cpu_shares_read_u64
,
8737 .write_u64
= cpu_shares_write_u64
,
8740 #ifdef CONFIG_CFS_BANDWIDTH
8742 .name
= "cfs_quota_us",
8743 .read_s64
= cpu_cfs_quota_read_s64
,
8744 .write_s64
= cpu_cfs_quota_write_s64
,
8747 .name
= "cfs_period_us",
8748 .read_u64
= cpu_cfs_period_read_u64
,
8749 .write_u64
= cpu_cfs_period_write_u64
,
8753 .seq_show
= cpu_stats_show
,
8756 #ifdef CONFIG_RT_GROUP_SCHED
8758 .name
= "rt_runtime_us",
8759 .read_s64
= cpu_rt_runtime_read
,
8760 .write_s64
= cpu_rt_runtime_write
,
8763 .name
= "rt_period_us",
8764 .read_u64
= cpu_rt_period_read_uint
,
8765 .write_u64
= cpu_rt_period_write_uint
,
8771 struct cgroup_subsys cpu_cgrp_subsys
= {
8772 .css_alloc
= cpu_cgroup_css_alloc
,
8773 .css_free
= cpu_cgroup_css_free
,
8774 .css_online
= cpu_cgroup_css_online
,
8775 .css_offline
= cpu_cgroup_css_offline
,
8776 .fork
= cpu_cgroup_fork
,
8777 .can_attach
= cpu_cgroup_can_attach
,
8778 .attach
= cpu_cgroup_attach
,
8779 .legacy_cftypes
= cpu_files
,
8783 #endif /* CONFIG_CGROUP_SCHED */
8785 void dump_cpu_task(int cpu
)
8787 pr_info("Task dump for CPU %d:\n", cpu
);
8788 sched_show_task(cpu_curr(cpu
));
8792 * Nice levels are multiplicative, with a gentle 10% change for every
8793 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
8794 * nice 1, it will get ~10% less CPU time than another CPU-bound task
8795 * that remained on nice 0.
8797 * The "10% effect" is relative and cumulative: from _any_ nice level,
8798 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
8799 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
8800 * If a task goes up by ~10% and another task goes down by ~10% then
8801 * the relative distance between them is ~25%.)
8803 const int sched_prio_to_weight
[40] = {
8804 /* -20 */ 88761, 71755, 56483, 46273, 36291,
8805 /* -15 */ 29154, 23254, 18705, 14949, 11916,
8806 /* -10 */ 9548, 7620, 6100, 4904, 3906,
8807 /* -5 */ 3121, 2501, 1991, 1586, 1277,
8808 /* 0 */ 1024, 820, 655, 526, 423,
8809 /* 5 */ 335, 272, 215, 172, 137,
8810 /* 10 */ 110, 87, 70, 56, 45,
8811 /* 15 */ 36, 29, 23, 18, 15,
8815 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
8817 * In cases where the weight does not change often, we can use the
8818 * precalculated inverse to speed up arithmetics by turning divisions
8819 * into multiplications:
8821 const u32 sched_prio_to_wmult
[40] = {
8822 /* -20 */ 48388, 59856, 76040, 92818, 118348,
8823 /* -15 */ 147320, 184698, 229616, 287308, 360437,
8824 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
8825 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
8826 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
8827 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
8828 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
8829 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,