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)
120 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
121 * Since cpu_power is a 'constant', we can use a reciprocal divide.
123 static inline u32
sg_div_cpu_power(const struct sched_group
*sg
, u32 load
)
125 return reciprocal_divide(load
, sg
->reciprocal_cpu_power
);
129 * Each time a sched group cpu_power is changed,
130 * we must compute its reciprocal value
132 static inline void sg_inc_cpu_power(struct sched_group
*sg
, u32 val
)
134 sg
->__cpu_power
+= val
;
135 sg
->reciprocal_cpu_power
= reciprocal_value(sg
->__cpu_power
);
139 static inline int rt_policy(int policy
)
141 if (unlikely(policy
== SCHED_FIFO
) || unlikely(policy
== SCHED_RR
))
146 static inline int task_has_rt_policy(struct task_struct
*p
)
148 return rt_policy(p
->policy
);
152 * This is the priority-queue data structure of the RT scheduling class:
154 struct rt_prio_array
{
155 DECLARE_BITMAP(bitmap
, MAX_RT_PRIO
+1); /* include 1 bit for delimiter */
156 struct list_head queue
[MAX_RT_PRIO
];
159 #ifdef CONFIG_GROUP_SCHED
161 #include <linux/cgroup.h>
165 static LIST_HEAD(task_groups
);
167 /* task group related information */
169 #ifdef CONFIG_CGROUP_SCHED
170 struct cgroup_subsys_state css
;
173 #ifdef CONFIG_FAIR_GROUP_SCHED
174 /* schedulable entities of this group on each cpu */
175 struct sched_entity
**se
;
176 /* runqueue "owned" by this group on each cpu */
177 struct cfs_rq
**cfs_rq
;
178 unsigned long shares
;
181 #ifdef CONFIG_RT_GROUP_SCHED
182 struct sched_rt_entity
**rt_se
;
183 struct rt_rq
**rt_rq
;
189 struct list_head list
;
192 #ifdef CONFIG_FAIR_GROUP_SCHED
193 /* Default task group's sched entity on each cpu */
194 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
195 /* Default task group's cfs_rq on each cpu */
196 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
198 static struct sched_entity
*init_sched_entity_p
[NR_CPUS
];
199 static struct cfs_rq
*init_cfs_rq_p
[NR_CPUS
];
202 #ifdef CONFIG_RT_GROUP_SCHED
203 static DEFINE_PER_CPU(struct sched_rt_entity
, init_sched_rt_entity
);
204 static DEFINE_PER_CPU(struct rt_rq
, init_rt_rq
) ____cacheline_aligned_in_smp
;
206 static struct sched_rt_entity
*init_sched_rt_entity_p
[NR_CPUS
];
207 static struct rt_rq
*init_rt_rq_p
[NR_CPUS
];
210 /* task_group_lock serializes add/remove of task groups and also changes to
211 * a task group's cpu shares.
213 static DEFINE_SPINLOCK(task_group_lock
);
215 /* doms_cur_mutex serializes access to doms_cur[] array */
216 static DEFINE_MUTEX(doms_cur_mutex
);
218 #ifdef CONFIG_FAIR_GROUP_SCHED
219 #ifdef CONFIG_USER_SCHED
220 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
222 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
225 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
228 /* Default task group.
229 * Every task in system belong to this group at bootup.
231 struct task_group init_task_group
= {
232 #ifdef CONFIG_FAIR_GROUP_SCHED
233 .se
= init_sched_entity_p
,
234 .cfs_rq
= init_cfs_rq_p
,
237 #ifdef CONFIG_RT_GROUP_SCHED
238 .rt_se
= init_sched_rt_entity_p
,
239 .rt_rq
= init_rt_rq_p
,
243 /* return group to which a task belongs */
244 static inline struct task_group
*task_group(struct task_struct
*p
)
246 struct task_group
*tg
;
248 #ifdef CONFIG_USER_SCHED
250 #elif defined(CONFIG_CGROUP_SCHED)
251 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
252 struct task_group
, css
);
254 tg
= &init_task_group
;
259 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
260 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
)
262 #ifdef CONFIG_FAIR_GROUP_SCHED
263 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
264 p
->se
.parent
= task_group(p
)->se
[cpu
];
267 #ifdef CONFIG_RT_GROUP_SCHED
268 p
->rt
.rt_rq
= task_group(p
)->rt_rq
[cpu
];
269 p
->rt
.parent
= task_group(p
)->rt_se
[cpu
];
273 static inline void lock_doms_cur(void)
275 mutex_lock(&doms_cur_mutex
);
278 static inline void unlock_doms_cur(void)
280 mutex_unlock(&doms_cur_mutex
);
285 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
) { }
286 static inline void lock_doms_cur(void) { }
287 static inline void unlock_doms_cur(void) { }
289 #endif /* CONFIG_GROUP_SCHED */
291 /* CFS-related fields in a runqueue */
293 struct load_weight load
;
294 unsigned long nr_running
;
299 struct rb_root tasks_timeline
;
300 struct rb_node
*rb_leftmost
;
301 struct rb_node
*rb_load_balance_curr
;
302 /* 'curr' points to currently running entity on this cfs_rq.
303 * It is set to NULL otherwise (i.e when none are currently running).
305 struct sched_entity
*curr
, *next
;
307 unsigned long nr_spread_over
;
309 #ifdef CONFIG_FAIR_GROUP_SCHED
310 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
313 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
314 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
315 * (like users, containers etc.)
317 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
318 * list is used during load balance.
320 struct list_head leaf_cfs_rq_list
;
321 struct task_group
*tg
; /* group that "owns" this runqueue */
325 /* Real-Time classes' related field in a runqueue: */
327 struct rt_prio_array active
;
328 unsigned long rt_nr_running
;
329 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
330 int highest_prio
; /* highest queued rt task prio */
333 unsigned long rt_nr_migratory
;
339 #ifdef CONFIG_RT_GROUP_SCHED
340 unsigned long rt_nr_boosted
;
343 struct list_head leaf_rt_rq_list
;
344 struct task_group
*tg
;
345 struct sched_rt_entity
*rt_se
;
352 * We add the notion of a root-domain which will be used to define per-domain
353 * variables. Each exclusive cpuset essentially defines an island domain by
354 * fully partitioning the member cpus from any other cpuset. Whenever a new
355 * exclusive cpuset is created, we also create and attach a new root-domain
365 * The "RT overload" flag: it gets set if a CPU has more than
366 * one runnable RT task.
373 * By default the system creates a single root-domain with all cpus as
374 * members (mimicking the global state we have today).
376 static struct root_domain def_root_domain
;
381 * This is the main, per-CPU runqueue data structure.
383 * Locking rule: those places that want to lock multiple runqueues
384 * (such as the load balancing or the thread migration code), lock
385 * acquire operations must be ordered by ascending &runqueue.
392 * nr_running and cpu_load should be in the same cacheline because
393 * remote CPUs use both these fields when doing load calculation.
395 unsigned long nr_running
;
396 #define CPU_LOAD_IDX_MAX 5
397 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
398 unsigned char idle_at_tick
;
400 unsigned char in_nohz_recently
;
402 /* capture load from *all* tasks on this cpu: */
403 struct load_weight load
;
404 unsigned long nr_load_updates
;
409 u64 rt_period_expire
;
412 #ifdef CONFIG_FAIR_GROUP_SCHED
413 /* list of leaf cfs_rq on this cpu: */
414 struct list_head leaf_cfs_rq_list
;
416 #ifdef CONFIG_RT_GROUP_SCHED
417 struct list_head leaf_rt_rq_list
;
421 * This is part of a global counter where only the total sum
422 * over all CPUs matters. A task can increase this counter on
423 * one CPU and if it got migrated afterwards it may decrease
424 * it on another CPU. Always updated under the runqueue lock:
426 unsigned long nr_uninterruptible
;
428 struct task_struct
*curr
, *idle
;
429 unsigned long next_balance
;
430 struct mm_struct
*prev_mm
;
432 u64 clock
, prev_clock_raw
;
435 unsigned int clock_warps
, clock_overflows
, clock_underflows
;
437 unsigned int clock_deep_idle_events
;
443 struct root_domain
*rd
;
444 struct sched_domain
*sd
;
446 /* For active balancing */
449 /* cpu of this runqueue: */
452 struct task_struct
*migration_thread
;
453 struct list_head migration_queue
;
456 #ifdef CONFIG_SCHED_HRTICK
457 unsigned long hrtick_flags
;
458 ktime_t hrtick_expire
;
459 struct hrtimer hrtick_timer
;
462 #ifdef CONFIG_SCHEDSTATS
464 struct sched_info rq_sched_info
;
466 /* sys_sched_yield() stats */
467 unsigned int yld_exp_empty
;
468 unsigned int yld_act_empty
;
469 unsigned int yld_both_empty
;
470 unsigned int yld_count
;
472 /* schedule() stats */
473 unsigned int sched_switch
;
474 unsigned int sched_count
;
475 unsigned int sched_goidle
;
477 /* try_to_wake_up() stats */
478 unsigned int ttwu_count
;
479 unsigned int ttwu_local
;
482 unsigned int bkl_count
;
484 struct lock_class_key rq_lock_key
;
487 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
489 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
)
491 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
);
494 static inline int cpu_of(struct rq
*rq
)
504 * Update the per-runqueue clock, as finegrained as the platform can give
505 * us, but without assuming monotonicity, etc.:
507 static void __update_rq_clock(struct rq
*rq
)
509 u64 prev_raw
= rq
->prev_clock_raw
;
510 u64 now
= sched_clock();
511 s64 delta
= now
- prev_raw
;
512 u64 clock
= rq
->clock
;
514 #ifdef CONFIG_SCHED_DEBUG
515 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
518 * Protect against sched_clock() occasionally going backwards:
520 if (unlikely(delta
< 0)) {
525 * Catch too large forward jumps too:
527 if (unlikely(clock
+ delta
> rq
->tick_timestamp
+ TICK_NSEC
)) {
528 if (clock
< rq
->tick_timestamp
+ TICK_NSEC
)
529 clock
= rq
->tick_timestamp
+ TICK_NSEC
;
532 rq
->clock_overflows
++;
534 if (unlikely(delta
> rq
->clock_max_delta
))
535 rq
->clock_max_delta
= delta
;
540 rq
->prev_clock_raw
= now
;
544 static void update_rq_clock(struct rq
*rq
)
546 if (likely(smp_processor_id() == cpu_of(rq
)))
547 __update_rq_clock(rq
);
551 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
552 * See detach_destroy_domains: synchronize_sched for details.
554 * The domain tree of any CPU may only be accessed from within
555 * preempt-disabled sections.
557 #define for_each_domain(cpu, __sd) \
558 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
560 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
561 #define this_rq() (&__get_cpu_var(runqueues))
562 #define task_rq(p) cpu_rq(task_cpu(p))
563 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
565 unsigned long rt_needs_cpu(int cpu
)
567 struct rq
*rq
= cpu_rq(cpu
);
570 if (!rq
->rt_throttled
)
573 if (rq
->clock
> rq
->rt_period_expire
)
576 delta
= rq
->rt_period_expire
- rq
->clock
;
577 do_div(delta
, NSEC_PER_SEC
/ HZ
);
579 return (unsigned long)delta
;
583 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
585 #ifdef CONFIG_SCHED_DEBUG
586 # define const_debug __read_mostly
588 # define const_debug static const
592 * Debugging: various feature bits
595 SCHED_FEAT_NEW_FAIR_SLEEPERS
= 1,
596 SCHED_FEAT_WAKEUP_PREEMPT
= 2,
597 SCHED_FEAT_START_DEBIT
= 4,
598 SCHED_FEAT_HRTICK
= 8,
599 SCHED_FEAT_DOUBLE_TICK
= 16,
602 const_debug
unsigned int sysctl_sched_features
=
603 SCHED_FEAT_NEW_FAIR_SLEEPERS
* 1 |
604 SCHED_FEAT_WAKEUP_PREEMPT
* 1 |
605 SCHED_FEAT_START_DEBIT
* 1 |
606 SCHED_FEAT_HRTICK
* 1 |
607 SCHED_FEAT_DOUBLE_TICK
* 0;
609 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
612 * Number of tasks to iterate in a single balance run.
613 * Limited because this is done with IRQs disabled.
615 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
618 * period over which we measure -rt task cpu usage in us.
621 unsigned int sysctl_sched_rt_period
= 1000000;
623 static __read_mostly
int scheduler_running
;
626 * part of the period that we allow rt tasks to run in us.
629 int sysctl_sched_rt_runtime
= 950000;
632 * single value that denotes runtime == period, ie unlimited time.
634 #define RUNTIME_INF ((u64)~0ULL)
636 static const unsigned long long time_sync_thresh
= 100000;
638 static DEFINE_PER_CPU(unsigned long long, time_offset
);
639 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time
);
642 * Global lock which we take every now and then to synchronize
643 * the CPUs time. This method is not warp-safe, but it's good
644 * enough to synchronize slowly diverging time sources and thus
645 * it's good enough for tracing:
647 static DEFINE_SPINLOCK(time_sync_lock
);
648 static unsigned long long prev_global_time
;
650 static unsigned long long __sync_cpu_clock(cycles_t time
, int cpu
)
654 spin_lock_irqsave(&time_sync_lock
, flags
);
656 if (time
< prev_global_time
) {
657 per_cpu(time_offset
, cpu
) += prev_global_time
- time
;
658 time
= prev_global_time
;
660 prev_global_time
= time
;
663 spin_unlock_irqrestore(&time_sync_lock
, flags
);
668 static unsigned long long __cpu_clock(int cpu
)
670 unsigned long long now
;
675 * Only call sched_clock() if the scheduler has already been
676 * initialized (some code might call cpu_clock() very early):
678 if (unlikely(!scheduler_running
))
681 local_irq_save(flags
);
685 local_irq_restore(flags
);
691 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
692 * clock constructed from sched_clock():
694 unsigned long long cpu_clock(int cpu
)
696 unsigned long long prev_cpu_time
, time
, delta_time
;
698 prev_cpu_time
= per_cpu(prev_cpu_time
, cpu
);
699 time
= __cpu_clock(cpu
) + per_cpu(time_offset
, cpu
);
700 delta_time
= time
-prev_cpu_time
;
702 if (unlikely(delta_time
> time_sync_thresh
))
703 time
= __sync_cpu_clock(time
, cpu
);
707 EXPORT_SYMBOL_GPL(cpu_clock
);
709 #ifndef prepare_arch_switch
710 # define prepare_arch_switch(next) do { } while (0)
712 #ifndef finish_arch_switch
713 # define finish_arch_switch(prev) do { } while (0)
716 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
718 return rq
->curr
== p
;
721 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
722 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
724 return task_current(rq
, p
);
727 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
731 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
733 #ifdef CONFIG_DEBUG_SPINLOCK
734 /* this is a valid case when another task releases the spinlock */
735 rq
->lock
.owner
= current
;
738 * If we are tracking spinlock dependencies then we have to
739 * fix up the runqueue lock - which gets 'carried over' from
742 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
744 spin_unlock_irq(&rq
->lock
);
747 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
748 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
753 return task_current(rq
, p
);
757 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
761 * We can optimise this out completely for !SMP, because the
762 * SMP rebalancing from interrupt is the only thing that cares
767 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
768 spin_unlock_irq(&rq
->lock
);
770 spin_unlock(&rq
->lock
);
774 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
778 * After ->oncpu is cleared, the task can be moved to a different CPU.
779 * We must ensure this doesn't happen until the switch is completely
785 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
789 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
792 * __task_rq_lock - lock the runqueue a given task resides on.
793 * Must be called interrupts disabled.
795 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
799 struct rq
*rq
= task_rq(p
);
800 spin_lock(&rq
->lock
);
801 if (likely(rq
== task_rq(p
)))
803 spin_unlock(&rq
->lock
);
808 * task_rq_lock - lock the runqueue a given task resides on and disable
809 * interrupts. Note the ordering: we can safely lookup the task_rq without
810 * explicitly disabling preemption.
812 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
818 local_irq_save(*flags
);
820 spin_lock(&rq
->lock
);
821 if (likely(rq
== task_rq(p
)))
823 spin_unlock_irqrestore(&rq
->lock
, *flags
);
827 static void __task_rq_unlock(struct rq
*rq
)
830 spin_unlock(&rq
->lock
);
833 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
836 spin_unlock_irqrestore(&rq
->lock
, *flags
);
840 * this_rq_lock - lock this runqueue and disable interrupts.
842 static struct rq
*this_rq_lock(void)
849 spin_lock(&rq
->lock
);
855 * We are going deep-idle (irqs are disabled):
857 void sched_clock_idle_sleep_event(void)
859 struct rq
*rq
= cpu_rq(smp_processor_id());
861 spin_lock(&rq
->lock
);
862 __update_rq_clock(rq
);
863 spin_unlock(&rq
->lock
);
864 rq
->clock_deep_idle_events
++;
866 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event
);
869 * We just idled delta nanoseconds (called with irqs disabled):
871 void sched_clock_idle_wakeup_event(u64 delta_ns
)
873 struct rq
*rq
= cpu_rq(smp_processor_id());
874 u64 now
= sched_clock();
876 rq
->idle_clock
+= delta_ns
;
878 * Override the previous timestamp and ignore all
879 * sched_clock() deltas that occured while we idled,
880 * and use the PM-provided delta_ns to advance the
883 spin_lock(&rq
->lock
);
884 rq
->prev_clock_raw
= now
;
885 rq
->clock
+= delta_ns
;
886 spin_unlock(&rq
->lock
);
887 touch_softlockup_watchdog();
889 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event
);
891 static void __resched_task(struct task_struct
*p
, int tif_bit
);
893 static inline void resched_task(struct task_struct
*p
)
895 __resched_task(p
, TIF_NEED_RESCHED
);
898 #ifdef CONFIG_SCHED_HRTICK
900 * Use HR-timers to deliver accurate preemption points.
902 * Its all a bit involved since we cannot program an hrt while holding the
903 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
906 * When we get rescheduled we reprogram the hrtick_timer outside of the
909 static inline void resched_hrt(struct task_struct
*p
)
911 __resched_task(p
, TIF_HRTICK_RESCHED
);
914 static inline void resched_rq(struct rq
*rq
)
918 spin_lock_irqsave(&rq
->lock
, flags
);
919 resched_task(rq
->curr
);
920 spin_unlock_irqrestore(&rq
->lock
, flags
);
924 HRTICK_SET
, /* re-programm hrtick_timer */
925 HRTICK_RESET
, /* not a new slice */
930 * - enabled by features
931 * - hrtimer is actually high res
933 static inline int hrtick_enabled(struct rq
*rq
)
935 if (!sched_feat(HRTICK
))
937 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
941 * Called to set the hrtick timer state.
943 * called with rq->lock held and irqs disabled
945 static void hrtick_start(struct rq
*rq
, u64 delay
, int reset
)
947 assert_spin_locked(&rq
->lock
);
950 * preempt at: now + delay
953 ktime_add_ns(rq
->hrtick_timer
.base
->get_time(), delay
);
955 * indicate we need to program the timer
957 __set_bit(HRTICK_SET
, &rq
->hrtick_flags
);
959 __set_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
962 * New slices are called from the schedule path and don't need a
966 resched_hrt(rq
->curr
);
969 static void hrtick_clear(struct rq
*rq
)
971 if (hrtimer_active(&rq
->hrtick_timer
))
972 hrtimer_cancel(&rq
->hrtick_timer
);
976 * Update the timer from the possible pending state.
978 static void hrtick_set(struct rq
*rq
)
984 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
986 spin_lock_irqsave(&rq
->lock
, flags
);
987 set
= __test_and_clear_bit(HRTICK_SET
, &rq
->hrtick_flags
);
988 reset
= __test_and_clear_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
989 time
= rq
->hrtick_expire
;
990 clear_thread_flag(TIF_HRTICK_RESCHED
);
991 spin_unlock_irqrestore(&rq
->lock
, flags
);
994 hrtimer_start(&rq
->hrtick_timer
, time
, HRTIMER_MODE_ABS
);
995 if (reset
&& !hrtimer_active(&rq
->hrtick_timer
))
1002 * High-resolution timer tick.
1003 * Runs from hardirq context with interrupts disabled.
1005 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
1007 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
1009 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1011 spin_lock(&rq
->lock
);
1012 __update_rq_clock(rq
);
1013 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
1014 spin_unlock(&rq
->lock
);
1016 return HRTIMER_NORESTART
;
1019 static inline void init_rq_hrtick(struct rq
*rq
)
1021 rq
->hrtick_flags
= 0;
1022 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1023 rq
->hrtick_timer
.function
= hrtick
;
1024 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
1027 void hrtick_resched(void)
1030 unsigned long flags
;
1032 if (!test_thread_flag(TIF_HRTICK_RESCHED
))
1035 local_irq_save(flags
);
1036 rq
= cpu_rq(smp_processor_id());
1038 local_irq_restore(flags
);
1041 static inline void hrtick_clear(struct rq
*rq
)
1045 static inline void hrtick_set(struct rq
*rq
)
1049 static inline void init_rq_hrtick(struct rq
*rq
)
1053 void hrtick_resched(void)
1059 * resched_task - mark a task 'to be rescheduled now'.
1061 * On UP this means the setting of the need_resched flag, on SMP it
1062 * might also involve a cross-CPU call to trigger the scheduler on
1067 #ifndef tsk_is_polling
1068 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1071 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1075 assert_spin_locked(&task_rq(p
)->lock
);
1077 if (unlikely(test_tsk_thread_flag(p
, tif_bit
)))
1080 set_tsk_thread_flag(p
, tif_bit
);
1083 if (cpu
== smp_processor_id())
1086 /* NEED_RESCHED must be visible before we test polling */
1088 if (!tsk_is_polling(p
))
1089 smp_send_reschedule(cpu
);
1092 static void resched_cpu(int cpu
)
1094 struct rq
*rq
= cpu_rq(cpu
);
1095 unsigned long flags
;
1097 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1099 resched_task(cpu_curr(cpu
));
1100 spin_unlock_irqrestore(&rq
->lock
, flags
);
1105 * When add_timer_on() enqueues a timer into the timer wheel of an
1106 * idle CPU then this timer might expire before the next timer event
1107 * which is scheduled to wake up that CPU. In case of a completely
1108 * idle system the next event might even be infinite time into the
1109 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1110 * leaves the inner idle loop so the newly added timer is taken into
1111 * account when the CPU goes back to idle and evaluates the timer
1112 * wheel for the next timer event.
1114 void wake_up_idle_cpu(int cpu
)
1116 struct rq
*rq
= cpu_rq(cpu
);
1118 if (cpu
== smp_processor_id())
1122 * This is safe, as this function is called with the timer
1123 * wheel base lock of (cpu) held. When the CPU is on the way
1124 * to idle and has not yet set rq->curr to idle then it will
1125 * be serialized on the timer wheel base lock and take the new
1126 * timer into account automatically.
1128 if (rq
->curr
!= rq
->idle
)
1132 * We can set TIF_RESCHED on the idle task of the other CPU
1133 * lockless. The worst case is that the other CPU runs the
1134 * idle task through an additional NOOP schedule()
1136 set_tsk_thread_flag(rq
->idle
, TIF_NEED_RESCHED
);
1138 /* NEED_RESCHED must be visible before we test polling */
1140 if (!tsk_is_polling(rq
->idle
))
1141 smp_send_reschedule(cpu
);
1146 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1148 assert_spin_locked(&task_rq(p
)->lock
);
1149 set_tsk_thread_flag(p
, tif_bit
);
1153 #if BITS_PER_LONG == 32
1154 # define WMULT_CONST (~0UL)
1156 # define WMULT_CONST (1UL << 32)
1159 #define WMULT_SHIFT 32
1162 * Shift right and round:
1164 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1166 static unsigned long
1167 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1168 struct load_weight
*lw
)
1172 if (unlikely(!lw
->inv_weight
))
1173 lw
->inv_weight
= (WMULT_CONST
-lw
->weight
/2) / (lw
->weight
+1);
1175 tmp
= (u64
)delta_exec
* weight
;
1177 * Check whether we'd overflow the 64-bit multiplication:
1179 if (unlikely(tmp
> WMULT_CONST
))
1180 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1183 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1185 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1188 static inline unsigned long
1189 calc_delta_fair(unsigned long delta_exec
, struct load_weight
*lw
)
1191 return calc_delta_mine(delta_exec
, NICE_0_LOAD
, lw
);
1194 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1200 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1207 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1208 * of tasks with abnormal "nice" values across CPUs the contribution that
1209 * each task makes to its run queue's load is weighted according to its
1210 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1211 * scaled version of the new time slice allocation that they receive on time
1215 #define WEIGHT_IDLEPRIO 2
1216 #define WMULT_IDLEPRIO (1 << 31)
1219 * Nice levels are multiplicative, with a gentle 10% change for every
1220 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1221 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1222 * that remained on nice 0.
1224 * The "10% effect" is relative and cumulative: from _any_ nice level,
1225 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1226 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1227 * If a task goes up by ~10% and another task goes down by ~10% then
1228 * the relative distance between them is ~25%.)
1230 static const int prio_to_weight
[40] = {
1231 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1232 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1233 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1234 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1235 /* 0 */ 1024, 820, 655, 526, 423,
1236 /* 5 */ 335, 272, 215, 172, 137,
1237 /* 10 */ 110, 87, 70, 56, 45,
1238 /* 15 */ 36, 29, 23, 18, 15,
1242 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1244 * In cases where the weight does not change often, we can use the
1245 * precalculated inverse to speed up arithmetics by turning divisions
1246 * into multiplications:
1248 static const u32 prio_to_wmult
[40] = {
1249 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1250 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1251 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1252 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1253 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1254 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1255 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1256 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1259 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1262 * runqueue iterator, to support SMP load-balancing between different
1263 * scheduling classes, without having to expose their internal data
1264 * structures to the load-balancing proper:
1266 struct rq_iterator
{
1268 struct task_struct
*(*start
)(void *);
1269 struct task_struct
*(*next
)(void *);
1273 static unsigned long
1274 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1275 unsigned long max_load_move
, struct sched_domain
*sd
,
1276 enum cpu_idle_type idle
, int *all_pinned
,
1277 int *this_best_prio
, struct rq_iterator
*iterator
);
1280 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1281 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1282 struct rq_iterator
*iterator
);
1285 #ifdef CONFIG_CGROUP_CPUACCT
1286 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1288 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1292 static unsigned long source_load(int cpu
, int type
);
1293 static unsigned long target_load(int cpu
, int type
);
1294 static unsigned long cpu_avg_load_per_task(int cpu
);
1295 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1296 #endif /* CONFIG_SMP */
1298 #include "sched_stats.h"
1299 #include "sched_idletask.c"
1300 #include "sched_fair.c"
1301 #include "sched_rt.c"
1302 #ifdef CONFIG_SCHED_DEBUG
1303 # include "sched_debug.c"
1306 #define sched_class_highest (&rt_sched_class)
1308 static inline void inc_load(struct rq
*rq
, const struct task_struct
*p
)
1310 update_load_add(&rq
->load
, p
->se
.load
.weight
);
1313 static inline void dec_load(struct rq
*rq
, const struct task_struct
*p
)
1315 update_load_sub(&rq
->load
, p
->se
.load
.weight
);
1318 static void inc_nr_running(struct task_struct
*p
, struct rq
*rq
)
1324 static void dec_nr_running(struct task_struct
*p
, struct rq
*rq
)
1330 static void set_load_weight(struct task_struct
*p
)
1332 if (task_has_rt_policy(p
)) {
1333 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1334 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1339 * SCHED_IDLE tasks get minimal weight:
1341 if (p
->policy
== SCHED_IDLE
) {
1342 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1343 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1347 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1348 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1351 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1353 sched_info_queued(p
);
1354 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1358 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1360 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1365 * __normal_prio - return the priority that is based on the static prio
1367 static inline int __normal_prio(struct task_struct
*p
)
1369 return p
->static_prio
;
1373 * Calculate the expected normal priority: i.e. priority
1374 * without taking RT-inheritance into account. Might be
1375 * boosted by interactivity modifiers. Changes upon fork,
1376 * setprio syscalls, and whenever the interactivity
1377 * estimator recalculates.
1379 static inline int normal_prio(struct task_struct
*p
)
1383 if (task_has_rt_policy(p
))
1384 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1386 prio
= __normal_prio(p
);
1391 * Calculate the current priority, i.e. the priority
1392 * taken into account by the scheduler. This value might
1393 * be boosted by RT tasks, or might be boosted by
1394 * interactivity modifiers. Will be RT if the task got
1395 * RT-boosted. If not then it returns p->normal_prio.
1397 static int effective_prio(struct task_struct
*p
)
1399 p
->normal_prio
= normal_prio(p
);
1401 * If we are RT tasks or we were boosted to RT priority,
1402 * keep the priority unchanged. Otherwise, update priority
1403 * to the normal priority:
1405 if (!rt_prio(p
->prio
))
1406 return p
->normal_prio
;
1411 * activate_task - move a task to the runqueue.
1413 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1415 if (task_contributes_to_load(p
))
1416 rq
->nr_uninterruptible
--;
1418 enqueue_task(rq
, p
, wakeup
);
1419 inc_nr_running(p
, rq
);
1423 * deactivate_task - remove a task from the runqueue.
1425 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1427 if (task_contributes_to_load(p
))
1428 rq
->nr_uninterruptible
++;
1430 dequeue_task(rq
, p
, sleep
);
1431 dec_nr_running(p
, rq
);
1435 * task_curr - is this task currently executing on a CPU?
1436 * @p: the task in question.
1438 inline int task_curr(const struct task_struct
*p
)
1440 return cpu_curr(task_cpu(p
)) == p
;
1443 /* Used instead of source_load when we know the type == 0 */
1444 unsigned long weighted_cpuload(const int cpu
)
1446 return cpu_rq(cpu
)->load
.weight
;
1449 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1451 set_task_rq(p
, cpu
);
1454 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1455 * successfuly executed on another CPU. We must ensure that updates of
1456 * per-task data have been completed by this moment.
1459 task_thread_info(p
)->cpu
= cpu
;
1463 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1464 const struct sched_class
*prev_class
,
1465 int oldprio
, int running
)
1467 if (prev_class
!= p
->sched_class
) {
1468 if (prev_class
->switched_from
)
1469 prev_class
->switched_from(rq
, p
, running
);
1470 p
->sched_class
->switched_to(rq
, p
, running
);
1472 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1478 * Is this task likely cache-hot:
1481 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
1486 * Buddy candidates are cache hot:
1488 if (&p
->se
== cfs_rq_of(&p
->se
)->next
)
1491 if (p
->sched_class
!= &fair_sched_class
)
1494 if (sysctl_sched_migration_cost
== -1)
1496 if (sysctl_sched_migration_cost
== 0)
1499 delta
= now
- p
->se
.exec_start
;
1501 return delta
< (s64
)sysctl_sched_migration_cost
;
1505 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1507 int old_cpu
= task_cpu(p
);
1508 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
1509 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
1510 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
1513 clock_offset
= old_rq
->clock
- new_rq
->clock
;
1515 #ifdef CONFIG_SCHEDSTATS
1516 if (p
->se
.wait_start
)
1517 p
->se
.wait_start
-= clock_offset
;
1518 if (p
->se
.sleep_start
)
1519 p
->se
.sleep_start
-= clock_offset
;
1520 if (p
->se
.block_start
)
1521 p
->se
.block_start
-= clock_offset
;
1522 if (old_cpu
!= new_cpu
) {
1523 schedstat_inc(p
, se
.nr_migrations
);
1524 if (task_hot(p
, old_rq
->clock
, NULL
))
1525 schedstat_inc(p
, se
.nr_forced2_migrations
);
1528 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
1529 new_cfsrq
->min_vruntime
;
1531 __set_task_cpu(p
, new_cpu
);
1534 struct migration_req
{
1535 struct list_head list
;
1537 struct task_struct
*task
;
1540 struct completion done
;
1544 * The task's runqueue lock must be held.
1545 * Returns true if you have to wait for migration thread.
1548 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1550 struct rq
*rq
= task_rq(p
);
1553 * If the task is not on a runqueue (and not running), then
1554 * it is sufficient to simply update the task's cpu field.
1556 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
1557 set_task_cpu(p
, dest_cpu
);
1561 init_completion(&req
->done
);
1563 req
->dest_cpu
= dest_cpu
;
1564 list_add(&req
->list
, &rq
->migration_queue
);
1570 * wait_task_inactive - wait for a thread to unschedule.
1572 * The caller must ensure that the task *will* unschedule sometime soon,
1573 * else this function might spin for a *long* time. This function can't
1574 * be called with interrupts off, or it may introduce deadlock with
1575 * smp_call_function() if an IPI is sent by the same process we are
1576 * waiting to become inactive.
1578 void wait_task_inactive(struct task_struct
*p
)
1580 unsigned long flags
;
1586 * We do the initial early heuristics without holding
1587 * any task-queue locks at all. We'll only try to get
1588 * the runqueue lock when things look like they will
1594 * If the task is actively running on another CPU
1595 * still, just relax and busy-wait without holding
1598 * NOTE! Since we don't hold any locks, it's not
1599 * even sure that "rq" stays as the right runqueue!
1600 * But we don't care, since "task_running()" will
1601 * return false if the runqueue has changed and p
1602 * is actually now running somewhere else!
1604 while (task_running(rq
, p
))
1608 * Ok, time to look more closely! We need the rq
1609 * lock now, to be *sure*. If we're wrong, we'll
1610 * just go back and repeat.
1612 rq
= task_rq_lock(p
, &flags
);
1613 running
= task_running(rq
, p
);
1614 on_rq
= p
->se
.on_rq
;
1615 task_rq_unlock(rq
, &flags
);
1618 * Was it really running after all now that we
1619 * checked with the proper locks actually held?
1621 * Oops. Go back and try again..
1623 if (unlikely(running
)) {
1629 * It's not enough that it's not actively running,
1630 * it must be off the runqueue _entirely_, and not
1633 * So if it wa still runnable (but just not actively
1634 * running right now), it's preempted, and we should
1635 * yield - it could be a while.
1637 if (unlikely(on_rq
)) {
1638 schedule_timeout_uninterruptible(1);
1643 * Ahh, all good. It wasn't running, and it wasn't
1644 * runnable, which means that it will never become
1645 * running in the future either. We're all done!
1652 * kick_process - kick a running thread to enter/exit the kernel
1653 * @p: the to-be-kicked thread
1655 * Cause a process which is running on another CPU to enter
1656 * kernel-mode, without any delay. (to get signals handled.)
1658 * NOTE: this function doesnt have to take the runqueue lock,
1659 * because all it wants to ensure is that the remote task enters
1660 * the kernel. If the IPI races and the task has been migrated
1661 * to another CPU then no harm is done and the purpose has been
1664 void kick_process(struct task_struct
*p
)
1670 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1671 smp_send_reschedule(cpu
);
1676 * Return a low guess at the load of a migration-source cpu weighted
1677 * according to the scheduling class and "nice" value.
1679 * We want to under-estimate the load of migration sources, to
1680 * balance conservatively.
1682 static unsigned long source_load(int cpu
, int type
)
1684 struct rq
*rq
= cpu_rq(cpu
);
1685 unsigned long total
= weighted_cpuload(cpu
);
1690 return min(rq
->cpu_load
[type
-1], total
);
1694 * Return a high guess at the load of a migration-target cpu weighted
1695 * according to the scheduling class and "nice" value.
1697 static unsigned long target_load(int cpu
, int type
)
1699 struct rq
*rq
= cpu_rq(cpu
);
1700 unsigned long total
= weighted_cpuload(cpu
);
1705 return max(rq
->cpu_load
[type
-1], total
);
1709 * Return the average load per task on the cpu's run queue
1711 static unsigned long cpu_avg_load_per_task(int cpu
)
1713 struct rq
*rq
= cpu_rq(cpu
);
1714 unsigned long total
= weighted_cpuload(cpu
);
1715 unsigned long n
= rq
->nr_running
;
1717 return n
? total
/ n
: SCHED_LOAD_SCALE
;
1721 * find_idlest_group finds and returns the least busy CPU group within the
1724 static struct sched_group
*
1725 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1727 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1728 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1729 int load_idx
= sd
->forkexec_idx
;
1730 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1733 unsigned long load
, avg_load
;
1737 /* Skip over this group if it has no CPUs allowed */
1738 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1741 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1743 /* Tally up the load of all CPUs in the group */
1746 for_each_cpu_mask(i
, group
->cpumask
) {
1747 /* Bias balancing toward cpus of our domain */
1749 load
= source_load(i
, load_idx
);
1751 load
= target_load(i
, load_idx
);
1756 /* Adjust by relative CPU power of the group */
1757 avg_load
= sg_div_cpu_power(group
,
1758 avg_load
* SCHED_LOAD_SCALE
);
1761 this_load
= avg_load
;
1763 } else if (avg_load
< min_load
) {
1764 min_load
= avg_load
;
1767 } while (group
= group
->next
, group
!= sd
->groups
);
1769 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1775 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1778 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
1781 unsigned long load
, min_load
= ULONG_MAX
;
1785 /* Traverse only the allowed CPUs */
1786 cpus_and(tmp
, group
->cpumask
, p
->cpus_allowed
);
1788 for_each_cpu_mask(i
, tmp
) {
1789 load
= weighted_cpuload(i
);
1791 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1801 * sched_balance_self: balance the current task (running on cpu) in domains
1802 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1805 * Balance, ie. select the least loaded group.
1807 * Returns the target CPU number, or the same CPU if no balancing is needed.
1809 * preempt must be disabled.
1811 static int sched_balance_self(int cpu
, int flag
)
1813 struct task_struct
*t
= current
;
1814 struct sched_domain
*tmp
, *sd
= NULL
;
1816 for_each_domain(cpu
, tmp
) {
1818 * If power savings logic is enabled for a domain, stop there.
1820 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
1822 if (tmp
->flags
& flag
)
1828 struct sched_group
*group
;
1829 int new_cpu
, weight
;
1831 if (!(sd
->flags
& flag
)) {
1837 group
= find_idlest_group(sd
, t
, cpu
);
1843 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
1844 if (new_cpu
== -1 || new_cpu
== cpu
) {
1845 /* Now try balancing at a lower domain level of cpu */
1850 /* Now try balancing at a lower domain level of new_cpu */
1853 weight
= cpus_weight(span
);
1854 for_each_domain(cpu
, tmp
) {
1855 if (weight
<= cpus_weight(tmp
->span
))
1857 if (tmp
->flags
& flag
)
1860 /* while loop will break here if sd == NULL */
1866 #endif /* CONFIG_SMP */
1869 * try_to_wake_up - wake up a thread
1870 * @p: the to-be-woken-up thread
1871 * @state: the mask of task states that can be woken
1872 * @sync: do a synchronous wakeup?
1874 * Put it on the run-queue if it's not already there. The "current"
1875 * thread is always on the run-queue (except when the actual
1876 * re-schedule is in progress), and as such you're allowed to do
1877 * the simpler "current->state = TASK_RUNNING" to mark yourself
1878 * runnable without the overhead of this.
1880 * returns failure only if the task is already active.
1882 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
1884 int cpu
, orig_cpu
, this_cpu
, success
= 0;
1885 unsigned long flags
;
1890 rq
= task_rq_lock(p
, &flags
);
1891 old_state
= p
->state
;
1892 if (!(old_state
& state
))
1900 this_cpu
= smp_processor_id();
1903 if (unlikely(task_running(rq
, p
)))
1906 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
1907 if (cpu
!= orig_cpu
) {
1908 set_task_cpu(p
, cpu
);
1909 task_rq_unlock(rq
, &flags
);
1910 /* might preempt at this point */
1911 rq
= task_rq_lock(p
, &flags
);
1912 old_state
= p
->state
;
1913 if (!(old_state
& state
))
1918 this_cpu
= smp_processor_id();
1922 #ifdef CONFIG_SCHEDSTATS
1923 schedstat_inc(rq
, ttwu_count
);
1924 if (cpu
== this_cpu
)
1925 schedstat_inc(rq
, ttwu_local
);
1927 struct sched_domain
*sd
;
1928 for_each_domain(this_cpu
, sd
) {
1929 if (cpu_isset(cpu
, sd
->span
)) {
1930 schedstat_inc(sd
, ttwu_wake_remote
);
1938 #endif /* CONFIG_SMP */
1939 schedstat_inc(p
, se
.nr_wakeups
);
1941 schedstat_inc(p
, se
.nr_wakeups_sync
);
1942 if (orig_cpu
!= cpu
)
1943 schedstat_inc(p
, se
.nr_wakeups_migrate
);
1944 if (cpu
== this_cpu
)
1945 schedstat_inc(p
, se
.nr_wakeups_local
);
1947 schedstat_inc(p
, se
.nr_wakeups_remote
);
1948 update_rq_clock(rq
);
1949 activate_task(rq
, p
, 1);
1953 check_preempt_curr(rq
, p
);
1955 p
->state
= TASK_RUNNING
;
1957 if (p
->sched_class
->task_wake_up
)
1958 p
->sched_class
->task_wake_up(rq
, p
);
1961 task_rq_unlock(rq
, &flags
);
1966 int wake_up_process(struct task_struct
*p
)
1968 return try_to_wake_up(p
, TASK_ALL
, 0);
1970 EXPORT_SYMBOL(wake_up_process
);
1972 int wake_up_state(struct task_struct
*p
, unsigned int state
)
1974 return try_to_wake_up(p
, state
, 0);
1978 * Perform scheduler related setup for a newly forked process p.
1979 * p is forked by current.
1981 * __sched_fork() is basic setup used by init_idle() too:
1983 static void __sched_fork(struct task_struct
*p
)
1985 p
->se
.exec_start
= 0;
1986 p
->se
.sum_exec_runtime
= 0;
1987 p
->se
.prev_sum_exec_runtime
= 0;
1988 p
->se
.last_wakeup
= 0;
1989 p
->se
.avg_overlap
= 0;
1991 #ifdef CONFIG_SCHEDSTATS
1992 p
->se
.wait_start
= 0;
1993 p
->se
.sum_sleep_runtime
= 0;
1994 p
->se
.sleep_start
= 0;
1995 p
->se
.block_start
= 0;
1996 p
->se
.sleep_max
= 0;
1997 p
->se
.block_max
= 0;
1999 p
->se
.slice_max
= 0;
2003 INIT_LIST_HEAD(&p
->rt
.run_list
);
2006 #ifdef CONFIG_PREEMPT_NOTIFIERS
2007 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
2011 * We mark the process as running here, but have not actually
2012 * inserted it onto the runqueue yet. This guarantees that
2013 * nobody will actually run it, and a signal or other external
2014 * event cannot wake it up and insert it on the runqueue either.
2016 p
->state
= TASK_RUNNING
;
2020 * fork()/clone()-time setup:
2022 void sched_fork(struct task_struct
*p
, int clone_flags
)
2024 int cpu
= get_cpu();
2029 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
2031 set_task_cpu(p
, cpu
);
2034 * Make sure we do not leak PI boosting priority to the child:
2036 p
->prio
= current
->normal_prio
;
2037 if (!rt_prio(p
->prio
))
2038 p
->sched_class
= &fair_sched_class
;
2040 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2041 if (likely(sched_info_on()))
2042 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
2044 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2047 #ifdef CONFIG_PREEMPT
2048 /* Want to start with kernel preemption disabled. */
2049 task_thread_info(p
)->preempt_count
= 1;
2055 * wake_up_new_task - wake up a newly created task for the first time.
2057 * This function will do some initial scheduler statistics housekeeping
2058 * that must be done for every newly created context, then puts the task
2059 * on the runqueue and wakes it.
2061 void wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
2063 unsigned long flags
;
2066 rq
= task_rq_lock(p
, &flags
);
2067 BUG_ON(p
->state
!= TASK_RUNNING
);
2068 update_rq_clock(rq
);
2070 p
->prio
= effective_prio(p
);
2072 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
2073 activate_task(rq
, p
, 0);
2076 * Let the scheduling class do new task startup
2077 * management (if any):
2079 p
->sched_class
->task_new(rq
, p
);
2080 inc_nr_running(p
, rq
);
2082 check_preempt_curr(rq
, p
);
2084 if (p
->sched_class
->task_wake_up
)
2085 p
->sched_class
->task_wake_up(rq
, p
);
2087 task_rq_unlock(rq
, &flags
);
2090 #ifdef CONFIG_PREEMPT_NOTIFIERS
2093 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2094 * @notifier: notifier struct to register
2096 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2098 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2100 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2103 * preempt_notifier_unregister - no longer interested in preemption notifications
2104 * @notifier: notifier struct to unregister
2106 * This is safe to call from within a preemption notifier.
2108 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2110 hlist_del(¬ifier
->link
);
2112 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2114 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2116 struct preempt_notifier
*notifier
;
2117 struct hlist_node
*node
;
2119 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2120 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2124 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2125 struct task_struct
*next
)
2127 struct preempt_notifier
*notifier
;
2128 struct hlist_node
*node
;
2130 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2131 notifier
->ops
->sched_out(notifier
, next
);
2136 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2141 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2142 struct task_struct
*next
)
2149 * prepare_task_switch - prepare to switch tasks
2150 * @rq: the runqueue preparing to switch
2151 * @prev: the current task that is being switched out
2152 * @next: the task we are going to switch to.
2154 * This is called with the rq lock held and interrupts off. It must
2155 * be paired with a subsequent finish_task_switch after the context
2158 * prepare_task_switch sets up locking and calls architecture specific
2162 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2163 struct task_struct
*next
)
2165 fire_sched_out_preempt_notifiers(prev
, next
);
2166 prepare_lock_switch(rq
, next
);
2167 prepare_arch_switch(next
);
2171 * finish_task_switch - clean up after a task-switch
2172 * @rq: runqueue associated with task-switch
2173 * @prev: the thread we just switched away from.
2175 * finish_task_switch must be called after the context switch, paired
2176 * with a prepare_task_switch call before the context switch.
2177 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2178 * and do any other architecture-specific cleanup actions.
2180 * Note that we may have delayed dropping an mm in context_switch(). If
2181 * so, we finish that here outside of the runqueue lock. (Doing it
2182 * with the lock held can cause deadlocks; see schedule() for
2185 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2186 __releases(rq
->lock
)
2188 struct mm_struct
*mm
= rq
->prev_mm
;
2194 * A task struct has one reference for the use as "current".
2195 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2196 * schedule one last time. The schedule call will never return, and
2197 * the scheduled task must drop that reference.
2198 * The test for TASK_DEAD must occur while the runqueue locks are
2199 * still held, otherwise prev could be scheduled on another cpu, die
2200 * there before we look at prev->state, and then the reference would
2202 * Manfred Spraul <manfred@colorfullife.com>
2204 prev_state
= prev
->state
;
2205 finish_arch_switch(prev
);
2206 finish_lock_switch(rq
, prev
);
2208 if (current
->sched_class
->post_schedule
)
2209 current
->sched_class
->post_schedule(rq
);
2212 fire_sched_in_preempt_notifiers(current
);
2215 if (unlikely(prev_state
== TASK_DEAD
)) {
2217 * Remove function-return probe instances associated with this
2218 * task and put them back on the free list.
2220 kprobe_flush_task(prev
);
2221 put_task_struct(prev
);
2226 * schedule_tail - first thing a freshly forked thread must call.
2227 * @prev: the thread we just switched away from.
2229 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2230 __releases(rq
->lock
)
2232 struct rq
*rq
= this_rq();
2234 finish_task_switch(rq
, prev
);
2235 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2236 /* In this case, finish_task_switch does not reenable preemption */
2239 if (current
->set_child_tid
)
2240 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2244 * context_switch - switch to the new MM and the new
2245 * thread's register state.
2248 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2249 struct task_struct
*next
)
2251 struct mm_struct
*mm
, *oldmm
;
2253 prepare_task_switch(rq
, prev
, next
);
2255 oldmm
= prev
->active_mm
;
2257 * For paravirt, this is coupled with an exit in switch_to to
2258 * combine the page table reload and the switch backend into
2261 arch_enter_lazy_cpu_mode();
2263 if (unlikely(!mm
)) {
2264 next
->active_mm
= oldmm
;
2265 atomic_inc(&oldmm
->mm_count
);
2266 enter_lazy_tlb(oldmm
, next
);
2268 switch_mm(oldmm
, mm
, next
);
2270 if (unlikely(!prev
->mm
)) {
2271 prev
->active_mm
= NULL
;
2272 rq
->prev_mm
= oldmm
;
2275 * Since the runqueue lock will be released by the next
2276 * task (which is an invalid locking op but in the case
2277 * of the scheduler it's an obvious special-case), so we
2278 * do an early lockdep release here:
2280 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2281 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2284 /* Here we just switch the register state and the stack. */
2285 switch_to(prev
, next
, prev
);
2289 * this_rq must be evaluated again because prev may have moved
2290 * CPUs since it called schedule(), thus the 'rq' on its stack
2291 * frame will be invalid.
2293 finish_task_switch(this_rq(), prev
);
2297 * nr_running, nr_uninterruptible and nr_context_switches:
2299 * externally visible scheduler statistics: current number of runnable
2300 * threads, current number of uninterruptible-sleeping threads, total
2301 * number of context switches performed since bootup.
2303 unsigned long nr_running(void)
2305 unsigned long i
, sum
= 0;
2307 for_each_online_cpu(i
)
2308 sum
+= cpu_rq(i
)->nr_running
;
2313 unsigned long nr_uninterruptible(void)
2315 unsigned long i
, sum
= 0;
2317 for_each_possible_cpu(i
)
2318 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2321 * Since we read the counters lockless, it might be slightly
2322 * inaccurate. Do not allow it to go below zero though:
2324 if (unlikely((long)sum
< 0))
2330 unsigned long long nr_context_switches(void)
2333 unsigned long long sum
= 0;
2335 for_each_possible_cpu(i
)
2336 sum
+= cpu_rq(i
)->nr_switches
;
2341 unsigned long nr_iowait(void)
2343 unsigned long i
, sum
= 0;
2345 for_each_possible_cpu(i
)
2346 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2351 unsigned long nr_active(void)
2353 unsigned long i
, running
= 0, uninterruptible
= 0;
2355 for_each_online_cpu(i
) {
2356 running
+= cpu_rq(i
)->nr_running
;
2357 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2360 if (unlikely((long)uninterruptible
< 0))
2361 uninterruptible
= 0;
2363 return running
+ uninterruptible
;
2367 * Update rq->cpu_load[] statistics. This function is usually called every
2368 * scheduler tick (TICK_NSEC).
2370 static void update_cpu_load(struct rq
*this_rq
)
2372 unsigned long this_load
= this_rq
->load
.weight
;
2375 this_rq
->nr_load_updates
++;
2377 /* Update our load: */
2378 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2379 unsigned long old_load
, new_load
;
2381 /* scale is effectively 1 << i now, and >> i divides by scale */
2383 old_load
= this_rq
->cpu_load
[i
];
2384 new_load
= this_load
;
2386 * Round up the averaging division if load is increasing. This
2387 * prevents us from getting stuck on 9 if the load is 10, for
2390 if (new_load
> old_load
)
2391 new_load
+= scale
-1;
2392 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2399 * double_rq_lock - safely lock two runqueues
2401 * Note this does not disable interrupts like task_rq_lock,
2402 * you need to do so manually before calling.
2404 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2405 __acquires(rq1
->lock
)
2406 __acquires(rq2
->lock
)
2408 BUG_ON(!irqs_disabled());
2410 spin_lock(&rq1
->lock
);
2411 __acquire(rq2
->lock
); /* Fake it out ;) */
2414 spin_lock(&rq1
->lock
);
2415 spin_lock(&rq2
->lock
);
2417 spin_lock(&rq2
->lock
);
2418 spin_lock(&rq1
->lock
);
2421 update_rq_clock(rq1
);
2422 update_rq_clock(rq2
);
2426 * double_rq_unlock - safely unlock two runqueues
2428 * Note this does not restore interrupts like task_rq_unlock,
2429 * you need to do so manually after calling.
2431 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2432 __releases(rq1
->lock
)
2433 __releases(rq2
->lock
)
2435 spin_unlock(&rq1
->lock
);
2437 spin_unlock(&rq2
->lock
);
2439 __release(rq2
->lock
);
2443 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2445 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
2446 __releases(this_rq
->lock
)
2447 __acquires(busiest
->lock
)
2448 __acquires(this_rq
->lock
)
2452 if (unlikely(!irqs_disabled())) {
2453 /* printk() doesn't work good under rq->lock */
2454 spin_unlock(&this_rq
->lock
);
2457 if (unlikely(!spin_trylock(&busiest
->lock
))) {
2458 if (busiest
< this_rq
) {
2459 spin_unlock(&this_rq
->lock
);
2460 spin_lock(&busiest
->lock
);
2461 spin_lock(&this_rq
->lock
);
2464 spin_lock(&busiest
->lock
);
2470 * If dest_cpu is allowed for this process, migrate the task to it.
2471 * This is accomplished by forcing the cpu_allowed mask to only
2472 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2473 * the cpu_allowed mask is restored.
2475 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
2477 struct migration_req req
;
2478 unsigned long flags
;
2481 rq
= task_rq_lock(p
, &flags
);
2482 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
2483 || unlikely(cpu_is_offline(dest_cpu
)))
2486 /* force the process onto the specified CPU */
2487 if (migrate_task(p
, dest_cpu
, &req
)) {
2488 /* Need to wait for migration thread (might exit: take ref). */
2489 struct task_struct
*mt
= rq
->migration_thread
;
2491 get_task_struct(mt
);
2492 task_rq_unlock(rq
, &flags
);
2493 wake_up_process(mt
);
2494 put_task_struct(mt
);
2495 wait_for_completion(&req
.done
);
2500 task_rq_unlock(rq
, &flags
);
2504 * sched_exec - execve() is a valuable balancing opportunity, because at
2505 * this point the task has the smallest effective memory and cache footprint.
2507 void sched_exec(void)
2509 int new_cpu
, this_cpu
= get_cpu();
2510 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
2512 if (new_cpu
!= this_cpu
)
2513 sched_migrate_task(current
, new_cpu
);
2517 * pull_task - move a task from a remote runqueue to the local runqueue.
2518 * Both runqueues must be locked.
2520 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
2521 struct rq
*this_rq
, int this_cpu
)
2523 deactivate_task(src_rq
, p
, 0);
2524 set_task_cpu(p
, this_cpu
);
2525 activate_task(this_rq
, p
, 0);
2527 * Note that idle threads have a prio of MAX_PRIO, for this test
2528 * to be always true for them.
2530 check_preempt_curr(this_rq
, p
);
2534 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2537 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2538 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2542 * We do not migrate tasks that are:
2543 * 1) running (obviously), or
2544 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2545 * 3) are cache-hot on their current CPU.
2547 if (!cpu_isset(this_cpu
, p
->cpus_allowed
)) {
2548 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
2553 if (task_running(rq
, p
)) {
2554 schedstat_inc(p
, se
.nr_failed_migrations_running
);
2559 * Aggressive migration if:
2560 * 1) task is cache cold, or
2561 * 2) too many balance attempts have failed.
2564 if (!task_hot(p
, rq
->clock
, sd
) ||
2565 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
2566 #ifdef CONFIG_SCHEDSTATS
2567 if (task_hot(p
, rq
->clock
, sd
)) {
2568 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2569 schedstat_inc(p
, se
.nr_forced_migrations
);
2575 if (task_hot(p
, rq
->clock
, sd
)) {
2576 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
2582 static unsigned long
2583 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2584 unsigned long max_load_move
, struct sched_domain
*sd
,
2585 enum cpu_idle_type idle
, int *all_pinned
,
2586 int *this_best_prio
, struct rq_iterator
*iterator
)
2588 int loops
= 0, pulled
= 0, pinned
= 0, skip_for_load
;
2589 struct task_struct
*p
;
2590 long rem_load_move
= max_load_move
;
2592 if (max_load_move
== 0)
2598 * Start the load-balancing iterator:
2600 p
= iterator
->start(iterator
->arg
);
2602 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
2605 * To help distribute high priority tasks across CPUs we don't
2606 * skip a task if it will be the highest priority task (i.e. smallest
2607 * prio value) on its new queue regardless of its load weight
2609 skip_for_load
= (p
->se
.load
.weight
>> 1) > rem_load_move
+
2610 SCHED_LOAD_SCALE_FUZZ
;
2611 if ((skip_for_load
&& p
->prio
>= *this_best_prio
) ||
2612 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2613 p
= iterator
->next(iterator
->arg
);
2617 pull_task(busiest
, p
, this_rq
, this_cpu
);
2619 rem_load_move
-= p
->se
.load
.weight
;
2622 * We only want to steal up to the prescribed amount of weighted load.
2624 if (rem_load_move
> 0) {
2625 if (p
->prio
< *this_best_prio
)
2626 *this_best_prio
= p
->prio
;
2627 p
= iterator
->next(iterator
->arg
);
2632 * Right now, this is one of only two places pull_task() is called,
2633 * so we can safely collect pull_task() stats here rather than
2634 * inside pull_task().
2636 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2639 *all_pinned
= pinned
;
2641 return max_load_move
- rem_load_move
;
2645 * move_tasks tries to move up to max_load_move weighted load from busiest to
2646 * this_rq, as part of a balancing operation within domain "sd".
2647 * Returns 1 if successful and 0 otherwise.
2649 * Called with both runqueues locked.
2651 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2652 unsigned long max_load_move
,
2653 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2656 const struct sched_class
*class = sched_class_highest
;
2657 unsigned long total_load_moved
= 0;
2658 int this_best_prio
= this_rq
->curr
->prio
;
2662 class->load_balance(this_rq
, this_cpu
, busiest
,
2663 max_load_move
- total_load_moved
,
2664 sd
, idle
, all_pinned
, &this_best_prio
);
2665 class = class->next
;
2666 } while (class && max_load_move
> total_load_moved
);
2668 return total_load_moved
> 0;
2672 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2673 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2674 struct rq_iterator
*iterator
)
2676 struct task_struct
*p
= iterator
->start(iterator
->arg
);
2680 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2681 pull_task(busiest
, p
, this_rq
, this_cpu
);
2683 * Right now, this is only the second place pull_task()
2684 * is called, so we can safely collect pull_task()
2685 * stats here rather than inside pull_task().
2687 schedstat_inc(sd
, lb_gained
[idle
]);
2691 p
= iterator
->next(iterator
->arg
);
2698 * move_one_task tries to move exactly one task from busiest to this_rq, as
2699 * part of active balancing operations within "domain".
2700 * Returns 1 if successful and 0 otherwise.
2702 * Called with both runqueues locked.
2704 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2705 struct sched_domain
*sd
, enum cpu_idle_type idle
)
2707 const struct sched_class
*class;
2709 for (class = sched_class_highest
; class; class = class->next
)
2710 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
2717 * find_busiest_group finds and returns the busiest CPU group within the
2718 * domain. It calculates and returns the amount of weighted load which
2719 * should be moved to restore balance via the imbalance parameter.
2721 static struct sched_group
*
2722 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2723 unsigned long *imbalance
, enum cpu_idle_type idle
,
2724 int *sd_idle
, cpumask_t
*cpus
, int *balance
)
2726 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2727 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2728 unsigned long max_pull
;
2729 unsigned long busiest_load_per_task
, busiest_nr_running
;
2730 unsigned long this_load_per_task
, this_nr_running
;
2731 int load_idx
, group_imb
= 0;
2732 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2733 int power_savings_balance
= 1;
2734 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2735 unsigned long min_nr_running
= ULONG_MAX
;
2736 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2739 max_load
= this_load
= total_load
= total_pwr
= 0;
2740 busiest_load_per_task
= busiest_nr_running
= 0;
2741 this_load_per_task
= this_nr_running
= 0;
2742 if (idle
== CPU_NOT_IDLE
)
2743 load_idx
= sd
->busy_idx
;
2744 else if (idle
== CPU_NEWLY_IDLE
)
2745 load_idx
= sd
->newidle_idx
;
2747 load_idx
= sd
->idle_idx
;
2750 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
2753 int __group_imb
= 0;
2754 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
2755 unsigned long sum_nr_running
, sum_weighted_load
;
2757 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2760 balance_cpu
= first_cpu(group
->cpumask
);
2762 /* Tally up the load of all CPUs in the group */
2763 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2765 min_cpu_load
= ~0UL;
2767 for_each_cpu_mask(i
, group
->cpumask
) {
2770 if (!cpu_isset(i
, *cpus
))
2775 if (*sd_idle
&& rq
->nr_running
)
2778 /* Bias balancing toward cpus of our domain */
2780 if (idle_cpu(i
) && !first_idle_cpu
) {
2785 load
= target_load(i
, load_idx
);
2787 load
= source_load(i
, load_idx
);
2788 if (load
> max_cpu_load
)
2789 max_cpu_load
= load
;
2790 if (min_cpu_load
> load
)
2791 min_cpu_load
= load
;
2795 sum_nr_running
+= rq
->nr_running
;
2796 sum_weighted_load
+= weighted_cpuload(i
);
2800 * First idle cpu or the first cpu(busiest) in this sched group
2801 * is eligible for doing load balancing at this and above
2802 * domains. In the newly idle case, we will allow all the cpu's
2803 * to do the newly idle load balance.
2805 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
2806 balance_cpu
!= this_cpu
&& balance
) {
2811 total_load
+= avg_load
;
2812 total_pwr
+= group
->__cpu_power
;
2814 /* Adjust by relative CPU power of the group */
2815 avg_load
= sg_div_cpu_power(group
,
2816 avg_load
* SCHED_LOAD_SCALE
);
2818 if ((max_cpu_load
- min_cpu_load
) > SCHED_LOAD_SCALE
)
2821 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
2824 this_load
= avg_load
;
2826 this_nr_running
= sum_nr_running
;
2827 this_load_per_task
= sum_weighted_load
;
2828 } else if (avg_load
> max_load
&&
2829 (sum_nr_running
> group_capacity
|| __group_imb
)) {
2830 max_load
= avg_load
;
2832 busiest_nr_running
= sum_nr_running
;
2833 busiest_load_per_task
= sum_weighted_load
;
2834 group_imb
= __group_imb
;
2837 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2839 * Busy processors will not participate in power savings
2842 if (idle
== CPU_NOT_IDLE
||
2843 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2847 * If the local group is idle or completely loaded
2848 * no need to do power savings balance at this domain
2850 if (local_group
&& (this_nr_running
>= group_capacity
||
2852 power_savings_balance
= 0;
2855 * If a group is already running at full capacity or idle,
2856 * don't include that group in power savings calculations
2858 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
2863 * Calculate the group which has the least non-idle load.
2864 * This is the group from where we need to pick up the load
2867 if ((sum_nr_running
< min_nr_running
) ||
2868 (sum_nr_running
== min_nr_running
&&
2869 first_cpu(group
->cpumask
) <
2870 first_cpu(group_min
->cpumask
))) {
2872 min_nr_running
= sum_nr_running
;
2873 min_load_per_task
= sum_weighted_load
/
2878 * Calculate the group which is almost near its
2879 * capacity but still has some space to pick up some load
2880 * from other group and save more power
2882 if (sum_nr_running
<= group_capacity
- 1) {
2883 if (sum_nr_running
> leader_nr_running
||
2884 (sum_nr_running
== leader_nr_running
&&
2885 first_cpu(group
->cpumask
) >
2886 first_cpu(group_leader
->cpumask
))) {
2887 group_leader
= group
;
2888 leader_nr_running
= sum_nr_running
;
2893 group
= group
->next
;
2894 } while (group
!= sd
->groups
);
2896 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
2899 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
2901 if (this_load
>= avg_load
||
2902 100*max_load
<= sd
->imbalance_pct
*this_load
)
2905 busiest_load_per_task
/= busiest_nr_running
;
2907 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
2910 * We're trying to get all the cpus to the average_load, so we don't
2911 * want to push ourselves above the average load, nor do we wish to
2912 * reduce the max loaded cpu below the average load, as either of these
2913 * actions would just result in more rebalancing later, and ping-pong
2914 * tasks around. Thus we look for the minimum possible imbalance.
2915 * Negative imbalances (*we* are more loaded than anyone else) will
2916 * be counted as no imbalance for these purposes -- we can't fix that
2917 * by pulling tasks to us. Be careful of negative numbers as they'll
2918 * appear as very large values with unsigned longs.
2920 if (max_load
<= busiest_load_per_task
)
2924 * In the presence of smp nice balancing, certain scenarios can have
2925 * max load less than avg load(as we skip the groups at or below
2926 * its cpu_power, while calculating max_load..)
2928 if (max_load
< avg_load
) {
2930 goto small_imbalance
;
2933 /* Don't want to pull so many tasks that a group would go idle */
2934 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
2936 /* How much load to actually move to equalise the imbalance */
2937 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
2938 (avg_load
- this_load
) * this->__cpu_power
)
2942 * if *imbalance is less than the average load per runnable task
2943 * there is no gaurantee that any tasks will be moved so we'll have
2944 * a think about bumping its value to force at least one task to be
2947 if (*imbalance
< busiest_load_per_task
) {
2948 unsigned long tmp
, pwr_now
, pwr_move
;
2952 pwr_move
= pwr_now
= 0;
2954 if (this_nr_running
) {
2955 this_load_per_task
/= this_nr_running
;
2956 if (busiest_load_per_task
> this_load_per_task
)
2959 this_load_per_task
= SCHED_LOAD_SCALE
;
2961 if (max_load
- this_load
+ SCHED_LOAD_SCALE_FUZZ
>=
2962 busiest_load_per_task
* imbn
) {
2963 *imbalance
= busiest_load_per_task
;
2968 * OK, we don't have enough imbalance to justify moving tasks,
2969 * however we may be able to increase total CPU power used by
2973 pwr_now
+= busiest
->__cpu_power
*
2974 min(busiest_load_per_task
, max_load
);
2975 pwr_now
+= this->__cpu_power
*
2976 min(this_load_per_task
, this_load
);
2977 pwr_now
/= SCHED_LOAD_SCALE
;
2979 /* Amount of load we'd subtract */
2980 tmp
= sg_div_cpu_power(busiest
,
2981 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2983 pwr_move
+= busiest
->__cpu_power
*
2984 min(busiest_load_per_task
, max_load
- tmp
);
2986 /* Amount of load we'd add */
2987 if (max_load
* busiest
->__cpu_power
<
2988 busiest_load_per_task
* SCHED_LOAD_SCALE
)
2989 tmp
= sg_div_cpu_power(this,
2990 max_load
* busiest
->__cpu_power
);
2992 tmp
= sg_div_cpu_power(this,
2993 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2994 pwr_move
+= this->__cpu_power
*
2995 min(this_load_per_task
, this_load
+ tmp
);
2996 pwr_move
/= SCHED_LOAD_SCALE
;
2998 /* Move if we gain throughput */
2999 if (pwr_move
> pwr_now
)
3000 *imbalance
= busiest_load_per_task
;
3006 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3007 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3010 if (this == group_leader
&& group_leader
!= group_min
) {
3011 *imbalance
= min_load_per_task
;
3021 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3024 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
3025 unsigned long imbalance
, cpumask_t
*cpus
)
3027 struct rq
*busiest
= NULL
, *rq
;
3028 unsigned long max_load
= 0;
3031 for_each_cpu_mask(i
, group
->cpumask
) {
3034 if (!cpu_isset(i
, *cpus
))
3038 wl
= weighted_cpuload(i
);
3040 if (rq
->nr_running
== 1 && wl
> imbalance
)
3043 if (wl
> max_load
) {
3053 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3054 * so long as it is large enough.
3056 #define MAX_PINNED_INTERVAL 512
3059 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3060 * tasks if there is an imbalance.
3062 static int load_balance(int this_cpu
, struct rq
*this_rq
,
3063 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3066 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
3067 struct sched_group
*group
;
3068 unsigned long imbalance
;
3070 cpumask_t cpus
= CPU_MASK_ALL
;
3071 unsigned long flags
;
3074 * When power savings policy is enabled for the parent domain, idle
3075 * sibling can pick up load irrespective of busy siblings. In this case,
3076 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3077 * portraying it as CPU_NOT_IDLE.
3079 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3080 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3083 schedstat_inc(sd
, lb_count
[idle
]);
3086 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
3093 schedstat_inc(sd
, lb_nobusyg
[idle
]);
3097 busiest
= find_busiest_queue(group
, idle
, imbalance
, &cpus
);
3099 schedstat_inc(sd
, lb_nobusyq
[idle
]);
3103 BUG_ON(busiest
== this_rq
);
3105 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
3108 if (busiest
->nr_running
> 1) {
3110 * Attempt to move tasks. If find_busiest_group has found
3111 * an imbalance but busiest->nr_running <= 1, the group is
3112 * still unbalanced. ld_moved simply stays zero, so it is
3113 * correctly treated as an imbalance.
3115 local_irq_save(flags
);
3116 double_rq_lock(this_rq
, busiest
);
3117 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3118 imbalance
, sd
, idle
, &all_pinned
);
3119 double_rq_unlock(this_rq
, busiest
);
3120 local_irq_restore(flags
);
3123 * some other cpu did the load balance for us.
3125 if (ld_moved
&& this_cpu
!= smp_processor_id())
3126 resched_cpu(this_cpu
);
3128 /* All tasks on this runqueue were pinned by CPU affinity */
3129 if (unlikely(all_pinned
)) {
3130 cpu_clear(cpu_of(busiest
), cpus
);
3131 if (!cpus_empty(cpus
))
3138 schedstat_inc(sd
, lb_failed
[idle
]);
3139 sd
->nr_balance_failed
++;
3141 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3143 spin_lock_irqsave(&busiest
->lock
, flags
);
3145 /* don't kick the migration_thread, if the curr
3146 * task on busiest cpu can't be moved to this_cpu
3148 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3149 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3151 goto out_one_pinned
;
3154 if (!busiest
->active_balance
) {
3155 busiest
->active_balance
= 1;
3156 busiest
->push_cpu
= this_cpu
;
3159 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3161 wake_up_process(busiest
->migration_thread
);
3164 * We've kicked active balancing, reset the failure
3167 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3170 sd
->nr_balance_failed
= 0;
3172 if (likely(!active_balance
)) {
3173 /* We were unbalanced, so reset the balancing interval */
3174 sd
->balance_interval
= sd
->min_interval
;
3177 * If we've begun active balancing, start to back off. This
3178 * case may not be covered by the all_pinned logic if there
3179 * is only 1 task on the busy runqueue (because we don't call
3182 if (sd
->balance_interval
< sd
->max_interval
)
3183 sd
->balance_interval
*= 2;
3186 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3187 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3192 schedstat_inc(sd
, lb_balanced
[idle
]);
3194 sd
->nr_balance_failed
= 0;
3197 /* tune up the balancing interval */
3198 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3199 (sd
->balance_interval
< sd
->max_interval
))
3200 sd
->balance_interval
*= 2;
3202 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3203 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3209 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3210 * tasks if there is an imbalance.
3212 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3213 * this_rq is locked.
3216 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
)
3218 struct sched_group
*group
;
3219 struct rq
*busiest
= NULL
;
3220 unsigned long imbalance
;
3224 cpumask_t cpus
= CPU_MASK_ALL
;
3227 * When power savings policy is enabled for the parent domain, idle
3228 * sibling can pick up load irrespective of busy siblings. In this case,
3229 * let the state of idle sibling percolate up as IDLE, instead of
3230 * portraying it as CPU_NOT_IDLE.
3232 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3233 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3236 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3238 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3239 &sd_idle
, &cpus
, NULL
);
3241 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3245 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
,
3248 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3252 BUG_ON(busiest
== this_rq
);
3254 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3257 if (busiest
->nr_running
> 1) {
3258 /* Attempt to move tasks */
3259 double_lock_balance(this_rq
, busiest
);
3260 /* this_rq->clock is already updated */
3261 update_rq_clock(busiest
);
3262 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3263 imbalance
, sd
, CPU_NEWLY_IDLE
,
3265 spin_unlock(&busiest
->lock
);
3267 if (unlikely(all_pinned
)) {
3268 cpu_clear(cpu_of(busiest
), cpus
);
3269 if (!cpus_empty(cpus
))
3275 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3276 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3277 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3280 sd
->nr_balance_failed
= 0;
3285 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3286 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3287 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3289 sd
->nr_balance_failed
= 0;
3295 * idle_balance is called by schedule() if this_cpu is about to become
3296 * idle. Attempts to pull tasks from other CPUs.
3298 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3300 struct sched_domain
*sd
;
3301 int pulled_task
= -1;
3302 unsigned long next_balance
= jiffies
+ HZ
;
3304 for_each_domain(this_cpu
, sd
) {
3305 unsigned long interval
;
3307 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3310 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3311 /* If we've pulled tasks over stop searching: */
3312 pulled_task
= load_balance_newidle(this_cpu
,
3315 interval
= msecs_to_jiffies(sd
->balance_interval
);
3316 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3317 next_balance
= sd
->last_balance
+ interval
;
3321 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3323 * We are going idle. next_balance may be set based on
3324 * a busy processor. So reset next_balance.
3326 this_rq
->next_balance
= next_balance
;
3331 * active_load_balance is run by migration threads. It pushes running tasks
3332 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3333 * running on each physical CPU where possible, and avoids physical /
3334 * logical imbalances.
3336 * Called with busiest_rq locked.
3338 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3340 int target_cpu
= busiest_rq
->push_cpu
;
3341 struct sched_domain
*sd
;
3342 struct rq
*target_rq
;
3344 /* Is there any task to move? */
3345 if (busiest_rq
->nr_running
<= 1)
3348 target_rq
= cpu_rq(target_cpu
);
3351 * This condition is "impossible", if it occurs
3352 * we need to fix it. Originally reported by
3353 * Bjorn Helgaas on a 128-cpu setup.
3355 BUG_ON(busiest_rq
== target_rq
);
3357 /* move a task from busiest_rq to target_rq */
3358 double_lock_balance(busiest_rq
, target_rq
);
3359 update_rq_clock(busiest_rq
);
3360 update_rq_clock(target_rq
);
3362 /* Search for an sd spanning us and the target CPU. */
3363 for_each_domain(target_cpu
, sd
) {
3364 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3365 cpu_isset(busiest_cpu
, sd
->span
))
3370 schedstat_inc(sd
, alb_count
);
3372 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3374 schedstat_inc(sd
, alb_pushed
);
3376 schedstat_inc(sd
, alb_failed
);
3378 spin_unlock(&target_rq
->lock
);
3383 atomic_t load_balancer
;
3385 } nohz ____cacheline_aligned
= {
3386 .load_balancer
= ATOMIC_INIT(-1),
3387 .cpu_mask
= CPU_MASK_NONE
,
3391 * This routine will try to nominate the ilb (idle load balancing)
3392 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3393 * load balancing on behalf of all those cpus. If all the cpus in the system
3394 * go into this tickless mode, then there will be no ilb owner (as there is
3395 * no need for one) and all the cpus will sleep till the next wakeup event
3398 * For the ilb owner, tick is not stopped. And this tick will be used
3399 * for idle load balancing. ilb owner will still be part of
3402 * While stopping the tick, this cpu will become the ilb owner if there
3403 * is no other owner. And will be the owner till that cpu becomes busy
3404 * or if all cpus in the system stop their ticks at which point
3405 * there is no need for ilb owner.
3407 * When the ilb owner becomes busy, it nominates another owner, during the
3408 * next busy scheduler_tick()
3410 int select_nohz_load_balancer(int stop_tick
)
3412 int cpu
= smp_processor_id();
3415 cpu_set(cpu
, nohz
.cpu_mask
);
3416 cpu_rq(cpu
)->in_nohz_recently
= 1;
3419 * If we are going offline and still the leader, give up!
3421 if (cpu_is_offline(cpu
) &&
3422 atomic_read(&nohz
.load_balancer
) == cpu
) {
3423 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3428 /* time for ilb owner also to sleep */
3429 if (cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3430 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3431 atomic_set(&nohz
.load_balancer
, -1);
3435 if (atomic_read(&nohz
.load_balancer
) == -1) {
3436 /* make me the ilb owner */
3437 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3439 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3442 if (!cpu_isset(cpu
, nohz
.cpu_mask
))
3445 cpu_clear(cpu
, nohz
.cpu_mask
);
3447 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3448 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3455 static DEFINE_SPINLOCK(balancing
);
3458 * It checks each scheduling domain to see if it is due to be balanced,
3459 * and initiates a balancing operation if so.
3461 * Balancing parameters are set up in arch_init_sched_domains.
3463 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
3466 struct rq
*rq
= cpu_rq(cpu
);
3467 unsigned long interval
;
3468 struct sched_domain
*sd
;
3469 /* Earliest time when we have to do rebalance again */
3470 unsigned long next_balance
= jiffies
+ 60*HZ
;
3471 int update_next_balance
= 0;
3473 for_each_domain(cpu
, sd
) {
3474 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3477 interval
= sd
->balance_interval
;
3478 if (idle
!= CPU_IDLE
)
3479 interval
*= sd
->busy_factor
;
3481 /* scale ms to jiffies */
3482 interval
= msecs_to_jiffies(interval
);
3483 if (unlikely(!interval
))
3485 if (interval
> HZ
*NR_CPUS
/10)
3486 interval
= HZ
*NR_CPUS
/10;
3489 if (sd
->flags
& SD_SERIALIZE
) {
3490 if (!spin_trylock(&balancing
))
3494 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
3495 if (load_balance(cpu
, rq
, sd
, idle
, &balance
)) {
3497 * We've pulled tasks over so either we're no
3498 * longer idle, or one of our SMT siblings is
3501 idle
= CPU_NOT_IDLE
;
3503 sd
->last_balance
= jiffies
;
3505 if (sd
->flags
& SD_SERIALIZE
)
3506 spin_unlock(&balancing
);
3508 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
3509 next_balance
= sd
->last_balance
+ interval
;
3510 update_next_balance
= 1;
3514 * Stop the load balance at this level. There is another
3515 * CPU in our sched group which is doing load balancing more
3523 * next_balance will be updated only when there is a need.
3524 * When the cpu is attached to null domain for ex, it will not be
3527 if (likely(update_next_balance
))
3528 rq
->next_balance
= next_balance
;
3532 * run_rebalance_domains is triggered when needed from the scheduler tick.
3533 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3534 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3536 static void run_rebalance_domains(struct softirq_action
*h
)
3538 int this_cpu
= smp_processor_id();
3539 struct rq
*this_rq
= cpu_rq(this_cpu
);
3540 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
3541 CPU_IDLE
: CPU_NOT_IDLE
;
3543 rebalance_domains(this_cpu
, idle
);
3547 * If this cpu is the owner for idle load balancing, then do the
3548 * balancing on behalf of the other idle cpus whose ticks are
3551 if (this_rq
->idle_at_tick
&&
3552 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
3553 cpumask_t cpus
= nohz
.cpu_mask
;
3557 cpu_clear(this_cpu
, cpus
);
3558 for_each_cpu_mask(balance_cpu
, cpus
) {
3560 * If this cpu gets work to do, stop the load balancing
3561 * work being done for other cpus. Next load
3562 * balancing owner will pick it up.
3567 rebalance_domains(balance_cpu
, CPU_IDLE
);
3569 rq
= cpu_rq(balance_cpu
);
3570 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
3571 this_rq
->next_balance
= rq
->next_balance
;
3578 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3580 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3581 * idle load balancing owner or decide to stop the periodic load balancing,
3582 * if the whole system is idle.
3584 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
3588 * If we were in the nohz mode recently and busy at the current
3589 * scheduler tick, then check if we need to nominate new idle
3592 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
3593 rq
->in_nohz_recently
= 0;
3595 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
3596 cpu_clear(cpu
, nohz
.cpu_mask
);
3597 atomic_set(&nohz
.load_balancer
, -1);
3600 if (atomic_read(&nohz
.load_balancer
) == -1) {
3602 * simple selection for now: Nominate the
3603 * first cpu in the nohz list to be the next
3606 * TBD: Traverse the sched domains and nominate
3607 * the nearest cpu in the nohz.cpu_mask.
3609 int ilb
= first_cpu(nohz
.cpu_mask
);
3617 * If this cpu is idle and doing idle load balancing for all the
3618 * cpus with ticks stopped, is it time for that to stop?
3620 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
3621 cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3627 * If this cpu is idle and the idle load balancing is done by
3628 * someone else, then no need raise the SCHED_SOFTIRQ
3630 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
3631 cpu_isset(cpu
, nohz
.cpu_mask
))
3634 if (time_after_eq(jiffies
, rq
->next_balance
))
3635 raise_softirq(SCHED_SOFTIRQ
);
3638 #else /* CONFIG_SMP */
3641 * on UP we do not need to balance between CPUs:
3643 static inline void idle_balance(int cpu
, struct rq
*rq
)
3649 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
3651 EXPORT_PER_CPU_SYMBOL(kstat
);
3654 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3655 * that have not yet been banked in case the task is currently running.
3657 unsigned long long task_sched_runtime(struct task_struct
*p
)
3659 unsigned long flags
;
3663 rq
= task_rq_lock(p
, &flags
);
3664 ns
= p
->se
.sum_exec_runtime
;
3665 if (task_current(rq
, p
)) {
3666 update_rq_clock(rq
);
3667 delta_exec
= rq
->clock
- p
->se
.exec_start
;
3668 if ((s64
)delta_exec
> 0)
3671 task_rq_unlock(rq
, &flags
);
3677 * Account user cpu time to a process.
3678 * @p: the process that the cpu time gets accounted to
3679 * @cputime: the cpu time spent in user space since the last update
3681 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
3683 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3686 p
->utime
= cputime_add(p
->utime
, cputime
);
3688 /* Add user time to cpustat. */
3689 tmp
= cputime_to_cputime64(cputime
);
3690 if (TASK_NICE(p
) > 0)
3691 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
3693 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3697 * Account guest cpu time to a process.
3698 * @p: the process that the cpu time gets accounted to
3699 * @cputime: the cpu time spent in virtual machine since the last update
3701 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
3704 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3706 tmp
= cputime_to_cputime64(cputime
);
3708 p
->utime
= cputime_add(p
->utime
, cputime
);
3709 p
->gtime
= cputime_add(p
->gtime
, cputime
);
3711 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3712 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
3716 * Account scaled user cpu time to a process.
3717 * @p: the process that the cpu time gets accounted to
3718 * @cputime: the cpu time spent in user space since the last update
3720 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3722 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
3726 * Account system cpu time to a process.
3727 * @p: the process that the cpu time gets accounted to
3728 * @hardirq_offset: the offset to subtract from hardirq_count()
3729 * @cputime: the cpu time spent in kernel space since the last update
3731 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
3734 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3735 struct rq
*rq
= this_rq();
3738 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0))
3739 return account_guest_time(p
, cputime
);
3741 p
->stime
= cputime_add(p
->stime
, cputime
);
3743 /* Add system time to cpustat. */
3744 tmp
= cputime_to_cputime64(cputime
);
3745 if (hardirq_count() - hardirq_offset
)
3746 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
3747 else if (softirq_count())
3748 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
3749 else if (p
!= rq
->idle
)
3750 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
3751 else if (atomic_read(&rq
->nr_iowait
) > 0)
3752 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3754 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3755 /* Account for system time used */
3756 acct_update_integrals(p
);
3760 * Account scaled system cpu time to a process.
3761 * @p: the process that the cpu time gets accounted to
3762 * @hardirq_offset: the offset to subtract from hardirq_count()
3763 * @cputime: the cpu time spent in kernel space since the last update
3765 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3767 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
3771 * Account for involuntary wait time.
3772 * @p: the process from which the cpu time has been stolen
3773 * @steal: the cpu time spent in involuntary wait
3775 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
3777 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3778 cputime64_t tmp
= cputime_to_cputime64(steal
);
3779 struct rq
*rq
= this_rq();
3781 if (p
== rq
->idle
) {
3782 p
->stime
= cputime_add(p
->stime
, steal
);
3783 if (atomic_read(&rq
->nr_iowait
) > 0)
3784 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3786 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3788 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
3792 * This function gets called by the timer code, with HZ frequency.
3793 * We call it with interrupts disabled.
3795 * It also gets called by the fork code, when changing the parent's
3798 void scheduler_tick(void)
3800 int cpu
= smp_processor_id();
3801 struct rq
*rq
= cpu_rq(cpu
);
3802 struct task_struct
*curr
= rq
->curr
;
3803 u64 next_tick
= rq
->tick_timestamp
+ TICK_NSEC
;
3805 spin_lock(&rq
->lock
);
3806 __update_rq_clock(rq
);
3808 * Let rq->clock advance by at least TICK_NSEC:
3810 if (unlikely(rq
->clock
< next_tick
)) {
3811 rq
->clock
= next_tick
;
3812 rq
->clock_underflows
++;
3814 rq
->tick_timestamp
= rq
->clock
;
3815 update_cpu_load(rq
);
3816 curr
->sched_class
->task_tick(rq
, curr
, 0);
3817 update_sched_rt_period(rq
);
3818 spin_unlock(&rq
->lock
);
3821 rq
->idle_at_tick
= idle_cpu(cpu
);
3822 trigger_load_balance(rq
, cpu
);
3826 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3828 void __kprobes
add_preempt_count(int val
)
3833 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3835 preempt_count() += val
;
3837 * Spinlock count overflowing soon?
3839 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
3842 EXPORT_SYMBOL(add_preempt_count
);
3844 void __kprobes
sub_preempt_count(int val
)
3849 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3852 * Is the spinlock portion underflowing?
3854 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3855 !(preempt_count() & PREEMPT_MASK
)))
3858 preempt_count() -= val
;
3860 EXPORT_SYMBOL(sub_preempt_count
);
3865 * Print scheduling while atomic bug:
3867 static noinline
void __schedule_bug(struct task_struct
*prev
)
3869 struct pt_regs
*regs
= get_irq_regs();
3871 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
3872 prev
->comm
, prev
->pid
, preempt_count());
3874 debug_show_held_locks(prev
);
3875 if (irqs_disabled())
3876 print_irqtrace_events(prev
);
3885 * Various schedule()-time debugging checks and statistics:
3887 static inline void schedule_debug(struct task_struct
*prev
)
3890 * Test if we are atomic. Since do_exit() needs to call into
3891 * schedule() atomically, we ignore that path for now.
3892 * Otherwise, whine if we are scheduling when we should not be.
3894 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev
->exit_state
))
3895 __schedule_bug(prev
);
3897 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3899 schedstat_inc(this_rq(), sched_count
);
3900 #ifdef CONFIG_SCHEDSTATS
3901 if (unlikely(prev
->lock_depth
>= 0)) {
3902 schedstat_inc(this_rq(), bkl_count
);
3903 schedstat_inc(prev
, sched_info
.bkl_count
);
3909 * Pick up the highest-prio task:
3911 static inline struct task_struct
*
3912 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
3914 const struct sched_class
*class;
3915 struct task_struct
*p
;
3918 * Optimization: we know that if all tasks are in
3919 * the fair class we can call that function directly:
3921 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
3922 p
= fair_sched_class
.pick_next_task(rq
);
3927 class = sched_class_highest
;
3929 p
= class->pick_next_task(rq
);
3933 * Will never be NULL as the idle class always
3934 * returns a non-NULL p:
3936 class = class->next
;
3941 * schedule() is the main scheduler function.
3943 asmlinkage
void __sched
schedule(void)
3945 struct task_struct
*prev
, *next
;
3946 unsigned long *switch_count
;
3952 cpu
= smp_processor_id();
3956 switch_count
= &prev
->nivcsw
;
3958 release_kernel_lock(prev
);
3959 need_resched_nonpreemptible
:
3961 schedule_debug(prev
);
3966 * Do the rq-clock update outside the rq lock:
3968 local_irq_disable();
3969 __update_rq_clock(rq
);
3970 spin_lock(&rq
->lock
);
3971 clear_tsk_need_resched(prev
);
3973 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
3974 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
3975 signal_pending(prev
))) {
3976 prev
->state
= TASK_RUNNING
;
3978 deactivate_task(rq
, prev
, 1);
3980 switch_count
= &prev
->nvcsw
;
3984 if (prev
->sched_class
->pre_schedule
)
3985 prev
->sched_class
->pre_schedule(rq
, prev
);
3988 if (unlikely(!rq
->nr_running
))
3989 idle_balance(cpu
, rq
);
3991 prev
->sched_class
->put_prev_task(rq
, prev
);
3992 next
= pick_next_task(rq
, prev
);
3994 sched_info_switch(prev
, next
);
3996 if (likely(prev
!= next
)) {
4001 context_switch(rq
, prev
, next
); /* unlocks the rq */
4003 * the context switch might have flipped the stack from under
4004 * us, hence refresh the local variables.
4006 cpu
= smp_processor_id();
4009 spin_unlock_irq(&rq
->lock
);
4013 if (unlikely(reacquire_kernel_lock(current
) < 0))
4014 goto need_resched_nonpreemptible
;
4016 preempt_enable_no_resched();
4017 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
4020 EXPORT_SYMBOL(schedule
);
4022 #ifdef CONFIG_PREEMPT
4024 * this is the entry point to schedule() from in-kernel preemption
4025 * off of preempt_enable. Kernel preemptions off return from interrupt
4026 * occur there and call schedule directly.
4028 asmlinkage
void __sched
preempt_schedule(void)
4030 struct thread_info
*ti
= current_thread_info();
4031 struct task_struct
*task
= current
;
4032 int saved_lock_depth
;
4035 * If there is a non-zero preempt_count or interrupts are disabled,
4036 * we do not want to preempt the current task. Just return..
4038 if (likely(ti
->preempt_count
|| irqs_disabled()))
4042 add_preempt_count(PREEMPT_ACTIVE
);
4045 * We keep the big kernel semaphore locked, but we
4046 * clear ->lock_depth so that schedule() doesnt
4047 * auto-release the semaphore:
4049 saved_lock_depth
= task
->lock_depth
;
4050 task
->lock_depth
= -1;
4052 task
->lock_depth
= saved_lock_depth
;
4053 sub_preempt_count(PREEMPT_ACTIVE
);
4056 * Check again in case we missed a preemption opportunity
4057 * between schedule and now.
4060 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4062 EXPORT_SYMBOL(preempt_schedule
);
4065 * this is the entry point to schedule() from kernel preemption
4066 * off of irq context.
4067 * Note, that this is called and return with irqs disabled. This will
4068 * protect us against recursive calling from irq.
4070 asmlinkage
void __sched
preempt_schedule_irq(void)
4072 struct thread_info
*ti
= current_thread_info();
4073 struct task_struct
*task
= current
;
4074 int saved_lock_depth
;
4076 /* Catch callers which need to be fixed */
4077 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
4080 add_preempt_count(PREEMPT_ACTIVE
);
4083 * We keep the big kernel semaphore locked, but we
4084 * clear ->lock_depth so that schedule() doesnt
4085 * auto-release the semaphore:
4087 saved_lock_depth
= task
->lock_depth
;
4088 task
->lock_depth
= -1;
4091 local_irq_disable();
4092 task
->lock_depth
= saved_lock_depth
;
4093 sub_preempt_count(PREEMPT_ACTIVE
);
4096 * Check again in case we missed a preemption opportunity
4097 * between schedule and now.
4100 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4103 #endif /* CONFIG_PREEMPT */
4105 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
4108 return try_to_wake_up(curr
->private, mode
, sync
);
4110 EXPORT_SYMBOL(default_wake_function
);
4113 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4114 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4115 * number) then we wake all the non-exclusive tasks and one exclusive task.
4117 * There are circumstances in which we can try to wake a task which has already
4118 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4119 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4121 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
4122 int nr_exclusive
, int sync
, void *key
)
4124 wait_queue_t
*curr
, *next
;
4126 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
4127 unsigned flags
= curr
->flags
;
4129 if (curr
->func(curr
, mode
, sync
, key
) &&
4130 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4136 * __wake_up - wake up threads blocked on a waitqueue.
4138 * @mode: which threads
4139 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4140 * @key: is directly passed to the wakeup function
4142 void __wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4143 int nr_exclusive
, void *key
)
4145 unsigned long flags
;
4147 spin_lock_irqsave(&q
->lock
, flags
);
4148 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4149 spin_unlock_irqrestore(&q
->lock
, flags
);
4151 EXPORT_SYMBOL(__wake_up
);
4154 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4156 void __wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4158 __wake_up_common(q
, mode
, 1, 0, NULL
);
4162 * __wake_up_sync - wake up threads blocked on a waitqueue.
4164 * @mode: which threads
4165 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4167 * The sync wakeup differs that the waker knows that it will schedule
4168 * away soon, so while the target thread will be woken up, it will not
4169 * be migrated to another CPU - ie. the two threads are 'synchronized'
4170 * with each other. This can prevent needless bouncing between CPUs.
4172 * On UP it can prevent extra preemption.
4175 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4177 unsigned long flags
;
4183 if (unlikely(!nr_exclusive
))
4186 spin_lock_irqsave(&q
->lock
, flags
);
4187 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4188 spin_unlock_irqrestore(&q
->lock
, flags
);
4190 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4192 void complete(struct completion
*x
)
4194 unsigned long flags
;
4196 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4198 __wake_up_common(&x
->wait
, TASK_NORMAL
, 1, 0, NULL
);
4199 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4201 EXPORT_SYMBOL(complete
);
4203 void complete_all(struct completion
*x
)
4205 unsigned long flags
;
4207 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4208 x
->done
+= UINT_MAX
/2;
4209 __wake_up_common(&x
->wait
, TASK_NORMAL
, 0, 0, NULL
);
4210 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4212 EXPORT_SYMBOL(complete_all
);
4214 static inline long __sched
4215 do_wait_for_common(struct completion
*x
, long timeout
, int state
)
4218 DECLARE_WAITQUEUE(wait
, current
);
4220 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
4221 __add_wait_queue_tail(&x
->wait
, &wait
);
4223 if ((state
== TASK_INTERRUPTIBLE
&&
4224 signal_pending(current
)) ||
4225 (state
== TASK_KILLABLE
&&
4226 fatal_signal_pending(current
))) {
4227 __remove_wait_queue(&x
->wait
, &wait
);
4228 return -ERESTARTSYS
;
4230 __set_current_state(state
);
4231 spin_unlock_irq(&x
->wait
.lock
);
4232 timeout
= schedule_timeout(timeout
);
4233 spin_lock_irq(&x
->wait
.lock
);
4235 __remove_wait_queue(&x
->wait
, &wait
);
4239 __remove_wait_queue(&x
->wait
, &wait
);
4246 wait_for_common(struct completion
*x
, long timeout
, int state
)
4250 spin_lock_irq(&x
->wait
.lock
);
4251 timeout
= do_wait_for_common(x
, timeout
, state
);
4252 spin_unlock_irq(&x
->wait
.lock
);
4256 void __sched
wait_for_completion(struct completion
*x
)
4258 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4260 EXPORT_SYMBOL(wait_for_completion
);
4262 unsigned long __sched
4263 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4265 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4267 EXPORT_SYMBOL(wait_for_completion_timeout
);
4269 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4271 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4272 if (t
== -ERESTARTSYS
)
4276 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4278 unsigned long __sched
4279 wait_for_completion_interruptible_timeout(struct completion
*x
,
4280 unsigned long timeout
)
4282 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4284 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4286 int __sched
wait_for_completion_killable(struct completion
*x
)
4288 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_KILLABLE
);
4289 if (t
== -ERESTARTSYS
)
4293 EXPORT_SYMBOL(wait_for_completion_killable
);
4296 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4298 unsigned long flags
;
4301 init_waitqueue_entry(&wait
, current
);
4303 __set_current_state(state
);
4305 spin_lock_irqsave(&q
->lock
, flags
);
4306 __add_wait_queue(q
, &wait
);
4307 spin_unlock(&q
->lock
);
4308 timeout
= schedule_timeout(timeout
);
4309 spin_lock_irq(&q
->lock
);
4310 __remove_wait_queue(q
, &wait
);
4311 spin_unlock_irqrestore(&q
->lock
, flags
);
4316 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4318 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4320 EXPORT_SYMBOL(interruptible_sleep_on
);
4323 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4325 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4327 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4329 void __sched
sleep_on(wait_queue_head_t
*q
)
4331 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4333 EXPORT_SYMBOL(sleep_on
);
4335 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4337 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4339 EXPORT_SYMBOL(sleep_on_timeout
);
4341 #ifdef CONFIG_RT_MUTEXES
4344 * rt_mutex_setprio - set the current priority of a task
4346 * @prio: prio value (kernel-internal form)
4348 * This function changes the 'effective' priority of a task. It does
4349 * not touch ->normal_prio like __setscheduler().
4351 * Used by the rt_mutex code to implement priority inheritance logic.
4353 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4355 unsigned long flags
;
4356 int oldprio
, on_rq
, running
;
4358 const struct sched_class
*prev_class
= p
->sched_class
;
4360 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4362 rq
= task_rq_lock(p
, &flags
);
4363 update_rq_clock(rq
);
4366 on_rq
= p
->se
.on_rq
;
4367 running
= task_current(rq
, p
);
4369 dequeue_task(rq
, p
, 0);
4371 p
->sched_class
->put_prev_task(rq
, p
);
4374 p
->sched_class
= &rt_sched_class
;
4376 p
->sched_class
= &fair_sched_class
;
4381 p
->sched_class
->set_curr_task(rq
);
4383 enqueue_task(rq
, p
, 0);
4385 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4387 task_rq_unlock(rq
, &flags
);
4392 void set_user_nice(struct task_struct
*p
, long nice
)
4394 int old_prio
, delta
, on_rq
;
4395 unsigned long flags
;
4398 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
4401 * We have to be careful, if called from sys_setpriority(),
4402 * the task might be in the middle of scheduling on another CPU.
4404 rq
= task_rq_lock(p
, &flags
);
4405 update_rq_clock(rq
);
4407 * The RT priorities are set via sched_setscheduler(), but we still
4408 * allow the 'normal' nice value to be set - but as expected
4409 * it wont have any effect on scheduling until the task is
4410 * SCHED_FIFO/SCHED_RR:
4412 if (task_has_rt_policy(p
)) {
4413 p
->static_prio
= NICE_TO_PRIO(nice
);
4416 on_rq
= p
->se
.on_rq
;
4418 dequeue_task(rq
, p
, 0);
4422 p
->static_prio
= NICE_TO_PRIO(nice
);
4425 p
->prio
= effective_prio(p
);
4426 delta
= p
->prio
- old_prio
;
4429 enqueue_task(rq
, p
, 0);
4432 * If the task increased its priority or is running and
4433 * lowered its priority, then reschedule its CPU:
4435 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
4436 resched_task(rq
->curr
);
4439 task_rq_unlock(rq
, &flags
);
4441 EXPORT_SYMBOL(set_user_nice
);
4444 * can_nice - check if a task can reduce its nice value
4448 int can_nice(const struct task_struct
*p
, const int nice
)
4450 /* convert nice value [19,-20] to rlimit style value [1,40] */
4451 int nice_rlim
= 20 - nice
;
4453 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
4454 capable(CAP_SYS_NICE
));
4457 #ifdef __ARCH_WANT_SYS_NICE
4460 * sys_nice - change the priority of the current process.
4461 * @increment: priority increment
4463 * sys_setpriority is a more generic, but much slower function that
4464 * does similar things.
4466 asmlinkage
long sys_nice(int increment
)
4471 * Setpriority might change our priority at the same moment.
4472 * We don't have to worry. Conceptually one call occurs first
4473 * and we have a single winner.
4475 if (increment
< -40)
4480 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
4486 if (increment
< 0 && !can_nice(current
, nice
))
4489 retval
= security_task_setnice(current
, nice
);
4493 set_user_nice(current
, nice
);
4500 * task_prio - return the priority value of a given task.
4501 * @p: the task in question.
4503 * This is the priority value as seen by users in /proc.
4504 * RT tasks are offset by -200. Normal tasks are centered
4505 * around 0, value goes from -16 to +15.
4507 int task_prio(const struct task_struct
*p
)
4509 return p
->prio
- MAX_RT_PRIO
;
4513 * task_nice - return the nice value of a given task.
4514 * @p: the task in question.
4516 int task_nice(const struct task_struct
*p
)
4518 return TASK_NICE(p
);
4520 EXPORT_SYMBOL(task_nice
);
4523 * idle_cpu - is a given cpu idle currently?
4524 * @cpu: the processor in question.
4526 int idle_cpu(int cpu
)
4528 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
4532 * idle_task - return the idle task for a given cpu.
4533 * @cpu: the processor in question.
4535 struct task_struct
*idle_task(int cpu
)
4537 return cpu_rq(cpu
)->idle
;
4541 * find_process_by_pid - find a process with a matching PID value.
4542 * @pid: the pid in question.
4544 static struct task_struct
*find_process_by_pid(pid_t pid
)
4546 return pid
? find_task_by_vpid(pid
) : current
;
4549 /* Actually do priority change: must hold rq lock. */
4551 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
4553 BUG_ON(p
->se
.on_rq
);
4556 switch (p
->policy
) {
4560 p
->sched_class
= &fair_sched_class
;
4564 p
->sched_class
= &rt_sched_class
;
4568 p
->rt_priority
= prio
;
4569 p
->normal_prio
= normal_prio(p
);
4570 /* we are holding p->pi_lock already */
4571 p
->prio
= rt_mutex_getprio(p
);
4576 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4577 * @p: the task in question.
4578 * @policy: new policy.
4579 * @param: structure containing the new RT priority.
4581 * NOTE that the task may be already dead.
4583 int sched_setscheduler(struct task_struct
*p
, int policy
,
4584 struct sched_param
*param
)
4586 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
4587 unsigned long flags
;
4588 const struct sched_class
*prev_class
= p
->sched_class
;
4591 /* may grab non-irq protected spin_locks */
4592 BUG_ON(in_interrupt());
4594 /* double check policy once rq lock held */
4596 policy
= oldpolicy
= p
->policy
;
4597 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4598 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
4599 policy
!= SCHED_IDLE
)
4602 * Valid priorities for SCHED_FIFO and SCHED_RR are
4603 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4604 * SCHED_BATCH and SCHED_IDLE is 0.
4606 if (param
->sched_priority
< 0 ||
4607 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4608 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4610 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
4614 * Allow unprivileged RT tasks to decrease priority:
4616 if (!capable(CAP_SYS_NICE
)) {
4617 if (rt_policy(policy
)) {
4618 unsigned long rlim_rtprio
;
4620 if (!lock_task_sighand(p
, &flags
))
4622 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
4623 unlock_task_sighand(p
, &flags
);
4625 /* can't set/change the rt policy */
4626 if (policy
!= p
->policy
&& !rlim_rtprio
)
4629 /* can't increase priority */
4630 if (param
->sched_priority
> p
->rt_priority
&&
4631 param
->sched_priority
> rlim_rtprio
)
4635 * Like positive nice levels, dont allow tasks to
4636 * move out of SCHED_IDLE either:
4638 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
4641 /* can't change other user's priorities */
4642 if ((current
->euid
!= p
->euid
) &&
4643 (current
->euid
!= p
->uid
))
4647 #ifdef CONFIG_RT_GROUP_SCHED
4649 * Do not allow realtime tasks into groups that have no runtime
4652 if (rt_policy(policy
) && task_group(p
)->rt_runtime
== 0)
4656 retval
= security_task_setscheduler(p
, policy
, param
);
4660 * make sure no PI-waiters arrive (or leave) while we are
4661 * changing the priority of the task:
4663 spin_lock_irqsave(&p
->pi_lock
, flags
);
4665 * To be able to change p->policy safely, the apropriate
4666 * runqueue lock must be held.
4668 rq
= __task_rq_lock(p
);
4669 /* recheck policy now with rq lock held */
4670 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4671 policy
= oldpolicy
= -1;
4672 __task_rq_unlock(rq
);
4673 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4676 update_rq_clock(rq
);
4677 on_rq
= p
->se
.on_rq
;
4678 running
= task_current(rq
, p
);
4680 deactivate_task(rq
, p
, 0);
4682 p
->sched_class
->put_prev_task(rq
, p
);
4685 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
4688 p
->sched_class
->set_curr_task(rq
);
4690 activate_task(rq
, p
, 0);
4692 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4694 __task_rq_unlock(rq
);
4695 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4697 rt_mutex_adjust_pi(p
);
4701 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4704 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4706 struct sched_param lparam
;
4707 struct task_struct
*p
;
4710 if (!param
|| pid
< 0)
4712 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4717 p
= find_process_by_pid(pid
);
4719 retval
= sched_setscheduler(p
, policy
, &lparam
);
4726 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4727 * @pid: the pid in question.
4728 * @policy: new policy.
4729 * @param: structure containing the new RT priority.
4732 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4734 /* negative values for policy are not valid */
4738 return do_sched_setscheduler(pid
, policy
, param
);
4742 * sys_sched_setparam - set/change the RT priority of a thread
4743 * @pid: the pid in question.
4744 * @param: structure containing the new RT priority.
4746 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4748 return do_sched_setscheduler(pid
, -1, param
);
4752 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4753 * @pid: the pid in question.
4755 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4757 struct task_struct
*p
;
4764 read_lock(&tasklist_lock
);
4765 p
= find_process_by_pid(pid
);
4767 retval
= security_task_getscheduler(p
);
4771 read_unlock(&tasklist_lock
);
4776 * sys_sched_getscheduler - get the RT priority of a thread
4777 * @pid: the pid in question.
4778 * @param: structure containing the RT priority.
4780 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4782 struct sched_param lp
;
4783 struct task_struct
*p
;
4786 if (!param
|| pid
< 0)
4789 read_lock(&tasklist_lock
);
4790 p
= find_process_by_pid(pid
);
4795 retval
= security_task_getscheduler(p
);
4799 lp
.sched_priority
= p
->rt_priority
;
4800 read_unlock(&tasklist_lock
);
4803 * This one might sleep, we cannot do it with a spinlock held ...
4805 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4810 read_unlock(&tasklist_lock
);
4814 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
4816 cpumask_t cpus_allowed
;
4817 struct task_struct
*p
;
4821 read_lock(&tasklist_lock
);
4823 p
= find_process_by_pid(pid
);
4825 read_unlock(&tasklist_lock
);
4831 * It is not safe to call set_cpus_allowed with the
4832 * tasklist_lock held. We will bump the task_struct's
4833 * usage count and then drop tasklist_lock.
4836 read_unlock(&tasklist_lock
);
4839 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
4840 !capable(CAP_SYS_NICE
))
4843 retval
= security_task_setscheduler(p
, 0, NULL
);
4847 cpus_allowed
= cpuset_cpus_allowed(p
);
4848 cpus_and(new_mask
, new_mask
, cpus_allowed
);
4850 retval
= set_cpus_allowed(p
, new_mask
);
4853 cpus_allowed
= cpuset_cpus_allowed(p
);
4854 if (!cpus_subset(new_mask
, cpus_allowed
)) {
4856 * We must have raced with a concurrent cpuset
4857 * update. Just reset the cpus_allowed to the
4858 * cpuset's cpus_allowed
4860 new_mask
= cpus_allowed
;
4870 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4871 cpumask_t
*new_mask
)
4873 if (len
< sizeof(cpumask_t
)) {
4874 memset(new_mask
, 0, sizeof(cpumask_t
));
4875 } else if (len
> sizeof(cpumask_t
)) {
4876 len
= sizeof(cpumask_t
);
4878 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4882 * sys_sched_setaffinity - set the cpu affinity of a process
4883 * @pid: pid of the process
4884 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4885 * @user_mask_ptr: user-space pointer to the new cpu mask
4887 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
4888 unsigned long __user
*user_mask_ptr
)
4893 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
4897 return sched_setaffinity(pid
, new_mask
);
4901 * Represents all cpu's present in the system
4902 * In systems capable of hotplug, this map could dynamically grow
4903 * as new cpu's are detected in the system via any platform specific
4904 * method, such as ACPI for e.g.
4907 cpumask_t cpu_present_map __read_mostly
;
4908 EXPORT_SYMBOL(cpu_present_map
);
4911 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
4912 EXPORT_SYMBOL(cpu_online_map
);
4914 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
4915 EXPORT_SYMBOL(cpu_possible_map
);
4918 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
4920 struct task_struct
*p
;
4924 read_lock(&tasklist_lock
);
4927 p
= find_process_by_pid(pid
);
4931 retval
= security_task_getscheduler(p
);
4935 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
4938 read_unlock(&tasklist_lock
);
4945 * sys_sched_getaffinity - get the cpu affinity of a process
4946 * @pid: pid of the process
4947 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4948 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4950 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
4951 unsigned long __user
*user_mask_ptr
)
4956 if (len
< sizeof(cpumask_t
))
4959 ret
= sched_getaffinity(pid
, &mask
);
4963 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
4966 return sizeof(cpumask_t
);
4970 * sys_sched_yield - yield the current processor to other threads.
4972 * This function yields the current CPU to other tasks. If there are no
4973 * other threads running on this CPU then this function will return.
4975 asmlinkage
long sys_sched_yield(void)
4977 struct rq
*rq
= this_rq_lock();
4979 schedstat_inc(rq
, yld_count
);
4980 current
->sched_class
->yield_task(rq
);
4983 * Since we are going to call schedule() anyway, there's
4984 * no need to preempt or enable interrupts:
4986 __release(rq
->lock
);
4987 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
4988 _raw_spin_unlock(&rq
->lock
);
4989 preempt_enable_no_resched();
4996 static void __cond_resched(void)
4998 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4999 __might_sleep(__FILE__
, __LINE__
);
5002 * The BKS might be reacquired before we have dropped
5003 * PREEMPT_ACTIVE, which could trigger a second
5004 * cond_resched() call.
5007 add_preempt_count(PREEMPT_ACTIVE
);
5009 sub_preempt_count(PREEMPT_ACTIVE
);
5010 } while (need_resched());
5013 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5014 int __sched
_cond_resched(void)
5016 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
5017 system_state
== SYSTEM_RUNNING
) {
5023 EXPORT_SYMBOL(_cond_resched
);
5027 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5028 * call schedule, and on return reacquire the lock.
5030 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5031 * operations here to prevent schedule() from being called twice (once via
5032 * spin_unlock(), once by hand).
5034 int cond_resched_lock(spinlock_t
*lock
)
5036 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
5039 if (spin_needbreak(lock
) || resched
) {
5041 if (resched
&& need_resched())
5050 EXPORT_SYMBOL(cond_resched_lock
);
5052 int __sched
cond_resched_softirq(void)
5054 BUG_ON(!in_softirq());
5056 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
5064 EXPORT_SYMBOL(cond_resched_softirq
);
5067 * yield - yield the current processor to other threads.
5069 * This is a shortcut for kernel-space yielding - it marks the
5070 * thread runnable and calls sys_sched_yield().
5072 void __sched
yield(void)
5074 set_current_state(TASK_RUNNING
);
5077 EXPORT_SYMBOL(yield
);
5080 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5081 * that process accounting knows that this is a task in IO wait state.
5083 * But don't do that if it is a deliberate, throttling IO wait (this task
5084 * has set its backing_dev_info: the queue against which it should throttle)
5086 void __sched
io_schedule(void)
5088 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5090 delayacct_blkio_start();
5091 atomic_inc(&rq
->nr_iowait
);
5093 atomic_dec(&rq
->nr_iowait
);
5094 delayacct_blkio_end();
5096 EXPORT_SYMBOL(io_schedule
);
5098 long __sched
io_schedule_timeout(long timeout
)
5100 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5103 delayacct_blkio_start();
5104 atomic_inc(&rq
->nr_iowait
);
5105 ret
= schedule_timeout(timeout
);
5106 atomic_dec(&rq
->nr_iowait
);
5107 delayacct_blkio_end();
5112 * sys_sched_get_priority_max - return maximum RT priority.
5113 * @policy: scheduling class.
5115 * this syscall returns the maximum rt_priority that can be used
5116 * by a given scheduling class.
5118 asmlinkage
long sys_sched_get_priority_max(int policy
)
5125 ret
= MAX_USER_RT_PRIO
-1;
5137 * sys_sched_get_priority_min - return minimum RT priority.
5138 * @policy: scheduling class.
5140 * this syscall returns the minimum rt_priority that can be used
5141 * by a given scheduling class.
5143 asmlinkage
long sys_sched_get_priority_min(int policy
)
5161 * sys_sched_rr_get_interval - return the default timeslice of a process.
5162 * @pid: pid of the process.
5163 * @interval: userspace pointer to the timeslice value.
5165 * this syscall writes the default timeslice value of a given process
5166 * into the user-space timespec buffer. A value of '0' means infinity.
5169 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5171 struct task_struct
*p
;
5172 unsigned int time_slice
;
5180 read_lock(&tasklist_lock
);
5181 p
= find_process_by_pid(pid
);
5185 retval
= security_task_getscheduler(p
);
5190 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5191 * tasks that are on an otherwise idle runqueue:
5194 if (p
->policy
== SCHED_RR
) {
5195 time_slice
= DEF_TIMESLICE
;
5196 } else if (p
->policy
!= SCHED_FIFO
) {
5197 struct sched_entity
*se
= &p
->se
;
5198 unsigned long flags
;
5201 rq
= task_rq_lock(p
, &flags
);
5202 if (rq
->cfs
.load
.weight
)
5203 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5204 task_rq_unlock(rq
, &flags
);
5206 read_unlock(&tasklist_lock
);
5207 jiffies_to_timespec(time_slice
, &t
);
5208 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5212 read_unlock(&tasklist_lock
);
5216 static const char stat_nam
[] = "RSDTtZX";
5218 void sched_show_task(struct task_struct
*p
)
5220 unsigned long free
= 0;
5223 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5224 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5225 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5226 #if BITS_PER_LONG == 32
5227 if (state
== TASK_RUNNING
)
5228 printk(KERN_CONT
" running ");
5230 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5232 if (state
== TASK_RUNNING
)
5233 printk(KERN_CONT
" running task ");
5235 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5237 #ifdef CONFIG_DEBUG_STACK_USAGE
5239 unsigned long *n
= end_of_stack(p
);
5242 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5245 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5246 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5248 show_stack(p
, NULL
);
5251 void show_state_filter(unsigned long state_filter
)
5253 struct task_struct
*g
, *p
;
5255 #if BITS_PER_LONG == 32
5257 " task PC stack pid father\n");
5260 " task PC stack pid father\n");
5262 read_lock(&tasklist_lock
);
5263 do_each_thread(g
, p
) {
5265 * reset the NMI-timeout, listing all files on a slow
5266 * console might take alot of time:
5268 touch_nmi_watchdog();
5269 if (!state_filter
|| (p
->state
& state_filter
))
5271 } while_each_thread(g
, p
);
5273 touch_all_softlockup_watchdogs();
5275 #ifdef CONFIG_SCHED_DEBUG
5276 sysrq_sched_debug_show();
5278 read_unlock(&tasklist_lock
);
5280 * Only show locks if all tasks are dumped:
5282 if (state_filter
== -1)
5283 debug_show_all_locks();
5286 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5288 idle
->sched_class
= &idle_sched_class
;
5292 * init_idle - set up an idle thread for a given CPU
5293 * @idle: task in question
5294 * @cpu: cpu the idle task belongs to
5296 * NOTE: this function does not set the idle thread's NEED_RESCHED
5297 * flag, to make booting more robust.
5299 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5301 struct rq
*rq
= cpu_rq(cpu
);
5302 unsigned long flags
;
5305 idle
->se
.exec_start
= sched_clock();
5307 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5308 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
5309 __set_task_cpu(idle
, cpu
);
5311 spin_lock_irqsave(&rq
->lock
, flags
);
5312 rq
->curr
= rq
->idle
= idle
;
5313 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5316 spin_unlock_irqrestore(&rq
->lock
, flags
);
5318 /* Set the preempt count _outside_ the spinlocks! */
5319 task_thread_info(idle
)->preempt_count
= 0;
5322 * The idle tasks have their own, simple scheduling class:
5324 idle
->sched_class
= &idle_sched_class
;
5328 * In a system that switches off the HZ timer nohz_cpu_mask
5329 * indicates which cpus entered this state. This is used
5330 * in the rcu update to wait only for active cpus. For system
5331 * which do not switch off the HZ timer nohz_cpu_mask should
5332 * always be CPU_MASK_NONE.
5334 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
5337 * Increase the granularity value when there are more CPUs,
5338 * because with more CPUs the 'effective latency' as visible
5339 * to users decreases. But the relationship is not linear,
5340 * so pick a second-best guess by going with the log2 of the
5343 * This idea comes from the SD scheduler of Con Kolivas:
5345 static inline void sched_init_granularity(void)
5347 unsigned int factor
= 1 + ilog2(num_online_cpus());
5348 const unsigned long limit
= 200000000;
5350 sysctl_sched_min_granularity
*= factor
;
5351 if (sysctl_sched_min_granularity
> limit
)
5352 sysctl_sched_min_granularity
= limit
;
5354 sysctl_sched_latency
*= factor
;
5355 if (sysctl_sched_latency
> limit
)
5356 sysctl_sched_latency
= limit
;
5358 sysctl_sched_wakeup_granularity
*= factor
;
5359 sysctl_sched_batch_wakeup_granularity
*= factor
;
5364 * This is how migration works:
5366 * 1) we queue a struct migration_req structure in the source CPU's
5367 * runqueue and wake up that CPU's migration thread.
5368 * 2) we down() the locked semaphore => thread blocks.
5369 * 3) migration thread wakes up (implicitly it forces the migrated
5370 * thread off the CPU)
5371 * 4) it gets the migration request and checks whether the migrated
5372 * task is still in the wrong runqueue.
5373 * 5) if it's in the wrong runqueue then the migration thread removes
5374 * it and puts it into the right queue.
5375 * 6) migration thread up()s the semaphore.
5376 * 7) we wake up and the migration is done.
5380 * Change a given task's CPU affinity. Migrate the thread to a
5381 * proper CPU and schedule it away if the CPU it's executing on
5382 * is removed from the allowed bitmask.
5384 * NOTE: the caller must have a valid reference to the task, the
5385 * task must not exit() & deallocate itself prematurely. The
5386 * call is not atomic; no spinlocks may be held.
5388 int set_cpus_allowed(struct task_struct
*p
, cpumask_t new_mask
)
5390 struct migration_req req
;
5391 unsigned long flags
;
5395 rq
= task_rq_lock(p
, &flags
);
5396 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
5401 if (p
->sched_class
->set_cpus_allowed
)
5402 p
->sched_class
->set_cpus_allowed(p
, &new_mask
);
5404 p
->cpus_allowed
= new_mask
;
5405 p
->rt
.nr_cpus_allowed
= cpus_weight(new_mask
);
5408 /* Can the task run on the task's current CPU? If so, we're done */
5409 if (cpu_isset(task_cpu(p
), new_mask
))
5412 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
5413 /* Need help from migration thread: drop lock and wait. */
5414 task_rq_unlock(rq
, &flags
);
5415 wake_up_process(rq
->migration_thread
);
5416 wait_for_completion(&req
.done
);
5417 tlb_migrate_finish(p
->mm
);
5421 task_rq_unlock(rq
, &flags
);
5425 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
5428 * Move (not current) task off this cpu, onto dest cpu. We're doing
5429 * this because either it can't run here any more (set_cpus_allowed()
5430 * away from this CPU, or CPU going down), or because we're
5431 * attempting to rebalance this task on exec (sched_exec).
5433 * So we race with normal scheduler movements, but that's OK, as long
5434 * as the task is no longer on this CPU.
5436 * Returns non-zero if task was successfully migrated.
5438 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5440 struct rq
*rq_dest
, *rq_src
;
5443 if (unlikely(cpu_is_offline(dest_cpu
)))
5446 rq_src
= cpu_rq(src_cpu
);
5447 rq_dest
= cpu_rq(dest_cpu
);
5449 double_rq_lock(rq_src
, rq_dest
);
5450 /* Already moved. */
5451 if (task_cpu(p
) != src_cpu
)
5453 /* Affinity changed (again). */
5454 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
5457 on_rq
= p
->se
.on_rq
;
5459 deactivate_task(rq_src
, p
, 0);
5461 set_task_cpu(p
, dest_cpu
);
5463 activate_task(rq_dest
, p
, 0);
5464 check_preempt_curr(rq_dest
, p
);
5468 double_rq_unlock(rq_src
, rq_dest
);
5473 * migration_thread - this is a highprio system thread that performs
5474 * thread migration by bumping thread off CPU then 'pushing' onto
5477 static int migration_thread(void *data
)
5479 int cpu
= (long)data
;
5483 BUG_ON(rq
->migration_thread
!= current
);
5485 set_current_state(TASK_INTERRUPTIBLE
);
5486 while (!kthread_should_stop()) {
5487 struct migration_req
*req
;
5488 struct list_head
*head
;
5490 spin_lock_irq(&rq
->lock
);
5492 if (cpu_is_offline(cpu
)) {
5493 spin_unlock_irq(&rq
->lock
);
5497 if (rq
->active_balance
) {
5498 active_load_balance(rq
, cpu
);
5499 rq
->active_balance
= 0;
5502 head
= &rq
->migration_queue
;
5504 if (list_empty(head
)) {
5505 spin_unlock_irq(&rq
->lock
);
5507 set_current_state(TASK_INTERRUPTIBLE
);
5510 req
= list_entry(head
->next
, struct migration_req
, list
);
5511 list_del_init(head
->next
);
5513 spin_unlock(&rq
->lock
);
5514 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
5517 complete(&req
->done
);
5519 __set_current_state(TASK_RUNNING
);
5523 /* Wait for kthread_stop */
5524 set_current_state(TASK_INTERRUPTIBLE
);
5525 while (!kthread_should_stop()) {
5527 set_current_state(TASK_INTERRUPTIBLE
);
5529 __set_current_state(TASK_RUNNING
);
5533 #ifdef CONFIG_HOTPLUG_CPU
5535 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5539 local_irq_disable();
5540 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
5546 * Figure out where task on dead CPU should go, use force if necessary.
5547 * NOTE: interrupts should be disabled by the caller
5549 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
5551 unsigned long flags
;
5558 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
5559 cpus_and(mask
, mask
, p
->cpus_allowed
);
5560 dest_cpu
= any_online_cpu(mask
);
5562 /* On any allowed CPU? */
5563 if (dest_cpu
== NR_CPUS
)
5564 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5566 /* No more Mr. Nice Guy. */
5567 if (dest_cpu
== NR_CPUS
) {
5568 cpumask_t cpus_allowed
= cpuset_cpus_allowed_locked(p
);
5570 * Try to stay on the same cpuset, where the
5571 * current cpuset may be a subset of all cpus.
5572 * The cpuset_cpus_allowed_locked() variant of
5573 * cpuset_cpus_allowed() will not block. It must be
5574 * called within calls to cpuset_lock/cpuset_unlock.
5576 rq
= task_rq_lock(p
, &flags
);
5577 p
->cpus_allowed
= cpus_allowed
;
5578 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5579 task_rq_unlock(rq
, &flags
);
5582 * Don't tell them about moving exiting tasks or
5583 * kernel threads (both mm NULL), since they never
5586 if (p
->mm
&& printk_ratelimit()) {
5587 printk(KERN_INFO
"process %d (%s) no "
5588 "longer affine to cpu%d\n",
5589 task_pid_nr(p
), p
->comm
, dead_cpu
);
5592 } while (!__migrate_task_irq(p
, dead_cpu
, dest_cpu
));
5596 * While a dead CPU has no uninterruptible tasks queued at this point,
5597 * it might still have a nonzero ->nr_uninterruptible counter, because
5598 * for performance reasons the counter is not stricly tracking tasks to
5599 * their home CPUs. So we just add the counter to another CPU's counter,
5600 * to keep the global sum constant after CPU-down:
5602 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
5604 struct rq
*rq_dest
= cpu_rq(any_online_cpu(CPU_MASK_ALL
));
5605 unsigned long flags
;
5607 local_irq_save(flags
);
5608 double_rq_lock(rq_src
, rq_dest
);
5609 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
5610 rq_src
->nr_uninterruptible
= 0;
5611 double_rq_unlock(rq_src
, rq_dest
);
5612 local_irq_restore(flags
);
5615 /* Run through task list and migrate tasks from the dead cpu. */
5616 static void migrate_live_tasks(int src_cpu
)
5618 struct task_struct
*p
, *t
;
5620 read_lock(&tasklist_lock
);
5622 do_each_thread(t
, p
) {
5626 if (task_cpu(p
) == src_cpu
)
5627 move_task_off_dead_cpu(src_cpu
, p
);
5628 } while_each_thread(t
, p
);
5630 read_unlock(&tasklist_lock
);
5634 * Schedules idle task to be the next runnable task on current CPU.
5635 * It does so by boosting its priority to highest possible.
5636 * Used by CPU offline code.
5638 void sched_idle_next(void)
5640 int this_cpu
= smp_processor_id();
5641 struct rq
*rq
= cpu_rq(this_cpu
);
5642 struct task_struct
*p
= rq
->idle
;
5643 unsigned long flags
;
5645 /* cpu has to be offline */
5646 BUG_ON(cpu_online(this_cpu
));
5649 * Strictly not necessary since rest of the CPUs are stopped by now
5650 * and interrupts disabled on the current cpu.
5652 spin_lock_irqsave(&rq
->lock
, flags
);
5654 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5656 update_rq_clock(rq
);
5657 activate_task(rq
, p
, 0);
5659 spin_unlock_irqrestore(&rq
->lock
, flags
);
5663 * Ensures that the idle task is using init_mm right before its cpu goes
5666 void idle_task_exit(void)
5668 struct mm_struct
*mm
= current
->active_mm
;
5670 BUG_ON(cpu_online(smp_processor_id()));
5673 switch_mm(mm
, &init_mm
, current
);
5677 /* called under rq->lock with disabled interrupts */
5678 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
5680 struct rq
*rq
= cpu_rq(dead_cpu
);
5682 /* Must be exiting, otherwise would be on tasklist. */
5683 BUG_ON(!p
->exit_state
);
5685 /* Cannot have done final schedule yet: would have vanished. */
5686 BUG_ON(p
->state
== TASK_DEAD
);
5691 * Drop lock around migration; if someone else moves it,
5692 * that's OK. No task can be added to this CPU, so iteration is
5695 spin_unlock_irq(&rq
->lock
);
5696 move_task_off_dead_cpu(dead_cpu
, p
);
5697 spin_lock_irq(&rq
->lock
);
5702 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5703 static void migrate_dead_tasks(unsigned int dead_cpu
)
5705 struct rq
*rq
= cpu_rq(dead_cpu
);
5706 struct task_struct
*next
;
5709 if (!rq
->nr_running
)
5711 update_rq_clock(rq
);
5712 next
= pick_next_task(rq
, rq
->curr
);
5715 migrate_dead(dead_cpu
, next
);
5719 #endif /* CONFIG_HOTPLUG_CPU */
5721 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5723 static struct ctl_table sd_ctl_dir
[] = {
5725 .procname
= "sched_domain",
5731 static struct ctl_table sd_ctl_root
[] = {
5733 .ctl_name
= CTL_KERN
,
5734 .procname
= "kernel",
5736 .child
= sd_ctl_dir
,
5741 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
5743 struct ctl_table
*entry
=
5744 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
5749 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
5751 struct ctl_table
*entry
;
5754 * In the intermediate directories, both the child directory and
5755 * procname are dynamically allocated and could fail but the mode
5756 * will always be set. In the lowest directory the names are
5757 * static strings and all have proc handlers.
5759 for (entry
= *tablep
; entry
->mode
; entry
++) {
5761 sd_free_ctl_entry(&entry
->child
);
5762 if (entry
->proc_handler
== NULL
)
5763 kfree(entry
->procname
);
5771 set_table_entry(struct ctl_table
*entry
,
5772 const char *procname
, void *data
, int maxlen
,
5773 mode_t mode
, proc_handler
*proc_handler
)
5775 entry
->procname
= procname
;
5777 entry
->maxlen
= maxlen
;
5779 entry
->proc_handler
= proc_handler
;
5782 static struct ctl_table
*
5783 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
5785 struct ctl_table
*table
= sd_alloc_ctl_entry(12);
5790 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
5791 sizeof(long), 0644, proc_doulongvec_minmax
);
5792 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
5793 sizeof(long), 0644, proc_doulongvec_minmax
);
5794 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
5795 sizeof(int), 0644, proc_dointvec_minmax
);
5796 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
5797 sizeof(int), 0644, proc_dointvec_minmax
);
5798 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
5799 sizeof(int), 0644, proc_dointvec_minmax
);
5800 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
5801 sizeof(int), 0644, proc_dointvec_minmax
);
5802 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
5803 sizeof(int), 0644, proc_dointvec_minmax
);
5804 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
5805 sizeof(int), 0644, proc_dointvec_minmax
);
5806 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
5807 sizeof(int), 0644, proc_dointvec_minmax
);
5808 set_table_entry(&table
[9], "cache_nice_tries",
5809 &sd
->cache_nice_tries
,
5810 sizeof(int), 0644, proc_dointvec_minmax
);
5811 set_table_entry(&table
[10], "flags", &sd
->flags
,
5812 sizeof(int), 0644, proc_dointvec_minmax
);
5813 /* &table[11] is terminator */
5818 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
5820 struct ctl_table
*entry
, *table
;
5821 struct sched_domain
*sd
;
5822 int domain_num
= 0, i
;
5825 for_each_domain(cpu
, sd
)
5827 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
5832 for_each_domain(cpu
, sd
) {
5833 snprintf(buf
, 32, "domain%d", i
);
5834 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5836 entry
->child
= sd_alloc_ctl_domain_table(sd
);
5843 static struct ctl_table_header
*sd_sysctl_header
;
5844 static void register_sched_domain_sysctl(void)
5846 int i
, cpu_num
= num_online_cpus();
5847 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
5850 WARN_ON(sd_ctl_dir
[0].child
);
5851 sd_ctl_dir
[0].child
= entry
;
5856 for_each_online_cpu(i
) {
5857 snprintf(buf
, 32, "cpu%d", i
);
5858 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5860 entry
->child
= sd_alloc_ctl_cpu_table(i
);
5864 WARN_ON(sd_sysctl_header
);
5865 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
5868 /* may be called multiple times per register */
5869 static void unregister_sched_domain_sysctl(void)
5871 if (sd_sysctl_header
)
5872 unregister_sysctl_table(sd_sysctl_header
);
5873 sd_sysctl_header
= NULL
;
5874 if (sd_ctl_dir
[0].child
)
5875 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
5878 static void register_sched_domain_sysctl(void)
5881 static void unregister_sched_domain_sysctl(void)
5887 * migration_call - callback that gets triggered when a CPU is added.
5888 * Here we can start up the necessary migration thread for the new CPU.
5890 static int __cpuinit
5891 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
5893 struct task_struct
*p
;
5894 int cpu
= (long)hcpu
;
5895 unsigned long flags
;
5900 case CPU_UP_PREPARE
:
5901 case CPU_UP_PREPARE_FROZEN
:
5902 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
5905 kthread_bind(p
, cpu
);
5906 /* Must be high prio: stop_machine expects to yield to it. */
5907 rq
= task_rq_lock(p
, &flags
);
5908 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5909 task_rq_unlock(rq
, &flags
);
5910 cpu_rq(cpu
)->migration_thread
= p
;
5914 case CPU_ONLINE_FROZEN
:
5915 /* Strictly unnecessary, as first user will wake it. */
5916 wake_up_process(cpu_rq(cpu
)->migration_thread
);
5918 /* Update our root-domain */
5920 spin_lock_irqsave(&rq
->lock
, flags
);
5922 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5923 cpu_set(cpu
, rq
->rd
->online
);
5925 spin_unlock_irqrestore(&rq
->lock
, flags
);
5928 #ifdef CONFIG_HOTPLUG_CPU
5929 case CPU_UP_CANCELED
:
5930 case CPU_UP_CANCELED_FROZEN
:
5931 if (!cpu_rq(cpu
)->migration_thread
)
5933 /* Unbind it from offline cpu so it can run. Fall thru. */
5934 kthread_bind(cpu_rq(cpu
)->migration_thread
,
5935 any_online_cpu(cpu_online_map
));
5936 kthread_stop(cpu_rq(cpu
)->migration_thread
);
5937 cpu_rq(cpu
)->migration_thread
= NULL
;
5941 case CPU_DEAD_FROZEN
:
5942 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5943 migrate_live_tasks(cpu
);
5945 kthread_stop(rq
->migration_thread
);
5946 rq
->migration_thread
= NULL
;
5947 /* Idle task back to normal (off runqueue, low prio) */
5948 spin_lock_irq(&rq
->lock
);
5949 update_rq_clock(rq
);
5950 deactivate_task(rq
, rq
->idle
, 0);
5951 rq
->idle
->static_prio
= MAX_PRIO
;
5952 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
5953 rq
->idle
->sched_class
= &idle_sched_class
;
5954 migrate_dead_tasks(cpu
);
5955 spin_unlock_irq(&rq
->lock
);
5957 migrate_nr_uninterruptible(rq
);
5958 BUG_ON(rq
->nr_running
!= 0);
5961 * No need to migrate the tasks: it was best-effort if
5962 * they didn't take sched_hotcpu_mutex. Just wake up
5965 spin_lock_irq(&rq
->lock
);
5966 while (!list_empty(&rq
->migration_queue
)) {
5967 struct migration_req
*req
;
5969 req
= list_entry(rq
->migration_queue
.next
,
5970 struct migration_req
, list
);
5971 list_del_init(&req
->list
);
5972 complete(&req
->done
);
5974 spin_unlock_irq(&rq
->lock
);
5978 case CPU_DYING_FROZEN
:
5979 /* Update our root-domain */
5981 spin_lock_irqsave(&rq
->lock
, flags
);
5983 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5984 cpu_clear(cpu
, rq
->rd
->online
);
5986 spin_unlock_irqrestore(&rq
->lock
, flags
);
5993 /* Register at highest priority so that task migration (migrate_all_tasks)
5994 * happens before everything else.
5996 static struct notifier_block __cpuinitdata migration_notifier
= {
5997 .notifier_call
= migration_call
,
6001 void __init
migration_init(void)
6003 void *cpu
= (void *)(long)smp_processor_id();
6006 /* Start one for the boot CPU: */
6007 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
6008 BUG_ON(err
== NOTIFY_BAD
);
6009 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
6010 register_cpu_notifier(&migration_notifier
);
6016 /* Number of possible processor ids */
6017 int nr_cpu_ids __read_mostly
= NR_CPUS
;
6018 EXPORT_SYMBOL(nr_cpu_ids
);
6020 #ifdef CONFIG_SCHED_DEBUG
6022 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
)
6024 struct sched_group
*group
= sd
->groups
;
6025 cpumask_t groupmask
;
6028 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
6029 cpus_clear(groupmask
);
6031 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
6033 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
6034 printk("does not load-balance\n");
6036 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
6041 printk(KERN_CONT
"span %s\n", str
);
6043 if (!cpu_isset(cpu
, sd
->span
)) {
6044 printk(KERN_ERR
"ERROR: domain->span does not contain "
6047 if (!cpu_isset(cpu
, group
->cpumask
)) {
6048 printk(KERN_ERR
"ERROR: domain->groups does not contain"
6052 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
6056 printk(KERN_ERR
"ERROR: group is NULL\n");
6060 if (!group
->__cpu_power
) {
6061 printk(KERN_CONT
"\n");
6062 printk(KERN_ERR
"ERROR: domain->cpu_power not "
6067 if (!cpus_weight(group
->cpumask
)) {
6068 printk(KERN_CONT
"\n");
6069 printk(KERN_ERR
"ERROR: empty group\n");
6073 if (cpus_intersects(groupmask
, group
->cpumask
)) {
6074 printk(KERN_CONT
"\n");
6075 printk(KERN_ERR
"ERROR: repeated CPUs\n");
6079 cpus_or(groupmask
, groupmask
, group
->cpumask
);
6081 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
6082 printk(KERN_CONT
" %s", str
);
6084 group
= group
->next
;
6085 } while (group
!= sd
->groups
);
6086 printk(KERN_CONT
"\n");
6088 if (!cpus_equal(sd
->span
, groupmask
))
6089 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
6091 if (sd
->parent
&& !cpus_subset(groupmask
, sd
->parent
->span
))
6092 printk(KERN_ERR
"ERROR: parent span is not a superset "
6093 "of domain->span\n");
6097 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
6102 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
6106 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
6109 if (sched_domain_debug_one(sd
, cpu
, level
))
6118 # define sched_domain_debug(sd, cpu) do { } while (0)
6121 static int sd_degenerate(struct sched_domain
*sd
)
6123 if (cpus_weight(sd
->span
) == 1)
6126 /* Following flags need at least 2 groups */
6127 if (sd
->flags
& (SD_LOAD_BALANCE
|
6128 SD_BALANCE_NEWIDLE
|
6132 SD_SHARE_PKG_RESOURCES
)) {
6133 if (sd
->groups
!= sd
->groups
->next
)
6137 /* Following flags don't use groups */
6138 if (sd
->flags
& (SD_WAKE_IDLE
|
6147 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6149 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6151 if (sd_degenerate(parent
))
6154 if (!cpus_equal(sd
->span
, parent
->span
))
6157 /* Does parent contain flags not in child? */
6158 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6159 if (cflags
& SD_WAKE_AFFINE
)
6160 pflags
&= ~SD_WAKE_BALANCE
;
6161 /* Flags needing groups don't count if only 1 group in parent */
6162 if (parent
->groups
== parent
->groups
->next
) {
6163 pflags
&= ~(SD_LOAD_BALANCE
|
6164 SD_BALANCE_NEWIDLE
|
6168 SD_SHARE_PKG_RESOURCES
);
6170 if (~cflags
& pflags
)
6176 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6178 unsigned long flags
;
6179 const struct sched_class
*class;
6181 spin_lock_irqsave(&rq
->lock
, flags
);
6184 struct root_domain
*old_rd
= rq
->rd
;
6186 for (class = sched_class_highest
; class; class = class->next
) {
6187 if (class->leave_domain
)
6188 class->leave_domain(rq
);
6191 cpu_clear(rq
->cpu
, old_rd
->span
);
6192 cpu_clear(rq
->cpu
, old_rd
->online
);
6194 if (atomic_dec_and_test(&old_rd
->refcount
))
6198 atomic_inc(&rd
->refcount
);
6201 cpu_set(rq
->cpu
, rd
->span
);
6202 if (cpu_isset(rq
->cpu
, cpu_online_map
))
6203 cpu_set(rq
->cpu
, rd
->online
);
6205 for (class = sched_class_highest
; class; class = class->next
) {
6206 if (class->join_domain
)
6207 class->join_domain(rq
);
6210 spin_unlock_irqrestore(&rq
->lock
, flags
);
6213 static void init_rootdomain(struct root_domain
*rd
)
6215 memset(rd
, 0, sizeof(*rd
));
6217 cpus_clear(rd
->span
);
6218 cpus_clear(rd
->online
);
6221 static void init_defrootdomain(void)
6223 init_rootdomain(&def_root_domain
);
6224 atomic_set(&def_root_domain
.refcount
, 1);
6227 static struct root_domain
*alloc_rootdomain(void)
6229 struct root_domain
*rd
;
6231 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6235 init_rootdomain(rd
);
6241 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6242 * hold the hotplug lock.
6245 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6247 struct rq
*rq
= cpu_rq(cpu
);
6248 struct sched_domain
*tmp
;
6250 /* Remove the sched domains which do not contribute to scheduling. */
6251 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
6252 struct sched_domain
*parent
= tmp
->parent
;
6255 if (sd_parent_degenerate(tmp
, parent
)) {
6256 tmp
->parent
= parent
->parent
;
6258 parent
->parent
->child
= tmp
;
6262 if (sd
&& sd_degenerate(sd
)) {
6268 sched_domain_debug(sd
, cpu
);
6270 rq_attach_root(rq
, rd
);
6271 rcu_assign_pointer(rq
->sd
, sd
);
6274 /* cpus with isolated domains */
6275 static cpumask_t cpu_isolated_map
= CPU_MASK_NONE
;
6277 /* Setup the mask of cpus configured for isolated domains */
6278 static int __init
isolated_cpu_setup(char *str
)
6280 int ints
[NR_CPUS
], i
;
6282 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
6283 cpus_clear(cpu_isolated_map
);
6284 for (i
= 1; i
<= ints
[0]; i
++)
6285 if (ints
[i
] < NR_CPUS
)
6286 cpu_set(ints
[i
], cpu_isolated_map
);
6290 __setup("isolcpus=", isolated_cpu_setup
);
6293 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6294 * to a function which identifies what group(along with sched group) a CPU
6295 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6296 * (due to the fact that we keep track of groups covered with a cpumask_t).
6298 * init_sched_build_groups will build a circular linked list of the groups
6299 * covered by the given span, and will set each group's ->cpumask correctly,
6300 * and ->cpu_power to 0.
6303 init_sched_build_groups(cpumask_t span
, const cpumask_t
*cpu_map
,
6304 int (*group_fn
)(int cpu
, const cpumask_t
*cpu_map
,
6305 struct sched_group
**sg
))
6307 struct sched_group
*first
= NULL
, *last
= NULL
;
6308 cpumask_t covered
= CPU_MASK_NONE
;
6311 for_each_cpu_mask(i
, span
) {
6312 struct sched_group
*sg
;
6313 int group
= group_fn(i
, cpu_map
, &sg
);
6316 if (cpu_isset(i
, covered
))
6319 sg
->cpumask
= CPU_MASK_NONE
;
6320 sg
->__cpu_power
= 0;
6322 for_each_cpu_mask(j
, span
) {
6323 if (group_fn(j
, cpu_map
, NULL
) != group
)
6326 cpu_set(j
, covered
);
6327 cpu_set(j
, sg
->cpumask
);
6338 #define SD_NODES_PER_DOMAIN 16
6343 * find_next_best_node - find the next node to include in a sched_domain
6344 * @node: node whose sched_domain we're building
6345 * @used_nodes: nodes already in the sched_domain
6347 * Find the next node to include in a given scheduling domain. Simply
6348 * finds the closest node not already in the @used_nodes map.
6350 * Should use nodemask_t.
6352 static int find_next_best_node(int node
, unsigned long *used_nodes
)
6354 int i
, n
, val
, min_val
, best_node
= 0;
6358 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6359 /* Start at @node */
6360 n
= (node
+ i
) % MAX_NUMNODES
;
6362 if (!nr_cpus_node(n
))
6365 /* Skip already used nodes */
6366 if (test_bit(n
, used_nodes
))
6369 /* Simple min distance search */
6370 val
= node_distance(node
, n
);
6372 if (val
< min_val
) {
6378 set_bit(best_node
, used_nodes
);
6383 * sched_domain_node_span - get a cpumask for a node's sched_domain
6384 * @node: node whose cpumask we're constructing
6385 * @size: number of nodes to include in this span
6387 * Given a node, construct a good cpumask for its sched_domain to span. It
6388 * should be one that prevents unnecessary balancing, but also spreads tasks
6391 static cpumask_t
sched_domain_node_span(int node
)
6393 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
6394 cpumask_t span
, nodemask
;
6398 bitmap_zero(used_nodes
, MAX_NUMNODES
);
6400 nodemask
= node_to_cpumask(node
);
6401 cpus_or(span
, span
, nodemask
);
6402 set_bit(node
, used_nodes
);
6404 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
6405 int next_node
= find_next_best_node(node
, used_nodes
);
6407 nodemask
= node_to_cpumask(next_node
);
6408 cpus_or(span
, span
, nodemask
);
6415 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
6418 * SMT sched-domains:
6420 #ifdef CONFIG_SCHED_SMT
6421 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6422 static DEFINE_PER_CPU(struct sched_group
, sched_group_cpus
);
6425 cpu_to_cpu_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6428 *sg
= &per_cpu(sched_group_cpus
, cpu
);
6434 * multi-core sched-domains:
6436 #ifdef CONFIG_SCHED_MC
6437 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6438 static DEFINE_PER_CPU(struct sched_group
, sched_group_core
);
6441 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6443 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6446 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6447 cpus_and(mask
, mask
, *cpu_map
);
6448 group
= first_cpu(mask
);
6450 *sg
= &per_cpu(sched_group_core
, group
);
6453 #elif defined(CONFIG_SCHED_MC)
6455 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6458 *sg
= &per_cpu(sched_group_core
, cpu
);
6463 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6464 static DEFINE_PER_CPU(struct sched_group
, sched_group_phys
);
6467 cpu_to_phys_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6470 #ifdef CONFIG_SCHED_MC
6471 cpumask_t mask
= cpu_coregroup_map(cpu
);
6472 cpus_and(mask
, mask
, *cpu_map
);
6473 group
= first_cpu(mask
);
6474 #elif defined(CONFIG_SCHED_SMT)
6475 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6476 cpus_and(mask
, mask
, *cpu_map
);
6477 group
= first_cpu(mask
);
6482 *sg
= &per_cpu(sched_group_phys
, group
);
6488 * The init_sched_build_groups can't handle what we want to do with node
6489 * groups, so roll our own. Now each node has its own list of groups which
6490 * gets dynamically allocated.
6492 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6493 static struct sched_group
**sched_group_nodes_bycpu
[NR_CPUS
];
6495 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6496 static DEFINE_PER_CPU(struct sched_group
, sched_group_allnodes
);
6498 static int cpu_to_allnodes_group(int cpu
, const cpumask_t
*cpu_map
,
6499 struct sched_group
**sg
)
6501 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(cpu
));
6504 cpus_and(nodemask
, nodemask
, *cpu_map
);
6505 group
= first_cpu(nodemask
);
6508 *sg
= &per_cpu(sched_group_allnodes
, group
);
6512 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6514 struct sched_group
*sg
= group_head
;
6520 for_each_cpu_mask(j
, sg
->cpumask
) {
6521 struct sched_domain
*sd
;
6523 sd
= &per_cpu(phys_domains
, j
);
6524 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6526 * Only add "power" once for each
6532 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
6535 } while (sg
!= group_head
);
6540 /* Free memory allocated for various sched_group structures */
6541 static void free_sched_groups(const cpumask_t
*cpu_map
)
6545 for_each_cpu_mask(cpu
, *cpu_map
) {
6546 struct sched_group
**sched_group_nodes
6547 = sched_group_nodes_bycpu
[cpu
];
6549 if (!sched_group_nodes
)
6552 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6553 cpumask_t nodemask
= node_to_cpumask(i
);
6554 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6556 cpus_and(nodemask
, nodemask
, *cpu_map
);
6557 if (cpus_empty(nodemask
))
6567 if (oldsg
!= sched_group_nodes
[i
])
6570 kfree(sched_group_nodes
);
6571 sched_group_nodes_bycpu
[cpu
] = NULL
;
6575 static void free_sched_groups(const cpumask_t
*cpu_map
)
6581 * Initialize sched groups cpu_power.
6583 * cpu_power indicates the capacity of sched group, which is used while
6584 * distributing the load between different sched groups in a sched domain.
6585 * Typically cpu_power for all the groups in a sched domain will be same unless
6586 * there are asymmetries in the topology. If there are asymmetries, group
6587 * having more cpu_power will pickup more load compared to the group having
6590 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6591 * the maximum number of tasks a group can handle in the presence of other idle
6592 * or lightly loaded groups in the same sched domain.
6594 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
6596 struct sched_domain
*child
;
6597 struct sched_group
*group
;
6599 WARN_ON(!sd
|| !sd
->groups
);
6601 if (cpu
!= first_cpu(sd
->groups
->cpumask
))
6606 sd
->groups
->__cpu_power
= 0;
6609 * For perf policy, if the groups in child domain share resources
6610 * (for example cores sharing some portions of the cache hierarchy
6611 * or SMT), then set this domain groups cpu_power such that each group
6612 * can handle only one task, when there are other idle groups in the
6613 * same sched domain.
6615 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
6617 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
6618 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
6623 * add cpu_power of each child group to this groups cpu_power
6625 group
= child
->groups
;
6627 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
6628 group
= group
->next
;
6629 } while (group
!= child
->groups
);
6633 * Build sched domains for a given set of cpus and attach the sched domains
6634 * to the individual cpus
6636 static int build_sched_domains(const cpumask_t
*cpu_map
)
6639 struct root_domain
*rd
;
6641 struct sched_group
**sched_group_nodes
= NULL
;
6642 int sd_allnodes
= 0;
6645 * Allocate the per-node list of sched groups
6647 sched_group_nodes
= kcalloc(MAX_NUMNODES
, sizeof(struct sched_group
*),
6649 if (!sched_group_nodes
) {
6650 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6653 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6656 rd
= alloc_rootdomain();
6658 printk(KERN_WARNING
"Cannot alloc root domain\n");
6663 * Set up domains for cpus specified by the cpu_map.
6665 for_each_cpu_mask(i
, *cpu_map
) {
6666 struct sched_domain
*sd
= NULL
, *p
;
6667 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
6669 cpus_and(nodemask
, nodemask
, *cpu_map
);
6672 if (cpus_weight(*cpu_map
) >
6673 SD_NODES_PER_DOMAIN
*cpus_weight(nodemask
)) {
6674 sd
= &per_cpu(allnodes_domains
, i
);
6675 *sd
= SD_ALLNODES_INIT
;
6676 sd
->span
= *cpu_map
;
6677 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
);
6683 sd
= &per_cpu(node_domains
, i
);
6685 sd
->span
= sched_domain_node_span(cpu_to_node(i
));
6689 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6693 sd
= &per_cpu(phys_domains
, i
);
6695 sd
->span
= nodemask
;
6699 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
);
6701 #ifdef CONFIG_SCHED_MC
6703 sd
= &per_cpu(core_domains
, i
);
6705 sd
->span
= cpu_coregroup_map(i
);
6706 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6709 cpu_to_core_group(i
, cpu_map
, &sd
->groups
);
6712 #ifdef CONFIG_SCHED_SMT
6714 sd
= &per_cpu(cpu_domains
, i
);
6715 *sd
= SD_SIBLING_INIT
;
6716 sd
->span
= per_cpu(cpu_sibling_map
, i
);
6717 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6720 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
);
6724 #ifdef CONFIG_SCHED_SMT
6725 /* Set up CPU (sibling) groups */
6726 for_each_cpu_mask(i
, *cpu_map
) {
6727 cpumask_t this_sibling_map
= per_cpu(cpu_sibling_map
, i
);
6728 cpus_and(this_sibling_map
, this_sibling_map
, *cpu_map
);
6729 if (i
!= first_cpu(this_sibling_map
))
6732 init_sched_build_groups(this_sibling_map
, cpu_map
,
6737 #ifdef CONFIG_SCHED_MC
6738 /* Set up multi-core groups */
6739 for_each_cpu_mask(i
, *cpu_map
) {
6740 cpumask_t this_core_map
= cpu_coregroup_map(i
);
6741 cpus_and(this_core_map
, this_core_map
, *cpu_map
);
6742 if (i
!= first_cpu(this_core_map
))
6744 init_sched_build_groups(this_core_map
, cpu_map
,
6745 &cpu_to_core_group
);
6749 /* Set up physical groups */
6750 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6751 cpumask_t nodemask
= node_to_cpumask(i
);
6753 cpus_and(nodemask
, nodemask
, *cpu_map
);
6754 if (cpus_empty(nodemask
))
6757 init_sched_build_groups(nodemask
, cpu_map
, &cpu_to_phys_group
);
6761 /* Set up node groups */
6763 init_sched_build_groups(*cpu_map
, cpu_map
,
6764 &cpu_to_allnodes_group
);
6766 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6767 /* Set up node groups */
6768 struct sched_group
*sg
, *prev
;
6769 cpumask_t nodemask
= node_to_cpumask(i
);
6770 cpumask_t domainspan
;
6771 cpumask_t covered
= CPU_MASK_NONE
;
6774 cpus_and(nodemask
, nodemask
, *cpu_map
);
6775 if (cpus_empty(nodemask
)) {
6776 sched_group_nodes
[i
] = NULL
;
6780 domainspan
= sched_domain_node_span(i
);
6781 cpus_and(domainspan
, domainspan
, *cpu_map
);
6783 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
6785 printk(KERN_WARNING
"Can not alloc domain group for "
6789 sched_group_nodes
[i
] = sg
;
6790 for_each_cpu_mask(j
, nodemask
) {
6791 struct sched_domain
*sd
;
6793 sd
= &per_cpu(node_domains
, j
);
6796 sg
->__cpu_power
= 0;
6797 sg
->cpumask
= nodemask
;
6799 cpus_or(covered
, covered
, nodemask
);
6802 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
6803 cpumask_t tmp
, notcovered
;
6804 int n
= (i
+ j
) % MAX_NUMNODES
;
6806 cpus_complement(notcovered
, covered
);
6807 cpus_and(tmp
, notcovered
, *cpu_map
);
6808 cpus_and(tmp
, tmp
, domainspan
);
6809 if (cpus_empty(tmp
))
6812 nodemask
= node_to_cpumask(n
);
6813 cpus_and(tmp
, tmp
, nodemask
);
6814 if (cpus_empty(tmp
))
6817 sg
= kmalloc_node(sizeof(struct sched_group
),
6821 "Can not alloc domain group for node %d\n", j
);
6824 sg
->__cpu_power
= 0;
6826 sg
->next
= prev
->next
;
6827 cpus_or(covered
, covered
, tmp
);
6834 /* Calculate CPU power for physical packages and nodes */
6835 #ifdef CONFIG_SCHED_SMT
6836 for_each_cpu_mask(i
, *cpu_map
) {
6837 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
);
6839 init_sched_groups_power(i
, sd
);
6842 #ifdef CONFIG_SCHED_MC
6843 for_each_cpu_mask(i
, *cpu_map
) {
6844 struct sched_domain
*sd
= &per_cpu(core_domains
, i
);
6846 init_sched_groups_power(i
, sd
);
6850 for_each_cpu_mask(i
, *cpu_map
) {
6851 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
);
6853 init_sched_groups_power(i
, sd
);
6857 for (i
= 0; i
< MAX_NUMNODES
; i
++)
6858 init_numa_sched_groups_power(sched_group_nodes
[i
]);
6861 struct sched_group
*sg
;
6863 cpu_to_allnodes_group(first_cpu(*cpu_map
), cpu_map
, &sg
);
6864 init_numa_sched_groups_power(sg
);
6868 /* Attach the domains */
6869 for_each_cpu_mask(i
, *cpu_map
) {
6870 struct sched_domain
*sd
;
6871 #ifdef CONFIG_SCHED_SMT
6872 sd
= &per_cpu(cpu_domains
, i
);
6873 #elif defined(CONFIG_SCHED_MC)
6874 sd
= &per_cpu(core_domains
, i
);
6876 sd
= &per_cpu(phys_domains
, i
);
6878 cpu_attach_domain(sd
, rd
, i
);
6885 free_sched_groups(cpu_map
);
6890 static cpumask_t
*doms_cur
; /* current sched domains */
6891 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
6894 * Special case: If a kmalloc of a doms_cur partition (array of
6895 * cpumask_t) fails, then fallback to a single sched domain,
6896 * as determined by the single cpumask_t fallback_doms.
6898 static cpumask_t fallback_doms
;
6900 void __attribute__((weak
)) arch_update_cpu_topology(void)
6905 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6906 * For now this just excludes isolated cpus, but could be used to
6907 * exclude other special cases in the future.
6909 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
6913 arch_update_cpu_topology();
6915 doms_cur
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
6917 doms_cur
= &fallback_doms
;
6918 cpus_andnot(*doms_cur
, *cpu_map
, cpu_isolated_map
);
6919 err
= build_sched_domains(doms_cur
);
6920 register_sched_domain_sysctl();
6925 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
)
6927 free_sched_groups(cpu_map
);
6931 * Detach sched domains from a group of cpus specified in cpu_map
6932 * These cpus will now be attached to the NULL domain
6934 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
6938 unregister_sched_domain_sysctl();
6940 for_each_cpu_mask(i
, *cpu_map
)
6941 cpu_attach_domain(NULL
, &def_root_domain
, i
);
6942 synchronize_sched();
6943 arch_destroy_sched_domains(cpu_map
);
6947 * Partition sched domains as specified by the 'ndoms_new'
6948 * cpumasks in the array doms_new[] of cpumasks. This compares
6949 * doms_new[] to the current sched domain partitioning, doms_cur[].
6950 * It destroys each deleted domain and builds each new domain.
6952 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6953 * The masks don't intersect (don't overlap.) We should setup one
6954 * sched domain for each mask. CPUs not in any of the cpumasks will
6955 * not be load balanced. If the same cpumask appears both in the
6956 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6959 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6960 * ownership of it and will kfree it when done with it. If the caller
6961 * failed the kmalloc call, then it can pass in doms_new == NULL,
6962 * and partition_sched_domains() will fallback to the single partition
6965 * Call with hotplug lock held
6967 void partition_sched_domains(int ndoms_new
, cpumask_t
*doms_new
)
6973 /* always unregister in case we don't destroy any domains */
6974 unregister_sched_domain_sysctl();
6976 if (doms_new
== NULL
) {
6978 doms_new
= &fallback_doms
;
6979 cpus_andnot(doms_new
[0], cpu_online_map
, cpu_isolated_map
);
6982 /* Destroy deleted domains */
6983 for (i
= 0; i
< ndoms_cur
; i
++) {
6984 for (j
= 0; j
< ndoms_new
; j
++) {
6985 if (cpus_equal(doms_cur
[i
], doms_new
[j
]))
6988 /* no match - a current sched domain not in new doms_new[] */
6989 detach_destroy_domains(doms_cur
+ i
);
6994 /* Build new domains */
6995 for (i
= 0; i
< ndoms_new
; i
++) {
6996 for (j
= 0; j
< ndoms_cur
; j
++) {
6997 if (cpus_equal(doms_new
[i
], doms_cur
[j
]))
7000 /* no match - add a new doms_new */
7001 build_sched_domains(doms_new
+ i
);
7006 /* Remember the new sched domains */
7007 if (doms_cur
!= &fallback_doms
)
7009 doms_cur
= doms_new
;
7010 ndoms_cur
= ndoms_new
;
7012 register_sched_domain_sysctl();
7017 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7018 int arch_reinit_sched_domains(void)
7023 detach_destroy_domains(&cpu_online_map
);
7024 err
= arch_init_sched_domains(&cpu_online_map
);
7030 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
7034 if (buf
[0] != '0' && buf
[0] != '1')
7038 sched_smt_power_savings
= (buf
[0] == '1');
7040 sched_mc_power_savings
= (buf
[0] == '1');
7042 ret
= arch_reinit_sched_domains();
7044 return ret
? ret
: count
;
7047 #ifdef CONFIG_SCHED_MC
7048 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
7050 return sprintf(page
, "%u\n", sched_mc_power_savings
);
7052 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
7053 const char *buf
, size_t count
)
7055 return sched_power_savings_store(buf
, count
, 0);
7057 static SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
7058 sched_mc_power_savings_store
);
7061 #ifdef CONFIG_SCHED_SMT
7062 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
7064 return sprintf(page
, "%u\n", sched_smt_power_savings
);
7066 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
7067 const char *buf
, size_t count
)
7069 return sched_power_savings_store(buf
, count
, 1);
7071 static SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
7072 sched_smt_power_savings_store
);
7075 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
7079 #ifdef CONFIG_SCHED_SMT
7081 err
= sysfs_create_file(&cls
->kset
.kobj
,
7082 &attr_sched_smt_power_savings
.attr
);
7084 #ifdef CONFIG_SCHED_MC
7085 if (!err
&& mc_capable())
7086 err
= sysfs_create_file(&cls
->kset
.kobj
,
7087 &attr_sched_mc_power_savings
.attr
);
7094 * Force a reinitialization of the sched domains hierarchy. The domains
7095 * and groups cannot be updated in place without racing with the balancing
7096 * code, so we temporarily attach all running cpus to the NULL domain
7097 * which will prevent rebalancing while the sched domains are recalculated.
7099 static int update_sched_domains(struct notifier_block
*nfb
,
7100 unsigned long action
, void *hcpu
)
7103 case CPU_UP_PREPARE
:
7104 case CPU_UP_PREPARE_FROZEN
:
7105 case CPU_DOWN_PREPARE
:
7106 case CPU_DOWN_PREPARE_FROZEN
:
7107 detach_destroy_domains(&cpu_online_map
);
7110 case CPU_UP_CANCELED
:
7111 case CPU_UP_CANCELED_FROZEN
:
7112 case CPU_DOWN_FAILED
:
7113 case CPU_DOWN_FAILED_FROZEN
:
7115 case CPU_ONLINE_FROZEN
:
7117 case CPU_DEAD_FROZEN
:
7119 * Fall through and re-initialise the domains.
7126 /* The hotplug lock is already held by cpu_up/cpu_down */
7127 arch_init_sched_domains(&cpu_online_map
);
7132 void __init
sched_init_smp(void)
7134 cpumask_t non_isolated_cpus
;
7137 arch_init_sched_domains(&cpu_online_map
);
7138 cpus_andnot(non_isolated_cpus
, cpu_possible_map
, cpu_isolated_map
);
7139 if (cpus_empty(non_isolated_cpus
))
7140 cpu_set(smp_processor_id(), non_isolated_cpus
);
7142 /* XXX: Theoretical race here - CPU may be hotplugged now */
7143 hotcpu_notifier(update_sched_domains
, 0);
7145 /* Move init over to a non-isolated CPU */
7146 if (set_cpus_allowed(current
, non_isolated_cpus
) < 0)
7148 sched_init_granularity();
7151 void __init
sched_init_smp(void)
7153 sched_init_granularity();
7155 #endif /* CONFIG_SMP */
7157 int in_sched_functions(unsigned long addr
)
7159 return in_lock_functions(addr
) ||
7160 (addr
>= (unsigned long)__sched_text_start
7161 && addr
< (unsigned long)__sched_text_end
);
7164 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
7166 cfs_rq
->tasks_timeline
= RB_ROOT
;
7167 #ifdef CONFIG_FAIR_GROUP_SCHED
7170 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
7173 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
7175 struct rt_prio_array
*array
;
7178 array
= &rt_rq
->active
;
7179 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
7180 INIT_LIST_HEAD(array
->queue
+ i
);
7181 __clear_bit(i
, array
->bitmap
);
7183 /* delimiter for bitsearch: */
7184 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
7186 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7187 rt_rq
->highest_prio
= MAX_RT_PRIO
;
7190 rt_rq
->rt_nr_migratory
= 0;
7191 rt_rq
->overloaded
= 0;
7195 rt_rq
->rt_throttled
= 0;
7197 #ifdef CONFIG_RT_GROUP_SCHED
7198 rt_rq
->rt_nr_boosted
= 0;
7203 #ifdef CONFIG_FAIR_GROUP_SCHED
7204 static void init_tg_cfs_entry(struct rq
*rq
, struct task_group
*tg
,
7205 struct cfs_rq
*cfs_rq
, struct sched_entity
*se
,
7208 tg
->cfs_rq
[cpu
] = cfs_rq
;
7209 init_cfs_rq(cfs_rq
, rq
);
7212 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7215 se
->cfs_rq
= &rq
->cfs
;
7217 se
->load
.weight
= tg
->shares
;
7218 se
->load
.inv_weight
= div64_64(1ULL<<32, se
->load
.weight
);
7223 #ifdef CONFIG_RT_GROUP_SCHED
7224 static void init_tg_rt_entry(struct rq
*rq
, struct task_group
*tg
,
7225 struct rt_rq
*rt_rq
, struct sched_rt_entity
*rt_se
,
7228 tg
->rt_rq
[cpu
] = rt_rq
;
7229 init_rt_rq(rt_rq
, rq
);
7231 rt_rq
->rt_se
= rt_se
;
7233 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
7235 tg
->rt_se
[cpu
] = rt_se
;
7236 rt_se
->rt_rq
= &rq
->rt
;
7237 rt_se
->my_q
= rt_rq
;
7238 rt_se
->parent
= NULL
;
7239 INIT_LIST_HEAD(&rt_se
->run_list
);
7243 void __init
sched_init(void)
7245 int highest_cpu
= 0;
7249 init_defrootdomain();
7252 #ifdef CONFIG_GROUP_SCHED
7253 list_add(&init_task_group
.list
, &task_groups
);
7256 for_each_possible_cpu(i
) {
7260 spin_lock_init(&rq
->lock
);
7261 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
7264 init_cfs_rq(&rq
->cfs
, rq
);
7265 init_rt_rq(&rq
->rt
, rq
);
7266 #ifdef CONFIG_FAIR_GROUP_SCHED
7267 init_task_group
.shares
= init_task_group_load
;
7268 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
7269 init_tg_cfs_entry(rq
, &init_task_group
,
7270 &per_cpu(init_cfs_rq
, i
),
7271 &per_cpu(init_sched_entity
, i
), i
, 1);
7274 #ifdef CONFIG_RT_GROUP_SCHED
7275 init_task_group
.rt_runtime
=
7276 sysctl_sched_rt_runtime
* NSEC_PER_USEC
;
7277 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
7278 init_tg_rt_entry(rq
, &init_task_group
,
7279 &per_cpu(init_rt_rq
, i
),
7280 &per_cpu(init_sched_rt_entity
, i
), i
, 1);
7282 rq
->rt_period_expire
= 0;
7283 rq
->rt_throttled
= 0;
7285 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
7286 rq
->cpu_load
[j
] = 0;
7290 rq
->active_balance
= 0;
7291 rq
->next_balance
= jiffies
;
7294 rq
->migration_thread
= NULL
;
7295 INIT_LIST_HEAD(&rq
->migration_queue
);
7296 rq_attach_root(rq
, &def_root_domain
);
7299 atomic_set(&rq
->nr_iowait
, 0);
7303 set_load_weight(&init_task
);
7305 #ifdef CONFIG_PREEMPT_NOTIFIERS
7306 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
7310 nr_cpu_ids
= highest_cpu
+ 1;
7311 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
, NULL
);
7314 #ifdef CONFIG_RT_MUTEXES
7315 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
7319 * The boot idle thread does lazy MMU switching as well:
7321 atomic_inc(&init_mm
.mm_count
);
7322 enter_lazy_tlb(&init_mm
, current
);
7325 * Make us the idle thread. Technically, schedule() should not be
7326 * called from this thread, however somewhere below it might be,
7327 * but because we are the idle thread, we just pick up running again
7328 * when this runqueue becomes "idle".
7330 init_idle(current
, smp_processor_id());
7332 * During early bootup we pretend to be a normal task:
7334 current
->sched_class
= &fair_sched_class
;
7336 scheduler_running
= 1;
7339 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7340 void __might_sleep(char *file
, int line
)
7343 static unsigned long prev_jiffy
; /* ratelimiting */
7345 if ((in_atomic() || irqs_disabled()) &&
7346 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
7347 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
7349 prev_jiffy
= jiffies
;
7350 printk(KERN_ERR
"BUG: sleeping function called from invalid"
7351 " context at %s:%d\n", file
, line
);
7352 printk("in_atomic():%d, irqs_disabled():%d\n",
7353 in_atomic(), irqs_disabled());
7354 debug_show_held_locks(current
);
7355 if (irqs_disabled())
7356 print_irqtrace_events(current
);
7361 EXPORT_SYMBOL(__might_sleep
);
7364 #ifdef CONFIG_MAGIC_SYSRQ
7365 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
7368 update_rq_clock(rq
);
7369 on_rq
= p
->se
.on_rq
;
7371 deactivate_task(rq
, p
, 0);
7372 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
7374 activate_task(rq
, p
, 0);
7375 resched_task(rq
->curr
);
7379 void normalize_rt_tasks(void)
7381 struct task_struct
*g
, *p
;
7382 unsigned long flags
;
7385 read_lock_irqsave(&tasklist_lock
, flags
);
7386 do_each_thread(g
, p
) {
7388 * Only normalize user tasks:
7393 p
->se
.exec_start
= 0;
7394 #ifdef CONFIG_SCHEDSTATS
7395 p
->se
.wait_start
= 0;
7396 p
->se
.sleep_start
= 0;
7397 p
->se
.block_start
= 0;
7399 task_rq(p
)->clock
= 0;
7403 * Renice negative nice level userspace
7406 if (TASK_NICE(p
) < 0 && p
->mm
)
7407 set_user_nice(p
, 0);
7411 spin_lock(&p
->pi_lock
);
7412 rq
= __task_rq_lock(p
);
7414 normalize_task(rq
, p
);
7416 __task_rq_unlock(rq
);
7417 spin_unlock(&p
->pi_lock
);
7418 } while_each_thread(g
, p
);
7420 read_unlock_irqrestore(&tasklist_lock
, flags
);
7423 #endif /* CONFIG_MAGIC_SYSRQ */
7427 * These functions are only useful for the IA64 MCA handling.
7429 * They can only be called when the whole system has been
7430 * stopped - every CPU needs to be quiescent, and no scheduling
7431 * activity can take place. Using them for anything else would
7432 * be a serious bug, and as a result, they aren't even visible
7433 * under any other configuration.
7437 * curr_task - return the current task for a given cpu.
7438 * @cpu: the processor in question.
7440 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7442 struct task_struct
*curr_task(int cpu
)
7444 return cpu_curr(cpu
);
7448 * set_curr_task - set the current task for a given cpu.
7449 * @cpu: the processor in question.
7450 * @p: the task pointer to set.
7452 * Description: This function must only be used when non-maskable interrupts
7453 * are serviced on a separate stack. It allows the architecture to switch the
7454 * notion of the current task on a cpu in a non-blocking manner. This function
7455 * must be called with all CPU's synchronized, and interrupts disabled, the
7456 * and caller must save the original value of the current task (see
7457 * curr_task() above) and restore that value before reenabling interrupts and
7458 * re-starting the system.
7460 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7462 void set_curr_task(int cpu
, struct task_struct
*p
)
7469 #ifdef CONFIG_GROUP_SCHED
7471 #ifdef CONFIG_FAIR_GROUP_SCHED
7472 static void free_fair_sched_group(struct task_group
*tg
)
7476 for_each_possible_cpu(i
) {
7478 kfree(tg
->cfs_rq
[i
]);
7487 static int alloc_fair_sched_group(struct task_group
*tg
)
7489 struct cfs_rq
*cfs_rq
;
7490 struct sched_entity
*se
;
7494 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * NR_CPUS
, GFP_KERNEL
);
7497 tg
->se
= kzalloc(sizeof(se
) * NR_CPUS
, GFP_KERNEL
);
7501 tg
->shares
= NICE_0_LOAD
;
7503 for_each_possible_cpu(i
) {
7506 cfs_rq
= kmalloc_node(sizeof(struct cfs_rq
),
7507 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7511 se
= kmalloc_node(sizeof(struct sched_entity
),
7512 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7516 init_tg_cfs_entry(rq
, tg
, cfs_rq
, se
, i
, 0);
7525 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
7527 list_add_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
,
7528 &cpu_rq(cpu
)->leaf_cfs_rq_list
);
7531 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
7533 list_del_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
);
7536 static inline void free_fair_sched_group(struct task_group
*tg
)
7540 static inline int alloc_fair_sched_group(struct task_group
*tg
)
7545 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
7549 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
7554 #ifdef CONFIG_RT_GROUP_SCHED
7555 static void free_rt_sched_group(struct task_group
*tg
)
7559 for_each_possible_cpu(i
) {
7561 kfree(tg
->rt_rq
[i
]);
7563 kfree(tg
->rt_se
[i
]);
7570 static int alloc_rt_sched_group(struct task_group
*tg
)
7572 struct rt_rq
*rt_rq
;
7573 struct sched_rt_entity
*rt_se
;
7577 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * NR_CPUS
, GFP_KERNEL
);
7580 tg
->rt_se
= kzalloc(sizeof(rt_se
) * NR_CPUS
, GFP_KERNEL
);
7586 for_each_possible_cpu(i
) {
7589 rt_rq
= kmalloc_node(sizeof(struct rt_rq
),
7590 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7594 rt_se
= kmalloc_node(sizeof(struct sched_rt_entity
),
7595 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7599 init_tg_rt_entry(rq
, tg
, rt_rq
, rt_se
, i
, 0);
7608 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
7610 list_add_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
,
7611 &cpu_rq(cpu
)->leaf_rt_rq_list
);
7614 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
7616 list_del_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
);
7619 static inline void free_rt_sched_group(struct task_group
*tg
)
7623 static inline int alloc_rt_sched_group(struct task_group
*tg
)
7628 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
7632 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
7637 static void free_sched_group(struct task_group
*tg
)
7639 free_fair_sched_group(tg
);
7640 free_rt_sched_group(tg
);
7644 /* allocate runqueue etc for a new task group */
7645 struct task_group
*sched_create_group(void)
7647 struct task_group
*tg
;
7648 unsigned long flags
;
7651 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
7653 return ERR_PTR(-ENOMEM
);
7655 if (!alloc_fair_sched_group(tg
))
7658 if (!alloc_rt_sched_group(tg
))
7661 spin_lock_irqsave(&task_group_lock
, flags
);
7662 for_each_possible_cpu(i
) {
7663 register_fair_sched_group(tg
, i
);
7664 register_rt_sched_group(tg
, i
);
7666 list_add_rcu(&tg
->list
, &task_groups
);
7667 spin_unlock_irqrestore(&task_group_lock
, flags
);
7672 free_sched_group(tg
);
7673 return ERR_PTR(-ENOMEM
);
7676 /* rcu callback to free various structures associated with a task group */
7677 static void free_sched_group_rcu(struct rcu_head
*rhp
)
7679 /* now it should be safe to free those cfs_rqs */
7680 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
7683 /* Destroy runqueue etc associated with a task group */
7684 void sched_destroy_group(struct task_group
*tg
)
7686 unsigned long flags
;
7689 spin_lock_irqsave(&task_group_lock
, flags
);
7690 for_each_possible_cpu(i
) {
7691 unregister_fair_sched_group(tg
, i
);
7692 unregister_rt_sched_group(tg
, i
);
7694 list_del_rcu(&tg
->list
);
7695 spin_unlock_irqrestore(&task_group_lock
, flags
);
7697 /* wait for possible concurrent references to cfs_rqs complete */
7698 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
7701 /* change task's runqueue when it moves between groups.
7702 * The caller of this function should have put the task in its new group
7703 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7704 * reflect its new group.
7706 void sched_move_task(struct task_struct
*tsk
)
7709 unsigned long flags
;
7712 rq
= task_rq_lock(tsk
, &flags
);
7714 update_rq_clock(rq
);
7716 running
= task_current(rq
, tsk
);
7717 on_rq
= tsk
->se
.on_rq
;
7720 dequeue_task(rq
, tsk
, 0);
7721 if (unlikely(running
))
7722 tsk
->sched_class
->put_prev_task(rq
, tsk
);
7724 set_task_rq(tsk
, task_cpu(tsk
));
7726 #ifdef CONFIG_FAIR_GROUP_SCHED
7727 if (tsk
->sched_class
->moved_group
)
7728 tsk
->sched_class
->moved_group(tsk
);
7731 if (unlikely(running
))
7732 tsk
->sched_class
->set_curr_task(rq
);
7734 enqueue_task(rq
, tsk
, 0);
7736 task_rq_unlock(rq
, &flags
);
7739 #ifdef CONFIG_FAIR_GROUP_SCHED
7740 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
7742 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
7743 struct rq
*rq
= cfs_rq
->rq
;
7746 spin_lock_irq(&rq
->lock
);
7750 dequeue_entity(cfs_rq
, se
, 0);
7752 se
->load
.weight
= shares
;
7753 se
->load
.inv_weight
= div64_64((1ULL<<32), shares
);
7756 enqueue_entity(cfs_rq
, se
, 0);
7758 spin_unlock_irq(&rq
->lock
);
7761 static DEFINE_MUTEX(shares_mutex
);
7763 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
7766 unsigned long flags
;
7769 * A weight of 0 or 1 can cause arithmetics problems.
7770 * (The default weight is 1024 - so there's no practical
7771 * limitation from this.)
7776 mutex_lock(&shares_mutex
);
7777 if (tg
->shares
== shares
)
7780 spin_lock_irqsave(&task_group_lock
, flags
);
7781 for_each_possible_cpu(i
)
7782 unregister_fair_sched_group(tg
, i
);
7783 spin_unlock_irqrestore(&task_group_lock
, flags
);
7785 /* wait for any ongoing reference to this group to finish */
7786 synchronize_sched();
7789 * Now we are free to modify the group's share on each cpu
7790 * w/o tripping rebalance_share or load_balance_fair.
7792 tg
->shares
= shares
;
7793 for_each_possible_cpu(i
)
7794 set_se_shares(tg
->se
[i
], shares
);
7797 * Enable load balance activity on this group, by inserting it back on
7798 * each cpu's rq->leaf_cfs_rq_list.
7800 spin_lock_irqsave(&task_group_lock
, flags
);
7801 for_each_possible_cpu(i
)
7802 register_fair_sched_group(tg
, i
);
7803 spin_unlock_irqrestore(&task_group_lock
, flags
);
7805 mutex_unlock(&shares_mutex
);
7809 unsigned long sched_group_shares(struct task_group
*tg
)
7815 #ifdef CONFIG_RT_GROUP_SCHED
7817 * Ensure that the real time constraints are schedulable.
7819 static DEFINE_MUTEX(rt_constraints_mutex
);
7821 static unsigned long to_ratio(u64 period
, u64 runtime
)
7823 if (runtime
== RUNTIME_INF
)
7826 return div64_64(runtime
<< 16, period
);
7829 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
7831 struct task_group
*tgi
;
7832 unsigned long total
= 0;
7833 unsigned long global_ratio
=
7834 to_ratio(sysctl_sched_rt_period
,
7835 sysctl_sched_rt_runtime
< 0 ?
7836 RUNTIME_INF
: sysctl_sched_rt_runtime
);
7839 list_for_each_entry_rcu(tgi
, &task_groups
, list
) {
7843 total
+= to_ratio(period
, tgi
->rt_runtime
);
7847 return total
+ to_ratio(period
, runtime
) < global_ratio
;
7850 /* Must be called with tasklist_lock held */
7851 static inline int tg_has_rt_tasks(struct task_group
*tg
)
7853 struct task_struct
*g
, *p
;
7854 do_each_thread(g
, p
) {
7855 if (rt_task(p
) && rt_rq_of_se(&p
->rt
)->tg
== tg
)
7857 } while_each_thread(g
, p
);
7861 int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
7863 u64 rt_runtime
, rt_period
;
7866 rt_period
= (u64
)sysctl_sched_rt_period
* NSEC_PER_USEC
;
7867 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
7868 if (rt_runtime_us
== -1)
7869 rt_runtime
= RUNTIME_INF
;
7871 mutex_lock(&rt_constraints_mutex
);
7872 read_lock(&tasklist_lock
);
7873 if (rt_runtime_us
== 0 && tg_has_rt_tasks(tg
)) {
7877 if (!__rt_schedulable(tg
, rt_period
, rt_runtime
)) {
7881 tg
->rt_runtime
= rt_runtime
;
7883 read_unlock(&tasklist_lock
);
7884 mutex_unlock(&rt_constraints_mutex
);
7889 long sched_group_rt_runtime(struct task_group
*tg
)
7893 if (tg
->rt_runtime
== RUNTIME_INF
)
7896 rt_runtime_us
= tg
->rt_runtime
;
7897 do_div(rt_runtime_us
, NSEC_PER_USEC
);
7898 return rt_runtime_us
;
7901 #endif /* CONFIG_GROUP_SCHED */
7903 #ifdef CONFIG_CGROUP_SCHED
7905 /* return corresponding task_group object of a cgroup */
7906 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
7908 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
7909 struct task_group
, css
);
7912 static struct cgroup_subsys_state
*
7913 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
7915 struct task_group
*tg
;
7917 if (!cgrp
->parent
) {
7918 /* This is early initialization for the top cgroup */
7919 init_task_group
.css
.cgroup
= cgrp
;
7920 return &init_task_group
.css
;
7923 /* we support only 1-level deep hierarchical scheduler atm */
7924 if (cgrp
->parent
->parent
)
7925 return ERR_PTR(-EINVAL
);
7927 tg
= sched_create_group();
7929 return ERR_PTR(-ENOMEM
);
7931 /* Bind the cgroup to task_group object we just created */
7932 tg
->css
.cgroup
= cgrp
;
7938 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
7940 struct task_group
*tg
= cgroup_tg(cgrp
);
7942 sched_destroy_group(tg
);
7946 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
7947 struct task_struct
*tsk
)
7949 #ifdef CONFIG_RT_GROUP_SCHED
7950 /* Don't accept realtime tasks when there is no way for them to run */
7951 if (rt_task(tsk
) && cgroup_tg(cgrp
)->rt_runtime
== 0)
7954 /* We don't support RT-tasks being in separate groups */
7955 if (tsk
->sched_class
!= &fair_sched_class
)
7963 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
7964 struct cgroup
*old_cont
, struct task_struct
*tsk
)
7966 sched_move_task(tsk
);
7969 #ifdef CONFIG_FAIR_GROUP_SCHED
7970 static int cpu_shares_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
7973 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
7976 static u64
cpu_shares_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
7978 struct task_group
*tg
= cgroup_tg(cgrp
);
7980 return (u64
) tg
->shares
;
7984 #ifdef CONFIG_RT_GROUP_SCHED
7985 static int cpu_rt_runtime_write(struct cgroup
*cgrp
, struct cftype
*cft
,
7987 const char __user
*userbuf
,
7988 size_t nbytes
, loff_t
*unused_ppos
)
7997 if (nbytes
>= sizeof(buffer
))
7999 if (copy_from_user(buffer
, userbuf
, nbytes
))
8002 buffer
[nbytes
] = 0; /* nul-terminate */
8004 /* strip newline if necessary */
8005 if (nbytes
&& (buffer
[nbytes
-1] == '\n'))
8006 buffer
[nbytes
-1] = 0;
8007 val
= simple_strtoll(buffer
, &end
, 0);
8011 /* Pass to subsystem */
8012 retval
= sched_group_set_rt_runtime(cgroup_tg(cgrp
), val
);
8018 static ssize_t
cpu_rt_runtime_read(struct cgroup
*cgrp
, struct cftype
*cft
,
8020 char __user
*buf
, size_t nbytes
,
8024 long val
= sched_group_rt_runtime(cgroup_tg(cgrp
));
8025 int len
= sprintf(tmp
, "%ld\n", val
);
8027 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
8031 static struct cftype cpu_files
[] = {
8032 #ifdef CONFIG_FAIR_GROUP_SCHED
8035 .read_uint
= cpu_shares_read_uint
,
8036 .write_uint
= cpu_shares_write_uint
,
8039 #ifdef CONFIG_RT_GROUP_SCHED
8041 .name
= "rt_runtime_us",
8042 .read
= cpu_rt_runtime_read
,
8043 .write
= cpu_rt_runtime_write
,
8048 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8050 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
8053 struct cgroup_subsys cpu_cgroup_subsys
= {
8055 .create
= cpu_cgroup_create
,
8056 .destroy
= cpu_cgroup_destroy
,
8057 .can_attach
= cpu_cgroup_can_attach
,
8058 .attach
= cpu_cgroup_attach
,
8059 .populate
= cpu_cgroup_populate
,
8060 .subsys_id
= cpu_cgroup_subsys_id
,
8064 #endif /* CONFIG_CGROUP_SCHED */
8066 #ifdef CONFIG_CGROUP_CPUACCT
8069 * CPU accounting code for task groups.
8071 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8072 * (balbir@in.ibm.com).
8075 /* track cpu usage of a group of tasks */
8077 struct cgroup_subsys_state css
;
8078 /* cpuusage holds pointer to a u64-type object on every cpu */
8082 struct cgroup_subsys cpuacct_subsys
;
8084 /* return cpu accounting group corresponding to this container */
8085 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cont
)
8087 return container_of(cgroup_subsys_state(cont
, cpuacct_subsys_id
),
8088 struct cpuacct
, css
);
8091 /* return cpu accounting group to which this task belongs */
8092 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
8094 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
8095 struct cpuacct
, css
);
8098 /* create a new cpu accounting group */
8099 static struct cgroup_subsys_state
*cpuacct_create(
8100 struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8102 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
8105 return ERR_PTR(-ENOMEM
);
8107 ca
->cpuusage
= alloc_percpu(u64
);
8108 if (!ca
->cpuusage
) {
8110 return ERR_PTR(-ENOMEM
);
8116 /* destroy an existing cpu accounting group */
8118 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8120 struct cpuacct
*ca
= cgroup_ca(cont
);
8122 free_percpu(ca
->cpuusage
);
8126 /* return total cpu usage (in nanoseconds) of a group */
8127 static u64
cpuusage_read(struct cgroup
*cont
, struct cftype
*cft
)
8129 struct cpuacct
*ca
= cgroup_ca(cont
);
8130 u64 totalcpuusage
= 0;
8133 for_each_possible_cpu(i
) {
8134 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
8137 * Take rq->lock to make 64-bit addition safe on 32-bit
8140 spin_lock_irq(&cpu_rq(i
)->lock
);
8141 totalcpuusage
+= *cpuusage
;
8142 spin_unlock_irq(&cpu_rq(i
)->lock
);
8145 return totalcpuusage
;
8148 static struct cftype files
[] = {
8151 .read_uint
= cpuusage_read
,
8155 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8157 return cgroup_add_files(cont
, ss
, files
, ARRAY_SIZE(files
));
8161 * charge this task's execution time to its accounting group.
8163 * called with rq->lock held.
8165 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
8169 if (!cpuacct_subsys
.active
)
8174 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, task_cpu(tsk
));
8176 *cpuusage
+= cputime
;
8180 struct cgroup_subsys cpuacct_subsys
= {
8182 .create
= cpuacct_create
,
8183 .destroy
= cpuacct_destroy
,
8184 .populate
= cpuacct_populate
,
8185 .subsys_id
= cpuacct_subsys_id
,
8187 #endif /* CONFIG_CGROUP_CPUACCT */