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/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/bootmem.h>
73 #include <asm/irq_regs.h>
76 * Scheduler clock - returns current time in nanosec units.
77 * This is default implementation.
78 * Architectures and sub-architectures can override this.
80 unsigned long long __attribute__((weak
)) sched_clock(void)
82 return (unsigned long long)jiffies
* (NSEC_PER_SEC
/ HZ
);
86 * Convert user-nice values [ -20 ... 0 ... 19 ]
87 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
90 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
91 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
92 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
95 * 'User priority' is the nice value converted to something we
96 * can work with better when scaling various scheduler parameters,
97 * it's a [ 0 ... 39 ] range.
99 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
100 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
101 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
104 * Helpers for converting nanosecond timing to jiffy resolution
106 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
108 #define NICE_0_LOAD SCHED_LOAD_SCALE
109 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
112 * These are the 'tuning knobs' of the scheduler:
114 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
115 * Timeslices get refilled after they expire.
117 #define DEF_TIMESLICE (100 * HZ / 1000)
120 * single value that denotes runtime == period, ie unlimited time.
122 #define RUNTIME_INF ((u64)~0ULL)
126 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
127 * Since cpu_power is a 'constant', we can use a reciprocal divide.
129 static inline u32
sg_div_cpu_power(const struct sched_group
*sg
, u32 load
)
131 return reciprocal_divide(load
, sg
->reciprocal_cpu_power
);
135 * Each time a sched group cpu_power is changed,
136 * we must compute its reciprocal value
138 static inline void sg_inc_cpu_power(struct sched_group
*sg
, u32 val
)
140 sg
->__cpu_power
+= val
;
141 sg
->reciprocal_cpu_power
= reciprocal_value(sg
->__cpu_power
);
145 static inline int rt_policy(int policy
)
147 if (unlikely(policy
== SCHED_FIFO
) || unlikely(policy
== SCHED_RR
))
152 static inline int task_has_rt_policy(struct task_struct
*p
)
154 return rt_policy(p
->policy
);
158 * This is the priority-queue data structure of the RT scheduling class:
160 struct rt_prio_array
{
161 DECLARE_BITMAP(bitmap
, MAX_RT_PRIO
+1); /* include 1 bit for delimiter */
162 struct list_head queue
[MAX_RT_PRIO
];
165 struct rt_bandwidth
{
166 /* nests inside the rq lock: */
167 spinlock_t rt_runtime_lock
;
170 struct hrtimer rt_period_timer
;
173 static struct rt_bandwidth def_rt_bandwidth
;
175 static int do_sched_rt_period_timer(struct rt_bandwidth
*rt_b
, int overrun
);
177 static enum hrtimer_restart
sched_rt_period_timer(struct hrtimer
*timer
)
179 struct rt_bandwidth
*rt_b
=
180 container_of(timer
, struct rt_bandwidth
, rt_period_timer
);
186 now
= hrtimer_cb_get_time(timer
);
187 overrun
= hrtimer_forward(timer
, now
, rt_b
->rt_period
);
192 idle
= do_sched_rt_period_timer(rt_b
, overrun
);
195 return idle
? HRTIMER_NORESTART
: HRTIMER_RESTART
;
199 void init_rt_bandwidth(struct rt_bandwidth
*rt_b
, u64 period
, u64 runtime
)
201 rt_b
->rt_period
= ns_to_ktime(period
);
202 rt_b
->rt_runtime
= runtime
;
204 spin_lock_init(&rt_b
->rt_runtime_lock
);
206 hrtimer_init(&rt_b
->rt_period_timer
,
207 CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
208 rt_b
->rt_period_timer
.function
= sched_rt_period_timer
;
209 rt_b
->rt_period_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
212 static void start_rt_bandwidth(struct rt_bandwidth
*rt_b
)
216 if (rt_b
->rt_runtime
== RUNTIME_INF
)
219 if (hrtimer_active(&rt_b
->rt_period_timer
))
222 spin_lock(&rt_b
->rt_runtime_lock
);
224 if (hrtimer_active(&rt_b
->rt_period_timer
))
227 now
= hrtimer_cb_get_time(&rt_b
->rt_period_timer
);
228 hrtimer_forward(&rt_b
->rt_period_timer
, now
, rt_b
->rt_period
);
229 hrtimer_start(&rt_b
->rt_period_timer
,
230 rt_b
->rt_period_timer
.expires
,
233 spin_unlock(&rt_b
->rt_runtime_lock
);
236 #ifdef CONFIG_RT_GROUP_SCHED
237 static void destroy_rt_bandwidth(struct rt_bandwidth
*rt_b
)
239 hrtimer_cancel(&rt_b
->rt_period_timer
);
243 #ifdef CONFIG_GROUP_SCHED
245 #include <linux/cgroup.h>
249 static LIST_HEAD(task_groups
);
251 /* task group related information */
253 #ifdef CONFIG_CGROUP_SCHED
254 struct cgroup_subsys_state css
;
257 #ifdef CONFIG_FAIR_GROUP_SCHED
258 /* schedulable entities of this group on each cpu */
259 struct sched_entity
**se
;
260 /* runqueue "owned" by this group on each cpu */
261 struct cfs_rq
**cfs_rq
;
262 unsigned long shares
;
265 #ifdef CONFIG_RT_GROUP_SCHED
266 struct sched_rt_entity
**rt_se
;
267 struct rt_rq
**rt_rq
;
269 struct rt_bandwidth rt_bandwidth
;
273 struct list_head list
;
275 struct task_group
*parent
;
276 struct list_head siblings
;
277 struct list_head children
;
280 #ifdef CONFIG_USER_SCHED
284 * Every UID task group (including init_task_group aka UID-0) will
285 * be a child to this group.
287 struct task_group root_task_group
;
289 #ifdef CONFIG_FAIR_GROUP_SCHED
290 /* Default task group's sched entity on each cpu */
291 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
292 /* Default task group's cfs_rq on each cpu */
293 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
296 #ifdef CONFIG_RT_GROUP_SCHED
297 static DEFINE_PER_CPU(struct sched_rt_entity
, init_sched_rt_entity
);
298 static DEFINE_PER_CPU(struct rt_rq
, init_rt_rq
) ____cacheline_aligned_in_smp
;
301 #define root_task_group init_task_group
304 /* task_group_lock serializes add/remove of task groups and also changes to
305 * a task group's cpu shares.
307 static DEFINE_SPINLOCK(task_group_lock
);
309 /* doms_cur_mutex serializes access to doms_cur[] array */
310 static DEFINE_MUTEX(doms_cur_mutex
);
312 #ifdef CONFIG_FAIR_GROUP_SCHED
313 #ifdef CONFIG_USER_SCHED
314 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
316 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
321 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
324 /* Default task group.
325 * Every task in system belong to this group at bootup.
327 struct task_group init_task_group
;
329 /* return group to which a task belongs */
330 static inline struct task_group
*task_group(struct task_struct
*p
)
332 struct task_group
*tg
;
334 #ifdef CONFIG_USER_SCHED
336 #elif defined(CONFIG_CGROUP_SCHED)
337 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
338 struct task_group
, css
);
340 tg
= &init_task_group
;
345 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
346 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
)
348 #ifdef CONFIG_FAIR_GROUP_SCHED
349 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
350 p
->se
.parent
= task_group(p
)->se
[cpu
];
353 #ifdef CONFIG_RT_GROUP_SCHED
354 p
->rt
.rt_rq
= task_group(p
)->rt_rq
[cpu
];
355 p
->rt
.parent
= task_group(p
)->rt_se
[cpu
];
359 static inline void lock_doms_cur(void)
361 mutex_lock(&doms_cur_mutex
);
364 static inline void unlock_doms_cur(void)
366 mutex_unlock(&doms_cur_mutex
);
371 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
) { }
372 static inline void lock_doms_cur(void) { }
373 static inline void unlock_doms_cur(void) { }
375 #endif /* CONFIG_GROUP_SCHED */
377 /* CFS-related fields in a runqueue */
379 struct load_weight load
;
380 unsigned long nr_running
;
385 struct rb_root tasks_timeline
;
386 struct rb_node
*rb_leftmost
;
387 struct rb_node
*rb_load_balance_curr
;
388 /* 'curr' points to currently running entity on this cfs_rq.
389 * It is set to NULL otherwise (i.e when none are currently running).
391 struct sched_entity
*curr
, *next
;
393 unsigned long nr_spread_over
;
395 #ifdef CONFIG_FAIR_GROUP_SCHED
396 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
399 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
400 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
401 * (like users, containers etc.)
403 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
404 * list is used during load balance.
406 struct list_head leaf_cfs_rq_list
;
407 struct task_group
*tg
; /* group that "owns" this runqueue */
410 unsigned long task_weight
;
411 unsigned long shares
;
413 * We need space to build a sched_domain wide view of the full task
414 * group tree, in order to avoid depending on dynamic memory allocation
415 * during the load balancing we place this in the per cpu task group
416 * hierarchy. This limits the load balancing to one instance per cpu,
417 * but more should not be needed anyway.
419 struct aggregate_struct
{
421 * load = weight(cpus) * f(tg)
423 * Where f(tg) is the recursive weight fraction assigned to
429 * part of the group weight distributed to this span.
431 unsigned long shares
;
434 * The sum of all runqueue weights within this span.
436 unsigned long rq_weight
;
439 * Weight contributed by tasks; this is the part we can
440 * influence by moving tasks around.
442 unsigned long task_weight
;
448 /* Real-Time classes' related field in a runqueue: */
450 struct rt_prio_array active
;
451 unsigned long rt_nr_running
;
452 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
453 int highest_prio
; /* highest queued rt task prio */
456 unsigned long rt_nr_migratory
;
462 /* Nests inside the rq lock: */
463 spinlock_t rt_runtime_lock
;
465 #ifdef CONFIG_RT_GROUP_SCHED
466 unsigned long rt_nr_boosted
;
469 struct list_head leaf_rt_rq_list
;
470 struct task_group
*tg
;
471 struct sched_rt_entity
*rt_se
;
478 * We add the notion of a root-domain which will be used to define per-domain
479 * variables. Each exclusive cpuset essentially defines an island domain by
480 * fully partitioning the member cpus from any other cpuset. Whenever a new
481 * exclusive cpuset is created, we also create and attach a new root-domain
491 * The "RT overload" flag: it gets set if a CPU has more than
492 * one runnable RT task.
499 * By default the system creates a single root-domain with all cpus as
500 * members (mimicking the global state we have today).
502 static struct root_domain def_root_domain
;
507 * This is the main, per-CPU runqueue data structure.
509 * Locking rule: those places that want to lock multiple runqueues
510 * (such as the load balancing or the thread migration code), lock
511 * acquire operations must be ordered by ascending &runqueue.
518 * nr_running and cpu_load should be in the same cacheline because
519 * remote CPUs use both these fields when doing load calculation.
521 unsigned long nr_running
;
522 #define CPU_LOAD_IDX_MAX 5
523 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
524 unsigned char idle_at_tick
;
526 unsigned long last_tick_seen
;
527 unsigned char in_nohz_recently
;
529 /* capture load from *all* tasks on this cpu: */
530 struct load_weight load
;
531 unsigned long nr_load_updates
;
537 #ifdef CONFIG_FAIR_GROUP_SCHED
538 /* list of leaf cfs_rq on this cpu: */
539 struct list_head leaf_cfs_rq_list
;
541 #ifdef CONFIG_RT_GROUP_SCHED
542 struct list_head leaf_rt_rq_list
;
546 * This is part of a global counter where only the total sum
547 * over all CPUs matters. A task can increase this counter on
548 * one CPU and if it got migrated afterwards it may decrease
549 * it on another CPU. Always updated under the runqueue lock:
551 unsigned long nr_uninterruptible
;
553 struct task_struct
*curr
, *idle
;
554 unsigned long next_balance
;
555 struct mm_struct
*prev_mm
;
557 u64 clock
, prev_clock_raw
;
560 unsigned int clock_warps
, clock_overflows
, clock_underflows
;
562 unsigned int clock_deep_idle_events
;
568 struct root_domain
*rd
;
569 struct sched_domain
*sd
;
571 /* For active balancing */
574 /* cpu of this runqueue: */
577 struct task_struct
*migration_thread
;
578 struct list_head migration_queue
;
581 #ifdef CONFIG_SCHED_HRTICK
582 unsigned long hrtick_flags
;
583 ktime_t hrtick_expire
;
584 struct hrtimer hrtick_timer
;
587 #ifdef CONFIG_SCHEDSTATS
589 struct sched_info rq_sched_info
;
591 /* sys_sched_yield() stats */
592 unsigned int yld_exp_empty
;
593 unsigned int yld_act_empty
;
594 unsigned int yld_both_empty
;
595 unsigned int yld_count
;
597 /* schedule() stats */
598 unsigned int sched_switch
;
599 unsigned int sched_count
;
600 unsigned int sched_goidle
;
602 /* try_to_wake_up() stats */
603 unsigned int ttwu_count
;
604 unsigned int ttwu_local
;
607 unsigned int bkl_count
;
609 struct lock_class_key rq_lock_key
;
612 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
614 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
)
616 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
);
619 static inline int cpu_of(struct rq
*rq
)
629 static inline bool nohz_on(int cpu
)
631 return tick_get_tick_sched(cpu
)->nohz_mode
!= NOHZ_MODE_INACTIVE
;
634 static inline u64
max_skipped_ticks(struct rq
*rq
)
636 return nohz_on(cpu_of(rq
)) ? jiffies
- rq
->last_tick_seen
+ 2 : 1;
639 static inline void update_last_tick_seen(struct rq
*rq
)
641 rq
->last_tick_seen
= jiffies
;
644 static inline u64
max_skipped_ticks(struct rq
*rq
)
649 static inline void update_last_tick_seen(struct rq
*rq
)
655 * Update the per-runqueue clock, as finegrained as the platform can give
656 * us, but without assuming monotonicity, etc.:
658 static void __update_rq_clock(struct rq
*rq
)
660 u64 prev_raw
= rq
->prev_clock_raw
;
661 u64 now
= sched_clock();
662 s64 delta
= now
- prev_raw
;
663 u64 clock
= rq
->clock
;
665 #ifdef CONFIG_SCHED_DEBUG
666 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
669 * Protect against sched_clock() occasionally going backwards:
671 if (unlikely(delta
< 0)) {
676 * Catch too large forward jumps too:
678 u64 max_jump
= max_skipped_ticks(rq
) * TICK_NSEC
;
679 u64 max_time
= rq
->tick_timestamp
+ max_jump
;
681 if (unlikely(clock
+ delta
> max_time
)) {
682 if (clock
< max_time
)
686 rq
->clock_overflows
++;
688 if (unlikely(delta
> rq
->clock_max_delta
))
689 rq
->clock_max_delta
= delta
;
694 rq
->prev_clock_raw
= now
;
698 static void update_rq_clock(struct rq
*rq
)
700 if (likely(smp_processor_id() == cpu_of(rq
)))
701 __update_rq_clock(rq
);
705 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
706 * See detach_destroy_domains: synchronize_sched for details.
708 * The domain tree of any CPU may only be accessed from within
709 * preempt-disabled sections.
711 #define for_each_domain(cpu, __sd) \
712 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
714 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
715 #define this_rq() (&__get_cpu_var(runqueues))
716 #define task_rq(p) cpu_rq(task_cpu(p))
717 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
720 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
722 #ifdef CONFIG_SCHED_DEBUG
723 # define const_debug __read_mostly
725 # define const_debug static const
729 * Debugging: various feature bits
732 SCHED_FEAT_NEW_FAIR_SLEEPERS
= 1,
733 SCHED_FEAT_WAKEUP_PREEMPT
= 2,
734 SCHED_FEAT_START_DEBIT
= 4,
735 SCHED_FEAT_AFFINE_WAKEUPS
= 8,
736 SCHED_FEAT_CACHE_HOT_BUDDY
= 16,
737 SCHED_FEAT_SYNC_WAKEUPS
= 32,
738 SCHED_FEAT_HRTICK
= 64,
739 SCHED_FEAT_DOUBLE_TICK
= 128,
740 SCHED_FEAT_NORMALIZED_SLEEPER
= 256,
743 const_debug
unsigned int sysctl_sched_features
=
744 SCHED_FEAT_NEW_FAIR_SLEEPERS
* 1 |
745 SCHED_FEAT_WAKEUP_PREEMPT
* 1 |
746 SCHED_FEAT_START_DEBIT
* 1 |
747 SCHED_FEAT_AFFINE_WAKEUPS
* 1 |
748 SCHED_FEAT_CACHE_HOT_BUDDY
* 1 |
749 SCHED_FEAT_SYNC_WAKEUPS
* 1 |
750 SCHED_FEAT_HRTICK
* 1 |
751 SCHED_FEAT_DOUBLE_TICK
* 0 |
752 SCHED_FEAT_NORMALIZED_SLEEPER
* 1;
754 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
757 * Number of tasks to iterate in a single balance run.
758 * Limited because this is done with IRQs disabled.
760 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
763 * period over which we measure -rt task cpu usage in us.
766 unsigned int sysctl_sched_rt_period
= 1000000;
768 static __read_mostly
int scheduler_running
;
771 * part of the period that we allow rt tasks to run in us.
774 int sysctl_sched_rt_runtime
= 950000;
776 static inline u64
global_rt_period(void)
778 return (u64
)sysctl_sched_rt_period
* NSEC_PER_USEC
;
781 static inline u64
global_rt_runtime(void)
783 if (sysctl_sched_rt_period
< 0)
786 return (u64
)sysctl_sched_rt_runtime
* NSEC_PER_USEC
;
789 static const unsigned long long time_sync_thresh
= 100000;
791 static DEFINE_PER_CPU(unsigned long long, time_offset
);
792 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time
);
795 * Global lock which we take every now and then to synchronize
796 * the CPUs time. This method is not warp-safe, but it's good
797 * enough to synchronize slowly diverging time sources and thus
798 * it's good enough for tracing:
800 static DEFINE_SPINLOCK(time_sync_lock
);
801 static unsigned long long prev_global_time
;
803 static unsigned long long __sync_cpu_clock(cycles_t time
, int cpu
)
807 spin_lock_irqsave(&time_sync_lock
, flags
);
809 if (time
< prev_global_time
) {
810 per_cpu(time_offset
, cpu
) += prev_global_time
- time
;
811 time
= prev_global_time
;
813 prev_global_time
= time
;
816 spin_unlock_irqrestore(&time_sync_lock
, flags
);
821 static unsigned long long __cpu_clock(int cpu
)
823 unsigned long long now
;
828 * Only call sched_clock() if the scheduler has already been
829 * initialized (some code might call cpu_clock() very early):
831 if (unlikely(!scheduler_running
))
834 local_irq_save(flags
);
838 local_irq_restore(flags
);
844 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
845 * clock constructed from sched_clock():
847 unsigned long long cpu_clock(int cpu
)
849 unsigned long long prev_cpu_time
, time
, delta_time
;
851 prev_cpu_time
= per_cpu(prev_cpu_time
, cpu
);
852 time
= __cpu_clock(cpu
) + per_cpu(time_offset
, cpu
);
853 delta_time
= time
-prev_cpu_time
;
855 if (unlikely(delta_time
> time_sync_thresh
))
856 time
= __sync_cpu_clock(time
, cpu
);
860 EXPORT_SYMBOL_GPL(cpu_clock
);
862 #ifndef prepare_arch_switch
863 # define prepare_arch_switch(next) do { } while (0)
865 #ifndef finish_arch_switch
866 # define finish_arch_switch(prev) do { } while (0)
869 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
871 return rq
->curr
== p
;
874 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
875 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
877 return task_current(rq
, p
);
880 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
884 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
886 #ifdef CONFIG_DEBUG_SPINLOCK
887 /* this is a valid case when another task releases the spinlock */
888 rq
->lock
.owner
= current
;
891 * If we are tracking spinlock dependencies then we have to
892 * fix up the runqueue lock - which gets 'carried over' from
895 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
897 spin_unlock_irq(&rq
->lock
);
900 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
901 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
906 return task_current(rq
, p
);
910 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
914 * We can optimise this out completely for !SMP, because the
915 * SMP rebalancing from interrupt is the only thing that cares
920 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
921 spin_unlock_irq(&rq
->lock
);
923 spin_unlock(&rq
->lock
);
927 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
931 * After ->oncpu is cleared, the task can be moved to a different CPU.
932 * We must ensure this doesn't happen until the switch is completely
938 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
942 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
945 * __task_rq_lock - lock the runqueue a given task resides on.
946 * Must be called interrupts disabled.
948 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
952 struct rq
*rq
= task_rq(p
);
953 spin_lock(&rq
->lock
);
954 if (likely(rq
== task_rq(p
)))
956 spin_unlock(&rq
->lock
);
961 * task_rq_lock - lock the runqueue a given task resides on and disable
962 * interrupts. Note the ordering: we can safely lookup the task_rq without
963 * explicitly disabling preemption.
965 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
971 local_irq_save(*flags
);
973 spin_lock(&rq
->lock
);
974 if (likely(rq
== task_rq(p
)))
976 spin_unlock_irqrestore(&rq
->lock
, *flags
);
980 static void __task_rq_unlock(struct rq
*rq
)
983 spin_unlock(&rq
->lock
);
986 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
989 spin_unlock_irqrestore(&rq
->lock
, *flags
);
993 * this_rq_lock - lock this runqueue and disable interrupts.
995 static struct rq
*this_rq_lock(void)
1000 local_irq_disable();
1002 spin_lock(&rq
->lock
);
1008 * We are going deep-idle (irqs are disabled):
1010 void sched_clock_idle_sleep_event(void)
1012 struct rq
*rq
= cpu_rq(smp_processor_id());
1014 spin_lock(&rq
->lock
);
1015 __update_rq_clock(rq
);
1016 spin_unlock(&rq
->lock
);
1017 rq
->clock_deep_idle_events
++;
1019 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event
);
1022 * We just idled delta nanoseconds (called with irqs disabled):
1024 void sched_clock_idle_wakeup_event(u64 delta_ns
)
1026 struct rq
*rq
= cpu_rq(smp_processor_id());
1027 u64 now
= sched_clock();
1029 rq
->idle_clock
+= delta_ns
;
1031 * Override the previous timestamp and ignore all
1032 * sched_clock() deltas that occured while we idled,
1033 * and use the PM-provided delta_ns to advance the
1036 spin_lock(&rq
->lock
);
1037 rq
->prev_clock_raw
= now
;
1038 rq
->clock
+= delta_ns
;
1039 spin_unlock(&rq
->lock
);
1040 touch_softlockup_watchdog();
1042 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event
);
1044 static void __resched_task(struct task_struct
*p
, int tif_bit
);
1046 static inline void resched_task(struct task_struct
*p
)
1048 __resched_task(p
, TIF_NEED_RESCHED
);
1051 #ifdef CONFIG_SCHED_HRTICK
1053 * Use HR-timers to deliver accurate preemption points.
1055 * Its all a bit involved since we cannot program an hrt while holding the
1056 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1059 * When we get rescheduled we reprogram the hrtick_timer outside of the
1062 static inline void resched_hrt(struct task_struct
*p
)
1064 __resched_task(p
, TIF_HRTICK_RESCHED
);
1067 static inline void resched_rq(struct rq
*rq
)
1069 unsigned long flags
;
1071 spin_lock_irqsave(&rq
->lock
, flags
);
1072 resched_task(rq
->curr
);
1073 spin_unlock_irqrestore(&rq
->lock
, flags
);
1077 HRTICK_SET
, /* re-programm hrtick_timer */
1078 HRTICK_RESET
, /* not a new slice */
1083 * - enabled by features
1084 * - hrtimer is actually high res
1086 static inline int hrtick_enabled(struct rq
*rq
)
1088 if (!sched_feat(HRTICK
))
1090 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
1094 * Called to set the hrtick timer state.
1096 * called with rq->lock held and irqs disabled
1098 static void hrtick_start(struct rq
*rq
, u64 delay
, int reset
)
1100 assert_spin_locked(&rq
->lock
);
1103 * preempt at: now + delay
1106 ktime_add_ns(rq
->hrtick_timer
.base
->get_time(), delay
);
1108 * indicate we need to program the timer
1110 __set_bit(HRTICK_SET
, &rq
->hrtick_flags
);
1112 __set_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
1115 * New slices are called from the schedule path and don't need a
1116 * forced reschedule.
1119 resched_hrt(rq
->curr
);
1122 static void hrtick_clear(struct rq
*rq
)
1124 if (hrtimer_active(&rq
->hrtick_timer
))
1125 hrtimer_cancel(&rq
->hrtick_timer
);
1129 * Update the timer from the possible pending state.
1131 static void hrtick_set(struct rq
*rq
)
1135 unsigned long flags
;
1137 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1139 spin_lock_irqsave(&rq
->lock
, flags
);
1140 set
= __test_and_clear_bit(HRTICK_SET
, &rq
->hrtick_flags
);
1141 reset
= __test_and_clear_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
1142 time
= rq
->hrtick_expire
;
1143 clear_thread_flag(TIF_HRTICK_RESCHED
);
1144 spin_unlock_irqrestore(&rq
->lock
, flags
);
1147 hrtimer_start(&rq
->hrtick_timer
, time
, HRTIMER_MODE_ABS
);
1148 if (reset
&& !hrtimer_active(&rq
->hrtick_timer
))
1155 * High-resolution timer tick.
1156 * Runs from hardirq context with interrupts disabled.
1158 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
1160 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
1162 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1164 spin_lock(&rq
->lock
);
1165 __update_rq_clock(rq
);
1166 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
1167 spin_unlock(&rq
->lock
);
1169 return HRTIMER_NORESTART
;
1172 static inline void init_rq_hrtick(struct rq
*rq
)
1174 rq
->hrtick_flags
= 0;
1175 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1176 rq
->hrtick_timer
.function
= hrtick
;
1177 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
1180 void hrtick_resched(void)
1183 unsigned long flags
;
1185 if (!test_thread_flag(TIF_HRTICK_RESCHED
))
1188 local_irq_save(flags
);
1189 rq
= cpu_rq(smp_processor_id());
1191 local_irq_restore(flags
);
1194 static inline void hrtick_clear(struct rq
*rq
)
1198 static inline void hrtick_set(struct rq
*rq
)
1202 static inline void init_rq_hrtick(struct rq
*rq
)
1206 void hrtick_resched(void)
1212 * resched_task - mark a task 'to be rescheduled now'.
1214 * On UP this means the setting of the need_resched flag, on SMP it
1215 * might also involve a cross-CPU call to trigger the scheduler on
1220 #ifndef tsk_is_polling
1221 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1224 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1228 assert_spin_locked(&task_rq(p
)->lock
);
1230 if (unlikely(test_tsk_thread_flag(p
, tif_bit
)))
1233 set_tsk_thread_flag(p
, tif_bit
);
1236 if (cpu
== smp_processor_id())
1239 /* NEED_RESCHED must be visible before we test polling */
1241 if (!tsk_is_polling(p
))
1242 smp_send_reschedule(cpu
);
1245 static void resched_cpu(int cpu
)
1247 struct rq
*rq
= cpu_rq(cpu
);
1248 unsigned long flags
;
1250 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1252 resched_task(cpu_curr(cpu
));
1253 spin_unlock_irqrestore(&rq
->lock
, flags
);
1258 * When add_timer_on() enqueues a timer into the timer wheel of an
1259 * idle CPU then this timer might expire before the next timer event
1260 * which is scheduled to wake up that CPU. In case of a completely
1261 * idle system the next event might even be infinite time into the
1262 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1263 * leaves the inner idle loop so the newly added timer is taken into
1264 * account when the CPU goes back to idle and evaluates the timer
1265 * wheel for the next timer event.
1267 void wake_up_idle_cpu(int cpu
)
1269 struct rq
*rq
= cpu_rq(cpu
);
1271 if (cpu
== smp_processor_id())
1275 * This is safe, as this function is called with the timer
1276 * wheel base lock of (cpu) held. When the CPU is on the way
1277 * to idle and has not yet set rq->curr to idle then it will
1278 * be serialized on the timer wheel base lock and take the new
1279 * timer into account automatically.
1281 if (rq
->curr
!= rq
->idle
)
1285 * We can set TIF_RESCHED on the idle task of the other CPU
1286 * lockless. The worst case is that the other CPU runs the
1287 * idle task through an additional NOOP schedule()
1289 set_tsk_thread_flag(rq
->idle
, TIF_NEED_RESCHED
);
1291 /* NEED_RESCHED must be visible before we test polling */
1293 if (!tsk_is_polling(rq
->idle
))
1294 smp_send_reschedule(cpu
);
1299 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1301 assert_spin_locked(&task_rq(p
)->lock
);
1302 set_tsk_thread_flag(p
, tif_bit
);
1306 #if BITS_PER_LONG == 32
1307 # define WMULT_CONST (~0UL)
1309 # define WMULT_CONST (1UL << 32)
1312 #define WMULT_SHIFT 32
1315 * Shift right and round:
1317 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1319 static unsigned long
1320 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1321 struct load_weight
*lw
)
1325 if (unlikely(!lw
->inv_weight
))
1326 lw
->inv_weight
= (WMULT_CONST
-lw
->weight
/2) / (lw
->weight
+1);
1328 tmp
= (u64
)delta_exec
* weight
;
1330 * Check whether we'd overflow the 64-bit multiplication:
1332 if (unlikely(tmp
> WMULT_CONST
))
1333 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1336 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1338 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1341 static inline unsigned long
1342 calc_delta_fair(unsigned long delta_exec
, struct load_weight
*lw
)
1344 return calc_delta_mine(delta_exec
, NICE_0_LOAD
, lw
);
1347 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1353 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1360 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1361 * of tasks with abnormal "nice" values across CPUs the contribution that
1362 * each task makes to its run queue's load is weighted according to its
1363 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1364 * scaled version of the new time slice allocation that they receive on time
1368 #define WEIGHT_IDLEPRIO 2
1369 #define WMULT_IDLEPRIO (1 << 31)
1372 * Nice levels are multiplicative, with a gentle 10% change for every
1373 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1374 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1375 * that remained on nice 0.
1377 * The "10% effect" is relative and cumulative: from _any_ nice level,
1378 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1379 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1380 * If a task goes up by ~10% and another task goes down by ~10% then
1381 * the relative distance between them is ~25%.)
1383 static const int prio_to_weight
[40] = {
1384 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1385 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1386 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1387 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1388 /* 0 */ 1024, 820, 655, 526, 423,
1389 /* 5 */ 335, 272, 215, 172, 137,
1390 /* 10 */ 110, 87, 70, 56, 45,
1391 /* 15 */ 36, 29, 23, 18, 15,
1395 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1397 * In cases where the weight does not change often, we can use the
1398 * precalculated inverse to speed up arithmetics by turning divisions
1399 * into multiplications:
1401 static const u32 prio_to_wmult
[40] = {
1402 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1403 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1404 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1405 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1406 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1407 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1408 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1409 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1412 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1415 * runqueue iterator, to support SMP load-balancing between different
1416 * scheduling classes, without having to expose their internal data
1417 * structures to the load-balancing proper:
1419 struct rq_iterator
{
1421 struct task_struct
*(*start
)(void *);
1422 struct task_struct
*(*next
)(void *);
1426 static unsigned long
1427 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1428 unsigned long max_load_move
, struct sched_domain
*sd
,
1429 enum cpu_idle_type idle
, int *all_pinned
,
1430 int *this_best_prio
, struct rq_iterator
*iterator
);
1433 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1434 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1435 struct rq_iterator
*iterator
);
1438 #ifdef CONFIG_CGROUP_CPUACCT
1439 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1441 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1444 static inline void inc_cpu_load(struct rq
*rq
, unsigned long load
)
1446 update_load_add(&rq
->load
, load
);
1449 static inline void dec_cpu_load(struct rq
*rq
, unsigned long load
)
1451 update_load_sub(&rq
->load
, load
);
1455 static unsigned long source_load(int cpu
, int type
);
1456 static unsigned long target_load(int cpu
, int type
);
1457 static unsigned long cpu_avg_load_per_task(int cpu
);
1458 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1460 #ifdef CONFIG_FAIR_GROUP_SCHED
1463 * Group load balancing.
1465 * We calculate a few balance domain wide aggregate numbers; load and weight.
1466 * Given the pictures below, and assuming each item has equal weight:
1477 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1478 * which equals 1/9-th of the total load.
1481 * The weight of this group on the selected cpus.
1484 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1488 * Part of the rq_weight contributed by tasks; all groups except B would
1492 static inline struct aggregate_struct
*
1493 aggregate(struct task_group
*tg
, struct sched_domain
*sd
)
1495 return &tg
->cfs_rq
[sd
->first_cpu
]->aggregate
;
1498 typedef void (*aggregate_func
)(struct task_group
*, struct sched_domain
*);
1501 * Iterate the full tree, calling @down when first entering a node and @up when
1502 * leaving it for the final time.
1505 void aggregate_walk_tree(aggregate_func down
, aggregate_func up
,
1506 struct sched_domain
*sd
)
1508 struct task_group
*parent
, *child
;
1511 parent
= &root_task_group
;
1513 (*down
)(parent
, sd
);
1514 list_for_each_entry_rcu(child
, &parent
->children
, siblings
) {
1524 parent
= parent
->parent
;
1531 * Calculate the aggregate runqueue weight.
1534 void aggregate_group_weight(struct task_group
*tg
, struct sched_domain
*sd
)
1536 unsigned long rq_weight
= 0;
1537 unsigned long task_weight
= 0;
1540 for_each_cpu_mask(i
, sd
->span
) {
1541 rq_weight
+= tg
->cfs_rq
[i
]->load
.weight
;
1542 task_weight
+= tg
->cfs_rq
[i
]->task_weight
;
1545 aggregate(tg
, sd
)->rq_weight
= rq_weight
;
1546 aggregate(tg
, sd
)->task_weight
= task_weight
;
1550 * Redistribute tg->shares amongst all tg->cfs_rq[]s.
1552 static void __aggregate_redistribute_shares(struct task_group
*tg
)
1554 int i
, max_cpu
= smp_processor_id();
1555 unsigned long rq_weight
= 0;
1556 unsigned long shares
, max_shares
= 0, shares_rem
= tg
->shares
;
1558 for_each_possible_cpu(i
)
1559 rq_weight
+= tg
->cfs_rq
[i
]->load
.weight
;
1561 for_each_possible_cpu(i
) {
1563 * divide shares proportional to the rq_weights.
1565 shares
= tg
->shares
* tg
->cfs_rq
[i
]->load
.weight
;
1566 shares
/= rq_weight
+ 1;
1568 tg
->cfs_rq
[i
]->shares
= shares
;
1570 if (shares
> max_shares
) {
1571 max_shares
= shares
;
1574 shares_rem
-= shares
;
1578 * Ensure it all adds up to tg->shares; we can loose a few
1579 * due to rounding down when computing the per-cpu shares.
1582 tg
->cfs_rq
[max_cpu
]->shares
+= shares_rem
;
1586 * Compute the weight of this group on the given cpus.
1589 void aggregate_group_shares(struct task_group
*tg
, struct sched_domain
*sd
)
1591 unsigned long shares
= 0;
1595 for_each_cpu_mask(i
, sd
->span
)
1596 shares
+= tg
->cfs_rq
[i
]->shares
;
1599 * When the span doesn't have any shares assigned, but does have
1600 * tasks to run do a machine wide rebalance (should be rare).
1602 if (unlikely(!shares
&& aggregate(tg
, sd
)->rq_weight
)) {
1603 __aggregate_redistribute_shares(tg
);
1607 aggregate(tg
, sd
)->shares
= shares
;
1611 * Compute the load fraction assigned to this group, relies on the aggregate
1612 * weight and this group's parent's load, i.e. top-down.
1615 void aggregate_group_load(struct task_group
*tg
, struct sched_domain
*sd
)
1623 for_each_cpu_mask(i
, sd
->span
)
1624 load
+= cpu_rq(i
)->load
.weight
;
1627 load
= aggregate(tg
->parent
, sd
)->load
;
1630 * shares is our weight in the parent's rq so
1631 * shares/parent->rq_weight gives our fraction of the load
1633 load
*= aggregate(tg
, sd
)->shares
;
1634 load
/= aggregate(tg
->parent
, sd
)->rq_weight
+ 1;
1637 aggregate(tg
, sd
)->load
= load
;
1640 static void __set_se_shares(struct sched_entity
*se
, unsigned long shares
);
1643 * Calculate and set the cpu's group shares.
1646 __update_group_shares_cpu(struct task_group
*tg
, struct sched_domain
*sd
,
1650 unsigned long shares
;
1651 unsigned long rq_weight
;
1656 rq_weight
= tg
->cfs_rq
[tcpu
]->load
.weight
;
1659 * If there are currently no tasks on the cpu pretend there is one of
1660 * average load so that when a new task gets to run here it will not
1661 * get delayed by group starvation.
1665 rq_weight
= NICE_0_LOAD
;
1669 * \Sum shares * rq_weight
1670 * shares = -----------------------
1674 shares
= aggregate(tg
, sd
)->shares
* rq_weight
;
1675 shares
/= aggregate(tg
, sd
)->rq_weight
+ 1;
1678 * record the actual number of shares, not the boosted amount.
1680 tg
->cfs_rq
[tcpu
]->shares
= boost
? 0 : shares
;
1682 if (shares
< MIN_SHARES
)
1683 shares
= MIN_SHARES
;
1685 __set_se_shares(tg
->se
[tcpu
], shares
);
1689 * Re-adjust the weights on the cpu the task came from and on the cpu the
1693 __move_group_shares(struct task_group
*tg
, struct sched_domain
*sd
,
1696 unsigned long shares
;
1698 shares
= tg
->cfs_rq
[scpu
]->shares
+ tg
->cfs_rq
[dcpu
]->shares
;
1700 __update_group_shares_cpu(tg
, sd
, scpu
);
1701 __update_group_shares_cpu(tg
, sd
, dcpu
);
1704 * ensure we never loose shares due to rounding errors in the
1705 * above redistribution.
1707 shares
-= tg
->cfs_rq
[scpu
]->shares
+ tg
->cfs_rq
[dcpu
]->shares
;
1709 tg
->cfs_rq
[dcpu
]->shares
+= shares
;
1713 * Because changing a group's shares changes the weight of the super-group
1714 * we need to walk up the tree and change all shares until we hit the root.
1717 move_group_shares(struct task_group
*tg
, struct sched_domain
*sd
,
1721 __move_group_shares(tg
, sd
, scpu
, dcpu
);
1727 void aggregate_group_set_shares(struct task_group
*tg
, struct sched_domain
*sd
)
1729 unsigned long shares
= aggregate(tg
, sd
)->shares
;
1732 for_each_cpu_mask(i
, sd
->span
) {
1733 struct rq
*rq
= cpu_rq(i
);
1734 unsigned long flags
;
1736 spin_lock_irqsave(&rq
->lock
, flags
);
1737 __update_group_shares_cpu(tg
, sd
, i
);
1738 spin_unlock_irqrestore(&rq
->lock
, flags
);
1741 aggregate_group_shares(tg
, sd
);
1744 * ensure we never loose shares due to rounding errors in the
1745 * above redistribution.
1747 shares
-= aggregate(tg
, sd
)->shares
;
1749 tg
->cfs_rq
[sd
->first_cpu
]->shares
+= shares
;
1750 aggregate(tg
, sd
)->shares
+= shares
;
1755 * Calculate the accumulative weight and recursive load of each task group
1756 * while walking down the tree.
1759 void aggregate_get_down(struct task_group
*tg
, struct sched_domain
*sd
)
1761 aggregate_group_weight(tg
, sd
);
1762 aggregate_group_shares(tg
, sd
);
1763 aggregate_group_load(tg
, sd
);
1767 * Rebalance the cpu shares while walking back up the tree.
1770 void aggregate_get_up(struct task_group
*tg
, struct sched_domain
*sd
)
1772 aggregate_group_set_shares(tg
, sd
);
1775 static DEFINE_PER_CPU(spinlock_t
, aggregate_lock
);
1777 static void __init
init_aggregate(void)
1781 for_each_possible_cpu(i
)
1782 spin_lock_init(&per_cpu(aggregate_lock
, i
));
1785 static int get_aggregate(struct sched_domain
*sd
)
1787 if (!spin_trylock(&per_cpu(aggregate_lock
, sd
->first_cpu
)))
1790 aggregate_walk_tree(aggregate_get_down
, aggregate_get_up
, sd
);
1794 static void put_aggregate(struct sched_domain
*sd
)
1796 spin_unlock(&per_cpu(aggregate_lock
, sd
->first_cpu
));
1799 static void cfs_rq_set_shares(struct cfs_rq
*cfs_rq
, unsigned long shares
)
1801 cfs_rq
->shares
= shares
;
1806 static inline void init_aggregate(void)
1810 static inline int get_aggregate(struct sched_domain
*sd
)
1815 static inline void put_aggregate(struct sched_domain
*sd
)
1820 #else /* CONFIG_SMP */
1822 #ifdef CONFIG_FAIR_GROUP_SCHED
1823 static void cfs_rq_set_shares(struct cfs_rq
*cfs_rq
, unsigned long shares
)
1828 #endif /* CONFIG_SMP */
1830 #include "sched_stats.h"
1831 #include "sched_idletask.c"
1832 #include "sched_fair.c"
1833 #include "sched_rt.c"
1834 #ifdef CONFIG_SCHED_DEBUG
1835 # include "sched_debug.c"
1838 #define sched_class_highest (&rt_sched_class)
1840 static void inc_nr_running(struct rq
*rq
)
1845 static void dec_nr_running(struct rq
*rq
)
1850 static void set_load_weight(struct task_struct
*p
)
1852 if (task_has_rt_policy(p
)) {
1853 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1854 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1859 * SCHED_IDLE tasks get minimal weight:
1861 if (p
->policy
== SCHED_IDLE
) {
1862 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1863 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1867 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1868 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1871 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1873 sched_info_queued(p
);
1874 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1878 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1880 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1885 * __normal_prio - return the priority that is based on the static prio
1887 static inline int __normal_prio(struct task_struct
*p
)
1889 return p
->static_prio
;
1893 * Calculate the expected normal priority: i.e. priority
1894 * without taking RT-inheritance into account. Might be
1895 * boosted by interactivity modifiers. Changes upon fork,
1896 * setprio syscalls, and whenever the interactivity
1897 * estimator recalculates.
1899 static inline int normal_prio(struct task_struct
*p
)
1903 if (task_has_rt_policy(p
))
1904 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1906 prio
= __normal_prio(p
);
1911 * Calculate the current priority, i.e. the priority
1912 * taken into account by the scheduler. This value might
1913 * be boosted by RT tasks, or might be boosted by
1914 * interactivity modifiers. Will be RT if the task got
1915 * RT-boosted. If not then it returns p->normal_prio.
1917 static int effective_prio(struct task_struct
*p
)
1919 p
->normal_prio
= normal_prio(p
);
1921 * If we are RT tasks or we were boosted to RT priority,
1922 * keep the priority unchanged. Otherwise, update priority
1923 * to the normal priority:
1925 if (!rt_prio(p
->prio
))
1926 return p
->normal_prio
;
1931 * activate_task - move a task to the runqueue.
1933 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1935 if (task_contributes_to_load(p
))
1936 rq
->nr_uninterruptible
--;
1938 enqueue_task(rq
, p
, wakeup
);
1943 * deactivate_task - remove a task from the runqueue.
1945 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1947 if (task_contributes_to_load(p
))
1948 rq
->nr_uninterruptible
++;
1950 dequeue_task(rq
, p
, sleep
);
1955 * task_curr - is this task currently executing on a CPU?
1956 * @p: the task in question.
1958 inline int task_curr(const struct task_struct
*p
)
1960 return cpu_curr(task_cpu(p
)) == p
;
1963 /* Used instead of source_load when we know the type == 0 */
1964 unsigned long weighted_cpuload(const int cpu
)
1966 return cpu_rq(cpu
)->load
.weight
;
1969 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1971 set_task_rq(p
, cpu
);
1974 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1975 * successfuly executed on another CPU. We must ensure that updates of
1976 * per-task data have been completed by this moment.
1979 task_thread_info(p
)->cpu
= cpu
;
1983 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1984 const struct sched_class
*prev_class
,
1985 int oldprio
, int running
)
1987 if (prev_class
!= p
->sched_class
) {
1988 if (prev_class
->switched_from
)
1989 prev_class
->switched_from(rq
, p
, running
);
1990 p
->sched_class
->switched_to(rq
, p
, running
);
1992 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1998 * Is this task likely cache-hot:
2001 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
2006 * Buddy candidates are cache hot:
2008 if (sched_feat(CACHE_HOT_BUDDY
) && (&p
->se
== cfs_rq_of(&p
->se
)->next
))
2011 if (p
->sched_class
!= &fair_sched_class
)
2014 if (sysctl_sched_migration_cost
== -1)
2016 if (sysctl_sched_migration_cost
== 0)
2019 delta
= now
- p
->se
.exec_start
;
2021 return delta
< (s64
)sysctl_sched_migration_cost
;
2025 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
2027 int old_cpu
= task_cpu(p
);
2028 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
2029 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
2030 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
2033 clock_offset
= old_rq
->clock
- new_rq
->clock
;
2035 #ifdef CONFIG_SCHEDSTATS
2036 if (p
->se
.wait_start
)
2037 p
->se
.wait_start
-= clock_offset
;
2038 if (p
->se
.sleep_start
)
2039 p
->se
.sleep_start
-= clock_offset
;
2040 if (p
->se
.block_start
)
2041 p
->se
.block_start
-= clock_offset
;
2042 if (old_cpu
!= new_cpu
) {
2043 schedstat_inc(p
, se
.nr_migrations
);
2044 if (task_hot(p
, old_rq
->clock
, NULL
))
2045 schedstat_inc(p
, se
.nr_forced2_migrations
);
2048 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
2049 new_cfsrq
->min_vruntime
;
2051 __set_task_cpu(p
, new_cpu
);
2054 struct migration_req
{
2055 struct list_head list
;
2057 struct task_struct
*task
;
2060 struct completion done
;
2064 * The task's runqueue lock must be held.
2065 * Returns true if you have to wait for migration thread.
2068 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
2070 struct rq
*rq
= task_rq(p
);
2073 * If the task is not on a runqueue (and not running), then
2074 * it is sufficient to simply update the task's cpu field.
2076 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
2077 set_task_cpu(p
, dest_cpu
);
2081 init_completion(&req
->done
);
2083 req
->dest_cpu
= dest_cpu
;
2084 list_add(&req
->list
, &rq
->migration_queue
);
2090 * wait_task_inactive - wait for a thread to unschedule.
2092 * The caller must ensure that the task *will* unschedule sometime soon,
2093 * else this function might spin for a *long* time. This function can't
2094 * be called with interrupts off, or it may introduce deadlock with
2095 * smp_call_function() if an IPI is sent by the same process we are
2096 * waiting to become inactive.
2098 void wait_task_inactive(struct task_struct
*p
)
2100 unsigned long flags
;
2106 * We do the initial early heuristics without holding
2107 * any task-queue locks at all. We'll only try to get
2108 * the runqueue lock when things look like they will
2114 * If the task is actively running on another CPU
2115 * still, just relax and busy-wait without holding
2118 * NOTE! Since we don't hold any locks, it's not
2119 * even sure that "rq" stays as the right runqueue!
2120 * But we don't care, since "task_running()" will
2121 * return false if the runqueue has changed and p
2122 * is actually now running somewhere else!
2124 while (task_running(rq
, p
))
2128 * Ok, time to look more closely! We need the rq
2129 * lock now, to be *sure*. If we're wrong, we'll
2130 * just go back and repeat.
2132 rq
= task_rq_lock(p
, &flags
);
2133 running
= task_running(rq
, p
);
2134 on_rq
= p
->se
.on_rq
;
2135 task_rq_unlock(rq
, &flags
);
2138 * Was it really running after all now that we
2139 * checked with the proper locks actually held?
2141 * Oops. Go back and try again..
2143 if (unlikely(running
)) {
2149 * It's not enough that it's not actively running,
2150 * it must be off the runqueue _entirely_, and not
2153 * So if it wa still runnable (but just not actively
2154 * running right now), it's preempted, and we should
2155 * yield - it could be a while.
2157 if (unlikely(on_rq
)) {
2158 schedule_timeout_uninterruptible(1);
2163 * Ahh, all good. It wasn't running, and it wasn't
2164 * runnable, which means that it will never become
2165 * running in the future either. We're all done!
2172 * kick_process - kick a running thread to enter/exit the kernel
2173 * @p: the to-be-kicked thread
2175 * Cause a process which is running on another CPU to enter
2176 * kernel-mode, without any delay. (to get signals handled.)
2178 * NOTE: this function doesnt have to take the runqueue lock,
2179 * because all it wants to ensure is that the remote task enters
2180 * the kernel. If the IPI races and the task has been migrated
2181 * to another CPU then no harm is done and the purpose has been
2184 void kick_process(struct task_struct
*p
)
2190 if ((cpu
!= smp_processor_id()) && task_curr(p
))
2191 smp_send_reschedule(cpu
);
2196 * Return a low guess at the load of a migration-source cpu weighted
2197 * according to the scheduling class and "nice" value.
2199 * We want to under-estimate the load of migration sources, to
2200 * balance conservatively.
2202 static unsigned long source_load(int cpu
, int type
)
2204 struct rq
*rq
= cpu_rq(cpu
);
2205 unsigned long total
= weighted_cpuload(cpu
);
2210 return min(rq
->cpu_load
[type
-1], total
);
2214 * Return a high guess at the load of a migration-target cpu weighted
2215 * according to the scheduling class and "nice" value.
2217 static unsigned long target_load(int cpu
, int type
)
2219 struct rq
*rq
= cpu_rq(cpu
);
2220 unsigned long total
= weighted_cpuload(cpu
);
2225 return max(rq
->cpu_load
[type
-1], total
);
2229 * Return the average load per task on the cpu's run queue
2231 static unsigned long cpu_avg_load_per_task(int cpu
)
2233 struct rq
*rq
= cpu_rq(cpu
);
2234 unsigned long total
= weighted_cpuload(cpu
);
2235 unsigned long n
= rq
->nr_running
;
2237 return n
? total
/ n
: SCHED_LOAD_SCALE
;
2241 * find_idlest_group finds and returns the least busy CPU group within the
2244 static struct sched_group
*
2245 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
2247 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2248 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
2249 int load_idx
= sd
->forkexec_idx
;
2250 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
2253 unsigned long load
, avg_load
;
2257 /* Skip over this group if it has no CPUs allowed */
2258 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
2261 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2263 /* Tally up the load of all CPUs in the group */
2266 for_each_cpu_mask(i
, group
->cpumask
) {
2267 /* Bias balancing toward cpus of our domain */
2269 load
= source_load(i
, load_idx
);
2271 load
= target_load(i
, load_idx
);
2276 /* Adjust by relative CPU power of the group */
2277 avg_load
= sg_div_cpu_power(group
,
2278 avg_load
* SCHED_LOAD_SCALE
);
2281 this_load
= avg_load
;
2283 } else if (avg_load
< min_load
) {
2284 min_load
= avg_load
;
2287 } while (group
= group
->next
, group
!= sd
->groups
);
2289 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
2295 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2298 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
,
2301 unsigned long load
, min_load
= ULONG_MAX
;
2305 /* Traverse only the allowed CPUs */
2306 cpus_and(*tmp
, group
->cpumask
, p
->cpus_allowed
);
2308 for_each_cpu_mask(i
, *tmp
) {
2309 load
= weighted_cpuload(i
);
2311 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
2321 * sched_balance_self: balance the current task (running on cpu) in domains
2322 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2325 * Balance, ie. select the least loaded group.
2327 * Returns the target CPU number, or the same CPU if no balancing is needed.
2329 * preempt must be disabled.
2331 static int sched_balance_self(int cpu
, int flag
)
2333 struct task_struct
*t
= current
;
2334 struct sched_domain
*tmp
, *sd
= NULL
;
2336 for_each_domain(cpu
, tmp
) {
2338 * If power savings logic is enabled for a domain, stop there.
2340 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
2342 if (tmp
->flags
& flag
)
2347 cpumask_t span
, tmpmask
;
2348 struct sched_group
*group
;
2349 int new_cpu
, weight
;
2351 if (!(sd
->flags
& flag
)) {
2357 group
= find_idlest_group(sd
, t
, cpu
);
2363 new_cpu
= find_idlest_cpu(group
, t
, cpu
, &tmpmask
);
2364 if (new_cpu
== -1 || new_cpu
== cpu
) {
2365 /* Now try balancing at a lower domain level of cpu */
2370 /* Now try balancing at a lower domain level of new_cpu */
2373 weight
= cpus_weight(span
);
2374 for_each_domain(cpu
, tmp
) {
2375 if (weight
<= cpus_weight(tmp
->span
))
2377 if (tmp
->flags
& flag
)
2380 /* while loop will break here if sd == NULL */
2386 #endif /* CONFIG_SMP */
2389 * try_to_wake_up - wake up a thread
2390 * @p: the to-be-woken-up thread
2391 * @state: the mask of task states that can be woken
2392 * @sync: do a synchronous wakeup?
2394 * Put it on the run-queue if it's not already there. The "current"
2395 * thread is always on the run-queue (except when the actual
2396 * re-schedule is in progress), and as such you're allowed to do
2397 * the simpler "current->state = TASK_RUNNING" to mark yourself
2398 * runnable without the overhead of this.
2400 * returns failure only if the task is already active.
2402 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
2404 int cpu
, orig_cpu
, this_cpu
, success
= 0;
2405 unsigned long flags
;
2409 if (!sched_feat(SYNC_WAKEUPS
))
2413 rq
= task_rq_lock(p
, &flags
);
2414 old_state
= p
->state
;
2415 if (!(old_state
& state
))
2423 this_cpu
= smp_processor_id();
2426 if (unlikely(task_running(rq
, p
)))
2429 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
2430 if (cpu
!= orig_cpu
) {
2431 set_task_cpu(p
, cpu
);
2432 task_rq_unlock(rq
, &flags
);
2433 /* might preempt at this point */
2434 rq
= task_rq_lock(p
, &flags
);
2435 old_state
= p
->state
;
2436 if (!(old_state
& state
))
2441 this_cpu
= smp_processor_id();
2445 #ifdef CONFIG_SCHEDSTATS
2446 schedstat_inc(rq
, ttwu_count
);
2447 if (cpu
== this_cpu
)
2448 schedstat_inc(rq
, ttwu_local
);
2450 struct sched_domain
*sd
;
2451 for_each_domain(this_cpu
, sd
) {
2452 if (cpu_isset(cpu
, sd
->span
)) {
2453 schedstat_inc(sd
, ttwu_wake_remote
);
2461 #endif /* CONFIG_SMP */
2462 schedstat_inc(p
, se
.nr_wakeups
);
2464 schedstat_inc(p
, se
.nr_wakeups_sync
);
2465 if (orig_cpu
!= cpu
)
2466 schedstat_inc(p
, se
.nr_wakeups_migrate
);
2467 if (cpu
== this_cpu
)
2468 schedstat_inc(p
, se
.nr_wakeups_local
);
2470 schedstat_inc(p
, se
.nr_wakeups_remote
);
2471 update_rq_clock(rq
);
2472 activate_task(rq
, p
, 1);
2476 check_preempt_curr(rq
, p
);
2478 p
->state
= TASK_RUNNING
;
2480 if (p
->sched_class
->task_wake_up
)
2481 p
->sched_class
->task_wake_up(rq
, p
);
2484 task_rq_unlock(rq
, &flags
);
2489 int wake_up_process(struct task_struct
*p
)
2491 return try_to_wake_up(p
, TASK_ALL
, 0);
2493 EXPORT_SYMBOL(wake_up_process
);
2495 int wake_up_state(struct task_struct
*p
, unsigned int state
)
2497 return try_to_wake_up(p
, state
, 0);
2501 * Perform scheduler related setup for a newly forked process p.
2502 * p is forked by current.
2504 * __sched_fork() is basic setup used by init_idle() too:
2506 static void __sched_fork(struct task_struct
*p
)
2508 p
->se
.exec_start
= 0;
2509 p
->se
.sum_exec_runtime
= 0;
2510 p
->se
.prev_sum_exec_runtime
= 0;
2511 p
->se
.last_wakeup
= 0;
2512 p
->se
.avg_overlap
= 0;
2514 #ifdef CONFIG_SCHEDSTATS
2515 p
->se
.wait_start
= 0;
2516 p
->se
.sum_sleep_runtime
= 0;
2517 p
->se
.sleep_start
= 0;
2518 p
->se
.block_start
= 0;
2519 p
->se
.sleep_max
= 0;
2520 p
->se
.block_max
= 0;
2522 p
->se
.slice_max
= 0;
2526 INIT_LIST_HEAD(&p
->rt
.run_list
);
2529 #ifdef CONFIG_PREEMPT_NOTIFIERS
2530 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
2534 * We mark the process as running here, but have not actually
2535 * inserted it onto the runqueue yet. This guarantees that
2536 * nobody will actually run it, and a signal or other external
2537 * event cannot wake it up and insert it on the runqueue either.
2539 p
->state
= TASK_RUNNING
;
2543 * fork()/clone()-time setup:
2545 void sched_fork(struct task_struct
*p
, int clone_flags
)
2547 int cpu
= get_cpu();
2552 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
2554 set_task_cpu(p
, cpu
);
2557 * Make sure we do not leak PI boosting priority to the child:
2559 p
->prio
= current
->normal_prio
;
2560 if (!rt_prio(p
->prio
))
2561 p
->sched_class
= &fair_sched_class
;
2563 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2564 if (likely(sched_info_on()))
2565 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
2567 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2570 #ifdef CONFIG_PREEMPT
2571 /* Want to start with kernel preemption disabled. */
2572 task_thread_info(p
)->preempt_count
= 1;
2578 * wake_up_new_task - wake up a newly created task for the first time.
2580 * This function will do some initial scheduler statistics housekeeping
2581 * that must be done for every newly created context, then puts the task
2582 * on the runqueue and wakes it.
2584 void wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
2586 unsigned long flags
;
2589 rq
= task_rq_lock(p
, &flags
);
2590 BUG_ON(p
->state
!= TASK_RUNNING
);
2591 update_rq_clock(rq
);
2593 p
->prio
= effective_prio(p
);
2595 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
2596 activate_task(rq
, p
, 0);
2599 * Let the scheduling class do new task startup
2600 * management (if any):
2602 p
->sched_class
->task_new(rq
, p
);
2605 check_preempt_curr(rq
, p
);
2607 if (p
->sched_class
->task_wake_up
)
2608 p
->sched_class
->task_wake_up(rq
, p
);
2610 task_rq_unlock(rq
, &flags
);
2613 #ifdef CONFIG_PREEMPT_NOTIFIERS
2616 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2617 * @notifier: notifier struct to register
2619 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2621 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2623 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2626 * preempt_notifier_unregister - no longer interested in preemption notifications
2627 * @notifier: notifier struct to unregister
2629 * This is safe to call from within a preemption notifier.
2631 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2633 hlist_del(¬ifier
->link
);
2635 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2637 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2639 struct preempt_notifier
*notifier
;
2640 struct hlist_node
*node
;
2642 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2643 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2647 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2648 struct task_struct
*next
)
2650 struct preempt_notifier
*notifier
;
2651 struct hlist_node
*node
;
2653 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2654 notifier
->ops
->sched_out(notifier
, next
);
2659 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2664 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2665 struct task_struct
*next
)
2672 * prepare_task_switch - prepare to switch tasks
2673 * @rq: the runqueue preparing to switch
2674 * @prev: the current task that is being switched out
2675 * @next: the task we are going to switch to.
2677 * This is called with the rq lock held and interrupts off. It must
2678 * be paired with a subsequent finish_task_switch after the context
2681 * prepare_task_switch sets up locking and calls architecture specific
2685 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2686 struct task_struct
*next
)
2688 fire_sched_out_preempt_notifiers(prev
, next
);
2689 prepare_lock_switch(rq
, next
);
2690 prepare_arch_switch(next
);
2694 * finish_task_switch - clean up after a task-switch
2695 * @rq: runqueue associated with task-switch
2696 * @prev: the thread we just switched away from.
2698 * finish_task_switch must be called after the context switch, paired
2699 * with a prepare_task_switch call before the context switch.
2700 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2701 * and do any other architecture-specific cleanup actions.
2703 * Note that we may have delayed dropping an mm in context_switch(). If
2704 * so, we finish that here outside of the runqueue lock. (Doing it
2705 * with the lock held can cause deadlocks; see schedule() for
2708 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2709 __releases(rq
->lock
)
2711 struct mm_struct
*mm
= rq
->prev_mm
;
2717 * A task struct has one reference for the use as "current".
2718 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2719 * schedule one last time. The schedule call will never return, and
2720 * the scheduled task must drop that reference.
2721 * The test for TASK_DEAD must occur while the runqueue locks are
2722 * still held, otherwise prev could be scheduled on another cpu, die
2723 * there before we look at prev->state, and then the reference would
2725 * Manfred Spraul <manfred@colorfullife.com>
2727 prev_state
= prev
->state
;
2728 finish_arch_switch(prev
);
2729 finish_lock_switch(rq
, prev
);
2731 if (current
->sched_class
->post_schedule
)
2732 current
->sched_class
->post_schedule(rq
);
2735 fire_sched_in_preempt_notifiers(current
);
2738 if (unlikely(prev_state
== TASK_DEAD
)) {
2740 * Remove function-return probe instances associated with this
2741 * task and put them back on the free list.
2743 kprobe_flush_task(prev
);
2744 put_task_struct(prev
);
2749 * schedule_tail - first thing a freshly forked thread must call.
2750 * @prev: the thread we just switched away from.
2752 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2753 __releases(rq
->lock
)
2755 struct rq
*rq
= this_rq();
2757 finish_task_switch(rq
, prev
);
2758 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2759 /* In this case, finish_task_switch does not reenable preemption */
2762 if (current
->set_child_tid
)
2763 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2767 * context_switch - switch to the new MM and the new
2768 * thread's register state.
2771 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2772 struct task_struct
*next
)
2774 struct mm_struct
*mm
, *oldmm
;
2776 prepare_task_switch(rq
, prev
, next
);
2778 oldmm
= prev
->active_mm
;
2780 * For paravirt, this is coupled with an exit in switch_to to
2781 * combine the page table reload and the switch backend into
2784 arch_enter_lazy_cpu_mode();
2786 if (unlikely(!mm
)) {
2787 next
->active_mm
= oldmm
;
2788 atomic_inc(&oldmm
->mm_count
);
2789 enter_lazy_tlb(oldmm
, next
);
2791 switch_mm(oldmm
, mm
, next
);
2793 if (unlikely(!prev
->mm
)) {
2794 prev
->active_mm
= NULL
;
2795 rq
->prev_mm
= oldmm
;
2798 * Since the runqueue lock will be released by the next
2799 * task (which is an invalid locking op but in the case
2800 * of the scheduler it's an obvious special-case), so we
2801 * do an early lockdep release here:
2803 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2804 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2807 /* Here we just switch the register state and the stack. */
2808 switch_to(prev
, next
, prev
);
2812 * this_rq must be evaluated again because prev may have moved
2813 * CPUs since it called schedule(), thus the 'rq' on its stack
2814 * frame will be invalid.
2816 finish_task_switch(this_rq(), prev
);
2820 * nr_running, nr_uninterruptible and nr_context_switches:
2822 * externally visible scheduler statistics: current number of runnable
2823 * threads, current number of uninterruptible-sleeping threads, total
2824 * number of context switches performed since bootup.
2826 unsigned long nr_running(void)
2828 unsigned long i
, sum
= 0;
2830 for_each_online_cpu(i
)
2831 sum
+= cpu_rq(i
)->nr_running
;
2836 unsigned long nr_uninterruptible(void)
2838 unsigned long i
, sum
= 0;
2840 for_each_possible_cpu(i
)
2841 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2844 * Since we read the counters lockless, it might be slightly
2845 * inaccurate. Do not allow it to go below zero though:
2847 if (unlikely((long)sum
< 0))
2853 unsigned long long nr_context_switches(void)
2856 unsigned long long sum
= 0;
2858 for_each_possible_cpu(i
)
2859 sum
+= cpu_rq(i
)->nr_switches
;
2864 unsigned long nr_iowait(void)
2866 unsigned long i
, sum
= 0;
2868 for_each_possible_cpu(i
)
2869 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2874 unsigned long nr_active(void)
2876 unsigned long i
, running
= 0, uninterruptible
= 0;
2878 for_each_online_cpu(i
) {
2879 running
+= cpu_rq(i
)->nr_running
;
2880 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2883 if (unlikely((long)uninterruptible
< 0))
2884 uninterruptible
= 0;
2886 return running
+ uninterruptible
;
2890 * Update rq->cpu_load[] statistics. This function is usually called every
2891 * scheduler tick (TICK_NSEC).
2893 static void update_cpu_load(struct rq
*this_rq
)
2895 unsigned long this_load
= this_rq
->load
.weight
;
2898 this_rq
->nr_load_updates
++;
2900 /* Update our load: */
2901 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2902 unsigned long old_load
, new_load
;
2904 /* scale is effectively 1 << i now, and >> i divides by scale */
2906 old_load
= this_rq
->cpu_load
[i
];
2907 new_load
= this_load
;
2909 * Round up the averaging division if load is increasing. This
2910 * prevents us from getting stuck on 9 if the load is 10, for
2913 if (new_load
> old_load
)
2914 new_load
+= scale
-1;
2915 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2922 * double_rq_lock - safely lock two runqueues
2924 * Note this does not disable interrupts like task_rq_lock,
2925 * you need to do so manually before calling.
2927 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2928 __acquires(rq1
->lock
)
2929 __acquires(rq2
->lock
)
2931 BUG_ON(!irqs_disabled());
2933 spin_lock(&rq1
->lock
);
2934 __acquire(rq2
->lock
); /* Fake it out ;) */
2937 spin_lock(&rq1
->lock
);
2938 spin_lock(&rq2
->lock
);
2940 spin_lock(&rq2
->lock
);
2941 spin_lock(&rq1
->lock
);
2944 update_rq_clock(rq1
);
2945 update_rq_clock(rq2
);
2949 * double_rq_unlock - safely unlock two runqueues
2951 * Note this does not restore interrupts like task_rq_unlock,
2952 * you need to do so manually after calling.
2954 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2955 __releases(rq1
->lock
)
2956 __releases(rq2
->lock
)
2958 spin_unlock(&rq1
->lock
);
2960 spin_unlock(&rq2
->lock
);
2962 __release(rq2
->lock
);
2966 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2968 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
2969 __releases(this_rq
->lock
)
2970 __acquires(busiest
->lock
)
2971 __acquires(this_rq
->lock
)
2975 if (unlikely(!irqs_disabled())) {
2976 /* printk() doesn't work good under rq->lock */
2977 spin_unlock(&this_rq
->lock
);
2980 if (unlikely(!spin_trylock(&busiest
->lock
))) {
2981 if (busiest
< this_rq
) {
2982 spin_unlock(&this_rq
->lock
);
2983 spin_lock(&busiest
->lock
);
2984 spin_lock(&this_rq
->lock
);
2987 spin_lock(&busiest
->lock
);
2993 * If dest_cpu is allowed for this process, migrate the task to it.
2994 * This is accomplished by forcing the cpu_allowed mask to only
2995 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2996 * the cpu_allowed mask is restored.
2998 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
3000 struct migration_req req
;
3001 unsigned long flags
;
3004 rq
= task_rq_lock(p
, &flags
);
3005 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
3006 || unlikely(cpu_is_offline(dest_cpu
)))
3009 /* force the process onto the specified CPU */
3010 if (migrate_task(p
, dest_cpu
, &req
)) {
3011 /* Need to wait for migration thread (might exit: take ref). */
3012 struct task_struct
*mt
= rq
->migration_thread
;
3014 get_task_struct(mt
);
3015 task_rq_unlock(rq
, &flags
);
3016 wake_up_process(mt
);
3017 put_task_struct(mt
);
3018 wait_for_completion(&req
.done
);
3023 task_rq_unlock(rq
, &flags
);
3027 * sched_exec - execve() is a valuable balancing opportunity, because at
3028 * this point the task has the smallest effective memory and cache footprint.
3030 void sched_exec(void)
3032 int new_cpu
, this_cpu
= get_cpu();
3033 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
3035 if (new_cpu
!= this_cpu
)
3036 sched_migrate_task(current
, new_cpu
);
3040 * pull_task - move a task from a remote runqueue to the local runqueue.
3041 * Both runqueues must be locked.
3043 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
3044 struct rq
*this_rq
, int this_cpu
)
3046 deactivate_task(src_rq
, p
, 0);
3047 set_task_cpu(p
, this_cpu
);
3048 activate_task(this_rq
, p
, 0);
3050 * Note that idle threads have a prio of MAX_PRIO, for this test
3051 * to be always true for them.
3053 check_preempt_curr(this_rq
, p
);
3057 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3060 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
3061 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3065 * We do not migrate tasks that are:
3066 * 1) running (obviously), or
3067 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3068 * 3) are cache-hot on their current CPU.
3070 if (!cpu_isset(this_cpu
, p
->cpus_allowed
)) {
3071 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
3076 if (task_running(rq
, p
)) {
3077 schedstat_inc(p
, se
.nr_failed_migrations_running
);
3082 * Aggressive migration if:
3083 * 1) task is cache cold, or
3084 * 2) too many balance attempts have failed.
3087 if (!task_hot(p
, rq
->clock
, sd
) ||
3088 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
3089 #ifdef CONFIG_SCHEDSTATS
3090 if (task_hot(p
, rq
->clock
, sd
)) {
3091 schedstat_inc(sd
, lb_hot_gained
[idle
]);
3092 schedstat_inc(p
, se
.nr_forced_migrations
);
3098 if (task_hot(p
, rq
->clock
, sd
)) {
3099 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
3105 static unsigned long
3106 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
3107 unsigned long max_load_move
, struct sched_domain
*sd
,
3108 enum cpu_idle_type idle
, int *all_pinned
,
3109 int *this_best_prio
, struct rq_iterator
*iterator
)
3111 int loops
= 0, pulled
= 0, pinned
= 0, skip_for_load
;
3112 struct task_struct
*p
;
3113 long rem_load_move
= max_load_move
;
3115 if (max_load_move
== 0)
3121 * Start the load-balancing iterator:
3123 p
= iterator
->start(iterator
->arg
);
3125 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
3128 * To help distribute high priority tasks across CPUs we don't
3129 * skip a task if it will be the highest priority task (i.e. smallest
3130 * prio value) on its new queue regardless of its load weight
3132 skip_for_load
= (p
->se
.load
.weight
>> 1) > rem_load_move
+
3133 SCHED_LOAD_SCALE_FUZZ
;
3134 if ((skip_for_load
&& p
->prio
>= *this_best_prio
) ||
3135 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
3136 p
= iterator
->next(iterator
->arg
);
3140 pull_task(busiest
, p
, this_rq
, this_cpu
);
3142 rem_load_move
-= p
->se
.load
.weight
;
3145 * We only want to steal up to the prescribed amount of weighted load.
3147 if (rem_load_move
> 0) {
3148 if (p
->prio
< *this_best_prio
)
3149 *this_best_prio
= p
->prio
;
3150 p
= iterator
->next(iterator
->arg
);
3155 * Right now, this is one of only two places pull_task() is called,
3156 * so we can safely collect pull_task() stats here rather than
3157 * inside pull_task().
3159 schedstat_add(sd
, lb_gained
[idle
], pulled
);
3162 *all_pinned
= pinned
;
3164 return max_load_move
- rem_load_move
;
3168 * move_tasks tries to move up to max_load_move weighted load from busiest to
3169 * this_rq, as part of a balancing operation within domain "sd".
3170 * Returns 1 if successful and 0 otherwise.
3172 * Called with both runqueues locked.
3174 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
3175 unsigned long max_load_move
,
3176 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3179 const struct sched_class
*class = sched_class_highest
;
3180 unsigned long total_load_moved
= 0;
3181 int this_best_prio
= this_rq
->curr
->prio
;
3185 class->load_balance(this_rq
, this_cpu
, busiest
,
3186 max_load_move
- total_load_moved
,
3187 sd
, idle
, all_pinned
, &this_best_prio
);
3188 class = class->next
;
3189 } while (class && max_load_move
> total_load_moved
);
3191 return total_load_moved
> 0;
3195 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
3196 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3197 struct rq_iterator
*iterator
)
3199 struct task_struct
*p
= iterator
->start(iterator
->arg
);
3203 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
3204 pull_task(busiest
, p
, this_rq
, this_cpu
);
3206 * Right now, this is only the second place pull_task()
3207 * is called, so we can safely collect pull_task()
3208 * stats here rather than inside pull_task().
3210 schedstat_inc(sd
, lb_gained
[idle
]);
3214 p
= iterator
->next(iterator
->arg
);
3221 * move_one_task tries to move exactly one task from busiest to this_rq, as
3222 * part of active balancing operations within "domain".
3223 * Returns 1 if successful and 0 otherwise.
3225 * Called with both runqueues locked.
3227 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
3228 struct sched_domain
*sd
, enum cpu_idle_type idle
)
3230 const struct sched_class
*class;
3232 for (class = sched_class_highest
; class; class = class->next
)
3233 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
3240 * find_busiest_group finds and returns the busiest CPU group within the
3241 * domain. It calculates and returns the amount of weighted load which
3242 * should be moved to restore balance via the imbalance parameter.
3244 static struct sched_group
*
3245 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
3246 unsigned long *imbalance
, enum cpu_idle_type idle
,
3247 int *sd_idle
, const cpumask_t
*cpus
, int *balance
)
3249 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
3250 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
3251 unsigned long max_pull
;
3252 unsigned long busiest_load_per_task
, busiest_nr_running
;
3253 unsigned long this_load_per_task
, this_nr_running
;
3254 int load_idx
, group_imb
= 0;
3255 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3256 int power_savings_balance
= 1;
3257 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
3258 unsigned long min_nr_running
= ULONG_MAX
;
3259 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
3262 max_load
= this_load
= total_load
= total_pwr
= 0;
3263 busiest_load_per_task
= busiest_nr_running
= 0;
3264 this_load_per_task
= this_nr_running
= 0;
3265 if (idle
== CPU_NOT_IDLE
)
3266 load_idx
= sd
->busy_idx
;
3267 else if (idle
== CPU_NEWLY_IDLE
)
3268 load_idx
= sd
->newidle_idx
;
3270 load_idx
= sd
->idle_idx
;
3273 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
3276 int __group_imb
= 0;
3277 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
3278 unsigned long sum_nr_running
, sum_weighted_load
;
3280 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
3283 balance_cpu
= first_cpu(group
->cpumask
);
3285 /* Tally up the load of all CPUs in the group */
3286 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
3288 min_cpu_load
= ~0UL;
3290 for_each_cpu_mask(i
, group
->cpumask
) {
3293 if (!cpu_isset(i
, *cpus
))
3298 if (*sd_idle
&& rq
->nr_running
)
3301 /* Bias balancing toward cpus of our domain */
3303 if (idle_cpu(i
) && !first_idle_cpu
) {
3308 load
= target_load(i
, load_idx
);
3310 load
= source_load(i
, load_idx
);
3311 if (load
> max_cpu_load
)
3312 max_cpu_load
= load
;
3313 if (min_cpu_load
> load
)
3314 min_cpu_load
= load
;
3318 sum_nr_running
+= rq
->nr_running
;
3319 sum_weighted_load
+= weighted_cpuload(i
);
3323 * First idle cpu or the first cpu(busiest) in this sched group
3324 * is eligible for doing load balancing at this and above
3325 * domains. In the newly idle case, we will allow all the cpu's
3326 * to do the newly idle load balance.
3328 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
3329 balance_cpu
!= this_cpu
&& balance
) {
3334 total_load
+= avg_load
;
3335 total_pwr
+= group
->__cpu_power
;
3337 /* Adjust by relative CPU power of the group */
3338 avg_load
= sg_div_cpu_power(group
,
3339 avg_load
* SCHED_LOAD_SCALE
);
3341 if ((max_cpu_load
- min_cpu_load
) > SCHED_LOAD_SCALE
)
3344 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
3347 this_load
= avg_load
;
3349 this_nr_running
= sum_nr_running
;
3350 this_load_per_task
= sum_weighted_load
;
3351 } else if (avg_load
> max_load
&&
3352 (sum_nr_running
> group_capacity
|| __group_imb
)) {
3353 max_load
= avg_load
;
3355 busiest_nr_running
= sum_nr_running
;
3356 busiest_load_per_task
= sum_weighted_load
;
3357 group_imb
= __group_imb
;
3360 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3362 * Busy processors will not participate in power savings
3365 if (idle
== CPU_NOT_IDLE
||
3366 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3370 * If the local group is idle or completely loaded
3371 * no need to do power savings balance at this domain
3373 if (local_group
&& (this_nr_running
>= group_capacity
||
3375 power_savings_balance
= 0;
3378 * If a group is already running at full capacity or idle,
3379 * don't include that group in power savings calculations
3381 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
3386 * Calculate the group which has the least non-idle load.
3387 * This is the group from where we need to pick up the load
3390 if ((sum_nr_running
< min_nr_running
) ||
3391 (sum_nr_running
== min_nr_running
&&
3392 first_cpu(group
->cpumask
) <
3393 first_cpu(group_min
->cpumask
))) {
3395 min_nr_running
= sum_nr_running
;
3396 min_load_per_task
= sum_weighted_load
/
3401 * Calculate the group which is almost near its
3402 * capacity but still has some space to pick up some load
3403 * from other group and save more power
3405 if (sum_nr_running
<= group_capacity
- 1) {
3406 if (sum_nr_running
> leader_nr_running
||
3407 (sum_nr_running
== leader_nr_running
&&
3408 first_cpu(group
->cpumask
) >
3409 first_cpu(group_leader
->cpumask
))) {
3410 group_leader
= group
;
3411 leader_nr_running
= sum_nr_running
;
3416 group
= group
->next
;
3417 } while (group
!= sd
->groups
);
3419 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
3422 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
3424 if (this_load
>= avg_load
||
3425 100*max_load
<= sd
->imbalance_pct
*this_load
)
3428 busiest_load_per_task
/= busiest_nr_running
;
3430 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
3433 * We're trying to get all the cpus to the average_load, so we don't
3434 * want to push ourselves above the average load, nor do we wish to
3435 * reduce the max loaded cpu below the average load, as either of these
3436 * actions would just result in more rebalancing later, and ping-pong
3437 * tasks around. Thus we look for the minimum possible imbalance.
3438 * Negative imbalances (*we* are more loaded than anyone else) will
3439 * be counted as no imbalance for these purposes -- we can't fix that
3440 * by pulling tasks to us. Be careful of negative numbers as they'll
3441 * appear as very large values with unsigned longs.
3443 if (max_load
<= busiest_load_per_task
)
3447 * In the presence of smp nice balancing, certain scenarios can have
3448 * max load less than avg load(as we skip the groups at or below
3449 * its cpu_power, while calculating max_load..)
3451 if (max_load
< avg_load
) {
3453 goto small_imbalance
;
3456 /* Don't want to pull so many tasks that a group would go idle */
3457 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
3459 /* How much load to actually move to equalise the imbalance */
3460 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
3461 (avg_load
- this_load
) * this->__cpu_power
)
3465 * if *imbalance is less than the average load per runnable task
3466 * there is no gaurantee that any tasks will be moved so we'll have
3467 * a think about bumping its value to force at least one task to be
3470 if (*imbalance
< busiest_load_per_task
) {
3471 unsigned long tmp
, pwr_now
, pwr_move
;
3475 pwr_move
= pwr_now
= 0;
3477 if (this_nr_running
) {
3478 this_load_per_task
/= this_nr_running
;
3479 if (busiest_load_per_task
> this_load_per_task
)
3482 this_load_per_task
= SCHED_LOAD_SCALE
;
3484 if (max_load
- this_load
+ SCHED_LOAD_SCALE_FUZZ
>=
3485 busiest_load_per_task
* imbn
) {
3486 *imbalance
= busiest_load_per_task
;
3491 * OK, we don't have enough imbalance to justify moving tasks,
3492 * however we may be able to increase total CPU power used by
3496 pwr_now
+= busiest
->__cpu_power
*
3497 min(busiest_load_per_task
, max_load
);
3498 pwr_now
+= this->__cpu_power
*
3499 min(this_load_per_task
, this_load
);
3500 pwr_now
/= SCHED_LOAD_SCALE
;
3502 /* Amount of load we'd subtract */
3503 tmp
= sg_div_cpu_power(busiest
,
3504 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3506 pwr_move
+= busiest
->__cpu_power
*
3507 min(busiest_load_per_task
, max_load
- tmp
);
3509 /* Amount of load we'd add */
3510 if (max_load
* busiest
->__cpu_power
<
3511 busiest_load_per_task
* SCHED_LOAD_SCALE
)
3512 tmp
= sg_div_cpu_power(this,
3513 max_load
* busiest
->__cpu_power
);
3515 tmp
= sg_div_cpu_power(this,
3516 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3517 pwr_move
+= this->__cpu_power
*
3518 min(this_load_per_task
, this_load
+ tmp
);
3519 pwr_move
/= SCHED_LOAD_SCALE
;
3521 /* Move if we gain throughput */
3522 if (pwr_move
> pwr_now
)
3523 *imbalance
= busiest_load_per_task
;
3529 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3530 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3533 if (this == group_leader
&& group_leader
!= group_min
) {
3534 *imbalance
= min_load_per_task
;
3544 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3547 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
3548 unsigned long imbalance
, const cpumask_t
*cpus
)
3550 struct rq
*busiest
= NULL
, *rq
;
3551 unsigned long max_load
= 0;
3554 for_each_cpu_mask(i
, group
->cpumask
) {
3557 if (!cpu_isset(i
, *cpus
))
3561 wl
= weighted_cpuload(i
);
3563 if (rq
->nr_running
== 1 && wl
> imbalance
)
3566 if (wl
> max_load
) {
3576 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3577 * so long as it is large enough.
3579 #define MAX_PINNED_INTERVAL 512
3582 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3583 * tasks if there is an imbalance.
3585 static int load_balance(int this_cpu
, struct rq
*this_rq
,
3586 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3587 int *balance
, cpumask_t
*cpus
)
3589 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
3590 struct sched_group
*group
;
3591 unsigned long imbalance
;
3593 unsigned long flags
;
3594 int unlock_aggregate
;
3598 unlock_aggregate
= get_aggregate(sd
);
3601 * When power savings policy is enabled for the parent domain, idle
3602 * sibling can pick up load irrespective of busy siblings. In this case,
3603 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3604 * portraying it as CPU_NOT_IDLE.
3606 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3607 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3610 schedstat_inc(sd
, lb_count
[idle
]);
3613 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
3620 schedstat_inc(sd
, lb_nobusyg
[idle
]);
3624 busiest
= find_busiest_queue(group
, idle
, imbalance
, cpus
);
3626 schedstat_inc(sd
, lb_nobusyq
[idle
]);
3630 BUG_ON(busiest
== this_rq
);
3632 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
3635 if (busiest
->nr_running
> 1) {
3637 * Attempt to move tasks. If find_busiest_group has found
3638 * an imbalance but busiest->nr_running <= 1, the group is
3639 * still unbalanced. ld_moved simply stays zero, so it is
3640 * correctly treated as an imbalance.
3642 local_irq_save(flags
);
3643 double_rq_lock(this_rq
, busiest
);
3644 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3645 imbalance
, sd
, idle
, &all_pinned
);
3646 double_rq_unlock(this_rq
, busiest
);
3647 local_irq_restore(flags
);
3650 * some other cpu did the load balance for us.
3652 if (ld_moved
&& this_cpu
!= smp_processor_id())
3653 resched_cpu(this_cpu
);
3655 /* All tasks on this runqueue were pinned by CPU affinity */
3656 if (unlikely(all_pinned
)) {
3657 cpu_clear(cpu_of(busiest
), *cpus
);
3658 if (!cpus_empty(*cpus
))
3665 schedstat_inc(sd
, lb_failed
[idle
]);
3666 sd
->nr_balance_failed
++;
3668 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3670 spin_lock_irqsave(&busiest
->lock
, flags
);
3672 /* don't kick the migration_thread, if the curr
3673 * task on busiest cpu can't be moved to this_cpu
3675 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3676 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3678 goto out_one_pinned
;
3681 if (!busiest
->active_balance
) {
3682 busiest
->active_balance
= 1;
3683 busiest
->push_cpu
= this_cpu
;
3686 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3688 wake_up_process(busiest
->migration_thread
);
3691 * We've kicked active balancing, reset the failure
3694 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3697 sd
->nr_balance_failed
= 0;
3699 if (likely(!active_balance
)) {
3700 /* We were unbalanced, so reset the balancing interval */
3701 sd
->balance_interval
= sd
->min_interval
;
3704 * If we've begun active balancing, start to back off. This
3705 * case may not be covered by the all_pinned logic if there
3706 * is only 1 task on the busy runqueue (because we don't call
3709 if (sd
->balance_interval
< sd
->max_interval
)
3710 sd
->balance_interval
*= 2;
3713 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3714 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3720 schedstat_inc(sd
, lb_balanced
[idle
]);
3722 sd
->nr_balance_failed
= 0;
3725 /* tune up the balancing interval */
3726 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3727 (sd
->balance_interval
< sd
->max_interval
))
3728 sd
->balance_interval
*= 2;
3730 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3731 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3736 if (unlock_aggregate
)
3742 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3743 * tasks if there is an imbalance.
3745 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3746 * this_rq is locked.
3749 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
,
3752 struct sched_group
*group
;
3753 struct rq
*busiest
= NULL
;
3754 unsigned long imbalance
;
3762 * When power savings policy is enabled for the parent domain, idle
3763 * sibling can pick up load irrespective of busy siblings. In this case,
3764 * let the state of idle sibling percolate up as IDLE, instead of
3765 * portraying it as CPU_NOT_IDLE.
3767 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3768 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3771 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3773 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3774 &sd_idle
, cpus
, NULL
);
3776 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3780 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
, cpus
);
3782 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3786 BUG_ON(busiest
== this_rq
);
3788 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3791 if (busiest
->nr_running
> 1) {
3792 /* Attempt to move tasks */
3793 double_lock_balance(this_rq
, busiest
);
3794 /* this_rq->clock is already updated */
3795 update_rq_clock(busiest
);
3796 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3797 imbalance
, sd
, CPU_NEWLY_IDLE
,
3799 spin_unlock(&busiest
->lock
);
3801 if (unlikely(all_pinned
)) {
3802 cpu_clear(cpu_of(busiest
), *cpus
);
3803 if (!cpus_empty(*cpus
))
3809 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3810 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3811 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3814 sd
->nr_balance_failed
= 0;
3819 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3820 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3821 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3823 sd
->nr_balance_failed
= 0;
3829 * idle_balance is called by schedule() if this_cpu is about to become
3830 * idle. Attempts to pull tasks from other CPUs.
3832 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3834 struct sched_domain
*sd
;
3835 int pulled_task
= -1;
3836 unsigned long next_balance
= jiffies
+ HZ
;
3839 for_each_domain(this_cpu
, sd
) {
3840 unsigned long interval
;
3842 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3845 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3846 /* If we've pulled tasks over stop searching: */
3847 pulled_task
= load_balance_newidle(this_cpu
, this_rq
,
3850 interval
= msecs_to_jiffies(sd
->balance_interval
);
3851 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3852 next_balance
= sd
->last_balance
+ interval
;
3856 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3858 * We are going idle. next_balance may be set based on
3859 * a busy processor. So reset next_balance.
3861 this_rq
->next_balance
= next_balance
;
3866 * active_load_balance is run by migration threads. It pushes running tasks
3867 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3868 * running on each physical CPU where possible, and avoids physical /
3869 * logical imbalances.
3871 * Called with busiest_rq locked.
3873 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3875 int target_cpu
= busiest_rq
->push_cpu
;
3876 struct sched_domain
*sd
;
3877 struct rq
*target_rq
;
3879 /* Is there any task to move? */
3880 if (busiest_rq
->nr_running
<= 1)
3883 target_rq
= cpu_rq(target_cpu
);
3886 * This condition is "impossible", if it occurs
3887 * we need to fix it. Originally reported by
3888 * Bjorn Helgaas on a 128-cpu setup.
3890 BUG_ON(busiest_rq
== target_rq
);
3892 /* move a task from busiest_rq to target_rq */
3893 double_lock_balance(busiest_rq
, target_rq
);
3894 update_rq_clock(busiest_rq
);
3895 update_rq_clock(target_rq
);
3897 /* Search for an sd spanning us and the target CPU. */
3898 for_each_domain(target_cpu
, sd
) {
3899 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3900 cpu_isset(busiest_cpu
, sd
->span
))
3905 schedstat_inc(sd
, alb_count
);
3907 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3909 schedstat_inc(sd
, alb_pushed
);
3911 schedstat_inc(sd
, alb_failed
);
3913 spin_unlock(&target_rq
->lock
);
3918 atomic_t load_balancer
;
3920 } nohz ____cacheline_aligned
= {
3921 .load_balancer
= ATOMIC_INIT(-1),
3922 .cpu_mask
= CPU_MASK_NONE
,
3926 * This routine will try to nominate the ilb (idle load balancing)
3927 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3928 * load balancing on behalf of all those cpus. If all the cpus in the system
3929 * go into this tickless mode, then there will be no ilb owner (as there is
3930 * no need for one) and all the cpus will sleep till the next wakeup event
3933 * For the ilb owner, tick is not stopped. And this tick will be used
3934 * for idle load balancing. ilb owner will still be part of
3937 * While stopping the tick, this cpu will become the ilb owner if there
3938 * is no other owner. And will be the owner till that cpu becomes busy
3939 * or if all cpus in the system stop their ticks at which point
3940 * there is no need for ilb owner.
3942 * When the ilb owner becomes busy, it nominates another owner, during the
3943 * next busy scheduler_tick()
3945 int select_nohz_load_balancer(int stop_tick
)
3947 int cpu
= smp_processor_id();
3950 cpu_set(cpu
, nohz
.cpu_mask
);
3951 cpu_rq(cpu
)->in_nohz_recently
= 1;
3954 * If we are going offline and still the leader, give up!
3956 if (cpu_is_offline(cpu
) &&
3957 atomic_read(&nohz
.load_balancer
) == cpu
) {
3958 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3963 /* time for ilb owner also to sleep */
3964 if (cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3965 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3966 atomic_set(&nohz
.load_balancer
, -1);
3970 if (atomic_read(&nohz
.load_balancer
) == -1) {
3971 /* make me the ilb owner */
3972 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3974 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3977 if (!cpu_isset(cpu
, nohz
.cpu_mask
))
3980 cpu_clear(cpu
, nohz
.cpu_mask
);
3982 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3983 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3990 static DEFINE_SPINLOCK(balancing
);
3993 * It checks each scheduling domain to see if it is due to be balanced,
3994 * and initiates a balancing operation if so.
3996 * Balancing parameters are set up in arch_init_sched_domains.
3998 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
4001 struct rq
*rq
= cpu_rq(cpu
);
4002 unsigned long interval
;
4003 struct sched_domain
*sd
;
4004 /* Earliest time when we have to do rebalance again */
4005 unsigned long next_balance
= jiffies
+ 60*HZ
;
4006 int update_next_balance
= 0;
4009 for_each_domain(cpu
, sd
) {
4010 if (!(sd
->flags
& SD_LOAD_BALANCE
))
4013 interval
= sd
->balance_interval
;
4014 if (idle
!= CPU_IDLE
)
4015 interval
*= sd
->busy_factor
;
4017 /* scale ms to jiffies */
4018 interval
= msecs_to_jiffies(interval
);
4019 if (unlikely(!interval
))
4021 if (interval
> HZ
*NR_CPUS
/10)
4022 interval
= HZ
*NR_CPUS
/10;
4025 if (sd
->flags
& SD_SERIALIZE
) {
4026 if (!spin_trylock(&balancing
))
4030 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
4031 if (load_balance(cpu
, rq
, sd
, idle
, &balance
, &tmp
)) {
4033 * We've pulled tasks over so either we're no
4034 * longer idle, or one of our SMT siblings is
4037 idle
= CPU_NOT_IDLE
;
4039 sd
->last_balance
= jiffies
;
4041 if (sd
->flags
& SD_SERIALIZE
)
4042 spin_unlock(&balancing
);
4044 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
4045 next_balance
= sd
->last_balance
+ interval
;
4046 update_next_balance
= 1;
4050 * Stop the load balance at this level. There is another
4051 * CPU in our sched group which is doing load balancing more
4059 * next_balance will be updated only when there is a need.
4060 * When the cpu is attached to null domain for ex, it will not be
4063 if (likely(update_next_balance
))
4064 rq
->next_balance
= next_balance
;
4068 * run_rebalance_domains is triggered when needed from the scheduler tick.
4069 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4070 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4072 static void run_rebalance_domains(struct softirq_action
*h
)
4074 int this_cpu
= smp_processor_id();
4075 struct rq
*this_rq
= cpu_rq(this_cpu
);
4076 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
4077 CPU_IDLE
: CPU_NOT_IDLE
;
4079 rebalance_domains(this_cpu
, idle
);
4083 * If this cpu is the owner for idle load balancing, then do the
4084 * balancing on behalf of the other idle cpus whose ticks are
4087 if (this_rq
->idle_at_tick
&&
4088 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
4089 cpumask_t cpus
= nohz
.cpu_mask
;
4093 cpu_clear(this_cpu
, cpus
);
4094 for_each_cpu_mask(balance_cpu
, cpus
) {
4096 * If this cpu gets work to do, stop the load balancing
4097 * work being done for other cpus. Next load
4098 * balancing owner will pick it up.
4103 rebalance_domains(balance_cpu
, CPU_IDLE
);
4105 rq
= cpu_rq(balance_cpu
);
4106 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
4107 this_rq
->next_balance
= rq
->next_balance
;
4114 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4116 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4117 * idle load balancing owner or decide to stop the periodic load balancing,
4118 * if the whole system is idle.
4120 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
4124 * If we were in the nohz mode recently and busy at the current
4125 * scheduler tick, then check if we need to nominate new idle
4128 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
4129 rq
->in_nohz_recently
= 0;
4131 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
4132 cpu_clear(cpu
, nohz
.cpu_mask
);
4133 atomic_set(&nohz
.load_balancer
, -1);
4136 if (atomic_read(&nohz
.load_balancer
) == -1) {
4138 * simple selection for now: Nominate the
4139 * first cpu in the nohz list to be the next
4142 * TBD: Traverse the sched domains and nominate
4143 * the nearest cpu in the nohz.cpu_mask.
4145 int ilb
= first_cpu(nohz
.cpu_mask
);
4147 if (ilb
< nr_cpu_ids
)
4153 * If this cpu is idle and doing idle load balancing for all the
4154 * cpus with ticks stopped, is it time for that to stop?
4156 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
4157 cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
4163 * If this cpu is idle and the idle load balancing is done by
4164 * someone else, then no need raise the SCHED_SOFTIRQ
4166 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
4167 cpu_isset(cpu
, nohz
.cpu_mask
))
4170 if (time_after_eq(jiffies
, rq
->next_balance
))
4171 raise_softirq(SCHED_SOFTIRQ
);
4174 #else /* CONFIG_SMP */
4177 * on UP we do not need to balance between CPUs:
4179 static inline void idle_balance(int cpu
, struct rq
*rq
)
4185 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
4187 EXPORT_PER_CPU_SYMBOL(kstat
);
4190 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4191 * that have not yet been banked in case the task is currently running.
4193 unsigned long long task_sched_runtime(struct task_struct
*p
)
4195 unsigned long flags
;
4199 rq
= task_rq_lock(p
, &flags
);
4200 ns
= p
->se
.sum_exec_runtime
;
4201 if (task_current(rq
, p
)) {
4202 update_rq_clock(rq
);
4203 delta_exec
= rq
->clock
- p
->se
.exec_start
;
4204 if ((s64
)delta_exec
> 0)
4207 task_rq_unlock(rq
, &flags
);
4213 * Account user cpu time to a process.
4214 * @p: the process that the cpu time gets accounted to
4215 * @cputime: the cpu time spent in user space since the last update
4217 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
4219 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4222 p
->utime
= cputime_add(p
->utime
, cputime
);
4224 /* Add user time to cpustat. */
4225 tmp
= cputime_to_cputime64(cputime
);
4226 if (TASK_NICE(p
) > 0)
4227 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
4229 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
4233 * Account guest cpu time to a process.
4234 * @p: the process that the cpu time gets accounted to
4235 * @cputime: the cpu time spent in virtual machine since the last update
4237 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
4240 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4242 tmp
= cputime_to_cputime64(cputime
);
4244 p
->utime
= cputime_add(p
->utime
, cputime
);
4245 p
->gtime
= cputime_add(p
->gtime
, cputime
);
4247 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
4248 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
4252 * Account scaled user cpu time to a process.
4253 * @p: the process that the cpu time gets accounted to
4254 * @cputime: the cpu time spent in user space since the last update
4256 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
4258 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
4262 * Account system cpu time to a process.
4263 * @p: the process that the cpu time gets accounted to
4264 * @hardirq_offset: the offset to subtract from hardirq_count()
4265 * @cputime: the cpu time spent in kernel space since the last update
4267 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
4270 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4271 struct rq
*rq
= this_rq();
4274 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0))
4275 return account_guest_time(p
, cputime
);
4277 p
->stime
= cputime_add(p
->stime
, cputime
);
4279 /* Add system time to cpustat. */
4280 tmp
= cputime_to_cputime64(cputime
);
4281 if (hardirq_count() - hardirq_offset
)
4282 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
4283 else if (softirq_count())
4284 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
4285 else if (p
!= rq
->idle
)
4286 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
4287 else if (atomic_read(&rq
->nr_iowait
) > 0)
4288 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
4290 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
4291 /* Account for system time used */
4292 acct_update_integrals(p
);
4296 * Account scaled system cpu time to a process.
4297 * @p: the process that the cpu time gets accounted to
4298 * @hardirq_offset: the offset to subtract from hardirq_count()
4299 * @cputime: the cpu time spent in kernel space since the last update
4301 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
4303 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
4307 * Account for involuntary wait time.
4308 * @p: the process from which the cpu time has been stolen
4309 * @steal: the cpu time spent in involuntary wait
4311 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
4313 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
4314 cputime64_t tmp
= cputime_to_cputime64(steal
);
4315 struct rq
*rq
= this_rq();
4317 if (p
== rq
->idle
) {
4318 p
->stime
= cputime_add(p
->stime
, steal
);
4319 if (atomic_read(&rq
->nr_iowait
) > 0)
4320 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
4322 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
4324 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
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
;
4339 u64 next_tick
= rq
->tick_timestamp
+ TICK_NSEC
;
4341 spin_lock(&rq
->lock
);
4342 __update_rq_clock(rq
);
4344 * Let rq->clock advance by at least TICK_NSEC:
4346 if (unlikely(rq
->clock
< next_tick
)) {
4347 rq
->clock
= next_tick
;
4348 rq
->clock_underflows
++;
4350 rq
->tick_timestamp
= rq
->clock
;
4351 update_last_tick_seen(rq
);
4352 update_cpu_load(rq
);
4353 curr
->sched_class
->task_tick(rq
, curr
, 0);
4354 spin_unlock(&rq
->lock
);
4357 rq
->idle_at_tick
= idle_cpu(cpu
);
4358 trigger_load_balance(rq
, cpu
);
4362 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4364 void __kprobes
add_preempt_count(int val
)
4369 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4371 preempt_count() += val
;
4373 * Spinlock count overflowing soon?
4375 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
4378 EXPORT_SYMBOL(add_preempt_count
);
4380 void __kprobes
sub_preempt_count(int val
)
4385 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
4388 * Is the spinlock portion underflowing?
4390 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
4391 !(preempt_count() & PREEMPT_MASK
)))
4394 preempt_count() -= val
;
4396 EXPORT_SYMBOL(sub_preempt_count
);
4401 * Print scheduling while atomic bug:
4403 static noinline
void __schedule_bug(struct task_struct
*prev
)
4405 struct pt_regs
*regs
= get_irq_regs();
4407 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
4408 prev
->comm
, prev
->pid
, preempt_count());
4410 debug_show_held_locks(prev
);
4411 if (irqs_disabled())
4412 print_irqtrace_events(prev
);
4421 * Various schedule()-time debugging checks and statistics:
4423 static inline void schedule_debug(struct task_struct
*prev
)
4426 * Test if we are atomic. Since do_exit() needs to call into
4427 * schedule() atomically, we ignore that path for now.
4428 * Otherwise, whine if we are scheduling when we should not be.
4430 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev
->exit_state
))
4431 __schedule_bug(prev
);
4433 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
4435 schedstat_inc(this_rq(), sched_count
);
4436 #ifdef CONFIG_SCHEDSTATS
4437 if (unlikely(prev
->lock_depth
>= 0)) {
4438 schedstat_inc(this_rq(), bkl_count
);
4439 schedstat_inc(prev
, sched_info
.bkl_count
);
4445 * Pick up the highest-prio task:
4447 static inline struct task_struct
*
4448 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
4450 const struct sched_class
*class;
4451 struct task_struct
*p
;
4454 * Optimization: we know that if all tasks are in
4455 * the fair class we can call that function directly:
4457 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
4458 p
= fair_sched_class
.pick_next_task(rq
);
4463 class = sched_class_highest
;
4465 p
= class->pick_next_task(rq
);
4469 * Will never be NULL as the idle class always
4470 * returns a non-NULL p:
4472 class = class->next
;
4477 * schedule() is the main scheduler function.
4479 asmlinkage
void __sched
schedule(void)
4481 struct task_struct
*prev
, *next
;
4482 unsigned long *switch_count
;
4488 cpu
= smp_processor_id();
4492 switch_count
= &prev
->nivcsw
;
4494 release_kernel_lock(prev
);
4495 need_resched_nonpreemptible
:
4497 schedule_debug(prev
);
4502 * Do the rq-clock update outside the rq lock:
4504 local_irq_disable();
4505 __update_rq_clock(rq
);
4506 spin_lock(&rq
->lock
);
4507 clear_tsk_need_resched(prev
);
4509 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
4510 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
4511 signal_pending(prev
))) {
4512 prev
->state
= TASK_RUNNING
;
4514 deactivate_task(rq
, prev
, 1);
4516 switch_count
= &prev
->nvcsw
;
4520 if (prev
->sched_class
->pre_schedule
)
4521 prev
->sched_class
->pre_schedule(rq
, prev
);
4524 if (unlikely(!rq
->nr_running
))
4525 idle_balance(cpu
, rq
);
4527 prev
->sched_class
->put_prev_task(rq
, prev
);
4528 next
= pick_next_task(rq
, prev
);
4530 sched_info_switch(prev
, next
);
4532 if (likely(prev
!= next
)) {
4537 context_switch(rq
, prev
, next
); /* unlocks the rq */
4539 * the context switch might have flipped the stack from under
4540 * us, hence refresh the local variables.
4542 cpu
= smp_processor_id();
4545 spin_unlock_irq(&rq
->lock
);
4549 if (unlikely(reacquire_kernel_lock(current
) < 0))
4550 goto need_resched_nonpreemptible
;
4552 preempt_enable_no_resched();
4553 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
4556 EXPORT_SYMBOL(schedule
);
4558 #ifdef CONFIG_PREEMPT
4560 * this is the entry point to schedule() from in-kernel preemption
4561 * off of preempt_enable. Kernel preemptions off return from interrupt
4562 * occur there and call schedule directly.
4564 asmlinkage
void __sched
preempt_schedule(void)
4566 struct thread_info
*ti
= current_thread_info();
4567 struct task_struct
*task
= current
;
4568 int saved_lock_depth
;
4571 * If there is a non-zero preempt_count or interrupts are disabled,
4572 * we do not want to preempt the current task. Just return..
4574 if (likely(ti
->preempt_count
|| irqs_disabled()))
4578 add_preempt_count(PREEMPT_ACTIVE
);
4581 * We keep the big kernel semaphore locked, but we
4582 * clear ->lock_depth so that schedule() doesnt
4583 * auto-release the semaphore:
4585 saved_lock_depth
= task
->lock_depth
;
4586 task
->lock_depth
= -1;
4588 task
->lock_depth
= saved_lock_depth
;
4589 sub_preempt_count(PREEMPT_ACTIVE
);
4592 * Check again in case we missed a preemption opportunity
4593 * between schedule and now.
4596 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4598 EXPORT_SYMBOL(preempt_schedule
);
4601 * this is the entry point to schedule() from kernel preemption
4602 * off of irq context.
4603 * Note, that this is called and return with irqs disabled. This will
4604 * protect us against recursive calling from irq.
4606 asmlinkage
void __sched
preempt_schedule_irq(void)
4608 struct thread_info
*ti
= current_thread_info();
4609 struct task_struct
*task
= current
;
4610 int saved_lock_depth
;
4612 /* Catch callers which need to be fixed */
4613 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
4616 add_preempt_count(PREEMPT_ACTIVE
);
4619 * We keep the big kernel semaphore locked, but we
4620 * clear ->lock_depth so that schedule() doesnt
4621 * auto-release the semaphore:
4623 saved_lock_depth
= task
->lock_depth
;
4624 task
->lock_depth
= -1;
4627 local_irq_disable();
4628 task
->lock_depth
= saved_lock_depth
;
4629 sub_preempt_count(PREEMPT_ACTIVE
);
4632 * Check again in case we missed a preemption opportunity
4633 * between schedule and now.
4636 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4639 #endif /* CONFIG_PREEMPT */
4641 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
4644 return try_to_wake_up(curr
->private, mode
, sync
);
4646 EXPORT_SYMBOL(default_wake_function
);
4649 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4650 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4651 * number) then we wake all the non-exclusive tasks and one exclusive task.
4653 * There are circumstances in which we can try to wake a task which has already
4654 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4655 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4657 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
4658 int nr_exclusive
, int sync
, void *key
)
4660 wait_queue_t
*curr
, *next
;
4662 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
4663 unsigned flags
= curr
->flags
;
4665 if (curr
->func(curr
, mode
, sync
, key
) &&
4666 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4672 * __wake_up - wake up threads blocked on a waitqueue.
4674 * @mode: which threads
4675 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4676 * @key: is directly passed to the wakeup function
4678 void __wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4679 int nr_exclusive
, void *key
)
4681 unsigned long flags
;
4683 spin_lock_irqsave(&q
->lock
, flags
);
4684 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4685 spin_unlock_irqrestore(&q
->lock
, flags
);
4687 EXPORT_SYMBOL(__wake_up
);
4690 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4692 void __wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4694 __wake_up_common(q
, mode
, 1, 0, NULL
);
4698 * __wake_up_sync - wake up threads blocked on a waitqueue.
4700 * @mode: which threads
4701 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4703 * The sync wakeup differs that the waker knows that it will schedule
4704 * away soon, so while the target thread will be woken up, it will not
4705 * be migrated to another CPU - ie. the two threads are 'synchronized'
4706 * with each other. This can prevent needless bouncing between CPUs.
4708 * On UP it can prevent extra preemption.
4711 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4713 unsigned long flags
;
4719 if (unlikely(!nr_exclusive
))
4722 spin_lock_irqsave(&q
->lock
, flags
);
4723 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4724 spin_unlock_irqrestore(&q
->lock
, flags
);
4726 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4728 void complete(struct completion
*x
)
4730 unsigned long flags
;
4732 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4734 __wake_up_common(&x
->wait
, TASK_NORMAL
, 1, 0, NULL
);
4735 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4737 EXPORT_SYMBOL(complete
);
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 ((state
== TASK_INTERRUPTIBLE
&&
4760 signal_pending(current
)) ||
4761 (state
== TASK_KILLABLE
&&
4762 fatal_signal_pending(current
))) {
4763 __remove_wait_queue(&x
->wait
, &wait
);
4764 return -ERESTARTSYS
;
4766 __set_current_state(state
);
4767 spin_unlock_irq(&x
->wait
.lock
);
4768 timeout
= schedule_timeout(timeout
);
4769 spin_lock_irq(&x
->wait
.lock
);
4771 __remove_wait_queue(&x
->wait
, &wait
);
4775 __remove_wait_queue(&x
->wait
, &wait
);
4782 wait_for_common(struct completion
*x
, long timeout
, int state
)
4786 spin_lock_irq(&x
->wait
.lock
);
4787 timeout
= do_wait_for_common(x
, timeout
, state
);
4788 spin_unlock_irq(&x
->wait
.lock
);
4792 void __sched
wait_for_completion(struct completion
*x
)
4794 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4796 EXPORT_SYMBOL(wait_for_completion
);
4798 unsigned long __sched
4799 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4801 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4803 EXPORT_SYMBOL(wait_for_completion_timeout
);
4805 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4807 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4808 if (t
== -ERESTARTSYS
)
4812 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4814 unsigned long __sched
4815 wait_for_completion_interruptible_timeout(struct completion
*x
,
4816 unsigned long timeout
)
4818 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4820 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4822 int __sched
wait_for_completion_killable(struct completion
*x
)
4824 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_KILLABLE
);
4825 if (t
== -ERESTARTSYS
)
4829 EXPORT_SYMBOL(wait_for_completion_killable
);
4832 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4834 unsigned long flags
;
4837 init_waitqueue_entry(&wait
, current
);
4839 __set_current_state(state
);
4841 spin_lock_irqsave(&q
->lock
, flags
);
4842 __add_wait_queue(q
, &wait
);
4843 spin_unlock(&q
->lock
);
4844 timeout
= schedule_timeout(timeout
);
4845 spin_lock_irq(&q
->lock
);
4846 __remove_wait_queue(q
, &wait
);
4847 spin_unlock_irqrestore(&q
->lock
, flags
);
4852 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4854 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4856 EXPORT_SYMBOL(interruptible_sleep_on
);
4859 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4861 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4863 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4865 void __sched
sleep_on(wait_queue_head_t
*q
)
4867 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4869 EXPORT_SYMBOL(sleep_on
);
4871 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4873 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4875 EXPORT_SYMBOL(sleep_on_timeout
);
4877 #ifdef CONFIG_RT_MUTEXES
4880 * rt_mutex_setprio - set the current priority of a task
4882 * @prio: prio value (kernel-internal form)
4884 * This function changes the 'effective' priority of a task. It does
4885 * not touch ->normal_prio like __setscheduler().
4887 * Used by the rt_mutex code to implement priority inheritance logic.
4889 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4891 unsigned long flags
;
4892 int oldprio
, on_rq
, running
;
4894 const struct sched_class
*prev_class
= p
->sched_class
;
4896 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4898 rq
= task_rq_lock(p
, &flags
);
4899 update_rq_clock(rq
);
4902 on_rq
= p
->se
.on_rq
;
4903 running
= task_current(rq
, p
);
4905 dequeue_task(rq
, p
, 0);
4907 p
->sched_class
->put_prev_task(rq
, p
);
4910 p
->sched_class
= &rt_sched_class
;
4912 p
->sched_class
= &fair_sched_class
;
4917 p
->sched_class
->set_curr_task(rq
);
4919 enqueue_task(rq
, p
, 0);
4921 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4923 task_rq_unlock(rq
, &flags
);
4928 void set_user_nice(struct task_struct
*p
, long nice
)
4930 int old_prio
, delta
, on_rq
;
4931 unsigned long flags
;
4934 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
4937 * We have to be careful, if called from sys_setpriority(),
4938 * the task might be in the middle of scheduling on another CPU.
4940 rq
= task_rq_lock(p
, &flags
);
4941 update_rq_clock(rq
);
4943 * The RT priorities are set via sched_setscheduler(), but we still
4944 * allow the 'normal' nice value to be set - but as expected
4945 * it wont have any effect on scheduling until the task is
4946 * SCHED_FIFO/SCHED_RR:
4948 if (task_has_rt_policy(p
)) {
4949 p
->static_prio
= NICE_TO_PRIO(nice
);
4952 on_rq
= p
->se
.on_rq
;
4954 dequeue_task(rq
, p
, 0);
4956 p
->static_prio
= NICE_TO_PRIO(nice
);
4959 p
->prio
= effective_prio(p
);
4960 delta
= p
->prio
- old_prio
;
4963 enqueue_task(rq
, p
, 0);
4965 * If the task increased its priority or is running and
4966 * lowered its priority, then reschedule its CPU:
4968 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
4969 resched_task(rq
->curr
);
4972 task_rq_unlock(rq
, &flags
);
4974 EXPORT_SYMBOL(set_user_nice
);
4977 * can_nice - check if a task can reduce its nice value
4981 int can_nice(const struct task_struct
*p
, const int nice
)
4983 /* convert nice value [19,-20] to rlimit style value [1,40] */
4984 int nice_rlim
= 20 - nice
;
4986 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
4987 capable(CAP_SYS_NICE
));
4990 #ifdef __ARCH_WANT_SYS_NICE
4993 * sys_nice - change the priority of the current process.
4994 * @increment: priority increment
4996 * sys_setpriority is a more generic, but much slower function that
4997 * does similar things.
4999 asmlinkage
long sys_nice(int increment
)
5004 * Setpriority might change our priority at the same moment.
5005 * We don't have to worry. Conceptually one call occurs first
5006 * and we have a single winner.
5008 if (increment
< -40)
5013 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
5019 if (increment
< 0 && !can_nice(current
, nice
))
5022 retval
= security_task_setnice(current
, nice
);
5026 set_user_nice(current
, nice
);
5033 * task_prio - return the priority value of a given task.
5034 * @p: the task in question.
5036 * This is the priority value as seen by users in /proc.
5037 * RT tasks are offset by -200. Normal tasks are centered
5038 * around 0, value goes from -16 to +15.
5040 int task_prio(const struct task_struct
*p
)
5042 return p
->prio
- MAX_RT_PRIO
;
5046 * task_nice - return the nice value of a given task.
5047 * @p: the task in question.
5049 int task_nice(const struct task_struct
*p
)
5051 return TASK_NICE(p
);
5053 EXPORT_SYMBOL(task_nice
);
5056 * idle_cpu - is a given cpu idle currently?
5057 * @cpu: the processor in question.
5059 int idle_cpu(int cpu
)
5061 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
5065 * idle_task - return the idle task for a given cpu.
5066 * @cpu: the processor in question.
5068 struct task_struct
*idle_task(int cpu
)
5070 return cpu_rq(cpu
)->idle
;
5074 * find_process_by_pid - find a process with a matching PID value.
5075 * @pid: the pid in question.
5077 static struct task_struct
*find_process_by_pid(pid_t pid
)
5079 return pid
? find_task_by_vpid(pid
) : current
;
5082 /* Actually do priority change: must hold rq lock. */
5084 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
5086 BUG_ON(p
->se
.on_rq
);
5089 switch (p
->policy
) {
5093 p
->sched_class
= &fair_sched_class
;
5097 p
->sched_class
= &rt_sched_class
;
5101 p
->rt_priority
= prio
;
5102 p
->normal_prio
= normal_prio(p
);
5103 /* we are holding p->pi_lock already */
5104 p
->prio
= rt_mutex_getprio(p
);
5109 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5110 * @p: the task in question.
5111 * @policy: new policy.
5112 * @param: structure containing the new RT priority.
5114 * NOTE that the task may be already dead.
5116 int sched_setscheduler(struct task_struct
*p
, int policy
,
5117 struct sched_param
*param
)
5119 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
5120 unsigned long flags
;
5121 const struct sched_class
*prev_class
= p
->sched_class
;
5124 /* may grab non-irq protected spin_locks */
5125 BUG_ON(in_interrupt());
5127 /* double check policy once rq lock held */
5129 policy
= oldpolicy
= p
->policy
;
5130 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
5131 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
5132 policy
!= SCHED_IDLE
)
5135 * Valid priorities for SCHED_FIFO and SCHED_RR are
5136 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5137 * SCHED_BATCH and SCHED_IDLE is 0.
5139 if (param
->sched_priority
< 0 ||
5140 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
5141 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
5143 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
5147 * Allow unprivileged RT tasks to decrease priority:
5149 if (!capable(CAP_SYS_NICE
)) {
5150 if (rt_policy(policy
)) {
5151 unsigned long rlim_rtprio
;
5153 if (!lock_task_sighand(p
, &flags
))
5155 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
5156 unlock_task_sighand(p
, &flags
);
5158 /* can't set/change the rt policy */
5159 if (policy
!= p
->policy
&& !rlim_rtprio
)
5162 /* can't increase priority */
5163 if (param
->sched_priority
> p
->rt_priority
&&
5164 param
->sched_priority
> rlim_rtprio
)
5168 * Like positive nice levels, dont allow tasks to
5169 * move out of SCHED_IDLE either:
5171 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
5174 /* can't change other user's priorities */
5175 if ((current
->euid
!= p
->euid
) &&
5176 (current
->euid
!= p
->uid
))
5180 #ifdef CONFIG_RT_GROUP_SCHED
5182 * Do not allow realtime tasks into groups that have no runtime
5185 if (rt_policy(policy
) && task_group(p
)->rt_bandwidth
.rt_runtime
== 0)
5189 retval
= security_task_setscheduler(p
, policy
, param
);
5193 * make sure no PI-waiters arrive (or leave) while we are
5194 * changing the priority of the task:
5196 spin_lock_irqsave(&p
->pi_lock
, flags
);
5198 * To be able to change p->policy safely, the apropriate
5199 * runqueue lock must be held.
5201 rq
= __task_rq_lock(p
);
5202 /* recheck policy now with rq lock held */
5203 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
5204 policy
= oldpolicy
= -1;
5205 __task_rq_unlock(rq
);
5206 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
5209 update_rq_clock(rq
);
5210 on_rq
= p
->se
.on_rq
;
5211 running
= task_current(rq
, p
);
5213 deactivate_task(rq
, p
, 0);
5215 p
->sched_class
->put_prev_task(rq
, p
);
5218 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
5221 p
->sched_class
->set_curr_task(rq
);
5223 activate_task(rq
, p
, 0);
5225 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
5227 __task_rq_unlock(rq
);
5228 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
5230 rt_mutex_adjust_pi(p
);
5234 EXPORT_SYMBOL_GPL(sched_setscheduler
);
5237 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
5239 struct sched_param lparam
;
5240 struct task_struct
*p
;
5243 if (!param
|| pid
< 0)
5245 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
5250 p
= find_process_by_pid(pid
);
5252 retval
= sched_setscheduler(p
, policy
, &lparam
);
5259 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5260 * @pid: the pid in question.
5261 * @policy: new policy.
5262 * @param: structure containing the new RT priority.
5265 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
5267 /* negative values for policy are not valid */
5271 return do_sched_setscheduler(pid
, policy
, param
);
5275 * sys_sched_setparam - set/change the RT priority of a thread
5276 * @pid: the pid in question.
5277 * @param: structure containing the new RT priority.
5279 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
5281 return do_sched_setscheduler(pid
, -1, param
);
5285 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5286 * @pid: the pid in question.
5288 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
5290 struct task_struct
*p
;
5297 read_lock(&tasklist_lock
);
5298 p
= find_process_by_pid(pid
);
5300 retval
= security_task_getscheduler(p
);
5304 read_unlock(&tasklist_lock
);
5309 * sys_sched_getscheduler - get the RT priority of a thread
5310 * @pid: the pid in question.
5311 * @param: structure containing the RT priority.
5313 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
5315 struct sched_param lp
;
5316 struct task_struct
*p
;
5319 if (!param
|| pid
< 0)
5322 read_lock(&tasklist_lock
);
5323 p
= find_process_by_pid(pid
);
5328 retval
= security_task_getscheduler(p
);
5332 lp
.sched_priority
= p
->rt_priority
;
5333 read_unlock(&tasklist_lock
);
5336 * This one might sleep, we cannot do it with a spinlock held ...
5338 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
5343 read_unlock(&tasklist_lock
);
5347 long sched_setaffinity(pid_t pid
, const cpumask_t
*in_mask
)
5349 cpumask_t cpus_allowed
;
5350 cpumask_t new_mask
= *in_mask
;
5351 struct task_struct
*p
;
5355 read_lock(&tasklist_lock
);
5357 p
= find_process_by_pid(pid
);
5359 read_unlock(&tasklist_lock
);
5365 * It is not safe to call set_cpus_allowed with the
5366 * tasklist_lock held. We will bump the task_struct's
5367 * usage count and then drop tasklist_lock.
5370 read_unlock(&tasklist_lock
);
5373 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
5374 !capable(CAP_SYS_NICE
))
5377 retval
= security_task_setscheduler(p
, 0, NULL
);
5381 cpuset_cpus_allowed(p
, &cpus_allowed
);
5382 cpus_and(new_mask
, new_mask
, cpus_allowed
);
5384 retval
= set_cpus_allowed_ptr(p
, &new_mask
);
5387 cpuset_cpus_allowed(p
, &cpus_allowed
);
5388 if (!cpus_subset(new_mask
, cpus_allowed
)) {
5390 * We must have raced with a concurrent cpuset
5391 * update. Just reset the cpus_allowed to the
5392 * cpuset's cpus_allowed
5394 new_mask
= cpus_allowed
;
5404 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
5405 cpumask_t
*new_mask
)
5407 if (len
< sizeof(cpumask_t
)) {
5408 memset(new_mask
, 0, sizeof(cpumask_t
));
5409 } else if (len
> sizeof(cpumask_t
)) {
5410 len
= sizeof(cpumask_t
);
5412 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
5416 * sys_sched_setaffinity - set the cpu affinity of a process
5417 * @pid: pid of the process
5418 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5419 * @user_mask_ptr: user-space pointer to the new cpu mask
5421 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
5422 unsigned long __user
*user_mask_ptr
)
5427 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
5431 return sched_setaffinity(pid
, &new_mask
);
5435 * Represents all cpu's present in the system
5436 * In systems capable of hotplug, this map could dynamically grow
5437 * as new cpu's are detected in the system via any platform specific
5438 * method, such as ACPI for e.g.
5441 cpumask_t cpu_present_map __read_mostly
;
5442 EXPORT_SYMBOL(cpu_present_map
);
5445 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
5446 EXPORT_SYMBOL(cpu_online_map
);
5448 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
5449 EXPORT_SYMBOL(cpu_possible_map
);
5452 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
5454 struct task_struct
*p
;
5458 read_lock(&tasklist_lock
);
5461 p
= find_process_by_pid(pid
);
5465 retval
= security_task_getscheduler(p
);
5469 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
5472 read_unlock(&tasklist_lock
);
5479 * sys_sched_getaffinity - get the cpu affinity of a process
5480 * @pid: pid of the process
5481 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5482 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5484 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
5485 unsigned long __user
*user_mask_ptr
)
5490 if (len
< sizeof(cpumask_t
))
5493 ret
= sched_getaffinity(pid
, &mask
);
5497 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
5500 return sizeof(cpumask_t
);
5504 * sys_sched_yield - yield the current processor to other threads.
5506 * This function yields the current CPU to other tasks. If there are no
5507 * other threads running on this CPU then this function will return.
5509 asmlinkage
long sys_sched_yield(void)
5511 struct rq
*rq
= this_rq_lock();
5513 schedstat_inc(rq
, yld_count
);
5514 current
->sched_class
->yield_task(rq
);
5517 * Since we are going to call schedule() anyway, there's
5518 * no need to preempt or enable interrupts:
5520 __release(rq
->lock
);
5521 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
5522 _raw_spin_unlock(&rq
->lock
);
5523 preempt_enable_no_resched();
5530 static void __cond_resched(void)
5532 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5533 __might_sleep(__FILE__
, __LINE__
);
5536 * The BKS might be reacquired before we have dropped
5537 * PREEMPT_ACTIVE, which could trigger a second
5538 * cond_resched() call.
5541 add_preempt_count(PREEMPT_ACTIVE
);
5543 sub_preempt_count(PREEMPT_ACTIVE
);
5544 } while (need_resched());
5547 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5548 int __sched
_cond_resched(void)
5550 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
5551 system_state
== SYSTEM_RUNNING
) {
5557 EXPORT_SYMBOL(_cond_resched
);
5561 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5562 * call schedule, and on return reacquire the lock.
5564 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5565 * operations here to prevent schedule() from being called twice (once via
5566 * spin_unlock(), once by hand).
5568 int cond_resched_lock(spinlock_t
*lock
)
5570 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
5573 if (spin_needbreak(lock
) || resched
) {
5575 if (resched
&& need_resched())
5584 EXPORT_SYMBOL(cond_resched_lock
);
5586 int __sched
cond_resched_softirq(void)
5588 BUG_ON(!in_softirq());
5590 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
5598 EXPORT_SYMBOL(cond_resched_softirq
);
5601 * yield - yield the current processor to other threads.
5603 * This is a shortcut for kernel-space yielding - it marks the
5604 * thread runnable and calls sys_sched_yield().
5606 void __sched
yield(void)
5608 set_current_state(TASK_RUNNING
);
5611 EXPORT_SYMBOL(yield
);
5614 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5615 * that process accounting knows that this is a task in IO wait state.
5617 * But don't do that if it is a deliberate, throttling IO wait (this task
5618 * has set its backing_dev_info: the queue against which it should throttle)
5620 void __sched
io_schedule(void)
5622 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5624 delayacct_blkio_start();
5625 atomic_inc(&rq
->nr_iowait
);
5627 atomic_dec(&rq
->nr_iowait
);
5628 delayacct_blkio_end();
5630 EXPORT_SYMBOL(io_schedule
);
5632 long __sched
io_schedule_timeout(long timeout
)
5634 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5637 delayacct_blkio_start();
5638 atomic_inc(&rq
->nr_iowait
);
5639 ret
= schedule_timeout(timeout
);
5640 atomic_dec(&rq
->nr_iowait
);
5641 delayacct_blkio_end();
5646 * sys_sched_get_priority_max - return maximum RT priority.
5647 * @policy: scheduling class.
5649 * this syscall returns the maximum rt_priority that can be used
5650 * by a given scheduling class.
5652 asmlinkage
long sys_sched_get_priority_max(int policy
)
5659 ret
= MAX_USER_RT_PRIO
-1;
5671 * sys_sched_get_priority_min - return minimum RT priority.
5672 * @policy: scheduling class.
5674 * this syscall returns the minimum rt_priority that can be used
5675 * by a given scheduling class.
5677 asmlinkage
long sys_sched_get_priority_min(int policy
)
5695 * sys_sched_rr_get_interval - return the default timeslice of a process.
5696 * @pid: pid of the process.
5697 * @interval: userspace pointer to the timeslice value.
5699 * this syscall writes the default timeslice value of a given process
5700 * into the user-space timespec buffer. A value of '0' means infinity.
5703 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5705 struct task_struct
*p
;
5706 unsigned int time_slice
;
5714 read_lock(&tasklist_lock
);
5715 p
= find_process_by_pid(pid
);
5719 retval
= security_task_getscheduler(p
);
5724 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5725 * tasks that are on an otherwise idle runqueue:
5728 if (p
->policy
== SCHED_RR
) {
5729 time_slice
= DEF_TIMESLICE
;
5730 } else if (p
->policy
!= SCHED_FIFO
) {
5731 struct sched_entity
*se
= &p
->se
;
5732 unsigned long flags
;
5735 rq
= task_rq_lock(p
, &flags
);
5736 if (rq
->cfs
.load
.weight
)
5737 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5738 task_rq_unlock(rq
, &flags
);
5740 read_unlock(&tasklist_lock
);
5741 jiffies_to_timespec(time_slice
, &t
);
5742 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5746 read_unlock(&tasklist_lock
);
5750 static const char stat_nam
[] = "RSDTtZX";
5752 void sched_show_task(struct task_struct
*p
)
5754 unsigned long free
= 0;
5757 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5758 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5759 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5760 #if BITS_PER_LONG == 32
5761 if (state
== TASK_RUNNING
)
5762 printk(KERN_CONT
" running ");
5764 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5766 if (state
== TASK_RUNNING
)
5767 printk(KERN_CONT
" running task ");
5769 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5771 #ifdef CONFIG_DEBUG_STACK_USAGE
5773 unsigned long *n
= end_of_stack(p
);
5776 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5779 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5780 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5782 show_stack(p
, NULL
);
5785 void show_state_filter(unsigned long state_filter
)
5787 struct task_struct
*g
, *p
;
5789 #if BITS_PER_LONG == 32
5791 " task PC stack pid father\n");
5794 " task PC stack pid father\n");
5796 read_lock(&tasklist_lock
);
5797 do_each_thread(g
, p
) {
5799 * reset the NMI-timeout, listing all files on a slow
5800 * console might take alot of time:
5802 touch_nmi_watchdog();
5803 if (!state_filter
|| (p
->state
& state_filter
))
5805 } while_each_thread(g
, p
);
5807 touch_all_softlockup_watchdogs();
5809 #ifdef CONFIG_SCHED_DEBUG
5810 sysrq_sched_debug_show();
5812 read_unlock(&tasklist_lock
);
5814 * Only show locks if all tasks are dumped:
5816 if (state_filter
== -1)
5817 debug_show_all_locks();
5820 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5822 idle
->sched_class
= &idle_sched_class
;
5826 * init_idle - set up an idle thread for a given CPU
5827 * @idle: task in question
5828 * @cpu: cpu the idle task belongs to
5830 * NOTE: this function does not set the idle thread's NEED_RESCHED
5831 * flag, to make booting more robust.
5833 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5835 struct rq
*rq
= cpu_rq(cpu
);
5836 unsigned long flags
;
5839 idle
->se
.exec_start
= sched_clock();
5841 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5842 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
5843 __set_task_cpu(idle
, cpu
);
5845 spin_lock_irqsave(&rq
->lock
, flags
);
5846 rq
->curr
= rq
->idle
= idle
;
5847 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5850 spin_unlock_irqrestore(&rq
->lock
, flags
);
5852 /* Set the preempt count _outside_ the spinlocks! */
5853 task_thread_info(idle
)->preempt_count
= 0;
5856 * The idle tasks have their own, simple scheduling class:
5858 idle
->sched_class
= &idle_sched_class
;
5862 * In a system that switches off the HZ timer nohz_cpu_mask
5863 * indicates which cpus entered this state. This is used
5864 * in the rcu update to wait only for active cpus. For system
5865 * which do not switch off the HZ timer nohz_cpu_mask should
5866 * always be CPU_MASK_NONE.
5868 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
5871 * Increase the granularity value when there are more CPUs,
5872 * because with more CPUs the 'effective latency' as visible
5873 * to users decreases. But the relationship is not linear,
5874 * so pick a second-best guess by going with the log2 of the
5877 * This idea comes from the SD scheduler of Con Kolivas:
5879 static inline void sched_init_granularity(void)
5881 unsigned int factor
= 1 + ilog2(num_online_cpus());
5882 const unsigned long limit
= 200000000;
5884 sysctl_sched_min_granularity
*= factor
;
5885 if (sysctl_sched_min_granularity
> limit
)
5886 sysctl_sched_min_granularity
= limit
;
5888 sysctl_sched_latency
*= factor
;
5889 if (sysctl_sched_latency
> limit
)
5890 sysctl_sched_latency
= limit
;
5892 sysctl_sched_wakeup_granularity
*= factor
;
5897 * This is how migration works:
5899 * 1) we queue a struct migration_req structure in the source CPU's
5900 * runqueue and wake up that CPU's migration thread.
5901 * 2) we down() the locked semaphore => thread blocks.
5902 * 3) migration thread wakes up (implicitly it forces the migrated
5903 * thread off the CPU)
5904 * 4) it gets the migration request and checks whether the migrated
5905 * task is still in the wrong runqueue.
5906 * 5) if it's in the wrong runqueue then the migration thread removes
5907 * it and puts it into the right queue.
5908 * 6) migration thread up()s the semaphore.
5909 * 7) we wake up and the migration is done.
5913 * Change a given task's CPU affinity. Migrate the thread to a
5914 * proper CPU and schedule it away if the CPU it's executing on
5915 * is removed from the allowed bitmask.
5917 * NOTE: the caller must have a valid reference to the task, the
5918 * task must not exit() & deallocate itself prematurely. The
5919 * call is not atomic; no spinlocks may be held.
5921 int set_cpus_allowed_ptr(struct task_struct
*p
, const cpumask_t
*new_mask
)
5923 struct migration_req req
;
5924 unsigned long flags
;
5928 rq
= task_rq_lock(p
, &flags
);
5929 if (!cpus_intersects(*new_mask
, cpu_online_map
)) {
5934 if (p
->sched_class
->set_cpus_allowed
)
5935 p
->sched_class
->set_cpus_allowed(p
, new_mask
);
5937 p
->cpus_allowed
= *new_mask
;
5938 p
->rt
.nr_cpus_allowed
= cpus_weight(*new_mask
);
5941 /* Can the task run on the task's current CPU? If so, we're done */
5942 if (cpu_isset(task_cpu(p
), *new_mask
))
5945 if (migrate_task(p
, any_online_cpu(*new_mask
), &req
)) {
5946 /* Need help from migration thread: drop lock and wait. */
5947 task_rq_unlock(rq
, &flags
);
5948 wake_up_process(rq
->migration_thread
);
5949 wait_for_completion(&req
.done
);
5950 tlb_migrate_finish(p
->mm
);
5954 task_rq_unlock(rq
, &flags
);
5958 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr
);
5961 * Move (not current) task off this cpu, onto dest cpu. We're doing
5962 * this because either it can't run here any more (set_cpus_allowed()
5963 * away from this CPU, or CPU going down), or because we're
5964 * attempting to rebalance this task on exec (sched_exec).
5966 * So we race with normal scheduler movements, but that's OK, as long
5967 * as the task is no longer on this CPU.
5969 * Returns non-zero if task was successfully migrated.
5971 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5973 struct rq
*rq_dest
, *rq_src
;
5976 if (unlikely(cpu_is_offline(dest_cpu
)))
5979 rq_src
= cpu_rq(src_cpu
);
5980 rq_dest
= cpu_rq(dest_cpu
);
5982 double_rq_lock(rq_src
, rq_dest
);
5983 /* Already moved. */
5984 if (task_cpu(p
) != src_cpu
)
5986 /* Affinity changed (again). */
5987 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
5990 on_rq
= p
->se
.on_rq
;
5992 deactivate_task(rq_src
, p
, 0);
5994 set_task_cpu(p
, dest_cpu
);
5996 activate_task(rq_dest
, p
, 0);
5997 check_preempt_curr(rq_dest
, p
);
6001 double_rq_unlock(rq_src
, rq_dest
);
6006 * migration_thread - this is a highprio system thread that performs
6007 * thread migration by bumping thread off CPU then 'pushing' onto
6010 static int migration_thread(void *data
)
6012 int cpu
= (long)data
;
6016 BUG_ON(rq
->migration_thread
!= current
);
6018 set_current_state(TASK_INTERRUPTIBLE
);
6019 while (!kthread_should_stop()) {
6020 struct migration_req
*req
;
6021 struct list_head
*head
;
6023 spin_lock_irq(&rq
->lock
);
6025 if (cpu_is_offline(cpu
)) {
6026 spin_unlock_irq(&rq
->lock
);
6030 if (rq
->active_balance
) {
6031 active_load_balance(rq
, cpu
);
6032 rq
->active_balance
= 0;
6035 head
= &rq
->migration_queue
;
6037 if (list_empty(head
)) {
6038 spin_unlock_irq(&rq
->lock
);
6040 set_current_state(TASK_INTERRUPTIBLE
);
6043 req
= list_entry(head
->next
, struct migration_req
, list
);
6044 list_del_init(head
->next
);
6046 spin_unlock(&rq
->lock
);
6047 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
6050 complete(&req
->done
);
6052 __set_current_state(TASK_RUNNING
);
6056 /* Wait for kthread_stop */
6057 set_current_state(TASK_INTERRUPTIBLE
);
6058 while (!kthread_should_stop()) {
6060 set_current_state(TASK_INTERRUPTIBLE
);
6062 __set_current_state(TASK_RUNNING
);
6066 #ifdef CONFIG_HOTPLUG_CPU
6068 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
6072 local_irq_disable();
6073 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
6079 * Figure out where task on dead CPU should go, use force if necessary.
6080 * NOTE: interrupts should be disabled by the caller
6082 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
6084 unsigned long flags
;
6091 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
6092 cpus_and(mask
, mask
, p
->cpus_allowed
);
6093 dest_cpu
= any_online_cpu(mask
);
6095 /* On any allowed CPU? */
6096 if (dest_cpu
>= nr_cpu_ids
)
6097 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
6099 /* No more Mr. Nice Guy. */
6100 if (dest_cpu
>= nr_cpu_ids
) {
6101 cpumask_t cpus_allowed
;
6103 cpuset_cpus_allowed_locked(p
, &cpus_allowed
);
6105 * Try to stay on the same cpuset, where the
6106 * current cpuset may be a subset of all cpus.
6107 * The cpuset_cpus_allowed_locked() variant of
6108 * cpuset_cpus_allowed() will not block. It must be
6109 * called within calls to cpuset_lock/cpuset_unlock.
6111 rq
= task_rq_lock(p
, &flags
);
6112 p
->cpus_allowed
= cpus_allowed
;
6113 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
6114 task_rq_unlock(rq
, &flags
);
6117 * Don't tell them about moving exiting tasks or
6118 * kernel threads (both mm NULL), since they never
6121 if (p
->mm
&& printk_ratelimit()) {
6122 printk(KERN_INFO
"process %d (%s) no "
6123 "longer affine to cpu%d\n",
6124 task_pid_nr(p
), p
->comm
, dead_cpu
);
6127 } while (!__migrate_task_irq(p
, dead_cpu
, dest_cpu
));
6131 * While a dead CPU has no uninterruptible tasks queued at this point,
6132 * it might still have a nonzero ->nr_uninterruptible counter, because
6133 * for performance reasons the counter is not stricly tracking tasks to
6134 * their home CPUs. So we just add the counter to another CPU's counter,
6135 * to keep the global sum constant after CPU-down:
6137 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
6139 struct rq
*rq_dest
= cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR
));
6140 unsigned long flags
;
6142 local_irq_save(flags
);
6143 double_rq_lock(rq_src
, rq_dest
);
6144 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
6145 rq_src
->nr_uninterruptible
= 0;
6146 double_rq_unlock(rq_src
, rq_dest
);
6147 local_irq_restore(flags
);
6150 /* Run through task list and migrate tasks from the dead cpu. */
6151 static void migrate_live_tasks(int src_cpu
)
6153 struct task_struct
*p
, *t
;
6155 read_lock(&tasklist_lock
);
6157 do_each_thread(t
, p
) {
6161 if (task_cpu(p
) == src_cpu
)
6162 move_task_off_dead_cpu(src_cpu
, p
);
6163 } while_each_thread(t
, p
);
6165 read_unlock(&tasklist_lock
);
6169 * Schedules idle task to be the next runnable task on current CPU.
6170 * It does so by boosting its priority to highest possible.
6171 * Used by CPU offline code.
6173 void sched_idle_next(void)
6175 int this_cpu
= smp_processor_id();
6176 struct rq
*rq
= cpu_rq(this_cpu
);
6177 struct task_struct
*p
= rq
->idle
;
6178 unsigned long flags
;
6180 /* cpu has to be offline */
6181 BUG_ON(cpu_online(this_cpu
));
6184 * Strictly not necessary since rest of the CPUs are stopped by now
6185 * and interrupts disabled on the current cpu.
6187 spin_lock_irqsave(&rq
->lock
, flags
);
6189 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
6191 update_rq_clock(rq
);
6192 activate_task(rq
, p
, 0);
6194 spin_unlock_irqrestore(&rq
->lock
, flags
);
6198 * Ensures that the idle task is using init_mm right before its cpu goes
6201 void idle_task_exit(void)
6203 struct mm_struct
*mm
= current
->active_mm
;
6205 BUG_ON(cpu_online(smp_processor_id()));
6208 switch_mm(mm
, &init_mm
, current
);
6212 /* called under rq->lock with disabled interrupts */
6213 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
6215 struct rq
*rq
= cpu_rq(dead_cpu
);
6217 /* Must be exiting, otherwise would be on tasklist. */
6218 BUG_ON(!p
->exit_state
);
6220 /* Cannot have done final schedule yet: would have vanished. */
6221 BUG_ON(p
->state
== TASK_DEAD
);
6226 * Drop lock around migration; if someone else moves it,
6227 * that's OK. No task can be added to this CPU, so iteration is
6230 spin_unlock_irq(&rq
->lock
);
6231 move_task_off_dead_cpu(dead_cpu
, p
);
6232 spin_lock_irq(&rq
->lock
);
6237 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6238 static void migrate_dead_tasks(unsigned int dead_cpu
)
6240 struct rq
*rq
= cpu_rq(dead_cpu
);
6241 struct task_struct
*next
;
6244 if (!rq
->nr_running
)
6246 update_rq_clock(rq
);
6247 next
= pick_next_task(rq
, rq
->curr
);
6250 migrate_dead(dead_cpu
, next
);
6254 #endif /* CONFIG_HOTPLUG_CPU */
6256 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6258 static struct ctl_table sd_ctl_dir
[] = {
6260 .procname
= "sched_domain",
6266 static struct ctl_table sd_ctl_root
[] = {
6268 .ctl_name
= CTL_KERN
,
6269 .procname
= "kernel",
6271 .child
= sd_ctl_dir
,
6276 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
6278 struct ctl_table
*entry
=
6279 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
6284 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
6286 struct ctl_table
*entry
;
6289 * In the intermediate directories, both the child directory and
6290 * procname are dynamically allocated and could fail but the mode
6291 * will always be set. In the lowest directory the names are
6292 * static strings and all have proc handlers.
6294 for (entry
= *tablep
; entry
->mode
; entry
++) {
6296 sd_free_ctl_entry(&entry
->child
);
6297 if (entry
->proc_handler
== NULL
)
6298 kfree(entry
->procname
);
6306 set_table_entry(struct ctl_table
*entry
,
6307 const char *procname
, void *data
, int maxlen
,
6308 mode_t mode
, proc_handler
*proc_handler
)
6310 entry
->procname
= procname
;
6312 entry
->maxlen
= maxlen
;
6314 entry
->proc_handler
= proc_handler
;
6317 static struct ctl_table
*
6318 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
6320 struct ctl_table
*table
= sd_alloc_ctl_entry(12);
6325 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
6326 sizeof(long), 0644, proc_doulongvec_minmax
);
6327 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
6328 sizeof(long), 0644, proc_doulongvec_minmax
);
6329 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
6330 sizeof(int), 0644, proc_dointvec_minmax
);
6331 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
6332 sizeof(int), 0644, proc_dointvec_minmax
);
6333 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
6334 sizeof(int), 0644, proc_dointvec_minmax
);
6335 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
6336 sizeof(int), 0644, proc_dointvec_minmax
);
6337 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
6338 sizeof(int), 0644, proc_dointvec_minmax
);
6339 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
6340 sizeof(int), 0644, proc_dointvec_minmax
);
6341 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
6342 sizeof(int), 0644, proc_dointvec_minmax
);
6343 set_table_entry(&table
[9], "cache_nice_tries",
6344 &sd
->cache_nice_tries
,
6345 sizeof(int), 0644, proc_dointvec_minmax
);
6346 set_table_entry(&table
[10], "flags", &sd
->flags
,
6347 sizeof(int), 0644, proc_dointvec_minmax
);
6348 /* &table[11] is terminator */
6353 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
6355 struct ctl_table
*entry
, *table
;
6356 struct sched_domain
*sd
;
6357 int domain_num
= 0, i
;
6360 for_each_domain(cpu
, sd
)
6362 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
6367 for_each_domain(cpu
, sd
) {
6368 snprintf(buf
, 32, "domain%d", i
);
6369 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
6371 entry
->child
= sd_alloc_ctl_domain_table(sd
);
6378 static struct ctl_table_header
*sd_sysctl_header
;
6379 static void register_sched_domain_sysctl(void)
6381 int i
, cpu_num
= num_online_cpus();
6382 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
6385 WARN_ON(sd_ctl_dir
[0].child
);
6386 sd_ctl_dir
[0].child
= entry
;
6391 for_each_online_cpu(i
) {
6392 snprintf(buf
, 32, "cpu%d", i
);
6393 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
6395 entry
->child
= sd_alloc_ctl_cpu_table(i
);
6399 WARN_ON(sd_sysctl_header
);
6400 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
6403 /* may be called multiple times per register */
6404 static void unregister_sched_domain_sysctl(void)
6406 if (sd_sysctl_header
)
6407 unregister_sysctl_table(sd_sysctl_header
);
6408 sd_sysctl_header
= NULL
;
6409 if (sd_ctl_dir
[0].child
)
6410 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
6413 static void register_sched_domain_sysctl(void)
6416 static void unregister_sched_domain_sysctl(void)
6422 * migration_call - callback that gets triggered when a CPU is added.
6423 * Here we can start up the necessary migration thread for the new CPU.
6425 static int __cpuinit
6426 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
6428 struct task_struct
*p
;
6429 int cpu
= (long)hcpu
;
6430 unsigned long flags
;
6435 case CPU_UP_PREPARE
:
6436 case CPU_UP_PREPARE_FROZEN
:
6437 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
6440 kthread_bind(p
, cpu
);
6441 /* Must be high prio: stop_machine expects to yield to it. */
6442 rq
= task_rq_lock(p
, &flags
);
6443 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
6444 task_rq_unlock(rq
, &flags
);
6445 cpu_rq(cpu
)->migration_thread
= p
;
6449 case CPU_ONLINE_FROZEN
:
6450 /* Strictly unnecessary, as first user will wake it. */
6451 wake_up_process(cpu_rq(cpu
)->migration_thread
);
6453 /* Update our root-domain */
6455 spin_lock_irqsave(&rq
->lock
, flags
);
6457 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
6458 cpu_set(cpu
, rq
->rd
->online
);
6460 spin_unlock_irqrestore(&rq
->lock
, flags
);
6463 #ifdef CONFIG_HOTPLUG_CPU
6464 case CPU_UP_CANCELED
:
6465 case CPU_UP_CANCELED_FROZEN
:
6466 if (!cpu_rq(cpu
)->migration_thread
)
6468 /* Unbind it from offline cpu so it can run. Fall thru. */
6469 kthread_bind(cpu_rq(cpu
)->migration_thread
,
6470 any_online_cpu(cpu_online_map
));
6471 kthread_stop(cpu_rq(cpu
)->migration_thread
);
6472 cpu_rq(cpu
)->migration_thread
= NULL
;
6476 case CPU_DEAD_FROZEN
:
6477 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6478 migrate_live_tasks(cpu
);
6480 kthread_stop(rq
->migration_thread
);
6481 rq
->migration_thread
= NULL
;
6482 /* Idle task back to normal (off runqueue, low prio) */
6483 spin_lock_irq(&rq
->lock
);
6484 update_rq_clock(rq
);
6485 deactivate_task(rq
, rq
->idle
, 0);
6486 rq
->idle
->static_prio
= MAX_PRIO
;
6487 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
6488 rq
->idle
->sched_class
= &idle_sched_class
;
6489 migrate_dead_tasks(cpu
);
6490 spin_unlock_irq(&rq
->lock
);
6492 migrate_nr_uninterruptible(rq
);
6493 BUG_ON(rq
->nr_running
!= 0);
6496 * No need to migrate the tasks: it was best-effort if
6497 * they didn't take sched_hotcpu_mutex. Just wake up
6500 spin_lock_irq(&rq
->lock
);
6501 while (!list_empty(&rq
->migration_queue
)) {
6502 struct migration_req
*req
;
6504 req
= list_entry(rq
->migration_queue
.next
,
6505 struct migration_req
, list
);
6506 list_del_init(&req
->list
);
6507 complete(&req
->done
);
6509 spin_unlock_irq(&rq
->lock
);
6513 case CPU_DYING_FROZEN
:
6514 /* Update our root-domain */
6516 spin_lock_irqsave(&rq
->lock
, flags
);
6518 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
6519 cpu_clear(cpu
, rq
->rd
->online
);
6521 spin_unlock_irqrestore(&rq
->lock
, flags
);
6528 /* Register at highest priority so that task migration (migrate_all_tasks)
6529 * happens before everything else.
6531 static struct notifier_block __cpuinitdata migration_notifier
= {
6532 .notifier_call
= migration_call
,
6536 void __init
migration_init(void)
6538 void *cpu
= (void *)(long)smp_processor_id();
6541 /* Start one for the boot CPU: */
6542 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
6543 BUG_ON(err
== NOTIFY_BAD
);
6544 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
6545 register_cpu_notifier(&migration_notifier
);
6551 #ifdef CONFIG_SCHED_DEBUG
6553 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
,
6554 cpumask_t
*groupmask
)
6556 struct sched_group
*group
= sd
->groups
;
6559 cpulist_scnprintf(str
, sizeof(str
), sd
->span
);
6560 cpus_clear(*groupmask
);
6562 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
6564 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
6565 printk("does not load-balance\n");
6567 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
6572 printk(KERN_CONT
"span %s\n", str
);
6574 if (!cpu_isset(cpu
, sd
->span
)) {
6575 printk(KERN_ERR
"ERROR: domain->span does not contain "
6578 if (!cpu_isset(cpu
, group
->cpumask
)) {
6579 printk(KERN_ERR
"ERROR: domain->groups does not contain"
6583 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
6587 printk(KERN_ERR
"ERROR: group is NULL\n");
6591 if (!group
->__cpu_power
) {
6592 printk(KERN_CONT
"\n");
6593 printk(KERN_ERR
"ERROR: domain->cpu_power not "
6598 if (!cpus_weight(group
->cpumask
)) {
6599 printk(KERN_CONT
"\n");
6600 printk(KERN_ERR
"ERROR: empty group\n");
6604 if (cpus_intersects(*groupmask
, group
->cpumask
)) {
6605 printk(KERN_CONT
"\n");
6606 printk(KERN_ERR
"ERROR: repeated CPUs\n");
6610 cpus_or(*groupmask
, *groupmask
, group
->cpumask
);
6612 cpulist_scnprintf(str
, sizeof(str
), group
->cpumask
);
6613 printk(KERN_CONT
" %s", str
);
6615 group
= group
->next
;
6616 } while (group
!= sd
->groups
);
6617 printk(KERN_CONT
"\n");
6619 if (!cpus_equal(sd
->span
, *groupmask
))
6620 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
6622 if (sd
->parent
&& !cpus_subset(*groupmask
, sd
->parent
->span
))
6623 printk(KERN_ERR
"ERROR: parent span is not a superset "
6624 "of domain->span\n");
6628 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
6630 cpumask_t
*groupmask
;
6634 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
6638 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
6640 groupmask
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
6642 printk(KERN_DEBUG
"Cannot load-balance (out of memory)\n");
6647 if (sched_domain_debug_one(sd
, cpu
, level
, groupmask
))
6657 # define sched_domain_debug(sd, cpu) do { } while (0)
6660 static int sd_degenerate(struct sched_domain
*sd
)
6662 if (cpus_weight(sd
->span
) == 1)
6665 /* Following flags need at least 2 groups */
6666 if (sd
->flags
& (SD_LOAD_BALANCE
|
6667 SD_BALANCE_NEWIDLE
|
6671 SD_SHARE_PKG_RESOURCES
)) {
6672 if (sd
->groups
!= sd
->groups
->next
)
6676 /* Following flags don't use groups */
6677 if (sd
->flags
& (SD_WAKE_IDLE
|
6686 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6688 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6690 if (sd_degenerate(parent
))
6693 if (!cpus_equal(sd
->span
, parent
->span
))
6696 /* Does parent contain flags not in child? */
6697 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6698 if (cflags
& SD_WAKE_AFFINE
)
6699 pflags
&= ~SD_WAKE_BALANCE
;
6700 /* Flags needing groups don't count if only 1 group in parent */
6701 if (parent
->groups
== parent
->groups
->next
) {
6702 pflags
&= ~(SD_LOAD_BALANCE
|
6703 SD_BALANCE_NEWIDLE
|
6707 SD_SHARE_PKG_RESOURCES
);
6709 if (~cflags
& pflags
)
6715 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6717 unsigned long flags
;
6718 const struct sched_class
*class;
6720 spin_lock_irqsave(&rq
->lock
, flags
);
6723 struct root_domain
*old_rd
= rq
->rd
;
6725 for (class = sched_class_highest
; class; class = class->next
) {
6726 if (class->leave_domain
)
6727 class->leave_domain(rq
);
6730 cpu_clear(rq
->cpu
, old_rd
->span
);
6731 cpu_clear(rq
->cpu
, old_rd
->online
);
6733 if (atomic_dec_and_test(&old_rd
->refcount
))
6737 atomic_inc(&rd
->refcount
);
6740 cpu_set(rq
->cpu
, rd
->span
);
6741 if (cpu_isset(rq
->cpu
, cpu_online_map
))
6742 cpu_set(rq
->cpu
, rd
->online
);
6744 for (class = sched_class_highest
; class; class = class->next
) {
6745 if (class->join_domain
)
6746 class->join_domain(rq
);
6749 spin_unlock_irqrestore(&rq
->lock
, flags
);
6752 static void init_rootdomain(struct root_domain
*rd
)
6754 memset(rd
, 0, sizeof(*rd
));
6756 cpus_clear(rd
->span
);
6757 cpus_clear(rd
->online
);
6760 static void init_defrootdomain(void)
6762 init_rootdomain(&def_root_domain
);
6763 atomic_set(&def_root_domain
.refcount
, 1);
6766 static struct root_domain
*alloc_rootdomain(void)
6768 struct root_domain
*rd
;
6770 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6774 init_rootdomain(rd
);
6780 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6781 * hold the hotplug lock.
6784 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6786 struct rq
*rq
= cpu_rq(cpu
);
6787 struct sched_domain
*tmp
;
6789 /* Remove the sched domains which do not contribute to scheduling. */
6790 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
6791 struct sched_domain
*parent
= tmp
->parent
;
6794 if (sd_parent_degenerate(tmp
, parent
)) {
6795 tmp
->parent
= parent
->parent
;
6797 parent
->parent
->child
= tmp
;
6801 if (sd
&& sd_degenerate(sd
)) {
6807 sched_domain_debug(sd
, cpu
);
6809 rq_attach_root(rq
, rd
);
6810 rcu_assign_pointer(rq
->sd
, sd
);
6813 /* cpus with isolated domains */
6814 static cpumask_t cpu_isolated_map
= CPU_MASK_NONE
;
6816 /* Setup the mask of cpus configured for isolated domains */
6817 static int __init
isolated_cpu_setup(char *str
)
6819 int ints
[NR_CPUS
], i
;
6821 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
6822 cpus_clear(cpu_isolated_map
);
6823 for (i
= 1; i
<= ints
[0]; i
++)
6824 if (ints
[i
] < NR_CPUS
)
6825 cpu_set(ints
[i
], cpu_isolated_map
);
6829 __setup("isolcpus=", isolated_cpu_setup
);
6832 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6833 * to a function which identifies what group(along with sched group) a CPU
6834 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6835 * (due to the fact that we keep track of groups covered with a cpumask_t).
6837 * init_sched_build_groups will build a circular linked list of the groups
6838 * covered by the given span, and will set each group's ->cpumask correctly,
6839 * and ->cpu_power to 0.
6842 init_sched_build_groups(const cpumask_t
*span
, const cpumask_t
*cpu_map
,
6843 int (*group_fn
)(int cpu
, const cpumask_t
*cpu_map
,
6844 struct sched_group
**sg
,
6845 cpumask_t
*tmpmask
),
6846 cpumask_t
*covered
, cpumask_t
*tmpmask
)
6848 struct sched_group
*first
= NULL
, *last
= NULL
;
6851 cpus_clear(*covered
);
6853 for_each_cpu_mask(i
, *span
) {
6854 struct sched_group
*sg
;
6855 int group
= group_fn(i
, cpu_map
, &sg
, tmpmask
);
6858 if (cpu_isset(i
, *covered
))
6861 cpus_clear(sg
->cpumask
);
6862 sg
->__cpu_power
= 0;
6864 for_each_cpu_mask(j
, *span
) {
6865 if (group_fn(j
, cpu_map
, NULL
, tmpmask
) != group
)
6868 cpu_set(j
, *covered
);
6869 cpu_set(j
, sg
->cpumask
);
6880 #define SD_NODES_PER_DOMAIN 16
6885 * find_next_best_node - find the next node to include in a sched_domain
6886 * @node: node whose sched_domain we're building
6887 * @used_nodes: nodes already in the sched_domain
6889 * Find the next node to include in a given scheduling domain. Simply
6890 * finds the closest node not already in the @used_nodes map.
6892 * Should use nodemask_t.
6894 static int find_next_best_node(int node
, nodemask_t
*used_nodes
)
6896 int i
, n
, val
, min_val
, best_node
= 0;
6900 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6901 /* Start at @node */
6902 n
= (node
+ i
) % MAX_NUMNODES
;
6904 if (!nr_cpus_node(n
))
6907 /* Skip already used nodes */
6908 if (node_isset(n
, *used_nodes
))
6911 /* Simple min distance search */
6912 val
= node_distance(node
, n
);
6914 if (val
< min_val
) {
6920 node_set(best_node
, *used_nodes
);
6925 * sched_domain_node_span - get a cpumask for a node's sched_domain
6926 * @node: node whose cpumask we're constructing
6928 * Given a node, construct a good cpumask for its sched_domain to span. It
6929 * should be one that prevents unnecessary balancing, but also spreads tasks
6932 static void sched_domain_node_span(int node
, cpumask_t
*span
)
6934 nodemask_t used_nodes
;
6935 node_to_cpumask_ptr(nodemask
, node
);
6939 nodes_clear(used_nodes
);
6941 cpus_or(*span
, *span
, *nodemask
);
6942 node_set(node
, used_nodes
);
6944 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
6945 int next_node
= find_next_best_node(node
, &used_nodes
);
6947 node_to_cpumask_ptr_next(nodemask
, next_node
);
6948 cpus_or(*span
, *span
, *nodemask
);
6953 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
6956 * SMT sched-domains:
6958 #ifdef CONFIG_SCHED_SMT
6959 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6960 static DEFINE_PER_CPU(struct sched_group
, sched_group_cpus
);
6963 cpu_to_cpu_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
6967 *sg
= &per_cpu(sched_group_cpus
, cpu
);
6973 * multi-core sched-domains:
6975 #ifdef CONFIG_SCHED_MC
6976 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6977 static DEFINE_PER_CPU(struct sched_group
, sched_group_core
);
6980 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6982 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
6987 *mask
= per_cpu(cpu_sibling_map
, cpu
);
6988 cpus_and(*mask
, *mask
, *cpu_map
);
6989 group
= first_cpu(*mask
);
6991 *sg
= &per_cpu(sched_group_core
, group
);
6994 #elif defined(CONFIG_SCHED_MC)
6996 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
7000 *sg
= &per_cpu(sched_group_core
, cpu
);
7005 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
7006 static DEFINE_PER_CPU(struct sched_group
, sched_group_phys
);
7009 cpu_to_phys_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
7013 #ifdef CONFIG_SCHED_MC
7014 *mask
= cpu_coregroup_map(cpu
);
7015 cpus_and(*mask
, *mask
, *cpu_map
);
7016 group
= first_cpu(*mask
);
7017 #elif defined(CONFIG_SCHED_SMT)
7018 *mask
= per_cpu(cpu_sibling_map
, cpu
);
7019 cpus_and(*mask
, *mask
, *cpu_map
);
7020 group
= first_cpu(*mask
);
7025 *sg
= &per_cpu(sched_group_phys
, group
);
7031 * The init_sched_build_groups can't handle what we want to do with node
7032 * groups, so roll our own. Now each node has its own list of groups which
7033 * gets dynamically allocated.
7035 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
7036 static struct sched_group
***sched_group_nodes_bycpu
;
7038 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
7039 static DEFINE_PER_CPU(struct sched_group
, sched_group_allnodes
);
7041 static int cpu_to_allnodes_group(int cpu
, const cpumask_t
*cpu_map
,
7042 struct sched_group
**sg
, cpumask_t
*nodemask
)
7046 *nodemask
= node_to_cpumask(cpu_to_node(cpu
));
7047 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7048 group
= first_cpu(*nodemask
);
7051 *sg
= &per_cpu(sched_group_allnodes
, group
);
7055 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
7057 struct sched_group
*sg
= group_head
;
7063 for_each_cpu_mask(j
, sg
->cpumask
) {
7064 struct sched_domain
*sd
;
7066 sd
= &per_cpu(phys_domains
, j
);
7067 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
7069 * Only add "power" once for each
7075 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
7078 } while (sg
!= group_head
);
7083 /* Free memory allocated for various sched_group structures */
7084 static void free_sched_groups(const cpumask_t
*cpu_map
, cpumask_t
*nodemask
)
7088 for_each_cpu_mask(cpu
, *cpu_map
) {
7089 struct sched_group
**sched_group_nodes
7090 = sched_group_nodes_bycpu
[cpu
];
7092 if (!sched_group_nodes
)
7095 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
7096 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
7098 *nodemask
= node_to_cpumask(i
);
7099 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7100 if (cpus_empty(*nodemask
))
7110 if (oldsg
!= sched_group_nodes
[i
])
7113 kfree(sched_group_nodes
);
7114 sched_group_nodes_bycpu
[cpu
] = NULL
;
7118 static void free_sched_groups(const cpumask_t
*cpu_map
, cpumask_t
*nodemask
)
7124 * Initialize sched groups cpu_power.
7126 * cpu_power indicates the capacity of sched group, which is used while
7127 * distributing the load between different sched groups in a sched domain.
7128 * Typically cpu_power for all the groups in a sched domain will be same unless
7129 * there are asymmetries in the topology. If there are asymmetries, group
7130 * having more cpu_power will pickup more load compared to the group having
7133 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7134 * the maximum number of tasks a group can handle in the presence of other idle
7135 * or lightly loaded groups in the same sched domain.
7137 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
7139 struct sched_domain
*child
;
7140 struct sched_group
*group
;
7142 WARN_ON(!sd
|| !sd
->groups
);
7144 if (cpu
!= first_cpu(sd
->groups
->cpumask
))
7149 sd
->groups
->__cpu_power
= 0;
7152 * For perf policy, if the groups in child domain share resources
7153 * (for example cores sharing some portions of the cache hierarchy
7154 * or SMT), then set this domain groups cpu_power such that each group
7155 * can handle only one task, when there are other idle groups in the
7156 * same sched domain.
7158 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
7160 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
7161 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
7166 * add cpu_power of each child group to this groups cpu_power
7168 group
= child
->groups
;
7170 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
7171 group
= group
->next
;
7172 } while (group
!= child
->groups
);
7176 * Initializers for schedule domains
7177 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7180 #define SD_INIT(sd, type) sd_init_##type(sd)
7181 #define SD_INIT_FUNC(type) \
7182 static noinline void sd_init_##type(struct sched_domain *sd) \
7184 memset(sd, 0, sizeof(*sd)); \
7185 *sd = SD_##type##_INIT; \
7186 sd->level = SD_LV_##type; \
7191 SD_INIT_FUNC(ALLNODES
)
7194 #ifdef CONFIG_SCHED_SMT
7195 SD_INIT_FUNC(SIBLING
)
7197 #ifdef CONFIG_SCHED_MC
7202 * To minimize stack usage kmalloc room for cpumasks and share the
7203 * space as the usage in build_sched_domains() dictates. Used only
7204 * if the amount of space is significant.
7207 cpumask_t tmpmask
; /* make this one first */
7210 cpumask_t this_sibling_map
;
7211 cpumask_t this_core_map
;
7213 cpumask_t send_covered
;
7216 cpumask_t domainspan
;
7218 cpumask_t notcovered
;
7223 #define SCHED_CPUMASK_ALLOC 1
7224 #define SCHED_CPUMASK_FREE(v) kfree(v)
7225 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7227 #define SCHED_CPUMASK_ALLOC 0
7228 #define SCHED_CPUMASK_FREE(v)
7229 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7232 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7233 ((unsigned long)(a) + offsetof(struct allmasks, v))
7235 static int default_relax_domain_level
= -1;
7237 static int __init
setup_relax_domain_level(char *str
)
7239 default_relax_domain_level
= simple_strtoul(str
, NULL
, 0);
7242 __setup("relax_domain_level=", setup_relax_domain_level
);
7244 static void set_domain_attribute(struct sched_domain
*sd
,
7245 struct sched_domain_attr
*attr
)
7249 if (!attr
|| attr
->relax_domain_level
< 0) {
7250 if (default_relax_domain_level
< 0)
7253 request
= default_relax_domain_level
;
7255 request
= attr
->relax_domain_level
;
7256 if (request
< sd
->level
) {
7257 /* turn off idle balance on this domain */
7258 sd
->flags
&= ~(SD_WAKE_IDLE
|SD_BALANCE_NEWIDLE
);
7260 /* turn on idle balance on this domain */
7261 sd
->flags
|= (SD_WAKE_IDLE_FAR
|SD_BALANCE_NEWIDLE
);
7266 * Build sched domains for a given set of cpus and attach the sched domains
7267 * to the individual cpus
7269 static int __build_sched_domains(const cpumask_t
*cpu_map
,
7270 struct sched_domain_attr
*attr
)
7273 struct root_domain
*rd
;
7274 SCHED_CPUMASK_DECLARE(allmasks
);
7277 struct sched_group
**sched_group_nodes
= NULL
;
7278 int sd_allnodes
= 0;
7281 * Allocate the per-node list of sched groups
7283 sched_group_nodes
= kcalloc(MAX_NUMNODES
, sizeof(struct sched_group
*),
7285 if (!sched_group_nodes
) {
7286 printk(KERN_WARNING
"Can not alloc sched group node list\n");
7291 rd
= alloc_rootdomain();
7293 printk(KERN_WARNING
"Cannot alloc root domain\n");
7295 kfree(sched_group_nodes
);
7300 #if SCHED_CPUMASK_ALLOC
7301 /* get space for all scratch cpumask variables */
7302 allmasks
= kmalloc(sizeof(*allmasks
), GFP_KERNEL
);
7304 printk(KERN_WARNING
"Cannot alloc cpumask array\n");
7307 kfree(sched_group_nodes
);
7312 tmpmask
= (cpumask_t
*)allmasks
;
7316 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
7320 * Set up domains for cpus specified by the cpu_map.
7322 for_each_cpu_mask(i
, *cpu_map
) {
7323 struct sched_domain
*sd
= NULL
, *p
;
7324 SCHED_CPUMASK_VAR(nodemask
, allmasks
);
7326 *nodemask
= node_to_cpumask(cpu_to_node(i
));
7327 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7330 if (cpus_weight(*cpu_map
) >
7331 SD_NODES_PER_DOMAIN
*cpus_weight(*nodemask
)) {
7332 sd
= &per_cpu(allnodes_domains
, i
);
7333 SD_INIT(sd
, ALLNODES
);
7334 set_domain_attribute(sd
, attr
);
7335 sd
->span
= *cpu_map
;
7336 sd
->first_cpu
= first_cpu(sd
->span
);
7337 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7343 sd
= &per_cpu(node_domains
, i
);
7345 set_domain_attribute(sd
, attr
);
7346 sched_domain_node_span(cpu_to_node(i
), &sd
->span
);
7347 sd
->first_cpu
= first_cpu(sd
->span
);
7351 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
7355 sd
= &per_cpu(phys_domains
, i
);
7357 set_domain_attribute(sd
, attr
);
7358 sd
->span
= *nodemask
;
7359 sd
->first_cpu
= first_cpu(sd
->span
);
7363 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7365 #ifdef CONFIG_SCHED_MC
7367 sd
= &per_cpu(core_domains
, i
);
7369 set_domain_attribute(sd
, attr
);
7370 sd
->span
= cpu_coregroup_map(i
);
7371 sd
->first_cpu
= first_cpu(sd
->span
);
7372 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
7375 cpu_to_core_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7378 #ifdef CONFIG_SCHED_SMT
7380 sd
= &per_cpu(cpu_domains
, i
);
7381 SD_INIT(sd
, SIBLING
);
7382 set_domain_attribute(sd
, attr
);
7383 sd
->span
= per_cpu(cpu_sibling_map
, i
);
7384 sd
->first_cpu
= first_cpu(sd
->span
);
7385 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
7388 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7392 #ifdef CONFIG_SCHED_SMT
7393 /* Set up CPU (sibling) groups */
7394 for_each_cpu_mask(i
, *cpu_map
) {
7395 SCHED_CPUMASK_VAR(this_sibling_map
, allmasks
);
7396 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7398 *this_sibling_map
= per_cpu(cpu_sibling_map
, i
);
7399 cpus_and(*this_sibling_map
, *this_sibling_map
, *cpu_map
);
7400 if (i
!= first_cpu(*this_sibling_map
))
7403 init_sched_build_groups(this_sibling_map
, cpu_map
,
7405 send_covered
, tmpmask
);
7409 #ifdef CONFIG_SCHED_MC
7410 /* Set up multi-core groups */
7411 for_each_cpu_mask(i
, *cpu_map
) {
7412 SCHED_CPUMASK_VAR(this_core_map
, allmasks
);
7413 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7415 *this_core_map
= cpu_coregroup_map(i
);
7416 cpus_and(*this_core_map
, *this_core_map
, *cpu_map
);
7417 if (i
!= first_cpu(*this_core_map
))
7420 init_sched_build_groups(this_core_map
, cpu_map
,
7422 send_covered
, tmpmask
);
7426 /* Set up physical groups */
7427 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
7428 SCHED_CPUMASK_VAR(nodemask
, allmasks
);
7429 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7431 *nodemask
= node_to_cpumask(i
);
7432 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7433 if (cpus_empty(*nodemask
))
7436 init_sched_build_groups(nodemask
, cpu_map
,
7438 send_covered
, tmpmask
);
7442 /* Set up node groups */
7444 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7446 init_sched_build_groups(cpu_map
, cpu_map
,
7447 &cpu_to_allnodes_group
,
7448 send_covered
, tmpmask
);
7451 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
7452 /* Set up node groups */
7453 struct sched_group
*sg
, *prev
;
7454 SCHED_CPUMASK_VAR(nodemask
, allmasks
);
7455 SCHED_CPUMASK_VAR(domainspan
, allmasks
);
7456 SCHED_CPUMASK_VAR(covered
, allmasks
);
7459 *nodemask
= node_to_cpumask(i
);
7460 cpus_clear(*covered
);
7462 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7463 if (cpus_empty(*nodemask
)) {
7464 sched_group_nodes
[i
] = NULL
;
7468 sched_domain_node_span(i
, domainspan
);
7469 cpus_and(*domainspan
, *domainspan
, *cpu_map
);
7471 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
7473 printk(KERN_WARNING
"Can not alloc domain group for "
7477 sched_group_nodes
[i
] = sg
;
7478 for_each_cpu_mask(j
, *nodemask
) {
7479 struct sched_domain
*sd
;
7481 sd
= &per_cpu(node_domains
, j
);
7484 sg
->__cpu_power
= 0;
7485 sg
->cpumask
= *nodemask
;
7487 cpus_or(*covered
, *covered
, *nodemask
);
7490 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
7491 SCHED_CPUMASK_VAR(notcovered
, allmasks
);
7492 int n
= (i
+ j
) % MAX_NUMNODES
;
7493 node_to_cpumask_ptr(pnodemask
, n
);
7495 cpus_complement(*notcovered
, *covered
);
7496 cpus_and(*tmpmask
, *notcovered
, *cpu_map
);
7497 cpus_and(*tmpmask
, *tmpmask
, *domainspan
);
7498 if (cpus_empty(*tmpmask
))
7501 cpus_and(*tmpmask
, *tmpmask
, *pnodemask
);
7502 if (cpus_empty(*tmpmask
))
7505 sg
= kmalloc_node(sizeof(struct sched_group
),
7509 "Can not alloc domain group for node %d\n", j
);
7512 sg
->__cpu_power
= 0;
7513 sg
->cpumask
= *tmpmask
;
7514 sg
->next
= prev
->next
;
7515 cpus_or(*covered
, *covered
, *tmpmask
);
7522 /* Calculate CPU power for physical packages and nodes */
7523 #ifdef CONFIG_SCHED_SMT
7524 for_each_cpu_mask(i
, *cpu_map
) {
7525 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
);
7527 init_sched_groups_power(i
, sd
);
7530 #ifdef CONFIG_SCHED_MC
7531 for_each_cpu_mask(i
, *cpu_map
) {
7532 struct sched_domain
*sd
= &per_cpu(core_domains
, i
);
7534 init_sched_groups_power(i
, sd
);
7538 for_each_cpu_mask(i
, *cpu_map
) {
7539 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
);
7541 init_sched_groups_power(i
, sd
);
7545 for (i
= 0; i
< MAX_NUMNODES
; i
++)
7546 init_numa_sched_groups_power(sched_group_nodes
[i
]);
7549 struct sched_group
*sg
;
7551 cpu_to_allnodes_group(first_cpu(*cpu_map
), cpu_map
, &sg
,
7553 init_numa_sched_groups_power(sg
);
7557 /* Attach the domains */
7558 for_each_cpu_mask(i
, *cpu_map
) {
7559 struct sched_domain
*sd
;
7560 #ifdef CONFIG_SCHED_SMT
7561 sd
= &per_cpu(cpu_domains
, i
);
7562 #elif defined(CONFIG_SCHED_MC)
7563 sd
= &per_cpu(core_domains
, i
);
7565 sd
= &per_cpu(phys_domains
, i
);
7567 cpu_attach_domain(sd
, rd
, i
);
7570 SCHED_CPUMASK_FREE((void *)allmasks
);
7575 free_sched_groups(cpu_map
, tmpmask
);
7576 SCHED_CPUMASK_FREE((void *)allmasks
);
7581 static int build_sched_domains(const cpumask_t
*cpu_map
)
7583 return __build_sched_domains(cpu_map
, NULL
);
7586 static cpumask_t
*doms_cur
; /* current sched domains */
7587 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
7588 static struct sched_domain_attr
*dattr_cur
; /* attribues of custom domains
7592 * Special case: If a kmalloc of a doms_cur partition (array of
7593 * cpumask_t) fails, then fallback to a single sched domain,
7594 * as determined by the single cpumask_t fallback_doms.
7596 static cpumask_t fallback_doms
;
7598 void __attribute__((weak
)) arch_update_cpu_topology(void)
7603 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7604 * For now this just excludes isolated cpus, but could be used to
7605 * exclude other special cases in the future.
7607 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
7611 arch_update_cpu_topology();
7613 doms_cur
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
7615 doms_cur
= &fallback_doms
;
7616 cpus_andnot(*doms_cur
, *cpu_map
, cpu_isolated_map
);
7618 err
= build_sched_domains(doms_cur
);
7619 register_sched_domain_sysctl();
7624 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
,
7627 free_sched_groups(cpu_map
, tmpmask
);
7631 * Detach sched domains from a group of cpus specified in cpu_map
7632 * These cpus will now be attached to the NULL domain
7634 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
7639 unregister_sched_domain_sysctl();
7641 for_each_cpu_mask(i
, *cpu_map
)
7642 cpu_attach_domain(NULL
, &def_root_domain
, i
);
7643 synchronize_sched();
7644 arch_destroy_sched_domains(cpu_map
, &tmpmask
);
7647 /* handle null as "default" */
7648 static int dattrs_equal(struct sched_domain_attr
*cur
, int idx_cur
,
7649 struct sched_domain_attr
*new, int idx_new
)
7651 struct sched_domain_attr tmp
;
7658 return !memcmp(cur
? (cur
+ idx_cur
) : &tmp
,
7659 new ? (new + idx_new
) : &tmp
,
7660 sizeof(struct sched_domain_attr
));
7664 * Partition sched domains as specified by the 'ndoms_new'
7665 * cpumasks in the array doms_new[] of cpumasks. This compares
7666 * doms_new[] to the current sched domain partitioning, doms_cur[].
7667 * It destroys each deleted domain and builds each new domain.
7669 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7670 * The masks don't intersect (don't overlap.) We should setup one
7671 * sched domain for each mask. CPUs not in any of the cpumasks will
7672 * not be load balanced. If the same cpumask appears both in the
7673 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7676 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7677 * ownership of it and will kfree it when done with it. If the caller
7678 * failed the kmalloc call, then it can pass in doms_new == NULL,
7679 * and partition_sched_domains() will fallback to the single partition
7682 * Call with hotplug lock held
7684 void partition_sched_domains(int ndoms_new
, cpumask_t
*doms_new
,
7685 struct sched_domain_attr
*dattr_new
)
7691 /* always unregister in case we don't destroy any domains */
7692 unregister_sched_domain_sysctl();
7694 if (doms_new
== NULL
) {
7696 doms_new
= &fallback_doms
;
7697 cpus_andnot(doms_new
[0], cpu_online_map
, cpu_isolated_map
);
7701 /* Destroy deleted domains */
7702 for (i
= 0; i
< ndoms_cur
; i
++) {
7703 for (j
= 0; j
< ndoms_new
; j
++) {
7704 if (cpus_equal(doms_cur
[i
], doms_new
[j
])
7705 && dattrs_equal(dattr_cur
, i
, dattr_new
, j
))
7708 /* no match - a current sched domain not in new doms_new[] */
7709 detach_destroy_domains(doms_cur
+ i
);
7714 /* Build new domains */
7715 for (i
= 0; i
< ndoms_new
; i
++) {
7716 for (j
= 0; j
< ndoms_cur
; j
++) {
7717 if (cpus_equal(doms_new
[i
], doms_cur
[j
])
7718 && dattrs_equal(dattr_new
, i
, dattr_cur
, j
))
7721 /* no match - add a new doms_new */
7722 __build_sched_domains(doms_new
+ i
,
7723 dattr_new
? dattr_new
+ i
: NULL
);
7728 /* Remember the new sched domains */
7729 if (doms_cur
!= &fallback_doms
)
7731 kfree(dattr_cur
); /* kfree(NULL) is safe */
7732 doms_cur
= doms_new
;
7733 dattr_cur
= dattr_new
;
7734 ndoms_cur
= ndoms_new
;
7736 register_sched_domain_sysctl();
7741 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7742 int arch_reinit_sched_domains(void)
7747 detach_destroy_domains(&cpu_online_map
);
7748 err
= arch_init_sched_domains(&cpu_online_map
);
7754 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
7758 if (buf
[0] != '0' && buf
[0] != '1')
7762 sched_smt_power_savings
= (buf
[0] == '1');
7764 sched_mc_power_savings
= (buf
[0] == '1');
7766 ret
= arch_reinit_sched_domains();
7768 return ret
? ret
: count
;
7771 #ifdef CONFIG_SCHED_MC
7772 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
7774 return sprintf(page
, "%u\n", sched_mc_power_savings
);
7776 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
7777 const char *buf
, size_t count
)
7779 return sched_power_savings_store(buf
, count
, 0);
7781 static SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
7782 sched_mc_power_savings_store
);
7785 #ifdef CONFIG_SCHED_SMT
7786 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
7788 return sprintf(page
, "%u\n", sched_smt_power_savings
);
7790 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
7791 const char *buf
, size_t count
)
7793 return sched_power_savings_store(buf
, count
, 1);
7795 static SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
7796 sched_smt_power_savings_store
);
7799 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
7803 #ifdef CONFIG_SCHED_SMT
7805 err
= sysfs_create_file(&cls
->kset
.kobj
,
7806 &attr_sched_smt_power_savings
.attr
);
7808 #ifdef CONFIG_SCHED_MC
7809 if (!err
&& mc_capable())
7810 err
= sysfs_create_file(&cls
->kset
.kobj
,
7811 &attr_sched_mc_power_savings
.attr
);
7818 * Force a reinitialization of the sched domains hierarchy. The domains
7819 * and groups cannot be updated in place without racing with the balancing
7820 * code, so we temporarily attach all running cpus to the NULL domain
7821 * which will prevent rebalancing while the sched domains are recalculated.
7823 static int update_sched_domains(struct notifier_block
*nfb
,
7824 unsigned long action
, void *hcpu
)
7827 case CPU_UP_PREPARE
:
7828 case CPU_UP_PREPARE_FROZEN
:
7829 case CPU_DOWN_PREPARE
:
7830 case CPU_DOWN_PREPARE_FROZEN
:
7831 detach_destroy_domains(&cpu_online_map
);
7834 case CPU_UP_CANCELED
:
7835 case CPU_UP_CANCELED_FROZEN
:
7836 case CPU_DOWN_FAILED
:
7837 case CPU_DOWN_FAILED_FROZEN
:
7839 case CPU_ONLINE_FROZEN
:
7841 case CPU_DEAD_FROZEN
:
7843 * Fall through and re-initialise the domains.
7850 /* The hotplug lock is already held by cpu_up/cpu_down */
7851 arch_init_sched_domains(&cpu_online_map
);
7856 void __init
sched_init_smp(void)
7858 cpumask_t non_isolated_cpus
;
7860 #if defined(CONFIG_NUMA)
7861 sched_group_nodes_bycpu
= kzalloc(nr_cpu_ids
* sizeof(void **),
7863 BUG_ON(sched_group_nodes_bycpu
== NULL
);
7866 arch_init_sched_domains(&cpu_online_map
);
7867 cpus_andnot(non_isolated_cpus
, cpu_possible_map
, cpu_isolated_map
);
7868 if (cpus_empty(non_isolated_cpus
))
7869 cpu_set(smp_processor_id(), non_isolated_cpus
);
7871 /* XXX: Theoretical race here - CPU may be hotplugged now */
7872 hotcpu_notifier(update_sched_domains
, 0);
7874 /* Move init over to a non-isolated CPU */
7875 if (set_cpus_allowed_ptr(current
, &non_isolated_cpus
) < 0)
7877 sched_init_granularity();
7880 void __init
sched_init_smp(void)
7882 #if defined(CONFIG_NUMA)
7883 sched_group_nodes_bycpu
= kzalloc(nr_cpu_ids
* sizeof(void **),
7885 BUG_ON(sched_group_nodes_bycpu
== NULL
);
7887 sched_init_granularity();
7889 #endif /* CONFIG_SMP */
7891 int in_sched_functions(unsigned long addr
)
7893 return in_lock_functions(addr
) ||
7894 (addr
>= (unsigned long)__sched_text_start
7895 && addr
< (unsigned long)__sched_text_end
);
7898 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
7900 cfs_rq
->tasks_timeline
= RB_ROOT
;
7901 #ifdef CONFIG_FAIR_GROUP_SCHED
7904 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
7907 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
7909 struct rt_prio_array
*array
;
7912 array
= &rt_rq
->active
;
7913 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
7914 INIT_LIST_HEAD(array
->queue
+ i
);
7915 __clear_bit(i
, array
->bitmap
);
7917 /* delimiter for bitsearch: */
7918 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
7920 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7921 rt_rq
->highest_prio
= MAX_RT_PRIO
;
7924 rt_rq
->rt_nr_migratory
= 0;
7925 rt_rq
->overloaded
= 0;
7929 rt_rq
->rt_throttled
= 0;
7930 rt_rq
->rt_runtime
= 0;
7931 spin_lock_init(&rt_rq
->rt_runtime_lock
);
7933 #ifdef CONFIG_RT_GROUP_SCHED
7934 rt_rq
->rt_nr_boosted
= 0;
7939 #ifdef CONFIG_FAIR_GROUP_SCHED
7940 static void init_tg_cfs_entry(struct task_group
*tg
, struct cfs_rq
*cfs_rq
,
7941 struct sched_entity
*se
, int cpu
, int add
,
7942 struct sched_entity
*parent
)
7944 struct rq
*rq
= cpu_rq(cpu
);
7945 tg
->cfs_rq
[cpu
] = cfs_rq
;
7946 init_cfs_rq(cfs_rq
, rq
);
7949 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7952 /* se could be NULL for init_task_group */
7957 se
->cfs_rq
= &rq
->cfs
;
7959 se
->cfs_rq
= parent
->my_q
;
7962 se
->load
.weight
= tg
->shares
;
7963 se
->load
.inv_weight
= div64_64(1ULL<<32, se
->load
.weight
);
7964 se
->parent
= parent
;
7968 #ifdef CONFIG_RT_GROUP_SCHED
7969 static void init_tg_rt_entry(struct task_group
*tg
, struct rt_rq
*rt_rq
,
7970 struct sched_rt_entity
*rt_se
, int cpu
, int add
,
7971 struct sched_rt_entity
*parent
)
7973 struct rq
*rq
= cpu_rq(cpu
);
7975 tg
->rt_rq
[cpu
] = rt_rq
;
7976 init_rt_rq(rt_rq
, rq
);
7978 rt_rq
->rt_se
= rt_se
;
7979 rt_rq
->rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
7981 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
7983 tg
->rt_se
[cpu
] = rt_se
;
7988 rt_se
->rt_rq
= &rq
->rt
;
7990 rt_se
->rt_rq
= parent
->my_q
;
7992 rt_se
->rt_rq
= &rq
->rt
;
7993 rt_se
->my_q
= rt_rq
;
7994 rt_se
->parent
= parent
;
7995 INIT_LIST_HEAD(&rt_se
->run_list
);
7999 void __init
sched_init(void)
8002 unsigned long alloc_size
= 0, ptr
;
8004 #ifdef CONFIG_FAIR_GROUP_SCHED
8005 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
8007 #ifdef CONFIG_RT_GROUP_SCHED
8008 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
8010 #ifdef CONFIG_USER_SCHED
8014 * As sched_init() is called before page_alloc is setup,
8015 * we use alloc_bootmem().
8018 ptr
= (unsigned long)alloc_bootmem_low(alloc_size
);
8020 #ifdef CONFIG_FAIR_GROUP_SCHED
8021 init_task_group
.se
= (struct sched_entity
**)ptr
;
8022 ptr
+= nr_cpu_ids
* sizeof(void **);
8024 init_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
8025 ptr
+= nr_cpu_ids
* sizeof(void **);
8027 #ifdef CONFIG_USER_SCHED
8028 root_task_group
.se
= (struct sched_entity
**)ptr
;
8029 ptr
+= nr_cpu_ids
* sizeof(void **);
8031 root_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
8032 ptr
+= nr_cpu_ids
* sizeof(void **);
8035 #ifdef CONFIG_RT_GROUP_SCHED
8036 init_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
8037 ptr
+= nr_cpu_ids
* sizeof(void **);
8039 init_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
8040 ptr
+= nr_cpu_ids
* sizeof(void **);
8042 #ifdef CONFIG_USER_SCHED
8043 root_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
8044 ptr
+= nr_cpu_ids
* sizeof(void **);
8046 root_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
8047 ptr
+= nr_cpu_ids
* sizeof(void **);
8054 init_defrootdomain();
8057 init_rt_bandwidth(&def_rt_bandwidth
,
8058 global_rt_period(), global_rt_runtime());
8060 #ifdef CONFIG_RT_GROUP_SCHED
8061 init_rt_bandwidth(&init_task_group
.rt_bandwidth
,
8062 global_rt_period(), global_rt_runtime());
8063 #ifdef CONFIG_USER_SCHED
8064 init_rt_bandwidth(&root_task_group
.rt_bandwidth
,
8065 global_rt_period(), RUNTIME_INF
);
8069 #ifdef CONFIG_GROUP_SCHED
8070 list_add(&init_task_group
.list
, &task_groups
);
8071 INIT_LIST_HEAD(&init_task_group
.children
);
8073 #ifdef CONFIG_USER_SCHED
8074 INIT_LIST_HEAD(&root_task_group
.children
);
8075 init_task_group
.parent
= &root_task_group
;
8076 list_add(&init_task_group
.siblings
, &root_task_group
.children
);
8080 for_each_possible_cpu(i
) {
8084 spin_lock_init(&rq
->lock
);
8085 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
8088 update_last_tick_seen(rq
);
8089 init_cfs_rq(&rq
->cfs
, rq
);
8090 init_rt_rq(&rq
->rt
, rq
);
8091 #ifdef CONFIG_FAIR_GROUP_SCHED
8092 init_task_group
.shares
= init_task_group_load
;
8093 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
8094 #ifdef CONFIG_CGROUP_SCHED
8096 * How much cpu bandwidth does init_task_group get?
8098 * In case of task-groups formed thr' the cgroup filesystem, it
8099 * gets 100% of the cpu resources in the system. This overall
8100 * system cpu resource is divided among the tasks of
8101 * init_task_group and its child task-groups in a fair manner,
8102 * based on each entity's (task or task-group's) weight
8103 * (se->load.weight).
8105 * In other words, if init_task_group has 10 tasks of weight
8106 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8107 * then A0's share of the cpu resource is:
8109 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8111 * We achieve this by letting init_task_group's tasks sit
8112 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8114 init_tg_cfs_entry(&init_task_group
, &rq
->cfs
, NULL
, i
, 1, NULL
);
8115 #elif defined CONFIG_USER_SCHED
8116 root_task_group
.shares
= NICE_0_LOAD
;
8117 init_tg_cfs_entry(&root_task_group
, &rq
->cfs
, NULL
, i
, 0, NULL
);
8119 * In case of task-groups formed thr' the user id of tasks,
8120 * init_task_group represents tasks belonging to root user.
8121 * Hence it forms a sibling of all subsequent groups formed.
8122 * In this case, init_task_group gets only a fraction of overall
8123 * system cpu resource, based on the weight assigned to root
8124 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8125 * by letting tasks of init_task_group sit in a separate cfs_rq
8126 * (init_cfs_rq) and having one entity represent this group of
8127 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8129 init_tg_cfs_entry(&init_task_group
,
8130 &per_cpu(init_cfs_rq
, i
),
8131 &per_cpu(init_sched_entity
, i
), i
, 1,
8132 root_task_group
.se
[i
]);
8135 #endif /* CONFIG_FAIR_GROUP_SCHED */
8137 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
8138 #ifdef CONFIG_RT_GROUP_SCHED
8139 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
8140 #ifdef CONFIG_CGROUP_SCHED
8141 init_tg_rt_entry(&init_task_group
, &rq
->rt
, NULL
, i
, 1, NULL
);
8142 #elif defined CONFIG_USER_SCHED
8143 init_tg_rt_entry(&root_task_group
, &rq
->rt
, NULL
, i
, 0, NULL
);
8144 init_tg_rt_entry(&init_task_group
,
8145 &per_cpu(init_rt_rq
, i
),
8146 &per_cpu(init_sched_rt_entity
, i
), i
, 1,
8147 root_task_group
.rt_se
[i
]);
8151 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
8152 rq
->cpu_load
[j
] = 0;
8156 rq
->active_balance
= 0;
8157 rq
->next_balance
= jiffies
;
8160 rq
->migration_thread
= NULL
;
8161 INIT_LIST_HEAD(&rq
->migration_queue
);
8162 rq_attach_root(rq
, &def_root_domain
);
8165 atomic_set(&rq
->nr_iowait
, 0);
8168 set_load_weight(&init_task
);
8170 #ifdef CONFIG_PREEMPT_NOTIFIERS
8171 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
8175 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
, NULL
);
8178 #ifdef CONFIG_RT_MUTEXES
8179 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
8183 * The boot idle thread does lazy MMU switching as well:
8185 atomic_inc(&init_mm
.mm_count
);
8186 enter_lazy_tlb(&init_mm
, current
);
8189 * Make us the idle thread. Technically, schedule() should not be
8190 * called from this thread, however somewhere below it might be,
8191 * but because we are the idle thread, we just pick up running again
8192 * when this runqueue becomes "idle".
8194 init_idle(current
, smp_processor_id());
8196 * During early bootup we pretend to be a normal task:
8198 current
->sched_class
= &fair_sched_class
;
8200 scheduler_running
= 1;
8203 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8204 void __might_sleep(char *file
, int line
)
8207 static unsigned long prev_jiffy
; /* ratelimiting */
8209 if ((in_atomic() || irqs_disabled()) &&
8210 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
8211 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
8213 prev_jiffy
= jiffies
;
8214 printk(KERN_ERR
"BUG: sleeping function called from invalid"
8215 " context at %s:%d\n", file
, line
);
8216 printk("in_atomic():%d, irqs_disabled():%d\n",
8217 in_atomic(), irqs_disabled());
8218 debug_show_held_locks(current
);
8219 if (irqs_disabled())
8220 print_irqtrace_events(current
);
8225 EXPORT_SYMBOL(__might_sleep
);
8228 #ifdef CONFIG_MAGIC_SYSRQ
8229 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
8232 update_rq_clock(rq
);
8233 on_rq
= p
->se
.on_rq
;
8235 deactivate_task(rq
, p
, 0);
8236 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
8238 activate_task(rq
, p
, 0);
8239 resched_task(rq
->curr
);
8243 void normalize_rt_tasks(void)
8245 struct task_struct
*g
, *p
;
8246 unsigned long flags
;
8249 read_lock_irqsave(&tasklist_lock
, flags
);
8250 do_each_thread(g
, p
) {
8252 * Only normalize user tasks:
8257 p
->se
.exec_start
= 0;
8258 #ifdef CONFIG_SCHEDSTATS
8259 p
->se
.wait_start
= 0;
8260 p
->se
.sleep_start
= 0;
8261 p
->se
.block_start
= 0;
8263 task_rq(p
)->clock
= 0;
8267 * Renice negative nice level userspace
8270 if (TASK_NICE(p
) < 0 && p
->mm
)
8271 set_user_nice(p
, 0);
8275 spin_lock(&p
->pi_lock
);
8276 rq
= __task_rq_lock(p
);
8278 normalize_task(rq
, p
);
8280 __task_rq_unlock(rq
);
8281 spin_unlock(&p
->pi_lock
);
8282 } while_each_thread(g
, p
);
8284 read_unlock_irqrestore(&tasklist_lock
, flags
);
8287 #endif /* CONFIG_MAGIC_SYSRQ */
8291 * These functions are only useful for the IA64 MCA handling.
8293 * They can only be called when the whole system has been
8294 * stopped - every CPU needs to be quiescent, and no scheduling
8295 * activity can take place. Using them for anything else would
8296 * be a serious bug, and as a result, they aren't even visible
8297 * under any other configuration.
8301 * curr_task - return the current task for a given cpu.
8302 * @cpu: the processor in question.
8304 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8306 struct task_struct
*curr_task(int cpu
)
8308 return cpu_curr(cpu
);
8312 * set_curr_task - set the current task for a given cpu.
8313 * @cpu: the processor in question.
8314 * @p: the task pointer to set.
8316 * Description: This function must only be used when non-maskable interrupts
8317 * are serviced on a separate stack. It allows the architecture to switch the
8318 * notion of the current task on a cpu in a non-blocking manner. This function
8319 * must be called with all CPU's synchronized, and interrupts disabled, the
8320 * and caller must save the original value of the current task (see
8321 * curr_task() above) and restore that value before reenabling interrupts and
8322 * re-starting the system.
8324 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8326 void set_curr_task(int cpu
, struct task_struct
*p
)
8333 #ifdef CONFIG_FAIR_GROUP_SCHED
8334 static void free_fair_sched_group(struct task_group
*tg
)
8338 for_each_possible_cpu(i
) {
8340 kfree(tg
->cfs_rq
[i
]);
8350 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8352 struct cfs_rq
*cfs_rq
;
8353 struct sched_entity
*se
, *parent_se
;
8357 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * nr_cpu_ids
, GFP_KERNEL
);
8360 tg
->se
= kzalloc(sizeof(se
) * nr_cpu_ids
, GFP_KERNEL
);
8364 tg
->shares
= NICE_0_LOAD
;
8366 for_each_possible_cpu(i
) {
8369 cfs_rq
= kmalloc_node(sizeof(struct cfs_rq
),
8370 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8374 se
= kmalloc_node(sizeof(struct sched_entity
),
8375 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8379 parent_se
= parent
? parent
->se
[i
] : NULL
;
8380 init_tg_cfs_entry(tg
, cfs_rq
, se
, i
, 0, parent_se
);
8389 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
8391 list_add_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
,
8392 &cpu_rq(cpu
)->leaf_cfs_rq_list
);
8395 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
8397 list_del_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
);
8400 static inline void free_fair_sched_group(struct task_group
*tg
)
8405 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8410 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
8414 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
8419 #ifdef CONFIG_RT_GROUP_SCHED
8420 static void free_rt_sched_group(struct task_group
*tg
)
8424 destroy_rt_bandwidth(&tg
->rt_bandwidth
);
8426 for_each_possible_cpu(i
) {
8428 kfree(tg
->rt_rq
[i
]);
8430 kfree(tg
->rt_se
[i
]);
8438 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8440 struct rt_rq
*rt_rq
;
8441 struct sched_rt_entity
*rt_se
, *parent_se
;
8445 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * nr_cpu_ids
, GFP_KERNEL
);
8448 tg
->rt_se
= kzalloc(sizeof(rt_se
) * nr_cpu_ids
, GFP_KERNEL
);
8452 init_rt_bandwidth(&tg
->rt_bandwidth
,
8453 ktime_to_ns(def_rt_bandwidth
.rt_period
), 0);
8455 for_each_possible_cpu(i
) {
8458 rt_rq
= kmalloc_node(sizeof(struct rt_rq
),
8459 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8463 rt_se
= kmalloc_node(sizeof(struct sched_rt_entity
),
8464 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8468 parent_se
= parent
? parent
->rt_se
[i
] : NULL
;
8469 init_tg_rt_entry(tg
, rt_rq
, rt_se
, i
, 0, parent_se
);
8478 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
8480 list_add_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
,
8481 &cpu_rq(cpu
)->leaf_rt_rq_list
);
8484 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
8486 list_del_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
);
8489 static inline void free_rt_sched_group(struct task_group
*tg
)
8494 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8499 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
8503 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
8508 #ifdef CONFIG_GROUP_SCHED
8509 static void free_sched_group(struct task_group
*tg
)
8511 free_fair_sched_group(tg
);
8512 free_rt_sched_group(tg
);
8516 /* allocate runqueue etc for a new task group */
8517 struct task_group
*sched_create_group(struct task_group
*parent
)
8519 struct task_group
*tg
;
8520 unsigned long flags
;
8523 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
8525 return ERR_PTR(-ENOMEM
);
8527 if (!alloc_fair_sched_group(tg
, parent
))
8530 if (!alloc_rt_sched_group(tg
, parent
))
8533 spin_lock_irqsave(&task_group_lock
, flags
);
8534 for_each_possible_cpu(i
) {
8535 register_fair_sched_group(tg
, i
);
8536 register_rt_sched_group(tg
, i
);
8538 list_add_rcu(&tg
->list
, &task_groups
);
8540 WARN_ON(!parent
); /* root should already exist */
8542 tg
->parent
= parent
;
8543 list_add_rcu(&tg
->siblings
, &parent
->children
);
8544 INIT_LIST_HEAD(&tg
->children
);
8545 spin_unlock_irqrestore(&task_group_lock
, flags
);
8550 free_sched_group(tg
);
8551 return ERR_PTR(-ENOMEM
);
8554 /* rcu callback to free various structures associated with a task group */
8555 static void free_sched_group_rcu(struct rcu_head
*rhp
)
8557 /* now it should be safe to free those cfs_rqs */
8558 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
8561 /* Destroy runqueue etc associated with a task group */
8562 void sched_destroy_group(struct task_group
*tg
)
8564 unsigned long flags
;
8567 spin_lock_irqsave(&task_group_lock
, flags
);
8568 for_each_possible_cpu(i
) {
8569 unregister_fair_sched_group(tg
, i
);
8570 unregister_rt_sched_group(tg
, i
);
8572 list_del_rcu(&tg
->list
);
8573 list_del_rcu(&tg
->siblings
);
8574 spin_unlock_irqrestore(&task_group_lock
, flags
);
8576 /* wait for possible concurrent references to cfs_rqs complete */
8577 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
8580 /* change task's runqueue when it moves between groups.
8581 * The caller of this function should have put the task in its new group
8582 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8583 * reflect its new group.
8585 void sched_move_task(struct task_struct
*tsk
)
8588 unsigned long flags
;
8591 rq
= task_rq_lock(tsk
, &flags
);
8593 update_rq_clock(rq
);
8595 running
= task_current(rq
, tsk
);
8596 on_rq
= tsk
->se
.on_rq
;
8599 dequeue_task(rq
, tsk
, 0);
8600 if (unlikely(running
))
8601 tsk
->sched_class
->put_prev_task(rq
, tsk
);
8603 set_task_rq(tsk
, task_cpu(tsk
));
8605 #ifdef CONFIG_FAIR_GROUP_SCHED
8606 if (tsk
->sched_class
->moved_group
)
8607 tsk
->sched_class
->moved_group(tsk
);
8610 if (unlikely(running
))
8611 tsk
->sched_class
->set_curr_task(rq
);
8613 enqueue_task(rq
, tsk
, 0);
8615 task_rq_unlock(rq
, &flags
);
8619 #ifdef CONFIG_FAIR_GROUP_SCHED
8620 static void __set_se_shares(struct sched_entity
*se
, unsigned long shares
)
8622 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
8627 dequeue_entity(cfs_rq
, se
, 0);
8629 se
->load
.weight
= shares
;
8630 se
->load
.inv_weight
= div64_64((1ULL<<32), shares
);
8633 enqueue_entity(cfs_rq
, se
, 0);
8636 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
8638 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
8639 struct rq
*rq
= cfs_rq
->rq
;
8640 unsigned long flags
;
8642 spin_lock_irqsave(&rq
->lock
, flags
);
8643 __set_se_shares(se
, shares
);
8644 spin_unlock_irqrestore(&rq
->lock
, flags
);
8647 static DEFINE_MUTEX(shares_mutex
);
8649 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
8652 unsigned long flags
;
8655 * We can't change the weight of the root cgroup.
8661 * A weight of 0 or 1 can cause arithmetics problems.
8662 * (The default weight is 1024 - so there's no practical
8663 * limitation from this.)
8665 if (shares
< MIN_SHARES
)
8666 shares
= MIN_SHARES
;
8668 mutex_lock(&shares_mutex
);
8669 if (tg
->shares
== shares
)
8672 spin_lock_irqsave(&task_group_lock
, flags
);
8673 for_each_possible_cpu(i
)
8674 unregister_fair_sched_group(tg
, i
);
8675 list_del_rcu(&tg
->siblings
);
8676 spin_unlock_irqrestore(&task_group_lock
, flags
);
8678 /* wait for any ongoing reference to this group to finish */
8679 synchronize_sched();
8682 * Now we are free to modify the group's share on each cpu
8683 * w/o tripping rebalance_share or load_balance_fair.
8685 tg
->shares
= shares
;
8686 for_each_possible_cpu(i
) {
8690 cfs_rq_set_shares(tg
->cfs_rq
[i
], 0);
8691 set_se_shares(tg
->se
[i
], shares
/nr_cpu_ids
);
8695 * Enable load balance activity on this group, by inserting it back on
8696 * each cpu's rq->leaf_cfs_rq_list.
8698 spin_lock_irqsave(&task_group_lock
, flags
);
8699 for_each_possible_cpu(i
)
8700 register_fair_sched_group(tg
, i
);
8701 list_add_rcu(&tg
->siblings
, &tg
->parent
->children
);
8702 spin_unlock_irqrestore(&task_group_lock
, flags
);
8704 mutex_unlock(&shares_mutex
);
8708 unsigned long sched_group_shares(struct task_group
*tg
)
8714 #ifdef CONFIG_RT_GROUP_SCHED
8716 * Ensure that the real time constraints are schedulable.
8718 static DEFINE_MUTEX(rt_constraints_mutex
);
8720 static unsigned long to_ratio(u64 period
, u64 runtime
)
8722 if (runtime
== RUNTIME_INF
)
8725 return div64_64(runtime
<< 16, period
);
8728 #ifdef CONFIG_CGROUP_SCHED
8729 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
8731 struct task_group
*tgi
, *parent
= tg
->parent
;
8732 unsigned long total
= 0;
8735 if (global_rt_period() < period
)
8738 return to_ratio(period
, runtime
) <
8739 to_ratio(global_rt_period(), global_rt_runtime());
8742 if (ktime_to_ns(parent
->rt_bandwidth
.rt_period
) < period
)
8746 list_for_each_entry_rcu(tgi
, &parent
->children
, siblings
) {
8750 total
+= to_ratio(ktime_to_ns(tgi
->rt_bandwidth
.rt_period
),
8751 tgi
->rt_bandwidth
.rt_runtime
);
8755 return total
+ to_ratio(period
, runtime
) <
8756 to_ratio(ktime_to_ns(parent
->rt_bandwidth
.rt_period
),
8757 parent
->rt_bandwidth
.rt_runtime
);
8759 #elif defined CONFIG_USER_SCHED
8760 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
8762 struct task_group
*tgi
;
8763 unsigned long total
= 0;
8764 unsigned long global_ratio
=
8765 to_ratio(global_rt_period(), global_rt_runtime());
8768 list_for_each_entry_rcu(tgi
, &task_groups
, list
) {
8772 total
+= to_ratio(ktime_to_ns(tgi
->rt_bandwidth
.rt_period
),
8773 tgi
->rt_bandwidth
.rt_runtime
);
8777 return total
+ to_ratio(period
, runtime
) < global_ratio
;
8781 /* Must be called with tasklist_lock held */
8782 static inline int tg_has_rt_tasks(struct task_group
*tg
)
8784 struct task_struct
*g
, *p
;
8785 do_each_thread(g
, p
) {
8786 if (rt_task(p
) && rt_rq_of_se(&p
->rt
)->tg
== tg
)
8788 } while_each_thread(g
, p
);
8792 static int tg_set_bandwidth(struct task_group
*tg
,
8793 u64 rt_period
, u64 rt_runtime
)
8797 mutex_lock(&rt_constraints_mutex
);
8798 read_lock(&tasklist_lock
);
8799 if (rt_runtime
== 0 && tg_has_rt_tasks(tg
)) {
8803 if (!__rt_schedulable(tg
, rt_period
, rt_runtime
)) {
8808 spin_lock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8809 tg
->rt_bandwidth
.rt_period
= ns_to_ktime(rt_period
);
8810 tg
->rt_bandwidth
.rt_runtime
= rt_runtime
;
8812 for_each_possible_cpu(i
) {
8813 struct rt_rq
*rt_rq
= tg
->rt_rq
[i
];
8815 spin_lock(&rt_rq
->rt_runtime_lock
);
8816 rt_rq
->rt_runtime
= rt_runtime
;
8817 spin_unlock(&rt_rq
->rt_runtime_lock
);
8819 spin_unlock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8821 read_unlock(&tasklist_lock
);
8822 mutex_unlock(&rt_constraints_mutex
);
8827 int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
8829 u64 rt_runtime
, rt_period
;
8831 rt_period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8832 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
8833 if (rt_runtime_us
< 0)
8834 rt_runtime
= RUNTIME_INF
;
8836 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
8839 long sched_group_rt_runtime(struct task_group
*tg
)
8843 if (tg
->rt_bandwidth
.rt_runtime
== RUNTIME_INF
)
8846 rt_runtime_us
= tg
->rt_bandwidth
.rt_runtime
;
8847 do_div(rt_runtime_us
, NSEC_PER_USEC
);
8848 return rt_runtime_us
;
8851 int sched_group_set_rt_period(struct task_group
*tg
, long rt_period_us
)
8853 u64 rt_runtime
, rt_period
;
8855 rt_period
= (u64
)rt_period_us
* NSEC_PER_USEC
;
8856 rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
8858 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
8861 long sched_group_rt_period(struct task_group
*tg
)
8865 rt_period_us
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8866 do_div(rt_period_us
, NSEC_PER_USEC
);
8867 return rt_period_us
;
8870 static int sched_rt_global_constraints(void)
8874 mutex_lock(&rt_constraints_mutex
);
8875 if (!__rt_schedulable(NULL
, 1, 0))
8877 mutex_unlock(&rt_constraints_mutex
);
8882 static int sched_rt_global_constraints(void)
8884 unsigned long flags
;
8887 spin_lock_irqsave(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8888 for_each_possible_cpu(i
) {
8889 struct rt_rq
*rt_rq
= &cpu_rq(i
)->rt
;
8891 spin_lock(&rt_rq
->rt_runtime_lock
);
8892 rt_rq
->rt_runtime
= global_rt_runtime();
8893 spin_unlock(&rt_rq
->rt_runtime_lock
);
8895 spin_unlock_irqrestore(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8901 int sched_rt_handler(struct ctl_table
*table
, int write
,
8902 struct file
*filp
, void __user
*buffer
, size_t *lenp
,
8906 int old_period
, old_runtime
;
8907 static DEFINE_MUTEX(mutex
);
8910 old_period
= sysctl_sched_rt_period
;
8911 old_runtime
= sysctl_sched_rt_runtime
;
8913 ret
= proc_dointvec(table
, write
, filp
, buffer
, lenp
, ppos
);
8915 if (!ret
&& write
) {
8916 ret
= sched_rt_global_constraints();
8918 sysctl_sched_rt_period
= old_period
;
8919 sysctl_sched_rt_runtime
= old_runtime
;
8921 def_rt_bandwidth
.rt_runtime
= global_rt_runtime();
8922 def_rt_bandwidth
.rt_period
=
8923 ns_to_ktime(global_rt_period());
8926 mutex_unlock(&mutex
);
8931 #ifdef CONFIG_CGROUP_SCHED
8933 /* return corresponding task_group object of a cgroup */
8934 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
8936 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
8937 struct task_group
, css
);
8940 static struct cgroup_subsys_state
*
8941 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8943 struct task_group
*tg
, *parent
;
8945 if (!cgrp
->parent
) {
8946 /* This is early initialization for the top cgroup */
8947 init_task_group
.css
.cgroup
= cgrp
;
8948 return &init_task_group
.css
;
8951 parent
= cgroup_tg(cgrp
->parent
);
8952 tg
= sched_create_group(parent
);
8954 return ERR_PTR(-ENOMEM
);
8956 /* Bind the cgroup to task_group object we just created */
8957 tg
->css
.cgroup
= cgrp
;
8963 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8965 struct task_group
*tg
= cgroup_tg(cgrp
);
8967 sched_destroy_group(tg
);
8971 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8972 struct task_struct
*tsk
)
8974 #ifdef CONFIG_RT_GROUP_SCHED
8975 /* Don't accept realtime tasks when there is no way for them to run */
8976 if (rt_task(tsk
) && cgroup_tg(cgrp
)->rt_bandwidth
.rt_runtime
== 0)
8979 /* We don't support RT-tasks being in separate groups */
8980 if (tsk
->sched_class
!= &fair_sched_class
)
8988 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8989 struct cgroup
*old_cont
, struct task_struct
*tsk
)
8991 sched_move_task(tsk
);
8994 #ifdef CONFIG_FAIR_GROUP_SCHED
8995 static int cpu_shares_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
8998 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
9001 static u64
cpu_shares_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
9003 struct task_group
*tg
= cgroup_tg(cgrp
);
9005 return (u64
) tg
->shares
;
9009 #ifdef CONFIG_RT_GROUP_SCHED
9010 static ssize_t
cpu_rt_runtime_write(struct cgroup
*cgrp
, struct cftype
*cft
,
9012 const char __user
*userbuf
,
9013 size_t nbytes
, loff_t
*unused_ppos
)
9022 if (nbytes
>= sizeof(buffer
))
9024 if (copy_from_user(buffer
, userbuf
, nbytes
))
9027 buffer
[nbytes
] = 0; /* nul-terminate */
9029 /* strip newline if necessary */
9030 if (nbytes
&& (buffer
[nbytes
-1] == '\n'))
9031 buffer
[nbytes
-1] = 0;
9032 val
= simple_strtoll(buffer
, &end
, 0);
9036 /* Pass to subsystem */
9037 retval
= sched_group_set_rt_runtime(cgroup_tg(cgrp
), val
);
9043 static ssize_t
cpu_rt_runtime_read(struct cgroup
*cgrp
, struct cftype
*cft
,
9045 char __user
*buf
, size_t nbytes
,
9049 long val
= sched_group_rt_runtime(cgroup_tg(cgrp
));
9050 int len
= sprintf(tmp
, "%ld\n", val
);
9052 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
9055 static int cpu_rt_period_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
9058 return sched_group_set_rt_period(cgroup_tg(cgrp
), rt_period_us
);
9061 static u64
cpu_rt_period_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
9063 return sched_group_rt_period(cgroup_tg(cgrp
));
9067 static struct cftype cpu_files
[] = {
9068 #ifdef CONFIG_FAIR_GROUP_SCHED
9071 .read_uint
= cpu_shares_read_uint
,
9072 .write_uint
= cpu_shares_write_uint
,
9075 #ifdef CONFIG_RT_GROUP_SCHED
9077 .name
= "rt_runtime_us",
9078 .read
= cpu_rt_runtime_read
,
9079 .write
= cpu_rt_runtime_write
,
9082 .name
= "rt_period_us",
9083 .read_uint
= cpu_rt_period_read_uint
,
9084 .write_uint
= cpu_rt_period_write_uint
,
9089 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
9091 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
9094 struct cgroup_subsys cpu_cgroup_subsys
= {
9096 .create
= cpu_cgroup_create
,
9097 .destroy
= cpu_cgroup_destroy
,
9098 .can_attach
= cpu_cgroup_can_attach
,
9099 .attach
= cpu_cgroup_attach
,
9100 .populate
= cpu_cgroup_populate
,
9101 .subsys_id
= cpu_cgroup_subsys_id
,
9105 #endif /* CONFIG_CGROUP_SCHED */
9107 #ifdef CONFIG_CGROUP_CPUACCT
9110 * CPU accounting code for task groups.
9112 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9113 * (balbir@in.ibm.com).
9116 /* track cpu usage of a group of tasks */
9118 struct cgroup_subsys_state css
;
9119 /* cpuusage holds pointer to a u64-type object on every cpu */
9123 struct cgroup_subsys cpuacct_subsys
;
9125 /* return cpu accounting group corresponding to this container */
9126 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cgrp
)
9128 return container_of(cgroup_subsys_state(cgrp
, cpuacct_subsys_id
),
9129 struct cpuacct
, css
);
9132 /* return cpu accounting group to which this task belongs */
9133 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
9135 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
9136 struct cpuacct
, css
);
9139 /* create a new cpu accounting group */
9140 static struct cgroup_subsys_state
*cpuacct_create(
9141 struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9143 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
9146 return ERR_PTR(-ENOMEM
);
9148 ca
->cpuusage
= alloc_percpu(u64
);
9149 if (!ca
->cpuusage
) {
9151 return ERR_PTR(-ENOMEM
);
9157 /* destroy an existing cpu accounting group */
9159 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9161 struct cpuacct
*ca
= cgroup_ca(cgrp
);
9163 free_percpu(ca
->cpuusage
);
9167 /* return total cpu usage (in nanoseconds) of a group */
9168 static u64
cpuusage_read(struct cgroup
*cgrp
, struct cftype
*cft
)
9170 struct cpuacct
*ca
= cgroup_ca(cgrp
);
9171 u64 totalcpuusage
= 0;
9174 for_each_possible_cpu(i
) {
9175 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
9178 * Take rq->lock to make 64-bit addition safe on 32-bit
9181 spin_lock_irq(&cpu_rq(i
)->lock
);
9182 totalcpuusage
+= *cpuusage
;
9183 spin_unlock_irq(&cpu_rq(i
)->lock
);
9186 return totalcpuusage
;
9189 static int cpuusage_write(struct cgroup
*cgrp
, struct cftype
*cftype
,
9192 struct cpuacct
*ca
= cgroup_ca(cgrp
);
9201 for_each_possible_cpu(i
) {
9202 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
9204 spin_lock_irq(&cpu_rq(i
)->lock
);
9206 spin_unlock_irq(&cpu_rq(i
)->lock
);
9212 static struct cftype files
[] = {
9215 .read_uint
= cpuusage_read
,
9216 .write_uint
= cpuusage_write
,
9220 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
9222 return cgroup_add_files(cgrp
, ss
, files
, ARRAY_SIZE(files
));
9226 * charge this task's execution time to its accounting group.
9228 * called with rq->lock held.
9230 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
9234 if (!cpuacct_subsys
.active
)
9239 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, task_cpu(tsk
));
9241 *cpuusage
+= cputime
;
9245 struct cgroup_subsys cpuacct_subsys
= {
9247 .create
= cpuacct_create
,
9248 .destroy
= cpuacct_destroy
,
9249 .populate
= cpuacct_populate
,
9250 .subsys_id
= cpuacct_subsys_id
,
9252 #endif /* CONFIG_CGROUP_CPUACCT */