4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/kthread.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/bootmem.h>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
75 #include <asm/irq_regs.h>
78 * Convert user-nice values [ -20 ... 0 ... 19 ]
79 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
82 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
83 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
84 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
87 * 'User priority' is the nice value converted to something we
88 * can work with better when scaling various scheduler parameters,
89 * it's a [ 0 ... 39 ] range.
91 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
92 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
93 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
96 * Helpers for converting nanosecond timing to jiffy resolution
98 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
100 #define NICE_0_LOAD SCHED_LOAD_SCALE
101 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
104 * These are the 'tuning knobs' of the scheduler:
106 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
107 * Timeslices get refilled after they expire.
109 #define DEF_TIMESLICE (100 * HZ / 1000)
112 * single value that denotes runtime == period, ie unlimited time.
114 #define RUNTIME_INF ((u64)~0ULL)
118 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
119 * Since cpu_power is a 'constant', we can use a reciprocal divide.
121 static inline u32
sg_div_cpu_power(const struct sched_group
*sg
, u32 load
)
123 return reciprocal_divide(load
, sg
->reciprocal_cpu_power
);
127 * Each time a sched group cpu_power is changed,
128 * we must compute its reciprocal value
130 static inline void sg_inc_cpu_power(struct sched_group
*sg
, u32 val
)
132 sg
->__cpu_power
+= val
;
133 sg
->reciprocal_cpu_power
= reciprocal_value(sg
->__cpu_power
);
137 static inline int rt_policy(int policy
)
139 if (unlikely(policy
== SCHED_FIFO
|| policy
== SCHED_RR
))
144 static inline int task_has_rt_policy(struct task_struct
*p
)
146 return rt_policy(p
->policy
);
150 * This is the priority-queue data structure of the RT scheduling class:
152 struct rt_prio_array
{
153 DECLARE_BITMAP(bitmap
, MAX_RT_PRIO
+1); /* include 1 bit for delimiter */
154 struct list_head queue
[MAX_RT_PRIO
];
157 struct rt_bandwidth
{
158 /* nests inside the rq lock: */
159 spinlock_t rt_runtime_lock
;
162 struct hrtimer rt_period_timer
;
165 static struct rt_bandwidth def_rt_bandwidth
;
167 static int do_sched_rt_period_timer(struct rt_bandwidth
*rt_b
, int overrun
);
169 static enum hrtimer_restart
sched_rt_period_timer(struct hrtimer
*timer
)
171 struct rt_bandwidth
*rt_b
=
172 container_of(timer
, struct rt_bandwidth
, rt_period_timer
);
178 now
= hrtimer_cb_get_time(timer
);
179 overrun
= hrtimer_forward(timer
, now
, rt_b
->rt_period
);
184 idle
= do_sched_rt_period_timer(rt_b
, overrun
);
187 return idle
? HRTIMER_NORESTART
: HRTIMER_RESTART
;
191 void init_rt_bandwidth(struct rt_bandwidth
*rt_b
, u64 period
, u64 runtime
)
193 rt_b
->rt_period
= ns_to_ktime(period
);
194 rt_b
->rt_runtime
= runtime
;
196 spin_lock_init(&rt_b
->rt_runtime_lock
);
198 hrtimer_init(&rt_b
->rt_period_timer
,
199 CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
200 rt_b
->rt_period_timer
.function
= sched_rt_period_timer
;
201 rt_b
->rt_period_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
204 static void start_rt_bandwidth(struct rt_bandwidth
*rt_b
)
208 if (rt_b
->rt_runtime
== RUNTIME_INF
)
211 if (hrtimer_active(&rt_b
->rt_period_timer
))
214 spin_lock(&rt_b
->rt_runtime_lock
);
216 if (hrtimer_active(&rt_b
->rt_period_timer
))
219 now
= hrtimer_cb_get_time(&rt_b
->rt_period_timer
);
220 hrtimer_forward(&rt_b
->rt_period_timer
, now
, rt_b
->rt_period
);
221 hrtimer_start(&rt_b
->rt_period_timer
,
222 rt_b
->rt_period_timer
.expires
,
225 spin_unlock(&rt_b
->rt_runtime_lock
);
228 #ifdef CONFIG_RT_GROUP_SCHED
229 static void destroy_rt_bandwidth(struct rt_bandwidth
*rt_b
)
231 hrtimer_cancel(&rt_b
->rt_period_timer
);
236 * sched_domains_mutex serializes calls to arch_init_sched_domains,
237 * detach_destroy_domains and partition_sched_domains.
239 static DEFINE_MUTEX(sched_domains_mutex
);
241 #ifdef CONFIG_GROUP_SCHED
243 #include <linux/cgroup.h>
247 static LIST_HEAD(task_groups
);
249 /* task group related information */
251 #ifdef CONFIG_CGROUP_SCHED
252 struct cgroup_subsys_state css
;
255 #ifdef CONFIG_FAIR_GROUP_SCHED
256 /* schedulable entities of this group on each cpu */
257 struct sched_entity
**se
;
258 /* runqueue "owned" by this group on each cpu */
259 struct cfs_rq
**cfs_rq
;
260 unsigned long shares
;
263 #ifdef CONFIG_RT_GROUP_SCHED
264 struct sched_rt_entity
**rt_se
;
265 struct rt_rq
**rt_rq
;
267 struct rt_bandwidth rt_bandwidth
;
271 struct list_head list
;
273 struct task_group
*parent
;
274 struct list_head siblings
;
275 struct list_head children
;
278 #ifdef CONFIG_USER_SCHED
282 * Every UID task group (including init_task_group aka UID-0) will
283 * be a child to this group.
285 struct task_group root_task_group
;
287 #ifdef CONFIG_FAIR_GROUP_SCHED
288 /* Default task group's sched entity on each cpu */
289 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
290 /* Default task group's cfs_rq on each cpu */
291 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
294 #ifdef CONFIG_RT_GROUP_SCHED
295 static DEFINE_PER_CPU(struct sched_rt_entity
, init_sched_rt_entity
);
296 static DEFINE_PER_CPU(struct rt_rq
, init_rt_rq
) ____cacheline_aligned_in_smp
;
299 #define root_task_group init_task_group
302 /* task_group_lock serializes add/remove of task groups and also changes to
303 * a task group's cpu shares.
305 static DEFINE_SPINLOCK(task_group_lock
);
307 #ifdef CONFIG_FAIR_GROUP_SCHED
308 #ifdef CONFIG_USER_SCHED
309 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
311 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
315 * A weight of 0 or 1 can cause arithmetics problems.
316 * A weight of a cfs_rq is the sum of weights of which entities
317 * are queued on this cfs_rq, so a weight of a entity should not be
318 * too large, so as the shares value of a task group.
319 * (The default weight is 1024 - so there's no practical
320 * limitation from this.)
323 #define MAX_SHARES (1UL << 18)
325 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
328 /* Default task group.
329 * Every task in system belong to this group at bootup.
331 struct task_group init_task_group
;
333 /* return group to which a task belongs */
334 static inline struct task_group
*task_group(struct task_struct
*p
)
336 struct task_group
*tg
;
338 #ifdef CONFIG_USER_SCHED
340 #elif defined(CONFIG_CGROUP_SCHED)
341 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
342 struct task_group
, css
);
344 tg
= &init_task_group
;
349 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
350 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
)
352 #ifdef CONFIG_FAIR_GROUP_SCHED
353 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
354 p
->se
.parent
= task_group(p
)->se
[cpu
];
357 #ifdef CONFIG_RT_GROUP_SCHED
358 p
->rt
.rt_rq
= task_group(p
)->rt_rq
[cpu
];
359 p
->rt
.parent
= task_group(p
)->rt_se
[cpu
];
365 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
) { }
367 #endif /* CONFIG_GROUP_SCHED */
369 /* CFS-related fields in a runqueue */
371 struct load_weight load
;
372 unsigned long nr_running
;
377 struct rb_root tasks_timeline
;
378 struct rb_node
*rb_leftmost
;
380 struct list_head tasks
;
381 struct list_head
*balance_iterator
;
384 * 'curr' points to currently running entity on this cfs_rq.
385 * It is set to NULL otherwise (i.e when none are currently running).
387 struct sched_entity
*curr
, *next
;
389 unsigned long nr_spread_over
;
391 #ifdef CONFIG_FAIR_GROUP_SCHED
392 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
395 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
396 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
397 * (like users, containers etc.)
399 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
400 * list is used during load balance.
402 struct list_head leaf_cfs_rq_list
;
403 struct task_group
*tg
; /* group that "owns" this runqueue */
407 /* Real-Time classes' related field in a runqueue: */
409 struct rt_prio_array active
;
410 unsigned long rt_nr_running
;
411 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
412 int highest_prio
; /* highest queued rt task prio */
415 unsigned long rt_nr_migratory
;
421 /* Nests inside the rq lock: */
422 spinlock_t rt_runtime_lock
;
424 #ifdef CONFIG_RT_GROUP_SCHED
425 unsigned long rt_nr_boosted
;
428 struct list_head leaf_rt_rq_list
;
429 struct task_group
*tg
;
430 struct sched_rt_entity
*rt_se
;
437 * We add the notion of a root-domain which will be used to define per-domain
438 * variables. Each exclusive cpuset essentially defines an island domain by
439 * fully partitioning the member cpus from any other cpuset. Whenever a new
440 * exclusive cpuset is created, we also create and attach a new root-domain
450 * The "RT overload" flag: it gets set if a CPU has more than
451 * one runnable RT task.
458 * By default the system creates a single root-domain with all cpus as
459 * members (mimicking the global state we have today).
461 static struct root_domain def_root_domain
;
466 * This is the main, per-CPU runqueue data structure.
468 * Locking rule: those places that want to lock multiple runqueues
469 * (such as the load balancing or the thread migration code), lock
470 * acquire operations must be ordered by ascending &runqueue.
477 * nr_running and cpu_load should be in the same cacheline because
478 * remote CPUs use both these fields when doing load calculation.
480 unsigned long nr_running
;
481 #define CPU_LOAD_IDX_MAX 5
482 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
483 unsigned char idle_at_tick
;
485 unsigned long last_tick_seen
;
486 unsigned char in_nohz_recently
;
488 /* capture load from *all* tasks on this cpu: */
489 struct load_weight load
;
490 unsigned long nr_load_updates
;
496 #ifdef CONFIG_FAIR_GROUP_SCHED
497 /* list of leaf cfs_rq on this cpu: */
498 struct list_head leaf_cfs_rq_list
;
500 #ifdef CONFIG_RT_GROUP_SCHED
501 struct list_head leaf_rt_rq_list
;
505 * This is part of a global counter where only the total sum
506 * over all CPUs matters. A task can increase this counter on
507 * one CPU and if it got migrated afterwards it may decrease
508 * it on another CPU. Always updated under the runqueue lock:
510 unsigned long nr_uninterruptible
;
512 struct task_struct
*curr
, *idle
;
513 unsigned long next_balance
;
514 struct mm_struct
*prev_mm
;
521 struct root_domain
*rd
;
522 struct sched_domain
*sd
;
524 /* For active balancing */
527 /* cpu of this runqueue: */
530 struct task_struct
*migration_thread
;
531 struct list_head migration_queue
;
534 #ifdef CONFIG_SCHED_HRTICK
535 unsigned long hrtick_flags
;
536 ktime_t hrtick_expire
;
537 struct hrtimer hrtick_timer
;
540 #ifdef CONFIG_SCHEDSTATS
542 struct sched_info rq_sched_info
;
544 /* sys_sched_yield() stats */
545 unsigned int yld_exp_empty
;
546 unsigned int yld_act_empty
;
547 unsigned int yld_both_empty
;
548 unsigned int yld_count
;
550 /* schedule() stats */
551 unsigned int sched_switch
;
552 unsigned int sched_count
;
553 unsigned int sched_goidle
;
555 /* try_to_wake_up() stats */
556 unsigned int ttwu_count
;
557 unsigned int ttwu_local
;
560 unsigned int bkl_count
;
562 struct lock_class_key rq_lock_key
;
565 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
567 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
)
569 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
);
572 static inline int cpu_of(struct rq
*rq
)
582 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
583 * See detach_destroy_domains: synchronize_sched for details.
585 * The domain tree of any CPU may only be accessed from within
586 * preempt-disabled sections.
588 #define for_each_domain(cpu, __sd) \
589 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
591 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
592 #define this_rq() (&__get_cpu_var(runqueues))
593 #define task_rq(p) cpu_rq(task_cpu(p))
594 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
596 static inline void update_rq_clock(struct rq
*rq
)
598 rq
->clock
= sched_clock_cpu(cpu_of(rq
));
602 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
604 #ifdef CONFIG_SCHED_DEBUG
605 # define const_debug __read_mostly
607 # define const_debug static const
611 * Debugging: various feature bits
614 #define SCHED_FEAT(name, enabled) \
615 __SCHED_FEAT_##name ,
618 #include "sched_features.h"
623 #define SCHED_FEAT(name, enabled) \
624 (1UL << __SCHED_FEAT_##name) * enabled |
626 const_debug
unsigned int sysctl_sched_features
=
627 #include "sched_features.h"
632 #ifdef CONFIG_SCHED_DEBUG
633 #define SCHED_FEAT(name, enabled) \
636 static __read_mostly
char *sched_feat_names
[] = {
637 #include "sched_features.h"
643 static int sched_feat_open(struct inode
*inode
, struct file
*filp
)
645 filp
->private_data
= inode
->i_private
;
650 sched_feat_read(struct file
*filp
, char __user
*ubuf
,
651 size_t cnt
, loff_t
*ppos
)
658 for (i
= 0; sched_feat_names
[i
]; i
++) {
659 len
+= strlen(sched_feat_names
[i
]);
663 buf
= kmalloc(len
+ 2, GFP_KERNEL
);
667 for (i
= 0; sched_feat_names
[i
]; i
++) {
668 if (sysctl_sched_features
& (1UL << i
))
669 r
+= sprintf(buf
+ r
, "%s ", sched_feat_names
[i
]);
671 r
+= sprintf(buf
+ r
, "NO_%s ", sched_feat_names
[i
]);
674 r
+= sprintf(buf
+ r
, "\n");
675 WARN_ON(r
>= len
+ 2);
677 r
= simple_read_from_buffer(ubuf
, cnt
, ppos
, buf
, r
);
685 sched_feat_write(struct file
*filp
, const char __user
*ubuf
,
686 size_t cnt
, loff_t
*ppos
)
696 if (copy_from_user(&buf
, ubuf
, cnt
))
701 if (strncmp(buf
, "NO_", 3) == 0) {
706 for (i
= 0; sched_feat_names
[i
]; i
++) {
707 int len
= strlen(sched_feat_names
[i
]);
709 if (strncmp(cmp
, sched_feat_names
[i
], len
) == 0) {
711 sysctl_sched_features
&= ~(1UL << i
);
713 sysctl_sched_features
|= (1UL << i
);
718 if (!sched_feat_names
[i
])
726 static struct file_operations sched_feat_fops
= {
727 .open
= sched_feat_open
,
728 .read
= sched_feat_read
,
729 .write
= sched_feat_write
,
732 static __init
int sched_init_debug(void)
734 debugfs_create_file("sched_features", 0644, NULL
, NULL
,
739 late_initcall(sched_init_debug
);
743 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
746 * Number of tasks to iterate in a single balance run.
747 * Limited because this is done with IRQs disabled.
749 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
752 * period over which we measure -rt task cpu usage in us.
755 unsigned int sysctl_sched_rt_period
= 1000000;
757 static __read_mostly
int scheduler_running
;
760 * part of the period that we allow rt tasks to run in us.
763 int sysctl_sched_rt_runtime
= 950000;
765 static inline u64
global_rt_period(void)
767 return (u64
)sysctl_sched_rt_period
* NSEC_PER_USEC
;
770 static inline u64
global_rt_runtime(void)
772 if (sysctl_sched_rt_period
< 0)
775 return (u64
)sysctl_sched_rt_runtime
* NSEC_PER_USEC
;
778 unsigned long long time_sync_thresh
= 100000;
780 static DEFINE_PER_CPU(unsigned long long, time_offset
);
781 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time
);
784 * Global lock which we take every now and then to synchronize
785 * the CPUs time. This method is not warp-safe, but it's good
786 * enough to synchronize slowly diverging time sources and thus
787 * it's good enough for tracing:
789 static DEFINE_SPINLOCK(time_sync_lock
);
790 static unsigned long long prev_global_time
;
792 static unsigned long long __sync_cpu_clock(unsigned long long time
, int cpu
)
795 * We want this inlined, to not get tracer function calls
796 * in this critical section:
798 spin_acquire(&time_sync_lock
.dep_map
, 0, 0, _THIS_IP_
);
799 __raw_spin_lock(&time_sync_lock
.raw_lock
);
801 if (time
< prev_global_time
) {
802 per_cpu(time_offset
, cpu
) += prev_global_time
- time
;
803 time
= prev_global_time
;
805 prev_global_time
= time
;
808 __raw_spin_unlock(&time_sync_lock
.raw_lock
);
809 spin_release(&time_sync_lock
.dep_map
, 1, _THIS_IP_
);
814 static unsigned long long __cpu_clock(int cpu
)
816 unsigned long long now
;
819 * Only call sched_clock() if the scheduler has already been
820 * initialized (some code might call cpu_clock() very early):
822 if (unlikely(!scheduler_running
))
825 now
= sched_clock_cpu(cpu
);
831 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
832 * clock constructed from sched_clock():
834 unsigned long long cpu_clock(int cpu
)
836 unsigned long long prev_cpu_time
, time
, delta_time
;
839 local_irq_save(flags
);
840 prev_cpu_time
= per_cpu(prev_cpu_time
, cpu
);
841 time
= __cpu_clock(cpu
) + per_cpu(time_offset
, cpu
);
842 delta_time
= time
-prev_cpu_time
;
844 if (unlikely(delta_time
> time_sync_thresh
)) {
845 time
= __sync_cpu_clock(time
, cpu
);
846 per_cpu(prev_cpu_time
, cpu
) = time
;
848 local_irq_restore(flags
);
852 EXPORT_SYMBOL_GPL(cpu_clock
);
854 #ifndef prepare_arch_switch
855 # define prepare_arch_switch(next) do { } while (0)
857 #ifndef finish_arch_switch
858 # define finish_arch_switch(prev) do { } while (0)
861 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
863 return rq
->curr
== p
;
866 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
867 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
869 return task_current(rq
, p
);
872 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
876 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
878 #ifdef CONFIG_DEBUG_SPINLOCK
879 /* this is a valid case when another task releases the spinlock */
880 rq
->lock
.owner
= current
;
883 * If we are tracking spinlock dependencies then we have to
884 * fix up the runqueue lock - which gets 'carried over' from
887 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
889 spin_unlock_irq(&rq
->lock
);
892 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
893 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
898 return task_current(rq
, p
);
902 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
906 * We can optimise this out completely for !SMP, because the
907 * SMP rebalancing from interrupt is the only thing that cares
912 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
913 spin_unlock_irq(&rq
->lock
);
915 spin_unlock(&rq
->lock
);
919 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
923 * After ->oncpu is cleared, the task can be moved to a different CPU.
924 * We must ensure this doesn't happen until the switch is completely
930 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
934 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
937 * __task_rq_lock - lock the runqueue a given task resides on.
938 * Must be called interrupts disabled.
940 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
944 struct rq
*rq
= task_rq(p
);
945 spin_lock(&rq
->lock
);
946 if (likely(rq
== task_rq(p
)))
948 spin_unlock(&rq
->lock
);
953 * task_rq_lock - lock the runqueue a given task resides on and disable
954 * interrupts. Note the ordering: we can safely lookup the task_rq without
955 * explicitly disabling preemption.
957 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
963 local_irq_save(*flags
);
965 spin_lock(&rq
->lock
);
966 if (likely(rq
== task_rq(p
)))
968 spin_unlock_irqrestore(&rq
->lock
, *flags
);
972 static void __task_rq_unlock(struct rq
*rq
)
975 spin_unlock(&rq
->lock
);
978 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
981 spin_unlock_irqrestore(&rq
->lock
, *flags
);
985 * this_rq_lock - lock this runqueue and disable interrupts.
987 static struct rq
*this_rq_lock(void)
994 spin_lock(&rq
->lock
);
999 static void __resched_task(struct task_struct
*p
, int tif_bit
);
1001 static inline void resched_task(struct task_struct
*p
)
1003 __resched_task(p
, TIF_NEED_RESCHED
);
1006 #ifdef CONFIG_SCHED_HRTICK
1008 * Use HR-timers to deliver accurate preemption points.
1010 * Its all a bit involved since we cannot program an hrt while holding the
1011 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1014 * When we get rescheduled we reprogram the hrtick_timer outside of the
1017 static inline void resched_hrt(struct task_struct
*p
)
1019 __resched_task(p
, TIF_HRTICK_RESCHED
);
1022 static inline void resched_rq(struct rq
*rq
)
1024 unsigned long flags
;
1026 spin_lock_irqsave(&rq
->lock
, flags
);
1027 resched_task(rq
->curr
);
1028 spin_unlock_irqrestore(&rq
->lock
, flags
);
1032 HRTICK_SET
, /* re-programm hrtick_timer */
1033 HRTICK_RESET
, /* not a new slice */
1034 HRTICK_BLOCK
, /* stop hrtick operations */
1039 * - enabled by features
1040 * - hrtimer is actually high res
1042 static inline int hrtick_enabled(struct rq
*rq
)
1044 if (!sched_feat(HRTICK
))
1046 if (unlikely(test_bit(HRTICK_BLOCK
, &rq
->hrtick_flags
)))
1048 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
1052 * Called to set the hrtick timer state.
1054 * called with rq->lock held and irqs disabled
1056 static void hrtick_start(struct rq
*rq
, u64 delay
, int reset
)
1058 assert_spin_locked(&rq
->lock
);
1061 * preempt at: now + delay
1064 ktime_add_ns(rq
->hrtick_timer
.base
->get_time(), delay
);
1066 * indicate we need to program the timer
1068 __set_bit(HRTICK_SET
, &rq
->hrtick_flags
);
1070 __set_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
1073 * New slices are called from the schedule path and don't need a
1074 * forced reschedule.
1077 resched_hrt(rq
->curr
);
1080 static void hrtick_clear(struct rq
*rq
)
1082 if (hrtimer_active(&rq
->hrtick_timer
))
1083 hrtimer_cancel(&rq
->hrtick_timer
);
1087 * Update the timer from the possible pending state.
1089 static void hrtick_set(struct rq
*rq
)
1093 unsigned long flags
;
1095 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1097 spin_lock_irqsave(&rq
->lock
, flags
);
1098 set
= __test_and_clear_bit(HRTICK_SET
, &rq
->hrtick_flags
);
1099 reset
= __test_and_clear_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
1100 time
= rq
->hrtick_expire
;
1101 clear_thread_flag(TIF_HRTICK_RESCHED
);
1102 spin_unlock_irqrestore(&rq
->lock
, flags
);
1105 hrtimer_start(&rq
->hrtick_timer
, time
, HRTIMER_MODE_ABS
);
1106 if (reset
&& !hrtimer_active(&rq
->hrtick_timer
))
1113 * High-resolution timer tick.
1114 * Runs from hardirq context with interrupts disabled.
1116 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
1118 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
1120 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1122 spin_lock(&rq
->lock
);
1123 update_rq_clock(rq
);
1124 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
1125 spin_unlock(&rq
->lock
);
1127 return HRTIMER_NORESTART
;
1130 static void hotplug_hrtick_disable(int cpu
)
1132 struct rq
*rq
= cpu_rq(cpu
);
1133 unsigned long flags
;
1135 spin_lock_irqsave(&rq
->lock
, flags
);
1136 rq
->hrtick_flags
= 0;
1137 __set_bit(HRTICK_BLOCK
, &rq
->hrtick_flags
);
1138 spin_unlock_irqrestore(&rq
->lock
, flags
);
1143 static void hotplug_hrtick_enable(int cpu
)
1145 struct rq
*rq
= cpu_rq(cpu
);
1146 unsigned long flags
;
1148 spin_lock_irqsave(&rq
->lock
, flags
);
1149 __clear_bit(HRTICK_BLOCK
, &rq
->hrtick_flags
);
1150 spin_unlock_irqrestore(&rq
->lock
, flags
);
1154 hotplug_hrtick(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
1156 int cpu
= (int)(long)hcpu
;
1159 case CPU_UP_CANCELED
:
1160 case CPU_UP_CANCELED_FROZEN
:
1161 case CPU_DOWN_PREPARE
:
1162 case CPU_DOWN_PREPARE_FROZEN
:
1164 case CPU_DEAD_FROZEN
:
1165 hotplug_hrtick_disable(cpu
);
1168 case CPU_UP_PREPARE
:
1169 case CPU_UP_PREPARE_FROZEN
:
1170 case CPU_DOWN_FAILED
:
1171 case CPU_DOWN_FAILED_FROZEN
:
1173 case CPU_ONLINE_FROZEN
:
1174 hotplug_hrtick_enable(cpu
);
1181 static void init_hrtick(void)
1183 hotcpu_notifier(hotplug_hrtick
, 0);
1186 static void init_rq_hrtick(struct rq
*rq
)
1188 rq
->hrtick_flags
= 0;
1189 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1190 rq
->hrtick_timer
.function
= hrtick
;
1191 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
1194 void hrtick_resched(void)
1197 unsigned long flags
;
1199 if (!test_thread_flag(TIF_HRTICK_RESCHED
))
1202 local_irq_save(flags
);
1203 rq
= cpu_rq(smp_processor_id());
1205 local_irq_restore(flags
);
1208 static inline void hrtick_clear(struct rq
*rq
)
1212 static inline void hrtick_set(struct rq
*rq
)
1216 static inline void init_rq_hrtick(struct rq
*rq
)
1220 void hrtick_resched(void)
1224 static inline void init_hrtick(void)
1230 * resched_task - mark a task 'to be rescheduled now'.
1232 * On UP this means the setting of the need_resched flag, on SMP it
1233 * might also involve a cross-CPU call to trigger the scheduler on
1238 #ifndef tsk_is_polling
1239 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1242 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1246 assert_spin_locked(&task_rq(p
)->lock
);
1248 if (unlikely(test_tsk_thread_flag(p
, tif_bit
)))
1251 set_tsk_thread_flag(p
, tif_bit
);
1254 if (cpu
== smp_processor_id())
1257 /* NEED_RESCHED must be visible before we test polling */
1259 if (!tsk_is_polling(p
))
1260 smp_send_reschedule(cpu
);
1263 static void resched_cpu(int cpu
)
1265 struct rq
*rq
= cpu_rq(cpu
);
1266 unsigned long flags
;
1268 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1270 resched_task(cpu_curr(cpu
));
1271 spin_unlock_irqrestore(&rq
->lock
, flags
);
1276 * When add_timer_on() enqueues a timer into the timer wheel of an
1277 * idle CPU then this timer might expire before the next timer event
1278 * which is scheduled to wake up that CPU. In case of a completely
1279 * idle system the next event might even be infinite time into the
1280 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1281 * leaves the inner idle loop so the newly added timer is taken into
1282 * account when the CPU goes back to idle and evaluates the timer
1283 * wheel for the next timer event.
1285 void wake_up_idle_cpu(int cpu
)
1287 struct rq
*rq
= cpu_rq(cpu
);
1289 if (cpu
== smp_processor_id())
1293 * This is safe, as this function is called with the timer
1294 * wheel base lock of (cpu) held. When the CPU is on the way
1295 * to idle and has not yet set rq->curr to idle then it will
1296 * be serialized on the timer wheel base lock and take the new
1297 * timer into account automatically.
1299 if (rq
->curr
!= rq
->idle
)
1303 * We can set TIF_RESCHED on the idle task of the other CPU
1304 * lockless. The worst case is that the other CPU runs the
1305 * idle task through an additional NOOP schedule()
1307 set_tsk_thread_flag(rq
->idle
, TIF_NEED_RESCHED
);
1309 /* NEED_RESCHED must be visible before we test polling */
1311 if (!tsk_is_polling(rq
->idle
))
1312 smp_send_reschedule(cpu
);
1317 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1319 assert_spin_locked(&task_rq(p
)->lock
);
1320 set_tsk_thread_flag(p
, tif_bit
);
1324 #if BITS_PER_LONG == 32
1325 # define WMULT_CONST (~0UL)
1327 # define WMULT_CONST (1UL << 32)
1330 #define WMULT_SHIFT 32
1333 * Shift right and round:
1335 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1337 static unsigned long
1338 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1339 struct load_weight
*lw
)
1343 if (!lw
->inv_weight
)
1344 lw
->inv_weight
= 1 + (WMULT_CONST
-lw
->weight
/2)/(lw
->weight
+1);
1346 tmp
= (u64
)delta_exec
* weight
;
1348 * Check whether we'd overflow the 64-bit multiplication:
1350 if (unlikely(tmp
> WMULT_CONST
))
1351 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1354 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1356 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1359 static inline unsigned long
1360 calc_delta_fair(unsigned long delta_exec
, struct load_weight
*lw
)
1362 return calc_delta_mine(delta_exec
, NICE_0_LOAD
, lw
);
1365 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1371 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1378 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1379 * of tasks with abnormal "nice" values across CPUs the contribution that
1380 * each task makes to its run queue's load is weighted according to its
1381 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1382 * scaled version of the new time slice allocation that they receive on time
1386 #define WEIGHT_IDLEPRIO 2
1387 #define WMULT_IDLEPRIO (1 << 31)
1390 * Nice levels are multiplicative, with a gentle 10% change for every
1391 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1392 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1393 * that remained on nice 0.
1395 * The "10% effect" is relative and cumulative: from _any_ nice level,
1396 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1397 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1398 * If a task goes up by ~10% and another task goes down by ~10% then
1399 * the relative distance between them is ~25%.)
1401 static const int prio_to_weight
[40] = {
1402 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1403 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1404 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1405 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1406 /* 0 */ 1024, 820, 655, 526, 423,
1407 /* 5 */ 335, 272, 215, 172, 137,
1408 /* 10 */ 110, 87, 70, 56, 45,
1409 /* 15 */ 36, 29, 23, 18, 15,
1413 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1415 * In cases where the weight does not change often, we can use the
1416 * precalculated inverse to speed up arithmetics by turning divisions
1417 * into multiplications:
1419 static const u32 prio_to_wmult
[40] = {
1420 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1421 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1422 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1423 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1424 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1425 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1426 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1427 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1430 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1433 * runqueue iterator, to support SMP load-balancing between different
1434 * scheduling classes, without having to expose their internal data
1435 * structures to the load-balancing proper:
1437 struct rq_iterator
{
1439 struct task_struct
*(*start
)(void *);
1440 struct task_struct
*(*next
)(void *);
1444 static unsigned long
1445 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1446 unsigned long max_load_move
, struct sched_domain
*sd
,
1447 enum cpu_idle_type idle
, int *all_pinned
,
1448 int *this_best_prio
, struct rq_iterator
*iterator
);
1451 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1452 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1453 struct rq_iterator
*iterator
);
1456 #ifdef CONFIG_CGROUP_CPUACCT
1457 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1459 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1462 static inline void inc_cpu_load(struct rq
*rq
, unsigned long load
)
1464 update_load_add(&rq
->load
, load
);
1467 static inline void dec_cpu_load(struct rq
*rq
, unsigned long load
)
1469 update_load_sub(&rq
->load
, load
);
1473 static unsigned long source_load(int cpu
, int type
);
1474 static unsigned long target_load(int cpu
, int type
);
1475 static unsigned long cpu_avg_load_per_task(int cpu
);
1476 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1477 #else /* CONFIG_SMP */
1479 #ifdef CONFIG_FAIR_GROUP_SCHED
1480 static void cfs_rq_set_shares(struct cfs_rq
*cfs_rq
, unsigned long shares
)
1485 #endif /* CONFIG_SMP */
1487 #include "sched_stats.h"
1488 #include "sched_idletask.c"
1489 #include "sched_fair.c"
1490 #include "sched_rt.c"
1491 #ifdef CONFIG_SCHED_DEBUG
1492 # include "sched_debug.c"
1495 #define sched_class_highest (&rt_sched_class)
1497 static inline void inc_load(struct rq
*rq
, const struct task_struct
*p
)
1499 update_load_add(&rq
->load
, p
->se
.load
.weight
);
1502 static inline void dec_load(struct rq
*rq
, const struct task_struct
*p
)
1504 update_load_sub(&rq
->load
, p
->se
.load
.weight
);
1507 static void inc_nr_running(struct task_struct
*p
, struct rq
*rq
)
1513 static void dec_nr_running(struct task_struct
*p
, struct rq
*rq
)
1519 static void set_load_weight(struct task_struct
*p
)
1521 if (task_has_rt_policy(p
)) {
1522 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1523 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1528 * SCHED_IDLE tasks get minimal weight:
1530 if (p
->policy
== SCHED_IDLE
) {
1531 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1532 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1536 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1537 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1540 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1542 sched_info_queued(p
);
1543 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1547 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1549 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1554 * __normal_prio - return the priority that is based on the static prio
1556 static inline int __normal_prio(struct task_struct
*p
)
1558 return p
->static_prio
;
1562 * Calculate the expected normal priority: i.e. priority
1563 * without taking RT-inheritance into account. Might be
1564 * boosted by interactivity modifiers. Changes upon fork,
1565 * setprio syscalls, and whenever the interactivity
1566 * estimator recalculates.
1568 static inline int normal_prio(struct task_struct
*p
)
1572 if (task_has_rt_policy(p
))
1573 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1575 prio
= __normal_prio(p
);
1580 * Calculate the current priority, i.e. the priority
1581 * taken into account by the scheduler. This value might
1582 * be boosted by RT tasks, or might be boosted by
1583 * interactivity modifiers. Will be RT if the task got
1584 * RT-boosted. If not then it returns p->normal_prio.
1586 static int effective_prio(struct task_struct
*p
)
1588 p
->normal_prio
= normal_prio(p
);
1590 * If we are RT tasks or we were boosted to RT priority,
1591 * keep the priority unchanged. Otherwise, update priority
1592 * to the normal priority:
1594 if (!rt_prio(p
->prio
))
1595 return p
->normal_prio
;
1600 * activate_task - move a task to the runqueue.
1602 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1604 if (task_contributes_to_load(p
))
1605 rq
->nr_uninterruptible
--;
1607 enqueue_task(rq
, p
, wakeup
);
1608 inc_nr_running(p
, rq
);
1612 * deactivate_task - remove a task from the runqueue.
1614 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1616 if (task_contributes_to_load(p
))
1617 rq
->nr_uninterruptible
++;
1619 dequeue_task(rq
, p
, sleep
);
1620 dec_nr_running(p
, rq
);
1624 * task_curr - is this task currently executing on a CPU?
1625 * @p: the task in question.
1627 inline int task_curr(const struct task_struct
*p
)
1629 return cpu_curr(task_cpu(p
)) == p
;
1632 /* Used instead of source_load when we know the type == 0 */
1633 unsigned long weighted_cpuload(const int cpu
)
1635 return cpu_rq(cpu
)->load
.weight
;
1638 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1640 set_task_rq(p
, cpu
);
1643 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1644 * successfuly executed on another CPU. We must ensure that updates of
1645 * per-task data have been completed by this moment.
1648 task_thread_info(p
)->cpu
= cpu
;
1652 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1653 const struct sched_class
*prev_class
,
1654 int oldprio
, int running
)
1656 if (prev_class
!= p
->sched_class
) {
1657 if (prev_class
->switched_from
)
1658 prev_class
->switched_from(rq
, p
, running
);
1659 p
->sched_class
->switched_to(rq
, p
, running
);
1661 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1667 * Is this task likely cache-hot:
1670 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
1675 * Buddy candidates are cache hot:
1677 if (sched_feat(CACHE_HOT_BUDDY
) && (&p
->se
== cfs_rq_of(&p
->se
)->next
))
1680 if (p
->sched_class
!= &fair_sched_class
)
1683 if (sysctl_sched_migration_cost
== -1)
1685 if (sysctl_sched_migration_cost
== 0)
1688 delta
= now
- p
->se
.exec_start
;
1690 return delta
< (s64
)sysctl_sched_migration_cost
;
1694 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1696 int old_cpu
= task_cpu(p
);
1697 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
1698 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
1699 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
1702 clock_offset
= old_rq
->clock
- new_rq
->clock
;
1704 #ifdef CONFIG_SCHEDSTATS
1705 if (p
->se
.wait_start
)
1706 p
->se
.wait_start
-= clock_offset
;
1707 if (p
->se
.sleep_start
)
1708 p
->se
.sleep_start
-= clock_offset
;
1709 if (p
->se
.block_start
)
1710 p
->se
.block_start
-= clock_offset
;
1711 if (old_cpu
!= new_cpu
) {
1712 schedstat_inc(p
, se
.nr_migrations
);
1713 if (task_hot(p
, old_rq
->clock
, NULL
))
1714 schedstat_inc(p
, se
.nr_forced2_migrations
);
1717 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
1718 new_cfsrq
->min_vruntime
;
1720 __set_task_cpu(p
, new_cpu
);
1723 struct migration_req
{
1724 struct list_head list
;
1726 struct task_struct
*task
;
1729 struct completion done
;
1733 * The task's runqueue lock must be held.
1734 * Returns true if you have to wait for migration thread.
1737 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1739 struct rq
*rq
= task_rq(p
);
1742 * If the task is not on a runqueue (and not running), then
1743 * it is sufficient to simply update the task's cpu field.
1745 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
1746 set_task_cpu(p
, dest_cpu
);
1750 init_completion(&req
->done
);
1752 req
->dest_cpu
= dest_cpu
;
1753 list_add(&req
->list
, &rq
->migration_queue
);
1759 * wait_task_inactive - wait for a thread to unschedule.
1761 * The caller must ensure that the task *will* unschedule sometime soon,
1762 * else this function might spin for a *long* time. This function can't
1763 * be called with interrupts off, or it may introduce deadlock with
1764 * smp_call_function() if an IPI is sent by the same process we are
1765 * waiting to become inactive.
1767 void wait_task_inactive(struct task_struct
*p
)
1769 unsigned long flags
;
1775 * We do the initial early heuristics without holding
1776 * any task-queue locks at all. We'll only try to get
1777 * the runqueue lock when things look like they will
1783 * If the task is actively running on another CPU
1784 * still, just relax and busy-wait without holding
1787 * NOTE! Since we don't hold any locks, it's not
1788 * even sure that "rq" stays as the right runqueue!
1789 * But we don't care, since "task_running()" will
1790 * return false if the runqueue has changed and p
1791 * is actually now running somewhere else!
1793 while (task_running(rq
, p
))
1797 * Ok, time to look more closely! We need the rq
1798 * lock now, to be *sure*. If we're wrong, we'll
1799 * just go back and repeat.
1801 rq
= task_rq_lock(p
, &flags
);
1802 running
= task_running(rq
, p
);
1803 on_rq
= p
->se
.on_rq
;
1804 task_rq_unlock(rq
, &flags
);
1807 * Was it really running after all now that we
1808 * checked with the proper locks actually held?
1810 * Oops. Go back and try again..
1812 if (unlikely(running
)) {
1818 * It's not enough that it's not actively running,
1819 * it must be off the runqueue _entirely_, and not
1822 * So if it wa still runnable (but just not actively
1823 * running right now), it's preempted, and we should
1824 * yield - it could be a while.
1826 if (unlikely(on_rq
)) {
1827 schedule_timeout_uninterruptible(1);
1832 * Ahh, all good. It wasn't running, and it wasn't
1833 * runnable, which means that it will never become
1834 * running in the future either. We're all done!
1841 * kick_process - kick a running thread to enter/exit the kernel
1842 * @p: the to-be-kicked thread
1844 * Cause a process which is running on another CPU to enter
1845 * kernel-mode, without any delay. (to get signals handled.)
1847 * NOTE: this function doesnt have to take the runqueue lock,
1848 * because all it wants to ensure is that the remote task enters
1849 * the kernel. If the IPI races and the task has been migrated
1850 * to another CPU then no harm is done and the purpose has been
1853 void kick_process(struct task_struct
*p
)
1859 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1860 smp_send_reschedule(cpu
);
1865 * Return a low guess at the load of a migration-source cpu weighted
1866 * according to the scheduling class and "nice" value.
1868 * We want to under-estimate the load of migration sources, to
1869 * balance conservatively.
1871 static unsigned long source_load(int cpu
, int type
)
1873 struct rq
*rq
= cpu_rq(cpu
);
1874 unsigned long total
= weighted_cpuload(cpu
);
1879 return min(rq
->cpu_load
[type
-1], total
);
1883 * Return a high guess at the load of a migration-target cpu weighted
1884 * according to the scheduling class and "nice" value.
1886 static unsigned long target_load(int cpu
, int type
)
1888 struct rq
*rq
= cpu_rq(cpu
);
1889 unsigned long total
= weighted_cpuload(cpu
);
1894 return max(rq
->cpu_load
[type
-1], total
);
1898 * Return the average load per task on the cpu's run queue
1900 static unsigned long cpu_avg_load_per_task(int cpu
)
1902 struct rq
*rq
= cpu_rq(cpu
);
1903 unsigned long total
= weighted_cpuload(cpu
);
1904 unsigned long n
= rq
->nr_running
;
1906 return n
? total
/ n
: SCHED_LOAD_SCALE
;
1910 * find_idlest_group finds and returns the least busy CPU group within the
1913 static struct sched_group
*
1914 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1916 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1917 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1918 int load_idx
= sd
->forkexec_idx
;
1919 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1922 unsigned long load
, avg_load
;
1926 /* Skip over this group if it has no CPUs allowed */
1927 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1930 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1932 /* Tally up the load of all CPUs in the group */
1935 for_each_cpu_mask(i
, group
->cpumask
) {
1936 /* Bias balancing toward cpus of our domain */
1938 load
= source_load(i
, load_idx
);
1940 load
= target_load(i
, load_idx
);
1945 /* Adjust by relative CPU power of the group */
1946 avg_load
= sg_div_cpu_power(group
,
1947 avg_load
* SCHED_LOAD_SCALE
);
1950 this_load
= avg_load
;
1952 } else if (avg_load
< min_load
) {
1953 min_load
= avg_load
;
1956 } while (group
= group
->next
, group
!= sd
->groups
);
1958 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1964 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1967 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
,
1970 unsigned long load
, min_load
= ULONG_MAX
;
1974 /* Traverse only the allowed CPUs */
1975 cpus_and(*tmp
, group
->cpumask
, p
->cpus_allowed
);
1977 for_each_cpu_mask(i
, *tmp
) {
1978 load
= weighted_cpuload(i
);
1980 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1990 * sched_balance_self: balance the current task (running on cpu) in domains
1991 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1994 * Balance, ie. select the least loaded group.
1996 * Returns the target CPU number, or the same CPU if no balancing is needed.
1998 * preempt must be disabled.
2000 static int sched_balance_self(int cpu
, int flag
)
2002 struct task_struct
*t
= current
;
2003 struct sched_domain
*tmp
, *sd
= NULL
;
2005 for_each_domain(cpu
, tmp
) {
2007 * If power savings logic is enabled for a domain, stop there.
2009 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
2011 if (tmp
->flags
& flag
)
2016 cpumask_t span
, tmpmask
;
2017 struct sched_group
*group
;
2018 int new_cpu
, weight
;
2020 if (!(sd
->flags
& flag
)) {
2026 group
= find_idlest_group(sd
, t
, cpu
);
2032 new_cpu
= find_idlest_cpu(group
, t
, cpu
, &tmpmask
);
2033 if (new_cpu
== -1 || new_cpu
== cpu
) {
2034 /* Now try balancing at a lower domain level of cpu */
2039 /* Now try balancing at a lower domain level of new_cpu */
2042 weight
= cpus_weight(span
);
2043 for_each_domain(cpu
, tmp
) {
2044 if (weight
<= cpus_weight(tmp
->span
))
2046 if (tmp
->flags
& flag
)
2049 /* while loop will break here if sd == NULL */
2055 #endif /* CONFIG_SMP */
2058 * try_to_wake_up - wake up a thread
2059 * @p: the to-be-woken-up thread
2060 * @state: the mask of task states that can be woken
2061 * @sync: do a synchronous wakeup?
2063 * Put it on the run-queue if it's not already there. The "current"
2064 * thread is always on the run-queue (except when the actual
2065 * re-schedule is in progress), and as such you're allowed to do
2066 * the simpler "current->state = TASK_RUNNING" to mark yourself
2067 * runnable without the overhead of this.
2069 * returns failure only if the task is already active.
2071 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
2073 int cpu
, orig_cpu
, this_cpu
, success
= 0;
2074 unsigned long flags
;
2078 if (!sched_feat(SYNC_WAKEUPS
))
2082 rq
= task_rq_lock(p
, &flags
);
2083 old_state
= p
->state
;
2084 if (!(old_state
& state
))
2092 this_cpu
= smp_processor_id();
2095 if (unlikely(task_running(rq
, p
)))
2098 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
2099 if (cpu
!= orig_cpu
) {
2100 set_task_cpu(p
, cpu
);
2101 task_rq_unlock(rq
, &flags
);
2102 /* might preempt at this point */
2103 rq
= task_rq_lock(p
, &flags
);
2104 old_state
= p
->state
;
2105 if (!(old_state
& state
))
2110 this_cpu
= smp_processor_id();
2114 #ifdef CONFIG_SCHEDSTATS
2115 schedstat_inc(rq
, ttwu_count
);
2116 if (cpu
== this_cpu
)
2117 schedstat_inc(rq
, ttwu_local
);
2119 struct sched_domain
*sd
;
2120 for_each_domain(this_cpu
, sd
) {
2121 if (cpu_isset(cpu
, sd
->span
)) {
2122 schedstat_inc(sd
, ttwu_wake_remote
);
2130 #endif /* CONFIG_SMP */
2131 schedstat_inc(p
, se
.nr_wakeups
);
2133 schedstat_inc(p
, se
.nr_wakeups_sync
);
2134 if (orig_cpu
!= cpu
)
2135 schedstat_inc(p
, se
.nr_wakeups_migrate
);
2136 if (cpu
== this_cpu
)
2137 schedstat_inc(p
, se
.nr_wakeups_local
);
2139 schedstat_inc(p
, se
.nr_wakeups_remote
);
2140 update_rq_clock(rq
);
2141 activate_task(rq
, p
, 1);
2145 check_preempt_curr(rq
, p
);
2147 p
->state
= TASK_RUNNING
;
2149 if (p
->sched_class
->task_wake_up
)
2150 p
->sched_class
->task_wake_up(rq
, p
);
2153 task_rq_unlock(rq
, &flags
);
2158 int wake_up_process(struct task_struct
*p
)
2160 return try_to_wake_up(p
, TASK_ALL
, 0);
2162 EXPORT_SYMBOL(wake_up_process
);
2164 int wake_up_state(struct task_struct
*p
, unsigned int state
)
2166 return try_to_wake_up(p
, state
, 0);
2170 * Perform scheduler related setup for a newly forked process p.
2171 * p is forked by current.
2173 * __sched_fork() is basic setup used by init_idle() too:
2175 static void __sched_fork(struct task_struct
*p
)
2177 p
->se
.exec_start
= 0;
2178 p
->se
.sum_exec_runtime
= 0;
2179 p
->se
.prev_sum_exec_runtime
= 0;
2180 p
->se
.last_wakeup
= 0;
2181 p
->se
.avg_overlap
= 0;
2183 #ifdef CONFIG_SCHEDSTATS
2184 p
->se
.wait_start
= 0;
2185 p
->se
.sum_sleep_runtime
= 0;
2186 p
->se
.sleep_start
= 0;
2187 p
->se
.block_start
= 0;
2188 p
->se
.sleep_max
= 0;
2189 p
->se
.block_max
= 0;
2191 p
->se
.slice_max
= 0;
2195 INIT_LIST_HEAD(&p
->rt
.run_list
);
2197 INIT_LIST_HEAD(&p
->se
.group_node
);
2199 #ifdef CONFIG_PREEMPT_NOTIFIERS
2200 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
2204 * We mark the process as running here, but have not actually
2205 * inserted it onto the runqueue yet. This guarantees that
2206 * nobody will actually run it, and a signal or other external
2207 * event cannot wake it up and insert it on the runqueue either.
2209 p
->state
= TASK_RUNNING
;
2213 * fork()/clone()-time setup:
2215 void sched_fork(struct task_struct
*p
, int clone_flags
)
2217 int cpu
= get_cpu();
2222 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
2224 set_task_cpu(p
, cpu
);
2227 * Make sure we do not leak PI boosting priority to the child:
2229 p
->prio
= current
->normal_prio
;
2230 if (!rt_prio(p
->prio
))
2231 p
->sched_class
= &fair_sched_class
;
2233 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2234 if (likely(sched_info_on()))
2235 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
2237 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2240 #ifdef CONFIG_PREEMPT
2241 /* Want to start with kernel preemption disabled. */
2242 task_thread_info(p
)->preempt_count
= 1;
2248 * wake_up_new_task - wake up a newly created task for the first time.
2250 * This function will do some initial scheduler statistics housekeeping
2251 * that must be done for every newly created context, then puts the task
2252 * on the runqueue and wakes it.
2254 void wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
2256 unsigned long flags
;
2259 rq
= task_rq_lock(p
, &flags
);
2260 BUG_ON(p
->state
!= TASK_RUNNING
);
2261 update_rq_clock(rq
);
2263 p
->prio
= effective_prio(p
);
2265 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
2266 activate_task(rq
, p
, 0);
2269 * Let the scheduling class do new task startup
2270 * management (if any):
2272 p
->sched_class
->task_new(rq
, p
);
2273 inc_nr_running(p
, rq
);
2275 check_preempt_curr(rq
, p
);
2277 if (p
->sched_class
->task_wake_up
)
2278 p
->sched_class
->task_wake_up(rq
, p
);
2280 task_rq_unlock(rq
, &flags
);
2283 #ifdef CONFIG_PREEMPT_NOTIFIERS
2286 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2287 * @notifier: notifier struct to register
2289 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2291 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2293 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2296 * preempt_notifier_unregister - no longer interested in preemption notifications
2297 * @notifier: notifier struct to unregister
2299 * This is safe to call from within a preemption notifier.
2301 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2303 hlist_del(¬ifier
->link
);
2305 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2307 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2309 struct preempt_notifier
*notifier
;
2310 struct hlist_node
*node
;
2312 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2313 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2317 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2318 struct task_struct
*next
)
2320 struct preempt_notifier
*notifier
;
2321 struct hlist_node
*node
;
2323 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2324 notifier
->ops
->sched_out(notifier
, next
);
2329 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2334 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2335 struct task_struct
*next
)
2342 * prepare_task_switch - prepare to switch tasks
2343 * @rq: the runqueue preparing to switch
2344 * @prev: the current task that is being switched out
2345 * @next: the task we are going to switch to.
2347 * This is called with the rq lock held and interrupts off. It must
2348 * be paired with a subsequent finish_task_switch after the context
2351 * prepare_task_switch sets up locking and calls architecture specific
2355 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2356 struct task_struct
*next
)
2358 fire_sched_out_preempt_notifiers(prev
, next
);
2359 prepare_lock_switch(rq
, next
);
2360 prepare_arch_switch(next
);
2364 * finish_task_switch - clean up after a task-switch
2365 * @rq: runqueue associated with task-switch
2366 * @prev: the thread we just switched away from.
2368 * finish_task_switch must be called after the context switch, paired
2369 * with a prepare_task_switch call before the context switch.
2370 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2371 * and do any other architecture-specific cleanup actions.
2373 * Note that we may have delayed dropping an mm in context_switch(). If
2374 * so, we finish that here outside of the runqueue lock. (Doing it
2375 * with the lock held can cause deadlocks; see schedule() for
2378 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2379 __releases(rq
->lock
)
2381 struct mm_struct
*mm
= rq
->prev_mm
;
2387 * A task struct has one reference for the use as "current".
2388 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2389 * schedule one last time. The schedule call will never return, and
2390 * the scheduled task must drop that reference.
2391 * The test for TASK_DEAD must occur while the runqueue locks are
2392 * still held, otherwise prev could be scheduled on another cpu, die
2393 * there before we look at prev->state, and then the reference would
2395 * Manfred Spraul <manfred@colorfullife.com>
2397 prev_state
= prev
->state
;
2398 finish_arch_switch(prev
);
2399 finish_lock_switch(rq
, prev
);
2401 if (current
->sched_class
->post_schedule
)
2402 current
->sched_class
->post_schedule(rq
);
2405 fire_sched_in_preempt_notifiers(current
);
2408 if (unlikely(prev_state
== TASK_DEAD
)) {
2410 * Remove function-return probe instances associated with this
2411 * task and put them back on the free list.
2413 kprobe_flush_task(prev
);
2414 put_task_struct(prev
);
2419 * schedule_tail - first thing a freshly forked thread must call.
2420 * @prev: the thread we just switched away from.
2422 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2423 __releases(rq
->lock
)
2425 struct rq
*rq
= this_rq();
2427 finish_task_switch(rq
, prev
);
2428 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2429 /* In this case, finish_task_switch does not reenable preemption */
2432 if (current
->set_child_tid
)
2433 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2437 * context_switch - switch to the new MM and the new
2438 * thread's register state.
2441 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2442 struct task_struct
*next
)
2444 struct mm_struct
*mm
, *oldmm
;
2446 prepare_task_switch(rq
, prev
, next
);
2448 oldmm
= prev
->active_mm
;
2450 * For paravirt, this is coupled with an exit in switch_to to
2451 * combine the page table reload and the switch backend into
2454 arch_enter_lazy_cpu_mode();
2456 if (unlikely(!mm
)) {
2457 next
->active_mm
= oldmm
;
2458 atomic_inc(&oldmm
->mm_count
);
2459 enter_lazy_tlb(oldmm
, next
);
2461 switch_mm(oldmm
, mm
, next
);
2463 if (unlikely(!prev
->mm
)) {
2464 prev
->active_mm
= NULL
;
2465 rq
->prev_mm
= oldmm
;
2468 * Since the runqueue lock will be released by the next
2469 * task (which is an invalid locking op but in the case
2470 * of the scheduler it's an obvious special-case), so we
2471 * do an early lockdep release here:
2473 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2474 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2477 /* Here we just switch the register state and the stack. */
2478 switch_to(prev
, next
, prev
);
2482 * this_rq must be evaluated again because prev may have moved
2483 * CPUs since it called schedule(), thus the 'rq' on its stack
2484 * frame will be invalid.
2486 finish_task_switch(this_rq(), prev
);
2490 * nr_running, nr_uninterruptible and nr_context_switches:
2492 * externally visible scheduler statistics: current number of runnable
2493 * threads, current number of uninterruptible-sleeping threads, total
2494 * number of context switches performed since bootup.
2496 unsigned long nr_running(void)
2498 unsigned long i
, sum
= 0;
2500 for_each_online_cpu(i
)
2501 sum
+= cpu_rq(i
)->nr_running
;
2506 unsigned long nr_uninterruptible(void)
2508 unsigned long i
, sum
= 0;
2510 for_each_possible_cpu(i
)
2511 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2514 * Since we read the counters lockless, it might be slightly
2515 * inaccurate. Do not allow it to go below zero though:
2517 if (unlikely((long)sum
< 0))
2523 unsigned long long nr_context_switches(void)
2526 unsigned long long sum
= 0;
2528 for_each_possible_cpu(i
)
2529 sum
+= cpu_rq(i
)->nr_switches
;
2534 unsigned long nr_iowait(void)
2536 unsigned long i
, sum
= 0;
2538 for_each_possible_cpu(i
)
2539 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2544 unsigned long nr_active(void)
2546 unsigned long i
, running
= 0, uninterruptible
= 0;
2548 for_each_online_cpu(i
) {
2549 running
+= cpu_rq(i
)->nr_running
;
2550 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2553 if (unlikely((long)uninterruptible
< 0))
2554 uninterruptible
= 0;
2556 return running
+ uninterruptible
;
2560 * Update rq->cpu_load[] statistics. This function is usually called every
2561 * scheduler tick (TICK_NSEC).
2563 static void update_cpu_load(struct rq
*this_rq
)
2565 unsigned long this_load
= this_rq
->load
.weight
;
2568 this_rq
->nr_load_updates
++;
2570 /* Update our load: */
2571 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2572 unsigned long old_load
, new_load
;
2574 /* scale is effectively 1 << i now, and >> i divides by scale */
2576 old_load
= this_rq
->cpu_load
[i
];
2577 new_load
= this_load
;
2579 * Round up the averaging division if load is increasing. This
2580 * prevents us from getting stuck on 9 if the load is 10, for
2583 if (new_load
> old_load
)
2584 new_load
+= scale
-1;
2585 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2592 * double_rq_lock - safely lock two runqueues
2594 * Note this does not disable interrupts like task_rq_lock,
2595 * you need to do so manually before calling.
2597 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2598 __acquires(rq1
->lock
)
2599 __acquires(rq2
->lock
)
2601 BUG_ON(!irqs_disabled());
2603 spin_lock(&rq1
->lock
);
2604 __acquire(rq2
->lock
); /* Fake it out ;) */
2607 spin_lock(&rq1
->lock
);
2608 spin_lock(&rq2
->lock
);
2610 spin_lock(&rq2
->lock
);
2611 spin_lock(&rq1
->lock
);
2614 update_rq_clock(rq1
);
2615 update_rq_clock(rq2
);
2619 * double_rq_unlock - safely unlock two runqueues
2621 * Note this does not restore interrupts like task_rq_unlock,
2622 * you need to do so manually after calling.
2624 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2625 __releases(rq1
->lock
)
2626 __releases(rq2
->lock
)
2628 spin_unlock(&rq1
->lock
);
2630 spin_unlock(&rq2
->lock
);
2632 __release(rq2
->lock
);
2636 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2638 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
2639 __releases(this_rq
->lock
)
2640 __acquires(busiest
->lock
)
2641 __acquires(this_rq
->lock
)
2645 if (unlikely(!irqs_disabled())) {
2646 /* printk() doesn't work good under rq->lock */
2647 spin_unlock(&this_rq
->lock
);
2650 if (unlikely(!spin_trylock(&busiest
->lock
))) {
2651 if (busiest
< this_rq
) {
2652 spin_unlock(&this_rq
->lock
);
2653 spin_lock(&busiest
->lock
);
2654 spin_lock(&this_rq
->lock
);
2657 spin_lock(&busiest
->lock
);
2663 * If dest_cpu is allowed for this process, migrate the task to it.
2664 * This is accomplished by forcing the cpu_allowed mask to only
2665 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2666 * the cpu_allowed mask is restored.
2668 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
2670 struct migration_req req
;
2671 unsigned long flags
;
2674 rq
= task_rq_lock(p
, &flags
);
2675 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
2676 || unlikely(cpu_is_offline(dest_cpu
)))
2679 /* force the process onto the specified CPU */
2680 if (migrate_task(p
, dest_cpu
, &req
)) {
2681 /* Need to wait for migration thread (might exit: take ref). */
2682 struct task_struct
*mt
= rq
->migration_thread
;
2684 get_task_struct(mt
);
2685 task_rq_unlock(rq
, &flags
);
2686 wake_up_process(mt
);
2687 put_task_struct(mt
);
2688 wait_for_completion(&req
.done
);
2693 task_rq_unlock(rq
, &flags
);
2697 * sched_exec - execve() is a valuable balancing opportunity, because at
2698 * this point the task has the smallest effective memory and cache footprint.
2700 void sched_exec(void)
2702 int new_cpu
, this_cpu
= get_cpu();
2703 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
2705 if (new_cpu
!= this_cpu
)
2706 sched_migrate_task(current
, new_cpu
);
2710 * pull_task - move a task from a remote runqueue to the local runqueue.
2711 * Both runqueues must be locked.
2713 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
2714 struct rq
*this_rq
, int this_cpu
)
2716 deactivate_task(src_rq
, p
, 0);
2717 set_task_cpu(p
, this_cpu
);
2718 activate_task(this_rq
, p
, 0);
2720 * Note that idle threads have a prio of MAX_PRIO, for this test
2721 * to be always true for them.
2723 check_preempt_curr(this_rq
, p
);
2727 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2730 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2731 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2735 * We do not migrate tasks that are:
2736 * 1) running (obviously), or
2737 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2738 * 3) are cache-hot on their current CPU.
2740 if (!cpu_isset(this_cpu
, p
->cpus_allowed
)) {
2741 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
2746 if (task_running(rq
, p
)) {
2747 schedstat_inc(p
, se
.nr_failed_migrations_running
);
2752 * Aggressive migration if:
2753 * 1) task is cache cold, or
2754 * 2) too many balance attempts have failed.
2757 if (!task_hot(p
, rq
->clock
, sd
) ||
2758 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
2759 #ifdef CONFIG_SCHEDSTATS
2760 if (task_hot(p
, rq
->clock
, sd
)) {
2761 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2762 schedstat_inc(p
, se
.nr_forced_migrations
);
2768 if (task_hot(p
, rq
->clock
, sd
)) {
2769 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
2775 static unsigned long
2776 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2777 unsigned long max_load_move
, struct sched_domain
*sd
,
2778 enum cpu_idle_type idle
, int *all_pinned
,
2779 int *this_best_prio
, struct rq_iterator
*iterator
)
2781 int loops
= 0, pulled
= 0, pinned
= 0, skip_for_load
;
2782 struct task_struct
*p
;
2783 long rem_load_move
= max_load_move
;
2785 if (max_load_move
== 0)
2791 * Start the load-balancing iterator:
2793 p
= iterator
->start(iterator
->arg
);
2795 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
2798 * To help distribute high priority tasks across CPUs we don't
2799 * skip a task if it will be the highest priority task (i.e. smallest
2800 * prio value) on its new queue regardless of its load weight
2802 skip_for_load
= (p
->se
.load
.weight
>> 1) > rem_load_move
+
2803 SCHED_LOAD_SCALE_FUZZ
;
2804 if ((skip_for_load
&& p
->prio
>= *this_best_prio
) ||
2805 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2806 p
= iterator
->next(iterator
->arg
);
2810 pull_task(busiest
, p
, this_rq
, this_cpu
);
2812 rem_load_move
-= p
->se
.load
.weight
;
2815 * We only want to steal up to the prescribed amount of weighted load.
2817 if (rem_load_move
> 0) {
2818 if (p
->prio
< *this_best_prio
)
2819 *this_best_prio
= p
->prio
;
2820 p
= iterator
->next(iterator
->arg
);
2825 * Right now, this is one of only two places pull_task() is called,
2826 * so we can safely collect pull_task() stats here rather than
2827 * inside pull_task().
2829 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2832 *all_pinned
= pinned
;
2834 return max_load_move
- rem_load_move
;
2838 * move_tasks tries to move up to max_load_move weighted load from busiest to
2839 * this_rq, as part of a balancing operation within domain "sd".
2840 * Returns 1 if successful and 0 otherwise.
2842 * Called with both runqueues locked.
2844 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2845 unsigned long max_load_move
,
2846 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2849 const struct sched_class
*class = sched_class_highest
;
2850 unsigned long total_load_moved
= 0;
2851 int this_best_prio
= this_rq
->curr
->prio
;
2855 class->load_balance(this_rq
, this_cpu
, busiest
,
2856 max_load_move
- total_load_moved
,
2857 sd
, idle
, all_pinned
, &this_best_prio
);
2858 class = class->next
;
2859 } while (class && max_load_move
> total_load_moved
);
2861 return total_load_moved
> 0;
2865 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2866 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2867 struct rq_iterator
*iterator
)
2869 struct task_struct
*p
= iterator
->start(iterator
->arg
);
2873 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2874 pull_task(busiest
, p
, this_rq
, this_cpu
);
2876 * Right now, this is only the second place pull_task()
2877 * is called, so we can safely collect pull_task()
2878 * stats here rather than inside pull_task().
2880 schedstat_inc(sd
, lb_gained
[idle
]);
2884 p
= iterator
->next(iterator
->arg
);
2891 * move_one_task tries to move exactly one task from busiest to this_rq, as
2892 * part of active balancing operations within "domain".
2893 * Returns 1 if successful and 0 otherwise.
2895 * Called with both runqueues locked.
2897 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2898 struct sched_domain
*sd
, enum cpu_idle_type idle
)
2900 const struct sched_class
*class;
2902 for (class = sched_class_highest
; class; class = class->next
)
2903 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
2910 * find_busiest_group finds and returns the busiest CPU group within the
2911 * domain. It calculates and returns the amount of weighted load which
2912 * should be moved to restore balance via the imbalance parameter.
2914 static struct sched_group
*
2915 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2916 unsigned long *imbalance
, enum cpu_idle_type idle
,
2917 int *sd_idle
, const cpumask_t
*cpus
, int *balance
)
2919 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2920 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2921 unsigned long max_pull
;
2922 unsigned long busiest_load_per_task
, busiest_nr_running
;
2923 unsigned long this_load_per_task
, this_nr_running
;
2924 int load_idx
, group_imb
= 0;
2925 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2926 int power_savings_balance
= 1;
2927 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2928 unsigned long min_nr_running
= ULONG_MAX
;
2929 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2932 max_load
= this_load
= total_load
= total_pwr
= 0;
2933 busiest_load_per_task
= busiest_nr_running
= 0;
2934 this_load_per_task
= this_nr_running
= 0;
2935 if (idle
== CPU_NOT_IDLE
)
2936 load_idx
= sd
->busy_idx
;
2937 else if (idle
== CPU_NEWLY_IDLE
)
2938 load_idx
= sd
->newidle_idx
;
2940 load_idx
= sd
->idle_idx
;
2943 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
2946 int __group_imb
= 0;
2947 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
2948 unsigned long sum_nr_running
, sum_weighted_load
;
2950 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2953 balance_cpu
= first_cpu(group
->cpumask
);
2955 /* Tally up the load of all CPUs in the group */
2956 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2958 min_cpu_load
= ~0UL;
2960 for_each_cpu_mask(i
, group
->cpumask
) {
2963 if (!cpu_isset(i
, *cpus
))
2968 if (*sd_idle
&& rq
->nr_running
)
2971 /* Bias balancing toward cpus of our domain */
2973 if (idle_cpu(i
) && !first_idle_cpu
) {
2978 load
= target_load(i
, load_idx
);
2980 load
= source_load(i
, load_idx
);
2981 if (load
> max_cpu_load
)
2982 max_cpu_load
= load
;
2983 if (min_cpu_load
> load
)
2984 min_cpu_load
= load
;
2988 sum_nr_running
+= rq
->nr_running
;
2989 sum_weighted_load
+= weighted_cpuload(i
);
2993 * First idle cpu or the first cpu(busiest) in this sched group
2994 * is eligible for doing load balancing at this and above
2995 * domains. In the newly idle case, we will allow all the cpu's
2996 * to do the newly idle load balance.
2998 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
2999 balance_cpu
!= this_cpu
&& balance
) {
3004 total_load
+= avg_load
;
3005 total_pwr
+= group
->__cpu_power
;
3007 /* Adjust by relative CPU power of the group */
3008 avg_load
= sg_div_cpu_power(group
,
3009 avg_load
* SCHED_LOAD_SCALE
);
3011 if ((max_cpu_load
- min_cpu_load
) > SCHED_LOAD_SCALE
)
3014 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
3017 this_load
= avg_load
;
3019 this_nr_running
= sum_nr_running
;
3020 this_load_per_task
= sum_weighted_load
;
3021 } else if (avg_load
> max_load
&&
3022 (sum_nr_running
> group_capacity
|| __group_imb
)) {
3023 max_load
= avg_load
;
3025 busiest_nr_running
= sum_nr_running
;
3026 busiest_load_per_task
= sum_weighted_load
;
3027 group_imb
= __group_imb
;
3030 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3032 * Busy processors will not participate in power savings
3035 if (idle
== CPU_NOT_IDLE
||
3036 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3040 * If the local group is idle or completely loaded
3041 * no need to do power savings balance at this domain
3043 if (local_group
&& (this_nr_running
>= group_capacity
||
3045 power_savings_balance
= 0;
3048 * If a group is already running at full capacity or idle,
3049 * don't include that group in power savings calculations
3051 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
3056 * Calculate the group which has the least non-idle load.
3057 * This is the group from where we need to pick up the load
3060 if ((sum_nr_running
< min_nr_running
) ||
3061 (sum_nr_running
== min_nr_running
&&
3062 first_cpu(group
->cpumask
) <
3063 first_cpu(group_min
->cpumask
))) {
3065 min_nr_running
= sum_nr_running
;
3066 min_load_per_task
= sum_weighted_load
/
3071 * Calculate the group which is almost near its
3072 * capacity but still has some space to pick up some load
3073 * from other group and save more power
3075 if (sum_nr_running
<= group_capacity
- 1) {
3076 if (sum_nr_running
> leader_nr_running
||
3077 (sum_nr_running
== leader_nr_running
&&
3078 first_cpu(group
->cpumask
) >
3079 first_cpu(group_leader
->cpumask
))) {
3080 group_leader
= group
;
3081 leader_nr_running
= sum_nr_running
;
3086 group
= group
->next
;
3087 } while (group
!= sd
->groups
);
3089 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
3092 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
3094 if (this_load
>= avg_load
||
3095 100*max_load
<= sd
->imbalance_pct
*this_load
)
3098 busiest_load_per_task
/= busiest_nr_running
;
3100 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
3103 * We're trying to get all the cpus to the average_load, so we don't
3104 * want to push ourselves above the average load, nor do we wish to
3105 * reduce the max loaded cpu below the average load, as either of these
3106 * actions would just result in more rebalancing later, and ping-pong
3107 * tasks around. Thus we look for the minimum possible imbalance.
3108 * Negative imbalances (*we* are more loaded than anyone else) will
3109 * be counted as no imbalance for these purposes -- we can't fix that
3110 * by pulling tasks to us. Be careful of negative numbers as they'll
3111 * appear as very large values with unsigned longs.
3113 if (max_load
<= busiest_load_per_task
)
3117 * In the presence of smp nice balancing, certain scenarios can have
3118 * max load less than avg load(as we skip the groups at or below
3119 * its cpu_power, while calculating max_load..)
3121 if (max_load
< avg_load
) {
3123 goto small_imbalance
;
3126 /* Don't want to pull so many tasks that a group would go idle */
3127 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
3129 /* How much load to actually move to equalise the imbalance */
3130 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
3131 (avg_load
- this_load
) * this->__cpu_power
)
3135 * if *imbalance is less than the average load per runnable task
3136 * there is no gaurantee that any tasks will be moved so we'll have
3137 * a think about bumping its value to force at least one task to be
3140 if (*imbalance
< busiest_load_per_task
) {
3141 unsigned long tmp
, pwr_now
, pwr_move
;
3145 pwr_move
= pwr_now
= 0;
3147 if (this_nr_running
) {
3148 this_load_per_task
/= this_nr_running
;
3149 if (busiest_load_per_task
> this_load_per_task
)
3152 this_load_per_task
= SCHED_LOAD_SCALE
;
3154 if (max_load
- this_load
+ SCHED_LOAD_SCALE_FUZZ
>=
3155 busiest_load_per_task
* imbn
) {
3156 *imbalance
= busiest_load_per_task
;
3161 * OK, we don't have enough imbalance to justify moving tasks,
3162 * however we may be able to increase total CPU power used by
3166 pwr_now
+= busiest
->__cpu_power
*
3167 min(busiest_load_per_task
, max_load
);
3168 pwr_now
+= this->__cpu_power
*
3169 min(this_load_per_task
, this_load
);
3170 pwr_now
/= SCHED_LOAD_SCALE
;
3172 /* Amount of load we'd subtract */
3173 tmp
= sg_div_cpu_power(busiest
,
3174 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3176 pwr_move
+= busiest
->__cpu_power
*
3177 min(busiest_load_per_task
, max_load
- tmp
);
3179 /* Amount of load we'd add */
3180 if (max_load
* busiest
->__cpu_power
<
3181 busiest_load_per_task
* SCHED_LOAD_SCALE
)
3182 tmp
= sg_div_cpu_power(this,
3183 max_load
* busiest
->__cpu_power
);
3185 tmp
= sg_div_cpu_power(this,
3186 busiest_load_per_task
* SCHED_LOAD_SCALE
);
3187 pwr_move
+= this->__cpu_power
*
3188 min(this_load_per_task
, this_load
+ tmp
);
3189 pwr_move
/= SCHED_LOAD_SCALE
;
3191 /* Move if we gain throughput */
3192 if (pwr_move
> pwr_now
)
3193 *imbalance
= busiest_load_per_task
;
3199 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3200 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3203 if (this == group_leader
&& group_leader
!= group_min
) {
3204 *imbalance
= min_load_per_task
;
3214 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3217 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
3218 unsigned long imbalance
, const cpumask_t
*cpus
)
3220 struct rq
*busiest
= NULL
, *rq
;
3221 unsigned long max_load
= 0;
3224 for_each_cpu_mask(i
, group
->cpumask
) {
3227 if (!cpu_isset(i
, *cpus
))
3231 wl
= weighted_cpuload(i
);
3233 if (rq
->nr_running
== 1 && wl
> imbalance
)
3236 if (wl
> max_load
) {
3246 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3247 * so long as it is large enough.
3249 #define MAX_PINNED_INTERVAL 512
3252 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3253 * tasks if there is an imbalance.
3255 static int load_balance(int this_cpu
, struct rq
*this_rq
,
3256 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3257 int *balance
, cpumask_t
*cpus
)
3259 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
3260 struct sched_group
*group
;
3261 unsigned long imbalance
;
3263 unsigned long flags
;
3268 * When power savings policy is enabled for the parent domain, idle
3269 * sibling can pick up load irrespective of busy siblings. In this case,
3270 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3271 * portraying it as CPU_NOT_IDLE.
3273 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3274 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3277 schedstat_inc(sd
, lb_count
[idle
]);
3280 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
3287 schedstat_inc(sd
, lb_nobusyg
[idle
]);
3291 busiest
= find_busiest_queue(group
, idle
, imbalance
, cpus
);
3293 schedstat_inc(sd
, lb_nobusyq
[idle
]);
3297 BUG_ON(busiest
== this_rq
);
3299 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
3302 if (busiest
->nr_running
> 1) {
3304 * Attempt to move tasks. If find_busiest_group has found
3305 * an imbalance but busiest->nr_running <= 1, the group is
3306 * still unbalanced. ld_moved simply stays zero, so it is
3307 * correctly treated as an imbalance.
3309 local_irq_save(flags
);
3310 double_rq_lock(this_rq
, busiest
);
3311 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3312 imbalance
, sd
, idle
, &all_pinned
);
3313 double_rq_unlock(this_rq
, busiest
);
3314 local_irq_restore(flags
);
3317 * some other cpu did the load balance for us.
3319 if (ld_moved
&& this_cpu
!= smp_processor_id())
3320 resched_cpu(this_cpu
);
3322 /* All tasks on this runqueue were pinned by CPU affinity */
3323 if (unlikely(all_pinned
)) {
3324 cpu_clear(cpu_of(busiest
), *cpus
);
3325 if (!cpus_empty(*cpus
))
3332 schedstat_inc(sd
, lb_failed
[idle
]);
3333 sd
->nr_balance_failed
++;
3335 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3337 spin_lock_irqsave(&busiest
->lock
, flags
);
3339 /* don't kick the migration_thread, if the curr
3340 * task on busiest cpu can't be moved to this_cpu
3342 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3343 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3345 goto out_one_pinned
;
3348 if (!busiest
->active_balance
) {
3349 busiest
->active_balance
= 1;
3350 busiest
->push_cpu
= this_cpu
;
3353 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3355 wake_up_process(busiest
->migration_thread
);
3358 * We've kicked active balancing, reset the failure
3361 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3364 sd
->nr_balance_failed
= 0;
3366 if (likely(!active_balance
)) {
3367 /* We were unbalanced, so reset the balancing interval */
3368 sd
->balance_interval
= sd
->min_interval
;
3371 * If we've begun active balancing, start to back off. This
3372 * case may not be covered by the all_pinned logic if there
3373 * is only 1 task on the busy runqueue (because we don't call
3376 if (sd
->balance_interval
< sd
->max_interval
)
3377 sd
->balance_interval
*= 2;
3380 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3381 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3386 schedstat_inc(sd
, lb_balanced
[idle
]);
3388 sd
->nr_balance_failed
= 0;
3391 /* tune up the balancing interval */
3392 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3393 (sd
->balance_interval
< sd
->max_interval
))
3394 sd
->balance_interval
*= 2;
3396 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3397 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3403 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3404 * tasks if there is an imbalance.
3406 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3407 * this_rq is locked.
3410 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
,
3413 struct sched_group
*group
;
3414 struct rq
*busiest
= NULL
;
3415 unsigned long imbalance
;
3423 * When power savings policy is enabled for the parent domain, idle
3424 * sibling can pick up load irrespective of busy siblings. In this case,
3425 * let the state of idle sibling percolate up as IDLE, instead of
3426 * portraying it as CPU_NOT_IDLE.
3428 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3429 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3432 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3434 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3435 &sd_idle
, cpus
, NULL
);
3437 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3441 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
, cpus
);
3443 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3447 BUG_ON(busiest
== this_rq
);
3449 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3452 if (busiest
->nr_running
> 1) {
3453 /* Attempt to move tasks */
3454 double_lock_balance(this_rq
, busiest
);
3455 /* this_rq->clock is already updated */
3456 update_rq_clock(busiest
);
3457 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3458 imbalance
, sd
, CPU_NEWLY_IDLE
,
3460 spin_unlock(&busiest
->lock
);
3462 if (unlikely(all_pinned
)) {
3463 cpu_clear(cpu_of(busiest
), *cpus
);
3464 if (!cpus_empty(*cpus
))
3470 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3471 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3472 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3475 sd
->nr_balance_failed
= 0;
3480 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3481 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3482 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3484 sd
->nr_balance_failed
= 0;
3490 * idle_balance is called by schedule() if this_cpu is about to become
3491 * idle. Attempts to pull tasks from other CPUs.
3493 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3495 struct sched_domain
*sd
;
3496 int pulled_task
= -1;
3497 unsigned long next_balance
= jiffies
+ HZ
;
3500 for_each_domain(this_cpu
, sd
) {
3501 unsigned long interval
;
3503 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3506 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3507 /* If we've pulled tasks over stop searching: */
3508 pulled_task
= load_balance_newidle(this_cpu
, this_rq
,
3511 interval
= msecs_to_jiffies(sd
->balance_interval
);
3512 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3513 next_balance
= sd
->last_balance
+ interval
;
3517 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3519 * We are going idle. next_balance may be set based on
3520 * a busy processor. So reset next_balance.
3522 this_rq
->next_balance
= next_balance
;
3527 * active_load_balance is run by migration threads. It pushes running tasks
3528 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3529 * running on each physical CPU where possible, and avoids physical /
3530 * logical imbalances.
3532 * Called with busiest_rq locked.
3534 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3536 int target_cpu
= busiest_rq
->push_cpu
;
3537 struct sched_domain
*sd
;
3538 struct rq
*target_rq
;
3540 /* Is there any task to move? */
3541 if (busiest_rq
->nr_running
<= 1)
3544 target_rq
= cpu_rq(target_cpu
);
3547 * This condition is "impossible", if it occurs
3548 * we need to fix it. Originally reported by
3549 * Bjorn Helgaas on a 128-cpu setup.
3551 BUG_ON(busiest_rq
== target_rq
);
3553 /* move a task from busiest_rq to target_rq */
3554 double_lock_balance(busiest_rq
, target_rq
);
3555 update_rq_clock(busiest_rq
);
3556 update_rq_clock(target_rq
);
3558 /* Search for an sd spanning us and the target CPU. */
3559 for_each_domain(target_cpu
, sd
) {
3560 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3561 cpu_isset(busiest_cpu
, sd
->span
))
3566 schedstat_inc(sd
, alb_count
);
3568 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3570 schedstat_inc(sd
, alb_pushed
);
3572 schedstat_inc(sd
, alb_failed
);
3574 spin_unlock(&target_rq
->lock
);
3579 atomic_t load_balancer
;
3581 } nohz ____cacheline_aligned
= {
3582 .load_balancer
= ATOMIC_INIT(-1),
3583 .cpu_mask
= CPU_MASK_NONE
,
3587 * This routine will try to nominate the ilb (idle load balancing)
3588 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3589 * load balancing on behalf of all those cpus. If all the cpus in the system
3590 * go into this tickless mode, then there will be no ilb owner (as there is
3591 * no need for one) and all the cpus will sleep till the next wakeup event
3594 * For the ilb owner, tick is not stopped. And this tick will be used
3595 * for idle load balancing. ilb owner will still be part of
3598 * While stopping the tick, this cpu will become the ilb owner if there
3599 * is no other owner. And will be the owner till that cpu becomes busy
3600 * or if all cpus in the system stop their ticks at which point
3601 * there is no need for ilb owner.
3603 * When the ilb owner becomes busy, it nominates another owner, during the
3604 * next busy scheduler_tick()
3606 int select_nohz_load_balancer(int stop_tick
)
3608 int cpu
= smp_processor_id();
3611 cpu_set(cpu
, nohz
.cpu_mask
);
3612 cpu_rq(cpu
)->in_nohz_recently
= 1;
3615 * If we are going offline and still the leader, give up!
3617 if (cpu_is_offline(cpu
) &&
3618 atomic_read(&nohz
.load_balancer
) == cpu
) {
3619 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3624 /* time for ilb owner also to sleep */
3625 if (cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3626 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3627 atomic_set(&nohz
.load_balancer
, -1);
3631 if (atomic_read(&nohz
.load_balancer
) == -1) {
3632 /* make me the ilb owner */
3633 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3635 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3638 if (!cpu_isset(cpu
, nohz
.cpu_mask
))
3641 cpu_clear(cpu
, nohz
.cpu_mask
);
3643 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3644 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3651 static DEFINE_SPINLOCK(balancing
);
3654 * It checks each scheduling domain to see if it is due to be balanced,
3655 * and initiates a balancing operation if so.
3657 * Balancing parameters are set up in arch_init_sched_domains.
3659 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
3662 struct rq
*rq
= cpu_rq(cpu
);
3663 unsigned long interval
;
3664 struct sched_domain
*sd
;
3665 /* Earliest time when we have to do rebalance again */
3666 unsigned long next_balance
= jiffies
+ 60*HZ
;
3667 int update_next_balance
= 0;
3670 for_each_domain(cpu
, sd
) {
3671 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3674 interval
= sd
->balance_interval
;
3675 if (idle
!= CPU_IDLE
)
3676 interval
*= sd
->busy_factor
;
3678 /* scale ms to jiffies */
3679 interval
= msecs_to_jiffies(interval
);
3680 if (unlikely(!interval
))
3682 if (interval
> HZ
*NR_CPUS
/10)
3683 interval
= HZ
*NR_CPUS
/10;
3686 if (sd
->flags
& SD_SERIALIZE
) {
3687 if (!spin_trylock(&balancing
))
3691 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
3692 if (load_balance(cpu
, rq
, sd
, idle
, &balance
, &tmp
)) {
3694 * We've pulled tasks over so either we're no
3695 * longer idle, or one of our SMT siblings is
3698 idle
= CPU_NOT_IDLE
;
3700 sd
->last_balance
= jiffies
;
3702 if (sd
->flags
& SD_SERIALIZE
)
3703 spin_unlock(&balancing
);
3705 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
3706 next_balance
= sd
->last_balance
+ interval
;
3707 update_next_balance
= 1;
3711 * Stop the load balance at this level. There is another
3712 * CPU in our sched group which is doing load balancing more
3720 * next_balance will be updated only when there is a need.
3721 * When the cpu is attached to null domain for ex, it will not be
3724 if (likely(update_next_balance
))
3725 rq
->next_balance
= next_balance
;
3729 * run_rebalance_domains is triggered when needed from the scheduler tick.
3730 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3731 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3733 static void run_rebalance_domains(struct softirq_action
*h
)
3735 int this_cpu
= smp_processor_id();
3736 struct rq
*this_rq
= cpu_rq(this_cpu
);
3737 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
3738 CPU_IDLE
: CPU_NOT_IDLE
;
3740 rebalance_domains(this_cpu
, idle
);
3744 * If this cpu is the owner for idle load balancing, then do the
3745 * balancing on behalf of the other idle cpus whose ticks are
3748 if (this_rq
->idle_at_tick
&&
3749 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
3750 cpumask_t cpus
= nohz
.cpu_mask
;
3754 cpu_clear(this_cpu
, cpus
);
3755 for_each_cpu_mask(balance_cpu
, cpus
) {
3757 * If this cpu gets work to do, stop the load balancing
3758 * work being done for other cpus. Next load
3759 * balancing owner will pick it up.
3764 rebalance_domains(balance_cpu
, CPU_IDLE
);
3766 rq
= cpu_rq(balance_cpu
);
3767 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
3768 this_rq
->next_balance
= rq
->next_balance
;
3775 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3777 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3778 * idle load balancing owner or decide to stop the periodic load balancing,
3779 * if the whole system is idle.
3781 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
3785 * If we were in the nohz mode recently and busy at the current
3786 * scheduler tick, then check if we need to nominate new idle
3789 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
3790 rq
->in_nohz_recently
= 0;
3792 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
3793 cpu_clear(cpu
, nohz
.cpu_mask
);
3794 atomic_set(&nohz
.load_balancer
, -1);
3797 if (atomic_read(&nohz
.load_balancer
) == -1) {
3799 * simple selection for now: Nominate the
3800 * first cpu in the nohz list to be the next
3803 * TBD: Traverse the sched domains and nominate
3804 * the nearest cpu in the nohz.cpu_mask.
3806 int ilb
= first_cpu(nohz
.cpu_mask
);
3808 if (ilb
< nr_cpu_ids
)
3814 * If this cpu is idle and doing idle load balancing for all the
3815 * cpus with ticks stopped, is it time for that to stop?
3817 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
3818 cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3824 * If this cpu is idle and the idle load balancing is done by
3825 * someone else, then no need raise the SCHED_SOFTIRQ
3827 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
3828 cpu_isset(cpu
, nohz
.cpu_mask
))
3831 if (time_after_eq(jiffies
, rq
->next_balance
))
3832 raise_softirq(SCHED_SOFTIRQ
);
3835 #else /* CONFIG_SMP */
3838 * on UP we do not need to balance between CPUs:
3840 static inline void idle_balance(int cpu
, struct rq
*rq
)
3846 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
3848 EXPORT_PER_CPU_SYMBOL(kstat
);
3851 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3852 * that have not yet been banked in case the task is currently running.
3854 unsigned long long task_sched_runtime(struct task_struct
*p
)
3856 unsigned long flags
;
3860 rq
= task_rq_lock(p
, &flags
);
3861 ns
= p
->se
.sum_exec_runtime
;
3862 if (task_current(rq
, p
)) {
3863 update_rq_clock(rq
);
3864 delta_exec
= rq
->clock
- p
->se
.exec_start
;
3865 if ((s64
)delta_exec
> 0)
3868 task_rq_unlock(rq
, &flags
);
3874 * Account user cpu time to a process.
3875 * @p: the process that the cpu time gets accounted to
3876 * @cputime: the cpu time spent in user space since the last update
3878 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
3880 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3883 p
->utime
= cputime_add(p
->utime
, cputime
);
3885 /* Add user time to cpustat. */
3886 tmp
= cputime_to_cputime64(cputime
);
3887 if (TASK_NICE(p
) > 0)
3888 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
3890 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3894 * Account guest cpu time to a process.
3895 * @p: the process that the cpu time gets accounted to
3896 * @cputime: the cpu time spent in virtual machine since the last update
3898 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
3901 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3903 tmp
= cputime_to_cputime64(cputime
);
3905 p
->utime
= cputime_add(p
->utime
, cputime
);
3906 p
->gtime
= cputime_add(p
->gtime
, cputime
);
3908 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3909 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
3913 * Account scaled user cpu time to a process.
3914 * @p: the process that the cpu time gets accounted to
3915 * @cputime: the cpu time spent in user space since the last update
3917 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3919 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
3923 * Account system cpu time to a process.
3924 * @p: the process that the cpu time gets accounted to
3925 * @hardirq_offset: the offset to subtract from hardirq_count()
3926 * @cputime: the cpu time spent in kernel space since the last update
3928 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
3931 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3932 struct rq
*rq
= this_rq();
3935 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0)) {
3936 account_guest_time(p
, cputime
);
3940 p
->stime
= cputime_add(p
->stime
, cputime
);
3942 /* Add system time to cpustat. */
3943 tmp
= cputime_to_cputime64(cputime
);
3944 if (hardirq_count() - hardirq_offset
)
3945 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
3946 else if (softirq_count())
3947 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
3948 else if (p
!= rq
->idle
)
3949 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
3950 else if (atomic_read(&rq
->nr_iowait
) > 0)
3951 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3953 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3954 /* Account for system time used */
3955 acct_update_integrals(p
);
3959 * Account scaled system cpu time to a process.
3960 * @p: the process that the cpu time gets accounted to
3961 * @hardirq_offset: the offset to subtract from hardirq_count()
3962 * @cputime: the cpu time spent in kernel space since the last update
3964 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3966 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
3970 * Account for involuntary wait time.
3971 * @p: the process from which the cpu time has been stolen
3972 * @steal: the cpu time spent in involuntary wait
3974 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
3976 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3977 cputime64_t tmp
= cputime_to_cputime64(steal
);
3978 struct rq
*rq
= this_rq();
3980 if (p
== rq
->idle
) {
3981 p
->stime
= cputime_add(p
->stime
, steal
);
3982 if (atomic_read(&rq
->nr_iowait
) > 0)
3983 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3985 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3987 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
3991 * This function gets called by the timer code, with HZ frequency.
3992 * We call it with interrupts disabled.
3994 * It also gets called by the fork code, when changing the parent's
3997 void scheduler_tick(void)
3999 int cpu
= smp_processor_id();
4000 struct rq
*rq
= cpu_rq(cpu
);
4001 struct task_struct
*curr
= rq
->curr
;
4005 spin_lock(&rq
->lock
);
4006 update_rq_clock(rq
);
4007 update_cpu_load(rq
);
4008 curr
->sched_class
->task_tick(rq
, curr
, 0);
4009 spin_unlock(&rq
->lock
);
4012 rq
->idle_at_tick
= idle_cpu(cpu
);
4013 trigger_load_balance(rq
, cpu
);
4017 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4019 void __kprobes
add_preempt_count(int val
)
4024 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4026 preempt_count() += val
;
4028 * Spinlock count overflowing soon?
4030 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
4033 EXPORT_SYMBOL(add_preempt_count
);
4035 void __kprobes
sub_preempt_count(int val
)
4040 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
4043 * Is the spinlock portion underflowing?
4045 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
4046 !(preempt_count() & PREEMPT_MASK
)))
4049 preempt_count() -= val
;
4051 EXPORT_SYMBOL(sub_preempt_count
);
4056 * Print scheduling while atomic bug:
4058 static noinline
void __schedule_bug(struct task_struct
*prev
)
4060 struct pt_regs
*regs
= get_irq_regs();
4062 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
4063 prev
->comm
, prev
->pid
, preempt_count());
4065 debug_show_held_locks(prev
);
4066 if (irqs_disabled())
4067 print_irqtrace_events(prev
);
4076 * Various schedule()-time debugging checks and statistics:
4078 static inline void schedule_debug(struct task_struct
*prev
)
4081 * Test if we are atomic. Since do_exit() needs to call into
4082 * schedule() atomically, we ignore that path for now.
4083 * Otherwise, whine if we are scheduling when we should not be.
4085 if (unlikely(in_atomic_preempt_off() && !prev
->exit_state
))
4086 __schedule_bug(prev
);
4088 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
4090 schedstat_inc(this_rq(), sched_count
);
4091 #ifdef CONFIG_SCHEDSTATS
4092 if (unlikely(prev
->lock_depth
>= 0)) {
4093 schedstat_inc(this_rq(), bkl_count
);
4094 schedstat_inc(prev
, sched_info
.bkl_count
);
4100 * Pick up the highest-prio task:
4102 static inline struct task_struct
*
4103 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
4105 const struct sched_class
*class;
4106 struct task_struct
*p
;
4109 * Optimization: we know that if all tasks are in
4110 * the fair class we can call that function directly:
4112 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
4113 p
= fair_sched_class
.pick_next_task(rq
);
4118 class = sched_class_highest
;
4120 p
= class->pick_next_task(rq
);
4124 * Will never be NULL as the idle class always
4125 * returns a non-NULL p:
4127 class = class->next
;
4132 * schedule() is the main scheduler function.
4134 asmlinkage
void __sched
schedule(void)
4136 struct task_struct
*prev
, *next
;
4137 unsigned long *switch_count
;
4143 cpu
= smp_processor_id();
4147 switch_count
= &prev
->nivcsw
;
4149 release_kernel_lock(prev
);
4150 need_resched_nonpreemptible
:
4152 schedule_debug(prev
);
4157 * Do the rq-clock update outside the rq lock:
4159 local_irq_disable();
4160 update_rq_clock(rq
);
4161 spin_lock(&rq
->lock
);
4162 clear_tsk_need_resched(prev
);
4164 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
4165 if (unlikely(signal_pending_state(prev
->state
, prev
)))
4166 prev
->state
= TASK_RUNNING
;
4168 deactivate_task(rq
, prev
, 1);
4169 switch_count
= &prev
->nvcsw
;
4173 if (prev
->sched_class
->pre_schedule
)
4174 prev
->sched_class
->pre_schedule(rq
, prev
);
4177 if (unlikely(!rq
->nr_running
))
4178 idle_balance(cpu
, rq
);
4180 prev
->sched_class
->put_prev_task(rq
, prev
);
4181 next
= pick_next_task(rq
, prev
);
4183 if (likely(prev
!= next
)) {
4184 sched_info_switch(prev
, next
);
4190 context_switch(rq
, prev
, next
); /* unlocks the rq */
4192 * the context switch might have flipped the stack from under
4193 * us, hence refresh the local variables.
4195 cpu
= smp_processor_id();
4198 spin_unlock_irq(&rq
->lock
);
4202 if (unlikely(reacquire_kernel_lock(current
) < 0))
4203 goto need_resched_nonpreemptible
;
4205 preempt_enable_no_resched();
4206 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
4209 EXPORT_SYMBOL(schedule
);
4211 #ifdef CONFIG_PREEMPT
4213 * this is the entry point to schedule() from in-kernel preemption
4214 * off of preempt_enable. Kernel preemptions off return from interrupt
4215 * occur there and call schedule directly.
4217 asmlinkage
void __sched
preempt_schedule(void)
4219 struct thread_info
*ti
= current_thread_info();
4222 * If there is a non-zero preempt_count or interrupts are disabled,
4223 * we do not want to preempt the current task. Just return..
4225 if (likely(ti
->preempt_count
|| irqs_disabled()))
4229 add_preempt_count(PREEMPT_ACTIVE
);
4231 sub_preempt_count(PREEMPT_ACTIVE
);
4234 * Check again in case we missed a preemption opportunity
4235 * between schedule and now.
4238 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4240 EXPORT_SYMBOL(preempt_schedule
);
4243 * this is the entry point to schedule() from kernel preemption
4244 * off of irq context.
4245 * Note, that this is called and return with irqs disabled. This will
4246 * protect us against recursive calling from irq.
4248 asmlinkage
void __sched
preempt_schedule_irq(void)
4250 struct thread_info
*ti
= current_thread_info();
4252 /* Catch callers which need to be fixed */
4253 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
4256 add_preempt_count(PREEMPT_ACTIVE
);
4259 local_irq_disable();
4260 sub_preempt_count(PREEMPT_ACTIVE
);
4263 * Check again in case we missed a preemption opportunity
4264 * between schedule and now.
4267 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4270 #endif /* CONFIG_PREEMPT */
4272 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
4275 return try_to_wake_up(curr
->private, mode
, sync
);
4277 EXPORT_SYMBOL(default_wake_function
);
4280 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4281 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4282 * number) then we wake all the non-exclusive tasks and one exclusive task.
4284 * There are circumstances in which we can try to wake a task which has already
4285 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4286 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4288 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
4289 int nr_exclusive
, int sync
, void *key
)
4291 wait_queue_t
*curr
, *next
;
4293 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
4294 unsigned flags
= curr
->flags
;
4296 if (curr
->func(curr
, mode
, sync
, key
) &&
4297 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4303 * __wake_up - wake up threads blocked on a waitqueue.
4305 * @mode: which threads
4306 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4307 * @key: is directly passed to the wakeup function
4309 void __wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4310 int nr_exclusive
, void *key
)
4312 unsigned long flags
;
4314 spin_lock_irqsave(&q
->lock
, flags
);
4315 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4316 spin_unlock_irqrestore(&q
->lock
, flags
);
4318 EXPORT_SYMBOL(__wake_up
);
4321 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4323 void __wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4325 __wake_up_common(q
, mode
, 1, 0, NULL
);
4329 * __wake_up_sync - wake up threads blocked on a waitqueue.
4331 * @mode: which threads
4332 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4334 * The sync wakeup differs that the waker knows that it will schedule
4335 * away soon, so while the target thread will be woken up, it will not
4336 * be migrated to another CPU - ie. the two threads are 'synchronized'
4337 * with each other. This can prevent needless bouncing between CPUs.
4339 * On UP it can prevent extra preemption.
4342 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4344 unsigned long flags
;
4350 if (unlikely(!nr_exclusive
))
4353 spin_lock_irqsave(&q
->lock
, flags
);
4354 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4355 spin_unlock_irqrestore(&q
->lock
, flags
);
4357 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4359 void complete(struct completion
*x
)
4361 unsigned long flags
;
4363 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4365 __wake_up_common(&x
->wait
, TASK_NORMAL
, 1, 0, NULL
);
4366 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4368 EXPORT_SYMBOL(complete
);
4370 void complete_all(struct completion
*x
)
4372 unsigned long flags
;
4374 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4375 x
->done
+= UINT_MAX
/2;
4376 __wake_up_common(&x
->wait
, TASK_NORMAL
, 0, 0, NULL
);
4377 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4379 EXPORT_SYMBOL(complete_all
);
4381 static inline long __sched
4382 do_wait_for_common(struct completion
*x
, long timeout
, int state
)
4385 DECLARE_WAITQUEUE(wait
, current
);
4387 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
4388 __add_wait_queue_tail(&x
->wait
, &wait
);
4390 if ((state
== TASK_INTERRUPTIBLE
&&
4391 signal_pending(current
)) ||
4392 (state
== TASK_KILLABLE
&&
4393 fatal_signal_pending(current
))) {
4394 __remove_wait_queue(&x
->wait
, &wait
);
4395 return -ERESTARTSYS
;
4397 __set_current_state(state
);
4398 spin_unlock_irq(&x
->wait
.lock
);
4399 timeout
= schedule_timeout(timeout
);
4400 spin_lock_irq(&x
->wait
.lock
);
4402 __remove_wait_queue(&x
->wait
, &wait
);
4406 __remove_wait_queue(&x
->wait
, &wait
);
4413 wait_for_common(struct completion
*x
, long timeout
, int state
)
4417 spin_lock_irq(&x
->wait
.lock
);
4418 timeout
= do_wait_for_common(x
, timeout
, state
);
4419 spin_unlock_irq(&x
->wait
.lock
);
4423 void __sched
wait_for_completion(struct completion
*x
)
4425 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4427 EXPORT_SYMBOL(wait_for_completion
);
4429 unsigned long __sched
4430 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4432 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4434 EXPORT_SYMBOL(wait_for_completion_timeout
);
4436 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4438 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4439 if (t
== -ERESTARTSYS
)
4443 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4445 unsigned long __sched
4446 wait_for_completion_interruptible_timeout(struct completion
*x
,
4447 unsigned long timeout
)
4449 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4451 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4453 int __sched
wait_for_completion_killable(struct completion
*x
)
4455 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_KILLABLE
);
4456 if (t
== -ERESTARTSYS
)
4460 EXPORT_SYMBOL(wait_for_completion_killable
);
4463 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4465 unsigned long flags
;
4468 init_waitqueue_entry(&wait
, current
);
4470 __set_current_state(state
);
4472 spin_lock_irqsave(&q
->lock
, flags
);
4473 __add_wait_queue(q
, &wait
);
4474 spin_unlock(&q
->lock
);
4475 timeout
= schedule_timeout(timeout
);
4476 spin_lock_irq(&q
->lock
);
4477 __remove_wait_queue(q
, &wait
);
4478 spin_unlock_irqrestore(&q
->lock
, flags
);
4483 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4485 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4487 EXPORT_SYMBOL(interruptible_sleep_on
);
4490 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4492 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4494 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4496 void __sched
sleep_on(wait_queue_head_t
*q
)
4498 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4500 EXPORT_SYMBOL(sleep_on
);
4502 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4504 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4506 EXPORT_SYMBOL(sleep_on_timeout
);
4508 #ifdef CONFIG_RT_MUTEXES
4511 * rt_mutex_setprio - set the current priority of a task
4513 * @prio: prio value (kernel-internal form)
4515 * This function changes the 'effective' priority of a task. It does
4516 * not touch ->normal_prio like __setscheduler().
4518 * Used by the rt_mutex code to implement priority inheritance logic.
4520 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4522 unsigned long flags
;
4523 int oldprio
, on_rq
, running
;
4525 const struct sched_class
*prev_class
= p
->sched_class
;
4527 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4529 rq
= task_rq_lock(p
, &flags
);
4530 update_rq_clock(rq
);
4533 on_rq
= p
->se
.on_rq
;
4534 running
= task_current(rq
, p
);
4536 dequeue_task(rq
, p
, 0);
4538 p
->sched_class
->put_prev_task(rq
, p
);
4541 p
->sched_class
= &rt_sched_class
;
4543 p
->sched_class
= &fair_sched_class
;
4548 p
->sched_class
->set_curr_task(rq
);
4550 enqueue_task(rq
, p
, 0);
4552 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4554 task_rq_unlock(rq
, &flags
);
4559 void set_user_nice(struct task_struct
*p
, long nice
)
4561 int old_prio
, delta
, on_rq
;
4562 unsigned long flags
;
4565 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
4568 * We have to be careful, if called from sys_setpriority(),
4569 * the task might be in the middle of scheduling on another CPU.
4571 rq
= task_rq_lock(p
, &flags
);
4572 update_rq_clock(rq
);
4574 * The RT priorities are set via sched_setscheduler(), but we still
4575 * allow the 'normal' nice value to be set - but as expected
4576 * it wont have any effect on scheduling until the task is
4577 * SCHED_FIFO/SCHED_RR:
4579 if (task_has_rt_policy(p
)) {
4580 p
->static_prio
= NICE_TO_PRIO(nice
);
4583 on_rq
= p
->se
.on_rq
;
4585 dequeue_task(rq
, p
, 0);
4589 p
->static_prio
= NICE_TO_PRIO(nice
);
4592 p
->prio
= effective_prio(p
);
4593 delta
= p
->prio
- old_prio
;
4596 enqueue_task(rq
, p
, 0);
4599 * If the task increased its priority or is running and
4600 * lowered its priority, then reschedule its CPU:
4602 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
4603 resched_task(rq
->curr
);
4606 task_rq_unlock(rq
, &flags
);
4608 EXPORT_SYMBOL(set_user_nice
);
4611 * can_nice - check if a task can reduce its nice value
4615 int can_nice(const struct task_struct
*p
, const int nice
)
4617 /* convert nice value [19,-20] to rlimit style value [1,40] */
4618 int nice_rlim
= 20 - nice
;
4620 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
4621 capable(CAP_SYS_NICE
));
4624 #ifdef __ARCH_WANT_SYS_NICE
4627 * sys_nice - change the priority of the current process.
4628 * @increment: priority increment
4630 * sys_setpriority is a more generic, but much slower function that
4631 * does similar things.
4633 asmlinkage
long sys_nice(int increment
)
4638 * Setpriority might change our priority at the same moment.
4639 * We don't have to worry. Conceptually one call occurs first
4640 * and we have a single winner.
4642 if (increment
< -40)
4647 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
4653 if (increment
< 0 && !can_nice(current
, nice
))
4656 retval
= security_task_setnice(current
, nice
);
4660 set_user_nice(current
, nice
);
4667 * task_prio - return the priority value of a given task.
4668 * @p: the task in question.
4670 * This is the priority value as seen by users in /proc.
4671 * RT tasks are offset by -200. Normal tasks are centered
4672 * around 0, value goes from -16 to +15.
4674 int task_prio(const struct task_struct
*p
)
4676 return p
->prio
- MAX_RT_PRIO
;
4680 * task_nice - return the nice value of a given task.
4681 * @p: the task in question.
4683 int task_nice(const struct task_struct
*p
)
4685 return TASK_NICE(p
);
4687 EXPORT_SYMBOL(task_nice
);
4690 * idle_cpu - is a given cpu idle currently?
4691 * @cpu: the processor in question.
4693 int idle_cpu(int cpu
)
4695 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
4699 * idle_task - return the idle task for a given cpu.
4700 * @cpu: the processor in question.
4702 struct task_struct
*idle_task(int cpu
)
4704 return cpu_rq(cpu
)->idle
;
4708 * find_process_by_pid - find a process with a matching PID value.
4709 * @pid: the pid in question.
4711 static struct task_struct
*find_process_by_pid(pid_t pid
)
4713 return pid
? find_task_by_vpid(pid
) : current
;
4716 /* Actually do priority change: must hold rq lock. */
4718 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
4720 BUG_ON(p
->se
.on_rq
);
4723 switch (p
->policy
) {
4727 p
->sched_class
= &fair_sched_class
;
4731 p
->sched_class
= &rt_sched_class
;
4735 p
->rt_priority
= prio
;
4736 p
->normal_prio
= normal_prio(p
);
4737 /* we are holding p->pi_lock already */
4738 p
->prio
= rt_mutex_getprio(p
);
4743 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4744 * @p: the task in question.
4745 * @policy: new policy.
4746 * @param: structure containing the new RT priority.
4748 * NOTE that the task may be already dead.
4750 int sched_setscheduler(struct task_struct
*p
, int policy
,
4751 struct sched_param
*param
)
4753 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
4754 unsigned long flags
;
4755 const struct sched_class
*prev_class
= p
->sched_class
;
4758 /* may grab non-irq protected spin_locks */
4759 BUG_ON(in_interrupt());
4761 /* double check policy once rq lock held */
4763 policy
= oldpolicy
= p
->policy
;
4764 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4765 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
4766 policy
!= SCHED_IDLE
)
4769 * Valid priorities for SCHED_FIFO and SCHED_RR are
4770 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4771 * SCHED_BATCH and SCHED_IDLE is 0.
4773 if (param
->sched_priority
< 0 ||
4774 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4775 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4777 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
4781 * Allow unprivileged RT tasks to decrease priority:
4783 if (!capable(CAP_SYS_NICE
)) {
4784 if (rt_policy(policy
)) {
4785 unsigned long rlim_rtprio
;
4787 if (!lock_task_sighand(p
, &flags
))
4789 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
4790 unlock_task_sighand(p
, &flags
);
4792 /* can't set/change the rt policy */
4793 if (policy
!= p
->policy
&& !rlim_rtprio
)
4796 /* can't increase priority */
4797 if (param
->sched_priority
> p
->rt_priority
&&
4798 param
->sched_priority
> rlim_rtprio
)
4802 * Like positive nice levels, dont allow tasks to
4803 * move out of SCHED_IDLE either:
4805 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
4808 /* can't change other user's priorities */
4809 if ((current
->euid
!= p
->euid
) &&
4810 (current
->euid
!= p
->uid
))
4814 #ifdef CONFIG_RT_GROUP_SCHED
4816 * Do not allow realtime tasks into groups that have no runtime
4819 if (rt_policy(policy
) && task_group(p
)->rt_bandwidth
.rt_runtime
== 0)
4823 retval
= security_task_setscheduler(p
, policy
, param
);
4827 * make sure no PI-waiters arrive (or leave) while we are
4828 * changing the priority of the task:
4830 spin_lock_irqsave(&p
->pi_lock
, flags
);
4832 * To be able to change p->policy safely, the apropriate
4833 * runqueue lock must be held.
4835 rq
= __task_rq_lock(p
);
4836 /* recheck policy now with rq lock held */
4837 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4838 policy
= oldpolicy
= -1;
4839 __task_rq_unlock(rq
);
4840 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4843 update_rq_clock(rq
);
4844 on_rq
= p
->se
.on_rq
;
4845 running
= task_current(rq
, p
);
4847 deactivate_task(rq
, p
, 0);
4849 p
->sched_class
->put_prev_task(rq
, p
);
4852 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
4855 p
->sched_class
->set_curr_task(rq
);
4857 activate_task(rq
, p
, 0);
4859 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4861 __task_rq_unlock(rq
);
4862 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4864 rt_mutex_adjust_pi(p
);
4868 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4871 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4873 struct sched_param lparam
;
4874 struct task_struct
*p
;
4877 if (!param
|| pid
< 0)
4879 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4884 p
= find_process_by_pid(pid
);
4886 retval
= sched_setscheduler(p
, policy
, &lparam
);
4893 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4894 * @pid: the pid in question.
4895 * @policy: new policy.
4896 * @param: structure containing the new RT priority.
4899 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4901 /* negative values for policy are not valid */
4905 return do_sched_setscheduler(pid
, policy
, param
);
4909 * sys_sched_setparam - set/change the RT priority of a thread
4910 * @pid: the pid in question.
4911 * @param: structure containing the new RT priority.
4913 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4915 return do_sched_setscheduler(pid
, -1, param
);
4919 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4920 * @pid: the pid in question.
4922 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4924 struct task_struct
*p
;
4931 read_lock(&tasklist_lock
);
4932 p
= find_process_by_pid(pid
);
4934 retval
= security_task_getscheduler(p
);
4938 read_unlock(&tasklist_lock
);
4943 * sys_sched_getscheduler - get the RT priority of a thread
4944 * @pid: the pid in question.
4945 * @param: structure containing the RT priority.
4947 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4949 struct sched_param lp
;
4950 struct task_struct
*p
;
4953 if (!param
|| pid
< 0)
4956 read_lock(&tasklist_lock
);
4957 p
= find_process_by_pid(pid
);
4962 retval
= security_task_getscheduler(p
);
4966 lp
.sched_priority
= p
->rt_priority
;
4967 read_unlock(&tasklist_lock
);
4970 * This one might sleep, we cannot do it with a spinlock held ...
4972 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4977 read_unlock(&tasklist_lock
);
4981 long sched_setaffinity(pid_t pid
, const cpumask_t
*in_mask
)
4983 cpumask_t cpus_allowed
;
4984 cpumask_t new_mask
= *in_mask
;
4985 struct task_struct
*p
;
4989 read_lock(&tasklist_lock
);
4991 p
= find_process_by_pid(pid
);
4993 read_unlock(&tasklist_lock
);
4999 * It is not safe to call set_cpus_allowed with the
5000 * tasklist_lock held. We will bump the task_struct's
5001 * usage count and then drop tasklist_lock.
5004 read_unlock(&tasklist_lock
);
5007 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
5008 !capable(CAP_SYS_NICE
))
5011 retval
= security_task_setscheduler(p
, 0, NULL
);
5015 cpuset_cpus_allowed(p
, &cpus_allowed
);
5016 cpus_and(new_mask
, new_mask
, cpus_allowed
);
5018 retval
= set_cpus_allowed_ptr(p
, &new_mask
);
5021 cpuset_cpus_allowed(p
, &cpus_allowed
);
5022 if (!cpus_subset(new_mask
, cpus_allowed
)) {
5024 * We must have raced with a concurrent cpuset
5025 * update. Just reset the cpus_allowed to the
5026 * cpuset's cpus_allowed
5028 new_mask
= cpus_allowed
;
5038 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
5039 cpumask_t
*new_mask
)
5041 if (len
< sizeof(cpumask_t
)) {
5042 memset(new_mask
, 0, sizeof(cpumask_t
));
5043 } else if (len
> sizeof(cpumask_t
)) {
5044 len
= sizeof(cpumask_t
);
5046 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
5050 * sys_sched_setaffinity - set the cpu affinity of a process
5051 * @pid: pid of the process
5052 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5053 * @user_mask_ptr: user-space pointer to the new cpu mask
5055 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
5056 unsigned long __user
*user_mask_ptr
)
5061 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
5065 return sched_setaffinity(pid
, &new_mask
);
5069 * Represents all cpu's present in the system
5070 * In systems capable of hotplug, this map could dynamically grow
5071 * as new cpu's are detected in the system via any platform specific
5072 * method, such as ACPI for e.g.
5075 cpumask_t cpu_present_map __read_mostly
;
5076 EXPORT_SYMBOL(cpu_present_map
);
5079 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
5080 EXPORT_SYMBOL(cpu_online_map
);
5082 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
5083 EXPORT_SYMBOL(cpu_possible_map
);
5086 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
5088 struct task_struct
*p
;
5092 read_lock(&tasklist_lock
);
5095 p
= find_process_by_pid(pid
);
5099 retval
= security_task_getscheduler(p
);
5103 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
5106 read_unlock(&tasklist_lock
);
5113 * sys_sched_getaffinity - get the cpu affinity of a process
5114 * @pid: pid of the process
5115 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5116 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5118 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
5119 unsigned long __user
*user_mask_ptr
)
5124 if (len
< sizeof(cpumask_t
))
5127 ret
= sched_getaffinity(pid
, &mask
);
5131 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
5134 return sizeof(cpumask_t
);
5138 * sys_sched_yield - yield the current processor to other threads.
5140 * This function yields the current CPU to other tasks. If there are no
5141 * other threads running on this CPU then this function will return.
5143 asmlinkage
long sys_sched_yield(void)
5145 struct rq
*rq
= this_rq_lock();
5147 schedstat_inc(rq
, yld_count
);
5148 current
->sched_class
->yield_task(rq
);
5151 * Since we are going to call schedule() anyway, there's
5152 * no need to preempt or enable interrupts:
5154 __release(rq
->lock
);
5155 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
5156 _raw_spin_unlock(&rq
->lock
);
5157 preempt_enable_no_resched();
5164 static void __cond_resched(void)
5166 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5167 __might_sleep(__FILE__
, __LINE__
);
5170 * The BKS might be reacquired before we have dropped
5171 * PREEMPT_ACTIVE, which could trigger a second
5172 * cond_resched() call.
5175 add_preempt_count(PREEMPT_ACTIVE
);
5177 sub_preempt_count(PREEMPT_ACTIVE
);
5178 } while (need_resched());
5181 int __sched
_cond_resched(void)
5183 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
5184 system_state
== SYSTEM_RUNNING
) {
5190 EXPORT_SYMBOL(_cond_resched
);
5193 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5194 * call schedule, and on return reacquire the lock.
5196 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5197 * operations here to prevent schedule() from being called twice (once via
5198 * spin_unlock(), once by hand).
5200 int cond_resched_lock(spinlock_t
*lock
)
5202 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
5205 if (spin_needbreak(lock
) || resched
) {
5207 if (resched
&& need_resched())
5216 EXPORT_SYMBOL(cond_resched_lock
);
5218 int __sched
cond_resched_softirq(void)
5220 BUG_ON(!in_softirq());
5222 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
5230 EXPORT_SYMBOL(cond_resched_softirq
);
5233 * yield - yield the current processor to other threads.
5235 * This is a shortcut for kernel-space yielding - it marks the
5236 * thread runnable and calls sys_sched_yield().
5238 void __sched
yield(void)
5240 set_current_state(TASK_RUNNING
);
5243 EXPORT_SYMBOL(yield
);
5246 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5247 * that process accounting knows that this is a task in IO wait state.
5249 * But don't do that if it is a deliberate, throttling IO wait (this task
5250 * has set its backing_dev_info: the queue against which it should throttle)
5252 void __sched
io_schedule(void)
5254 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5256 delayacct_blkio_start();
5257 atomic_inc(&rq
->nr_iowait
);
5259 atomic_dec(&rq
->nr_iowait
);
5260 delayacct_blkio_end();
5262 EXPORT_SYMBOL(io_schedule
);
5264 long __sched
io_schedule_timeout(long timeout
)
5266 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5269 delayacct_blkio_start();
5270 atomic_inc(&rq
->nr_iowait
);
5271 ret
= schedule_timeout(timeout
);
5272 atomic_dec(&rq
->nr_iowait
);
5273 delayacct_blkio_end();
5278 * sys_sched_get_priority_max - return maximum RT priority.
5279 * @policy: scheduling class.
5281 * this syscall returns the maximum rt_priority that can be used
5282 * by a given scheduling class.
5284 asmlinkage
long sys_sched_get_priority_max(int policy
)
5291 ret
= MAX_USER_RT_PRIO
-1;
5303 * sys_sched_get_priority_min - return minimum RT priority.
5304 * @policy: scheduling class.
5306 * this syscall returns the minimum rt_priority that can be used
5307 * by a given scheduling class.
5309 asmlinkage
long sys_sched_get_priority_min(int policy
)
5327 * sys_sched_rr_get_interval - return the default timeslice of a process.
5328 * @pid: pid of the process.
5329 * @interval: userspace pointer to the timeslice value.
5331 * this syscall writes the default timeslice value of a given process
5332 * into the user-space timespec buffer. A value of '0' means infinity.
5335 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5337 struct task_struct
*p
;
5338 unsigned int time_slice
;
5346 read_lock(&tasklist_lock
);
5347 p
= find_process_by_pid(pid
);
5351 retval
= security_task_getscheduler(p
);
5356 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5357 * tasks that are on an otherwise idle runqueue:
5360 if (p
->policy
== SCHED_RR
) {
5361 time_slice
= DEF_TIMESLICE
;
5362 } else if (p
->policy
!= SCHED_FIFO
) {
5363 struct sched_entity
*se
= &p
->se
;
5364 unsigned long flags
;
5367 rq
= task_rq_lock(p
, &flags
);
5368 if (rq
->cfs
.load
.weight
)
5369 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5370 task_rq_unlock(rq
, &flags
);
5372 read_unlock(&tasklist_lock
);
5373 jiffies_to_timespec(time_slice
, &t
);
5374 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5378 read_unlock(&tasklist_lock
);
5382 static const char stat_nam
[] = "RSDTtZX";
5384 void sched_show_task(struct task_struct
*p
)
5386 unsigned long free
= 0;
5389 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5390 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5391 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5392 #if BITS_PER_LONG == 32
5393 if (state
== TASK_RUNNING
)
5394 printk(KERN_CONT
" running ");
5396 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5398 if (state
== TASK_RUNNING
)
5399 printk(KERN_CONT
" running task ");
5401 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5403 #ifdef CONFIG_DEBUG_STACK_USAGE
5405 unsigned long *n
= end_of_stack(p
);
5408 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5411 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5412 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5414 show_stack(p
, NULL
);
5417 void show_state_filter(unsigned long state_filter
)
5419 struct task_struct
*g
, *p
;
5421 #if BITS_PER_LONG == 32
5423 " task PC stack pid father\n");
5426 " task PC stack pid father\n");
5428 read_lock(&tasklist_lock
);
5429 do_each_thread(g
, p
) {
5431 * reset the NMI-timeout, listing all files on a slow
5432 * console might take alot of time:
5434 touch_nmi_watchdog();
5435 if (!state_filter
|| (p
->state
& state_filter
))
5437 } while_each_thread(g
, p
);
5439 touch_all_softlockup_watchdogs();
5441 #ifdef CONFIG_SCHED_DEBUG
5442 sysrq_sched_debug_show();
5444 read_unlock(&tasklist_lock
);
5446 * Only show locks if all tasks are dumped:
5448 if (state_filter
== -1)
5449 debug_show_all_locks();
5452 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5454 idle
->sched_class
= &idle_sched_class
;
5458 * init_idle - set up an idle thread for a given CPU
5459 * @idle: task in question
5460 * @cpu: cpu the idle task belongs to
5462 * NOTE: this function does not set the idle thread's NEED_RESCHED
5463 * flag, to make booting more robust.
5465 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5467 struct rq
*rq
= cpu_rq(cpu
);
5468 unsigned long flags
;
5471 idle
->se
.exec_start
= sched_clock();
5473 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5474 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
5475 __set_task_cpu(idle
, cpu
);
5477 spin_lock_irqsave(&rq
->lock
, flags
);
5478 rq
->curr
= rq
->idle
= idle
;
5479 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5482 spin_unlock_irqrestore(&rq
->lock
, flags
);
5484 /* Set the preempt count _outside_ the spinlocks! */
5485 #if defined(CONFIG_PREEMPT)
5486 task_thread_info(idle
)->preempt_count
= (idle
->lock_depth
>= 0);
5488 task_thread_info(idle
)->preempt_count
= 0;
5491 * The idle tasks have their own, simple scheduling class:
5493 idle
->sched_class
= &idle_sched_class
;
5497 * In a system that switches off the HZ timer nohz_cpu_mask
5498 * indicates which cpus entered this state. This is used
5499 * in the rcu update to wait only for active cpus. For system
5500 * which do not switch off the HZ timer nohz_cpu_mask should
5501 * always be CPU_MASK_NONE.
5503 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
5506 * Increase the granularity value when there are more CPUs,
5507 * because with more CPUs the 'effective latency' as visible
5508 * to users decreases. But the relationship is not linear,
5509 * so pick a second-best guess by going with the log2 of the
5512 * This idea comes from the SD scheduler of Con Kolivas:
5514 static inline void sched_init_granularity(void)
5516 unsigned int factor
= 1 + ilog2(num_online_cpus());
5517 const unsigned long limit
= 200000000;
5519 sysctl_sched_min_granularity
*= factor
;
5520 if (sysctl_sched_min_granularity
> limit
)
5521 sysctl_sched_min_granularity
= limit
;
5523 sysctl_sched_latency
*= factor
;
5524 if (sysctl_sched_latency
> limit
)
5525 sysctl_sched_latency
= limit
;
5527 sysctl_sched_wakeup_granularity
*= factor
;
5532 * This is how migration works:
5534 * 1) we queue a struct migration_req structure in the source CPU's
5535 * runqueue and wake up that CPU's migration thread.
5536 * 2) we down() the locked semaphore => thread blocks.
5537 * 3) migration thread wakes up (implicitly it forces the migrated
5538 * thread off the CPU)
5539 * 4) it gets the migration request and checks whether the migrated
5540 * task is still in the wrong runqueue.
5541 * 5) if it's in the wrong runqueue then the migration thread removes
5542 * it and puts it into the right queue.
5543 * 6) migration thread up()s the semaphore.
5544 * 7) we wake up and the migration is done.
5548 * Change a given task's CPU affinity. Migrate the thread to a
5549 * proper CPU and schedule it away if the CPU it's executing on
5550 * is removed from the allowed bitmask.
5552 * NOTE: the caller must have a valid reference to the task, the
5553 * task must not exit() & deallocate itself prematurely. The
5554 * call is not atomic; no spinlocks may be held.
5556 int set_cpus_allowed_ptr(struct task_struct
*p
, const cpumask_t
*new_mask
)
5558 struct migration_req req
;
5559 unsigned long flags
;
5563 rq
= task_rq_lock(p
, &flags
);
5564 if (!cpus_intersects(*new_mask
, cpu_online_map
)) {
5569 if (p
->sched_class
->set_cpus_allowed
)
5570 p
->sched_class
->set_cpus_allowed(p
, new_mask
);
5572 p
->cpus_allowed
= *new_mask
;
5573 p
->rt
.nr_cpus_allowed
= cpus_weight(*new_mask
);
5576 /* Can the task run on the task's current CPU? If so, we're done */
5577 if (cpu_isset(task_cpu(p
), *new_mask
))
5580 if (migrate_task(p
, any_online_cpu(*new_mask
), &req
)) {
5581 /* Need help from migration thread: drop lock and wait. */
5582 task_rq_unlock(rq
, &flags
);
5583 wake_up_process(rq
->migration_thread
);
5584 wait_for_completion(&req
.done
);
5585 tlb_migrate_finish(p
->mm
);
5589 task_rq_unlock(rq
, &flags
);
5593 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr
);
5596 * Move (not current) task off this cpu, onto dest cpu. We're doing
5597 * this because either it can't run here any more (set_cpus_allowed()
5598 * away from this CPU, or CPU going down), or because we're
5599 * attempting to rebalance this task on exec (sched_exec).
5601 * So we race with normal scheduler movements, but that's OK, as long
5602 * as the task is no longer on this CPU.
5604 * Returns non-zero if task was successfully migrated.
5606 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5608 struct rq
*rq_dest
, *rq_src
;
5611 if (unlikely(cpu_is_offline(dest_cpu
)))
5614 rq_src
= cpu_rq(src_cpu
);
5615 rq_dest
= cpu_rq(dest_cpu
);
5617 double_rq_lock(rq_src
, rq_dest
);
5618 /* Already moved. */
5619 if (task_cpu(p
) != src_cpu
)
5621 /* Affinity changed (again). */
5622 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
5625 on_rq
= p
->se
.on_rq
;
5627 deactivate_task(rq_src
, p
, 0);
5629 set_task_cpu(p
, dest_cpu
);
5631 activate_task(rq_dest
, p
, 0);
5632 check_preempt_curr(rq_dest
, p
);
5636 double_rq_unlock(rq_src
, rq_dest
);
5641 * migration_thread - this is a highprio system thread that performs
5642 * thread migration by bumping thread off CPU then 'pushing' onto
5645 static int migration_thread(void *data
)
5647 int cpu
= (long)data
;
5651 BUG_ON(rq
->migration_thread
!= current
);
5653 set_current_state(TASK_INTERRUPTIBLE
);
5654 while (!kthread_should_stop()) {
5655 struct migration_req
*req
;
5656 struct list_head
*head
;
5658 spin_lock_irq(&rq
->lock
);
5660 if (cpu_is_offline(cpu
)) {
5661 spin_unlock_irq(&rq
->lock
);
5665 if (rq
->active_balance
) {
5666 active_load_balance(rq
, cpu
);
5667 rq
->active_balance
= 0;
5670 head
= &rq
->migration_queue
;
5672 if (list_empty(head
)) {
5673 spin_unlock_irq(&rq
->lock
);
5675 set_current_state(TASK_INTERRUPTIBLE
);
5678 req
= list_entry(head
->next
, struct migration_req
, list
);
5679 list_del_init(head
->next
);
5681 spin_unlock(&rq
->lock
);
5682 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
5685 complete(&req
->done
);
5687 __set_current_state(TASK_RUNNING
);
5691 /* Wait for kthread_stop */
5692 set_current_state(TASK_INTERRUPTIBLE
);
5693 while (!kthread_should_stop()) {
5695 set_current_state(TASK_INTERRUPTIBLE
);
5697 __set_current_state(TASK_RUNNING
);
5701 #ifdef CONFIG_HOTPLUG_CPU
5703 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5707 local_irq_disable();
5708 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
5714 * Figure out where task on dead CPU should go, use force if necessary.
5715 * NOTE: interrupts should be disabled by the caller
5717 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
5719 unsigned long flags
;
5726 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
5727 cpus_and(mask
, mask
, p
->cpus_allowed
);
5728 dest_cpu
= any_online_cpu(mask
);
5730 /* On any allowed CPU? */
5731 if (dest_cpu
>= nr_cpu_ids
)
5732 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5734 /* No more Mr. Nice Guy. */
5735 if (dest_cpu
>= nr_cpu_ids
) {
5736 cpumask_t cpus_allowed
;
5738 cpuset_cpus_allowed_locked(p
, &cpus_allowed
);
5740 * Try to stay on the same cpuset, where the
5741 * current cpuset may be a subset of all cpus.
5742 * The cpuset_cpus_allowed_locked() variant of
5743 * cpuset_cpus_allowed() will not block. It must be
5744 * called within calls to cpuset_lock/cpuset_unlock.
5746 rq
= task_rq_lock(p
, &flags
);
5747 p
->cpus_allowed
= cpus_allowed
;
5748 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5749 task_rq_unlock(rq
, &flags
);
5752 * Don't tell them about moving exiting tasks or
5753 * kernel threads (both mm NULL), since they never
5756 if (p
->mm
&& printk_ratelimit()) {
5757 printk(KERN_INFO
"process %d (%s) no "
5758 "longer affine to cpu%d\n",
5759 task_pid_nr(p
), p
->comm
, dead_cpu
);
5762 } while (!__migrate_task_irq(p
, dead_cpu
, dest_cpu
));
5766 * While a dead CPU has no uninterruptible tasks queued at this point,
5767 * it might still have a nonzero ->nr_uninterruptible counter, because
5768 * for performance reasons the counter is not stricly tracking tasks to
5769 * their home CPUs. So we just add the counter to another CPU's counter,
5770 * to keep the global sum constant after CPU-down:
5772 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
5774 struct rq
*rq_dest
= cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR
));
5775 unsigned long flags
;
5777 local_irq_save(flags
);
5778 double_rq_lock(rq_src
, rq_dest
);
5779 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
5780 rq_src
->nr_uninterruptible
= 0;
5781 double_rq_unlock(rq_src
, rq_dest
);
5782 local_irq_restore(flags
);
5785 /* Run through task list and migrate tasks from the dead cpu. */
5786 static void migrate_live_tasks(int src_cpu
)
5788 struct task_struct
*p
, *t
;
5790 read_lock(&tasklist_lock
);
5792 do_each_thread(t
, p
) {
5796 if (task_cpu(p
) == src_cpu
)
5797 move_task_off_dead_cpu(src_cpu
, p
);
5798 } while_each_thread(t
, p
);
5800 read_unlock(&tasklist_lock
);
5804 * Schedules idle task to be the next runnable task on current CPU.
5805 * It does so by boosting its priority to highest possible.
5806 * Used by CPU offline code.
5808 void sched_idle_next(void)
5810 int this_cpu
= smp_processor_id();
5811 struct rq
*rq
= cpu_rq(this_cpu
);
5812 struct task_struct
*p
= rq
->idle
;
5813 unsigned long flags
;
5815 /* cpu has to be offline */
5816 BUG_ON(cpu_online(this_cpu
));
5819 * Strictly not necessary since rest of the CPUs are stopped by now
5820 * and interrupts disabled on the current cpu.
5822 spin_lock_irqsave(&rq
->lock
, flags
);
5824 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5826 update_rq_clock(rq
);
5827 activate_task(rq
, p
, 0);
5829 spin_unlock_irqrestore(&rq
->lock
, flags
);
5833 * Ensures that the idle task is using init_mm right before its cpu goes
5836 void idle_task_exit(void)
5838 struct mm_struct
*mm
= current
->active_mm
;
5840 BUG_ON(cpu_online(smp_processor_id()));
5843 switch_mm(mm
, &init_mm
, current
);
5847 /* called under rq->lock with disabled interrupts */
5848 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
5850 struct rq
*rq
= cpu_rq(dead_cpu
);
5852 /* Must be exiting, otherwise would be on tasklist. */
5853 BUG_ON(!p
->exit_state
);
5855 /* Cannot have done final schedule yet: would have vanished. */
5856 BUG_ON(p
->state
== TASK_DEAD
);
5861 * Drop lock around migration; if someone else moves it,
5862 * that's OK. No task can be added to this CPU, so iteration is
5865 spin_unlock_irq(&rq
->lock
);
5866 move_task_off_dead_cpu(dead_cpu
, p
);
5867 spin_lock_irq(&rq
->lock
);
5872 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5873 static void migrate_dead_tasks(unsigned int dead_cpu
)
5875 struct rq
*rq
= cpu_rq(dead_cpu
);
5876 struct task_struct
*next
;
5879 if (!rq
->nr_running
)
5881 update_rq_clock(rq
);
5882 next
= pick_next_task(rq
, rq
->curr
);
5885 migrate_dead(dead_cpu
, next
);
5889 #endif /* CONFIG_HOTPLUG_CPU */
5891 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5893 static struct ctl_table sd_ctl_dir
[] = {
5895 .procname
= "sched_domain",
5901 static struct ctl_table sd_ctl_root
[] = {
5903 .ctl_name
= CTL_KERN
,
5904 .procname
= "kernel",
5906 .child
= sd_ctl_dir
,
5911 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
5913 struct ctl_table
*entry
=
5914 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
5919 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
5921 struct ctl_table
*entry
;
5924 * In the intermediate directories, both the child directory and
5925 * procname are dynamically allocated and could fail but the mode
5926 * will always be set. In the lowest directory the names are
5927 * static strings and all have proc handlers.
5929 for (entry
= *tablep
; entry
->mode
; entry
++) {
5931 sd_free_ctl_entry(&entry
->child
);
5932 if (entry
->proc_handler
== NULL
)
5933 kfree(entry
->procname
);
5941 set_table_entry(struct ctl_table
*entry
,
5942 const char *procname
, void *data
, int maxlen
,
5943 mode_t mode
, proc_handler
*proc_handler
)
5945 entry
->procname
= procname
;
5947 entry
->maxlen
= maxlen
;
5949 entry
->proc_handler
= proc_handler
;
5952 static struct ctl_table
*
5953 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
5955 struct ctl_table
*table
= sd_alloc_ctl_entry(12);
5960 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
5961 sizeof(long), 0644, proc_doulongvec_minmax
);
5962 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
5963 sizeof(long), 0644, proc_doulongvec_minmax
);
5964 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
5965 sizeof(int), 0644, proc_dointvec_minmax
);
5966 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
5967 sizeof(int), 0644, proc_dointvec_minmax
);
5968 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
5969 sizeof(int), 0644, proc_dointvec_minmax
);
5970 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
5971 sizeof(int), 0644, proc_dointvec_minmax
);
5972 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
5973 sizeof(int), 0644, proc_dointvec_minmax
);
5974 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
5975 sizeof(int), 0644, proc_dointvec_minmax
);
5976 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
5977 sizeof(int), 0644, proc_dointvec_minmax
);
5978 set_table_entry(&table
[9], "cache_nice_tries",
5979 &sd
->cache_nice_tries
,
5980 sizeof(int), 0644, proc_dointvec_minmax
);
5981 set_table_entry(&table
[10], "flags", &sd
->flags
,
5982 sizeof(int), 0644, proc_dointvec_minmax
);
5983 /* &table[11] is terminator */
5988 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
5990 struct ctl_table
*entry
, *table
;
5991 struct sched_domain
*sd
;
5992 int domain_num
= 0, i
;
5995 for_each_domain(cpu
, sd
)
5997 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
6002 for_each_domain(cpu
, sd
) {
6003 snprintf(buf
, 32, "domain%d", i
);
6004 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
6006 entry
->child
= sd_alloc_ctl_domain_table(sd
);
6013 static struct ctl_table_header
*sd_sysctl_header
;
6014 static void register_sched_domain_sysctl(void)
6016 int i
, cpu_num
= num_online_cpus();
6017 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
6020 WARN_ON(sd_ctl_dir
[0].child
);
6021 sd_ctl_dir
[0].child
= entry
;
6026 for_each_online_cpu(i
) {
6027 snprintf(buf
, 32, "cpu%d", i
);
6028 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
6030 entry
->child
= sd_alloc_ctl_cpu_table(i
);
6034 WARN_ON(sd_sysctl_header
);
6035 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
6038 /* may be called multiple times per register */
6039 static void unregister_sched_domain_sysctl(void)
6041 if (sd_sysctl_header
)
6042 unregister_sysctl_table(sd_sysctl_header
);
6043 sd_sysctl_header
= NULL
;
6044 if (sd_ctl_dir
[0].child
)
6045 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
6048 static void register_sched_domain_sysctl(void)
6051 static void unregister_sched_domain_sysctl(void)
6057 * migration_call - callback that gets triggered when a CPU is added.
6058 * Here we can start up the necessary migration thread for the new CPU.
6060 static int __cpuinit
6061 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
6063 struct task_struct
*p
;
6064 int cpu
= (long)hcpu
;
6065 unsigned long flags
;
6070 case CPU_UP_PREPARE
:
6071 case CPU_UP_PREPARE_FROZEN
:
6072 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
6075 kthread_bind(p
, cpu
);
6076 /* Must be high prio: stop_machine expects to yield to it. */
6077 rq
= task_rq_lock(p
, &flags
);
6078 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
6079 task_rq_unlock(rq
, &flags
);
6080 cpu_rq(cpu
)->migration_thread
= p
;
6084 case CPU_ONLINE_FROZEN
:
6085 /* Strictly unnecessary, as first user will wake it. */
6086 wake_up_process(cpu_rq(cpu
)->migration_thread
);
6088 /* Update our root-domain */
6090 spin_lock_irqsave(&rq
->lock
, flags
);
6092 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
6093 cpu_set(cpu
, rq
->rd
->online
);
6095 spin_unlock_irqrestore(&rq
->lock
, flags
);
6098 #ifdef CONFIG_HOTPLUG_CPU
6099 case CPU_UP_CANCELED
:
6100 case CPU_UP_CANCELED_FROZEN
:
6101 if (!cpu_rq(cpu
)->migration_thread
)
6103 /* Unbind it from offline cpu so it can run. Fall thru. */
6104 kthread_bind(cpu_rq(cpu
)->migration_thread
,
6105 any_online_cpu(cpu_online_map
));
6106 kthread_stop(cpu_rq(cpu
)->migration_thread
);
6107 cpu_rq(cpu
)->migration_thread
= NULL
;
6111 case CPU_DEAD_FROZEN
:
6112 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6113 migrate_live_tasks(cpu
);
6115 kthread_stop(rq
->migration_thread
);
6116 rq
->migration_thread
= NULL
;
6117 /* Idle task back to normal (off runqueue, low prio) */
6118 spin_lock_irq(&rq
->lock
);
6119 update_rq_clock(rq
);
6120 deactivate_task(rq
, rq
->idle
, 0);
6121 rq
->idle
->static_prio
= MAX_PRIO
;
6122 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
6123 rq
->idle
->sched_class
= &idle_sched_class
;
6124 migrate_dead_tasks(cpu
);
6125 spin_unlock_irq(&rq
->lock
);
6127 migrate_nr_uninterruptible(rq
);
6128 BUG_ON(rq
->nr_running
!= 0);
6131 * No need to migrate the tasks: it was best-effort if
6132 * they didn't take sched_hotcpu_mutex. Just wake up
6135 spin_lock_irq(&rq
->lock
);
6136 while (!list_empty(&rq
->migration_queue
)) {
6137 struct migration_req
*req
;
6139 req
= list_entry(rq
->migration_queue
.next
,
6140 struct migration_req
, list
);
6141 list_del_init(&req
->list
);
6142 complete(&req
->done
);
6144 spin_unlock_irq(&rq
->lock
);
6148 case CPU_DYING_FROZEN
:
6149 /* Update our root-domain */
6151 spin_lock_irqsave(&rq
->lock
, flags
);
6153 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
6154 cpu_clear(cpu
, rq
->rd
->online
);
6156 spin_unlock_irqrestore(&rq
->lock
, flags
);
6163 /* Register at highest priority so that task migration (migrate_all_tasks)
6164 * happens before everything else.
6166 static struct notifier_block __cpuinitdata migration_notifier
= {
6167 .notifier_call
= migration_call
,
6171 void __init
migration_init(void)
6173 void *cpu
= (void *)(long)smp_processor_id();
6176 /* Start one for the boot CPU: */
6177 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
6178 BUG_ON(err
== NOTIFY_BAD
);
6179 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
6180 register_cpu_notifier(&migration_notifier
);
6186 #ifdef CONFIG_SCHED_DEBUG
6188 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
,
6189 cpumask_t
*groupmask
)
6191 struct sched_group
*group
= sd
->groups
;
6194 cpulist_scnprintf(str
, sizeof(str
), sd
->span
);
6195 cpus_clear(*groupmask
);
6197 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
6199 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
6200 printk("does not load-balance\n");
6202 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
6207 printk(KERN_CONT
"span %s\n", str
);
6209 if (!cpu_isset(cpu
, sd
->span
)) {
6210 printk(KERN_ERR
"ERROR: domain->span does not contain "
6213 if (!cpu_isset(cpu
, group
->cpumask
)) {
6214 printk(KERN_ERR
"ERROR: domain->groups does not contain"
6218 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
6222 printk(KERN_ERR
"ERROR: group is NULL\n");
6226 if (!group
->__cpu_power
) {
6227 printk(KERN_CONT
"\n");
6228 printk(KERN_ERR
"ERROR: domain->cpu_power not "
6233 if (!cpus_weight(group
->cpumask
)) {
6234 printk(KERN_CONT
"\n");
6235 printk(KERN_ERR
"ERROR: empty group\n");
6239 if (cpus_intersects(*groupmask
, group
->cpumask
)) {
6240 printk(KERN_CONT
"\n");
6241 printk(KERN_ERR
"ERROR: repeated CPUs\n");
6245 cpus_or(*groupmask
, *groupmask
, group
->cpumask
);
6247 cpulist_scnprintf(str
, sizeof(str
), group
->cpumask
);
6248 printk(KERN_CONT
" %s", str
);
6250 group
= group
->next
;
6251 } while (group
!= sd
->groups
);
6252 printk(KERN_CONT
"\n");
6254 if (!cpus_equal(sd
->span
, *groupmask
))
6255 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
6257 if (sd
->parent
&& !cpus_subset(*groupmask
, sd
->parent
->span
))
6258 printk(KERN_ERR
"ERROR: parent span is not a superset "
6259 "of domain->span\n");
6263 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
6265 cpumask_t
*groupmask
;
6269 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
6273 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
6275 groupmask
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
6277 printk(KERN_DEBUG
"Cannot load-balance (out of memory)\n");
6282 if (sched_domain_debug_one(sd
, cpu
, level
, groupmask
))
6292 # define sched_domain_debug(sd, cpu) do { } while (0)
6295 static int sd_degenerate(struct sched_domain
*sd
)
6297 if (cpus_weight(sd
->span
) == 1)
6300 /* Following flags need at least 2 groups */
6301 if (sd
->flags
& (SD_LOAD_BALANCE
|
6302 SD_BALANCE_NEWIDLE
|
6306 SD_SHARE_PKG_RESOURCES
)) {
6307 if (sd
->groups
!= sd
->groups
->next
)
6311 /* Following flags don't use groups */
6312 if (sd
->flags
& (SD_WAKE_IDLE
|
6321 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6323 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6325 if (sd_degenerate(parent
))
6328 if (!cpus_equal(sd
->span
, parent
->span
))
6331 /* Does parent contain flags not in child? */
6332 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6333 if (cflags
& SD_WAKE_AFFINE
)
6334 pflags
&= ~SD_WAKE_BALANCE
;
6335 /* Flags needing groups don't count if only 1 group in parent */
6336 if (parent
->groups
== parent
->groups
->next
) {
6337 pflags
&= ~(SD_LOAD_BALANCE
|
6338 SD_BALANCE_NEWIDLE
|
6342 SD_SHARE_PKG_RESOURCES
);
6344 if (~cflags
& pflags
)
6350 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6352 unsigned long flags
;
6353 const struct sched_class
*class;
6355 spin_lock_irqsave(&rq
->lock
, flags
);
6358 struct root_domain
*old_rd
= rq
->rd
;
6360 for (class = sched_class_highest
; class; class = class->next
) {
6361 if (class->leave_domain
)
6362 class->leave_domain(rq
);
6365 cpu_clear(rq
->cpu
, old_rd
->span
);
6366 cpu_clear(rq
->cpu
, old_rd
->online
);
6368 if (atomic_dec_and_test(&old_rd
->refcount
))
6372 atomic_inc(&rd
->refcount
);
6375 cpu_set(rq
->cpu
, rd
->span
);
6376 if (cpu_isset(rq
->cpu
, cpu_online_map
))
6377 cpu_set(rq
->cpu
, rd
->online
);
6379 for (class = sched_class_highest
; class; class = class->next
) {
6380 if (class->join_domain
)
6381 class->join_domain(rq
);
6384 spin_unlock_irqrestore(&rq
->lock
, flags
);
6387 static void init_rootdomain(struct root_domain
*rd
)
6389 memset(rd
, 0, sizeof(*rd
));
6391 cpus_clear(rd
->span
);
6392 cpus_clear(rd
->online
);
6395 static void init_defrootdomain(void)
6397 init_rootdomain(&def_root_domain
);
6398 atomic_set(&def_root_domain
.refcount
, 1);
6401 static struct root_domain
*alloc_rootdomain(void)
6403 struct root_domain
*rd
;
6405 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6409 init_rootdomain(rd
);
6415 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6416 * hold the hotplug lock.
6419 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6421 struct rq
*rq
= cpu_rq(cpu
);
6422 struct sched_domain
*tmp
;
6424 /* Remove the sched domains which do not contribute to scheduling. */
6425 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
6426 struct sched_domain
*parent
= tmp
->parent
;
6429 if (sd_parent_degenerate(tmp
, parent
)) {
6430 tmp
->parent
= parent
->parent
;
6432 parent
->parent
->child
= tmp
;
6436 if (sd
&& sd_degenerate(sd
)) {
6442 sched_domain_debug(sd
, cpu
);
6444 rq_attach_root(rq
, rd
);
6445 rcu_assign_pointer(rq
->sd
, sd
);
6448 /* cpus with isolated domains */
6449 static cpumask_t cpu_isolated_map
= CPU_MASK_NONE
;
6451 /* Setup the mask of cpus configured for isolated domains */
6452 static int __init
isolated_cpu_setup(char *str
)
6454 int ints
[NR_CPUS
], i
;
6456 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
6457 cpus_clear(cpu_isolated_map
);
6458 for (i
= 1; i
<= ints
[0]; i
++)
6459 if (ints
[i
] < NR_CPUS
)
6460 cpu_set(ints
[i
], cpu_isolated_map
);
6464 __setup("isolcpus=", isolated_cpu_setup
);
6467 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6468 * to a function which identifies what group(along with sched group) a CPU
6469 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6470 * (due to the fact that we keep track of groups covered with a cpumask_t).
6472 * init_sched_build_groups will build a circular linked list of the groups
6473 * covered by the given span, and will set each group's ->cpumask correctly,
6474 * and ->cpu_power to 0.
6477 init_sched_build_groups(const cpumask_t
*span
, const cpumask_t
*cpu_map
,
6478 int (*group_fn
)(int cpu
, const cpumask_t
*cpu_map
,
6479 struct sched_group
**sg
,
6480 cpumask_t
*tmpmask
),
6481 cpumask_t
*covered
, cpumask_t
*tmpmask
)
6483 struct sched_group
*first
= NULL
, *last
= NULL
;
6486 cpus_clear(*covered
);
6488 for_each_cpu_mask(i
, *span
) {
6489 struct sched_group
*sg
;
6490 int group
= group_fn(i
, cpu_map
, &sg
, tmpmask
);
6493 if (cpu_isset(i
, *covered
))
6496 cpus_clear(sg
->cpumask
);
6497 sg
->__cpu_power
= 0;
6499 for_each_cpu_mask(j
, *span
) {
6500 if (group_fn(j
, cpu_map
, NULL
, tmpmask
) != group
)
6503 cpu_set(j
, *covered
);
6504 cpu_set(j
, sg
->cpumask
);
6515 #define SD_NODES_PER_DOMAIN 16
6520 * find_next_best_node - find the next node to include in a sched_domain
6521 * @node: node whose sched_domain we're building
6522 * @used_nodes: nodes already in the sched_domain
6524 * Find the next node to include in a given scheduling domain. Simply
6525 * finds the closest node not already in the @used_nodes map.
6527 * Should use nodemask_t.
6529 static int find_next_best_node(int node
, nodemask_t
*used_nodes
)
6531 int i
, n
, val
, min_val
, best_node
= 0;
6535 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6536 /* Start at @node */
6537 n
= (node
+ i
) % MAX_NUMNODES
;
6539 if (!nr_cpus_node(n
))
6542 /* Skip already used nodes */
6543 if (node_isset(n
, *used_nodes
))
6546 /* Simple min distance search */
6547 val
= node_distance(node
, n
);
6549 if (val
< min_val
) {
6555 node_set(best_node
, *used_nodes
);
6560 * sched_domain_node_span - get a cpumask for a node's sched_domain
6561 * @node: node whose cpumask we're constructing
6562 * @span: resulting cpumask
6564 * Given a node, construct a good cpumask for its sched_domain to span. It
6565 * should be one that prevents unnecessary balancing, but also spreads tasks
6568 static void sched_domain_node_span(int node
, cpumask_t
*span
)
6570 nodemask_t used_nodes
;
6571 node_to_cpumask_ptr(nodemask
, node
);
6575 nodes_clear(used_nodes
);
6577 cpus_or(*span
, *span
, *nodemask
);
6578 node_set(node
, used_nodes
);
6580 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
6581 int next_node
= find_next_best_node(node
, &used_nodes
);
6583 node_to_cpumask_ptr_next(nodemask
, next_node
);
6584 cpus_or(*span
, *span
, *nodemask
);
6589 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
6592 * SMT sched-domains:
6594 #ifdef CONFIG_SCHED_SMT
6595 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6596 static DEFINE_PER_CPU(struct sched_group
, sched_group_cpus
);
6599 cpu_to_cpu_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
6603 *sg
= &per_cpu(sched_group_cpus
, cpu
);
6609 * multi-core sched-domains:
6611 #ifdef CONFIG_SCHED_MC
6612 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6613 static DEFINE_PER_CPU(struct sched_group
, sched_group_core
);
6616 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6618 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
6623 *mask
= per_cpu(cpu_sibling_map
, cpu
);
6624 cpus_and(*mask
, *mask
, *cpu_map
);
6625 group
= first_cpu(*mask
);
6627 *sg
= &per_cpu(sched_group_core
, group
);
6630 #elif defined(CONFIG_SCHED_MC)
6632 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
6636 *sg
= &per_cpu(sched_group_core
, cpu
);
6641 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6642 static DEFINE_PER_CPU(struct sched_group
, sched_group_phys
);
6645 cpu_to_phys_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
,
6649 #ifdef CONFIG_SCHED_MC
6650 *mask
= cpu_coregroup_map(cpu
);
6651 cpus_and(*mask
, *mask
, *cpu_map
);
6652 group
= first_cpu(*mask
);
6653 #elif defined(CONFIG_SCHED_SMT)
6654 *mask
= per_cpu(cpu_sibling_map
, cpu
);
6655 cpus_and(*mask
, *mask
, *cpu_map
);
6656 group
= first_cpu(*mask
);
6661 *sg
= &per_cpu(sched_group_phys
, group
);
6667 * The init_sched_build_groups can't handle what we want to do with node
6668 * groups, so roll our own. Now each node has its own list of groups which
6669 * gets dynamically allocated.
6671 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6672 static struct sched_group
***sched_group_nodes_bycpu
;
6674 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6675 static DEFINE_PER_CPU(struct sched_group
, sched_group_allnodes
);
6677 static int cpu_to_allnodes_group(int cpu
, const cpumask_t
*cpu_map
,
6678 struct sched_group
**sg
, cpumask_t
*nodemask
)
6682 *nodemask
= node_to_cpumask(cpu_to_node(cpu
));
6683 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
6684 group
= first_cpu(*nodemask
);
6687 *sg
= &per_cpu(sched_group_allnodes
, group
);
6691 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6693 struct sched_group
*sg
= group_head
;
6699 for_each_cpu_mask(j
, sg
->cpumask
) {
6700 struct sched_domain
*sd
;
6702 sd
= &per_cpu(phys_domains
, j
);
6703 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6705 * Only add "power" once for each
6711 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
6714 } while (sg
!= group_head
);
6719 /* Free memory allocated for various sched_group structures */
6720 static void free_sched_groups(const cpumask_t
*cpu_map
, cpumask_t
*nodemask
)
6724 for_each_cpu_mask(cpu
, *cpu_map
) {
6725 struct sched_group
**sched_group_nodes
6726 = sched_group_nodes_bycpu
[cpu
];
6728 if (!sched_group_nodes
)
6731 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6732 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6734 *nodemask
= node_to_cpumask(i
);
6735 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
6736 if (cpus_empty(*nodemask
))
6746 if (oldsg
!= sched_group_nodes
[i
])
6749 kfree(sched_group_nodes
);
6750 sched_group_nodes_bycpu
[cpu
] = NULL
;
6754 static void free_sched_groups(const cpumask_t
*cpu_map
, cpumask_t
*nodemask
)
6760 * Initialize sched groups cpu_power.
6762 * cpu_power indicates the capacity of sched group, which is used while
6763 * distributing the load between different sched groups in a sched domain.
6764 * Typically cpu_power for all the groups in a sched domain will be same unless
6765 * there are asymmetries in the topology. If there are asymmetries, group
6766 * having more cpu_power will pickup more load compared to the group having
6769 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6770 * the maximum number of tasks a group can handle in the presence of other idle
6771 * or lightly loaded groups in the same sched domain.
6773 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
6775 struct sched_domain
*child
;
6776 struct sched_group
*group
;
6778 WARN_ON(!sd
|| !sd
->groups
);
6780 if (cpu
!= first_cpu(sd
->groups
->cpumask
))
6785 sd
->groups
->__cpu_power
= 0;
6788 * For perf policy, if the groups in child domain share resources
6789 * (for example cores sharing some portions of the cache hierarchy
6790 * or SMT), then set this domain groups cpu_power such that each group
6791 * can handle only one task, when there are other idle groups in the
6792 * same sched domain.
6794 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
6796 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
6797 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
6802 * add cpu_power of each child group to this groups cpu_power
6804 group
= child
->groups
;
6806 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
6807 group
= group
->next
;
6808 } while (group
!= child
->groups
);
6812 * Initializers for schedule domains
6813 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6816 #define SD_INIT(sd, type) sd_init_##type(sd)
6817 #define SD_INIT_FUNC(type) \
6818 static noinline void sd_init_##type(struct sched_domain *sd) \
6820 memset(sd, 0, sizeof(*sd)); \
6821 *sd = SD_##type##_INIT; \
6822 sd->level = SD_LV_##type; \
6827 SD_INIT_FUNC(ALLNODES
)
6830 #ifdef CONFIG_SCHED_SMT
6831 SD_INIT_FUNC(SIBLING
)
6833 #ifdef CONFIG_SCHED_MC
6838 * To minimize stack usage kmalloc room for cpumasks and share the
6839 * space as the usage in build_sched_domains() dictates. Used only
6840 * if the amount of space is significant.
6843 cpumask_t tmpmask
; /* make this one first */
6846 cpumask_t this_sibling_map
;
6847 cpumask_t this_core_map
;
6849 cpumask_t send_covered
;
6852 cpumask_t domainspan
;
6854 cpumask_t notcovered
;
6859 #define SCHED_CPUMASK_ALLOC 1
6860 #define SCHED_CPUMASK_FREE(v) kfree(v)
6861 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
6863 #define SCHED_CPUMASK_ALLOC 0
6864 #define SCHED_CPUMASK_FREE(v)
6865 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
6868 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
6869 ((unsigned long)(a) + offsetof(struct allmasks, v))
6871 static int default_relax_domain_level
= -1;
6873 static int __init
setup_relax_domain_level(char *str
)
6875 default_relax_domain_level
= simple_strtoul(str
, NULL
, 0);
6878 __setup("relax_domain_level=", setup_relax_domain_level
);
6880 static void set_domain_attribute(struct sched_domain
*sd
,
6881 struct sched_domain_attr
*attr
)
6885 if (!attr
|| attr
->relax_domain_level
< 0) {
6886 if (default_relax_domain_level
< 0)
6889 request
= default_relax_domain_level
;
6891 request
= attr
->relax_domain_level
;
6892 if (request
< sd
->level
) {
6893 /* turn off idle balance on this domain */
6894 sd
->flags
&= ~(SD_WAKE_IDLE
|SD_BALANCE_NEWIDLE
);
6896 /* turn on idle balance on this domain */
6897 sd
->flags
|= (SD_WAKE_IDLE_FAR
|SD_BALANCE_NEWIDLE
);
6902 * Build sched domains for a given set of cpus and attach the sched domains
6903 * to the individual cpus
6905 static int __build_sched_domains(const cpumask_t
*cpu_map
,
6906 struct sched_domain_attr
*attr
)
6909 struct root_domain
*rd
;
6910 SCHED_CPUMASK_DECLARE(allmasks
);
6913 struct sched_group
**sched_group_nodes
= NULL
;
6914 int sd_allnodes
= 0;
6917 * Allocate the per-node list of sched groups
6919 sched_group_nodes
= kcalloc(MAX_NUMNODES
, sizeof(struct sched_group
*),
6921 if (!sched_group_nodes
) {
6922 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6927 rd
= alloc_rootdomain();
6929 printk(KERN_WARNING
"Cannot alloc root domain\n");
6931 kfree(sched_group_nodes
);
6936 #if SCHED_CPUMASK_ALLOC
6937 /* get space for all scratch cpumask variables */
6938 allmasks
= kmalloc(sizeof(*allmasks
), GFP_KERNEL
);
6940 printk(KERN_WARNING
"Cannot alloc cpumask array\n");
6943 kfree(sched_group_nodes
);
6948 tmpmask
= (cpumask_t
*)allmasks
;
6952 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6956 * Set up domains for cpus specified by the cpu_map.
6958 for_each_cpu_mask(i
, *cpu_map
) {
6959 struct sched_domain
*sd
= NULL
, *p
;
6960 SCHED_CPUMASK_VAR(nodemask
, allmasks
);
6962 *nodemask
= node_to_cpumask(cpu_to_node(i
));
6963 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
6966 if (cpus_weight(*cpu_map
) >
6967 SD_NODES_PER_DOMAIN
*cpus_weight(*nodemask
)) {
6968 sd
= &per_cpu(allnodes_domains
, i
);
6969 SD_INIT(sd
, ALLNODES
);
6970 set_domain_attribute(sd
, attr
);
6971 sd
->span
= *cpu_map
;
6972 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
6978 sd
= &per_cpu(node_domains
, i
);
6980 set_domain_attribute(sd
, attr
);
6981 sched_domain_node_span(cpu_to_node(i
), &sd
->span
);
6985 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6989 sd
= &per_cpu(phys_domains
, i
);
6991 set_domain_attribute(sd
, attr
);
6992 sd
->span
= *nodemask
;
6996 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
6998 #ifdef CONFIG_SCHED_MC
7000 sd
= &per_cpu(core_domains
, i
);
7002 set_domain_attribute(sd
, attr
);
7003 sd
->span
= cpu_coregroup_map(i
);
7004 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
7007 cpu_to_core_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7010 #ifdef CONFIG_SCHED_SMT
7012 sd
= &per_cpu(cpu_domains
, i
);
7013 SD_INIT(sd
, SIBLING
);
7014 set_domain_attribute(sd
, attr
);
7015 sd
->span
= per_cpu(cpu_sibling_map
, i
);
7016 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
7019 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
7023 #ifdef CONFIG_SCHED_SMT
7024 /* Set up CPU (sibling) groups */
7025 for_each_cpu_mask(i
, *cpu_map
) {
7026 SCHED_CPUMASK_VAR(this_sibling_map
, allmasks
);
7027 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7029 *this_sibling_map
= per_cpu(cpu_sibling_map
, i
);
7030 cpus_and(*this_sibling_map
, *this_sibling_map
, *cpu_map
);
7031 if (i
!= first_cpu(*this_sibling_map
))
7034 init_sched_build_groups(this_sibling_map
, cpu_map
,
7036 send_covered
, tmpmask
);
7040 #ifdef CONFIG_SCHED_MC
7041 /* Set up multi-core groups */
7042 for_each_cpu_mask(i
, *cpu_map
) {
7043 SCHED_CPUMASK_VAR(this_core_map
, allmasks
);
7044 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7046 *this_core_map
= cpu_coregroup_map(i
);
7047 cpus_and(*this_core_map
, *this_core_map
, *cpu_map
);
7048 if (i
!= first_cpu(*this_core_map
))
7051 init_sched_build_groups(this_core_map
, cpu_map
,
7053 send_covered
, tmpmask
);
7057 /* Set up physical groups */
7058 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
7059 SCHED_CPUMASK_VAR(nodemask
, allmasks
);
7060 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7062 *nodemask
= node_to_cpumask(i
);
7063 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7064 if (cpus_empty(*nodemask
))
7067 init_sched_build_groups(nodemask
, cpu_map
,
7069 send_covered
, tmpmask
);
7073 /* Set up node groups */
7075 SCHED_CPUMASK_VAR(send_covered
, allmasks
);
7077 init_sched_build_groups(cpu_map
, cpu_map
,
7078 &cpu_to_allnodes_group
,
7079 send_covered
, tmpmask
);
7082 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
7083 /* Set up node groups */
7084 struct sched_group
*sg
, *prev
;
7085 SCHED_CPUMASK_VAR(nodemask
, allmasks
);
7086 SCHED_CPUMASK_VAR(domainspan
, allmasks
);
7087 SCHED_CPUMASK_VAR(covered
, allmasks
);
7090 *nodemask
= node_to_cpumask(i
);
7091 cpus_clear(*covered
);
7093 cpus_and(*nodemask
, *nodemask
, *cpu_map
);
7094 if (cpus_empty(*nodemask
)) {
7095 sched_group_nodes
[i
] = NULL
;
7099 sched_domain_node_span(i
, domainspan
);
7100 cpus_and(*domainspan
, *domainspan
, *cpu_map
);
7102 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
7104 printk(KERN_WARNING
"Can not alloc domain group for "
7108 sched_group_nodes
[i
] = sg
;
7109 for_each_cpu_mask(j
, *nodemask
) {
7110 struct sched_domain
*sd
;
7112 sd
= &per_cpu(node_domains
, j
);
7115 sg
->__cpu_power
= 0;
7116 sg
->cpumask
= *nodemask
;
7118 cpus_or(*covered
, *covered
, *nodemask
);
7121 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
7122 SCHED_CPUMASK_VAR(notcovered
, allmasks
);
7123 int n
= (i
+ j
) % MAX_NUMNODES
;
7124 node_to_cpumask_ptr(pnodemask
, n
);
7126 cpus_complement(*notcovered
, *covered
);
7127 cpus_and(*tmpmask
, *notcovered
, *cpu_map
);
7128 cpus_and(*tmpmask
, *tmpmask
, *domainspan
);
7129 if (cpus_empty(*tmpmask
))
7132 cpus_and(*tmpmask
, *tmpmask
, *pnodemask
);
7133 if (cpus_empty(*tmpmask
))
7136 sg
= kmalloc_node(sizeof(struct sched_group
),
7140 "Can not alloc domain group for node %d\n", j
);
7143 sg
->__cpu_power
= 0;
7144 sg
->cpumask
= *tmpmask
;
7145 sg
->next
= prev
->next
;
7146 cpus_or(*covered
, *covered
, *tmpmask
);
7153 /* Calculate CPU power for physical packages and nodes */
7154 #ifdef CONFIG_SCHED_SMT
7155 for_each_cpu_mask(i
, *cpu_map
) {
7156 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
);
7158 init_sched_groups_power(i
, sd
);
7161 #ifdef CONFIG_SCHED_MC
7162 for_each_cpu_mask(i
, *cpu_map
) {
7163 struct sched_domain
*sd
= &per_cpu(core_domains
, i
);
7165 init_sched_groups_power(i
, sd
);
7169 for_each_cpu_mask(i
, *cpu_map
) {
7170 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
);
7172 init_sched_groups_power(i
, sd
);
7176 for (i
= 0; i
< MAX_NUMNODES
; i
++)
7177 init_numa_sched_groups_power(sched_group_nodes
[i
]);
7180 struct sched_group
*sg
;
7182 cpu_to_allnodes_group(first_cpu(*cpu_map
), cpu_map
, &sg
,
7184 init_numa_sched_groups_power(sg
);
7188 /* Attach the domains */
7189 for_each_cpu_mask(i
, *cpu_map
) {
7190 struct sched_domain
*sd
;
7191 #ifdef CONFIG_SCHED_SMT
7192 sd
= &per_cpu(cpu_domains
, i
);
7193 #elif defined(CONFIG_SCHED_MC)
7194 sd
= &per_cpu(core_domains
, i
);
7196 sd
= &per_cpu(phys_domains
, i
);
7198 cpu_attach_domain(sd
, rd
, i
);
7201 SCHED_CPUMASK_FREE((void *)allmasks
);
7206 free_sched_groups(cpu_map
, tmpmask
);
7207 SCHED_CPUMASK_FREE((void *)allmasks
);
7212 static int build_sched_domains(const cpumask_t
*cpu_map
)
7214 return __build_sched_domains(cpu_map
, NULL
);
7217 static cpumask_t
*doms_cur
; /* current sched domains */
7218 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
7219 static struct sched_domain_attr
*dattr_cur
;
7220 /* attribues of custom domains in 'doms_cur' */
7223 * Special case: If a kmalloc of a doms_cur partition (array of
7224 * cpumask_t) fails, then fallback to a single sched domain,
7225 * as determined by the single cpumask_t fallback_doms.
7227 static cpumask_t fallback_doms
;
7229 void __attribute__((weak
)) arch_update_cpu_topology(void)
7234 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7235 * For now this just excludes isolated cpus, but could be used to
7236 * exclude other special cases in the future.
7238 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
7242 arch_update_cpu_topology();
7244 doms_cur
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
7246 doms_cur
= &fallback_doms
;
7247 cpus_andnot(*doms_cur
, *cpu_map
, cpu_isolated_map
);
7249 err
= build_sched_domains(doms_cur
);
7250 register_sched_domain_sysctl();
7255 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
,
7258 free_sched_groups(cpu_map
, tmpmask
);
7262 * Detach sched domains from a group of cpus specified in cpu_map
7263 * These cpus will now be attached to the NULL domain
7265 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
7270 unregister_sched_domain_sysctl();
7272 for_each_cpu_mask(i
, *cpu_map
)
7273 cpu_attach_domain(NULL
, &def_root_domain
, i
);
7274 synchronize_sched();
7275 arch_destroy_sched_domains(cpu_map
, &tmpmask
);
7278 /* handle null as "default" */
7279 static int dattrs_equal(struct sched_domain_attr
*cur
, int idx_cur
,
7280 struct sched_domain_attr
*new, int idx_new
)
7282 struct sched_domain_attr tmp
;
7289 return !memcmp(cur
? (cur
+ idx_cur
) : &tmp
,
7290 new ? (new + idx_new
) : &tmp
,
7291 sizeof(struct sched_domain_attr
));
7295 * Partition sched domains as specified by the 'ndoms_new'
7296 * cpumasks in the array doms_new[] of cpumasks. This compares
7297 * doms_new[] to the current sched domain partitioning, doms_cur[].
7298 * It destroys each deleted domain and builds each new domain.
7300 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7301 * The masks don't intersect (don't overlap.) We should setup one
7302 * sched domain for each mask. CPUs not in any of the cpumasks will
7303 * not be load balanced. If the same cpumask appears both in the
7304 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7307 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7308 * ownership of it and will kfree it when done with it. If the caller
7309 * failed the kmalloc call, then it can pass in doms_new == NULL,
7310 * and partition_sched_domains() will fallback to the single partition
7313 * Call with hotplug lock held
7315 void partition_sched_domains(int ndoms_new
, cpumask_t
*doms_new
,
7316 struct sched_domain_attr
*dattr_new
)
7320 mutex_lock(&sched_domains_mutex
);
7322 /* always unregister in case we don't destroy any domains */
7323 unregister_sched_domain_sysctl();
7325 if (doms_new
== NULL
) {
7327 doms_new
= &fallback_doms
;
7328 cpus_andnot(doms_new
[0], cpu_online_map
, cpu_isolated_map
);
7332 /* Destroy deleted domains */
7333 for (i
= 0; i
< ndoms_cur
; i
++) {
7334 for (j
= 0; j
< ndoms_new
; j
++) {
7335 if (cpus_equal(doms_cur
[i
], doms_new
[j
])
7336 && dattrs_equal(dattr_cur
, i
, dattr_new
, j
))
7339 /* no match - a current sched domain not in new doms_new[] */
7340 detach_destroy_domains(doms_cur
+ i
);
7345 /* Build new domains */
7346 for (i
= 0; i
< ndoms_new
; i
++) {
7347 for (j
= 0; j
< ndoms_cur
; j
++) {
7348 if (cpus_equal(doms_new
[i
], doms_cur
[j
])
7349 && dattrs_equal(dattr_new
, i
, dattr_cur
, j
))
7352 /* no match - add a new doms_new */
7353 __build_sched_domains(doms_new
+ i
,
7354 dattr_new
? dattr_new
+ i
: NULL
);
7359 /* Remember the new sched domains */
7360 if (doms_cur
!= &fallback_doms
)
7362 kfree(dattr_cur
); /* kfree(NULL) is safe */
7363 doms_cur
= doms_new
;
7364 dattr_cur
= dattr_new
;
7365 ndoms_cur
= ndoms_new
;
7367 register_sched_domain_sysctl();
7369 mutex_unlock(&sched_domains_mutex
);
7372 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7373 int arch_reinit_sched_domains(void)
7378 mutex_lock(&sched_domains_mutex
);
7379 detach_destroy_domains(&cpu_online_map
);
7380 err
= arch_init_sched_domains(&cpu_online_map
);
7381 mutex_unlock(&sched_domains_mutex
);
7387 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
7391 if (buf
[0] != '0' && buf
[0] != '1')
7395 sched_smt_power_savings
= (buf
[0] == '1');
7397 sched_mc_power_savings
= (buf
[0] == '1');
7399 ret
= arch_reinit_sched_domains();
7401 return ret
? ret
: count
;
7404 #ifdef CONFIG_SCHED_MC
7405 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
7407 return sprintf(page
, "%u\n", sched_mc_power_savings
);
7409 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
7410 const char *buf
, size_t count
)
7412 return sched_power_savings_store(buf
, count
, 0);
7414 static SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
7415 sched_mc_power_savings_store
);
7418 #ifdef CONFIG_SCHED_SMT
7419 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
7421 return sprintf(page
, "%u\n", sched_smt_power_savings
);
7423 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
7424 const char *buf
, size_t count
)
7426 return sched_power_savings_store(buf
, count
, 1);
7428 static SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
7429 sched_smt_power_savings_store
);
7432 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
7436 #ifdef CONFIG_SCHED_SMT
7438 err
= sysfs_create_file(&cls
->kset
.kobj
,
7439 &attr_sched_smt_power_savings
.attr
);
7441 #ifdef CONFIG_SCHED_MC
7442 if (!err
&& mc_capable())
7443 err
= sysfs_create_file(&cls
->kset
.kobj
,
7444 &attr_sched_mc_power_savings
.attr
);
7451 * Force a reinitialization of the sched domains hierarchy. The domains
7452 * and groups cannot be updated in place without racing with the balancing
7453 * code, so we temporarily attach all running cpus to the NULL domain
7454 * which will prevent rebalancing while the sched domains are recalculated.
7456 static int update_sched_domains(struct notifier_block
*nfb
,
7457 unsigned long action
, void *hcpu
)
7460 case CPU_UP_PREPARE
:
7461 case CPU_UP_PREPARE_FROZEN
:
7462 case CPU_DOWN_PREPARE
:
7463 case CPU_DOWN_PREPARE_FROZEN
:
7464 detach_destroy_domains(&cpu_online_map
);
7467 case CPU_UP_CANCELED
:
7468 case CPU_UP_CANCELED_FROZEN
:
7469 case CPU_DOWN_FAILED
:
7470 case CPU_DOWN_FAILED_FROZEN
:
7472 case CPU_ONLINE_FROZEN
:
7474 case CPU_DEAD_FROZEN
:
7476 * Fall through and re-initialise the domains.
7483 /* The hotplug lock is already held by cpu_up/cpu_down */
7484 arch_init_sched_domains(&cpu_online_map
);
7489 void __init
sched_init_smp(void)
7491 cpumask_t non_isolated_cpus
;
7493 #if defined(CONFIG_NUMA)
7494 sched_group_nodes_bycpu
= kzalloc(nr_cpu_ids
* sizeof(void **),
7496 BUG_ON(sched_group_nodes_bycpu
== NULL
);
7499 mutex_lock(&sched_domains_mutex
);
7500 arch_init_sched_domains(&cpu_online_map
);
7501 cpus_andnot(non_isolated_cpus
, cpu_possible_map
, cpu_isolated_map
);
7502 if (cpus_empty(non_isolated_cpus
))
7503 cpu_set(smp_processor_id(), non_isolated_cpus
);
7504 mutex_unlock(&sched_domains_mutex
);
7506 /* XXX: Theoretical race here - CPU may be hotplugged now */
7507 hotcpu_notifier(update_sched_domains
, 0);
7510 /* Move init over to a non-isolated CPU */
7511 if (set_cpus_allowed_ptr(current
, &non_isolated_cpus
) < 0)
7513 sched_init_granularity();
7516 void __init
sched_init_smp(void)
7518 sched_init_granularity();
7520 #endif /* CONFIG_SMP */
7522 int in_sched_functions(unsigned long addr
)
7524 return in_lock_functions(addr
) ||
7525 (addr
>= (unsigned long)__sched_text_start
7526 && addr
< (unsigned long)__sched_text_end
);
7529 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
7531 cfs_rq
->tasks_timeline
= RB_ROOT
;
7532 INIT_LIST_HEAD(&cfs_rq
->tasks
);
7533 #ifdef CONFIG_FAIR_GROUP_SCHED
7536 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
7539 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
7541 struct rt_prio_array
*array
;
7544 array
= &rt_rq
->active
;
7545 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
7546 INIT_LIST_HEAD(array
->queue
+ i
);
7547 __clear_bit(i
, array
->bitmap
);
7549 /* delimiter for bitsearch: */
7550 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
7552 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7553 rt_rq
->highest_prio
= MAX_RT_PRIO
;
7556 rt_rq
->rt_nr_migratory
= 0;
7557 rt_rq
->overloaded
= 0;
7561 rt_rq
->rt_throttled
= 0;
7562 rt_rq
->rt_runtime
= 0;
7563 spin_lock_init(&rt_rq
->rt_runtime_lock
);
7565 #ifdef CONFIG_RT_GROUP_SCHED
7566 rt_rq
->rt_nr_boosted
= 0;
7571 #ifdef CONFIG_FAIR_GROUP_SCHED
7572 static void init_tg_cfs_entry(struct task_group
*tg
, struct cfs_rq
*cfs_rq
,
7573 struct sched_entity
*se
, int cpu
, int add
,
7574 struct sched_entity
*parent
)
7576 struct rq
*rq
= cpu_rq(cpu
);
7577 tg
->cfs_rq
[cpu
] = cfs_rq
;
7578 init_cfs_rq(cfs_rq
, rq
);
7581 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7584 /* se could be NULL for init_task_group */
7589 se
->cfs_rq
= &rq
->cfs
;
7591 se
->cfs_rq
= parent
->my_q
;
7594 se
->load
.weight
= tg
->shares
;
7595 se
->load
.inv_weight
= 0;
7596 se
->parent
= parent
;
7600 #ifdef CONFIG_RT_GROUP_SCHED
7601 static void init_tg_rt_entry(struct task_group
*tg
, struct rt_rq
*rt_rq
,
7602 struct sched_rt_entity
*rt_se
, int cpu
, int add
,
7603 struct sched_rt_entity
*parent
)
7605 struct rq
*rq
= cpu_rq(cpu
);
7607 tg
->rt_rq
[cpu
] = rt_rq
;
7608 init_rt_rq(rt_rq
, rq
);
7610 rt_rq
->rt_se
= rt_se
;
7611 rt_rq
->rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
7613 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
7615 tg
->rt_se
[cpu
] = rt_se
;
7620 rt_se
->rt_rq
= &rq
->rt
;
7622 rt_se
->rt_rq
= parent
->my_q
;
7624 rt_se
->rt_rq
= &rq
->rt
;
7625 rt_se
->my_q
= rt_rq
;
7626 rt_se
->parent
= parent
;
7627 INIT_LIST_HEAD(&rt_se
->run_list
);
7631 void __init
sched_init(void)
7634 unsigned long alloc_size
= 0, ptr
;
7636 #ifdef CONFIG_FAIR_GROUP_SCHED
7637 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
7639 #ifdef CONFIG_RT_GROUP_SCHED
7640 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
7642 #ifdef CONFIG_USER_SCHED
7646 * As sched_init() is called before page_alloc is setup,
7647 * we use alloc_bootmem().
7650 ptr
= (unsigned long)alloc_bootmem(alloc_size
);
7652 #ifdef CONFIG_FAIR_GROUP_SCHED
7653 init_task_group
.se
= (struct sched_entity
**)ptr
;
7654 ptr
+= nr_cpu_ids
* sizeof(void **);
7656 init_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
7657 ptr
+= nr_cpu_ids
* sizeof(void **);
7659 #ifdef CONFIG_USER_SCHED
7660 root_task_group
.se
= (struct sched_entity
**)ptr
;
7661 ptr
+= nr_cpu_ids
* sizeof(void **);
7663 root_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
7664 ptr
+= nr_cpu_ids
* sizeof(void **);
7667 #ifdef CONFIG_RT_GROUP_SCHED
7668 init_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
7669 ptr
+= nr_cpu_ids
* sizeof(void **);
7671 init_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
7672 ptr
+= nr_cpu_ids
* sizeof(void **);
7674 #ifdef CONFIG_USER_SCHED
7675 root_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
7676 ptr
+= nr_cpu_ids
* sizeof(void **);
7678 root_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
7679 ptr
+= nr_cpu_ids
* sizeof(void **);
7685 init_defrootdomain();
7688 init_rt_bandwidth(&def_rt_bandwidth
,
7689 global_rt_period(), global_rt_runtime());
7691 #ifdef CONFIG_RT_GROUP_SCHED
7692 init_rt_bandwidth(&init_task_group
.rt_bandwidth
,
7693 global_rt_period(), global_rt_runtime());
7694 #ifdef CONFIG_USER_SCHED
7695 init_rt_bandwidth(&root_task_group
.rt_bandwidth
,
7696 global_rt_period(), RUNTIME_INF
);
7700 #ifdef CONFIG_GROUP_SCHED
7701 list_add(&init_task_group
.list
, &task_groups
);
7702 INIT_LIST_HEAD(&init_task_group
.children
);
7704 #ifdef CONFIG_USER_SCHED
7705 INIT_LIST_HEAD(&root_task_group
.children
);
7706 init_task_group
.parent
= &root_task_group
;
7707 list_add(&init_task_group
.siblings
, &root_task_group
.children
);
7711 for_each_possible_cpu(i
) {
7715 spin_lock_init(&rq
->lock
);
7716 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
7718 init_cfs_rq(&rq
->cfs
, rq
);
7719 init_rt_rq(&rq
->rt
, rq
);
7720 #ifdef CONFIG_FAIR_GROUP_SCHED
7721 init_task_group
.shares
= init_task_group_load
;
7722 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
7723 #ifdef CONFIG_CGROUP_SCHED
7725 * How much cpu bandwidth does init_task_group get?
7727 * In case of task-groups formed thr' the cgroup filesystem, it
7728 * gets 100% of the cpu resources in the system. This overall
7729 * system cpu resource is divided among the tasks of
7730 * init_task_group and its child task-groups in a fair manner,
7731 * based on each entity's (task or task-group's) weight
7732 * (se->load.weight).
7734 * In other words, if init_task_group has 10 tasks of weight
7735 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7736 * then A0's share of the cpu resource is:
7738 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7740 * We achieve this by letting init_task_group's tasks sit
7741 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
7743 init_tg_cfs_entry(&init_task_group
, &rq
->cfs
, NULL
, i
, 1, NULL
);
7744 #elif defined CONFIG_USER_SCHED
7745 root_task_group
.shares
= NICE_0_LOAD
;
7746 init_tg_cfs_entry(&root_task_group
, &rq
->cfs
, NULL
, i
, 0, NULL
);
7748 * In case of task-groups formed thr' the user id of tasks,
7749 * init_task_group represents tasks belonging to root user.
7750 * Hence it forms a sibling of all subsequent groups formed.
7751 * In this case, init_task_group gets only a fraction of overall
7752 * system cpu resource, based on the weight assigned to root
7753 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
7754 * by letting tasks of init_task_group sit in a separate cfs_rq
7755 * (init_cfs_rq) and having one entity represent this group of
7756 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
7758 init_tg_cfs_entry(&init_task_group
,
7759 &per_cpu(init_cfs_rq
, i
),
7760 &per_cpu(init_sched_entity
, i
), i
, 1,
7761 root_task_group
.se
[i
]);
7764 #endif /* CONFIG_FAIR_GROUP_SCHED */
7766 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
7767 #ifdef CONFIG_RT_GROUP_SCHED
7768 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
7769 #ifdef CONFIG_CGROUP_SCHED
7770 init_tg_rt_entry(&init_task_group
, &rq
->rt
, NULL
, i
, 1, NULL
);
7771 #elif defined CONFIG_USER_SCHED
7772 init_tg_rt_entry(&root_task_group
, &rq
->rt
, NULL
, i
, 0, NULL
);
7773 init_tg_rt_entry(&init_task_group
,
7774 &per_cpu(init_rt_rq
, i
),
7775 &per_cpu(init_sched_rt_entity
, i
), i
, 1,
7776 root_task_group
.rt_se
[i
]);
7780 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
7781 rq
->cpu_load
[j
] = 0;
7785 rq
->active_balance
= 0;
7786 rq
->next_balance
= jiffies
;
7789 rq
->migration_thread
= NULL
;
7790 INIT_LIST_HEAD(&rq
->migration_queue
);
7791 rq_attach_root(rq
, &def_root_domain
);
7794 atomic_set(&rq
->nr_iowait
, 0);
7797 set_load_weight(&init_task
);
7799 #ifdef CONFIG_PREEMPT_NOTIFIERS
7800 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
7804 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
, NULL
);
7807 #ifdef CONFIG_RT_MUTEXES
7808 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
7812 * The boot idle thread does lazy MMU switching as well:
7814 atomic_inc(&init_mm
.mm_count
);
7815 enter_lazy_tlb(&init_mm
, current
);
7818 * Make us the idle thread. Technically, schedule() should not be
7819 * called from this thread, however somewhere below it might be,
7820 * but because we are the idle thread, we just pick up running again
7821 * when this runqueue becomes "idle".
7823 init_idle(current
, smp_processor_id());
7825 * During early bootup we pretend to be a normal task:
7827 current
->sched_class
= &fair_sched_class
;
7829 scheduler_running
= 1;
7832 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7833 void __might_sleep(char *file
, int line
)
7836 static unsigned long prev_jiffy
; /* ratelimiting */
7838 if ((in_atomic() || irqs_disabled()) &&
7839 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
7840 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
7842 prev_jiffy
= jiffies
;
7843 printk(KERN_ERR
"BUG: sleeping function called from invalid"
7844 " context at %s:%d\n", file
, line
);
7845 printk("in_atomic():%d, irqs_disabled():%d\n",
7846 in_atomic(), irqs_disabled());
7847 debug_show_held_locks(current
);
7848 if (irqs_disabled())
7849 print_irqtrace_events(current
);
7854 EXPORT_SYMBOL(__might_sleep
);
7857 #ifdef CONFIG_MAGIC_SYSRQ
7858 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
7862 update_rq_clock(rq
);
7863 on_rq
= p
->se
.on_rq
;
7865 deactivate_task(rq
, p
, 0);
7866 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
7868 activate_task(rq
, p
, 0);
7869 resched_task(rq
->curr
);
7873 void normalize_rt_tasks(void)
7875 struct task_struct
*g
, *p
;
7876 unsigned long flags
;
7879 read_lock_irqsave(&tasklist_lock
, flags
);
7880 do_each_thread(g
, p
) {
7882 * Only normalize user tasks:
7887 p
->se
.exec_start
= 0;
7888 #ifdef CONFIG_SCHEDSTATS
7889 p
->se
.wait_start
= 0;
7890 p
->se
.sleep_start
= 0;
7891 p
->se
.block_start
= 0;
7896 * Renice negative nice level userspace
7899 if (TASK_NICE(p
) < 0 && p
->mm
)
7900 set_user_nice(p
, 0);
7904 spin_lock(&p
->pi_lock
);
7905 rq
= __task_rq_lock(p
);
7907 normalize_task(rq
, p
);
7909 __task_rq_unlock(rq
);
7910 spin_unlock(&p
->pi_lock
);
7911 } while_each_thread(g
, p
);
7913 read_unlock_irqrestore(&tasklist_lock
, flags
);
7916 #endif /* CONFIG_MAGIC_SYSRQ */
7920 * These functions are only useful for the IA64 MCA handling.
7922 * They can only be called when the whole system has been
7923 * stopped - every CPU needs to be quiescent, and no scheduling
7924 * activity can take place. Using them for anything else would
7925 * be a serious bug, and as a result, they aren't even visible
7926 * under any other configuration.
7930 * curr_task - return the current task for a given cpu.
7931 * @cpu: the processor in question.
7933 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7935 struct task_struct
*curr_task(int cpu
)
7937 return cpu_curr(cpu
);
7941 * set_curr_task - set the current task for a given cpu.
7942 * @cpu: the processor in question.
7943 * @p: the task pointer to set.
7945 * Description: This function must only be used when non-maskable interrupts
7946 * are serviced on a separate stack. It allows the architecture to switch the
7947 * notion of the current task on a cpu in a non-blocking manner. This function
7948 * must be called with all CPU's synchronized, and interrupts disabled, the
7949 * and caller must save the original value of the current task (see
7950 * curr_task() above) and restore that value before reenabling interrupts and
7951 * re-starting the system.
7953 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7955 void set_curr_task(int cpu
, struct task_struct
*p
)
7962 #ifdef CONFIG_FAIR_GROUP_SCHED
7963 static void free_fair_sched_group(struct task_group
*tg
)
7967 for_each_possible_cpu(i
) {
7969 kfree(tg
->cfs_rq
[i
]);
7979 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
7981 struct cfs_rq
*cfs_rq
;
7982 struct sched_entity
*se
, *parent_se
;
7986 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * nr_cpu_ids
, GFP_KERNEL
);
7989 tg
->se
= kzalloc(sizeof(se
) * nr_cpu_ids
, GFP_KERNEL
);
7993 tg
->shares
= NICE_0_LOAD
;
7995 for_each_possible_cpu(i
) {
7998 cfs_rq
= kmalloc_node(sizeof(struct cfs_rq
),
7999 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8003 se
= kmalloc_node(sizeof(struct sched_entity
),
8004 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8008 parent_se
= parent
? parent
->se
[i
] : NULL
;
8009 init_tg_cfs_entry(tg
, cfs_rq
, se
, i
, 0, parent_se
);
8018 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
8020 list_add_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
,
8021 &cpu_rq(cpu
)->leaf_cfs_rq_list
);
8024 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
8026 list_del_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
);
8029 static inline void free_fair_sched_group(struct task_group
*tg
)
8034 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8039 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
8043 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
8048 #ifdef CONFIG_RT_GROUP_SCHED
8049 static void free_rt_sched_group(struct task_group
*tg
)
8053 destroy_rt_bandwidth(&tg
->rt_bandwidth
);
8055 for_each_possible_cpu(i
) {
8057 kfree(tg
->rt_rq
[i
]);
8059 kfree(tg
->rt_se
[i
]);
8067 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8069 struct rt_rq
*rt_rq
;
8070 struct sched_rt_entity
*rt_se
, *parent_se
;
8074 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * nr_cpu_ids
, GFP_KERNEL
);
8077 tg
->rt_se
= kzalloc(sizeof(rt_se
) * nr_cpu_ids
, GFP_KERNEL
);
8081 init_rt_bandwidth(&tg
->rt_bandwidth
,
8082 ktime_to_ns(def_rt_bandwidth
.rt_period
), 0);
8084 for_each_possible_cpu(i
) {
8087 rt_rq
= kmalloc_node(sizeof(struct rt_rq
),
8088 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8092 rt_se
= kmalloc_node(sizeof(struct sched_rt_entity
),
8093 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
8097 parent_se
= parent
? parent
->rt_se
[i
] : NULL
;
8098 init_tg_rt_entry(tg
, rt_rq
, rt_se
, i
, 0, parent_se
);
8107 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
8109 list_add_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
,
8110 &cpu_rq(cpu
)->leaf_rt_rq_list
);
8113 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
8115 list_del_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
);
8118 static inline void free_rt_sched_group(struct task_group
*tg
)
8123 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
8128 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
8132 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
8137 #ifdef CONFIG_GROUP_SCHED
8138 static void free_sched_group(struct task_group
*tg
)
8140 free_fair_sched_group(tg
);
8141 free_rt_sched_group(tg
);
8145 /* allocate runqueue etc for a new task group */
8146 struct task_group
*sched_create_group(struct task_group
*parent
)
8148 struct task_group
*tg
;
8149 unsigned long flags
;
8152 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
8154 return ERR_PTR(-ENOMEM
);
8156 if (!alloc_fair_sched_group(tg
, parent
))
8159 if (!alloc_rt_sched_group(tg
, parent
))
8162 spin_lock_irqsave(&task_group_lock
, flags
);
8163 for_each_possible_cpu(i
) {
8164 register_fair_sched_group(tg
, i
);
8165 register_rt_sched_group(tg
, i
);
8167 list_add_rcu(&tg
->list
, &task_groups
);
8169 WARN_ON(!parent
); /* root should already exist */
8171 tg
->parent
= parent
;
8172 list_add_rcu(&tg
->siblings
, &parent
->children
);
8173 INIT_LIST_HEAD(&tg
->children
);
8174 spin_unlock_irqrestore(&task_group_lock
, flags
);
8179 free_sched_group(tg
);
8180 return ERR_PTR(-ENOMEM
);
8183 /* rcu callback to free various structures associated with a task group */
8184 static void free_sched_group_rcu(struct rcu_head
*rhp
)
8186 /* now it should be safe to free those cfs_rqs */
8187 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
8190 /* Destroy runqueue etc associated with a task group */
8191 void sched_destroy_group(struct task_group
*tg
)
8193 unsigned long flags
;
8196 spin_lock_irqsave(&task_group_lock
, flags
);
8197 for_each_possible_cpu(i
) {
8198 unregister_fair_sched_group(tg
, i
);
8199 unregister_rt_sched_group(tg
, i
);
8201 list_del_rcu(&tg
->list
);
8202 list_del_rcu(&tg
->siblings
);
8203 spin_unlock_irqrestore(&task_group_lock
, flags
);
8205 /* wait for possible concurrent references to cfs_rqs complete */
8206 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
8209 /* change task's runqueue when it moves between groups.
8210 * The caller of this function should have put the task in its new group
8211 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8212 * reflect its new group.
8214 void sched_move_task(struct task_struct
*tsk
)
8217 unsigned long flags
;
8220 rq
= task_rq_lock(tsk
, &flags
);
8222 update_rq_clock(rq
);
8224 running
= task_current(rq
, tsk
);
8225 on_rq
= tsk
->se
.on_rq
;
8228 dequeue_task(rq
, tsk
, 0);
8229 if (unlikely(running
))
8230 tsk
->sched_class
->put_prev_task(rq
, tsk
);
8232 set_task_rq(tsk
, task_cpu(tsk
));
8234 #ifdef CONFIG_FAIR_GROUP_SCHED
8235 if (tsk
->sched_class
->moved_group
)
8236 tsk
->sched_class
->moved_group(tsk
);
8239 if (unlikely(running
))
8240 tsk
->sched_class
->set_curr_task(rq
);
8242 enqueue_task(rq
, tsk
, 0);
8244 task_rq_unlock(rq
, &flags
);
8248 #ifdef CONFIG_FAIR_GROUP_SCHED
8249 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
8251 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
8252 struct rq
*rq
= cfs_rq
->rq
;
8255 spin_lock_irq(&rq
->lock
);
8259 dequeue_entity(cfs_rq
, se
, 0);
8261 se
->load
.weight
= shares
;
8262 se
->load
.inv_weight
= 0;
8265 enqueue_entity(cfs_rq
, se
, 0);
8267 spin_unlock_irq(&rq
->lock
);
8270 static DEFINE_MUTEX(shares_mutex
);
8272 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
8275 unsigned long flags
;
8278 * We can't change the weight of the root cgroup.
8283 if (shares
< MIN_SHARES
)
8284 shares
= MIN_SHARES
;
8285 else if (shares
> MAX_SHARES
)
8286 shares
= MAX_SHARES
;
8288 mutex_lock(&shares_mutex
);
8289 if (tg
->shares
== shares
)
8292 spin_lock_irqsave(&task_group_lock
, flags
);
8293 for_each_possible_cpu(i
)
8294 unregister_fair_sched_group(tg
, i
);
8295 list_del_rcu(&tg
->siblings
);
8296 spin_unlock_irqrestore(&task_group_lock
, flags
);
8298 /* wait for any ongoing reference to this group to finish */
8299 synchronize_sched();
8302 * Now we are free to modify the group's share on each cpu
8303 * w/o tripping rebalance_share or load_balance_fair.
8305 tg
->shares
= shares
;
8306 for_each_possible_cpu(i
)
8307 set_se_shares(tg
->se
[i
], shares
);
8310 * Enable load balance activity on this group, by inserting it back on
8311 * each cpu's rq->leaf_cfs_rq_list.
8313 spin_lock_irqsave(&task_group_lock
, flags
);
8314 for_each_possible_cpu(i
)
8315 register_fair_sched_group(tg
, i
);
8316 list_add_rcu(&tg
->siblings
, &tg
->parent
->children
);
8317 spin_unlock_irqrestore(&task_group_lock
, flags
);
8319 mutex_unlock(&shares_mutex
);
8323 unsigned long sched_group_shares(struct task_group
*tg
)
8329 #ifdef CONFIG_RT_GROUP_SCHED
8331 * Ensure that the real time constraints are schedulable.
8333 static DEFINE_MUTEX(rt_constraints_mutex
);
8335 static unsigned long to_ratio(u64 period
, u64 runtime
)
8337 if (runtime
== RUNTIME_INF
)
8340 return div64_u64(runtime
<< 16, period
);
8343 #ifdef CONFIG_CGROUP_SCHED
8344 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
8346 struct task_group
*tgi
, *parent
= tg
->parent
;
8347 unsigned long total
= 0;
8350 if (global_rt_period() < period
)
8353 return to_ratio(period
, runtime
) <
8354 to_ratio(global_rt_period(), global_rt_runtime());
8357 if (ktime_to_ns(parent
->rt_bandwidth
.rt_period
) < period
)
8361 list_for_each_entry_rcu(tgi
, &parent
->children
, siblings
) {
8365 total
+= to_ratio(ktime_to_ns(tgi
->rt_bandwidth
.rt_period
),
8366 tgi
->rt_bandwidth
.rt_runtime
);
8370 return total
+ to_ratio(period
, runtime
) <
8371 to_ratio(ktime_to_ns(parent
->rt_bandwidth
.rt_period
),
8372 parent
->rt_bandwidth
.rt_runtime
);
8374 #elif defined CONFIG_USER_SCHED
8375 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
8377 struct task_group
*tgi
;
8378 unsigned long total
= 0;
8379 unsigned long global_ratio
=
8380 to_ratio(global_rt_period(), global_rt_runtime());
8383 list_for_each_entry_rcu(tgi
, &task_groups
, list
) {
8387 total
+= to_ratio(ktime_to_ns(tgi
->rt_bandwidth
.rt_period
),
8388 tgi
->rt_bandwidth
.rt_runtime
);
8392 return total
+ to_ratio(period
, runtime
) < global_ratio
;
8396 /* Must be called with tasklist_lock held */
8397 static inline int tg_has_rt_tasks(struct task_group
*tg
)
8399 struct task_struct
*g
, *p
;
8400 do_each_thread(g
, p
) {
8401 if (rt_task(p
) && rt_rq_of_se(&p
->rt
)->tg
== tg
)
8403 } while_each_thread(g
, p
);
8407 static int tg_set_bandwidth(struct task_group
*tg
,
8408 u64 rt_period
, u64 rt_runtime
)
8412 mutex_lock(&rt_constraints_mutex
);
8413 read_lock(&tasklist_lock
);
8414 if (rt_runtime
== 0 && tg_has_rt_tasks(tg
)) {
8418 if (!__rt_schedulable(tg
, rt_period
, rt_runtime
)) {
8423 spin_lock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8424 tg
->rt_bandwidth
.rt_period
= ns_to_ktime(rt_period
);
8425 tg
->rt_bandwidth
.rt_runtime
= rt_runtime
;
8427 for_each_possible_cpu(i
) {
8428 struct rt_rq
*rt_rq
= tg
->rt_rq
[i
];
8430 spin_lock(&rt_rq
->rt_runtime_lock
);
8431 rt_rq
->rt_runtime
= rt_runtime
;
8432 spin_unlock(&rt_rq
->rt_runtime_lock
);
8434 spin_unlock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
8436 read_unlock(&tasklist_lock
);
8437 mutex_unlock(&rt_constraints_mutex
);
8442 int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
8444 u64 rt_runtime
, rt_period
;
8446 rt_period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8447 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
8448 if (rt_runtime_us
< 0)
8449 rt_runtime
= RUNTIME_INF
;
8451 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
8454 long sched_group_rt_runtime(struct task_group
*tg
)
8458 if (tg
->rt_bandwidth
.rt_runtime
== RUNTIME_INF
)
8461 rt_runtime_us
= tg
->rt_bandwidth
.rt_runtime
;
8462 do_div(rt_runtime_us
, NSEC_PER_USEC
);
8463 return rt_runtime_us
;
8466 int sched_group_set_rt_period(struct task_group
*tg
, long rt_period_us
)
8468 u64 rt_runtime
, rt_period
;
8470 rt_period
= (u64
)rt_period_us
* NSEC_PER_USEC
;
8471 rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
8473 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
8476 long sched_group_rt_period(struct task_group
*tg
)
8480 rt_period_us
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
8481 do_div(rt_period_us
, NSEC_PER_USEC
);
8482 return rt_period_us
;
8485 static int sched_rt_global_constraints(void)
8489 mutex_lock(&rt_constraints_mutex
);
8490 if (!__rt_schedulable(NULL
, 1, 0))
8492 mutex_unlock(&rt_constraints_mutex
);
8497 static int sched_rt_global_constraints(void)
8499 unsigned long flags
;
8502 spin_lock_irqsave(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8503 for_each_possible_cpu(i
) {
8504 struct rt_rq
*rt_rq
= &cpu_rq(i
)->rt
;
8506 spin_lock(&rt_rq
->rt_runtime_lock
);
8507 rt_rq
->rt_runtime
= global_rt_runtime();
8508 spin_unlock(&rt_rq
->rt_runtime_lock
);
8510 spin_unlock_irqrestore(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
8516 int sched_rt_handler(struct ctl_table
*table
, int write
,
8517 struct file
*filp
, void __user
*buffer
, size_t *lenp
,
8521 int old_period
, old_runtime
;
8522 static DEFINE_MUTEX(mutex
);
8525 old_period
= sysctl_sched_rt_period
;
8526 old_runtime
= sysctl_sched_rt_runtime
;
8528 ret
= proc_dointvec(table
, write
, filp
, buffer
, lenp
, ppos
);
8530 if (!ret
&& write
) {
8531 ret
= sched_rt_global_constraints();
8533 sysctl_sched_rt_period
= old_period
;
8534 sysctl_sched_rt_runtime
= old_runtime
;
8536 def_rt_bandwidth
.rt_runtime
= global_rt_runtime();
8537 def_rt_bandwidth
.rt_period
=
8538 ns_to_ktime(global_rt_period());
8541 mutex_unlock(&mutex
);
8546 #ifdef CONFIG_CGROUP_SCHED
8548 /* return corresponding task_group object of a cgroup */
8549 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
8551 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
8552 struct task_group
, css
);
8555 static struct cgroup_subsys_state
*
8556 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8558 struct task_group
*tg
, *parent
;
8560 if (!cgrp
->parent
) {
8561 /* This is early initialization for the top cgroup */
8562 init_task_group
.css
.cgroup
= cgrp
;
8563 return &init_task_group
.css
;
8566 parent
= cgroup_tg(cgrp
->parent
);
8567 tg
= sched_create_group(parent
);
8569 return ERR_PTR(-ENOMEM
);
8571 /* Bind the cgroup to task_group object we just created */
8572 tg
->css
.cgroup
= cgrp
;
8578 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8580 struct task_group
*tg
= cgroup_tg(cgrp
);
8582 sched_destroy_group(tg
);
8586 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8587 struct task_struct
*tsk
)
8589 #ifdef CONFIG_RT_GROUP_SCHED
8590 /* Don't accept realtime tasks when there is no way for them to run */
8591 if (rt_task(tsk
) && cgroup_tg(cgrp
)->rt_bandwidth
.rt_runtime
== 0)
8594 /* We don't support RT-tasks being in separate groups */
8595 if (tsk
->sched_class
!= &fair_sched_class
)
8603 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8604 struct cgroup
*old_cont
, struct task_struct
*tsk
)
8606 sched_move_task(tsk
);
8609 #ifdef CONFIG_FAIR_GROUP_SCHED
8610 static int cpu_shares_write_u64(struct cgroup
*cgrp
, struct cftype
*cftype
,
8613 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
8616 static u64
cpu_shares_read_u64(struct cgroup
*cgrp
, struct cftype
*cft
)
8618 struct task_group
*tg
= cgroup_tg(cgrp
);
8620 return (u64
) tg
->shares
;
8624 #ifdef CONFIG_RT_GROUP_SCHED
8625 static int cpu_rt_runtime_write(struct cgroup
*cgrp
, struct cftype
*cft
,
8628 return sched_group_set_rt_runtime(cgroup_tg(cgrp
), val
);
8631 static s64
cpu_rt_runtime_read(struct cgroup
*cgrp
, struct cftype
*cft
)
8633 return sched_group_rt_runtime(cgroup_tg(cgrp
));
8636 static int cpu_rt_period_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
8639 return sched_group_set_rt_period(cgroup_tg(cgrp
), rt_period_us
);
8642 static u64
cpu_rt_period_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
8644 return sched_group_rt_period(cgroup_tg(cgrp
));
8648 static struct cftype cpu_files
[] = {
8649 #ifdef CONFIG_FAIR_GROUP_SCHED
8652 .read_u64
= cpu_shares_read_u64
,
8653 .write_u64
= cpu_shares_write_u64
,
8656 #ifdef CONFIG_RT_GROUP_SCHED
8658 .name
= "rt_runtime_us",
8659 .read_s64
= cpu_rt_runtime_read
,
8660 .write_s64
= cpu_rt_runtime_write
,
8663 .name
= "rt_period_us",
8664 .read_u64
= cpu_rt_period_read_uint
,
8665 .write_u64
= cpu_rt_period_write_uint
,
8670 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8672 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
8675 struct cgroup_subsys cpu_cgroup_subsys
= {
8677 .create
= cpu_cgroup_create
,
8678 .destroy
= cpu_cgroup_destroy
,
8679 .can_attach
= cpu_cgroup_can_attach
,
8680 .attach
= cpu_cgroup_attach
,
8681 .populate
= cpu_cgroup_populate
,
8682 .subsys_id
= cpu_cgroup_subsys_id
,
8686 #endif /* CONFIG_CGROUP_SCHED */
8688 #ifdef CONFIG_CGROUP_CPUACCT
8691 * CPU accounting code for task groups.
8693 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8694 * (balbir@in.ibm.com).
8697 /* track cpu usage of a group of tasks */
8699 struct cgroup_subsys_state css
;
8700 /* cpuusage holds pointer to a u64-type object on every cpu */
8704 struct cgroup_subsys cpuacct_subsys
;
8706 /* return cpu accounting group corresponding to this container */
8707 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cgrp
)
8709 return container_of(cgroup_subsys_state(cgrp
, cpuacct_subsys_id
),
8710 struct cpuacct
, css
);
8713 /* return cpu accounting group to which this task belongs */
8714 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
8716 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
8717 struct cpuacct
, css
);
8720 /* create a new cpu accounting group */
8721 static struct cgroup_subsys_state
*cpuacct_create(
8722 struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8724 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
8727 return ERR_PTR(-ENOMEM
);
8729 ca
->cpuusage
= alloc_percpu(u64
);
8730 if (!ca
->cpuusage
) {
8732 return ERR_PTR(-ENOMEM
);
8738 /* destroy an existing cpu accounting group */
8740 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8742 struct cpuacct
*ca
= cgroup_ca(cgrp
);
8744 free_percpu(ca
->cpuusage
);
8748 /* return total cpu usage (in nanoseconds) of a group */
8749 static u64
cpuusage_read(struct cgroup
*cgrp
, struct cftype
*cft
)
8751 struct cpuacct
*ca
= cgroup_ca(cgrp
);
8752 u64 totalcpuusage
= 0;
8755 for_each_possible_cpu(i
) {
8756 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
8759 * Take rq->lock to make 64-bit addition safe on 32-bit
8762 spin_lock_irq(&cpu_rq(i
)->lock
);
8763 totalcpuusage
+= *cpuusage
;
8764 spin_unlock_irq(&cpu_rq(i
)->lock
);
8767 return totalcpuusage
;
8770 static int cpuusage_write(struct cgroup
*cgrp
, struct cftype
*cftype
,
8773 struct cpuacct
*ca
= cgroup_ca(cgrp
);
8782 for_each_possible_cpu(i
) {
8783 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
8785 spin_lock_irq(&cpu_rq(i
)->lock
);
8787 spin_unlock_irq(&cpu_rq(i
)->lock
);
8793 static struct cftype files
[] = {
8796 .read_u64
= cpuusage_read
,
8797 .write_u64
= cpuusage_write
,
8801 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8803 return cgroup_add_files(cgrp
, ss
, files
, ARRAY_SIZE(files
));
8807 * charge this task's execution time to its accounting group.
8809 * called with rq->lock held.
8811 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
8815 if (!cpuacct_subsys
.active
)
8820 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, task_cpu(tsk
));
8822 *cpuusage
+= cputime
;
8826 struct cgroup_subsys cpuacct_subsys
= {
8828 .create
= cpuacct_create
,
8829 .destroy
= cpuacct_destroy
,
8830 .populate
= cpuacct_populate
,
8831 .subsys_id
= cpuacct_subsys_id
,
8833 #endif /* CONFIG_CGROUP_CPUACCT */