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 <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/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/kthread.h>
58 #include <linux/proc_fs.h>
59 #include <linux/seq_file.h>
60 #include <linux/sysctl.h>
61 #include <linux/syscalls.h>
62 #include <linux/times.h>
63 #include <linux/tsacct_kern.h>
64 #include <linux/kprobes.h>
65 #include <linux/delayacct.h>
66 #include <linux/reciprocal_div.h>
67 #include <linux/unistd.h>
68 #include <linux/pagemap.h>
69 #include <linux/hrtimer.h>
70 #include <linux/tick.h>
71 #include <linux/bootmem.h>
72 #include <linux/debugfs.h>
73 #include <linux/ctype.h>
74 #include <linux/ftrace.h>
75 #include <trace/sched.h>
78 #include <asm/irq_regs.h>
80 #include "sched_cpupri.h"
83 * Convert user-nice values [ -20 ... 0 ... 19 ]
84 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
87 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
88 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
89 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
92 * 'User priority' is the nice value converted to something we
93 * can work with better when scaling various scheduler parameters,
94 * it's a [ 0 ... 39 ] range.
96 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
97 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
98 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
101 * Helpers for converting nanosecond timing to jiffy resolution
103 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
105 #define NICE_0_LOAD SCHED_LOAD_SCALE
106 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
109 * These are the 'tuning knobs' of the scheduler:
111 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
112 * Timeslices get refilled after they expire.
114 #define DEF_TIMESLICE (100 * HZ / 1000)
117 * single value that denotes runtime == period, ie unlimited time.
119 #define RUNTIME_INF ((u64)~0ULL)
121 DEFINE_TRACE(sched_wait_task
);
122 DEFINE_TRACE(sched_wakeup
);
123 DEFINE_TRACE(sched_wakeup_new
);
124 DEFINE_TRACE(sched_switch
);
125 DEFINE_TRACE(sched_migrate_task
);
129 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
130 * Since cpu_power is a 'constant', we can use a reciprocal divide.
132 static inline u32
sg_div_cpu_power(const struct sched_group
*sg
, u32 load
)
134 return reciprocal_divide(load
, sg
->reciprocal_cpu_power
);
138 * Each time a sched group cpu_power is changed,
139 * we must compute its reciprocal value
141 static inline void sg_inc_cpu_power(struct sched_group
*sg
, u32 val
)
143 sg
->__cpu_power
+= val
;
144 sg
->reciprocal_cpu_power
= reciprocal_value(sg
->__cpu_power
);
148 static inline int rt_policy(int policy
)
150 if (unlikely(policy
== SCHED_FIFO
|| policy
== SCHED_RR
))
155 static inline int task_has_rt_policy(struct task_struct
*p
)
157 return rt_policy(p
->policy
);
161 * This is the priority-queue data structure of the RT scheduling class:
163 struct rt_prio_array
{
164 DECLARE_BITMAP(bitmap
, MAX_RT_PRIO
+1); /* include 1 bit for delimiter */
165 struct list_head queue
[MAX_RT_PRIO
];
168 struct rt_bandwidth
{
169 /* nests inside the rq lock: */
170 spinlock_t rt_runtime_lock
;
173 struct hrtimer rt_period_timer
;
176 static struct rt_bandwidth def_rt_bandwidth
;
178 static int do_sched_rt_period_timer(struct rt_bandwidth
*rt_b
, int overrun
);
180 static enum hrtimer_restart
sched_rt_period_timer(struct hrtimer
*timer
)
182 struct rt_bandwidth
*rt_b
=
183 container_of(timer
, struct rt_bandwidth
, rt_period_timer
);
189 now
= hrtimer_cb_get_time(timer
);
190 overrun
= hrtimer_forward(timer
, now
, rt_b
->rt_period
);
195 idle
= do_sched_rt_period_timer(rt_b
, overrun
);
198 return idle
? HRTIMER_NORESTART
: HRTIMER_RESTART
;
202 void init_rt_bandwidth(struct rt_bandwidth
*rt_b
, u64 period
, u64 runtime
)
204 rt_b
->rt_period
= ns_to_ktime(period
);
205 rt_b
->rt_runtime
= runtime
;
207 spin_lock_init(&rt_b
->rt_runtime_lock
);
209 hrtimer_init(&rt_b
->rt_period_timer
,
210 CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
211 rt_b
->rt_period_timer
.function
= sched_rt_period_timer
;
212 rt_b
->rt_period_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_UNLOCKED
;
215 static inline int rt_bandwidth_enabled(void)
217 return sysctl_sched_rt_runtime
>= 0;
220 static void start_rt_bandwidth(struct rt_bandwidth
*rt_b
)
224 if (rt_bandwidth_enabled() && rt_b
->rt_runtime
== RUNTIME_INF
)
227 if (hrtimer_active(&rt_b
->rt_period_timer
))
230 spin_lock(&rt_b
->rt_runtime_lock
);
232 if (hrtimer_active(&rt_b
->rt_period_timer
))
235 now
= hrtimer_cb_get_time(&rt_b
->rt_period_timer
);
236 hrtimer_forward(&rt_b
->rt_period_timer
, now
, rt_b
->rt_period
);
237 hrtimer_start_expires(&rt_b
->rt_period_timer
,
240 spin_unlock(&rt_b
->rt_runtime_lock
);
243 #ifdef CONFIG_RT_GROUP_SCHED
244 static void destroy_rt_bandwidth(struct rt_bandwidth
*rt_b
)
246 hrtimer_cancel(&rt_b
->rt_period_timer
);
251 * sched_domains_mutex serializes calls to arch_init_sched_domains,
252 * detach_destroy_domains and partition_sched_domains.
254 static DEFINE_MUTEX(sched_domains_mutex
);
256 #ifdef CONFIG_GROUP_SCHED
258 #include <linux/cgroup.h>
262 static LIST_HEAD(task_groups
);
264 /* task group related information */
266 #ifdef CONFIG_CGROUP_SCHED
267 struct cgroup_subsys_state css
;
270 #ifdef CONFIG_USER_SCHED
274 #ifdef CONFIG_FAIR_GROUP_SCHED
275 /* schedulable entities of this group on each cpu */
276 struct sched_entity
**se
;
277 /* runqueue "owned" by this group on each cpu */
278 struct cfs_rq
**cfs_rq
;
279 unsigned long shares
;
282 #ifdef CONFIG_RT_GROUP_SCHED
283 struct sched_rt_entity
**rt_se
;
284 struct rt_rq
**rt_rq
;
286 struct rt_bandwidth rt_bandwidth
;
290 struct list_head list
;
292 struct task_group
*parent
;
293 struct list_head siblings
;
294 struct list_head children
;
297 #ifdef CONFIG_USER_SCHED
299 /* Helper function to pass uid information to create_sched_user() */
300 void set_tg_uid(struct user_struct
*user
)
302 user
->tg
->uid
= user
->uid
;
307 * Every UID task group (including init_task_group aka UID-0) will
308 * be a child to this group.
310 struct task_group root_task_group
;
312 #ifdef CONFIG_FAIR_GROUP_SCHED
313 /* Default task group's sched entity on each cpu */
314 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
315 /* Default task group's cfs_rq on each cpu */
316 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
317 #endif /* CONFIG_FAIR_GROUP_SCHED */
319 #ifdef CONFIG_RT_GROUP_SCHED
320 static DEFINE_PER_CPU(struct sched_rt_entity
, init_sched_rt_entity
);
321 static DEFINE_PER_CPU(struct rt_rq
, init_rt_rq
) ____cacheline_aligned_in_smp
;
322 #endif /* CONFIG_RT_GROUP_SCHED */
323 #else /* !CONFIG_USER_SCHED */
324 #define root_task_group init_task_group
325 #endif /* CONFIG_USER_SCHED */
327 /* task_group_lock serializes add/remove of task groups and also changes to
328 * a task group's cpu shares.
330 static DEFINE_SPINLOCK(task_group_lock
);
332 #ifdef CONFIG_FAIR_GROUP_SCHED
333 #ifdef CONFIG_USER_SCHED
334 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
335 #else /* !CONFIG_USER_SCHED */
336 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
337 #endif /* CONFIG_USER_SCHED */
340 * A weight of 0 or 1 can cause arithmetics problems.
341 * A weight of a cfs_rq is the sum of weights of which entities
342 * are queued on this cfs_rq, so a weight of a entity should not be
343 * too large, so as the shares value of a task group.
344 * (The default weight is 1024 - so there's no practical
345 * limitation from this.)
348 #define MAX_SHARES (1UL << 18)
350 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
353 /* Default task group.
354 * Every task in system belong to this group at bootup.
356 struct task_group init_task_group
;
358 /* return group to which a task belongs */
359 static inline struct task_group
*task_group(struct task_struct
*p
)
361 struct task_group
*tg
;
363 #ifdef CONFIG_USER_SCHED
365 #elif defined(CONFIG_CGROUP_SCHED)
366 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
367 struct task_group
, css
);
369 tg
= &init_task_group
;
374 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
375 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
)
377 #ifdef CONFIG_FAIR_GROUP_SCHED
378 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
379 p
->se
.parent
= task_group(p
)->se
[cpu
];
382 #ifdef CONFIG_RT_GROUP_SCHED
383 p
->rt
.rt_rq
= task_group(p
)->rt_rq
[cpu
];
384 p
->rt
.parent
= task_group(p
)->rt_se
[cpu
];
390 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
) { }
391 static inline struct task_group
*task_group(struct task_struct
*p
)
396 #endif /* CONFIG_GROUP_SCHED */
398 /* CFS-related fields in a runqueue */
400 struct load_weight load
;
401 unsigned long nr_running
;
406 struct rb_root tasks_timeline
;
407 struct rb_node
*rb_leftmost
;
409 struct list_head tasks
;
410 struct list_head
*balance_iterator
;
413 * 'curr' points to currently running entity on this cfs_rq.
414 * It is set to NULL otherwise (i.e when none are currently running).
416 struct sched_entity
*curr
, *next
, *last
;
418 unsigned int nr_spread_over
;
420 #ifdef CONFIG_FAIR_GROUP_SCHED
421 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
424 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
425 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
426 * (like users, containers etc.)
428 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
429 * list is used during load balance.
431 struct list_head leaf_cfs_rq_list
;
432 struct task_group
*tg
; /* group that "owns" this runqueue */
436 * the part of load.weight contributed by tasks
438 unsigned long task_weight
;
441 * h_load = weight * f(tg)
443 * Where f(tg) is the recursive weight fraction assigned to
446 unsigned long h_load
;
449 * this cpu's part of tg->shares
451 unsigned long shares
;
454 * load.weight at the time we set shares
456 unsigned long rq_weight
;
461 /* Real-Time classes' related field in a runqueue: */
463 struct rt_prio_array active
;
464 unsigned long rt_nr_running
;
465 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
466 int highest_prio
; /* highest queued rt task prio */
469 unsigned long rt_nr_migratory
;
475 /* Nests inside the rq lock: */
476 spinlock_t rt_runtime_lock
;
478 #ifdef CONFIG_RT_GROUP_SCHED
479 unsigned long rt_nr_boosted
;
482 struct list_head leaf_rt_rq_list
;
483 struct task_group
*tg
;
484 struct sched_rt_entity
*rt_se
;
491 * We add the notion of a root-domain which will be used to define per-domain
492 * variables. Each exclusive cpuset essentially defines an island domain by
493 * fully partitioning the member cpus from any other cpuset. Whenever a new
494 * exclusive cpuset is created, we also create and attach a new root-domain
501 cpumask_var_t online
;
504 * The "RT overload" flag: it gets set if a CPU has more than
505 * one runnable RT task.
507 cpumask_var_t rto_mask
;
510 struct cpupri cpupri
;
512 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
514 * Preferred wake up cpu nominated by sched_mc balance that will be
515 * used when most cpus are idle in the system indicating overall very
516 * low system utilisation. Triggered at POWERSAVINGS_BALANCE_WAKEUP(2)
518 unsigned int sched_mc_preferred_wakeup_cpu
;
523 * By default the system creates a single root-domain with all cpus as
524 * members (mimicking the global state we have today).
526 static struct root_domain def_root_domain
;
531 * This is the main, per-CPU runqueue data structure.
533 * Locking rule: those places that want to lock multiple runqueues
534 * (such as the load balancing or the thread migration code), lock
535 * acquire operations must be ordered by ascending &runqueue.
542 * nr_running and cpu_load should be in the same cacheline because
543 * remote CPUs use both these fields when doing load calculation.
545 unsigned long nr_running
;
546 #define CPU_LOAD_IDX_MAX 5
547 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
548 unsigned char idle_at_tick
;
550 unsigned long last_tick_seen
;
551 unsigned char in_nohz_recently
;
553 /* capture load from *all* tasks on this cpu: */
554 struct load_weight load
;
555 unsigned long nr_load_updates
;
561 #ifdef CONFIG_FAIR_GROUP_SCHED
562 /* list of leaf cfs_rq on this cpu: */
563 struct list_head leaf_cfs_rq_list
;
565 #ifdef CONFIG_RT_GROUP_SCHED
566 struct list_head leaf_rt_rq_list
;
570 * This is part of a global counter where only the total sum
571 * over all CPUs matters. A task can increase this counter on
572 * one CPU and if it got migrated afterwards it may decrease
573 * it on another CPU. Always updated under the runqueue lock:
575 unsigned long nr_uninterruptible
;
577 struct task_struct
*curr
, *idle
;
578 unsigned long next_balance
;
579 struct mm_struct
*prev_mm
;
586 struct root_domain
*rd
;
587 struct sched_domain
*sd
;
589 /* For active balancing */
592 /* cpu of this runqueue: */
596 unsigned long avg_load_per_task
;
598 struct task_struct
*migration_thread
;
599 struct list_head migration_queue
;
602 #ifdef CONFIG_SCHED_HRTICK
604 int hrtick_csd_pending
;
605 struct call_single_data hrtick_csd
;
607 struct hrtimer hrtick_timer
;
610 #ifdef CONFIG_SCHEDSTATS
612 struct sched_info rq_sched_info
;
614 /* sys_sched_yield() stats */
615 unsigned int yld_exp_empty
;
616 unsigned int yld_act_empty
;
617 unsigned int yld_both_empty
;
618 unsigned int yld_count
;
620 /* schedule() stats */
621 unsigned int sched_switch
;
622 unsigned int sched_count
;
623 unsigned int sched_goidle
;
625 /* try_to_wake_up() stats */
626 unsigned int ttwu_count
;
627 unsigned int ttwu_local
;
630 unsigned int bkl_count
;
634 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
636 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
, int sync
)
638 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
, sync
);
641 static inline int cpu_of(struct rq
*rq
)
651 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
652 * See detach_destroy_domains: synchronize_sched for details.
654 * The domain tree of any CPU may only be accessed from within
655 * preempt-disabled sections.
657 #define for_each_domain(cpu, __sd) \
658 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
660 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
661 #define this_rq() (&__get_cpu_var(runqueues))
662 #define task_rq(p) cpu_rq(task_cpu(p))
663 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
665 static inline void update_rq_clock(struct rq
*rq
)
667 rq
->clock
= sched_clock_cpu(cpu_of(rq
));
671 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
673 #ifdef CONFIG_SCHED_DEBUG
674 # define const_debug __read_mostly
676 # define const_debug static const
682 * Returns true if the current cpu runqueue is locked.
683 * This interface allows printk to be called with the runqueue lock
684 * held and know whether or not it is OK to wake up the klogd.
686 int runqueue_is_locked(void)
689 struct rq
*rq
= cpu_rq(cpu
);
692 ret
= spin_is_locked(&rq
->lock
);
698 * Debugging: various feature bits
701 #define SCHED_FEAT(name, enabled) \
702 __SCHED_FEAT_##name ,
705 #include "sched_features.h"
710 #define SCHED_FEAT(name, enabled) \
711 (1UL << __SCHED_FEAT_##name) * enabled |
713 const_debug
unsigned int sysctl_sched_features
=
714 #include "sched_features.h"
719 #ifdef CONFIG_SCHED_DEBUG
720 #define SCHED_FEAT(name, enabled) \
723 static __read_mostly
char *sched_feat_names
[] = {
724 #include "sched_features.h"
730 static int sched_feat_show(struct seq_file
*m
, void *v
)
734 for (i
= 0; sched_feat_names
[i
]; i
++) {
735 if (!(sysctl_sched_features
& (1UL << i
)))
737 seq_printf(m
, "%s ", sched_feat_names
[i
]);
745 sched_feat_write(struct file
*filp
, const char __user
*ubuf
,
746 size_t cnt
, loff_t
*ppos
)
756 if (copy_from_user(&buf
, ubuf
, cnt
))
761 if (strncmp(buf
, "NO_", 3) == 0) {
766 for (i
= 0; sched_feat_names
[i
]; i
++) {
767 int len
= strlen(sched_feat_names
[i
]);
769 if (strncmp(cmp
, sched_feat_names
[i
], len
) == 0) {
771 sysctl_sched_features
&= ~(1UL << i
);
773 sysctl_sched_features
|= (1UL << i
);
778 if (!sched_feat_names
[i
])
786 static int sched_feat_open(struct inode
*inode
, struct file
*filp
)
788 return single_open(filp
, sched_feat_show
, NULL
);
791 static struct file_operations sched_feat_fops
= {
792 .open
= sched_feat_open
,
793 .write
= sched_feat_write
,
796 .release
= single_release
,
799 static __init
int sched_init_debug(void)
801 debugfs_create_file("sched_features", 0644, NULL
, NULL
,
806 late_initcall(sched_init_debug
);
810 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
813 * Number of tasks to iterate in a single balance run.
814 * Limited because this is done with IRQs disabled.
816 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
819 * ratelimit for updating the group shares.
822 unsigned int sysctl_sched_shares_ratelimit
= 250000;
825 * Inject some fuzzyness into changing the per-cpu group shares
826 * this avoids remote rq-locks at the expense of fairness.
829 unsigned int sysctl_sched_shares_thresh
= 4;
832 * period over which we measure -rt task cpu usage in us.
835 unsigned int sysctl_sched_rt_period
= 1000000;
837 static __read_mostly
int scheduler_running
;
840 * part of the period that we allow rt tasks to run in us.
843 int sysctl_sched_rt_runtime
= 950000;
845 static inline u64
global_rt_period(void)
847 return (u64
)sysctl_sched_rt_period
* NSEC_PER_USEC
;
850 static inline u64
global_rt_runtime(void)
852 if (sysctl_sched_rt_runtime
< 0)
855 return (u64
)sysctl_sched_rt_runtime
* NSEC_PER_USEC
;
858 #ifndef prepare_arch_switch
859 # define prepare_arch_switch(next) do { } while (0)
861 #ifndef finish_arch_switch
862 # define finish_arch_switch(prev) do { } while (0)
865 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
867 return rq
->curr
== p
;
870 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
871 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
873 return task_current(rq
, p
);
876 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
880 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
882 #ifdef CONFIG_DEBUG_SPINLOCK
883 /* this is a valid case when another task releases the spinlock */
884 rq
->lock
.owner
= current
;
887 * If we are tracking spinlock dependencies then we have to
888 * fix up the runqueue lock - which gets 'carried over' from
891 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
893 spin_unlock_irq(&rq
->lock
);
896 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
897 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
902 return task_current(rq
, p
);
906 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
910 * We can optimise this out completely for !SMP, because the
911 * SMP rebalancing from interrupt is the only thing that cares
916 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
917 spin_unlock_irq(&rq
->lock
);
919 spin_unlock(&rq
->lock
);
923 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
927 * After ->oncpu is cleared, the task can be moved to a different CPU.
928 * We must ensure this doesn't happen until the switch is completely
934 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
938 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
941 * __task_rq_lock - lock the runqueue a given task resides on.
942 * Must be called interrupts disabled.
944 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
948 struct rq
*rq
= task_rq(p
);
949 spin_lock(&rq
->lock
);
950 if (likely(rq
== task_rq(p
)))
952 spin_unlock(&rq
->lock
);
957 * task_rq_lock - lock the runqueue a given task resides on and disable
958 * interrupts. Note the ordering: we can safely lookup the task_rq without
959 * explicitly disabling preemption.
961 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
967 local_irq_save(*flags
);
969 spin_lock(&rq
->lock
);
970 if (likely(rq
== task_rq(p
)))
972 spin_unlock_irqrestore(&rq
->lock
, *flags
);
976 void task_rq_unlock_wait(struct task_struct
*p
)
978 struct rq
*rq
= task_rq(p
);
980 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
981 spin_unlock_wait(&rq
->lock
);
984 static void __task_rq_unlock(struct rq
*rq
)
987 spin_unlock(&rq
->lock
);
990 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
993 spin_unlock_irqrestore(&rq
->lock
, *flags
);
997 * this_rq_lock - lock this runqueue and disable interrupts.
999 static struct rq
*this_rq_lock(void)
1000 __acquires(rq
->lock
)
1004 local_irq_disable();
1006 spin_lock(&rq
->lock
);
1011 #ifdef CONFIG_SCHED_HRTICK
1013 * Use HR-timers to deliver accurate preemption points.
1015 * Its all a bit involved since we cannot program an hrt while holding the
1016 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1019 * When we get rescheduled we reprogram the hrtick_timer outside of the
1025 * - enabled by features
1026 * - hrtimer is actually high res
1028 static inline int hrtick_enabled(struct rq
*rq
)
1030 if (!sched_feat(HRTICK
))
1032 if (!cpu_active(cpu_of(rq
)))
1034 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
1037 static void hrtick_clear(struct rq
*rq
)
1039 if (hrtimer_active(&rq
->hrtick_timer
))
1040 hrtimer_cancel(&rq
->hrtick_timer
);
1044 * High-resolution timer tick.
1045 * Runs from hardirq context with interrupts disabled.
1047 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
1049 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
1051 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1053 spin_lock(&rq
->lock
);
1054 update_rq_clock(rq
);
1055 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
1056 spin_unlock(&rq
->lock
);
1058 return HRTIMER_NORESTART
;
1063 * called from hardirq (IPI) context
1065 static void __hrtick_start(void *arg
)
1067 struct rq
*rq
= arg
;
1069 spin_lock(&rq
->lock
);
1070 hrtimer_restart(&rq
->hrtick_timer
);
1071 rq
->hrtick_csd_pending
= 0;
1072 spin_unlock(&rq
->lock
);
1076 * Called to set the hrtick timer state.
1078 * called with rq->lock held and irqs disabled
1080 static void hrtick_start(struct rq
*rq
, u64 delay
)
1082 struct hrtimer
*timer
= &rq
->hrtick_timer
;
1083 ktime_t time
= ktime_add_ns(timer
->base
->get_time(), delay
);
1085 hrtimer_set_expires(timer
, time
);
1087 if (rq
== this_rq()) {
1088 hrtimer_restart(timer
);
1089 } else if (!rq
->hrtick_csd_pending
) {
1090 __smp_call_function_single(cpu_of(rq
), &rq
->hrtick_csd
);
1091 rq
->hrtick_csd_pending
= 1;
1096 hotplug_hrtick(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
1098 int cpu
= (int)(long)hcpu
;
1101 case CPU_UP_CANCELED
:
1102 case CPU_UP_CANCELED_FROZEN
:
1103 case CPU_DOWN_PREPARE
:
1104 case CPU_DOWN_PREPARE_FROZEN
:
1106 case CPU_DEAD_FROZEN
:
1107 hrtick_clear(cpu_rq(cpu
));
1114 static __init
void init_hrtick(void)
1116 hotcpu_notifier(hotplug_hrtick
, 0);
1120 * Called to set the hrtick timer state.
1122 * called with rq->lock held and irqs disabled
1124 static void hrtick_start(struct rq
*rq
, u64 delay
)
1126 hrtimer_start(&rq
->hrtick_timer
, ns_to_ktime(delay
), HRTIMER_MODE_REL
);
1129 static inline void init_hrtick(void)
1132 #endif /* CONFIG_SMP */
1134 static void init_rq_hrtick(struct rq
*rq
)
1137 rq
->hrtick_csd_pending
= 0;
1139 rq
->hrtick_csd
.flags
= 0;
1140 rq
->hrtick_csd
.func
= __hrtick_start
;
1141 rq
->hrtick_csd
.info
= rq
;
1144 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1145 rq
->hrtick_timer
.function
= hrtick
;
1146 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_PERCPU
;
1148 #else /* CONFIG_SCHED_HRTICK */
1149 static inline void hrtick_clear(struct rq
*rq
)
1153 static inline void init_rq_hrtick(struct rq
*rq
)
1157 static inline void init_hrtick(void)
1160 #endif /* CONFIG_SCHED_HRTICK */
1163 * resched_task - mark a task 'to be rescheduled now'.
1165 * On UP this means the setting of the need_resched flag, on SMP it
1166 * might also involve a cross-CPU call to trigger the scheduler on
1171 #ifndef tsk_is_polling
1172 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1175 static void resched_task(struct task_struct
*p
)
1179 assert_spin_locked(&task_rq(p
)->lock
);
1181 if (unlikely(test_tsk_thread_flag(p
, TIF_NEED_RESCHED
)))
1184 set_tsk_thread_flag(p
, TIF_NEED_RESCHED
);
1187 if (cpu
== smp_processor_id())
1190 /* NEED_RESCHED must be visible before we test polling */
1192 if (!tsk_is_polling(p
))
1193 smp_send_reschedule(cpu
);
1196 static void resched_cpu(int cpu
)
1198 struct rq
*rq
= cpu_rq(cpu
);
1199 unsigned long flags
;
1201 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1203 resched_task(cpu_curr(cpu
));
1204 spin_unlock_irqrestore(&rq
->lock
, flags
);
1209 * When add_timer_on() enqueues a timer into the timer wheel of an
1210 * idle CPU then this timer might expire before the next timer event
1211 * which is scheduled to wake up that CPU. In case of a completely
1212 * idle system the next event might even be infinite time into the
1213 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1214 * leaves the inner idle loop so the newly added timer is taken into
1215 * account when the CPU goes back to idle and evaluates the timer
1216 * wheel for the next timer event.
1218 void wake_up_idle_cpu(int cpu
)
1220 struct rq
*rq
= cpu_rq(cpu
);
1222 if (cpu
== smp_processor_id())
1226 * This is safe, as this function is called with the timer
1227 * wheel base lock of (cpu) held. When the CPU is on the way
1228 * to idle and has not yet set rq->curr to idle then it will
1229 * be serialized on the timer wheel base lock and take the new
1230 * timer into account automatically.
1232 if (rq
->curr
!= rq
->idle
)
1236 * We can set TIF_RESCHED on the idle task of the other CPU
1237 * lockless. The worst case is that the other CPU runs the
1238 * idle task through an additional NOOP schedule()
1240 set_tsk_thread_flag(rq
->idle
, TIF_NEED_RESCHED
);
1242 /* NEED_RESCHED must be visible before we test polling */
1244 if (!tsk_is_polling(rq
->idle
))
1245 smp_send_reschedule(cpu
);
1247 #endif /* CONFIG_NO_HZ */
1249 #else /* !CONFIG_SMP */
1250 static void resched_task(struct task_struct
*p
)
1252 assert_spin_locked(&task_rq(p
)->lock
);
1253 set_tsk_need_resched(p
);
1255 #endif /* CONFIG_SMP */
1257 #if BITS_PER_LONG == 32
1258 # define WMULT_CONST (~0UL)
1260 # define WMULT_CONST (1UL << 32)
1263 #define WMULT_SHIFT 32
1266 * Shift right and round:
1268 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1271 * delta *= weight / lw
1273 static unsigned long
1274 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1275 struct load_weight
*lw
)
1279 if (!lw
->inv_weight
) {
1280 if (BITS_PER_LONG
> 32 && unlikely(lw
->weight
>= WMULT_CONST
))
1283 lw
->inv_weight
= 1 + (WMULT_CONST
-lw
->weight
/2)
1287 tmp
= (u64
)delta_exec
* weight
;
1289 * Check whether we'd overflow the 64-bit multiplication:
1291 if (unlikely(tmp
> WMULT_CONST
))
1292 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1295 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1297 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1300 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1306 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1313 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1314 * of tasks with abnormal "nice" values across CPUs the contribution that
1315 * each task makes to its run queue's load is weighted according to its
1316 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1317 * scaled version of the new time slice allocation that they receive on time
1321 #define WEIGHT_IDLEPRIO 2
1322 #define WMULT_IDLEPRIO (1 << 31)
1325 * Nice levels are multiplicative, with a gentle 10% change for every
1326 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1327 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1328 * that remained on nice 0.
1330 * The "10% effect" is relative and cumulative: from _any_ nice level,
1331 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1332 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1333 * If a task goes up by ~10% and another task goes down by ~10% then
1334 * the relative distance between them is ~25%.)
1336 static const int prio_to_weight
[40] = {
1337 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1338 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1339 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1340 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1341 /* 0 */ 1024, 820, 655, 526, 423,
1342 /* 5 */ 335, 272, 215, 172, 137,
1343 /* 10 */ 110, 87, 70, 56, 45,
1344 /* 15 */ 36, 29, 23, 18, 15,
1348 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1350 * In cases where the weight does not change often, we can use the
1351 * precalculated inverse to speed up arithmetics by turning divisions
1352 * into multiplications:
1354 static const u32 prio_to_wmult
[40] = {
1355 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1356 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1357 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1358 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1359 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1360 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1361 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1362 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1365 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1368 * runqueue iterator, to support SMP load-balancing between different
1369 * scheduling classes, without having to expose their internal data
1370 * structures to the load-balancing proper:
1372 struct rq_iterator
{
1374 struct task_struct
*(*start
)(void *);
1375 struct task_struct
*(*next
)(void *);
1379 static unsigned long
1380 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1381 unsigned long max_load_move
, struct sched_domain
*sd
,
1382 enum cpu_idle_type idle
, int *all_pinned
,
1383 int *this_best_prio
, struct rq_iterator
*iterator
);
1386 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1387 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1388 struct rq_iterator
*iterator
);
1391 #ifdef CONFIG_CGROUP_CPUACCT
1392 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1394 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1397 static inline void inc_cpu_load(struct rq
*rq
, unsigned long load
)
1399 update_load_add(&rq
->load
, load
);
1402 static inline void dec_cpu_load(struct rq
*rq
, unsigned long load
)
1404 update_load_sub(&rq
->load
, load
);
1407 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1408 typedef int (*tg_visitor
)(struct task_group
*, void *);
1411 * Iterate the full tree, calling @down when first entering a node and @up when
1412 * leaving it for the final time.
1414 static int walk_tg_tree(tg_visitor down
, tg_visitor up
, void *data
)
1416 struct task_group
*parent
, *child
;
1420 parent
= &root_task_group
;
1422 ret
= (*down
)(parent
, data
);
1425 list_for_each_entry_rcu(child
, &parent
->children
, siblings
) {
1432 ret
= (*up
)(parent
, data
);
1437 parent
= parent
->parent
;
1446 static int tg_nop(struct task_group
*tg
, void *data
)
1453 static unsigned long source_load(int cpu
, int type
);
1454 static unsigned long target_load(int cpu
, int type
);
1455 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1457 static unsigned long cpu_avg_load_per_task(int cpu
)
1459 struct rq
*rq
= cpu_rq(cpu
);
1460 unsigned long nr_running
= ACCESS_ONCE(rq
->nr_running
);
1463 rq
->avg_load_per_task
= rq
->load
.weight
/ nr_running
;
1465 rq
->avg_load_per_task
= 0;
1467 return rq
->avg_load_per_task
;
1470 #ifdef CONFIG_FAIR_GROUP_SCHED
1472 static void __set_se_shares(struct sched_entity
*se
, unsigned long shares
);
1475 * Calculate and set the cpu's group shares.
1478 update_group_shares_cpu(struct task_group
*tg
, int cpu
,
1479 unsigned long sd_shares
, unsigned long sd_rq_weight
)
1481 unsigned long shares
;
1482 unsigned long rq_weight
;
1487 rq_weight
= tg
->cfs_rq
[cpu
]->rq_weight
;
1490 * \Sum shares * rq_weight
1491 * shares = -----------------------
1495 shares
= (sd_shares
* rq_weight
) / sd_rq_weight
;
1496 shares
= clamp_t(unsigned long, shares
, MIN_SHARES
, MAX_SHARES
);
1498 if (abs(shares
- tg
->se
[cpu
]->load
.weight
) >
1499 sysctl_sched_shares_thresh
) {
1500 struct rq
*rq
= cpu_rq(cpu
);
1501 unsigned long flags
;
1503 spin_lock_irqsave(&rq
->lock
, flags
);
1504 tg
->cfs_rq
[cpu
]->shares
= shares
;
1506 __set_se_shares(tg
->se
[cpu
], shares
);
1507 spin_unlock_irqrestore(&rq
->lock
, flags
);
1512 * Re-compute the task group their per cpu shares over the given domain.
1513 * This needs to be done in a bottom-up fashion because the rq weight of a
1514 * parent group depends on the shares of its child groups.
1516 static int tg_shares_up(struct task_group
*tg
, void *data
)
1518 unsigned long weight
, rq_weight
= 0;
1519 unsigned long shares
= 0;
1520 struct sched_domain
*sd
= data
;
1523 for_each_cpu(i
, sched_domain_span(sd
)) {
1525 * If there are currently no tasks on the cpu pretend there
1526 * is one of average load so that when a new task gets to
1527 * run here it will not get delayed by group starvation.
1529 weight
= tg
->cfs_rq
[i
]->load
.weight
;
1531 weight
= NICE_0_LOAD
;
1533 tg
->cfs_rq
[i
]->rq_weight
= weight
;
1534 rq_weight
+= weight
;
1535 shares
+= tg
->cfs_rq
[i
]->shares
;
1538 if ((!shares
&& rq_weight
) || shares
> tg
->shares
)
1539 shares
= tg
->shares
;
1541 if (!sd
->parent
|| !(sd
->parent
->flags
& SD_LOAD_BALANCE
))
1542 shares
= tg
->shares
;
1544 for_each_cpu(i
, sched_domain_span(sd
))
1545 update_group_shares_cpu(tg
, i
, shares
, rq_weight
);
1551 * Compute the cpu's hierarchical load factor for each task group.
1552 * This needs to be done in a top-down fashion because the load of a child
1553 * group is a fraction of its parents load.
1555 static int tg_load_down(struct task_group
*tg
, void *data
)
1558 long cpu
= (long)data
;
1561 load
= cpu_rq(cpu
)->load
.weight
;
1563 load
= tg
->parent
->cfs_rq
[cpu
]->h_load
;
1564 load
*= tg
->cfs_rq
[cpu
]->shares
;
1565 load
/= tg
->parent
->cfs_rq
[cpu
]->load
.weight
+ 1;
1568 tg
->cfs_rq
[cpu
]->h_load
= load
;
1573 static void update_shares(struct sched_domain
*sd
)
1575 u64 now
= cpu_clock(raw_smp_processor_id());
1576 s64 elapsed
= now
- sd
->last_update
;
1578 if (elapsed
>= (s64
)(u64
)sysctl_sched_shares_ratelimit
) {
1579 sd
->last_update
= now
;
1580 walk_tg_tree(tg_nop
, tg_shares_up
, sd
);
1584 static void update_shares_locked(struct rq
*rq
, struct sched_domain
*sd
)
1586 spin_unlock(&rq
->lock
);
1588 spin_lock(&rq
->lock
);
1591 static void update_h_load(long cpu
)
1593 walk_tg_tree(tg_load_down
, tg_nop
, (void *)cpu
);
1598 static inline void update_shares(struct sched_domain
*sd
)
1602 static inline void update_shares_locked(struct rq
*rq
, struct sched_domain
*sd
)
1609 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1611 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
1612 __releases(this_rq
->lock
)
1613 __acquires(busiest
->lock
)
1614 __acquires(this_rq
->lock
)
1618 if (unlikely(!irqs_disabled())) {
1619 /* printk() doesn't work good under rq->lock */
1620 spin_unlock(&this_rq
->lock
);
1623 if (unlikely(!spin_trylock(&busiest
->lock
))) {
1624 if (busiest
< this_rq
) {
1625 spin_unlock(&this_rq
->lock
);
1626 spin_lock(&busiest
->lock
);
1627 spin_lock_nested(&this_rq
->lock
, SINGLE_DEPTH_NESTING
);
1630 spin_lock_nested(&busiest
->lock
, SINGLE_DEPTH_NESTING
);
1635 static inline void double_unlock_balance(struct rq
*this_rq
, struct rq
*busiest
)
1636 __releases(busiest
->lock
)
1638 spin_unlock(&busiest
->lock
);
1639 lock_set_subclass(&this_rq
->lock
.dep_map
, 0, _RET_IP_
);
1643 #ifdef CONFIG_FAIR_GROUP_SCHED
1644 static void cfs_rq_set_shares(struct cfs_rq
*cfs_rq
, unsigned long shares
)
1647 cfs_rq
->shares
= shares
;
1652 #include "sched_stats.h"
1653 #include "sched_idletask.c"
1654 #include "sched_fair.c"
1655 #include "sched_rt.c"
1656 #ifdef CONFIG_SCHED_DEBUG
1657 # include "sched_debug.c"
1660 #define sched_class_highest (&rt_sched_class)
1661 #define for_each_class(class) \
1662 for (class = sched_class_highest; class; class = class->next)
1664 static void inc_nr_running(struct rq
*rq
)
1669 static void dec_nr_running(struct rq
*rq
)
1674 static void set_load_weight(struct task_struct
*p
)
1676 if (task_has_rt_policy(p
)) {
1677 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1678 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1683 * SCHED_IDLE tasks get minimal weight:
1685 if (p
->policy
== SCHED_IDLE
) {
1686 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1687 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1691 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1692 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1695 static void update_avg(u64
*avg
, u64 sample
)
1697 s64 diff
= sample
- *avg
;
1701 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1703 sched_info_queued(p
);
1704 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1708 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1710 if (sleep
&& p
->se
.last_wakeup
) {
1711 update_avg(&p
->se
.avg_overlap
,
1712 p
->se
.sum_exec_runtime
- p
->se
.last_wakeup
);
1713 p
->se
.last_wakeup
= 0;
1716 sched_info_dequeued(p
);
1717 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1722 * __normal_prio - return the priority that is based on the static prio
1724 static inline int __normal_prio(struct task_struct
*p
)
1726 return p
->static_prio
;
1730 * Calculate the expected normal priority: i.e. priority
1731 * without taking RT-inheritance into account. Might be
1732 * boosted by interactivity modifiers. Changes upon fork,
1733 * setprio syscalls, and whenever the interactivity
1734 * estimator recalculates.
1736 static inline int normal_prio(struct task_struct
*p
)
1740 if (task_has_rt_policy(p
))
1741 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1743 prio
= __normal_prio(p
);
1748 * Calculate the current priority, i.e. the priority
1749 * taken into account by the scheduler. This value might
1750 * be boosted by RT tasks, or might be boosted by
1751 * interactivity modifiers. Will be RT if the task got
1752 * RT-boosted. If not then it returns p->normal_prio.
1754 static int effective_prio(struct task_struct
*p
)
1756 p
->normal_prio
= normal_prio(p
);
1758 * If we are RT tasks or we were boosted to RT priority,
1759 * keep the priority unchanged. Otherwise, update priority
1760 * to the normal priority:
1762 if (!rt_prio(p
->prio
))
1763 return p
->normal_prio
;
1768 * activate_task - move a task to the runqueue.
1770 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1772 if (task_contributes_to_load(p
))
1773 rq
->nr_uninterruptible
--;
1775 enqueue_task(rq
, p
, wakeup
);
1780 * deactivate_task - remove a task from the runqueue.
1782 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1784 if (task_contributes_to_load(p
))
1785 rq
->nr_uninterruptible
++;
1787 dequeue_task(rq
, p
, sleep
);
1792 * task_curr - is this task currently executing on a CPU?
1793 * @p: the task in question.
1795 inline int task_curr(const struct task_struct
*p
)
1797 return cpu_curr(task_cpu(p
)) == p
;
1800 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1802 set_task_rq(p
, cpu
);
1805 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1806 * successfuly executed on another CPU. We must ensure that updates of
1807 * per-task data have been completed by this moment.
1810 task_thread_info(p
)->cpu
= cpu
;
1814 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1815 const struct sched_class
*prev_class
,
1816 int oldprio
, int running
)
1818 if (prev_class
!= p
->sched_class
) {
1819 if (prev_class
->switched_from
)
1820 prev_class
->switched_from(rq
, p
, running
);
1821 p
->sched_class
->switched_to(rq
, p
, running
);
1823 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1828 /* Used instead of source_load when we know the type == 0 */
1829 static unsigned long weighted_cpuload(const int cpu
)
1831 return cpu_rq(cpu
)->load
.weight
;
1835 * Is this task likely cache-hot:
1838 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
1843 * Buddy candidates are cache hot:
1845 if (sched_feat(CACHE_HOT_BUDDY
) &&
1846 (&p
->se
== cfs_rq_of(&p
->se
)->next
||
1847 &p
->se
== cfs_rq_of(&p
->se
)->last
))
1850 if (p
->sched_class
!= &fair_sched_class
)
1853 if (sysctl_sched_migration_cost
== -1)
1855 if (sysctl_sched_migration_cost
== 0)
1858 delta
= now
- p
->se
.exec_start
;
1860 return delta
< (s64
)sysctl_sched_migration_cost
;
1864 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1866 int old_cpu
= task_cpu(p
);
1867 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
1868 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
1869 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
1872 clock_offset
= old_rq
->clock
- new_rq
->clock
;
1874 #ifdef CONFIG_SCHEDSTATS
1875 if (p
->se
.wait_start
)
1876 p
->se
.wait_start
-= clock_offset
;
1877 if (p
->se
.sleep_start
)
1878 p
->se
.sleep_start
-= clock_offset
;
1879 if (p
->se
.block_start
)
1880 p
->se
.block_start
-= clock_offset
;
1881 if (old_cpu
!= new_cpu
) {
1882 schedstat_inc(p
, se
.nr_migrations
);
1883 if (task_hot(p
, old_rq
->clock
, NULL
))
1884 schedstat_inc(p
, se
.nr_forced2_migrations
);
1887 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
1888 new_cfsrq
->min_vruntime
;
1890 __set_task_cpu(p
, new_cpu
);
1893 struct migration_req
{
1894 struct list_head list
;
1896 struct task_struct
*task
;
1899 struct completion done
;
1903 * The task's runqueue lock must be held.
1904 * Returns true if you have to wait for migration thread.
1907 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1909 struct rq
*rq
= task_rq(p
);
1912 * If the task is not on a runqueue (and not running), then
1913 * it is sufficient to simply update the task's cpu field.
1915 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
1916 set_task_cpu(p
, dest_cpu
);
1920 init_completion(&req
->done
);
1922 req
->dest_cpu
= dest_cpu
;
1923 list_add(&req
->list
, &rq
->migration_queue
);
1929 * wait_task_inactive - wait for a thread to unschedule.
1931 * If @match_state is nonzero, it's the @p->state value just checked and
1932 * not expected to change. If it changes, i.e. @p might have woken up,
1933 * then return zero. When we succeed in waiting for @p to be off its CPU,
1934 * we return a positive number (its total switch count). If a second call
1935 * a short while later returns the same number, the caller can be sure that
1936 * @p has remained unscheduled the whole time.
1938 * The caller must ensure that the task *will* unschedule sometime soon,
1939 * else this function might spin for a *long* time. This function can't
1940 * be called with interrupts off, or it may introduce deadlock with
1941 * smp_call_function() if an IPI is sent by the same process we are
1942 * waiting to become inactive.
1944 unsigned long wait_task_inactive(struct task_struct
*p
, long match_state
)
1946 unsigned long flags
;
1953 * We do the initial early heuristics without holding
1954 * any task-queue locks at all. We'll only try to get
1955 * the runqueue lock when things look like they will
1961 * If the task is actively running on another CPU
1962 * still, just relax and busy-wait without holding
1965 * NOTE! Since we don't hold any locks, it's not
1966 * even sure that "rq" stays as the right runqueue!
1967 * But we don't care, since "task_running()" will
1968 * return false if the runqueue has changed and p
1969 * is actually now running somewhere else!
1971 while (task_running(rq
, p
)) {
1972 if (match_state
&& unlikely(p
->state
!= match_state
))
1978 * Ok, time to look more closely! We need the rq
1979 * lock now, to be *sure*. If we're wrong, we'll
1980 * just go back and repeat.
1982 rq
= task_rq_lock(p
, &flags
);
1983 trace_sched_wait_task(rq
, p
);
1984 running
= task_running(rq
, p
);
1985 on_rq
= p
->se
.on_rq
;
1987 if (!match_state
|| p
->state
== match_state
)
1988 ncsw
= p
->nvcsw
| LONG_MIN
; /* sets MSB */
1989 task_rq_unlock(rq
, &flags
);
1992 * If it changed from the expected state, bail out now.
1994 if (unlikely(!ncsw
))
1998 * Was it really running after all now that we
1999 * checked with the proper locks actually held?
2001 * Oops. Go back and try again..
2003 if (unlikely(running
)) {
2009 * It's not enough that it's not actively running,
2010 * it must be off the runqueue _entirely_, and not
2013 * So if it wa still runnable (but just not actively
2014 * running right now), it's preempted, and we should
2015 * yield - it could be a while.
2017 if (unlikely(on_rq
)) {
2018 schedule_timeout_uninterruptible(1);
2023 * Ahh, all good. It wasn't running, and it wasn't
2024 * runnable, which means that it will never become
2025 * running in the future either. We're all done!
2034 * kick_process - kick a running thread to enter/exit the kernel
2035 * @p: the to-be-kicked thread
2037 * Cause a process which is running on another CPU to enter
2038 * kernel-mode, without any delay. (to get signals handled.)
2040 * NOTE: this function doesnt have to take the runqueue lock,
2041 * because all it wants to ensure is that the remote task enters
2042 * the kernel. If the IPI races and the task has been migrated
2043 * to another CPU then no harm is done and the purpose has been
2046 void kick_process(struct task_struct
*p
)
2052 if ((cpu
!= smp_processor_id()) && task_curr(p
))
2053 smp_send_reschedule(cpu
);
2058 * Return a low guess at the load of a migration-source cpu weighted
2059 * according to the scheduling class and "nice" value.
2061 * We want to under-estimate the load of migration sources, to
2062 * balance conservatively.
2064 static unsigned long source_load(int cpu
, int type
)
2066 struct rq
*rq
= cpu_rq(cpu
);
2067 unsigned long total
= weighted_cpuload(cpu
);
2069 if (type
== 0 || !sched_feat(LB_BIAS
))
2072 return min(rq
->cpu_load
[type
-1], total
);
2076 * Return a high guess at the load of a migration-target cpu weighted
2077 * according to the scheduling class and "nice" value.
2079 static unsigned long target_load(int cpu
, int type
)
2081 struct rq
*rq
= cpu_rq(cpu
);
2082 unsigned long total
= weighted_cpuload(cpu
);
2084 if (type
== 0 || !sched_feat(LB_BIAS
))
2087 return max(rq
->cpu_load
[type
-1], total
);
2091 * find_idlest_group finds and returns the least busy CPU group within the
2094 static struct sched_group
*
2095 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
2097 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2098 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
2099 int load_idx
= sd
->forkexec_idx
;
2100 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
2103 unsigned long load
, avg_load
;
2107 /* Skip over this group if it has no CPUs allowed */
2108 if (!cpumask_intersects(sched_group_cpus(group
),
2112 local_group
= cpumask_test_cpu(this_cpu
,
2113 sched_group_cpus(group
));
2115 /* Tally up the load of all CPUs in the group */
2118 for_each_cpu(i
, sched_group_cpus(group
)) {
2119 /* Bias balancing toward cpus of our domain */
2121 load
= source_load(i
, load_idx
);
2123 load
= target_load(i
, load_idx
);
2128 /* Adjust by relative CPU power of the group */
2129 avg_load
= sg_div_cpu_power(group
,
2130 avg_load
* SCHED_LOAD_SCALE
);
2133 this_load
= avg_load
;
2135 } else if (avg_load
< min_load
) {
2136 min_load
= avg_load
;
2139 } while (group
= group
->next
, group
!= sd
->groups
);
2141 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
2147 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2150 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
2152 unsigned long load
, min_load
= ULONG_MAX
;
2156 /* Traverse only the allowed CPUs */
2157 for_each_cpu_and(i
, sched_group_cpus(group
), &p
->cpus_allowed
) {
2158 load
= weighted_cpuload(i
);
2160 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
2170 * sched_balance_self: balance the current task (running on cpu) in domains
2171 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2174 * Balance, ie. select the least loaded group.
2176 * Returns the target CPU number, or the same CPU if no balancing is needed.
2178 * preempt must be disabled.
2180 static int sched_balance_self(int cpu
, int flag
)
2182 struct task_struct
*t
= current
;
2183 struct sched_domain
*tmp
, *sd
= NULL
;
2185 for_each_domain(cpu
, tmp
) {
2187 * If power savings logic is enabled for a domain, stop there.
2189 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
2191 if (tmp
->flags
& flag
)
2199 struct sched_group
*group
;
2200 int new_cpu
, weight
;
2202 if (!(sd
->flags
& flag
)) {
2207 group
= find_idlest_group(sd
, t
, cpu
);
2213 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
2214 if (new_cpu
== -1 || new_cpu
== cpu
) {
2215 /* Now try balancing at a lower domain level of cpu */
2220 /* Now try balancing at a lower domain level of new_cpu */
2222 weight
= cpumask_weight(sched_domain_span(sd
));
2224 for_each_domain(cpu
, tmp
) {
2225 if (weight
<= cpumask_weight(sched_domain_span(tmp
)))
2227 if (tmp
->flags
& flag
)
2230 /* while loop will break here if sd == NULL */
2236 #endif /* CONFIG_SMP */
2239 * try_to_wake_up - wake up a thread
2240 * @p: the to-be-woken-up thread
2241 * @state: the mask of task states that can be woken
2242 * @sync: do a synchronous wakeup?
2244 * Put it on the run-queue if it's not already there. The "current"
2245 * thread is always on the run-queue (except when the actual
2246 * re-schedule is in progress), and as such you're allowed to do
2247 * the simpler "current->state = TASK_RUNNING" to mark yourself
2248 * runnable without the overhead of this.
2250 * returns failure only if the task is already active.
2252 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
2254 int cpu
, orig_cpu
, this_cpu
, success
= 0;
2255 unsigned long flags
;
2259 if (!sched_feat(SYNC_WAKEUPS
))
2263 if (sched_feat(LB_WAKEUP_UPDATE
)) {
2264 struct sched_domain
*sd
;
2266 this_cpu
= raw_smp_processor_id();
2269 for_each_domain(this_cpu
, sd
) {
2270 if (cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
2279 rq
= task_rq_lock(p
, &flags
);
2280 old_state
= p
->state
;
2281 if (!(old_state
& state
))
2289 this_cpu
= smp_processor_id();
2292 if (unlikely(task_running(rq
, p
)))
2295 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
2296 if (cpu
!= orig_cpu
) {
2297 set_task_cpu(p
, cpu
);
2298 task_rq_unlock(rq
, &flags
);
2299 /* might preempt at this point */
2300 rq
= task_rq_lock(p
, &flags
);
2301 old_state
= p
->state
;
2302 if (!(old_state
& state
))
2307 this_cpu
= smp_processor_id();
2311 #ifdef CONFIG_SCHEDSTATS
2312 schedstat_inc(rq
, ttwu_count
);
2313 if (cpu
== this_cpu
)
2314 schedstat_inc(rq
, ttwu_local
);
2316 struct sched_domain
*sd
;
2317 for_each_domain(this_cpu
, sd
) {
2318 if (cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
2319 schedstat_inc(sd
, ttwu_wake_remote
);
2324 #endif /* CONFIG_SCHEDSTATS */
2327 #endif /* CONFIG_SMP */
2328 schedstat_inc(p
, se
.nr_wakeups
);
2330 schedstat_inc(p
, se
.nr_wakeups_sync
);
2331 if (orig_cpu
!= cpu
)
2332 schedstat_inc(p
, se
.nr_wakeups_migrate
);
2333 if (cpu
== this_cpu
)
2334 schedstat_inc(p
, se
.nr_wakeups_local
);
2336 schedstat_inc(p
, se
.nr_wakeups_remote
);
2337 update_rq_clock(rq
);
2338 activate_task(rq
, p
, 1);
2342 trace_sched_wakeup(rq
, p
);
2343 check_preempt_curr(rq
, p
, sync
);
2345 p
->state
= TASK_RUNNING
;
2347 if (p
->sched_class
->task_wake_up
)
2348 p
->sched_class
->task_wake_up(rq
, p
);
2351 current
->se
.last_wakeup
= current
->se
.sum_exec_runtime
;
2353 task_rq_unlock(rq
, &flags
);
2358 int wake_up_process(struct task_struct
*p
)
2360 return try_to_wake_up(p
, TASK_ALL
, 0);
2362 EXPORT_SYMBOL(wake_up_process
);
2364 int wake_up_state(struct task_struct
*p
, unsigned int state
)
2366 return try_to_wake_up(p
, state
, 0);
2370 * Perform scheduler related setup for a newly forked process p.
2371 * p is forked by current.
2373 * __sched_fork() is basic setup used by init_idle() too:
2375 static void __sched_fork(struct task_struct
*p
)
2377 p
->se
.exec_start
= 0;
2378 p
->se
.sum_exec_runtime
= 0;
2379 p
->se
.prev_sum_exec_runtime
= 0;
2380 p
->se
.last_wakeup
= 0;
2381 p
->se
.avg_overlap
= 0;
2383 #ifdef CONFIG_SCHEDSTATS
2384 p
->se
.wait_start
= 0;
2385 p
->se
.sum_sleep_runtime
= 0;
2386 p
->se
.sleep_start
= 0;
2387 p
->se
.block_start
= 0;
2388 p
->se
.sleep_max
= 0;
2389 p
->se
.block_max
= 0;
2391 p
->se
.slice_max
= 0;
2395 INIT_LIST_HEAD(&p
->rt
.run_list
);
2397 INIT_LIST_HEAD(&p
->se
.group_node
);
2399 #ifdef CONFIG_PREEMPT_NOTIFIERS
2400 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
2404 * We mark the process as running here, but have not actually
2405 * inserted it onto the runqueue yet. This guarantees that
2406 * nobody will actually run it, and a signal or other external
2407 * event cannot wake it up and insert it on the runqueue either.
2409 p
->state
= TASK_RUNNING
;
2413 * fork()/clone()-time setup:
2415 void sched_fork(struct task_struct
*p
, int clone_flags
)
2417 int cpu
= get_cpu();
2422 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
2424 set_task_cpu(p
, cpu
);
2427 * Make sure we do not leak PI boosting priority to the child:
2429 p
->prio
= current
->normal_prio
;
2430 if (!rt_prio(p
->prio
))
2431 p
->sched_class
= &fair_sched_class
;
2433 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2434 if (likely(sched_info_on()))
2435 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
2437 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2440 #ifdef CONFIG_PREEMPT
2441 /* Want to start with kernel preemption disabled. */
2442 task_thread_info(p
)->preempt_count
= 1;
2448 * wake_up_new_task - wake up a newly created task for the first time.
2450 * This function will do some initial scheduler statistics housekeeping
2451 * that must be done for every newly created context, then puts the task
2452 * on the runqueue and wakes it.
2454 void wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
2456 unsigned long flags
;
2459 rq
= task_rq_lock(p
, &flags
);
2460 BUG_ON(p
->state
!= TASK_RUNNING
);
2461 update_rq_clock(rq
);
2463 p
->prio
= effective_prio(p
);
2465 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
2466 activate_task(rq
, p
, 0);
2469 * Let the scheduling class do new task startup
2470 * management (if any):
2472 p
->sched_class
->task_new(rq
, p
);
2475 trace_sched_wakeup_new(rq
, p
);
2476 check_preempt_curr(rq
, p
, 0);
2478 if (p
->sched_class
->task_wake_up
)
2479 p
->sched_class
->task_wake_up(rq
, p
);
2481 task_rq_unlock(rq
, &flags
);
2484 #ifdef CONFIG_PREEMPT_NOTIFIERS
2487 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2488 * @notifier: notifier struct to register
2490 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2492 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2494 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2497 * preempt_notifier_unregister - no longer interested in preemption notifications
2498 * @notifier: notifier struct to unregister
2500 * This is safe to call from within a preemption notifier.
2502 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2504 hlist_del(¬ifier
->link
);
2506 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2508 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2510 struct preempt_notifier
*notifier
;
2511 struct hlist_node
*node
;
2513 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2514 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2518 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2519 struct task_struct
*next
)
2521 struct preempt_notifier
*notifier
;
2522 struct hlist_node
*node
;
2524 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2525 notifier
->ops
->sched_out(notifier
, next
);
2528 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2530 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2535 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2536 struct task_struct
*next
)
2540 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2543 * prepare_task_switch - prepare to switch tasks
2544 * @rq: the runqueue preparing to switch
2545 * @prev: the current task that is being switched out
2546 * @next: the task we are going to switch to.
2548 * This is called with the rq lock held and interrupts off. It must
2549 * be paired with a subsequent finish_task_switch after the context
2552 * prepare_task_switch sets up locking and calls architecture specific
2556 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2557 struct task_struct
*next
)
2559 fire_sched_out_preempt_notifiers(prev
, next
);
2560 prepare_lock_switch(rq
, next
);
2561 prepare_arch_switch(next
);
2565 * finish_task_switch - clean up after a task-switch
2566 * @rq: runqueue associated with task-switch
2567 * @prev: the thread we just switched away from.
2569 * finish_task_switch must be called after the context switch, paired
2570 * with a prepare_task_switch call before the context switch.
2571 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2572 * and do any other architecture-specific cleanup actions.
2574 * Note that we may have delayed dropping an mm in context_switch(). If
2575 * so, we finish that here outside of the runqueue lock. (Doing it
2576 * with the lock held can cause deadlocks; see schedule() for
2579 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2580 __releases(rq
->lock
)
2582 struct mm_struct
*mm
= rq
->prev_mm
;
2588 * A task struct has one reference for the use as "current".
2589 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2590 * schedule one last time. The schedule call will never return, and
2591 * the scheduled task must drop that reference.
2592 * The test for TASK_DEAD must occur while the runqueue locks are
2593 * still held, otherwise prev could be scheduled on another cpu, die
2594 * there before we look at prev->state, and then the reference would
2596 * Manfred Spraul <manfred@colorfullife.com>
2598 prev_state
= prev
->state
;
2599 finish_arch_switch(prev
);
2600 finish_lock_switch(rq
, prev
);
2602 if (current
->sched_class
->post_schedule
)
2603 current
->sched_class
->post_schedule(rq
);
2606 fire_sched_in_preempt_notifiers(current
);
2609 if (unlikely(prev_state
== TASK_DEAD
)) {
2611 * Remove function-return probe instances associated with this
2612 * task and put them back on the free list.
2614 kprobe_flush_task(prev
);
2615 put_task_struct(prev
);
2620 * schedule_tail - first thing a freshly forked thread must call.
2621 * @prev: the thread we just switched away from.
2623 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2624 __releases(rq
->lock
)
2626 struct rq
*rq
= this_rq();
2628 finish_task_switch(rq
, prev
);
2629 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2630 /* In this case, finish_task_switch does not reenable preemption */
2633 if (current
->set_child_tid
)
2634 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2638 * context_switch - switch to the new MM and the new
2639 * thread's register state.
2642 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2643 struct task_struct
*next
)
2645 struct mm_struct
*mm
, *oldmm
;
2647 prepare_task_switch(rq
, prev
, next
);
2648 trace_sched_switch(rq
, prev
, next
);
2650 oldmm
= prev
->active_mm
;
2652 * For paravirt, this is coupled with an exit in switch_to to
2653 * combine the page table reload and the switch backend into
2656 arch_enter_lazy_cpu_mode();
2658 if (unlikely(!mm
)) {
2659 next
->active_mm
= oldmm
;
2660 atomic_inc(&oldmm
->mm_count
);
2661 enter_lazy_tlb(oldmm
, next
);
2663 switch_mm(oldmm
, mm
, next
);
2665 if (unlikely(!prev
->mm
)) {
2666 prev
->active_mm
= NULL
;
2667 rq
->prev_mm
= oldmm
;
2670 * Since the runqueue lock will be released by the next
2671 * task (which is an invalid locking op but in the case
2672 * of the scheduler it's an obvious special-case), so we
2673 * do an early lockdep release here:
2675 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2676 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2679 /* Here we just switch the register state and the stack. */
2680 switch_to(prev
, next
, prev
);
2684 * this_rq must be evaluated again because prev may have moved
2685 * CPUs since it called schedule(), thus the 'rq' on its stack
2686 * frame will be invalid.
2688 finish_task_switch(this_rq(), prev
);
2692 * nr_running, nr_uninterruptible and nr_context_switches:
2694 * externally visible scheduler statistics: current number of runnable
2695 * threads, current number of uninterruptible-sleeping threads, total
2696 * number of context switches performed since bootup.
2698 unsigned long nr_running(void)
2700 unsigned long i
, sum
= 0;
2702 for_each_online_cpu(i
)
2703 sum
+= cpu_rq(i
)->nr_running
;
2708 unsigned long nr_uninterruptible(void)
2710 unsigned long i
, sum
= 0;
2712 for_each_possible_cpu(i
)
2713 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2716 * Since we read the counters lockless, it might be slightly
2717 * inaccurate. Do not allow it to go below zero though:
2719 if (unlikely((long)sum
< 0))
2725 unsigned long long nr_context_switches(void)
2728 unsigned long long sum
= 0;
2730 for_each_possible_cpu(i
)
2731 sum
+= cpu_rq(i
)->nr_switches
;
2736 unsigned long nr_iowait(void)
2738 unsigned long i
, sum
= 0;
2740 for_each_possible_cpu(i
)
2741 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2746 unsigned long nr_active(void)
2748 unsigned long i
, running
= 0, uninterruptible
= 0;
2750 for_each_online_cpu(i
) {
2751 running
+= cpu_rq(i
)->nr_running
;
2752 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2755 if (unlikely((long)uninterruptible
< 0))
2756 uninterruptible
= 0;
2758 return running
+ uninterruptible
;
2762 * Update rq->cpu_load[] statistics. This function is usually called every
2763 * scheduler tick (TICK_NSEC).
2765 static void update_cpu_load(struct rq
*this_rq
)
2767 unsigned long this_load
= this_rq
->load
.weight
;
2770 this_rq
->nr_load_updates
++;
2772 /* Update our load: */
2773 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2774 unsigned long old_load
, new_load
;
2776 /* scale is effectively 1 << i now, and >> i divides by scale */
2778 old_load
= this_rq
->cpu_load
[i
];
2779 new_load
= this_load
;
2781 * Round up the averaging division if load is increasing. This
2782 * prevents us from getting stuck on 9 if the load is 10, for
2785 if (new_load
> old_load
)
2786 new_load
+= scale
-1;
2787 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2794 * double_rq_lock - safely lock two runqueues
2796 * Note this does not disable interrupts like task_rq_lock,
2797 * you need to do so manually before calling.
2799 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2800 __acquires(rq1
->lock
)
2801 __acquires(rq2
->lock
)
2803 BUG_ON(!irqs_disabled());
2805 spin_lock(&rq1
->lock
);
2806 __acquire(rq2
->lock
); /* Fake it out ;) */
2809 spin_lock(&rq1
->lock
);
2810 spin_lock_nested(&rq2
->lock
, SINGLE_DEPTH_NESTING
);
2812 spin_lock(&rq2
->lock
);
2813 spin_lock_nested(&rq1
->lock
, SINGLE_DEPTH_NESTING
);
2816 update_rq_clock(rq1
);
2817 update_rq_clock(rq2
);
2821 * double_rq_unlock - safely unlock two runqueues
2823 * Note this does not restore interrupts like task_rq_unlock,
2824 * you need to do so manually after calling.
2826 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2827 __releases(rq1
->lock
)
2828 __releases(rq2
->lock
)
2830 spin_unlock(&rq1
->lock
);
2832 spin_unlock(&rq2
->lock
);
2834 __release(rq2
->lock
);
2838 * If dest_cpu is allowed for this process, migrate the task to it.
2839 * This is accomplished by forcing the cpu_allowed mask to only
2840 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2841 * the cpu_allowed mask is restored.
2843 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
2845 struct migration_req req
;
2846 unsigned long flags
;
2849 rq
= task_rq_lock(p
, &flags
);
2850 if (!cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
)
2851 || unlikely(!cpu_active(dest_cpu
)))
2854 trace_sched_migrate_task(rq
, p
, dest_cpu
);
2855 /* force the process onto the specified CPU */
2856 if (migrate_task(p
, dest_cpu
, &req
)) {
2857 /* Need to wait for migration thread (might exit: take ref). */
2858 struct task_struct
*mt
= rq
->migration_thread
;
2860 get_task_struct(mt
);
2861 task_rq_unlock(rq
, &flags
);
2862 wake_up_process(mt
);
2863 put_task_struct(mt
);
2864 wait_for_completion(&req
.done
);
2869 task_rq_unlock(rq
, &flags
);
2873 * sched_exec - execve() is a valuable balancing opportunity, because at
2874 * this point the task has the smallest effective memory and cache footprint.
2876 void sched_exec(void)
2878 int new_cpu
, this_cpu
= get_cpu();
2879 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
2881 if (new_cpu
!= this_cpu
)
2882 sched_migrate_task(current
, new_cpu
);
2886 * pull_task - move a task from a remote runqueue to the local runqueue.
2887 * Both runqueues must be locked.
2889 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
2890 struct rq
*this_rq
, int this_cpu
)
2892 deactivate_task(src_rq
, p
, 0);
2893 set_task_cpu(p
, this_cpu
);
2894 activate_task(this_rq
, p
, 0);
2896 * Note that idle threads have a prio of MAX_PRIO, for this test
2897 * to be always true for them.
2899 check_preempt_curr(this_rq
, p
, 0);
2903 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2906 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2907 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2911 * We do not migrate tasks that are:
2912 * 1) running (obviously), or
2913 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2914 * 3) are cache-hot on their current CPU.
2916 if (!cpumask_test_cpu(this_cpu
, &p
->cpus_allowed
)) {
2917 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
2922 if (task_running(rq
, p
)) {
2923 schedstat_inc(p
, se
.nr_failed_migrations_running
);
2928 * Aggressive migration if:
2929 * 1) task is cache cold, or
2930 * 2) too many balance attempts have failed.
2933 if (!task_hot(p
, rq
->clock
, sd
) ||
2934 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
2935 #ifdef CONFIG_SCHEDSTATS
2936 if (task_hot(p
, rq
->clock
, sd
)) {
2937 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2938 schedstat_inc(p
, se
.nr_forced_migrations
);
2944 if (task_hot(p
, rq
->clock
, sd
)) {
2945 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
2951 static unsigned long
2952 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2953 unsigned long max_load_move
, struct sched_domain
*sd
,
2954 enum cpu_idle_type idle
, int *all_pinned
,
2955 int *this_best_prio
, struct rq_iterator
*iterator
)
2957 int loops
= 0, pulled
= 0, pinned
= 0;
2958 struct task_struct
*p
;
2959 long rem_load_move
= max_load_move
;
2961 if (max_load_move
== 0)
2967 * Start the load-balancing iterator:
2969 p
= iterator
->start(iterator
->arg
);
2971 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
2974 if ((p
->se
.load
.weight
>> 1) > rem_load_move
||
2975 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2976 p
= iterator
->next(iterator
->arg
);
2980 pull_task(busiest
, p
, this_rq
, this_cpu
);
2982 rem_load_move
-= p
->se
.load
.weight
;
2985 * We only want to steal up to the prescribed amount of weighted load.
2987 if (rem_load_move
> 0) {
2988 if (p
->prio
< *this_best_prio
)
2989 *this_best_prio
= p
->prio
;
2990 p
= iterator
->next(iterator
->arg
);
2995 * Right now, this is one of only two places pull_task() is called,
2996 * so we can safely collect pull_task() stats here rather than
2997 * inside pull_task().
2999 schedstat_add(sd
, lb_gained
[idle
], pulled
);
3002 *all_pinned
= pinned
;
3004 return max_load_move
- rem_load_move
;
3008 * move_tasks tries to move up to max_load_move weighted load from busiest to
3009 * this_rq, as part of a balancing operation within domain "sd".
3010 * Returns 1 if successful and 0 otherwise.
3012 * Called with both runqueues locked.
3014 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
3015 unsigned long max_load_move
,
3016 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3019 const struct sched_class
*class = sched_class_highest
;
3020 unsigned long total_load_moved
= 0;
3021 int this_best_prio
= this_rq
->curr
->prio
;
3025 class->load_balance(this_rq
, this_cpu
, busiest
,
3026 max_load_move
- total_load_moved
,
3027 sd
, idle
, all_pinned
, &this_best_prio
);
3028 class = class->next
;
3030 if (idle
== CPU_NEWLY_IDLE
&& this_rq
->nr_running
)
3033 } while (class && max_load_move
> total_load_moved
);
3035 return total_load_moved
> 0;
3039 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
3040 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3041 struct rq_iterator
*iterator
)
3043 struct task_struct
*p
= iterator
->start(iterator
->arg
);
3047 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
3048 pull_task(busiest
, p
, this_rq
, this_cpu
);
3050 * Right now, this is only the second place pull_task()
3051 * is called, so we can safely collect pull_task()
3052 * stats here rather than inside pull_task().
3054 schedstat_inc(sd
, lb_gained
[idle
]);
3058 p
= iterator
->next(iterator
->arg
);
3065 * move_one_task tries to move exactly one task from busiest to this_rq, as
3066 * part of active balancing operations within "domain".
3067 * Returns 1 if successful and 0 otherwise.
3069 * Called with both runqueues locked.
3071 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
3072 struct sched_domain
*sd
, enum cpu_idle_type idle
)
3074 const struct sched_class
*class;
3076 for (class = sched_class_highest
; class; class = class->next
)
3077 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
3084 * find_busiest_group finds and returns the busiest CPU group within the
3085 * domain. It calculates and returns the amount of weighted load which
3086 * should be moved to restore balance via the imbalance parameter.
3088 static struct sched_group
*
3089 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
3090 unsigned long *imbalance
, enum cpu_idle_type idle
,
3091 int *sd_idle
, const struct cpumask
*cpus
, int *balance
)
3093 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
3094 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
3095 unsigned long max_pull
;
3096 unsigned long busiest_load_per_task
, busiest_nr_running
;
3097 unsigned long this_load_per_task
, this_nr_running
;
3098 int load_idx
, group_imb
= 0;
3099 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3100 int power_savings_balance
= 1;
3101 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
3102 unsigned long min_nr_running
= ULONG_MAX
;
3103 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
3106 max_load
= this_load
= total_load
= total_pwr
= 0;
3107 busiest_load_per_task
= busiest_nr_running
= 0;
3108 this_load_per_task
= this_nr_running
= 0;
3110 if (idle
== CPU_NOT_IDLE
)
3111 load_idx
= sd
->busy_idx
;
3112 else if (idle
== CPU_NEWLY_IDLE
)
3113 load_idx
= sd
->newidle_idx
;
3115 load_idx
= sd
->idle_idx
;
3118 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
3121 int __group_imb
= 0;
3122 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
3123 unsigned long sum_nr_running
, sum_weighted_load
;
3124 unsigned long sum_avg_load_per_task
;
3125 unsigned long avg_load_per_task
;
3127 local_group
= cpumask_test_cpu(this_cpu
,
3128 sched_group_cpus(group
));
3131 balance_cpu
= cpumask_first(sched_group_cpus(group
));
3133 /* Tally up the load of all CPUs in the group */
3134 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
3135 sum_avg_load_per_task
= avg_load_per_task
= 0;
3138 min_cpu_load
= ~0UL;
3140 for_each_cpu_and(i
, sched_group_cpus(group
), cpus
) {
3141 struct rq
*rq
= cpu_rq(i
);
3143 if (*sd_idle
&& rq
->nr_running
)
3146 /* Bias balancing toward cpus of our domain */
3148 if (idle_cpu(i
) && !first_idle_cpu
) {
3153 load
= target_load(i
, load_idx
);
3155 load
= source_load(i
, load_idx
);
3156 if (load
> max_cpu_load
)
3157 max_cpu_load
= load
;
3158 if (min_cpu_load
> load
)
3159 min_cpu_load
= load
;
3163 sum_nr_running
+= rq
->nr_running
;
3164 sum_weighted_load
+= weighted_cpuload(i
);
3166 sum_avg_load_per_task
+= cpu_avg_load_per_task(i
);
3170 * First idle cpu or the first cpu(busiest) in this sched group
3171 * is eligible for doing load balancing at this and above
3172 * domains. In the newly idle case, we will allow all the cpu's
3173 * to do the newly idle load balance.
3175 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
3176 balance_cpu
!= this_cpu
&& balance
) {
3181 total_load
+= avg_load
;
3182 total_pwr
+= group
->__cpu_power
;
3184 /* Adjust by relative CPU power of the group */
3185 avg_load
= sg_div_cpu_power(group
,
3186 avg_load
* SCHED_LOAD_SCALE
);
3190 * Consider the group unbalanced when the imbalance is larger
3191 * than the average weight of two tasks.
3193 * APZ: with cgroup the avg task weight can vary wildly and
3194 * might not be a suitable number - should we keep a
3195 * normalized nr_running number somewhere that negates
3198 avg_load_per_task
= sg_div_cpu_power(group
,
3199 sum_avg_load_per_task
* SCHED_LOAD_SCALE
);
3201 if ((max_cpu_load
- min_cpu_load
) > 2*avg_load_per_task
)
3204 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
3207 this_load
= avg_load
;
3209 this_nr_running
= sum_nr_running
;
3210 this_load_per_task
= sum_weighted_load
;
3211 } else if (avg_load
> max_load
&&
3212 (sum_nr_running
> group_capacity
|| __group_imb
)) {
3213 max_load
= avg_load
;
3215 busiest_nr_running
= sum_nr_running
;
3216 busiest_load_per_task
= sum_weighted_load
;
3217 group_imb
= __group_imb
;
3220 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3222 * Busy processors will not participate in power savings
3225 if (idle
== CPU_NOT_IDLE
||
3226 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3230 * If the local group is idle or completely loaded
3231 * no need to do power savings balance at this domain
3233 if (local_group
&& (this_nr_running
>= group_capacity
||
3235 power_savings_balance
= 0;
3238 * If a group is already running at full capacity or idle,
3239 * don't include that group in power savings calculations
3241 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
3246 * Calculate the group which has the least non-idle load.
3247 * This is the group from where we need to pick up the load
3250 if ((sum_nr_running
< min_nr_running
) ||
3251 (sum_nr_running
== min_nr_running
&&
3252 cpumask_first(sched_group_cpus(group
)) >
3253 cpumask_first(sched_group_cpus(group_min
)))) {
3255 min_nr_running
= sum_nr_running
;
3256 min_load_per_task
= sum_weighted_load
/
3261 * Calculate the group which is almost near its
3262 * capacity but still has some space to pick up some load
3263 * from other group and save more power
3265 if (sum_nr_running
<= group_capacity
- 1) {
3266 if (sum_nr_running
> leader_nr_running
||
3267 (sum_nr_running
== leader_nr_running
&&
3268 cpumask_first(sched_group_cpus(group
)) <
3269 cpumask_first(sched_group_cpus(group_leader
)))) {
3270 group_leader
= group
;
3271 leader_nr_running
= sum_nr_running
;
3276 group
= group
->next
;
3277 } while (group
!= sd
->groups
);
3279 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
3282 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
3284 if (this_load
>= avg_load
||
3285 100*max_load
<= sd
->imbalance_pct
*this_load
)
3288 busiest_load_per_task
/= busiest_nr_running
;
3290 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
3293 * We're trying to get all the cpus to the average_load, so we don't
3294 * want to push ourselves above the average load, nor do we wish to
3295 * reduce the max loaded cpu below the average load, as either of these
3296 * actions would just result in more rebalancing later, and ping-pong
3297 * tasks around. Thus we look for the minimum possible imbalance.
3298 * Negative imbalances (*we* are more loaded than anyone else) will
3299 * be counted as no imbalance for these purposes -- we can't fix that
3300 * by pulling tasks to us. Be careful of negative numbers as they'll
3301 * appear as very large values with unsigned longs.
3303 if (max_load
<= busiest_load_per_task
)
3307 * In the presence of smp nice balancing, certain scenarios can have
3308 * max load less than avg load(as we skip the groups at or below
3309 * its cpu_power, while calculating max_load..)
3311 if (max_load
< avg_load
) {
3313 goto small_imbalance
;
3316 /* Don't want to pull so many tasks that a group would go idle */
3317 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
3319 /* How much load to actually move to equalise the imbalance */
3320 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
3321 (avg_load
- this_load
) * this->__cpu_power
)
3325 * if *imbalance is less than the average load per runnable task
3326 * there is no gaurantee that any tasks will be moved so we'll have
3327 * a think about bumping its value to force at least one task to be
3330 if (*imbalance
< busiest_load_per_task
) {
3331 unsigned long tmp
, pwr_now
, pwr_move
;
3335 pwr_move
= pwr_now
= 0;
3337 if (this_nr_running
) {
3338 this_load_per_task
/= this_nr_running
;
3339 if (busiest_load_per_task
> this_load_per_task
)
3342 this_load_per_task
= cpu_avg_load_per_task(this_cpu
);
3344 if (max_load
- this_load
+ busiest_load_per_task
>=
3345 busiest_load_per_task
* imbn
) {
3346 *imbalance
= busiest_load_per_task
;
3351 * OK, we don't have enough imbalance to justify moving tasks,
3352 * however we may be able to increase total CPU power used by
3356 pwr_now
+= busiest
->__cpu_power
*
3357 min(busiest_load_per_task
, max_load
);
3358 pwr_now
+= this->__cpu_power
*
3359 min(this_load_per_task
, this_load
);
3360 pwr_now
/= SCHED_LOAD_SCALE
;
3362 /* Amount of load we'd subtract */
3363 tmp
= sg_div_cpu_power(busiest
,
3364 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3366 pwr_move
+= busiest
->__cpu_power
*
3367 min(busiest_load_per_task
, max_load
- tmp
);
3369 /* Amount of load we'd add */
3370 if (max_load
* busiest
->__cpu_power
<
3371 busiest_load_per_task
* SCHED_LOAD_SCALE
)
3372 tmp
= sg_div_cpu_power(this,
3373 max_load
* busiest
->__cpu_power
);
3375 tmp
= sg_div_cpu_power(this,
3376 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3377 pwr_move
+= this->__cpu_power
*
3378 min(this_load_per_task
, this_load
+ tmp
);
3379 pwr_move
/= SCHED_LOAD_SCALE
;
3381 /* Move if we gain throughput */
3382 if (pwr_move
> pwr_now
)
3383 *imbalance
= busiest_load_per_task
;
3389 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3390 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3393 if (this == group_leader
&& group_leader
!= group_min
) {
3394 *imbalance
= min_load_per_task
;
3395 if (sched_mc_power_savings
>= POWERSAVINGS_BALANCE_WAKEUP
) {
3396 cpu_rq(this_cpu
)->rd
->sched_mc_preferred_wakeup_cpu
=
3397 first_cpu(group_leader
->cpumask
);
3408 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3411 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
3412 unsigned long imbalance
, const struct cpumask
*cpus
)
3414 struct rq
*busiest
= NULL
, *rq
;
3415 unsigned long max_load
= 0;
3418 for_each_cpu(i
, sched_group_cpus(group
)) {
3421 if (!cpumask_test_cpu(i
, cpus
))
3425 wl
= weighted_cpuload(i
);
3427 if (rq
->nr_running
== 1 && wl
> imbalance
)
3430 if (wl
> max_load
) {
3440 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3441 * so long as it is large enough.
3443 #define MAX_PINNED_INTERVAL 512
3446 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3447 * tasks if there is an imbalance.
3449 static int load_balance(int this_cpu
, struct rq
*this_rq
,
3450 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3451 int *balance
, struct cpumask
*cpus
)
3453 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
3454 struct sched_group
*group
;
3455 unsigned long imbalance
;
3457 unsigned long flags
;
3459 cpumask_setall(cpus
);
3462 * When power savings policy is enabled for the parent domain, idle
3463 * sibling can pick up load irrespective of busy siblings. In this case,
3464 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3465 * portraying it as CPU_NOT_IDLE.
3467 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3468 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3471 schedstat_inc(sd
, lb_count
[idle
]);
3475 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
3482 schedstat_inc(sd
, lb_nobusyg
[idle
]);
3486 busiest
= find_busiest_queue(group
, idle
, imbalance
, cpus
);
3488 schedstat_inc(sd
, lb_nobusyq
[idle
]);
3492 BUG_ON(busiest
== this_rq
);
3494 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
3497 if (busiest
->nr_running
> 1) {
3499 * Attempt to move tasks. If find_busiest_group has found
3500 * an imbalance but busiest->nr_running <= 1, the group is
3501 * still unbalanced. ld_moved simply stays zero, so it is
3502 * correctly treated as an imbalance.
3504 local_irq_save(flags
);
3505 double_rq_lock(this_rq
, busiest
);
3506 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3507 imbalance
, sd
, idle
, &all_pinned
);
3508 double_rq_unlock(this_rq
, busiest
);
3509 local_irq_restore(flags
);
3512 * some other cpu did the load balance for us.
3514 if (ld_moved
&& this_cpu
!= smp_processor_id())
3515 resched_cpu(this_cpu
);
3517 /* All tasks on this runqueue were pinned by CPU affinity */
3518 if (unlikely(all_pinned
)) {
3519 cpumask_clear_cpu(cpu_of(busiest
), cpus
);
3520 if (!cpumask_empty(cpus
))
3527 schedstat_inc(sd
, lb_failed
[idle
]);
3528 sd
->nr_balance_failed
++;
3530 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3532 spin_lock_irqsave(&busiest
->lock
, flags
);
3534 /* don't kick the migration_thread, if the curr
3535 * task on busiest cpu can't be moved to this_cpu
3537 if (!cpumask_test_cpu(this_cpu
,
3538 &busiest
->curr
->cpus_allowed
)) {
3539 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3541 goto out_one_pinned
;
3544 if (!busiest
->active_balance
) {
3545 busiest
->active_balance
= 1;
3546 busiest
->push_cpu
= this_cpu
;
3549 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3551 wake_up_process(busiest
->migration_thread
);
3554 * We've kicked active balancing, reset the failure
3557 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3560 sd
->nr_balance_failed
= 0;
3562 if (likely(!active_balance
)) {
3563 /* We were unbalanced, so reset the balancing interval */
3564 sd
->balance_interval
= sd
->min_interval
;
3567 * If we've begun active balancing, start to back off. This
3568 * case may not be covered by the all_pinned logic if there
3569 * is only 1 task on the busy runqueue (because we don't call
3572 if (sd
->balance_interval
< sd
->max_interval
)
3573 sd
->balance_interval
*= 2;
3576 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3577 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3583 schedstat_inc(sd
, lb_balanced
[idle
]);
3585 sd
->nr_balance_failed
= 0;
3588 /* tune up the balancing interval */
3589 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3590 (sd
->balance_interval
< sd
->max_interval
))
3591 sd
->balance_interval
*= 2;
3593 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3594 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3605 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3606 * tasks if there is an imbalance.
3608 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3609 * this_rq is locked.
3612 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
,
3613 struct cpumask
*cpus
)
3615 struct sched_group
*group
;
3616 struct rq
*busiest
= NULL
;
3617 unsigned long imbalance
;
3622 cpumask_setall(cpus
);
3625 * When power savings policy is enabled for the parent domain, idle
3626 * sibling can pick up load irrespective of busy siblings. In this case,
3627 * let the state of idle sibling percolate up as IDLE, instead of
3628 * portraying it as CPU_NOT_IDLE.
3630 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3631 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3634 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3636 update_shares_locked(this_rq
, sd
);
3637 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3638 &sd_idle
, cpus
, NULL
);
3640 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3644 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
, cpus
);
3646 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3650 BUG_ON(busiest
== this_rq
);
3652 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3655 if (busiest
->nr_running
> 1) {
3656 /* Attempt to move tasks */
3657 double_lock_balance(this_rq
, busiest
);
3658 /* this_rq->clock is already updated */
3659 update_rq_clock(busiest
);
3660 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3661 imbalance
, sd
, CPU_NEWLY_IDLE
,
3663 double_unlock_balance(this_rq
, busiest
);
3665 if (unlikely(all_pinned
)) {
3666 cpumask_clear_cpu(cpu_of(busiest
), cpus
);
3667 if (!cpumask_empty(cpus
))
3675 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3676 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3677 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3680 if (sched_mc_power_savings
< POWERSAVINGS_BALANCE_WAKEUP
)
3683 if (sd
->nr_balance_failed
++ < 2)
3687 * The only task running in a non-idle cpu can be moved to this
3688 * cpu in an attempt to completely freeup the other CPU
3689 * package. The same method used to move task in load_balance()
3690 * have been extended for load_balance_newidle() to speedup
3691 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
3693 * The package power saving logic comes from
3694 * find_busiest_group(). If there are no imbalance, then
3695 * f_b_g() will return NULL. However when sched_mc={1,2} then
3696 * f_b_g() will select a group from which a running task may be
3697 * pulled to this cpu in order to make the other package idle.
3698 * If there is no opportunity to make a package idle and if
3699 * there are no imbalance, then f_b_g() will return NULL and no
3700 * action will be taken in load_balance_newidle().
3702 * Under normal task pull operation due to imbalance, there
3703 * will be more than one task in the source run queue and
3704 * move_tasks() will succeed. ld_moved will be true and this
3705 * active balance code will not be triggered.
3708 /* Lock busiest in correct order while this_rq is held */
3709 double_lock_balance(this_rq
, busiest
);
3712 * don't kick the migration_thread, if the curr
3713 * task on busiest cpu can't be moved to this_cpu
3715 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3716 double_unlock_balance(this_rq
, busiest
);
3721 if (!busiest
->active_balance
) {
3722 busiest
->active_balance
= 1;
3723 busiest
->push_cpu
= this_cpu
;
3727 double_unlock_balance(this_rq
, busiest
);
3729 wake_up_process(busiest
->migration_thread
);
3732 sd
->nr_balance_failed
= 0;
3734 update_shares_locked(this_rq
, sd
);
3738 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3739 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3740 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3742 sd
->nr_balance_failed
= 0;
3748 * idle_balance is called by schedule() if this_cpu is about to become
3749 * idle. Attempts to pull tasks from other CPUs.
3751 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3753 struct sched_domain
*sd
;
3754 int pulled_task
= 0;
3755 unsigned long next_balance
= jiffies
+ HZ
;
3756 cpumask_var_t tmpmask
;
3758 if (!alloc_cpumask_var(&tmpmask
, GFP_ATOMIC
))
3761 for_each_domain(this_cpu
, sd
) {
3762 unsigned long interval
;
3764 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3767 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3768 /* If we've pulled tasks over stop searching: */
3769 pulled_task
= load_balance_newidle(this_cpu
, this_rq
,
3772 interval
= msecs_to_jiffies(sd
->balance_interval
);
3773 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3774 next_balance
= sd
->last_balance
+ interval
;
3778 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3780 * We are going idle. next_balance may be set based on
3781 * a busy processor. So reset next_balance.
3783 this_rq
->next_balance
= next_balance
;
3785 free_cpumask_var(tmpmask
);
3789 * active_load_balance is run by migration threads. It pushes running tasks
3790 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3791 * running on each physical CPU where possible, and avoids physical /
3792 * logical imbalances.
3794 * Called with busiest_rq locked.
3796 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3798 int target_cpu
= busiest_rq
->push_cpu
;
3799 struct sched_domain
*sd
;
3800 struct rq
*target_rq
;
3802 /* Is there any task to move? */
3803 if (busiest_rq
->nr_running
<= 1)
3806 target_rq
= cpu_rq(target_cpu
);
3809 * This condition is "impossible", if it occurs
3810 * we need to fix it. Originally reported by
3811 * Bjorn Helgaas on a 128-cpu setup.
3813 BUG_ON(busiest_rq
== target_rq
);
3815 /* move a task from busiest_rq to target_rq */
3816 double_lock_balance(busiest_rq
, target_rq
);
3817 update_rq_clock(busiest_rq
);
3818 update_rq_clock(target_rq
);
3820 /* Search for an sd spanning us and the target CPU. */
3821 for_each_domain(target_cpu
, sd
) {
3822 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3823 cpumask_test_cpu(busiest_cpu
, sched_domain_span(sd
)))
3828 schedstat_inc(sd
, alb_count
);
3830 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3832 schedstat_inc(sd
, alb_pushed
);
3834 schedstat_inc(sd
, alb_failed
);
3836 double_unlock_balance(busiest_rq
, target_rq
);
3841 atomic_t load_balancer
;
3842 cpumask_var_t cpu_mask
;
3843 } nohz ____cacheline_aligned
= {
3844 .load_balancer
= ATOMIC_INIT(-1),
3848 * This routine will try to nominate the ilb (idle load balancing)
3849 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3850 * load balancing on behalf of all those cpus. If all the cpus in the system
3851 * go into this tickless mode, then there will be no ilb owner (as there is
3852 * no need for one) and all the cpus will sleep till the next wakeup event
3855 * For the ilb owner, tick is not stopped. And this tick will be used
3856 * for idle load balancing. ilb owner will still be part of
3859 * While stopping the tick, this cpu will become the ilb owner if there
3860 * is no other owner. And will be the owner till that cpu becomes busy
3861 * or if all cpus in the system stop their ticks at which point
3862 * there is no need for ilb owner.
3864 * When the ilb owner becomes busy, it nominates another owner, during the
3865 * next busy scheduler_tick()
3867 int select_nohz_load_balancer(int stop_tick
)
3869 int cpu
= smp_processor_id();
3872 cpumask_set_cpu(cpu
, nohz
.cpu_mask
);
3873 cpu_rq(cpu
)->in_nohz_recently
= 1;
3876 * If we are going offline and still the leader, give up!
3878 if (!cpu_active(cpu
) &&
3879 atomic_read(&nohz
.load_balancer
) == cpu
) {
3880 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3885 /* time for ilb owner also to sleep */
3886 if (cpumask_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3887 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3888 atomic_set(&nohz
.load_balancer
, -1);
3892 if (atomic_read(&nohz
.load_balancer
) == -1) {
3893 /* make me the ilb owner */
3894 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3896 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3899 if (!cpumask_test_cpu(cpu
, nohz
.cpu_mask
))
3902 cpumask_clear_cpu(cpu
, nohz
.cpu_mask
);
3904 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3905 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3912 static DEFINE_SPINLOCK(balancing
);
3915 * It checks each scheduling domain to see if it is due to be balanced,
3916 * and initiates a balancing operation if so.
3918 * Balancing parameters are set up in arch_init_sched_domains.
3920 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
3923 struct rq
*rq
= cpu_rq(cpu
);
3924 unsigned long interval
;
3925 struct sched_domain
*sd
;
3926 /* Earliest time when we have to do rebalance again */
3927 unsigned long next_balance
= jiffies
+ 60*HZ
;
3928 int update_next_balance
= 0;
3932 /* Fails alloc? Rebalancing probably not a priority right now. */
3933 if (!alloc_cpumask_var(&tmp
, GFP_ATOMIC
))
3936 for_each_domain(cpu
, sd
) {
3937 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3940 interval
= sd
->balance_interval
;
3941 if (idle
!= CPU_IDLE
)
3942 interval
*= sd
->busy_factor
;
3944 /* scale ms to jiffies */
3945 interval
= msecs_to_jiffies(interval
);
3946 if (unlikely(!interval
))
3948 if (interval
> HZ
*NR_CPUS
/10)
3949 interval
= HZ
*NR_CPUS
/10;
3951 need_serialize
= sd
->flags
& SD_SERIALIZE
;
3953 if (need_serialize
) {
3954 if (!spin_trylock(&balancing
))
3958 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
3959 if (load_balance(cpu
, rq
, sd
, idle
, &balance
, tmp
)) {
3961 * We've pulled tasks over so either we're no
3962 * longer idle, or one of our SMT siblings is
3965 idle
= CPU_NOT_IDLE
;
3967 sd
->last_balance
= jiffies
;
3970 spin_unlock(&balancing
);
3972 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
3973 next_balance
= sd
->last_balance
+ interval
;
3974 update_next_balance
= 1;
3978 * Stop the load balance at this level. There is another
3979 * CPU in our sched group which is doing load balancing more
3987 * next_balance will be updated only when there is a need.
3988 * When the cpu is attached to null domain for ex, it will not be
3991 if (likely(update_next_balance
))
3992 rq
->next_balance
= next_balance
;
3994 free_cpumask_var(tmp
);
3998 * run_rebalance_domains is triggered when needed from the scheduler tick.
3999 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4000 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4002 static void run_rebalance_domains(struct softirq_action
*h
)
4004 int this_cpu
= smp_processor_id();
4005 struct rq
*this_rq
= cpu_rq(this_cpu
);
4006 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
4007 CPU_IDLE
: CPU_NOT_IDLE
;
4009 rebalance_domains(this_cpu
, idle
);
4013 * If this cpu is the owner for idle load balancing, then do the
4014 * balancing on behalf of the other idle cpus whose ticks are
4017 if (this_rq
->idle_at_tick
&&
4018 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
4022 for_each_cpu(balance_cpu
, nohz
.cpu_mask
) {
4023 if (balance_cpu
== this_cpu
)
4027 * If this cpu gets work to do, stop the load balancing
4028 * work being done for other cpus. Next load
4029 * balancing owner will pick it up.
4034 rebalance_domains(balance_cpu
, CPU_IDLE
);
4036 rq
= cpu_rq(balance_cpu
);
4037 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
4038 this_rq
->next_balance
= rq
->next_balance
;
4045 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4047 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4048 * idle load balancing owner or decide to stop the periodic load balancing,
4049 * if the whole system is idle.
4051 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
4055 * If we were in the nohz mode recently and busy at the current
4056 * scheduler tick, then check if we need to nominate new idle
4059 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
4060 rq
->in_nohz_recently
= 0;
4062 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
4063 cpumask_clear_cpu(cpu
, nohz
.cpu_mask
);
4064 atomic_set(&nohz
.load_balancer
, -1);
4067 if (atomic_read(&nohz
.load_balancer
) == -1) {
4069 * simple selection for now: Nominate the
4070 * first cpu in the nohz list to be the next
4073 * TBD: Traverse the sched domains and nominate
4074 * the nearest cpu in the nohz.cpu_mask.
4076 int ilb
= cpumask_first(nohz
.cpu_mask
);
4078 if (ilb
< nr_cpu_ids
)
4084 * If this cpu is idle and doing idle load balancing for all the
4085 * cpus with ticks stopped, is it time for that to stop?
4087 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
4088 cpumask_weight(nohz
.cpu_mask
) == num_online_cpus()) {
4094 * If this cpu is idle and the idle load balancing is done by
4095 * someone else, then no need raise the SCHED_SOFTIRQ
4097 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
4098 cpumask_test_cpu(cpu
, nohz
.cpu_mask
))
4101 if (time_after_eq(jiffies
, rq
->next_balance
))
4102 raise_softirq(SCHED_SOFTIRQ
);
4105 #else /* CONFIG_SMP */
4108 * on UP we do not need to balance between CPUs:
4110 static inline void idle_balance(int cpu
, struct rq
*rq
)
4116 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
4118 EXPORT_PER_CPU_SYMBOL(kstat
);
4121 * Return any ns on the sched_clock that have not yet been banked in
4122 * @p in case that task is currently running.
4124 unsigned long long task_delta_exec(struct task_struct
*p
)
4126 unsigned long flags
;
4130 rq
= task_rq_lock(p
, &flags
);
4132 if (task_current(rq
, p
)) {
4135 update_rq_clock(rq
);
4136 delta_exec
= rq
->clock
- p
->se
.exec_start
;
4137 if ((s64
)delta_exec
> 0)
4141 task_rq_unlock(rq
, &flags
);
4147 * Account user cpu time to a process.
4148 * @p: the process that the cpu time gets accounted to
4149 * @cputime: the cpu time spent in user space since the last update
4151 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
4153 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4156 p
->utime
= cputime_add(p
->utime
, cputime
);
4157 account_group_user_time(p
, cputime
);
4159 /* Add user time to cpustat. */
4160 tmp
= cputime_to_cputime64(cputime
);
4161 if (TASK_NICE(p
) > 0)
4162 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
4164 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
4165 /* Account for user time used */
4166 acct_update_integrals(p
);
4170 * Account guest cpu time to a process.
4171 * @p: the process that the cpu time gets accounted to
4172 * @cputime: the cpu time spent in virtual machine since the last update
4174 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
4177 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4179 tmp
= cputime_to_cputime64(cputime
);
4181 p
->utime
= cputime_add(p
->utime
, cputime
);
4182 account_group_user_time(p
, cputime
);
4183 p
->gtime
= cputime_add(p
->gtime
, cputime
);
4185 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
4186 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
4190 * Account scaled user cpu time to a process.
4191 * @p: the process that the cpu time gets accounted to
4192 * @cputime: the cpu time spent in user space since the last update
4194 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
4196 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
4200 * Account system cpu time to a process.
4201 * @p: the process that the cpu time gets accounted to
4202 * @hardirq_offset: the offset to subtract from hardirq_count()
4203 * @cputime: the cpu time spent in kernel space since the last update
4205 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
4208 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4209 struct rq
*rq
= this_rq();
4212 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0)) {
4213 account_guest_time(p
, cputime
);
4217 p
->stime
= cputime_add(p
->stime
, cputime
);
4218 account_group_system_time(p
, cputime
);
4220 /* Add system time to cpustat. */
4221 tmp
= cputime_to_cputime64(cputime
);
4222 if (hardirq_count() - hardirq_offset
)
4223 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
4224 else if (softirq_count())
4225 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
4226 else if (p
!= rq
->idle
)
4227 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
4228 else if (atomic_read(&rq
->nr_iowait
) > 0)
4229 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
4231 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
4232 /* Account for system time used */
4233 acct_update_integrals(p
);
4237 * Account scaled system cpu time to a process.
4238 * @p: the process that the cpu time gets accounted to
4239 * @hardirq_offset: the offset to subtract from hardirq_count()
4240 * @cputime: the cpu time spent in kernel space since the last update
4242 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
4244 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
4248 * Account for involuntary wait time.
4249 * @p: the process from which the cpu time has been stolen
4250 * @steal: the cpu time spent in involuntary wait
4252 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
4254 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4255 cputime64_t tmp
= cputime_to_cputime64(steal
);
4256 struct rq
*rq
= this_rq();
4258 if (p
== rq
->idle
) {
4259 p
->stime
= cputime_add(p
->stime
, steal
);
4260 if (atomic_read(&rq
->nr_iowait
) > 0)
4261 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
4263 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
4265 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
4269 * Use precise platform statistics if available:
4271 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
4272 cputime_t
task_utime(struct task_struct
*p
)
4277 cputime_t
task_stime(struct task_struct
*p
)
4282 cputime_t
task_utime(struct task_struct
*p
)
4284 clock_t utime
= cputime_to_clock_t(p
->utime
),
4285 total
= utime
+ cputime_to_clock_t(p
->stime
);
4289 * Use CFS's precise accounting:
4291 temp
= (u64
)nsec_to_clock_t(p
->se
.sum_exec_runtime
);
4295 do_div(temp
, total
);
4297 utime
= (clock_t)temp
;
4299 p
->prev_utime
= max(p
->prev_utime
, clock_t_to_cputime(utime
));
4300 return p
->prev_utime
;
4303 cputime_t
task_stime(struct task_struct
*p
)
4308 * Use CFS's precise accounting. (we subtract utime from
4309 * the total, to make sure the total observed by userspace
4310 * grows monotonically - apps rely on that):
4312 stime
= nsec_to_clock_t(p
->se
.sum_exec_runtime
) -
4313 cputime_to_clock_t(task_utime(p
));
4316 p
->prev_stime
= max(p
->prev_stime
, clock_t_to_cputime(stime
));
4318 return p
->prev_stime
;
4322 inline cputime_t
task_gtime(struct task_struct
*p
)
4328 * This function gets called by the timer code, with HZ frequency.
4329 * We call it with interrupts disabled.
4331 * It also gets called by the fork code, when changing the parent's
4334 void scheduler_tick(void)
4336 int cpu
= smp_processor_id();
4337 struct rq
*rq
= cpu_rq(cpu
);
4338 struct task_struct
*curr
= rq
->curr
;
4342 spin_lock(&rq
->lock
);
4343 update_rq_clock(rq
);
4344 update_cpu_load(rq
);
4345 curr
->sched_class
->task_tick(rq
, curr
, 0);
4346 spin_unlock(&rq
->lock
);
4349 rq
->idle_at_tick
= idle_cpu(cpu
);
4350 trigger_load_balance(rq
, cpu
);
4354 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4355 defined(CONFIG_PREEMPT_TRACER))
4357 static inline unsigned long get_parent_ip(unsigned long addr
)
4359 if (in_lock_functions(addr
)) {
4360 addr
= CALLER_ADDR2
;
4361 if (in_lock_functions(addr
))
4362 addr
= CALLER_ADDR3
;
4367 void __kprobes
add_preempt_count(int val
)
4369 #ifdef CONFIG_DEBUG_PREEMPT
4373 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4376 preempt_count() += val
;
4377 #ifdef CONFIG_DEBUG_PREEMPT
4379 * Spinlock count overflowing soon?
4381 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
4384 if (preempt_count() == val
)
4385 trace_preempt_off(CALLER_ADDR0
, get_parent_ip(CALLER_ADDR1
));
4387 EXPORT_SYMBOL(add_preempt_count
);
4389 void __kprobes
sub_preempt_count(int val
)
4391 #ifdef CONFIG_DEBUG_PREEMPT
4395 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count() - (!!kernel_locked())))
4398 * Is the spinlock portion underflowing?
4400 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
4401 !(preempt_count() & PREEMPT_MASK
)))
4405 if (preempt_count() == val
)
4406 trace_preempt_on(CALLER_ADDR0
, get_parent_ip(CALLER_ADDR1
));
4407 preempt_count() -= val
;
4409 EXPORT_SYMBOL(sub_preempt_count
);
4414 * Print scheduling while atomic bug:
4416 static noinline
void __schedule_bug(struct task_struct
*prev
)
4418 struct pt_regs
*regs
= get_irq_regs();
4420 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
4421 prev
->comm
, prev
->pid
, preempt_count());
4423 debug_show_held_locks(prev
);
4425 if (irqs_disabled())
4426 print_irqtrace_events(prev
);
4435 * Various schedule()-time debugging checks and statistics:
4437 static inline void schedule_debug(struct task_struct
*prev
)
4440 * Test if we are atomic. Since do_exit() needs to call into
4441 * schedule() atomically, we ignore that path for now.
4442 * Otherwise, whine if we are scheduling when we should not be.
4444 if (unlikely(in_atomic_preempt_off() && !prev
->exit_state
))
4445 __schedule_bug(prev
);
4447 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
4449 schedstat_inc(this_rq(), sched_count
);
4450 #ifdef CONFIG_SCHEDSTATS
4451 if (unlikely(prev
->lock_depth
>= 0)) {
4452 schedstat_inc(this_rq(), bkl_count
);
4453 schedstat_inc(prev
, sched_info
.bkl_count
);
4459 * Pick up the highest-prio task:
4461 static inline struct task_struct
*
4462 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
4464 const struct sched_class
*class;
4465 struct task_struct
*p
;
4468 * Optimization: we know that if all tasks are in
4469 * the fair class we can call that function directly:
4471 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
4472 p
= fair_sched_class
.pick_next_task(rq
);
4477 class = sched_class_highest
;
4479 p
= class->pick_next_task(rq
);
4483 * Will never be NULL as the idle class always
4484 * returns a non-NULL p:
4486 class = class->next
;
4491 * schedule() is the main scheduler function.
4493 asmlinkage
void __sched
schedule(void)
4495 struct task_struct
*prev
, *next
;
4496 unsigned long *switch_count
;
4502 cpu
= smp_processor_id();
4506 switch_count
= &prev
->nivcsw
;
4508 release_kernel_lock(prev
);
4509 need_resched_nonpreemptible
:
4511 schedule_debug(prev
);
4513 if (sched_feat(HRTICK
))
4516 spin_lock_irq(&rq
->lock
);
4517 update_rq_clock(rq
);
4518 clear_tsk_need_resched(prev
);
4520 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
4521 if (unlikely(signal_pending_state(prev
->state
, prev
)))
4522 prev
->state
= TASK_RUNNING
;
4524 deactivate_task(rq
, prev
, 1);
4525 switch_count
= &prev
->nvcsw
;
4529 if (prev
->sched_class
->pre_schedule
)
4530 prev
->sched_class
->pre_schedule(rq
, prev
);
4533 if (unlikely(!rq
->nr_running
))
4534 idle_balance(cpu
, rq
);
4536 prev
->sched_class
->put_prev_task(rq
, prev
);
4537 next
= pick_next_task(rq
, prev
);
4539 if (likely(prev
!= next
)) {
4540 sched_info_switch(prev
, next
);
4546 context_switch(rq
, prev
, next
); /* unlocks the rq */
4548 * the context switch might have flipped the stack from under
4549 * us, hence refresh the local variables.
4551 cpu
= smp_processor_id();
4554 spin_unlock_irq(&rq
->lock
);
4556 if (unlikely(reacquire_kernel_lock(current
) < 0))
4557 goto need_resched_nonpreemptible
;
4559 preempt_enable_no_resched();
4560 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
4563 EXPORT_SYMBOL(schedule
);
4565 #ifdef CONFIG_PREEMPT
4567 * this is the entry point to schedule() from in-kernel preemption
4568 * off of preempt_enable. Kernel preemptions off return from interrupt
4569 * occur there and call schedule directly.
4571 asmlinkage
void __sched
preempt_schedule(void)
4573 struct thread_info
*ti
= current_thread_info();
4576 * If there is a non-zero preempt_count or interrupts are disabled,
4577 * we do not want to preempt the current task. Just return..
4579 if (likely(ti
->preempt_count
|| irqs_disabled()))
4583 add_preempt_count(PREEMPT_ACTIVE
);
4585 sub_preempt_count(PREEMPT_ACTIVE
);
4588 * Check again in case we missed a preemption opportunity
4589 * between schedule and now.
4592 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4594 EXPORT_SYMBOL(preempt_schedule
);
4597 * this is the entry point to schedule() from kernel preemption
4598 * off of irq context.
4599 * Note, that this is called and return with irqs disabled. This will
4600 * protect us against recursive calling from irq.
4602 asmlinkage
void __sched
preempt_schedule_irq(void)
4604 struct thread_info
*ti
= current_thread_info();
4606 /* Catch callers which need to be fixed */
4607 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
4610 add_preempt_count(PREEMPT_ACTIVE
);
4613 local_irq_disable();
4614 sub_preempt_count(PREEMPT_ACTIVE
);
4617 * Check again in case we missed a preemption opportunity
4618 * between schedule and now.
4621 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4624 #endif /* CONFIG_PREEMPT */
4626 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
4629 return try_to_wake_up(curr
->private, mode
, sync
);
4631 EXPORT_SYMBOL(default_wake_function
);
4634 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4635 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4636 * number) then we wake all the non-exclusive tasks and one exclusive task.
4638 * There are circumstances in which we can try to wake a task which has already
4639 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4640 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4642 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
4643 int nr_exclusive
, int sync
, void *key
)
4645 wait_queue_t
*curr
, *next
;
4647 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
4648 unsigned flags
= curr
->flags
;
4650 if (curr
->func(curr
, mode
, sync
, key
) &&
4651 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4657 * __wake_up - wake up threads blocked on a waitqueue.
4659 * @mode: which threads
4660 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4661 * @key: is directly passed to the wakeup function
4663 void __wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4664 int nr_exclusive
, void *key
)
4666 unsigned long flags
;
4668 spin_lock_irqsave(&q
->lock
, flags
);
4669 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4670 spin_unlock_irqrestore(&q
->lock
, flags
);
4672 EXPORT_SYMBOL(__wake_up
);
4675 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4677 void __wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4679 __wake_up_common(q
, mode
, 1, 0, NULL
);
4683 * __wake_up_sync - wake up threads blocked on a waitqueue.
4685 * @mode: which threads
4686 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4688 * The sync wakeup differs that the waker knows that it will schedule
4689 * away soon, so while the target thread will be woken up, it will not
4690 * be migrated to another CPU - ie. the two threads are 'synchronized'
4691 * with each other. This can prevent needless bouncing between CPUs.
4693 * On UP it can prevent extra preemption.
4696 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4698 unsigned long flags
;
4704 if (unlikely(!nr_exclusive
))
4707 spin_lock_irqsave(&q
->lock
, flags
);
4708 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4709 spin_unlock_irqrestore(&q
->lock
, flags
);
4711 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4714 * complete: - signals a single thread waiting on this completion
4715 * @x: holds the state of this particular completion
4717 * This will wake up a single thread waiting on this completion. Threads will be
4718 * awakened in the same order in which they were queued.
4720 * See also complete_all(), wait_for_completion() and related routines.
4722 void complete(struct completion
*x
)
4724 unsigned long flags
;
4726 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4728 __wake_up_common(&x
->wait
, TASK_NORMAL
, 1, 0, NULL
);
4729 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4731 EXPORT_SYMBOL(complete
);
4734 * complete_all: - signals all threads waiting on this completion
4735 * @x: holds the state of this particular completion
4737 * This will wake up all threads waiting on this particular completion event.
4739 void complete_all(struct completion
*x
)
4741 unsigned long flags
;
4743 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4744 x
->done
+= UINT_MAX
/2;
4745 __wake_up_common(&x
->wait
, TASK_NORMAL
, 0, 0, NULL
);
4746 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4748 EXPORT_SYMBOL(complete_all
);
4750 static inline long __sched
4751 do_wait_for_common(struct completion
*x
, long timeout
, int state
)
4754 DECLARE_WAITQUEUE(wait
, current
);
4756 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
4757 __add_wait_queue_tail(&x
->wait
, &wait
);
4759 if (signal_pending_state(state
, current
)) {
4760 timeout
= -ERESTARTSYS
;
4763 __set_current_state(state
);
4764 spin_unlock_irq(&x
->wait
.lock
);
4765 timeout
= schedule_timeout(timeout
);
4766 spin_lock_irq(&x
->wait
.lock
);
4767 } while (!x
->done
&& timeout
);
4768 __remove_wait_queue(&x
->wait
, &wait
);
4773 return timeout
?: 1;
4777 wait_for_common(struct completion
*x
, long timeout
, int state
)
4781 spin_lock_irq(&x
->wait
.lock
);
4782 timeout
= do_wait_for_common(x
, timeout
, state
);
4783 spin_unlock_irq(&x
->wait
.lock
);
4788 * wait_for_completion: - waits for completion of a task
4789 * @x: holds the state of this particular completion
4791 * This waits to be signaled for completion of a specific task. It is NOT
4792 * interruptible and there is no timeout.
4794 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4795 * and interrupt capability. Also see complete().
4797 void __sched
wait_for_completion(struct completion
*x
)
4799 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4801 EXPORT_SYMBOL(wait_for_completion
);
4804 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4805 * @x: holds the state of this particular completion
4806 * @timeout: timeout value in jiffies
4808 * This waits for either a completion of a specific task to be signaled or for a
4809 * specified timeout to expire. The timeout is in jiffies. It is not
4812 unsigned long __sched
4813 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4815 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4817 EXPORT_SYMBOL(wait_for_completion_timeout
);
4820 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4821 * @x: holds the state of this particular completion
4823 * This waits for completion of a specific task to be signaled. It is
4826 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4828 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4829 if (t
== -ERESTARTSYS
)
4833 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4836 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4837 * @x: holds the state of this particular completion
4838 * @timeout: timeout value in jiffies
4840 * This waits for either a completion of a specific task to be signaled or for a
4841 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4843 unsigned long __sched
4844 wait_for_completion_interruptible_timeout(struct completion
*x
,
4845 unsigned long timeout
)
4847 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4849 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4852 * wait_for_completion_killable: - waits for completion of a task (killable)
4853 * @x: holds the state of this particular completion
4855 * This waits to be signaled for completion of a specific task. It can be
4856 * interrupted by a kill signal.
4858 int __sched
wait_for_completion_killable(struct completion
*x
)
4860 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_KILLABLE
);
4861 if (t
== -ERESTARTSYS
)
4865 EXPORT_SYMBOL(wait_for_completion_killable
);
4868 * try_wait_for_completion - try to decrement a completion without blocking
4869 * @x: completion structure
4871 * Returns: 0 if a decrement cannot be done without blocking
4872 * 1 if a decrement succeeded.
4874 * If a completion is being used as a counting completion,
4875 * attempt to decrement the counter without blocking. This
4876 * enables us to avoid waiting if the resource the completion
4877 * is protecting is not available.
4879 bool try_wait_for_completion(struct completion
*x
)
4883 spin_lock_irq(&x
->wait
.lock
);
4888 spin_unlock_irq(&x
->wait
.lock
);
4891 EXPORT_SYMBOL(try_wait_for_completion
);
4894 * completion_done - Test to see if a completion has any waiters
4895 * @x: completion structure
4897 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4898 * 1 if there are no waiters.
4901 bool completion_done(struct completion
*x
)
4905 spin_lock_irq(&x
->wait
.lock
);
4908 spin_unlock_irq(&x
->wait
.lock
);
4911 EXPORT_SYMBOL(completion_done
);
4914 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4916 unsigned long flags
;
4919 init_waitqueue_entry(&wait
, current
);
4921 __set_current_state(state
);
4923 spin_lock_irqsave(&q
->lock
, flags
);
4924 __add_wait_queue(q
, &wait
);
4925 spin_unlock(&q
->lock
);
4926 timeout
= schedule_timeout(timeout
);
4927 spin_lock_irq(&q
->lock
);
4928 __remove_wait_queue(q
, &wait
);
4929 spin_unlock_irqrestore(&q
->lock
, flags
);
4934 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4936 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4938 EXPORT_SYMBOL(interruptible_sleep_on
);
4941 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4943 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4945 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4947 void __sched
sleep_on(wait_queue_head_t
*q
)
4949 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4951 EXPORT_SYMBOL(sleep_on
);
4953 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4955 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4957 EXPORT_SYMBOL(sleep_on_timeout
);
4959 #ifdef CONFIG_RT_MUTEXES
4962 * rt_mutex_setprio - set the current priority of a task
4964 * @prio: prio value (kernel-internal form)
4966 * This function changes the 'effective' priority of a task. It does
4967 * not touch ->normal_prio like __setscheduler().
4969 * Used by the rt_mutex code to implement priority inheritance logic.
4971 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4973 unsigned long flags
;
4974 int oldprio
, on_rq
, running
;
4976 const struct sched_class
*prev_class
= p
->sched_class
;
4978 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4980 rq
= task_rq_lock(p
, &flags
);
4981 update_rq_clock(rq
);
4984 on_rq
= p
->se
.on_rq
;
4985 running
= task_current(rq
, p
);
4987 dequeue_task(rq
, p
, 0);
4989 p
->sched_class
->put_prev_task(rq
, p
);
4992 p
->sched_class
= &rt_sched_class
;
4994 p
->sched_class
= &fair_sched_class
;
4999 p
->sched_class
->set_curr_task(rq
);
5001 enqueue_task(rq
, p
, 0);
5003 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
5005 task_rq_unlock(rq
, &flags
);
5010 void set_user_nice(struct task_struct
*p
, long nice
)
5012 int old_prio
, delta
, on_rq
;
5013 unsigned long flags
;
5016 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
5019 * We have to be careful, if called from sys_setpriority(),
5020 * the task might be in the middle of scheduling on another CPU.
5022 rq
= task_rq_lock(p
, &flags
);
5023 update_rq_clock(rq
);
5025 * The RT priorities are set via sched_setscheduler(), but we still
5026 * allow the 'normal' nice value to be set - but as expected
5027 * it wont have any effect on scheduling until the task is
5028 * SCHED_FIFO/SCHED_RR:
5030 if (task_has_rt_policy(p
)) {
5031 p
->static_prio
= NICE_TO_PRIO(nice
);
5034 on_rq
= p
->se
.on_rq
;
5036 dequeue_task(rq
, p
, 0);
5038 p
->static_prio
= NICE_TO_PRIO(nice
);
5041 p
->prio
= effective_prio(p
);
5042 delta
= p
->prio
- old_prio
;
5045 enqueue_task(rq
, p
, 0);
5047 * If the task increased its priority or is running and
5048 * lowered its priority, then reschedule its CPU:
5050 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
5051 resched_task(rq
->curr
);
5054 task_rq_unlock(rq
, &flags
);
5056 EXPORT_SYMBOL(set_user_nice
);
5059 * can_nice - check if a task can reduce its nice value
5063 int can_nice(const struct task_struct
*p
, const int nice
)
5065 /* convert nice value [19,-20] to rlimit style value [1,40] */
5066 int nice_rlim
= 20 - nice
;
5068 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
5069 capable(CAP_SYS_NICE
));
5072 #ifdef __ARCH_WANT_SYS_NICE
5075 * sys_nice - change the priority of the current process.
5076 * @increment: priority increment
5078 * sys_setpriority is a more generic, but much slower function that
5079 * does similar things.
5081 asmlinkage
long sys_nice(int increment
)
5086 * Setpriority might change our priority at the same moment.
5087 * We don't have to worry. Conceptually one call occurs first
5088 * and we have a single winner.
5090 if (increment
< -40)
5095 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
5101 if (increment
< 0 && !can_nice(current
, nice
))
5104 retval
= security_task_setnice(current
, nice
);
5108 set_user_nice(current
, nice
);
5115 * task_prio - return the priority value of a given task.
5116 * @p: the task in question.
5118 * This is the priority value as seen by users in /proc.
5119 * RT tasks are offset by -200. Normal tasks are centered
5120 * around 0, value goes from -16 to +15.
5122 int task_prio(const struct task_struct
*p
)
5124 return p
->prio
- MAX_RT_PRIO
;
5128 * task_nice - return the nice value of a given task.
5129 * @p: the task in question.
5131 int task_nice(const struct task_struct
*p
)
5133 return TASK_NICE(p
);
5135 EXPORT_SYMBOL(task_nice
);
5138 * idle_cpu - is a given cpu idle currently?
5139 * @cpu: the processor in question.
5141 int idle_cpu(int cpu
)
5143 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
5147 * idle_task - return the idle task for a given cpu.
5148 * @cpu: the processor in question.
5150 struct task_struct
*idle_task(int cpu
)
5152 return cpu_rq(cpu
)->idle
;
5156 * find_process_by_pid - find a process with a matching PID value.
5157 * @pid: the pid in question.
5159 static struct task_struct
*find_process_by_pid(pid_t pid
)
5161 return pid
? find_task_by_vpid(pid
) : current
;
5164 /* Actually do priority change: must hold rq lock. */
5166 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
5168 BUG_ON(p
->se
.on_rq
);
5171 switch (p
->policy
) {
5175 p
->sched_class
= &fair_sched_class
;
5179 p
->sched_class
= &rt_sched_class
;
5183 p
->rt_priority
= prio
;
5184 p
->normal_prio
= normal_prio(p
);
5185 /* we are holding p->pi_lock already */
5186 p
->prio
= rt_mutex_getprio(p
);
5190 static int __sched_setscheduler(struct task_struct
*p
, int policy
,
5191 struct sched_param
*param
, bool user
)
5193 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
5194 unsigned long flags
;
5195 const struct sched_class
*prev_class
= p
->sched_class
;
5198 /* may grab non-irq protected spin_locks */
5199 BUG_ON(in_interrupt());
5201 /* double check policy once rq lock held */
5203 policy
= oldpolicy
= p
->policy
;
5204 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
5205 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
5206 policy
!= SCHED_IDLE
)
5209 * Valid priorities for SCHED_FIFO and SCHED_RR are
5210 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5211 * SCHED_BATCH and SCHED_IDLE is 0.
5213 if (param
->sched_priority
< 0 ||
5214 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
5215 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
5217 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
5221 * Allow unprivileged RT tasks to decrease priority:
5223 if (user
&& !capable(CAP_SYS_NICE
)) {
5224 if (rt_policy(policy
)) {
5225 unsigned long rlim_rtprio
;
5227 if (!lock_task_sighand(p
, &flags
))
5229 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
5230 unlock_task_sighand(p
, &flags
);
5232 /* can't set/change the rt policy */
5233 if (policy
!= p
->policy
&& !rlim_rtprio
)
5236 /* can't increase priority */
5237 if (param
->sched_priority
> p
->rt_priority
&&
5238 param
->sched_priority
> rlim_rtprio
)
5242 * Like positive nice levels, dont allow tasks to
5243 * move out of SCHED_IDLE either:
5245 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
5248 /* can't change other user's priorities */
5249 if ((current
->euid
!= p
->euid
) &&
5250 (current
->euid
!= p
->uid
))
5255 #ifdef CONFIG_RT_GROUP_SCHED
5257 * Do not allow realtime tasks into groups that have no runtime
5260 if (rt_bandwidth_enabled() && rt_policy(policy
) &&
5261 task_group(p
)->rt_bandwidth
.rt_runtime
== 0)
5265 retval
= security_task_setscheduler(p
, policy
, param
);
5271 * make sure no PI-waiters arrive (or leave) while we are
5272 * changing the priority of the task:
5274 spin_lock_irqsave(&p
->pi_lock
, flags
);
5276 * To be able to change p->policy safely, the apropriate
5277 * runqueue lock must be held.
5279 rq
= __task_rq_lock(p
);
5280 /* recheck policy now with rq lock held */
5281 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
5282 policy
= oldpolicy
= -1;
5283 __task_rq_unlock(rq
);
5284 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
5287 update_rq_clock(rq
);
5288 on_rq
= p
->se
.on_rq
;
5289 running
= task_current(rq
, p
);
5291 deactivate_task(rq
, p
, 0);
5293 p
->sched_class
->put_prev_task(rq
, p
);
5296 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
5299 p
->sched_class
->set_curr_task(rq
);
5301 activate_task(rq
, p
, 0);
5303 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
5305 __task_rq_unlock(rq
);
5306 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
5308 rt_mutex_adjust_pi(p
);
5314 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5315 * @p: the task in question.
5316 * @policy: new policy.
5317 * @param: structure containing the new RT priority.
5319 * NOTE that the task may be already dead.
5321 int sched_setscheduler(struct task_struct
*p
, int policy
,
5322 struct sched_param
*param
)
5324 return __sched_setscheduler(p
, policy
, param
, true);
5326 EXPORT_SYMBOL_GPL(sched_setscheduler
);
5329 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5330 * @p: the task in question.
5331 * @policy: new policy.
5332 * @param: structure containing the new RT priority.
5334 * Just like sched_setscheduler, only don't bother checking if the
5335 * current context has permission. For example, this is needed in
5336 * stop_machine(): we create temporary high priority worker threads,
5337 * but our caller might not have that capability.
5339 int sched_setscheduler_nocheck(struct task_struct
*p
, int policy
,
5340 struct sched_param
*param
)
5342 return __sched_setscheduler(p
, policy
, param
, false);
5346 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
5348 struct sched_param lparam
;
5349 struct task_struct
*p
;
5352 if (!param
|| pid
< 0)
5354 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
5359 p
= find_process_by_pid(pid
);
5361 retval
= sched_setscheduler(p
, policy
, &lparam
);
5368 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5369 * @pid: the pid in question.
5370 * @policy: new policy.
5371 * @param: structure containing the new RT priority.
5374 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
5376 /* negative values for policy are not valid */
5380 return do_sched_setscheduler(pid
, policy
, param
);
5384 * sys_sched_setparam - set/change the RT priority of a thread
5385 * @pid: the pid in question.
5386 * @param: structure containing the new RT priority.
5388 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
5390 return do_sched_setscheduler(pid
, -1, param
);
5394 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5395 * @pid: the pid in question.
5397 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
5399 struct task_struct
*p
;
5406 read_lock(&tasklist_lock
);
5407 p
= find_process_by_pid(pid
);
5409 retval
= security_task_getscheduler(p
);
5413 read_unlock(&tasklist_lock
);
5418 * sys_sched_getscheduler - get the RT priority of a thread
5419 * @pid: the pid in question.
5420 * @param: structure containing the RT priority.
5422 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
5424 struct sched_param lp
;
5425 struct task_struct
*p
;
5428 if (!param
|| pid
< 0)
5431 read_lock(&tasklist_lock
);
5432 p
= find_process_by_pid(pid
);
5437 retval
= security_task_getscheduler(p
);
5441 lp
.sched_priority
= p
->rt_priority
;
5442 read_unlock(&tasklist_lock
);
5445 * This one might sleep, we cannot do it with a spinlock held ...
5447 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
5452 read_unlock(&tasklist_lock
);
5456 long sched_setaffinity(pid_t pid
, const struct cpumask
*in_mask
)
5458 cpumask_var_t cpus_allowed
, new_mask
;
5459 struct task_struct
*p
;
5463 read_lock(&tasklist_lock
);
5465 p
= find_process_by_pid(pid
);
5467 read_unlock(&tasklist_lock
);
5473 * It is not safe to call set_cpus_allowed with the
5474 * tasklist_lock held. We will bump the task_struct's
5475 * usage count and then drop tasklist_lock.
5478 read_unlock(&tasklist_lock
);
5480 if (!alloc_cpumask_var(&cpus_allowed
, GFP_KERNEL
)) {
5484 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
)) {
5486 goto out_free_cpus_allowed
;
5489 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
5490 !capable(CAP_SYS_NICE
))
5493 retval
= security_task_setscheduler(p
, 0, NULL
);
5497 cpuset_cpus_allowed(p
, cpus_allowed
);
5498 cpumask_and(new_mask
, in_mask
, cpus_allowed
);
5500 retval
= set_cpus_allowed_ptr(p
, new_mask
);
5503 cpuset_cpus_allowed(p
, cpus_allowed
);
5504 if (!cpumask_subset(new_mask
, cpus_allowed
)) {
5506 * We must have raced with a concurrent cpuset
5507 * update. Just reset the cpus_allowed to the
5508 * cpuset's cpus_allowed
5510 cpumask_copy(new_mask
, cpus_allowed
);
5515 free_cpumask_var(new_mask
);
5516 out_free_cpus_allowed
:
5517 free_cpumask_var(cpus_allowed
);
5524 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
5525 struct cpumask
*new_mask
)
5527 if (len
< cpumask_size())
5528 cpumask_clear(new_mask
);
5529 else if (len
> cpumask_size())
5530 len
= cpumask_size();
5532 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
5536 * sys_sched_setaffinity - set the cpu affinity of a process
5537 * @pid: pid of the process
5538 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5539 * @user_mask_ptr: user-space pointer to the new cpu mask
5541 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
5542 unsigned long __user
*user_mask_ptr
)
5544 cpumask_var_t new_mask
;
5547 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
))
5550 retval
= get_user_cpu_mask(user_mask_ptr
, len
, new_mask
);
5552 retval
= sched_setaffinity(pid
, new_mask
);
5553 free_cpumask_var(new_mask
);
5557 long sched_getaffinity(pid_t pid
, struct cpumask
*mask
)
5559 struct task_struct
*p
;
5563 read_lock(&tasklist_lock
);
5566 p
= find_process_by_pid(pid
);
5570 retval
= security_task_getscheduler(p
);
5574 cpumask_and(mask
, &p
->cpus_allowed
, cpu_online_mask
);
5577 read_unlock(&tasklist_lock
);
5584 * sys_sched_getaffinity - get the cpu affinity of a process
5585 * @pid: pid of the process
5586 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5587 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5589 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
5590 unsigned long __user
*user_mask_ptr
)
5595 if (len
< cpumask_size())
5598 if (!alloc_cpumask_var(&mask
, GFP_KERNEL
))
5601 ret
= sched_getaffinity(pid
, mask
);
5603 if (copy_to_user(user_mask_ptr
, mask
, cpumask_size()))
5606 ret
= cpumask_size();
5608 free_cpumask_var(mask
);
5614 * sys_sched_yield - yield the current processor to other threads.
5616 * This function yields the current CPU to other tasks. If there are no
5617 * other threads running on this CPU then this function will return.
5619 asmlinkage
long sys_sched_yield(void)
5621 struct rq
*rq
= this_rq_lock();
5623 schedstat_inc(rq
, yld_count
);
5624 current
->sched_class
->yield_task(rq
);
5627 * Since we are going to call schedule() anyway, there's
5628 * no need to preempt or enable interrupts:
5630 __release(rq
->lock
);
5631 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
5632 _raw_spin_unlock(&rq
->lock
);
5633 preempt_enable_no_resched();
5640 static void __cond_resched(void)
5642 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5643 __might_sleep(__FILE__
, __LINE__
);
5646 * The BKS might be reacquired before we have dropped
5647 * PREEMPT_ACTIVE, which could trigger a second
5648 * cond_resched() call.
5651 add_preempt_count(PREEMPT_ACTIVE
);
5653 sub_preempt_count(PREEMPT_ACTIVE
);
5654 } while (need_resched());
5657 int __sched
_cond_resched(void)
5659 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
5660 system_state
== SYSTEM_RUNNING
) {
5666 EXPORT_SYMBOL(_cond_resched
);
5669 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5670 * call schedule, and on return reacquire the lock.
5672 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5673 * operations here to prevent schedule() from being called twice (once via
5674 * spin_unlock(), once by hand).
5676 int cond_resched_lock(spinlock_t
*lock
)
5678 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
5681 if (spin_needbreak(lock
) || resched
) {
5683 if (resched
&& need_resched())
5692 EXPORT_SYMBOL(cond_resched_lock
);
5694 int __sched
cond_resched_softirq(void)
5696 BUG_ON(!in_softirq());
5698 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
5706 EXPORT_SYMBOL(cond_resched_softirq
);
5709 * yield - yield the current processor to other threads.
5711 * This is a shortcut for kernel-space yielding - it marks the
5712 * thread runnable and calls sys_sched_yield().
5714 void __sched
yield(void)
5716 set_current_state(TASK_RUNNING
);
5719 EXPORT_SYMBOL(yield
);
5722 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5723 * that process accounting knows that this is a task in IO wait state.
5725 * But don't do that if it is a deliberate, throttling IO wait (this task
5726 * has set its backing_dev_info: the queue against which it should throttle)
5728 void __sched
io_schedule(void)
5730 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5732 delayacct_blkio_start();
5733 atomic_inc(&rq
->nr_iowait
);
5735 atomic_dec(&rq
->nr_iowait
);
5736 delayacct_blkio_end();
5738 EXPORT_SYMBOL(io_schedule
);
5740 long __sched
io_schedule_timeout(long timeout
)
5742 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5745 delayacct_blkio_start();
5746 atomic_inc(&rq
->nr_iowait
);
5747 ret
= schedule_timeout(timeout
);
5748 atomic_dec(&rq
->nr_iowait
);
5749 delayacct_blkio_end();
5754 * sys_sched_get_priority_max - return maximum RT priority.
5755 * @policy: scheduling class.
5757 * this syscall returns the maximum rt_priority that can be used
5758 * by a given scheduling class.
5760 asmlinkage
long sys_sched_get_priority_max(int policy
)
5767 ret
= MAX_USER_RT_PRIO
-1;
5779 * sys_sched_get_priority_min - return minimum RT priority.
5780 * @policy: scheduling class.
5782 * this syscall returns the minimum rt_priority that can be used
5783 * by a given scheduling class.
5785 asmlinkage
long sys_sched_get_priority_min(int policy
)
5803 * sys_sched_rr_get_interval - return the default timeslice of a process.
5804 * @pid: pid of the process.
5805 * @interval: userspace pointer to the timeslice value.
5807 * this syscall writes the default timeslice value of a given process
5808 * into the user-space timespec buffer. A value of '0' means infinity.
5811 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5813 struct task_struct
*p
;
5814 unsigned int time_slice
;
5822 read_lock(&tasklist_lock
);
5823 p
= find_process_by_pid(pid
);
5827 retval
= security_task_getscheduler(p
);
5832 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5833 * tasks that are on an otherwise idle runqueue:
5836 if (p
->policy
== SCHED_RR
) {
5837 time_slice
= DEF_TIMESLICE
;
5838 } else if (p
->policy
!= SCHED_FIFO
) {
5839 struct sched_entity
*se
= &p
->se
;
5840 unsigned long flags
;
5843 rq
= task_rq_lock(p
, &flags
);
5844 if (rq
->cfs
.load
.weight
)
5845 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5846 task_rq_unlock(rq
, &flags
);
5848 read_unlock(&tasklist_lock
);
5849 jiffies_to_timespec(time_slice
, &t
);
5850 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5854 read_unlock(&tasklist_lock
);
5858 static const char stat_nam
[] = TASK_STATE_TO_CHAR_STR
;
5860 void sched_show_task(struct task_struct
*p
)
5862 unsigned long free
= 0;
5865 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5866 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5867 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5868 #if BITS_PER_LONG == 32
5869 if (state
== TASK_RUNNING
)
5870 printk(KERN_CONT
" running ");
5872 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5874 if (state
== TASK_RUNNING
)
5875 printk(KERN_CONT
" running task ");
5877 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5879 #ifdef CONFIG_DEBUG_STACK_USAGE
5881 unsigned long *n
= end_of_stack(p
);
5884 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5887 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5888 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5890 show_stack(p
, NULL
);
5893 void show_state_filter(unsigned long state_filter
)
5895 struct task_struct
*g
, *p
;
5897 #if BITS_PER_LONG == 32
5899 " task PC stack pid father\n");
5902 " task PC stack pid father\n");
5904 read_lock(&tasklist_lock
);
5905 do_each_thread(g
, p
) {
5907 * reset the NMI-timeout, listing all files on a slow
5908 * console might take alot of time:
5910 touch_nmi_watchdog();
5911 if (!state_filter
|| (p
->state
& state_filter
))
5913 } while_each_thread(g
, p
);
5915 touch_all_softlockup_watchdogs();
5917 #ifdef CONFIG_SCHED_DEBUG
5918 sysrq_sched_debug_show();
5920 read_unlock(&tasklist_lock
);
5922 * Only show locks if all tasks are dumped:
5924 if (state_filter
== -1)
5925 debug_show_all_locks();
5928 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5930 idle
->sched_class
= &idle_sched_class
;
5934 * init_idle - set up an idle thread for a given CPU
5935 * @idle: task in question
5936 * @cpu: cpu the idle task belongs to
5938 * NOTE: this function does not set the idle thread's NEED_RESCHED
5939 * flag, to make booting more robust.
5941 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5943 struct rq
*rq
= cpu_rq(cpu
);
5944 unsigned long flags
;
5946 spin_lock_irqsave(&rq
->lock
, flags
);
5949 idle
->se
.exec_start
= sched_clock();
5951 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5952 cpumask_copy(&idle
->cpus_allowed
, cpumask_of(cpu
));
5953 __set_task_cpu(idle
, cpu
);
5955 rq
->curr
= rq
->idle
= idle
;
5956 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5959 spin_unlock_irqrestore(&rq
->lock
, flags
);
5961 /* Set the preempt count _outside_ the spinlocks! */
5962 #if defined(CONFIG_PREEMPT)
5963 task_thread_info(idle
)->preempt_count
= (idle
->lock_depth
>= 0);
5965 task_thread_info(idle
)->preempt_count
= 0;
5968 * The idle tasks have their own, simple scheduling class:
5970 idle
->sched_class
= &idle_sched_class
;
5971 ftrace_graph_init_task(idle
);
5975 * In a system that switches off the HZ timer nohz_cpu_mask
5976 * indicates which cpus entered this state. This is used
5977 * in the rcu update to wait only for active cpus. For system
5978 * which do not switch off the HZ timer nohz_cpu_mask should
5979 * always be CPU_BITS_NONE.
5981 cpumask_var_t nohz_cpu_mask
;
5984 * Increase the granularity value when there are more CPUs,
5985 * because with more CPUs the 'effective latency' as visible
5986 * to users decreases. But the relationship is not linear,
5987 * so pick a second-best guess by going with the log2 of the
5990 * This idea comes from the SD scheduler of Con Kolivas:
5992 static inline void sched_init_granularity(void)
5994 unsigned int factor
= 1 + ilog2(num_online_cpus());
5995 const unsigned long limit
= 200000000;
5997 sysctl_sched_min_granularity
*= factor
;
5998 if (sysctl_sched_min_granularity
> limit
)
5999 sysctl_sched_min_granularity
= limit
;
6001 sysctl_sched_latency
*= factor
;
6002 if (sysctl_sched_latency
> limit
)
6003 sysctl_sched_latency
= limit
;
6005 sysctl_sched_wakeup_granularity
*= factor
;
6007 sysctl_sched_shares_ratelimit
*= factor
;
6012 * This is how migration works:
6014 * 1) we queue a struct migration_req structure in the source CPU's
6015 * runqueue and wake up that CPU's migration thread.
6016 * 2) we down() the locked semaphore => thread blocks.
6017 * 3) migration thread wakes up (implicitly it forces the migrated
6018 * thread off the CPU)
6019 * 4) it gets the migration request and checks whether the migrated
6020 * task is still in the wrong runqueue.
6021 * 5) if it's in the wrong runqueue then the migration thread removes
6022 * it and puts it into the right queue.
6023 * 6) migration thread up()s the semaphore.
6024 * 7) we wake up and the migration is done.
6028 * Change a given task's CPU affinity. Migrate the thread to a
6029 * proper CPU and schedule it away if the CPU it's executing on
6030 * is removed from the allowed bitmask.
6032 * NOTE: the caller must have a valid reference to the task, the
6033 * task must not exit() & deallocate itself prematurely. The
6034 * call is not atomic; no spinlocks may be held.
6036 int set_cpus_allowed_ptr(struct task_struct
*p
, const struct cpumask
*new_mask
)
6038 struct migration_req req
;
6039 unsigned long flags
;
6043 rq
= task_rq_lock(p
, &flags
);
6044 if (!cpumask_intersects(new_mask
, cpu_online_mask
)) {
6049 if (unlikely((p
->flags
& PF_THREAD_BOUND
) && p
!= current
&&
6050 !cpumask_equal(&p
->cpus_allowed
, new_mask
))) {
6055 if (p
->sched_class
->set_cpus_allowed
)
6056 p
->sched_class
->set_cpus_allowed(p
, new_mask
);
6058 cpumask_copy(&p
->cpus_allowed
, new_mask
);
6059 p
->rt
.nr_cpus_allowed
= cpumask_weight(new_mask
);
6062 /* Can the task run on the task's current CPU? If so, we're done */
6063 if (cpumask_test_cpu(task_cpu(p
), new_mask
))
6066 if (migrate_task(p
, cpumask_any_and(cpu_online_mask
, new_mask
), &req
)) {
6067 /* Need help from migration thread: drop lock and wait. */
6068 task_rq_unlock(rq
, &flags
);
6069 wake_up_process(rq
->migration_thread
);
6070 wait_for_completion(&req
.done
);
6071 tlb_migrate_finish(p
->mm
);
6075 task_rq_unlock(rq
, &flags
);
6079 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr
);
6082 * Move (not current) task off this cpu, onto dest cpu. We're doing
6083 * this because either it can't run here any more (set_cpus_allowed()
6084 * away from this CPU, or CPU going down), or because we're
6085 * attempting to rebalance this task on exec (sched_exec).
6087 * So we race with normal scheduler movements, but that's OK, as long
6088 * as the task is no longer on this CPU.
6090 * Returns non-zero if task was successfully migrated.
6092 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
6094 struct rq
*rq_dest
, *rq_src
;
6097 if (unlikely(!cpu_active(dest_cpu
)))
6100 rq_src
= cpu_rq(src_cpu
);
6101 rq_dest
= cpu_rq(dest_cpu
);
6103 double_rq_lock(rq_src
, rq_dest
);
6104 /* Already moved. */
6105 if (task_cpu(p
) != src_cpu
)
6107 /* Affinity changed (again). */
6108 if (!cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
))
6111 on_rq
= p
->se
.on_rq
;
6113 deactivate_task(rq_src
, p
, 0);
6115 set_task_cpu(p
, dest_cpu
);
6117 activate_task(rq_dest
, p
, 0);
6118 check_preempt_curr(rq_dest
, p
, 0);
6123 double_rq_unlock(rq_src
, rq_dest
);
6128 * migration_thread - this is a highprio system thread that performs
6129 * thread migration by bumping thread off CPU then 'pushing' onto
6132 static int migration_thread(void *data
)
6134 int cpu
= (long)data
;
6138 BUG_ON(rq
->migration_thread
!= current
);
6140 set_current_state(TASK_INTERRUPTIBLE
);
6141 while (!kthread_should_stop()) {
6142 struct migration_req
*req
;
6143 struct list_head
*head
;
6145 spin_lock_irq(&rq
->lock
);
6147 if (cpu_is_offline(cpu
)) {
6148 spin_unlock_irq(&rq
->lock
);
6152 if (rq
->active_balance
) {
6153 active_load_balance(rq
, cpu
);
6154 rq
->active_balance
= 0;
6157 head
= &rq
->migration_queue
;
6159 if (list_empty(head
)) {
6160 spin_unlock_irq(&rq
->lock
);
6162 set_current_state(TASK_INTERRUPTIBLE
);
6165 req
= list_entry(head
->next
, struct migration_req
, list
);
6166 list_del_init(head
->next
);
6168 spin_unlock(&rq
->lock
);
6169 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
6172 complete(&req
->done
);
6174 __set_current_state(TASK_RUNNING
);
6178 /* Wait for kthread_stop */
6179 set_current_state(TASK_INTERRUPTIBLE
);
6180 while (!kthread_should_stop()) {
6182 set_current_state(TASK_INTERRUPTIBLE
);
6184 __set_current_state(TASK_RUNNING
);
6188 #ifdef CONFIG_HOTPLUG_CPU
6190 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
6194 local_irq_disable();
6195 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
6201 * Figure out where task on dead CPU should go, use force if necessary.
6203 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
6206 /* FIXME: Use cpumask_of_node here. */
6207 cpumask_t _nodemask
= node_to_cpumask(cpu_to_node(dead_cpu
));
6208 const struct cpumask
*nodemask
= &_nodemask
;
6211 /* Look for allowed, online CPU in same node. */
6212 for_each_cpu_and(dest_cpu
, nodemask
, cpu_online_mask
)
6213 if (cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
))
6216 /* Any allowed, online CPU? */
6217 dest_cpu
= cpumask_any_and(&p
->cpus_allowed
, cpu_online_mask
);
6218 if (dest_cpu
< nr_cpu_ids
)
6221 /* No more Mr. Nice Guy. */
6222 if (dest_cpu
>= nr_cpu_ids
) {
6223 cpuset_cpus_allowed_locked(p
, &p
->cpus_allowed
);
6224 dest_cpu
= cpumask_any_and(cpu_online_mask
, &p
->cpus_allowed
);
6227 * Don't tell them about moving exiting tasks or
6228 * kernel threads (both mm NULL), since they never
6231 if (p
->mm
&& printk_ratelimit()) {
6232 printk(KERN_INFO
"process %d (%s) no "
6233 "longer affine to cpu%d\n",
6234 task_pid_nr(p
), p
->comm
, dead_cpu
);
6239 /* It can have affinity changed while we were choosing. */
6240 if (unlikely(!__migrate_task_irq(p
, dead_cpu
, dest_cpu
)))
6245 * While a dead CPU has no uninterruptible tasks queued at this point,
6246 * it might still have a nonzero ->nr_uninterruptible counter, because
6247 * for performance reasons the counter is not stricly tracking tasks to
6248 * their home CPUs. So we just add the counter to another CPU's counter,
6249 * to keep the global sum constant after CPU-down:
6251 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
6253 struct rq
*rq_dest
= cpu_rq(cpumask_any(cpu_online_mask
));
6254 unsigned long flags
;
6256 local_irq_save(flags
);
6257 double_rq_lock(rq_src
, rq_dest
);
6258 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
6259 rq_src
->nr_uninterruptible
= 0;
6260 double_rq_unlock(rq_src
, rq_dest
);
6261 local_irq_restore(flags
);
6264 /* Run through task list and migrate tasks from the dead cpu. */
6265 static void migrate_live_tasks(int src_cpu
)
6267 struct task_struct
*p
, *t
;
6269 read_lock(&tasklist_lock
);
6271 do_each_thread(t
, p
) {
6275 if (task_cpu(p
) == src_cpu
)
6276 move_task_off_dead_cpu(src_cpu
, p
);
6277 } while_each_thread(t
, p
);
6279 read_unlock(&tasklist_lock
);
6283 * Schedules idle task to be the next runnable task on current CPU.
6284 * It does so by boosting its priority to highest possible.
6285 * Used by CPU offline code.
6287 void sched_idle_next(void)
6289 int this_cpu
= smp_processor_id();
6290 struct rq
*rq
= cpu_rq(this_cpu
);
6291 struct task_struct
*p
= rq
->idle
;
6292 unsigned long flags
;
6294 /* cpu has to be offline */
6295 BUG_ON(cpu_online(this_cpu
));
6298 * Strictly not necessary since rest of the CPUs are stopped by now
6299 * and interrupts disabled on the current cpu.
6301 spin_lock_irqsave(&rq
->lock
, flags
);
6303 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
6305 update_rq_clock(rq
);
6306 activate_task(rq
, p
, 0);
6308 spin_unlock_irqrestore(&rq
->lock
, flags
);
6312 * Ensures that the idle task is using init_mm right before its cpu goes
6315 void idle_task_exit(void)
6317 struct mm_struct
*mm
= current
->active_mm
;
6319 BUG_ON(cpu_online(smp_processor_id()));
6322 switch_mm(mm
, &init_mm
, current
);
6326 /* called under rq->lock with disabled interrupts */
6327 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
6329 struct rq
*rq
= cpu_rq(dead_cpu
);
6331 /* Must be exiting, otherwise would be on tasklist. */
6332 BUG_ON(!p
->exit_state
);
6334 /* Cannot have done final schedule yet: would have vanished. */
6335 BUG_ON(p
->state
== TASK_DEAD
);
6340 * Drop lock around migration; if someone else moves it,
6341 * that's OK. No task can be added to this CPU, so iteration is
6344 spin_unlock_irq(&rq
->lock
);
6345 move_task_off_dead_cpu(dead_cpu
, p
);
6346 spin_lock_irq(&rq
->lock
);
6351 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6352 static void migrate_dead_tasks(unsigned int dead_cpu
)
6354 struct rq
*rq
= cpu_rq(dead_cpu
);
6355 struct task_struct
*next
;
6358 if (!rq
->nr_running
)
6360 update_rq_clock(rq
);
6361 next
= pick_next_task(rq
, rq
->curr
);
6364 next
->sched_class
->put_prev_task(rq
, next
);
6365 migrate_dead(dead_cpu
, next
);
6369 #endif /* CONFIG_HOTPLUG_CPU */
6371 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6373 static struct ctl_table sd_ctl_dir
[] = {
6375 .procname
= "sched_domain",
6381 static struct ctl_table sd_ctl_root
[] = {
6383 .ctl_name
= CTL_KERN
,
6384 .procname
= "kernel",
6386 .child
= sd_ctl_dir
,
6391 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
6393 struct ctl_table
*entry
=
6394 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
6399 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
6401 struct ctl_table
*entry
;
6404 * In the intermediate directories, both the child directory and
6405 * procname are dynamically allocated and could fail but the mode
6406 * will always be set. In the lowest directory the names are
6407 * static strings and all have proc handlers.
6409 for (entry
= *tablep
; entry
->mode
; entry
++) {
6411 sd_free_ctl_entry(&entry
->child
);
6412 if (entry
->proc_handler
== NULL
)
6413 kfree(entry
->procname
);
6421 set_table_entry(struct ctl_table
*entry
,
6422 const char *procname
, void *data
, int maxlen
,
6423 mode_t mode
, proc_handler
*proc_handler
)
6425 entry
->procname
= procname
;
6427 entry
->maxlen
= maxlen
;
6429 entry
->proc_handler
= proc_handler
;
6432 static struct ctl_table
*
6433 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
6435 struct ctl_table
*table
= sd_alloc_ctl_entry(13);
6440 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
6441 sizeof(long), 0644, proc_doulongvec_minmax
);
6442 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
6443 sizeof(long), 0644, proc_doulongvec_minmax
);
6444 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
6445 sizeof(int), 0644, proc_dointvec_minmax
);
6446 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
6447 sizeof(int), 0644, proc_dointvec_minmax
);
6448 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
6449 sizeof(int), 0644, proc_dointvec_minmax
);
6450 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
6451 sizeof(int), 0644, proc_dointvec_minmax
);
6452 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
6453 sizeof(int), 0644, proc_dointvec_minmax
);
6454 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
6455 sizeof(int), 0644, proc_dointvec_minmax
);
6456 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
6457 sizeof(int), 0644, proc_dointvec_minmax
);
6458 set_table_entry(&table
[9], "cache_nice_tries",
6459 &sd
->cache_nice_tries
,
6460 sizeof(int), 0644, proc_dointvec_minmax
);
6461 set_table_entry(&table
[10], "flags", &sd
->flags
,
6462 sizeof(int), 0644, proc_dointvec_minmax
);
6463 set_table_entry(&table
[11], "name", sd
->name
,
6464 CORENAME_MAX_SIZE
, 0444, proc_dostring
);
6465 /* &table[12] is terminator */
6470 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
6472 struct ctl_table
*entry
, *table
;
6473 struct sched_domain
*sd
;
6474 int domain_num
= 0, i
;
6477 for_each_domain(cpu
, sd
)
6479 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
6484 for_each_domain(cpu
, sd
) {
6485 snprintf(buf
, 32, "domain%d", i
);
6486 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
6488 entry
->child
= sd_alloc_ctl_domain_table(sd
);
6495 static struct ctl_table_header
*sd_sysctl_header
;
6496 static void register_sched_domain_sysctl(void)
6498 int i
, cpu_num
= num_online_cpus();
6499 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
6502 WARN_ON(sd_ctl_dir
[0].child
);
6503 sd_ctl_dir
[0].child
= entry
;
6508 for_each_online_cpu(i
) {
6509 snprintf(buf
, 32, "cpu%d", i
);
6510 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
6512 entry
->child
= sd_alloc_ctl_cpu_table(i
);
6516 WARN_ON(sd_sysctl_header
);
6517 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
6520 /* may be called multiple times per register */
6521 static void unregister_sched_domain_sysctl(void)
6523 if (sd_sysctl_header
)
6524 unregister_sysctl_table(sd_sysctl_header
);
6525 sd_sysctl_header
= NULL
;
6526 if (sd_ctl_dir
[0].child
)
6527 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
6530 static void register_sched_domain_sysctl(void)
6533 static void unregister_sched_domain_sysctl(void)
6538 static void set_rq_online(struct rq
*rq
)
6541 const struct sched_class
*class;
6543 cpumask_set_cpu(rq
->cpu
, rq
->rd
->online
);
6546 for_each_class(class) {
6547 if (class->rq_online
)
6548 class->rq_online(rq
);
6553 static void set_rq_offline(struct rq
*rq
)
6556 const struct sched_class
*class;
6558 for_each_class(class) {
6559 if (class->rq_offline
)
6560 class->rq_offline(rq
);
6563 cpumask_clear_cpu(rq
->cpu
, rq
->rd
->online
);
6569 * migration_call - callback that gets triggered when a CPU is added.
6570 * Here we can start up the necessary migration thread for the new CPU.
6572 static int __cpuinit
6573 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
6575 struct task_struct
*p
;
6576 int cpu
= (long)hcpu
;
6577 unsigned long flags
;
6582 case CPU_UP_PREPARE
:
6583 case CPU_UP_PREPARE_FROZEN
:
6584 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
6587 kthread_bind(p
, cpu
);
6588 /* Must be high prio: stop_machine expects to yield to it. */
6589 rq
= task_rq_lock(p
, &flags
);
6590 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
6591 task_rq_unlock(rq
, &flags
);
6592 cpu_rq(cpu
)->migration_thread
= p
;
6596 case CPU_ONLINE_FROZEN
:
6597 /* Strictly unnecessary, as first user will wake it. */
6598 wake_up_process(cpu_rq(cpu
)->migration_thread
);
6600 /* Update our root-domain */
6602 spin_lock_irqsave(&rq
->lock
, flags
);
6604 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
6608 spin_unlock_irqrestore(&rq
->lock
, flags
);
6611 #ifdef CONFIG_HOTPLUG_CPU
6612 case CPU_UP_CANCELED
:
6613 case CPU_UP_CANCELED_FROZEN
:
6614 if (!cpu_rq(cpu
)->migration_thread
)
6616 /* Unbind it from offline cpu so it can run. Fall thru. */
6617 kthread_bind(cpu_rq(cpu
)->migration_thread
,
6618 cpumask_any(cpu_online_mask
));
6619 kthread_stop(cpu_rq(cpu
)->migration_thread
);
6620 cpu_rq(cpu
)->migration_thread
= NULL
;
6624 case CPU_DEAD_FROZEN
:
6625 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6626 migrate_live_tasks(cpu
);
6628 kthread_stop(rq
->migration_thread
);
6629 rq
->migration_thread
= NULL
;
6630 /* Idle task back to normal (off runqueue, low prio) */
6631 spin_lock_irq(&rq
->lock
);
6632 update_rq_clock(rq
);
6633 deactivate_task(rq
, rq
->idle
, 0);
6634 rq
->idle
->static_prio
= MAX_PRIO
;
6635 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
6636 rq
->idle
->sched_class
= &idle_sched_class
;
6637 migrate_dead_tasks(cpu
);
6638 spin_unlock_irq(&rq
->lock
);
6640 migrate_nr_uninterruptible(rq
);
6641 BUG_ON(rq
->nr_running
!= 0);
6644 * No need to migrate the tasks: it was best-effort if
6645 * they didn't take sched_hotcpu_mutex. Just wake up
6648 spin_lock_irq(&rq
->lock
);
6649 while (!list_empty(&rq
->migration_queue
)) {
6650 struct migration_req
*req
;
6652 req
= list_entry(rq
->migration_queue
.next
,
6653 struct migration_req
, list
);
6654 list_del_init(&req
->list
);
6655 spin_unlock_irq(&rq
->lock
);
6656 complete(&req
->done
);
6657 spin_lock_irq(&rq
->lock
);
6659 spin_unlock_irq(&rq
->lock
);
6663 case CPU_DYING_FROZEN
:
6664 /* Update our root-domain */
6666 spin_lock_irqsave(&rq
->lock
, flags
);
6668 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
6671 spin_unlock_irqrestore(&rq
->lock
, flags
);
6678 /* Register at highest priority so that task migration (migrate_all_tasks)
6679 * happens before everything else.
6681 static struct notifier_block __cpuinitdata migration_notifier
= {
6682 .notifier_call
= migration_call
,
6686 static int __init
migration_init(void)
6688 void *cpu
= (void *)(long)smp_processor_id();
6691 /* Start one for the boot CPU: */
6692 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
6693 BUG_ON(err
== NOTIFY_BAD
);
6694 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
6695 register_cpu_notifier(&migration_notifier
);
6699 early_initcall(migration_init
);
6704 #ifdef CONFIG_SCHED_DEBUG
6706 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
,
6707 struct cpumask
*groupmask
)
6709 struct sched_group
*group
= sd
->groups
;
6712 cpulist_scnprintf(str
, sizeof(str
), sched_domain_span(sd
));
6713 cpumask_clear(groupmask
);
6715 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
6717 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
6718 printk("does not load-balance\n");
6720 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
6725 printk(KERN_CONT
"span %s level %s\n", str
, sd
->name
);
6727 if (!cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
6728 printk(KERN_ERR
"ERROR: domain->span does not contain "
6731 if (!cpumask_test_cpu(cpu
, sched_group_cpus(group
))) {
6732 printk(KERN_ERR
"ERROR: domain->groups does not contain"
6736 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
6740 printk(KERN_ERR
"ERROR: group is NULL\n");
6744 if (!group
->__cpu_power
) {
6745 printk(KERN_CONT
"\n");
6746 printk(KERN_ERR
"ERROR: domain->cpu_power not "
6751 if (!cpumask_weight(sched_group_cpus(group
))) {
6752 printk(KERN_CONT
"\n");
6753 printk(KERN_ERR
"ERROR: empty group\n");
6757 if (cpumask_intersects(groupmask
, sched_group_cpus(group
))) {
6758 printk(KERN_CONT
"\n");
6759 printk(KERN_ERR
"ERROR: repeated CPUs\n");
6763 cpumask_or(groupmask
, groupmask
, sched_group_cpus(group
));
6765 cpulist_scnprintf(str
, sizeof(str
), sched_group_cpus(group
));
6766 printk(KERN_CONT
" %s", str
);
6768 group
= group
->next
;
6769 } while (group
!= sd
->groups
);
6770 printk(KERN_CONT
"\n");
6772 if (!cpumask_equal(sched_domain_span(sd
), groupmask
))
6773 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
6776 !cpumask_subset(groupmask
, sched_domain_span(sd
->parent
)))
6777 printk(KERN_ERR
"ERROR: parent span is not a superset "
6778 "of domain->span\n");
6782 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
6784 cpumask_var_t groupmask
;
6788 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
6792 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
6794 if (!alloc_cpumask_var(&groupmask
, GFP_KERNEL
)) {
6795 printk(KERN_DEBUG
"Cannot load-balance (out of memory)\n");
6800 if (sched_domain_debug_one(sd
, cpu
, level
, groupmask
))
6807 free_cpumask_var(groupmask
);
6809 #else /* !CONFIG_SCHED_DEBUG */
6810 # define sched_domain_debug(sd, cpu) do { } while (0)
6811 #endif /* CONFIG_SCHED_DEBUG */
6813 static int sd_degenerate(struct sched_domain
*sd
)
6815 if (cpumask_weight(sched_domain_span(sd
)) == 1)
6818 /* Following flags need at least 2 groups */
6819 if (sd
->flags
& (SD_LOAD_BALANCE
|
6820 SD_BALANCE_NEWIDLE
|
6824 SD_SHARE_PKG_RESOURCES
)) {
6825 if (sd
->groups
!= sd
->groups
->next
)
6829 /* Following flags don't use groups */
6830 if (sd
->flags
& (SD_WAKE_IDLE
|
6839 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6841 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6843 if (sd_degenerate(parent
))
6846 if (!cpumask_equal(sched_domain_span(sd
), sched_domain_span(parent
)))
6849 /* Does parent contain flags not in child? */
6850 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6851 if (cflags
& SD_WAKE_AFFINE
)
6852 pflags
&= ~SD_WAKE_BALANCE
;
6853 /* Flags needing groups don't count if only 1 group in parent */
6854 if (parent
->groups
== parent
->groups
->next
) {
6855 pflags
&= ~(SD_LOAD_BALANCE
|
6856 SD_BALANCE_NEWIDLE
|
6860 SD_SHARE_PKG_RESOURCES
);
6861 if (nr_node_ids
== 1)
6862 pflags
&= ~SD_SERIALIZE
;
6864 if (~cflags
& pflags
)
6870 static void free_rootdomain(struct root_domain
*rd
)
6872 cpupri_cleanup(&rd
->cpupri
);
6874 free_cpumask_var(rd
->rto_mask
);
6875 free_cpumask_var(rd
->online
);
6876 free_cpumask_var(rd
->span
);
6880 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6882 unsigned long flags
;
6884 spin_lock_irqsave(&rq
->lock
, flags
);
6887 struct root_domain
*old_rd
= rq
->rd
;
6889 if (cpumask_test_cpu(rq
->cpu
, old_rd
->online
))
6892 cpumask_clear_cpu(rq
->cpu
, old_rd
->span
);
6894 if (atomic_dec_and_test(&old_rd
->refcount
))
6895 free_rootdomain(old_rd
);
6898 atomic_inc(&rd
->refcount
);
6901 cpumask_set_cpu(rq
->cpu
, rd
->span
);
6902 if (cpumask_test_cpu(rq
->cpu
, cpu_online_mask
))
6905 spin_unlock_irqrestore(&rq
->lock
, flags
);
6908 static int init_rootdomain(struct root_domain
*rd
, bool bootmem
)
6910 memset(rd
, 0, sizeof(*rd
));
6913 alloc_bootmem_cpumask_var(&def_root_domain
.span
);
6914 alloc_bootmem_cpumask_var(&def_root_domain
.online
);
6915 alloc_bootmem_cpumask_var(&def_root_domain
.rto_mask
);
6916 cpupri_init(&rd
->cpupri
, true);
6920 if (!alloc_cpumask_var(&rd
->span
, GFP_KERNEL
))
6922 if (!alloc_cpumask_var(&rd
->online
, GFP_KERNEL
))
6924 if (!alloc_cpumask_var(&rd
->rto_mask
, GFP_KERNEL
))
6927 if (cpupri_init(&rd
->cpupri
, false) != 0)
6932 free_cpumask_var(rd
->rto_mask
);
6934 free_cpumask_var(rd
->online
);
6936 free_cpumask_var(rd
->span
);
6942 static void init_defrootdomain(void)
6944 init_rootdomain(&def_root_domain
, true);
6946 atomic_set(&def_root_domain
.refcount
, 1);
6949 static struct root_domain
*alloc_rootdomain(void)
6951 struct root_domain
*rd
;
6953 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6957 if (init_rootdomain(rd
, false) != 0) {
6966 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6967 * hold the hotplug lock.
6970 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6972 struct rq
*rq
= cpu_rq(cpu
);
6973 struct sched_domain
*tmp
;
6975 /* Remove the sched domains which do not contribute to scheduling. */
6976 for (tmp
= sd
; tmp
; ) {
6977 struct sched_domain
*parent
= tmp
->parent
;
6981 if (sd_parent_degenerate(tmp
, parent
)) {
6982 tmp
->parent
= parent
->parent
;
6984 parent
->parent
->child
= tmp
;
6989 if (sd
&& sd_degenerate(sd
)) {
6995 sched_domain_debug(sd
, cpu
);
6997 rq_attach_root(rq
, rd
);
6998 rcu_assign_pointer(rq
->sd
, sd
);
7001 /* cpus with isolated domains */
7002 static cpumask_var_t cpu_isolated_map
;
7004 /* Setup the mask of cpus configured for isolated domains */
7005 static int __init
isolated_cpu_setup(char *str
)
7007 cpulist_parse(str
, cpu_isolated_map
);
7011 __setup("isolcpus=", isolated_cpu_setup
);
7014 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
7015 * to a function which identifies what group(along with sched group) a CPU
7016 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
7017 * (due to the fact that we keep track of groups covered with a struct cpumask).
7019 * init_sched_build_groups will build a circular linked list of the groups
7020 * covered by the given span, and will set each group's ->cpumask correctly,
7021 * and ->cpu_power to 0.
7024 init_sched_build_groups(const struct cpumask
*span
,
7025 const struct cpumask
*cpu_map
,
7026 int (*group_fn
)(int cpu
, const struct cpumask
*cpu_map
,
7027 struct sched_group
**sg
,
7028 struct cpumask
*tmpmask
),
7029 struct cpumask
*covered
, struct cpumask
*tmpmask
)
7031 struct sched_group
*first
= NULL
, *last
= NULL
;
7034 cpumask_clear(covered
);
7036 for_each_cpu(i
, span
) {
7037 struct sched_group
*sg
;
7038 int group
= group_fn(i
, cpu_map
, &sg
, tmpmask
);
7041 if (cpumask_test_cpu(i
, covered
))
7044 cpumask_clear(sched_group_cpus(sg
));
7045 sg
->__cpu_power
= 0;
7047 for_each_cpu(j
, span
) {
7048 if (group_fn(j
, cpu_map
, NULL
, tmpmask
) != group
)
7051 cpumask_set_cpu(j
, covered
);
7052 cpumask_set_cpu(j
, sched_group_cpus(sg
));
7063 #define SD_NODES_PER_DOMAIN 16
7068 * find_next_best_node - find the next node to include in a sched_domain
7069 * @node: node whose sched_domain we're building
7070 * @used_nodes: nodes already in the sched_domain
7072 * Find the next node to include in a given scheduling domain. Simply
7073 * finds the closest node not already in the @used_nodes map.
7075 * Should use nodemask_t.
7077 static int find_next_best_node(int node
, nodemask_t
*used_nodes
)
7079 int i
, n
, val
, min_val
, best_node
= 0;
7083 for (i
= 0; i
< nr_node_ids
; i
++) {
7084 /* Start at @node */
7085 n
= (node
+ i
) % nr_node_ids
;
7087 if (!nr_cpus_node(n
))
7090 /* Skip already used nodes */
7091 if (node_isset(n
, *used_nodes
))
7094 /* Simple min distance search */
7095 val
= node_distance(node
, n
);
7097 if (val
< min_val
) {
7103 node_set(best_node
, *used_nodes
);
7108 * sched_domain_node_span - get a cpumask for a node's sched_domain
7109 * @node: node whose cpumask we're constructing
7110 * @span: resulting cpumask
7112 * Given a node, construct a good cpumask for its sched_domain to span. It
7113 * should be one that prevents unnecessary balancing, but also spreads tasks
7116 static void sched_domain_node_span(int node
, struct cpumask
*span
)
7118 nodemask_t used_nodes
;
7119 /* FIXME: use cpumask_of_node() */
7120 node_to_cpumask_ptr(nodemask
, node
);
7124 nodes_clear(used_nodes
);
7126 cpus_or(*span
, *span
, *nodemask
);
7127 node_set(node
, used_nodes
);
7129 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
7130 int next_node
= find_next_best_node(node
, &used_nodes
);
7132 node_to_cpumask_ptr_next(nodemask
, next_node
);
7133 cpus_or(*span
, *span
, *nodemask
);
7136 #endif /* CONFIG_NUMA */
7138 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
7141 * The cpus mask in sched_group and sched_domain hangs off the end.
7142 * FIXME: use cpumask_var_t or dynamic percpu alloc to avoid wasting space
7143 * for nr_cpu_ids < CONFIG_NR_CPUS.
7145 struct static_sched_group
{
7146 struct sched_group sg
;
7147 DECLARE_BITMAP(cpus
, CONFIG_NR_CPUS
);
7150 struct static_sched_domain
{
7151 struct sched_domain sd
;
7152 DECLARE_BITMAP(span
, CONFIG_NR_CPUS
);
7156 * SMT sched-domains:
7158 #ifdef CONFIG_SCHED_SMT
7159 static DEFINE_PER_CPU(struct static_sched_domain
, cpu_domains
);
7160 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_cpus
);
7163 cpu_to_cpu_group(int cpu
, const struct cpumask
*cpu_map
,
7164 struct sched_group
**sg
, struct cpumask
*unused
)
7167 *sg
= &per_cpu(sched_group_cpus
, cpu
).sg
;
7170 #endif /* CONFIG_SCHED_SMT */
7173 * multi-core sched-domains:
7175 #ifdef CONFIG_SCHED_MC
7176 static DEFINE_PER_CPU(struct static_sched_domain
, core_domains
);
7177 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_core
);
7178 #endif /* CONFIG_SCHED_MC */
7180 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7182 cpu_to_core_group(int cpu
, const struct cpumask
*cpu_map
,
7183 struct sched_group
**sg
, struct cpumask
*mask
)
7187 cpumask_and(mask
, &per_cpu(cpu_sibling_map
, cpu
), cpu_map
);
7188 group
= cpumask_first(mask
);
7190 *sg
= &per_cpu(sched_group_core
, group
).sg
;
7193 #elif defined(CONFIG_SCHED_MC)
7195 cpu_to_core_group(int cpu
, const struct cpumask
*cpu_map
,
7196 struct sched_group
**sg
, struct cpumask
*unused
)
7199 *sg
= &per_cpu(sched_group_core
, cpu
).sg
;
7204 static DEFINE_PER_CPU(struct static_sched_domain
, phys_domains
);
7205 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_phys
);
7208 cpu_to_phys_group(int cpu
, const struct cpumask
*cpu_map
,
7209 struct sched_group
**sg
, struct cpumask
*mask
)
7212 #ifdef CONFIG_SCHED_MC
7213 /* FIXME: Use cpu_coregroup_mask. */
7214 *mask
= cpu_coregroup_map(cpu
);
7215 cpus_and(*mask
, *mask
, *cpu_map
);
7216 group
= cpumask_first(mask
);
7217 #elif defined(CONFIG_SCHED_SMT)
7218 cpumask_and(mask
, &per_cpu(cpu_sibling_map
, cpu
), cpu_map
);
7219 group
= cpumask_first(mask
);
7224 *sg
= &per_cpu(sched_group_phys
, group
).sg
;
7230 * The init_sched_build_groups can't handle what we want to do with node
7231 * groups, so roll our own. Now each node has its own list of groups which
7232 * gets dynamically allocated.
7234 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
7235 static struct sched_group
***sched_group_nodes_bycpu
;
7237 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
7238 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_allnodes
);
7240 static int cpu_to_allnodes_group(int cpu
, const struct cpumask
*cpu_map
,
7241 struct sched_group
**sg
,
7242 struct cpumask
*nodemask
)
7245 /* FIXME: use cpumask_of_node */
7246 node_to_cpumask_ptr(pnodemask
, cpu_to_node(cpu
));
7248 cpumask_and(nodemask
, pnodemask
, cpu_map
);
7249 group
= cpumask_first(nodemask
);
7252 *sg
= &per_cpu(sched_group_allnodes
, group
).sg
;
7256 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
7258 struct sched_group
*sg
= group_head
;
7264 for_each_cpu(j
, sched_group_cpus(sg
)) {
7265 struct sched_domain
*sd
;
7267 sd
= &per_cpu(phys_domains
, j
).sd
;
7268 if (j
!= cpumask_first(sched_group_cpus(sd
->groups
))) {
7270 * Only add "power" once for each
7276 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
7279 } while (sg
!= group_head
);
7281 #endif /* CONFIG_NUMA */
7284 /* Free memory allocated for various sched_group structures */
7285 static void free_sched_groups(const struct cpumask
*cpu_map
,
7286 struct cpumask
*nodemask
)
7290 for_each_cpu(cpu
, cpu_map
) {
7291 struct sched_group
**sched_group_nodes
7292 = sched_group_nodes_bycpu
[cpu
];
7294 if (!sched_group_nodes
)
7297 for (i
= 0; i
< nr_node_ids
; i
++) {
7298 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
7299 /* FIXME: Use cpumask_of_node */
7300 node_to_cpumask_ptr(pnodemask
, i
);
7302 cpus_and(*nodemask
, *pnodemask
, *cpu_map
);
7303 if (cpumask_empty(nodemask
))
7313 if (oldsg
!= sched_group_nodes
[i
])
7316 kfree(sched_group_nodes
);
7317 sched_group_nodes_bycpu
[cpu
] = NULL
;
7320 #else /* !CONFIG_NUMA */
7321 static void free_sched_groups(const struct cpumask
*cpu_map
,
7322 struct cpumask
*nodemask
)
7325 #endif /* CONFIG_NUMA */
7328 * Initialize sched groups cpu_power.
7330 * cpu_power indicates the capacity of sched group, which is used while
7331 * distributing the load between different sched groups in a sched domain.
7332 * Typically cpu_power for all the groups in a sched domain will be same unless
7333 * there are asymmetries in the topology. If there are asymmetries, group
7334 * having more cpu_power will pickup more load compared to the group having
7337 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7338 * the maximum number of tasks a group can handle in the presence of other idle
7339 * or lightly loaded groups in the same sched domain.
7341 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
7343 struct sched_domain
*child
;
7344 struct sched_group
*group
;
7346 WARN_ON(!sd
|| !sd
->groups
);
7348 if (cpu
!= cpumask_first(sched_group_cpus(sd
->groups
)))
7353 sd
->groups
->__cpu_power
= 0;
7356 * For perf policy, if the groups in child domain share resources
7357 * (for example cores sharing some portions of the cache hierarchy
7358 * or SMT), then set this domain groups cpu_power such that each group
7359 * can handle only one task, when there are other idle groups in the
7360 * same sched domain.
7362 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
7364 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
7365 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
7370 * add cpu_power of each child group to this groups cpu_power
7372 group
= child
->groups
;
7374 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
7375 group
= group
->next
;
7376 } while (group
!= child
->groups
);
7380 * Initializers for schedule domains
7381 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7384 #ifdef CONFIG_SCHED_DEBUG
7385 # define SD_INIT_NAME(sd, type) sd->name = #type
7387 # define SD_INIT_NAME(sd, type) do { } while (0)
7390 #define SD_INIT(sd, type) sd_init_##type(sd)
7392 #define SD_INIT_FUNC(type) \
7393 static noinline void sd_init_##type(struct sched_domain *sd) \
7395 memset(sd, 0, sizeof(*sd)); \
7396 *sd = SD_##type##_INIT; \
7397 sd->level = SD_LV_##type; \
7398 SD_INIT_NAME(sd, type); \
7403 SD_INIT_FUNC(ALLNODES
)
7406 #ifdef CONFIG_SCHED_SMT
7407 SD_INIT_FUNC(SIBLING
)
7409 #ifdef CONFIG_SCHED_MC
7413 static int default_relax_domain_level
= -1;
7415 static int __init
setup_relax_domain_level(char *str
)
7419 val
= simple_strtoul(str
, NULL
, 0);
7420 if (val
< SD_LV_MAX
)
7421 default_relax_domain_level
= val
;
7425 __setup("relax_domain_level=", setup_relax_domain_level
);
7427 static void set_domain_attribute(struct sched_domain
*sd
,
7428 struct sched_domain_attr
*attr
)
7432 if (!attr
|| attr
->relax_domain_level
< 0) {
7433 if (default_relax_domain_level
< 0)
7436 request
= default_relax_domain_level
;
7438 request
= attr
->relax_domain_level
;
7439 if (request
< sd
->level
) {
7440 /* turn off idle balance on this domain */
7441 sd
->flags
&= ~(SD_WAKE_IDLE
|SD_BALANCE_NEWIDLE
);
7443 /* turn on idle balance on this domain */
7444 sd
->flags
|= (SD_WAKE_IDLE_FAR
|SD_BALANCE_NEWIDLE
);
7449 * Build sched domains for a given set of cpus and attach the sched domains
7450 * to the individual cpus
7452 static int __build_sched_domains(const struct cpumask
*cpu_map
,
7453 struct sched_domain_attr
*attr
)
7455 int i
, err
= -ENOMEM
;
7456 struct root_domain
*rd
;
7457 cpumask_var_t nodemask
, this_sibling_map
, this_core_map
, send_covered
,
7460 cpumask_var_t domainspan
, covered
, notcovered
;
7461 struct sched_group
**sched_group_nodes
= NULL
;
7462 int sd_allnodes
= 0;
7464 if (!alloc_cpumask_var(&domainspan
, GFP_KERNEL
))
7466 if (!alloc_cpumask_var(&covered
, GFP_KERNEL
))
7467 goto free_domainspan
;
7468 if (!alloc_cpumask_var(¬covered
, GFP_KERNEL
))
7472 if (!alloc_cpumask_var(&nodemask
, GFP_KERNEL
))
7473 goto free_notcovered
;
7474 if (!alloc_cpumask_var(&this_sibling_map
, GFP_KERNEL
))
7476 if (!alloc_cpumask_var(&this_core_map
, GFP_KERNEL
))
7477 goto free_this_sibling_map
;
7478 if (!alloc_cpumask_var(&send_covered
, GFP_KERNEL
))
7479 goto free_this_core_map
;
7480 if (!alloc_cpumask_var(&tmpmask
, GFP_KERNEL
))
7481 goto free_send_covered
;
7485 * Allocate the per-node list of sched groups
7487 sched_group_nodes
= kcalloc(nr_node_ids
, sizeof(struct sched_group
*),
7489 if (!sched_group_nodes
) {
7490 printk(KERN_WARNING
"Can not alloc sched group node list\n");
7495 rd
= alloc_rootdomain();
7497 printk(KERN_WARNING
"Cannot alloc root domain\n");
7498 goto free_sched_groups
;
7502 sched_group_nodes_bycpu
[cpumask_first(cpu_map
)] = sched_group_nodes
;
7506 * Set up domains for cpus specified by the cpu_map.
7508 for_each_cpu(i
, cpu_map
) {
7509 struct sched_domain
*sd
= NULL
, *p
;
7511 /* FIXME: use cpumask_of_node */
7512 *nodemask
= node_to_cpumask(cpu_to_node(i
));
7513 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7516 if (cpumask_weight(cpu_map
) >
7517 SD_NODES_PER_DOMAIN
*cpumask_weight(nodemask
)) {
7518 sd
= &per_cpu(allnodes_domains
, i
);
7519 SD_INIT(sd
, ALLNODES
);
7520 set_domain_attribute(sd
, attr
);
7521 cpumask_copy(sched_domain_span(sd
), cpu_map
);
7522 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7528 sd
= &per_cpu(node_domains
, i
);
7530 set_domain_attribute(sd
, attr
);
7531 sched_domain_node_span(cpu_to_node(i
), sched_domain_span(sd
));
7535 cpumask_and(sched_domain_span(sd
),
7536 sched_domain_span(sd
), cpu_map
);
7540 sd
= &per_cpu(phys_domains
, i
).sd
;
7542 set_domain_attribute(sd
, attr
);
7543 cpumask_copy(sched_domain_span(sd
), nodemask
);
7547 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7549 #ifdef CONFIG_SCHED_MC
7551 sd
= &per_cpu(core_domains
, i
).sd
;
7553 set_domain_attribute(sd
, attr
);
7554 *sched_domain_span(sd
) = cpu_coregroup_map(i
);
7555 cpumask_and(sched_domain_span(sd
),
7556 sched_domain_span(sd
), cpu_map
);
7559 cpu_to_core_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7562 #ifdef CONFIG_SCHED_SMT
7564 sd
= &per_cpu(cpu_domains
, i
).sd
;
7565 SD_INIT(sd
, SIBLING
);
7566 set_domain_attribute(sd
, attr
);
7567 cpumask_and(sched_domain_span(sd
),
7568 &per_cpu(cpu_sibling_map
, i
), cpu_map
);
7571 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7575 #ifdef CONFIG_SCHED_SMT
7576 /* Set up CPU (sibling) groups */
7577 for_each_cpu(i
, cpu_map
) {
7578 cpumask_and(this_sibling_map
,
7579 &per_cpu(cpu_sibling_map
, i
), cpu_map
);
7580 if (i
!= cpumask_first(this_sibling_map
))
7583 init_sched_build_groups(this_sibling_map
, cpu_map
,
7585 send_covered
, tmpmask
);
7589 #ifdef CONFIG_SCHED_MC
7590 /* Set up multi-core groups */
7591 for_each_cpu(i
, cpu_map
) {
7592 /* FIXME: Use cpu_coregroup_mask */
7593 *this_core_map
= cpu_coregroup_map(i
);
7594 cpus_and(*this_core_map
, *this_core_map
, *cpu_map
);
7595 if (i
!= cpumask_first(this_core_map
))
7598 init_sched_build_groups(this_core_map
, cpu_map
,
7600 send_covered
, tmpmask
);
7604 /* Set up physical groups */
7605 for (i
= 0; i
< nr_node_ids
; i
++) {
7606 /* FIXME: Use cpumask_of_node */
7607 *nodemask
= node_to_cpumask(i
);
7608 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7609 if (cpumask_empty(nodemask
))
7612 init_sched_build_groups(nodemask
, cpu_map
,
7614 send_covered
, tmpmask
);
7618 /* Set up node groups */
7620 init_sched_build_groups(cpu_map
, cpu_map
,
7621 &cpu_to_allnodes_group
,
7622 send_covered
, tmpmask
);
7625 for (i
= 0; i
< nr_node_ids
; i
++) {
7626 /* Set up node groups */
7627 struct sched_group
*sg
, *prev
;
7630 /* FIXME: Use cpumask_of_node */
7631 *nodemask
= node_to_cpumask(i
);
7632 cpumask_clear(covered
);
7634 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7635 if (cpumask_empty(nodemask
)) {
7636 sched_group_nodes
[i
] = NULL
;
7640 sched_domain_node_span(i
, domainspan
);
7641 cpumask_and(domainspan
, domainspan
, cpu_map
);
7643 sg
= kmalloc_node(sizeof(struct sched_group
) + cpumask_size(),
7646 printk(KERN_WARNING
"Can not alloc domain group for "
7650 sched_group_nodes
[i
] = sg
;
7651 for_each_cpu(j
, nodemask
) {
7652 struct sched_domain
*sd
;
7654 sd
= &per_cpu(node_domains
, j
);
7657 sg
->__cpu_power
= 0;
7658 cpumask_copy(sched_group_cpus(sg
), nodemask
);
7660 cpumask_or(covered
, covered
, nodemask
);
7663 for (j
= 0; j
< nr_node_ids
; j
++) {
7664 int n
= (i
+ j
) % nr_node_ids
;
7665 /* FIXME: Use cpumask_of_node */
7666 node_to_cpumask_ptr(pnodemask
, n
);
7668 cpumask_complement(notcovered
, covered
);
7669 cpumask_and(tmpmask
, notcovered
, cpu_map
);
7670 cpumask_and(tmpmask
, tmpmask
, domainspan
);
7671 if (cpumask_empty(tmpmask
))
7674 cpumask_and(tmpmask
, tmpmask
, pnodemask
);
7675 if (cpumask_empty(tmpmask
))
7678 sg
= kmalloc_node(sizeof(struct sched_group
) +
7683 "Can not alloc domain group for node %d\n", j
);
7686 sg
->__cpu_power
= 0;
7687 cpumask_copy(sched_group_cpus(sg
), tmpmask
);
7688 sg
->next
= prev
->next
;
7689 cpumask_or(covered
, covered
, tmpmask
);
7696 /* Calculate CPU power for physical packages and nodes */
7697 #ifdef CONFIG_SCHED_SMT
7698 for_each_cpu(i
, cpu_map
) {
7699 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
).sd
;
7701 init_sched_groups_power(i
, sd
);
7704 #ifdef CONFIG_SCHED_MC
7705 for_each_cpu(i
, cpu_map
) {
7706 struct sched_domain
*sd
= &per_cpu(core_domains
, i
).sd
;
7708 init_sched_groups_power(i
, sd
);
7712 for_each_cpu(i
, cpu_map
) {
7713 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
).sd
;
7715 init_sched_groups_power(i
, sd
);
7719 for (i
= 0; i
< nr_node_ids
; i
++)
7720 init_numa_sched_groups_power(sched_group_nodes
[i
]);
7723 struct sched_group
*sg
;
7725 cpu_to_allnodes_group(cpumask_first(cpu_map
), cpu_map
, &sg
,
7727 init_numa_sched_groups_power(sg
);
7731 /* Attach the domains */
7732 for_each_cpu(i
, cpu_map
) {
7733 struct sched_domain
*sd
;
7734 #ifdef CONFIG_SCHED_SMT
7735 sd
= &per_cpu(cpu_domains
, i
).sd
;
7736 #elif defined(CONFIG_SCHED_MC)
7737 sd
= &per_cpu(core_domains
, i
).sd
;
7739 sd
= &per_cpu(phys_domains
, i
).sd
;
7741 cpu_attach_domain(sd
, rd
, i
);
7747 free_cpumask_var(tmpmask
);
7749 free_cpumask_var(send_covered
);
7751 free_cpumask_var(this_core_map
);
7752 free_this_sibling_map
:
7753 free_cpumask_var(this_sibling_map
);
7755 free_cpumask_var(nodemask
);
7758 free_cpumask_var(notcovered
);
7760 free_cpumask_var(covered
);
7762 free_cpumask_var(domainspan
);
7769 kfree(sched_group_nodes
);
7775 free_sched_groups(cpu_map
, tmpmask
);
7776 free_rootdomain(rd
);
7781 static int build_sched_domains(const struct cpumask
*cpu_map
)
7783 return __build_sched_domains(cpu_map
, NULL
);
7786 static struct cpumask
*doms_cur
; /* current sched domains */
7787 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
7788 static struct sched_domain_attr
*dattr_cur
;
7789 /* attribues of custom domains in 'doms_cur' */
7792 * Special case: If a kmalloc of a doms_cur partition (array of
7793 * cpumask) fails, then fallback to a single sched domain,
7794 * as determined by the single cpumask fallback_doms.
7796 static cpumask_var_t fallback_doms
;
7799 * arch_update_cpu_topology lets virtualized architectures update the
7800 * cpu core maps. It is supposed to return 1 if the topology changed
7801 * or 0 if it stayed the same.
7803 int __attribute__((weak
)) arch_update_cpu_topology(void)
7809 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7810 * For now this just excludes isolated cpus, but could be used to
7811 * exclude other special cases in the future.
7813 static int arch_init_sched_domains(const struct cpumask
*cpu_map
)
7817 arch_update_cpu_topology();
7819 doms_cur
= kmalloc(cpumask_size(), GFP_KERNEL
);
7821 doms_cur
= fallback_doms
;
7822 cpumask_andnot(doms_cur
, cpu_map
, cpu_isolated_map
);
7824 err
= build_sched_domains(doms_cur
);
7825 register_sched_domain_sysctl();
7830 static void arch_destroy_sched_domains(const struct cpumask
*cpu_map
,
7831 struct cpumask
*tmpmask
)
7833 free_sched_groups(cpu_map
, tmpmask
);
7837 * Detach sched domains from a group of cpus specified in cpu_map
7838 * These cpus will now be attached to the NULL domain
7840 static void detach_destroy_domains(const struct cpumask
*cpu_map
)
7842 /* Save because hotplug lock held. */
7843 static DECLARE_BITMAP(tmpmask
, CONFIG_NR_CPUS
);
7846 for_each_cpu(i
, cpu_map
)
7847 cpu_attach_domain(NULL
, &def_root_domain
, i
);
7848 synchronize_sched();
7849 arch_destroy_sched_domains(cpu_map
, to_cpumask(tmpmask
));
7852 /* handle null as "default" */
7853 static int dattrs_equal(struct sched_domain_attr
*cur
, int idx_cur
,
7854 struct sched_domain_attr
*new, int idx_new
)
7856 struct sched_domain_attr tmp
;
7863 return !memcmp(cur
? (cur
+ idx_cur
) : &tmp
,
7864 new ? (new + idx_new
) : &tmp
,
7865 sizeof(struct sched_domain_attr
));
7869 * Partition sched domains as specified by the 'ndoms_new'
7870 * cpumasks in the array doms_new[] of cpumasks. This compares
7871 * doms_new[] to the current sched domain partitioning, doms_cur[].
7872 * It destroys each deleted domain and builds each new domain.
7874 * 'doms_new' is an array of cpumask's of length 'ndoms_new'.
7875 * The masks don't intersect (don't overlap.) We should setup one
7876 * sched domain for each mask. CPUs not in any of the cpumasks will
7877 * not be load balanced. If the same cpumask appears both in the
7878 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7881 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7882 * ownership of it and will kfree it when done with it. If the caller
7883 * failed the kmalloc call, then it can pass in doms_new == NULL &&
7884 * ndoms_new == 1, and partition_sched_domains() will fallback to
7885 * the single partition 'fallback_doms', it also forces the domains
7888 * If doms_new == NULL it will be replaced with cpu_online_mask.
7889 * ndoms_new == 0 is a special case for destroying existing domains,
7890 * and it will not create the default domain.
7892 * Call with hotplug lock held
7894 /* FIXME: Change to struct cpumask *doms_new[] */
7895 void partition_sched_domains(int ndoms_new
, struct cpumask
*doms_new
,
7896 struct sched_domain_attr
*dattr_new
)
7901 mutex_lock(&sched_domains_mutex
);
7903 /* always unregister in case we don't destroy any domains */
7904 unregister_sched_domain_sysctl();
7906 /* Let architecture update cpu core mappings. */
7907 new_topology
= arch_update_cpu_topology();
7909 n
= doms_new
? ndoms_new
: 0;
7911 /* Destroy deleted domains */
7912 for (i
= 0; i
< ndoms_cur
; i
++) {
7913 for (j
= 0; j
< n
&& !new_topology
; j
++) {
7914 if (cpumask_equal(&doms_cur
[i
], &doms_new
[j
])
7915 && dattrs_equal(dattr_cur
, i
, dattr_new
, j
))
7918 /* no match - a current sched domain not in new doms_new[] */
7919 detach_destroy_domains(doms_cur
+ i
);
7924 if (doms_new
== NULL
) {
7926 doms_new
= fallback_doms
;
7927 cpumask_andnot(&doms_new
[0], cpu_online_mask
, cpu_isolated_map
);
7928 WARN_ON_ONCE(dattr_new
);
7931 /* Build new domains */
7932 for (i
= 0; i
< ndoms_new
; i
++) {
7933 for (j
= 0; j
< ndoms_cur
&& !new_topology
; j
++) {
7934 if (cpumask_equal(&doms_new
[i
], &doms_cur
[j
])
7935 && dattrs_equal(dattr_new
, i
, dattr_cur
, j
))
7938 /* no match - add a new doms_new */
7939 __build_sched_domains(doms_new
+ i
,
7940 dattr_new
? dattr_new
+ i
: NULL
);
7945 /* Remember the new sched domains */
7946 if (doms_cur
!= fallback_doms
)
7948 kfree(dattr_cur
); /* kfree(NULL) is safe */
7949 doms_cur
= doms_new
;
7950 dattr_cur
= dattr_new
;
7951 ndoms_cur
= ndoms_new
;
7953 register_sched_domain_sysctl();
7955 mutex_unlock(&sched_domains_mutex
);
7958 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7959 int arch_reinit_sched_domains(void)
7963 /* Destroy domains first to force the rebuild */
7964 partition_sched_domains(0, NULL
, NULL
);
7966 rebuild_sched_domains();
7972 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
7975 unsigned int level
= 0;
7977 if (sscanf(buf
, "%u", &level
) != 1)
7981 * level is always be positive so don't check for
7982 * level < POWERSAVINGS_BALANCE_NONE which is 0
7983 * What happens on 0 or 1 byte write,
7984 * need to check for count as well?
7987 if (level
>= MAX_POWERSAVINGS_BALANCE_LEVELS
)
7991 sched_smt_power_savings
= level
;
7993 sched_mc_power_savings
= level
;
7995 ret
= arch_reinit_sched_domains();
7997 return ret
? ret
: count
;
8000 #ifdef CONFIG_SCHED_MC
8001 static ssize_t
sched_mc_power_savings_show(struct sysdev_class
*class,
8004 return sprintf(page
, "%u\n", sched_mc_power_savings
);
8006 static ssize_t
sched_mc_power_savings_store(struct sysdev_class
*class,
8007 const char *buf
, size_t count
)
8009 return sched_power_savings_store(buf
, count
, 0);
8011 static SYSDEV_CLASS_ATTR(sched_mc_power_savings
, 0644,
8012 sched_mc_power_savings_show
,
8013 sched_mc_power_savings_store
);
8016 #ifdef CONFIG_SCHED_SMT
8017 static ssize_t
sched_smt_power_savings_show(struct sysdev_class
*dev
,
8020 return sprintf(page
, "%u\n", sched_smt_power_savings
);
8022 static ssize_t
sched_smt_power_savings_store(struct sysdev_class
*dev
,
8023 const char *buf
, size_t count
)
8025 return sched_power_savings_store(buf
, count
, 1);
8027 static SYSDEV_CLASS_ATTR(sched_smt_power_savings
, 0644,
8028 sched_smt_power_savings_show
,
8029 sched_smt_power_savings_store
);
8032 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
8036 #ifdef CONFIG_SCHED_SMT
8038 err
= sysfs_create_file(&cls
->kset
.kobj
,
8039 &attr_sched_smt_power_savings
.attr
);
8041 #ifdef CONFIG_SCHED_MC
8042 if (!err
&& mc_capable())
8043 err
= sysfs_create_file(&cls
->kset
.kobj
,
8044 &attr_sched_mc_power_savings
.attr
);
8048 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
8050 #ifndef CONFIG_CPUSETS
8052 * Add online and remove offline CPUs from the scheduler domains.
8053 * When cpusets are enabled they take over this function.
8055 static int update_sched_domains(struct notifier_block
*nfb
,
8056 unsigned long action
, void *hcpu
)
8060 case CPU_ONLINE_FROZEN
:
8062 case CPU_DEAD_FROZEN
:
8063 partition_sched_domains(1, NULL
, NULL
);
8072 static int update_runtime(struct notifier_block
*nfb
,
8073 unsigned long action
, void *hcpu
)
8075 int cpu
= (int)(long)hcpu
;
8078 case CPU_DOWN_PREPARE
:
8079 case CPU_DOWN_PREPARE_FROZEN
:
8080 disable_runtime(cpu_rq(cpu
));
8083 case CPU_DOWN_FAILED
:
8084 case CPU_DOWN_FAILED_FROZEN
:
8086 case CPU_ONLINE_FROZEN
:
8087 enable_runtime(cpu_rq(cpu
));
8095 void __init
sched_init_smp(void)
8097 cpumask_var_t non_isolated_cpus
;
8099 alloc_cpumask_var(&non_isolated_cpus
, GFP_KERNEL
);
8101 #if defined(CONFIG_NUMA)
8102 sched_group_nodes_bycpu
= kzalloc(nr_cpu_ids
* sizeof(void **),
8104 BUG_ON(sched_group_nodes_bycpu
== NULL
);
8107 mutex_lock(&sched_domains_mutex
);
8108 arch_init_sched_domains(cpu_online_mask
);
8109 cpumask_andnot(non_isolated_cpus
, cpu_possible_mask
, cpu_isolated_map
);
8110 if (cpumask_empty(non_isolated_cpus
))
8111 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus
);
8112 mutex_unlock(&sched_domains_mutex
);
8115 #ifndef CONFIG_CPUSETS
8116 /* XXX: Theoretical race here - CPU may be hotplugged now */
8117 hotcpu_notifier(update_sched_domains
, 0);
8120 /* RT runtime code needs to handle some hotplug events */
8121 hotcpu_notifier(update_runtime
, 0);
8125 /* Move init over to a non-isolated CPU */
8126 if (set_cpus_allowed_ptr(current
, non_isolated_cpus
) < 0)
8128 sched_init_granularity();
8129 free_cpumask_var(non_isolated_cpus
);
8131 alloc_cpumask_var(&fallback_doms
, GFP_KERNEL
);
8132 init_sched_rt_class();
8135 void __init
sched_init_smp(void)
8137 sched_init_granularity();
8139 #endif /* CONFIG_SMP */
8141 int in_sched_functions(unsigned long addr
)
8143 return in_lock_functions(addr
) ||
8144 (addr
>= (unsigned long)__sched_text_start
8145 && addr
< (unsigned long)__sched_text_end
);
8148 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
8150 cfs_rq
->tasks_timeline
= RB_ROOT
;
8151 INIT_LIST_HEAD(&cfs_rq
->tasks
);
8152 #ifdef CONFIG_FAIR_GROUP_SCHED
8155 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
8158 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
8160 struct rt_prio_array
*array
;
8163 array
= &rt_rq
->active
;
8164 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
8165 INIT_LIST_HEAD(array
->queue
+ i
);
8166 __clear_bit(i
, array
->bitmap
);
8168 /* delimiter for bitsearch: */
8169 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
8171 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8172 rt_rq
->highest_prio
= MAX_RT_PRIO
;
8175 rt_rq
->rt_nr_migratory
= 0;
8176 rt_rq
->overloaded
= 0;
8180 rt_rq
->rt_throttled
= 0;
8181 rt_rq
->rt_runtime
= 0;
8182 spin_lock_init(&rt_rq
->rt_runtime_lock
);
8184 #ifdef CONFIG_RT_GROUP_SCHED
8185 rt_rq
->rt_nr_boosted
= 0;
8190 #ifdef CONFIG_FAIR_GROUP_SCHED
8191 static void init_tg_cfs_entry(struct task_group
*tg
, struct cfs_rq
*cfs_rq
,
8192 struct sched_entity
*se
, int cpu
, int add
,
8193 struct sched_entity
*parent
)
8195 struct rq
*rq
= cpu_rq(cpu
);
8196 tg
->cfs_rq
[cpu
] = cfs_rq
;
8197 init_cfs_rq(cfs_rq
, rq
);
8200 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
8203 /* se could be NULL for init_task_group */
8208 se
->cfs_rq
= &rq
->cfs
;
8210 se
->cfs_rq
= parent
->my_q
;
8213 se
->load
.weight
= tg
->shares
;
8214 se
->load
.inv_weight
= 0;
8215 se
->parent
= parent
;
8219 #ifdef CONFIG_RT_GROUP_SCHED
8220 static void init_tg_rt_entry(struct task_group
*tg
, struct rt_rq
*rt_rq
,
8221 struct sched_rt_entity
*rt_se
, int cpu
, int add
,
8222 struct sched_rt_entity
*parent
)
8224 struct rq
*rq
= cpu_rq(cpu
);
8226 tg
->rt_rq
[cpu
] = rt_rq
;
8227 init_rt_rq(rt_rq
, rq
);
8229 rt_rq
->rt_se
= rt_se
;
8230 rt_rq
->rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
8232 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
8234 tg
->rt_se
[cpu
] = rt_se
;
8239 rt_se
->rt_rq
= &rq
->rt
;
8241 rt_se
->rt_rq
= parent
->my_q
;
8243 rt_se
->my_q
= rt_rq
;
8244 rt_se
->parent
= parent
;
8245 INIT_LIST_HEAD(&rt_se
->run_list
);
8249 void __init
sched_init(void)
8252 unsigned long alloc_size
= 0, ptr
;
8254 #ifdef CONFIG_FAIR_GROUP_SCHED
8255 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
8257 #ifdef CONFIG_RT_GROUP_SCHED
8258 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
8260 #ifdef CONFIG_USER_SCHED
8264 * As sched_init() is called before page_alloc is setup,
8265 * we use alloc_bootmem().
8268 ptr
= (unsigned long)alloc_bootmem(alloc_size
);
8270 #ifdef CONFIG_FAIR_GROUP_SCHED
8271 init_task_group
.se
= (struct sched_entity
**)ptr
;
8272 ptr
+= nr_cpu_ids
* sizeof(void **);
8274 init_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
8275 ptr
+= nr_cpu_ids
* sizeof(void **);
8277 #ifdef CONFIG_USER_SCHED
8278 root_task_group
.se
= (struct sched_entity
**)ptr
;
8279 ptr
+= nr_cpu_ids
* sizeof(void **);
8281 root_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
8282 ptr
+= nr_cpu_ids
* sizeof(void **);
8283 #endif /* CONFIG_USER_SCHED */
8284 #endif /* CONFIG_FAIR_GROUP_SCHED */
8285 #ifdef CONFIG_RT_GROUP_SCHED
8286 init_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
8287 ptr
+= nr_cpu_ids
* sizeof(void **);
8289 init_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
8290 ptr
+= nr_cpu_ids
* sizeof(void **);
8292 #ifdef CONFIG_USER_SCHED
8293 root_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
8294 ptr
+= nr_cpu_ids
* sizeof(void **);
8296 root_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
8297 ptr
+= nr_cpu_ids
* sizeof(void **);
8298 #endif /* CONFIG_USER_SCHED */
8299 #endif /* CONFIG_RT_GROUP_SCHED */
8303 init_defrootdomain();
8306 init_rt_bandwidth(&def_rt_bandwidth
,
8307 global_rt_period(), global_rt_runtime());
8309 #ifdef CONFIG_RT_GROUP_SCHED
8310 init_rt_bandwidth(&init_task_group
.rt_bandwidth
,
8311 global_rt_period(), global_rt_runtime());
8312 #ifdef CONFIG_USER_SCHED
8313 init_rt_bandwidth(&root_task_group
.rt_bandwidth
,
8314 global_rt_period(), RUNTIME_INF
);
8315 #endif /* CONFIG_USER_SCHED */
8316 #endif /* CONFIG_RT_GROUP_SCHED */
8318 #ifdef CONFIG_GROUP_SCHED
8319 list_add(&init_task_group
.list
, &task_groups
);
8320 INIT_LIST_HEAD(&init_task_group
.children
);
8322 #ifdef CONFIG_USER_SCHED
8323 INIT_LIST_HEAD(&root_task_group
.children
);
8324 init_task_group
.parent
= &root_task_group
;
8325 list_add(&init_task_group
.siblings
, &root_task_group
.children
);
8326 #endif /* CONFIG_USER_SCHED */
8327 #endif /* CONFIG_GROUP_SCHED */
8329 for_each_possible_cpu(i
) {
8333 spin_lock_init(&rq
->lock
);
8335 init_cfs_rq(&rq
->cfs
, rq
);
8336 init_rt_rq(&rq
->rt
, rq
);
8337 #ifdef CONFIG_FAIR_GROUP_SCHED
8338 init_task_group
.shares
= init_task_group_load
;
8339 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
8340 #ifdef CONFIG_CGROUP_SCHED
8342 * How much cpu bandwidth does init_task_group get?
8344 * In case of task-groups formed thr' the cgroup filesystem, it
8345 * gets 100% of the cpu resources in the system. This overall
8346 * system cpu resource is divided among the tasks of
8347 * init_task_group and its child task-groups in a fair manner,
8348 * based on each entity's (task or task-group's) weight
8349 * (se->load.weight).
8351 * In other words, if init_task_group has 10 tasks of weight
8352 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8353 * then A0's share of the cpu resource is:
8355 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8357 * We achieve this by letting init_task_group's tasks sit
8358 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8360 init_tg_cfs_entry(&init_task_group
, &rq
->cfs
, NULL
, i
, 1, NULL
);
8361 #elif defined CONFIG_USER_SCHED
8362 root_task_group
.shares
= NICE_0_LOAD
;
8363 init_tg_cfs_entry(&root_task_group
, &rq
->cfs
, NULL
, i
, 0, NULL
);
8365 * In case of task-groups formed thr' the user id of tasks,
8366 * init_task_group represents tasks belonging to root user.
8367 * Hence it forms a sibling of all subsequent groups formed.
8368 * In this case, init_task_group gets only a fraction of overall
8369 * system cpu resource, based on the weight assigned to root
8370 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8371 * by letting tasks of init_task_group sit in a separate cfs_rq
8372 * (init_cfs_rq) and having one entity represent this group of
8373 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8375 init_tg_cfs_entry(&init_task_group
,
8376 &per_cpu(init_cfs_rq
, i
),
8377 &per_cpu(init_sched_entity
, i
), i
, 1,
8378 root_task_group
.se
[i
]);
8381 #endif /* CONFIG_FAIR_GROUP_SCHED */
8383 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
8384 #ifdef CONFIG_RT_GROUP_SCHED
8385 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
8386 #ifdef CONFIG_CGROUP_SCHED
8387 init_tg_rt_entry(&init_task_group
, &rq
->rt
, NULL
, i
, 1, NULL
);
8388 #elif defined CONFIG_USER_SCHED
8389 init_tg_rt_entry(&root_task_group
, &rq
->rt
, NULL
, i
, 0, NULL
);
8390 init_tg_rt_entry(&init_task_group
,
8391 &per_cpu(init_rt_rq
, i
),
8392 &per_cpu(init_sched_rt_entity
, i
), i
, 1,
8393 root_task_group
.rt_se
[i
]);
8397 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
8398 rq
->cpu_load
[j
] = 0;
8402 rq
->active_balance
= 0;
8403 rq
->next_balance
= jiffies
;
8407 rq
->migration_thread
= NULL
;
8408 INIT_LIST_HEAD(&rq
->migration_queue
);
8409 rq_attach_root(rq
, &def_root_domain
);
8412 atomic_set(&rq
->nr_iowait
, 0);
8415 set_load_weight(&init_task
);
8417 #ifdef CONFIG_PREEMPT_NOTIFIERS
8418 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
8422 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
);
8425 #ifdef CONFIG_RT_MUTEXES
8426 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
8430 * The boot idle thread does lazy MMU switching as well:
8432 atomic_inc(&init_mm
.mm_count
);
8433 enter_lazy_tlb(&init_mm
, current
);
8436 * Make us the idle thread. Technically, schedule() should not be
8437 * called from this thread, however somewhere below it might be,
8438 * but because we are the idle thread, we just pick up running again
8439 * when this runqueue becomes "idle".
8441 init_idle(current
, smp_processor_id());
8443 * During early bootup we pretend to be a normal task:
8445 current
->sched_class
= &fair_sched_class
;
8447 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
8448 alloc_bootmem_cpumask_var(&nohz_cpu_mask
);
8451 alloc_bootmem_cpumask_var(&nohz
.cpu_mask
);
8453 alloc_bootmem_cpumask_var(&cpu_isolated_map
);
8456 scheduler_running
= 1;
8459 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8460 void __might_sleep(char *file
, int line
)
8463 static unsigned long prev_jiffy
; /* ratelimiting */
8465 if ((!in_atomic() && !irqs_disabled()) ||
8466 system_state
!= SYSTEM_RUNNING
|| oops_in_progress
)
8468 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
8470 prev_jiffy
= jiffies
;
8473 "BUG: sleeping function called from invalid context at %s:%d\n",
8476 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8477 in_atomic(), irqs_disabled(),
8478 current
->pid
, current
->comm
);
8480 debug_show_held_locks(current
);
8481 if (irqs_disabled())
8482 print_irqtrace_events(current
);
8486 EXPORT_SYMBOL(__might_sleep
);
8489 #ifdef CONFIG_MAGIC_SYSRQ
8490 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
8494 update_rq_clock(rq
);
8495 on_rq
= p
->se
.on_rq
;
8497 deactivate_task(rq
, p
, 0);
8498 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
8500 activate_task(rq
, p
, 0);
8501 resched_task(rq
->curr
);
8505 void normalize_rt_tasks(void)
8507 struct task_struct
*g
, *p
;
8508 unsigned long flags
;
8511 read_lock_irqsave(&tasklist_lock
, flags
);
8512 do_each_thread(g
, p
) {
8514 * Only normalize user tasks:
8519 p
->se
.exec_start
= 0;
8520 #ifdef CONFIG_SCHEDSTATS
8521 p
->se
.wait_start
= 0;
8522 p
->se
.sleep_start
= 0;
8523 p
->se
.block_start
= 0;
8528 * Renice negative nice level userspace
8531 if (TASK_NICE(p
) < 0 && p
->mm
)
8532 set_user_nice(p
, 0);
8536 spin_lock(&p
->pi_lock
);
8537 rq
= __task_rq_lock(p
);
8539 normalize_task(rq
, p
);
8541 __task_rq_unlock(rq
);
8542 spin_unlock(&p
->pi_lock
);
8543 } while_each_thread(g
, p
);
8545 read_unlock_irqrestore(&tasklist_lock
, flags
);
8548 #endif /* CONFIG_MAGIC_SYSRQ */
8552 * These functions are only useful for the IA64 MCA handling.
8554 * They can only be called when the whole system has been
8555 * stopped - every CPU needs to be quiescent, and no scheduling
8556 * activity can take place. Using them for anything else would
8557 * be a serious bug, and as a result, they aren't even visible
8558 * under any other configuration.
8562 * curr_task - return the current task for a given cpu.
8563 * @cpu: the processor in question.
8565 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8567 struct task_struct
*curr_task(int cpu
)
8569 return cpu_curr(cpu
);
8573 * set_curr_task - set the current task for a given cpu.
8574 * @cpu: the processor in question.
8575 * @p: the task pointer to set.
8577 * Description: This function must only be used when non-maskable interrupts
8578 * are serviced on a separate stack. It allows the architecture to switch the
8579 * notion of the current task on a cpu in a non-blocking manner. This function
8580 * must be called with all CPU's synchronized, and interrupts disabled, the
8581 * and caller must save the original value of the current task (see
8582 * curr_task() above) and restore that value before reenabling interrupts and
8583 * re-starting the system.
8585 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8587 void set_curr_task(int cpu
, struct task_struct
*p
)
8594 #ifdef CONFIG_FAIR_GROUP_SCHED
8595 static void free_fair_sched_group(struct task_group
*tg
)
8599 for_each_possible_cpu(i
) {
8601 kfree(tg
->cfs_rq
[i
]);
8611 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8613 struct cfs_rq
*cfs_rq
;
8614 struct sched_entity
*se
;
8618 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * nr_cpu_ids
, GFP_KERNEL
);
8621 tg
->se
= kzalloc(sizeof(se
) * nr_cpu_ids
, GFP_KERNEL
);
8625 tg
->shares
= NICE_0_LOAD
;
8627 for_each_possible_cpu(i
) {
8630 cfs_rq
= kzalloc_node(sizeof(struct cfs_rq
),
8631 GFP_KERNEL
, cpu_to_node(i
));
8635 se
= kzalloc_node(sizeof(struct sched_entity
),
8636 GFP_KERNEL
, cpu_to_node(i
));
8640 init_tg_cfs_entry(tg
, cfs_rq
, se
, i
, 0, parent
->se
[i
]);
8649 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
8651 list_add_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
,
8652 &cpu_rq(cpu
)->leaf_cfs_rq_list
);
8655 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
8657 list_del_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
);
8659 #else /* !CONFG_FAIR_GROUP_SCHED */
8660 static inline void free_fair_sched_group(struct task_group
*tg
)
8665 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8670 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
8674 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
8677 #endif /* CONFIG_FAIR_GROUP_SCHED */
8679 #ifdef CONFIG_RT_GROUP_SCHED
8680 static void free_rt_sched_group(struct task_group
*tg
)
8684 destroy_rt_bandwidth(&tg
->rt_bandwidth
);
8686 for_each_possible_cpu(i
) {
8688 kfree(tg
->rt_rq
[i
]);
8690 kfree(tg
->rt_se
[i
]);
8698 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8700 struct rt_rq
*rt_rq
;
8701 struct sched_rt_entity
*rt_se
;
8705 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * nr_cpu_ids
, GFP_KERNEL
);
8708 tg
->rt_se
= kzalloc(sizeof(rt_se
) * nr_cpu_ids
, GFP_KERNEL
);
8712 init_rt_bandwidth(&tg
->rt_bandwidth
,
8713 ktime_to_ns(def_rt_bandwidth
.rt_period
), 0);
8715 for_each_possible_cpu(i
) {
8718 rt_rq
= kzalloc_node(sizeof(struct rt_rq
),
8719 GFP_KERNEL
, cpu_to_node(i
));
8723 rt_se
= kzalloc_node(sizeof(struct sched_rt_entity
),
8724 GFP_KERNEL
, cpu_to_node(i
));
8728 init_tg_rt_entry(tg
, rt_rq
, rt_se
, i
, 0, parent
->rt_se
[i
]);
8737 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
8739 list_add_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
,
8740 &cpu_rq(cpu
)->leaf_rt_rq_list
);
8743 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
8745 list_del_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
);
8747 #else /* !CONFIG_RT_GROUP_SCHED */
8748 static inline void free_rt_sched_group(struct task_group
*tg
)
8753 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8758 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
8762 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
8765 #endif /* CONFIG_RT_GROUP_SCHED */
8767 #ifdef CONFIG_GROUP_SCHED
8768 static void free_sched_group(struct task_group
*tg
)
8770 free_fair_sched_group(tg
);
8771 free_rt_sched_group(tg
);
8775 /* allocate runqueue etc for a new task group */
8776 struct task_group
*sched_create_group(struct task_group
*parent
)
8778 struct task_group
*tg
;
8779 unsigned long flags
;
8782 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
8784 return ERR_PTR(-ENOMEM
);
8786 if (!alloc_fair_sched_group(tg
, parent
))
8789 if (!alloc_rt_sched_group(tg
, parent
))
8792 spin_lock_irqsave(&task_group_lock
, flags
);
8793 for_each_possible_cpu(i
) {
8794 register_fair_sched_group(tg
, i
);
8795 register_rt_sched_group(tg
, i
);
8797 list_add_rcu(&tg
->list
, &task_groups
);
8799 WARN_ON(!parent
); /* root should already exist */
8801 tg
->parent
= parent
;
8802 INIT_LIST_HEAD(&tg
->children
);
8803 list_add_rcu(&tg
->siblings
, &parent
->children
);
8804 spin_unlock_irqrestore(&task_group_lock
, flags
);
8809 free_sched_group(tg
);
8810 return ERR_PTR(-ENOMEM
);
8813 /* rcu callback to free various structures associated with a task group */
8814 static void free_sched_group_rcu(struct rcu_head
*rhp
)
8816 /* now it should be safe to free those cfs_rqs */
8817 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
8820 /* Destroy runqueue etc associated with a task group */
8821 void sched_destroy_group(struct task_group
*tg
)
8823 unsigned long flags
;
8826 spin_lock_irqsave(&task_group_lock
, flags
);
8827 for_each_possible_cpu(i
) {
8828 unregister_fair_sched_group(tg
, i
);
8829 unregister_rt_sched_group(tg
, i
);
8831 list_del_rcu(&tg
->list
);
8832 list_del_rcu(&tg
->siblings
);
8833 spin_unlock_irqrestore(&task_group_lock
, flags
);
8835 /* wait for possible concurrent references to cfs_rqs complete */
8836 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
8839 /* change task's runqueue when it moves between groups.
8840 * The caller of this function should have put the task in its new group
8841 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8842 * reflect its new group.
8844 void sched_move_task(struct task_struct
*tsk
)
8847 unsigned long flags
;
8850 rq
= task_rq_lock(tsk
, &flags
);
8852 update_rq_clock(rq
);
8854 running
= task_current(rq
, tsk
);
8855 on_rq
= tsk
->se
.on_rq
;
8858 dequeue_task(rq
, tsk
, 0);
8859 if (unlikely(running
))
8860 tsk
->sched_class
->put_prev_task(rq
, tsk
);
8862 set_task_rq(tsk
, task_cpu(tsk
));
8864 #ifdef CONFIG_FAIR_GROUP_SCHED
8865 if (tsk
->sched_class
->moved_group
)
8866 tsk
->sched_class
->moved_group(tsk
);
8869 if (unlikely(running
))
8870 tsk
->sched_class
->set_curr_task(rq
);
8872 enqueue_task(rq
, tsk
, 0);
8874 task_rq_unlock(rq
, &flags
);
8876 #endif /* CONFIG_GROUP_SCHED */
8878 #ifdef CONFIG_FAIR_GROUP_SCHED
8879 static void __set_se_shares(struct sched_entity
*se
, unsigned long shares
)
8881 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
8886 dequeue_entity(cfs_rq
, se
, 0);
8888 se
->load
.weight
= shares
;
8889 se
->load
.inv_weight
= 0;
8892 enqueue_entity(cfs_rq
, se
, 0);
8895 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
8897 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
8898 struct rq
*rq
= cfs_rq
->rq
;
8899 unsigned long flags
;
8901 spin_lock_irqsave(&rq
->lock
, flags
);
8902 __set_se_shares(se
, shares
);
8903 spin_unlock_irqrestore(&rq
->lock
, flags
);
8906 static DEFINE_MUTEX(shares_mutex
);
8908 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
8911 unsigned long flags
;
8914 * We can't change the weight of the root cgroup.
8919 if (shares
< MIN_SHARES
)
8920 shares
= MIN_SHARES
;
8921 else if (shares
> MAX_SHARES
)
8922 shares
= MAX_SHARES
;
8924 mutex_lock(&shares_mutex
);
8925 if (tg
->shares
== shares
)
8928 spin_lock_irqsave(&task_group_lock
, flags
);
8929 for_each_possible_cpu(i
)
8930 unregister_fair_sched_group(tg
, i
);
8931 list_del_rcu(&tg
->siblings
);
8932 spin_unlock_irqrestore(&task_group_lock
, flags
);
8934 /* wait for any ongoing reference to this group to finish */
8935 synchronize_sched();
8938 * Now we are free to modify the group's share on each cpu
8939 * w/o tripping rebalance_share or load_balance_fair.
8941 tg
->shares
= shares
;
8942 for_each_possible_cpu(i
) {
8946 cfs_rq_set_shares(tg
->cfs_rq
[i
], 0);
8947 set_se_shares(tg
->se
[i
], shares
);
8951 * Enable load balance activity on this group, by inserting it back on
8952 * each cpu's rq->leaf_cfs_rq_list.
8954 spin_lock_irqsave(&task_group_lock
, flags
);
8955 for_each_possible_cpu(i
)
8956 register_fair_sched_group(tg
, i
);
8957 list_add_rcu(&tg
->siblings
, &tg
->parent
->children
);
8958 spin_unlock_irqrestore(&task_group_lock
, flags
);
8960 mutex_unlock(&shares_mutex
);
8964 unsigned long sched_group_shares(struct task_group
*tg
)
8970 #ifdef CONFIG_RT_GROUP_SCHED
8972 * Ensure that the real time constraints are schedulable.
8974 static DEFINE_MUTEX(rt_constraints_mutex
);
8976 static unsigned long to_ratio(u64 period
, u64 runtime
)
8978 if (runtime
== RUNTIME_INF
)
8981 return div64_u64(runtime
<< 20, period
);
8984 /* Must be called with tasklist_lock held */
8985 static inline int tg_has_rt_tasks(struct task_group
*tg
)
8987 struct task_struct
*g
, *p
;
8989 do_each_thread(g
, p
) {
8990 if (rt_task(p
) && rt_rq_of_se(&p
->rt
)->tg
== tg
)
8992 } while_each_thread(g
, p
);
8997 struct rt_schedulable_data
{
8998 struct task_group
*tg
;
9003 static int tg_schedulable(struct task_group
*tg
, void *data
)
9005 struct rt_schedulable_data
*d
= data
;
9006 struct task_group
*child
;
9007 unsigned long total
, sum
= 0;
9008 u64 period
, runtime
;
9010 period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
9011 runtime
= tg
->rt_bandwidth
.rt_runtime
;
9014 period
= d
->rt_period
;
9015 runtime
= d
->rt_runtime
;
9019 * Cannot have more runtime than the period.
9021 if (runtime
> period
&& runtime
!= RUNTIME_INF
)
9025 * Ensure we don't starve existing RT tasks.
9027 if (rt_bandwidth_enabled() && !runtime
&& tg_has_rt_tasks(tg
))
9030 total
= to_ratio(period
, runtime
);
9033 * Nobody can have more than the global setting allows.
9035 if (total
> to_ratio(global_rt_period(), global_rt_runtime()))
9039 * The sum of our children's runtime should not exceed our own.
9041 list_for_each_entry_rcu(child
, &tg
->children
, siblings
) {
9042 period
= ktime_to_ns(child
->rt_bandwidth
.rt_period
);
9043 runtime
= child
->rt_bandwidth
.rt_runtime
;
9045 if (child
== d
->tg
) {
9046 period
= d
->rt_period
;
9047 runtime
= d
->rt_runtime
;
9050 sum
+= to_ratio(period
, runtime
);
9059 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
9061 struct rt_schedulable_data data
= {
9063 .rt_period
= period
,
9064 .rt_runtime
= runtime
,
9067 return walk_tg_tree(tg_schedulable
, tg_nop
, &data
);
9070 static int tg_set_bandwidth(struct task_group
*tg
,
9071 u64 rt_period
, u64 rt_runtime
)
9075 mutex_lock(&rt_constraints_mutex
);
9076 read_lock(&tasklist_lock
);
9077 err
= __rt_schedulable(tg
, rt_period
, rt_runtime
);
9081 spin_lock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
9082 tg
->rt_bandwidth
.rt_period
= ns_to_ktime(rt_period
);
9083 tg
->rt_bandwidth
.rt_runtime
= rt_runtime
;
9085 for_each_possible_cpu(i
) {
9086 struct rt_rq
*rt_rq
= tg
->rt_rq
[i
];
9088 spin_lock(&rt_rq
->rt_runtime_lock
);
9089 rt_rq
->rt_runtime
= rt_runtime
;
9090 spin_unlock(&rt_rq
->rt_runtime_lock
);
9092 spin_unlock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
9094 read_unlock(&tasklist_lock
);
9095 mutex_unlock(&rt_constraints_mutex
);
9100 int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
9102 u64 rt_runtime
, rt_period
;
9104 rt_period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
9105 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
9106 if (rt_runtime_us
< 0)
9107 rt_runtime
= RUNTIME_INF
;
9109 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
9112 long sched_group_rt_runtime(struct task_group
*tg
)
9116 if (tg
->rt_bandwidth
.rt_runtime
== RUNTIME_INF
)
9119 rt_runtime_us
= tg
->rt_bandwidth
.rt_runtime
;
9120 do_div(rt_runtime_us
, NSEC_PER_USEC
);
9121 return rt_runtime_us
;
9124 int sched_group_set_rt_period(struct task_group
*tg
, long rt_period_us
)
9126 u64 rt_runtime
, rt_period
;
9128 rt_period
= (u64
)rt_period_us
* NSEC_PER_USEC
;
9129 rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
9134 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
9137 long sched_group_rt_period(struct task_group
*tg
)
9141 rt_period_us
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
9142 do_div(rt_period_us
, NSEC_PER_USEC
);
9143 return rt_period_us
;
9146 static int sched_rt_global_constraints(void)
9148 u64 runtime
, period
;
9151 if (sysctl_sched_rt_period
<= 0)
9154 runtime
= global_rt_runtime();
9155 period
= global_rt_period();
9158 * Sanity check on the sysctl variables.
9160 if (runtime
> period
&& runtime
!= RUNTIME_INF
)
9163 mutex_lock(&rt_constraints_mutex
);
9164 read_lock(&tasklist_lock
);
9165 ret
= __rt_schedulable(NULL
, 0, 0);
9166 read_unlock(&tasklist_lock
);
9167 mutex_unlock(&rt_constraints_mutex
);
9171 #else /* !CONFIG_RT_GROUP_SCHED */
9172 static int sched_rt_global_constraints(void)
9174 unsigned long flags
;
9177 if (sysctl_sched_rt_period
<= 0)
9180 spin_lock_irqsave(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
9181 for_each_possible_cpu(i
) {
9182 struct rt_rq
*rt_rq
= &cpu_rq(i
)->rt
;
9184 spin_lock(&rt_rq
->rt_runtime_lock
);
9185 rt_rq
->rt_runtime
= global_rt_runtime();
9186 spin_unlock(&rt_rq
->rt_runtime_lock
);
9188 spin_unlock_irqrestore(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
9192 #endif /* CONFIG_RT_GROUP_SCHED */
9194 int sched_rt_handler(struct ctl_table
*table
, int write
,
9195 struct file
*filp
, void __user
*buffer
, size_t *lenp
,
9199 int old_period
, old_runtime
;
9200 static DEFINE_MUTEX(mutex
);
9203 old_period
= sysctl_sched_rt_period
;
9204 old_runtime
= sysctl_sched_rt_runtime
;
9206 ret
= proc_dointvec(table
, write
, filp
, buffer
, lenp
, ppos
);
9208 if (!ret
&& write
) {
9209 ret
= sched_rt_global_constraints();
9211 sysctl_sched_rt_period
= old_period
;
9212 sysctl_sched_rt_runtime
= old_runtime
;
9214 def_rt_bandwidth
.rt_runtime
= global_rt_runtime();
9215 def_rt_bandwidth
.rt_period
=
9216 ns_to_ktime(global_rt_period());
9219 mutex_unlock(&mutex
);
9224 #ifdef CONFIG_CGROUP_SCHED
9226 /* return corresponding task_group object of a cgroup */
9227 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
9229 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
9230 struct task_group
, css
);
9233 static struct cgroup_subsys_state
*
9234 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9236 struct task_group
*tg
, *parent
;
9238 if (!cgrp
->parent
) {
9239 /* This is early initialization for the top cgroup */
9240 return &init_task_group
.css
;
9243 parent
= cgroup_tg(cgrp
->parent
);
9244 tg
= sched_create_group(parent
);
9246 return ERR_PTR(-ENOMEM
);
9252 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9254 struct task_group
*tg
= cgroup_tg(cgrp
);
9256 sched_destroy_group(tg
);
9260 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
9261 struct task_struct
*tsk
)
9263 #ifdef CONFIG_RT_GROUP_SCHED
9264 /* Don't accept realtime tasks when there is no way for them to run */
9265 if (rt_task(tsk
) && cgroup_tg(cgrp
)->rt_bandwidth
.rt_runtime
== 0)
9268 /* We don't support RT-tasks being in separate groups */
9269 if (tsk
->sched_class
!= &fair_sched_class
)
9277 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
9278 struct cgroup
*old_cont
, struct task_struct
*tsk
)
9280 sched_move_task(tsk
);
9283 #ifdef CONFIG_FAIR_GROUP_SCHED
9284 static int cpu_shares_write_u64(struct cgroup
*cgrp
, struct cftype
*cftype
,
9287 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
9290 static u64
cpu_shares_read_u64(struct cgroup
*cgrp
, struct cftype
*cft
)
9292 struct task_group
*tg
= cgroup_tg(cgrp
);
9294 return (u64
) tg
->shares
;
9296 #endif /* CONFIG_FAIR_GROUP_SCHED */
9298 #ifdef CONFIG_RT_GROUP_SCHED
9299 static int cpu_rt_runtime_write(struct cgroup
*cgrp
, struct cftype
*cft
,
9302 return sched_group_set_rt_runtime(cgroup_tg(cgrp
), val
);
9305 static s64
cpu_rt_runtime_read(struct cgroup
*cgrp
, struct cftype
*cft
)
9307 return sched_group_rt_runtime(cgroup_tg(cgrp
));
9310 static int cpu_rt_period_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
9313 return sched_group_set_rt_period(cgroup_tg(cgrp
), rt_period_us
);
9316 static u64
cpu_rt_period_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
9318 return sched_group_rt_period(cgroup_tg(cgrp
));
9320 #endif /* CONFIG_RT_GROUP_SCHED */
9322 static struct cftype cpu_files
[] = {
9323 #ifdef CONFIG_FAIR_GROUP_SCHED
9326 .read_u64
= cpu_shares_read_u64
,
9327 .write_u64
= cpu_shares_write_u64
,
9330 #ifdef CONFIG_RT_GROUP_SCHED
9332 .name
= "rt_runtime_us",
9333 .read_s64
= cpu_rt_runtime_read
,
9334 .write_s64
= cpu_rt_runtime_write
,
9337 .name
= "rt_period_us",
9338 .read_u64
= cpu_rt_period_read_uint
,
9339 .write_u64
= cpu_rt_period_write_uint
,
9344 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
9346 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
9349 struct cgroup_subsys cpu_cgroup_subsys
= {
9351 .create
= cpu_cgroup_create
,
9352 .destroy
= cpu_cgroup_destroy
,
9353 .can_attach
= cpu_cgroup_can_attach
,
9354 .attach
= cpu_cgroup_attach
,
9355 .populate
= cpu_cgroup_populate
,
9356 .subsys_id
= cpu_cgroup_subsys_id
,
9360 #endif /* CONFIG_CGROUP_SCHED */
9362 #ifdef CONFIG_CGROUP_CPUACCT
9365 * CPU accounting code for task groups.
9367 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9368 * (balbir@in.ibm.com).
9371 /* track cpu usage of a group of tasks and its child groups */
9373 struct cgroup_subsys_state css
;
9374 /* cpuusage holds pointer to a u64-type object on every cpu */
9376 struct cpuacct
*parent
;
9379 struct cgroup_subsys cpuacct_subsys
;
9381 /* return cpu accounting group corresponding to this container */
9382 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cgrp
)
9384 return container_of(cgroup_subsys_state(cgrp
, cpuacct_subsys_id
),
9385 struct cpuacct
, css
);
9388 /* return cpu accounting group to which this task belongs */
9389 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
9391 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
9392 struct cpuacct
, css
);
9395 /* create a new cpu accounting group */
9396 static struct cgroup_subsys_state
*cpuacct_create(
9397 struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9399 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
9402 return ERR_PTR(-ENOMEM
);
9404 ca
->cpuusage
= alloc_percpu(u64
);
9405 if (!ca
->cpuusage
) {
9407 return ERR_PTR(-ENOMEM
);
9411 ca
->parent
= cgroup_ca(cgrp
->parent
);
9416 /* destroy an existing cpu accounting group */
9418 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9420 struct cpuacct
*ca
= cgroup_ca(cgrp
);
9422 free_percpu(ca
->cpuusage
);
9426 /* return total cpu usage (in nanoseconds) of a group */
9427 static u64
cpuusage_read(struct cgroup
*cgrp
, struct cftype
*cft
)
9429 struct cpuacct
*ca
= cgroup_ca(cgrp
);
9430 u64 totalcpuusage
= 0;
9433 for_each_possible_cpu(i
) {
9434 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
9437 * Take rq->lock to make 64-bit addition safe on 32-bit
9440 spin_lock_irq(&cpu_rq(i
)->lock
);
9441 totalcpuusage
+= *cpuusage
;
9442 spin_unlock_irq(&cpu_rq(i
)->lock
);
9445 return totalcpuusage
;
9448 static int cpuusage_write(struct cgroup
*cgrp
, struct cftype
*cftype
,
9451 struct cpuacct
*ca
= cgroup_ca(cgrp
);
9460 for_each_possible_cpu(i
) {
9461 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
9463 spin_lock_irq(&cpu_rq(i
)->lock
);
9465 spin_unlock_irq(&cpu_rq(i
)->lock
);
9471 static struct cftype files
[] = {
9474 .read_u64
= cpuusage_read
,
9475 .write_u64
= cpuusage_write
,
9479 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9481 return cgroup_add_files(cgrp
, ss
, files
, ARRAY_SIZE(files
));
9485 * charge this task's execution time to its accounting group.
9487 * called with rq->lock held.
9489 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
9494 if (!cpuacct_subsys
.active
)
9497 cpu
= task_cpu(tsk
);
9500 for (; ca
; ca
= ca
->parent
) {
9501 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, cpu
);
9502 *cpuusage
+= cputime
;
9506 struct cgroup_subsys cpuacct_subsys
= {
9508 .create
= cpuacct_create
,
9509 .destroy
= cpuacct_destroy
,
9510 .populate
= cpuacct_populate
,
9511 .subsys_id
= cpuacct_subsys_id
,
9513 #endif /* CONFIG_CGROUP_CPUACCT */