sched, cpuset: customize sched domains, docs
[linux-2.6/mini2440.git] / kernel / sched.c
blob475e3fcab738b15d5e2953e2a5fc83b7bcc594de
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>
69 #include <linux/tick.h>
70 #include <linux/bootmem.h>
72 #include <asm/tlb.h>
73 #include <asm/irq_regs.h>
76 * Scheduler clock - returns current time in nanosec units.
77 * This is default implementation.
78 * Architectures and sub-architectures can override this.
80 unsigned long long __attribute__((weak)) sched_clock(void)
82 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
86 * Convert user-nice values [ -20 ... 0 ... 19 ]
87 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
88 * and back.
90 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
91 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
92 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
95 * 'User priority' is the nice value converted to something we
96 * can work with better when scaling various scheduler parameters,
97 * it's a [ 0 ... 39 ] range.
99 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
100 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
101 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
104 * Helpers for converting nanosecond timing to jiffy resolution
106 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
108 #define NICE_0_LOAD SCHED_LOAD_SCALE
109 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
112 * These are the 'tuning knobs' of the scheduler:
114 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
115 * Timeslices get refilled after they expire.
117 #define DEF_TIMESLICE (100 * HZ / 1000)
120 * single value that denotes runtime == period, ie unlimited time.
122 #define RUNTIME_INF ((u64)~0ULL)
124 #ifdef CONFIG_SMP
126 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
127 * Since cpu_power is a 'constant', we can use a reciprocal divide.
129 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
131 return reciprocal_divide(load, sg->reciprocal_cpu_power);
135 * Each time a sched group cpu_power is changed,
136 * we must compute its reciprocal value
138 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
140 sg->__cpu_power += val;
141 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
143 #endif
145 static inline int rt_policy(int policy)
147 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
148 return 1;
149 return 0;
152 static inline int task_has_rt_policy(struct task_struct *p)
154 return rt_policy(p->policy);
158 * This is the priority-queue data structure of the RT scheduling class:
160 struct rt_prio_array {
161 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
162 struct list_head queue[MAX_RT_PRIO];
165 struct rt_bandwidth {
166 /* nests inside the rq lock: */
167 spinlock_t rt_runtime_lock;
168 ktime_t rt_period;
169 u64 rt_runtime;
170 struct hrtimer rt_period_timer;
173 static struct rt_bandwidth def_rt_bandwidth;
175 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
177 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
179 struct rt_bandwidth *rt_b =
180 container_of(timer, struct rt_bandwidth, rt_period_timer);
181 ktime_t now;
182 int overrun;
183 int idle = 0;
185 for (;;) {
186 now = hrtimer_cb_get_time(timer);
187 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
189 if (!overrun)
190 break;
192 idle = do_sched_rt_period_timer(rt_b, overrun);
195 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
198 static
199 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
201 rt_b->rt_period = ns_to_ktime(period);
202 rt_b->rt_runtime = runtime;
204 spin_lock_init(&rt_b->rt_runtime_lock);
206 hrtimer_init(&rt_b->rt_period_timer,
207 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
208 rt_b->rt_period_timer.function = sched_rt_period_timer;
209 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
212 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
214 ktime_t now;
216 if (rt_b->rt_runtime == RUNTIME_INF)
217 return;
219 if (hrtimer_active(&rt_b->rt_period_timer))
220 return;
222 spin_lock(&rt_b->rt_runtime_lock);
223 for (;;) {
224 if (hrtimer_active(&rt_b->rt_period_timer))
225 break;
227 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
228 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
229 hrtimer_start(&rt_b->rt_period_timer,
230 rt_b->rt_period_timer.expires,
231 HRTIMER_MODE_ABS);
233 spin_unlock(&rt_b->rt_runtime_lock);
236 #ifdef CONFIG_RT_GROUP_SCHED
237 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
239 hrtimer_cancel(&rt_b->rt_period_timer);
241 #endif
243 #ifdef CONFIG_GROUP_SCHED
245 #include <linux/cgroup.h>
247 struct cfs_rq;
249 static LIST_HEAD(task_groups);
251 /* task group related information */
252 struct task_group {
253 #ifdef CONFIG_CGROUP_SCHED
254 struct cgroup_subsys_state css;
255 #endif
257 #ifdef CONFIG_FAIR_GROUP_SCHED
258 /* schedulable entities of this group on each cpu */
259 struct sched_entity **se;
260 /* runqueue "owned" by this group on each cpu */
261 struct cfs_rq **cfs_rq;
262 unsigned long shares;
263 #endif
265 #ifdef CONFIG_RT_GROUP_SCHED
266 struct sched_rt_entity **rt_se;
267 struct rt_rq **rt_rq;
269 struct rt_bandwidth rt_bandwidth;
270 #endif
272 struct rcu_head rcu;
273 struct list_head list;
275 struct task_group *parent;
276 struct list_head siblings;
277 struct list_head children;
280 #ifdef CONFIG_USER_SCHED
283 * Root task group.
284 * Every UID task group (including init_task_group aka UID-0) will
285 * be a child to this group.
287 struct task_group root_task_group;
289 #ifdef CONFIG_FAIR_GROUP_SCHED
290 /* Default task group's sched entity on each cpu */
291 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
292 /* Default task group's cfs_rq on each cpu */
293 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
294 #endif
296 #ifdef CONFIG_RT_GROUP_SCHED
297 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
298 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
299 #endif
300 #else
301 #define root_task_group init_task_group
302 #endif
304 /* task_group_lock serializes add/remove of task groups and also changes to
305 * a task group's cpu shares.
307 static DEFINE_SPINLOCK(task_group_lock);
309 /* doms_cur_mutex serializes access to doms_cur[] array */
310 static DEFINE_MUTEX(doms_cur_mutex);
312 #ifdef CONFIG_FAIR_GROUP_SCHED
313 #ifdef CONFIG_USER_SCHED
314 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
315 #else
316 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
317 #endif
319 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
320 #endif
322 /* Default task group.
323 * Every task in system belong to this group at bootup.
325 struct task_group init_task_group;
327 /* return group to which a task belongs */
328 static inline struct task_group *task_group(struct task_struct *p)
330 struct task_group *tg;
332 #ifdef CONFIG_USER_SCHED
333 tg = p->user->tg;
334 #elif defined(CONFIG_CGROUP_SCHED)
335 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
336 struct task_group, css);
337 #else
338 tg = &init_task_group;
339 #endif
340 return tg;
343 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
344 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
346 #ifdef CONFIG_FAIR_GROUP_SCHED
347 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
348 p->se.parent = task_group(p)->se[cpu];
349 #endif
351 #ifdef CONFIG_RT_GROUP_SCHED
352 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
353 p->rt.parent = task_group(p)->rt_se[cpu];
354 #endif
357 static inline void lock_doms_cur(void)
359 mutex_lock(&doms_cur_mutex);
362 static inline void unlock_doms_cur(void)
364 mutex_unlock(&doms_cur_mutex);
367 #else
369 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
370 static inline void lock_doms_cur(void) { }
371 static inline void unlock_doms_cur(void) { }
373 #endif /* CONFIG_GROUP_SCHED */
375 /* CFS-related fields in a runqueue */
376 struct cfs_rq {
377 struct load_weight load;
378 unsigned long nr_running;
380 u64 exec_clock;
381 u64 min_vruntime;
383 struct rb_root tasks_timeline;
384 struct rb_node *rb_leftmost;
385 struct rb_node *rb_load_balance_curr;
386 /* 'curr' points to currently running entity on this cfs_rq.
387 * It is set to NULL otherwise (i.e when none are currently running).
389 struct sched_entity *curr, *next;
391 unsigned long nr_spread_over;
393 #ifdef CONFIG_FAIR_GROUP_SCHED
394 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
397 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
398 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
399 * (like users, containers etc.)
401 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
402 * list is used during load balance.
404 struct list_head leaf_cfs_rq_list;
405 struct task_group *tg; /* group that "owns" this runqueue */
406 #endif
409 /* Real-Time classes' related field in a runqueue: */
410 struct rt_rq {
411 struct rt_prio_array active;
412 unsigned long rt_nr_running;
413 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
414 int highest_prio; /* highest queued rt task prio */
415 #endif
416 #ifdef CONFIG_SMP
417 unsigned long rt_nr_migratory;
418 int overloaded;
419 #endif
420 int rt_throttled;
421 u64 rt_time;
422 u64 rt_runtime;
423 /* Nests inside the rq lock: */
424 spinlock_t rt_runtime_lock;
426 #ifdef CONFIG_RT_GROUP_SCHED
427 unsigned long rt_nr_boosted;
429 struct rq *rq;
430 struct list_head leaf_rt_rq_list;
431 struct task_group *tg;
432 struct sched_rt_entity *rt_se;
433 #endif
436 #ifdef CONFIG_SMP
439 * We add the notion of a root-domain which will be used to define per-domain
440 * variables. Each exclusive cpuset essentially defines an island domain by
441 * fully partitioning the member cpus from any other cpuset. Whenever a new
442 * exclusive cpuset is created, we also create and attach a new root-domain
443 * object.
446 struct root_domain {
447 atomic_t refcount;
448 cpumask_t span;
449 cpumask_t online;
452 * The "RT overload" flag: it gets set if a CPU has more than
453 * one runnable RT task.
455 cpumask_t rto_mask;
456 atomic_t rto_count;
460 * By default the system creates a single root-domain with all cpus as
461 * members (mimicking the global state we have today).
463 static struct root_domain def_root_domain;
465 #endif
468 * This is the main, per-CPU runqueue data structure.
470 * Locking rule: those places that want to lock multiple runqueues
471 * (such as the load balancing or the thread migration code), lock
472 * acquire operations must be ordered by ascending &runqueue.
474 struct rq {
475 /* runqueue lock: */
476 spinlock_t lock;
479 * nr_running and cpu_load should be in the same cacheline because
480 * remote CPUs use both these fields when doing load calculation.
482 unsigned long nr_running;
483 #define CPU_LOAD_IDX_MAX 5
484 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
485 unsigned char idle_at_tick;
486 #ifdef CONFIG_NO_HZ
487 unsigned long last_tick_seen;
488 unsigned char in_nohz_recently;
489 #endif
490 /* capture load from *all* tasks on this cpu: */
491 struct load_weight load;
492 unsigned long nr_load_updates;
493 u64 nr_switches;
495 struct cfs_rq cfs;
496 struct rt_rq rt;
498 #ifdef CONFIG_FAIR_GROUP_SCHED
499 /* list of leaf cfs_rq on this cpu: */
500 struct list_head leaf_cfs_rq_list;
501 #endif
502 #ifdef CONFIG_RT_GROUP_SCHED
503 struct list_head leaf_rt_rq_list;
504 #endif
507 * This is part of a global counter where only the total sum
508 * over all CPUs matters. A task can increase this counter on
509 * one CPU and if it got migrated afterwards it may decrease
510 * it on another CPU. Always updated under the runqueue lock:
512 unsigned long nr_uninterruptible;
514 struct task_struct *curr, *idle;
515 unsigned long next_balance;
516 struct mm_struct *prev_mm;
518 u64 clock, prev_clock_raw;
519 s64 clock_max_delta;
521 unsigned int clock_warps, clock_overflows, clock_underflows;
522 u64 idle_clock;
523 unsigned int clock_deep_idle_events;
524 u64 tick_timestamp;
526 atomic_t nr_iowait;
528 #ifdef CONFIG_SMP
529 struct root_domain *rd;
530 struct sched_domain *sd;
532 /* For active balancing */
533 int active_balance;
534 int push_cpu;
535 /* cpu of this runqueue: */
536 int cpu;
538 struct task_struct *migration_thread;
539 struct list_head migration_queue;
540 #endif
542 #ifdef CONFIG_SCHED_HRTICK
543 unsigned long hrtick_flags;
544 ktime_t hrtick_expire;
545 struct hrtimer hrtick_timer;
546 #endif
548 #ifdef CONFIG_SCHEDSTATS
549 /* latency stats */
550 struct sched_info rq_sched_info;
552 /* sys_sched_yield() stats */
553 unsigned int yld_exp_empty;
554 unsigned int yld_act_empty;
555 unsigned int yld_both_empty;
556 unsigned int yld_count;
558 /* schedule() stats */
559 unsigned int sched_switch;
560 unsigned int sched_count;
561 unsigned int sched_goidle;
563 /* try_to_wake_up() stats */
564 unsigned int ttwu_count;
565 unsigned int ttwu_local;
567 /* BKL stats */
568 unsigned int bkl_count;
569 #endif
570 struct lock_class_key rq_lock_key;
573 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
575 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
577 rq->curr->sched_class->check_preempt_curr(rq, p);
580 static inline int cpu_of(struct rq *rq)
582 #ifdef CONFIG_SMP
583 return rq->cpu;
584 #else
585 return 0;
586 #endif
589 #ifdef CONFIG_NO_HZ
590 static inline bool nohz_on(int cpu)
592 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
595 static inline u64 max_skipped_ticks(struct rq *rq)
597 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
600 static inline void update_last_tick_seen(struct rq *rq)
602 rq->last_tick_seen = jiffies;
604 #else
605 static inline u64 max_skipped_ticks(struct rq *rq)
607 return 1;
610 static inline void update_last_tick_seen(struct rq *rq)
613 #endif
616 * Update the per-runqueue clock, as finegrained as the platform can give
617 * us, but without assuming monotonicity, etc.:
619 static void __update_rq_clock(struct rq *rq)
621 u64 prev_raw = rq->prev_clock_raw;
622 u64 now = sched_clock();
623 s64 delta = now - prev_raw;
624 u64 clock = rq->clock;
626 #ifdef CONFIG_SCHED_DEBUG
627 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
628 #endif
630 * Protect against sched_clock() occasionally going backwards:
632 if (unlikely(delta < 0)) {
633 clock++;
634 rq->clock_warps++;
635 } else {
637 * Catch too large forward jumps too:
639 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
640 u64 max_time = rq->tick_timestamp + max_jump;
642 if (unlikely(clock + delta > max_time)) {
643 if (clock < max_time)
644 clock = max_time;
645 else
646 clock++;
647 rq->clock_overflows++;
648 } else {
649 if (unlikely(delta > rq->clock_max_delta))
650 rq->clock_max_delta = delta;
651 clock += delta;
655 rq->prev_clock_raw = now;
656 rq->clock = clock;
659 static void update_rq_clock(struct rq *rq)
661 if (likely(smp_processor_id() == cpu_of(rq)))
662 __update_rq_clock(rq);
666 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
667 * See detach_destroy_domains: synchronize_sched for details.
669 * The domain tree of any CPU may only be accessed from within
670 * preempt-disabled sections.
672 #define for_each_domain(cpu, __sd) \
673 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
675 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
676 #define this_rq() (&__get_cpu_var(runqueues))
677 #define task_rq(p) cpu_rq(task_cpu(p))
678 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
681 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
683 #ifdef CONFIG_SCHED_DEBUG
684 # define const_debug __read_mostly
685 #else
686 # define const_debug static const
687 #endif
690 * Debugging: various feature bits
692 enum {
693 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
694 SCHED_FEAT_WAKEUP_PREEMPT = 2,
695 SCHED_FEAT_START_DEBIT = 4,
696 SCHED_FEAT_AFFINE_WAKEUPS = 8,
697 SCHED_FEAT_CACHE_HOT_BUDDY = 16,
698 SCHED_FEAT_SYNC_WAKEUPS = 32,
699 SCHED_FEAT_HRTICK = 64,
700 SCHED_FEAT_DOUBLE_TICK = 128,
701 SCHED_FEAT_NORMALIZED_SLEEPER = 256,
704 const_debug unsigned int sysctl_sched_features =
705 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
706 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
707 SCHED_FEAT_START_DEBIT * 1 |
708 SCHED_FEAT_AFFINE_WAKEUPS * 1 |
709 SCHED_FEAT_CACHE_HOT_BUDDY * 1 |
710 SCHED_FEAT_SYNC_WAKEUPS * 1 |
711 SCHED_FEAT_HRTICK * 1 |
712 SCHED_FEAT_DOUBLE_TICK * 0 |
713 SCHED_FEAT_NORMALIZED_SLEEPER * 1;
715 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
718 * Number of tasks to iterate in a single balance run.
719 * Limited because this is done with IRQs disabled.
721 const_debug unsigned int sysctl_sched_nr_migrate = 32;
724 * period over which we measure -rt task cpu usage in us.
725 * default: 1s
727 unsigned int sysctl_sched_rt_period = 1000000;
729 static __read_mostly int scheduler_running;
732 * part of the period that we allow rt tasks to run in us.
733 * default: 0.95s
735 int sysctl_sched_rt_runtime = 950000;
737 static inline u64 global_rt_period(void)
739 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
742 static inline u64 global_rt_runtime(void)
744 if (sysctl_sched_rt_period < 0)
745 return RUNTIME_INF;
747 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
750 static const unsigned long long time_sync_thresh = 100000;
752 static DEFINE_PER_CPU(unsigned long long, time_offset);
753 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
756 * Global lock which we take every now and then to synchronize
757 * the CPUs time. This method is not warp-safe, but it's good
758 * enough to synchronize slowly diverging time sources and thus
759 * it's good enough for tracing:
761 static DEFINE_SPINLOCK(time_sync_lock);
762 static unsigned long long prev_global_time;
764 static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
766 unsigned long flags;
768 spin_lock_irqsave(&time_sync_lock, flags);
770 if (time < prev_global_time) {
771 per_cpu(time_offset, cpu) += prev_global_time - time;
772 time = prev_global_time;
773 } else {
774 prev_global_time = time;
777 spin_unlock_irqrestore(&time_sync_lock, flags);
779 return time;
782 static unsigned long long __cpu_clock(int cpu)
784 unsigned long long now;
785 unsigned long flags;
786 struct rq *rq;
789 * Only call sched_clock() if the scheduler has already been
790 * initialized (some code might call cpu_clock() very early):
792 if (unlikely(!scheduler_running))
793 return 0;
795 local_irq_save(flags);
796 rq = cpu_rq(cpu);
797 update_rq_clock(rq);
798 now = rq->clock;
799 local_irq_restore(flags);
801 return now;
805 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
806 * clock constructed from sched_clock():
808 unsigned long long cpu_clock(int cpu)
810 unsigned long long prev_cpu_time, time, delta_time;
812 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
813 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
814 delta_time = time-prev_cpu_time;
816 if (unlikely(delta_time > time_sync_thresh))
817 time = __sync_cpu_clock(time, cpu);
819 return time;
821 EXPORT_SYMBOL_GPL(cpu_clock);
823 #ifndef prepare_arch_switch
824 # define prepare_arch_switch(next) do { } while (0)
825 #endif
826 #ifndef finish_arch_switch
827 # define finish_arch_switch(prev) do { } while (0)
828 #endif
830 static inline int task_current(struct rq *rq, struct task_struct *p)
832 return rq->curr == p;
835 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
836 static inline int task_running(struct rq *rq, struct task_struct *p)
838 return task_current(rq, p);
841 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
845 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
847 #ifdef CONFIG_DEBUG_SPINLOCK
848 /* this is a valid case when another task releases the spinlock */
849 rq->lock.owner = current;
850 #endif
852 * If we are tracking spinlock dependencies then we have to
853 * fix up the runqueue lock - which gets 'carried over' from
854 * prev into current:
856 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
858 spin_unlock_irq(&rq->lock);
861 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
862 static inline int task_running(struct rq *rq, struct task_struct *p)
864 #ifdef CONFIG_SMP
865 return p->oncpu;
866 #else
867 return task_current(rq, p);
868 #endif
871 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
873 #ifdef CONFIG_SMP
875 * We can optimise this out completely for !SMP, because the
876 * SMP rebalancing from interrupt is the only thing that cares
877 * here.
879 next->oncpu = 1;
880 #endif
881 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
882 spin_unlock_irq(&rq->lock);
883 #else
884 spin_unlock(&rq->lock);
885 #endif
888 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
890 #ifdef CONFIG_SMP
892 * After ->oncpu is cleared, the task can be moved to a different CPU.
893 * We must ensure this doesn't happen until the switch is completely
894 * finished.
896 smp_wmb();
897 prev->oncpu = 0;
898 #endif
899 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
900 local_irq_enable();
901 #endif
903 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
906 * __task_rq_lock - lock the runqueue a given task resides on.
907 * Must be called interrupts disabled.
909 static inline struct rq *__task_rq_lock(struct task_struct *p)
910 __acquires(rq->lock)
912 for (;;) {
913 struct rq *rq = task_rq(p);
914 spin_lock(&rq->lock);
915 if (likely(rq == task_rq(p)))
916 return rq;
917 spin_unlock(&rq->lock);
922 * task_rq_lock - lock the runqueue a given task resides on and disable
923 * interrupts. Note the ordering: we can safely lookup the task_rq without
924 * explicitly disabling preemption.
926 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
927 __acquires(rq->lock)
929 struct rq *rq;
931 for (;;) {
932 local_irq_save(*flags);
933 rq = task_rq(p);
934 spin_lock(&rq->lock);
935 if (likely(rq == task_rq(p)))
936 return rq;
937 spin_unlock_irqrestore(&rq->lock, *flags);
941 static void __task_rq_unlock(struct rq *rq)
942 __releases(rq->lock)
944 spin_unlock(&rq->lock);
947 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
948 __releases(rq->lock)
950 spin_unlock_irqrestore(&rq->lock, *flags);
954 * this_rq_lock - lock this runqueue and disable interrupts.
956 static struct rq *this_rq_lock(void)
957 __acquires(rq->lock)
959 struct rq *rq;
961 local_irq_disable();
962 rq = this_rq();
963 spin_lock(&rq->lock);
965 return rq;
969 * We are going deep-idle (irqs are disabled):
971 void sched_clock_idle_sleep_event(void)
973 struct rq *rq = cpu_rq(smp_processor_id());
975 spin_lock(&rq->lock);
976 __update_rq_clock(rq);
977 spin_unlock(&rq->lock);
978 rq->clock_deep_idle_events++;
980 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
983 * We just idled delta nanoseconds (called with irqs disabled):
985 void sched_clock_idle_wakeup_event(u64 delta_ns)
987 struct rq *rq = cpu_rq(smp_processor_id());
988 u64 now = sched_clock();
990 rq->idle_clock += delta_ns;
992 * Override the previous timestamp and ignore all
993 * sched_clock() deltas that occured while we idled,
994 * and use the PM-provided delta_ns to advance the
995 * rq clock:
997 spin_lock(&rq->lock);
998 rq->prev_clock_raw = now;
999 rq->clock += delta_ns;
1000 spin_unlock(&rq->lock);
1001 touch_softlockup_watchdog();
1003 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1005 static void __resched_task(struct task_struct *p, int tif_bit);
1007 static inline void resched_task(struct task_struct *p)
1009 __resched_task(p, TIF_NEED_RESCHED);
1012 #ifdef CONFIG_SCHED_HRTICK
1014 * Use HR-timers to deliver accurate preemption points.
1016 * Its all a bit involved since we cannot program an hrt while holding the
1017 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1018 * reschedule event.
1020 * When we get rescheduled we reprogram the hrtick_timer outside of the
1021 * rq->lock.
1023 static inline void resched_hrt(struct task_struct *p)
1025 __resched_task(p, TIF_HRTICK_RESCHED);
1028 static inline void resched_rq(struct rq *rq)
1030 unsigned long flags;
1032 spin_lock_irqsave(&rq->lock, flags);
1033 resched_task(rq->curr);
1034 spin_unlock_irqrestore(&rq->lock, flags);
1037 enum {
1038 HRTICK_SET, /* re-programm hrtick_timer */
1039 HRTICK_RESET, /* not a new slice */
1043 * Use hrtick when:
1044 * - enabled by features
1045 * - hrtimer is actually high res
1047 static inline int hrtick_enabled(struct rq *rq)
1049 if (!sched_feat(HRTICK))
1050 return 0;
1051 return hrtimer_is_hres_active(&rq->hrtick_timer);
1055 * Called to set the hrtick timer state.
1057 * called with rq->lock held and irqs disabled
1059 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1061 assert_spin_locked(&rq->lock);
1064 * preempt at: now + delay
1066 rq->hrtick_expire =
1067 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1069 * indicate we need to program the timer
1071 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1072 if (reset)
1073 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1076 * New slices are called from the schedule path and don't need a
1077 * forced reschedule.
1079 if (reset)
1080 resched_hrt(rq->curr);
1083 static void hrtick_clear(struct rq *rq)
1085 if (hrtimer_active(&rq->hrtick_timer))
1086 hrtimer_cancel(&rq->hrtick_timer);
1090 * Update the timer from the possible pending state.
1092 static void hrtick_set(struct rq *rq)
1094 ktime_t time;
1095 int set, reset;
1096 unsigned long flags;
1098 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1100 spin_lock_irqsave(&rq->lock, flags);
1101 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1102 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1103 time = rq->hrtick_expire;
1104 clear_thread_flag(TIF_HRTICK_RESCHED);
1105 spin_unlock_irqrestore(&rq->lock, flags);
1107 if (set) {
1108 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1109 if (reset && !hrtimer_active(&rq->hrtick_timer))
1110 resched_rq(rq);
1111 } else
1112 hrtick_clear(rq);
1116 * High-resolution timer tick.
1117 * Runs from hardirq context with interrupts disabled.
1119 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1121 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1123 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1125 spin_lock(&rq->lock);
1126 __update_rq_clock(rq);
1127 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1128 spin_unlock(&rq->lock);
1130 return HRTIMER_NORESTART;
1133 static inline void init_rq_hrtick(struct rq *rq)
1135 rq->hrtick_flags = 0;
1136 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1137 rq->hrtick_timer.function = hrtick;
1138 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1141 void hrtick_resched(void)
1143 struct rq *rq;
1144 unsigned long flags;
1146 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1147 return;
1149 local_irq_save(flags);
1150 rq = cpu_rq(smp_processor_id());
1151 hrtick_set(rq);
1152 local_irq_restore(flags);
1154 #else
1155 static inline void hrtick_clear(struct rq *rq)
1159 static inline void hrtick_set(struct rq *rq)
1163 static inline void init_rq_hrtick(struct rq *rq)
1167 void hrtick_resched(void)
1170 #endif
1173 * resched_task - mark a task 'to be rescheduled now'.
1175 * On UP this means the setting of the need_resched flag, on SMP it
1176 * might also involve a cross-CPU call to trigger the scheduler on
1177 * the target CPU.
1179 #ifdef CONFIG_SMP
1181 #ifndef tsk_is_polling
1182 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1183 #endif
1185 static void __resched_task(struct task_struct *p, int tif_bit)
1187 int cpu;
1189 assert_spin_locked(&task_rq(p)->lock);
1191 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1192 return;
1194 set_tsk_thread_flag(p, tif_bit);
1196 cpu = task_cpu(p);
1197 if (cpu == smp_processor_id())
1198 return;
1200 /* NEED_RESCHED must be visible before we test polling */
1201 smp_mb();
1202 if (!tsk_is_polling(p))
1203 smp_send_reschedule(cpu);
1206 static void resched_cpu(int cpu)
1208 struct rq *rq = cpu_rq(cpu);
1209 unsigned long flags;
1211 if (!spin_trylock_irqsave(&rq->lock, flags))
1212 return;
1213 resched_task(cpu_curr(cpu));
1214 spin_unlock_irqrestore(&rq->lock, flags);
1217 #ifdef CONFIG_NO_HZ
1219 * When add_timer_on() enqueues a timer into the timer wheel of an
1220 * idle CPU then this timer might expire before the next timer event
1221 * which is scheduled to wake up that CPU. In case of a completely
1222 * idle system the next event might even be infinite time into the
1223 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1224 * leaves the inner idle loop so the newly added timer is taken into
1225 * account when the CPU goes back to idle and evaluates the timer
1226 * wheel for the next timer event.
1228 void wake_up_idle_cpu(int cpu)
1230 struct rq *rq = cpu_rq(cpu);
1232 if (cpu == smp_processor_id())
1233 return;
1236 * This is safe, as this function is called with the timer
1237 * wheel base lock of (cpu) held. When the CPU is on the way
1238 * to idle and has not yet set rq->curr to idle then it will
1239 * be serialized on the timer wheel base lock and take the new
1240 * timer into account automatically.
1242 if (rq->curr != rq->idle)
1243 return;
1246 * We can set TIF_RESCHED on the idle task of the other CPU
1247 * lockless. The worst case is that the other CPU runs the
1248 * idle task through an additional NOOP schedule()
1250 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1252 /* NEED_RESCHED must be visible before we test polling */
1253 smp_mb();
1254 if (!tsk_is_polling(rq->idle))
1255 smp_send_reschedule(cpu);
1257 #endif
1259 #else
1260 static void __resched_task(struct task_struct *p, int tif_bit)
1262 assert_spin_locked(&task_rq(p)->lock);
1263 set_tsk_thread_flag(p, tif_bit);
1265 #endif
1267 #if BITS_PER_LONG == 32
1268 # define WMULT_CONST (~0UL)
1269 #else
1270 # define WMULT_CONST (1UL << 32)
1271 #endif
1273 #define WMULT_SHIFT 32
1276 * Shift right and round:
1278 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1280 static unsigned long
1281 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1282 struct load_weight *lw)
1284 u64 tmp;
1286 if (unlikely(!lw->inv_weight))
1287 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1289 tmp = (u64)delta_exec * weight;
1291 * Check whether we'd overflow the 64-bit multiplication:
1293 if (unlikely(tmp > WMULT_CONST))
1294 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1295 WMULT_SHIFT/2);
1296 else
1297 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1299 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1302 static inline unsigned long
1303 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
1305 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
1308 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1310 lw->weight += inc;
1311 lw->inv_weight = 0;
1314 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1316 lw->weight -= dec;
1317 lw->inv_weight = 0;
1321 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1322 * of tasks with abnormal "nice" values across CPUs the contribution that
1323 * each task makes to its run queue's load is weighted according to its
1324 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1325 * scaled version of the new time slice allocation that they receive on time
1326 * slice expiry etc.
1329 #define WEIGHT_IDLEPRIO 2
1330 #define WMULT_IDLEPRIO (1 << 31)
1333 * Nice levels are multiplicative, with a gentle 10% change for every
1334 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1335 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1336 * that remained on nice 0.
1338 * The "10% effect" is relative and cumulative: from _any_ nice level,
1339 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1340 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1341 * If a task goes up by ~10% and another task goes down by ~10% then
1342 * the relative distance between them is ~25%.)
1344 static const int prio_to_weight[40] = {
1345 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1346 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1347 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1348 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1349 /* 0 */ 1024, 820, 655, 526, 423,
1350 /* 5 */ 335, 272, 215, 172, 137,
1351 /* 10 */ 110, 87, 70, 56, 45,
1352 /* 15 */ 36, 29, 23, 18, 15,
1356 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1358 * In cases where the weight does not change often, we can use the
1359 * precalculated inverse to speed up arithmetics by turning divisions
1360 * into multiplications:
1362 static const u32 prio_to_wmult[40] = {
1363 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1364 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1365 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1366 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1367 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1368 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1369 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1370 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1373 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1376 * runqueue iterator, to support SMP load-balancing between different
1377 * scheduling classes, without having to expose their internal data
1378 * structures to the load-balancing proper:
1380 struct rq_iterator {
1381 void *arg;
1382 struct task_struct *(*start)(void *);
1383 struct task_struct *(*next)(void *);
1386 #ifdef CONFIG_SMP
1387 static unsigned long
1388 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1389 unsigned long max_load_move, struct sched_domain *sd,
1390 enum cpu_idle_type idle, int *all_pinned,
1391 int *this_best_prio, struct rq_iterator *iterator);
1393 static int
1394 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1395 struct sched_domain *sd, enum cpu_idle_type idle,
1396 struct rq_iterator *iterator);
1397 #endif
1399 #ifdef CONFIG_CGROUP_CPUACCT
1400 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1401 #else
1402 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1403 #endif
1405 #ifdef CONFIG_SMP
1406 static unsigned long source_load(int cpu, int type);
1407 static unsigned long target_load(int cpu, int type);
1408 static unsigned long cpu_avg_load_per_task(int cpu);
1409 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1410 #endif /* CONFIG_SMP */
1412 #include "sched_stats.h"
1413 #include "sched_idletask.c"
1414 #include "sched_fair.c"
1415 #include "sched_rt.c"
1416 #ifdef CONFIG_SCHED_DEBUG
1417 # include "sched_debug.c"
1418 #endif
1420 #define sched_class_highest (&rt_sched_class)
1422 static inline void inc_load(struct rq *rq, const struct task_struct *p)
1424 update_load_add(&rq->load, p->se.load.weight);
1427 static inline void dec_load(struct rq *rq, const struct task_struct *p)
1429 update_load_sub(&rq->load, p->se.load.weight);
1432 static void inc_nr_running(struct task_struct *p, struct rq *rq)
1434 rq->nr_running++;
1435 inc_load(rq, p);
1438 static void dec_nr_running(struct task_struct *p, struct rq *rq)
1440 rq->nr_running--;
1441 dec_load(rq, p);
1444 static void set_load_weight(struct task_struct *p)
1446 if (task_has_rt_policy(p)) {
1447 p->se.load.weight = prio_to_weight[0] * 2;
1448 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1449 return;
1453 * SCHED_IDLE tasks get minimal weight:
1455 if (p->policy == SCHED_IDLE) {
1456 p->se.load.weight = WEIGHT_IDLEPRIO;
1457 p->se.load.inv_weight = WMULT_IDLEPRIO;
1458 return;
1461 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1462 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1465 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1467 sched_info_queued(p);
1468 p->sched_class->enqueue_task(rq, p, wakeup);
1469 p->se.on_rq = 1;
1472 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1474 p->sched_class->dequeue_task(rq, p, sleep);
1475 p->se.on_rq = 0;
1479 * __normal_prio - return the priority that is based on the static prio
1481 static inline int __normal_prio(struct task_struct *p)
1483 return p->static_prio;
1487 * Calculate the expected normal priority: i.e. priority
1488 * without taking RT-inheritance into account. Might be
1489 * boosted by interactivity modifiers. Changes upon fork,
1490 * setprio syscalls, and whenever the interactivity
1491 * estimator recalculates.
1493 static inline int normal_prio(struct task_struct *p)
1495 int prio;
1497 if (task_has_rt_policy(p))
1498 prio = MAX_RT_PRIO-1 - p->rt_priority;
1499 else
1500 prio = __normal_prio(p);
1501 return prio;
1505 * Calculate the current priority, i.e. the priority
1506 * taken into account by the scheduler. This value might
1507 * be boosted by RT tasks, or might be boosted by
1508 * interactivity modifiers. Will be RT if the task got
1509 * RT-boosted. If not then it returns p->normal_prio.
1511 static int effective_prio(struct task_struct *p)
1513 p->normal_prio = normal_prio(p);
1515 * If we are RT tasks or we were boosted to RT priority,
1516 * keep the priority unchanged. Otherwise, update priority
1517 * to the normal priority:
1519 if (!rt_prio(p->prio))
1520 return p->normal_prio;
1521 return p->prio;
1525 * activate_task - move a task to the runqueue.
1527 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1529 if (task_contributes_to_load(p))
1530 rq->nr_uninterruptible--;
1532 enqueue_task(rq, p, wakeup);
1533 inc_nr_running(p, rq);
1537 * deactivate_task - remove a task from the runqueue.
1539 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1541 if (task_contributes_to_load(p))
1542 rq->nr_uninterruptible++;
1544 dequeue_task(rq, p, sleep);
1545 dec_nr_running(p, rq);
1549 * task_curr - is this task currently executing on a CPU?
1550 * @p: the task in question.
1552 inline int task_curr(const struct task_struct *p)
1554 return cpu_curr(task_cpu(p)) == p;
1557 /* Used instead of source_load when we know the type == 0 */
1558 unsigned long weighted_cpuload(const int cpu)
1560 return cpu_rq(cpu)->load.weight;
1563 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1565 set_task_rq(p, cpu);
1566 #ifdef CONFIG_SMP
1568 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1569 * successfuly executed on another CPU. We must ensure that updates of
1570 * per-task data have been completed by this moment.
1572 smp_wmb();
1573 task_thread_info(p)->cpu = cpu;
1574 #endif
1577 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1578 const struct sched_class *prev_class,
1579 int oldprio, int running)
1581 if (prev_class != p->sched_class) {
1582 if (prev_class->switched_from)
1583 prev_class->switched_from(rq, p, running);
1584 p->sched_class->switched_to(rq, p, running);
1585 } else
1586 p->sched_class->prio_changed(rq, p, oldprio, running);
1589 #ifdef CONFIG_SMP
1592 * Is this task likely cache-hot:
1594 static int
1595 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1597 s64 delta;
1600 * Buddy candidates are cache hot:
1602 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
1603 return 1;
1605 if (p->sched_class != &fair_sched_class)
1606 return 0;
1608 if (sysctl_sched_migration_cost == -1)
1609 return 1;
1610 if (sysctl_sched_migration_cost == 0)
1611 return 0;
1613 delta = now - p->se.exec_start;
1615 return delta < (s64)sysctl_sched_migration_cost;
1619 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1621 int old_cpu = task_cpu(p);
1622 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1623 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1624 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1625 u64 clock_offset;
1627 clock_offset = old_rq->clock - new_rq->clock;
1629 #ifdef CONFIG_SCHEDSTATS
1630 if (p->se.wait_start)
1631 p->se.wait_start -= clock_offset;
1632 if (p->se.sleep_start)
1633 p->se.sleep_start -= clock_offset;
1634 if (p->se.block_start)
1635 p->se.block_start -= clock_offset;
1636 if (old_cpu != new_cpu) {
1637 schedstat_inc(p, se.nr_migrations);
1638 if (task_hot(p, old_rq->clock, NULL))
1639 schedstat_inc(p, se.nr_forced2_migrations);
1641 #endif
1642 p->se.vruntime -= old_cfsrq->min_vruntime -
1643 new_cfsrq->min_vruntime;
1645 __set_task_cpu(p, new_cpu);
1648 struct migration_req {
1649 struct list_head list;
1651 struct task_struct *task;
1652 int dest_cpu;
1654 struct completion done;
1658 * The task's runqueue lock must be held.
1659 * Returns true if you have to wait for migration thread.
1661 static int
1662 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1664 struct rq *rq = task_rq(p);
1667 * If the task is not on a runqueue (and not running), then
1668 * it is sufficient to simply update the task's cpu field.
1670 if (!p->se.on_rq && !task_running(rq, p)) {
1671 set_task_cpu(p, dest_cpu);
1672 return 0;
1675 init_completion(&req->done);
1676 req->task = p;
1677 req->dest_cpu = dest_cpu;
1678 list_add(&req->list, &rq->migration_queue);
1680 return 1;
1684 * wait_task_inactive - wait for a thread to unschedule.
1686 * The caller must ensure that the task *will* unschedule sometime soon,
1687 * else this function might spin for a *long* time. This function can't
1688 * be called with interrupts off, or it may introduce deadlock with
1689 * smp_call_function() if an IPI is sent by the same process we are
1690 * waiting to become inactive.
1692 void wait_task_inactive(struct task_struct *p)
1694 unsigned long flags;
1695 int running, on_rq;
1696 struct rq *rq;
1698 for (;;) {
1700 * We do the initial early heuristics without holding
1701 * any task-queue locks at all. We'll only try to get
1702 * the runqueue lock when things look like they will
1703 * work out!
1705 rq = task_rq(p);
1708 * If the task is actively running on another CPU
1709 * still, just relax and busy-wait without holding
1710 * any locks.
1712 * NOTE! Since we don't hold any locks, it's not
1713 * even sure that "rq" stays as the right runqueue!
1714 * But we don't care, since "task_running()" will
1715 * return false if the runqueue has changed and p
1716 * is actually now running somewhere else!
1718 while (task_running(rq, p))
1719 cpu_relax();
1722 * Ok, time to look more closely! We need the rq
1723 * lock now, to be *sure*. If we're wrong, we'll
1724 * just go back and repeat.
1726 rq = task_rq_lock(p, &flags);
1727 running = task_running(rq, p);
1728 on_rq = p->se.on_rq;
1729 task_rq_unlock(rq, &flags);
1732 * Was it really running after all now that we
1733 * checked with the proper locks actually held?
1735 * Oops. Go back and try again..
1737 if (unlikely(running)) {
1738 cpu_relax();
1739 continue;
1743 * It's not enough that it's not actively running,
1744 * it must be off the runqueue _entirely_, and not
1745 * preempted!
1747 * So if it wa still runnable (but just not actively
1748 * running right now), it's preempted, and we should
1749 * yield - it could be a while.
1751 if (unlikely(on_rq)) {
1752 schedule_timeout_uninterruptible(1);
1753 continue;
1757 * Ahh, all good. It wasn't running, and it wasn't
1758 * runnable, which means that it will never become
1759 * running in the future either. We're all done!
1761 break;
1765 /***
1766 * kick_process - kick a running thread to enter/exit the kernel
1767 * @p: the to-be-kicked thread
1769 * Cause a process which is running on another CPU to enter
1770 * kernel-mode, without any delay. (to get signals handled.)
1772 * NOTE: this function doesnt have to take the runqueue lock,
1773 * because all it wants to ensure is that the remote task enters
1774 * the kernel. If the IPI races and the task has been migrated
1775 * to another CPU then no harm is done and the purpose has been
1776 * achieved as well.
1778 void kick_process(struct task_struct *p)
1780 int cpu;
1782 preempt_disable();
1783 cpu = task_cpu(p);
1784 if ((cpu != smp_processor_id()) && task_curr(p))
1785 smp_send_reschedule(cpu);
1786 preempt_enable();
1790 * Return a low guess at the load of a migration-source cpu weighted
1791 * according to the scheduling class and "nice" value.
1793 * We want to under-estimate the load of migration sources, to
1794 * balance conservatively.
1796 static unsigned long source_load(int cpu, int type)
1798 struct rq *rq = cpu_rq(cpu);
1799 unsigned long total = weighted_cpuload(cpu);
1801 if (type == 0)
1802 return total;
1804 return min(rq->cpu_load[type-1], total);
1808 * Return a high guess at the load of a migration-target cpu weighted
1809 * according to the scheduling class and "nice" value.
1811 static unsigned long target_load(int cpu, int type)
1813 struct rq *rq = cpu_rq(cpu);
1814 unsigned long total = weighted_cpuload(cpu);
1816 if (type == 0)
1817 return total;
1819 return max(rq->cpu_load[type-1], total);
1823 * Return the average load per task on the cpu's run queue
1825 static unsigned long cpu_avg_load_per_task(int cpu)
1827 struct rq *rq = cpu_rq(cpu);
1828 unsigned long total = weighted_cpuload(cpu);
1829 unsigned long n = rq->nr_running;
1831 return n ? total / n : SCHED_LOAD_SCALE;
1835 * find_idlest_group finds and returns the least busy CPU group within the
1836 * domain.
1838 static struct sched_group *
1839 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1841 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1842 unsigned long min_load = ULONG_MAX, this_load = 0;
1843 int load_idx = sd->forkexec_idx;
1844 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1846 do {
1847 unsigned long load, avg_load;
1848 int local_group;
1849 int i;
1851 /* Skip over this group if it has no CPUs allowed */
1852 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1853 continue;
1855 local_group = cpu_isset(this_cpu, group->cpumask);
1857 /* Tally up the load of all CPUs in the group */
1858 avg_load = 0;
1860 for_each_cpu_mask(i, group->cpumask) {
1861 /* Bias balancing toward cpus of our domain */
1862 if (local_group)
1863 load = source_load(i, load_idx);
1864 else
1865 load = target_load(i, load_idx);
1867 avg_load += load;
1870 /* Adjust by relative CPU power of the group */
1871 avg_load = sg_div_cpu_power(group,
1872 avg_load * SCHED_LOAD_SCALE);
1874 if (local_group) {
1875 this_load = avg_load;
1876 this = group;
1877 } else if (avg_load < min_load) {
1878 min_load = avg_load;
1879 idlest = group;
1881 } while (group = group->next, group != sd->groups);
1883 if (!idlest || 100*this_load < imbalance*min_load)
1884 return NULL;
1885 return idlest;
1889 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1891 static int
1892 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
1893 cpumask_t *tmp)
1895 unsigned long load, min_load = ULONG_MAX;
1896 int idlest = -1;
1897 int i;
1899 /* Traverse only the allowed CPUs */
1900 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
1902 for_each_cpu_mask(i, *tmp) {
1903 load = weighted_cpuload(i);
1905 if (load < min_load || (load == min_load && i == this_cpu)) {
1906 min_load = load;
1907 idlest = i;
1911 return idlest;
1915 * sched_balance_self: balance the current task (running on cpu) in domains
1916 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1917 * SD_BALANCE_EXEC.
1919 * Balance, ie. select the least loaded group.
1921 * Returns the target CPU number, or the same CPU if no balancing is needed.
1923 * preempt must be disabled.
1925 static int sched_balance_self(int cpu, int flag)
1927 struct task_struct *t = current;
1928 struct sched_domain *tmp, *sd = NULL;
1930 for_each_domain(cpu, tmp) {
1932 * If power savings logic is enabled for a domain, stop there.
1934 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1935 break;
1936 if (tmp->flags & flag)
1937 sd = tmp;
1940 while (sd) {
1941 cpumask_t span, tmpmask;
1942 struct sched_group *group;
1943 int new_cpu, weight;
1945 if (!(sd->flags & flag)) {
1946 sd = sd->child;
1947 continue;
1950 span = sd->span;
1951 group = find_idlest_group(sd, t, cpu);
1952 if (!group) {
1953 sd = sd->child;
1954 continue;
1957 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
1958 if (new_cpu == -1 || new_cpu == cpu) {
1959 /* Now try balancing at a lower domain level of cpu */
1960 sd = sd->child;
1961 continue;
1964 /* Now try balancing at a lower domain level of new_cpu */
1965 cpu = new_cpu;
1966 sd = NULL;
1967 weight = cpus_weight(span);
1968 for_each_domain(cpu, tmp) {
1969 if (weight <= cpus_weight(tmp->span))
1970 break;
1971 if (tmp->flags & flag)
1972 sd = tmp;
1974 /* while loop will break here if sd == NULL */
1977 return cpu;
1980 #endif /* CONFIG_SMP */
1982 /***
1983 * try_to_wake_up - wake up a thread
1984 * @p: the to-be-woken-up thread
1985 * @state: the mask of task states that can be woken
1986 * @sync: do a synchronous wakeup?
1988 * Put it on the run-queue if it's not already there. The "current"
1989 * thread is always on the run-queue (except when the actual
1990 * re-schedule is in progress), and as such you're allowed to do
1991 * the simpler "current->state = TASK_RUNNING" to mark yourself
1992 * runnable without the overhead of this.
1994 * returns failure only if the task is already active.
1996 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1998 int cpu, orig_cpu, this_cpu, success = 0;
1999 unsigned long flags;
2000 long old_state;
2001 struct rq *rq;
2003 if (!sched_feat(SYNC_WAKEUPS))
2004 sync = 0;
2006 smp_wmb();
2007 rq = task_rq_lock(p, &flags);
2008 old_state = p->state;
2009 if (!(old_state & state))
2010 goto out;
2012 if (p->se.on_rq)
2013 goto out_running;
2015 cpu = task_cpu(p);
2016 orig_cpu = cpu;
2017 this_cpu = smp_processor_id();
2019 #ifdef CONFIG_SMP
2020 if (unlikely(task_running(rq, p)))
2021 goto out_activate;
2023 cpu = p->sched_class->select_task_rq(p, sync);
2024 if (cpu != orig_cpu) {
2025 set_task_cpu(p, cpu);
2026 task_rq_unlock(rq, &flags);
2027 /* might preempt at this point */
2028 rq = task_rq_lock(p, &flags);
2029 old_state = p->state;
2030 if (!(old_state & state))
2031 goto out;
2032 if (p->se.on_rq)
2033 goto out_running;
2035 this_cpu = smp_processor_id();
2036 cpu = task_cpu(p);
2039 #ifdef CONFIG_SCHEDSTATS
2040 schedstat_inc(rq, ttwu_count);
2041 if (cpu == this_cpu)
2042 schedstat_inc(rq, ttwu_local);
2043 else {
2044 struct sched_domain *sd;
2045 for_each_domain(this_cpu, sd) {
2046 if (cpu_isset(cpu, sd->span)) {
2047 schedstat_inc(sd, ttwu_wake_remote);
2048 break;
2052 #endif
2054 out_activate:
2055 #endif /* CONFIG_SMP */
2056 schedstat_inc(p, se.nr_wakeups);
2057 if (sync)
2058 schedstat_inc(p, se.nr_wakeups_sync);
2059 if (orig_cpu != cpu)
2060 schedstat_inc(p, se.nr_wakeups_migrate);
2061 if (cpu == this_cpu)
2062 schedstat_inc(p, se.nr_wakeups_local);
2063 else
2064 schedstat_inc(p, se.nr_wakeups_remote);
2065 update_rq_clock(rq);
2066 activate_task(rq, p, 1);
2067 success = 1;
2069 out_running:
2070 check_preempt_curr(rq, p);
2072 p->state = TASK_RUNNING;
2073 #ifdef CONFIG_SMP
2074 if (p->sched_class->task_wake_up)
2075 p->sched_class->task_wake_up(rq, p);
2076 #endif
2077 out:
2078 task_rq_unlock(rq, &flags);
2080 return success;
2083 int wake_up_process(struct task_struct *p)
2085 return try_to_wake_up(p, TASK_ALL, 0);
2087 EXPORT_SYMBOL(wake_up_process);
2089 int wake_up_state(struct task_struct *p, unsigned int state)
2091 return try_to_wake_up(p, state, 0);
2095 * Perform scheduler related setup for a newly forked process p.
2096 * p is forked by current.
2098 * __sched_fork() is basic setup used by init_idle() too:
2100 static void __sched_fork(struct task_struct *p)
2102 p->se.exec_start = 0;
2103 p->se.sum_exec_runtime = 0;
2104 p->se.prev_sum_exec_runtime = 0;
2105 p->se.last_wakeup = 0;
2106 p->se.avg_overlap = 0;
2108 #ifdef CONFIG_SCHEDSTATS
2109 p->se.wait_start = 0;
2110 p->se.sum_sleep_runtime = 0;
2111 p->se.sleep_start = 0;
2112 p->se.block_start = 0;
2113 p->se.sleep_max = 0;
2114 p->se.block_max = 0;
2115 p->se.exec_max = 0;
2116 p->se.slice_max = 0;
2117 p->se.wait_max = 0;
2118 #endif
2120 INIT_LIST_HEAD(&p->rt.run_list);
2121 p->se.on_rq = 0;
2123 #ifdef CONFIG_PREEMPT_NOTIFIERS
2124 INIT_HLIST_HEAD(&p->preempt_notifiers);
2125 #endif
2128 * We mark the process as running here, but have not actually
2129 * inserted it onto the runqueue yet. This guarantees that
2130 * nobody will actually run it, and a signal or other external
2131 * event cannot wake it up and insert it on the runqueue either.
2133 p->state = TASK_RUNNING;
2137 * fork()/clone()-time setup:
2139 void sched_fork(struct task_struct *p, int clone_flags)
2141 int cpu = get_cpu();
2143 __sched_fork(p);
2145 #ifdef CONFIG_SMP
2146 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2147 #endif
2148 set_task_cpu(p, cpu);
2151 * Make sure we do not leak PI boosting priority to the child:
2153 p->prio = current->normal_prio;
2154 if (!rt_prio(p->prio))
2155 p->sched_class = &fair_sched_class;
2157 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2158 if (likely(sched_info_on()))
2159 memset(&p->sched_info, 0, sizeof(p->sched_info));
2160 #endif
2161 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2162 p->oncpu = 0;
2163 #endif
2164 #ifdef CONFIG_PREEMPT
2165 /* Want to start with kernel preemption disabled. */
2166 task_thread_info(p)->preempt_count = 1;
2167 #endif
2168 put_cpu();
2172 * wake_up_new_task - wake up a newly created task for the first time.
2174 * This function will do some initial scheduler statistics housekeeping
2175 * that must be done for every newly created context, then puts the task
2176 * on the runqueue and wakes it.
2178 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2180 unsigned long flags;
2181 struct rq *rq;
2183 rq = task_rq_lock(p, &flags);
2184 BUG_ON(p->state != TASK_RUNNING);
2185 update_rq_clock(rq);
2187 p->prio = effective_prio(p);
2189 if (!p->sched_class->task_new || !current->se.on_rq) {
2190 activate_task(rq, p, 0);
2191 } else {
2193 * Let the scheduling class do new task startup
2194 * management (if any):
2196 p->sched_class->task_new(rq, p);
2197 inc_nr_running(p, rq);
2199 check_preempt_curr(rq, p);
2200 #ifdef CONFIG_SMP
2201 if (p->sched_class->task_wake_up)
2202 p->sched_class->task_wake_up(rq, p);
2203 #endif
2204 task_rq_unlock(rq, &flags);
2207 #ifdef CONFIG_PREEMPT_NOTIFIERS
2210 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2211 * @notifier: notifier struct to register
2213 void preempt_notifier_register(struct preempt_notifier *notifier)
2215 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2217 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2220 * preempt_notifier_unregister - no longer interested in preemption notifications
2221 * @notifier: notifier struct to unregister
2223 * This is safe to call from within a preemption notifier.
2225 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2227 hlist_del(&notifier->link);
2229 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2231 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2233 struct preempt_notifier *notifier;
2234 struct hlist_node *node;
2236 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2237 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2240 static void
2241 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2242 struct task_struct *next)
2244 struct preempt_notifier *notifier;
2245 struct hlist_node *node;
2247 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2248 notifier->ops->sched_out(notifier, next);
2251 #else
2253 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2257 static void
2258 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2259 struct task_struct *next)
2263 #endif
2266 * prepare_task_switch - prepare to switch tasks
2267 * @rq: the runqueue preparing to switch
2268 * @prev: the current task that is being switched out
2269 * @next: the task we are going to switch to.
2271 * This is called with the rq lock held and interrupts off. It must
2272 * be paired with a subsequent finish_task_switch after the context
2273 * switch.
2275 * prepare_task_switch sets up locking and calls architecture specific
2276 * hooks.
2278 static inline void
2279 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2280 struct task_struct *next)
2282 fire_sched_out_preempt_notifiers(prev, next);
2283 prepare_lock_switch(rq, next);
2284 prepare_arch_switch(next);
2288 * finish_task_switch - clean up after a task-switch
2289 * @rq: runqueue associated with task-switch
2290 * @prev: the thread we just switched away from.
2292 * finish_task_switch must be called after the context switch, paired
2293 * with a prepare_task_switch call before the context switch.
2294 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2295 * and do any other architecture-specific cleanup actions.
2297 * Note that we may have delayed dropping an mm in context_switch(). If
2298 * so, we finish that here outside of the runqueue lock. (Doing it
2299 * with the lock held can cause deadlocks; see schedule() for
2300 * details.)
2302 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2303 __releases(rq->lock)
2305 struct mm_struct *mm = rq->prev_mm;
2306 long prev_state;
2308 rq->prev_mm = NULL;
2311 * A task struct has one reference for the use as "current".
2312 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2313 * schedule one last time. The schedule call will never return, and
2314 * the scheduled task must drop that reference.
2315 * The test for TASK_DEAD must occur while the runqueue locks are
2316 * still held, otherwise prev could be scheduled on another cpu, die
2317 * there before we look at prev->state, and then the reference would
2318 * be dropped twice.
2319 * Manfred Spraul <manfred@colorfullife.com>
2321 prev_state = prev->state;
2322 finish_arch_switch(prev);
2323 finish_lock_switch(rq, prev);
2324 #ifdef CONFIG_SMP
2325 if (current->sched_class->post_schedule)
2326 current->sched_class->post_schedule(rq);
2327 #endif
2329 fire_sched_in_preempt_notifiers(current);
2330 if (mm)
2331 mmdrop(mm);
2332 if (unlikely(prev_state == TASK_DEAD)) {
2334 * Remove function-return probe instances associated with this
2335 * task and put them back on the free list.
2337 kprobe_flush_task(prev);
2338 put_task_struct(prev);
2343 * schedule_tail - first thing a freshly forked thread must call.
2344 * @prev: the thread we just switched away from.
2346 asmlinkage void schedule_tail(struct task_struct *prev)
2347 __releases(rq->lock)
2349 struct rq *rq = this_rq();
2351 finish_task_switch(rq, prev);
2352 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2353 /* In this case, finish_task_switch does not reenable preemption */
2354 preempt_enable();
2355 #endif
2356 if (current->set_child_tid)
2357 put_user(task_pid_vnr(current), current->set_child_tid);
2361 * context_switch - switch to the new MM and the new
2362 * thread's register state.
2364 static inline void
2365 context_switch(struct rq *rq, struct task_struct *prev,
2366 struct task_struct *next)
2368 struct mm_struct *mm, *oldmm;
2370 prepare_task_switch(rq, prev, next);
2371 mm = next->mm;
2372 oldmm = prev->active_mm;
2374 * For paravirt, this is coupled with an exit in switch_to to
2375 * combine the page table reload and the switch backend into
2376 * one hypercall.
2378 arch_enter_lazy_cpu_mode();
2380 if (unlikely(!mm)) {
2381 next->active_mm = oldmm;
2382 atomic_inc(&oldmm->mm_count);
2383 enter_lazy_tlb(oldmm, next);
2384 } else
2385 switch_mm(oldmm, mm, next);
2387 if (unlikely(!prev->mm)) {
2388 prev->active_mm = NULL;
2389 rq->prev_mm = oldmm;
2392 * Since the runqueue lock will be released by the next
2393 * task (which is an invalid locking op but in the case
2394 * of the scheduler it's an obvious special-case), so we
2395 * do an early lockdep release here:
2397 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2398 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2399 #endif
2401 /* Here we just switch the register state and the stack. */
2402 switch_to(prev, next, prev);
2404 barrier();
2406 * this_rq must be evaluated again because prev may have moved
2407 * CPUs since it called schedule(), thus the 'rq' on its stack
2408 * frame will be invalid.
2410 finish_task_switch(this_rq(), prev);
2414 * nr_running, nr_uninterruptible and nr_context_switches:
2416 * externally visible scheduler statistics: current number of runnable
2417 * threads, current number of uninterruptible-sleeping threads, total
2418 * number of context switches performed since bootup.
2420 unsigned long nr_running(void)
2422 unsigned long i, sum = 0;
2424 for_each_online_cpu(i)
2425 sum += cpu_rq(i)->nr_running;
2427 return sum;
2430 unsigned long nr_uninterruptible(void)
2432 unsigned long i, sum = 0;
2434 for_each_possible_cpu(i)
2435 sum += cpu_rq(i)->nr_uninterruptible;
2438 * Since we read the counters lockless, it might be slightly
2439 * inaccurate. Do not allow it to go below zero though:
2441 if (unlikely((long)sum < 0))
2442 sum = 0;
2444 return sum;
2447 unsigned long long nr_context_switches(void)
2449 int i;
2450 unsigned long long sum = 0;
2452 for_each_possible_cpu(i)
2453 sum += cpu_rq(i)->nr_switches;
2455 return sum;
2458 unsigned long nr_iowait(void)
2460 unsigned long i, sum = 0;
2462 for_each_possible_cpu(i)
2463 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2465 return sum;
2468 unsigned long nr_active(void)
2470 unsigned long i, running = 0, uninterruptible = 0;
2472 for_each_online_cpu(i) {
2473 running += cpu_rq(i)->nr_running;
2474 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2477 if (unlikely((long)uninterruptible < 0))
2478 uninterruptible = 0;
2480 return running + uninterruptible;
2484 * Update rq->cpu_load[] statistics. This function is usually called every
2485 * scheduler tick (TICK_NSEC).
2487 static void update_cpu_load(struct rq *this_rq)
2489 unsigned long this_load = this_rq->load.weight;
2490 int i, scale;
2492 this_rq->nr_load_updates++;
2494 /* Update our load: */
2495 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2496 unsigned long old_load, new_load;
2498 /* scale is effectively 1 << i now, and >> i divides by scale */
2500 old_load = this_rq->cpu_load[i];
2501 new_load = this_load;
2503 * Round up the averaging division if load is increasing. This
2504 * prevents us from getting stuck on 9 if the load is 10, for
2505 * example.
2507 if (new_load > old_load)
2508 new_load += scale-1;
2509 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2513 #ifdef CONFIG_SMP
2516 * double_rq_lock - safely lock two runqueues
2518 * Note this does not disable interrupts like task_rq_lock,
2519 * you need to do so manually before calling.
2521 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2522 __acquires(rq1->lock)
2523 __acquires(rq2->lock)
2525 BUG_ON(!irqs_disabled());
2526 if (rq1 == rq2) {
2527 spin_lock(&rq1->lock);
2528 __acquire(rq2->lock); /* Fake it out ;) */
2529 } else {
2530 if (rq1 < rq2) {
2531 spin_lock(&rq1->lock);
2532 spin_lock(&rq2->lock);
2533 } else {
2534 spin_lock(&rq2->lock);
2535 spin_lock(&rq1->lock);
2538 update_rq_clock(rq1);
2539 update_rq_clock(rq2);
2543 * double_rq_unlock - safely unlock two runqueues
2545 * Note this does not restore interrupts like task_rq_unlock,
2546 * you need to do so manually after calling.
2548 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2549 __releases(rq1->lock)
2550 __releases(rq2->lock)
2552 spin_unlock(&rq1->lock);
2553 if (rq1 != rq2)
2554 spin_unlock(&rq2->lock);
2555 else
2556 __release(rq2->lock);
2560 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2562 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2563 __releases(this_rq->lock)
2564 __acquires(busiest->lock)
2565 __acquires(this_rq->lock)
2567 int ret = 0;
2569 if (unlikely(!irqs_disabled())) {
2570 /* printk() doesn't work good under rq->lock */
2571 spin_unlock(&this_rq->lock);
2572 BUG_ON(1);
2574 if (unlikely(!spin_trylock(&busiest->lock))) {
2575 if (busiest < this_rq) {
2576 spin_unlock(&this_rq->lock);
2577 spin_lock(&busiest->lock);
2578 spin_lock(&this_rq->lock);
2579 ret = 1;
2580 } else
2581 spin_lock(&busiest->lock);
2583 return ret;
2587 * If dest_cpu is allowed for this process, migrate the task to it.
2588 * This is accomplished by forcing the cpu_allowed mask to only
2589 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2590 * the cpu_allowed mask is restored.
2592 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2594 struct migration_req req;
2595 unsigned long flags;
2596 struct rq *rq;
2598 rq = task_rq_lock(p, &flags);
2599 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2600 || unlikely(cpu_is_offline(dest_cpu)))
2601 goto out;
2603 /* force the process onto the specified CPU */
2604 if (migrate_task(p, dest_cpu, &req)) {
2605 /* Need to wait for migration thread (might exit: take ref). */
2606 struct task_struct *mt = rq->migration_thread;
2608 get_task_struct(mt);
2609 task_rq_unlock(rq, &flags);
2610 wake_up_process(mt);
2611 put_task_struct(mt);
2612 wait_for_completion(&req.done);
2614 return;
2616 out:
2617 task_rq_unlock(rq, &flags);
2621 * sched_exec - execve() is a valuable balancing opportunity, because at
2622 * this point the task has the smallest effective memory and cache footprint.
2624 void sched_exec(void)
2626 int new_cpu, this_cpu = get_cpu();
2627 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2628 put_cpu();
2629 if (new_cpu != this_cpu)
2630 sched_migrate_task(current, new_cpu);
2634 * pull_task - move a task from a remote runqueue to the local runqueue.
2635 * Both runqueues must be locked.
2637 static void pull_task(struct rq *src_rq, struct task_struct *p,
2638 struct rq *this_rq, int this_cpu)
2640 deactivate_task(src_rq, p, 0);
2641 set_task_cpu(p, this_cpu);
2642 activate_task(this_rq, p, 0);
2644 * Note that idle threads have a prio of MAX_PRIO, for this test
2645 * to be always true for them.
2647 check_preempt_curr(this_rq, p);
2651 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2653 static
2654 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2655 struct sched_domain *sd, enum cpu_idle_type idle,
2656 int *all_pinned)
2659 * We do not migrate tasks that are:
2660 * 1) running (obviously), or
2661 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2662 * 3) are cache-hot on their current CPU.
2664 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2665 schedstat_inc(p, se.nr_failed_migrations_affine);
2666 return 0;
2668 *all_pinned = 0;
2670 if (task_running(rq, p)) {
2671 schedstat_inc(p, se.nr_failed_migrations_running);
2672 return 0;
2676 * Aggressive migration if:
2677 * 1) task is cache cold, or
2678 * 2) too many balance attempts have failed.
2681 if (!task_hot(p, rq->clock, sd) ||
2682 sd->nr_balance_failed > sd->cache_nice_tries) {
2683 #ifdef CONFIG_SCHEDSTATS
2684 if (task_hot(p, rq->clock, sd)) {
2685 schedstat_inc(sd, lb_hot_gained[idle]);
2686 schedstat_inc(p, se.nr_forced_migrations);
2688 #endif
2689 return 1;
2692 if (task_hot(p, rq->clock, sd)) {
2693 schedstat_inc(p, se.nr_failed_migrations_hot);
2694 return 0;
2696 return 1;
2699 static unsigned long
2700 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2701 unsigned long max_load_move, struct sched_domain *sd,
2702 enum cpu_idle_type idle, int *all_pinned,
2703 int *this_best_prio, struct rq_iterator *iterator)
2705 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
2706 struct task_struct *p;
2707 long rem_load_move = max_load_move;
2709 if (max_load_move == 0)
2710 goto out;
2712 pinned = 1;
2715 * Start the load-balancing iterator:
2717 p = iterator->start(iterator->arg);
2718 next:
2719 if (!p || loops++ > sysctl_sched_nr_migrate)
2720 goto out;
2722 * To help distribute high priority tasks across CPUs we don't
2723 * skip a task if it will be the highest priority task (i.e. smallest
2724 * prio value) on its new queue regardless of its load weight
2726 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2727 SCHED_LOAD_SCALE_FUZZ;
2728 if ((skip_for_load && p->prio >= *this_best_prio) ||
2729 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2730 p = iterator->next(iterator->arg);
2731 goto next;
2734 pull_task(busiest, p, this_rq, this_cpu);
2735 pulled++;
2736 rem_load_move -= p->se.load.weight;
2739 * We only want to steal up to the prescribed amount of weighted load.
2741 if (rem_load_move > 0) {
2742 if (p->prio < *this_best_prio)
2743 *this_best_prio = p->prio;
2744 p = iterator->next(iterator->arg);
2745 goto next;
2747 out:
2749 * Right now, this is one of only two places pull_task() is called,
2750 * so we can safely collect pull_task() stats here rather than
2751 * inside pull_task().
2753 schedstat_add(sd, lb_gained[idle], pulled);
2755 if (all_pinned)
2756 *all_pinned = pinned;
2758 return max_load_move - rem_load_move;
2762 * move_tasks tries to move up to max_load_move weighted load from busiest to
2763 * this_rq, as part of a balancing operation within domain "sd".
2764 * Returns 1 if successful and 0 otherwise.
2766 * Called with both runqueues locked.
2768 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2769 unsigned long max_load_move,
2770 struct sched_domain *sd, enum cpu_idle_type idle,
2771 int *all_pinned)
2773 const struct sched_class *class = sched_class_highest;
2774 unsigned long total_load_moved = 0;
2775 int this_best_prio = this_rq->curr->prio;
2777 do {
2778 total_load_moved +=
2779 class->load_balance(this_rq, this_cpu, busiest,
2780 max_load_move - total_load_moved,
2781 sd, idle, all_pinned, &this_best_prio);
2782 class = class->next;
2783 } while (class && max_load_move > total_load_moved);
2785 return total_load_moved > 0;
2788 static int
2789 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2790 struct sched_domain *sd, enum cpu_idle_type idle,
2791 struct rq_iterator *iterator)
2793 struct task_struct *p = iterator->start(iterator->arg);
2794 int pinned = 0;
2796 while (p) {
2797 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2798 pull_task(busiest, p, this_rq, this_cpu);
2800 * Right now, this is only the second place pull_task()
2801 * is called, so we can safely collect pull_task()
2802 * stats here rather than inside pull_task().
2804 schedstat_inc(sd, lb_gained[idle]);
2806 return 1;
2808 p = iterator->next(iterator->arg);
2811 return 0;
2815 * move_one_task tries to move exactly one task from busiest to this_rq, as
2816 * part of active balancing operations within "domain".
2817 * Returns 1 if successful and 0 otherwise.
2819 * Called with both runqueues locked.
2821 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2822 struct sched_domain *sd, enum cpu_idle_type idle)
2824 const struct sched_class *class;
2826 for (class = sched_class_highest; class; class = class->next)
2827 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
2828 return 1;
2830 return 0;
2834 * find_busiest_group finds and returns the busiest CPU group within the
2835 * domain. It calculates and returns the amount of weighted load which
2836 * should be moved to restore balance via the imbalance parameter.
2838 static struct sched_group *
2839 find_busiest_group(struct sched_domain *sd, int this_cpu,
2840 unsigned long *imbalance, enum cpu_idle_type idle,
2841 int *sd_idle, const cpumask_t *cpus, int *balance)
2843 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2844 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2845 unsigned long max_pull;
2846 unsigned long busiest_load_per_task, busiest_nr_running;
2847 unsigned long this_load_per_task, this_nr_running;
2848 int load_idx, group_imb = 0;
2849 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2850 int power_savings_balance = 1;
2851 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2852 unsigned long min_nr_running = ULONG_MAX;
2853 struct sched_group *group_min = NULL, *group_leader = NULL;
2854 #endif
2856 max_load = this_load = total_load = total_pwr = 0;
2857 busiest_load_per_task = busiest_nr_running = 0;
2858 this_load_per_task = this_nr_running = 0;
2859 if (idle == CPU_NOT_IDLE)
2860 load_idx = sd->busy_idx;
2861 else if (idle == CPU_NEWLY_IDLE)
2862 load_idx = sd->newidle_idx;
2863 else
2864 load_idx = sd->idle_idx;
2866 do {
2867 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
2868 int local_group;
2869 int i;
2870 int __group_imb = 0;
2871 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2872 unsigned long sum_nr_running, sum_weighted_load;
2874 local_group = cpu_isset(this_cpu, group->cpumask);
2876 if (local_group)
2877 balance_cpu = first_cpu(group->cpumask);
2879 /* Tally up the load of all CPUs in the group */
2880 sum_weighted_load = sum_nr_running = avg_load = 0;
2881 max_cpu_load = 0;
2882 min_cpu_load = ~0UL;
2884 for_each_cpu_mask(i, group->cpumask) {
2885 struct rq *rq;
2887 if (!cpu_isset(i, *cpus))
2888 continue;
2890 rq = cpu_rq(i);
2892 if (*sd_idle && rq->nr_running)
2893 *sd_idle = 0;
2895 /* Bias balancing toward cpus of our domain */
2896 if (local_group) {
2897 if (idle_cpu(i) && !first_idle_cpu) {
2898 first_idle_cpu = 1;
2899 balance_cpu = i;
2902 load = target_load(i, load_idx);
2903 } else {
2904 load = source_load(i, load_idx);
2905 if (load > max_cpu_load)
2906 max_cpu_load = load;
2907 if (min_cpu_load > load)
2908 min_cpu_load = load;
2911 avg_load += load;
2912 sum_nr_running += rq->nr_running;
2913 sum_weighted_load += weighted_cpuload(i);
2917 * First idle cpu or the first cpu(busiest) in this sched group
2918 * is eligible for doing load balancing at this and above
2919 * domains. In the newly idle case, we will allow all the cpu's
2920 * to do the newly idle load balance.
2922 if (idle != CPU_NEWLY_IDLE && local_group &&
2923 balance_cpu != this_cpu && balance) {
2924 *balance = 0;
2925 goto ret;
2928 total_load += avg_load;
2929 total_pwr += group->__cpu_power;
2931 /* Adjust by relative CPU power of the group */
2932 avg_load = sg_div_cpu_power(group,
2933 avg_load * SCHED_LOAD_SCALE);
2935 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2936 __group_imb = 1;
2938 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2940 if (local_group) {
2941 this_load = avg_load;
2942 this = group;
2943 this_nr_running = sum_nr_running;
2944 this_load_per_task = sum_weighted_load;
2945 } else if (avg_load > max_load &&
2946 (sum_nr_running > group_capacity || __group_imb)) {
2947 max_load = avg_load;
2948 busiest = group;
2949 busiest_nr_running = sum_nr_running;
2950 busiest_load_per_task = sum_weighted_load;
2951 group_imb = __group_imb;
2954 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2956 * Busy processors will not participate in power savings
2957 * balance.
2959 if (idle == CPU_NOT_IDLE ||
2960 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2961 goto group_next;
2964 * If the local group is idle or completely loaded
2965 * no need to do power savings balance at this domain
2967 if (local_group && (this_nr_running >= group_capacity ||
2968 !this_nr_running))
2969 power_savings_balance = 0;
2972 * If a group is already running at full capacity or idle,
2973 * don't include that group in power savings calculations
2975 if (!power_savings_balance || sum_nr_running >= group_capacity
2976 || !sum_nr_running)
2977 goto group_next;
2980 * Calculate the group which has the least non-idle load.
2981 * This is the group from where we need to pick up the load
2982 * for saving power
2984 if ((sum_nr_running < min_nr_running) ||
2985 (sum_nr_running == min_nr_running &&
2986 first_cpu(group->cpumask) <
2987 first_cpu(group_min->cpumask))) {
2988 group_min = group;
2989 min_nr_running = sum_nr_running;
2990 min_load_per_task = sum_weighted_load /
2991 sum_nr_running;
2995 * Calculate the group which is almost near its
2996 * capacity but still has some space to pick up some load
2997 * from other group and save more power
2999 if (sum_nr_running <= group_capacity - 1) {
3000 if (sum_nr_running > leader_nr_running ||
3001 (sum_nr_running == leader_nr_running &&
3002 first_cpu(group->cpumask) >
3003 first_cpu(group_leader->cpumask))) {
3004 group_leader = group;
3005 leader_nr_running = sum_nr_running;
3008 group_next:
3009 #endif
3010 group = group->next;
3011 } while (group != sd->groups);
3013 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3014 goto out_balanced;
3016 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3018 if (this_load >= avg_load ||
3019 100*max_load <= sd->imbalance_pct*this_load)
3020 goto out_balanced;
3022 busiest_load_per_task /= busiest_nr_running;
3023 if (group_imb)
3024 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3027 * We're trying to get all the cpus to the average_load, so we don't
3028 * want to push ourselves above the average load, nor do we wish to
3029 * reduce the max loaded cpu below the average load, as either of these
3030 * actions would just result in more rebalancing later, and ping-pong
3031 * tasks around. Thus we look for the minimum possible imbalance.
3032 * Negative imbalances (*we* are more loaded than anyone else) will
3033 * be counted as no imbalance for these purposes -- we can't fix that
3034 * by pulling tasks to us. Be careful of negative numbers as they'll
3035 * appear as very large values with unsigned longs.
3037 if (max_load <= busiest_load_per_task)
3038 goto out_balanced;
3041 * In the presence of smp nice balancing, certain scenarios can have
3042 * max load less than avg load(as we skip the groups at or below
3043 * its cpu_power, while calculating max_load..)
3045 if (max_load < avg_load) {
3046 *imbalance = 0;
3047 goto small_imbalance;
3050 /* Don't want to pull so many tasks that a group would go idle */
3051 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3053 /* How much load to actually move to equalise the imbalance */
3054 *imbalance = min(max_pull * busiest->__cpu_power,
3055 (avg_load - this_load) * this->__cpu_power)
3056 / SCHED_LOAD_SCALE;
3059 * if *imbalance is less than the average load per runnable task
3060 * there is no gaurantee that any tasks will be moved so we'll have
3061 * a think about bumping its value to force at least one task to be
3062 * moved
3064 if (*imbalance < busiest_load_per_task) {
3065 unsigned long tmp, pwr_now, pwr_move;
3066 unsigned int imbn;
3068 small_imbalance:
3069 pwr_move = pwr_now = 0;
3070 imbn = 2;
3071 if (this_nr_running) {
3072 this_load_per_task /= this_nr_running;
3073 if (busiest_load_per_task > this_load_per_task)
3074 imbn = 1;
3075 } else
3076 this_load_per_task = SCHED_LOAD_SCALE;
3078 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3079 busiest_load_per_task * imbn) {
3080 *imbalance = busiest_load_per_task;
3081 return busiest;
3085 * OK, we don't have enough imbalance to justify moving tasks,
3086 * however we may be able to increase total CPU power used by
3087 * moving them.
3090 pwr_now += busiest->__cpu_power *
3091 min(busiest_load_per_task, max_load);
3092 pwr_now += this->__cpu_power *
3093 min(this_load_per_task, this_load);
3094 pwr_now /= SCHED_LOAD_SCALE;
3096 /* Amount of load we'd subtract */
3097 tmp = sg_div_cpu_power(busiest,
3098 busiest_load_per_task * SCHED_LOAD_SCALE);
3099 if (max_load > tmp)
3100 pwr_move += busiest->__cpu_power *
3101 min(busiest_load_per_task, max_load - tmp);
3103 /* Amount of load we'd add */
3104 if (max_load * busiest->__cpu_power <
3105 busiest_load_per_task * SCHED_LOAD_SCALE)
3106 tmp = sg_div_cpu_power(this,
3107 max_load * busiest->__cpu_power);
3108 else
3109 tmp = sg_div_cpu_power(this,
3110 busiest_load_per_task * SCHED_LOAD_SCALE);
3111 pwr_move += this->__cpu_power *
3112 min(this_load_per_task, this_load + tmp);
3113 pwr_move /= SCHED_LOAD_SCALE;
3115 /* Move if we gain throughput */
3116 if (pwr_move > pwr_now)
3117 *imbalance = busiest_load_per_task;
3120 return busiest;
3122 out_balanced:
3123 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3124 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3125 goto ret;
3127 if (this == group_leader && group_leader != group_min) {
3128 *imbalance = min_load_per_task;
3129 return group_min;
3131 #endif
3132 ret:
3133 *imbalance = 0;
3134 return NULL;
3138 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3140 static struct rq *
3141 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3142 unsigned long imbalance, const cpumask_t *cpus)
3144 struct rq *busiest = NULL, *rq;
3145 unsigned long max_load = 0;
3146 int i;
3148 for_each_cpu_mask(i, group->cpumask) {
3149 unsigned long wl;
3151 if (!cpu_isset(i, *cpus))
3152 continue;
3154 rq = cpu_rq(i);
3155 wl = weighted_cpuload(i);
3157 if (rq->nr_running == 1 && wl > imbalance)
3158 continue;
3160 if (wl > max_load) {
3161 max_load = wl;
3162 busiest = rq;
3166 return busiest;
3170 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3171 * so long as it is large enough.
3173 #define MAX_PINNED_INTERVAL 512
3176 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3177 * tasks if there is an imbalance.
3179 static int load_balance(int this_cpu, struct rq *this_rq,
3180 struct sched_domain *sd, enum cpu_idle_type idle,
3181 int *balance, cpumask_t *cpus)
3183 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3184 struct sched_group *group;
3185 unsigned long imbalance;
3186 struct rq *busiest;
3187 unsigned long flags;
3189 cpus_setall(*cpus);
3192 * When power savings policy is enabled for the parent domain, idle
3193 * sibling can pick up load irrespective of busy siblings. In this case,
3194 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3195 * portraying it as CPU_NOT_IDLE.
3197 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3198 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3199 sd_idle = 1;
3201 schedstat_inc(sd, lb_count[idle]);
3203 redo:
3204 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3205 cpus, balance);
3207 if (*balance == 0)
3208 goto out_balanced;
3210 if (!group) {
3211 schedstat_inc(sd, lb_nobusyg[idle]);
3212 goto out_balanced;
3215 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3216 if (!busiest) {
3217 schedstat_inc(sd, lb_nobusyq[idle]);
3218 goto out_balanced;
3221 BUG_ON(busiest == this_rq);
3223 schedstat_add(sd, lb_imbalance[idle], imbalance);
3225 ld_moved = 0;
3226 if (busiest->nr_running > 1) {
3228 * Attempt to move tasks. If find_busiest_group has found
3229 * an imbalance but busiest->nr_running <= 1, the group is
3230 * still unbalanced. ld_moved simply stays zero, so it is
3231 * correctly treated as an imbalance.
3233 local_irq_save(flags);
3234 double_rq_lock(this_rq, busiest);
3235 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3236 imbalance, sd, idle, &all_pinned);
3237 double_rq_unlock(this_rq, busiest);
3238 local_irq_restore(flags);
3241 * some other cpu did the load balance for us.
3243 if (ld_moved && this_cpu != smp_processor_id())
3244 resched_cpu(this_cpu);
3246 /* All tasks on this runqueue were pinned by CPU affinity */
3247 if (unlikely(all_pinned)) {
3248 cpu_clear(cpu_of(busiest), *cpus);
3249 if (!cpus_empty(*cpus))
3250 goto redo;
3251 goto out_balanced;
3255 if (!ld_moved) {
3256 schedstat_inc(sd, lb_failed[idle]);
3257 sd->nr_balance_failed++;
3259 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3261 spin_lock_irqsave(&busiest->lock, flags);
3263 /* don't kick the migration_thread, if the curr
3264 * task on busiest cpu can't be moved to this_cpu
3266 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3267 spin_unlock_irqrestore(&busiest->lock, flags);
3268 all_pinned = 1;
3269 goto out_one_pinned;
3272 if (!busiest->active_balance) {
3273 busiest->active_balance = 1;
3274 busiest->push_cpu = this_cpu;
3275 active_balance = 1;
3277 spin_unlock_irqrestore(&busiest->lock, flags);
3278 if (active_balance)
3279 wake_up_process(busiest->migration_thread);
3282 * We've kicked active balancing, reset the failure
3283 * counter.
3285 sd->nr_balance_failed = sd->cache_nice_tries+1;
3287 } else
3288 sd->nr_balance_failed = 0;
3290 if (likely(!active_balance)) {
3291 /* We were unbalanced, so reset the balancing interval */
3292 sd->balance_interval = sd->min_interval;
3293 } else {
3295 * If we've begun active balancing, start to back off. This
3296 * case may not be covered by the all_pinned logic if there
3297 * is only 1 task on the busy runqueue (because we don't call
3298 * move_tasks).
3300 if (sd->balance_interval < sd->max_interval)
3301 sd->balance_interval *= 2;
3304 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3305 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3306 return -1;
3307 return ld_moved;
3309 out_balanced:
3310 schedstat_inc(sd, lb_balanced[idle]);
3312 sd->nr_balance_failed = 0;
3314 out_one_pinned:
3315 /* tune up the balancing interval */
3316 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3317 (sd->balance_interval < sd->max_interval))
3318 sd->balance_interval *= 2;
3320 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3321 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3322 return -1;
3323 return 0;
3327 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3328 * tasks if there is an imbalance.
3330 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3331 * this_rq is locked.
3333 static int
3334 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3335 cpumask_t *cpus)
3337 struct sched_group *group;
3338 struct rq *busiest = NULL;
3339 unsigned long imbalance;
3340 int ld_moved = 0;
3341 int sd_idle = 0;
3342 int all_pinned = 0;
3344 cpus_setall(*cpus);
3347 * When power savings policy is enabled for the parent domain, idle
3348 * sibling can pick up load irrespective of busy siblings. In this case,
3349 * let the state of idle sibling percolate up as IDLE, instead of
3350 * portraying it as CPU_NOT_IDLE.
3352 if (sd->flags & SD_SHARE_CPUPOWER &&
3353 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3354 sd_idle = 1;
3356 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3357 redo:
3358 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3359 &sd_idle, cpus, NULL);
3360 if (!group) {
3361 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3362 goto out_balanced;
3365 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3366 if (!busiest) {
3367 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3368 goto out_balanced;
3371 BUG_ON(busiest == this_rq);
3373 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3375 ld_moved = 0;
3376 if (busiest->nr_running > 1) {
3377 /* Attempt to move tasks */
3378 double_lock_balance(this_rq, busiest);
3379 /* this_rq->clock is already updated */
3380 update_rq_clock(busiest);
3381 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3382 imbalance, sd, CPU_NEWLY_IDLE,
3383 &all_pinned);
3384 spin_unlock(&busiest->lock);
3386 if (unlikely(all_pinned)) {
3387 cpu_clear(cpu_of(busiest), *cpus);
3388 if (!cpus_empty(*cpus))
3389 goto redo;
3393 if (!ld_moved) {
3394 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3395 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3396 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3397 return -1;
3398 } else
3399 sd->nr_balance_failed = 0;
3401 return ld_moved;
3403 out_balanced:
3404 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3405 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3406 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3407 return -1;
3408 sd->nr_balance_failed = 0;
3410 return 0;
3414 * idle_balance is called by schedule() if this_cpu is about to become
3415 * idle. Attempts to pull tasks from other CPUs.
3417 static void idle_balance(int this_cpu, struct rq *this_rq)
3419 struct sched_domain *sd;
3420 int pulled_task = -1;
3421 unsigned long next_balance = jiffies + HZ;
3422 cpumask_t tmpmask;
3424 for_each_domain(this_cpu, sd) {
3425 unsigned long interval;
3427 if (!(sd->flags & SD_LOAD_BALANCE))
3428 continue;
3430 if (sd->flags & SD_BALANCE_NEWIDLE)
3431 /* If we've pulled tasks over stop searching: */
3432 pulled_task = load_balance_newidle(this_cpu, this_rq,
3433 sd, &tmpmask);
3435 interval = msecs_to_jiffies(sd->balance_interval);
3436 if (time_after(next_balance, sd->last_balance + interval))
3437 next_balance = sd->last_balance + interval;
3438 if (pulled_task)
3439 break;
3441 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3443 * We are going idle. next_balance may be set based on
3444 * a busy processor. So reset next_balance.
3446 this_rq->next_balance = next_balance;
3451 * active_load_balance is run by migration threads. It pushes running tasks
3452 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3453 * running on each physical CPU where possible, and avoids physical /
3454 * logical imbalances.
3456 * Called with busiest_rq locked.
3458 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3460 int target_cpu = busiest_rq->push_cpu;
3461 struct sched_domain *sd;
3462 struct rq *target_rq;
3464 /* Is there any task to move? */
3465 if (busiest_rq->nr_running <= 1)
3466 return;
3468 target_rq = cpu_rq(target_cpu);
3471 * This condition is "impossible", if it occurs
3472 * we need to fix it. Originally reported by
3473 * Bjorn Helgaas on a 128-cpu setup.
3475 BUG_ON(busiest_rq == target_rq);
3477 /* move a task from busiest_rq to target_rq */
3478 double_lock_balance(busiest_rq, target_rq);
3479 update_rq_clock(busiest_rq);
3480 update_rq_clock(target_rq);
3482 /* Search for an sd spanning us and the target CPU. */
3483 for_each_domain(target_cpu, sd) {
3484 if ((sd->flags & SD_LOAD_BALANCE) &&
3485 cpu_isset(busiest_cpu, sd->span))
3486 break;
3489 if (likely(sd)) {
3490 schedstat_inc(sd, alb_count);
3492 if (move_one_task(target_rq, target_cpu, busiest_rq,
3493 sd, CPU_IDLE))
3494 schedstat_inc(sd, alb_pushed);
3495 else
3496 schedstat_inc(sd, alb_failed);
3498 spin_unlock(&target_rq->lock);
3501 #ifdef CONFIG_NO_HZ
3502 static struct {
3503 atomic_t load_balancer;
3504 cpumask_t cpu_mask;
3505 } nohz ____cacheline_aligned = {
3506 .load_balancer = ATOMIC_INIT(-1),
3507 .cpu_mask = CPU_MASK_NONE,
3511 * This routine will try to nominate the ilb (idle load balancing)
3512 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3513 * load balancing on behalf of all those cpus. If all the cpus in the system
3514 * go into this tickless mode, then there will be no ilb owner (as there is
3515 * no need for one) and all the cpus will sleep till the next wakeup event
3516 * arrives...
3518 * For the ilb owner, tick is not stopped. And this tick will be used
3519 * for idle load balancing. ilb owner will still be part of
3520 * nohz.cpu_mask..
3522 * While stopping the tick, this cpu will become the ilb owner if there
3523 * is no other owner. And will be the owner till that cpu becomes busy
3524 * or if all cpus in the system stop their ticks at which point
3525 * there is no need for ilb owner.
3527 * When the ilb owner becomes busy, it nominates another owner, during the
3528 * next busy scheduler_tick()
3530 int select_nohz_load_balancer(int stop_tick)
3532 int cpu = smp_processor_id();
3534 if (stop_tick) {
3535 cpu_set(cpu, nohz.cpu_mask);
3536 cpu_rq(cpu)->in_nohz_recently = 1;
3539 * If we are going offline and still the leader, give up!
3541 if (cpu_is_offline(cpu) &&
3542 atomic_read(&nohz.load_balancer) == cpu) {
3543 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3544 BUG();
3545 return 0;
3548 /* time for ilb owner also to sleep */
3549 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3550 if (atomic_read(&nohz.load_balancer) == cpu)
3551 atomic_set(&nohz.load_balancer, -1);
3552 return 0;
3555 if (atomic_read(&nohz.load_balancer) == -1) {
3556 /* make me the ilb owner */
3557 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3558 return 1;
3559 } else if (atomic_read(&nohz.load_balancer) == cpu)
3560 return 1;
3561 } else {
3562 if (!cpu_isset(cpu, nohz.cpu_mask))
3563 return 0;
3565 cpu_clear(cpu, nohz.cpu_mask);
3567 if (atomic_read(&nohz.load_balancer) == cpu)
3568 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3569 BUG();
3571 return 0;
3573 #endif
3575 static DEFINE_SPINLOCK(balancing);
3578 * It checks each scheduling domain to see if it is due to be balanced,
3579 * and initiates a balancing operation if so.
3581 * Balancing parameters are set up in arch_init_sched_domains.
3583 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3585 int balance = 1;
3586 struct rq *rq = cpu_rq(cpu);
3587 unsigned long interval;
3588 struct sched_domain *sd;
3589 /* Earliest time when we have to do rebalance again */
3590 unsigned long next_balance = jiffies + 60*HZ;
3591 int update_next_balance = 0;
3592 cpumask_t tmp;
3594 for_each_domain(cpu, sd) {
3595 if (!(sd->flags & SD_LOAD_BALANCE))
3596 continue;
3598 interval = sd->balance_interval;
3599 if (idle != CPU_IDLE)
3600 interval *= sd->busy_factor;
3602 /* scale ms to jiffies */
3603 interval = msecs_to_jiffies(interval);
3604 if (unlikely(!interval))
3605 interval = 1;
3606 if (interval > HZ*NR_CPUS/10)
3607 interval = HZ*NR_CPUS/10;
3610 if (sd->flags & SD_SERIALIZE) {
3611 if (!spin_trylock(&balancing))
3612 goto out;
3615 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3616 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
3618 * We've pulled tasks over so either we're no
3619 * longer idle, or one of our SMT siblings is
3620 * not idle.
3622 idle = CPU_NOT_IDLE;
3624 sd->last_balance = jiffies;
3626 if (sd->flags & SD_SERIALIZE)
3627 spin_unlock(&balancing);
3628 out:
3629 if (time_after(next_balance, sd->last_balance + interval)) {
3630 next_balance = sd->last_balance + interval;
3631 update_next_balance = 1;
3635 * Stop the load balance at this level. There is another
3636 * CPU in our sched group which is doing load balancing more
3637 * actively.
3639 if (!balance)
3640 break;
3644 * next_balance will be updated only when there is a need.
3645 * When the cpu is attached to null domain for ex, it will not be
3646 * updated.
3648 if (likely(update_next_balance))
3649 rq->next_balance = next_balance;
3653 * run_rebalance_domains is triggered when needed from the scheduler tick.
3654 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3655 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3657 static void run_rebalance_domains(struct softirq_action *h)
3659 int this_cpu = smp_processor_id();
3660 struct rq *this_rq = cpu_rq(this_cpu);
3661 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3662 CPU_IDLE : CPU_NOT_IDLE;
3664 rebalance_domains(this_cpu, idle);
3666 #ifdef CONFIG_NO_HZ
3668 * If this cpu is the owner for idle load balancing, then do the
3669 * balancing on behalf of the other idle cpus whose ticks are
3670 * stopped.
3672 if (this_rq->idle_at_tick &&
3673 atomic_read(&nohz.load_balancer) == this_cpu) {
3674 cpumask_t cpus = nohz.cpu_mask;
3675 struct rq *rq;
3676 int balance_cpu;
3678 cpu_clear(this_cpu, cpus);
3679 for_each_cpu_mask(balance_cpu, cpus) {
3681 * If this cpu gets work to do, stop the load balancing
3682 * work being done for other cpus. Next load
3683 * balancing owner will pick it up.
3685 if (need_resched())
3686 break;
3688 rebalance_domains(balance_cpu, CPU_IDLE);
3690 rq = cpu_rq(balance_cpu);
3691 if (time_after(this_rq->next_balance, rq->next_balance))
3692 this_rq->next_balance = rq->next_balance;
3695 #endif
3699 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3701 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3702 * idle load balancing owner or decide to stop the periodic load balancing,
3703 * if the whole system is idle.
3705 static inline void trigger_load_balance(struct rq *rq, int cpu)
3707 #ifdef CONFIG_NO_HZ
3709 * If we were in the nohz mode recently and busy at the current
3710 * scheduler tick, then check if we need to nominate new idle
3711 * load balancer.
3713 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3714 rq->in_nohz_recently = 0;
3716 if (atomic_read(&nohz.load_balancer) == cpu) {
3717 cpu_clear(cpu, nohz.cpu_mask);
3718 atomic_set(&nohz.load_balancer, -1);
3721 if (atomic_read(&nohz.load_balancer) == -1) {
3723 * simple selection for now: Nominate the
3724 * first cpu in the nohz list to be the next
3725 * ilb owner.
3727 * TBD: Traverse the sched domains and nominate
3728 * the nearest cpu in the nohz.cpu_mask.
3730 int ilb = first_cpu(nohz.cpu_mask);
3732 if (ilb < nr_cpu_ids)
3733 resched_cpu(ilb);
3738 * If this cpu is idle and doing idle load balancing for all the
3739 * cpus with ticks stopped, is it time for that to stop?
3741 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3742 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3743 resched_cpu(cpu);
3744 return;
3748 * If this cpu is idle and the idle load balancing is done by
3749 * someone else, then no need raise the SCHED_SOFTIRQ
3751 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3752 cpu_isset(cpu, nohz.cpu_mask))
3753 return;
3754 #endif
3755 if (time_after_eq(jiffies, rq->next_balance))
3756 raise_softirq(SCHED_SOFTIRQ);
3759 #else /* CONFIG_SMP */
3762 * on UP we do not need to balance between CPUs:
3764 static inline void idle_balance(int cpu, struct rq *rq)
3768 #endif
3770 DEFINE_PER_CPU(struct kernel_stat, kstat);
3772 EXPORT_PER_CPU_SYMBOL(kstat);
3775 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3776 * that have not yet been banked in case the task is currently running.
3778 unsigned long long task_sched_runtime(struct task_struct *p)
3780 unsigned long flags;
3781 u64 ns, delta_exec;
3782 struct rq *rq;
3784 rq = task_rq_lock(p, &flags);
3785 ns = p->se.sum_exec_runtime;
3786 if (task_current(rq, p)) {
3787 update_rq_clock(rq);
3788 delta_exec = rq->clock - p->se.exec_start;
3789 if ((s64)delta_exec > 0)
3790 ns += delta_exec;
3792 task_rq_unlock(rq, &flags);
3794 return ns;
3798 * Account user cpu time to a process.
3799 * @p: the process that the cpu time gets accounted to
3800 * @cputime: the cpu time spent in user space since the last update
3802 void account_user_time(struct task_struct *p, cputime_t cputime)
3804 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3805 cputime64_t tmp;
3807 p->utime = cputime_add(p->utime, cputime);
3809 /* Add user time to cpustat. */
3810 tmp = cputime_to_cputime64(cputime);
3811 if (TASK_NICE(p) > 0)
3812 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3813 else
3814 cpustat->user = cputime64_add(cpustat->user, tmp);
3818 * Account guest cpu time to a process.
3819 * @p: the process that the cpu time gets accounted to
3820 * @cputime: the cpu time spent in virtual machine since the last update
3822 static void account_guest_time(struct task_struct *p, cputime_t cputime)
3824 cputime64_t tmp;
3825 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3827 tmp = cputime_to_cputime64(cputime);
3829 p->utime = cputime_add(p->utime, cputime);
3830 p->gtime = cputime_add(p->gtime, cputime);
3832 cpustat->user = cputime64_add(cpustat->user, tmp);
3833 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3837 * Account scaled user cpu time to a process.
3838 * @p: the process that the cpu time gets accounted to
3839 * @cputime: the cpu time spent in user space since the last update
3841 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3843 p->utimescaled = cputime_add(p->utimescaled, cputime);
3847 * Account system cpu time to a process.
3848 * @p: the process that the cpu time gets accounted to
3849 * @hardirq_offset: the offset to subtract from hardirq_count()
3850 * @cputime: the cpu time spent in kernel space since the last update
3852 void account_system_time(struct task_struct *p, int hardirq_offset,
3853 cputime_t cputime)
3855 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3856 struct rq *rq = this_rq();
3857 cputime64_t tmp;
3859 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3860 return account_guest_time(p, cputime);
3862 p->stime = cputime_add(p->stime, cputime);
3864 /* Add system time to cpustat. */
3865 tmp = cputime_to_cputime64(cputime);
3866 if (hardirq_count() - hardirq_offset)
3867 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3868 else if (softirq_count())
3869 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3870 else if (p != rq->idle)
3871 cpustat->system = cputime64_add(cpustat->system, tmp);
3872 else if (atomic_read(&rq->nr_iowait) > 0)
3873 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3874 else
3875 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3876 /* Account for system time used */
3877 acct_update_integrals(p);
3881 * Account scaled system cpu time to a process.
3882 * @p: the process that the cpu time gets accounted to
3883 * @hardirq_offset: the offset to subtract from hardirq_count()
3884 * @cputime: the cpu time spent in kernel space since the last update
3886 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3888 p->stimescaled = cputime_add(p->stimescaled, cputime);
3892 * Account for involuntary wait time.
3893 * @p: the process from which the cpu time has been stolen
3894 * @steal: the cpu time spent in involuntary wait
3896 void account_steal_time(struct task_struct *p, cputime_t steal)
3898 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3899 cputime64_t tmp = cputime_to_cputime64(steal);
3900 struct rq *rq = this_rq();
3902 if (p == rq->idle) {
3903 p->stime = cputime_add(p->stime, steal);
3904 if (atomic_read(&rq->nr_iowait) > 0)
3905 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3906 else
3907 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3908 } else
3909 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3913 * This function gets called by the timer code, with HZ frequency.
3914 * We call it with interrupts disabled.
3916 * It also gets called by the fork code, when changing the parent's
3917 * timeslices.
3919 void scheduler_tick(void)
3921 int cpu = smp_processor_id();
3922 struct rq *rq = cpu_rq(cpu);
3923 struct task_struct *curr = rq->curr;
3924 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3926 spin_lock(&rq->lock);
3927 __update_rq_clock(rq);
3929 * Let rq->clock advance by at least TICK_NSEC:
3931 if (unlikely(rq->clock < next_tick)) {
3932 rq->clock = next_tick;
3933 rq->clock_underflows++;
3935 rq->tick_timestamp = rq->clock;
3936 update_last_tick_seen(rq);
3937 update_cpu_load(rq);
3938 curr->sched_class->task_tick(rq, curr, 0);
3939 spin_unlock(&rq->lock);
3941 #ifdef CONFIG_SMP
3942 rq->idle_at_tick = idle_cpu(cpu);
3943 trigger_load_balance(rq, cpu);
3944 #endif
3947 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3949 void __kprobes add_preempt_count(int val)
3952 * Underflow?
3954 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3955 return;
3956 preempt_count() += val;
3958 * Spinlock count overflowing soon?
3960 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3961 PREEMPT_MASK - 10);
3963 EXPORT_SYMBOL(add_preempt_count);
3965 void __kprobes sub_preempt_count(int val)
3968 * Underflow?
3970 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3971 return;
3973 * Is the spinlock portion underflowing?
3975 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3976 !(preempt_count() & PREEMPT_MASK)))
3977 return;
3979 preempt_count() -= val;
3981 EXPORT_SYMBOL(sub_preempt_count);
3983 #endif
3986 * Print scheduling while atomic bug:
3988 static noinline void __schedule_bug(struct task_struct *prev)
3990 struct pt_regs *regs = get_irq_regs();
3992 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3993 prev->comm, prev->pid, preempt_count());
3995 debug_show_held_locks(prev);
3996 if (irqs_disabled())
3997 print_irqtrace_events(prev);
3999 if (regs)
4000 show_regs(regs);
4001 else
4002 dump_stack();
4006 * Various schedule()-time debugging checks and statistics:
4008 static inline void schedule_debug(struct task_struct *prev)
4011 * Test if we are atomic. Since do_exit() needs to call into
4012 * schedule() atomically, we ignore that path for now.
4013 * Otherwise, whine if we are scheduling when we should not be.
4015 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4016 __schedule_bug(prev);
4018 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4020 schedstat_inc(this_rq(), sched_count);
4021 #ifdef CONFIG_SCHEDSTATS
4022 if (unlikely(prev->lock_depth >= 0)) {
4023 schedstat_inc(this_rq(), bkl_count);
4024 schedstat_inc(prev, sched_info.bkl_count);
4026 #endif
4030 * Pick up the highest-prio task:
4032 static inline struct task_struct *
4033 pick_next_task(struct rq *rq, struct task_struct *prev)
4035 const struct sched_class *class;
4036 struct task_struct *p;
4039 * Optimization: we know that if all tasks are in
4040 * the fair class we can call that function directly:
4042 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4043 p = fair_sched_class.pick_next_task(rq);
4044 if (likely(p))
4045 return p;
4048 class = sched_class_highest;
4049 for ( ; ; ) {
4050 p = class->pick_next_task(rq);
4051 if (p)
4052 return p;
4054 * Will never be NULL as the idle class always
4055 * returns a non-NULL p:
4057 class = class->next;
4062 * schedule() is the main scheduler function.
4064 asmlinkage void __sched schedule(void)
4066 struct task_struct *prev, *next;
4067 unsigned long *switch_count;
4068 struct rq *rq;
4069 int cpu;
4071 need_resched:
4072 preempt_disable();
4073 cpu = smp_processor_id();
4074 rq = cpu_rq(cpu);
4075 rcu_qsctr_inc(cpu);
4076 prev = rq->curr;
4077 switch_count = &prev->nivcsw;
4079 release_kernel_lock(prev);
4080 need_resched_nonpreemptible:
4082 schedule_debug(prev);
4084 hrtick_clear(rq);
4087 * Do the rq-clock update outside the rq lock:
4089 local_irq_disable();
4090 __update_rq_clock(rq);
4091 spin_lock(&rq->lock);
4092 clear_tsk_need_resched(prev);
4094 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4095 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4096 signal_pending(prev))) {
4097 prev->state = TASK_RUNNING;
4098 } else {
4099 deactivate_task(rq, prev, 1);
4101 switch_count = &prev->nvcsw;
4104 #ifdef CONFIG_SMP
4105 if (prev->sched_class->pre_schedule)
4106 prev->sched_class->pre_schedule(rq, prev);
4107 #endif
4109 if (unlikely(!rq->nr_running))
4110 idle_balance(cpu, rq);
4112 prev->sched_class->put_prev_task(rq, prev);
4113 next = pick_next_task(rq, prev);
4115 sched_info_switch(prev, next);
4117 if (likely(prev != next)) {
4118 rq->nr_switches++;
4119 rq->curr = next;
4120 ++*switch_count;
4122 context_switch(rq, prev, next); /* unlocks the rq */
4124 * the context switch might have flipped the stack from under
4125 * us, hence refresh the local variables.
4127 cpu = smp_processor_id();
4128 rq = cpu_rq(cpu);
4129 } else
4130 spin_unlock_irq(&rq->lock);
4132 hrtick_set(rq);
4134 if (unlikely(reacquire_kernel_lock(current) < 0))
4135 goto need_resched_nonpreemptible;
4137 preempt_enable_no_resched();
4138 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4139 goto need_resched;
4141 EXPORT_SYMBOL(schedule);
4143 #ifdef CONFIG_PREEMPT
4145 * this is the entry point to schedule() from in-kernel preemption
4146 * off of preempt_enable. Kernel preemptions off return from interrupt
4147 * occur there and call schedule directly.
4149 asmlinkage void __sched preempt_schedule(void)
4151 struct thread_info *ti = current_thread_info();
4152 struct task_struct *task = current;
4153 int saved_lock_depth;
4156 * If there is a non-zero preempt_count or interrupts are disabled,
4157 * we do not want to preempt the current task. Just return..
4159 if (likely(ti->preempt_count || irqs_disabled()))
4160 return;
4162 do {
4163 add_preempt_count(PREEMPT_ACTIVE);
4166 * We keep the big kernel semaphore locked, but we
4167 * clear ->lock_depth so that schedule() doesnt
4168 * auto-release the semaphore:
4170 saved_lock_depth = task->lock_depth;
4171 task->lock_depth = -1;
4172 schedule();
4173 task->lock_depth = saved_lock_depth;
4174 sub_preempt_count(PREEMPT_ACTIVE);
4177 * Check again in case we missed a preemption opportunity
4178 * between schedule and now.
4180 barrier();
4181 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4183 EXPORT_SYMBOL(preempt_schedule);
4186 * this is the entry point to schedule() from kernel preemption
4187 * off of irq context.
4188 * Note, that this is called and return with irqs disabled. This will
4189 * protect us against recursive calling from irq.
4191 asmlinkage void __sched preempt_schedule_irq(void)
4193 struct thread_info *ti = current_thread_info();
4194 struct task_struct *task = current;
4195 int saved_lock_depth;
4197 /* Catch callers which need to be fixed */
4198 BUG_ON(ti->preempt_count || !irqs_disabled());
4200 do {
4201 add_preempt_count(PREEMPT_ACTIVE);
4204 * We keep the big kernel semaphore locked, but we
4205 * clear ->lock_depth so that schedule() doesnt
4206 * auto-release the semaphore:
4208 saved_lock_depth = task->lock_depth;
4209 task->lock_depth = -1;
4210 local_irq_enable();
4211 schedule();
4212 local_irq_disable();
4213 task->lock_depth = saved_lock_depth;
4214 sub_preempt_count(PREEMPT_ACTIVE);
4217 * Check again in case we missed a preemption opportunity
4218 * between schedule and now.
4220 barrier();
4221 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4224 #endif /* CONFIG_PREEMPT */
4226 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4227 void *key)
4229 return try_to_wake_up(curr->private, mode, sync);
4231 EXPORT_SYMBOL(default_wake_function);
4234 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4235 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4236 * number) then we wake all the non-exclusive tasks and one exclusive task.
4238 * There are circumstances in which we can try to wake a task which has already
4239 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4240 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4242 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4243 int nr_exclusive, int sync, void *key)
4245 wait_queue_t *curr, *next;
4247 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4248 unsigned flags = curr->flags;
4250 if (curr->func(curr, mode, sync, key) &&
4251 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4252 break;
4257 * __wake_up - wake up threads blocked on a waitqueue.
4258 * @q: the waitqueue
4259 * @mode: which threads
4260 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4261 * @key: is directly passed to the wakeup function
4263 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4264 int nr_exclusive, void *key)
4266 unsigned long flags;
4268 spin_lock_irqsave(&q->lock, flags);
4269 __wake_up_common(q, mode, nr_exclusive, 0, key);
4270 spin_unlock_irqrestore(&q->lock, flags);
4272 EXPORT_SYMBOL(__wake_up);
4275 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4277 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4279 __wake_up_common(q, mode, 1, 0, NULL);
4283 * __wake_up_sync - wake up threads blocked on a waitqueue.
4284 * @q: the waitqueue
4285 * @mode: which threads
4286 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4288 * The sync wakeup differs that the waker knows that it will schedule
4289 * away soon, so while the target thread will be woken up, it will not
4290 * be migrated to another CPU - ie. the two threads are 'synchronized'
4291 * with each other. This can prevent needless bouncing between CPUs.
4293 * On UP it can prevent extra preemption.
4295 void
4296 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4298 unsigned long flags;
4299 int sync = 1;
4301 if (unlikely(!q))
4302 return;
4304 if (unlikely(!nr_exclusive))
4305 sync = 0;
4307 spin_lock_irqsave(&q->lock, flags);
4308 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4309 spin_unlock_irqrestore(&q->lock, flags);
4311 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4313 void complete(struct completion *x)
4315 unsigned long flags;
4317 spin_lock_irqsave(&x->wait.lock, flags);
4318 x->done++;
4319 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4320 spin_unlock_irqrestore(&x->wait.lock, flags);
4322 EXPORT_SYMBOL(complete);
4324 void complete_all(struct completion *x)
4326 unsigned long flags;
4328 spin_lock_irqsave(&x->wait.lock, flags);
4329 x->done += UINT_MAX/2;
4330 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4331 spin_unlock_irqrestore(&x->wait.lock, flags);
4333 EXPORT_SYMBOL(complete_all);
4335 static inline long __sched
4336 do_wait_for_common(struct completion *x, long timeout, int state)
4338 if (!x->done) {
4339 DECLARE_WAITQUEUE(wait, current);
4341 wait.flags |= WQ_FLAG_EXCLUSIVE;
4342 __add_wait_queue_tail(&x->wait, &wait);
4343 do {
4344 if ((state == TASK_INTERRUPTIBLE &&
4345 signal_pending(current)) ||
4346 (state == TASK_KILLABLE &&
4347 fatal_signal_pending(current))) {
4348 __remove_wait_queue(&x->wait, &wait);
4349 return -ERESTARTSYS;
4351 __set_current_state(state);
4352 spin_unlock_irq(&x->wait.lock);
4353 timeout = schedule_timeout(timeout);
4354 spin_lock_irq(&x->wait.lock);
4355 if (!timeout) {
4356 __remove_wait_queue(&x->wait, &wait);
4357 return timeout;
4359 } while (!x->done);
4360 __remove_wait_queue(&x->wait, &wait);
4362 x->done--;
4363 return timeout;
4366 static long __sched
4367 wait_for_common(struct completion *x, long timeout, int state)
4369 might_sleep();
4371 spin_lock_irq(&x->wait.lock);
4372 timeout = do_wait_for_common(x, timeout, state);
4373 spin_unlock_irq(&x->wait.lock);
4374 return timeout;
4377 void __sched wait_for_completion(struct completion *x)
4379 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4381 EXPORT_SYMBOL(wait_for_completion);
4383 unsigned long __sched
4384 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4386 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4388 EXPORT_SYMBOL(wait_for_completion_timeout);
4390 int __sched wait_for_completion_interruptible(struct completion *x)
4392 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4393 if (t == -ERESTARTSYS)
4394 return t;
4395 return 0;
4397 EXPORT_SYMBOL(wait_for_completion_interruptible);
4399 unsigned long __sched
4400 wait_for_completion_interruptible_timeout(struct completion *x,
4401 unsigned long timeout)
4403 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4405 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4407 int __sched wait_for_completion_killable(struct completion *x)
4409 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4410 if (t == -ERESTARTSYS)
4411 return t;
4412 return 0;
4414 EXPORT_SYMBOL(wait_for_completion_killable);
4416 static long __sched
4417 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4419 unsigned long flags;
4420 wait_queue_t wait;
4422 init_waitqueue_entry(&wait, current);
4424 __set_current_state(state);
4426 spin_lock_irqsave(&q->lock, flags);
4427 __add_wait_queue(q, &wait);
4428 spin_unlock(&q->lock);
4429 timeout = schedule_timeout(timeout);
4430 spin_lock_irq(&q->lock);
4431 __remove_wait_queue(q, &wait);
4432 spin_unlock_irqrestore(&q->lock, flags);
4434 return timeout;
4437 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4439 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4441 EXPORT_SYMBOL(interruptible_sleep_on);
4443 long __sched
4444 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4446 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4448 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4450 void __sched sleep_on(wait_queue_head_t *q)
4452 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4454 EXPORT_SYMBOL(sleep_on);
4456 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4458 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4460 EXPORT_SYMBOL(sleep_on_timeout);
4462 #ifdef CONFIG_RT_MUTEXES
4465 * rt_mutex_setprio - set the current priority of a task
4466 * @p: task
4467 * @prio: prio value (kernel-internal form)
4469 * This function changes the 'effective' priority of a task. It does
4470 * not touch ->normal_prio like __setscheduler().
4472 * Used by the rt_mutex code to implement priority inheritance logic.
4474 void rt_mutex_setprio(struct task_struct *p, int prio)
4476 unsigned long flags;
4477 int oldprio, on_rq, running;
4478 struct rq *rq;
4479 const struct sched_class *prev_class = p->sched_class;
4481 BUG_ON(prio < 0 || prio > MAX_PRIO);
4483 rq = task_rq_lock(p, &flags);
4484 update_rq_clock(rq);
4486 oldprio = p->prio;
4487 on_rq = p->se.on_rq;
4488 running = task_current(rq, p);
4489 if (on_rq)
4490 dequeue_task(rq, p, 0);
4491 if (running)
4492 p->sched_class->put_prev_task(rq, p);
4494 if (rt_prio(prio))
4495 p->sched_class = &rt_sched_class;
4496 else
4497 p->sched_class = &fair_sched_class;
4499 p->prio = prio;
4501 if (running)
4502 p->sched_class->set_curr_task(rq);
4503 if (on_rq) {
4504 enqueue_task(rq, p, 0);
4506 check_class_changed(rq, p, prev_class, oldprio, running);
4508 task_rq_unlock(rq, &flags);
4511 #endif
4513 void set_user_nice(struct task_struct *p, long nice)
4515 int old_prio, delta, on_rq;
4516 unsigned long flags;
4517 struct rq *rq;
4519 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4520 return;
4522 * We have to be careful, if called from sys_setpriority(),
4523 * the task might be in the middle of scheduling on another CPU.
4525 rq = task_rq_lock(p, &flags);
4526 update_rq_clock(rq);
4528 * The RT priorities are set via sched_setscheduler(), but we still
4529 * allow the 'normal' nice value to be set - but as expected
4530 * it wont have any effect on scheduling until the task is
4531 * SCHED_FIFO/SCHED_RR:
4533 if (task_has_rt_policy(p)) {
4534 p->static_prio = NICE_TO_PRIO(nice);
4535 goto out_unlock;
4537 on_rq = p->se.on_rq;
4538 if (on_rq) {
4539 dequeue_task(rq, p, 0);
4540 dec_load(rq, p);
4543 p->static_prio = NICE_TO_PRIO(nice);
4544 set_load_weight(p);
4545 old_prio = p->prio;
4546 p->prio = effective_prio(p);
4547 delta = p->prio - old_prio;
4549 if (on_rq) {
4550 enqueue_task(rq, p, 0);
4551 inc_load(rq, p);
4553 * If the task increased its priority or is running and
4554 * lowered its priority, then reschedule its CPU:
4556 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4557 resched_task(rq->curr);
4559 out_unlock:
4560 task_rq_unlock(rq, &flags);
4562 EXPORT_SYMBOL(set_user_nice);
4565 * can_nice - check if a task can reduce its nice value
4566 * @p: task
4567 * @nice: nice value
4569 int can_nice(const struct task_struct *p, const int nice)
4571 /* convert nice value [19,-20] to rlimit style value [1,40] */
4572 int nice_rlim = 20 - nice;
4574 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4575 capable(CAP_SYS_NICE));
4578 #ifdef __ARCH_WANT_SYS_NICE
4581 * sys_nice - change the priority of the current process.
4582 * @increment: priority increment
4584 * sys_setpriority is a more generic, but much slower function that
4585 * does similar things.
4587 asmlinkage long sys_nice(int increment)
4589 long nice, retval;
4592 * Setpriority might change our priority at the same moment.
4593 * We don't have to worry. Conceptually one call occurs first
4594 * and we have a single winner.
4596 if (increment < -40)
4597 increment = -40;
4598 if (increment > 40)
4599 increment = 40;
4601 nice = PRIO_TO_NICE(current->static_prio) + increment;
4602 if (nice < -20)
4603 nice = -20;
4604 if (nice > 19)
4605 nice = 19;
4607 if (increment < 0 && !can_nice(current, nice))
4608 return -EPERM;
4610 retval = security_task_setnice(current, nice);
4611 if (retval)
4612 return retval;
4614 set_user_nice(current, nice);
4615 return 0;
4618 #endif
4621 * task_prio - return the priority value of a given task.
4622 * @p: the task in question.
4624 * This is the priority value as seen by users in /proc.
4625 * RT tasks are offset by -200. Normal tasks are centered
4626 * around 0, value goes from -16 to +15.
4628 int task_prio(const struct task_struct *p)
4630 return p->prio - MAX_RT_PRIO;
4634 * task_nice - return the nice value of a given task.
4635 * @p: the task in question.
4637 int task_nice(const struct task_struct *p)
4639 return TASK_NICE(p);
4641 EXPORT_SYMBOL(task_nice);
4644 * idle_cpu - is a given cpu idle currently?
4645 * @cpu: the processor in question.
4647 int idle_cpu(int cpu)
4649 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4653 * idle_task - return the idle task for a given cpu.
4654 * @cpu: the processor in question.
4656 struct task_struct *idle_task(int cpu)
4658 return cpu_rq(cpu)->idle;
4662 * find_process_by_pid - find a process with a matching PID value.
4663 * @pid: the pid in question.
4665 static struct task_struct *find_process_by_pid(pid_t pid)
4667 return pid ? find_task_by_vpid(pid) : current;
4670 /* Actually do priority change: must hold rq lock. */
4671 static void
4672 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4674 BUG_ON(p->se.on_rq);
4676 p->policy = policy;
4677 switch (p->policy) {
4678 case SCHED_NORMAL:
4679 case SCHED_BATCH:
4680 case SCHED_IDLE:
4681 p->sched_class = &fair_sched_class;
4682 break;
4683 case SCHED_FIFO:
4684 case SCHED_RR:
4685 p->sched_class = &rt_sched_class;
4686 break;
4689 p->rt_priority = prio;
4690 p->normal_prio = normal_prio(p);
4691 /* we are holding p->pi_lock already */
4692 p->prio = rt_mutex_getprio(p);
4693 set_load_weight(p);
4697 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4698 * @p: the task in question.
4699 * @policy: new policy.
4700 * @param: structure containing the new RT priority.
4702 * NOTE that the task may be already dead.
4704 int sched_setscheduler(struct task_struct *p, int policy,
4705 struct sched_param *param)
4707 int retval, oldprio, oldpolicy = -1, on_rq, running;
4708 unsigned long flags;
4709 const struct sched_class *prev_class = p->sched_class;
4710 struct rq *rq;
4712 /* may grab non-irq protected spin_locks */
4713 BUG_ON(in_interrupt());
4714 recheck:
4715 /* double check policy once rq lock held */
4716 if (policy < 0)
4717 policy = oldpolicy = p->policy;
4718 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4719 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4720 policy != SCHED_IDLE)
4721 return -EINVAL;
4723 * Valid priorities for SCHED_FIFO and SCHED_RR are
4724 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4725 * SCHED_BATCH and SCHED_IDLE is 0.
4727 if (param->sched_priority < 0 ||
4728 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4729 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4730 return -EINVAL;
4731 if (rt_policy(policy) != (param->sched_priority != 0))
4732 return -EINVAL;
4735 * Allow unprivileged RT tasks to decrease priority:
4737 if (!capable(CAP_SYS_NICE)) {
4738 if (rt_policy(policy)) {
4739 unsigned long rlim_rtprio;
4741 if (!lock_task_sighand(p, &flags))
4742 return -ESRCH;
4743 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4744 unlock_task_sighand(p, &flags);
4746 /* can't set/change the rt policy */
4747 if (policy != p->policy && !rlim_rtprio)
4748 return -EPERM;
4750 /* can't increase priority */
4751 if (param->sched_priority > p->rt_priority &&
4752 param->sched_priority > rlim_rtprio)
4753 return -EPERM;
4756 * Like positive nice levels, dont allow tasks to
4757 * move out of SCHED_IDLE either:
4759 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4760 return -EPERM;
4762 /* can't change other user's priorities */
4763 if ((current->euid != p->euid) &&
4764 (current->euid != p->uid))
4765 return -EPERM;
4768 #ifdef CONFIG_RT_GROUP_SCHED
4770 * Do not allow realtime tasks into groups that have no runtime
4771 * assigned.
4773 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
4774 return -EPERM;
4775 #endif
4777 retval = security_task_setscheduler(p, policy, param);
4778 if (retval)
4779 return retval;
4781 * make sure no PI-waiters arrive (or leave) while we are
4782 * changing the priority of the task:
4784 spin_lock_irqsave(&p->pi_lock, flags);
4786 * To be able to change p->policy safely, the apropriate
4787 * runqueue lock must be held.
4789 rq = __task_rq_lock(p);
4790 /* recheck policy now with rq lock held */
4791 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4792 policy = oldpolicy = -1;
4793 __task_rq_unlock(rq);
4794 spin_unlock_irqrestore(&p->pi_lock, flags);
4795 goto recheck;
4797 update_rq_clock(rq);
4798 on_rq = p->se.on_rq;
4799 running = task_current(rq, p);
4800 if (on_rq)
4801 deactivate_task(rq, p, 0);
4802 if (running)
4803 p->sched_class->put_prev_task(rq, p);
4805 oldprio = p->prio;
4806 __setscheduler(rq, p, policy, param->sched_priority);
4808 if (running)
4809 p->sched_class->set_curr_task(rq);
4810 if (on_rq) {
4811 activate_task(rq, p, 0);
4813 check_class_changed(rq, p, prev_class, oldprio, running);
4815 __task_rq_unlock(rq);
4816 spin_unlock_irqrestore(&p->pi_lock, flags);
4818 rt_mutex_adjust_pi(p);
4820 return 0;
4822 EXPORT_SYMBOL_GPL(sched_setscheduler);
4824 static int
4825 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4827 struct sched_param lparam;
4828 struct task_struct *p;
4829 int retval;
4831 if (!param || pid < 0)
4832 return -EINVAL;
4833 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4834 return -EFAULT;
4836 rcu_read_lock();
4837 retval = -ESRCH;
4838 p = find_process_by_pid(pid);
4839 if (p != NULL)
4840 retval = sched_setscheduler(p, policy, &lparam);
4841 rcu_read_unlock();
4843 return retval;
4847 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4848 * @pid: the pid in question.
4849 * @policy: new policy.
4850 * @param: structure containing the new RT priority.
4852 asmlinkage long
4853 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4855 /* negative values for policy are not valid */
4856 if (policy < 0)
4857 return -EINVAL;
4859 return do_sched_setscheduler(pid, policy, param);
4863 * sys_sched_setparam - set/change the RT priority of a thread
4864 * @pid: the pid in question.
4865 * @param: structure containing the new RT priority.
4867 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4869 return do_sched_setscheduler(pid, -1, param);
4873 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4874 * @pid: the pid in question.
4876 asmlinkage long sys_sched_getscheduler(pid_t pid)
4878 struct task_struct *p;
4879 int retval;
4881 if (pid < 0)
4882 return -EINVAL;
4884 retval = -ESRCH;
4885 read_lock(&tasklist_lock);
4886 p = find_process_by_pid(pid);
4887 if (p) {
4888 retval = security_task_getscheduler(p);
4889 if (!retval)
4890 retval = p->policy;
4892 read_unlock(&tasklist_lock);
4893 return retval;
4897 * sys_sched_getscheduler - get the RT priority of a thread
4898 * @pid: the pid in question.
4899 * @param: structure containing the RT priority.
4901 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4903 struct sched_param lp;
4904 struct task_struct *p;
4905 int retval;
4907 if (!param || pid < 0)
4908 return -EINVAL;
4910 read_lock(&tasklist_lock);
4911 p = find_process_by_pid(pid);
4912 retval = -ESRCH;
4913 if (!p)
4914 goto out_unlock;
4916 retval = security_task_getscheduler(p);
4917 if (retval)
4918 goto out_unlock;
4920 lp.sched_priority = p->rt_priority;
4921 read_unlock(&tasklist_lock);
4924 * This one might sleep, we cannot do it with a spinlock held ...
4926 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4928 return retval;
4930 out_unlock:
4931 read_unlock(&tasklist_lock);
4932 return retval;
4935 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
4937 cpumask_t cpus_allowed;
4938 cpumask_t new_mask = *in_mask;
4939 struct task_struct *p;
4940 int retval;
4942 get_online_cpus();
4943 read_lock(&tasklist_lock);
4945 p = find_process_by_pid(pid);
4946 if (!p) {
4947 read_unlock(&tasklist_lock);
4948 put_online_cpus();
4949 return -ESRCH;
4953 * It is not safe to call set_cpus_allowed with the
4954 * tasklist_lock held. We will bump the task_struct's
4955 * usage count and then drop tasklist_lock.
4957 get_task_struct(p);
4958 read_unlock(&tasklist_lock);
4960 retval = -EPERM;
4961 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4962 !capable(CAP_SYS_NICE))
4963 goto out_unlock;
4965 retval = security_task_setscheduler(p, 0, NULL);
4966 if (retval)
4967 goto out_unlock;
4969 cpuset_cpus_allowed(p, &cpus_allowed);
4970 cpus_and(new_mask, new_mask, cpus_allowed);
4971 again:
4972 retval = set_cpus_allowed_ptr(p, &new_mask);
4974 if (!retval) {
4975 cpuset_cpus_allowed(p, &cpus_allowed);
4976 if (!cpus_subset(new_mask, cpus_allowed)) {
4978 * We must have raced with a concurrent cpuset
4979 * update. Just reset the cpus_allowed to the
4980 * cpuset's cpus_allowed
4982 new_mask = cpus_allowed;
4983 goto again;
4986 out_unlock:
4987 put_task_struct(p);
4988 put_online_cpus();
4989 return retval;
4992 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4993 cpumask_t *new_mask)
4995 if (len < sizeof(cpumask_t)) {
4996 memset(new_mask, 0, sizeof(cpumask_t));
4997 } else if (len > sizeof(cpumask_t)) {
4998 len = sizeof(cpumask_t);
5000 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5004 * sys_sched_setaffinity - set the cpu affinity of a process
5005 * @pid: pid of the process
5006 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5007 * @user_mask_ptr: user-space pointer to the new cpu mask
5009 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5010 unsigned long __user *user_mask_ptr)
5012 cpumask_t new_mask;
5013 int retval;
5015 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5016 if (retval)
5017 return retval;
5019 return sched_setaffinity(pid, &new_mask);
5023 * Represents all cpu's present in the system
5024 * In systems capable of hotplug, this map could dynamically grow
5025 * as new cpu's are detected in the system via any platform specific
5026 * method, such as ACPI for e.g.
5029 cpumask_t cpu_present_map __read_mostly;
5030 EXPORT_SYMBOL(cpu_present_map);
5032 #ifndef CONFIG_SMP
5033 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5034 EXPORT_SYMBOL(cpu_online_map);
5036 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5037 EXPORT_SYMBOL(cpu_possible_map);
5038 #endif
5040 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5042 struct task_struct *p;
5043 int retval;
5045 get_online_cpus();
5046 read_lock(&tasklist_lock);
5048 retval = -ESRCH;
5049 p = find_process_by_pid(pid);
5050 if (!p)
5051 goto out_unlock;
5053 retval = security_task_getscheduler(p);
5054 if (retval)
5055 goto out_unlock;
5057 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5059 out_unlock:
5060 read_unlock(&tasklist_lock);
5061 put_online_cpus();
5063 return retval;
5067 * sys_sched_getaffinity - get the cpu affinity of a process
5068 * @pid: pid of the process
5069 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5070 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5072 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5073 unsigned long __user *user_mask_ptr)
5075 int ret;
5076 cpumask_t mask;
5078 if (len < sizeof(cpumask_t))
5079 return -EINVAL;
5081 ret = sched_getaffinity(pid, &mask);
5082 if (ret < 0)
5083 return ret;
5085 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5086 return -EFAULT;
5088 return sizeof(cpumask_t);
5092 * sys_sched_yield - yield the current processor to other threads.
5094 * This function yields the current CPU to other tasks. If there are no
5095 * other threads running on this CPU then this function will return.
5097 asmlinkage long sys_sched_yield(void)
5099 struct rq *rq = this_rq_lock();
5101 schedstat_inc(rq, yld_count);
5102 current->sched_class->yield_task(rq);
5105 * Since we are going to call schedule() anyway, there's
5106 * no need to preempt or enable interrupts:
5108 __release(rq->lock);
5109 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5110 _raw_spin_unlock(&rq->lock);
5111 preempt_enable_no_resched();
5113 schedule();
5115 return 0;
5118 static void __cond_resched(void)
5120 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5121 __might_sleep(__FILE__, __LINE__);
5122 #endif
5124 * The BKS might be reacquired before we have dropped
5125 * PREEMPT_ACTIVE, which could trigger a second
5126 * cond_resched() call.
5128 do {
5129 add_preempt_count(PREEMPT_ACTIVE);
5130 schedule();
5131 sub_preempt_count(PREEMPT_ACTIVE);
5132 } while (need_resched());
5135 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5136 int __sched _cond_resched(void)
5138 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5139 system_state == SYSTEM_RUNNING) {
5140 __cond_resched();
5141 return 1;
5143 return 0;
5145 EXPORT_SYMBOL(_cond_resched);
5146 #endif
5149 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5150 * call schedule, and on return reacquire the lock.
5152 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5153 * operations here to prevent schedule() from being called twice (once via
5154 * spin_unlock(), once by hand).
5156 int cond_resched_lock(spinlock_t *lock)
5158 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5159 int ret = 0;
5161 if (spin_needbreak(lock) || resched) {
5162 spin_unlock(lock);
5163 if (resched && need_resched())
5164 __cond_resched();
5165 else
5166 cpu_relax();
5167 ret = 1;
5168 spin_lock(lock);
5170 return ret;
5172 EXPORT_SYMBOL(cond_resched_lock);
5174 int __sched cond_resched_softirq(void)
5176 BUG_ON(!in_softirq());
5178 if (need_resched() && system_state == SYSTEM_RUNNING) {
5179 local_bh_enable();
5180 __cond_resched();
5181 local_bh_disable();
5182 return 1;
5184 return 0;
5186 EXPORT_SYMBOL(cond_resched_softirq);
5189 * yield - yield the current processor to other threads.
5191 * This is a shortcut for kernel-space yielding - it marks the
5192 * thread runnable and calls sys_sched_yield().
5194 void __sched yield(void)
5196 set_current_state(TASK_RUNNING);
5197 sys_sched_yield();
5199 EXPORT_SYMBOL(yield);
5202 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5203 * that process accounting knows that this is a task in IO wait state.
5205 * But don't do that if it is a deliberate, throttling IO wait (this task
5206 * has set its backing_dev_info: the queue against which it should throttle)
5208 void __sched io_schedule(void)
5210 struct rq *rq = &__raw_get_cpu_var(runqueues);
5212 delayacct_blkio_start();
5213 atomic_inc(&rq->nr_iowait);
5214 schedule();
5215 atomic_dec(&rq->nr_iowait);
5216 delayacct_blkio_end();
5218 EXPORT_SYMBOL(io_schedule);
5220 long __sched io_schedule_timeout(long timeout)
5222 struct rq *rq = &__raw_get_cpu_var(runqueues);
5223 long ret;
5225 delayacct_blkio_start();
5226 atomic_inc(&rq->nr_iowait);
5227 ret = schedule_timeout(timeout);
5228 atomic_dec(&rq->nr_iowait);
5229 delayacct_blkio_end();
5230 return ret;
5234 * sys_sched_get_priority_max - return maximum RT priority.
5235 * @policy: scheduling class.
5237 * this syscall returns the maximum rt_priority that can be used
5238 * by a given scheduling class.
5240 asmlinkage long sys_sched_get_priority_max(int policy)
5242 int ret = -EINVAL;
5244 switch (policy) {
5245 case SCHED_FIFO:
5246 case SCHED_RR:
5247 ret = MAX_USER_RT_PRIO-1;
5248 break;
5249 case SCHED_NORMAL:
5250 case SCHED_BATCH:
5251 case SCHED_IDLE:
5252 ret = 0;
5253 break;
5255 return ret;
5259 * sys_sched_get_priority_min - return minimum RT priority.
5260 * @policy: scheduling class.
5262 * this syscall returns the minimum rt_priority that can be used
5263 * by a given scheduling class.
5265 asmlinkage long sys_sched_get_priority_min(int policy)
5267 int ret = -EINVAL;
5269 switch (policy) {
5270 case SCHED_FIFO:
5271 case SCHED_RR:
5272 ret = 1;
5273 break;
5274 case SCHED_NORMAL:
5275 case SCHED_BATCH:
5276 case SCHED_IDLE:
5277 ret = 0;
5279 return ret;
5283 * sys_sched_rr_get_interval - return the default timeslice of a process.
5284 * @pid: pid of the process.
5285 * @interval: userspace pointer to the timeslice value.
5287 * this syscall writes the default timeslice value of a given process
5288 * into the user-space timespec buffer. A value of '0' means infinity.
5290 asmlinkage
5291 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5293 struct task_struct *p;
5294 unsigned int time_slice;
5295 int retval;
5296 struct timespec t;
5298 if (pid < 0)
5299 return -EINVAL;
5301 retval = -ESRCH;
5302 read_lock(&tasklist_lock);
5303 p = find_process_by_pid(pid);
5304 if (!p)
5305 goto out_unlock;
5307 retval = security_task_getscheduler(p);
5308 if (retval)
5309 goto out_unlock;
5312 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5313 * tasks that are on an otherwise idle runqueue:
5315 time_slice = 0;
5316 if (p->policy == SCHED_RR) {
5317 time_slice = DEF_TIMESLICE;
5318 } else if (p->policy != SCHED_FIFO) {
5319 struct sched_entity *se = &p->se;
5320 unsigned long flags;
5321 struct rq *rq;
5323 rq = task_rq_lock(p, &flags);
5324 if (rq->cfs.load.weight)
5325 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5326 task_rq_unlock(rq, &flags);
5328 read_unlock(&tasklist_lock);
5329 jiffies_to_timespec(time_slice, &t);
5330 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5331 return retval;
5333 out_unlock:
5334 read_unlock(&tasklist_lock);
5335 return retval;
5338 static const char stat_nam[] = "RSDTtZX";
5340 void sched_show_task(struct task_struct *p)
5342 unsigned long free = 0;
5343 unsigned state;
5345 state = p->state ? __ffs(p->state) + 1 : 0;
5346 printk(KERN_INFO "%-13.13s %c", p->comm,
5347 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5348 #if BITS_PER_LONG == 32
5349 if (state == TASK_RUNNING)
5350 printk(KERN_CONT " running ");
5351 else
5352 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5353 #else
5354 if (state == TASK_RUNNING)
5355 printk(KERN_CONT " running task ");
5356 else
5357 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5358 #endif
5359 #ifdef CONFIG_DEBUG_STACK_USAGE
5361 unsigned long *n = end_of_stack(p);
5362 while (!*n)
5363 n++;
5364 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5366 #endif
5367 printk(KERN_CONT "%5lu %5d %6d\n", free,
5368 task_pid_nr(p), task_pid_nr(p->real_parent));
5370 show_stack(p, NULL);
5373 void show_state_filter(unsigned long state_filter)
5375 struct task_struct *g, *p;
5377 #if BITS_PER_LONG == 32
5378 printk(KERN_INFO
5379 " task PC stack pid father\n");
5380 #else
5381 printk(KERN_INFO
5382 " task PC stack pid father\n");
5383 #endif
5384 read_lock(&tasklist_lock);
5385 do_each_thread(g, p) {
5387 * reset the NMI-timeout, listing all files on a slow
5388 * console might take alot of time:
5390 touch_nmi_watchdog();
5391 if (!state_filter || (p->state & state_filter))
5392 sched_show_task(p);
5393 } while_each_thread(g, p);
5395 touch_all_softlockup_watchdogs();
5397 #ifdef CONFIG_SCHED_DEBUG
5398 sysrq_sched_debug_show();
5399 #endif
5400 read_unlock(&tasklist_lock);
5402 * Only show locks if all tasks are dumped:
5404 if (state_filter == -1)
5405 debug_show_all_locks();
5408 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5410 idle->sched_class = &idle_sched_class;
5414 * init_idle - set up an idle thread for a given CPU
5415 * @idle: task in question
5416 * @cpu: cpu the idle task belongs to
5418 * NOTE: this function does not set the idle thread's NEED_RESCHED
5419 * flag, to make booting more robust.
5421 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5423 struct rq *rq = cpu_rq(cpu);
5424 unsigned long flags;
5426 __sched_fork(idle);
5427 idle->se.exec_start = sched_clock();
5429 idle->prio = idle->normal_prio = MAX_PRIO;
5430 idle->cpus_allowed = cpumask_of_cpu(cpu);
5431 __set_task_cpu(idle, cpu);
5433 spin_lock_irqsave(&rq->lock, flags);
5434 rq->curr = rq->idle = idle;
5435 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5436 idle->oncpu = 1;
5437 #endif
5438 spin_unlock_irqrestore(&rq->lock, flags);
5440 /* Set the preempt count _outside_ the spinlocks! */
5441 task_thread_info(idle)->preempt_count = 0;
5444 * The idle tasks have their own, simple scheduling class:
5446 idle->sched_class = &idle_sched_class;
5450 * In a system that switches off the HZ timer nohz_cpu_mask
5451 * indicates which cpus entered this state. This is used
5452 * in the rcu update to wait only for active cpus. For system
5453 * which do not switch off the HZ timer nohz_cpu_mask should
5454 * always be CPU_MASK_NONE.
5456 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5459 * Increase the granularity value when there are more CPUs,
5460 * because with more CPUs the 'effective latency' as visible
5461 * to users decreases. But the relationship is not linear,
5462 * so pick a second-best guess by going with the log2 of the
5463 * number of CPUs.
5465 * This idea comes from the SD scheduler of Con Kolivas:
5467 static inline void sched_init_granularity(void)
5469 unsigned int factor = 1 + ilog2(num_online_cpus());
5470 const unsigned long limit = 200000000;
5472 sysctl_sched_min_granularity *= factor;
5473 if (sysctl_sched_min_granularity > limit)
5474 sysctl_sched_min_granularity = limit;
5476 sysctl_sched_latency *= factor;
5477 if (sysctl_sched_latency > limit)
5478 sysctl_sched_latency = limit;
5480 sysctl_sched_wakeup_granularity *= factor;
5483 #ifdef CONFIG_SMP
5485 * This is how migration works:
5487 * 1) we queue a struct migration_req structure in the source CPU's
5488 * runqueue and wake up that CPU's migration thread.
5489 * 2) we down() the locked semaphore => thread blocks.
5490 * 3) migration thread wakes up (implicitly it forces the migrated
5491 * thread off the CPU)
5492 * 4) it gets the migration request and checks whether the migrated
5493 * task is still in the wrong runqueue.
5494 * 5) if it's in the wrong runqueue then the migration thread removes
5495 * it and puts it into the right queue.
5496 * 6) migration thread up()s the semaphore.
5497 * 7) we wake up and the migration is done.
5501 * Change a given task's CPU affinity. Migrate the thread to a
5502 * proper CPU and schedule it away if the CPU it's executing on
5503 * is removed from the allowed bitmask.
5505 * NOTE: the caller must have a valid reference to the task, the
5506 * task must not exit() & deallocate itself prematurely. The
5507 * call is not atomic; no spinlocks may be held.
5509 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
5511 struct migration_req req;
5512 unsigned long flags;
5513 struct rq *rq;
5514 int ret = 0;
5516 rq = task_rq_lock(p, &flags);
5517 if (!cpus_intersects(*new_mask, cpu_online_map)) {
5518 ret = -EINVAL;
5519 goto out;
5522 if (p->sched_class->set_cpus_allowed)
5523 p->sched_class->set_cpus_allowed(p, new_mask);
5524 else {
5525 p->cpus_allowed = *new_mask;
5526 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
5529 /* Can the task run on the task's current CPU? If so, we're done */
5530 if (cpu_isset(task_cpu(p), *new_mask))
5531 goto out;
5533 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
5534 /* Need help from migration thread: drop lock and wait. */
5535 task_rq_unlock(rq, &flags);
5536 wake_up_process(rq->migration_thread);
5537 wait_for_completion(&req.done);
5538 tlb_migrate_finish(p->mm);
5539 return 0;
5541 out:
5542 task_rq_unlock(rq, &flags);
5544 return ret;
5546 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5549 * Move (not current) task off this cpu, onto dest cpu. We're doing
5550 * this because either it can't run here any more (set_cpus_allowed()
5551 * away from this CPU, or CPU going down), or because we're
5552 * attempting to rebalance this task on exec (sched_exec).
5554 * So we race with normal scheduler movements, but that's OK, as long
5555 * as the task is no longer on this CPU.
5557 * Returns non-zero if task was successfully migrated.
5559 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5561 struct rq *rq_dest, *rq_src;
5562 int ret = 0, on_rq;
5564 if (unlikely(cpu_is_offline(dest_cpu)))
5565 return ret;
5567 rq_src = cpu_rq(src_cpu);
5568 rq_dest = cpu_rq(dest_cpu);
5570 double_rq_lock(rq_src, rq_dest);
5571 /* Already moved. */
5572 if (task_cpu(p) != src_cpu)
5573 goto out;
5574 /* Affinity changed (again). */
5575 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5576 goto out;
5578 on_rq = p->se.on_rq;
5579 if (on_rq)
5580 deactivate_task(rq_src, p, 0);
5582 set_task_cpu(p, dest_cpu);
5583 if (on_rq) {
5584 activate_task(rq_dest, p, 0);
5585 check_preempt_curr(rq_dest, p);
5587 ret = 1;
5588 out:
5589 double_rq_unlock(rq_src, rq_dest);
5590 return ret;
5594 * migration_thread - this is a highprio system thread that performs
5595 * thread migration by bumping thread off CPU then 'pushing' onto
5596 * another runqueue.
5598 static int migration_thread(void *data)
5600 int cpu = (long)data;
5601 struct rq *rq;
5603 rq = cpu_rq(cpu);
5604 BUG_ON(rq->migration_thread != current);
5606 set_current_state(TASK_INTERRUPTIBLE);
5607 while (!kthread_should_stop()) {
5608 struct migration_req *req;
5609 struct list_head *head;
5611 spin_lock_irq(&rq->lock);
5613 if (cpu_is_offline(cpu)) {
5614 spin_unlock_irq(&rq->lock);
5615 goto wait_to_die;
5618 if (rq->active_balance) {
5619 active_load_balance(rq, cpu);
5620 rq->active_balance = 0;
5623 head = &rq->migration_queue;
5625 if (list_empty(head)) {
5626 spin_unlock_irq(&rq->lock);
5627 schedule();
5628 set_current_state(TASK_INTERRUPTIBLE);
5629 continue;
5631 req = list_entry(head->next, struct migration_req, list);
5632 list_del_init(head->next);
5634 spin_unlock(&rq->lock);
5635 __migrate_task(req->task, cpu, req->dest_cpu);
5636 local_irq_enable();
5638 complete(&req->done);
5640 __set_current_state(TASK_RUNNING);
5641 return 0;
5643 wait_to_die:
5644 /* Wait for kthread_stop */
5645 set_current_state(TASK_INTERRUPTIBLE);
5646 while (!kthread_should_stop()) {
5647 schedule();
5648 set_current_state(TASK_INTERRUPTIBLE);
5650 __set_current_state(TASK_RUNNING);
5651 return 0;
5654 #ifdef CONFIG_HOTPLUG_CPU
5656 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5658 int ret;
5660 local_irq_disable();
5661 ret = __migrate_task(p, src_cpu, dest_cpu);
5662 local_irq_enable();
5663 return ret;
5667 * Figure out where task on dead CPU should go, use force if necessary.
5668 * NOTE: interrupts should be disabled by the caller
5670 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5672 unsigned long flags;
5673 cpumask_t mask;
5674 struct rq *rq;
5675 int dest_cpu;
5677 do {
5678 /* On same node? */
5679 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5680 cpus_and(mask, mask, p->cpus_allowed);
5681 dest_cpu = any_online_cpu(mask);
5683 /* On any allowed CPU? */
5684 if (dest_cpu >= nr_cpu_ids)
5685 dest_cpu = any_online_cpu(p->cpus_allowed);
5687 /* No more Mr. Nice Guy. */
5688 if (dest_cpu >= nr_cpu_ids) {
5689 cpumask_t cpus_allowed;
5691 cpuset_cpus_allowed_locked(p, &cpus_allowed);
5693 * Try to stay on the same cpuset, where the
5694 * current cpuset may be a subset of all cpus.
5695 * The cpuset_cpus_allowed_locked() variant of
5696 * cpuset_cpus_allowed() will not block. It must be
5697 * called within calls to cpuset_lock/cpuset_unlock.
5699 rq = task_rq_lock(p, &flags);
5700 p->cpus_allowed = cpus_allowed;
5701 dest_cpu = any_online_cpu(p->cpus_allowed);
5702 task_rq_unlock(rq, &flags);
5705 * Don't tell them about moving exiting tasks or
5706 * kernel threads (both mm NULL), since they never
5707 * leave kernel.
5709 if (p->mm && printk_ratelimit()) {
5710 printk(KERN_INFO "process %d (%s) no "
5711 "longer affine to cpu%d\n",
5712 task_pid_nr(p), p->comm, dead_cpu);
5715 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5719 * While a dead CPU has no uninterruptible tasks queued at this point,
5720 * it might still have a nonzero ->nr_uninterruptible counter, because
5721 * for performance reasons the counter is not stricly tracking tasks to
5722 * their home CPUs. So we just add the counter to another CPU's counter,
5723 * to keep the global sum constant after CPU-down:
5725 static void migrate_nr_uninterruptible(struct rq *rq_src)
5727 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
5728 unsigned long flags;
5730 local_irq_save(flags);
5731 double_rq_lock(rq_src, rq_dest);
5732 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5733 rq_src->nr_uninterruptible = 0;
5734 double_rq_unlock(rq_src, rq_dest);
5735 local_irq_restore(flags);
5738 /* Run through task list and migrate tasks from the dead cpu. */
5739 static void migrate_live_tasks(int src_cpu)
5741 struct task_struct *p, *t;
5743 read_lock(&tasklist_lock);
5745 do_each_thread(t, p) {
5746 if (p == current)
5747 continue;
5749 if (task_cpu(p) == src_cpu)
5750 move_task_off_dead_cpu(src_cpu, p);
5751 } while_each_thread(t, p);
5753 read_unlock(&tasklist_lock);
5757 * Schedules idle task to be the next runnable task on current CPU.
5758 * It does so by boosting its priority to highest possible.
5759 * Used by CPU offline code.
5761 void sched_idle_next(void)
5763 int this_cpu = smp_processor_id();
5764 struct rq *rq = cpu_rq(this_cpu);
5765 struct task_struct *p = rq->idle;
5766 unsigned long flags;
5768 /* cpu has to be offline */
5769 BUG_ON(cpu_online(this_cpu));
5772 * Strictly not necessary since rest of the CPUs are stopped by now
5773 * and interrupts disabled on the current cpu.
5775 spin_lock_irqsave(&rq->lock, flags);
5777 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5779 update_rq_clock(rq);
5780 activate_task(rq, p, 0);
5782 spin_unlock_irqrestore(&rq->lock, flags);
5786 * Ensures that the idle task is using init_mm right before its cpu goes
5787 * offline.
5789 void idle_task_exit(void)
5791 struct mm_struct *mm = current->active_mm;
5793 BUG_ON(cpu_online(smp_processor_id()));
5795 if (mm != &init_mm)
5796 switch_mm(mm, &init_mm, current);
5797 mmdrop(mm);
5800 /* called under rq->lock with disabled interrupts */
5801 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5803 struct rq *rq = cpu_rq(dead_cpu);
5805 /* Must be exiting, otherwise would be on tasklist. */
5806 BUG_ON(!p->exit_state);
5808 /* Cannot have done final schedule yet: would have vanished. */
5809 BUG_ON(p->state == TASK_DEAD);
5811 get_task_struct(p);
5814 * Drop lock around migration; if someone else moves it,
5815 * that's OK. No task can be added to this CPU, so iteration is
5816 * fine.
5818 spin_unlock_irq(&rq->lock);
5819 move_task_off_dead_cpu(dead_cpu, p);
5820 spin_lock_irq(&rq->lock);
5822 put_task_struct(p);
5825 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5826 static void migrate_dead_tasks(unsigned int dead_cpu)
5828 struct rq *rq = cpu_rq(dead_cpu);
5829 struct task_struct *next;
5831 for ( ; ; ) {
5832 if (!rq->nr_running)
5833 break;
5834 update_rq_clock(rq);
5835 next = pick_next_task(rq, rq->curr);
5836 if (!next)
5837 break;
5838 migrate_dead(dead_cpu, next);
5842 #endif /* CONFIG_HOTPLUG_CPU */
5844 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5846 static struct ctl_table sd_ctl_dir[] = {
5848 .procname = "sched_domain",
5849 .mode = 0555,
5851 {0, },
5854 static struct ctl_table sd_ctl_root[] = {
5856 .ctl_name = CTL_KERN,
5857 .procname = "kernel",
5858 .mode = 0555,
5859 .child = sd_ctl_dir,
5861 {0, },
5864 static struct ctl_table *sd_alloc_ctl_entry(int n)
5866 struct ctl_table *entry =
5867 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5869 return entry;
5872 static void sd_free_ctl_entry(struct ctl_table **tablep)
5874 struct ctl_table *entry;
5877 * In the intermediate directories, both the child directory and
5878 * procname are dynamically allocated and could fail but the mode
5879 * will always be set. In the lowest directory the names are
5880 * static strings and all have proc handlers.
5882 for (entry = *tablep; entry->mode; entry++) {
5883 if (entry->child)
5884 sd_free_ctl_entry(&entry->child);
5885 if (entry->proc_handler == NULL)
5886 kfree(entry->procname);
5889 kfree(*tablep);
5890 *tablep = NULL;
5893 static void
5894 set_table_entry(struct ctl_table *entry,
5895 const char *procname, void *data, int maxlen,
5896 mode_t mode, proc_handler *proc_handler)
5898 entry->procname = procname;
5899 entry->data = data;
5900 entry->maxlen = maxlen;
5901 entry->mode = mode;
5902 entry->proc_handler = proc_handler;
5905 static struct ctl_table *
5906 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5908 struct ctl_table *table = sd_alloc_ctl_entry(12);
5910 if (table == NULL)
5911 return NULL;
5913 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5914 sizeof(long), 0644, proc_doulongvec_minmax);
5915 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5916 sizeof(long), 0644, proc_doulongvec_minmax);
5917 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5918 sizeof(int), 0644, proc_dointvec_minmax);
5919 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5920 sizeof(int), 0644, proc_dointvec_minmax);
5921 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5922 sizeof(int), 0644, proc_dointvec_minmax);
5923 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5924 sizeof(int), 0644, proc_dointvec_minmax);
5925 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5926 sizeof(int), 0644, proc_dointvec_minmax);
5927 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5928 sizeof(int), 0644, proc_dointvec_minmax);
5929 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5930 sizeof(int), 0644, proc_dointvec_minmax);
5931 set_table_entry(&table[9], "cache_nice_tries",
5932 &sd->cache_nice_tries,
5933 sizeof(int), 0644, proc_dointvec_minmax);
5934 set_table_entry(&table[10], "flags", &sd->flags,
5935 sizeof(int), 0644, proc_dointvec_minmax);
5936 /* &table[11] is terminator */
5938 return table;
5941 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5943 struct ctl_table *entry, *table;
5944 struct sched_domain *sd;
5945 int domain_num = 0, i;
5946 char buf[32];
5948 for_each_domain(cpu, sd)
5949 domain_num++;
5950 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5951 if (table == NULL)
5952 return NULL;
5954 i = 0;
5955 for_each_domain(cpu, sd) {
5956 snprintf(buf, 32, "domain%d", i);
5957 entry->procname = kstrdup(buf, GFP_KERNEL);
5958 entry->mode = 0555;
5959 entry->child = sd_alloc_ctl_domain_table(sd);
5960 entry++;
5961 i++;
5963 return table;
5966 static struct ctl_table_header *sd_sysctl_header;
5967 static void register_sched_domain_sysctl(void)
5969 int i, cpu_num = num_online_cpus();
5970 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5971 char buf[32];
5973 WARN_ON(sd_ctl_dir[0].child);
5974 sd_ctl_dir[0].child = entry;
5976 if (entry == NULL)
5977 return;
5979 for_each_online_cpu(i) {
5980 snprintf(buf, 32, "cpu%d", i);
5981 entry->procname = kstrdup(buf, GFP_KERNEL);
5982 entry->mode = 0555;
5983 entry->child = sd_alloc_ctl_cpu_table(i);
5984 entry++;
5987 WARN_ON(sd_sysctl_header);
5988 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5991 /* may be called multiple times per register */
5992 static void unregister_sched_domain_sysctl(void)
5994 if (sd_sysctl_header)
5995 unregister_sysctl_table(sd_sysctl_header);
5996 sd_sysctl_header = NULL;
5997 if (sd_ctl_dir[0].child)
5998 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6000 #else
6001 static void register_sched_domain_sysctl(void)
6004 static void unregister_sched_domain_sysctl(void)
6007 #endif
6010 * migration_call - callback that gets triggered when a CPU is added.
6011 * Here we can start up the necessary migration thread for the new CPU.
6013 static int __cpuinit
6014 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6016 struct task_struct *p;
6017 int cpu = (long)hcpu;
6018 unsigned long flags;
6019 struct rq *rq;
6021 switch (action) {
6023 case CPU_UP_PREPARE:
6024 case CPU_UP_PREPARE_FROZEN:
6025 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6026 if (IS_ERR(p))
6027 return NOTIFY_BAD;
6028 kthread_bind(p, cpu);
6029 /* Must be high prio: stop_machine expects to yield to it. */
6030 rq = task_rq_lock(p, &flags);
6031 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6032 task_rq_unlock(rq, &flags);
6033 cpu_rq(cpu)->migration_thread = p;
6034 break;
6036 case CPU_ONLINE:
6037 case CPU_ONLINE_FROZEN:
6038 /* Strictly unnecessary, as first user will wake it. */
6039 wake_up_process(cpu_rq(cpu)->migration_thread);
6041 /* Update our root-domain */
6042 rq = cpu_rq(cpu);
6043 spin_lock_irqsave(&rq->lock, flags);
6044 if (rq->rd) {
6045 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6046 cpu_set(cpu, rq->rd->online);
6048 spin_unlock_irqrestore(&rq->lock, flags);
6049 break;
6051 #ifdef CONFIG_HOTPLUG_CPU
6052 case CPU_UP_CANCELED:
6053 case CPU_UP_CANCELED_FROZEN:
6054 if (!cpu_rq(cpu)->migration_thread)
6055 break;
6056 /* Unbind it from offline cpu so it can run. Fall thru. */
6057 kthread_bind(cpu_rq(cpu)->migration_thread,
6058 any_online_cpu(cpu_online_map));
6059 kthread_stop(cpu_rq(cpu)->migration_thread);
6060 cpu_rq(cpu)->migration_thread = NULL;
6061 break;
6063 case CPU_DEAD:
6064 case CPU_DEAD_FROZEN:
6065 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6066 migrate_live_tasks(cpu);
6067 rq = cpu_rq(cpu);
6068 kthread_stop(rq->migration_thread);
6069 rq->migration_thread = NULL;
6070 /* Idle task back to normal (off runqueue, low prio) */
6071 spin_lock_irq(&rq->lock);
6072 update_rq_clock(rq);
6073 deactivate_task(rq, rq->idle, 0);
6074 rq->idle->static_prio = MAX_PRIO;
6075 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6076 rq->idle->sched_class = &idle_sched_class;
6077 migrate_dead_tasks(cpu);
6078 spin_unlock_irq(&rq->lock);
6079 cpuset_unlock();
6080 migrate_nr_uninterruptible(rq);
6081 BUG_ON(rq->nr_running != 0);
6084 * No need to migrate the tasks: it was best-effort if
6085 * they didn't take sched_hotcpu_mutex. Just wake up
6086 * the requestors.
6088 spin_lock_irq(&rq->lock);
6089 while (!list_empty(&rq->migration_queue)) {
6090 struct migration_req *req;
6092 req = list_entry(rq->migration_queue.next,
6093 struct migration_req, list);
6094 list_del_init(&req->list);
6095 complete(&req->done);
6097 spin_unlock_irq(&rq->lock);
6098 break;
6100 case CPU_DYING:
6101 case CPU_DYING_FROZEN:
6102 /* Update our root-domain */
6103 rq = cpu_rq(cpu);
6104 spin_lock_irqsave(&rq->lock, flags);
6105 if (rq->rd) {
6106 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6107 cpu_clear(cpu, rq->rd->online);
6109 spin_unlock_irqrestore(&rq->lock, flags);
6110 break;
6111 #endif
6113 return NOTIFY_OK;
6116 /* Register at highest priority so that task migration (migrate_all_tasks)
6117 * happens before everything else.
6119 static struct notifier_block __cpuinitdata migration_notifier = {
6120 .notifier_call = migration_call,
6121 .priority = 10
6124 void __init migration_init(void)
6126 void *cpu = (void *)(long)smp_processor_id();
6127 int err;
6129 /* Start one for the boot CPU: */
6130 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6131 BUG_ON(err == NOTIFY_BAD);
6132 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6133 register_cpu_notifier(&migration_notifier);
6135 #endif
6137 #ifdef CONFIG_SMP
6139 #ifdef CONFIG_SCHED_DEBUG
6141 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6142 cpumask_t *groupmask)
6144 struct sched_group *group = sd->groups;
6145 char str[256];
6147 cpulist_scnprintf(str, sizeof(str), sd->span);
6148 cpus_clear(*groupmask);
6150 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6152 if (!(sd->flags & SD_LOAD_BALANCE)) {
6153 printk("does not load-balance\n");
6154 if (sd->parent)
6155 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6156 " has parent");
6157 return -1;
6160 printk(KERN_CONT "span %s\n", str);
6162 if (!cpu_isset(cpu, sd->span)) {
6163 printk(KERN_ERR "ERROR: domain->span does not contain "
6164 "CPU%d\n", cpu);
6166 if (!cpu_isset(cpu, group->cpumask)) {
6167 printk(KERN_ERR "ERROR: domain->groups does not contain"
6168 " CPU%d\n", cpu);
6171 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6172 do {
6173 if (!group) {
6174 printk("\n");
6175 printk(KERN_ERR "ERROR: group is NULL\n");
6176 break;
6179 if (!group->__cpu_power) {
6180 printk(KERN_CONT "\n");
6181 printk(KERN_ERR "ERROR: domain->cpu_power not "
6182 "set\n");
6183 break;
6186 if (!cpus_weight(group->cpumask)) {
6187 printk(KERN_CONT "\n");
6188 printk(KERN_ERR "ERROR: empty group\n");
6189 break;
6192 if (cpus_intersects(*groupmask, group->cpumask)) {
6193 printk(KERN_CONT "\n");
6194 printk(KERN_ERR "ERROR: repeated CPUs\n");
6195 break;
6198 cpus_or(*groupmask, *groupmask, group->cpumask);
6200 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6201 printk(KERN_CONT " %s", str);
6203 group = group->next;
6204 } while (group != sd->groups);
6205 printk(KERN_CONT "\n");
6207 if (!cpus_equal(sd->span, *groupmask))
6208 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6210 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6211 printk(KERN_ERR "ERROR: parent span is not a superset "
6212 "of domain->span\n");
6213 return 0;
6216 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6218 cpumask_t *groupmask;
6219 int level = 0;
6221 if (!sd) {
6222 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6223 return;
6226 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6228 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6229 if (!groupmask) {
6230 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6231 return;
6234 for (;;) {
6235 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6236 break;
6237 level++;
6238 sd = sd->parent;
6239 if (!sd)
6240 break;
6242 kfree(groupmask);
6244 #else
6245 # define sched_domain_debug(sd, cpu) do { } while (0)
6246 #endif
6248 static int sd_degenerate(struct sched_domain *sd)
6250 if (cpus_weight(sd->span) == 1)
6251 return 1;
6253 /* Following flags need at least 2 groups */
6254 if (sd->flags & (SD_LOAD_BALANCE |
6255 SD_BALANCE_NEWIDLE |
6256 SD_BALANCE_FORK |
6257 SD_BALANCE_EXEC |
6258 SD_SHARE_CPUPOWER |
6259 SD_SHARE_PKG_RESOURCES)) {
6260 if (sd->groups != sd->groups->next)
6261 return 0;
6264 /* Following flags don't use groups */
6265 if (sd->flags & (SD_WAKE_IDLE |
6266 SD_WAKE_AFFINE |
6267 SD_WAKE_BALANCE))
6268 return 0;
6270 return 1;
6273 static int
6274 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6276 unsigned long cflags = sd->flags, pflags = parent->flags;
6278 if (sd_degenerate(parent))
6279 return 1;
6281 if (!cpus_equal(sd->span, parent->span))
6282 return 0;
6284 /* Does parent contain flags not in child? */
6285 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6286 if (cflags & SD_WAKE_AFFINE)
6287 pflags &= ~SD_WAKE_BALANCE;
6288 /* Flags needing groups don't count if only 1 group in parent */
6289 if (parent->groups == parent->groups->next) {
6290 pflags &= ~(SD_LOAD_BALANCE |
6291 SD_BALANCE_NEWIDLE |
6292 SD_BALANCE_FORK |
6293 SD_BALANCE_EXEC |
6294 SD_SHARE_CPUPOWER |
6295 SD_SHARE_PKG_RESOURCES);
6297 if (~cflags & pflags)
6298 return 0;
6300 return 1;
6303 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6305 unsigned long flags;
6306 const struct sched_class *class;
6308 spin_lock_irqsave(&rq->lock, flags);
6310 if (rq->rd) {
6311 struct root_domain *old_rd = rq->rd;
6313 for (class = sched_class_highest; class; class = class->next) {
6314 if (class->leave_domain)
6315 class->leave_domain(rq);
6318 cpu_clear(rq->cpu, old_rd->span);
6319 cpu_clear(rq->cpu, old_rd->online);
6321 if (atomic_dec_and_test(&old_rd->refcount))
6322 kfree(old_rd);
6325 atomic_inc(&rd->refcount);
6326 rq->rd = rd;
6328 cpu_set(rq->cpu, rd->span);
6329 if (cpu_isset(rq->cpu, cpu_online_map))
6330 cpu_set(rq->cpu, rd->online);
6332 for (class = sched_class_highest; class; class = class->next) {
6333 if (class->join_domain)
6334 class->join_domain(rq);
6337 spin_unlock_irqrestore(&rq->lock, flags);
6340 static void init_rootdomain(struct root_domain *rd)
6342 memset(rd, 0, sizeof(*rd));
6344 cpus_clear(rd->span);
6345 cpus_clear(rd->online);
6348 static void init_defrootdomain(void)
6350 init_rootdomain(&def_root_domain);
6351 atomic_set(&def_root_domain.refcount, 1);
6354 static struct root_domain *alloc_rootdomain(void)
6356 struct root_domain *rd;
6358 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6359 if (!rd)
6360 return NULL;
6362 init_rootdomain(rd);
6364 return rd;
6368 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6369 * hold the hotplug lock.
6371 static void
6372 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6374 struct rq *rq = cpu_rq(cpu);
6375 struct sched_domain *tmp;
6377 /* Remove the sched domains which do not contribute to scheduling. */
6378 for (tmp = sd; tmp; tmp = tmp->parent) {
6379 struct sched_domain *parent = tmp->parent;
6380 if (!parent)
6381 break;
6382 if (sd_parent_degenerate(tmp, parent)) {
6383 tmp->parent = parent->parent;
6384 if (parent->parent)
6385 parent->parent->child = tmp;
6389 if (sd && sd_degenerate(sd)) {
6390 sd = sd->parent;
6391 if (sd)
6392 sd->child = NULL;
6395 sched_domain_debug(sd, cpu);
6397 rq_attach_root(rq, rd);
6398 rcu_assign_pointer(rq->sd, sd);
6401 /* cpus with isolated domains */
6402 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6404 /* Setup the mask of cpus configured for isolated domains */
6405 static int __init isolated_cpu_setup(char *str)
6407 int ints[NR_CPUS], i;
6409 str = get_options(str, ARRAY_SIZE(ints), ints);
6410 cpus_clear(cpu_isolated_map);
6411 for (i = 1; i <= ints[0]; i++)
6412 if (ints[i] < NR_CPUS)
6413 cpu_set(ints[i], cpu_isolated_map);
6414 return 1;
6417 __setup("isolcpus=", isolated_cpu_setup);
6420 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6421 * to a function which identifies what group(along with sched group) a CPU
6422 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6423 * (due to the fact that we keep track of groups covered with a cpumask_t).
6425 * init_sched_build_groups will build a circular linked list of the groups
6426 * covered by the given span, and will set each group's ->cpumask correctly,
6427 * and ->cpu_power to 0.
6429 static void
6430 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6431 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6432 struct sched_group **sg,
6433 cpumask_t *tmpmask),
6434 cpumask_t *covered, cpumask_t *tmpmask)
6436 struct sched_group *first = NULL, *last = NULL;
6437 int i;
6439 cpus_clear(*covered);
6441 for_each_cpu_mask(i, *span) {
6442 struct sched_group *sg;
6443 int group = group_fn(i, cpu_map, &sg, tmpmask);
6444 int j;
6446 if (cpu_isset(i, *covered))
6447 continue;
6449 cpus_clear(sg->cpumask);
6450 sg->__cpu_power = 0;
6452 for_each_cpu_mask(j, *span) {
6453 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6454 continue;
6456 cpu_set(j, *covered);
6457 cpu_set(j, sg->cpumask);
6459 if (!first)
6460 first = sg;
6461 if (last)
6462 last->next = sg;
6463 last = sg;
6465 last->next = first;
6468 #define SD_NODES_PER_DOMAIN 16
6470 #ifdef CONFIG_NUMA
6473 * find_next_best_node - find the next node to include in a sched_domain
6474 * @node: node whose sched_domain we're building
6475 * @used_nodes: nodes already in the sched_domain
6477 * Find the next node to include in a given scheduling domain. Simply
6478 * finds the closest node not already in the @used_nodes map.
6480 * Should use nodemask_t.
6482 static int find_next_best_node(int node, nodemask_t *used_nodes)
6484 int i, n, val, min_val, best_node = 0;
6486 min_val = INT_MAX;
6488 for (i = 0; i < MAX_NUMNODES; i++) {
6489 /* Start at @node */
6490 n = (node + i) % MAX_NUMNODES;
6492 if (!nr_cpus_node(n))
6493 continue;
6495 /* Skip already used nodes */
6496 if (node_isset(n, *used_nodes))
6497 continue;
6499 /* Simple min distance search */
6500 val = node_distance(node, n);
6502 if (val < min_val) {
6503 min_val = val;
6504 best_node = n;
6508 node_set(best_node, *used_nodes);
6509 return best_node;
6513 * sched_domain_node_span - get a cpumask for a node's sched_domain
6514 * @node: node whose cpumask we're constructing
6516 * Given a node, construct a good cpumask for its sched_domain to span. It
6517 * should be one that prevents unnecessary balancing, but also spreads tasks
6518 * out optimally.
6520 static void sched_domain_node_span(int node, cpumask_t *span)
6522 nodemask_t used_nodes;
6523 node_to_cpumask_ptr(nodemask, node);
6524 int i;
6526 cpus_clear(*span);
6527 nodes_clear(used_nodes);
6529 cpus_or(*span, *span, *nodemask);
6530 node_set(node, used_nodes);
6532 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6533 int next_node = find_next_best_node(node, &used_nodes);
6535 node_to_cpumask_ptr_next(nodemask, next_node);
6536 cpus_or(*span, *span, *nodemask);
6539 #endif
6541 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6544 * SMT sched-domains:
6546 #ifdef CONFIG_SCHED_SMT
6547 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6548 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6550 static int
6551 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6552 cpumask_t *unused)
6554 if (sg)
6555 *sg = &per_cpu(sched_group_cpus, cpu);
6556 return cpu;
6558 #endif
6561 * multi-core sched-domains:
6563 #ifdef CONFIG_SCHED_MC
6564 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6565 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6566 #endif
6568 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6569 static int
6570 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6571 cpumask_t *mask)
6573 int group;
6575 *mask = per_cpu(cpu_sibling_map, cpu);
6576 cpus_and(*mask, *mask, *cpu_map);
6577 group = first_cpu(*mask);
6578 if (sg)
6579 *sg = &per_cpu(sched_group_core, group);
6580 return group;
6582 #elif defined(CONFIG_SCHED_MC)
6583 static int
6584 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6585 cpumask_t *unused)
6587 if (sg)
6588 *sg = &per_cpu(sched_group_core, cpu);
6589 return cpu;
6591 #endif
6593 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6594 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6596 static int
6597 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6598 cpumask_t *mask)
6600 int group;
6601 #ifdef CONFIG_SCHED_MC
6602 *mask = cpu_coregroup_map(cpu);
6603 cpus_and(*mask, *mask, *cpu_map);
6604 group = first_cpu(*mask);
6605 #elif defined(CONFIG_SCHED_SMT)
6606 *mask = per_cpu(cpu_sibling_map, cpu);
6607 cpus_and(*mask, *mask, *cpu_map);
6608 group = first_cpu(*mask);
6609 #else
6610 group = cpu;
6611 #endif
6612 if (sg)
6613 *sg = &per_cpu(sched_group_phys, group);
6614 return group;
6617 #ifdef CONFIG_NUMA
6619 * The init_sched_build_groups can't handle what we want to do with node
6620 * groups, so roll our own. Now each node has its own list of groups which
6621 * gets dynamically allocated.
6623 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6624 static struct sched_group ***sched_group_nodes_bycpu;
6626 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6627 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6629 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6630 struct sched_group **sg, cpumask_t *nodemask)
6632 int group;
6634 *nodemask = node_to_cpumask(cpu_to_node(cpu));
6635 cpus_and(*nodemask, *nodemask, *cpu_map);
6636 group = first_cpu(*nodemask);
6638 if (sg)
6639 *sg = &per_cpu(sched_group_allnodes, group);
6640 return group;
6643 static void init_numa_sched_groups_power(struct sched_group *group_head)
6645 struct sched_group *sg = group_head;
6646 int j;
6648 if (!sg)
6649 return;
6650 do {
6651 for_each_cpu_mask(j, sg->cpumask) {
6652 struct sched_domain *sd;
6654 sd = &per_cpu(phys_domains, j);
6655 if (j != first_cpu(sd->groups->cpumask)) {
6657 * Only add "power" once for each
6658 * physical package.
6660 continue;
6663 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6665 sg = sg->next;
6666 } while (sg != group_head);
6668 #endif
6670 #ifdef CONFIG_NUMA
6671 /* Free memory allocated for various sched_group structures */
6672 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
6674 int cpu, i;
6676 for_each_cpu_mask(cpu, *cpu_map) {
6677 struct sched_group **sched_group_nodes
6678 = sched_group_nodes_bycpu[cpu];
6680 if (!sched_group_nodes)
6681 continue;
6683 for (i = 0; i < MAX_NUMNODES; i++) {
6684 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6686 *nodemask = node_to_cpumask(i);
6687 cpus_and(*nodemask, *nodemask, *cpu_map);
6688 if (cpus_empty(*nodemask))
6689 continue;
6691 if (sg == NULL)
6692 continue;
6693 sg = sg->next;
6694 next_sg:
6695 oldsg = sg;
6696 sg = sg->next;
6697 kfree(oldsg);
6698 if (oldsg != sched_group_nodes[i])
6699 goto next_sg;
6701 kfree(sched_group_nodes);
6702 sched_group_nodes_bycpu[cpu] = NULL;
6705 #else
6706 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
6709 #endif
6712 * Initialize sched groups cpu_power.
6714 * cpu_power indicates the capacity of sched group, which is used while
6715 * distributing the load between different sched groups in a sched domain.
6716 * Typically cpu_power for all the groups in a sched domain will be same unless
6717 * there are asymmetries in the topology. If there are asymmetries, group
6718 * having more cpu_power will pickup more load compared to the group having
6719 * less cpu_power.
6721 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6722 * the maximum number of tasks a group can handle in the presence of other idle
6723 * or lightly loaded groups in the same sched domain.
6725 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6727 struct sched_domain *child;
6728 struct sched_group *group;
6730 WARN_ON(!sd || !sd->groups);
6732 if (cpu != first_cpu(sd->groups->cpumask))
6733 return;
6735 child = sd->child;
6737 sd->groups->__cpu_power = 0;
6740 * For perf policy, if the groups in child domain share resources
6741 * (for example cores sharing some portions of the cache hierarchy
6742 * or SMT), then set this domain groups cpu_power such that each group
6743 * can handle only one task, when there are other idle groups in the
6744 * same sched domain.
6746 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6747 (child->flags &
6748 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6749 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6750 return;
6754 * add cpu_power of each child group to this groups cpu_power
6756 group = child->groups;
6757 do {
6758 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6759 group = group->next;
6760 } while (group != child->groups);
6764 * Initializers for schedule domains
6765 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6768 #define SD_INIT(sd, type) sd_init_##type(sd)
6769 #define SD_INIT_FUNC(type) \
6770 static noinline void sd_init_##type(struct sched_domain *sd) \
6772 memset(sd, 0, sizeof(*sd)); \
6773 *sd = SD_##type##_INIT; \
6776 SD_INIT_FUNC(CPU)
6777 #ifdef CONFIG_NUMA
6778 SD_INIT_FUNC(ALLNODES)
6779 SD_INIT_FUNC(NODE)
6780 #endif
6781 #ifdef CONFIG_SCHED_SMT
6782 SD_INIT_FUNC(SIBLING)
6783 #endif
6784 #ifdef CONFIG_SCHED_MC
6785 SD_INIT_FUNC(MC)
6786 #endif
6789 * To minimize stack usage kmalloc room for cpumasks and share the
6790 * space as the usage in build_sched_domains() dictates. Used only
6791 * if the amount of space is significant.
6793 struct allmasks {
6794 cpumask_t tmpmask; /* make this one first */
6795 union {
6796 cpumask_t nodemask;
6797 cpumask_t this_sibling_map;
6798 cpumask_t this_core_map;
6800 cpumask_t send_covered;
6802 #ifdef CONFIG_NUMA
6803 cpumask_t domainspan;
6804 cpumask_t covered;
6805 cpumask_t notcovered;
6806 #endif
6809 #if NR_CPUS > 128
6810 #define SCHED_CPUMASK_ALLOC 1
6811 #define SCHED_CPUMASK_FREE(v) kfree(v)
6812 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
6813 #else
6814 #define SCHED_CPUMASK_ALLOC 0
6815 #define SCHED_CPUMASK_FREE(v)
6816 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
6817 #endif
6819 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
6820 ((unsigned long)(a) + offsetof(struct allmasks, v))
6823 * Build sched domains for a given set of cpus and attach the sched domains
6824 * to the individual cpus
6826 static int build_sched_domains(const cpumask_t *cpu_map)
6828 int i;
6829 struct root_domain *rd;
6830 SCHED_CPUMASK_DECLARE(allmasks);
6831 cpumask_t *tmpmask;
6832 #ifdef CONFIG_NUMA
6833 struct sched_group **sched_group_nodes = NULL;
6834 int sd_allnodes = 0;
6837 * Allocate the per-node list of sched groups
6839 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6840 GFP_KERNEL);
6841 if (!sched_group_nodes) {
6842 printk(KERN_WARNING "Can not alloc sched group node list\n");
6843 return -ENOMEM;
6845 #endif
6847 rd = alloc_rootdomain();
6848 if (!rd) {
6849 printk(KERN_WARNING "Cannot alloc root domain\n");
6850 #ifdef CONFIG_NUMA
6851 kfree(sched_group_nodes);
6852 #endif
6853 return -ENOMEM;
6856 #if SCHED_CPUMASK_ALLOC
6857 /* get space for all scratch cpumask variables */
6858 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
6859 if (!allmasks) {
6860 printk(KERN_WARNING "Cannot alloc cpumask array\n");
6861 kfree(rd);
6862 #ifdef CONFIG_NUMA
6863 kfree(sched_group_nodes);
6864 #endif
6865 return -ENOMEM;
6867 #endif
6868 tmpmask = (cpumask_t *)allmasks;
6871 #ifdef CONFIG_NUMA
6872 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6873 #endif
6876 * Set up domains for cpus specified by the cpu_map.
6878 for_each_cpu_mask(i, *cpu_map) {
6879 struct sched_domain *sd = NULL, *p;
6880 SCHED_CPUMASK_VAR(nodemask, allmasks);
6882 *nodemask = node_to_cpumask(cpu_to_node(i));
6883 cpus_and(*nodemask, *nodemask, *cpu_map);
6885 #ifdef CONFIG_NUMA
6886 if (cpus_weight(*cpu_map) >
6887 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
6888 sd = &per_cpu(allnodes_domains, i);
6889 SD_INIT(sd, ALLNODES);
6890 sd->span = *cpu_map;
6891 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
6892 p = sd;
6893 sd_allnodes = 1;
6894 } else
6895 p = NULL;
6897 sd = &per_cpu(node_domains, i);
6898 SD_INIT(sd, NODE);
6899 sched_domain_node_span(cpu_to_node(i), &sd->span);
6900 sd->parent = p;
6901 if (p)
6902 p->child = sd;
6903 cpus_and(sd->span, sd->span, *cpu_map);
6904 #endif
6906 p = sd;
6907 sd = &per_cpu(phys_domains, i);
6908 SD_INIT(sd, CPU);
6909 sd->span = *nodemask;
6910 sd->parent = p;
6911 if (p)
6912 p->child = sd;
6913 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
6915 #ifdef CONFIG_SCHED_MC
6916 p = sd;
6917 sd = &per_cpu(core_domains, i);
6918 SD_INIT(sd, MC);
6919 sd->span = cpu_coregroup_map(i);
6920 cpus_and(sd->span, sd->span, *cpu_map);
6921 sd->parent = p;
6922 p->child = sd;
6923 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
6924 #endif
6926 #ifdef CONFIG_SCHED_SMT
6927 p = sd;
6928 sd = &per_cpu(cpu_domains, i);
6929 SD_INIT(sd, SIBLING);
6930 sd->span = per_cpu(cpu_sibling_map, i);
6931 cpus_and(sd->span, sd->span, *cpu_map);
6932 sd->parent = p;
6933 p->child = sd;
6934 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
6935 #endif
6938 #ifdef CONFIG_SCHED_SMT
6939 /* Set up CPU (sibling) groups */
6940 for_each_cpu_mask(i, *cpu_map) {
6941 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
6942 SCHED_CPUMASK_VAR(send_covered, allmasks);
6944 *this_sibling_map = per_cpu(cpu_sibling_map, i);
6945 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
6946 if (i != first_cpu(*this_sibling_map))
6947 continue;
6949 init_sched_build_groups(this_sibling_map, cpu_map,
6950 &cpu_to_cpu_group,
6951 send_covered, tmpmask);
6953 #endif
6955 #ifdef CONFIG_SCHED_MC
6956 /* Set up multi-core groups */
6957 for_each_cpu_mask(i, *cpu_map) {
6958 SCHED_CPUMASK_VAR(this_core_map, allmasks);
6959 SCHED_CPUMASK_VAR(send_covered, allmasks);
6961 *this_core_map = cpu_coregroup_map(i);
6962 cpus_and(*this_core_map, *this_core_map, *cpu_map);
6963 if (i != first_cpu(*this_core_map))
6964 continue;
6966 init_sched_build_groups(this_core_map, cpu_map,
6967 &cpu_to_core_group,
6968 send_covered, tmpmask);
6970 #endif
6972 /* Set up physical groups */
6973 for (i = 0; i < MAX_NUMNODES; i++) {
6974 SCHED_CPUMASK_VAR(nodemask, allmasks);
6975 SCHED_CPUMASK_VAR(send_covered, allmasks);
6977 *nodemask = node_to_cpumask(i);
6978 cpus_and(*nodemask, *nodemask, *cpu_map);
6979 if (cpus_empty(*nodemask))
6980 continue;
6982 init_sched_build_groups(nodemask, cpu_map,
6983 &cpu_to_phys_group,
6984 send_covered, tmpmask);
6987 #ifdef CONFIG_NUMA
6988 /* Set up node groups */
6989 if (sd_allnodes) {
6990 SCHED_CPUMASK_VAR(send_covered, allmasks);
6992 init_sched_build_groups(cpu_map, cpu_map,
6993 &cpu_to_allnodes_group,
6994 send_covered, tmpmask);
6997 for (i = 0; i < MAX_NUMNODES; i++) {
6998 /* Set up node groups */
6999 struct sched_group *sg, *prev;
7000 SCHED_CPUMASK_VAR(nodemask, allmasks);
7001 SCHED_CPUMASK_VAR(domainspan, allmasks);
7002 SCHED_CPUMASK_VAR(covered, allmasks);
7003 int j;
7005 *nodemask = node_to_cpumask(i);
7006 cpus_clear(*covered);
7008 cpus_and(*nodemask, *nodemask, *cpu_map);
7009 if (cpus_empty(*nodemask)) {
7010 sched_group_nodes[i] = NULL;
7011 continue;
7014 sched_domain_node_span(i, domainspan);
7015 cpus_and(*domainspan, *domainspan, *cpu_map);
7017 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7018 if (!sg) {
7019 printk(KERN_WARNING "Can not alloc domain group for "
7020 "node %d\n", i);
7021 goto error;
7023 sched_group_nodes[i] = sg;
7024 for_each_cpu_mask(j, *nodemask) {
7025 struct sched_domain *sd;
7027 sd = &per_cpu(node_domains, j);
7028 sd->groups = sg;
7030 sg->__cpu_power = 0;
7031 sg->cpumask = *nodemask;
7032 sg->next = sg;
7033 cpus_or(*covered, *covered, *nodemask);
7034 prev = sg;
7036 for (j = 0; j < MAX_NUMNODES; j++) {
7037 SCHED_CPUMASK_VAR(notcovered, allmasks);
7038 int n = (i + j) % MAX_NUMNODES;
7039 node_to_cpumask_ptr(pnodemask, n);
7041 cpus_complement(*notcovered, *covered);
7042 cpus_and(*tmpmask, *notcovered, *cpu_map);
7043 cpus_and(*tmpmask, *tmpmask, *domainspan);
7044 if (cpus_empty(*tmpmask))
7045 break;
7047 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7048 if (cpus_empty(*tmpmask))
7049 continue;
7051 sg = kmalloc_node(sizeof(struct sched_group),
7052 GFP_KERNEL, i);
7053 if (!sg) {
7054 printk(KERN_WARNING
7055 "Can not alloc domain group for node %d\n", j);
7056 goto error;
7058 sg->__cpu_power = 0;
7059 sg->cpumask = *tmpmask;
7060 sg->next = prev->next;
7061 cpus_or(*covered, *covered, *tmpmask);
7062 prev->next = sg;
7063 prev = sg;
7066 #endif
7068 /* Calculate CPU power for physical packages and nodes */
7069 #ifdef CONFIG_SCHED_SMT
7070 for_each_cpu_mask(i, *cpu_map) {
7071 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7073 init_sched_groups_power(i, sd);
7075 #endif
7076 #ifdef CONFIG_SCHED_MC
7077 for_each_cpu_mask(i, *cpu_map) {
7078 struct sched_domain *sd = &per_cpu(core_domains, i);
7080 init_sched_groups_power(i, sd);
7082 #endif
7084 for_each_cpu_mask(i, *cpu_map) {
7085 struct sched_domain *sd = &per_cpu(phys_domains, i);
7087 init_sched_groups_power(i, sd);
7090 #ifdef CONFIG_NUMA
7091 for (i = 0; i < MAX_NUMNODES; i++)
7092 init_numa_sched_groups_power(sched_group_nodes[i]);
7094 if (sd_allnodes) {
7095 struct sched_group *sg;
7097 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7098 tmpmask);
7099 init_numa_sched_groups_power(sg);
7101 #endif
7103 /* Attach the domains */
7104 for_each_cpu_mask(i, *cpu_map) {
7105 struct sched_domain *sd;
7106 #ifdef CONFIG_SCHED_SMT
7107 sd = &per_cpu(cpu_domains, i);
7108 #elif defined(CONFIG_SCHED_MC)
7109 sd = &per_cpu(core_domains, i);
7110 #else
7111 sd = &per_cpu(phys_domains, i);
7112 #endif
7113 cpu_attach_domain(sd, rd, i);
7116 SCHED_CPUMASK_FREE((void *)allmasks);
7117 return 0;
7119 #ifdef CONFIG_NUMA
7120 error:
7121 free_sched_groups(cpu_map, tmpmask);
7122 SCHED_CPUMASK_FREE((void *)allmasks);
7123 return -ENOMEM;
7124 #endif
7127 static cpumask_t *doms_cur; /* current sched domains */
7128 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7131 * Special case: If a kmalloc of a doms_cur partition (array of
7132 * cpumask_t) fails, then fallback to a single sched domain,
7133 * as determined by the single cpumask_t fallback_doms.
7135 static cpumask_t fallback_doms;
7137 void __attribute__((weak)) arch_update_cpu_topology(void)
7142 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7143 * For now this just excludes isolated cpus, but could be used to
7144 * exclude other special cases in the future.
7146 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7148 int err;
7150 arch_update_cpu_topology();
7151 ndoms_cur = 1;
7152 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7153 if (!doms_cur)
7154 doms_cur = &fallback_doms;
7155 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7156 err = build_sched_domains(doms_cur);
7157 register_sched_domain_sysctl();
7159 return err;
7162 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7163 cpumask_t *tmpmask)
7165 free_sched_groups(cpu_map, tmpmask);
7169 * Detach sched domains from a group of cpus specified in cpu_map
7170 * These cpus will now be attached to the NULL domain
7172 static void detach_destroy_domains(const cpumask_t *cpu_map)
7174 cpumask_t tmpmask;
7175 int i;
7177 unregister_sched_domain_sysctl();
7179 for_each_cpu_mask(i, *cpu_map)
7180 cpu_attach_domain(NULL, &def_root_domain, i);
7181 synchronize_sched();
7182 arch_destroy_sched_domains(cpu_map, &tmpmask);
7186 * Partition sched domains as specified by the 'ndoms_new'
7187 * cpumasks in the array doms_new[] of cpumasks. This compares
7188 * doms_new[] to the current sched domain partitioning, doms_cur[].
7189 * It destroys each deleted domain and builds each new domain.
7191 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7192 * The masks don't intersect (don't overlap.) We should setup one
7193 * sched domain for each mask. CPUs not in any of the cpumasks will
7194 * not be load balanced. If the same cpumask appears both in the
7195 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7196 * it as it is.
7198 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7199 * ownership of it and will kfree it when done with it. If the caller
7200 * failed the kmalloc call, then it can pass in doms_new == NULL,
7201 * and partition_sched_domains() will fallback to the single partition
7202 * 'fallback_doms'.
7204 * Call with hotplug lock held
7206 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
7208 int i, j;
7210 lock_doms_cur();
7212 /* always unregister in case we don't destroy any domains */
7213 unregister_sched_domain_sysctl();
7215 if (doms_new == NULL) {
7216 ndoms_new = 1;
7217 doms_new = &fallback_doms;
7218 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7221 /* Destroy deleted domains */
7222 for (i = 0; i < ndoms_cur; i++) {
7223 for (j = 0; j < ndoms_new; j++) {
7224 if (cpus_equal(doms_cur[i], doms_new[j]))
7225 goto match1;
7227 /* no match - a current sched domain not in new doms_new[] */
7228 detach_destroy_domains(doms_cur + i);
7229 match1:
7233 /* Build new domains */
7234 for (i = 0; i < ndoms_new; i++) {
7235 for (j = 0; j < ndoms_cur; j++) {
7236 if (cpus_equal(doms_new[i], doms_cur[j]))
7237 goto match2;
7239 /* no match - add a new doms_new */
7240 build_sched_domains(doms_new + i);
7241 match2:
7245 /* Remember the new sched domains */
7246 if (doms_cur != &fallback_doms)
7247 kfree(doms_cur);
7248 doms_cur = doms_new;
7249 ndoms_cur = ndoms_new;
7251 register_sched_domain_sysctl();
7253 unlock_doms_cur();
7256 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7257 int arch_reinit_sched_domains(void)
7259 int err;
7261 get_online_cpus();
7262 detach_destroy_domains(&cpu_online_map);
7263 err = arch_init_sched_domains(&cpu_online_map);
7264 put_online_cpus();
7266 return err;
7269 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7271 int ret;
7273 if (buf[0] != '0' && buf[0] != '1')
7274 return -EINVAL;
7276 if (smt)
7277 sched_smt_power_savings = (buf[0] == '1');
7278 else
7279 sched_mc_power_savings = (buf[0] == '1');
7281 ret = arch_reinit_sched_domains();
7283 return ret ? ret : count;
7286 #ifdef CONFIG_SCHED_MC
7287 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7289 return sprintf(page, "%u\n", sched_mc_power_savings);
7291 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7292 const char *buf, size_t count)
7294 return sched_power_savings_store(buf, count, 0);
7296 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7297 sched_mc_power_savings_store);
7298 #endif
7300 #ifdef CONFIG_SCHED_SMT
7301 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7303 return sprintf(page, "%u\n", sched_smt_power_savings);
7305 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7306 const char *buf, size_t count)
7308 return sched_power_savings_store(buf, count, 1);
7310 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7311 sched_smt_power_savings_store);
7312 #endif
7314 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7316 int err = 0;
7318 #ifdef CONFIG_SCHED_SMT
7319 if (smt_capable())
7320 err = sysfs_create_file(&cls->kset.kobj,
7321 &attr_sched_smt_power_savings.attr);
7322 #endif
7323 #ifdef CONFIG_SCHED_MC
7324 if (!err && mc_capable())
7325 err = sysfs_create_file(&cls->kset.kobj,
7326 &attr_sched_mc_power_savings.attr);
7327 #endif
7328 return err;
7330 #endif
7333 * Force a reinitialization of the sched domains hierarchy. The domains
7334 * and groups cannot be updated in place without racing with the balancing
7335 * code, so we temporarily attach all running cpus to the NULL domain
7336 * which will prevent rebalancing while the sched domains are recalculated.
7338 static int update_sched_domains(struct notifier_block *nfb,
7339 unsigned long action, void *hcpu)
7341 switch (action) {
7342 case CPU_UP_PREPARE:
7343 case CPU_UP_PREPARE_FROZEN:
7344 case CPU_DOWN_PREPARE:
7345 case CPU_DOWN_PREPARE_FROZEN:
7346 detach_destroy_domains(&cpu_online_map);
7347 return NOTIFY_OK;
7349 case CPU_UP_CANCELED:
7350 case CPU_UP_CANCELED_FROZEN:
7351 case CPU_DOWN_FAILED:
7352 case CPU_DOWN_FAILED_FROZEN:
7353 case CPU_ONLINE:
7354 case CPU_ONLINE_FROZEN:
7355 case CPU_DEAD:
7356 case CPU_DEAD_FROZEN:
7358 * Fall through and re-initialise the domains.
7360 break;
7361 default:
7362 return NOTIFY_DONE;
7365 /* The hotplug lock is already held by cpu_up/cpu_down */
7366 arch_init_sched_domains(&cpu_online_map);
7368 return NOTIFY_OK;
7371 void __init sched_init_smp(void)
7373 cpumask_t non_isolated_cpus;
7375 #if defined(CONFIG_NUMA)
7376 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7377 GFP_KERNEL);
7378 BUG_ON(sched_group_nodes_bycpu == NULL);
7379 #endif
7380 get_online_cpus();
7381 arch_init_sched_domains(&cpu_online_map);
7382 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7383 if (cpus_empty(non_isolated_cpus))
7384 cpu_set(smp_processor_id(), non_isolated_cpus);
7385 put_online_cpus();
7386 /* XXX: Theoretical race here - CPU may be hotplugged now */
7387 hotcpu_notifier(update_sched_domains, 0);
7389 /* Move init over to a non-isolated CPU */
7390 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
7391 BUG();
7392 sched_init_granularity();
7394 #else
7395 void __init sched_init_smp(void)
7397 #if defined(CONFIG_NUMA)
7398 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7399 GFP_KERNEL);
7400 BUG_ON(sched_group_nodes_bycpu == NULL);
7401 #endif
7402 sched_init_granularity();
7404 #endif /* CONFIG_SMP */
7406 int in_sched_functions(unsigned long addr)
7408 return in_lock_functions(addr) ||
7409 (addr >= (unsigned long)__sched_text_start
7410 && addr < (unsigned long)__sched_text_end);
7413 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7415 cfs_rq->tasks_timeline = RB_ROOT;
7416 #ifdef CONFIG_FAIR_GROUP_SCHED
7417 cfs_rq->rq = rq;
7418 #endif
7419 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7422 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7424 struct rt_prio_array *array;
7425 int i;
7427 array = &rt_rq->active;
7428 for (i = 0; i < MAX_RT_PRIO; i++) {
7429 INIT_LIST_HEAD(array->queue + i);
7430 __clear_bit(i, array->bitmap);
7432 /* delimiter for bitsearch: */
7433 __set_bit(MAX_RT_PRIO, array->bitmap);
7435 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7436 rt_rq->highest_prio = MAX_RT_PRIO;
7437 #endif
7438 #ifdef CONFIG_SMP
7439 rt_rq->rt_nr_migratory = 0;
7440 rt_rq->overloaded = 0;
7441 #endif
7443 rt_rq->rt_time = 0;
7444 rt_rq->rt_throttled = 0;
7445 rt_rq->rt_runtime = 0;
7446 spin_lock_init(&rt_rq->rt_runtime_lock);
7448 #ifdef CONFIG_RT_GROUP_SCHED
7449 rt_rq->rt_nr_boosted = 0;
7450 rt_rq->rq = rq;
7451 #endif
7454 #ifdef CONFIG_FAIR_GROUP_SCHED
7455 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7456 struct sched_entity *se, int cpu, int add,
7457 struct sched_entity *parent)
7459 struct rq *rq = cpu_rq(cpu);
7460 tg->cfs_rq[cpu] = cfs_rq;
7461 init_cfs_rq(cfs_rq, rq);
7462 cfs_rq->tg = tg;
7463 if (add)
7464 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7466 tg->se[cpu] = se;
7467 /* se could be NULL for init_task_group */
7468 if (!se)
7469 return;
7471 if (!parent)
7472 se->cfs_rq = &rq->cfs;
7473 else
7474 se->cfs_rq = parent->my_q;
7476 se->my_q = cfs_rq;
7477 se->load.weight = tg->shares;
7478 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
7479 se->parent = parent;
7481 #endif
7483 #ifdef CONFIG_RT_GROUP_SCHED
7484 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7485 struct sched_rt_entity *rt_se, int cpu, int add,
7486 struct sched_rt_entity *parent)
7488 struct rq *rq = cpu_rq(cpu);
7490 tg->rt_rq[cpu] = rt_rq;
7491 init_rt_rq(rt_rq, rq);
7492 rt_rq->tg = tg;
7493 rt_rq->rt_se = rt_se;
7494 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7495 if (add)
7496 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7498 tg->rt_se[cpu] = rt_se;
7499 if (!rt_se)
7500 return;
7502 if (!parent)
7503 rt_se->rt_rq = &rq->rt;
7504 else
7505 rt_se->rt_rq = parent->my_q;
7507 rt_se->rt_rq = &rq->rt;
7508 rt_se->my_q = rt_rq;
7509 rt_se->parent = parent;
7510 INIT_LIST_HEAD(&rt_se->run_list);
7512 #endif
7514 void __init sched_init(void)
7516 int i, j;
7517 unsigned long alloc_size = 0, ptr;
7519 #ifdef CONFIG_FAIR_GROUP_SCHED
7520 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7521 #endif
7522 #ifdef CONFIG_RT_GROUP_SCHED
7523 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7524 #endif
7525 #ifdef CONFIG_USER_SCHED
7526 alloc_size *= 2;
7527 #endif
7529 * As sched_init() is called before page_alloc is setup,
7530 * we use alloc_bootmem().
7532 if (alloc_size) {
7533 ptr = (unsigned long)alloc_bootmem_low(alloc_size);
7535 #ifdef CONFIG_FAIR_GROUP_SCHED
7536 init_task_group.se = (struct sched_entity **)ptr;
7537 ptr += nr_cpu_ids * sizeof(void **);
7539 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
7540 ptr += nr_cpu_ids * sizeof(void **);
7542 #ifdef CONFIG_USER_SCHED
7543 root_task_group.se = (struct sched_entity **)ptr;
7544 ptr += nr_cpu_ids * sizeof(void **);
7546 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7547 ptr += nr_cpu_ids * sizeof(void **);
7548 #endif
7549 #endif
7550 #ifdef CONFIG_RT_GROUP_SCHED
7551 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
7552 ptr += nr_cpu_ids * sizeof(void **);
7554 init_task_group.rt_rq = (struct rt_rq **)ptr;
7555 ptr += nr_cpu_ids * sizeof(void **);
7557 #ifdef CONFIG_USER_SCHED
7558 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7559 ptr += nr_cpu_ids * sizeof(void **);
7561 root_task_group.rt_rq = (struct rt_rq **)ptr;
7562 ptr += nr_cpu_ids * sizeof(void **);
7563 #endif
7564 #endif
7567 #ifdef CONFIG_SMP
7568 init_defrootdomain();
7569 #endif
7571 init_rt_bandwidth(&def_rt_bandwidth,
7572 global_rt_period(), global_rt_runtime());
7574 #ifdef CONFIG_RT_GROUP_SCHED
7575 init_rt_bandwidth(&init_task_group.rt_bandwidth,
7576 global_rt_period(), global_rt_runtime());
7577 #ifdef CONFIG_USER_SCHED
7578 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7579 global_rt_period(), RUNTIME_INF);
7580 #endif
7581 #endif
7583 #ifdef CONFIG_GROUP_SCHED
7584 list_add(&init_task_group.list, &task_groups);
7585 INIT_LIST_HEAD(&init_task_group.children);
7587 #ifdef CONFIG_USER_SCHED
7588 INIT_LIST_HEAD(&root_task_group.children);
7589 init_task_group.parent = &root_task_group;
7590 list_add(&init_task_group.siblings, &root_task_group.children);
7591 #endif
7592 #endif
7594 for_each_possible_cpu(i) {
7595 struct rq *rq;
7597 rq = cpu_rq(i);
7598 spin_lock_init(&rq->lock);
7599 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7600 rq->nr_running = 0;
7601 rq->clock = 1;
7602 update_last_tick_seen(rq);
7603 init_cfs_rq(&rq->cfs, rq);
7604 init_rt_rq(&rq->rt, rq);
7605 #ifdef CONFIG_FAIR_GROUP_SCHED
7606 init_task_group.shares = init_task_group_load;
7607 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7608 #ifdef CONFIG_CGROUP_SCHED
7610 * How much cpu bandwidth does init_task_group get?
7612 * In case of task-groups formed thr' the cgroup filesystem, it
7613 * gets 100% of the cpu resources in the system. This overall
7614 * system cpu resource is divided among the tasks of
7615 * init_task_group and its child task-groups in a fair manner,
7616 * based on each entity's (task or task-group's) weight
7617 * (se->load.weight).
7619 * In other words, if init_task_group has 10 tasks of weight
7620 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7621 * then A0's share of the cpu resource is:
7623 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7625 * We achieve this by letting init_task_group's tasks sit
7626 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
7628 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
7629 #elif defined CONFIG_USER_SCHED
7630 root_task_group.shares = NICE_0_LOAD;
7631 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
7633 * In case of task-groups formed thr' the user id of tasks,
7634 * init_task_group represents tasks belonging to root user.
7635 * Hence it forms a sibling of all subsequent groups formed.
7636 * In this case, init_task_group gets only a fraction of overall
7637 * system cpu resource, based on the weight assigned to root
7638 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
7639 * by letting tasks of init_task_group sit in a separate cfs_rq
7640 * (init_cfs_rq) and having one entity represent this group of
7641 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
7643 init_tg_cfs_entry(&init_task_group,
7644 &per_cpu(init_cfs_rq, i),
7645 &per_cpu(init_sched_entity, i), i, 1,
7646 root_task_group.se[i]);
7648 #endif
7649 #endif /* CONFIG_FAIR_GROUP_SCHED */
7651 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7652 #ifdef CONFIG_RT_GROUP_SCHED
7653 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7654 #ifdef CONFIG_CGROUP_SCHED
7655 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
7656 #elif defined CONFIG_USER_SCHED
7657 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
7658 init_tg_rt_entry(&init_task_group,
7659 &per_cpu(init_rt_rq, i),
7660 &per_cpu(init_sched_rt_entity, i), i, 1,
7661 root_task_group.rt_se[i]);
7662 #endif
7663 #endif
7665 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7666 rq->cpu_load[j] = 0;
7667 #ifdef CONFIG_SMP
7668 rq->sd = NULL;
7669 rq->rd = NULL;
7670 rq->active_balance = 0;
7671 rq->next_balance = jiffies;
7672 rq->push_cpu = 0;
7673 rq->cpu = i;
7674 rq->migration_thread = NULL;
7675 INIT_LIST_HEAD(&rq->migration_queue);
7676 rq_attach_root(rq, &def_root_domain);
7677 #endif
7678 init_rq_hrtick(rq);
7679 atomic_set(&rq->nr_iowait, 0);
7682 set_load_weight(&init_task);
7684 #ifdef CONFIG_PREEMPT_NOTIFIERS
7685 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7686 #endif
7688 #ifdef CONFIG_SMP
7689 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7690 #endif
7692 #ifdef CONFIG_RT_MUTEXES
7693 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7694 #endif
7697 * The boot idle thread does lazy MMU switching as well:
7699 atomic_inc(&init_mm.mm_count);
7700 enter_lazy_tlb(&init_mm, current);
7703 * Make us the idle thread. Technically, schedule() should not be
7704 * called from this thread, however somewhere below it might be,
7705 * but because we are the idle thread, we just pick up running again
7706 * when this runqueue becomes "idle".
7708 init_idle(current, smp_processor_id());
7710 * During early bootup we pretend to be a normal task:
7712 current->sched_class = &fair_sched_class;
7714 scheduler_running = 1;
7717 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7718 void __might_sleep(char *file, int line)
7720 #ifdef in_atomic
7721 static unsigned long prev_jiffy; /* ratelimiting */
7723 if ((in_atomic() || irqs_disabled()) &&
7724 system_state == SYSTEM_RUNNING && !oops_in_progress) {
7725 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7726 return;
7727 prev_jiffy = jiffies;
7728 printk(KERN_ERR "BUG: sleeping function called from invalid"
7729 " context at %s:%d\n", file, line);
7730 printk("in_atomic():%d, irqs_disabled():%d\n",
7731 in_atomic(), irqs_disabled());
7732 debug_show_held_locks(current);
7733 if (irqs_disabled())
7734 print_irqtrace_events(current);
7735 dump_stack();
7737 #endif
7739 EXPORT_SYMBOL(__might_sleep);
7740 #endif
7742 #ifdef CONFIG_MAGIC_SYSRQ
7743 static void normalize_task(struct rq *rq, struct task_struct *p)
7745 int on_rq;
7746 update_rq_clock(rq);
7747 on_rq = p->se.on_rq;
7748 if (on_rq)
7749 deactivate_task(rq, p, 0);
7750 __setscheduler(rq, p, SCHED_NORMAL, 0);
7751 if (on_rq) {
7752 activate_task(rq, p, 0);
7753 resched_task(rq->curr);
7757 void normalize_rt_tasks(void)
7759 struct task_struct *g, *p;
7760 unsigned long flags;
7761 struct rq *rq;
7763 read_lock_irqsave(&tasklist_lock, flags);
7764 do_each_thread(g, p) {
7766 * Only normalize user tasks:
7768 if (!p->mm)
7769 continue;
7771 p->se.exec_start = 0;
7772 #ifdef CONFIG_SCHEDSTATS
7773 p->se.wait_start = 0;
7774 p->se.sleep_start = 0;
7775 p->se.block_start = 0;
7776 #endif
7777 task_rq(p)->clock = 0;
7779 if (!rt_task(p)) {
7781 * Renice negative nice level userspace
7782 * tasks back to 0:
7784 if (TASK_NICE(p) < 0 && p->mm)
7785 set_user_nice(p, 0);
7786 continue;
7789 spin_lock(&p->pi_lock);
7790 rq = __task_rq_lock(p);
7792 normalize_task(rq, p);
7794 __task_rq_unlock(rq);
7795 spin_unlock(&p->pi_lock);
7796 } while_each_thread(g, p);
7798 read_unlock_irqrestore(&tasklist_lock, flags);
7801 #endif /* CONFIG_MAGIC_SYSRQ */
7803 #ifdef CONFIG_IA64
7805 * These functions are only useful for the IA64 MCA handling.
7807 * They can only be called when the whole system has been
7808 * stopped - every CPU needs to be quiescent, and no scheduling
7809 * activity can take place. Using them for anything else would
7810 * be a serious bug, and as a result, they aren't even visible
7811 * under any other configuration.
7815 * curr_task - return the current task for a given cpu.
7816 * @cpu: the processor in question.
7818 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7820 struct task_struct *curr_task(int cpu)
7822 return cpu_curr(cpu);
7826 * set_curr_task - set the current task for a given cpu.
7827 * @cpu: the processor in question.
7828 * @p: the task pointer to set.
7830 * Description: This function must only be used when non-maskable interrupts
7831 * are serviced on a separate stack. It allows the architecture to switch the
7832 * notion of the current task on a cpu in a non-blocking manner. This function
7833 * must be called with all CPU's synchronized, and interrupts disabled, the
7834 * and caller must save the original value of the current task (see
7835 * curr_task() above) and restore that value before reenabling interrupts and
7836 * re-starting the system.
7838 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7840 void set_curr_task(int cpu, struct task_struct *p)
7842 cpu_curr(cpu) = p;
7845 #endif
7847 #ifdef CONFIG_FAIR_GROUP_SCHED
7848 static void free_fair_sched_group(struct task_group *tg)
7850 int i;
7852 for_each_possible_cpu(i) {
7853 if (tg->cfs_rq)
7854 kfree(tg->cfs_rq[i]);
7855 if (tg->se)
7856 kfree(tg->se[i]);
7859 kfree(tg->cfs_rq);
7860 kfree(tg->se);
7863 static
7864 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7866 struct cfs_rq *cfs_rq;
7867 struct sched_entity *se, *parent_se;
7868 struct rq *rq;
7869 int i;
7871 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
7872 if (!tg->cfs_rq)
7873 goto err;
7874 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
7875 if (!tg->se)
7876 goto err;
7878 tg->shares = NICE_0_LOAD;
7880 for_each_possible_cpu(i) {
7881 rq = cpu_rq(i);
7883 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
7884 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7885 if (!cfs_rq)
7886 goto err;
7888 se = kmalloc_node(sizeof(struct sched_entity),
7889 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7890 if (!se)
7891 goto err;
7893 parent_se = parent ? parent->se[i] : NULL;
7894 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
7897 return 1;
7899 err:
7900 return 0;
7903 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7905 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
7906 &cpu_rq(cpu)->leaf_cfs_rq_list);
7909 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7911 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
7913 #else
7914 static inline void free_fair_sched_group(struct task_group *tg)
7918 static inline
7919 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7921 return 1;
7924 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7928 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7931 #endif
7933 #ifdef CONFIG_RT_GROUP_SCHED
7934 static void free_rt_sched_group(struct task_group *tg)
7936 int i;
7938 destroy_rt_bandwidth(&tg->rt_bandwidth);
7940 for_each_possible_cpu(i) {
7941 if (tg->rt_rq)
7942 kfree(tg->rt_rq[i]);
7943 if (tg->rt_se)
7944 kfree(tg->rt_se[i]);
7947 kfree(tg->rt_rq);
7948 kfree(tg->rt_se);
7951 static
7952 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
7954 struct rt_rq *rt_rq;
7955 struct sched_rt_entity *rt_se, *parent_se;
7956 struct rq *rq;
7957 int i;
7959 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
7960 if (!tg->rt_rq)
7961 goto err;
7962 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
7963 if (!tg->rt_se)
7964 goto err;
7966 init_rt_bandwidth(&tg->rt_bandwidth,
7967 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
7969 for_each_possible_cpu(i) {
7970 rq = cpu_rq(i);
7972 rt_rq = kmalloc_node(sizeof(struct rt_rq),
7973 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7974 if (!rt_rq)
7975 goto err;
7977 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
7978 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7979 if (!rt_se)
7980 goto err;
7982 parent_se = parent ? parent->rt_se[i] : NULL;
7983 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
7986 return 1;
7988 err:
7989 return 0;
7992 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7994 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
7995 &cpu_rq(cpu)->leaf_rt_rq_list);
7998 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8000 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8002 #else
8003 static inline void free_rt_sched_group(struct task_group *tg)
8007 static inline
8008 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8010 return 1;
8013 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8017 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8020 #endif
8022 #ifdef CONFIG_GROUP_SCHED
8023 static void free_sched_group(struct task_group *tg)
8025 free_fair_sched_group(tg);
8026 free_rt_sched_group(tg);
8027 kfree(tg);
8030 /* allocate runqueue etc for a new task group */
8031 struct task_group *sched_create_group(struct task_group *parent)
8033 struct task_group *tg;
8034 unsigned long flags;
8035 int i;
8037 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8038 if (!tg)
8039 return ERR_PTR(-ENOMEM);
8041 if (!alloc_fair_sched_group(tg, parent))
8042 goto err;
8044 if (!alloc_rt_sched_group(tg, parent))
8045 goto err;
8047 spin_lock_irqsave(&task_group_lock, flags);
8048 for_each_possible_cpu(i) {
8049 register_fair_sched_group(tg, i);
8050 register_rt_sched_group(tg, i);
8052 list_add_rcu(&tg->list, &task_groups);
8054 WARN_ON(!parent); /* root should already exist */
8056 tg->parent = parent;
8057 list_add_rcu(&tg->siblings, &parent->children);
8058 INIT_LIST_HEAD(&tg->children);
8059 spin_unlock_irqrestore(&task_group_lock, flags);
8061 return tg;
8063 err:
8064 free_sched_group(tg);
8065 return ERR_PTR(-ENOMEM);
8068 /* rcu callback to free various structures associated with a task group */
8069 static void free_sched_group_rcu(struct rcu_head *rhp)
8071 /* now it should be safe to free those cfs_rqs */
8072 free_sched_group(container_of(rhp, struct task_group, rcu));
8075 /* Destroy runqueue etc associated with a task group */
8076 void sched_destroy_group(struct task_group *tg)
8078 unsigned long flags;
8079 int i;
8081 spin_lock_irqsave(&task_group_lock, flags);
8082 for_each_possible_cpu(i) {
8083 unregister_fair_sched_group(tg, i);
8084 unregister_rt_sched_group(tg, i);
8086 list_del_rcu(&tg->list);
8087 list_del_rcu(&tg->siblings);
8088 spin_unlock_irqrestore(&task_group_lock, flags);
8090 /* wait for possible concurrent references to cfs_rqs complete */
8091 call_rcu(&tg->rcu, free_sched_group_rcu);
8094 /* change task's runqueue when it moves between groups.
8095 * The caller of this function should have put the task in its new group
8096 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8097 * reflect its new group.
8099 void sched_move_task(struct task_struct *tsk)
8101 int on_rq, running;
8102 unsigned long flags;
8103 struct rq *rq;
8105 rq = task_rq_lock(tsk, &flags);
8107 update_rq_clock(rq);
8109 running = task_current(rq, tsk);
8110 on_rq = tsk->se.on_rq;
8112 if (on_rq)
8113 dequeue_task(rq, tsk, 0);
8114 if (unlikely(running))
8115 tsk->sched_class->put_prev_task(rq, tsk);
8117 set_task_rq(tsk, task_cpu(tsk));
8119 #ifdef CONFIG_FAIR_GROUP_SCHED
8120 if (tsk->sched_class->moved_group)
8121 tsk->sched_class->moved_group(tsk);
8122 #endif
8124 if (unlikely(running))
8125 tsk->sched_class->set_curr_task(rq);
8126 if (on_rq)
8127 enqueue_task(rq, tsk, 0);
8129 task_rq_unlock(rq, &flags);
8131 #endif
8133 #ifdef CONFIG_FAIR_GROUP_SCHED
8134 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8136 struct cfs_rq *cfs_rq = se->cfs_rq;
8137 struct rq *rq = cfs_rq->rq;
8138 int on_rq;
8140 spin_lock_irq(&rq->lock);
8142 on_rq = se->on_rq;
8143 if (on_rq)
8144 dequeue_entity(cfs_rq, se, 0);
8146 se->load.weight = shares;
8147 se->load.inv_weight = div64_64((1ULL<<32), shares);
8149 if (on_rq)
8150 enqueue_entity(cfs_rq, se, 0);
8152 spin_unlock_irq(&rq->lock);
8155 static DEFINE_MUTEX(shares_mutex);
8157 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8159 int i;
8160 unsigned long flags;
8163 * We can't change the weight of the root cgroup.
8165 if (!tg->se[0])
8166 return -EINVAL;
8169 * A weight of 0 or 1 can cause arithmetics problems.
8170 * (The default weight is 1024 - so there's no practical
8171 * limitation from this.)
8173 if (shares < 2)
8174 shares = 2;
8176 mutex_lock(&shares_mutex);
8177 if (tg->shares == shares)
8178 goto done;
8180 spin_lock_irqsave(&task_group_lock, flags);
8181 for_each_possible_cpu(i)
8182 unregister_fair_sched_group(tg, i);
8183 list_del_rcu(&tg->siblings);
8184 spin_unlock_irqrestore(&task_group_lock, flags);
8186 /* wait for any ongoing reference to this group to finish */
8187 synchronize_sched();
8190 * Now we are free to modify the group's share on each cpu
8191 * w/o tripping rebalance_share or load_balance_fair.
8193 tg->shares = shares;
8194 for_each_possible_cpu(i)
8195 set_se_shares(tg->se[i], shares);
8198 * Enable load balance activity on this group, by inserting it back on
8199 * each cpu's rq->leaf_cfs_rq_list.
8201 spin_lock_irqsave(&task_group_lock, flags);
8202 for_each_possible_cpu(i)
8203 register_fair_sched_group(tg, i);
8204 list_add_rcu(&tg->siblings, &tg->parent->children);
8205 spin_unlock_irqrestore(&task_group_lock, flags);
8206 done:
8207 mutex_unlock(&shares_mutex);
8208 return 0;
8211 unsigned long sched_group_shares(struct task_group *tg)
8213 return tg->shares;
8215 #endif
8217 #ifdef CONFIG_RT_GROUP_SCHED
8219 * Ensure that the real time constraints are schedulable.
8221 static DEFINE_MUTEX(rt_constraints_mutex);
8223 static unsigned long to_ratio(u64 period, u64 runtime)
8225 if (runtime == RUNTIME_INF)
8226 return 1ULL << 16;
8228 return div64_64(runtime << 16, period);
8231 #ifdef CONFIG_CGROUP_SCHED
8232 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8234 struct task_group *tgi, *parent = tg->parent;
8235 unsigned long total = 0;
8237 if (!parent) {
8238 if (global_rt_period() < period)
8239 return 0;
8241 return to_ratio(period, runtime) <
8242 to_ratio(global_rt_period(), global_rt_runtime());
8245 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8246 return 0;
8248 rcu_read_lock();
8249 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8250 if (tgi == tg)
8251 continue;
8253 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8254 tgi->rt_bandwidth.rt_runtime);
8256 rcu_read_unlock();
8258 return total + to_ratio(period, runtime) <
8259 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8260 parent->rt_bandwidth.rt_runtime);
8262 #elif defined CONFIG_USER_SCHED
8263 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8265 struct task_group *tgi;
8266 unsigned long total = 0;
8267 unsigned long global_ratio =
8268 to_ratio(global_rt_period(), global_rt_runtime());
8270 rcu_read_lock();
8271 list_for_each_entry_rcu(tgi, &task_groups, list) {
8272 if (tgi == tg)
8273 continue;
8275 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8276 tgi->rt_bandwidth.rt_runtime);
8278 rcu_read_unlock();
8280 return total + to_ratio(period, runtime) < global_ratio;
8282 #endif
8284 /* Must be called with tasklist_lock held */
8285 static inline int tg_has_rt_tasks(struct task_group *tg)
8287 struct task_struct *g, *p;
8288 do_each_thread(g, p) {
8289 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8290 return 1;
8291 } while_each_thread(g, p);
8292 return 0;
8295 static int tg_set_bandwidth(struct task_group *tg,
8296 u64 rt_period, u64 rt_runtime)
8298 int i, err = 0;
8300 mutex_lock(&rt_constraints_mutex);
8301 read_lock(&tasklist_lock);
8302 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8303 err = -EBUSY;
8304 goto unlock;
8306 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8307 err = -EINVAL;
8308 goto unlock;
8311 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8312 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8313 tg->rt_bandwidth.rt_runtime = rt_runtime;
8315 for_each_possible_cpu(i) {
8316 struct rt_rq *rt_rq = tg->rt_rq[i];
8318 spin_lock(&rt_rq->rt_runtime_lock);
8319 rt_rq->rt_runtime = rt_runtime;
8320 spin_unlock(&rt_rq->rt_runtime_lock);
8322 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8323 unlock:
8324 read_unlock(&tasklist_lock);
8325 mutex_unlock(&rt_constraints_mutex);
8327 return err;
8330 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8332 u64 rt_runtime, rt_period;
8334 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8335 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8336 if (rt_runtime_us < 0)
8337 rt_runtime = RUNTIME_INF;
8339 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8342 long sched_group_rt_runtime(struct task_group *tg)
8344 u64 rt_runtime_us;
8346 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8347 return -1;
8349 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8350 do_div(rt_runtime_us, NSEC_PER_USEC);
8351 return rt_runtime_us;
8354 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8356 u64 rt_runtime, rt_period;
8358 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8359 rt_runtime = tg->rt_bandwidth.rt_runtime;
8361 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8364 long sched_group_rt_period(struct task_group *tg)
8366 u64 rt_period_us;
8368 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8369 do_div(rt_period_us, NSEC_PER_USEC);
8370 return rt_period_us;
8373 static int sched_rt_global_constraints(void)
8375 int ret = 0;
8377 mutex_lock(&rt_constraints_mutex);
8378 if (!__rt_schedulable(NULL, 1, 0))
8379 ret = -EINVAL;
8380 mutex_unlock(&rt_constraints_mutex);
8382 return ret;
8384 #else
8385 static int sched_rt_global_constraints(void)
8387 unsigned long flags;
8388 int i;
8390 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8391 for_each_possible_cpu(i) {
8392 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8394 spin_lock(&rt_rq->rt_runtime_lock);
8395 rt_rq->rt_runtime = global_rt_runtime();
8396 spin_unlock(&rt_rq->rt_runtime_lock);
8398 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8400 return 0;
8402 #endif
8404 int sched_rt_handler(struct ctl_table *table, int write,
8405 struct file *filp, void __user *buffer, size_t *lenp,
8406 loff_t *ppos)
8408 int ret;
8409 int old_period, old_runtime;
8410 static DEFINE_MUTEX(mutex);
8412 mutex_lock(&mutex);
8413 old_period = sysctl_sched_rt_period;
8414 old_runtime = sysctl_sched_rt_runtime;
8416 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
8418 if (!ret && write) {
8419 ret = sched_rt_global_constraints();
8420 if (ret) {
8421 sysctl_sched_rt_period = old_period;
8422 sysctl_sched_rt_runtime = old_runtime;
8423 } else {
8424 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8425 def_rt_bandwidth.rt_period =
8426 ns_to_ktime(global_rt_period());
8429 mutex_unlock(&mutex);
8431 return ret;
8434 #ifdef CONFIG_CGROUP_SCHED
8436 /* return corresponding task_group object of a cgroup */
8437 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8439 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8440 struct task_group, css);
8443 static struct cgroup_subsys_state *
8444 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8446 struct task_group *tg, *parent;
8448 if (!cgrp->parent) {
8449 /* This is early initialization for the top cgroup */
8450 init_task_group.css.cgroup = cgrp;
8451 return &init_task_group.css;
8454 parent = cgroup_tg(cgrp->parent);
8455 tg = sched_create_group(parent);
8456 if (IS_ERR(tg))
8457 return ERR_PTR(-ENOMEM);
8459 /* Bind the cgroup to task_group object we just created */
8460 tg->css.cgroup = cgrp;
8462 return &tg->css;
8465 static void
8466 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8468 struct task_group *tg = cgroup_tg(cgrp);
8470 sched_destroy_group(tg);
8473 static int
8474 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8475 struct task_struct *tsk)
8477 #ifdef CONFIG_RT_GROUP_SCHED
8478 /* Don't accept realtime tasks when there is no way for them to run */
8479 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
8480 return -EINVAL;
8481 #else
8482 /* We don't support RT-tasks being in separate groups */
8483 if (tsk->sched_class != &fair_sched_class)
8484 return -EINVAL;
8485 #endif
8487 return 0;
8490 static void
8491 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8492 struct cgroup *old_cont, struct task_struct *tsk)
8494 sched_move_task(tsk);
8497 #ifdef CONFIG_FAIR_GROUP_SCHED
8498 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8499 u64 shareval)
8501 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8504 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
8506 struct task_group *tg = cgroup_tg(cgrp);
8508 return (u64) tg->shares;
8510 #endif
8512 #ifdef CONFIG_RT_GROUP_SCHED
8513 static ssize_t cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8514 struct file *file,
8515 const char __user *userbuf,
8516 size_t nbytes, loff_t *unused_ppos)
8518 char buffer[64];
8519 int retval = 0;
8520 s64 val;
8521 char *end;
8523 if (!nbytes)
8524 return -EINVAL;
8525 if (nbytes >= sizeof(buffer))
8526 return -E2BIG;
8527 if (copy_from_user(buffer, userbuf, nbytes))
8528 return -EFAULT;
8530 buffer[nbytes] = 0; /* nul-terminate */
8532 /* strip newline if necessary */
8533 if (nbytes && (buffer[nbytes-1] == '\n'))
8534 buffer[nbytes-1] = 0;
8535 val = simple_strtoll(buffer, &end, 0);
8536 if (*end)
8537 return -EINVAL;
8539 /* Pass to subsystem */
8540 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8541 if (!retval)
8542 retval = nbytes;
8543 return retval;
8546 static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
8547 struct file *file,
8548 char __user *buf, size_t nbytes,
8549 loff_t *ppos)
8551 char tmp[64];
8552 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
8553 int len = sprintf(tmp, "%ld\n", val);
8555 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
8558 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8559 u64 rt_period_us)
8561 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8564 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8566 return sched_group_rt_period(cgroup_tg(cgrp));
8568 #endif
8570 static struct cftype cpu_files[] = {
8571 #ifdef CONFIG_FAIR_GROUP_SCHED
8573 .name = "shares",
8574 .read_uint = cpu_shares_read_uint,
8575 .write_uint = cpu_shares_write_uint,
8577 #endif
8578 #ifdef CONFIG_RT_GROUP_SCHED
8580 .name = "rt_runtime_us",
8581 .read = cpu_rt_runtime_read,
8582 .write = cpu_rt_runtime_write,
8585 .name = "rt_period_us",
8586 .read_uint = cpu_rt_period_read_uint,
8587 .write_uint = cpu_rt_period_write_uint,
8589 #endif
8592 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8594 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8597 struct cgroup_subsys cpu_cgroup_subsys = {
8598 .name = "cpu",
8599 .create = cpu_cgroup_create,
8600 .destroy = cpu_cgroup_destroy,
8601 .can_attach = cpu_cgroup_can_attach,
8602 .attach = cpu_cgroup_attach,
8603 .populate = cpu_cgroup_populate,
8604 .subsys_id = cpu_cgroup_subsys_id,
8605 .early_init = 1,
8608 #endif /* CONFIG_CGROUP_SCHED */
8610 #ifdef CONFIG_CGROUP_CPUACCT
8613 * CPU accounting code for task groups.
8615 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8616 * (balbir@in.ibm.com).
8619 /* track cpu usage of a group of tasks */
8620 struct cpuacct {
8621 struct cgroup_subsys_state css;
8622 /* cpuusage holds pointer to a u64-type object on every cpu */
8623 u64 *cpuusage;
8626 struct cgroup_subsys cpuacct_subsys;
8628 /* return cpu accounting group corresponding to this container */
8629 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
8631 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
8632 struct cpuacct, css);
8635 /* return cpu accounting group to which this task belongs */
8636 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8638 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8639 struct cpuacct, css);
8642 /* create a new cpu accounting group */
8643 static struct cgroup_subsys_state *cpuacct_create(
8644 struct cgroup_subsys *ss, struct cgroup *cgrp)
8646 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8648 if (!ca)
8649 return ERR_PTR(-ENOMEM);
8651 ca->cpuusage = alloc_percpu(u64);
8652 if (!ca->cpuusage) {
8653 kfree(ca);
8654 return ERR_PTR(-ENOMEM);
8657 return &ca->css;
8660 /* destroy an existing cpu accounting group */
8661 static void
8662 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8664 struct cpuacct *ca = cgroup_ca(cgrp);
8666 free_percpu(ca->cpuusage);
8667 kfree(ca);
8670 /* return total cpu usage (in nanoseconds) of a group */
8671 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
8673 struct cpuacct *ca = cgroup_ca(cgrp);
8674 u64 totalcpuusage = 0;
8675 int i;
8677 for_each_possible_cpu(i) {
8678 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8681 * Take rq->lock to make 64-bit addition safe on 32-bit
8682 * platforms.
8684 spin_lock_irq(&cpu_rq(i)->lock);
8685 totalcpuusage += *cpuusage;
8686 spin_unlock_irq(&cpu_rq(i)->lock);
8689 return totalcpuusage;
8692 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
8693 u64 reset)
8695 struct cpuacct *ca = cgroup_ca(cgrp);
8696 int err = 0;
8697 int i;
8699 if (reset) {
8700 err = -EINVAL;
8701 goto out;
8704 for_each_possible_cpu(i) {
8705 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8707 spin_lock_irq(&cpu_rq(i)->lock);
8708 *cpuusage = 0;
8709 spin_unlock_irq(&cpu_rq(i)->lock);
8711 out:
8712 return err;
8715 static struct cftype files[] = {
8717 .name = "usage",
8718 .read_uint = cpuusage_read,
8719 .write_uint = cpuusage_write,
8723 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
8725 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
8729 * charge this task's execution time to its accounting group.
8731 * called with rq->lock held.
8733 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8735 struct cpuacct *ca;
8737 if (!cpuacct_subsys.active)
8738 return;
8740 ca = task_ca(tsk);
8741 if (ca) {
8742 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
8744 *cpuusage += cputime;
8748 struct cgroup_subsys cpuacct_subsys = {
8749 .name = "cpuacct",
8750 .create = cpuacct_create,
8751 .destroy = cpuacct_destroy,
8752 .populate = cpuacct_populate,
8753 .subsys_id = cpuacct_subsys_id,
8755 #endif /* CONFIG_CGROUP_CPUACCT */