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>
72 #include <asm/irq_regs.h>
75 * Scheduler clock - returns current time in nanosec units.
76 * This is default implementation.
77 * Architectures and sub-architectures can override this.
79 unsigned long long __attribute__((weak
)) sched_clock(void)
81 return (unsigned long long)jiffies
* (NSEC_PER_SEC
/ HZ
);
85 * Convert user-nice values [ -20 ... 0 ... 19 ]
86 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
89 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
90 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
91 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
94 * 'User priority' is the nice value converted to something we
95 * can work with better when scaling various scheduler parameters,
96 * it's a [ 0 ... 39 ] range.
98 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
99 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
100 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
103 * Helpers for converting nanosecond timing to jiffy resolution
105 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
107 #define NICE_0_LOAD SCHED_LOAD_SCALE
108 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
111 * These are the 'tuning knobs' of the scheduler:
113 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
114 * Timeslices get refilled after they expire.
116 #define DEF_TIMESLICE (100 * HZ / 1000)
119 * single value that denotes runtime == period, ie unlimited time.
121 #define RUNTIME_INF ((u64)~0ULL)
125 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
126 * Since cpu_power is a 'constant', we can use a reciprocal divide.
128 static inline u32
sg_div_cpu_power(const struct sched_group
*sg
, u32 load
)
130 return reciprocal_divide(load
, sg
->reciprocal_cpu_power
);
134 * Each time a sched group cpu_power is changed,
135 * we must compute its reciprocal value
137 static inline void sg_inc_cpu_power(struct sched_group
*sg
, u32 val
)
139 sg
->__cpu_power
+= val
;
140 sg
->reciprocal_cpu_power
= reciprocal_value(sg
->__cpu_power
);
144 static inline int rt_policy(int policy
)
146 if (unlikely(policy
== SCHED_FIFO
) || unlikely(policy
== SCHED_RR
))
151 static inline int task_has_rt_policy(struct task_struct
*p
)
153 return rt_policy(p
->policy
);
157 * This is the priority-queue data structure of the RT scheduling class:
159 struct rt_prio_array
{
160 DECLARE_BITMAP(bitmap
, MAX_RT_PRIO
+1); /* include 1 bit for delimiter */
161 struct list_head queue
[MAX_RT_PRIO
];
164 struct rt_bandwidth
{
167 spinlock_t rt_runtime_lock
;
168 struct hrtimer rt_period_timer
;
171 static struct rt_bandwidth def_rt_bandwidth
;
173 static int do_sched_rt_period_timer(struct rt_bandwidth
*rt_b
, int overrun
);
175 static enum hrtimer_restart
sched_rt_period_timer(struct hrtimer
*timer
)
177 struct rt_bandwidth
*rt_b
=
178 container_of(timer
, struct rt_bandwidth
, rt_period_timer
);
184 now
= hrtimer_cb_get_time(timer
);
185 overrun
= hrtimer_forward(timer
, now
, rt_b
->rt_period
);
190 idle
= do_sched_rt_period_timer(rt_b
, overrun
);
193 return idle
? HRTIMER_NORESTART
: HRTIMER_RESTART
;
197 void init_rt_bandwidth(struct rt_bandwidth
*rt_b
, u64 period
, u64 runtime
)
199 rt_b
->rt_period
= ns_to_ktime(period
);
200 rt_b
->rt_runtime
= runtime
;
202 spin_lock_init(&rt_b
->rt_runtime_lock
);
204 hrtimer_init(&rt_b
->rt_period_timer
,
205 CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
206 rt_b
->rt_period_timer
.function
= sched_rt_period_timer
;
207 rt_b
->rt_period_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
210 static void start_rt_bandwidth(struct rt_bandwidth
*rt_b
)
214 if (rt_b
->rt_runtime
== RUNTIME_INF
)
217 if (hrtimer_active(&rt_b
->rt_period_timer
))
220 spin_lock(&rt_b
->rt_runtime_lock
);
222 if (hrtimer_active(&rt_b
->rt_period_timer
))
225 now
= hrtimer_cb_get_time(&rt_b
->rt_period_timer
);
226 hrtimer_forward(&rt_b
->rt_period_timer
, now
, rt_b
->rt_period
);
227 hrtimer_start(&rt_b
->rt_period_timer
,
228 rt_b
->rt_period_timer
.expires
,
231 spin_unlock(&rt_b
->rt_runtime_lock
);
234 #ifdef CONFIG_RT_GROUP_SCHED
235 static void destroy_rt_bandwidth(struct rt_bandwidth
*rt_b
)
237 hrtimer_cancel(&rt_b
->rt_period_timer
);
241 #ifdef CONFIG_GROUP_SCHED
243 #include <linux/cgroup.h>
247 static LIST_HEAD(task_groups
);
249 /* task group related information */
251 #ifdef CONFIG_CGROUP_SCHED
252 struct cgroup_subsys_state css
;
255 #ifdef CONFIG_FAIR_GROUP_SCHED
256 /* schedulable entities of this group on each cpu */
257 struct sched_entity
**se
;
258 /* runqueue "owned" by this group on each cpu */
259 struct cfs_rq
**cfs_rq
;
260 unsigned long shares
;
263 #ifdef CONFIG_RT_GROUP_SCHED
264 struct sched_rt_entity
**rt_se
;
265 struct rt_rq
**rt_rq
;
267 struct rt_bandwidth rt_bandwidth
;
271 struct list_head list
;
274 #ifdef CONFIG_FAIR_GROUP_SCHED
275 /* Default task group's sched entity on each cpu */
276 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
277 /* Default task group's cfs_rq on each cpu */
278 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
280 static struct sched_entity
*init_sched_entity_p
[NR_CPUS
];
281 static struct cfs_rq
*init_cfs_rq_p
[NR_CPUS
];
284 #ifdef CONFIG_RT_GROUP_SCHED
285 static DEFINE_PER_CPU(struct sched_rt_entity
, init_sched_rt_entity
);
286 static DEFINE_PER_CPU(struct rt_rq
, init_rt_rq
) ____cacheline_aligned_in_smp
;
288 static struct sched_rt_entity
*init_sched_rt_entity_p
[NR_CPUS
];
289 static struct rt_rq
*init_rt_rq_p
[NR_CPUS
];
292 /* task_group_lock serializes add/remove of task groups and also changes to
293 * a task group's cpu shares.
295 static DEFINE_SPINLOCK(task_group_lock
);
297 /* doms_cur_mutex serializes access to doms_cur[] array */
298 static DEFINE_MUTEX(doms_cur_mutex
);
300 #ifdef CONFIG_FAIR_GROUP_SCHED
301 #ifdef CONFIG_USER_SCHED
302 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
304 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
307 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
310 /* Default task group.
311 * Every task in system belong to this group at bootup.
313 struct task_group init_task_group
= {
314 #ifdef CONFIG_FAIR_GROUP_SCHED
315 .se
= init_sched_entity_p
,
316 .cfs_rq
= init_cfs_rq_p
,
319 #ifdef CONFIG_RT_GROUP_SCHED
320 .rt_se
= init_sched_rt_entity_p
,
321 .rt_rq
= init_rt_rq_p
,
325 /* return group to which a task belongs */
326 static inline struct task_group
*task_group(struct task_struct
*p
)
328 struct task_group
*tg
;
330 #ifdef CONFIG_USER_SCHED
332 #elif defined(CONFIG_CGROUP_SCHED)
333 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
334 struct task_group
, css
);
336 tg
= &init_task_group
;
341 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
342 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
)
344 #ifdef CONFIG_FAIR_GROUP_SCHED
345 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
346 p
->se
.parent
= task_group(p
)->se
[cpu
];
349 #ifdef CONFIG_RT_GROUP_SCHED
350 p
->rt
.rt_rq
= task_group(p
)->rt_rq
[cpu
];
351 p
->rt
.parent
= task_group(p
)->rt_se
[cpu
];
355 static inline void lock_doms_cur(void)
357 mutex_lock(&doms_cur_mutex
);
360 static inline void unlock_doms_cur(void)
362 mutex_unlock(&doms_cur_mutex
);
367 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
) { }
368 static inline void lock_doms_cur(void) { }
369 static inline void unlock_doms_cur(void) { }
371 #endif /* CONFIG_GROUP_SCHED */
373 /* CFS-related fields in a runqueue */
375 struct load_weight load
;
376 unsigned long nr_running
;
381 struct rb_root tasks_timeline
;
382 struct rb_node
*rb_leftmost
;
383 struct rb_node
*rb_load_balance_curr
;
384 /* 'curr' points to currently running entity on this cfs_rq.
385 * It is set to NULL otherwise (i.e when none are currently running).
387 struct sched_entity
*curr
, *next
;
389 unsigned long nr_spread_over
;
391 #ifdef CONFIG_FAIR_GROUP_SCHED
392 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
395 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
396 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
397 * (like users, containers etc.)
399 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
400 * list is used during load balance.
402 struct list_head leaf_cfs_rq_list
;
403 struct task_group
*tg
; /* group that "owns" this runqueue */
407 /* Real-Time classes' related field in a runqueue: */
409 struct rt_prio_array active
;
410 unsigned long rt_nr_running
;
411 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
412 int highest_prio
; /* highest queued rt task prio */
415 unsigned long rt_nr_migratory
;
421 spinlock_t rt_runtime_lock
;
423 #ifdef CONFIG_RT_GROUP_SCHED
424 unsigned long rt_nr_boosted
;
427 struct list_head leaf_rt_rq_list
;
428 struct task_group
*tg
;
429 struct sched_rt_entity
*rt_se
;
436 * We add the notion of a root-domain which will be used to define per-domain
437 * variables. Each exclusive cpuset essentially defines an island domain by
438 * fully partitioning the member cpus from any other cpuset. Whenever a new
439 * exclusive cpuset is created, we also create and attach a new root-domain
449 * The "RT overload" flag: it gets set if a CPU has more than
450 * one runnable RT task.
457 * By default the system creates a single root-domain with all cpus as
458 * members (mimicking the global state we have today).
460 static struct root_domain def_root_domain
;
465 * This is the main, per-CPU runqueue data structure.
467 * Locking rule: those places that want to lock multiple runqueues
468 * (such as the load balancing or the thread migration code), lock
469 * acquire operations must be ordered by ascending &runqueue.
476 * nr_running and cpu_load should be in the same cacheline because
477 * remote CPUs use both these fields when doing load calculation.
479 unsigned long nr_running
;
480 #define CPU_LOAD_IDX_MAX 5
481 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
482 unsigned char idle_at_tick
;
484 unsigned long last_tick_seen
;
485 unsigned char in_nohz_recently
;
487 /* capture load from *all* tasks on this cpu: */
488 struct load_weight load
;
489 unsigned long nr_load_updates
;
495 #ifdef CONFIG_FAIR_GROUP_SCHED
496 /* list of leaf cfs_rq on this cpu: */
497 struct list_head leaf_cfs_rq_list
;
499 #ifdef CONFIG_RT_GROUP_SCHED
500 struct list_head leaf_rt_rq_list
;
504 * This is part of a global counter where only the total sum
505 * over all CPUs matters. A task can increase this counter on
506 * one CPU and if it got migrated afterwards it may decrease
507 * it on another CPU. Always updated under the runqueue lock:
509 unsigned long nr_uninterruptible
;
511 struct task_struct
*curr
, *idle
;
512 unsigned long next_balance
;
513 struct mm_struct
*prev_mm
;
515 u64 clock
, prev_clock_raw
;
518 unsigned int clock_warps
, clock_overflows
, clock_underflows
;
520 unsigned int clock_deep_idle_events
;
526 struct root_domain
*rd
;
527 struct sched_domain
*sd
;
529 /* For active balancing */
532 /* cpu of this runqueue: */
535 struct task_struct
*migration_thread
;
536 struct list_head migration_queue
;
539 #ifdef CONFIG_SCHED_HRTICK
540 unsigned long hrtick_flags
;
541 ktime_t hrtick_expire
;
542 struct hrtimer hrtick_timer
;
545 #ifdef CONFIG_SCHEDSTATS
547 struct sched_info rq_sched_info
;
549 /* sys_sched_yield() stats */
550 unsigned int yld_exp_empty
;
551 unsigned int yld_act_empty
;
552 unsigned int yld_both_empty
;
553 unsigned int yld_count
;
555 /* schedule() stats */
556 unsigned int sched_switch
;
557 unsigned int sched_count
;
558 unsigned int sched_goidle
;
560 /* try_to_wake_up() stats */
561 unsigned int ttwu_count
;
562 unsigned int ttwu_local
;
565 unsigned int bkl_count
;
567 struct lock_class_key rq_lock_key
;
570 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
572 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
)
574 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
);
577 static inline int cpu_of(struct rq
*rq
)
587 static inline bool nohz_on(int cpu
)
589 return tick_get_tick_sched(cpu
)->nohz_mode
!= NOHZ_MODE_INACTIVE
;
592 static inline u64
max_skipped_ticks(struct rq
*rq
)
594 return nohz_on(cpu_of(rq
)) ? jiffies
- rq
->last_tick_seen
+ 2 : 1;
597 static inline void update_last_tick_seen(struct rq
*rq
)
599 rq
->last_tick_seen
= jiffies
;
602 static inline u64
max_skipped_ticks(struct rq
*rq
)
607 static inline void update_last_tick_seen(struct rq
*rq
)
613 * Update the per-runqueue clock, as finegrained as the platform can give
614 * us, but without assuming monotonicity, etc.:
616 static void __update_rq_clock(struct rq
*rq
)
618 u64 prev_raw
= rq
->prev_clock_raw
;
619 u64 now
= sched_clock();
620 s64 delta
= now
- prev_raw
;
621 u64 clock
= rq
->clock
;
623 #ifdef CONFIG_SCHED_DEBUG
624 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
627 * Protect against sched_clock() occasionally going backwards:
629 if (unlikely(delta
< 0)) {
634 * Catch too large forward jumps too:
636 u64 max_jump
= max_skipped_ticks(rq
) * TICK_NSEC
;
637 u64 max_time
= rq
->tick_timestamp
+ max_jump
;
639 if (unlikely(clock
+ delta
> max_time
)) {
640 if (clock
< max_time
)
644 rq
->clock_overflows
++;
646 if (unlikely(delta
> rq
->clock_max_delta
))
647 rq
->clock_max_delta
= delta
;
652 rq
->prev_clock_raw
= now
;
656 static void update_rq_clock(struct rq
*rq
)
658 if (likely(smp_processor_id() == cpu_of(rq
)))
659 __update_rq_clock(rq
);
663 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
664 * See detach_destroy_domains: synchronize_sched for details.
666 * The domain tree of any CPU may only be accessed from within
667 * preempt-disabled sections.
669 #define for_each_domain(cpu, __sd) \
670 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
672 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
673 #define this_rq() (&__get_cpu_var(runqueues))
674 #define task_rq(p) cpu_rq(task_cpu(p))
675 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
678 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
680 #ifdef CONFIG_SCHED_DEBUG
681 # define const_debug __read_mostly
683 # define const_debug static const
687 * Debugging: various feature bits
690 SCHED_FEAT_NEW_FAIR_SLEEPERS
= 1,
691 SCHED_FEAT_WAKEUP_PREEMPT
= 2,
692 SCHED_FEAT_START_DEBIT
= 4,
693 SCHED_FEAT_AFFINE_WAKEUPS
= 8,
694 SCHED_FEAT_CACHE_HOT_BUDDY
= 16,
695 SCHED_FEAT_SYNC_WAKEUPS
= 32,
696 SCHED_FEAT_HRTICK
= 64,
697 SCHED_FEAT_DOUBLE_TICK
= 128,
700 const_debug
unsigned int sysctl_sched_features
=
701 SCHED_FEAT_NEW_FAIR_SLEEPERS
* 1 |
702 SCHED_FEAT_WAKEUP_PREEMPT
* 1 |
703 SCHED_FEAT_START_DEBIT
* 1 |
704 SCHED_FEAT_AFFINE_WAKEUPS
* 1 |
705 SCHED_FEAT_CACHE_HOT_BUDDY
* 1 |
706 SCHED_FEAT_SYNC_WAKEUPS
* 1 |
707 SCHED_FEAT_HRTICK
* 1 |
708 SCHED_FEAT_DOUBLE_TICK
* 0;
710 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
713 * Number of tasks to iterate in a single balance run.
714 * Limited because this is done with IRQs disabled.
716 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
719 * period over which we measure -rt task cpu usage in us.
722 unsigned int sysctl_sched_rt_period
= 1000000;
724 static __read_mostly
int scheduler_running
;
727 * part of the period that we allow rt tasks to run in us.
730 int sysctl_sched_rt_runtime
= 950000;
732 static inline u64
global_rt_period(void)
734 return (u64
)sysctl_sched_rt_period
* NSEC_PER_USEC
;
737 static inline u64
global_rt_runtime(void)
739 if (sysctl_sched_rt_period
< 0)
742 return (u64
)sysctl_sched_rt_runtime
* NSEC_PER_USEC
;
745 static const unsigned long long time_sync_thresh
= 100000;
747 static DEFINE_PER_CPU(unsigned long long, time_offset
);
748 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time
);
751 * Global lock which we take every now and then to synchronize
752 * the CPUs time. This method is not warp-safe, but it's good
753 * enough to synchronize slowly diverging time sources and thus
754 * it's good enough for tracing:
756 static DEFINE_SPINLOCK(time_sync_lock
);
757 static unsigned long long prev_global_time
;
759 static unsigned long long __sync_cpu_clock(cycles_t time
, int cpu
)
763 spin_lock_irqsave(&time_sync_lock
, flags
);
765 if (time
< prev_global_time
) {
766 per_cpu(time_offset
, cpu
) += prev_global_time
- time
;
767 time
= prev_global_time
;
769 prev_global_time
= time
;
772 spin_unlock_irqrestore(&time_sync_lock
, flags
);
777 static unsigned long long __cpu_clock(int cpu
)
779 unsigned long long now
;
784 * Only call sched_clock() if the scheduler has already been
785 * initialized (some code might call cpu_clock() very early):
787 if (unlikely(!scheduler_running
))
790 local_irq_save(flags
);
794 local_irq_restore(flags
);
800 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
801 * clock constructed from sched_clock():
803 unsigned long long cpu_clock(int cpu
)
805 unsigned long long prev_cpu_time
, time
, delta_time
;
807 prev_cpu_time
= per_cpu(prev_cpu_time
, cpu
);
808 time
= __cpu_clock(cpu
) + per_cpu(time_offset
, cpu
);
809 delta_time
= time
-prev_cpu_time
;
811 if (unlikely(delta_time
> time_sync_thresh
))
812 time
= __sync_cpu_clock(time
, cpu
);
816 EXPORT_SYMBOL_GPL(cpu_clock
);
818 #ifndef prepare_arch_switch
819 # define prepare_arch_switch(next) do { } while (0)
821 #ifndef finish_arch_switch
822 # define finish_arch_switch(prev) do { } while (0)
825 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
827 return rq
->curr
== p
;
830 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
831 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
833 return task_current(rq
, p
);
836 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
840 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
842 #ifdef CONFIG_DEBUG_SPINLOCK
843 /* this is a valid case when another task releases the spinlock */
844 rq
->lock
.owner
= current
;
847 * If we are tracking spinlock dependencies then we have to
848 * fix up the runqueue lock - which gets 'carried over' from
851 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
853 spin_unlock_irq(&rq
->lock
);
856 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
857 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
862 return task_current(rq
, p
);
866 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
870 * We can optimise this out completely for !SMP, because the
871 * SMP rebalancing from interrupt is the only thing that cares
876 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
877 spin_unlock_irq(&rq
->lock
);
879 spin_unlock(&rq
->lock
);
883 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
887 * After ->oncpu is cleared, the task can be moved to a different CPU.
888 * We must ensure this doesn't happen until the switch is completely
894 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
898 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
901 * __task_rq_lock - lock the runqueue a given task resides on.
902 * Must be called interrupts disabled.
904 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
908 struct rq
*rq
= task_rq(p
);
909 spin_lock(&rq
->lock
);
910 if (likely(rq
== task_rq(p
)))
912 spin_unlock(&rq
->lock
);
917 * task_rq_lock - lock the runqueue a given task resides on and disable
918 * interrupts. Note the ordering: we can safely lookup the task_rq without
919 * explicitly disabling preemption.
921 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
927 local_irq_save(*flags
);
929 spin_lock(&rq
->lock
);
930 if (likely(rq
== task_rq(p
)))
932 spin_unlock_irqrestore(&rq
->lock
, *flags
);
936 static void __task_rq_unlock(struct rq
*rq
)
939 spin_unlock(&rq
->lock
);
942 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
945 spin_unlock_irqrestore(&rq
->lock
, *flags
);
949 * this_rq_lock - lock this runqueue and disable interrupts.
951 static struct rq
*this_rq_lock(void)
958 spin_lock(&rq
->lock
);
964 * We are going deep-idle (irqs are disabled):
966 void sched_clock_idle_sleep_event(void)
968 struct rq
*rq
= cpu_rq(smp_processor_id());
970 spin_lock(&rq
->lock
);
971 __update_rq_clock(rq
);
972 spin_unlock(&rq
->lock
);
973 rq
->clock_deep_idle_events
++;
975 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event
);
978 * We just idled delta nanoseconds (called with irqs disabled):
980 void sched_clock_idle_wakeup_event(u64 delta_ns
)
982 struct rq
*rq
= cpu_rq(smp_processor_id());
983 u64 now
= sched_clock();
985 rq
->idle_clock
+= delta_ns
;
987 * Override the previous timestamp and ignore all
988 * sched_clock() deltas that occured while we idled,
989 * and use the PM-provided delta_ns to advance the
992 spin_lock(&rq
->lock
);
993 rq
->prev_clock_raw
= now
;
994 rq
->clock
+= delta_ns
;
995 spin_unlock(&rq
->lock
);
996 touch_softlockup_watchdog();
998 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event
);
1000 static void __resched_task(struct task_struct
*p
, int tif_bit
);
1002 static inline void resched_task(struct task_struct
*p
)
1004 __resched_task(p
, TIF_NEED_RESCHED
);
1007 #ifdef CONFIG_SCHED_HRTICK
1009 * Use HR-timers to deliver accurate preemption points.
1011 * Its all a bit involved since we cannot program an hrt while holding the
1012 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1015 * When we get rescheduled we reprogram the hrtick_timer outside of the
1018 static inline void resched_hrt(struct task_struct
*p
)
1020 __resched_task(p
, TIF_HRTICK_RESCHED
);
1023 static inline void resched_rq(struct rq
*rq
)
1025 unsigned long flags
;
1027 spin_lock_irqsave(&rq
->lock
, flags
);
1028 resched_task(rq
->curr
);
1029 spin_unlock_irqrestore(&rq
->lock
, flags
);
1033 HRTICK_SET
, /* re-programm hrtick_timer */
1034 HRTICK_RESET
, /* not a new slice */
1039 * - enabled by features
1040 * - hrtimer is actually high res
1042 static inline int hrtick_enabled(struct rq
*rq
)
1044 if (!sched_feat(HRTICK
))
1046 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
1050 * Called to set the hrtick timer state.
1052 * called with rq->lock held and irqs disabled
1054 static void hrtick_start(struct rq
*rq
, u64 delay
, int reset
)
1056 assert_spin_locked(&rq
->lock
);
1059 * preempt at: now + delay
1062 ktime_add_ns(rq
->hrtick_timer
.base
->get_time(), delay
);
1064 * indicate we need to program the timer
1066 __set_bit(HRTICK_SET
, &rq
->hrtick_flags
);
1068 __set_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
1071 * New slices are called from the schedule path and don't need a
1072 * forced reschedule.
1075 resched_hrt(rq
->curr
);
1078 static void hrtick_clear(struct rq
*rq
)
1080 if (hrtimer_active(&rq
->hrtick_timer
))
1081 hrtimer_cancel(&rq
->hrtick_timer
);
1085 * Update the timer from the possible pending state.
1087 static void hrtick_set(struct rq
*rq
)
1091 unsigned long flags
;
1093 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1095 spin_lock_irqsave(&rq
->lock
, flags
);
1096 set
= __test_and_clear_bit(HRTICK_SET
, &rq
->hrtick_flags
);
1097 reset
= __test_and_clear_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
1098 time
= rq
->hrtick_expire
;
1099 clear_thread_flag(TIF_HRTICK_RESCHED
);
1100 spin_unlock_irqrestore(&rq
->lock
, flags
);
1103 hrtimer_start(&rq
->hrtick_timer
, time
, HRTIMER_MODE_ABS
);
1104 if (reset
&& !hrtimer_active(&rq
->hrtick_timer
))
1111 * High-resolution timer tick.
1112 * Runs from hardirq context with interrupts disabled.
1114 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
1116 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
1118 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1120 spin_lock(&rq
->lock
);
1121 __update_rq_clock(rq
);
1122 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
1123 spin_unlock(&rq
->lock
);
1125 return HRTIMER_NORESTART
;
1128 static inline void init_rq_hrtick(struct rq
*rq
)
1130 rq
->hrtick_flags
= 0;
1131 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1132 rq
->hrtick_timer
.function
= hrtick
;
1133 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
1136 void hrtick_resched(void)
1139 unsigned long flags
;
1141 if (!test_thread_flag(TIF_HRTICK_RESCHED
))
1144 local_irq_save(flags
);
1145 rq
= cpu_rq(smp_processor_id());
1147 local_irq_restore(flags
);
1150 static inline void hrtick_clear(struct rq
*rq
)
1154 static inline void hrtick_set(struct rq
*rq
)
1158 static inline void init_rq_hrtick(struct rq
*rq
)
1162 void hrtick_resched(void)
1168 * resched_task - mark a task 'to be rescheduled now'.
1170 * On UP this means the setting of the need_resched flag, on SMP it
1171 * might also involve a cross-CPU call to trigger the scheduler on
1176 #ifndef tsk_is_polling
1177 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1180 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1184 assert_spin_locked(&task_rq(p
)->lock
);
1186 if (unlikely(test_tsk_thread_flag(p
, tif_bit
)))
1189 set_tsk_thread_flag(p
, tif_bit
);
1192 if (cpu
== smp_processor_id())
1195 /* NEED_RESCHED must be visible before we test polling */
1197 if (!tsk_is_polling(p
))
1198 smp_send_reschedule(cpu
);
1201 static void resched_cpu(int cpu
)
1203 struct rq
*rq
= cpu_rq(cpu
);
1204 unsigned long flags
;
1206 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1208 resched_task(cpu_curr(cpu
));
1209 spin_unlock_irqrestore(&rq
->lock
, flags
);
1214 * When add_timer_on() enqueues a timer into the timer wheel of an
1215 * idle CPU then this timer might expire before the next timer event
1216 * which is scheduled to wake up that CPU. In case of a completely
1217 * idle system the next event might even be infinite time into the
1218 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1219 * leaves the inner idle loop so the newly added timer is taken into
1220 * account when the CPU goes back to idle and evaluates the timer
1221 * wheel for the next timer event.
1223 void wake_up_idle_cpu(int cpu
)
1225 struct rq
*rq
= cpu_rq(cpu
);
1227 if (cpu
== smp_processor_id())
1231 * This is safe, as this function is called with the timer
1232 * wheel base lock of (cpu) held. When the CPU is on the way
1233 * to idle and has not yet set rq->curr to idle then it will
1234 * be serialized on the timer wheel base lock and take the new
1235 * timer into account automatically.
1237 if (rq
->curr
!= rq
->idle
)
1241 * We can set TIF_RESCHED on the idle task of the other CPU
1242 * lockless. The worst case is that the other CPU runs the
1243 * idle task through an additional NOOP schedule()
1245 set_tsk_thread_flag(rq
->idle
, TIF_NEED_RESCHED
);
1247 /* NEED_RESCHED must be visible before we test polling */
1249 if (!tsk_is_polling(rq
->idle
))
1250 smp_send_reschedule(cpu
);
1255 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1257 assert_spin_locked(&task_rq(p
)->lock
);
1258 set_tsk_thread_flag(p
, tif_bit
);
1262 #if BITS_PER_LONG == 32
1263 # define WMULT_CONST (~0UL)
1265 # define WMULT_CONST (1UL << 32)
1268 #define WMULT_SHIFT 32
1271 * Shift right and round:
1273 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1275 static unsigned long
1276 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1277 struct load_weight
*lw
)
1281 if (unlikely(!lw
->inv_weight
))
1282 lw
->inv_weight
= (WMULT_CONST
-lw
->weight
/2) / (lw
->weight
+1);
1284 tmp
= (u64
)delta_exec
* weight
;
1286 * Check whether we'd overflow the 64-bit multiplication:
1288 if (unlikely(tmp
> WMULT_CONST
))
1289 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1292 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1294 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1297 static inline unsigned long
1298 calc_delta_fair(unsigned long delta_exec
, struct load_weight
*lw
)
1300 return calc_delta_mine(delta_exec
, NICE_0_LOAD
, lw
);
1303 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1309 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1316 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1317 * of tasks with abnormal "nice" values across CPUs the contribution that
1318 * each task makes to its run queue's load is weighted according to its
1319 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1320 * scaled version of the new time slice allocation that they receive on time
1324 #define WEIGHT_IDLEPRIO 2
1325 #define WMULT_IDLEPRIO (1 << 31)
1328 * Nice levels are multiplicative, with a gentle 10% change for every
1329 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1330 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1331 * that remained on nice 0.
1333 * The "10% effect" is relative and cumulative: from _any_ nice level,
1334 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1335 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1336 * If a task goes up by ~10% and another task goes down by ~10% then
1337 * the relative distance between them is ~25%.)
1339 static const int prio_to_weight
[40] = {
1340 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1341 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1342 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1343 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1344 /* 0 */ 1024, 820, 655, 526, 423,
1345 /* 5 */ 335, 272, 215, 172, 137,
1346 /* 10 */ 110, 87, 70, 56, 45,
1347 /* 15 */ 36, 29, 23, 18, 15,
1351 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1353 * In cases where the weight does not change often, we can use the
1354 * precalculated inverse to speed up arithmetics by turning divisions
1355 * into multiplications:
1357 static const u32 prio_to_wmult
[40] = {
1358 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1359 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1360 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1361 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1362 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1363 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1364 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1365 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1368 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1371 * runqueue iterator, to support SMP load-balancing between different
1372 * scheduling classes, without having to expose their internal data
1373 * structures to the load-balancing proper:
1375 struct rq_iterator
{
1377 struct task_struct
*(*start
)(void *);
1378 struct task_struct
*(*next
)(void *);
1382 static unsigned long
1383 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1384 unsigned long max_load_move
, struct sched_domain
*sd
,
1385 enum cpu_idle_type idle
, int *all_pinned
,
1386 int *this_best_prio
, struct rq_iterator
*iterator
);
1389 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1390 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1391 struct rq_iterator
*iterator
);
1394 #ifdef CONFIG_CGROUP_CPUACCT
1395 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1397 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1401 static unsigned long source_load(int cpu
, int type
);
1402 static unsigned long target_load(int cpu
, int type
);
1403 static unsigned long cpu_avg_load_per_task(int cpu
);
1404 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1405 #endif /* CONFIG_SMP */
1407 #include "sched_stats.h"
1408 #include "sched_idletask.c"
1409 #include "sched_fair.c"
1410 #include "sched_rt.c"
1411 #ifdef CONFIG_SCHED_DEBUG
1412 # include "sched_debug.c"
1415 #define sched_class_highest (&rt_sched_class)
1417 static inline void inc_load(struct rq
*rq
, const struct task_struct
*p
)
1419 update_load_add(&rq
->load
, p
->se
.load
.weight
);
1422 static inline void dec_load(struct rq
*rq
, const struct task_struct
*p
)
1424 update_load_sub(&rq
->load
, p
->se
.load
.weight
);
1427 static void inc_nr_running(struct task_struct
*p
, struct rq
*rq
)
1433 static void dec_nr_running(struct task_struct
*p
, struct rq
*rq
)
1439 static void set_load_weight(struct task_struct
*p
)
1441 if (task_has_rt_policy(p
)) {
1442 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1443 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1448 * SCHED_IDLE tasks get minimal weight:
1450 if (p
->policy
== SCHED_IDLE
) {
1451 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1452 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1456 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1457 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1460 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1462 sched_info_queued(p
);
1463 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1467 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1469 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1474 * __normal_prio - return the priority that is based on the static prio
1476 static inline int __normal_prio(struct task_struct
*p
)
1478 return p
->static_prio
;
1482 * Calculate the expected normal priority: i.e. priority
1483 * without taking RT-inheritance into account. Might be
1484 * boosted by interactivity modifiers. Changes upon fork,
1485 * setprio syscalls, and whenever the interactivity
1486 * estimator recalculates.
1488 static inline int normal_prio(struct task_struct
*p
)
1492 if (task_has_rt_policy(p
))
1493 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1495 prio
= __normal_prio(p
);
1500 * Calculate the current priority, i.e. the priority
1501 * taken into account by the scheduler. This value might
1502 * be boosted by RT tasks, or might be boosted by
1503 * interactivity modifiers. Will be RT if the task got
1504 * RT-boosted. If not then it returns p->normal_prio.
1506 static int effective_prio(struct task_struct
*p
)
1508 p
->normal_prio
= normal_prio(p
);
1510 * If we are RT tasks or we were boosted to RT priority,
1511 * keep the priority unchanged. Otherwise, update priority
1512 * to the normal priority:
1514 if (!rt_prio(p
->prio
))
1515 return p
->normal_prio
;
1520 * activate_task - move a task to the runqueue.
1522 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1524 if (task_contributes_to_load(p
))
1525 rq
->nr_uninterruptible
--;
1527 enqueue_task(rq
, p
, wakeup
);
1528 inc_nr_running(p
, rq
);
1532 * deactivate_task - remove a task from the runqueue.
1534 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1536 if (task_contributes_to_load(p
))
1537 rq
->nr_uninterruptible
++;
1539 dequeue_task(rq
, p
, sleep
);
1540 dec_nr_running(p
, rq
);
1544 * task_curr - is this task currently executing on a CPU?
1545 * @p: the task in question.
1547 inline int task_curr(const struct task_struct
*p
)
1549 return cpu_curr(task_cpu(p
)) == p
;
1552 /* Used instead of source_load when we know the type == 0 */
1553 unsigned long weighted_cpuload(const int cpu
)
1555 return cpu_rq(cpu
)->load
.weight
;
1558 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1560 set_task_rq(p
, cpu
);
1563 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1564 * successfuly executed on another CPU. We must ensure that updates of
1565 * per-task data have been completed by this moment.
1568 task_thread_info(p
)->cpu
= cpu
;
1572 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1573 const struct sched_class
*prev_class
,
1574 int oldprio
, int running
)
1576 if (prev_class
!= p
->sched_class
) {
1577 if (prev_class
->switched_from
)
1578 prev_class
->switched_from(rq
, p
, running
);
1579 p
->sched_class
->switched_to(rq
, p
, running
);
1581 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1587 * Is this task likely cache-hot:
1590 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
1595 * Buddy candidates are cache hot:
1597 if (sched_feat(CACHE_HOT_BUDDY
) && (&p
->se
== cfs_rq_of(&p
->se
)->next
))
1600 if (p
->sched_class
!= &fair_sched_class
)
1603 if (sysctl_sched_migration_cost
== -1)
1605 if (sysctl_sched_migration_cost
== 0)
1608 delta
= now
- p
->se
.exec_start
;
1610 return delta
< (s64
)sysctl_sched_migration_cost
;
1614 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1616 int old_cpu
= task_cpu(p
);
1617 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
1618 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
1619 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
1622 clock_offset
= old_rq
->clock
- new_rq
->clock
;
1624 #ifdef CONFIG_SCHEDSTATS
1625 if (p
->se
.wait_start
)
1626 p
->se
.wait_start
-= clock_offset
;
1627 if (p
->se
.sleep_start
)
1628 p
->se
.sleep_start
-= clock_offset
;
1629 if (p
->se
.block_start
)
1630 p
->se
.block_start
-= clock_offset
;
1631 if (old_cpu
!= new_cpu
) {
1632 schedstat_inc(p
, se
.nr_migrations
);
1633 if (task_hot(p
, old_rq
->clock
, NULL
))
1634 schedstat_inc(p
, se
.nr_forced2_migrations
);
1637 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
1638 new_cfsrq
->min_vruntime
;
1640 __set_task_cpu(p
, new_cpu
);
1643 struct migration_req
{
1644 struct list_head list
;
1646 struct task_struct
*task
;
1649 struct completion done
;
1653 * The task's runqueue lock must be held.
1654 * Returns true if you have to wait for migration thread.
1657 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1659 struct rq
*rq
= task_rq(p
);
1662 * If the task is not on a runqueue (and not running), then
1663 * it is sufficient to simply update the task's cpu field.
1665 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
1666 set_task_cpu(p
, dest_cpu
);
1670 init_completion(&req
->done
);
1672 req
->dest_cpu
= dest_cpu
;
1673 list_add(&req
->list
, &rq
->migration_queue
);
1679 * wait_task_inactive - wait for a thread to unschedule.
1681 * The caller must ensure that the task *will* unschedule sometime soon,
1682 * else this function might spin for a *long* time. This function can't
1683 * be called with interrupts off, or it may introduce deadlock with
1684 * smp_call_function() if an IPI is sent by the same process we are
1685 * waiting to become inactive.
1687 void wait_task_inactive(struct task_struct
*p
)
1689 unsigned long flags
;
1695 * We do the initial early heuristics without holding
1696 * any task-queue locks at all. We'll only try to get
1697 * the runqueue lock when things look like they will
1703 * If the task is actively running on another CPU
1704 * still, just relax and busy-wait without holding
1707 * NOTE! Since we don't hold any locks, it's not
1708 * even sure that "rq" stays as the right runqueue!
1709 * But we don't care, since "task_running()" will
1710 * return false if the runqueue has changed and p
1711 * is actually now running somewhere else!
1713 while (task_running(rq
, p
))
1717 * Ok, time to look more closely! We need the rq
1718 * lock now, to be *sure*. If we're wrong, we'll
1719 * just go back and repeat.
1721 rq
= task_rq_lock(p
, &flags
);
1722 running
= task_running(rq
, p
);
1723 on_rq
= p
->se
.on_rq
;
1724 task_rq_unlock(rq
, &flags
);
1727 * Was it really running after all now that we
1728 * checked with the proper locks actually held?
1730 * Oops. Go back and try again..
1732 if (unlikely(running
)) {
1738 * It's not enough that it's not actively running,
1739 * it must be off the runqueue _entirely_, and not
1742 * So if it wa still runnable (but just not actively
1743 * running right now), it's preempted, and we should
1744 * yield - it could be a while.
1746 if (unlikely(on_rq
)) {
1747 schedule_timeout_uninterruptible(1);
1752 * Ahh, all good. It wasn't running, and it wasn't
1753 * runnable, which means that it will never become
1754 * running in the future either. We're all done!
1761 * kick_process - kick a running thread to enter/exit the kernel
1762 * @p: the to-be-kicked thread
1764 * Cause a process which is running on another CPU to enter
1765 * kernel-mode, without any delay. (to get signals handled.)
1767 * NOTE: this function doesnt have to take the runqueue lock,
1768 * because all it wants to ensure is that the remote task enters
1769 * the kernel. If the IPI races and the task has been migrated
1770 * to another CPU then no harm is done and the purpose has been
1773 void kick_process(struct task_struct
*p
)
1779 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1780 smp_send_reschedule(cpu
);
1785 * Return a low guess at the load of a migration-source cpu weighted
1786 * according to the scheduling class and "nice" value.
1788 * We want to under-estimate the load of migration sources, to
1789 * balance conservatively.
1791 static unsigned long source_load(int cpu
, int type
)
1793 struct rq
*rq
= cpu_rq(cpu
);
1794 unsigned long total
= weighted_cpuload(cpu
);
1799 return min(rq
->cpu_load
[type
-1], total
);
1803 * Return a high guess at the load of a migration-target cpu weighted
1804 * according to the scheduling class and "nice" value.
1806 static unsigned long target_load(int cpu
, int type
)
1808 struct rq
*rq
= cpu_rq(cpu
);
1809 unsigned long total
= weighted_cpuload(cpu
);
1814 return max(rq
->cpu_load
[type
-1], total
);
1818 * Return the average load per task on the cpu's run queue
1820 static unsigned long cpu_avg_load_per_task(int cpu
)
1822 struct rq
*rq
= cpu_rq(cpu
);
1823 unsigned long total
= weighted_cpuload(cpu
);
1824 unsigned long n
= rq
->nr_running
;
1826 return n
? total
/ n
: SCHED_LOAD_SCALE
;
1830 * find_idlest_group finds and returns the least busy CPU group within the
1833 static struct sched_group
*
1834 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1836 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1837 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1838 int load_idx
= sd
->forkexec_idx
;
1839 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1842 unsigned long load
, avg_load
;
1846 /* Skip over this group if it has no CPUs allowed */
1847 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1850 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1852 /* Tally up the load of all CPUs in the group */
1855 for_each_cpu_mask(i
, group
->cpumask
) {
1856 /* Bias balancing toward cpus of our domain */
1858 load
= source_load(i
, load_idx
);
1860 load
= target_load(i
, load_idx
);
1865 /* Adjust by relative CPU power of the group */
1866 avg_load
= sg_div_cpu_power(group
,
1867 avg_load
* SCHED_LOAD_SCALE
);
1870 this_load
= avg_load
;
1872 } else if (avg_load
< min_load
) {
1873 min_load
= avg_load
;
1876 } while (group
= group
->next
, group
!= sd
->groups
);
1878 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1884 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1887 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
1890 unsigned long load
, min_load
= ULONG_MAX
;
1894 /* Traverse only the allowed CPUs */
1895 cpus_and(tmp
, group
->cpumask
, p
->cpus_allowed
);
1897 for_each_cpu_mask(i
, tmp
) {
1898 load
= weighted_cpuload(i
);
1900 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1910 * sched_balance_self: balance the current task (running on cpu) in domains
1911 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1914 * Balance, ie. select the least loaded group.
1916 * Returns the target CPU number, or the same CPU if no balancing is needed.
1918 * preempt must be disabled.
1920 static int sched_balance_self(int cpu
, int flag
)
1922 struct task_struct
*t
= current
;
1923 struct sched_domain
*tmp
, *sd
= NULL
;
1925 for_each_domain(cpu
, tmp
) {
1927 * If power savings logic is enabled for a domain, stop there.
1929 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
1931 if (tmp
->flags
& flag
)
1937 struct sched_group
*group
;
1938 int new_cpu
, weight
;
1940 if (!(sd
->flags
& flag
)) {
1946 group
= find_idlest_group(sd
, t
, cpu
);
1952 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
1953 if (new_cpu
== -1 || new_cpu
== cpu
) {
1954 /* Now try balancing at a lower domain level of cpu */
1959 /* Now try balancing at a lower domain level of new_cpu */
1962 weight
= cpus_weight(span
);
1963 for_each_domain(cpu
, tmp
) {
1964 if (weight
<= cpus_weight(tmp
->span
))
1966 if (tmp
->flags
& flag
)
1969 /* while loop will break here if sd == NULL */
1975 #endif /* CONFIG_SMP */
1978 * try_to_wake_up - wake up a thread
1979 * @p: the to-be-woken-up thread
1980 * @state: the mask of task states that can be woken
1981 * @sync: do a synchronous wakeup?
1983 * Put it on the run-queue if it's not already there. The "current"
1984 * thread is always on the run-queue (except when the actual
1985 * re-schedule is in progress), and as such you're allowed to do
1986 * the simpler "current->state = TASK_RUNNING" to mark yourself
1987 * runnable without the overhead of this.
1989 * returns failure only if the task is already active.
1991 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
1993 int cpu
, orig_cpu
, this_cpu
, success
= 0;
1994 unsigned long flags
;
1998 if (!sched_feat(SYNC_WAKEUPS
))
2002 rq
= task_rq_lock(p
, &flags
);
2003 old_state
= p
->state
;
2004 if (!(old_state
& state
))
2012 this_cpu
= smp_processor_id();
2015 if (unlikely(task_running(rq
, p
)))
2018 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
2019 if (cpu
!= orig_cpu
) {
2020 set_task_cpu(p
, cpu
);
2021 task_rq_unlock(rq
, &flags
);
2022 /* might preempt at this point */
2023 rq
= task_rq_lock(p
, &flags
);
2024 old_state
= p
->state
;
2025 if (!(old_state
& state
))
2030 this_cpu
= smp_processor_id();
2034 #ifdef CONFIG_SCHEDSTATS
2035 schedstat_inc(rq
, ttwu_count
);
2036 if (cpu
== this_cpu
)
2037 schedstat_inc(rq
, ttwu_local
);
2039 struct sched_domain
*sd
;
2040 for_each_domain(this_cpu
, sd
) {
2041 if (cpu_isset(cpu
, sd
->span
)) {
2042 schedstat_inc(sd
, ttwu_wake_remote
);
2050 #endif /* CONFIG_SMP */
2051 schedstat_inc(p
, se
.nr_wakeups
);
2053 schedstat_inc(p
, se
.nr_wakeups_sync
);
2054 if (orig_cpu
!= cpu
)
2055 schedstat_inc(p
, se
.nr_wakeups_migrate
);
2056 if (cpu
== this_cpu
)
2057 schedstat_inc(p
, se
.nr_wakeups_local
);
2059 schedstat_inc(p
, se
.nr_wakeups_remote
);
2060 update_rq_clock(rq
);
2061 activate_task(rq
, p
, 1);
2065 check_preempt_curr(rq
, p
);
2067 p
->state
= TASK_RUNNING
;
2069 if (p
->sched_class
->task_wake_up
)
2070 p
->sched_class
->task_wake_up(rq
, p
);
2073 task_rq_unlock(rq
, &flags
);
2078 int wake_up_process(struct task_struct
*p
)
2080 return try_to_wake_up(p
, TASK_ALL
, 0);
2082 EXPORT_SYMBOL(wake_up_process
);
2084 int wake_up_state(struct task_struct
*p
, unsigned int state
)
2086 return try_to_wake_up(p
, state
, 0);
2090 * Perform scheduler related setup for a newly forked process p.
2091 * p is forked by current.
2093 * __sched_fork() is basic setup used by init_idle() too:
2095 static void __sched_fork(struct task_struct
*p
)
2097 p
->se
.exec_start
= 0;
2098 p
->se
.sum_exec_runtime
= 0;
2099 p
->se
.prev_sum_exec_runtime
= 0;
2100 p
->se
.last_wakeup
= 0;
2101 p
->se
.avg_overlap
= 0;
2103 #ifdef CONFIG_SCHEDSTATS
2104 p
->se
.wait_start
= 0;
2105 p
->se
.sum_sleep_runtime
= 0;
2106 p
->se
.sleep_start
= 0;
2107 p
->se
.block_start
= 0;
2108 p
->se
.sleep_max
= 0;
2109 p
->se
.block_max
= 0;
2111 p
->se
.slice_max
= 0;
2115 INIT_LIST_HEAD(&p
->rt
.run_list
);
2118 #ifdef CONFIG_PREEMPT_NOTIFIERS
2119 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
2123 * We mark the process as running here, but have not actually
2124 * inserted it onto the runqueue yet. This guarantees that
2125 * nobody will actually run it, and a signal or other external
2126 * event cannot wake it up and insert it on the runqueue either.
2128 p
->state
= TASK_RUNNING
;
2132 * fork()/clone()-time setup:
2134 void sched_fork(struct task_struct
*p
, int clone_flags
)
2136 int cpu
= get_cpu();
2141 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
2143 set_task_cpu(p
, cpu
);
2146 * Make sure we do not leak PI boosting priority to the child:
2148 p
->prio
= current
->normal_prio
;
2149 if (!rt_prio(p
->prio
))
2150 p
->sched_class
= &fair_sched_class
;
2152 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2153 if (likely(sched_info_on()))
2154 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
2156 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2159 #ifdef CONFIG_PREEMPT
2160 /* Want to start with kernel preemption disabled. */
2161 task_thread_info(p
)->preempt_count
= 1;
2167 * wake_up_new_task - wake up a newly created task for the first time.
2169 * This function will do some initial scheduler statistics housekeeping
2170 * that must be done for every newly created context, then puts the task
2171 * on the runqueue and wakes it.
2173 void wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
2175 unsigned long flags
;
2178 rq
= task_rq_lock(p
, &flags
);
2179 BUG_ON(p
->state
!= TASK_RUNNING
);
2180 update_rq_clock(rq
);
2182 p
->prio
= effective_prio(p
);
2184 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
2185 activate_task(rq
, p
, 0);
2188 * Let the scheduling class do new task startup
2189 * management (if any):
2191 p
->sched_class
->task_new(rq
, p
);
2192 inc_nr_running(p
, rq
);
2194 check_preempt_curr(rq
, p
);
2196 if (p
->sched_class
->task_wake_up
)
2197 p
->sched_class
->task_wake_up(rq
, p
);
2199 task_rq_unlock(rq
, &flags
);
2202 #ifdef CONFIG_PREEMPT_NOTIFIERS
2205 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2206 * @notifier: notifier struct to register
2208 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2210 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2212 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2215 * preempt_notifier_unregister - no longer interested in preemption notifications
2216 * @notifier: notifier struct to unregister
2218 * This is safe to call from within a preemption notifier.
2220 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2222 hlist_del(¬ifier
->link
);
2224 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2226 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2228 struct preempt_notifier
*notifier
;
2229 struct hlist_node
*node
;
2231 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2232 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2236 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2237 struct task_struct
*next
)
2239 struct preempt_notifier
*notifier
;
2240 struct hlist_node
*node
;
2242 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2243 notifier
->ops
->sched_out(notifier
, next
);
2248 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2253 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2254 struct task_struct
*next
)
2261 * prepare_task_switch - prepare to switch tasks
2262 * @rq: the runqueue preparing to switch
2263 * @prev: the current task that is being switched out
2264 * @next: the task we are going to switch to.
2266 * This is called with the rq lock held and interrupts off. It must
2267 * be paired with a subsequent finish_task_switch after the context
2270 * prepare_task_switch sets up locking and calls architecture specific
2274 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2275 struct task_struct
*next
)
2277 fire_sched_out_preempt_notifiers(prev
, next
);
2278 prepare_lock_switch(rq
, next
);
2279 prepare_arch_switch(next
);
2283 * finish_task_switch - clean up after a task-switch
2284 * @rq: runqueue associated with task-switch
2285 * @prev: the thread we just switched away from.
2287 * finish_task_switch must be called after the context switch, paired
2288 * with a prepare_task_switch call before the context switch.
2289 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2290 * and do any other architecture-specific cleanup actions.
2292 * Note that we may have delayed dropping an mm in context_switch(). If
2293 * so, we finish that here outside of the runqueue lock. (Doing it
2294 * with the lock held can cause deadlocks; see schedule() for
2297 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2298 __releases(rq
->lock
)
2300 struct mm_struct
*mm
= rq
->prev_mm
;
2306 * A task struct has one reference for the use as "current".
2307 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2308 * schedule one last time. The schedule call will never return, and
2309 * the scheduled task must drop that reference.
2310 * The test for TASK_DEAD must occur while the runqueue locks are
2311 * still held, otherwise prev could be scheduled on another cpu, die
2312 * there before we look at prev->state, and then the reference would
2314 * Manfred Spraul <manfred@colorfullife.com>
2316 prev_state
= prev
->state
;
2317 finish_arch_switch(prev
);
2318 finish_lock_switch(rq
, prev
);
2320 if (current
->sched_class
->post_schedule
)
2321 current
->sched_class
->post_schedule(rq
);
2324 fire_sched_in_preempt_notifiers(current
);
2327 if (unlikely(prev_state
== TASK_DEAD
)) {
2329 * Remove function-return probe instances associated with this
2330 * task and put them back on the free list.
2332 kprobe_flush_task(prev
);
2333 put_task_struct(prev
);
2338 * schedule_tail - first thing a freshly forked thread must call.
2339 * @prev: the thread we just switched away from.
2341 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2342 __releases(rq
->lock
)
2344 struct rq
*rq
= this_rq();
2346 finish_task_switch(rq
, prev
);
2347 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2348 /* In this case, finish_task_switch does not reenable preemption */
2351 if (current
->set_child_tid
)
2352 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2356 * context_switch - switch to the new MM and the new
2357 * thread's register state.
2360 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2361 struct task_struct
*next
)
2363 struct mm_struct
*mm
, *oldmm
;
2365 prepare_task_switch(rq
, prev
, next
);
2367 oldmm
= prev
->active_mm
;
2369 * For paravirt, this is coupled with an exit in switch_to to
2370 * combine the page table reload and the switch backend into
2373 arch_enter_lazy_cpu_mode();
2375 if (unlikely(!mm
)) {
2376 next
->active_mm
= oldmm
;
2377 atomic_inc(&oldmm
->mm_count
);
2378 enter_lazy_tlb(oldmm
, next
);
2380 switch_mm(oldmm
, mm
, next
);
2382 if (unlikely(!prev
->mm
)) {
2383 prev
->active_mm
= NULL
;
2384 rq
->prev_mm
= oldmm
;
2387 * Since the runqueue lock will be released by the next
2388 * task (which is an invalid locking op but in the case
2389 * of the scheduler it's an obvious special-case), so we
2390 * do an early lockdep release here:
2392 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2393 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2396 /* Here we just switch the register state and the stack. */
2397 switch_to(prev
, next
, prev
);
2401 * this_rq must be evaluated again because prev may have moved
2402 * CPUs since it called schedule(), thus the 'rq' on its stack
2403 * frame will be invalid.
2405 finish_task_switch(this_rq(), prev
);
2409 * nr_running, nr_uninterruptible and nr_context_switches:
2411 * externally visible scheduler statistics: current number of runnable
2412 * threads, current number of uninterruptible-sleeping threads, total
2413 * number of context switches performed since bootup.
2415 unsigned long nr_running(void)
2417 unsigned long i
, sum
= 0;
2419 for_each_online_cpu(i
)
2420 sum
+= cpu_rq(i
)->nr_running
;
2425 unsigned long nr_uninterruptible(void)
2427 unsigned long i
, sum
= 0;
2429 for_each_possible_cpu(i
)
2430 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2433 * Since we read the counters lockless, it might be slightly
2434 * inaccurate. Do not allow it to go below zero though:
2436 if (unlikely((long)sum
< 0))
2442 unsigned long long nr_context_switches(void)
2445 unsigned long long sum
= 0;
2447 for_each_possible_cpu(i
)
2448 sum
+= cpu_rq(i
)->nr_switches
;
2453 unsigned long nr_iowait(void)
2455 unsigned long i
, sum
= 0;
2457 for_each_possible_cpu(i
)
2458 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2463 unsigned long nr_active(void)
2465 unsigned long i
, running
= 0, uninterruptible
= 0;
2467 for_each_online_cpu(i
) {
2468 running
+= cpu_rq(i
)->nr_running
;
2469 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2472 if (unlikely((long)uninterruptible
< 0))
2473 uninterruptible
= 0;
2475 return running
+ uninterruptible
;
2479 * Update rq->cpu_load[] statistics. This function is usually called every
2480 * scheduler tick (TICK_NSEC).
2482 static void update_cpu_load(struct rq
*this_rq
)
2484 unsigned long this_load
= this_rq
->load
.weight
;
2487 this_rq
->nr_load_updates
++;
2489 /* Update our load: */
2490 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2491 unsigned long old_load
, new_load
;
2493 /* scale is effectively 1 << i now, and >> i divides by scale */
2495 old_load
= this_rq
->cpu_load
[i
];
2496 new_load
= this_load
;
2498 * Round up the averaging division if load is increasing. This
2499 * prevents us from getting stuck on 9 if the load is 10, for
2502 if (new_load
> old_load
)
2503 new_load
+= scale
-1;
2504 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2511 * double_rq_lock - safely lock two runqueues
2513 * Note this does not disable interrupts like task_rq_lock,
2514 * you need to do so manually before calling.
2516 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2517 __acquires(rq1
->lock
)
2518 __acquires(rq2
->lock
)
2520 BUG_ON(!irqs_disabled());
2522 spin_lock(&rq1
->lock
);
2523 __acquire(rq2
->lock
); /* Fake it out ;) */
2526 spin_lock(&rq1
->lock
);
2527 spin_lock(&rq2
->lock
);
2529 spin_lock(&rq2
->lock
);
2530 spin_lock(&rq1
->lock
);
2533 update_rq_clock(rq1
);
2534 update_rq_clock(rq2
);
2538 * double_rq_unlock - safely unlock two runqueues
2540 * Note this does not restore interrupts like task_rq_unlock,
2541 * you need to do so manually after calling.
2543 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2544 __releases(rq1
->lock
)
2545 __releases(rq2
->lock
)
2547 spin_unlock(&rq1
->lock
);
2549 spin_unlock(&rq2
->lock
);
2551 __release(rq2
->lock
);
2555 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2557 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
2558 __releases(this_rq
->lock
)
2559 __acquires(busiest
->lock
)
2560 __acquires(this_rq
->lock
)
2564 if (unlikely(!irqs_disabled())) {
2565 /* printk() doesn't work good under rq->lock */
2566 spin_unlock(&this_rq
->lock
);
2569 if (unlikely(!spin_trylock(&busiest
->lock
))) {
2570 if (busiest
< this_rq
) {
2571 spin_unlock(&this_rq
->lock
);
2572 spin_lock(&busiest
->lock
);
2573 spin_lock(&this_rq
->lock
);
2576 spin_lock(&busiest
->lock
);
2582 * If dest_cpu is allowed for this process, migrate the task to it.
2583 * This is accomplished by forcing the cpu_allowed mask to only
2584 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2585 * the cpu_allowed mask is restored.
2587 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
2589 struct migration_req req
;
2590 unsigned long flags
;
2593 rq
= task_rq_lock(p
, &flags
);
2594 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
2595 || unlikely(cpu_is_offline(dest_cpu
)))
2598 /* force the process onto the specified CPU */
2599 if (migrate_task(p
, dest_cpu
, &req
)) {
2600 /* Need to wait for migration thread (might exit: take ref). */
2601 struct task_struct
*mt
= rq
->migration_thread
;
2603 get_task_struct(mt
);
2604 task_rq_unlock(rq
, &flags
);
2605 wake_up_process(mt
);
2606 put_task_struct(mt
);
2607 wait_for_completion(&req
.done
);
2612 task_rq_unlock(rq
, &flags
);
2616 * sched_exec - execve() is a valuable balancing opportunity, because at
2617 * this point the task has the smallest effective memory and cache footprint.
2619 void sched_exec(void)
2621 int new_cpu
, this_cpu
= get_cpu();
2622 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
2624 if (new_cpu
!= this_cpu
)
2625 sched_migrate_task(current
, new_cpu
);
2629 * pull_task - move a task from a remote runqueue to the local runqueue.
2630 * Both runqueues must be locked.
2632 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
2633 struct rq
*this_rq
, int this_cpu
)
2635 deactivate_task(src_rq
, p
, 0);
2636 set_task_cpu(p
, this_cpu
);
2637 activate_task(this_rq
, p
, 0);
2639 * Note that idle threads have a prio of MAX_PRIO, for this test
2640 * to be always true for them.
2642 check_preempt_curr(this_rq
, p
);
2646 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2649 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2650 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2654 * We do not migrate tasks that are:
2655 * 1) running (obviously), or
2656 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2657 * 3) are cache-hot on their current CPU.
2659 if (!cpu_isset(this_cpu
, p
->cpus_allowed
)) {
2660 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
2665 if (task_running(rq
, p
)) {
2666 schedstat_inc(p
, se
.nr_failed_migrations_running
);
2671 * Aggressive migration if:
2672 * 1) task is cache cold, or
2673 * 2) too many balance attempts have failed.
2676 if (!task_hot(p
, rq
->clock
, sd
) ||
2677 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
2678 #ifdef CONFIG_SCHEDSTATS
2679 if (task_hot(p
, rq
->clock
, sd
)) {
2680 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2681 schedstat_inc(p
, se
.nr_forced_migrations
);
2687 if (task_hot(p
, rq
->clock
, sd
)) {
2688 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
2694 static unsigned long
2695 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2696 unsigned long max_load_move
, struct sched_domain
*sd
,
2697 enum cpu_idle_type idle
, int *all_pinned
,
2698 int *this_best_prio
, struct rq_iterator
*iterator
)
2700 int loops
= 0, pulled
= 0, pinned
= 0, skip_for_load
;
2701 struct task_struct
*p
;
2702 long rem_load_move
= max_load_move
;
2704 if (max_load_move
== 0)
2710 * Start the load-balancing iterator:
2712 p
= iterator
->start(iterator
->arg
);
2714 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
2717 * To help distribute high priority tasks across CPUs we don't
2718 * skip a task if it will be the highest priority task (i.e. smallest
2719 * prio value) on its new queue regardless of its load weight
2721 skip_for_load
= (p
->se
.load
.weight
>> 1) > rem_load_move
+
2722 SCHED_LOAD_SCALE_FUZZ
;
2723 if ((skip_for_load
&& p
->prio
>= *this_best_prio
) ||
2724 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2725 p
= iterator
->next(iterator
->arg
);
2729 pull_task(busiest
, p
, this_rq
, this_cpu
);
2731 rem_load_move
-= p
->se
.load
.weight
;
2734 * We only want to steal up to the prescribed amount of weighted load.
2736 if (rem_load_move
> 0) {
2737 if (p
->prio
< *this_best_prio
)
2738 *this_best_prio
= p
->prio
;
2739 p
= iterator
->next(iterator
->arg
);
2744 * Right now, this is one of only two places pull_task() is called,
2745 * so we can safely collect pull_task() stats here rather than
2746 * inside pull_task().
2748 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2751 *all_pinned
= pinned
;
2753 return max_load_move
- rem_load_move
;
2757 * move_tasks tries to move up to max_load_move weighted load from busiest to
2758 * this_rq, as part of a balancing operation within domain "sd".
2759 * Returns 1 if successful and 0 otherwise.
2761 * Called with both runqueues locked.
2763 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2764 unsigned long max_load_move
,
2765 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2768 const struct sched_class
*class = sched_class_highest
;
2769 unsigned long total_load_moved
= 0;
2770 int this_best_prio
= this_rq
->curr
->prio
;
2774 class->load_balance(this_rq
, this_cpu
, busiest
,
2775 max_load_move
- total_load_moved
,
2776 sd
, idle
, all_pinned
, &this_best_prio
);
2777 class = class->next
;
2778 } while (class && max_load_move
> total_load_moved
);
2780 return total_load_moved
> 0;
2784 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2785 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2786 struct rq_iterator
*iterator
)
2788 struct task_struct
*p
= iterator
->start(iterator
->arg
);
2792 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2793 pull_task(busiest
, p
, this_rq
, this_cpu
);
2795 * Right now, this is only the second place pull_task()
2796 * is called, so we can safely collect pull_task()
2797 * stats here rather than inside pull_task().
2799 schedstat_inc(sd
, lb_gained
[idle
]);
2803 p
= iterator
->next(iterator
->arg
);
2810 * move_one_task tries to move exactly one task from busiest to this_rq, as
2811 * part of active balancing operations within "domain".
2812 * Returns 1 if successful and 0 otherwise.
2814 * Called with both runqueues locked.
2816 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2817 struct sched_domain
*sd
, enum cpu_idle_type idle
)
2819 const struct sched_class
*class;
2821 for (class = sched_class_highest
; class; class = class->next
)
2822 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
2829 * find_busiest_group finds and returns the busiest CPU group within the
2830 * domain. It calculates and returns the amount of weighted load which
2831 * should be moved to restore balance via the imbalance parameter.
2833 static struct sched_group
*
2834 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2835 unsigned long *imbalance
, enum cpu_idle_type idle
,
2836 int *sd_idle
, cpumask_t
*cpus
, int *balance
)
2838 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2839 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2840 unsigned long max_pull
;
2841 unsigned long busiest_load_per_task
, busiest_nr_running
;
2842 unsigned long this_load_per_task
, this_nr_running
;
2843 int load_idx
, group_imb
= 0;
2844 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2845 int power_savings_balance
= 1;
2846 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2847 unsigned long min_nr_running
= ULONG_MAX
;
2848 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2851 max_load
= this_load
= total_load
= total_pwr
= 0;
2852 busiest_load_per_task
= busiest_nr_running
= 0;
2853 this_load_per_task
= this_nr_running
= 0;
2854 if (idle
== CPU_NOT_IDLE
)
2855 load_idx
= sd
->busy_idx
;
2856 else if (idle
== CPU_NEWLY_IDLE
)
2857 load_idx
= sd
->newidle_idx
;
2859 load_idx
= sd
->idle_idx
;
2862 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
2865 int __group_imb
= 0;
2866 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
2867 unsigned long sum_nr_running
, sum_weighted_load
;
2869 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2872 balance_cpu
= first_cpu(group
->cpumask
);
2874 /* Tally up the load of all CPUs in the group */
2875 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2877 min_cpu_load
= ~0UL;
2879 for_each_cpu_mask(i
, group
->cpumask
) {
2882 if (!cpu_isset(i
, *cpus
))
2887 if (*sd_idle
&& rq
->nr_running
)
2890 /* Bias balancing toward cpus of our domain */
2892 if (idle_cpu(i
) && !first_idle_cpu
) {
2897 load
= target_load(i
, load_idx
);
2899 load
= source_load(i
, load_idx
);
2900 if (load
> max_cpu_load
)
2901 max_cpu_load
= load
;
2902 if (min_cpu_load
> load
)
2903 min_cpu_load
= load
;
2907 sum_nr_running
+= rq
->nr_running
;
2908 sum_weighted_load
+= weighted_cpuload(i
);
2912 * First idle cpu or the first cpu(busiest) in this sched group
2913 * is eligible for doing load balancing at this and above
2914 * domains. In the newly idle case, we will allow all the cpu's
2915 * to do the newly idle load balance.
2917 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
2918 balance_cpu
!= this_cpu
&& balance
) {
2923 total_load
+= avg_load
;
2924 total_pwr
+= group
->__cpu_power
;
2926 /* Adjust by relative CPU power of the group */
2927 avg_load
= sg_div_cpu_power(group
,
2928 avg_load
* SCHED_LOAD_SCALE
);
2930 if ((max_cpu_load
- min_cpu_load
) > SCHED_LOAD_SCALE
)
2933 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
2936 this_load
= avg_load
;
2938 this_nr_running
= sum_nr_running
;
2939 this_load_per_task
= sum_weighted_load
;
2940 } else if (avg_load
> max_load
&&
2941 (sum_nr_running
> group_capacity
|| __group_imb
)) {
2942 max_load
= avg_load
;
2944 busiest_nr_running
= sum_nr_running
;
2945 busiest_load_per_task
= sum_weighted_load
;
2946 group_imb
= __group_imb
;
2949 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2951 * Busy processors will not participate in power savings
2954 if (idle
== CPU_NOT_IDLE
||
2955 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2959 * If the local group is idle or completely loaded
2960 * no need to do power savings balance at this domain
2962 if (local_group
&& (this_nr_running
>= group_capacity
||
2964 power_savings_balance
= 0;
2967 * If a group is already running at full capacity or idle,
2968 * don't include that group in power savings calculations
2970 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
2975 * Calculate the group which has the least non-idle load.
2976 * This is the group from where we need to pick up the load
2979 if ((sum_nr_running
< min_nr_running
) ||
2980 (sum_nr_running
== min_nr_running
&&
2981 first_cpu(group
->cpumask
) <
2982 first_cpu(group_min
->cpumask
))) {
2984 min_nr_running
= sum_nr_running
;
2985 min_load_per_task
= sum_weighted_load
/
2990 * Calculate the group which is almost near its
2991 * capacity but still has some space to pick up some load
2992 * from other group and save more power
2994 if (sum_nr_running
<= group_capacity
- 1) {
2995 if (sum_nr_running
> leader_nr_running
||
2996 (sum_nr_running
== leader_nr_running
&&
2997 first_cpu(group
->cpumask
) >
2998 first_cpu(group_leader
->cpumask
))) {
2999 group_leader
= group
;
3000 leader_nr_running
= sum_nr_running
;
3005 group
= group
->next
;
3006 } while (group
!= sd
->groups
);
3008 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
3011 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
3013 if (this_load
>= avg_load
||
3014 100*max_load
<= sd
->imbalance_pct
*this_load
)
3017 busiest_load_per_task
/= busiest_nr_running
;
3019 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
3022 * We're trying to get all the cpus to the average_load, so we don't
3023 * want to push ourselves above the average load, nor do we wish to
3024 * reduce the max loaded cpu below the average load, as either of these
3025 * actions would just result in more rebalancing later, and ping-pong
3026 * tasks around. Thus we look for the minimum possible imbalance.
3027 * Negative imbalances (*we* are more loaded than anyone else) will
3028 * be counted as no imbalance for these purposes -- we can't fix that
3029 * by pulling tasks to us. Be careful of negative numbers as they'll
3030 * appear as very large values with unsigned longs.
3032 if (max_load
<= busiest_load_per_task
)
3036 * In the presence of smp nice balancing, certain scenarios can have
3037 * max load less than avg load(as we skip the groups at or below
3038 * its cpu_power, while calculating max_load..)
3040 if (max_load
< avg_load
) {
3042 goto small_imbalance
;
3045 /* Don't want to pull so many tasks that a group would go idle */
3046 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
3048 /* How much load to actually move to equalise the imbalance */
3049 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
3050 (avg_load
- this_load
) * this->__cpu_power
)
3054 * if *imbalance is less than the average load per runnable task
3055 * there is no gaurantee that any tasks will be moved so we'll have
3056 * a think about bumping its value to force at least one task to be
3059 if (*imbalance
< busiest_load_per_task
) {
3060 unsigned long tmp
, pwr_now
, pwr_move
;
3064 pwr_move
= pwr_now
= 0;
3066 if (this_nr_running
) {
3067 this_load_per_task
/= this_nr_running
;
3068 if (busiest_load_per_task
> this_load_per_task
)
3071 this_load_per_task
= SCHED_LOAD_SCALE
;
3073 if (max_load
- this_load
+ SCHED_LOAD_SCALE_FUZZ
>=
3074 busiest_load_per_task
* imbn
) {
3075 *imbalance
= busiest_load_per_task
;
3080 * OK, we don't have enough imbalance to justify moving tasks,
3081 * however we may be able to increase total CPU power used by
3085 pwr_now
+= busiest
->__cpu_power
*
3086 min(busiest_load_per_task
, max_load
);
3087 pwr_now
+= this->__cpu_power
*
3088 min(this_load_per_task
, this_load
);
3089 pwr_now
/= SCHED_LOAD_SCALE
;
3091 /* Amount of load we'd subtract */
3092 tmp
= sg_div_cpu_power(busiest
,
3093 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3095 pwr_move
+= busiest
->__cpu_power
*
3096 min(busiest_load_per_task
, max_load
- tmp
);
3098 /* Amount of load we'd add */
3099 if (max_load
* busiest
->__cpu_power
<
3100 busiest_load_per_task
* SCHED_LOAD_SCALE
)
3101 tmp
= sg_div_cpu_power(this,
3102 max_load
* busiest
->__cpu_power
);
3104 tmp
= sg_div_cpu_power(this,
3105 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3106 pwr_move
+= this->__cpu_power
*
3107 min(this_load_per_task
, this_load
+ tmp
);
3108 pwr_move
/= SCHED_LOAD_SCALE
;
3110 /* Move if we gain throughput */
3111 if (pwr_move
> pwr_now
)
3112 *imbalance
= busiest_load_per_task
;
3118 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3119 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3122 if (this == group_leader
&& group_leader
!= group_min
) {
3123 *imbalance
= min_load_per_task
;
3133 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3136 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
3137 unsigned long imbalance
, cpumask_t
*cpus
)
3139 struct rq
*busiest
= NULL
, *rq
;
3140 unsigned long max_load
= 0;
3143 for_each_cpu_mask(i
, group
->cpumask
) {
3146 if (!cpu_isset(i
, *cpus
))
3150 wl
= weighted_cpuload(i
);
3152 if (rq
->nr_running
== 1 && wl
> imbalance
)
3155 if (wl
> max_load
) {
3165 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3166 * so long as it is large enough.
3168 #define MAX_PINNED_INTERVAL 512
3171 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3172 * tasks if there is an imbalance.
3174 static int load_balance(int this_cpu
, struct rq
*this_rq
,
3175 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3178 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
3179 struct sched_group
*group
;
3180 unsigned long imbalance
;
3182 cpumask_t cpus
= CPU_MASK_ALL
;
3183 unsigned long flags
;
3186 * When power savings policy is enabled for the parent domain, idle
3187 * sibling can pick up load irrespective of busy siblings. In this case,
3188 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3189 * portraying it as CPU_NOT_IDLE.
3191 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3192 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3195 schedstat_inc(sd
, lb_count
[idle
]);
3198 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
3205 schedstat_inc(sd
, lb_nobusyg
[idle
]);
3209 busiest
= find_busiest_queue(group
, idle
, imbalance
, &cpus
);
3211 schedstat_inc(sd
, lb_nobusyq
[idle
]);
3215 BUG_ON(busiest
== this_rq
);
3217 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
3220 if (busiest
->nr_running
> 1) {
3222 * Attempt to move tasks. If find_busiest_group has found
3223 * an imbalance but busiest->nr_running <= 1, the group is
3224 * still unbalanced. ld_moved simply stays zero, so it is
3225 * correctly treated as an imbalance.
3227 local_irq_save(flags
);
3228 double_rq_lock(this_rq
, busiest
);
3229 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3230 imbalance
, sd
, idle
, &all_pinned
);
3231 double_rq_unlock(this_rq
, busiest
);
3232 local_irq_restore(flags
);
3235 * some other cpu did the load balance for us.
3237 if (ld_moved
&& this_cpu
!= smp_processor_id())
3238 resched_cpu(this_cpu
);
3240 /* All tasks on this runqueue were pinned by CPU affinity */
3241 if (unlikely(all_pinned
)) {
3242 cpu_clear(cpu_of(busiest
), cpus
);
3243 if (!cpus_empty(cpus
))
3250 schedstat_inc(sd
, lb_failed
[idle
]);
3251 sd
->nr_balance_failed
++;
3253 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3255 spin_lock_irqsave(&busiest
->lock
, flags
);
3257 /* don't kick the migration_thread, if the curr
3258 * task on busiest cpu can't be moved to this_cpu
3260 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3261 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3263 goto out_one_pinned
;
3266 if (!busiest
->active_balance
) {
3267 busiest
->active_balance
= 1;
3268 busiest
->push_cpu
= this_cpu
;
3271 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3273 wake_up_process(busiest
->migration_thread
);
3276 * We've kicked active balancing, reset the failure
3279 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3282 sd
->nr_balance_failed
= 0;
3284 if (likely(!active_balance
)) {
3285 /* We were unbalanced, so reset the balancing interval */
3286 sd
->balance_interval
= sd
->min_interval
;
3289 * If we've begun active balancing, start to back off. This
3290 * case may not be covered by the all_pinned logic if there
3291 * is only 1 task on the busy runqueue (because we don't call
3294 if (sd
->balance_interval
< sd
->max_interval
)
3295 sd
->balance_interval
*= 2;
3298 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3299 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3304 schedstat_inc(sd
, lb_balanced
[idle
]);
3306 sd
->nr_balance_failed
= 0;
3309 /* tune up the balancing interval */
3310 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3311 (sd
->balance_interval
< sd
->max_interval
))
3312 sd
->balance_interval
*= 2;
3314 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3315 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3321 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3322 * tasks if there is an imbalance.
3324 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3325 * this_rq is locked.
3328 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
)
3330 struct sched_group
*group
;
3331 struct rq
*busiest
= NULL
;
3332 unsigned long imbalance
;
3336 cpumask_t cpus
= CPU_MASK_ALL
;
3339 * When power savings policy is enabled for the parent domain, idle
3340 * sibling can pick up load irrespective of busy siblings. In this case,
3341 * let the state of idle sibling percolate up as IDLE, instead of
3342 * portraying it as CPU_NOT_IDLE.
3344 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3345 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3348 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3350 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3351 &sd_idle
, &cpus
, NULL
);
3353 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3357 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
,
3360 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3364 BUG_ON(busiest
== this_rq
);
3366 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3369 if (busiest
->nr_running
> 1) {
3370 /* Attempt to move tasks */
3371 double_lock_balance(this_rq
, busiest
);
3372 /* this_rq->clock is already updated */
3373 update_rq_clock(busiest
);
3374 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3375 imbalance
, sd
, CPU_NEWLY_IDLE
,
3377 spin_unlock(&busiest
->lock
);
3379 if (unlikely(all_pinned
)) {
3380 cpu_clear(cpu_of(busiest
), cpus
);
3381 if (!cpus_empty(cpus
))
3387 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3388 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3389 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3392 sd
->nr_balance_failed
= 0;
3397 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3398 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3399 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3401 sd
->nr_balance_failed
= 0;
3407 * idle_balance is called by schedule() if this_cpu is about to become
3408 * idle. Attempts to pull tasks from other CPUs.
3410 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3412 struct sched_domain
*sd
;
3413 int pulled_task
= -1;
3414 unsigned long next_balance
= jiffies
+ HZ
;
3416 for_each_domain(this_cpu
, sd
) {
3417 unsigned long interval
;
3419 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3422 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3423 /* If we've pulled tasks over stop searching: */
3424 pulled_task
= load_balance_newidle(this_cpu
,
3427 interval
= msecs_to_jiffies(sd
->balance_interval
);
3428 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3429 next_balance
= sd
->last_balance
+ interval
;
3433 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3435 * We are going idle. next_balance may be set based on
3436 * a busy processor. So reset next_balance.
3438 this_rq
->next_balance
= next_balance
;
3443 * active_load_balance is run by migration threads. It pushes running tasks
3444 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3445 * running on each physical CPU where possible, and avoids physical /
3446 * logical imbalances.
3448 * Called with busiest_rq locked.
3450 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3452 int target_cpu
= busiest_rq
->push_cpu
;
3453 struct sched_domain
*sd
;
3454 struct rq
*target_rq
;
3456 /* Is there any task to move? */
3457 if (busiest_rq
->nr_running
<= 1)
3460 target_rq
= cpu_rq(target_cpu
);
3463 * This condition is "impossible", if it occurs
3464 * we need to fix it. Originally reported by
3465 * Bjorn Helgaas on a 128-cpu setup.
3467 BUG_ON(busiest_rq
== target_rq
);
3469 /* move a task from busiest_rq to target_rq */
3470 double_lock_balance(busiest_rq
, target_rq
);
3471 update_rq_clock(busiest_rq
);
3472 update_rq_clock(target_rq
);
3474 /* Search for an sd spanning us and the target CPU. */
3475 for_each_domain(target_cpu
, sd
) {
3476 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3477 cpu_isset(busiest_cpu
, sd
->span
))
3482 schedstat_inc(sd
, alb_count
);
3484 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3486 schedstat_inc(sd
, alb_pushed
);
3488 schedstat_inc(sd
, alb_failed
);
3490 spin_unlock(&target_rq
->lock
);
3495 atomic_t load_balancer
;
3497 } nohz ____cacheline_aligned
= {
3498 .load_balancer
= ATOMIC_INIT(-1),
3499 .cpu_mask
= CPU_MASK_NONE
,
3503 * This routine will try to nominate the ilb (idle load balancing)
3504 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3505 * load balancing on behalf of all those cpus. If all the cpus in the system
3506 * go into this tickless mode, then there will be no ilb owner (as there is
3507 * no need for one) and all the cpus will sleep till the next wakeup event
3510 * For the ilb owner, tick is not stopped. And this tick will be used
3511 * for idle load balancing. ilb owner will still be part of
3514 * While stopping the tick, this cpu will become the ilb owner if there
3515 * is no other owner. And will be the owner till that cpu becomes busy
3516 * or if all cpus in the system stop their ticks at which point
3517 * there is no need for ilb owner.
3519 * When the ilb owner becomes busy, it nominates another owner, during the
3520 * next busy scheduler_tick()
3522 int select_nohz_load_balancer(int stop_tick
)
3524 int cpu
= smp_processor_id();
3527 cpu_set(cpu
, nohz
.cpu_mask
);
3528 cpu_rq(cpu
)->in_nohz_recently
= 1;
3531 * If we are going offline and still the leader, give up!
3533 if (cpu_is_offline(cpu
) &&
3534 atomic_read(&nohz
.load_balancer
) == cpu
) {
3535 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3540 /* time for ilb owner also to sleep */
3541 if (cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3542 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3543 atomic_set(&nohz
.load_balancer
, -1);
3547 if (atomic_read(&nohz
.load_balancer
) == -1) {
3548 /* make me the ilb owner */
3549 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3551 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3554 if (!cpu_isset(cpu
, nohz
.cpu_mask
))
3557 cpu_clear(cpu
, nohz
.cpu_mask
);
3559 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3560 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3567 static DEFINE_SPINLOCK(balancing
);
3570 * It checks each scheduling domain to see if it is due to be balanced,
3571 * and initiates a balancing operation if so.
3573 * Balancing parameters are set up in arch_init_sched_domains.
3575 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
3578 struct rq
*rq
= cpu_rq(cpu
);
3579 unsigned long interval
;
3580 struct sched_domain
*sd
;
3581 /* Earliest time when we have to do rebalance again */
3582 unsigned long next_balance
= jiffies
+ 60*HZ
;
3583 int update_next_balance
= 0;
3585 for_each_domain(cpu
, sd
) {
3586 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3589 interval
= sd
->balance_interval
;
3590 if (idle
!= CPU_IDLE
)
3591 interval
*= sd
->busy_factor
;
3593 /* scale ms to jiffies */
3594 interval
= msecs_to_jiffies(interval
);
3595 if (unlikely(!interval
))
3597 if (interval
> HZ
*NR_CPUS
/10)
3598 interval
= HZ
*NR_CPUS
/10;
3601 if (sd
->flags
& SD_SERIALIZE
) {
3602 if (!spin_trylock(&balancing
))
3606 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
3607 if (load_balance(cpu
, rq
, sd
, idle
, &balance
)) {
3609 * We've pulled tasks over so either we're no
3610 * longer idle, or one of our SMT siblings is
3613 idle
= CPU_NOT_IDLE
;
3615 sd
->last_balance
= jiffies
;
3617 if (sd
->flags
& SD_SERIALIZE
)
3618 spin_unlock(&balancing
);
3620 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
3621 next_balance
= sd
->last_balance
+ interval
;
3622 update_next_balance
= 1;
3626 * Stop the load balance at this level. There is another
3627 * CPU in our sched group which is doing load balancing more
3635 * next_balance will be updated only when there is a need.
3636 * When the cpu is attached to null domain for ex, it will not be
3639 if (likely(update_next_balance
))
3640 rq
->next_balance
= next_balance
;
3644 * run_rebalance_domains is triggered when needed from the scheduler tick.
3645 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3646 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3648 static void run_rebalance_domains(struct softirq_action
*h
)
3650 int this_cpu
= smp_processor_id();
3651 struct rq
*this_rq
= cpu_rq(this_cpu
);
3652 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
3653 CPU_IDLE
: CPU_NOT_IDLE
;
3655 rebalance_domains(this_cpu
, idle
);
3659 * If this cpu is the owner for idle load balancing, then do the
3660 * balancing on behalf of the other idle cpus whose ticks are
3663 if (this_rq
->idle_at_tick
&&
3664 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
3665 cpumask_t cpus
= nohz
.cpu_mask
;
3669 cpu_clear(this_cpu
, cpus
);
3670 for_each_cpu_mask(balance_cpu
, cpus
) {
3672 * If this cpu gets work to do, stop the load balancing
3673 * work being done for other cpus. Next load
3674 * balancing owner will pick it up.
3679 rebalance_domains(balance_cpu
, CPU_IDLE
);
3681 rq
= cpu_rq(balance_cpu
);
3682 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
3683 this_rq
->next_balance
= rq
->next_balance
;
3690 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3692 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3693 * idle load balancing owner or decide to stop the periodic load balancing,
3694 * if the whole system is idle.
3696 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
3700 * If we were in the nohz mode recently and busy at the current
3701 * scheduler tick, then check if we need to nominate new idle
3704 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
3705 rq
->in_nohz_recently
= 0;
3707 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
3708 cpu_clear(cpu
, nohz
.cpu_mask
);
3709 atomic_set(&nohz
.load_balancer
, -1);
3712 if (atomic_read(&nohz
.load_balancer
) == -1) {
3714 * simple selection for now: Nominate the
3715 * first cpu in the nohz list to be the next
3718 * TBD: Traverse the sched domains and nominate
3719 * the nearest cpu in the nohz.cpu_mask.
3721 int ilb
= first_cpu(nohz
.cpu_mask
);
3729 * If this cpu is idle and doing idle load balancing for all the
3730 * cpus with ticks stopped, is it time for that to stop?
3732 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
3733 cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3739 * If this cpu is idle and the idle load balancing is done by
3740 * someone else, then no need raise the SCHED_SOFTIRQ
3742 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
3743 cpu_isset(cpu
, nohz
.cpu_mask
))
3746 if (time_after_eq(jiffies
, rq
->next_balance
))
3747 raise_softirq(SCHED_SOFTIRQ
);
3750 #else /* CONFIG_SMP */
3753 * on UP we do not need to balance between CPUs:
3755 static inline void idle_balance(int cpu
, struct rq
*rq
)
3761 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
3763 EXPORT_PER_CPU_SYMBOL(kstat
);
3766 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3767 * that have not yet been banked in case the task is currently running.
3769 unsigned long long task_sched_runtime(struct task_struct
*p
)
3771 unsigned long flags
;
3775 rq
= task_rq_lock(p
, &flags
);
3776 ns
= p
->se
.sum_exec_runtime
;
3777 if (task_current(rq
, p
)) {
3778 update_rq_clock(rq
);
3779 delta_exec
= rq
->clock
- p
->se
.exec_start
;
3780 if ((s64
)delta_exec
> 0)
3783 task_rq_unlock(rq
, &flags
);
3789 * Account user cpu time to a process.
3790 * @p: the process that the cpu time gets accounted to
3791 * @cputime: the cpu time spent in user space since the last update
3793 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
3795 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3798 p
->utime
= cputime_add(p
->utime
, cputime
);
3800 /* Add user time to cpustat. */
3801 tmp
= cputime_to_cputime64(cputime
);
3802 if (TASK_NICE(p
) > 0)
3803 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
3805 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3809 * Account guest cpu time to a process.
3810 * @p: the process that the cpu time gets accounted to
3811 * @cputime: the cpu time spent in virtual machine since the last update
3813 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
3816 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3818 tmp
= cputime_to_cputime64(cputime
);
3820 p
->utime
= cputime_add(p
->utime
, cputime
);
3821 p
->gtime
= cputime_add(p
->gtime
, cputime
);
3823 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3824 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
3828 * Account scaled user cpu time to a process.
3829 * @p: the process that the cpu time gets accounted to
3830 * @cputime: the cpu time spent in user space since the last update
3832 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3834 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
3838 * Account system cpu time to a process.
3839 * @p: the process that the cpu time gets accounted to
3840 * @hardirq_offset: the offset to subtract from hardirq_count()
3841 * @cputime: the cpu time spent in kernel space since the last update
3843 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
3846 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3847 struct rq
*rq
= this_rq();
3850 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0))
3851 return account_guest_time(p
, cputime
);
3853 p
->stime
= cputime_add(p
->stime
, cputime
);
3855 /* Add system time to cpustat. */
3856 tmp
= cputime_to_cputime64(cputime
);
3857 if (hardirq_count() - hardirq_offset
)
3858 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
3859 else if (softirq_count())
3860 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
3861 else if (p
!= rq
->idle
)
3862 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
3863 else if (atomic_read(&rq
->nr_iowait
) > 0)
3864 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3866 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3867 /* Account for system time used */
3868 acct_update_integrals(p
);
3872 * Account scaled system cpu time to a process.
3873 * @p: the process that the cpu time gets accounted to
3874 * @hardirq_offset: the offset to subtract from hardirq_count()
3875 * @cputime: the cpu time spent in kernel space since the last update
3877 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3879 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
3883 * Account for involuntary wait time.
3884 * @p: the process from which the cpu time has been stolen
3885 * @steal: the cpu time spent in involuntary wait
3887 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
3889 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3890 cputime64_t tmp
= cputime_to_cputime64(steal
);
3891 struct rq
*rq
= this_rq();
3893 if (p
== rq
->idle
) {
3894 p
->stime
= cputime_add(p
->stime
, steal
);
3895 if (atomic_read(&rq
->nr_iowait
) > 0)
3896 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3898 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3900 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
3904 * This function gets called by the timer code, with HZ frequency.
3905 * We call it with interrupts disabled.
3907 * It also gets called by the fork code, when changing the parent's
3910 void scheduler_tick(void)
3912 int cpu
= smp_processor_id();
3913 struct rq
*rq
= cpu_rq(cpu
);
3914 struct task_struct
*curr
= rq
->curr
;
3915 u64 next_tick
= rq
->tick_timestamp
+ TICK_NSEC
;
3917 spin_lock(&rq
->lock
);
3918 __update_rq_clock(rq
);
3920 * Let rq->clock advance by at least TICK_NSEC:
3922 if (unlikely(rq
->clock
< next_tick
)) {
3923 rq
->clock
= next_tick
;
3924 rq
->clock_underflows
++;
3926 rq
->tick_timestamp
= rq
->clock
;
3927 update_last_tick_seen(rq
);
3928 update_cpu_load(rq
);
3929 curr
->sched_class
->task_tick(rq
, curr
, 0);
3930 spin_unlock(&rq
->lock
);
3933 rq
->idle_at_tick
= idle_cpu(cpu
);
3934 trigger_load_balance(rq
, cpu
);
3938 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3940 void __kprobes
add_preempt_count(int val
)
3945 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3947 preempt_count() += val
;
3949 * Spinlock count overflowing soon?
3951 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
3954 EXPORT_SYMBOL(add_preempt_count
);
3956 void __kprobes
sub_preempt_count(int val
)
3961 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3964 * Is the spinlock portion underflowing?
3966 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3967 !(preempt_count() & PREEMPT_MASK
)))
3970 preempt_count() -= val
;
3972 EXPORT_SYMBOL(sub_preempt_count
);
3977 * Print scheduling while atomic bug:
3979 static noinline
void __schedule_bug(struct task_struct
*prev
)
3981 struct pt_regs
*regs
= get_irq_regs();
3983 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
3984 prev
->comm
, prev
->pid
, preempt_count());
3986 debug_show_held_locks(prev
);
3987 if (irqs_disabled())
3988 print_irqtrace_events(prev
);
3997 * Various schedule()-time debugging checks and statistics:
3999 static inline void schedule_debug(struct task_struct
*prev
)
4002 * Test if we are atomic. Since do_exit() needs to call into
4003 * schedule() atomically, we ignore that path for now.
4004 * Otherwise, whine if we are scheduling when we should not be.
4006 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev
->exit_state
))
4007 __schedule_bug(prev
);
4009 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
4011 schedstat_inc(this_rq(), sched_count
);
4012 #ifdef CONFIG_SCHEDSTATS
4013 if (unlikely(prev
->lock_depth
>= 0)) {
4014 schedstat_inc(this_rq(), bkl_count
);
4015 schedstat_inc(prev
, sched_info
.bkl_count
);
4021 * Pick up the highest-prio task:
4023 static inline struct task_struct
*
4024 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
4026 const struct sched_class
*class;
4027 struct task_struct
*p
;
4030 * Optimization: we know that if all tasks are in
4031 * the fair class we can call that function directly:
4033 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
4034 p
= fair_sched_class
.pick_next_task(rq
);
4039 class = sched_class_highest
;
4041 p
= class->pick_next_task(rq
);
4045 * Will never be NULL as the idle class always
4046 * returns a non-NULL p:
4048 class = class->next
;
4053 * schedule() is the main scheduler function.
4055 asmlinkage
void __sched
schedule(void)
4057 struct task_struct
*prev
, *next
;
4058 unsigned long *switch_count
;
4064 cpu
= smp_processor_id();
4068 switch_count
= &prev
->nivcsw
;
4070 release_kernel_lock(prev
);
4071 need_resched_nonpreemptible
:
4073 schedule_debug(prev
);
4078 * Do the rq-clock update outside the rq lock:
4080 local_irq_disable();
4081 __update_rq_clock(rq
);
4082 spin_lock(&rq
->lock
);
4083 clear_tsk_need_resched(prev
);
4085 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
4086 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
4087 signal_pending(prev
))) {
4088 prev
->state
= TASK_RUNNING
;
4090 deactivate_task(rq
, prev
, 1);
4092 switch_count
= &prev
->nvcsw
;
4096 if (prev
->sched_class
->pre_schedule
)
4097 prev
->sched_class
->pre_schedule(rq
, prev
);
4100 if (unlikely(!rq
->nr_running
))
4101 idle_balance(cpu
, rq
);
4103 prev
->sched_class
->put_prev_task(rq
, prev
);
4104 next
= pick_next_task(rq
, prev
);
4106 sched_info_switch(prev
, next
);
4108 if (likely(prev
!= next
)) {
4113 context_switch(rq
, prev
, next
); /* unlocks the rq */
4115 * the context switch might have flipped the stack from under
4116 * us, hence refresh the local variables.
4118 cpu
= smp_processor_id();
4121 spin_unlock_irq(&rq
->lock
);
4125 if (unlikely(reacquire_kernel_lock(current
) < 0))
4126 goto need_resched_nonpreemptible
;
4128 preempt_enable_no_resched();
4129 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
4132 EXPORT_SYMBOL(schedule
);
4134 #ifdef CONFIG_PREEMPT
4136 * this is the entry point to schedule() from in-kernel preemption
4137 * off of preempt_enable. Kernel preemptions off return from interrupt
4138 * occur there and call schedule directly.
4140 asmlinkage
void __sched
preempt_schedule(void)
4142 struct thread_info
*ti
= current_thread_info();
4143 struct task_struct
*task
= current
;
4144 int saved_lock_depth
;
4147 * If there is a non-zero preempt_count or interrupts are disabled,
4148 * we do not want to preempt the current task. Just return..
4150 if (likely(ti
->preempt_count
|| irqs_disabled()))
4154 add_preempt_count(PREEMPT_ACTIVE
);
4157 * We keep the big kernel semaphore locked, but we
4158 * clear ->lock_depth so that schedule() doesnt
4159 * auto-release the semaphore:
4161 saved_lock_depth
= task
->lock_depth
;
4162 task
->lock_depth
= -1;
4164 task
->lock_depth
= saved_lock_depth
;
4165 sub_preempt_count(PREEMPT_ACTIVE
);
4168 * Check again in case we missed a preemption opportunity
4169 * between schedule and now.
4172 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4174 EXPORT_SYMBOL(preempt_schedule
);
4177 * this is the entry point to schedule() from kernel preemption
4178 * off of irq context.
4179 * Note, that this is called and return with irqs disabled. This will
4180 * protect us against recursive calling from irq.
4182 asmlinkage
void __sched
preempt_schedule_irq(void)
4184 struct thread_info
*ti
= current_thread_info();
4185 struct task_struct
*task
= current
;
4186 int saved_lock_depth
;
4188 /* Catch callers which need to be fixed */
4189 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
4192 add_preempt_count(PREEMPT_ACTIVE
);
4195 * We keep the big kernel semaphore locked, but we
4196 * clear ->lock_depth so that schedule() doesnt
4197 * auto-release the semaphore:
4199 saved_lock_depth
= task
->lock_depth
;
4200 task
->lock_depth
= -1;
4203 local_irq_disable();
4204 task
->lock_depth
= saved_lock_depth
;
4205 sub_preempt_count(PREEMPT_ACTIVE
);
4208 * Check again in case we missed a preemption opportunity
4209 * between schedule and now.
4212 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4215 #endif /* CONFIG_PREEMPT */
4217 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
4220 return try_to_wake_up(curr
->private, mode
, sync
);
4222 EXPORT_SYMBOL(default_wake_function
);
4225 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4226 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4227 * number) then we wake all the non-exclusive tasks and one exclusive task.
4229 * There are circumstances in which we can try to wake a task which has already
4230 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4231 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4233 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
4234 int nr_exclusive
, int sync
, void *key
)
4236 wait_queue_t
*curr
, *next
;
4238 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
4239 unsigned flags
= curr
->flags
;
4241 if (curr
->func(curr
, mode
, sync
, key
) &&
4242 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4248 * __wake_up - wake up threads blocked on a waitqueue.
4250 * @mode: which threads
4251 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4252 * @key: is directly passed to the wakeup function
4254 void __wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4255 int nr_exclusive
, void *key
)
4257 unsigned long flags
;
4259 spin_lock_irqsave(&q
->lock
, flags
);
4260 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4261 spin_unlock_irqrestore(&q
->lock
, flags
);
4263 EXPORT_SYMBOL(__wake_up
);
4266 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4268 void __wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4270 __wake_up_common(q
, mode
, 1, 0, NULL
);
4274 * __wake_up_sync - wake up threads blocked on a waitqueue.
4276 * @mode: which threads
4277 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4279 * The sync wakeup differs that the waker knows that it will schedule
4280 * away soon, so while the target thread will be woken up, it will not
4281 * be migrated to another CPU - ie. the two threads are 'synchronized'
4282 * with each other. This can prevent needless bouncing between CPUs.
4284 * On UP it can prevent extra preemption.
4287 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4289 unsigned long flags
;
4295 if (unlikely(!nr_exclusive
))
4298 spin_lock_irqsave(&q
->lock
, flags
);
4299 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4300 spin_unlock_irqrestore(&q
->lock
, flags
);
4302 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4304 void complete(struct completion
*x
)
4306 unsigned long flags
;
4308 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4310 __wake_up_common(&x
->wait
, TASK_NORMAL
, 1, 0, NULL
);
4311 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4313 EXPORT_SYMBOL(complete
);
4315 void complete_all(struct completion
*x
)
4317 unsigned long flags
;
4319 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4320 x
->done
+= UINT_MAX
/2;
4321 __wake_up_common(&x
->wait
, TASK_NORMAL
, 0, 0, NULL
);
4322 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4324 EXPORT_SYMBOL(complete_all
);
4326 static inline long __sched
4327 do_wait_for_common(struct completion
*x
, long timeout
, int state
)
4330 DECLARE_WAITQUEUE(wait
, current
);
4332 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
4333 __add_wait_queue_tail(&x
->wait
, &wait
);
4335 if ((state
== TASK_INTERRUPTIBLE
&&
4336 signal_pending(current
)) ||
4337 (state
== TASK_KILLABLE
&&
4338 fatal_signal_pending(current
))) {
4339 __remove_wait_queue(&x
->wait
, &wait
);
4340 return -ERESTARTSYS
;
4342 __set_current_state(state
);
4343 spin_unlock_irq(&x
->wait
.lock
);
4344 timeout
= schedule_timeout(timeout
);
4345 spin_lock_irq(&x
->wait
.lock
);
4347 __remove_wait_queue(&x
->wait
, &wait
);
4351 __remove_wait_queue(&x
->wait
, &wait
);
4358 wait_for_common(struct completion
*x
, long timeout
, int state
)
4362 spin_lock_irq(&x
->wait
.lock
);
4363 timeout
= do_wait_for_common(x
, timeout
, state
);
4364 spin_unlock_irq(&x
->wait
.lock
);
4368 void __sched
wait_for_completion(struct completion
*x
)
4370 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4372 EXPORT_SYMBOL(wait_for_completion
);
4374 unsigned long __sched
4375 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4377 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4379 EXPORT_SYMBOL(wait_for_completion_timeout
);
4381 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4383 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4384 if (t
== -ERESTARTSYS
)
4388 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4390 unsigned long __sched
4391 wait_for_completion_interruptible_timeout(struct completion
*x
,
4392 unsigned long timeout
)
4394 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4396 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4398 int __sched
wait_for_completion_killable(struct completion
*x
)
4400 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_KILLABLE
);
4401 if (t
== -ERESTARTSYS
)
4405 EXPORT_SYMBOL(wait_for_completion_killable
);
4408 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4410 unsigned long flags
;
4413 init_waitqueue_entry(&wait
, current
);
4415 __set_current_state(state
);
4417 spin_lock_irqsave(&q
->lock
, flags
);
4418 __add_wait_queue(q
, &wait
);
4419 spin_unlock(&q
->lock
);
4420 timeout
= schedule_timeout(timeout
);
4421 spin_lock_irq(&q
->lock
);
4422 __remove_wait_queue(q
, &wait
);
4423 spin_unlock_irqrestore(&q
->lock
, flags
);
4428 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4430 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4432 EXPORT_SYMBOL(interruptible_sleep_on
);
4435 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4437 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4439 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4441 void __sched
sleep_on(wait_queue_head_t
*q
)
4443 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4445 EXPORT_SYMBOL(sleep_on
);
4447 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4449 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4451 EXPORT_SYMBOL(sleep_on_timeout
);
4453 #ifdef CONFIG_RT_MUTEXES
4456 * rt_mutex_setprio - set the current priority of a task
4458 * @prio: prio value (kernel-internal form)
4460 * This function changes the 'effective' priority of a task. It does
4461 * not touch ->normal_prio like __setscheduler().
4463 * Used by the rt_mutex code to implement priority inheritance logic.
4465 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4467 unsigned long flags
;
4468 int oldprio
, on_rq
, running
;
4470 const struct sched_class
*prev_class
= p
->sched_class
;
4472 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4474 rq
= task_rq_lock(p
, &flags
);
4475 update_rq_clock(rq
);
4478 on_rq
= p
->se
.on_rq
;
4479 running
= task_current(rq
, p
);
4481 dequeue_task(rq
, p
, 0);
4483 p
->sched_class
->put_prev_task(rq
, p
);
4486 p
->sched_class
= &rt_sched_class
;
4488 p
->sched_class
= &fair_sched_class
;
4493 p
->sched_class
->set_curr_task(rq
);
4495 enqueue_task(rq
, p
, 0);
4497 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4499 task_rq_unlock(rq
, &flags
);
4504 void set_user_nice(struct task_struct
*p
, long nice
)
4506 int old_prio
, delta
, on_rq
;
4507 unsigned long flags
;
4510 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
4513 * We have to be careful, if called from sys_setpriority(),
4514 * the task might be in the middle of scheduling on another CPU.
4516 rq
= task_rq_lock(p
, &flags
);
4517 update_rq_clock(rq
);
4519 * The RT priorities are set via sched_setscheduler(), but we still
4520 * allow the 'normal' nice value to be set - but as expected
4521 * it wont have any effect on scheduling until the task is
4522 * SCHED_FIFO/SCHED_RR:
4524 if (task_has_rt_policy(p
)) {
4525 p
->static_prio
= NICE_TO_PRIO(nice
);
4528 on_rq
= p
->se
.on_rq
;
4530 dequeue_task(rq
, p
, 0);
4534 p
->static_prio
= NICE_TO_PRIO(nice
);
4537 p
->prio
= effective_prio(p
);
4538 delta
= p
->prio
- old_prio
;
4541 enqueue_task(rq
, p
, 0);
4544 * If the task increased its priority or is running and
4545 * lowered its priority, then reschedule its CPU:
4547 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
4548 resched_task(rq
->curr
);
4551 task_rq_unlock(rq
, &flags
);
4553 EXPORT_SYMBOL(set_user_nice
);
4556 * can_nice - check if a task can reduce its nice value
4560 int can_nice(const struct task_struct
*p
, const int nice
)
4562 /* convert nice value [19,-20] to rlimit style value [1,40] */
4563 int nice_rlim
= 20 - nice
;
4565 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
4566 capable(CAP_SYS_NICE
));
4569 #ifdef __ARCH_WANT_SYS_NICE
4572 * sys_nice - change the priority of the current process.
4573 * @increment: priority increment
4575 * sys_setpriority is a more generic, but much slower function that
4576 * does similar things.
4578 asmlinkage
long sys_nice(int increment
)
4583 * Setpriority might change our priority at the same moment.
4584 * We don't have to worry. Conceptually one call occurs first
4585 * and we have a single winner.
4587 if (increment
< -40)
4592 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
4598 if (increment
< 0 && !can_nice(current
, nice
))
4601 retval
= security_task_setnice(current
, nice
);
4605 set_user_nice(current
, nice
);
4612 * task_prio - return the priority value of a given task.
4613 * @p: the task in question.
4615 * This is the priority value as seen by users in /proc.
4616 * RT tasks are offset by -200. Normal tasks are centered
4617 * around 0, value goes from -16 to +15.
4619 int task_prio(const struct task_struct
*p
)
4621 return p
->prio
- MAX_RT_PRIO
;
4625 * task_nice - return the nice value of a given task.
4626 * @p: the task in question.
4628 int task_nice(const struct task_struct
*p
)
4630 return TASK_NICE(p
);
4632 EXPORT_SYMBOL(task_nice
);
4635 * idle_cpu - is a given cpu idle currently?
4636 * @cpu: the processor in question.
4638 int idle_cpu(int cpu
)
4640 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
4644 * idle_task - return the idle task for a given cpu.
4645 * @cpu: the processor in question.
4647 struct task_struct
*idle_task(int cpu
)
4649 return cpu_rq(cpu
)->idle
;
4653 * find_process_by_pid - find a process with a matching PID value.
4654 * @pid: the pid in question.
4656 static struct task_struct
*find_process_by_pid(pid_t pid
)
4658 return pid
? find_task_by_vpid(pid
) : current
;
4661 /* Actually do priority change: must hold rq lock. */
4663 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
4665 BUG_ON(p
->se
.on_rq
);
4668 switch (p
->policy
) {
4672 p
->sched_class
= &fair_sched_class
;
4676 p
->sched_class
= &rt_sched_class
;
4680 p
->rt_priority
= prio
;
4681 p
->normal_prio
= normal_prio(p
);
4682 /* we are holding p->pi_lock already */
4683 p
->prio
= rt_mutex_getprio(p
);
4688 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4689 * @p: the task in question.
4690 * @policy: new policy.
4691 * @param: structure containing the new RT priority.
4693 * NOTE that the task may be already dead.
4695 int sched_setscheduler(struct task_struct
*p
, int policy
,
4696 struct sched_param
*param
)
4698 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
4699 unsigned long flags
;
4700 const struct sched_class
*prev_class
= p
->sched_class
;
4703 /* may grab non-irq protected spin_locks */
4704 BUG_ON(in_interrupt());
4706 /* double check policy once rq lock held */
4708 policy
= oldpolicy
= p
->policy
;
4709 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4710 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
4711 policy
!= SCHED_IDLE
)
4714 * Valid priorities for SCHED_FIFO and SCHED_RR are
4715 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4716 * SCHED_BATCH and SCHED_IDLE is 0.
4718 if (param
->sched_priority
< 0 ||
4719 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4720 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4722 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
4726 * Allow unprivileged RT tasks to decrease priority:
4728 if (!capable(CAP_SYS_NICE
)) {
4729 if (rt_policy(policy
)) {
4730 unsigned long rlim_rtprio
;
4732 if (!lock_task_sighand(p
, &flags
))
4734 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
4735 unlock_task_sighand(p
, &flags
);
4737 /* can't set/change the rt policy */
4738 if (policy
!= p
->policy
&& !rlim_rtprio
)
4741 /* can't increase priority */
4742 if (param
->sched_priority
> p
->rt_priority
&&
4743 param
->sched_priority
> rlim_rtprio
)
4747 * Like positive nice levels, dont allow tasks to
4748 * move out of SCHED_IDLE either:
4750 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
4753 /* can't change other user's priorities */
4754 if ((current
->euid
!= p
->euid
) &&
4755 (current
->euid
!= p
->uid
))
4759 #ifdef CONFIG_RT_GROUP_SCHED
4761 * Do not allow realtime tasks into groups that have no runtime
4764 if (rt_policy(policy
) && task_group(p
)->rt_bandwidth
.rt_runtime
== 0)
4768 retval
= security_task_setscheduler(p
, policy
, param
);
4772 * make sure no PI-waiters arrive (or leave) while we are
4773 * changing the priority of the task:
4775 spin_lock_irqsave(&p
->pi_lock
, flags
);
4777 * To be able to change p->policy safely, the apropriate
4778 * runqueue lock must be held.
4780 rq
= __task_rq_lock(p
);
4781 /* recheck policy now with rq lock held */
4782 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4783 policy
= oldpolicy
= -1;
4784 __task_rq_unlock(rq
);
4785 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4788 update_rq_clock(rq
);
4789 on_rq
= p
->se
.on_rq
;
4790 running
= task_current(rq
, p
);
4792 deactivate_task(rq
, p
, 0);
4794 p
->sched_class
->put_prev_task(rq
, p
);
4797 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
4800 p
->sched_class
->set_curr_task(rq
);
4802 activate_task(rq
, p
, 0);
4804 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4806 __task_rq_unlock(rq
);
4807 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4809 rt_mutex_adjust_pi(p
);
4813 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4816 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4818 struct sched_param lparam
;
4819 struct task_struct
*p
;
4822 if (!param
|| pid
< 0)
4824 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4829 p
= find_process_by_pid(pid
);
4831 retval
= sched_setscheduler(p
, policy
, &lparam
);
4838 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4839 * @pid: the pid in question.
4840 * @policy: new policy.
4841 * @param: structure containing the new RT priority.
4844 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4846 /* negative values for policy are not valid */
4850 return do_sched_setscheduler(pid
, policy
, param
);
4854 * sys_sched_setparam - set/change the RT priority of a thread
4855 * @pid: the pid in question.
4856 * @param: structure containing the new RT priority.
4858 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4860 return do_sched_setscheduler(pid
, -1, param
);
4864 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4865 * @pid: the pid in question.
4867 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4869 struct task_struct
*p
;
4876 read_lock(&tasklist_lock
);
4877 p
= find_process_by_pid(pid
);
4879 retval
= security_task_getscheduler(p
);
4883 read_unlock(&tasklist_lock
);
4888 * sys_sched_getscheduler - get the RT priority of a thread
4889 * @pid: the pid in question.
4890 * @param: structure containing the RT priority.
4892 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4894 struct sched_param lp
;
4895 struct task_struct
*p
;
4898 if (!param
|| pid
< 0)
4901 read_lock(&tasklist_lock
);
4902 p
= find_process_by_pid(pid
);
4907 retval
= security_task_getscheduler(p
);
4911 lp
.sched_priority
= p
->rt_priority
;
4912 read_unlock(&tasklist_lock
);
4915 * This one might sleep, we cannot do it with a spinlock held ...
4917 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4922 read_unlock(&tasklist_lock
);
4926 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
4928 cpumask_t cpus_allowed
;
4929 struct task_struct
*p
;
4933 read_lock(&tasklist_lock
);
4935 p
= find_process_by_pid(pid
);
4937 read_unlock(&tasklist_lock
);
4943 * It is not safe to call set_cpus_allowed with the
4944 * tasklist_lock held. We will bump the task_struct's
4945 * usage count and then drop tasklist_lock.
4948 read_unlock(&tasklist_lock
);
4951 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
4952 !capable(CAP_SYS_NICE
))
4955 retval
= security_task_setscheduler(p
, 0, NULL
);
4959 cpus_allowed
= cpuset_cpus_allowed(p
);
4960 cpus_and(new_mask
, new_mask
, cpus_allowed
);
4962 retval
= set_cpus_allowed(p
, new_mask
);
4965 cpus_allowed
= cpuset_cpus_allowed(p
);
4966 if (!cpus_subset(new_mask
, cpus_allowed
)) {
4968 * We must have raced with a concurrent cpuset
4969 * update. Just reset the cpus_allowed to the
4970 * cpuset's cpus_allowed
4972 new_mask
= cpus_allowed
;
4982 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4983 cpumask_t
*new_mask
)
4985 if (len
< sizeof(cpumask_t
)) {
4986 memset(new_mask
, 0, sizeof(cpumask_t
));
4987 } else if (len
> sizeof(cpumask_t
)) {
4988 len
= sizeof(cpumask_t
);
4990 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4994 * sys_sched_setaffinity - set the cpu affinity of a process
4995 * @pid: pid of the process
4996 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4997 * @user_mask_ptr: user-space pointer to the new cpu mask
4999 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
5000 unsigned long __user
*user_mask_ptr
)
5005 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
5009 return sched_setaffinity(pid
, new_mask
);
5013 * Represents all cpu's present in the system
5014 * In systems capable of hotplug, this map could dynamically grow
5015 * as new cpu's are detected in the system via any platform specific
5016 * method, such as ACPI for e.g.
5019 cpumask_t cpu_present_map __read_mostly
;
5020 EXPORT_SYMBOL(cpu_present_map
);
5023 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
5024 EXPORT_SYMBOL(cpu_online_map
);
5026 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
5027 EXPORT_SYMBOL(cpu_possible_map
);
5030 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
5032 struct task_struct
*p
;
5036 read_lock(&tasklist_lock
);
5039 p
= find_process_by_pid(pid
);
5043 retval
= security_task_getscheduler(p
);
5047 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
5050 read_unlock(&tasklist_lock
);
5057 * sys_sched_getaffinity - get the cpu affinity of a process
5058 * @pid: pid of the process
5059 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5060 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5062 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
5063 unsigned long __user
*user_mask_ptr
)
5068 if (len
< sizeof(cpumask_t
))
5071 ret
= sched_getaffinity(pid
, &mask
);
5075 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
5078 return sizeof(cpumask_t
);
5082 * sys_sched_yield - yield the current processor to other threads.
5084 * This function yields the current CPU to other tasks. If there are no
5085 * other threads running on this CPU then this function will return.
5087 asmlinkage
long sys_sched_yield(void)
5089 struct rq
*rq
= this_rq_lock();
5091 schedstat_inc(rq
, yld_count
);
5092 current
->sched_class
->yield_task(rq
);
5095 * Since we are going to call schedule() anyway, there's
5096 * no need to preempt or enable interrupts:
5098 __release(rq
->lock
);
5099 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
5100 _raw_spin_unlock(&rq
->lock
);
5101 preempt_enable_no_resched();
5108 static void __cond_resched(void)
5110 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5111 __might_sleep(__FILE__
, __LINE__
);
5114 * The BKS might be reacquired before we have dropped
5115 * PREEMPT_ACTIVE, which could trigger a second
5116 * cond_resched() call.
5119 add_preempt_count(PREEMPT_ACTIVE
);
5121 sub_preempt_count(PREEMPT_ACTIVE
);
5122 } while (need_resched());
5125 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5126 int __sched
_cond_resched(void)
5128 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
5129 system_state
== SYSTEM_RUNNING
) {
5135 EXPORT_SYMBOL(_cond_resched
);
5139 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5140 * call schedule, and on return reacquire the lock.
5142 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5143 * operations here to prevent schedule() from being called twice (once via
5144 * spin_unlock(), once by hand).
5146 int cond_resched_lock(spinlock_t
*lock
)
5148 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
5151 if (spin_needbreak(lock
) || resched
) {
5153 if (resched
&& need_resched())
5162 EXPORT_SYMBOL(cond_resched_lock
);
5164 int __sched
cond_resched_softirq(void)
5166 BUG_ON(!in_softirq());
5168 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
5176 EXPORT_SYMBOL(cond_resched_softirq
);
5179 * yield - yield the current processor to other threads.
5181 * This is a shortcut for kernel-space yielding - it marks the
5182 * thread runnable and calls sys_sched_yield().
5184 void __sched
yield(void)
5186 set_current_state(TASK_RUNNING
);
5189 EXPORT_SYMBOL(yield
);
5192 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5193 * that process accounting knows that this is a task in IO wait state.
5195 * But don't do that if it is a deliberate, throttling IO wait (this task
5196 * has set its backing_dev_info: the queue against which it should throttle)
5198 void __sched
io_schedule(void)
5200 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5202 delayacct_blkio_start();
5203 atomic_inc(&rq
->nr_iowait
);
5205 atomic_dec(&rq
->nr_iowait
);
5206 delayacct_blkio_end();
5208 EXPORT_SYMBOL(io_schedule
);
5210 long __sched
io_schedule_timeout(long timeout
)
5212 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5215 delayacct_blkio_start();
5216 atomic_inc(&rq
->nr_iowait
);
5217 ret
= schedule_timeout(timeout
);
5218 atomic_dec(&rq
->nr_iowait
);
5219 delayacct_blkio_end();
5224 * sys_sched_get_priority_max - return maximum RT priority.
5225 * @policy: scheduling class.
5227 * this syscall returns the maximum rt_priority that can be used
5228 * by a given scheduling class.
5230 asmlinkage
long sys_sched_get_priority_max(int policy
)
5237 ret
= MAX_USER_RT_PRIO
-1;
5249 * sys_sched_get_priority_min - return minimum RT priority.
5250 * @policy: scheduling class.
5252 * this syscall returns the minimum rt_priority that can be used
5253 * by a given scheduling class.
5255 asmlinkage
long sys_sched_get_priority_min(int policy
)
5273 * sys_sched_rr_get_interval - return the default timeslice of a process.
5274 * @pid: pid of the process.
5275 * @interval: userspace pointer to the timeslice value.
5277 * this syscall writes the default timeslice value of a given process
5278 * into the user-space timespec buffer. A value of '0' means infinity.
5281 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5283 struct task_struct
*p
;
5284 unsigned int time_slice
;
5292 read_lock(&tasklist_lock
);
5293 p
= find_process_by_pid(pid
);
5297 retval
= security_task_getscheduler(p
);
5302 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5303 * tasks that are on an otherwise idle runqueue:
5306 if (p
->policy
== SCHED_RR
) {
5307 time_slice
= DEF_TIMESLICE
;
5308 } else if (p
->policy
!= SCHED_FIFO
) {
5309 struct sched_entity
*se
= &p
->se
;
5310 unsigned long flags
;
5313 rq
= task_rq_lock(p
, &flags
);
5314 if (rq
->cfs
.load
.weight
)
5315 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5316 task_rq_unlock(rq
, &flags
);
5318 read_unlock(&tasklist_lock
);
5319 jiffies_to_timespec(time_slice
, &t
);
5320 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5324 read_unlock(&tasklist_lock
);
5328 static const char stat_nam
[] = "RSDTtZX";
5330 void sched_show_task(struct task_struct
*p
)
5332 unsigned long free
= 0;
5335 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5336 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5337 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5338 #if BITS_PER_LONG == 32
5339 if (state
== TASK_RUNNING
)
5340 printk(KERN_CONT
" running ");
5342 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5344 if (state
== TASK_RUNNING
)
5345 printk(KERN_CONT
" running task ");
5347 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5349 #ifdef CONFIG_DEBUG_STACK_USAGE
5351 unsigned long *n
= end_of_stack(p
);
5354 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5357 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5358 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5360 show_stack(p
, NULL
);
5363 void show_state_filter(unsigned long state_filter
)
5365 struct task_struct
*g
, *p
;
5367 #if BITS_PER_LONG == 32
5369 " task PC stack pid father\n");
5372 " task PC stack pid father\n");
5374 read_lock(&tasklist_lock
);
5375 do_each_thread(g
, p
) {
5377 * reset the NMI-timeout, listing all files on a slow
5378 * console might take alot of time:
5380 touch_nmi_watchdog();
5381 if (!state_filter
|| (p
->state
& state_filter
))
5383 } while_each_thread(g
, p
);
5385 touch_all_softlockup_watchdogs();
5387 #ifdef CONFIG_SCHED_DEBUG
5388 sysrq_sched_debug_show();
5390 read_unlock(&tasklist_lock
);
5392 * Only show locks if all tasks are dumped:
5394 if (state_filter
== -1)
5395 debug_show_all_locks();
5398 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5400 idle
->sched_class
= &idle_sched_class
;
5404 * init_idle - set up an idle thread for a given CPU
5405 * @idle: task in question
5406 * @cpu: cpu the idle task belongs to
5408 * NOTE: this function does not set the idle thread's NEED_RESCHED
5409 * flag, to make booting more robust.
5411 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5413 struct rq
*rq
= cpu_rq(cpu
);
5414 unsigned long flags
;
5417 idle
->se
.exec_start
= sched_clock();
5419 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5420 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
5421 __set_task_cpu(idle
, cpu
);
5423 spin_lock_irqsave(&rq
->lock
, flags
);
5424 rq
->curr
= rq
->idle
= idle
;
5425 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5428 spin_unlock_irqrestore(&rq
->lock
, flags
);
5430 /* Set the preempt count _outside_ the spinlocks! */
5431 task_thread_info(idle
)->preempt_count
= 0;
5434 * The idle tasks have their own, simple scheduling class:
5436 idle
->sched_class
= &idle_sched_class
;
5440 * In a system that switches off the HZ timer nohz_cpu_mask
5441 * indicates which cpus entered this state. This is used
5442 * in the rcu update to wait only for active cpus. For system
5443 * which do not switch off the HZ timer nohz_cpu_mask should
5444 * always be CPU_MASK_NONE.
5446 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
5449 * Increase the granularity value when there are more CPUs,
5450 * because with more CPUs the 'effective latency' as visible
5451 * to users decreases. But the relationship is not linear,
5452 * so pick a second-best guess by going with the log2 of the
5455 * This idea comes from the SD scheduler of Con Kolivas:
5457 static inline void sched_init_granularity(void)
5459 unsigned int factor
= 1 + ilog2(num_online_cpus());
5460 const unsigned long limit
= 200000000;
5462 sysctl_sched_min_granularity
*= factor
;
5463 if (sysctl_sched_min_granularity
> limit
)
5464 sysctl_sched_min_granularity
= limit
;
5466 sysctl_sched_latency
*= factor
;
5467 if (sysctl_sched_latency
> limit
)
5468 sysctl_sched_latency
= limit
;
5470 sysctl_sched_wakeup_granularity
*= factor
;
5475 * This is how migration works:
5477 * 1) we queue a struct migration_req structure in the source CPU's
5478 * runqueue and wake up that CPU's migration thread.
5479 * 2) we down() the locked semaphore => thread blocks.
5480 * 3) migration thread wakes up (implicitly it forces the migrated
5481 * thread off the CPU)
5482 * 4) it gets the migration request and checks whether the migrated
5483 * task is still in the wrong runqueue.
5484 * 5) if it's in the wrong runqueue then the migration thread removes
5485 * it and puts it into the right queue.
5486 * 6) migration thread up()s the semaphore.
5487 * 7) we wake up and the migration is done.
5491 * Change a given task's CPU affinity. Migrate the thread to a
5492 * proper CPU and schedule it away if the CPU it's executing on
5493 * is removed from the allowed bitmask.
5495 * NOTE: the caller must have a valid reference to the task, the
5496 * task must not exit() & deallocate itself prematurely. The
5497 * call is not atomic; no spinlocks may be held.
5499 int set_cpus_allowed(struct task_struct
*p
, cpumask_t new_mask
)
5501 struct migration_req req
;
5502 unsigned long flags
;
5506 rq
= task_rq_lock(p
, &flags
);
5507 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
5512 if (p
->sched_class
->set_cpus_allowed
)
5513 p
->sched_class
->set_cpus_allowed(p
, &new_mask
);
5515 p
->cpus_allowed
= new_mask
;
5516 p
->rt
.nr_cpus_allowed
= cpus_weight(new_mask
);
5519 /* Can the task run on the task's current CPU? If so, we're done */
5520 if (cpu_isset(task_cpu(p
), new_mask
))
5523 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
5524 /* Need help from migration thread: drop lock and wait. */
5525 task_rq_unlock(rq
, &flags
);
5526 wake_up_process(rq
->migration_thread
);
5527 wait_for_completion(&req
.done
);
5528 tlb_migrate_finish(p
->mm
);
5532 task_rq_unlock(rq
, &flags
);
5536 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
5539 * Move (not current) task off this cpu, onto dest cpu. We're doing
5540 * this because either it can't run here any more (set_cpus_allowed()
5541 * away from this CPU, or CPU going down), or because we're
5542 * attempting to rebalance this task on exec (sched_exec).
5544 * So we race with normal scheduler movements, but that's OK, as long
5545 * as the task is no longer on this CPU.
5547 * Returns non-zero if task was successfully migrated.
5549 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5551 struct rq
*rq_dest
, *rq_src
;
5554 if (unlikely(cpu_is_offline(dest_cpu
)))
5557 rq_src
= cpu_rq(src_cpu
);
5558 rq_dest
= cpu_rq(dest_cpu
);
5560 double_rq_lock(rq_src
, rq_dest
);
5561 /* Already moved. */
5562 if (task_cpu(p
) != src_cpu
)
5564 /* Affinity changed (again). */
5565 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
5568 on_rq
= p
->se
.on_rq
;
5570 deactivate_task(rq_src
, p
, 0);
5572 set_task_cpu(p
, dest_cpu
);
5574 activate_task(rq_dest
, p
, 0);
5575 check_preempt_curr(rq_dest
, p
);
5579 double_rq_unlock(rq_src
, rq_dest
);
5584 * migration_thread - this is a highprio system thread that performs
5585 * thread migration by bumping thread off CPU then 'pushing' onto
5588 static int migration_thread(void *data
)
5590 int cpu
= (long)data
;
5594 BUG_ON(rq
->migration_thread
!= current
);
5596 set_current_state(TASK_INTERRUPTIBLE
);
5597 while (!kthread_should_stop()) {
5598 struct migration_req
*req
;
5599 struct list_head
*head
;
5601 spin_lock_irq(&rq
->lock
);
5603 if (cpu_is_offline(cpu
)) {
5604 spin_unlock_irq(&rq
->lock
);
5608 if (rq
->active_balance
) {
5609 active_load_balance(rq
, cpu
);
5610 rq
->active_balance
= 0;
5613 head
= &rq
->migration_queue
;
5615 if (list_empty(head
)) {
5616 spin_unlock_irq(&rq
->lock
);
5618 set_current_state(TASK_INTERRUPTIBLE
);
5621 req
= list_entry(head
->next
, struct migration_req
, list
);
5622 list_del_init(head
->next
);
5624 spin_unlock(&rq
->lock
);
5625 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
5628 complete(&req
->done
);
5630 __set_current_state(TASK_RUNNING
);
5634 /* Wait for kthread_stop */
5635 set_current_state(TASK_INTERRUPTIBLE
);
5636 while (!kthread_should_stop()) {
5638 set_current_state(TASK_INTERRUPTIBLE
);
5640 __set_current_state(TASK_RUNNING
);
5644 #ifdef CONFIG_HOTPLUG_CPU
5646 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5650 local_irq_disable();
5651 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
5657 * Figure out where task on dead CPU should go, use force if necessary.
5658 * NOTE: interrupts should be disabled by the caller
5660 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
5662 unsigned long flags
;
5669 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
5670 cpus_and(mask
, mask
, p
->cpus_allowed
);
5671 dest_cpu
= any_online_cpu(mask
);
5673 /* On any allowed CPU? */
5674 if (dest_cpu
== NR_CPUS
)
5675 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5677 /* No more Mr. Nice Guy. */
5678 if (dest_cpu
== NR_CPUS
) {
5679 cpumask_t cpus_allowed
= cpuset_cpus_allowed_locked(p
);
5681 * Try to stay on the same cpuset, where the
5682 * current cpuset may be a subset of all cpus.
5683 * The cpuset_cpus_allowed_locked() variant of
5684 * cpuset_cpus_allowed() will not block. It must be
5685 * called within calls to cpuset_lock/cpuset_unlock.
5687 rq
= task_rq_lock(p
, &flags
);
5688 p
->cpus_allowed
= cpus_allowed
;
5689 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5690 task_rq_unlock(rq
, &flags
);
5693 * Don't tell them about moving exiting tasks or
5694 * kernel threads (both mm NULL), since they never
5697 if (p
->mm
&& printk_ratelimit()) {
5698 printk(KERN_INFO
"process %d (%s) no "
5699 "longer affine to cpu%d\n",
5700 task_pid_nr(p
), p
->comm
, dead_cpu
);
5703 } while (!__migrate_task_irq(p
, dead_cpu
, dest_cpu
));
5707 * While a dead CPU has no uninterruptible tasks queued at this point,
5708 * it might still have a nonzero ->nr_uninterruptible counter, because
5709 * for performance reasons the counter is not stricly tracking tasks to
5710 * their home CPUs. So we just add the counter to another CPU's counter,
5711 * to keep the global sum constant after CPU-down:
5713 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
5715 struct rq
*rq_dest
= cpu_rq(any_online_cpu(CPU_MASK_ALL
));
5716 unsigned long flags
;
5718 local_irq_save(flags
);
5719 double_rq_lock(rq_src
, rq_dest
);
5720 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
5721 rq_src
->nr_uninterruptible
= 0;
5722 double_rq_unlock(rq_src
, rq_dest
);
5723 local_irq_restore(flags
);
5726 /* Run through task list and migrate tasks from the dead cpu. */
5727 static void migrate_live_tasks(int src_cpu
)
5729 struct task_struct
*p
, *t
;
5731 read_lock(&tasklist_lock
);
5733 do_each_thread(t
, p
) {
5737 if (task_cpu(p
) == src_cpu
)
5738 move_task_off_dead_cpu(src_cpu
, p
);
5739 } while_each_thread(t
, p
);
5741 read_unlock(&tasklist_lock
);
5745 * Schedules idle task to be the next runnable task on current CPU.
5746 * It does so by boosting its priority to highest possible.
5747 * Used by CPU offline code.
5749 void sched_idle_next(void)
5751 int this_cpu
= smp_processor_id();
5752 struct rq
*rq
= cpu_rq(this_cpu
);
5753 struct task_struct
*p
= rq
->idle
;
5754 unsigned long flags
;
5756 /* cpu has to be offline */
5757 BUG_ON(cpu_online(this_cpu
));
5760 * Strictly not necessary since rest of the CPUs are stopped by now
5761 * and interrupts disabled on the current cpu.
5763 spin_lock_irqsave(&rq
->lock
, flags
);
5765 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5767 update_rq_clock(rq
);
5768 activate_task(rq
, p
, 0);
5770 spin_unlock_irqrestore(&rq
->lock
, flags
);
5774 * Ensures that the idle task is using init_mm right before its cpu goes
5777 void idle_task_exit(void)
5779 struct mm_struct
*mm
= current
->active_mm
;
5781 BUG_ON(cpu_online(smp_processor_id()));
5784 switch_mm(mm
, &init_mm
, current
);
5788 /* called under rq->lock with disabled interrupts */
5789 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
5791 struct rq
*rq
= cpu_rq(dead_cpu
);
5793 /* Must be exiting, otherwise would be on tasklist. */
5794 BUG_ON(!p
->exit_state
);
5796 /* Cannot have done final schedule yet: would have vanished. */
5797 BUG_ON(p
->state
== TASK_DEAD
);
5802 * Drop lock around migration; if someone else moves it,
5803 * that's OK. No task can be added to this CPU, so iteration is
5806 spin_unlock_irq(&rq
->lock
);
5807 move_task_off_dead_cpu(dead_cpu
, p
);
5808 spin_lock_irq(&rq
->lock
);
5813 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5814 static void migrate_dead_tasks(unsigned int dead_cpu
)
5816 struct rq
*rq
= cpu_rq(dead_cpu
);
5817 struct task_struct
*next
;
5820 if (!rq
->nr_running
)
5822 update_rq_clock(rq
);
5823 next
= pick_next_task(rq
, rq
->curr
);
5826 migrate_dead(dead_cpu
, next
);
5830 #endif /* CONFIG_HOTPLUG_CPU */
5832 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5834 static struct ctl_table sd_ctl_dir
[] = {
5836 .procname
= "sched_domain",
5842 static struct ctl_table sd_ctl_root
[] = {
5844 .ctl_name
= CTL_KERN
,
5845 .procname
= "kernel",
5847 .child
= sd_ctl_dir
,
5852 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
5854 struct ctl_table
*entry
=
5855 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
5860 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
5862 struct ctl_table
*entry
;
5865 * In the intermediate directories, both the child directory and
5866 * procname are dynamically allocated and could fail but the mode
5867 * will always be set. In the lowest directory the names are
5868 * static strings and all have proc handlers.
5870 for (entry
= *tablep
; entry
->mode
; entry
++) {
5872 sd_free_ctl_entry(&entry
->child
);
5873 if (entry
->proc_handler
== NULL
)
5874 kfree(entry
->procname
);
5882 set_table_entry(struct ctl_table
*entry
,
5883 const char *procname
, void *data
, int maxlen
,
5884 mode_t mode
, proc_handler
*proc_handler
)
5886 entry
->procname
= procname
;
5888 entry
->maxlen
= maxlen
;
5890 entry
->proc_handler
= proc_handler
;
5893 static struct ctl_table
*
5894 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
5896 struct ctl_table
*table
= sd_alloc_ctl_entry(12);
5901 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
5902 sizeof(long), 0644, proc_doulongvec_minmax
);
5903 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
5904 sizeof(long), 0644, proc_doulongvec_minmax
);
5905 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
5906 sizeof(int), 0644, proc_dointvec_minmax
);
5907 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
5908 sizeof(int), 0644, proc_dointvec_minmax
);
5909 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
5910 sizeof(int), 0644, proc_dointvec_minmax
);
5911 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
5912 sizeof(int), 0644, proc_dointvec_minmax
);
5913 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
5914 sizeof(int), 0644, proc_dointvec_minmax
);
5915 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
5916 sizeof(int), 0644, proc_dointvec_minmax
);
5917 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
5918 sizeof(int), 0644, proc_dointvec_minmax
);
5919 set_table_entry(&table
[9], "cache_nice_tries",
5920 &sd
->cache_nice_tries
,
5921 sizeof(int), 0644, proc_dointvec_minmax
);
5922 set_table_entry(&table
[10], "flags", &sd
->flags
,
5923 sizeof(int), 0644, proc_dointvec_minmax
);
5924 /* &table[11] is terminator */
5929 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
5931 struct ctl_table
*entry
, *table
;
5932 struct sched_domain
*sd
;
5933 int domain_num
= 0, i
;
5936 for_each_domain(cpu
, sd
)
5938 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
5943 for_each_domain(cpu
, sd
) {
5944 snprintf(buf
, 32, "domain%d", i
);
5945 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5947 entry
->child
= sd_alloc_ctl_domain_table(sd
);
5954 static struct ctl_table_header
*sd_sysctl_header
;
5955 static void register_sched_domain_sysctl(void)
5957 int i
, cpu_num
= num_online_cpus();
5958 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
5961 WARN_ON(sd_ctl_dir
[0].child
);
5962 sd_ctl_dir
[0].child
= entry
;
5967 for_each_online_cpu(i
) {
5968 snprintf(buf
, 32, "cpu%d", i
);
5969 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5971 entry
->child
= sd_alloc_ctl_cpu_table(i
);
5975 WARN_ON(sd_sysctl_header
);
5976 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
5979 /* may be called multiple times per register */
5980 static void unregister_sched_domain_sysctl(void)
5982 if (sd_sysctl_header
)
5983 unregister_sysctl_table(sd_sysctl_header
);
5984 sd_sysctl_header
= NULL
;
5985 if (sd_ctl_dir
[0].child
)
5986 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
5989 static void register_sched_domain_sysctl(void)
5992 static void unregister_sched_domain_sysctl(void)
5998 * migration_call - callback that gets triggered when a CPU is added.
5999 * Here we can start up the necessary migration thread for the new CPU.
6001 static int __cpuinit
6002 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
6004 struct task_struct
*p
;
6005 int cpu
= (long)hcpu
;
6006 unsigned long flags
;
6011 case CPU_UP_PREPARE
:
6012 case CPU_UP_PREPARE_FROZEN
:
6013 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
6016 kthread_bind(p
, cpu
);
6017 /* Must be high prio: stop_machine expects to yield to it. */
6018 rq
= task_rq_lock(p
, &flags
);
6019 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
6020 task_rq_unlock(rq
, &flags
);
6021 cpu_rq(cpu
)->migration_thread
= p
;
6025 case CPU_ONLINE_FROZEN
:
6026 /* Strictly unnecessary, as first user will wake it. */
6027 wake_up_process(cpu_rq(cpu
)->migration_thread
);
6029 /* Update our root-domain */
6031 spin_lock_irqsave(&rq
->lock
, flags
);
6033 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
6034 cpu_set(cpu
, rq
->rd
->online
);
6036 spin_unlock_irqrestore(&rq
->lock
, flags
);
6039 #ifdef CONFIG_HOTPLUG_CPU
6040 case CPU_UP_CANCELED
:
6041 case CPU_UP_CANCELED_FROZEN
:
6042 if (!cpu_rq(cpu
)->migration_thread
)
6044 /* Unbind it from offline cpu so it can run. Fall thru. */
6045 kthread_bind(cpu_rq(cpu
)->migration_thread
,
6046 any_online_cpu(cpu_online_map
));
6047 kthread_stop(cpu_rq(cpu
)->migration_thread
);
6048 cpu_rq(cpu
)->migration_thread
= NULL
;
6052 case CPU_DEAD_FROZEN
:
6053 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6054 migrate_live_tasks(cpu
);
6056 kthread_stop(rq
->migration_thread
);
6057 rq
->migration_thread
= NULL
;
6058 /* Idle task back to normal (off runqueue, low prio) */
6059 spin_lock_irq(&rq
->lock
);
6060 update_rq_clock(rq
);
6061 deactivate_task(rq
, rq
->idle
, 0);
6062 rq
->idle
->static_prio
= MAX_PRIO
;
6063 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
6064 rq
->idle
->sched_class
= &idle_sched_class
;
6065 migrate_dead_tasks(cpu
);
6066 spin_unlock_irq(&rq
->lock
);
6068 migrate_nr_uninterruptible(rq
);
6069 BUG_ON(rq
->nr_running
!= 0);
6072 * No need to migrate the tasks: it was best-effort if
6073 * they didn't take sched_hotcpu_mutex. Just wake up
6076 spin_lock_irq(&rq
->lock
);
6077 while (!list_empty(&rq
->migration_queue
)) {
6078 struct migration_req
*req
;
6080 req
= list_entry(rq
->migration_queue
.next
,
6081 struct migration_req
, list
);
6082 list_del_init(&req
->list
);
6083 complete(&req
->done
);
6085 spin_unlock_irq(&rq
->lock
);
6089 case CPU_DYING_FROZEN
:
6090 /* Update our root-domain */
6092 spin_lock_irqsave(&rq
->lock
, flags
);
6094 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
6095 cpu_clear(cpu
, rq
->rd
->online
);
6097 spin_unlock_irqrestore(&rq
->lock
, flags
);
6104 /* Register at highest priority so that task migration (migrate_all_tasks)
6105 * happens before everything else.
6107 static struct notifier_block __cpuinitdata migration_notifier
= {
6108 .notifier_call
= migration_call
,
6112 void __init
migration_init(void)
6114 void *cpu
= (void *)(long)smp_processor_id();
6117 /* Start one for the boot CPU: */
6118 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
6119 BUG_ON(err
== NOTIFY_BAD
);
6120 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
6121 register_cpu_notifier(&migration_notifier
);
6127 /* Number of possible processor ids */
6128 int nr_cpu_ids __read_mostly
= NR_CPUS
;
6129 EXPORT_SYMBOL(nr_cpu_ids
);
6131 #ifdef CONFIG_SCHED_DEBUG
6133 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
)
6135 struct sched_group
*group
= sd
->groups
;
6136 cpumask_t groupmask
;
6139 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
6140 cpus_clear(groupmask
);
6142 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
6144 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
6145 printk("does not load-balance\n");
6147 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
6152 printk(KERN_CONT
"span %s\n", str
);
6154 if (!cpu_isset(cpu
, sd
->span
)) {
6155 printk(KERN_ERR
"ERROR: domain->span does not contain "
6158 if (!cpu_isset(cpu
, group
->cpumask
)) {
6159 printk(KERN_ERR
"ERROR: domain->groups does not contain"
6163 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
6167 printk(KERN_ERR
"ERROR: group is NULL\n");
6171 if (!group
->__cpu_power
) {
6172 printk(KERN_CONT
"\n");
6173 printk(KERN_ERR
"ERROR: domain->cpu_power not "
6178 if (!cpus_weight(group
->cpumask
)) {
6179 printk(KERN_CONT
"\n");
6180 printk(KERN_ERR
"ERROR: empty group\n");
6184 if (cpus_intersects(groupmask
, group
->cpumask
)) {
6185 printk(KERN_CONT
"\n");
6186 printk(KERN_ERR
"ERROR: repeated CPUs\n");
6190 cpus_or(groupmask
, groupmask
, group
->cpumask
);
6192 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
6193 printk(KERN_CONT
" %s", str
);
6195 group
= group
->next
;
6196 } while (group
!= sd
->groups
);
6197 printk(KERN_CONT
"\n");
6199 if (!cpus_equal(sd
->span
, groupmask
))
6200 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
6202 if (sd
->parent
&& !cpus_subset(groupmask
, sd
->parent
->span
))
6203 printk(KERN_ERR
"ERROR: parent span is not a superset "
6204 "of domain->span\n");
6208 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
6213 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
6217 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
6220 if (sched_domain_debug_one(sd
, cpu
, level
))
6229 # define sched_domain_debug(sd, cpu) do { } while (0)
6232 static int sd_degenerate(struct sched_domain
*sd
)
6234 if (cpus_weight(sd
->span
) == 1)
6237 /* Following flags need at least 2 groups */
6238 if (sd
->flags
& (SD_LOAD_BALANCE
|
6239 SD_BALANCE_NEWIDLE
|
6243 SD_SHARE_PKG_RESOURCES
)) {
6244 if (sd
->groups
!= sd
->groups
->next
)
6248 /* Following flags don't use groups */
6249 if (sd
->flags
& (SD_WAKE_IDLE
|
6258 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6260 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6262 if (sd_degenerate(parent
))
6265 if (!cpus_equal(sd
->span
, parent
->span
))
6268 /* Does parent contain flags not in child? */
6269 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6270 if (cflags
& SD_WAKE_AFFINE
)
6271 pflags
&= ~SD_WAKE_BALANCE
;
6272 /* Flags needing groups don't count if only 1 group in parent */
6273 if (parent
->groups
== parent
->groups
->next
) {
6274 pflags
&= ~(SD_LOAD_BALANCE
|
6275 SD_BALANCE_NEWIDLE
|
6279 SD_SHARE_PKG_RESOURCES
);
6281 if (~cflags
& pflags
)
6287 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6289 unsigned long flags
;
6290 const struct sched_class
*class;
6292 spin_lock_irqsave(&rq
->lock
, flags
);
6295 struct root_domain
*old_rd
= rq
->rd
;
6297 for (class = sched_class_highest
; class; class = class->next
) {
6298 if (class->leave_domain
)
6299 class->leave_domain(rq
);
6302 cpu_clear(rq
->cpu
, old_rd
->span
);
6303 cpu_clear(rq
->cpu
, old_rd
->online
);
6305 if (atomic_dec_and_test(&old_rd
->refcount
))
6309 atomic_inc(&rd
->refcount
);
6312 cpu_set(rq
->cpu
, rd
->span
);
6313 if (cpu_isset(rq
->cpu
, cpu_online_map
))
6314 cpu_set(rq
->cpu
, rd
->online
);
6316 for (class = sched_class_highest
; class; class = class->next
) {
6317 if (class->join_domain
)
6318 class->join_domain(rq
);
6321 spin_unlock_irqrestore(&rq
->lock
, flags
);
6324 static void init_rootdomain(struct root_domain
*rd
)
6326 memset(rd
, 0, sizeof(*rd
));
6328 cpus_clear(rd
->span
);
6329 cpus_clear(rd
->online
);
6332 static void init_defrootdomain(void)
6334 init_rootdomain(&def_root_domain
);
6335 atomic_set(&def_root_domain
.refcount
, 1);
6338 static struct root_domain
*alloc_rootdomain(void)
6340 struct root_domain
*rd
;
6342 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6346 init_rootdomain(rd
);
6352 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6353 * hold the hotplug lock.
6356 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6358 struct rq
*rq
= cpu_rq(cpu
);
6359 struct sched_domain
*tmp
;
6361 /* Remove the sched domains which do not contribute to scheduling. */
6362 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
6363 struct sched_domain
*parent
= tmp
->parent
;
6366 if (sd_parent_degenerate(tmp
, parent
)) {
6367 tmp
->parent
= parent
->parent
;
6369 parent
->parent
->child
= tmp
;
6373 if (sd
&& sd_degenerate(sd
)) {
6379 sched_domain_debug(sd
, cpu
);
6381 rq_attach_root(rq
, rd
);
6382 rcu_assign_pointer(rq
->sd
, sd
);
6385 /* cpus with isolated domains */
6386 static cpumask_t cpu_isolated_map
= CPU_MASK_NONE
;
6388 /* Setup the mask of cpus configured for isolated domains */
6389 static int __init
isolated_cpu_setup(char *str
)
6391 int ints
[NR_CPUS
], i
;
6393 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
6394 cpus_clear(cpu_isolated_map
);
6395 for (i
= 1; i
<= ints
[0]; i
++)
6396 if (ints
[i
] < NR_CPUS
)
6397 cpu_set(ints
[i
], cpu_isolated_map
);
6401 __setup("isolcpus=", isolated_cpu_setup
);
6404 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6405 * to a function which identifies what group(along with sched group) a CPU
6406 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6407 * (due to the fact that we keep track of groups covered with a cpumask_t).
6409 * init_sched_build_groups will build a circular linked list of the groups
6410 * covered by the given span, and will set each group's ->cpumask correctly,
6411 * and ->cpu_power to 0.
6414 init_sched_build_groups(cpumask_t span
, const cpumask_t
*cpu_map
,
6415 int (*group_fn
)(int cpu
, const cpumask_t
*cpu_map
,
6416 struct sched_group
**sg
))
6418 struct sched_group
*first
= NULL
, *last
= NULL
;
6419 cpumask_t covered
= CPU_MASK_NONE
;
6422 for_each_cpu_mask(i
, span
) {
6423 struct sched_group
*sg
;
6424 int group
= group_fn(i
, cpu_map
, &sg
);
6427 if (cpu_isset(i
, covered
))
6430 sg
->cpumask
= CPU_MASK_NONE
;
6431 sg
->__cpu_power
= 0;
6433 for_each_cpu_mask(j
, span
) {
6434 if (group_fn(j
, cpu_map
, NULL
) != group
)
6437 cpu_set(j
, covered
);
6438 cpu_set(j
, sg
->cpumask
);
6449 #define SD_NODES_PER_DOMAIN 16
6454 * find_next_best_node - find the next node to include in a sched_domain
6455 * @node: node whose sched_domain we're building
6456 * @used_nodes: nodes already in the sched_domain
6458 * Find the next node to include in a given scheduling domain. Simply
6459 * finds the closest node not already in the @used_nodes map.
6461 * Should use nodemask_t.
6463 static int find_next_best_node(int node
, unsigned long *used_nodes
)
6465 int i
, n
, val
, min_val
, best_node
= 0;
6469 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6470 /* Start at @node */
6471 n
= (node
+ i
) % MAX_NUMNODES
;
6473 if (!nr_cpus_node(n
))
6476 /* Skip already used nodes */
6477 if (test_bit(n
, used_nodes
))
6480 /* Simple min distance search */
6481 val
= node_distance(node
, n
);
6483 if (val
< min_val
) {
6489 set_bit(best_node
, used_nodes
);
6494 * sched_domain_node_span - get a cpumask for a node's sched_domain
6495 * @node: node whose cpumask we're constructing
6496 * @size: number of nodes to include in this span
6498 * Given a node, construct a good cpumask for its sched_domain to span. It
6499 * should be one that prevents unnecessary balancing, but also spreads tasks
6502 static cpumask_t
sched_domain_node_span(int node
)
6504 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
6505 cpumask_t span
, nodemask
;
6509 bitmap_zero(used_nodes
, MAX_NUMNODES
);
6511 nodemask
= node_to_cpumask(node
);
6512 cpus_or(span
, span
, nodemask
);
6513 set_bit(node
, used_nodes
);
6515 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
6516 int next_node
= find_next_best_node(node
, used_nodes
);
6518 nodemask
= node_to_cpumask(next_node
);
6519 cpus_or(span
, span
, nodemask
);
6526 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
6529 * SMT sched-domains:
6531 #ifdef CONFIG_SCHED_SMT
6532 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6533 static DEFINE_PER_CPU(struct sched_group
, sched_group_cpus
);
6536 cpu_to_cpu_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6539 *sg
= &per_cpu(sched_group_cpus
, cpu
);
6545 * multi-core sched-domains:
6547 #ifdef CONFIG_SCHED_MC
6548 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6549 static DEFINE_PER_CPU(struct sched_group
, sched_group_core
);
6552 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6554 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6557 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6558 cpus_and(mask
, mask
, *cpu_map
);
6559 group
= first_cpu(mask
);
6561 *sg
= &per_cpu(sched_group_core
, group
);
6564 #elif defined(CONFIG_SCHED_MC)
6566 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6569 *sg
= &per_cpu(sched_group_core
, cpu
);
6574 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6575 static DEFINE_PER_CPU(struct sched_group
, sched_group_phys
);
6578 cpu_to_phys_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6581 #ifdef CONFIG_SCHED_MC
6582 cpumask_t mask
= cpu_coregroup_map(cpu
);
6583 cpus_and(mask
, mask
, *cpu_map
);
6584 group
= first_cpu(mask
);
6585 #elif defined(CONFIG_SCHED_SMT)
6586 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6587 cpus_and(mask
, mask
, *cpu_map
);
6588 group
= first_cpu(mask
);
6593 *sg
= &per_cpu(sched_group_phys
, group
);
6599 * The init_sched_build_groups can't handle what we want to do with node
6600 * groups, so roll our own. Now each node has its own list of groups which
6601 * gets dynamically allocated.
6603 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6604 static struct sched_group
**sched_group_nodes_bycpu
[NR_CPUS
];
6606 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6607 static DEFINE_PER_CPU(struct sched_group
, sched_group_allnodes
);
6609 static int cpu_to_allnodes_group(int cpu
, const cpumask_t
*cpu_map
,
6610 struct sched_group
**sg
)
6612 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(cpu
));
6615 cpus_and(nodemask
, nodemask
, *cpu_map
);
6616 group
= first_cpu(nodemask
);
6619 *sg
= &per_cpu(sched_group_allnodes
, group
);
6623 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6625 struct sched_group
*sg
= group_head
;
6631 for_each_cpu_mask(j
, sg
->cpumask
) {
6632 struct sched_domain
*sd
;
6634 sd
= &per_cpu(phys_domains
, j
);
6635 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6637 * Only add "power" once for each
6643 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
6646 } while (sg
!= group_head
);
6651 /* Free memory allocated for various sched_group structures */
6652 static void free_sched_groups(const cpumask_t
*cpu_map
)
6656 for_each_cpu_mask(cpu
, *cpu_map
) {
6657 struct sched_group
**sched_group_nodes
6658 = sched_group_nodes_bycpu
[cpu
];
6660 if (!sched_group_nodes
)
6663 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6664 cpumask_t nodemask
= node_to_cpumask(i
);
6665 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6667 cpus_and(nodemask
, nodemask
, *cpu_map
);
6668 if (cpus_empty(nodemask
))
6678 if (oldsg
!= sched_group_nodes
[i
])
6681 kfree(sched_group_nodes
);
6682 sched_group_nodes_bycpu
[cpu
] = NULL
;
6686 static void free_sched_groups(const cpumask_t
*cpu_map
)
6692 * Initialize sched groups cpu_power.
6694 * cpu_power indicates the capacity of sched group, which is used while
6695 * distributing the load between different sched groups in a sched domain.
6696 * Typically cpu_power for all the groups in a sched domain will be same unless
6697 * there are asymmetries in the topology. If there are asymmetries, group
6698 * having more cpu_power will pickup more load compared to the group having
6701 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6702 * the maximum number of tasks a group can handle in the presence of other idle
6703 * or lightly loaded groups in the same sched domain.
6705 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
6707 struct sched_domain
*child
;
6708 struct sched_group
*group
;
6710 WARN_ON(!sd
|| !sd
->groups
);
6712 if (cpu
!= first_cpu(sd
->groups
->cpumask
))
6717 sd
->groups
->__cpu_power
= 0;
6720 * For perf policy, if the groups in child domain share resources
6721 * (for example cores sharing some portions of the cache hierarchy
6722 * or SMT), then set this domain groups cpu_power such that each group
6723 * can handle only one task, when there are other idle groups in the
6724 * same sched domain.
6726 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
6728 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
6729 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
6734 * add cpu_power of each child group to this groups cpu_power
6736 group
= child
->groups
;
6738 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
6739 group
= group
->next
;
6740 } while (group
!= child
->groups
);
6744 * Build sched domains for a given set of cpus and attach the sched domains
6745 * to the individual cpus
6747 static int build_sched_domains(const cpumask_t
*cpu_map
)
6750 struct root_domain
*rd
;
6752 struct sched_group
**sched_group_nodes
= NULL
;
6753 int sd_allnodes
= 0;
6756 * Allocate the per-node list of sched groups
6758 sched_group_nodes
= kcalloc(MAX_NUMNODES
, sizeof(struct sched_group
*),
6760 if (!sched_group_nodes
) {
6761 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6764 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6767 rd
= alloc_rootdomain();
6769 printk(KERN_WARNING
"Cannot alloc root domain\n");
6774 * Set up domains for cpus specified by the cpu_map.
6776 for_each_cpu_mask(i
, *cpu_map
) {
6777 struct sched_domain
*sd
= NULL
, *p
;
6778 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
6780 cpus_and(nodemask
, nodemask
, *cpu_map
);
6783 if (cpus_weight(*cpu_map
) >
6784 SD_NODES_PER_DOMAIN
*cpus_weight(nodemask
)) {
6785 sd
= &per_cpu(allnodes_domains
, i
);
6786 *sd
= SD_ALLNODES_INIT
;
6787 sd
->span
= *cpu_map
;
6788 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
);
6794 sd
= &per_cpu(node_domains
, i
);
6796 sd
->span
= sched_domain_node_span(cpu_to_node(i
));
6800 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6804 sd
= &per_cpu(phys_domains
, i
);
6806 sd
->span
= nodemask
;
6810 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
);
6812 #ifdef CONFIG_SCHED_MC
6814 sd
= &per_cpu(core_domains
, i
);
6816 sd
->span
= cpu_coregroup_map(i
);
6817 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6820 cpu_to_core_group(i
, cpu_map
, &sd
->groups
);
6823 #ifdef CONFIG_SCHED_SMT
6825 sd
= &per_cpu(cpu_domains
, i
);
6826 *sd
= SD_SIBLING_INIT
;
6827 sd
->span
= per_cpu(cpu_sibling_map
, i
);
6828 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6831 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
);
6835 #ifdef CONFIG_SCHED_SMT
6836 /* Set up CPU (sibling) groups */
6837 for_each_cpu_mask(i
, *cpu_map
) {
6838 cpumask_t this_sibling_map
= per_cpu(cpu_sibling_map
, i
);
6839 cpus_and(this_sibling_map
, this_sibling_map
, *cpu_map
);
6840 if (i
!= first_cpu(this_sibling_map
))
6843 init_sched_build_groups(this_sibling_map
, cpu_map
,
6848 #ifdef CONFIG_SCHED_MC
6849 /* Set up multi-core groups */
6850 for_each_cpu_mask(i
, *cpu_map
) {
6851 cpumask_t this_core_map
= cpu_coregroup_map(i
);
6852 cpus_and(this_core_map
, this_core_map
, *cpu_map
);
6853 if (i
!= first_cpu(this_core_map
))
6855 init_sched_build_groups(this_core_map
, cpu_map
,
6856 &cpu_to_core_group
);
6860 /* Set up physical groups */
6861 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6862 cpumask_t nodemask
= node_to_cpumask(i
);
6864 cpus_and(nodemask
, nodemask
, *cpu_map
);
6865 if (cpus_empty(nodemask
))
6868 init_sched_build_groups(nodemask
, cpu_map
, &cpu_to_phys_group
);
6872 /* Set up node groups */
6874 init_sched_build_groups(*cpu_map
, cpu_map
,
6875 &cpu_to_allnodes_group
);
6877 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6878 /* Set up node groups */
6879 struct sched_group
*sg
, *prev
;
6880 cpumask_t nodemask
= node_to_cpumask(i
);
6881 cpumask_t domainspan
;
6882 cpumask_t covered
= CPU_MASK_NONE
;
6885 cpus_and(nodemask
, nodemask
, *cpu_map
);
6886 if (cpus_empty(nodemask
)) {
6887 sched_group_nodes
[i
] = NULL
;
6891 domainspan
= sched_domain_node_span(i
);
6892 cpus_and(domainspan
, domainspan
, *cpu_map
);
6894 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
6896 printk(KERN_WARNING
"Can not alloc domain group for "
6900 sched_group_nodes
[i
] = sg
;
6901 for_each_cpu_mask(j
, nodemask
) {
6902 struct sched_domain
*sd
;
6904 sd
= &per_cpu(node_domains
, j
);
6907 sg
->__cpu_power
= 0;
6908 sg
->cpumask
= nodemask
;
6910 cpus_or(covered
, covered
, nodemask
);
6913 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
6914 cpumask_t tmp
, notcovered
;
6915 int n
= (i
+ j
) % MAX_NUMNODES
;
6917 cpus_complement(notcovered
, covered
);
6918 cpus_and(tmp
, notcovered
, *cpu_map
);
6919 cpus_and(tmp
, tmp
, domainspan
);
6920 if (cpus_empty(tmp
))
6923 nodemask
= node_to_cpumask(n
);
6924 cpus_and(tmp
, tmp
, nodemask
);
6925 if (cpus_empty(tmp
))
6928 sg
= kmalloc_node(sizeof(struct sched_group
),
6932 "Can not alloc domain group for node %d\n", j
);
6935 sg
->__cpu_power
= 0;
6937 sg
->next
= prev
->next
;
6938 cpus_or(covered
, covered
, tmp
);
6945 /* Calculate CPU power for physical packages and nodes */
6946 #ifdef CONFIG_SCHED_SMT
6947 for_each_cpu_mask(i
, *cpu_map
) {
6948 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
);
6950 init_sched_groups_power(i
, sd
);
6953 #ifdef CONFIG_SCHED_MC
6954 for_each_cpu_mask(i
, *cpu_map
) {
6955 struct sched_domain
*sd
= &per_cpu(core_domains
, i
);
6957 init_sched_groups_power(i
, sd
);
6961 for_each_cpu_mask(i
, *cpu_map
) {
6962 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
);
6964 init_sched_groups_power(i
, sd
);
6968 for (i
= 0; i
< MAX_NUMNODES
; i
++)
6969 init_numa_sched_groups_power(sched_group_nodes
[i
]);
6972 struct sched_group
*sg
;
6974 cpu_to_allnodes_group(first_cpu(*cpu_map
), cpu_map
, &sg
);
6975 init_numa_sched_groups_power(sg
);
6979 /* Attach the domains */
6980 for_each_cpu_mask(i
, *cpu_map
) {
6981 struct sched_domain
*sd
;
6982 #ifdef CONFIG_SCHED_SMT
6983 sd
= &per_cpu(cpu_domains
, i
);
6984 #elif defined(CONFIG_SCHED_MC)
6985 sd
= &per_cpu(core_domains
, i
);
6987 sd
= &per_cpu(phys_domains
, i
);
6989 cpu_attach_domain(sd
, rd
, i
);
6996 free_sched_groups(cpu_map
);
7001 static cpumask_t
*doms_cur
; /* current sched domains */
7002 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
7005 * Special case: If a kmalloc of a doms_cur partition (array of
7006 * cpumask_t) fails, then fallback to a single sched domain,
7007 * as determined by the single cpumask_t fallback_doms.
7009 static cpumask_t fallback_doms
;
7011 void __attribute__((weak
)) arch_update_cpu_topology(void)
7016 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7017 * For now this just excludes isolated cpus, but could be used to
7018 * exclude other special cases in the future.
7020 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
7024 arch_update_cpu_topology();
7026 doms_cur
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
7028 doms_cur
= &fallback_doms
;
7029 cpus_andnot(*doms_cur
, *cpu_map
, cpu_isolated_map
);
7030 err
= build_sched_domains(doms_cur
);
7031 register_sched_domain_sysctl();
7036 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
)
7038 free_sched_groups(cpu_map
);
7042 * Detach sched domains from a group of cpus specified in cpu_map
7043 * These cpus will now be attached to the NULL domain
7045 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
7049 unregister_sched_domain_sysctl();
7051 for_each_cpu_mask(i
, *cpu_map
)
7052 cpu_attach_domain(NULL
, &def_root_domain
, i
);
7053 synchronize_sched();
7054 arch_destroy_sched_domains(cpu_map
);
7058 * Partition sched domains as specified by the 'ndoms_new'
7059 * cpumasks in the array doms_new[] of cpumasks. This compares
7060 * doms_new[] to the current sched domain partitioning, doms_cur[].
7061 * It destroys each deleted domain and builds each new domain.
7063 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7064 * The masks don't intersect (don't overlap.) We should setup one
7065 * sched domain for each mask. CPUs not in any of the cpumasks will
7066 * not be load balanced. If the same cpumask appears both in the
7067 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7070 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7071 * ownership of it and will kfree it when done with it. If the caller
7072 * failed the kmalloc call, then it can pass in doms_new == NULL,
7073 * and partition_sched_domains() will fallback to the single partition
7076 * Call with hotplug lock held
7078 void partition_sched_domains(int ndoms_new
, cpumask_t
*doms_new
)
7084 /* always unregister in case we don't destroy any domains */
7085 unregister_sched_domain_sysctl();
7087 if (doms_new
== NULL
) {
7089 doms_new
= &fallback_doms
;
7090 cpus_andnot(doms_new
[0], cpu_online_map
, cpu_isolated_map
);
7093 /* Destroy deleted domains */
7094 for (i
= 0; i
< ndoms_cur
; i
++) {
7095 for (j
= 0; j
< ndoms_new
; j
++) {
7096 if (cpus_equal(doms_cur
[i
], doms_new
[j
]))
7099 /* no match - a current sched domain not in new doms_new[] */
7100 detach_destroy_domains(doms_cur
+ i
);
7105 /* Build new domains */
7106 for (i
= 0; i
< ndoms_new
; i
++) {
7107 for (j
= 0; j
< ndoms_cur
; j
++) {
7108 if (cpus_equal(doms_new
[i
], doms_cur
[j
]))
7111 /* no match - add a new doms_new */
7112 build_sched_domains(doms_new
+ i
);
7117 /* Remember the new sched domains */
7118 if (doms_cur
!= &fallback_doms
)
7120 doms_cur
= doms_new
;
7121 ndoms_cur
= ndoms_new
;
7123 register_sched_domain_sysctl();
7128 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7129 int arch_reinit_sched_domains(void)
7134 detach_destroy_domains(&cpu_online_map
);
7135 err
= arch_init_sched_domains(&cpu_online_map
);
7141 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
7145 if (buf
[0] != '0' && buf
[0] != '1')
7149 sched_smt_power_savings
= (buf
[0] == '1');
7151 sched_mc_power_savings
= (buf
[0] == '1');
7153 ret
= arch_reinit_sched_domains();
7155 return ret
? ret
: count
;
7158 #ifdef CONFIG_SCHED_MC
7159 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
7161 return sprintf(page
, "%u\n", sched_mc_power_savings
);
7163 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
7164 const char *buf
, size_t count
)
7166 return sched_power_savings_store(buf
, count
, 0);
7168 static SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
7169 sched_mc_power_savings_store
);
7172 #ifdef CONFIG_SCHED_SMT
7173 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
7175 return sprintf(page
, "%u\n", sched_smt_power_savings
);
7177 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
7178 const char *buf
, size_t count
)
7180 return sched_power_savings_store(buf
, count
, 1);
7182 static SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
7183 sched_smt_power_savings_store
);
7186 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
7190 #ifdef CONFIG_SCHED_SMT
7192 err
= sysfs_create_file(&cls
->kset
.kobj
,
7193 &attr_sched_smt_power_savings
.attr
);
7195 #ifdef CONFIG_SCHED_MC
7196 if (!err
&& mc_capable())
7197 err
= sysfs_create_file(&cls
->kset
.kobj
,
7198 &attr_sched_mc_power_savings
.attr
);
7205 * Force a reinitialization of the sched domains hierarchy. The domains
7206 * and groups cannot be updated in place without racing with the balancing
7207 * code, so we temporarily attach all running cpus to the NULL domain
7208 * which will prevent rebalancing while the sched domains are recalculated.
7210 static int update_sched_domains(struct notifier_block
*nfb
,
7211 unsigned long action
, void *hcpu
)
7214 case CPU_UP_PREPARE
:
7215 case CPU_UP_PREPARE_FROZEN
:
7216 case CPU_DOWN_PREPARE
:
7217 case CPU_DOWN_PREPARE_FROZEN
:
7218 detach_destroy_domains(&cpu_online_map
);
7221 case CPU_UP_CANCELED
:
7222 case CPU_UP_CANCELED_FROZEN
:
7223 case CPU_DOWN_FAILED
:
7224 case CPU_DOWN_FAILED_FROZEN
:
7226 case CPU_ONLINE_FROZEN
:
7228 case CPU_DEAD_FROZEN
:
7230 * Fall through and re-initialise the domains.
7237 /* The hotplug lock is already held by cpu_up/cpu_down */
7238 arch_init_sched_domains(&cpu_online_map
);
7243 void __init
sched_init_smp(void)
7245 cpumask_t non_isolated_cpus
;
7248 arch_init_sched_domains(&cpu_online_map
);
7249 cpus_andnot(non_isolated_cpus
, cpu_possible_map
, cpu_isolated_map
);
7250 if (cpus_empty(non_isolated_cpus
))
7251 cpu_set(smp_processor_id(), non_isolated_cpus
);
7253 /* XXX: Theoretical race here - CPU may be hotplugged now */
7254 hotcpu_notifier(update_sched_domains
, 0);
7256 /* Move init over to a non-isolated CPU */
7257 if (set_cpus_allowed(current
, non_isolated_cpus
) < 0)
7259 sched_init_granularity();
7262 void __init
sched_init_smp(void)
7264 sched_init_granularity();
7266 #endif /* CONFIG_SMP */
7268 int in_sched_functions(unsigned long addr
)
7270 return in_lock_functions(addr
) ||
7271 (addr
>= (unsigned long)__sched_text_start
7272 && addr
< (unsigned long)__sched_text_end
);
7275 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
7277 cfs_rq
->tasks_timeline
= RB_ROOT
;
7278 #ifdef CONFIG_FAIR_GROUP_SCHED
7281 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
7284 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
7286 struct rt_prio_array
*array
;
7289 array
= &rt_rq
->active
;
7290 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
7291 INIT_LIST_HEAD(array
->queue
+ i
);
7292 __clear_bit(i
, array
->bitmap
);
7294 /* delimiter for bitsearch: */
7295 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
7297 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7298 rt_rq
->highest_prio
= MAX_RT_PRIO
;
7301 rt_rq
->rt_nr_migratory
= 0;
7302 rt_rq
->overloaded
= 0;
7306 rt_rq
->rt_throttled
= 0;
7307 rt_rq
->rt_runtime
= 0;
7308 spin_lock_init(&rt_rq
->rt_runtime_lock
);
7310 #ifdef CONFIG_RT_GROUP_SCHED
7311 rt_rq
->rt_nr_boosted
= 0;
7316 #ifdef CONFIG_FAIR_GROUP_SCHED
7317 static void init_tg_cfs_entry(struct rq
*rq
, struct task_group
*tg
,
7318 struct cfs_rq
*cfs_rq
, struct sched_entity
*se
,
7321 tg
->cfs_rq
[cpu
] = cfs_rq
;
7322 init_cfs_rq(cfs_rq
, rq
);
7325 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7328 se
->cfs_rq
= &rq
->cfs
;
7330 se
->load
.weight
= tg
->shares
;
7331 se
->load
.inv_weight
= div64_64(1ULL<<32, se
->load
.weight
);
7336 #ifdef CONFIG_RT_GROUP_SCHED
7337 static void init_tg_rt_entry(struct rq
*rq
, struct task_group
*tg
,
7338 struct rt_rq
*rt_rq
, struct sched_rt_entity
*rt_se
,
7341 tg
->rt_rq
[cpu
] = rt_rq
;
7342 init_rt_rq(rt_rq
, rq
);
7344 rt_rq
->rt_se
= rt_se
;
7345 rt_rq
->rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
7347 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
7349 tg
->rt_se
[cpu
] = rt_se
;
7350 rt_se
->rt_rq
= &rq
->rt
;
7351 rt_se
->my_q
= rt_rq
;
7352 rt_se
->parent
= NULL
;
7353 INIT_LIST_HEAD(&rt_se
->run_list
);
7357 void __init
sched_init(void)
7359 int highest_cpu
= 0;
7363 init_defrootdomain();
7366 init_rt_bandwidth(&def_rt_bandwidth
,
7367 global_rt_period(), global_rt_runtime());
7369 #ifdef CONFIG_RT_GROUP_SCHED
7370 init_rt_bandwidth(&init_task_group
.rt_bandwidth
,
7371 global_rt_period(), global_rt_runtime());
7374 #ifdef CONFIG_GROUP_SCHED
7375 list_add(&init_task_group
.list
, &task_groups
);
7378 for_each_possible_cpu(i
) {
7382 spin_lock_init(&rq
->lock
);
7383 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
7386 update_last_tick_seen(rq
);
7387 init_cfs_rq(&rq
->cfs
, rq
);
7388 init_rt_rq(&rq
->rt
, rq
);
7389 #ifdef CONFIG_FAIR_GROUP_SCHED
7390 init_task_group
.shares
= init_task_group_load
;
7391 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
7392 init_tg_cfs_entry(rq
, &init_task_group
,
7393 &per_cpu(init_cfs_rq
, i
),
7394 &per_cpu(init_sched_entity
, i
), i
, 1);
7397 #ifdef CONFIG_RT_GROUP_SCHED
7398 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
7399 init_tg_rt_entry(rq
, &init_task_group
,
7400 &per_cpu(init_rt_rq
, i
),
7401 &per_cpu(init_sched_rt_entity
, i
), i
, 1);
7403 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
7406 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
7407 rq
->cpu_load
[j
] = 0;
7411 rq
->active_balance
= 0;
7412 rq
->next_balance
= jiffies
;
7415 rq
->migration_thread
= NULL
;
7416 INIT_LIST_HEAD(&rq
->migration_queue
);
7417 rq_attach_root(rq
, &def_root_domain
);
7420 atomic_set(&rq
->nr_iowait
, 0);
7424 set_load_weight(&init_task
);
7426 #ifdef CONFIG_PREEMPT_NOTIFIERS
7427 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
7431 nr_cpu_ids
= highest_cpu
+ 1;
7432 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
, NULL
);
7435 #ifdef CONFIG_RT_MUTEXES
7436 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
7440 * The boot idle thread does lazy MMU switching as well:
7442 atomic_inc(&init_mm
.mm_count
);
7443 enter_lazy_tlb(&init_mm
, current
);
7446 * Make us the idle thread. Technically, schedule() should not be
7447 * called from this thread, however somewhere below it might be,
7448 * but because we are the idle thread, we just pick up running again
7449 * when this runqueue becomes "idle".
7451 init_idle(current
, smp_processor_id());
7453 * During early bootup we pretend to be a normal task:
7455 current
->sched_class
= &fair_sched_class
;
7457 scheduler_running
= 1;
7460 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7461 void __might_sleep(char *file
, int line
)
7464 static unsigned long prev_jiffy
; /* ratelimiting */
7466 if ((in_atomic() || irqs_disabled()) &&
7467 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
7468 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
7470 prev_jiffy
= jiffies
;
7471 printk(KERN_ERR
"BUG: sleeping function called from invalid"
7472 " context at %s:%d\n", file
, line
);
7473 printk("in_atomic():%d, irqs_disabled():%d\n",
7474 in_atomic(), irqs_disabled());
7475 debug_show_held_locks(current
);
7476 if (irqs_disabled())
7477 print_irqtrace_events(current
);
7482 EXPORT_SYMBOL(__might_sleep
);
7485 #ifdef CONFIG_MAGIC_SYSRQ
7486 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
7489 update_rq_clock(rq
);
7490 on_rq
= p
->se
.on_rq
;
7492 deactivate_task(rq
, p
, 0);
7493 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
7495 activate_task(rq
, p
, 0);
7496 resched_task(rq
->curr
);
7500 void normalize_rt_tasks(void)
7502 struct task_struct
*g
, *p
;
7503 unsigned long flags
;
7506 read_lock_irqsave(&tasklist_lock
, flags
);
7507 do_each_thread(g
, p
) {
7509 * Only normalize user tasks:
7514 p
->se
.exec_start
= 0;
7515 #ifdef CONFIG_SCHEDSTATS
7516 p
->se
.wait_start
= 0;
7517 p
->se
.sleep_start
= 0;
7518 p
->se
.block_start
= 0;
7520 task_rq(p
)->clock
= 0;
7524 * Renice negative nice level userspace
7527 if (TASK_NICE(p
) < 0 && p
->mm
)
7528 set_user_nice(p
, 0);
7532 spin_lock(&p
->pi_lock
);
7533 rq
= __task_rq_lock(p
);
7535 normalize_task(rq
, p
);
7537 __task_rq_unlock(rq
);
7538 spin_unlock(&p
->pi_lock
);
7539 } while_each_thread(g
, p
);
7541 read_unlock_irqrestore(&tasklist_lock
, flags
);
7544 #endif /* CONFIG_MAGIC_SYSRQ */
7548 * These functions are only useful for the IA64 MCA handling.
7550 * They can only be called when the whole system has been
7551 * stopped - every CPU needs to be quiescent, and no scheduling
7552 * activity can take place. Using them for anything else would
7553 * be a serious bug, and as a result, they aren't even visible
7554 * under any other configuration.
7558 * curr_task - return the current task for a given cpu.
7559 * @cpu: the processor in question.
7561 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7563 struct task_struct
*curr_task(int cpu
)
7565 return cpu_curr(cpu
);
7569 * set_curr_task - set the current task for a given cpu.
7570 * @cpu: the processor in question.
7571 * @p: the task pointer to set.
7573 * Description: This function must only be used when non-maskable interrupts
7574 * are serviced on a separate stack. It allows the architecture to switch the
7575 * notion of the current task on a cpu in a non-blocking manner. This function
7576 * must be called with all CPU's synchronized, and interrupts disabled, the
7577 * and caller must save the original value of the current task (see
7578 * curr_task() above) and restore that value before reenabling interrupts and
7579 * re-starting the system.
7581 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7583 void set_curr_task(int cpu
, struct task_struct
*p
)
7590 #ifdef CONFIG_FAIR_GROUP_SCHED
7591 static void free_fair_sched_group(struct task_group
*tg
)
7595 for_each_possible_cpu(i
) {
7597 kfree(tg
->cfs_rq
[i
]);
7606 static int alloc_fair_sched_group(struct task_group
*tg
)
7608 struct cfs_rq
*cfs_rq
;
7609 struct sched_entity
*se
;
7613 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * NR_CPUS
, GFP_KERNEL
);
7616 tg
->se
= kzalloc(sizeof(se
) * NR_CPUS
, GFP_KERNEL
);
7620 tg
->shares
= NICE_0_LOAD
;
7622 for_each_possible_cpu(i
) {
7625 cfs_rq
= kmalloc_node(sizeof(struct cfs_rq
),
7626 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7630 se
= kmalloc_node(sizeof(struct sched_entity
),
7631 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7635 init_tg_cfs_entry(rq
, tg
, cfs_rq
, se
, i
, 0);
7644 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
7646 list_add_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
,
7647 &cpu_rq(cpu
)->leaf_cfs_rq_list
);
7650 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
7652 list_del_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
);
7655 static inline void free_fair_sched_group(struct task_group
*tg
)
7659 static inline int alloc_fair_sched_group(struct task_group
*tg
)
7664 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
7668 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
7673 #ifdef CONFIG_RT_GROUP_SCHED
7674 static void free_rt_sched_group(struct task_group
*tg
)
7678 destroy_rt_bandwidth(&tg
->rt_bandwidth
);
7680 for_each_possible_cpu(i
) {
7682 kfree(tg
->rt_rq
[i
]);
7684 kfree(tg
->rt_se
[i
]);
7691 static int alloc_rt_sched_group(struct task_group
*tg
)
7693 struct rt_rq
*rt_rq
;
7694 struct sched_rt_entity
*rt_se
;
7698 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * NR_CPUS
, GFP_KERNEL
);
7701 tg
->rt_se
= kzalloc(sizeof(rt_se
) * NR_CPUS
, GFP_KERNEL
);
7705 init_rt_bandwidth(&tg
->rt_bandwidth
,
7706 ktime_to_ns(def_rt_bandwidth
.rt_period
), 0);
7708 for_each_possible_cpu(i
) {
7711 rt_rq
= kmalloc_node(sizeof(struct rt_rq
),
7712 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7716 rt_se
= kmalloc_node(sizeof(struct sched_rt_entity
),
7717 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7721 init_tg_rt_entry(rq
, tg
, rt_rq
, rt_se
, i
, 0);
7730 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
7732 list_add_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
,
7733 &cpu_rq(cpu
)->leaf_rt_rq_list
);
7736 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
7738 list_del_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
);
7741 static inline void free_rt_sched_group(struct task_group
*tg
)
7745 static inline int alloc_rt_sched_group(struct task_group
*tg
)
7750 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
7754 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
7759 #ifdef CONFIG_GROUP_SCHED
7760 static void free_sched_group(struct task_group
*tg
)
7762 free_fair_sched_group(tg
);
7763 free_rt_sched_group(tg
);
7767 /* allocate runqueue etc for a new task group */
7768 struct task_group
*sched_create_group(void)
7770 struct task_group
*tg
;
7771 unsigned long flags
;
7774 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
7776 return ERR_PTR(-ENOMEM
);
7778 if (!alloc_fair_sched_group(tg
))
7781 if (!alloc_rt_sched_group(tg
))
7784 spin_lock_irqsave(&task_group_lock
, flags
);
7785 for_each_possible_cpu(i
) {
7786 register_fair_sched_group(tg
, i
);
7787 register_rt_sched_group(tg
, i
);
7789 list_add_rcu(&tg
->list
, &task_groups
);
7790 spin_unlock_irqrestore(&task_group_lock
, flags
);
7795 free_sched_group(tg
);
7796 return ERR_PTR(-ENOMEM
);
7799 /* rcu callback to free various structures associated with a task group */
7800 static void free_sched_group_rcu(struct rcu_head
*rhp
)
7802 /* now it should be safe to free those cfs_rqs */
7803 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
7806 /* Destroy runqueue etc associated with a task group */
7807 void sched_destroy_group(struct task_group
*tg
)
7809 unsigned long flags
;
7812 spin_lock_irqsave(&task_group_lock
, flags
);
7813 for_each_possible_cpu(i
) {
7814 unregister_fair_sched_group(tg
, i
);
7815 unregister_rt_sched_group(tg
, i
);
7817 list_del_rcu(&tg
->list
);
7818 spin_unlock_irqrestore(&task_group_lock
, flags
);
7820 /* wait for possible concurrent references to cfs_rqs complete */
7821 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
7824 /* change task's runqueue when it moves between groups.
7825 * The caller of this function should have put the task in its new group
7826 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7827 * reflect its new group.
7829 void sched_move_task(struct task_struct
*tsk
)
7832 unsigned long flags
;
7835 rq
= task_rq_lock(tsk
, &flags
);
7837 update_rq_clock(rq
);
7839 running
= task_current(rq
, tsk
);
7840 on_rq
= tsk
->se
.on_rq
;
7843 dequeue_task(rq
, tsk
, 0);
7844 if (unlikely(running
))
7845 tsk
->sched_class
->put_prev_task(rq
, tsk
);
7847 set_task_rq(tsk
, task_cpu(tsk
));
7849 #ifdef CONFIG_FAIR_GROUP_SCHED
7850 if (tsk
->sched_class
->moved_group
)
7851 tsk
->sched_class
->moved_group(tsk
);
7854 if (unlikely(running
))
7855 tsk
->sched_class
->set_curr_task(rq
);
7857 enqueue_task(rq
, tsk
, 0);
7859 task_rq_unlock(rq
, &flags
);
7863 #ifdef CONFIG_FAIR_GROUP_SCHED
7864 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
7866 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
7867 struct rq
*rq
= cfs_rq
->rq
;
7870 spin_lock_irq(&rq
->lock
);
7874 dequeue_entity(cfs_rq
, se
, 0);
7876 se
->load
.weight
= shares
;
7877 se
->load
.inv_weight
= div64_64((1ULL<<32), shares
);
7880 enqueue_entity(cfs_rq
, se
, 0);
7882 spin_unlock_irq(&rq
->lock
);
7885 static DEFINE_MUTEX(shares_mutex
);
7887 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
7890 unsigned long flags
;
7893 * A weight of 0 or 1 can cause arithmetics problems.
7894 * (The default weight is 1024 - so there's no practical
7895 * limitation from this.)
7900 mutex_lock(&shares_mutex
);
7901 if (tg
->shares
== shares
)
7904 spin_lock_irqsave(&task_group_lock
, flags
);
7905 for_each_possible_cpu(i
)
7906 unregister_fair_sched_group(tg
, i
);
7907 spin_unlock_irqrestore(&task_group_lock
, flags
);
7909 /* wait for any ongoing reference to this group to finish */
7910 synchronize_sched();
7913 * Now we are free to modify the group's share on each cpu
7914 * w/o tripping rebalance_share or load_balance_fair.
7916 tg
->shares
= shares
;
7917 for_each_possible_cpu(i
)
7918 set_se_shares(tg
->se
[i
], shares
);
7921 * Enable load balance activity on this group, by inserting it back on
7922 * each cpu's rq->leaf_cfs_rq_list.
7924 spin_lock_irqsave(&task_group_lock
, flags
);
7925 for_each_possible_cpu(i
)
7926 register_fair_sched_group(tg
, i
);
7927 spin_unlock_irqrestore(&task_group_lock
, flags
);
7929 mutex_unlock(&shares_mutex
);
7933 unsigned long sched_group_shares(struct task_group
*tg
)
7939 #ifdef CONFIG_RT_GROUP_SCHED
7941 * Ensure that the real time constraints are schedulable.
7943 static DEFINE_MUTEX(rt_constraints_mutex
);
7945 static unsigned long to_ratio(u64 period
, u64 runtime
)
7947 if (runtime
== RUNTIME_INF
)
7950 return div64_64(runtime
<< 16, period
);
7953 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
7955 struct task_group
*tgi
;
7956 unsigned long total
= 0;
7957 unsigned long global_ratio
=
7958 to_ratio(global_rt_period(), global_rt_runtime());
7961 list_for_each_entry_rcu(tgi
, &task_groups
, list
) {
7965 total
+= to_ratio(ktime_to_ns(tgi
->rt_bandwidth
.rt_period
),
7966 tgi
->rt_bandwidth
.rt_runtime
);
7970 return total
+ to_ratio(period
, runtime
) < global_ratio
;
7973 /* Must be called with tasklist_lock held */
7974 static inline int tg_has_rt_tasks(struct task_group
*tg
)
7976 struct task_struct
*g
, *p
;
7977 do_each_thread(g
, p
) {
7978 if (rt_task(p
) && rt_rq_of_se(&p
->rt
)->tg
== tg
)
7980 } while_each_thread(g
, p
);
7984 static int tg_set_bandwidth(struct task_group
*tg
,
7985 u64 rt_period
, u64 rt_runtime
)
7989 mutex_lock(&rt_constraints_mutex
);
7990 read_lock(&tasklist_lock
);
7991 if (rt_runtime
== 0 && tg_has_rt_tasks(tg
)) {
7995 if (!__rt_schedulable(tg
, rt_period
, rt_runtime
)) {
8000 spin_lock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8001 tg
->rt_bandwidth
.rt_period
= ns_to_ktime(rt_period
);
8002 tg
->rt_bandwidth
.rt_runtime
= rt_runtime
;
8004 for_each_possible_cpu(i
) {
8005 struct rt_rq
*rt_rq
= tg
->rt_rq
[i
];
8007 spin_lock(&rt_rq
->rt_runtime_lock
);
8008 rt_rq
->rt_runtime
= rt_runtime
;
8009 spin_unlock(&rt_rq
->rt_runtime_lock
);
8011 spin_unlock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8013 read_unlock(&tasklist_lock
);
8014 mutex_unlock(&rt_constraints_mutex
);
8019 int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
8021 u64 rt_runtime
, rt_period
;
8023 rt_period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8024 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
8025 if (rt_runtime_us
< 0)
8026 rt_runtime
= RUNTIME_INF
;
8028 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
8031 long sched_group_rt_runtime(struct task_group
*tg
)
8035 if (tg
->rt_bandwidth
.rt_runtime
== RUNTIME_INF
)
8038 rt_runtime_us
= tg
->rt_bandwidth
.rt_runtime
;
8039 do_div(rt_runtime_us
, NSEC_PER_USEC
);
8040 return rt_runtime_us
;
8043 int sched_group_set_rt_period(struct task_group
*tg
, long rt_period_us
)
8045 u64 rt_runtime
, rt_period
;
8047 rt_period
= (u64
)rt_period_us
* NSEC_PER_USEC
;
8048 rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
8050 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
8053 long sched_group_rt_period(struct task_group
*tg
)
8057 rt_period_us
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8058 do_div(rt_period_us
, NSEC_PER_USEC
);
8059 return rt_period_us
;
8062 static int sched_rt_global_constraints(void)
8066 mutex_lock(&rt_constraints_mutex
);
8067 if (!__rt_schedulable(NULL
, 1, 0))
8069 mutex_unlock(&rt_constraints_mutex
);
8074 static int sched_rt_global_constraints(void)
8076 unsigned long flags
;
8079 spin_lock_irqsave(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8080 for_each_possible_cpu(i
) {
8081 struct rt_rq
*rt_rq
= &cpu_rq(i
)->rt
;
8083 spin_lock(&rt_rq
->rt_runtime_lock
);
8084 rt_rq
->rt_runtime
= global_rt_runtime();
8085 spin_unlock(&rt_rq
->rt_runtime_lock
);
8087 spin_unlock_irqrestore(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8093 int sched_rt_handler(struct ctl_table
*table
, int write
,
8094 struct file
*filp
, void __user
*buffer
, size_t *lenp
,
8098 int old_period
, old_runtime
;
8099 static DEFINE_MUTEX(mutex
);
8102 old_period
= sysctl_sched_rt_period
;
8103 old_runtime
= sysctl_sched_rt_runtime
;
8105 ret
= proc_dointvec(table
, write
, filp
, buffer
, lenp
, ppos
);
8107 if (!ret
&& write
) {
8108 ret
= sched_rt_global_constraints();
8110 sysctl_sched_rt_period
= old_period
;
8111 sysctl_sched_rt_runtime
= old_runtime
;
8113 def_rt_bandwidth
.rt_runtime
= global_rt_runtime();
8114 def_rt_bandwidth
.rt_period
=
8115 ns_to_ktime(global_rt_period());
8118 mutex_unlock(&mutex
);
8123 #ifdef CONFIG_CGROUP_SCHED
8125 /* return corresponding task_group object of a cgroup */
8126 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
8128 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
8129 struct task_group
, css
);
8132 static struct cgroup_subsys_state
*
8133 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8135 struct task_group
*tg
;
8137 if (!cgrp
->parent
) {
8138 /* This is early initialization for the top cgroup */
8139 init_task_group
.css
.cgroup
= cgrp
;
8140 return &init_task_group
.css
;
8143 /* we support only 1-level deep hierarchical scheduler atm */
8144 if (cgrp
->parent
->parent
)
8145 return ERR_PTR(-EINVAL
);
8147 tg
= sched_create_group();
8149 return ERR_PTR(-ENOMEM
);
8151 /* Bind the cgroup to task_group object we just created */
8152 tg
->css
.cgroup
= cgrp
;
8158 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8160 struct task_group
*tg
= cgroup_tg(cgrp
);
8162 sched_destroy_group(tg
);
8166 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8167 struct task_struct
*tsk
)
8169 #ifdef CONFIG_RT_GROUP_SCHED
8170 /* Don't accept realtime tasks when there is no way for them to run */
8171 if (rt_task(tsk
) && cgroup_tg(cgrp
)->rt_bandwidth
.rt_runtime
== 0)
8174 /* We don't support RT-tasks being in separate groups */
8175 if (tsk
->sched_class
!= &fair_sched_class
)
8183 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8184 struct cgroup
*old_cont
, struct task_struct
*tsk
)
8186 sched_move_task(tsk
);
8189 #ifdef CONFIG_FAIR_GROUP_SCHED
8190 static int cpu_shares_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
8193 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
8196 static u64
cpu_shares_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
8198 struct task_group
*tg
= cgroup_tg(cgrp
);
8200 return (u64
) tg
->shares
;
8204 #ifdef CONFIG_RT_GROUP_SCHED
8205 static ssize_t
cpu_rt_runtime_write(struct cgroup
*cgrp
, struct cftype
*cft
,
8207 const char __user
*userbuf
,
8208 size_t nbytes
, loff_t
*unused_ppos
)
8217 if (nbytes
>= sizeof(buffer
))
8219 if (copy_from_user(buffer
, userbuf
, nbytes
))
8222 buffer
[nbytes
] = 0; /* nul-terminate */
8224 /* strip newline if necessary */
8225 if (nbytes
&& (buffer
[nbytes
-1] == '\n'))
8226 buffer
[nbytes
-1] = 0;
8227 val
= simple_strtoll(buffer
, &end
, 0);
8231 /* Pass to subsystem */
8232 retval
= sched_group_set_rt_runtime(cgroup_tg(cgrp
), val
);
8238 static ssize_t
cpu_rt_runtime_read(struct cgroup
*cgrp
, struct cftype
*cft
,
8240 char __user
*buf
, size_t nbytes
,
8244 long val
= sched_group_rt_runtime(cgroup_tg(cgrp
));
8245 int len
= sprintf(tmp
, "%ld\n", val
);
8247 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
8250 static int cpu_rt_period_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
8253 return sched_group_set_rt_period(cgroup_tg(cgrp
), rt_period_us
);
8256 static u64
cpu_rt_period_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
8258 return sched_group_rt_period(cgroup_tg(cgrp
));
8262 static struct cftype cpu_files
[] = {
8263 #ifdef CONFIG_FAIR_GROUP_SCHED
8266 .read_uint
= cpu_shares_read_uint
,
8267 .write_uint
= cpu_shares_write_uint
,
8270 #ifdef CONFIG_RT_GROUP_SCHED
8272 .name
= "rt_runtime_us",
8273 .read
= cpu_rt_runtime_read
,
8274 .write
= cpu_rt_runtime_write
,
8277 .name
= "rt_period_us",
8278 .read_uint
= cpu_rt_period_read_uint
,
8279 .write_uint
= cpu_rt_period_write_uint
,
8284 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8286 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
8289 struct cgroup_subsys cpu_cgroup_subsys
= {
8291 .create
= cpu_cgroup_create
,
8292 .destroy
= cpu_cgroup_destroy
,
8293 .can_attach
= cpu_cgroup_can_attach
,
8294 .attach
= cpu_cgroup_attach
,
8295 .populate
= cpu_cgroup_populate
,
8296 .subsys_id
= cpu_cgroup_subsys_id
,
8300 #endif /* CONFIG_CGROUP_SCHED */
8302 #ifdef CONFIG_CGROUP_CPUACCT
8305 * CPU accounting code for task groups.
8307 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8308 * (balbir@in.ibm.com).
8311 /* track cpu usage of a group of tasks */
8313 struct cgroup_subsys_state css
;
8314 /* cpuusage holds pointer to a u64-type object on every cpu */
8318 struct cgroup_subsys cpuacct_subsys
;
8320 /* return cpu accounting group corresponding to this container */
8321 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cgrp
)
8323 return container_of(cgroup_subsys_state(cgrp
, cpuacct_subsys_id
),
8324 struct cpuacct
, css
);
8327 /* return cpu accounting group to which this task belongs */
8328 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
8330 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
8331 struct cpuacct
, css
);
8334 /* create a new cpu accounting group */
8335 static struct cgroup_subsys_state
*cpuacct_create(
8336 struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8338 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
8341 return ERR_PTR(-ENOMEM
);
8343 ca
->cpuusage
= alloc_percpu(u64
);
8344 if (!ca
->cpuusage
) {
8346 return ERR_PTR(-ENOMEM
);
8352 /* destroy an existing cpu accounting group */
8354 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8356 struct cpuacct
*ca
= cgroup_ca(cgrp
);
8358 free_percpu(ca
->cpuusage
);
8362 /* return total cpu usage (in nanoseconds) of a group */
8363 static u64
cpuusage_read(struct cgroup
*cgrp
, struct cftype
*cft
)
8365 struct cpuacct
*ca
= cgroup_ca(cgrp
);
8366 u64 totalcpuusage
= 0;
8369 for_each_possible_cpu(i
) {
8370 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
8373 * Take rq->lock to make 64-bit addition safe on 32-bit
8376 spin_lock_irq(&cpu_rq(i
)->lock
);
8377 totalcpuusage
+= *cpuusage
;
8378 spin_unlock_irq(&cpu_rq(i
)->lock
);
8381 return totalcpuusage
;
8384 static int cpuusage_write(struct cgroup
*cgrp
, struct cftype
*cftype
,
8387 struct cpuacct
*ca
= cgroup_ca(cgrp
);
8396 for_each_possible_cpu(i
) {
8397 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
8399 spin_lock_irq(&cpu_rq(i
)->lock
);
8401 spin_unlock_irq(&cpu_rq(i
)->lock
);
8407 static struct cftype files
[] = {
8410 .read_uint
= cpuusage_read
,
8411 .write_uint
= cpuusage_write
,
8415 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8417 return cgroup_add_files(cgrp
, ss
, files
, ARRAY_SIZE(files
));
8421 * charge this task's execution time to its accounting group.
8423 * called with rq->lock held.
8425 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
8429 if (!cpuacct_subsys
.active
)
8434 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, task_cpu(tsk
));
8436 *cpuusage
+= cputime
;
8440 struct cgroup_subsys cpuacct_subsys
= {
8442 .create
= cpuacct_create
,
8443 .destroy
= cpuacct_destroy
,
8444 .populate
= cpuacct_populate
,
8445 .subsys_id
= cpuacct_subsys_id
,
8447 #endif /* CONFIG_CGROUP_CPUACCT */