Merge git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6
[wrt350n-kernel.git] / kernel / sched.c
blobe258796498bd3d609993bc68f1fc30102cc2c87b
1 /*
2 * kernel/sched.c
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
11 * by Andrea Arcangeli
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
22 * by Peter Williams
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
29 #include <linux/mm.h>
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>
70 #include <asm/tlb.h>
71 #include <asm/irq_regs.h>
74 * Scheduler clock - returns current time in nanosec units.
75 * This is default implementation.
76 * Architectures and sub-architectures can override this.
78 unsigned long long __attribute__((weak)) sched_clock(void)
80 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
84 * Convert user-nice values [ -20 ... 0 ... 19 ]
85 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
86 * and back.
88 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
89 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
90 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
93 * 'User priority' is the nice value converted to something we
94 * can work with better when scaling various scheduler parameters,
95 * it's a [ 0 ... 39 ] range.
97 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
98 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
99 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
102 * Helpers for converting nanosecond timing to jiffy resolution
104 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
106 #define NICE_0_LOAD SCHED_LOAD_SCALE
107 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
110 * These are the 'tuning knobs' of the scheduler:
112 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
113 * Timeslices get refilled after they expire.
115 #define DEF_TIMESLICE (100 * HZ / 1000)
117 #ifdef CONFIG_SMP
119 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
120 * Since cpu_power is a 'constant', we can use a reciprocal divide.
122 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
124 return reciprocal_divide(load, sg->reciprocal_cpu_power);
128 * Each time a sched group cpu_power is changed,
129 * we must compute its reciprocal value
131 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
133 sg->__cpu_power += val;
134 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
136 #endif
138 static inline int rt_policy(int policy)
140 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
141 return 1;
142 return 0;
145 static inline int task_has_rt_policy(struct task_struct *p)
147 return rt_policy(p->policy);
151 * This is the priority-queue data structure of the RT scheduling class:
153 struct rt_prio_array {
154 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
155 struct list_head queue[MAX_RT_PRIO];
158 #ifdef CONFIG_GROUP_SCHED
160 #include <linux/cgroup.h>
162 struct cfs_rq;
164 static LIST_HEAD(task_groups);
166 /* task group related information */
167 struct task_group {
168 #ifdef CONFIG_CGROUP_SCHED
169 struct cgroup_subsys_state css;
170 #endif
172 #ifdef CONFIG_FAIR_GROUP_SCHED
173 /* schedulable entities of this group on each cpu */
174 struct sched_entity **se;
175 /* runqueue "owned" by this group on each cpu */
176 struct cfs_rq **cfs_rq;
177 <<<<<<< HEAD:kernel/sched.c
180 * shares assigned to a task group governs how much of cpu bandwidth
181 * is allocated to the group. The more shares a group has, the more is
182 * the cpu bandwidth allocated to it.
184 * For ex, lets say that there are three task groups, A, B and C which
185 * have been assigned shares 1000, 2000 and 3000 respectively. Then,
186 * cpu bandwidth allocated by the scheduler to task groups A, B and C
187 * should be:
189 * Bw(A) = 1000/(1000+2000+3000) * 100 = 16.66%
190 * Bw(B) = 2000/(1000+2000+3000) * 100 = 33.33%
191 * Bw(C) = 3000/(1000+2000+3000) * 100 = 50%
193 * The weight assigned to a task group's schedulable entities on every
194 * cpu (task_group.se[a_cpu]->load.weight) is derived from the task
195 * group's shares. For ex: lets say that task group A has been
196 * assigned shares of 1000 and there are two CPUs in a system. Then,
198 * tg_A->se[0]->load.weight = tg_A->se[1]->load.weight = 1000;
200 * Note: It's not necessary that each of a task's group schedulable
201 * entity have the same weight on all CPUs. If the group
202 * has 2 of its tasks on CPU0 and 1 task on CPU1, then a
203 * better distribution of weight could be:
205 * tg_A->se[0]->load.weight = 2/3 * 2000 = 1333
206 * tg_A->se[1]->load.weight = 1/2 * 2000 = 667
208 * rebalance_shares() is responsible for distributing the shares of a
209 * task groups like this among the group's schedulable entities across
210 * cpus.
213 =======
214 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
215 unsigned long shares;
216 #endif
218 #ifdef CONFIG_RT_GROUP_SCHED
219 struct sched_rt_entity **rt_se;
220 struct rt_rq **rt_rq;
222 u64 rt_runtime;
223 #endif
225 struct rcu_head rcu;
226 struct list_head list;
229 #ifdef CONFIG_FAIR_GROUP_SCHED
230 /* Default task group's sched entity on each cpu */
231 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
232 /* Default task group's cfs_rq on each cpu */
233 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
235 static struct sched_entity *init_sched_entity_p[NR_CPUS];
236 static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
237 #endif
239 #ifdef CONFIG_RT_GROUP_SCHED
240 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
241 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
243 static struct sched_rt_entity *init_sched_rt_entity_p[NR_CPUS];
244 static struct rt_rq *init_rt_rq_p[NR_CPUS];
245 #endif
247 /* task_group_lock serializes add/remove of task groups and also changes to
248 * a task group's cpu shares.
250 static DEFINE_SPINLOCK(task_group_lock);
252 /* doms_cur_mutex serializes access to doms_cur[] array */
253 static DEFINE_MUTEX(doms_cur_mutex);
255 #ifdef CONFIG_FAIR_GROUP_SCHED
256 <<<<<<< HEAD:kernel/sched.c
257 #ifdef CONFIG_SMP
258 /* kernel thread that runs rebalance_shares() periodically */
259 static struct task_struct *lb_monitor_task;
260 static int load_balance_monitor(void *unused);
261 #endif
263 static void set_se_shares(struct sched_entity *se, unsigned long shares);
265 =======
266 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
267 #ifdef CONFIG_USER_SCHED
268 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
269 #else
270 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
271 #endif
273 <<<<<<< HEAD:kernel/sched.c
274 #define MIN_GROUP_SHARES 2
276 =======
277 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
278 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
279 #endif
281 /* Default task group.
282 * Every task in system belong to this group at bootup.
284 struct task_group init_task_group = {
285 #ifdef CONFIG_FAIR_GROUP_SCHED
286 .se = init_sched_entity_p,
287 .cfs_rq = init_cfs_rq_p,
288 #endif
290 #ifdef CONFIG_RT_GROUP_SCHED
291 .rt_se = init_sched_rt_entity_p,
292 .rt_rq = init_rt_rq_p,
293 #endif
296 /* return group to which a task belongs */
297 static inline struct task_group *task_group(struct task_struct *p)
299 struct task_group *tg;
301 #ifdef CONFIG_USER_SCHED
302 tg = p->user->tg;
303 #elif defined(CONFIG_CGROUP_SCHED)
304 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
305 struct task_group, css);
306 #else
307 tg = &init_task_group;
308 #endif
309 return tg;
312 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
313 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
315 #ifdef CONFIG_FAIR_GROUP_SCHED
316 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
317 p->se.parent = task_group(p)->se[cpu];
318 #endif
320 #ifdef CONFIG_RT_GROUP_SCHED
321 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
322 p->rt.parent = task_group(p)->rt_se[cpu];
323 #endif
326 static inline void lock_doms_cur(void)
328 mutex_lock(&doms_cur_mutex);
331 static inline void unlock_doms_cur(void)
333 mutex_unlock(&doms_cur_mutex);
336 #else
338 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
339 static inline void lock_doms_cur(void) { }
340 static inline void unlock_doms_cur(void) { }
342 #endif /* CONFIG_GROUP_SCHED */
344 /* CFS-related fields in a runqueue */
345 struct cfs_rq {
346 struct load_weight load;
347 unsigned long nr_running;
349 u64 exec_clock;
350 u64 min_vruntime;
352 struct rb_root tasks_timeline;
353 struct rb_node *rb_leftmost;
354 struct rb_node *rb_load_balance_curr;
355 /* 'curr' points to currently running entity on this cfs_rq.
356 * It is set to NULL otherwise (i.e when none are currently running).
358 <<<<<<< HEAD:kernel/sched.c
359 struct sched_entity *curr;
360 =======
361 struct sched_entity *curr, *next;
362 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
364 unsigned long nr_spread_over;
366 #ifdef CONFIG_FAIR_GROUP_SCHED
367 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
370 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
371 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
372 * (like users, containers etc.)
374 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
375 * list is used during load balance.
377 struct list_head leaf_cfs_rq_list;
378 struct task_group *tg; /* group that "owns" this runqueue */
379 #endif
382 /* Real-Time classes' related field in a runqueue: */
383 struct rt_rq {
384 struct rt_prio_array active;
385 unsigned long rt_nr_running;
386 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
387 int highest_prio; /* highest queued rt task prio */
388 #endif
389 #ifdef CONFIG_SMP
390 unsigned long rt_nr_migratory;
391 int overloaded;
392 #endif
393 int rt_throttled;
394 u64 rt_time;
396 #ifdef CONFIG_RT_GROUP_SCHED
397 unsigned long rt_nr_boosted;
399 struct rq *rq;
400 struct list_head leaf_rt_rq_list;
401 struct task_group *tg;
402 struct sched_rt_entity *rt_se;
403 #endif
406 #ifdef CONFIG_SMP
409 * We add the notion of a root-domain which will be used to define per-domain
410 * variables. Each exclusive cpuset essentially defines an island domain by
411 * fully partitioning the member cpus from any other cpuset. Whenever a new
412 * exclusive cpuset is created, we also create and attach a new root-domain
413 * object.
416 struct root_domain {
417 atomic_t refcount;
418 cpumask_t span;
419 cpumask_t online;
422 * The "RT overload" flag: it gets set if a CPU has more than
423 * one runnable RT task.
425 cpumask_t rto_mask;
426 atomic_t rto_count;
430 * By default the system creates a single root-domain with all cpus as
431 * members (mimicking the global state we have today).
433 static struct root_domain def_root_domain;
435 #endif
438 * This is the main, per-CPU runqueue data structure.
440 * Locking rule: those places that want to lock multiple runqueues
441 * (such as the load balancing or the thread migration code), lock
442 * acquire operations must be ordered by ascending &runqueue.
444 struct rq {
445 /* runqueue lock: */
446 spinlock_t lock;
449 * nr_running and cpu_load should be in the same cacheline because
450 * remote CPUs use both these fields when doing load calculation.
452 unsigned long nr_running;
453 #define CPU_LOAD_IDX_MAX 5
454 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
455 unsigned char idle_at_tick;
456 #ifdef CONFIG_NO_HZ
457 unsigned char in_nohz_recently;
458 #endif
459 /* capture load from *all* tasks on this cpu: */
460 struct load_weight load;
461 unsigned long nr_load_updates;
462 u64 nr_switches;
464 struct cfs_rq cfs;
465 struct rt_rq rt;
466 u64 rt_period_expire;
467 int rt_throttled;
469 #ifdef CONFIG_FAIR_GROUP_SCHED
470 /* list of leaf cfs_rq on this cpu: */
471 struct list_head leaf_cfs_rq_list;
472 #endif
473 #ifdef CONFIG_RT_GROUP_SCHED
474 struct list_head leaf_rt_rq_list;
475 #endif
478 * This is part of a global counter where only the total sum
479 * over all CPUs matters. A task can increase this counter on
480 * one CPU and if it got migrated afterwards it may decrease
481 * it on another CPU. Always updated under the runqueue lock:
483 unsigned long nr_uninterruptible;
485 struct task_struct *curr, *idle;
486 unsigned long next_balance;
487 struct mm_struct *prev_mm;
489 u64 clock, prev_clock_raw;
490 s64 clock_max_delta;
492 unsigned int clock_warps, clock_overflows, clock_underflows;
493 u64 idle_clock;
494 unsigned int clock_deep_idle_events;
495 u64 tick_timestamp;
497 atomic_t nr_iowait;
499 #ifdef CONFIG_SMP
500 struct root_domain *rd;
501 struct sched_domain *sd;
503 /* For active balancing */
504 int active_balance;
505 int push_cpu;
506 /* cpu of this runqueue: */
507 int cpu;
509 struct task_struct *migration_thread;
510 struct list_head migration_queue;
511 #endif
513 #ifdef CONFIG_SCHED_HRTICK
514 unsigned long hrtick_flags;
515 ktime_t hrtick_expire;
516 struct hrtimer hrtick_timer;
517 #endif
519 #ifdef CONFIG_SCHEDSTATS
520 /* latency stats */
521 struct sched_info rq_sched_info;
523 /* sys_sched_yield() stats */
524 unsigned int yld_exp_empty;
525 unsigned int yld_act_empty;
526 unsigned int yld_both_empty;
527 unsigned int yld_count;
529 /* schedule() stats */
530 unsigned int sched_switch;
531 unsigned int sched_count;
532 unsigned int sched_goidle;
534 /* try_to_wake_up() stats */
535 unsigned int ttwu_count;
536 unsigned int ttwu_local;
538 /* BKL stats */
539 unsigned int bkl_count;
540 #endif
541 struct lock_class_key rq_lock_key;
544 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
546 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
548 rq->curr->sched_class->check_preempt_curr(rq, p);
551 static inline int cpu_of(struct rq *rq)
553 #ifdef CONFIG_SMP
554 return rq->cpu;
555 #else
556 return 0;
557 #endif
561 * Update the per-runqueue clock, as finegrained as the platform can give
562 * us, but without assuming monotonicity, etc.:
564 static void __update_rq_clock(struct rq *rq)
566 u64 prev_raw = rq->prev_clock_raw;
567 u64 now = sched_clock();
568 s64 delta = now - prev_raw;
569 u64 clock = rq->clock;
571 #ifdef CONFIG_SCHED_DEBUG
572 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
573 #endif
575 * Protect against sched_clock() occasionally going backwards:
577 if (unlikely(delta < 0)) {
578 clock++;
579 rq->clock_warps++;
580 } else {
582 * Catch too large forward jumps too:
584 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
585 if (clock < rq->tick_timestamp + TICK_NSEC)
586 clock = rq->tick_timestamp + TICK_NSEC;
587 else
588 clock++;
589 rq->clock_overflows++;
590 } else {
591 if (unlikely(delta > rq->clock_max_delta))
592 rq->clock_max_delta = delta;
593 clock += delta;
597 rq->prev_clock_raw = now;
598 rq->clock = clock;
601 static void update_rq_clock(struct rq *rq)
603 if (likely(smp_processor_id() == cpu_of(rq)))
604 __update_rq_clock(rq);
608 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
609 * See detach_destroy_domains: synchronize_sched for details.
611 * The domain tree of any CPU may only be accessed from within
612 * preempt-disabled sections.
614 #define for_each_domain(cpu, __sd) \
615 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
617 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
618 #define this_rq() (&__get_cpu_var(runqueues))
619 #define task_rq(p) cpu_rq(task_cpu(p))
620 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
622 unsigned long rt_needs_cpu(int cpu)
624 struct rq *rq = cpu_rq(cpu);
625 u64 delta;
627 if (!rq->rt_throttled)
628 return 0;
630 if (rq->clock > rq->rt_period_expire)
631 return 1;
633 delta = rq->rt_period_expire - rq->clock;
634 do_div(delta, NSEC_PER_SEC / HZ);
636 return (unsigned long)delta;
640 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
642 #ifdef CONFIG_SCHED_DEBUG
643 # define const_debug __read_mostly
644 #else
645 # define const_debug static const
646 #endif
649 * Debugging: various feature bits
651 enum {
652 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
653 SCHED_FEAT_WAKEUP_PREEMPT = 2,
654 SCHED_FEAT_START_DEBIT = 4,
655 SCHED_FEAT_TREE_AVG = 8,
656 SCHED_FEAT_APPROX_AVG = 16,
657 SCHED_FEAT_HRTICK = 32,
658 SCHED_FEAT_DOUBLE_TICK = 64,
661 const_debug unsigned int sysctl_sched_features =
662 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
663 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
664 SCHED_FEAT_START_DEBIT * 1 |
665 SCHED_FEAT_TREE_AVG * 0 |
666 SCHED_FEAT_APPROX_AVG * 0 |
667 SCHED_FEAT_HRTICK * 1 |
668 SCHED_FEAT_DOUBLE_TICK * 0;
670 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
673 * Number of tasks to iterate in a single balance run.
674 * Limited because this is done with IRQs disabled.
676 const_debug unsigned int sysctl_sched_nr_migrate = 32;
679 * period over which we measure -rt task cpu usage in us.
680 * default: 1s
682 unsigned int sysctl_sched_rt_period = 1000000;
684 <<<<<<< HEAD:kernel/sched.c
685 =======
686 static __read_mostly int scheduler_running;
688 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
690 * part of the period that we allow rt tasks to run in us.
691 * default: 0.95s
693 int sysctl_sched_rt_runtime = 950000;
696 * single value that denotes runtime == period, ie unlimited time.
698 #define RUNTIME_INF ((u64)~0ULL)
701 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
702 * clock constructed from sched_clock():
704 unsigned long long cpu_clock(int cpu)
706 unsigned long long now;
707 unsigned long flags;
708 struct rq *rq;
710 <<<<<<< HEAD:kernel/sched.c
711 local_irq_save(flags);
712 rq = cpu_rq(cpu);
713 =======
714 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
716 * Only call sched_clock() if the scheduler has already been
717 * initialized (some code might call cpu_clock() very early):
719 <<<<<<< HEAD:kernel/sched.c
720 if (rq->idle)
721 update_rq_clock(rq);
722 =======
723 if (unlikely(!scheduler_running))
724 return 0;
726 local_irq_save(flags);
727 rq = cpu_rq(cpu);
728 update_rq_clock(rq);
729 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
730 now = rq->clock;
731 local_irq_restore(flags);
733 return now;
735 EXPORT_SYMBOL_GPL(cpu_clock);
737 #ifndef prepare_arch_switch
738 # define prepare_arch_switch(next) do { } while (0)
739 #endif
740 #ifndef finish_arch_switch
741 # define finish_arch_switch(prev) do { } while (0)
742 #endif
744 static inline int task_current(struct rq *rq, struct task_struct *p)
746 return rq->curr == p;
749 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
750 static inline int task_running(struct rq *rq, struct task_struct *p)
752 return task_current(rq, p);
755 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
759 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
761 #ifdef CONFIG_DEBUG_SPINLOCK
762 /* this is a valid case when another task releases the spinlock */
763 rq->lock.owner = current;
764 #endif
766 * If we are tracking spinlock dependencies then we have to
767 * fix up the runqueue lock - which gets 'carried over' from
768 * prev into current:
770 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
772 spin_unlock_irq(&rq->lock);
775 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
776 static inline int task_running(struct rq *rq, struct task_struct *p)
778 #ifdef CONFIG_SMP
779 return p->oncpu;
780 #else
781 return task_current(rq, p);
782 #endif
785 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
787 #ifdef CONFIG_SMP
789 * We can optimise this out completely for !SMP, because the
790 * SMP rebalancing from interrupt is the only thing that cares
791 * here.
793 next->oncpu = 1;
794 #endif
795 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
796 spin_unlock_irq(&rq->lock);
797 #else
798 spin_unlock(&rq->lock);
799 #endif
802 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
804 #ifdef CONFIG_SMP
806 * After ->oncpu is cleared, the task can be moved to a different CPU.
807 * We must ensure this doesn't happen until the switch is completely
808 * finished.
810 smp_wmb();
811 prev->oncpu = 0;
812 #endif
813 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
814 local_irq_enable();
815 #endif
817 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
820 * __task_rq_lock - lock the runqueue a given task resides on.
821 * Must be called interrupts disabled.
823 static inline struct rq *__task_rq_lock(struct task_struct *p)
824 __acquires(rq->lock)
826 for (;;) {
827 struct rq *rq = task_rq(p);
828 spin_lock(&rq->lock);
829 if (likely(rq == task_rq(p)))
830 return rq;
831 spin_unlock(&rq->lock);
836 * task_rq_lock - lock the runqueue a given task resides on and disable
837 * interrupts. Note the ordering: we can safely lookup the task_rq without
838 * explicitly disabling preemption.
840 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
841 __acquires(rq->lock)
843 struct rq *rq;
845 for (;;) {
846 local_irq_save(*flags);
847 rq = task_rq(p);
848 spin_lock(&rq->lock);
849 if (likely(rq == task_rq(p)))
850 return rq;
851 spin_unlock_irqrestore(&rq->lock, *flags);
855 static void __task_rq_unlock(struct rq *rq)
856 __releases(rq->lock)
858 spin_unlock(&rq->lock);
861 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
862 __releases(rq->lock)
864 spin_unlock_irqrestore(&rq->lock, *flags);
868 * this_rq_lock - lock this runqueue and disable interrupts.
870 static struct rq *this_rq_lock(void)
871 __acquires(rq->lock)
873 struct rq *rq;
875 local_irq_disable();
876 rq = this_rq();
877 spin_lock(&rq->lock);
879 return rq;
883 * We are going deep-idle (irqs are disabled):
885 void sched_clock_idle_sleep_event(void)
887 struct rq *rq = cpu_rq(smp_processor_id());
889 spin_lock(&rq->lock);
890 __update_rq_clock(rq);
891 spin_unlock(&rq->lock);
892 rq->clock_deep_idle_events++;
894 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
897 * We just idled delta nanoseconds (called with irqs disabled):
899 void sched_clock_idle_wakeup_event(u64 delta_ns)
901 struct rq *rq = cpu_rq(smp_processor_id());
902 u64 now = sched_clock();
904 rq->idle_clock += delta_ns;
906 * Override the previous timestamp and ignore all
907 * sched_clock() deltas that occured while we idled,
908 * and use the PM-provided delta_ns to advance the
909 * rq clock:
911 spin_lock(&rq->lock);
912 rq->prev_clock_raw = now;
913 rq->clock += delta_ns;
914 spin_unlock(&rq->lock);
915 touch_softlockup_watchdog();
917 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
919 static void __resched_task(struct task_struct *p, int tif_bit);
921 static inline void resched_task(struct task_struct *p)
923 __resched_task(p, TIF_NEED_RESCHED);
926 #ifdef CONFIG_SCHED_HRTICK
928 * Use HR-timers to deliver accurate preemption points.
930 * Its all a bit involved since we cannot program an hrt while holding the
931 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
932 * reschedule event.
934 * When we get rescheduled we reprogram the hrtick_timer outside of the
935 * rq->lock.
937 static inline void resched_hrt(struct task_struct *p)
939 __resched_task(p, TIF_HRTICK_RESCHED);
942 static inline void resched_rq(struct rq *rq)
944 unsigned long flags;
946 spin_lock_irqsave(&rq->lock, flags);
947 resched_task(rq->curr);
948 spin_unlock_irqrestore(&rq->lock, flags);
951 enum {
952 HRTICK_SET, /* re-programm hrtick_timer */
953 HRTICK_RESET, /* not a new slice */
957 * Use hrtick when:
958 * - enabled by features
959 * - hrtimer is actually high res
961 static inline int hrtick_enabled(struct rq *rq)
963 if (!sched_feat(HRTICK))
964 return 0;
965 return hrtimer_is_hres_active(&rq->hrtick_timer);
969 * Called to set the hrtick timer state.
971 * called with rq->lock held and irqs disabled
973 static void hrtick_start(struct rq *rq, u64 delay, int reset)
975 assert_spin_locked(&rq->lock);
978 * preempt at: now + delay
980 rq->hrtick_expire =
981 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
983 * indicate we need to program the timer
985 __set_bit(HRTICK_SET, &rq->hrtick_flags);
986 if (reset)
987 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
990 * New slices are called from the schedule path and don't need a
991 * forced reschedule.
993 if (reset)
994 resched_hrt(rq->curr);
997 static void hrtick_clear(struct rq *rq)
999 if (hrtimer_active(&rq->hrtick_timer))
1000 hrtimer_cancel(&rq->hrtick_timer);
1004 * Update the timer from the possible pending state.
1006 static void hrtick_set(struct rq *rq)
1008 ktime_t time;
1009 int set, reset;
1010 unsigned long flags;
1012 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1014 spin_lock_irqsave(&rq->lock, flags);
1015 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1016 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1017 time = rq->hrtick_expire;
1018 clear_thread_flag(TIF_HRTICK_RESCHED);
1019 spin_unlock_irqrestore(&rq->lock, flags);
1021 if (set) {
1022 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1023 if (reset && !hrtimer_active(&rq->hrtick_timer))
1024 resched_rq(rq);
1025 } else
1026 hrtick_clear(rq);
1030 * High-resolution timer tick.
1031 * Runs from hardirq context with interrupts disabled.
1033 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1035 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1037 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1039 spin_lock(&rq->lock);
1040 __update_rq_clock(rq);
1041 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1042 spin_unlock(&rq->lock);
1044 return HRTIMER_NORESTART;
1047 static inline void init_rq_hrtick(struct rq *rq)
1049 rq->hrtick_flags = 0;
1050 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1051 rq->hrtick_timer.function = hrtick;
1052 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1055 void hrtick_resched(void)
1057 struct rq *rq;
1058 unsigned long flags;
1060 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1061 return;
1063 local_irq_save(flags);
1064 rq = cpu_rq(smp_processor_id());
1065 hrtick_set(rq);
1066 local_irq_restore(flags);
1068 #else
1069 static inline void hrtick_clear(struct rq *rq)
1073 static inline void hrtick_set(struct rq *rq)
1077 static inline void init_rq_hrtick(struct rq *rq)
1081 void hrtick_resched(void)
1084 #endif
1087 * resched_task - mark a task 'to be rescheduled now'.
1089 * On UP this means the setting of the need_resched flag, on SMP it
1090 * might also involve a cross-CPU call to trigger the scheduler on
1091 * the target CPU.
1093 #ifdef CONFIG_SMP
1095 #ifndef tsk_is_polling
1096 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1097 #endif
1099 static void __resched_task(struct task_struct *p, int tif_bit)
1101 int cpu;
1103 assert_spin_locked(&task_rq(p)->lock);
1105 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1106 return;
1108 set_tsk_thread_flag(p, tif_bit);
1110 cpu = task_cpu(p);
1111 if (cpu == smp_processor_id())
1112 return;
1114 /* NEED_RESCHED must be visible before we test polling */
1115 smp_mb();
1116 if (!tsk_is_polling(p))
1117 smp_send_reschedule(cpu);
1120 static void resched_cpu(int cpu)
1122 struct rq *rq = cpu_rq(cpu);
1123 unsigned long flags;
1125 if (!spin_trylock_irqsave(&rq->lock, flags))
1126 return;
1127 resched_task(cpu_curr(cpu));
1128 spin_unlock_irqrestore(&rq->lock, flags);
1130 #else
1131 static void __resched_task(struct task_struct *p, int tif_bit)
1133 assert_spin_locked(&task_rq(p)->lock);
1134 set_tsk_thread_flag(p, tif_bit);
1136 #endif
1138 #if BITS_PER_LONG == 32
1139 # define WMULT_CONST (~0UL)
1140 #else
1141 # define WMULT_CONST (1UL << 32)
1142 #endif
1144 #define WMULT_SHIFT 32
1147 * Shift right and round:
1149 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1151 static unsigned long
1152 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1153 struct load_weight *lw)
1155 u64 tmp;
1157 if (unlikely(!lw->inv_weight))
1158 <<<<<<< HEAD:kernel/sched.c
1159 lw->inv_weight = (WMULT_CONST - lw->weight/2) / lw->weight + 1;
1160 =======
1161 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1162 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1164 tmp = (u64)delta_exec * weight;
1166 * Check whether we'd overflow the 64-bit multiplication:
1168 if (unlikely(tmp > WMULT_CONST))
1169 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1170 WMULT_SHIFT/2);
1171 else
1172 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1174 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1177 static inline unsigned long
1178 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
1180 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
1183 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1185 lw->weight += inc;
1186 <<<<<<< HEAD:kernel/sched.c
1187 =======
1188 lw->inv_weight = 0;
1189 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1192 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1194 lw->weight -= dec;
1195 <<<<<<< HEAD:kernel/sched.c
1196 =======
1197 lw->inv_weight = 0;
1198 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1202 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1203 * of tasks with abnormal "nice" values across CPUs the contribution that
1204 * each task makes to its run queue's load is weighted according to its
1205 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1206 * scaled version of the new time slice allocation that they receive on time
1207 * slice expiry etc.
1210 #define WEIGHT_IDLEPRIO 2
1211 #define WMULT_IDLEPRIO (1 << 31)
1214 * Nice levels are multiplicative, with a gentle 10% change for every
1215 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1216 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1217 * that remained on nice 0.
1219 * The "10% effect" is relative and cumulative: from _any_ nice level,
1220 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1221 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1222 * If a task goes up by ~10% and another task goes down by ~10% then
1223 * the relative distance between them is ~25%.)
1225 static const int prio_to_weight[40] = {
1226 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1227 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1228 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1229 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1230 /* 0 */ 1024, 820, 655, 526, 423,
1231 /* 5 */ 335, 272, 215, 172, 137,
1232 /* 10 */ 110, 87, 70, 56, 45,
1233 /* 15 */ 36, 29, 23, 18, 15,
1237 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1239 * In cases where the weight does not change often, we can use the
1240 * precalculated inverse to speed up arithmetics by turning divisions
1241 * into multiplications:
1243 static const u32 prio_to_wmult[40] = {
1244 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1245 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1246 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1247 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1248 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1249 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1250 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1251 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1254 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1257 * runqueue iterator, to support SMP load-balancing between different
1258 * scheduling classes, without having to expose their internal data
1259 * structures to the load-balancing proper:
1261 struct rq_iterator {
1262 void *arg;
1263 struct task_struct *(*start)(void *);
1264 struct task_struct *(*next)(void *);
1267 #ifdef CONFIG_SMP
1268 static unsigned long
1269 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1270 unsigned long max_load_move, struct sched_domain *sd,
1271 enum cpu_idle_type idle, int *all_pinned,
1272 int *this_best_prio, struct rq_iterator *iterator);
1274 static int
1275 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1276 struct sched_domain *sd, enum cpu_idle_type idle,
1277 struct rq_iterator *iterator);
1278 #endif
1280 #ifdef CONFIG_CGROUP_CPUACCT
1281 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1282 #else
1283 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1284 #endif
1286 <<<<<<< HEAD:kernel/sched.c
1287 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1289 update_load_add(&rq->load, load);
1292 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1294 update_load_sub(&rq->load, load);
1297 =======
1298 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1299 #ifdef CONFIG_SMP
1300 static unsigned long source_load(int cpu, int type);
1301 static unsigned long target_load(int cpu, int type);
1302 static unsigned long cpu_avg_load_per_task(int cpu);
1303 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1304 #endif /* CONFIG_SMP */
1306 #include "sched_stats.h"
1307 #include "sched_idletask.c"
1308 #include "sched_fair.c"
1309 #include "sched_rt.c"
1310 #ifdef CONFIG_SCHED_DEBUG
1311 # include "sched_debug.c"
1312 #endif
1314 #define sched_class_highest (&rt_sched_class)
1316 <<<<<<< HEAD:kernel/sched.c
1317 static void inc_nr_running(struct rq *rq)
1318 =======
1319 static inline void inc_load(struct rq *rq, const struct task_struct *p)
1321 update_load_add(&rq->load, p->se.load.weight);
1324 static inline void dec_load(struct rq *rq, const struct task_struct *p)
1326 update_load_sub(&rq->load, p->se.load.weight);
1329 static void inc_nr_running(struct task_struct *p, struct rq *rq)
1330 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1332 rq->nr_running++;
1333 <<<<<<< HEAD:kernel/sched.c
1334 =======
1335 inc_load(rq, p);
1336 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1339 <<<<<<< HEAD:kernel/sched.c
1340 static void dec_nr_running(struct rq *rq)
1341 =======
1342 static void dec_nr_running(struct task_struct *p, struct rq *rq)
1343 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1345 rq->nr_running--;
1346 <<<<<<< HEAD:kernel/sched.c
1347 =======
1348 dec_load(rq, p);
1349 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1352 static void set_load_weight(struct task_struct *p)
1354 if (task_has_rt_policy(p)) {
1355 p->se.load.weight = prio_to_weight[0] * 2;
1356 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1357 return;
1361 * SCHED_IDLE tasks get minimal weight:
1363 if (p->policy == SCHED_IDLE) {
1364 p->se.load.weight = WEIGHT_IDLEPRIO;
1365 p->se.load.inv_weight = WMULT_IDLEPRIO;
1366 return;
1369 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1370 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1373 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1375 sched_info_queued(p);
1376 p->sched_class->enqueue_task(rq, p, wakeup);
1377 p->se.on_rq = 1;
1380 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1382 p->sched_class->dequeue_task(rq, p, sleep);
1383 p->se.on_rq = 0;
1387 * __normal_prio - return the priority that is based on the static prio
1389 static inline int __normal_prio(struct task_struct *p)
1391 return p->static_prio;
1395 * Calculate the expected normal priority: i.e. priority
1396 * without taking RT-inheritance into account. Might be
1397 * boosted by interactivity modifiers. Changes upon fork,
1398 * setprio syscalls, and whenever the interactivity
1399 * estimator recalculates.
1401 static inline int normal_prio(struct task_struct *p)
1403 int prio;
1405 if (task_has_rt_policy(p))
1406 prio = MAX_RT_PRIO-1 - p->rt_priority;
1407 else
1408 prio = __normal_prio(p);
1409 return prio;
1413 * Calculate the current priority, i.e. the priority
1414 * taken into account by the scheduler. This value might
1415 * be boosted by RT tasks, or might be boosted by
1416 * interactivity modifiers. Will be RT if the task got
1417 * RT-boosted. If not then it returns p->normal_prio.
1419 static int effective_prio(struct task_struct *p)
1421 p->normal_prio = normal_prio(p);
1423 * If we are RT tasks or we were boosted to RT priority,
1424 * keep the priority unchanged. Otherwise, update priority
1425 * to the normal priority:
1427 if (!rt_prio(p->prio))
1428 return p->normal_prio;
1429 return p->prio;
1433 * activate_task - move a task to the runqueue.
1435 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1437 if (task_contributes_to_load(p))
1438 rq->nr_uninterruptible--;
1440 enqueue_task(rq, p, wakeup);
1441 <<<<<<< HEAD:kernel/sched.c
1442 inc_nr_running(rq);
1443 =======
1444 inc_nr_running(p, rq);
1445 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1449 * deactivate_task - remove a task from the runqueue.
1451 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1453 if (task_contributes_to_load(p))
1454 rq->nr_uninterruptible++;
1456 dequeue_task(rq, p, sleep);
1457 <<<<<<< HEAD:kernel/sched.c
1458 dec_nr_running(rq);
1459 =======
1460 dec_nr_running(p, rq);
1461 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1465 * task_curr - is this task currently executing on a CPU?
1466 * @p: the task in question.
1468 inline int task_curr(const struct task_struct *p)
1470 return cpu_curr(task_cpu(p)) == p;
1473 /* Used instead of source_load when we know the type == 0 */
1474 unsigned long weighted_cpuload(const int cpu)
1476 return cpu_rq(cpu)->load.weight;
1479 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1481 set_task_rq(p, cpu);
1482 #ifdef CONFIG_SMP
1484 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1485 * successfuly executed on another CPU. We must ensure that updates of
1486 * per-task data have been completed by this moment.
1488 smp_wmb();
1489 task_thread_info(p)->cpu = cpu;
1490 #endif
1493 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1494 const struct sched_class *prev_class,
1495 int oldprio, int running)
1497 if (prev_class != p->sched_class) {
1498 if (prev_class->switched_from)
1499 prev_class->switched_from(rq, p, running);
1500 p->sched_class->switched_to(rq, p, running);
1501 } else
1502 p->sched_class->prio_changed(rq, p, oldprio, running);
1505 #ifdef CONFIG_SMP
1508 * Is this task likely cache-hot:
1510 static int
1511 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1513 s64 delta;
1515 <<<<<<< HEAD:kernel/sched.c
1516 =======
1518 * Buddy candidates are cache hot:
1520 if (&p->se == cfs_rq_of(&p->se)->next)
1521 return 1;
1523 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1524 if (p->sched_class != &fair_sched_class)
1525 return 0;
1527 if (sysctl_sched_migration_cost == -1)
1528 return 1;
1529 if (sysctl_sched_migration_cost == 0)
1530 return 0;
1532 delta = now - p->se.exec_start;
1534 return delta < (s64)sysctl_sched_migration_cost;
1538 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1540 int old_cpu = task_cpu(p);
1541 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1542 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1543 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1544 u64 clock_offset;
1546 clock_offset = old_rq->clock - new_rq->clock;
1548 #ifdef CONFIG_SCHEDSTATS
1549 if (p->se.wait_start)
1550 p->se.wait_start -= clock_offset;
1551 if (p->se.sleep_start)
1552 p->se.sleep_start -= clock_offset;
1553 if (p->se.block_start)
1554 p->se.block_start -= clock_offset;
1555 if (old_cpu != new_cpu) {
1556 schedstat_inc(p, se.nr_migrations);
1557 if (task_hot(p, old_rq->clock, NULL))
1558 schedstat_inc(p, se.nr_forced2_migrations);
1560 #endif
1561 p->se.vruntime -= old_cfsrq->min_vruntime -
1562 new_cfsrq->min_vruntime;
1564 __set_task_cpu(p, new_cpu);
1567 struct migration_req {
1568 struct list_head list;
1570 struct task_struct *task;
1571 int dest_cpu;
1573 struct completion done;
1577 * The task's runqueue lock must be held.
1578 * Returns true if you have to wait for migration thread.
1580 static int
1581 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1583 struct rq *rq = task_rq(p);
1586 * If the task is not on a runqueue (and not running), then
1587 * it is sufficient to simply update the task's cpu field.
1589 if (!p->se.on_rq && !task_running(rq, p)) {
1590 set_task_cpu(p, dest_cpu);
1591 return 0;
1594 init_completion(&req->done);
1595 req->task = p;
1596 req->dest_cpu = dest_cpu;
1597 list_add(&req->list, &rq->migration_queue);
1599 return 1;
1603 * wait_task_inactive - wait for a thread to unschedule.
1605 * The caller must ensure that the task *will* unschedule sometime soon,
1606 * else this function might spin for a *long* time. This function can't
1607 * be called with interrupts off, or it may introduce deadlock with
1608 * smp_call_function() if an IPI is sent by the same process we are
1609 * waiting to become inactive.
1611 void wait_task_inactive(struct task_struct *p)
1613 unsigned long flags;
1614 int running, on_rq;
1615 struct rq *rq;
1617 for (;;) {
1619 * We do the initial early heuristics without holding
1620 * any task-queue locks at all. We'll only try to get
1621 * the runqueue lock when things look like they will
1622 * work out!
1624 rq = task_rq(p);
1627 * If the task is actively running on another CPU
1628 * still, just relax and busy-wait without holding
1629 * any locks.
1631 * NOTE! Since we don't hold any locks, it's not
1632 * even sure that "rq" stays as the right runqueue!
1633 * But we don't care, since "task_running()" will
1634 * return false if the runqueue has changed and p
1635 * is actually now running somewhere else!
1637 while (task_running(rq, p))
1638 cpu_relax();
1641 * Ok, time to look more closely! We need the rq
1642 * lock now, to be *sure*. If we're wrong, we'll
1643 * just go back and repeat.
1645 rq = task_rq_lock(p, &flags);
1646 running = task_running(rq, p);
1647 on_rq = p->se.on_rq;
1648 task_rq_unlock(rq, &flags);
1651 * Was it really running after all now that we
1652 * checked with the proper locks actually held?
1654 * Oops. Go back and try again..
1656 if (unlikely(running)) {
1657 cpu_relax();
1658 continue;
1662 * It's not enough that it's not actively running,
1663 * it must be off the runqueue _entirely_, and not
1664 * preempted!
1666 * So if it wa still runnable (but just not actively
1667 * running right now), it's preempted, and we should
1668 * yield - it could be a while.
1670 if (unlikely(on_rq)) {
1671 schedule_timeout_uninterruptible(1);
1672 continue;
1676 * Ahh, all good. It wasn't running, and it wasn't
1677 * runnable, which means that it will never become
1678 * running in the future either. We're all done!
1680 break;
1684 /***
1685 * kick_process - kick a running thread to enter/exit the kernel
1686 * @p: the to-be-kicked thread
1688 * Cause a process which is running on another CPU to enter
1689 * kernel-mode, without any delay. (to get signals handled.)
1691 * NOTE: this function doesnt have to take the runqueue lock,
1692 * because all it wants to ensure is that the remote task enters
1693 * the kernel. If the IPI races and the task has been migrated
1694 * to another CPU then no harm is done and the purpose has been
1695 * achieved as well.
1697 void kick_process(struct task_struct *p)
1699 int cpu;
1701 preempt_disable();
1702 cpu = task_cpu(p);
1703 if ((cpu != smp_processor_id()) && task_curr(p))
1704 smp_send_reschedule(cpu);
1705 preempt_enable();
1709 * Return a low guess at the load of a migration-source cpu weighted
1710 * according to the scheduling class and "nice" value.
1712 * We want to under-estimate the load of migration sources, to
1713 * balance conservatively.
1715 static unsigned long source_load(int cpu, int type)
1717 struct rq *rq = cpu_rq(cpu);
1718 unsigned long total = weighted_cpuload(cpu);
1720 if (type == 0)
1721 return total;
1723 return min(rq->cpu_load[type-1], total);
1727 * Return a high guess at the load of a migration-target cpu weighted
1728 * according to the scheduling class and "nice" value.
1730 static unsigned long target_load(int cpu, int type)
1732 struct rq *rq = cpu_rq(cpu);
1733 unsigned long total = weighted_cpuload(cpu);
1735 if (type == 0)
1736 return total;
1738 return max(rq->cpu_load[type-1], total);
1742 * Return the average load per task on the cpu's run queue
1744 static unsigned long cpu_avg_load_per_task(int cpu)
1746 struct rq *rq = cpu_rq(cpu);
1747 unsigned long total = weighted_cpuload(cpu);
1748 unsigned long n = rq->nr_running;
1750 return n ? total / n : SCHED_LOAD_SCALE;
1754 * find_idlest_group finds and returns the least busy CPU group within the
1755 * domain.
1757 static struct sched_group *
1758 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1760 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1761 unsigned long min_load = ULONG_MAX, this_load = 0;
1762 int load_idx = sd->forkexec_idx;
1763 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1765 do {
1766 unsigned long load, avg_load;
1767 int local_group;
1768 int i;
1770 /* Skip over this group if it has no CPUs allowed */
1771 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1772 continue;
1774 local_group = cpu_isset(this_cpu, group->cpumask);
1776 /* Tally up the load of all CPUs in the group */
1777 avg_load = 0;
1779 for_each_cpu_mask(i, group->cpumask) {
1780 /* Bias balancing toward cpus of our domain */
1781 if (local_group)
1782 load = source_load(i, load_idx);
1783 else
1784 load = target_load(i, load_idx);
1786 avg_load += load;
1789 /* Adjust by relative CPU power of the group */
1790 avg_load = sg_div_cpu_power(group,
1791 avg_load * SCHED_LOAD_SCALE);
1793 if (local_group) {
1794 this_load = avg_load;
1795 this = group;
1796 } else if (avg_load < min_load) {
1797 min_load = avg_load;
1798 idlest = group;
1800 } while (group = group->next, group != sd->groups);
1802 if (!idlest || 100*this_load < imbalance*min_load)
1803 return NULL;
1804 return idlest;
1808 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1810 static int
1811 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1813 cpumask_t tmp;
1814 unsigned long load, min_load = ULONG_MAX;
1815 int idlest = -1;
1816 int i;
1818 /* Traverse only the allowed CPUs */
1819 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1821 for_each_cpu_mask(i, tmp) {
1822 load = weighted_cpuload(i);
1824 if (load < min_load || (load == min_load && i == this_cpu)) {
1825 min_load = load;
1826 idlest = i;
1830 return idlest;
1834 * sched_balance_self: balance the current task (running on cpu) in domains
1835 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1836 * SD_BALANCE_EXEC.
1838 * Balance, ie. select the least loaded group.
1840 * Returns the target CPU number, or the same CPU if no balancing is needed.
1842 * preempt must be disabled.
1844 static int sched_balance_self(int cpu, int flag)
1846 struct task_struct *t = current;
1847 struct sched_domain *tmp, *sd = NULL;
1849 for_each_domain(cpu, tmp) {
1851 * If power savings logic is enabled for a domain, stop there.
1853 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1854 break;
1855 if (tmp->flags & flag)
1856 sd = tmp;
1859 while (sd) {
1860 cpumask_t span;
1861 struct sched_group *group;
1862 int new_cpu, weight;
1864 if (!(sd->flags & flag)) {
1865 sd = sd->child;
1866 continue;
1869 span = sd->span;
1870 group = find_idlest_group(sd, t, cpu);
1871 if (!group) {
1872 sd = sd->child;
1873 continue;
1876 new_cpu = find_idlest_cpu(group, t, cpu);
1877 if (new_cpu == -1 || new_cpu == cpu) {
1878 /* Now try balancing at a lower domain level of cpu */
1879 sd = sd->child;
1880 continue;
1883 /* Now try balancing at a lower domain level of new_cpu */
1884 cpu = new_cpu;
1885 sd = NULL;
1886 weight = cpus_weight(span);
1887 for_each_domain(cpu, tmp) {
1888 if (weight <= cpus_weight(tmp->span))
1889 break;
1890 if (tmp->flags & flag)
1891 sd = tmp;
1893 /* while loop will break here if sd == NULL */
1896 return cpu;
1899 #endif /* CONFIG_SMP */
1901 /***
1902 * try_to_wake_up - wake up a thread
1903 * @p: the to-be-woken-up thread
1904 * @state: the mask of task states that can be woken
1905 * @sync: do a synchronous wakeup?
1907 * Put it on the run-queue if it's not already there. The "current"
1908 * thread is always on the run-queue (except when the actual
1909 * re-schedule is in progress), and as such you're allowed to do
1910 * the simpler "current->state = TASK_RUNNING" to mark yourself
1911 * runnable without the overhead of this.
1913 * returns failure only if the task is already active.
1915 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1917 int cpu, orig_cpu, this_cpu, success = 0;
1918 unsigned long flags;
1919 long old_state;
1920 struct rq *rq;
1922 <<<<<<< HEAD:kernel/sched.c
1923 =======
1924 smp_wmb();
1925 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1926 rq = task_rq_lock(p, &flags);
1927 old_state = p->state;
1928 if (!(old_state & state))
1929 goto out;
1931 if (p->se.on_rq)
1932 goto out_running;
1934 cpu = task_cpu(p);
1935 orig_cpu = cpu;
1936 this_cpu = smp_processor_id();
1938 #ifdef CONFIG_SMP
1939 if (unlikely(task_running(rq, p)))
1940 goto out_activate;
1942 cpu = p->sched_class->select_task_rq(p, sync);
1943 if (cpu != orig_cpu) {
1944 set_task_cpu(p, cpu);
1945 task_rq_unlock(rq, &flags);
1946 /* might preempt at this point */
1947 rq = task_rq_lock(p, &flags);
1948 old_state = p->state;
1949 if (!(old_state & state))
1950 goto out;
1951 if (p->se.on_rq)
1952 goto out_running;
1954 this_cpu = smp_processor_id();
1955 cpu = task_cpu(p);
1958 #ifdef CONFIG_SCHEDSTATS
1959 schedstat_inc(rq, ttwu_count);
1960 if (cpu == this_cpu)
1961 schedstat_inc(rq, ttwu_local);
1962 else {
1963 struct sched_domain *sd;
1964 for_each_domain(this_cpu, sd) {
1965 if (cpu_isset(cpu, sd->span)) {
1966 schedstat_inc(sd, ttwu_wake_remote);
1967 break;
1971 #endif
1973 out_activate:
1974 #endif /* CONFIG_SMP */
1975 schedstat_inc(p, se.nr_wakeups);
1976 if (sync)
1977 schedstat_inc(p, se.nr_wakeups_sync);
1978 if (orig_cpu != cpu)
1979 schedstat_inc(p, se.nr_wakeups_migrate);
1980 if (cpu == this_cpu)
1981 schedstat_inc(p, se.nr_wakeups_local);
1982 else
1983 schedstat_inc(p, se.nr_wakeups_remote);
1984 update_rq_clock(rq);
1985 activate_task(rq, p, 1);
1986 <<<<<<< HEAD:kernel/sched.c
1987 check_preempt_curr(rq, p);
1988 =======
1989 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1990 success = 1;
1992 out_running:
1993 <<<<<<< HEAD:kernel/sched.c
1994 =======
1995 check_preempt_curr(rq, p);
1997 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
1998 p->state = TASK_RUNNING;
1999 #ifdef CONFIG_SMP
2000 if (p->sched_class->task_wake_up)
2001 p->sched_class->task_wake_up(rq, p);
2002 #endif
2003 out:
2004 task_rq_unlock(rq, &flags);
2006 return success;
2009 int wake_up_process(struct task_struct *p)
2011 return try_to_wake_up(p, TASK_ALL, 0);
2013 EXPORT_SYMBOL(wake_up_process);
2015 int wake_up_state(struct task_struct *p, unsigned int state)
2017 return try_to_wake_up(p, state, 0);
2021 * Perform scheduler related setup for a newly forked process p.
2022 * p is forked by current.
2024 * __sched_fork() is basic setup used by init_idle() too:
2026 static void __sched_fork(struct task_struct *p)
2028 p->se.exec_start = 0;
2029 p->se.sum_exec_runtime = 0;
2030 p->se.prev_sum_exec_runtime = 0;
2031 <<<<<<< HEAD:kernel/sched.c
2032 =======
2033 p->se.last_wakeup = 0;
2034 p->se.avg_overlap = 0;
2035 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
2037 #ifdef CONFIG_SCHEDSTATS
2038 p->se.wait_start = 0;
2039 p->se.sum_sleep_runtime = 0;
2040 p->se.sleep_start = 0;
2041 p->se.block_start = 0;
2042 p->se.sleep_max = 0;
2043 p->se.block_max = 0;
2044 p->se.exec_max = 0;
2045 p->se.slice_max = 0;
2046 p->se.wait_max = 0;
2047 #endif
2049 INIT_LIST_HEAD(&p->rt.run_list);
2050 p->se.on_rq = 0;
2052 #ifdef CONFIG_PREEMPT_NOTIFIERS
2053 INIT_HLIST_HEAD(&p->preempt_notifiers);
2054 #endif
2057 * We mark the process as running here, but have not actually
2058 * inserted it onto the runqueue yet. This guarantees that
2059 * nobody will actually run it, and a signal or other external
2060 * event cannot wake it up and insert it on the runqueue either.
2062 p->state = TASK_RUNNING;
2066 * fork()/clone()-time setup:
2068 void sched_fork(struct task_struct *p, int clone_flags)
2070 int cpu = get_cpu();
2072 __sched_fork(p);
2074 #ifdef CONFIG_SMP
2075 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2076 #endif
2077 set_task_cpu(p, cpu);
2080 * Make sure we do not leak PI boosting priority to the child:
2082 p->prio = current->normal_prio;
2083 if (!rt_prio(p->prio))
2084 p->sched_class = &fair_sched_class;
2086 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2087 if (likely(sched_info_on()))
2088 memset(&p->sched_info, 0, sizeof(p->sched_info));
2089 #endif
2090 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2091 p->oncpu = 0;
2092 #endif
2093 #ifdef CONFIG_PREEMPT
2094 /* Want to start with kernel preemption disabled. */
2095 task_thread_info(p)->preempt_count = 1;
2096 #endif
2097 put_cpu();
2101 * wake_up_new_task - wake up a newly created task for the first time.
2103 * This function will do some initial scheduler statistics housekeeping
2104 * that must be done for every newly created context, then puts the task
2105 * on the runqueue and wakes it.
2107 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2109 unsigned long flags;
2110 struct rq *rq;
2112 rq = task_rq_lock(p, &flags);
2113 BUG_ON(p->state != TASK_RUNNING);
2114 update_rq_clock(rq);
2116 p->prio = effective_prio(p);
2118 if (!p->sched_class->task_new || !current->se.on_rq) {
2119 activate_task(rq, p, 0);
2120 } else {
2122 * Let the scheduling class do new task startup
2123 * management (if any):
2125 p->sched_class->task_new(rq, p);
2126 <<<<<<< HEAD:kernel/sched.c
2127 inc_nr_running(rq);
2128 =======
2129 inc_nr_running(p, rq);
2130 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
2132 check_preempt_curr(rq, p);
2133 #ifdef CONFIG_SMP
2134 if (p->sched_class->task_wake_up)
2135 p->sched_class->task_wake_up(rq, p);
2136 #endif
2137 task_rq_unlock(rq, &flags);
2140 #ifdef CONFIG_PREEMPT_NOTIFIERS
2143 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2144 * @notifier: notifier struct to register
2146 void preempt_notifier_register(struct preempt_notifier *notifier)
2148 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2150 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2153 * preempt_notifier_unregister - no longer interested in preemption notifications
2154 * @notifier: notifier struct to unregister
2156 * This is safe to call from within a preemption notifier.
2158 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2160 hlist_del(&notifier->link);
2162 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2164 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2166 struct preempt_notifier *notifier;
2167 struct hlist_node *node;
2169 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2170 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2173 static void
2174 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2175 struct task_struct *next)
2177 struct preempt_notifier *notifier;
2178 struct hlist_node *node;
2180 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2181 notifier->ops->sched_out(notifier, next);
2184 #else
2186 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2190 static void
2191 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2192 struct task_struct *next)
2196 #endif
2199 * prepare_task_switch - prepare to switch tasks
2200 * @rq: the runqueue preparing to switch
2201 * @prev: the current task that is being switched out
2202 * @next: the task we are going to switch to.
2204 * This is called with the rq lock held and interrupts off. It must
2205 * be paired with a subsequent finish_task_switch after the context
2206 * switch.
2208 * prepare_task_switch sets up locking and calls architecture specific
2209 * hooks.
2211 static inline void
2212 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2213 struct task_struct *next)
2215 fire_sched_out_preempt_notifiers(prev, next);
2216 prepare_lock_switch(rq, next);
2217 prepare_arch_switch(next);
2221 * finish_task_switch - clean up after a task-switch
2222 * @rq: runqueue associated with task-switch
2223 * @prev: the thread we just switched away from.
2225 * finish_task_switch must be called after the context switch, paired
2226 * with a prepare_task_switch call before the context switch.
2227 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2228 * and do any other architecture-specific cleanup actions.
2230 * Note that we may have delayed dropping an mm in context_switch(). If
2231 * so, we finish that here outside of the runqueue lock. (Doing it
2232 * with the lock held can cause deadlocks; see schedule() for
2233 * details.)
2235 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2236 __releases(rq->lock)
2238 struct mm_struct *mm = rq->prev_mm;
2239 long prev_state;
2241 rq->prev_mm = NULL;
2244 * A task struct has one reference for the use as "current".
2245 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2246 * schedule one last time. The schedule call will never return, and
2247 * the scheduled task must drop that reference.
2248 * The test for TASK_DEAD must occur while the runqueue locks are
2249 * still held, otherwise prev could be scheduled on another cpu, die
2250 * there before we look at prev->state, and then the reference would
2251 * be dropped twice.
2252 * Manfred Spraul <manfred@colorfullife.com>
2254 prev_state = prev->state;
2255 finish_arch_switch(prev);
2256 finish_lock_switch(rq, prev);
2257 #ifdef CONFIG_SMP
2258 if (current->sched_class->post_schedule)
2259 current->sched_class->post_schedule(rq);
2260 #endif
2262 fire_sched_in_preempt_notifiers(current);
2263 if (mm)
2264 mmdrop(mm);
2265 if (unlikely(prev_state == TASK_DEAD)) {
2267 * Remove function-return probe instances associated with this
2268 * task and put them back on the free list.
2270 kprobe_flush_task(prev);
2271 put_task_struct(prev);
2276 * schedule_tail - first thing a freshly forked thread must call.
2277 * @prev: the thread we just switched away from.
2279 asmlinkage void schedule_tail(struct task_struct *prev)
2280 __releases(rq->lock)
2282 struct rq *rq = this_rq();
2284 finish_task_switch(rq, prev);
2285 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2286 /* In this case, finish_task_switch does not reenable preemption */
2287 preempt_enable();
2288 #endif
2289 if (current->set_child_tid)
2290 put_user(task_pid_vnr(current), current->set_child_tid);
2294 * context_switch - switch to the new MM and the new
2295 * thread's register state.
2297 static inline void
2298 context_switch(struct rq *rq, struct task_struct *prev,
2299 struct task_struct *next)
2301 struct mm_struct *mm, *oldmm;
2303 prepare_task_switch(rq, prev, next);
2304 mm = next->mm;
2305 oldmm = prev->active_mm;
2307 * For paravirt, this is coupled with an exit in switch_to to
2308 * combine the page table reload and the switch backend into
2309 * one hypercall.
2311 arch_enter_lazy_cpu_mode();
2313 if (unlikely(!mm)) {
2314 next->active_mm = oldmm;
2315 atomic_inc(&oldmm->mm_count);
2316 enter_lazy_tlb(oldmm, next);
2317 } else
2318 switch_mm(oldmm, mm, next);
2320 if (unlikely(!prev->mm)) {
2321 prev->active_mm = NULL;
2322 rq->prev_mm = oldmm;
2325 * Since the runqueue lock will be released by the next
2326 * task (which is an invalid locking op but in the case
2327 * of the scheduler it's an obvious special-case), so we
2328 * do an early lockdep release here:
2330 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2331 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2332 #endif
2334 /* Here we just switch the register state and the stack. */
2335 switch_to(prev, next, prev);
2337 barrier();
2339 * this_rq must be evaluated again because prev may have moved
2340 * CPUs since it called schedule(), thus the 'rq' on its stack
2341 * frame will be invalid.
2343 finish_task_switch(this_rq(), prev);
2347 * nr_running, nr_uninterruptible and nr_context_switches:
2349 * externally visible scheduler statistics: current number of runnable
2350 * threads, current number of uninterruptible-sleeping threads, total
2351 * number of context switches performed since bootup.
2353 unsigned long nr_running(void)
2355 unsigned long i, sum = 0;
2357 for_each_online_cpu(i)
2358 sum += cpu_rq(i)->nr_running;
2360 return sum;
2363 unsigned long nr_uninterruptible(void)
2365 unsigned long i, sum = 0;
2367 for_each_possible_cpu(i)
2368 sum += cpu_rq(i)->nr_uninterruptible;
2371 * Since we read the counters lockless, it might be slightly
2372 * inaccurate. Do not allow it to go below zero though:
2374 if (unlikely((long)sum < 0))
2375 sum = 0;
2377 return sum;
2380 unsigned long long nr_context_switches(void)
2382 int i;
2383 unsigned long long sum = 0;
2385 for_each_possible_cpu(i)
2386 sum += cpu_rq(i)->nr_switches;
2388 return sum;
2391 unsigned long nr_iowait(void)
2393 unsigned long i, sum = 0;
2395 for_each_possible_cpu(i)
2396 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2398 return sum;
2401 unsigned long nr_active(void)
2403 unsigned long i, running = 0, uninterruptible = 0;
2405 for_each_online_cpu(i) {
2406 running += cpu_rq(i)->nr_running;
2407 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2410 if (unlikely((long)uninterruptible < 0))
2411 uninterruptible = 0;
2413 return running + uninterruptible;
2417 * Update rq->cpu_load[] statistics. This function is usually called every
2418 * scheduler tick (TICK_NSEC).
2420 static void update_cpu_load(struct rq *this_rq)
2422 unsigned long this_load = this_rq->load.weight;
2423 int i, scale;
2425 this_rq->nr_load_updates++;
2427 /* Update our load: */
2428 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2429 unsigned long old_load, new_load;
2431 /* scale is effectively 1 << i now, and >> i divides by scale */
2433 old_load = this_rq->cpu_load[i];
2434 new_load = this_load;
2436 * Round up the averaging division if load is increasing. This
2437 * prevents us from getting stuck on 9 if the load is 10, for
2438 * example.
2440 if (new_load > old_load)
2441 new_load += scale-1;
2442 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2446 #ifdef CONFIG_SMP
2449 * double_rq_lock - safely lock two runqueues
2451 * Note this does not disable interrupts like task_rq_lock,
2452 * you need to do so manually before calling.
2454 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2455 __acquires(rq1->lock)
2456 __acquires(rq2->lock)
2458 BUG_ON(!irqs_disabled());
2459 if (rq1 == rq2) {
2460 spin_lock(&rq1->lock);
2461 __acquire(rq2->lock); /* Fake it out ;) */
2462 } else {
2463 if (rq1 < rq2) {
2464 spin_lock(&rq1->lock);
2465 spin_lock(&rq2->lock);
2466 } else {
2467 spin_lock(&rq2->lock);
2468 spin_lock(&rq1->lock);
2471 update_rq_clock(rq1);
2472 update_rq_clock(rq2);
2476 * double_rq_unlock - safely unlock two runqueues
2478 * Note this does not restore interrupts like task_rq_unlock,
2479 * you need to do so manually after calling.
2481 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2482 __releases(rq1->lock)
2483 __releases(rq2->lock)
2485 spin_unlock(&rq1->lock);
2486 if (rq1 != rq2)
2487 spin_unlock(&rq2->lock);
2488 else
2489 __release(rq2->lock);
2493 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2495 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2496 __releases(this_rq->lock)
2497 __acquires(busiest->lock)
2498 __acquires(this_rq->lock)
2500 int ret = 0;
2502 if (unlikely(!irqs_disabled())) {
2503 /* printk() doesn't work good under rq->lock */
2504 spin_unlock(&this_rq->lock);
2505 BUG_ON(1);
2507 if (unlikely(!spin_trylock(&busiest->lock))) {
2508 if (busiest < this_rq) {
2509 spin_unlock(&this_rq->lock);
2510 spin_lock(&busiest->lock);
2511 spin_lock(&this_rq->lock);
2512 ret = 1;
2513 } else
2514 spin_lock(&busiest->lock);
2516 return ret;
2520 * If dest_cpu is allowed for this process, migrate the task to it.
2521 * This is accomplished by forcing the cpu_allowed mask to only
2522 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2523 * the cpu_allowed mask is restored.
2525 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2527 struct migration_req req;
2528 unsigned long flags;
2529 struct rq *rq;
2531 rq = task_rq_lock(p, &flags);
2532 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2533 || unlikely(cpu_is_offline(dest_cpu)))
2534 goto out;
2536 /* force the process onto the specified CPU */
2537 if (migrate_task(p, dest_cpu, &req)) {
2538 /* Need to wait for migration thread (might exit: take ref). */
2539 struct task_struct *mt = rq->migration_thread;
2541 get_task_struct(mt);
2542 task_rq_unlock(rq, &flags);
2543 wake_up_process(mt);
2544 put_task_struct(mt);
2545 wait_for_completion(&req.done);
2547 return;
2549 out:
2550 task_rq_unlock(rq, &flags);
2554 * sched_exec - execve() is a valuable balancing opportunity, because at
2555 * this point the task has the smallest effective memory and cache footprint.
2557 void sched_exec(void)
2559 int new_cpu, this_cpu = get_cpu();
2560 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2561 put_cpu();
2562 if (new_cpu != this_cpu)
2563 sched_migrate_task(current, new_cpu);
2567 * pull_task - move a task from a remote runqueue to the local runqueue.
2568 * Both runqueues must be locked.
2570 static void pull_task(struct rq *src_rq, struct task_struct *p,
2571 struct rq *this_rq, int this_cpu)
2573 deactivate_task(src_rq, p, 0);
2574 set_task_cpu(p, this_cpu);
2575 activate_task(this_rq, p, 0);
2577 * Note that idle threads have a prio of MAX_PRIO, for this test
2578 * to be always true for them.
2580 check_preempt_curr(this_rq, p);
2584 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2586 static
2587 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2588 struct sched_domain *sd, enum cpu_idle_type idle,
2589 int *all_pinned)
2592 * We do not migrate tasks that are:
2593 * 1) running (obviously), or
2594 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2595 * 3) are cache-hot on their current CPU.
2597 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2598 schedstat_inc(p, se.nr_failed_migrations_affine);
2599 return 0;
2601 *all_pinned = 0;
2603 if (task_running(rq, p)) {
2604 schedstat_inc(p, se.nr_failed_migrations_running);
2605 return 0;
2609 * Aggressive migration if:
2610 * 1) task is cache cold, or
2611 * 2) too many balance attempts have failed.
2614 if (!task_hot(p, rq->clock, sd) ||
2615 sd->nr_balance_failed > sd->cache_nice_tries) {
2616 #ifdef CONFIG_SCHEDSTATS
2617 if (task_hot(p, rq->clock, sd)) {
2618 schedstat_inc(sd, lb_hot_gained[idle]);
2619 schedstat_inc(p, se.nr_forced_migrations);
2621 #endif
2622 return 1;
2625 if (task_hot(p, rq->clock, sd)) {
2626 schedstat_inc(p, se.nr_failed_migrations_hot);
2627 return 0;
2629 return 1;
2632 static unsigned long
2633 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2634 unsigned long max_load_move, struct sched_domain *sd,
2635 enum cpu_idle_type idle, int *all_pinned,
2636 int *this_best_prio, struct rq_iterator *iterator)
2638 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
2639 struct task_struct *p;
2640 long rem_load_move = max_load_move;
2642 if (max_load_move == 0)
2643 goto out;
2645 pinned = 1;
2648 * Start the load-balancing iterator:
2650 p = iterator->start(iterator->arg);
2651 next:
2652 if (!p || loops++ > sysctl_sched_nr_migrate)
2653 goto out;
2655 * To help distribute high priority tasks across CPUs we don't
2656 * skip a task if it will be the highest priority task (i.e. smallest
2657 * prio value) on its new queue regardless of its load weight
2659 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2660 SCHED_LOAD_SCALE_FUZZ;
2661 if ((skip_for_load && p->prio >= *this_best_prio) ||
2662 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2663 p = iterator->next(iterator->arg);
2664 goto next;
2667 pull_task(busiest, p, this_rq, this_cpu);
2668 pulled++;
2669 rem_load_move -= p->se.load.weight;
2672 * We only want to steal up to the prescribed amount of weighted load.
2674 if (rem_load_move > 0) {
2675 if (p->prio < *this_best_prio)
2676 *this_best_prio = p->prio;
2677 p = iterator->next(iterator->arg);
2678 goto next;
2680 out:
2682 * Right now, this is one of only two places pull_task() is called,
2683 * so we can safely collect pull_task() stats here rather than
2684 * inside pull_task().
2686 schedstat_add(sd, lb_gained[idle], pulled);
2688 if (all_pinned)
2689 *all_pinned = pinned;
2691 return max_load_move - rem_load_move;
2695 * move_tasks tries to move up to max_load_move weighted load from busiest to
2696 * this_rq, as part of a balancing operation within domain "sd".
2697 * Returns 1 if successful and 0 otherwise.
2699 * Called with both runqueues locked.
2701 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2702 unsigned long max_load_move,
2703 struct sched_domain *sd, enum cpu_idle_type idle,
2704 int *all_pinned)
2706 const struct sched_class *class = sched_class_highest;
2707 unsigned long total_load_moved = 0;
2708 int this_best_prio = this_rq->curr->prio;
2710 do {
2711 total_load_moved +=
2712 class->load_balance(this_rq, this_cpu, busiest,
2713 max_load_move - total_load_moved,
2714 sd, idle, all_pinned, &this_best_prio);
2715 class = class->next;
2716 } while (class && max_load_move > total_load_moved);
2718 return total_load_moved > 0;
2721 static int
2722 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2723 struct sched_domain *sd, enum cpu_idle_type idle,
2724 struct rq_iterator *iterator)
2726 struct task_struct *p = iterator->start(iterator->arg);
2727 int pinned = 0;
2729 while (p) {
2730 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2731 pull_task(busiest, p, this_rq, this_cpu);
2733 * Right now, this is only the second place pull_task()
2734 * is called, so we can safely collect pull_task()
2735 * stats here rather than inside pull_task().
2737 schedstat_inc(sd, lb_gained[idle]);
2739 return 1;
2741 p = iterator->next(iterator->arg);
2744 return 0;
2748 * move_one_task tries to move exactly one task from busiest to this_rq, as
2749 * part of active balancing operations within "domain".
2750 * Returns 1 if successful and 0 otherwise.
2752 * Called with both runqueues locked.
2754 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2755 struct sched_domain *sd, enum cpu_idle_type idle)
2757 const struct sched_class *class;
2759 for (class = sched_class_highest; class; class = class->next)
2760 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
2761 return 1;
2763 return 0;
2767 * find_busiest_group finds and returns the busiest CPU group within the
2768 * domain. It calculates and returns the amount of weighted load which
2769 * should be moved to restore balance via the imbalance parameter.
2771 static struct sched_group *
2772 find_busiest_group(struct sched_domain *sd, int this_cpu,
2773 unsigned long *imbalance, enum cpu_idle_type idle,
2774 int *sd_idle, cpumask_t *cpus, int *balance)
2776 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2777 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2778 unsigned long max_pull;
2779 unsigned long busiest_load_per_task, busiest_nr_running;
2780 unsigned long this_load_per_task, this_nr_running;
2781 int load_idx, group_imb = 0;
2782 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2783 int power_savings_balance = 1;
2784 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2785 unsigned long min_nr_running = ULONG_MAX;
2786 struct sched_group *group_min = NULL, *group_leader = NULL;
2787 #endif
2789 max_load = this_load = total_load = total_pwr = 0;
2790 busiest_load_per_task = busiest_nr_running = 0;
2791 this_load_per_task = this_nr_running = 0;
2792 if (idle == CPU_NOT_IDLE)
2793 load_idx = sd->busy_idx;
2794 else if (idle == CPU_NEWLY_IDLE)
2795 load_idx = sd->newidle_idx;
2796 else
2797 load_idx = sd->idle_idx;
2799 do {
2800 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
2801 int local_group;
2802 int i;
2803 int __group_imb = 0;
2804 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2805 unsigned long sum_nr_running, sum_weighted_load;
2807 local_group = cpu_isset(this_cpu, group->cpumask);
2809 if (local_group)
2810 balance_cpu = first_cpu(group->cpumask);
2812 /* Tally up the load of all CPUs in the group */
2813 sum_weighted_load = sum_nr_running = avg_load = 0;
2814 max_cpu_load = 0;
2815 min_cpu_load = ~0UL;
2817 for_each_cpu_mask(i, group->cpumask) {
2818 struct rq *rq;
2820 if (!cpu_isset(i, *cpus))
2821 continue;
2823 rq = cpu_rq(i);
2825 if (*sd_idle && rq->nr_running)
2826 *sd_idle = 0;
2828 /* Bias balancing toward cpus of our domain */
2829 if (local_group) {
2830 if (idle_cpu(i) && !first_idle_cpu) {
2831 first_idle_cpu = 1;
2832 balance_cpu = i;
2835 load = target_load(i, load_idx);
2836 } else {
2837 load = source_load(i, load_idx);
2838 if (load > max_cpu_load)
2839 max_cpu_load = load;
2840 if (min_cpu_load > load)
2841 min_cpu_load = load;
2844 avg_load += load;
2845 sum_nr_running += rq->nr_running;
2846 sum_weighted_load += weighted_cpuload(i);
2850 * First idle cpu or the first cpu(busiest) in this sched group
2851 * is eligible for doing load balancing at this and above
2852 * domains. In the newly idle case, we will allow all the cpu's
2853 * to do the newly idle load balance.
2855 if (idle != CPU_NEWLY_IDLE && local_group &&
2856 balance_cpu != this_cpu && balance) {
2857 *balance = 0;
2858 goto ret;
2861 total_load += avg_load;
2862 total_pwr += group->__cpu_power;
2864 /* Adjust by relative CPU power of the group */
2865 avg_load = sg_div_cpu_power(group,
2866 avg_load * SCHED_LOAD_SCALE);
2868 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2869 __group_imb = 1;
2871 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2873 if (local_group) {
2874 this_load = avg_load;
2875 this = group;
2876 this_nr_running = sum_nr_running;
2877 this_load_per_task = sum_weighted_load;
2878 } else if (avg_load > max_load &&
2879 (sum_nr_running > group_capacity || __group_imb)) {
2880 max_load = avg_load;
2881 busiest = group;
2882 busiest_nr_running = sum_nr_running;
2883 busiest_load_per_task = sum_weighted_load;
2884 group_imb = __group_imb;
2887 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2889 * Busy processors will not participate in power savings
2890 * balance.
2892 if (idle == CPU_NOT_IDLE ||
2893 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2894 goto group_next;
2897 * If the local group is idle or completely loaded
2898 * no need to do power savings balance at this domain
2900 if (local_group && (this_nr_running >= group_capacity ||
2901 !this_nr_running))
2902 power_savings_balance = 0;
2905 * If a group is already running at full capacity or idle,
2906 * don't include that group in power savings calculations
2908 if (!power_savings_balance || sum_nr_running >= group_capacity
2909 || !sum_nr_running)
2910 goto group_next;
2913 * Calculate the group which has the least non-idle load.
2914 * This is the group from where we need to pick up the load
2915 * for saving power
2917 if ((sum_nr_running < min_nr_running) ||
2918 (sum_nr_running == min_nr_running &&
2919 first_cpu(group->cpumask) <
2920 first_cpu(group_min->cpumask))) {
2921 group_min = group;
2922 min_nr_running = sum_nr_running;
2923 min_load_per_task = sum_weighted_load /
2924 sum_nr_running;
2928 * Calculate the group which is almost near its
2929 * capacity but still has some space to pick up some load
2930 * from other group and save more power
2932 if (sum_nr_running <= group_capacity - 1) {
2933 if (sum_nr_running > leader_nr_running ||
2934 (sum_nr_running == leader_nr_running &&
2935 first_cpu(group->cpumask) >
2936 first_cpu(group_leader->cpumask))) {
2937 group_leader = group;
2938 leader_nr_running = sum_nr_running;
2941 group_next:
2942 #endif
2943 group = group->next;
2944 } while (group != sd->groups);
2946 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2947 goto out_balanced;
2949 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2951 if (this_load >= avg_load ||
2952 100*max_load <= sd->imbalance_pct*this_load)
2953 goto out_balanced;
2955 busiest_load_per_task /= busiest_nr_running;
2956 if (group_imb)
2957 busiest_load_per_task = min(busiest_load_per_task, avg_load);
2960 * We're trying to get all the cpus to the average_load, so we don't
2961 * want to push ourselves above the average load, nor do we wish to
2962 * reduce the max loaded cpu below the average load, as either of these
2963 * actions would just result in more rebalancing later, and ping-pong
2964 * tasks around. Thus we look for the minimum possible imbalance.
2965 * Negative imbalances (*we* are more loaded than anyone else) will
2966 * be counted as no imbalance for these purposes -- we can't fix that
2967 * by pulling tasks to us. Be careful of negative numbers as they'll
2968 * appear as very large values with unsigned longs.
2970 if (max_load <= busiest_load_per_task)
2971 goto out_balanced;
2974 * In the presence of smp nice balancing, certain scenarios can have
2975 * max load less than avg load(as we skip the groups at or below
2976 * its cpu_power, while calculating max_load..)
2978 if (max_load < avg_load) {
2979 *imbalance = 0;
2980 goto small_imbalance;
2983 /* Don't want to pull so many tasks that a group would go idle */
2984 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2986 /* How much load to actually move to equalise the imbalance */
2987 *imbalance = min(max_pull * busiest->__cpu_power,
2988 (avg_load - this_load) * this->__cpu_power)
2989 / SCHED_LOAD_SCALE;
2992 * if *imbalance is less than the average load per runnable task
2993 * there is no gaurantee that any tasks will be moved so we'll have
2994 * a think about bumping its value to force at least one task to be
2995 * moved
2997 if (*imbalance < busiest_load_per_task) {
2998 unsigned long tmp, pwr_now, pwr_move;
2999 unsigned int imbn;
3001 small_imbalance:
3002 pwr_move = pwr_now = 0;
3003 imbn = 2;
3004 if (this_nr_running) {
3005 this_load_per_task /= this_nr_running;
3006 if (busiest_load_per_task > this_load_per_task)
3007 imbn = 1;
3008 } else
3009 this_load_per_task = SCHED_LOAD_SCALE;
3011 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3012 busiest_load_per_task * imbn) {
3013 *imbalance = busiest_load_per_task;
3014 return busiest;
3018 * OK, we don't have enough imbalance to justify moving tasks,
3019 * however we may be able to increase total CPU power used by
3020 * moving them.
3023 pwr_now += busiest->__cpu_power *
3024 min(busiest_load_per_task, max_load);
3025 pwr_now += this->__cpu_power *
3026 min(this_load_per_task, this_load);
3027 pwr_now /= SCHED_LOAD_SCALE;
3029 /* Amount of load we'd subtract */
3030 tmp = sg_div_cpu_power(busiest,
3031 busiest_load_per_task * SCHED_LOAD_SCALE);
3032 if (max_load > tmp)
3033 pwr_move += busiest->__cpu_power *
3034 min(busiest_load_per_task, max_load - tmp);
3036 /* Amount of load we'd add */
3037 if (max_load * busiest->__cpu_power <
3038 busiest_load_per_task * SCHED_LOAD_SCALE)
3039 tmp = sg_div_cpu_power(this,
3040 max_load * busiest->__cpu_power);
3041 else
3042 tmp = sg_div_cpu_power(this,
3043 busiest_load_per_task * SCHED_LOAD_SCALE);
3044 pwr_move += this->__cpu_power *
3045 min(this_load_per_task, this_load + tmp);
3046 pwr_move /= SCHED_LOAD_SCALE;
3048 /* Move if we gain throughput */
3049 if (pwr_move > pwr_now)
3050 *imbalance = busiest_load_per_task;
3053 return busiest;
3055 out_balanced:
3056 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3057 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3058 goto ret;
3060 if (this == group_leader && group_leader != group_min) {
3061 *imbalance = min_load_per_task;
3062 return group_min;
3064 #endif
3065 ret:
3066 *imbalance = 0;
3067 return NULL;
3071 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3073 static struct rq *
3074 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3075 unsigned long imbalance, cpumask_t *cpus)
3077 struct rq *busiest = NULL, *rq;
3078 unsigned long max_load = 0;
3079 int i;
3081 for_each_cpu_mask(i, group->cpumask) {
3082 unsigned long wl;
3084 if (!cpu_isset(i, *cpus))
3085 continue;
3087 rq = cpu_rq(i);
3088 wl = weighted_cpuload(i);
3090 if (rq->nr_running == 1 && wl > imbalance)
3091 continue;
3093 if (wl > max_load) {
3094 max_load = wl;
3095 busiest = rq;
3099 return busiest;
3103 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3104 * so long as it is large enough.
3106 #define MAX_PINNED_INTERVAL 512
3109 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3110 * tasks if there is an imbalance.
3112 static int load_balance(int this_cpu, struct rq *this_rq,
3113 struct sched_domain *sd, enum cpu_idle_type idle,
3114 int *balance)
3116 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3117 struct sched_group *group;
3118 unsigned long imbalance;
3119 struct rq *busiest;
3120 cpumask_t cpus = CPU_MASK_ALL;
3121 unsigned long flags;
3124 * When power savings policy is enabled for the parent domain, idle
3125 * sibling can pick up load irrespective of busy siblings. In this case,
3126 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3127 * portraying it as CPU_NOT_IDLE.
3129 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3130 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3131 sd_idle = 1;
3133 schedstat_inc(sd, lb_count[idle]);
3135 redo:
3136 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3137 &cpus, balance);
3139 if (*balance == 0)
3140 goto out_balanced;
3142 if (!group) {
3143 schedstat_inc(sd, lb_nobusyg[idle]);
3144 goto out_balanced;
3147 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
3148 if (!busiest) {
3149 schedstat_inc(sd, lb_nobusyq[idle]);
3150 goto out_balanced;
3153 BUG_ON(busiest == this_rq);
3155 schedstat_add(sd, lb_imbalance[idle], imbalance);
3157 ld_moved = 0;
3158 if (busiest->nr_running > 1) {
3160 * Attempt to move tasks. If find_busiest_group has found
3161 * an imbalance but busiest->nr_running <= 1, the group is
3162 * still unbalanced. ld_moved simply stays zero, so it is
3163 * correctly treated as an imbalance.
3165 local_irq_save(flags);
3166 double_rq_lock(this_rq, busiest);
3167 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3168 imbalance, sd, idle, &all_pinned);
3169 double_rq_unlock(this_rq, busiest);
3170 local_irq_restore(flags);
3173 * some other cpu did the load balance for us.
3175 if (ld_moved && this_cpu != smp_processor_id())
3176 resched_cpu(this_cpu);
3178 /* All tasks on this runqueue were pinned by CPU affinity */
3179 if (unlikely(all_pinned)) {
3180 cpu_clear(cpu_of(busiest), cpus);
3181 if (!cpus_empty(cpus))
3182 goto redo;
3183 goto out_balanced;
3187 if (!ld_moved) {
3188 schedstat_inc(sd, lb_failed[idle]);
3189 sd->nr_balance_failed++;
3191 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3193 spin_lock_irqsave(&busiest->lock, flags);
3195 /* don't kick the migration_thread, if the curr
3196 * task on busiest cpu can't be moved to this_cpu
3198 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3199 spin_unlock_irqrestore(&busiest->lock, flags);
3200 all_pinned = 1;
3201 goto out_one_pinned;
3204 if (!busiest->active_balance) {
3205 busiest->active_balance = 1;
3206 busiest->push_cpu = this_cpu;
3207 active_balance = 1;
3209 spin_unlock_irqrestore(&busiest->lock, flags);
3210 if (active_balance)
3211 wake_up_process(busiest->migration_thread);
3214 * We've kicked active balancing, reset the failure
3215 * counter.
3217 sd->nr_balance_failed = sd->cache_nice_tries+1;
3219 } else
3220 sd->nr_balance_failed = 0;
3222 if (likely(!active_balance)) {
3223 /* We were unbalanced, so reset the balancing interval */
3224 sd->balance_interval = sd->min_interval;
3225 } else {
3227 * If we've begun active balancing, start to back off. This
3228 * case may not be covered by the all_pinned logic if there
3229 * is only 1 task on the busy runqueue (because we don't call
3230 * move_tasks).
3232 if (sd->balance_interval < sd->max_interval)
3233 sd->balance_interval *= 2;
3236 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3237 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3238 return -1;
3239 return ld_moved;
3241 out_balanced:
3242 schedstat_inc(sd, lb_balanced[idle]);
3244 sd->nr_balance_failed = 0;
3246 out_one_pinned:
3247 /* tune up the balancing interval */
3248 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3249 (sd->balance_interval < sd->max_interval))
3250 sd->balance_interval *= 2;
3252 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3253 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3254 return -1;
3255 return 0;
3259 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3260 * tasks if there is an imbalance.
3262 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3263 * this_rq is locked.
3265 static int
3266 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
3268 struct sched_group *group;
3269 struct rq *busiest = NULL;
3270 unsigned long imbalance;
3271 int ld_moved = 0;
3272 int sd_idle = 0;
3273 int all_pinned = 0;
3274 cpumask_t cpus = CPU_MASK_ALL;
3277 * When power savings policy is enabled for the parent domain, idle
3278 * sibling can pick up load irrespective of busy siblings. In this case,
3279 * let the state of idle sibling percolate up as IDLE, instead of
3280 * portraying it as CPU_NOT_IDLE.
3282 if (sd->flags & SD_SHARE_CPUPOWER &&
3283 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3284 sd_idle = 1;
3286 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3287 redo:
3288 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3289 &sd_idle, &cpus, NULL);
3290 if (!group) {
3291 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3292 goto out_balanced;
3295 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
3296 &cpus);
3297 if (!busiest) {
3298 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3299 goto out_balanced;
3302 BUG_ON(busiest == this_rq);
3304 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3306 ld_moved = 0;
3307 if (busiest->nr_running > 1) {
3308 /* Attempt to move tasks */
3309 double_lock_balance(this_rq, busiest);
3310 /* this_rq->clock is already updated */
3311 update_rq_clock(busiest);
3312 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3313 imbalance, sd, CPU_NEWLY_IDLE,
3314 &all_pinned);
3315 spin_unlock(&busiest->lock);
3317 if (unlikely(all_pinned)) {
3318 cpu_clear(cpu_of(busiest), cpus);
3319 if (!cpus_empty(cpus))
3320 goto redo;
3324 if (!ld_moved) {
3325 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3326 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3327 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3328 return -1;
3329 } else
3330 sd->nr_balance_failed = 0;
3332 return ld_moved;
3334 out_balanced:
3335 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3336 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3337 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3338 return -1;
3339 sd->nr_balance_failed = 0;
3341 return 0;
3345 * idle_balance is called by schedule() if this_cpu is about to become
3346 * idle. Attempts to pull tasks from other CPUs.
3348 static void idle_balance(int this_cpu, struct rq *this_rq)
3350 struct sched_domain *sd;
3351 int pulled_task = -1;
3352 unsigned long next_balance = jiffies + HZ;
3354 for_each_domain(this_cpu, sd) {
3355 unsigned long interval;
3357 if (!(sd->flags & SD_LOAD_BALANCE))
3358 continue;
3360 if (sd->flags & SD_BALANCE_NEWIDLE)
3361 /* If we've pulled tasks over stop searching: */
3362 pulled_task = load_balance_newidle(this_cpu,
3363 this_rq, sd);
3365 interval = msecs_to_jiffies(sd->balance_interval);
3366 if (time_after(next_balance, sd->last_balance + interval))
3367 next_balance = sd->last_balance + interval;
3368 if (pulled_task)
3369 break;
3371 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3373 * We are going idle. next_balance may be set based on
3374 * a busy processor. So reset next_balance.
3376 this_rq->next_balance = next_balance;
3381 * active_load_balance is run by migration threads. It pushes running tasks
3382 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3383 * running on each physical CPU where possible, and avoids physical /
3384 * logical imbalances.
3386 * Called with busiest_rq locked.
3388 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3390 int target_cpu = busiest_rq->push_cpu;
3391 struct sched_domain *sd;
3392 struct rq *target_rq;
3394 /* Is there any task to move? */
3395 if (busiest_rq->nr_running <= 1)
3396 return;
3398 target_rq = cpu_rq(target_cpu);
3401 * This condition is "impossible", if it occurs
3402 * we need to fix it. Originally reported by
3403 * Bjorn Helgaas on a 128-cpu setup.
3405 BUG_ON(busiest_rq == target_rq);
3407 /* move a task from busiest_rq to target_rq */
3408 double_lock_balance(busiest_rq, target_rq);
3409 update_rq_clock(busiest_rq);
3410 update_rq_clock(target_rq);
3412 /* Search for an sd spanning us and the target CPU. */
3413 for_each_domain(target_cpu, sd) {
3414 if ((sd->flags & SD_LOAD_BALANCE) &&
3415 cpu_isset(busiest_cpu, sd->span))
3416 break;
3419 if (likely(sd)) {
3420 schedstat_inc(sd, alb_count);
3422 if (move_one_task(target_rq, target_cpu, busiest_rq,
3423 sd, CPU_IDLE))
3424 schedstat_inc(sd, alb_pushed);
3425 else
3426 schedstat_inc(sd, alb_failed);
3428 spin_unlock(&target_rq->lock);
3431 #ifdef CONFIG_NO_HZ
3432 static struct {
3433 atomic_t load_balancer;
3434 cpumask_t cpu_mask;
3435 } nohz ____cacheline_aligned = {
3436 .load_balancer = ATOMIC_INIT(-1),
3437 .cpu_mask = CPU_MASK_NONE,
3441 * This routine will try to nominate the ilb (idle load balancing)
3442 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3443 * load balancing on behalf of all those cpus. If all the cpus in the system
3444 * go into this tickless mode, then there will be no ilb owner (as there is
3445 * no need for one) and all the cpus will sleep till the next wakeup event
3446 * arrives...
3448 * For the ilb owner, tick is not stopped. And this tick will be used
3449 * for idle load balancing. ilb owner will still be part of
3450 * nohz.cpu_mask..
3452 * While stopping the tick, this cpu will become the ilb owner if there
3453 * is no other owner. And will be the owner till that cpu becomes busy
3454 * or if all cpus in the system stop their ticks at which point
3455 * there is no need for ilb owner.
3457 * When the ilb owner becomes busy, it nominates another owner, during the
3458 * next busy scheduler_tick()
3460 int select_nohz_load_balancer(int stop_tick)
3462 int cpu = smp_processor_id();
3464 if (stop_tick) {
3465 cpu_set(cpu, nohz.cpu_mask);
3466 cpu_rq(cpu)->in_nohz_recently = 1;
3469 * If we are going offline and still the leader, give up!
3471 if (cpu_is_offline(cpu) &&
3472 atomic_read(&nohz.load_balancer) == cpu) {
3473 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3474 BUG();
3475 return 0;
3478 /* time for ilb owner also to sleep */
3479 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3480 if (atomic_read(&nohz.load_balancer) == cpu)
3481 atomic_set(&nohz.load_balancer, -1);
3482 return 0;
3485 if (atomic_read(&nohz.load_balancer) == -1) {
3486 /* make me the ilb owner */
3487 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3488 return 1;
3489 } else if (atomic_read(&nohz.load_balancer) == cpu)
3490 return 1;
3491 } else {
3492 if (!cpu_isset(cpu, nohz.cpu_mask))
3493 return 0;
3495 cpu_clear(cpu, nohz.cpu_mask);
3497 if (atomic_read(&nohz.load_balancer) == cpu)
3498 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3499 BUG();
3501 return 0;
3503 #endif
3505 static DEFINE_SPINLOCK(balancing);
3508 * It checks each scheduling domain to see if it is due to be balanced,
3509 * and initiates a balancing operation if so.
3511 * Balancing parameters are set up in arch_init_sched_domains.
3513 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3515 int balance = 1;
3516 struct rq *rq = cpu_rq(cpu);
3517 unsigned long interval;
3518 struct sched_domain *sd;
3519 /* Earliest time when we have to do rebalance again */
3520 unsigned long next_balance = jiffies + 60*HZ;
3521 int update_next_balance = 0;
3523 for_each_domain(cpu, sd) {
3524 if (!(sd->flags & SD_LOAD_BALANCE))
3525 continue;
3527 interval = sd->balance_interval;
3528 if (idle != CPU_IDLE)
3529 interval *= sd->busy_factor;
3531 /* scale ms to jiffies */
3532 interval = msecs_to_jiffies(interval);
3533 if (unlikely(!interval))
3534 interval = 1;
3535 if (interval > HZ*NR_CPUS/10)
3536 interval = HZ*NR_CPUS/10;
3539 if (sd->flags & SD_SERIALIZE) {
3540 if (!spin_trylock(&balancing))
3541 goto out;
3544 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3545 if (load_balance(cpu, rq, sd, idle, &balance)) {
3547 * We've pulled tasks over so either we're no
3548 * longer idle, or one of our SMT siblings is
3549 * not idle.
3551 idle = CPU_NOT_IDLE;
3553 sd->last_balance = jiffies;
3555 if (sd->flags & SD_SERIALIZE)
3556 spin_unlock(&balancing);
3557 out:
3558 if (time_after(next_balance, sd->last_balance + interval)) {
3559 next_balance = sd->last_balance + interval;
3560 update_next_balance = 1;
3564 * Stop the load balance at this level. There is another
3565 * CPU in our sched group which is doing load balancing more
3566 * actively.
3568 if (!balance)
3569 break;
3573 * next_balance will be updated only when there is a need.
3574 * When the cpu is attached to null domain for ex, it will not be
3575 * updated.
3577 if (likely(update_next_balance))
3578 rq->next_balance = next_balance;
3582 * run_rebalance_domains is triggered when needed from the scheduler tick.
3583 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3584 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3586 static void run_rebalance_domains(struct softirq_action *h)
3588 int this_cpu = smp_processor_id();
3589 struct rq *this_rq = cpu_rq(this_cpu);
3590 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3591 CPU_IDLE : CPU_NOT_IDLE;
3593 rebalance_domains(this_cpu, idle);
3595 #ifdef CONFIG_NO_HZ
3597 * If this cpu is the owner for idle load balancing, then do the
3598 * balancing on behalf of the other idle cpus whose ticks are
3599 * stopped.
3601 if (this_rq->idle_at_tick &&
3602 atomic_read(&nohz.load_balancer) == this_cpu) {
3603 cpumask_t cpus = nohz.cpu_mask;
3604 struct rq *rq;
3605 int balance_cpu;
3607 cpu_clear(this_cpu, cpus);
3608 for_each_cpu_mask(balance_cpu, cpus) {
3610 * If this cpu gets work to do, stop the load balancing
3611 * work being done for other cpus. Next load
3612 * balancing owner will pick it up.
3614 if (need_resched())
3615 break;
3617 rebalance_domains(balance_cpu, CPU_IDLE);
3619 rq = cpu_rq(balance_cpu);
3620 if (time_after(this_rq->next_balance, rq->next_balance))
3621 this_rq->next_balance = rq->next_balance;
3624 #endif
3628 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3630 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3631 * idle load balancing owner or decide to stop the periodic load balancing,
3632 * if the whole system is idle.
3634 static inline void trigger_load_balance(struct rq *rq, int cpu)
3636 #ifdef CONFIG_NO_HZ
3638 * If we were in the nohz mode recently and busy at the current
3639 * scheduler tick, then check if we need to nominate new idle
3640 * load balancer.
3642 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3643 rq->in_nohz_recently = 0;
3645 if (atomic_read(&nohz.load_balancer) == cpu) {
3646 cpu_clear(cpu, nohz.cpu_mask);
3647 atomic_set(&nohz.load_balancer, -1);
3650 if (atomic_read(&nohz.load_balancer) == -1) {
3652 * simple selection for now: Nominate the
3653 * first cpu in the nohz list to be the next
3654 * ilb owner.
3656 * TBD: Traverse the sched domains and nominate
3657 * the nearest cpu in the nohz.cpu_mask.
3659 int ilb = first_cpu(nohz.cpu_mask);
3661 if (ilb != NR_CPUS)
3662 resched_cpu(ilb);
3667 * If this cpu is idle and doing idle load balancing for all the
3668 * cpus with ticks stopped, is it time for that to stop?
3670 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3671 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3672 resched_cpu(cpu);
3673 return;
3677 * If this cpu is idle and the idle load balancing is done by
3678 * someone else, then no need raise the SCHED_SOFTIRQ
3680 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3681 cpu_isset(cpu, nohz.cpu_mask))
3682 return;
3683 #endif
3684 if (time_after_eq(jiffies, rq->next_balance))
3685 raise_softirq(SCHED_SOFTIRQ);
3688 #else /* CONFIG_SMP */
3691 * on UP we do not need to balance between CPUs:
3693 static inline void idle_balance(int cpu, struct rq *rq)
3697 #endif
3699 DEFINE_PER_CPU(struct kernel_stat, kstat);
3701 EXPORT_PER_CPU_SYMBOL(kstat);
3704 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3705 * that have not yet been banked in case the task is currently running.
3707 unsigned long long task_sched_runtime(struct task_struct *p)
3709 unsigned long flags;
3710 u64 ns, delta_exec;
3711 struct rq *rq;
3713 rq = task_rq_lock(p, &flags);
3714 ns = p->se.sum_exec_runtime;
3715 if (task_current(rq, p)) {
3716 update_rq_clock(rq);
3717 delta_exec = rq->clock - p->se.exec_start;
3718 if ((s64)delta_exec > 0)
3719 ns += delta_exec;
3721 task_rq_unlock(rq, &flags);
3723 return ns;
3727 * Account user cpu time to a process.
3728 * @p: the process that the cpu time gets accounted to
3729 * @cputime: the cpu time spent in user space since the last update
3731 void account_user_time(struct task_struct *p, cputime_t cputime)
3733 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3734 cputime64_t tmp;
3736 p->utime = cputime_add(p->utime, cputime);
3738 /* Add user time to cpustat. */
3739 tmp = cputime_to_cputime64(cputime);
3740 if (TASK_NICE(p) > 0)
3741 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3742 else
3743 cpustat->user = cputime64_add(cpustat->user, tmp);
3747 * Account guest cpu time to a process.
3748 * @p: the process that the cpu time gets accounted to
3749 * @cputime: the cpu time spent in virtual machine since the last update
3751 static void account_guest_time(struct task_struct *p, cputime_t cputime)
3753 cputime64_t tmp;
3754 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3756 tmp = cputime_to_cputime64(cputime);
3758 p->utime = cputime_add(p->utime, cputime);
3759 p->gtime = cputime_add(p->gtime, cputime);
3761 cpustat->user = cputime64_add(cpustat->user, tmp);
3762 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3766 * Account scaled user cpu time to a process.
3767 * @p: the process that the cpu time gets accounted to
3768 * @cputime: the cpu time spent in user space since the last update
3770 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3772 p->utimescaled = cputime_add(p->utimescaled, cputime);
3776 * Account system cpu time to a process.
3777 * @p: the process that the cpu time gets accounted to
3778 * @hardirq_offset: the offset to subtract from hardirq_count()
3779 * @cputime: the cpu time spent in kernel space since the last update
3781 void account_system_time(struct task_struct *p, int hardirq_offset,
3782 cputime_t cputime)
3784 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3785 struct rq *rq = this_rq();
3786 cputime64_t tmp;
3788 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3789 return account_guest_time(p, cputime);
3791 p->stime = cputime_add(p->stime, cputime);
3793 /* Add system time to cpustat. */
3794 tmp = cputime_to_cputime64(cputime);
3795 if (hardirq_count() - hardirq_offset)
3796 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3797 else if (softirq_count())
3798 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3799 else if (p != rq->idle)
3800 cpustat->system = cputime64_add(cpustat->system, tmp);
3801 else if (atomic_read(&rq->nr_iowait) > 0)
3802 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3803 else
3804 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3805 /* Account for system time used */
3806 acct_update_integrals(p);
3810 * Account scaled system cpu time to a process.
3811 * @p: the process that the cpu time gets accounted to
3812 * @hardirq_offset: the offset to subtract from hardirq_count()
3813 * @cputime: the cpu time spent in kernel space since the last update
3815 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3817 p->stimescaled = cputime_add(p->stimescaled, cputime);
3821 * Account for involuntary wait time.
3822 * @p: the process from which the cpu time has been stolen
3823 * @steal: the cpu time spent in involuntary wait
3825 void account_steal_time(struct task_struct *p, cputime_t steal)
3827 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3828 cputime64_t tmp = cputime_to_cputime64(steal);
3829 struct rq *rq = this_rq();
3831 if (p == rq->idle) {
3832 p->stime = cputime_add(p->stime, steal);
3833 if (atomic_read(&rq->nr_iowait) > 0)
3834 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3835 else
3836 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3837 } else
3838 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3842 * This function gets called by the timer code, with HZ frequency.
3843 * We call it with interrupts disabled.
3845 * It also gets called by the fork code, when changing the parent's
3846 * timeslices.
3848 void scheduler_tick(void)
3850 int cpu = smp_processor_id();
3851 struct rq *rq = cpu_rq(cpu);
3852 struct task_struct *curr = rq->curr;
3853 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3855 spin_lock(&rq->lock);
3856 __update_rq_clock(rq);
3858 * Let rq->clock advance by at least TICK_NSEC:
3860 if (unlikely(rq->clock < next_tick)) {
3861 rq->clock = next_tick;
3862 rq->clock_underflows++;
3864 rq->tick_timestamp = rq->clock;
3865 update_cpu_load(rq);
3866 curr->sched_class->task_tick(rq, curr, 0);
3867 update_sched_rt_period(rq);
3868 spin_unlock(&rq->lock);
3870 #ifdef CONFIG_SMP
3871 rq->idle_at_tick = idle_cpu(cpu);
3872 trigger_load_balance(rq, cpu);
3873 #endif
3876 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3878 <<<<<<< HEAD:kernel/sched.c
3879 void add_preempt_count(int val)
3880 =======
3881 void __kprobes add_preempt_count(int val)
3882 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
3885 * Underflow?
3887 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3888 return;
3889 preempt_count() += val;
3891 * Spinlock count overflowing soon?
3893 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3894 PREEMPT_MASK - 10);
3896 EXPORT_SYMBOL(add_preempt_count);
3898 <<<<<<< HEAD:kernel/sched.c
3899 void sub_preempt_count(int val)
3900 =======
3901 void __kprobes sub_preempt_count(int val)
3902 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
3905 * Underflow?
3907 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3908 return;
3910 * Is the spinlock portion underflowing?
3912 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3913 !(preempt_count() & PREEMPT_MASK)))
3914 return;
3916 preempt_count() -= val;
3918 EXPORT_SYMBOL(sub_preempt_count);
3920 #endif
3923 * Print scheduling while atomic bug:
3925 static noinline void __schedule_bug(struct task_struct *prev)
3927 struct pt_regs *regs = get_irq_regs();
3929 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3930 prev->comm, prev->pid, preempt_count());
3932 debug_show_held_locks(prev);
3933 if (irqs_disabled())
3934 print_irqtrace_events(prev);
3936 if (regs)
3937 show_regs(regs);
3938 else
3939 dump_stack();
3943 * Various schedule()-time debugging checks and statistics:
3945 static inline void schedule_debug(struct task_struct *prev)
3948 * Test if we are atomic. Since do_exit() needs to call into
3949 * schedule() atomically, we ignore that path for now.
3950 * Otherwise, whine if we are scheduling when we should not be.
3952 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3953 __schedule_bug(prev);
3955 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3957 schedstat_inc(this_rq(), sched_count);
3958 #ifdef CONFIG_SCHEDSTATS
3959 if (unlikely(prev->lock_depth >= 0)) {
3960 schedstat_inc(this_rq(), bkl_count);
3961 schedstat_inc(prev, sched_info.bkl_count);
3963 #endif
3967 * Pick up the highest-prio task:
3969 static inline struct task_struct *
3970 pick_next_task(struct rq *rq, struct task_struct *prev)
3972 const struct sched_class *class;
3973 struct task_struct *p;
3976 * Optimization: we know that if all tasks are in
3977 * the fair class we can call that function directly:
3979 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3980 p = fair_sched_class.pick_next_task(rq);
3981 if (likely(p))
3982 return p;
3985 class = sched_class_highest;
3986 for ( ; ; ) {
3987 p = class->pick_next_task(rq);
3988 if (p)
3989 return p;
3991 * Will never be NULL as the idle class always
3992 * returns a non-NULL p:
3994 class = class->next;
3999 * schedule() is the main scheduler function.
4001 asmlinkage void __sched schedule(void)
4003 struct task_struct *prev, *next;
4004 <<<<<<< HEAD:kernel/sched.c
4005 long *switch_count;
4006 =======
4007 unsigned long *switch_count;
4008 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4009 struct rq *rq;
4010 int cpu;
4012 need_resched:
4013 preempt_disable();
4014 cpu = smp_processor_id();
4015 rq = cpu_rq(cpu);
4016 rcu_qsctr_inc(cpu);
4017 prev = rq->curr;
4018 switch_count = &prev->nivcsw;
4020 release_kernel_lock(prev);
4021 need_resched_nonpreemptible:
4023 schedule_debug(prev);
4025 hrtick_clear(rq);
4028 * Do the rq-clock update outside the rq lock:
4030 local_irq_disable();
4031 __update_rq_clock(rq);
4032 spin_lock(&rq->lock);
4033 clear_tsk_need_resched(prev);
4035 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4036 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4037 unlikely(signal_pending(prev)))) {
4038 prev->state = TASK_RUNNING;
4039 } else {
4040 deactivate_task(rq, prev, 1);
4042 switch_count = &prev->nvcsw;
4045 #ifdef CONFIG_SMP
4046 if (prev->sched_class->pre_schedule)
4047 prev->sched_class->pre_schedule(rq, prev);
4048 #endif
4050 if (unlikely(!rq->nr_running))
4051 idle_balance(cpu, rq);
4053 prev->sched_class->put_prev_task(rq, prev);
4054 next = pick_next_task(rq, prev);
4056 sched_info_switch(prev, next);
4058 if (likely(prev != next)) {
4059 rq->nr_switches++;
4060 rq->curr = next;
4061 ++*switch_count;
4063 context_switch(rq, prev, next); /* unlocks the rq */
4065 * the context switch might have flipped the stack from under
4066 * us, hence refresh the local variables.
4068 cpu = smp_processor_id();
4069 rq = cpu_rq(cpu);
4070 } else
4071 spin_unlock_irq(&rq->lock);
4073 hrtick_set(rq);
4075 if (unlikely(reacquire_kernel_lock(current) < 0))
4076 goto need_resched_nonpreemptible;
4078 preempt_enable_no_resched();
4079 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4080 goto need_resched;
4082 EXPORT_SYMBOL(schedule);
4084 #ifdef CONFIG_PREEMPT
4086 * this is the entry point to schedule() from in-kernel preemption
4087 * off of preempt_enable. Kernel preemptions off return from interrupt
4088 * occur there and call schedule directly.
4090 asmlinkage void __sched preempt_schedule(void)
4092 struct thread_info *ti = current_thread_info();
4093 struct task_struct *task = current;
4094 int saved_lock_depth;
4097 * If there is a non-zero preempt_count or interrupts are disabled,
4098 * we do not want to preempt the current task. Just return..
4100 if (likely(ti->preempt_count || irqs_disabled()))
4101 return;
4103 do {
4104 add_preempt_count(PREEMPT_ACTIVE);
4107 * We keep the big kernel semaphore locked, but we
4108 * clear ->lock_depth so that schedule() doesnt
4109 * auto-release the semaphore:
4111 saved_lock_depth = task->lock_depth;
4112 task->lock_depth = -1;
4113 schedule();
4114 task->lock_depth = saved_lock_depth;
4115 sub_preempt_count(PREEMPT_ACTIVE);
4118 * Check again in case we missed a preemption opportunity
4119 * between schedule and now.
4121 barrier();
4122 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4124 EXPORT_SYMBOL(preempt_schedule);
4127 * this is the entry point to schedule() from kernel preemption
4128 * off of irq context.
4129 * Note, that this is called and return with irqs disabled. This will
4130 * protect us against recursive calling from irq.
4132 asmlinkage void __sched preempt_schedule_irq(void)
4134 struct thread_info *ti = current_thread_info();
4135 struct task_struct *task = current;
4136 int saved_lock_depth;
4138 /* Catch callers which need to be fixed */
4139 BUG_ON(ti->preempt_count || !irqs_disabled());
4141 do {
4142 add_preempt_count(PREEMPT_ACTIVE);
4145 * We keep the big kernel semaphore locked, but we
4146 * clear ->lock_depth so that schedule() doesnt
4147 * auto-release the semaphore:
4149 saved_lock_depth = task->lock_depth;
4150 task->lock_depth = -1;
4151 local_irq_enable();
4152 schedule();
4153 local_irq_disable();
4154 task->lock_depth = saved_lock_depth;
4155 sub_preempt_count(PREEMPT_ACTIVE);
4158 * Check again in case we missed a preemption opportunity
4159 * between schedule and now.
4161 barrier();
4162 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4165 #endif /* CONFIG_PREEMPT */
4167 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4168 void *key)
4170 return try_to_wake_up(curr->private, mode, sync);
4172 EXPORT_SYMBOL(default_wake_function);
4175 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4176 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4177 * number) then we wake all the non-exclusive tasks and one exclusive task.
4179 * There are circumstances in which we can try to wake a task which has already
4180 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4181 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4183 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4184 int nr_exclusive, int sync, void *key)
4186 wait_queue_t *curr, *next;
4188 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4189 unsigned flags = curr->flags;
4191 if (curr->func(curr, mode, sync, key) &&
4192 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4193 break;
4198 * __wake_up - wake up threads blocked on a waitqueue.
4199 * @q: the waitqueue
4200 * @mode: which threads
4201 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4202 * @key: is directly passed to the wakeup function
4204 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4205 int nr_exclusive, void *key)
4207 unsigned long flags;
4209 spin_lock_irqsave(&q->lock, flags);
4210 __wake_up_common(q, mode, nr_exclusive, 0, key);
4211 spin_unlock_irqrestore(&q->lock, flags);
4213 EXPORT_SYMBOL(__wake_up);
4216 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4218 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4220 __wake_up_common(q, mode, 1, 0, NULL);
4224 * __wake_up_sync - wake up threads blocked on a waitqueue.
4225 * @q: the waitqueue
4226 * @mode: which threads
4227 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4229 * The sync wakeup differs that the waker knows that it will schedule
4230 * away soon, so while the target thread will be woken up, it will not
4231 * be migrated to another CPU - ie. the two threads are 'synchronized'
4232 * with each other. This can prevent needless bouncing between CPUs.
4234 * On UP it can prevent extra preemption.
4236 void
4237 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4239 unsigned long flags;
4240 int sync = 1;
4242 if (unlikely(!q))
4243 return;
4245 if (unlikely(!nr_exclusive))
4246 sync = 0;
4248 spin_lock_irqsave(&q->lock, flags);
4249 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4250 spin_unlock_irqrestore(&q->lock, flags);
4252 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4254 void complete(struct completion *x)
4256 unsigned long flags;
4258 spin_lock_irqsave(&x->wait.lock, flags);
4259 x->done++;
4260 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4261 spin_unlock_irqrestore(&x->wait.lock, flags);
4263 EXPORT_SYMBOL(complete);
4265 void complete_all(struct completion *x)
4267 unsigned long flags;
4269 spin_lock_irqsave(&x->wait.lock, flags);
4270 x->done += UINT_MAX/2;
4271 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4272 spin_unlock_irqrestore(&x->wait.lock, flags);
4274 EXPORT_SYMBOL(complete_all);
4276 static inline long __sched
4277 do_wait_for_common(struct completion *x, long timeout, int state)
4279 if (!x->done) {
4280 DECLARE_WAITQUEUE(wait, current);
4282 wait.flags |= WQ_FLAG_EXCLUSIVE;
4283 __add_wait_queue_tail(&x->wait, &wait);
4284 do {
4285 if ((state == TASK_INTERRUPTIBLE &&
4286 signal_pending(current)) ||
4287 (state == TASK_KILLABLE &&
4288 fatal_signal_pending(current))) {
4289 __remove_wait_queue(&x->wait, &wait);
4290 return -ERESTARTSYS;
4292 __set_current_state(state);
4293 spin_unlock_irq(&x->wait.lock);
4294 timeout = schedule_timeout(timeout);
4295 spin_lock_irq(&x->wait.lock);
4296 if (!timeout) {
4297 __remove_wait_queue(&x->wait, &wait);
4298 return timeout;
4300 } while (!x->done);
4301 __remove_wait_queue(&x->wait, &wait);
4303 x->done--;
4304 return timeout;
4307 static long __sched
4308 wait_for_common(struct completion *x, long timeout, int state)
4310 might_sleep();
4312 spin_lock_irq(&x->wait.lock);
4313 timeout = do_wait_for_common(x, timeout, state);
4314 spin_unlock_irq(&x->wait.lock);
4315 return timeout;
4318 void __sched wait_for_completion(struct completion *x)
4320 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4322 EXPORT_SYMBOL(wait_for_completion);
4324 unsigned long __sched
4325 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4327 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4329 EXPORT_SYMBOL(wait_for_completion_timeout);
4331 int __sched wait_for_completion_interruptible(struct completion *x)
4333 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4334 if (t == -ERESTARTSYS)
4335 return t;
4336 return 0;
4338 EXPORT_SYMBOL(wait_for_completion_interruptible);
4340 unsigned long __sched
4341 wait_for_completion_interruptible_timeout(struct completion *x,
4342 unsigned long timeout)
4344 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4346 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4348 int __sched wait_for_completion_killable(struct completion *x)
4350 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4351 if (t == -ERESTARTSYS)
4352 return t;
4353 return 0;
4355 EXPORT_SYMBOL(wait_for_completion_killable);
4357 static long __sched
4358 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4360 unsigned long flags;
4361 wait_queue_t wait;
4363 init_waitqueue_entry(&wait, current);
4365 __set_current_state(state);
4367 spin_lock_irqsave(&q->lock, flags);
4368 __add_wait_queue(q, &wait);
4369 spin_unlock(&q->lock);
4370 timeout = schedule_timeout(timeout);
4371 spin_lock_irq(&q->lock);
4372 __remove_wait_queue(q, &wait);
4373 spin_unlock_irqrestore(&q->lock, flags);
4375 return timeout;
4378 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4380 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4382 EXPORT_SYMBOL(interruptible_sleep_on);
4384 long __sched
4385 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4387 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4389 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4391 void __sched sleep_on(wait_queue_head_t *q)
4393 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4395 EXPORT_SYMBOL(sleep_on);
4397 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4399 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4401 EXPORT_SYMBOL(sleep_on_timeout);
4403 #ifdef CONFIG_RT_MUTEXES
4406 * rt_mutex_setprio - set the current priority of a task
4407 * @p: task
4408 * @prio: prio value (kernel-internal form)
4410 * This function changes the 'effective' priority of a task. It does
4411 * not touch ->normal_prio like __setscheduler().
4413 * Used by the rt_mutex code to implement priority inheritance logic.
4415 void rt_mutex_setprio(struct task_struct *p, int prio)
4417 unsigned long flags;
4418 int oldprio, on_rq, running;
4419 struct rq *rq;
4420 const struct sched_class *prev_class = p->sched_class;
4422 BUG_ON(prio < 0 || prio > MAX_PRIO);
4424 rq = task_rq_lock(p, &flags);
4425 update_rq_clock(rq);
4427 oldprio = p->prio;
4428 on_rq = p->se.on_rq;
4429 running = task_current(rq, p);
4430 <<<<<<< HEAD:kernel/sched.c
4431 if (on_rq) {
4432 =======
4433 if (on_rq)
4434 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4435 dequeue_task(rq, p, 0);
4436 <<<<<<< HEAD:kernel/sched.c
4437 if (running)
4438 p->sched_class->put_prev_task(rq, p);
4440 =======
4441 if (running)
4442 p->sched_class->put_prev_task(rq, p);
4443 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4445 if (rt_prio(prio))
4446 p->sched_class = &rt_sched_class;
4447 else
4448 p->sched_class = &fair_sched_class;
4450 p->prio = prio;
4452 <<<<<<< HEAD:kernel/sched.c
4453 =======
4454 if (running)
4455 p->sched_class->set_curr_task(rq);
4456 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4457 if (on_rq) {
4458 <<<<<<< HEAD:kernel/sched.c
4459 if (running)
4460 p->sched_class->set_curr_task(rq);
4462 =======
4463 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4464 enqueue_task(rq, p, 0);
4466 check_class_changed(rq, p, prev_class, oldprio, running);
4468 task_rq_unlock(rq, &flags);
4471 #endif
4473 void set_user_nice(struct task_struct *p, long nice)
4475 int old_prio, delta, on_rq;
4476 unsigned long flags;
4477 struct rq *rq;
4479 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4480 return;
4482 * We have to be careful, if called from sys_setpriority(),
4483 * the task might be in the middle of scheduling on another CPU.
4485 rq = task_rq_lock(p, &flags);
4486 update_rq_clock(rq);
4488 * The RT priorities are set via sched_setscheduler(), but we still
4489 * allow the 'normal' nice value to be set - but as expected
4490 * it wont have any effect on scheduling until the task is
4491 * SCHED_FIFO/SCHED_RR:
4493 if (task_has_rt_policy(p)) {
4494 p->static_prio = NICE_TO_PRIO(nice);
4495 goto out_unlock;
4497 on_rq = p->se.on_rq;
4498 <<<<<<< HEAD:kernel/sched.c
4499 if (on_rq)
4500 =======
4501 if (on_rq) {
4502 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4503 dequeue_task(rq, p, 0);
4504 <<<<<<< HEAD:kernel/sched.c
4505 =======
4506 dec_load(rq, p);
4508 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4510 p->static_prio = NICE_TO_PRIO(nice);
4511 set_load_weight(p);
4512 old_prio = p->prio;
4513 p->prio = effective_prio(p);
4514 delta = p->prio - old_prio;
4516 if (on_rq) {
4517 enqueue_task(rq, p, 0);
4518 <<<<<<< HEAD:kernel/sched.c
4519 =======
4520 inc_load(rq, p);
4521 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4523 * If the task increased its priority or is running and
4524 * lowered its priority, then reschedule its CPU:
4526 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4527 resched_task(rq->curr);
4529 out_unlock:
4530 task_rq_unlock(rq, &flags);
4532 EXPORT_SYMBOL(set_user_nice);
4535 * can_nice - check if a task can reduce its nice value
4536 * @p: task
4537 * @nice: nice value
4539 int can_nice(const struct task_struct *p, const int nice)
4541 /* convert nice value [19,-20] to rlimit style value [1,40] */
4542 int nice_rlim = 20 - nice;
4544 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4545 capable(CAP_SYS_NICE));
4548 #ifdef __ARCH_WANT_SYS_NICE
4551 * sys_nice - change the priority of the current process.
4552 * @increment: priority increment
4554 * sys_setpriority is a more generic, but much slower function that
4555 * does similar things.
4557 asmlinkage long sys_nice(int increment)
4559 long nice, retval;
4562 * Setpriority might change our priority at the same moment.
4563 * We don't have to worry. Conceptually one call occurs first
4564 * and we have a single winner.
4566 if (increment < -40)
4567 increment = -40;
4568 if (increment > 40)
4569 increment = 40;
4571 nice = PRIO_TO_NICE(current->static_prio) + increment;
4572 if (nice < -20)
4573 nice = -20;
4574 if (nice > 19)
4575 nice = 19;
4577 if (increment < 0 && !can_nice(current, nice))
4578 return -EPERM;
4580 retval = security_task_setnice(current, nice);
4581 if (retval)
4582 return retval;
4584 set_user_nice(current, nice);
4585 return 0;
4588 #endif
4591 * task_prio - return the priority value of a given task.
4592 * @p: the task in question.
4594 * This is the priority value as seen by users in /proc.
4595 * RT tasks are offset by -200. Normal tasks are centered
4596 * around 0, value goes from -16 to +15.
4598 int task_prio(const struct task_struct *p)
4600 return p->prio - MAX_RT_PRIO;
4604 * task_nice - return the nice value of a given task.
4605 * @p: the task in question.
4607 int task_nice(const struct task_struct *p)
4609 return TASK_NICE(p);
4611 <<<<<<< HEAD:kernel/sched.c
4612 EXPORT_SYMBOL_GPL(task_nice);
4613 =======
4614 EXPORT_SYMBOL(task_nice);
4615 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4618 * idle_cpu - is a given cpu idle currently?
4619 * @cpu: the processor in question.
4621 int idle_cpu(int cpu)
4623 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4627 * idle_task - return the idle task for a given cpu.
4628 * @cpu: the processor in question.
4630 struct task_struct *idle_task(int cpu)
4632 return cpu_rq(cpu)->idle;
4636 * find_process_by_pid - find a process with a matching PID value.
4637 * @pid: the pid in question.
4639 static struct task_struct *find_process_by_pid(pid_t pid)
4641 return pid ? find_task_by_vpid(pid) : current;
4644 /* Actually do priority change: must hold rq lock. */
4645 static void
4646 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4648 BUG_ON(p->se.on_rq);
4650 p->policy = policy;
4651 switch (p->policy) {
4652 case SCHED_NORMAL:
4653 case SCHED_BATCH:
4654 case SCHED_IDLE:
4655 p->sched_class = &fair_sched_class;
4656 break;
4657 case SCHED_FIFO:
4658 case SCHED_RR:
4659 p->sched_class = &rt_sched_class;
4660 break;
4663 p->rt_priority = prio;
4664 p->normal_prio = normal_prio(p);
4665 /* we are holding p->pi_lock already */
4666 p->prio = rt_mutex_getprio(p);
4667 set_load_weight(p);
4671 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4672 * @p: the task in question.
4673 * @policy: new policy.
4674 * @param: structure containing the new RT priority.
4676 * NOTE that the task may be already dead.
4678 int sched_setscheduler(struct task_struct *p, int policy,
4679 struct sched_param *param)
4681 int retval, oldprio, oldpolicy = -1, on_rq, running;
4682 unsigned long flags;
4683 const struct sched_class *prev_class = p->sched_class;
4684 struct rq *rq;
4686 /* may grab non-irq protected spin_locks */
4687 BUG_ON(in_interrupt());
4688 recheck:
4689 /* double check policy once rq lock held */
4690 if (policy < 0)
4691 policy = oldpolicy = p->policy;
4692 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4693 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4694 policy != SCHED_IDLE)
4695 return -EINVAL;
4697 * Valid priorities for SCHED_FIFO and SCHED_RR are
4698 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4699 * SCHED_BATCH and SCHED_IDLE is 0.
4701 if (param->sched_priority < 0 ||
4702 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4703 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4704 return -EINVAL;
4705 if (rt_policy(policy) != (param->sched_priority != 0))
4706 return -EINVAL;
4709 * Allow unprivileged RT tasks to decrease priority:
4711 if (!capable(CAP_SYS_NICE)) {
4712 if (rt_policy(policy)) {
4713 unsigned long rlim_rtprio;
4715 if (!lock_task_sighand(p, &flags))
4716 return -ESRCH;
4717 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4718 unlock_task_sighand(p, &flags);
4720 /* can't set/change the rt policy */
4721 if (policy != p->policy && !rlim_rtprio)
4722 return -EPERM;
4724 /* can't increase priority */
4725 if (param->sched_priority > p->rt_priority &&
4726 param->sched_priority > rlim_rtprio)
4727 return -EPERM;
4730 * Like positive nice levels, dont allow tasks to
4731 * move out of SCHED_IDLE either:
4733 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4734 return -EPERM;
4736 /* can't change other user's priorities */
4737 if ((current->euid != p->euid) &&
4738 (current->euid != p->uid))
4739 return -EPERM;
4742 #ifdef CONFIG_RT_GROUP_SCHED
4744 * Do not allow realtime tasks into groups that have no runtime
4745 * assigned.
4747 if (rt_policy(policy) && task_group(p)->rt_runtime == 0)
4748 return -EPERM;
4749 #endif
4751 retval = security_task_setscheduler(p, policy, param);
4752 if (retval)
4753 return retval;
4755 * make sure no PI-waiters arrive (or leave) while we are
4756 * changing the priority of the task:
4758 spin_lock_irqsave(&p->pi_lock, flags);
4760 * To be able to change p->policy safely, the apropriate
4761 * runqueue lock must be held.
4763 rq = __task_rq_lock(p);
4764 /* recheck policy now with rq lock held */
4765 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4766 policy = oldpolicy = -1;
4767 __task_rq_unlock(rq);
4768 spin_unlock_irqrestore(&p->pi_lock, flags);
4769 goto recheck;
4771 update_rq_clock(rq);
4772 on_rq = p->se.on_rq;
4773 running = task_current(rq, p);
4774 <<<<<<< HEAD:kernel/sched.c
4775 if (on_rq) {
4776 =======
4777 if (on_rq)
4778 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4779 deactivate_task(rq, p, 0);
4780 <<<<<<< HEAD:kernel/sched.c
4781 if (running)
4782 p->sched_class->put_prev_task(rq, p);
4784 =======
4785 if (running)
4786 p->sched_class->put_prev_task(rq, p);
4787 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4789 oldprio = p->prio;
4790 __setscheduler(rq, p, policy, param->sched_priority);
4792 <<<<<<< HEAD:kernel/sched.c
4793 =======
4794 if (running)
4795 p->sched_class->set_curr_task(rq);
4796 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4797 if (on_rq) {
4798 <<<<<<< HEAD:kernel/sched.c
4799 if (running)
4800 p->sched_class->set_curr_task(rq);
4802 =======
4803 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
4804 activate_task(rq, p, 0);
4806 check_class_changed(rq, p, prev_class, oldprio, running);
4808 __task_rq_unlock(rq);
4809 spin_unlock_irqrestore(&p->pi_lock, flags);
4811 rt_mutex_adjust_pi(p);
4813 return 0;
4815 EXPORT_SYMBOL_GPL(sched_setscheduler);
4817 static int
4818 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4820 struct sched_param lparam;
4821 struct task_struct *p;
4822 int retval;
4824 if (!param || pid < 0)
4825 return -EINVAL;
4826 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4827 return -EFAULT;
4829 rcu_read_lock();
4830 retval = -ESRCH;
4831 p = find_process_by_pid(pid);
4832 if (p != NULL)
4833 retval = sched_setscheduler(p, policy, &lparam);
4834 rcu_read_unlock();
4836 return retval;
4840 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4841 * @pid: the pid in question.
4842 * @policy: new policy.
4843 * @param: structure containing the new RT priority.
4845 asmlinkage long
4846 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4848 /* negative values for policy are not valid */
4849 if (policy < 0)
4850 return -EINVAL;
4852 return do_sched_setscheduler(pid, policy, param);
4856 * sys_sched_setparam - set/change the RT priority of a thread
4857 * @pid: the pid in question.
4858 * @param: structure containing the new RT priority.
4860 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4862 return do_sched_setscheduler(pid, -1, param);
4866 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4867 * @pid: the pid in question.
4869 asmlinkage long sys_sched_getscheduler(pid_t pid)
4871 struct task_struct *p;
4872 int retval;
4874 if (pid < 0)
4875 return -EINVAL;
4877 retval = -ESRCH;
4878 read_lock(&tasklist_lock);
4879 p = find_process_by_pid(pid);
4880 if (p) {
4881 retval = security_task_getscheduler(p);
4882 if (!retval)
4883 retval = p->policy;
4885 read_unlock(&tasklist_lock);
4886 return retval;
4890 * sys_sched_getscheduler - get the RT priority of a thread
4891 * @pid: the pid in question.
4892 * @param: structure containing the RT priority.
4894 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4896 struct sched_param lp;
4897 struct task_struct *p;
4898 int retval;
4900 if (!param || pid < 0)
4901 return -EINVAL;
4903 read_lock(&tasklist_lock);
4904 p = find_process_by_pid(pid);
4905 retval = -ESRCH;
4906 if (!p)
4907 goto out_unlock;
4909 retval = security_task_getscheduler(p);
4910 if (retval)
4911 goto out_unlock;
4913 lp.sched_priority = p->rt_priority;
4914 read_unlock(&tasklist_lock);
4917 * This one might sleep, we cannot do it with a spinlock held ...
4919 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4921 return retval;
4923 out_unlock:
4924 read_unlock(&tasklist_lock);
4925 return retval;
4928 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4930 cpumask_t cpus_allowed;
4931 struct task_struct *p;
4932 int retval;
4934 get_online_cpus();
4935 read_lock(&tasklist_lock);
4937 p = find_process_by_pid(pid);
4938 if (!p) {
4939 read_unlock(&tasklist_lock);
4940 put_online_cpus();
4941 return -ESRCH;
4945 * It is not safe to call set_cpus_allowed with the
4946 * tasklist_lock held. We will bump the task_struct's
4947 * usage count and then drop tasklist_lock.
4949 get_task_struct(p);
4950 read_unlock(&tasklist_lock);
4952 retval = -EPERM;
4953 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4954 !capable(CAP_SYS_NICE))
4955 goto out_unlock;
4957 retval = security_task_setscheduler(p, 0, NULL);
4958 if (retval)
4959 goto out_unlock;
4961 cpus_allowed = cpuset_cpus_allowed(p);
4962 cpus_and(new_mask, new_mask, cpus_allowed);
4963 again:
4964 retval = set_cpus_allowed(p, new_mask);
4966 if (!retval) {
4967 cpus_allowed = cpuset_cpus_allowed(p);
4968 if (!cpus_subset(new_mask, cpus_allowed)) {
4970 * We must have raced with a concurrent cpuset
4971 * update. Just reset the cpus_allowed to the
4972 * cpuset's cpus_allowed
4974 new_mask = cpus_allowed;
4975 goto again;
4978 out_unlock:
4979 put_task_struct(p);
4980 put_online_cpus();
4981 return retval;
4984 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4985 cpumask_t *new_mask)
4987 if (len < sizeof(cpumask_t)) {
4988 memset(new_mask, 0, sizeof(cpumask_t));
4989 } else if (len > sizeof(cpumask_t)) {
4990 len = sizeof(cpumask_t);
4992 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4996 * sys_sched_setaffinity - set the cpu affinity of a process
4997 * @pid: pid of the process
4998 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4999 * @user_mask_ptr: user-space pointer to the new cpu mask
5001 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5002 unsigned long __user *user_mask_ptr)
5004 cpumask_t new_mask;
5005 int retval;
5007 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5008 if (retval)
5009 return retval;
5011 return sched_setaffinity(pid, new_mask);
5015 * Represents all cpu's present in the system
5016 * In systems capable of hotplug, this map could dynamically grow
5017 * as new cpu's are detected in the system via any platform specific
5018 * method, such as ACPI for e.g.
5021 cpumask_t cpu_present_map __read_mostly;
5022 EXPORT_SYMBOL(cpu_present_map);
5024 #ifndef CONFIG_SMP
5025 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5026 EXPORT_SYMBOL(cpu_online_map);
5028 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5029 EXPORT_SYMBOL(cpu_possible_map);
5030 #endif
5032 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5034 struct task_struct *p;
5035 int retval;
5037 get_online_cpus();
5038 read_lock(&tasklist_lock);
5040 retval = -ESRCH;
5041 p = find_process_by_pid(pid);
5042 if (!p)
5043 goto out_unlock;
5045 retval = security_task_getscheduler(p);
5046 if (retval)
5047 goto out_unlock;
5049 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5051 out_unlock:
5052 read_unlock(&tasklist_lock);
5053 put_online_cpus();
5055 return retval;
5059 * sys_sched_getaffinity - get the cpu affinity of a process
5060 * @pid: pid of the process
5061 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5062 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5064 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5065 unsigned long __user *user_mask_ptr)
5067 int ret;
5068 cpumask_t mask;
5070 if (len < sizeof(cpumask_t))
5071 return -EINVAL;
5073 ret = sched_getaffinity(pid, &mask);
5074 if (ret < 0)
5075 return ret;
5077 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5078 return -EFAULT;
5080 return sizeof(cpumask_t);
5084 * sys_sched_yield - yield the current processor to other threads.
5086 * This function yields the current CPU to other tasks. If there are no
5087 * other threads running on this CPU then this function will return.
5089 asmlinkage long sys_sched_yield(void)
5091 struct rq *rq = this_rq_lock();
5093 schedstat_inc(rq, yld_count);
5094 current->sched_class->yield_task(rq);
5097 * Since we are going to call schedule() anyway, there's
5098 * no need to preempt or enable interrupts:
5100 __release(rq->lock);
5101 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5102 _raw_spin_unlock(&rq->lock);
5103 preempt_enable_no_resched();
5105 schedule();
5107 return 0;
5110 static void __cond_resched(void)
5112 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5113 __might_sleep(__FILE__, __LINE__);
5114 #endif
5116 * The BKS might be reacquired before we have dropped
5117 * PREEMPT_ACTIVE, which could trigger a second
5118 * cond_resched() call.
5120 do {
5121 add_preempt_count(PREEMPT_ACTIVE);
5122 schedule();
5123 sub_preempt_count(PREEMPT_ACTIVE);
5124 } while (need_resched());
5127 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5128 int __sched _cond_resched(void)
5130 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5131 system_state == SYSTEM_RUNNING) {
5132 __cond_resched();
5133 return 1;
5135 return 0;
5137 EXPORT_SYMBOL(_cond_resched);
5138 #endif
5141 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5142 * call schedule, and on return reacquire the lock.
5144 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5145 * operations here to prevent schedule() from being called twice (once via
5146 * spin_unlock(), once by hand).
5148 int cond_resched_lock(spinlock_t *lock)
5150 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5151 int ret = 0;
5153 if (spin_needbreak(lock) || resched) {
5154 spin_unlock(lock);
5155 if (resched && need_resched())
5156 __cond_resched();
5157 else
5158 cpu_relax();
5159 ret = 1;
5160 spin_lock(lock);
5162 return ret;
5164 EXPORT_SYMBOL(cond_resched_lock);
5166 int __sched cond_resched_softirq(void)
5168 BUG_ON(!in_softirq());
5170 if (need_resched() && system_state == SYSTEM_RUNNING) {
5171 local_bh_enable();
5172 __cond_resched();
5173 local_bh_disable();
5174 return 1;
5176 return 0;
5178 EXPORT_SYMBOL(cond_resched_softirq);
5181 * yield - yield the current processor to other threads.
5183 * This is a shortcut for kernel-space yielding - it marks the
5184 * thread runnable and calls sys_sched_yield().
5186 void __sched yield(void)
5188 set_current_state(TASK_RUNNING);
5189 sys_sched_yield();
5191 EXPORT_SYMBOL(yield);
5194 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5195 * that process accounting knows that this is a task in IO wait state.
5197 * But don't do that if it is a deliberate, throttling IO wait (this task
5198 * has set its backing_dev_info: the queue against which it should throttle)
5200 void __sched io_schedule(void)
5202 struct rq *rq = &__raw_get_cpu_var(runqueues);
5204 delayacct_blkio_start();
5205 atomic_inc(&rq->nr_iowait);
5206 schedule();
5207 atomic_dec(&rq->nr_iowait);
5208 delayacct_blkio_end();
5210 EXPORT_SYMBOL(io_schedule);
5212 long __sched io_schedule_timeout(long timeout)
5214 struct rq *rq = &__raw_get_cpu_var(runqueues);
5215 long ret;
5217 delayacct_blkio_start();
5218 atomic_inc(&rq->nr_iowait);
5219 ret = schedule_timeout(timeout);
5220 atomic_dec(&rq->nr_iowait);
5221 delayacct_blkio_end();
5222 return ret;
5226 * sys_sched_get_priority_max - return maximum RT priority.
5227 * @policy: scheduling class.
5229 * this syscall returns the maximum rt_priority that can be used
5230 * by a given scheduling class.
5232 asmlinkage long sys_sched_get_priority_max(int policy)
5234 int ret = -EINVAL;
5236 switch (policy) {
5237 case SCHED_FIFO:
5238 case SCHED_RR:
5239 ret = MAX_USER_RT_PRIO-1;
5240 break;
5241 case SCHED_NORMAL:
5242 case SCHED_BATCH:
5243 case SCHED_IDLE:
5244 ret = 0;
5245 break;
5247 return ret;
5251 * sys_sched_get_priority_min - return minimum RT priority.
5252 * @policy: scheduling class.
5254 * this syscall returns the minimum rt_priority that can be used
5255 * by a given scheduling class.
5257 asmlinkage long sys_sched_get_priority_min(int policy)
5259 int ret = -EINVAL;
5261 switch (policy) {
5262 case SCHED_FIFO:
5263 case SCHED_RR:
5264 ret = 1;
5265 break;
5266 case SCHED_NORMAL:
5267 case SCHED_BATCH:
5268 case SCHED_IDLE:
5269 ret = 0;
5271 return ret;
5275 * sys_sched_rr_get_interval - return the default timeslice of a process.
5276 * @pid: pid of the process.
5277 * @interval: userspace pointer to the timeslice value.
5279 * this syscall writes the default timeslice value of a given process
5280 * into the user-space timespec buffer. A value of '0' means infinity.
5282 asmlinkage
5283 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5285 struct task_struct *p;
5286 unsigned int time_slice;
5287 int retval;
5288 struct timespec t;
5290 if (pid < 0)
5291 return -EINVAL;
5293 retval = -ESRCH;
5294 read_lock(&tasklist_lock);
5295 p = find_process_by_pid(pid);
5296 if (!p)
5297 goto out_unlock;
5299 retval = security_task_getscheduler(p);
5300 if (retval)
5301 goto out_unlock;
5304 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5305 * tasks that are on an otherwise idle runqueue:
5307 time_slice = 0;
5308 if (p->policy == SCHED_RR) {
5309 time_slice = DEF_TIMESLICE;
5310 <<<<<<< HEAD:kernel/sched.c
5311 } else {
5312 =======
5313 } else if (p->policy != SCHED_FIFO) {
5314 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
5315 struct sched_entity *se = &p->se;
5316 unsigned long flags;
5317 struct rq *rq;
5319 rq = task_rq_lock(p, &flags);
5320 if (rq->cfs.load.weight)
5321 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5322 task_rq_unlock(rq, &flags);
5324 read_unlock(&tasklist_lock);
5325 jiffies_to_timespec(time_slice, &t);
5326 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5327 return retval;
5329 out_unlock:
5330 read_unlock(&tasklist_lock);
5331 return retval;
5334 static const char stat_nam[] = "RSDTtZX";
5336 void sched_show_task(struct task_struct *p)
5338 unsigned long free = 0;
5339 unsigned state;
5341 state = p->state ? __ffs(p->state) + 1 : 0;
5342 printk(KERN_INFO "%-13.13s %c", p->comm,
5343 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5344 #if BITS_PER_LONG == 32
5345 if (state == TASK_RUNNING)
5346 printk(KERN_CONT " running ");
5347 else
5348 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5349 #else
5350 if (state == TASK_RUNNING)
5351 printk(KERN_CONT " running task ");
5352 else
5353 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5354 #endif
5355 #ifdef CONFIG_DEBUG_STACK_USAGE
5357 unsigned long *n = end_of_stack(p);
5358 while (!*n)
5359 n++;
5360 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5362 #endif
5363 printk(KERN_CONT "%5lu %5d %6d\n", free,
5364 task_pid_nr(p), task_pid_nr(p->real_parent));
5366 show_stack(p, NULL);
5369 void show_state_filter(unsigned long state_filter)
5371 struct task_struct *g, *p;
5373 #if BITS_PER_LONG == 32
5374 printk(KERN_INFO
5375 " task PC stack pid father\n");
5376 #else
5377 printk(KERN_INFO
5378 " task PC stack pid father\n");
5379 #endif
5380 read_lock(&tasklist_lock);
5381 do_each_thread(g, p) {
5383 * reset the NMI-timeout, listing all files on a slow
5384 * console might take alot of time:
5386 touch_nmi_watchdog();
5387 if (!state_filter || (p->state & state_filter))
5388 sched_show_task(p);
5389 } while_each_thread(g, p);
5391 touch_all_softlockup_watchdogs();
5393 #ifdef CONFIG_SCHED_DEBUG
5394 sysrq_sched_debug_show();
5395 #endif
5396 read_unlock(&tasklist_lock);
5398 * Only show locks if all tasks are dumped:
5400 if (state_filter == -1)
5401 debug_show_all_locks();
5404 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5406 idle->sched_class = &idle_sched_class;
5410 * init_idle - set up an idle thread for a given CPU
5411 * @idle: task in question
5412 * @cpu: cpu the idle task belongs to
5414 * NOTE: this function does not set the idle thread's NEED_RESCHED
5415 * flag, to make booting more robust.
5417 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5419 struct rq *rq = cpu_rq(cpu);
5420 unsigned long flags;
5422 __sched_fork(idle);
5423 idle->se.exec_start = sched_clock();
5425 idle->prio = idle->normal_prio = MAX_PRIO;
5426 idle->cpus_allowed = cpumask_of_cpu(cpu);
5427 __set_task_cpu(idle, cpu);
5429 spin_lock_irqsave(&rq->lock, flags);
5430 rq->curr = rq->idle = idle;
5431 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5432 idle->oncpu = 1;
5433 #endif
5434 spin_unlock_irqrestore(&rq->lock, flags);
5436 /* Set the preempt count _outside_ the spinlocks! */
5437 task_thread_info(idle)->preempt_count = 0;
5440 * The idle tasks have their own, simple scheduling class:
5442 idle->sched_class = &idle_sched_class;
5446 * In a system that switches off the HZ timer nohz_cpu_mask
5447 * indicates which cpus entered this state. This is used
5448 * in the rcu update to wait only for active cpus. For system
5449 * which do not switch off the HZ timer nohz_cpu_mask should
5450 * always be CPU_MASK_NONE.
5452 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5455 * Increase the granularity value when there are more CPUs,
5456 * because with more CPUs the 'effective latency' as visible
5457 * to users decreases. But the relationship is not linear,
5458 * so pick a second-best guess by going with the log2 of the
5459 * number of CPUs.
5461 * This idea comes from the SD scheduler of Con Kolivas:
5463 static inline void sched_init_granularity(void)
5465 unsigned int factor = 1 + ilog2(num_online_cpus());
5466 const unsigned long limit = 200000000;
5468 sysctl_sched_min_granularity *= factor;
5469 if (sysctl_sched_min_granularity > limit)
5470 sysctl_sched_min_granularity = limit;
5472 sysctl_sched_latency *= factor;
5473 if (sysctl_sched_latency > limit)
5474 sysctl_sched_latency = limit;
5476 sysctl_sched_wakeup_granularity *= factor;
5477 sysctl_sched_batch_wakeup_granularity *= factor;
5480 #ifdef CONFIG_SMP
5482 * This is how migration works:
5484 * 1) we queue a struct migration_req structure in the source CPU's
5485 * runqueue and wake up that CPU's migration thread.
5486 * 2) we down() the locked semaphore => thread blocks.
5487 * 3) migration thread wakes up (implicitly it forces the migrated
5488 * thread off the CPU)
5489 * 4) it gets the migration request and checks whether the migrated
5490 * task is still in the wrong runqueue.
5491 * 5) if it's in the wrong runqueue then the migration thread removes
5492 * it and puts it into the right queue.
5493 * 6) migration thread up()s the semaphore.
5494 * 7) we wake up and the migration is done.
5498 * Change a given task's CPU affinity. Migrate the thread to a
5499 * proper CPU and schedule it away if the CPU it's executing on
5500 * is removed from the allowed bitmask.
5502 * NOTE: the caller must have a valid reference to the task, the
5503 * task must not exit() & deallocate itself prematurely. The
5504 * call is not atomic; no spinlocks may be held.
5506 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5508 struct migration_req req;
5509 unsigned long flags;
5510 struct rq *rq;
5511 int ret = 0;
5513 rq = task_rq_lock(p, &flags);
5514 if (!cpus_intersects(new_mask, cpu_online_map)) {
5515 ret = -EINVAL;
5516 goto out;
5519 if (p->sched_class->set_cpus_allowed)
5520 p->sched_class->set_cpus_allowed(p, &new_mask);
5521 else {
5522 p->cpus_allowed = new_mask;
5523 p->rt.nr_cpus_allowed = cpus_weight(new_mask);
5526 /* Can the task run on the task's current CPU? If so, we're done */
5527 if (cpu_isset(task_cpu(p), new_mask))
5528 goto out;
5530 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5531 /* Need help from migration thread: drop lock and wait. */
5532 task_rq_unlock(rq, &flags);
5533 wake_up_process(rq->migration_thread);
5534 wait_for_completion(&req.done);
5535 tlb_migrate_finish(p->mm);
5536 return 0;
5538 out:
5539 task_rq_unlock(rq, &flags);
5541 return ret;
5543 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5546 * Move (not current) task off this cpu, onto dest cpu. We're doing
5547 * this because either it can't run here any more (set_cpus_allowed()
5548 * away from this CPU, or CPU going down), or because we're
5549 * attempting to rebalance this task on exec (sched_exec).
5551 * So we race with normal scheduler movements, but that's OK, as long
5552 * as the task is no longer on this CPU.
5554 * Returns non-zero if task was successfully migrated.
5556 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5558 struct rq *rq_dest, *rq_src;
5559 int ret = 0, on_rq;
5561 if (unlikely(cpu_is_offline(dest_cpu)))
5562 return ret;
5564 rq_src = cpu_rq(src_cpu);
5565 rq_dest = cpu_rq(dest_cpu);
5567 double_rq_lock(rq_src, rq_dest);
5568 /* Already moved. */
5569 if (task_cpu(p) != src_cpu)
5570 goto out;
5571 /* Affinity changed (again). */
5572 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5573 goto out;
5575 on_rq = p->se.on_rq;
5576 if (on_rq)
5577 deactivate_task(rq_src, p, 0);
5579 set_task_cpu(p, dest_cpu);
5580 if (on_rq) {
5581 activate_task(rq_dest, p, 0);
5582 check_preempt_curr(rq_dest, p);
5584 ret = 1;
5585 out:
5586 double_rq_unlock(rq_src, rq_dest);
5587 return ret;
5591 * migration_thread - this is a highprio system thread that performs
5592 * thread migration by bumping thread off CPU then 'pushing' onto
5593 * another runqueue.
5595 static int migration_thread(void *data)
5597 int cpu = (long)data;
5598 struct rq *rq;
5600 rq = cpu_rq(cpu);
5601 BUG_ON(rq->migration_thread != current);
5603 set_current_state(TASK_INTERRUPTIBLE);
5604 while (!kthread_should_stop()) {
5605 struct migration_req *req;
5606 struct list_head *head;
5608 spin_lock_irq(&rq->lock);
5610 if (cpu_is_offline(cpu)) {
5611 spin_unlock_irq(&rq->lock);
5612 goto wait_to_die;
5615 if (rq->active_balance) {
5616 active_load_balance(rq, cpu);
5617 rq->active_balance = 0;
5620 head = &rq->migration_queue;
5622 if (list_empty(head)) {
5623 spin_unlock_irq(&rq->lock);
5624 schedule();
5625 set_current_state(TASK_INTERRUPTIBLE);
5626 continue;
5628 req = list_entry(head->next, struct migration_req, list);
5629 list_del_init(head->next);
5631 spin_unlock(&rq->lock);
5632 __migrate_task(req->task, cpu, req->dest_cpu);
5633 local_irq_enable();
5635 complete(&req->done);
5637 __set_current_state(TASK_RUNNING);
5638 return 0;
5640 wait_to_die:
5641 /* Wait for kthread_stop */
5642 set_current_state(TASK_INTERRUPTIBLE);
5643 while (!kthread_should_stop()) {
5644 schedule();
5645 set_current_state(TASK_INTERRUPTIBLE);
5647 __set_current_state(TASK_RUNNING);
5648 return 0;
5651 #ifdef CONFIG_HOTPLUG_CPU
5653 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5655 int ret;
5657 local_irq_disable();
5658 ret = __migrate_task(p, src_cpu, dest_cpu);
5659 local_irq_enable();
5660 return ret;
5664 * Figure out where task on dead CPU should go, use force if necessary.
5665 * NOTE: interrupts should be disabled by the caller
5667 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5669 unsigned long flags;
5670 cpumask_t mask;
5671 struct rq *rq;
5672 int dest_cpu;
5674 do {
5675 /* On same node? */
5676 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5677 cpus_and(mask, mask, p->cpus_allowed);
5678 dest_cpu = any_online_cpu(mask);
5680 /* On any allowed CPU? */
5681 if (dest_cpu == NR_CPUS)
5682 dest_cpu = any_online_cpu(p->cpus_allowed);
5684 /* No more Mr. Nice Guy. */
5685 if (dest_cpu == NR_CPUS) {
5686 cpumask_t cpus_allowed = cpuset_cpus_allowed_locked(p);
5688 * Try to stay on the same cpuset, where the
5689 * current cpuset may be a subset of all cpus.
5690 * The cpuset_cpus_allowed_locked() variant of
5691 * cpuset_cpus_allowed() will not block. It must be
5692 * called within calls to cpuset_lock/cpuset_unlock.
5694 rq = task_rq_lock(p, &flags);
5695 p->cpus_allowed = cpus_allowed;
5696 dest_cpu = any_online_cpu(p->cpus_allowed);
5697 task_rq_unlock(rq, &flags);
5700 * Don't tell them about moving exiting tasks or
5701 * kernel threads (both mm NULL), since they never
5702 * leave kernel.
5704 if (p->mm && printk_ratelimit()) {
5705 printk(KERN_INFO "process %d (%s) no "
5706 "longer affine to cpu%d\n",
5707 task_pid_nr(p), p->comm, dead_cpu);
5710 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5714 * While a dead CPU has no uninterruptible tasks queued at this point,
5715 * it might still have a nonzero ->nr_uninterruptible counter, because
5716 * for performance reasons the counter is not stricly tracking tasks to
5717 * their home CPUs. So we just add the counter to another CPU's counter,
5718 * to keep the global sum constant after CPU-down:
5720 static void migrate_nr_uninterruptible(struct rq *rq_src)
5722 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5723 unsigned long flags;
5725 local_irq_save(flags);
5726 double_rq_lock(rq_src, rq_dest);
5727 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5728 rq_src->nr_uninterruptible = 0;
5729 double_rq_unlock(rq_src, rq_dest);
5730 local_irq_restore(flags);
5733 /* Run through task list and migrate tasks from the dead cpu. */
5734 static void migrate_live_tasks(int src_cpu)
5736 struct task_struct *p, *t;
5738 read_lock(&tasklist_lock);
5740 do_each_thread(t, p) {
5741 if (p == current)
5742 continue;
5744 if (task_cpu(p) == src_cpu)
5745 move_task_off_dead_cpu(src_cpu, p);
5746 } while_each_thread(t, p);
5748 read_unlock(&tasklist_lock);
5752 * Schedules idle task to be the next runnable task on current CPU.
5753 * It does so by boosting its priority to highest possible.
5754 * Used by CPU offline code.
5756 void sched_idle_next(void)
5758 int this_cpu = smp_processor_id();
5759 struct rq *rq = cpu_rq(this_cpu);
5760 struct task_struct *p = rq->idle;
5761 unsigned long flags;
5763 /* cpu has to be offline */
5764 BUG_ON(cpu_online(this_cpu));
5767 * Strictly not necessary since rest of the CPUs are stopped by now
5768 * and interrupts disabled on the current cpu.
5770 spin_lock_irqsave(&rq->lock, flags);
5772 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5774 update_rq_clock(rq);
5775 activate_task(rq, p, 0);
5777 spin_unlock_irqrestore(&rq->lock, flags);
5781 * Ensures that the idle task is using init_mm right before its cpu goes
5782 * offline.
5784 void idle_task_exit(void)
5786 struct mm_struct *mm = current->active_mm;
5788 BUG_ON(cpu_online(smp_processor_id()));
5790 if (mm != &init_mm)
5791 switch_mm(mm, &init_mm, current);
5792 mmdrop(mm);
5795 /* called under rq->lock with disabled interrupts */
5796 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5798 struct rq *rq = cpu_rq(dead_cpu);
5800 /* Must be exiting, otherwise would be on tasklist. */
5801 BUG_ON(!p->exit_state);
5803 /* Cannot have done final schedule yet: would have vanished. */
5804 BUG_ON(p->state == TASK_DEAD);
5806 get_task_struct(p);
5809 * Drop lock around migration; if someone else moves it,
5810 * that's OK. No task can be added to this CPU, so iteration is
5811 * fine.
5813 spin_unlock_irq(&rq->lock);
5814 move_task_off_dead_cpu(dead_cpu, p);
5815 spin_lock_irq(&rq->lock);
5817 put_task_struct(p);
5820 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5821 static void migrate_dead_tasks(unsigned int dead_cpu)
5823 struct rq *rq = cpu_rq(dead_cpu);
5824 struct task_struct *next;
5826 for ( ; ; ) {
5827 if (!rq->nr_running)
5828 break;
5829 update_rq_clock(rq);
5830 next = pick_next_task(rq, rq->curr);
5831 if (!next)
5832 break;
5833 migrate_dead(dead_cpu, next);
5837 #endif /* CONFIG_HOTPLUG_CPU */
5839 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5841 static struct ctl_table sd_ctl_dir[] = {
5843 .procname = "sched_domain",
5844 .mode = 0555,
5846 {0, },
5849 static struct ctl_table sd_ctl_root[] = {
5851 .ctl_name = CTL_KERN,
5852 .procname = "kernel",
5853 .mode = 0555,
5854 .child = sd_ctl_dir,
5856 {0, },
5859 static struct ctl_table *sd_alloc_ctl_entry(int n)
5861 struct ctl_table *entry =
5862 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5864 return entry;
5867 static void sd_free_ctl_entry(struct ctl_table **tablep)
5869 struct ctl_table *entry;
5872 * In the intermediate directories, both the child directory and
5873 * procname are dynamically allocated and could fail but the mode
5874 * will always be set. In the lowest directory the names are
5875 * static strings and all have proc handlers.
5877 for (entry = *tablep; entry->mode; entry++) {
5878 if (entry->child)
5879 sd_free_ctl_entry(&entry->child);
5880 if (entry->proc_handler == NULL)
5881 kfree(entry->procname);
5884 kfree(*tablep);
5885 *tablep = NULL;
5888 static void
5889 set_table_entry(struct ctl_table *entry,
5890 const char *procname, void *data, int maxlen,
5891 mode_t mode, proc_handler *proc_handler)
5893 entry->procname = procname;
5894 entry->data = data;
5895 entry->maxlen = maxlen;
5896 entry->mode = mode;
5897 entry->proc_handler = proc_handler;
5900 static struct ctl_table *
5901 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5903 struct ctl_table *table = sd_alloc_ctl_entry(12);
5905 if (table == NULL)
5906 return NULL;
5908 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5909 sizeof(long), 0644, proc_doulongvec_minmax);
5910 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5911 sizeof(long), 0644, proc_doulongvec_minmax);
5912 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5913 sizeof(int), 0644, proc_dointvec_minmax);
5914 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5915 sizeof(int), 0644, proc_dointvec_minmax);
5916 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5917 sizeof(int), 0644, proc_dointvec_minmax);
5918 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5919 sizeof(int), 0644, proc_dointvec_minmax);
5920 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5921 sizeof(int), 0644, proc_dointvec_minmax);
5922 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5923 sizeof(int), 0644, proc_dointvec_minmax);
5924 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5925 sizeof(int), 0644, proc_dointvec_minmax);
5926 set_table_entry(&table[9], "cache_nice_tries",
5927 &sd->cache_nice_tries,
5928 sizeof(int), 0644, proc_dointvec_minmax);
5929 set_table_entry(&table[10], "flags", &sd->flags,
5930 sizeof(int), 0644, proc_dointvec_minmax);
5931 /* &table[11] is terminator */
5933 return table;
5936 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5938 struct ctl_table *entry, *table;
5939 struct sched_domain *sd;
5940 int domain_num = 0, i;
5941 char buf[32];
5943 for_each_domain(cpu, sd)
5944 domain_num++;
5945 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5946 if (table == NULL)
5947 return NULL;
5949 i = 0;
5950 for_each_domain(cpu, sd) {
5951 snprintf(buf, 32, "domain%d", i);
5952 entry->procname = kstrdup(buf, GFP_KERNEL);
5953 entry->mode = 0555;
5954 entry->child = sd_alloc_ctl_domain_table(sd);
5955 entry++;
5956 i++;
5958 return table;
5961 static struct ctl_table_header *sd_sysctl_header;
5962 static void register_sched_domain_sysctl(void)
5964 int i, cpu_num = num_online_cpus();
5965 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5966 char buf[32];
5968 WARN_ON(sd_ctl_dir[0].child);
5969 sd_ctl_dir[0].child = entry;
5971 if (entry == NULL)
5972 return;
5974 for_each_online_cpu(i) {
5975 snprintf(buf, 32, "cpu%d", i);
5976 entry->procname = kstrdup(buf, GFP_KERNEL);
5977 entry->mode = 0555;
5978 entry->child = sd_alloc_ctl_cpu_table(i);
5979 entry++;
5982 WARN_ON(sd_sysctl_header);
5983 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5986 /* may be called multiple times per register */
5987 static void unregister_sched_domain_sysctl(void)
5989 if (sd_sysctl_header)
5990 unregister_sysctl_table(sd_sysctl_header);
5991 sd_sysctl_header = NULL;
5992 if (sd_ctl_dir[0].child)
5993 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5995 #else
5996 static void register_sched_domain_sysctl(void)
5999 static void unregister_sched_domain_sysctl(void)
6002 #endif
6005 * migration_call - callback that gets triggered when a CPU is added.
6006 * Here we can start up the necessary migration thread for the new CPU.
6008 static int __cpuinit
6009 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6011 struct task_struct *p;
6012 int cpu = (long)hcpu;
6013 unsigned long flags;
6014 struct rq *rq;
6016 switch (action) {
6018 case CPU_UP_PREPARE:
6019 case CPU_UP_PREPARE_FROZEN:
6020 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6021 if (IS_ERR(p))
6022 return NOTIFY_BAD;
6023 kthread_bind(p, cpu);
6024 /* Must be high prio: stop_machine expects to yield to it. */
6025 rq = task_rq_lock(p, &flags);
6026 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6027 task_rq_unlock(rq, &flags);
6028 cpu_rq(cpu)->migration_thread = p;
6029 break;
6031 case CPU_ONLINE:
6032 case CPU_ONLINE_FROZEN:
6033 /* Strictly unnecessary, as first user will wake it. */
6034 wake_up_process(cpu_rq(cpu)->migration_thread);
6036 /* Update our root-domain */
6037 rq = cpu_rq(cpu);
6038 spin_lock_irqsave(&rq->lock, flags);
6039 if (rq->rd) {
6040 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6041 cpu_set(cpu, rq->rd->online);
6043 spin_unlock_irqrestore(&rq->lock, flags);
6044 break;
6046 #ifdef CONFIG_HOTPLUG_CPU
6047 case CPU_UP_CANCELED:
6048 case CPU_UP_CANCELED_FROZEN:
6049 if (!cpu_rq(cpu)->migration_thread)
6050 break;
6051 /* Unbind it from offline cpu so it can run. Fall thru. */
6052 kthread_bind(cpu_rq(cpu)->migration_thread,
6053 any_online_cpu(cpu_online_map));
6054 kthread_stop(cpu_rq(cpu)->migration_thread);
6055 cpu_rq(cpu)->migration_thread = NULL;
6056 break;
6058 case CPU_DEAD:
6059 case CPU_DEAD_FROZEN:
6060 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6061 migrate_live_tasks(cpu);
6062 rq = cpu_rq(cpu);
6063 kthread_stop(rq->migration_thread);
6064 rq->migration_thread = NULL;
6065 /* Idle task back to normal (off runqueue, low prio) */
6066 spin_lock_irq(&rq->lock);
6067 update_rq_clock(rq);
6068 deactivate_task(rq, rq->idle, 0);
6069 rq->idle->static_prio = MAX_PRIO;
6070 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6071 rq->idle->sched_class = &idle_sched_class;
6072 migrate_dead_tasks(cpu);
6073 spin_unlock_irq(&rq->lock);
6074 cpuset_unlock();
6075 migrate_nr_uninterruptible(rq);
6076 BUG_ON(rq->nr_running != 0);
6079 * No need to migrate the tasks: it was best-effort if
6080 * they didn't take sched_hotcpu_mutex. Just wake up
6081 * the requestors.
6083 spin_lock_irq(&rq->lock);
6084 while (!list_empty(&rq->migration_queue)) {
6085 struct migration_req *req;
6087 req = list_entry(rq->migration_queue.next,
6088 struct migration_req, list);
6089 list_del_init(&req->list);
6090 complete(&req->done);
6092 spin_unlock_irq(&rq->lock);
6093 break;
6095 <<<<<<< HEAD:kernel/sched.c
6096 case CPU_DOWN_PREPARE:
6097 =======
6098 case CPU_DYING:
6099 case CPU_DYING_FROZEN:
6100 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
6101 /* Update our root-domain */
6102 rq = cpu_rq(cpu);
6103 spin_lock_irqsave(&rq->lock, flags);
6104 if (rq->rd) {
6105 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6106 cpu_clear(cpu, rq->rd->online);
6108 spin_unlock_irqrestore(&rq->lock, flags);
6109 break;
6110 #endif
6112 return NOTIFY_OK;
6115 /* Register at highest priority so that task migration (migrate_all_tasks)
6116 * happens before everything else.
6118 static struct notifier_block __cpuinitdata migration_notifier = {
6119 .notifier_call = migration_call,
6120 .priority = 10
6123 void __init migration_init(void)
6125 void *cpu = (void *)(long)smp_processor_id();
6126 int err;
6128 /* Start one for the boot CPU: */
6129 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6130 BUG_ON(err == NOTIFY_BAD);
6131 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6132 register_cpu_notifier(&migration_notifier);
6134 #endif
6136 #ifdef CONFIG_SMP
6138 /* Number of possible processor ids */
6139 int nr_cpu_ids __read_mostly = NR_CPUS;
6140 EXPORT_SYMBOL(nr_cpu_ids);
6142 #ifdef CONFIG_SCHED_DEBUG
6144 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level)
6146 struct sched_group *group = sd->groups;
6147 cpumask_t groupmask;
6148 char str[NR_CPUS];
6150 cpumask_scnprintf(str, NR_CPUS, sd->span);
6151 cpus_clear(groupmask);
6153 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6155 if (!(sd->flags & SD_LOAD_BALANCE)) {
6156 printk("does not load-balance\n");
6157 if (sd->parent)
6158 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6159 " has parent");
6160 return -1;
6163 printk(KERN_CONT "span %s\n", str);
6165 if (!cpu_isset(cpu, sd->span)) {
6166 printk(KERN_ERR "ERROR: domain->span does not contain "
6167 "CPU%d\n", cpu);
6169 if (!cpu_isset(cpu, group->cpumask)) {
6170 printk(KERN_ERR "ERROR: domain->groups does not contain"
6171 " CPU%d\n", cpu);
6174 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6175 do {
6176 if (!group) {
6177 printk("\n");
6178 printk(KERN_ERR "ERROR: group is NULL\n");
6179 break;
6182 if (!group->__cpu_power) {
6183 printk(KERN_CONT "\n");
6184 printk(KERN_ERR "ERROR: domain->cpu_power not "
6185 "set\n");
6186 break;
6189 if (!cpus_weight(group->cpumask)) {
6190 printk(KERN_CONT "\n");
6191 printk(KERN_ERR "ERROR: empty group\n");
6192 break;
6195 if (cpus_intersects(groupmask, group->cpumask)) {
6196 printk(KERN_CONT "\n");
6197 printk(KERN_ERR "ERROR: repeated CPUs\n");
6198 break;
6201 cpus_or(groupmask, groupmask, group->cpumask);
6203 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
6204 printk(KERN_CONT " %s", str);
6206 group = group->next;
6207 } while (group != sd->groups);
6208 printk(KERN_CONT "\n");
6210 if (!cpus_equal(sd->span, groupmask))
6211 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6213 if (sd->parent && !cpus_subset(groupmask, sd->parent->span))
6214 printk(KERN_ERR "ERROR: parent span is not a superset "
6215 "of domain->span\n");
6216 return 0;
6219 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6221 int level = 0;
6223 if (!sd) {
6224 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6225 return;
6228 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6230 for (;;) {
6231 if (sched_domain_debug_one(sd, cpu, level))
6232 break;
6233 level++;
6234 sd = sd->parent;
6235 if (!sd)
6236 break;
6239 #else
6240 # define sched_domain_debug(sd, cpu) do { } while (0)
6241 #endif
6243 static int sd_degenerate(struct sched_domain *sd)
6245 if (cpus_weight(sd->span) == 1)
6246 return 1;
6248 /* Following flags need at least 2 groups */
6249 if (sd->flags & (SD_LOAD_BALANCE |
6250 SD_BALANCE_NEWIDLE |
6251 SD_BALANCE_FORK |
6252 SD_BALANCE_EXEC |
6253 SD_SHARE_CPUPOWER |
6254 SD_SHARE_PKG_RESOURCES)) {
6255 if (sd->groups != sd->groups->next)
6256 return 0;
6259 /* Following flags don't use groups */
6260 if (sd->flags & (SD_WAKE_IDLE |
6261 SD_WAKE_AFFINE |
6262 SD_WAKE_BALANCE))
6263 return 0;
6265 return 1;
6268 static int
6269 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6271 unsigned long cflags = sd->flags, pflags = parent->flags;
6273 if (sd_degenerate(parent))
6274 return 1;
6276 if (!cpus_equal(sd->span, parent->span))
6277 return 0;
6279 /* Does parent contain flags not in child? */
6280 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6281 if (cflags & SD_WAKE_AFFINE)
6282 pflags &= ~SD_WAKE_BALANCE;
6283 /* Flags needing groups don't count if only 1 group in parent */
6284 if (parent->groups == parent->groups->next) {
6285 pflags &= ~(SD_LOAD_BALANCE |
6286 SD_BALANCE_NEWIDLE |
6287 SD_BALANCE_FORK |
6288 SD_BALANCE_EXEC |
6289 SD_SHARE_CPUPOWER |
6290 SD_SHARE_PKG_RESOURCES);
6292 if (~cflags & pflags)
6293 return 0;
6295 return 1;
6298 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6300 unsigned long flags;
6301 const struct sched_class *class;
6303 spin_lock_irqsave(&rq->lock, flags);
6305 if (rq->rd) {
6306 struct root_domain *old_rd = rq->rd;
6308 for (class = sched_class_highest; class; class = class->next) {
6309 if (class->leave_domain)
6310 class->leave_domain(rq);
6313 cpu_clear(rq->cpu, old_rd->span);
6314 cpu_clear(rq->cpu, old_rd->online);
6316 if (atomic_dec_and_test(&old_rd->refcount))
6317 kfree(old_rd);
6320 atomic_inc(&rd->refcount);
6321 rq->rd = rd;
6323 cpu_set(rq->cpu, rd->span);
6324 if (cpu_isset(rq->cpu, cpu_online_map))
6325 cpu_set(rq->cpu, rd->online);
6327 for (class = sched_class_highest; class; class = class->next) {
6328 if (class->join_domain)
6329 class->join_domain(rq);
6332 spin_unlock_irqrestore(&rq->lock, flags);
6335 static void init_rootdomain(struct root_domain *rd)
6337 memset(rd, 0, sizeof(*rd));
6339 cpus_clear(rd->span);
6340 cpus_clear(rd->online);
6343 static void init_defrootdomain(void)
6345 init_rootdomain(&def_root_domain);
6346 atomic_set(&def_root_domain.refcount, 1);
6349 static struct root_domain *alloc_rootdomain(void)
6351 struct root_domain *rd;
6353 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6354 if (!rd)
6355 return NULL;
6357 init_rootdomain(rd);
6359 return rd;
6363 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6364 * hold the hotplug lock.
6366 static void
6367 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6369 struct rq *rq = cpu_rq(cpu);
6370 struct sched_domain *tmp;
6372 /* Remove the sched domains which do not contribute to scheduling. */
6373 for (tmp = sd; tmp; tmp = tmp->parent) {
6374 struct sched_domain *parent = tmp->parent;
6375 if (!parent)
6376 break;
6377 if (sd_parent_degenerate(tmp, parent)) {
6378 tmp->parent = parent->parent;
6379 if (parent->parent)
6380 parent->parent->child = tmp;
6384 if (sd && sd_degenerate(sd)) {
6385 sd = sd->parent;
6386 if (sd)
6387 sd->child = NULL;
6390 sched_domain_debug(sd, cpu);
6392 rq_attach_root(rq, rd);
6393 rcu_assign_pointer(rq->sd, sd);
6396 /* cpus with isolated domains */
6397 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6399 /* Setup the mask of cpus configured for isolated domains */
6400 static int __init isolated_cpu_setup(char *str)
6402 int ints[NR_CPUS], i;
6404 str = get_options(str, ARRAY_SIZE(ints), ints);
6405 cpus_clear(cpu_isolated_map);
6406 for (i = 1; i <= ints[0]; i++)
6407 if (ints[i] < NR_CPUS)
6408 cpu_set(ints[i], cpu_isolated_map);
6409 return 1;
6412 __setup("isolcpus=", isolated_cpu_setup);
6415 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6416 * to a function which identifies what group(along with sched group) a CPU
6417 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6418 * (due to the fact that we keep track of groups covered with a cpumask_t).
6420 * init_sched_build_groups will build a circular linked list of the groups
6421 * covered by the given span, and will set each group's ->cpumask correctly,
6422 * and ->cpu_power to 0.
6424 static void
6425 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
6426 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6427 struct sched_group **sg))
6429 struct sched_group *first = NULL, *last = NULL;
6430 cpumask_t covered = CPU_MASK_NONE;
6431 int i;
6433 for_each_cpu_mask(i, span) {
6434 struct sched_group *sg;
6435 int group = group_fn(i, cpu_map, &sg);
6436 int j;
6438 if (cpu_isset(i, covered))
6439 continue;
6441 sg->cpumask = CPU_MASK_NONE;
6442 sg->__cpu_power = 0;
6444 for_each_cpu_mask(j, span) {
6445 if (group_fn(j, cpu_map, NULL) != group)
6446 continue;
6448 cpu_set(j, covered);
6449 cpu_set(j, sg->cpumask);
6451 if (!first)
6452 first = sg;
6453 if (last)
6454 last->next = sg;
6455 last = sg;
6457 last->next = first;
6460 #define SD_NODES_PER_DOMAIN 16
6462 #ifdef CONFIG_NUMA
6465 * find_next_best_node - find the next node to include in a sched_domain
6466 * @node: node whose sched_domain we're building
6467 * @used_nodes: nodes already in the sched_domain
6469 * Find the next node to include in a given scheduling domain. Simply
6470 * finds the closest node not already in the @used_nodes map.
6472 * Should use nodemask_t.
6474 static int find_next_best_node(int node, unsigned long *used_nodes)
6476 int i, n, val, min_val, best_node = 0;
6478 min_val = INT_MAX;
6480 for (i = 0; i < MAX_NUMNODES; i++) {
6481 /* Start at @node */
6482 n = (node + i) % MAX_NUMNODES;
6484 if (!nr_cpus_node(n))
6485 continue;
6487 /* Skip already used nodes */
6488 if (test_bit(n, used_nodes))
6489 continue;
6491 /* Simple min distance search */
6492 val = node_distance(node, n);
6494 if (val < min_val) {
6495 min_val = val;
6496 best_node = n;
6500 set_bit(best_node, used_nodes);
6501 return best_node;
6505 * sched_domain_node_span - get a cpumask for a node's sched_domain
6506 * @node: node whose cpumask we're constructing
6507 * @size: number of nodes to include in this span
6509 * Given a node, construct a good cpumask for its sched_domain to span. It
6510 * should be one that prevents unnecessary balancing, but also spreads tasks
6511 * out optimally.
6513 static cpumask_t sched_domain_node_span(int node)
6515 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6516 cpumask_t span, nodemask;
6517 int i;
6519 cpus_clear(span);
6520 bitmap_zero(used_nodes, MAX_NUMNODES);
6522 nodemask = node_to_cpumask(node);
6523 cpus_or(span, span, nodemask);
6524 set_bit(node, used_nodes);
6526 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6527 int next_node = find_next_best_node(node, used_nodes);
6529 nodemask = node_to_cpumask(next_node);
6530 cpus_or(span, span, nodemask);
6533 return span;
6535 #endif
6537 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6540 * SMT sched-domains:
6542 #ifdef CONFIG_SCHED_SMT
6543 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6544 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6546 static int
6547 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6549 if (sg)
6550 *sg = &per_cpu(sched_group_cpus, cpu);
6551 return cpu;
6553 #endif
6556 * multi-core sched-domains:
6558 #ifdef CONFIG_SCHED_MC
6559 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6560 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6561 #endif
6563 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6564 static int
6565 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6567 int group;
6568 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6569 cpus_and(mask, mask, *cpu_map);
6570 group = first_cpu(mask);
6571 if (sg)
6572 *sg = &per_cpu(sched_group_core, group);
6573 return group;
6575 #elif defined(CONFIG_SCHED_MC)
6576 static int
6577 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6579 if (sg)
6580 *sg = &per_cpu(sched_group_core, cpu);
6581 return cpu;
6583 #endif
6585 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6586 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6588 static int
6589 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6591 int group;
6592 #ifdef CONFIG_SCHED_MC
6593 cpumask_t mask = cpu_coregroup_map(cpu);
6594 cpus_and(mask, mask, *cpu_map);
6595 group = first_cpu(mask);
6596 #elif defined(CONFIG_SCHED_SMT)
6597 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6598 cpus_and(mask, mask, *cpu_map);
6599 group = first_cpu(mask);
6600 #else
6601 group = cpu;
6602 #endif
6603 if (sg)
6604 *sg = &per_cpu(sched_group_phys, group);
6605 return group;
6608 #ifdef CONFIG_NUMA
6610 * The init_sched_build_groups can't handle what we want to do with node
6611 * groups, so roll our own. Now each node has its own list of groups which
6612 * gets dynamically allocated.
6614 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6615 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6617 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6618 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6620 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6621 struct sched_group **sg)
6623 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6624 int group;
6626 cpus_and(nodemask, nodemask, *cpu_map);
6627 group = first_cpu(nodemask);
6629 if (sg)
6630 *sg = &per_cpu(sched_group_allnodes, group);
6631 return group;
6634 static void init_numa_sched_groups_power(struct sched_group *group_head)
6636 struct sched_group *sg = group_head;
6637 int j;
6639 if (!sg)
6640 return;
6641 do {
6642 for_each_cpu_mask(j, sg->cpumask) {
6643 struct sched_domain *sd;
6645 sd = &per_cpu(phys_domains, j);
6646 if (j != first_cpu(sd->groups->cpumask)) {
6648 * Only add "power" once for each
6649 * physical package.
6651 continue;
6654 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6656 sg = sg->next;
6657 } while (sg != group_head);
6659 #endif
6661 #ifdef CONFIG_NUMA
6662 /* Free memory allocated for various sched_group structures */
6663 static void free_sched_groups(const cpumask_t *cpu_map)
6665 int cpu, i;
6667 for_each_cpu_mask(cpu, *cpu_map) {
6668 struct sched_group **sched_group_nodes
6669 = sched_group_nodes_bycpu[cpu];
6671 if (!sched_group_nodes)
6672 continue;
6674 for (i = 0; i < MAX_NUMNODES; i++) {
6675 cpumask_t nodemask = node_to_cpumask(i);
6676 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6678 cpus_and(nodemask, nodemask, *cpu_map);
6679 if (cpus_empty(nodemask))
6680 continue;
6682 if (sg == NULL)
6683 continue;
6684 sg = sg->next;
6685 next_sg:
6686 oldsg = sg;
6687 sg = sg->next;
6688 kfree(oldsg);
6689 if (oldsg != sched_group_nodes[i])
6690 goto next_sg;
6692 kfree(sched_group_nodes);
6693 sched_group_nodes_bycpu[cpu] = NULL;
6696 #else
6697 static void free_sched_groups(const cpumask_t *cpu_map)
6700 #endif
6703 * Initialize sched groups cpu_power.
6705 * cpu_power indicates the capacity of sched group, which is used while
6706 * distributing the load between different sched groups in a sched domain.
6707 * Typically cpu_power for all the groups in a sched domain will be same unless
6708 * there are asymmetries in the topology. If there are asymmetries, group
6709 * having more cpu_power will pickup more load compared to the group having
6710 * less cpu_power.
6712 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6713 * the maximum number of tasks a group can handle in the presence of other idle
6714 * or lightly loaded groups in the same sched domain.
6716 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6718 struct sched_domain *child;
6719 struct sched_group *group;
6721 WARN_ON(!sd || !sd->groups);
6723 if (cpu != first_cpu(sd->groups->cpumask))
6724 return;
6726 child = sd->child;
6728 sd->groups->__cpu_power = 0;
6731 * For perf policy, if the groups in child domain share resources
6732 * (for example cores sharing some portions of the cache hierarchy
6733 * or SMT), then set this domain groups cpu_power such that each group
6734 * can handle only one task, when there are other idle groups in the
6735 * same sched domain.
6737 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6738 (child->flags &
6739 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6740 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6741 return;
6745 * add cpu_power of each child group to this groups cpu_power
6747 group = child->groups;
6748 do {
6749 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6750 group = group->next;
6751 } while (group != child->groups);
6755 * Build sched domains for a given set of cpus and attach the sched domains
6756 * to the individual cpus
6758 static int build_sched_domains(const cpumask_t *cpu_map)
6760 int i;
6761 struct root_domain *rd;
6762 #ifdef CONFIG_NUMA
6763 struct sched_group **sched_group_nodes = NULL;
6764 int sd_allnodes = 0;
6767 * Allocate the per-node list of sched groups
6769 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6770 GFP_KERNEL);
6771 if (!sched_group_nodes) {
6772 printk(KERN_WARNING "Can not alloc sched group node list\n");
6773 return -ENOMEM;
6775 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6776 #endif
6778 rd = alloc_rootdomain();
6779 if (!rd) {
6780 printk(KERN_WARNING "Cannot alloc root domain\n");
6781 return -ENOMEM;
6785 * Set up domains for cpus specified by the cpu_map.
6787 for_each_cpu_mask(i, *cpu_map) {
6788 struct sched_domain *sd = NULL, *p;
6789 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6791 cpus_and(nodemask, nodemask, *cpu_map);
6793 #ifdef CONFIG_NUMA
6794 if (cpus_weight(*cpu_map) >
6795 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6796 sd = &per_cpu(allnodes_domains, i);
6797 *sd = SD_ALLNODES_INIT;
6798 sd->span = *cpu_map;
6799 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6800 p = sd;
6801 sd_allnodes = 1;
6802 } else
6803 p = NULL;
6805 sd = &per_cpu(node_domains, i);
6806 *sd = SD_NODE_INIT;
6807 sd->span = sched_domain_node_span(cpu_to_node(i));
6808 sd->parent = p;
6809 if (p)
6810 p->child = sd;
6811 cpus_and(sd->span, sd->span, *cpu_map);
6812 #endif
6814 p = sd;
6815 sd = &per_cpu(phys_domains, i);
6816 *sd = SD_CPU_INIT;
6817 sd->span = nodemask;
6818 sd->parent = p;
6819 if (p)
6820 p->child = sd;
6821 cpu_to_phys_group(i, cpu_map, &sd->groups);
6823 #ifdef CONFIG_SCHED_MC
6824 p = sd;
6825 sd = &per_cpu(core_domains, i);
6826 *sd = SD_MC_INIT;
6827 sd->span = cpu_coregroup_map(i);
6828 cpus_and(sd->span, sd->span, *cpu_map);
6829 sd->parent = p;
6830 p->child = sd;
6831 cpu_to_core_group(i, cpu_map, &sd->groups);
6832 #endif
6834 #ifdef CONFIG_SCHED_SMT
6835 p = sd;
6836 sd = &per_cpu(cpu_domains, i);
6837 *sd = SD_SIBLING_INIT;
6838 sd->span = per_cpu(cpu_sibling_map, i);
6839 cpus_and(sd->span, sd->span, *cpu_map);
6840 sd->parent = p;
6841 p->child = sd;
6842 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6843 #endif
6846 #ifdef CONFIG_SCHED_SMT
6847 /* Set up CPU (sibling) groups */
6848 for_each_cpu_mask(i, *cpu_map) {
6849 cpumask_t this_sibling_map = per_cpu(cpu_sibling_map, i);
6850 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6851 if (i != first_cpu(this_sibling_map))
6852 continue;
6854 init_sched_build_groups(this_sibling_map, cpu_map,
6855 &cpu_to_cpu_group);
6857 #endif
6859 #ifdef CONFIG_SCHED_MC
6860 /* Set up multi-core groups */
6861 for_each_cpu_mask(i, *cpu_map) {
6862 cpumask_t this_core_map = cpu_coregroup_map(i);
6863 cpus_and(this_core_map, this_core_map, *cpu_map);
6864 if (i != first_cpu(this_core_map))
6865 continue;
6866 init_sched_build_groups(this_core_map, cpu_map,
6867 &cpu_to_core_group);
6869 #endif
6871 /* Set up physical groups */
6872 for (i = 0; i < MAX_NUMNODES; i++) {
6873 cpumask_t nodemask = node_to_cpumask(i);
6875 cpus_and(nodemask, nodemask, *cpu_map);
6876 if (cpus_empty(nodemask))
6877 continue;
6879 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6882 #ifdef CONFIG_NUMA
6883 /* Set up node groups */
6884 if (sd_allnodes)
6885 init_sched_build_groups(*cpu_map, cpu_map,
6886 &cpu_to_allnodes_group);
6888 for (i = 0; i < MAX_NUMNODES; i++) {
6889 /* Set up node groups */
6890 struct sched_group *sg, *prev;
6891 cpumask_t nodemask = node_to_cpumask(i);
6892 cpumask_t domainspan;
6893 cpumask_t covered = CPU_MASK_NONE;
6894 int j;
6896 cpus_and(nodemask, nodemask, *cpu_map);
6897 if (cpus_empty(nodemask)) {
6898 sched_group_nodes[i] = NULL;
6899 continue;
6902 domainspan = sched_domain_node_span(i);
6903 cpus_and(domainspan, domainspan, *cpu_map);
6905 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6906 if (!sg) {
6907 printk(KERN_WARNING "Can not alloc domain group for "
6908 "node %d\n", i);
6909 goto error;
6911 sched_group_nodes[i] = sg;
6912 for_each_cpu_mask(j, nodemask) {
6913 struct sched_domain *sd;
6915 sd = &per_cpu(node_domains, j);
6916 sd->groups = sg;
6918 sg->__cpu_power = 0;
6919 sg->cpumask = nodemask;
6920 sg->next = sg;
6921 cpus_or(covered, covered, nodemask);
6922 prev = sg;
6924 for (j = 0; j < MAX_NUMNODES; j++) {
6925 cpumask_t tmp, notcovered;
6926 int n = (i + j) % MAX_NUMNODES;
6928 cpus_complement(notcovered, covered);
6929 cpus_and(tmp, notcovered, *cpu_map);
6930 cpus_and(tmp, tmp, domainspan);
6931 if (cpus_empty(tmp))
6932 break;
6934 nodemask = node_to_cpumask(n);
6935 cpus_and(tmp, tmp, nodemask);
6936 if (cpus_empty(tmp))
6937 continue;
6939 sg = kmalloc_node(sizeof(struct sched_group),
6940 GFP_KERNEL, i);
6941 if (!sg) {
6942 printk(KERN_WARNING
6943 "Can not alloc domain group for node %d\n", j);
6944 goto error;
6946 sg->__cpu_power = 0;
6947 sg->cpumask = tmp;
6948 sg->next = prev->next;
6949 cpus_or(covered, covered, tmp);
6950 prev->next = sg;
6951 prev = sg;
6954 #endif
6956 /* Calculate CPU power for physical packages and nodes */
6957 #ifdef CONFIG_SCHED_SMT
6958 for_each_cpu_mask(i, *cpu_map) {
6959 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6961 init_sched_groups_power(i, sd);
6963 #endif
6964 #ifdef CONFIG_SCHED_MC
6965 for_each_cpu_mask(i, *cpu_map) {
6966 struct sched_domain *sd = &per_cpu(core_domains, i);
6968 init_sched_groups_power(i, sd);
6970 #endif
6972 for_each_cpu_mask(i, *cpu_map) {
6973 struct sched_domain *sd = &per_cpu(phys_domains, i);
6975 init_sched_groups_power(i, sd);
6978 #ifdef CONFIG_NUMA
6979 for (i = 0; i < MAX_NUMNODES; i++)
6980 init_numa_sched_groups_power(sched_group_nodes[i]);
6982 if (sd_allnodes) {
6983 struct sched_group *sg;
6985 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6986 init_numa_sched_groups_power(sg);
6988 #endif
6990 /* Attach the domains */
6991 for_each_cpu_mask(i, *cpu_map) {
6992 struct sched_domain *sd;
6993 #ifdef CONFIG_SCHED_SMT
6994 sd = &per_cpu(cpu_domains, i);
6995 #elif defined(CONFIG_SCHED_MC)
6996 sd = &per_cpu(core_domains, i);
6997 #else
6998 sd = &per_cpu(phys_domains, i);
6999 #endif
7000 cpu_attach_domain(sd, rd, i);
7003 return 0;
7005 #ifdef CONFIG_NUMA
7006 error:
7007 free_sched_groups(cpu_map);
7008 return -ENOMEM;
7009 #endif
7012 static cpumask_t *doms_cur; /* current sched domains */
7013 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7016 * Special case: If a kmalloc of a doms_cur partition (array of
7017 * cpumask_t) fails, then fallback to a single sched domain,
7018 * as determined by the single cpumask_t fallback_doms.
7020 static cpumask_t fallback_doms;
7023 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7024 * For now this just excludes isolated cpus, but could be used to
7025 * exclude other special cases in the future.
7027 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7029 int err;
7031 ndoms_cur = 1;
7032 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7033 if (!doms_cur)
7034 doms_cur = &fallback_doms;
7035 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7036 err = build_sched_domains(doms_cur);
7037 register_sched_domain_sysctl();
7039 return err;
7042 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
7044 free_sched_groups(cpu_map);
7048 * Detach sched domains from a group of cpus specified in cpu_map
7049 * These cpus will now be attached to the NULL domain
7051 static void detach_destroy_domains(const cpumask_t *cpu_map)
7053 int i;
7055 unregister_sched_domain_sysctl();
7057 for_each_cpu_mask(i, *cpu_map)
7058 cpu_attach_domain(NULL, &def_root_domain, i);
7059 synchronize_sched();
7060 arch_destroy_sched_domains(cpu_map);
7064 * Partition sched domains as specified by the 'ndoms_new'
7065 * cpumasks in the array doms_new[] of cpumasks. This compares
7066 * doms_new[] to the current sched domain partitioning, doms_cur[].
7067 * It destroys each deleted domain and builds each new domain.
7069 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7070 * The masks don't intersect (don't overlap.) We should setup one
7071 * sched domain for each mask. CPUs not in any of the cpumasks will
7072 * not be load balanced. If the same cpumask appears both in the
7073 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7074 * it as it is.
7076 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7077 * ownership of it and will kfree it when done with it. If the caller
7078 * failed the kmalloc call, then it can pass in doms_new == NULL,
7079 * and partition_sched_domains() will fallback to the single partition
7080 * 'fallback_doms'.
7082 * Call with hotplug lock held
7084 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
7086 int i, j;
7088 lock_doms_cur();
7090 /* always unregister in case we don't destroy any domains */
7091 unregister_sched_domain_sysctl();
7093 if (doms_new == NULL) {
7094 ndoms_new = 1;
7095 doms_new = &fallback_doms;
7096 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7099 /* Destroy deleted domains */
7100 for (i = 0; i < ndoms_cur; i++) {
7101 for (j = 0; j < ndoms_new; j++) {
7102 if (cpus_equal(doms_cur[i], doms_new[j]))
7103 goto match1;
7105 /* no match - a current sched domain not in new doms_new[] */
7106 detach_destroy_domains(doms_cur + i);
7107 match1:
7111 /* Build new domains */
7112 for (i = 0; i < ndoms_new; i++) {
7113 for (j = 0; j < ndoms_cur; j++) {
7114 if (cpus_equal(doms_new[i], doms_cur[j]))
7115 goto match2;
7117 /* no match - add a new doms_new */
7118 build_sched_domains(doms_new + i);
7119 match2:
7123 /* Remember the new sched domains */
7124 if (doms_cur != &fallback_doms)
7125 kfree(doms_cur);
7126 doms_cur = doms_new;
7127 ndoms_cur = ndoms_new;
7129 register_sched_domain_sysctl();
7131 unlock_doms_cur();
7134 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7135 static int arch_reinit_sched_domains(void)
7137 int err;
7139 get_online_cpus();
7140 detach_destroy_domains(&cpu_online_map);
7141 err = arch_init_sched_domains(&cpu_online_map);
7142 put_online_cpus();
7144 return err;
7147 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7149 int ret;
7151 if (buf[0] != '0' && buf[0] != '1')
7152 return -EINVAL;
7154 if (smt)
7155 sched_smt_power_savings = (buf[0] == '1');
7156 else
7157 sched_mc_power_savings = (buf[0] == '1');
7159 ret = arch_reinit_sched_domains();
7161 return ret ? ret : count;
7164 #ifdef CONFIG_SCHED_MC
7165 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7167 return sprintf(page, "%u\n", sched_mc_power_savings);
7169 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7170 const char *buf, size_t count)
7172 return sched_power_savings_store(buf, count, 0);
7174 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7175 sched_mc_power_savings_store);
7176 #endif
7178 #ifdef CONFIG_SCHED_SMT
7179 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7181 return sprintf(page, "%u\n", sched_smt_power_savings);
7183 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7184 const char *buf, size_t count)
7186 return sched_power_savings_store(buf, count, 1);
7188 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7189 sched_smt_power_savings_store);
7190 #endif
7192 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7194 int err = 0;
7196 #ifdef CONFIG_SCHED_SMT
7197 if (smt_capable())
7198 err = sysfs_create_file(&cls->kset.kobj,
7199 &attr_sched_smt_power_savings.attr);
7200 #endif
7201 #ifdef CONFIG_SCHED_MC
7202 if (!err && mc_capable())
7203 err = sysfs_create_file(&cls->kset.kobj,
7204 &attr_sched_mc_power_savings.attr);
7205 #endif
7206 return err;
7208 #endif
7211 * Force a reinitialization of the sched domains hierarchy. The domains
7212 * and groups cannot be updated in place without racing with the balancing
7213 * code, so we temporarily attach all running cpus to the NULL domain
7214 * which will prevent rebalancing while the sched domains are recalculated.
7216 static int update_sched_domains(struct notifier_block *nfb,
7217 unsigned long action, void *hcpu)
7219 switch (action) {
7220 case CPU_UP_PREPARE:
7221 case CPU_UP_PREPARE_FROZEN:
7222 case CPU_DOWN_PREPARE:
7223 case CPU_DOWN_PREPARE_FROZEN:
7224 detach_destroy_domains(&cpu_online_map);
7225 return NOTIFY_OK;
7227 case CPU_UP_CANCELED:
7228 case CPU_UP_CANCELED_FROZEN:
7229 case CPU_DOWN_FAILED:
7230 case CPU_DOWN_FAILED_FROZEN:
7231 case CPU_ONLINE:
7232 case CPU_ONLINE_FROZEN:
7233 case CPU_DEAD:
7234 case CPU_DEAD_FROZEN:
7236 * Fall through and re-initialise the domains.
7238 break;
7239 default:
7240 return NOTIFY_DONE;
7243 /* The hotplug lock is already held by cpu_up/cpu_down */
7244 arch_init_sched_domains(&cpu_online_map);
7246 return NOTIFY_OK;
7249 void __init sched_init_smp(void)
7251 cpumask_t non_isolated_cpus;
7253 get_online_cpus();
7254 arch_init_sched_domains(&cpu_online_map);
7255 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7256 if (cpus_empty(non_isolated_cpus))
7257 cpu_set(smp_processor_id(), non_isolated_cpus);
7258 put_online_cpus();
7259 /* XXX: Theoretical race here - CPU may be hotplugged now */
7260 hotcpu_notifier(update_sched_domains, 0);
7262 /* Move init over to a non-isolated CPU */
7263 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
7264 BUG();
7265 sched_init_granularity();
7266 <<<<<<< HEAD:kernel/sched.c
7268 #ifdef CONFIG_FAIR_GROUP_SCHED
7269 if (nr_cpu_ids == 1)
7270 return;
7272 lb_monitor_task = kthread_create(load_balance_monitor, NULL,
7273 "group_balance");
7274 if (!IS_ERR(lb_monitor_task)) {
7275 lb_monitor_task->flags |= PF_NOFREEZE;
7276 wake_up_process(lb_monitor_task);
7277 } else {
7278 printk(KERN_ERR "Could not create load balance monitor thread"
7279 "(error = %ld) \n", PTR_ERR(lb_monitor_task));
7281 #endif
7282 =======
7283 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
7285 #else
7286 void __init sched_init_smp(void)
7288 sched_init_granularity();
7290 #endif /* CONFIG_SMP */
7292 int in_sched_functions(unsigned long addr)
7294 return in_lock_functions(addr) ||
7295 (addr >= (unsigned long)__sched_text_start
7296 && addr < (unsigned long)__sched_text_end);
7299 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7301 cfs_rq->tasks_timeline = RB_ROOT;
7302 #ifdef CONFIG_FAIR_GROUP_SCHED
7303 cfs_rq->rq = rq;
7304 #endif
7305 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7308 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7310 struct rt_prio_array *array;
7311 int i;
7313 array = &rt_rq->active;
7314 for (i = 0; i < MAX_RT_PRIO; i++) {
7315 INIT_LIST_HEAD(array->queue + i);
7316 __clear_bit(i, array->bitmap);
7318 /* delimiter for bitsearch: */
7319 __set_bit(MAX_RT_PRIO, array->bitmap);
7321 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7322 rt_rq->highest_prio = MAX_RT_PRIO;
7323 #endif
7324 #ifdef CONFIG_SMP
7325 rt_rq->rt_nr_migratory = 0;
7326 rt_rq->overloaded = 0;
7327 #endif
7329 rt_rq->rt_time = 0;
7330 rt_rq->rt_throttled = 0;
7332 #ifdef CONFIG_RT_GROUP_SCHED
7333 rt_rq->rt_nr_boosted = 0;
7334 rt_rq->rq = rq;
7335 #endif
7338 #ifdef CONFIG_FAIR_GROUP_SCHED
7339 static void init_tg_cfs_entry(struct rq *rq, struct task_group *tg,
7340 struct cfs_rq *cfs_rq, struct sched_entity *se,
7341 int cpu, int add)
7343 tg->cfs_rq[cpu] = cfs_rq;
7344 init_cfs_rq(cfs_rq, rq);
7345 cfs_rq->tg = tg;
7346 if (add)
7347 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7349 tg->se[cpu] = se;
7350 se->cfs_rq = &rq->cfs;
7351 se->my_q = cfs_rq;
7352 se->load.weight = tg->shares;
7353 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
7354 se->parent = NULL;
7356 #endif
7358 #ifdef CONFIG_RT_GROUP_SCHED
7359 static void init_tg_rt_entry(struct rq *rq, struct task_group *tg,
7360 struct rt_rq *rt_rq, struct sched_rt_entity *rt_se,
7361 int cpu, int add)
7363 tg->rt_rq[cpu] = rt_rq;
7364 init_rt_rq(rt_rq, rq);
7365 rt_rq->tg = tg;
7366 rt_rq->rt_se = rt_se;
7367 if (add)
7368 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7370 tg->rt_se[cpu] = rt_se;
7371 rt_se->rt_rq = &rq->rt;
7372 rt_se->my_q = rt_rq;
7373 rt_se->parent = NULL;
7374 INIT_LIST_HEAD(&rt_se->run_list);
7376 #endif
7378 void __init sched_init(void)
7380 int highest_cpu = 0;
7381 int i, j;
7383 #ifdef CONFIG_SMP
7384 init_defrootdomain();
7385 #endif
7387 #ifdef CONFIG_GROUP_SCHED
7388 list_add(&init_task_group.list, &task_groups);
7389 #endif
7391 for_each_possible_cpu(i) {
7392 struct rq *rq;
7394 rq = cpu_rq(i);
7395 spin_lock_init(&rq->lock);
7396 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7397 rq->nr_running = 0;
7398 rq->clock = 1;
7399 init_cfs_rq(&rq->cfs, rq);
7400 init_rt_rq(&rq->rt, rq);
7401 #ifdef CONFIG_FAIR_GROUP_SCHED
7402 init_task_group.shares = init_task_group_load;
7403 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7404 init_tg_cfs_entry(rq, &init_task_group,
7405 &per_cpu(init_cfs_rq, i),
7406 &per_cpu(init_sched_entity, i), i, 1);
7408 #endif
7409 #ifdef CONFIG_RT_GROUP_SCHED
7410 init_task_group.rt_runtime =
7411 sysctl_sched_rt_runtime * NSEC_PER_USEC;
7412 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7413 init_tg_rt_entry(rq, &init_task_group,
7414 &per_cpu(init_rt_rq, i),
7415 &per_cpu(init_sched_rt_entity, i), i, 1);
7416 #endif
7417 rq->rt_period_expire = 0;
7418 rq->rt_throttled = 0;
7420 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7421 rq->cpu_load[j] = 0;
7422 #ifdef CONFIG_SMP
7423 rq->sd = NULL;
7424 rq->rd = NULL;
7425 rq->active_balance = 0;
7426 rq->next_balance = jiffies;
7427 rq->push_cpu = 0;
7428 rq->cpu = i;
7429 rq->migration_thread = NULL;
7430 INIT_LIST_HEAD(&rq->migration_queue);
7431 rq_attach_root(rq, &def_root_domain);
7432 #endif
7433 init_rq_hrtick(rq);
7434 atomic_set(&rq->nr_iowait, 0);
7435 highest_cpu = i;
7438 set_load_weight(&init_task);
7440 #ifdef CONFIG_PREEMPT_NOTIFIERS
7441 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7442 #endif
7444 #ifdef CONFIG_SMP
7445 nr_cpu_ids = highest_cpu + 1;
7446 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7447 #endif
7449 #ifdef CONFIG_RT_MUTEXES
7450 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7451 #endif
7454 * The boot idle thread does lazy MMU switching as well:
7456 atomic_inc(&init_mm.mm_count);
7457 enter_lazy_tlb(&init_mm, current);
7460 * Make us the idle thread. Technically, schedule() should not be
7461 * called from this thread, however somewhere below it might be,
7462 * but because we are the idle thread, we just pick up running again
7463 * when this runqueue becomes "idle".
7465 init_idle(current, smp_processor_id());
7467 * During early bootup we pretend to be a normal task:
7469 current->sched_class = &fair_sched_class;
7470 <<<<<<< HEAD:kernel/sched.c
7471 =======
7473 scheduler_running = 1;
7474 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
7477 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7478 void __might_sleep(char *file, int line)
7480 #ifdef in_atomic
7481 static unsigned long prev_jiffy; /* ratelimiting */
7483 if ((in_atomic() || irqs_disabled()) &&
7484 system_state == SYSTEM_RUNNING && !oops_in_progress) {
7485 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7486 return;
7487 prev_jiffy = jiffies;
7488 printk(KERN_ERR "BUG: sleeping function called from invalid"
7489 " context at %s:%d\n", file, line);
7490 printk("in_atomic():%d, irqs_disabled():%d\n",
7491 in_atomic(), irqs_disabled());
7492 debug_show_held_locks(current);
7493 if (irqs_disabled())
7494 print_irqtrace_events(current);
7495 dump_stack();
7497 #endif
7499 EXPORT_SYMBOL(__might_sleep);
7500 #endif
7502 #ifdef CONFIG_MAGIC_SYSRQ
7503 static void normalize_task(struct rq *rq, struct task_struct *p)
7505 int on_rq;
7506 update_rq_clock(rq);
7507 on_rq = p->se.on_rq;
7508 if (on_rq)
7509 deactivate_task(rq, p, 0);
7510 __setscheduler(rq, p, SCHED_NORMAL, 0);
7511 if (on_rq) {
7512 activate_task(rq, p, 0);
7513 resched_task(rq->curr);
7517 void normalize_rt_tasks(void)
7519 struct task_struct *g, *p;
7520 unsigned long flags;
7521 struct rq *rq;
7523 read_lock_irqsave(&tasklist_lock, flags);
7524 do_each_thread(g, p) {
7526 * Only normalize user tasks:
7528 if (!p->mm)
7529 continue;
7531 p->se.exec_start = 0;
7532 #ifdef CONFIG_SCHEDSTATS
7533 p->se.wait_start = 0;
7534 p->se.sleep_start = 0;
7535 p->se.block_start = 0;
7536 #endif
7537 task_rq(p)->clock = 0;
7539 if (!rt_task(p)) {
7541 * Renice negative nice level userspace
7542 * tasks back to 0:
7544 if (TASK_NICE(p) < 0 && p->mm)
7545 set_user_nice(p, 0);
7546 continue;
7549 spin_lock(&p->pi_lock);
7550 rq = __task_rq_lock(p);
7552 normalize_task(rq, p);
7554 __task_rq_unlock(rq);
7555 spin_unlock(&p->pi_lock);
7556 } while_each_thread(g, p);
7558 read_unlock_irqrestore(&tasklist_lock, flags);
7561 #endif /* CONFIG_MAGIC_SYSRQ */
7563 #ifdef CONFIG_IA64
7565 * These functions are only useful for the IA64 MCA handling.
7567 * They can only be called when the whole system has been
7568 * stopped - every CPU needs to be quiescent, and no scheduling
7569 * activity can take place. Using them for anything else would
7570 * be a serious bug, and as a result, they aren't even visible
7571 * under any other configuration.
7575 * curr_task - return the current task for a given cpu.
7576 * @cpu: the processor in question.
7578 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7580 struct task_struct *curr_task(int cpu)
7582 return cpu_curr(cpu);
7586 * set_curr_task - set the current task for a given cpu.
7587 * @cpu: the processor in question.
7588 * @p: the task pointer to set.
7590 * Description: This function must only be used when non-maskable interrupts
7591 * are serviced on a separate stack. It allows the architecture to switch the
7592 * notion of the current task on a cpu in a non-blocking manner. This function
7593 * must be called with all CPU's synchronized, and interrupts disabled, the
7594 * and caller must save the original value of the current task (see
7595 * curr_task() above) and restore that value before reenabling interrupts and
7596 * re-starting the system.
7598 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7600 void set_curr_task(int cpu, struct task_struct *p)
7602 cpu_curr(cpu) = p;
7605 #endif
7607 #ifdef CONFIG_GROUP_SCHED
7609 <<<<<<< HEAD:kernel/sched.c
7610 #if defined CONFIG_FAIR_GROUP_SCHED && defined CONFIG_SMP
7612 * distribute shares of all task groups among their schedulable entities,
7613 * to reflect load distribution across cpus.
7615 static int rebalance_shares(struct sched_domain *sd, int this_cpu)
7617 struct cfs_rq *cfs_rq;
7618 struct rq *rq = cpu_rq(this_cpu);
7619 cpumask_t sdspan = sd->span;
7620 int balanced = 1;
7622 /* Walk thr' all the task groups that we have */
7623 for_each_leaf_cfs_rq(rq, cfs_rq) {
7624 int i;
7625 unsigned long total_load = 0, total_shares;
7626 struct task_group *tg = cfs_rq->tg;
7628 /* Gather total task load of this group across cpus */
7629 for_each_cpu_mask(i, sdspan)
7630 total_load += tg->cfs_rq[i]->load.weight;
7632 /* Nothing to do if this group has no load */
7633 if (!total_load)
7634 continue;
7637 * tg->shares represents the number of cpu shares the task group
7638 * is eligible to hold on a single cpu. On N cpus, it is
7639 * eligible to hold (N * tg->shares) number of cpu shares.
7641 total_shares = tg->shares * cpus_weight(sdspan);
7644 * redistribute total_shares across cpus as per the task load
7645 * distribution.
7647 for_each_cpu_mask(i, sdspan) {
7648 unsigned long local_load, local_shares;
7650 local_load = tg->cfs_rq[i]->load.weight;
7651 local_shares = (local_load * total_shares) / total_load;
7652 if (!local_shares)
7653 local_shares = MIN_GROUP_SHARES;
7654 if (local_shares == tg->se[i]->load.weight)
7655 continue;
7657 spin_lock_irq(&cpu_rq(i)->lock);
7658 set_se_shares(tg->se[i], local_shares);
7659 spin_unlock_irq(&cpu_rq(i)->lock);
7660 balanced = 0;
7664 return balanced;
7668 * How frequently should we rebalance_shares() across cpus?
7670 * The more frequently we rebalance shares, the more accurate is the fairness
7671 * of cpu bandwidth distribution between task groups. However higher frequency
7672 * also implies increased scheduling overhead.
7674 * sysctl_sched_min_bal_int_shares represents the minimum interval between
7675 * consecutive calls to rebalance_shares() in the same sched domain.
7677 * sysctl_sched_max_bal_int_shares represents the maximum interval between
7678 * consecutive calls to rebalance_shares() in the same sched domain.
7680 * These settings allows for the appropriate trade-off between accuracy of
7681 * fairness and the associated overhead.
7685 /* default: 8ms, units: milliseconds */
7686 const_debug unsigned int sysctl_sched_min_bal_int_shares = 8;
7688 /* default: 128ms, units: milliseconds */
7689 const_debug unsigned int sysctl_sched_max_bal_int_shares = 128;
7691 /* kernel thread that runs rebalance_shares() periodically */
7692 static int load_balance_monitor(void *unused)
7694 unsigned int timeout = sysctl_sched_min_bal_int_shares;
7695 struct sched_param schedparm;
7696 int ret;
7699 * We don't want this thread's execution to be limited by the shares
7700 * assigned to default group (init_task_group). Hence make it run
7701 * as a SCHED_RR RT task at the lowest priority.
7703 schedparm.sched_priority = 1;
7704 ret = sched_setscheduler(current, SCHED_RR, &schedparm);
7705 if (ret)
7706 printk(KERN_ERR "Couldn't set SCHED_RR policy for load balance"
7707 " monitor thread (error = %d) \n", ret);
7709 while (!kthread_should_stop()) {
7710 int i, cpu, balanced = 1;
7712 /* Prevent cpus going down or coming up */
7713 get_online_cpus();
7714 /* lockout changes to doms_cur[] array */
7715 lock_doms_cur();
7717 * Enter a rcu read-side critical section to safely walk rq->sd
7718 * chain on various cpus and to walk task group list
7719 * (rq->leaf_cfs_rq_list) in rebalance_shares().
7721 rcu_read_lock();
7723 for (i = 0; i < ndoms_cur; i++) {
7724 cpumask_t cpumap = doms_cur[i];
7725 struct sched_domain *sd = NULL, *sd_prev = NULL;
7727 cpu = first_cpu(cpumap);
7729 /* Find the highest domain at which to balance shares */
7730 for_each_domain(cpu, sd) {
7731 if (!(sd->flags & SD_LOAD_BALANCE))
7732 continue;
7733 sd_prev = sd;
7736 sd = sd_prev;
7737 /* sd == NULL? No load balance reqd in this domain */
7738 if (!sd)
7739 continue;
7741 balanced &= rebalance_shares(sd, cpu);
7744 rcu_read_unlock();
7746 unlock_doms_cur();
7747 put_online_cpus();
7749 if (!balanced)
7750 timeout = sysctl_sched_min_bal_int_shares;
7751 else if (timeout < sysctl_sched_max_bal_int_shares)
7752 timeout *= 2;
7754 msleep_interruptible(timeout);
7757 return 0;
7759 #endif /* CONFIG_SMP */
7761 =======
7762 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
7763 #ifdef CONFIG_FAIR_GROUP_SCHED
7764 static void free_fair_sched_group(struct task_group *tg)
7766 int i;
7768 for_each_possible_cpu(i) {
7769 if (tg->cfs_rq)
7770 kfree(tg->cfs_rq[i]);
7771 if (tg->se)
7772 kfree(tg->se[i]);
7775 kfree(tg->cfs_rq);
7776 kfree(tg->se);
7779 static int alloc_fair_sched_group(struct task_group *tg)
7781 struct cfs_rq *cfs_rq;
7782 struct sched_entity *se;
7783 struct rq *rq;
7784 int i;
7786 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
7787 if (!tg->cfs_rq)
7788 goto err;
7789 tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
7790 if (!tg->se)
7791 goto err;
7793 tg->shares = NICE_0_LOAD;
7795 for_each_possible_cpu(i) {
7796 rq = cpu_rq(i);
7798 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
7799 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7800 if (!cfs_rq)
7801 goto err;
7803 se = kmalloc_node(sizeof(struct sched_entity),
7804 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7805 if (!se)
7806 goto err;
7808 init_tg_cfs_entry(rq, tg, cfs_rq, se, i, 0);
7811 return 1;
7813 err:
7814 return 0;
7817 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7819 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
7820 &cpu_rq(cpu)->leaf_cfs_rq_list);
7823 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7825 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
7827 #else
7828 static inline void free_fair_sched_group(struct task_group *tg)
7832 static inline int alloc_fair_sched_group(struct task_group *tg)
7834 return 1;
7837 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7841 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7844 #endif
7846 #ifdef CONFIG_RT_GROUP_SCHED
7847 static void free_rt_sched_group(struct task_group *tg)
7849 int i;
7851 for_each_possible_cpu(i) {
7852 if (tg->rt_rq)
7853 kfree(tg->rt_rq[i]);
7854 if (tg->rt_se)
7855 kfree(tg->rt_se[i]);
7858 kfree(tg->rt_rq);
7859 kfree(tg->rt_se);
7862 static int alloc_rt_sched_group(struct task_group *tg)
7864 struct rt_rq *rt_rq;
7865 struct sched_rt_entity *rt_se;
7866 struct rq *rq;
7867 int i;
7869 tg->rt_rq = kzalloc(sizeof(rt_rq) * NR_CPUS, GFP_KERNEL);
7870 if (!tg->rt_rq)
7871 goto err;
7872 tg->rt_se = kzalloc(sizeof(rt_se) * NR_CPUS, GFP_KERNEL);
7873 if (!tg->rt_se)
7874 goto err;
7876 tg->rt_runtime = 0;
7878 for_each_possible_cpu(i) {
7879 rq = cpu_rq(i);
7881 rt_rq = kmalloc_node(sizeof(struct rt_rq),
7882 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7883 if (!rt_rq)
7884 goto err;
7886 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
7887 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7888 if (!rt_se)
7889 goto err;
7891 init_tg_rt_entry(rq, tg, rt_rq, rt_se, i, 0);
7894 return 1;
7896 err:
7897 return 0;
7900 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7902 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
7903 &cpu_rq(cpu)->leaf_rt_rq_list);
7906 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7908 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
7910 #else
7911 static inline void free_rt_sched_group(struct task_group *tg)
7915 static inline int alloc_rt_sched_group(struct task_group *tg)
7917 return 1;
7920 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7924 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7927 #endif
7929 static void free_sched_group(struct task_group *tg)
7931 free_fair_sched_group(tg);
7932 free_rt_sched_group(tg);
7933 kfree(tg);
7936 /* allocate runqueue etc for a new task group */
7937 struct task_group *sched_create_group(void)
7939 struct task_group *tg;
7940 unsigned long flags;
7941 int i;
7943 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7944 if (!tg)
7945 return ERR_PTR(-ENOMEM);
7947 if (!alloc_fair_sched_group(tg))
7948 goto err;
7950 if (!alloc_rt_sched_group(tg))
7951 goto err;
7953 spin_lock_irqsave(&task_group_lock, flags);
7954 for_each_possible_cpu(i) {
7955 register_fair_sched_group(tg, i);
7956 register_rt_sched_group(tg, i);
7958 list_add_rcu(&tg->list, &task_groups);
7959 spin_unlock_irqrestore(&task_group_lock, flags);
7961 return tg;
7963 err:
7964 free_sched_group(tg);
7965 return ERR_PTR(-ENOMEM);
7968 /* rcu callback to free various structures associated with a task group */
7969 static void free_sched_group_rcu(struct rcu_head *rhp)
7971 /* now it should be safe to free those cfs_rqs */
7972 free_sched_group(container_of(rhp, struct task_group, rcu));
7975 /* Destroy runqueue etc associated with a task group */
7976 void sched_destroy_group(struct task_group *tg)
7978 unsigned long flags;
7979 int i;
7981 spin_lock_irqsave(&task_group_lock, flags);
7982 for_each_possible_cpu(i) {
7983 unregister_fair_sched_group(tg, i);
7984 unregister_rt_sched_group(tg, i);
7986 list_del_rcu(&tg->list);
7987 spin_unlock_irqrestore(&task_group_lock, flags);
7989 /* wait for possible concurrent references to cfs_rqs complete */
7990 call_rcu(&tg->rcu, free_sched_group_rcu);
7993 /* change task's runqueue when it moves between groups.
7994 * The caller of this function should have put the task in its new group
7995 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7996 * reflect its new group.
7998 void sched_move_task(struct task_struct *tsk)
8000 int on_rq, running;
8001 unsigned long flags;
8002 struct rq *rq;
8004 rq = task_rq_lock(tsk, &flags);
8006 update_rq_clock(rq);
8008 running = task_current(rq, tsk);
8009 on_rq = tsk->se.on_rq;
8011 <<<<<<< HEAD:kernel/sched.c
8012 if (on_rq) {
8013 =======
8014 if (on_rq)
8015 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8016 dequeue_task(rq, tsk, 0);
8017 <<<<<<< HEAD:kernel/sched.c
8018 if (unlikely(running))
8019 tsk->sched_class->put_prev_task(rq, tsk);
8021 =======
8022 if (unlikely(running))
8023 tsk->sched_class->put_prev_task(rq, tsk);
8024 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8026 set_task_rq(tsk, task_cpu(tsk));
8028 <<<<<<< HEAD:kernel/sched.c
8029 if (on_rq) {
8030 if (unlikely(running))
8031 tsk->sched_class->set_curr_task(rq);
8032 =======
8033 #ifdef CONFIG_FAIR_GROUP_SCHED
8034 if (tsk->sched_class->moved_group)
8035 tsk->sched_class->moved_group(tsk);
8036 #endif
8038 if (unlikely(running))
8039 tsk->sched_class->set_curr_task(rq);
8040 if (on_rq)
8041 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8042 enqueue_task(rq, tsk, 0);
8043 <<<<<<< HEAD:kernel/sched.c
8045 =======
8046 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8048 task_rq_unlock(rq, &flags);
8051 #ifdef CONFIG_FAIR_GROUP_SCHED
8052 <<<<<<< HEAD:kernel/sched.c
8053 /* rq->lock to be locked by caller */
8054 =======
8055 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8056 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8058 struct cfs_rq *cfs_rq = se->cfs_rq;
8059 struct rq *rq = cfs_rq->rq;
8060 int on_rq;
8062 <<<<<<< HEAD:kernel/sched.c
8063 if (!shares)
8064 shares = MIN_GROUP_SHARES;
8065 =======
8066 spin_lock_irq(&rq->lock);
8067 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8069 on_rq = se->on_rq;
8070 <<<<<<< HEAD:kernel/sched.c
8071 if (on_rq) {
8072 =======
8073 if (on_rq)
8074 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8075 dequeue_entity(cfs_rq, se, 0);
8076 <<<<<<< HEAD:kernel/sched.c
8077 dec_cpu_load(rq, se->load.weight);
8079 =======
8080 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8082 se->load.weight = shares;
8083 se->load.inv_weight = div64_64((1ULL<<32), shares);
8085 <<<<<<< HEAD:kernel/sched.c
8086 if (on_rq) {
8087 =======
8088 if (on_rq)
8089 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8090 enqueue_entity(cfs_rq, se, 0);
8091 <<<<<<< HEAD:kernel/sched.c
8092 inc_cpu_load(rq, se->load.weight);
8094 =======
8096 spin_unlock_irq(&rq->lock);
8097 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8100 static DEFINE_MUTEX(shares_mutex);
8102 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8104 int i;
8105 unsigned long flags;
8107 <<<<<<< HEAD:kernel/sched.c
8108 =======
8110 * A weight of 0 or 1 can cause arithmetics problems.
8111 * (The default weight is 1024 - so there's no practical
8112 * limitation from this.)
8114 if (shares < 2)
8115 shares = 2;
8117 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8118 mutex_lock(&shares_mutex);
8119 if (tg->shares == shares)
8120 goto done;
8122 <<<<<<< HEAD:kernel/sched.c
8123 if (shares < MIN_GROUP_SHARES)
8124 shares = MIN_GROUP_SHARES;
8127 * Prevent any load balance activity (rebalance_shares,
8128 * load_balance_fair) from referring to this group first,
8129 * by taking it off the rq->leaf_cfs_rq_list on each cpu.
8131 =======
8132 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8133 spin_lock_irqsave(&task_group_lock, flags);
8134 for_each_possible_cpu(i)
8135 unregister_fair_sched_group(tg, i);
8136 spin_unlock_irqrestore(&task_group_lock, flags);
8138 /* wait for any ongoing reference to this group to finish */
8139 synchronize_sched();
8142 * Now we are free to modify the group's share on each cpu
8143 * w/o tripping rebalance_share or load_balance_fair.
8145 tg->shares = shares;
8146 <<<<<<< HEAD:kernel/sched.c
8147 for_each_possible_cpu(i) {
8148 spin_lock_irq(&cpu_rq(i)->lock);
8149 =======
8150 for_each_possible_cpu(i)
8151 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8152 set_se_shares(tg->se[i], shares);
8153 <<<<<<< HEAD:kernel/sched.c
8154 spin_unlock_irq(&cpu_rq(i)->lock);
8156 =======
8157 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8160 * Enable load balance activity on this group, by inserting it back on
8161 * each cpu's rq->leaf_cfs_rq_list.
8163 spin_lock_irqsave(&task_group_lock, flags);
8164 for_each_possible_cpu(i)
8165 register_fair_sched_group(tg, i);
8166 spin_unlock_irqrestore(&task_group_lock, flags);
8167 done:
8168 mutex_unlock(&shares_mutex);
8169 return 0;
8172 unsigned long sched_group_shares(struct task_group *tg)
8174 return tg->shares;
8176 #endif
8178 #ifdef CONFIG_RT_GROUP_SCHED
8180 * Ensure that the real time constraints are schedulable.
8182 static DEFINE_MUTEX(rt_constraints_mutex);
8184 static unsigned long to_ratio(u64 period, u64 runtime)
8186 if (runtime == RUNTIME_INF)
8187 return 1ULL << 16;
8189 <<<<<<< HEAD:kernel/sched.c
8190 runtime *= (1ULL << 16);
8191 div64_64(runtime, period);
8192 return runtime;
8193 =======
8194 return div64_64(runtime << 16, period);
8195 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8198 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8200 struct task_group *tgi;
8201 unsigned long total = 0;
8202 unsigned long global_ratio =
8203 to_ratio(sysctl_sched_rt_period,
8204 sysctl_sched_rt_runtime < 0 ?
8205 RUNTIME_INF : sysctl_sched_rt_runtime);
8207 rcu_read_lock();
8208 list_for_each_entry_rcu(tgi, &task_groups, list) {
8209 if (tgi == tg)
8210 continue;
8212 total += to_ratio(period, tgi->rt_runtime);
8214 rcu_read_unlock();
8216 return total + to_ratio(period, runtime) < global_ratio;
8219 <<<<<<< HEAD:kernel/sched.c
8220 =======
8221 /* Must be called with tasklist_lock held */
8222 static inline int tg_has_rt_tasks(struct task_group *tg)
8224 struct task_struct *g, *p;
8225 do_each_thread(g, p) {
8226 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8227 return 1;
8228 } while_each_thread(g, p);
8229 return 0;
8232 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8233 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8235 u64 rt_runtime, rt_period;
8236 int err = 0;
8238 <<<<<<< HEAD:kernel/sched.c
8239 rt_period = sysctl_sched_rt_period * NSEC_PER_USEC;
8240 =======
8241 rt_period = (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
8242 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8243 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8244 if (rt_runtime_us == -1)
8245 <<<<<<< HEAD:kernel/sched.c
8246 rt_runtime = rt_period;
8247 =======
8248 rt_runtime = RUNTIME_INF;
8249 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8251 mutex_lock(&rt_constraints_mutex);
8252 <<<<<<< HEAD:kernel/sched.c
8253 =======
8254 read_lock(&tasklist_lock);
8255 if (rt_runtime_us == 0 && tg_has_rt_tasks(tg)) {
8256 err = -EBUSY;
8257 goto unlock;
8259 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8260 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8261 err = -EINVAL;
8262 goto unlock;
8264 <<<<<<< HEAD:kernel/sched.c
8265 if (rt_runtime_us == -1)
8266 rt_runtime = RUNTIME_INF;
8267 =======
8268 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8269 tg->rt_runtime = rt_runtime;
8270 unlock:
8271 <<<<<<< HEAD:kernel/sched.c
8272 =======
8273 read_unlock(&tasklist_lock);
8274 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:kernel/sched.c
8275 mutex_unlock(&rt_constraints_mutex);
8277 return err;
8280 long sched_group_rt_runtime(struct task_group *tg)
8282 u64 rt_runtime_us;
8284 if (tg->rt_runtime == RUNTIME_INF)
8285 return -1;
8287 rt_runtime_us = tg->rt_runtime;
8288 do_div(rt_runtime_us, NSEC_PER_USEC);
8289 return rt_runtime_us;
8291 #endif
8292 #endif /* CONFIG_GROUP_SCHED */
8294 #ifdef CONFIG_CGROUP_SCHED
8296 /* return corresponding task_group object of a cgroup */
8297 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8299 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8300 struct task_group, css);
8303 static struct cgroup_subsys_state *
8304 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8306 struct task_group *tg;
8308 if (!cgrp->parent) {
8309 /* This is early initialization for the top cgroup */
8310 init_task_group.css.cgroup = cgrp;
8311 return &init_task_group.css;
8314 /* we support only 1-level deep hierarchical scheduler atm */
8315 if (cgrp->parent->parent)
8316 return ERR_PTR(-EINVAL);
8318 tg = sched_create_group();
8319 if (IS_ERR(tg))
8320 return ERR_PTR(-ENOMEM);
8322 /* Bind the cgroup to task_group object we just created */
8323 tg->css.cgroup = cgrp;
8325 return &tg->css;
8328 static void
8329 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8331 struct task_group *tg = cgroup_tg(cgrp);
8333 sched_destroy_group(tg);
8336 static int
8337 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8338 struct task_struct *tsk)
8340 #ifdef CONFIG_RT_GROUP_SCHED
8341 /* Don't accept realtime tasks when there is no way for them to run */
8342 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_runtime == 0)
8343 return -EINVAL;
8344 #else
8345 /* We don't support RT-tasks being in separate groups */
8346 if (tsk->sched_class != &fair_sched_class)
8347 return -EINVAL;
8348 #endif
8350 return 0;
8353 static void
8354 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8355 struct cgroup *old_cont, struct task_struct *tsk)
8357 sched_move_task(tsk);
8360 #ifdef CONFIG_FAIR_GROUP_SCHED
8361 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8362 u64 shareval)
8364 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8367 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
8369 struct task_group *tg = cgroup_tg(cgrp);
8371 return (u64) tg->shares;
8373 #endif
8375 #ifdef CONFIG_RT_GROUP_SCHED
8376 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8377 struct file *file,
8378 const char __user *userbuf,
8379 size_t nbytes, loff_t *unused_ppos)
8381 char buffer[64];
8382 int retval = 0;
8383 s64 val;
8384 char *end;
8386 if (!nbytes)
8387 return -EINVAL;
8388 if (nbytes >= sizeof(buffer))
8389 return -E2BIG;
8390 if (copy_from_user(buffer, userbuf, nbytes))
8391 return -EFAULT;
8393 buffer[nbytes] = 0; /* nul-terminate */
8395 /* strip newline if necessary */
8396 if (nbytes && (buffer[nbytes-1] == '\n'))
8397 buffer[nbytes-1] = 0;
8398 val = simple_strtoll(buffer, &end, 0);
8399 if (*end)
8400 return -EINVAL;
8402 /* Pass to subsystem */
8403 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8404 if (!retval)
8405 retval = nbytes;
8406 return retval;
8409 static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
8410 struct file *file,
8411 char __user *buf, size_t nbytes,
8412 loff_t *ppos)
8414 char tmp[64];
8415 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
8416 int len = sprintf(tmp, "%ld\n", val);
8418 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
8420 #endif
8422 static struct cftype cpu_files[] = {
8423 #ifdef CONFIG_FAIR_GROUP_SCHED
8425 .name = "shares",
8426 .read_uint = cpu_shares_read_uint,
8427 .write_uint = cpu_shares_write_uint,
8429 #endif
8430 #ifdef CONFIG_RT_GROUP_SCHED
8432 .name = "rt_runtime_us",
8433 .read = cpu_rt_runtime_read,
8434 .write = cpu_rt_runtime_write,
8436 #endif
8439 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8441 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8444 struct cgroup_subsys cpu_cgroup_subsys = {
8445 .name = "cpu",
8446 .create = cpu_cgroup_create,
8447 .destroy = cpu_cgroup_destroy,
8448 .can_attach = cpu_cgroup_can_attach,
8449 .attach = cpu_cgroup_attach,
8450 .populate = cpu_cgroup_populate,
8451 .subsys_id = cpu_cgroup_subsys_id,
8452 .early_init = 1,
8455 #endif /* CONFIG_CGROUP_SCHED */
8457 #ifdef CONFIG_CGROUP_CPUACCT
8460 * CPU accounting code for task groups.
8462 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8463 * (balbir@in.ibm.com).
8466 /* track cpu usage of a group of tasks */
8467 struct cpuacct {
8468 struct cgroup_subsys_state css;
8469 /* cpuusage holds pointer to a u64-type object on every cpu */
8470 u64 *cpuusage;
8473 struct cgroup_subsys cpuacct_subsys;
8475 /* return cpu accounting group corresponding to this container */
8476 static inline struct cpuacct *cgroup_ca(struct cgroup *cont)
8478 return container_of(cgroup_subsys_state(cont, cpuacct_subsys_id),
8479 struct cpuacct, css);
8482 /* return cpu accounting group to which this task belongs */
8483 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8485 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8486 struct cpuacct, css);
8489 /* create a new cpu accounting group */
8490 static struct cgroup_subsys_state *cpuacct_create(
8491 struct cgroup_subsys *ss, struct cgroup *cont)
8493 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8495 if (!ca)
8496 return ERR_PTR(-ENOMEM);
8498 ca->cpuusage = alloc_percpu(u64);
8499 if (!ca->cpuusage) {
8500 kfree(ca);
8501 return ERR_PTR(-ENOMEM);
8504 return &ca->css;
8507 /* destroy an existing cpu accounting group */
8508 static void
8509 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
8511 struct cpuacct *ca = cgroup_ca(cont);
8513 free_percpu(ca->cpuusage);
8514 kfree(ca);
8517 /* return total cpu usage (in nanoseconds) of a group */
8518 static u64 cpuusage_read(struct cgroup *cont, struct cftype *cft)
8520 struct cpuacct *ca = cgroup_ca(cont);
8521 u64 totalcpuusage = 0;
8522 int i;
8524 for_each_possible_cpu(i) {
8525 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8528 * Take rq->lock to make 64-bit addition safe on 32-bit
8529 * platforms.
8531 spin_lock_irq(&cpu_rq(i)->lock);
8532 totalcpuusage += *cpuusage;
8533 spin_unlock_irq(&cpu_rq(i)->lock);
8536 return totalcpuusage;
8539 static struct cftype files[] = {
8541 .name = "usage",
8542 .read_uint = cpuusage_read,
8546 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8548 return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
8552 * charge this task's execution time to its accounting group.
8554 * called with rq->lock held.
8556 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8558 struct cpuacct *ca;
8560 if (!cpuacct_subsys.active)
8561 return;
8563 ca = task_ca(tsk);
8564 if (ca) {
8565 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
8567 *cpuusage += cputime;
8571 struct cgroup_subsys cpuacct_subsys = {
8572 .name = "cpuacct",
8573 .create = cpuacct_create,
8574 .destroy = cpuacct_destroy,
8575 .populate = cpuacct_populate,
8576 .subsys_id = cpuacct_subsys_id,
8578 #endif /* CONFIG_CGROUP_CPUACCT */