sched: fix missing locking in sched_domains code
[linux-2.6/linux-2.6-openrd.git] / kernel / sched.c
blob561b3b39bdb873d0dcc56c760752155b7fa106a4
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>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
74 #include <asm/tlb.h>
75 #include <asm/irq_regs.h>
78 * Scheduler clock - returns current time in nanosec units.
79 * This is default implementation.
80 * Architectures and sub-architectures can override this.
82 unsigned long long __attribute__((weak)) sched_clock(void)
84 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
88 * Convert user-nice values [ -20 ... 0 ... 19 ]
89 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
90 * and back.
92 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
93 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
94 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
97 * 'User priority' is the nice value converted to something we
98 * can work with better when scaling various scheduler parameters,
99 * it's a [ 0 ... 39 ] range.
101 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
102 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
103 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
106 * Helpers for converting nanosecond timing to jiffy resolution
108 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
110 #define NICE_0_LOAD SCHED_LOAD_SCALE
111 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
114 * These are the 'tuning knobs' of the scheduler:
116 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
117 * Timeslices get refilled after they expire.
119 #define DEF_TIMESLICE (100 * HZ / 1000)
122 * single value that denotes runtime == period, ie unlimited time.
124 #define RUNTIME_INF ((u64)~0ULL)
126 #ifdef CONFIG_SMP
128 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
129 * Since cpu_power is a 'constant', we can use a reciprocal divide.
131 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
133 return reciprocal_divide(load, sg->reciprocal_cpu_power);
137 * Each time a sched group cpu_power is changed,
138 * we must compute its reciprocal value
140 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
142 sg->__cpu_power += val;
143 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
145 #endif
147 static inline int rt_policy(int policy)
149 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
150 return 1;
151 return 0;
154 static inline int task_has_rt_policy(struct task_struct *p)
156 return rt_policy(p->policy);
160 * This is the priority-queue data structure of the RT scheduling class:
162 struct rt_prio_array {
163 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
164 struct list_head queue[MAX_RT_PRIO];
167 struct rt_bandwidth {
168 /* nests inside the rq lock: */
169 spinlock_t rt_runtime_lock;
170 ktime_t rt_period;
171 u64 rt_runtime;
172 struct hrtimer rt_period_timer;
175 static struct rt_bandwidth def_rt_bandwidth;
177 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
179 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
181 struct rt_bandwidth *rt_b =
182 container_of(timer, struct rt_bandwidth, rt_period_timer);
183 ktime_t now;
184 int overrun;
185 int idle = 0;
187 for (;;) {
188 now = hrtimer_cb_get_time(timer);
189 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
191 if (!overrun)
192 break;
194 idle = do_sched_rt_period_timer(rt_b, overrun);
197 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
200 static
201 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
203 rt_b->rt_period = ns_to_ktime(period);
204 rt_b->rt_runtime = runtime;
206 spin_lock_init(&rt_b->rt_runtime_lock);
208 hrtimer_init(&rt_b->rt_period_timer,
209 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
210 rt_b->rt_period_timer.function = sched_rt_period_timer;
211 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
214 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
216 ktime_t now;
218 if (rt_b->rt_runtime == RUNTIME_INF)
219 return;
221 if (hrtimer_active(&rt_b->rt_period_timer))
222 return;
224 spin_lock(&rt_b->rt_runtime_lock);
225 for (;;) {
226 if (hrtimer_active(&rt_b->rt_period_timer))
227 break;
229 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
230 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
231 hrtimer_start(&rt_b->rt_period_timer,
232 rt_b->rt_period_timer.expires,
233 HRTIMER_MODE_ABS);
235 spin_unlock(&rt_b->rt_runtime_lock);
238 #ifdef CONFIG_RT_GROUP_SCHED
239 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
241 hrtimer_cancel(&rt_b->rt_period_timer);
243 #endif
246 * sched_domains_mutex serializes calls to arch_init_sched_domains,
247 * detach_destroy_domains and partition_sched_domains.
249 static DEFINE_MUTEX(sched_domains_mutex);
251 #ifdef CONFIG_GROUP_SCHED
253 #include <linux/cgroup.h>
255 struct cfs_rq;
257 static LIST_HEAD(task_groups);
259 /* task group related information */
260 struct task_group {
261 #ifdef CONFIG_CGROUP_SCHED
262 struct cgroup_subsys_state css;
263 #endif
265 #ifdef CONFIG_FAIR_GROUP_SCHED
266 /* schedulable entities of this group on each cpu */
267 struct sched_entity **se;
268 /* runqueue "owned" by this group on each cpu */
269 struct cfs_rq **cfs_rq;
270 unsigned long shares;
271 #endif
273 #ifdef CONFIG_RT_GROUP_SCHED
274 struct sched_rt_entity **rt_se;
275 struct rt_rq **rt_rq;
277 struct rt_bandwidth rt_bandwidth;
278 #endif
280 struct rcu_head rcu;
281 struct list_head list;
283 struct task_group *parent;
284 struct list_head siblings;
285 struct list_head children;
288 #ifdef CONFIG_USER_SCHED
291 * Root task group.
292 * Every UID task group (including init_task_group aka UID-0) will
293 * be a child to this group.
295 struct task_group root_task_group;
297 #ifdef CONFIG_FAIR_GROUP_SCHED
298 /* Default task group's sched entity on each cpu */
299 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
300 /* Default task group's cfs_rq on each cpu */
301 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
302 #endif
304 #ifdef CONFIG_RT_GROUP_SCHED
305 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
306 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
307 #endif
308 #else
309 #define root_task_group init_task_group
310 #endif
312 /* task_group_lock serializes add/remove of task groups and also changes to
313 * a task group's cpu shares.
315 static DEFINE_SPINLOCK(task_group_lock);
317 #ifdef CONFIG_FAIR_GROUP_SCHED
318 #ifdef CONFIG_USER_SCHED
319 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
320 #else
321 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
322 #endif
324 #define MIN_SHARES 2
326 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
327 #endif
329 /* Default task group.
330 * Every task in system belong to this group at bootup.
332 struct task_group init_task_group;
334 /* return group to which a task belongs */
335 static inline struct task_group *task_group(struct task_struct *p)
337 struct task_group *tg;
339 #ifdef CONFIG_USER_SCHED
340 tg = p->user->tg;
341 #elif defined(CONFIG_CGROUP_SCHED)
342 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
343 struct task_group, css);
344 #else
345 tg = &init_task_group;
346 #endif
347 return tg;
350 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
351 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
353 #ifdef CONFIG_FAIR_GROUP_SCHED
354 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
355 p->se.parent = task_group(p)->se[cpu];
356 #endif
358 #ifdef CONFIG_RT_GROUP_SCHED
359 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
360 p->rt.parent = task_group(p)->rt_se[cpu];
361 #endif
364 #else
366 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
368 #endif /* CONFIG_GROUP_SCHED */
370 /* CFS-related fields in a runqueue */
371 struct cfs_rq {
372 struct load_weight load;
373 unsigned long nr_running;
375 u64 exec_clock;
376 u64 min_vruntime;
378 struct rb_root tasks_timeline;
379 struct rb_node *rb_leftmost;
381 struct list_head tasks;
382 struct list_head *balance_iterator;
385 * 'curr' points to currently running entity on this cfs_rq.
386 * It is set to NULL otherwise (i.e when none are currently running).
388 struct sched_entity *curr, *next;
390 unsigned long nr_spread_over;
392 #ifdef CONFIG_FAIR_GROUP_SCHED
393 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
396 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
397 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
398 * (like users, containers etc.)
400 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
401 * list is used during load balance.
403 struct list_head leaf_cfs_rq_list;
404 struct task_group *tg; /* group that "owns" this runqueue */
406 #ifdef CONFIG_SMP
407 unsigned long task_weight;
408 unsigned long shares;
410 * We need space to build a sched_domain wide view of the full task
411 * group tree, in order to avoid depending on dynamic memory allocation
412 * during the load balancing we place this in the per cpu task group
413 * hierarchy. This limits the load balancing to one instance per cpu,
414 * but more should not be needed anyway.
416 struct aggregate_struct {
418 * load = weight(cpus) * f(tg)
420 * Where f(tg) is the recursive weight fraction assigned to
421 * this group.
423 unsigned long load;
426 * part of the group weight distributed to this span.
428 unsigned long shares;
431 * The sum of all runqueue weights within this span.
433 unsigned long rq_weight;
436 * Weight contributed by tasks; this is the part we can
437 * influence by moving tasks around.
439 unsigned long task_weight;
440 } aggregate;
441 #endif
442 #endif
445 /* Real-Time classes' related field in a runqueue: */
446 struct rt_rq {
447 struct rt_prio_array active;
448 unsigned long rt_nr_running;
449 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
450 int highest_prio; /* highest queued rt task prio */
451 #endif
452 #ifdef CONFIG_SMP
453 unsigned long rt_nr_migratory;
454 int overloaded;
455 #endif
456 int rt_throttled;
457 u64 rt_time;
458 u64 rt_runtime;
459 /* Nests inside the rq lock: */
460 spinlock_t rt_runtime_lock;
462 #ifdef CONFIG_RT_GROUP_SCHED
463 unsigned long rt_nr_boosted;
465 struct rq *rq;
466 struct list_head leaf_rt_rq_list;
467 struct task_group *tg;
468 struct sched_rt_entity *rt_se;
469 #endif
472 #ifdef CONFIG_SMP
475 * We add the notion of a root-domain which will be used to define per-domain
476 * variables. Each exclusive cpuset essentially defines an island domain by
477 * fully partitioning the member cpus from any other cpuset. Whenever a new
478 * exclusive cpuset is created, we also create and attach a new root-domain
479 * object.
482 struct root_domain {
483 atomic_t refcount;
484 cpumask_t span;
485 cpumask_t online;
488 * The "RT overload" flag: it gets set if a CPU has more than
489 * one runnable RT task.
491 cpumask_t rto_mask;
492 atomic_t rto_count;
496 * By default the system creates a single root-domain with all cpus as
497 * members (mimicking the global state we have today).
499 static struct root_domain def_root_domain;
501 #endif
504 * This is the main, per-CPU runqueue data structure.
506 * Locking rule: those places that want to lock multiple runqueues
507 * (such as the load balancing or the thread migration code), lock
508 * acquire operations must be ordered by ascending &runqueue.
510 struct rq {
511 /* runqueue lock: */
512 spinlock_t lock;
515 * nr_running and cpu_load should be in the same cacheline because
516 * remote CPUs use both these fields when doing load calculation.
518 unsigned long nr_running;
519 #define CPU_LOAD_IDX_MAX 5
520 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
521 unsigned char idle_at_tick;
522 #ifdef CONFIG_NO_HZ
523 unsigned long last_tick_seen;
524 unsigned char in_nohz_recently;
525 #endif
526 /* capture load from *all* tasks on this cpu: */
527 struct load_weight load;
528 unsigned long nr_load_updates;
529 u64 nr_switches;
531 struct cfs_rq cfs;
532 struct rt_rq rt;
534 #ifdef CONFIG_FAIR_GROUP_SCHED
535 /* list of leaf cfs_rq on this cpu: */
536 struct list_head leaf_cfs_rq_list;
537 #endif
538 #ifdef CONFIG_RT_GROUP_SCHED
539 struct list_head leaf_rt_rq_list;
540 #endif
543 * This is part of a global counter where only the total sum
544 * over all CPUs matters. A task can increase this counter on
545 * one CPU and if it got migrated afterwards it may decrease
546 * it on another CPU. Always updated under the runqueue lock:
548 unsigned long nr_uninterruptible;
550 struct task_struct *curr, *idle;
551 unsigned long next_balance;
552 struct mm_struct *prev_mm;
554 u64 clock, prev_clock_raw;
555 s64 clock_max_delta;
557 unsigned int clock_warps, clock_overflows, clock_underflows;
558 u64 idle_clock;
559 unsigned int clock_deep_idle_events;
560 u64 tick_timestamp;
562 atomic_t nr_iowait;
564 #ifdef CONFIG_SMP
565 struct root_domain *rd;
566 struct sched_domain *sd;
568 /* For active balancing */
569 int active_balance;
570 int push_cpu;
571 /* cpu of this runqueue: */
572 int cpu;
574 struct task_struct *migration_thread;
575 struct list_head migration_queue;
576 #endif
578 #ifdef CONFIG_SCHED_HRTICK
579 unsigned long hrtick_flags;
580 ktime_t hrtick_expire;
581 struct hrtimer hrtick_timer;
582 #endif
584 #ifdef CONFIG_SCHEDSTATS
585 /* latency stats */
586 struct sched_info rq_sched_info;
588 /* sys_sched_yield() stats */
589 unsigned int yld_exp_empty;
590 unsigned int yld_act_empty;
591 unsigned int yld_both_empty;
592 unsigned int yld_count;
594 /* schedule() stats */
595 unsigned int sched_switch;
596 unsigned int sched_count;
597 unsigned int sched_goidle;
599 /* try_to_wake_up() stats */
600 unsigned int ttwu_count;
601 unsigned int ttwu_local;
603 /* BKL stats */
604 unsigned int bkl_count;
605 #endif
606 struct lock_class_key rq_lock_key;
609 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
611 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
613 rq->curr->sched_class->check_preempt_curr(rq, p);
616 static inline int cpu_of(struct rq *rq)
618 #ifdef CONFIG_SMP
619 return rq->cpu;
620 #else
621 return 0;
622 #endif
625 #ifdef CONFIG_NO_HZ
626 static inline bool nohz_on(int cpu)
628 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
631 static inline u64 max_skipped_ticks(struct rq *rq)
633 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
636 static inline void update_last_tick_seen(struct rq *rq)
638 rq->last_tick_seen = jiffies;
640 #else
641 static inline u64 max_skipped_ticks(struct rq *rq)
643 return 1;
646 static inline void update_last_tick_seen(struct rq *rq)
649 #endif
652 * Update the per-runqueue clock, as finegrained as the platform can give
653 * us, but without assuming monotonicity, etc.:
655 static void __update_rq_clock(struct rq *rq)
657 u64 prev_raw = rq->prev_clock_raw;
658 u64 now = sched_clock();
659 s64 delta = now - prev_raw;
660 u64 clock = rq->clock;
662 #ifdef CONFIG_SCHED_DEBUG
663 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
664 #endif
666 * Protect against sched_clock() occasionally going backwards:
668 if (unlikely(delta < 0)) {
669 clock++;
670 rq->clock_warps++;
671 } else {
673 * Catch too large forward jumps too:
675 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
676 u64 max_time = rq->tick_timestamp + max_jump;
678 if (unlikely(clock + delta > max_time)) {
679 if (clock < max_time)
680 clock = max_time;
681 else
682 clock++;
683 rq->clock_overflows++;
684 } else {
685 if (unlikely(delta > rq->clock_max_delta))
686 rq->clock_max_delta = delta;
687 clock += delta;
691 rq->prev_clock_raw = now;
692 rq->clock = clock;
695 static void update_rq_clock(struct rq *rq)
697 if (likely(smp_processor_id() == cpu_of(rq)))
698 __update_rq_clock(rq);
702 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
703 * See detach_destroy_domains: synchronize_sched for details.
705 * The domain tree of any CPU may only be accessed from within
706 * preempt-disabled sections.
708 #define for_each_domain(cpu, __sd) \
709 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
711 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
712 #define this_rq() (&__get_cpu_var(runqueues))
713 #define task_rq(p) cpu_rq(task_cpu(p))
714 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
717 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
719 #ifdef CONFIG_SCHED_DEBUG
720 # define const_debug __read_mostly
721 #else
722 # define const_debug static const
723 #endif
726 * Debugging: various feature bits
729 #define SCHED_FEAT(name, enabled) \
730 __SCHED_FEAT_##name ,
732 enum {
733 #include "sched_features.h"
736 #undef SCHED_FEAT
738 #define SCHED_FEAT(name, enabled) \
739 (1UL << __SCHED_FEAT_##name) * enabled |
741 const_debug unsigned int sysctl_sched_features =
742 #include "sched_features.h"
745 #undef SCHED_FEAT
747 #ifdef CONFIG_SCHED_DEBUG
748 #define SCHED_FEAT(name, enabled) \
749 #name ,
751 static __read_mostly char *sched_feat_names[] = {
752 #include "sched_features.h"
753 NULL
756 #undef SCHED_FEAT
758 static int sched_feat_open(struct inode *inode, struct file *filp)
760 filp->private_data = inode->i_private;
761 return 0;
764 static ssize_t
765 sched_feat_read(struct file *filp, char __user *ubuf,
766 size_t cnt, loff_t *ppos)
768 char *buf;
769 int r = 0;
770 int len = 0;
771 int i;
773 for (i = 0; sched_feat_names[i]; i++) {
774 len += strlen(sched_feat_names[i]);
775 len += 4;
778 buf = kmalloc(len + 2, GFP_KERNEL);
779 if (!buf)
780 return -ENOMEM;
782 for (i = 0; sched_feat_names[i]; i++) {
783 if (sysctl_sched_features & (1UL << i))
784 r += sprintf(buf + r, "%s ", sched_feat_names[i]);
785 else
786 r += sprintf(buf + r, "NO_%s ", sched_feat_names[i]);
789 r += sprintf(buf + r, "\n");
790 WARN_ON(r >= len + 2);
792 r = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
794 kfree(buf);
796 return r;
799 static ssize_t
800 sched_feat_write(struct file *filp, const char __user *ubuf,
801 size_t cnt, loff_t *ppos)
803 char buf[64];
804 char *cmp = buf;
805 int neg = 0;
806 int i;
808 if (cnt > 63)
809 cnt = 63;
811 if (copy_from_user(&buf, ubuf, cnt))
812 return -EFAULT;
814 buf[cnt] = 0;
816 if (strncmp(buf, "NO_", 3) == 0) {
817 neg = 1;
818 cmp += 3;
821 for (i = 0; sched_feat_names[i]; i++) {
822 int len = strlen(sched_feat_names[i]);
824 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
825 if (neg)
826 sysctl_sched_features &= ~(1UL << i);
827 else
828 sysctl_sched_features |= (1UL << i);
829 break;
833 if (!sched_feat_names[i])
834 return -EINVAL;
836 filp->f_pos += cnt;
838 return cnt;
841 static struct file_operations sched_feat_fops = {
842 .open = sched_feat_open,
843 .read = sched_feat_read,
844 .write = sched_feat_write,
847 static __init int sched_init_debug(void)
849 debugfs_create_file("sched_features", 0644, NULL, NULL,
850 &sched_feat_fops);
852 return 0;
854 late_initcall(sched_init_debug);
856 #endif
858 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
861 * Number of tasks to iterate in a single balance run.
862 * Limited because this is done with IRQs disabled.
864 const_debug unsigned int sysctl_sched_nr_migrate = 32;
867 * period over which we measure -rt task cpu usage in us.
868 * default: 1s
870 unsigned int sysctl_sched_rt_period = 1000000;
872 static __read_mostly int scheduler_running;
875 * part of the period that we allow rt tasks to run in us.
876 * default: 0.95s
878 int sysctl_sched_rt_runtime = 950000;
880 static inline u64 global_rt_period(void)
882 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
885 static inline u64 global_rt_runtime(void)
887 if (sysctl_sched_rt_period < 0)
888 return RUNTIME_INF;
890 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
893 unsigned long long time_sync_thresh = 100000;
895 static DEFINE_PER_CPU(unsigned long long, time_offset);
896 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
899 * Global lock which we take every now and then to synchronize
900 * the CPUs time. This method is not warp-safe, but it's good
901 * enough to synchronize slowly diverging time sources and thus
902 * it's good enough for tracing:
904 static DEFINE_SPINLOCK(time_sync_lock);
905 static unsigned long long prev_global_time;
907 static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
909 unsigned long flags;
911 spin_lock_irqsave(&time_sync_lock, flags);
913 if (time < prev_global_time) {
914 per_cpu(time_offset, cpu) += prev_global_time - time;
915 time = prev_global_time;
916 } else {
917 prev_global_time = time;
920 spin_unlock_irqrestore(&time_sync_lock, flags);
922 return time;
925 static unsigned long long __cpu_clock(int cpu)
927 unsigned long long now;
928 unsigned long flags;
929 struct rq *rq;
932 * Only call sched_clock() if the scheduler has already been
933 * initialized (some code might call cpu_clock() very early):
935 if (unlikely(!scheduler_running))
936 return 0;
938 local_irq_save(flags);
939 rq = cpu_rq(cpu);
940 update_rq_clock(rq);
941 now = rq->clock;
942 local_irq_restore(flags);
944 return now;
948 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
949 * clock constructed from sched_clock():
951 unsigned long long cpu_clock(int cpu)
953 unsigned long long prev_cpu_time, time, delta_time;
955 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
956 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
957 delta_time = time-prev_cpu_time;
959 if (unlikely(delta_time > time_sync_thresh))
960 time = __sync_cpu_clock(time, cpu);
962 return time;
964 EXPORT_SYMBOL_GPL(cpu_clock);
966 #ifndef prepare_arch_switch
967 # define prepare_arch_switch(next) do { } while (0)
968 #endif
969 #ifndef finish_arch_switch
970 # define finish_arch_switch(prev) do { } while (0)
971 #endif
973 static inline int task_current(struct rq *rq, struct task_struct *p)
975 return rq->curr == p;
978 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
979 static inline int task_running(struct rq *rq, struct task_struct *p)
981 return task_current(rq, p);
984 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
988 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
990 #ifdef CONFIG_DEBUG_SPINLOCK
991 /* this is a valid case when another task releases the spinlock */
992 rq->lock.owner = current;
993 #endif
995 * If we are tracking spinlock dependencies then we have to
996 * fix up the runqueue lock - which gets 'carried over' from
997 * prev into current:
999 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
1001 spin_unlock_irq(&rq->lock);
1004 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
1005 static inline int task_running(struct rq *rq, struct task_struct *p)
1007 #ifdef CONFIG_SMP
1008 return p->oncpu;
1009 #else
1010 return task_current(rq, p);
1011 #endif
1014 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
1016 #ifdef CONFIG_SMP
1018 * We can optimise this out completely for !SMP, because the
1019 * SMP rebalancing from interrupt is the only thing that cares
1020 * here.
1022 next->oncpu = 1;
1023 #endif
1024 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1025 spin_unlock_irq(&rq->lock);
1026 #else
1027 spin_unlock(&rq->lock);
1028 #endif
1031 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
1033 #ifdef CONFIG_SMP
1035 * After ->oncpu is cleared, the task can be moved to a different CPU.
1036 * We must ensure this doesn't happen until the switch is completely
1037 * finished.
1039 smp_wmb();
1040 prev->oncpu = 0;
1041 #endif
1042 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1043 local_irq_enable();
1044 #endif
1046 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1049 * __task_rq_lock - lock the runqueue a given task resides on.
1050 * Must be called interrupts disabled.
1052 static inline struct rq *__task_rq_lock(struct task_struct *p)
1053 __acquires(rq->lock)
1055 for (;;) {
1056 struct rq *rq = task_rq(p);
1057 spin_lock(&rq->lock);
1058 if (likely(rq == task_rq(p)))
1059 return rq;
1060 spin_unlock(&rq->lock);
1065 * task_rq_lock - lock the runqueue a given task resides on and disable
1066 * interrupts. Note the ordering: we can safely lookup the task_rq without
1067 * explicitly disabling preemption.
1069 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1070 __acquires(rq->lock)
1072 struct rq *rq;
1074 for (;;) {
1075 local_irq_save(*flags);
1076 rq = task_rq(p);
1077 spin_lock(&rq->lock);
1078 if (likely(rq == task_rq(p)))
1079 return rq;
1080 spin_unlock_irqrestore(&rq->lock, *flags);
1084 static void __task_rq_unlock(struct rq *rq)
1085 __releases(rq->lock)
1087 spin_unlock(&rq->lock);
1090 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1091 __releases(rq->lock)
1093 spin_unlock_irqrestore(&rq->lock, *flags);
1097 * this_rq_lock - lock this runqueue and disable interrupts.
1099 static struct rq *this_rq_lock(void)
1100 __acquires(rq->lock)
1102 struct rq *rq;
1104 local_irq_disable();
1105 rq = this_rq();
1106 spin_lock(&rq->lock);
1108 return rq;
1112 * We are going deep-idle (irqs are disabled):
1114 void sched_clock_idle_sleep_event(void)
1116 struct rq *rq = cpu_rq(smp_processor_id());
1118 WARN_ON(!irqs_disabled());
1119 spin_lock(&rq->lock);
1120 __update_rq_clock(rq);
1121 spin_unlock(&rq->lock);
1122 rq->clock_deep_idle_events++;
1124 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
1127 * We just idled delta nanoseconds (called with irqs disabled):
1129 void sched_clock_idle_wakeup_event(u64 delta_ns)
1131 struct rq *rq = cpu_rq(smp_processor_id());
1132 u64 now = sched_clock();
1134 WARN_ON(!irqs_disabled());
1135 rq->idle_clock += delta_ns;
1137 * Override the previous timestamp and ignore all
1138 * sched_clock() deltas that occured while we idled,
1139 * and use the PM-provided delta_ns to advance the
1140 * rq clock:
1142 spin_lock(&rq->lock);
1143 rq->prev_clock_raw = now;
1144 rq->clock += delta_ns;
1145 spin_unlock(&rq->lock);
1146 touch_softlockup_watchdog();
1148 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1150 static void __resched_task(struct task_struct *p, int tif_bit);
1152 static inline void resched_task(struct task_struct *p)
1154 __resched_task(p, TIF_NEED_RESCHED);
1157 #ifdef CONFIG_SCHED_HRTICK
1159 * Use HR-timers to deliver accurate preemption points.
1161 * Its all a bit involved since we cannot program an hrt while holding the
1162 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1163 * reschedule event.
1165 * When we get rescheduled we reprogram the hrtick_timer outside of the
1166 * rq->lock.
1168 static inline void resched_hrt(struct task_struct *p)
1170 __resched_task(p, TIF_HRTICK_RESCHED);
1173 static inline void resched_rq(struct rq *rq)
1175 unsigned long flags;
1177 spin_lock_irqsave(&rq->lock, flags);
1178 resched_task(rq->curr);
1179 spin_unlock_irqrestore(&rq->lock, flags);
1182 enum {
1183 HRTICK_SET, /* re-programm hrtick_timer */
1184 HRTICK_RESET, /* not a new slice */
1185 HRTICK_BLOCK, /* stop hrtick operations */
1189 * Use hrtick when:
1190 * - enabled by features
1191 * - hrtimer is actually high res
1193 static inline int hrtick_enabled(struct rq *rq)
1195 if (!sched_feat(HRTICK))
1196 return 0;
1197 if (unlikely(test_bit(HRTICK_BLOCK, &rq->hrtick_flags)))
1198 return 0;
1199 return hrtimer_is_hres_active(&rq->hrtick_timer);
1203 * Called to set the hrtick timer state.
1205 * called with rq->lock held and irqs disabled
1207 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1209 assert_spin_locked(&rq->lock);
1212 * preempt at: now + delay
1214 rq->hrtick_expire =
1215 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1217 * indicate we need to program the timer
1219 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1220 if (reset)
1221 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1224 * New slices are called from the schedule path and don't need a
1225 * forced reschedule.
1227 if (reset)
1228 resched_hrt(rq->curr);
1231 static void hrtick_clear(struct rq *rq)
1233 if (hrtimer_active(&rq->hrtick_timer))
1234 hrtimer_cancel(&rq->hrtick_timer);
1238 * Update the timer from the possible pending state.
1240 static void hrtick_set(struct rq *rq)
1242 ktime_t time;
1243 int set, reset;
1244 unsigned long flags;
1246 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1248 spin_lock_irqsave(&rq->lock, flags);
1249 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1250 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1251 time = rq->hrtick_expire;
1252 clear_thread_flag(TIF_HRTICK_RESCHED);
1253 spin_unlock_irqrestore(&rq->lock, flags);
1255 if (set) {
1256 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1257 if (reset && !hrtimer_active(&rq->hrtick_timer))
1258 resched_rq(rq);
1259 } else
1260 hrtick_clear(rq);
1264 * High-resolution timer tick.
1265 * Runs from hardirq context with interrupts disabled.
1267 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1269 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1271 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1273 spin_lock(&rq->lock);
1274 __update_rq_clock(rq);
1275 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1276 spin_unlock(&rq->lock);
1278 return HRTIMER_NORESTART;
1281 static void hotplug_hrtick_disable(int cpu)
1283 struct rq *rq = cpu_rq(cpu);
1284 unsigned long flags;
1286 spin_lock_irqsave(&rq->lock, flags);
1287 rq->hrtick_flags = 0;
1288 __set_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1289 spin_unlock_irqrestore(&rq->lock, flags);
1291 hrtick_clear(rq);
1294 static void hotplug_hrtick_enable(int cpu)
1296 struct rq *rq = cpu_rq(cpu);
1297 unsigned long flags;
1299 spin_lock_irqsave(&rq->lock, flags);
1300 __clear_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1301 spin_unlock_irqrestore(&rq->lock, flags);
1304 static int
1305 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1307 int cpu = (int)(long)hcpu;
1309 switch (action) {
1310 case CPU_UP_CANCELED:
1311 case CPU_UP_CANCELED_FROZEN:
1312 case CPU_DOWN_PREPARE:
1313 case CPU_DOWN_PREPARE_FROZEN:
1314 case CPU_DEAD:
1315 case CPU_DEAD_FROZEN:
1316 hotplug_hrtick_disable(cpu);
1317 return NOTIFY_OK;
1319 case CPU_UP_PREPARE:
1320 case CPU_UP_PREPARE_FROZEN:
1321 case CPU_DOWN_FAILED:
1322 case CPU_DOWN_FAILED_FROZEN:
1323 case CPU_ONLINE:
1324 case CPU_ONLINE_FROZEN:
1325 hotplug_hrtick_enable(cpu);
1326 return NOTIFY_OK;
1329 return NOTIFY_DONE;
1332 static void init_hrtick(void)
1334 hotcpu_notifier(hotplug_hrtick, 0);
1337 static void init_rq_hrtick(struct rq *rq)
1339 rq->hrtick_flags = 0;
1340 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1341 rq->hrtick_timer.function = hrtick;
1342 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1345 void hrtick_resched(void)
1347 struct rq *rq;
1348 unsigned long flags;
1350 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1351 return;
1353 local_irq_save(flags);
1354 rq = cpu_rq(smp_processor_id());
1355 hrtick_set(rq);
1356 local_irq_restore(flags);
1358 #else
1359 static inline void hrtick_clear(struct rq *rq)
1363 static inline void hrtick_set(struct rq *rq)
1367 static inline void init_rq_hrtick(struct rq *rq)
1371 void hrtick_resched(void)
1375 static inline void init_hrtick(void)
1378 #endif
1381 * resched_task - mark a task 'to be rescheduled now'.
1383 * On UP this means the setting of the need_resched flag, on SMP it
1384 * might also involve a cross-CPU call to trigger the scheduler on
1385 * the target CPU.
1387 #ifdef CONFIG_SMP
1389 #ifndef tsk_is_polling
1390 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1391 #endif
1393 static void __resched_task(struct task_struct *p, int tif_bit)
1395 int cpu;
1397 assert_spin_locked(&task_rq(p)->lock);
1399 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1400 return;
1402 set_tsk_thread_flag(p, tif_bit);
1404 cpu = task_cpu(p);
1405 if (cpu == smp_processor_id())
1406 return;
1408 /* NEED_RESCHED must be visible before we test polling */
1409 smp_mb();
1410 if (!tsk_is_polling(p))
1411 smp_send_reschedule(cpu);
1414 static void resched_cpu(int cpu)
1416 struct rq *rq = cpu_rq(cpu);
1417 unsigned long flags;
1419 if (!spin_trylock_irqsave(&rq->lock, flags))
1420 return;
1421 resched_task(cpu_curr(cpu));
1422 spin_unlock_irqrestore(&rq->lock, flags);
1425 #ifdef CONFIG_NO_HZ
1427 * When add_timer_on() enqueues a timer into the timer wheel of an
1428 * idle CPU then this timer might expire before the next timer event
1429 * which is scheduled to wake up that CPU. In case of a completely
1430 * idle system the next event might even be infinite time into the
1431 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1432 * leaves the inner idle loop so the newly added timer is taken into
1433 * account when the CPU goes back to idle and evaluates the timer
1434 * wheel for the next timer event.
1436 void wake_up_idle_cpu(int cpu)
1438 struct rq *rq = cpu_rq(cpu);
1440 if (cpu == smp_processor_id())
1441 return;
1444 * This is safe, as this function is called with the timer
1445 * wheel base lock of (cpu) held. When the CPU is on the way
1446 * to idle and has not yet set rq->curr to idle then it will
1447 * be serialized on the timer wheel base lock and take the new
1448 * timer into account automatically.
1450 if (rq->curr != rq->idle)
1451 return;
1454 * We can set TIF_RESCHED on the idle task of the other CPU
1455 * lockless. The worst case is that the other CPU runs the
1456 * idle task through an additional NOOP schedule()
1458 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1460 /* NEED_RESCHED must be visible before we test polling */
1461 smp_mb();
1462 if (!tsk_is_polling(rq->idle))
1463 smp_send_reschedule(cpu);
1465 #endif
1467 #else
1468 static void __resched_task(struct task_struct *p, int tif_bit)
1470 assert_spin_locked(&task_rq(p)->lock);
1471 set_tsk_thread_flag(p, tif_bit);
1473 #endif
1475 #if BITS_PER_LONG == 32
1476 # define WMULT_CONST (~0UL)
1477 #else
1478 # define WMULT_CONST (1UL << 32)
1479 #endif
1481 #define WMULT_SHIFT 32
1484 * Shift right and round:
1486 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1489 * delta *= weight / lw
1491 static unsigned long
1492 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1493 struct load_weight *lw)
1495 u64 tmp;
1497 if (!lw->inv_weight)
1498 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)/(lw->weight+1);
1500 tmp = (u64)delta_exec * weight;
1502 * Check whether we'd overflow the 64-bit multiplication:
1504 if (unlikely(tmp > WMULT_CONST))
1505 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1506 WMULT_SHIFT/2);
1507 else
1508 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1510 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1513 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1515 lw->weight += inc;
1516 lw->inv_weight = 0;
1519 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1521 lw->weight -= dec;
1522 lw->inv_weight = 0;
1526 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1527 * of tasks with abnormal "nice" values across CPUs the contribution that
1528 * each task makes to its run queue's load is weighted according to its
1529 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1530 * scaled version of the new time slice allocation that they receive on time
1531 * slice expiry etc.
1534 #define WEIGHT_IDLEPRIO 2
1535 #define WMULT_IDLEPRIO (1 << 31)
1538 * Nice levels are multiplicative, with a gentle 10% change for every
1539 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1540 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1541 * that remained on nice 0.
1543 * The "10% effect" is relative and cumulative: from _any_ nice level,
1544 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1545 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1546 * If a task goes up by ~10% and another task goes down by ~10% then
1547 * the relative distance between them is ~25%.)
1549 static const int prio_to_weight[40] = {
1550 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1551 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1552 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1553 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1554 /* 0 */ 1024, 820, 655, 526, 423,
1555 /* 5 */ 335, 272, 215, 172, 137,
1556 /* 10 */ 110, 87, 70, 56, 45,
1557 /* 15 */ 36, 29, 23, 18, 15,
1561 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1563 * In cases where the weight does not change often, we can use the
1564 * precalculated inverse to speed up arithmetics by turning divisions
1565 * into multiplications:
1567 static const u32 prio_to_wmult[40] = {
1568 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1569 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1570 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1571 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1572 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1573 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1574 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1575 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1578 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1581 * runqueue iterator, to support SMP load-balancing between different
1582 * scheduling classes, without having to expose their internal data
1583 * structures to the load-balancing proper:
1585 struct rq_iterator {
1586 void *arg;
1587 struct task_struct *(*start)(void *);
1588 struct task_struct *(*next)(void *);
1591 #ifdef CONFIG_SMP
1592 static unsigned long
1593 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1594 unsigned long max_load_move, struct sched_domain *sd,
1595 enum cpu_idle_type idle, int *all_pinned,
1596 int *this_best_prio, struct rq_iterator *iterator);
1598 static int
1599 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1600 struct sched_domain *sd, enum cpu_idle_type idle,
1601 struct rq_iterator *iterator);
1602 #endif
1604 #ifdef CONFIG_CGROUP_CPUACCT
1605 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1606 #else
1607 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1608 #endif
1610 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1612 update_load_add(&rq->load, load);
1615 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1617 update_load_sub(&rq->load, load);
1620 #ifdef CONFIG_SMP
1621 static unsigned long source_load(int cpu, int type);
1622 static unsigned long target_load(int cpu, int type);
1623 static unsigned long cpu_avg_load_per_task(int cpu);
1624 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1626 #ifdef CONFIG_FAIR_GROUP_SCHED
1629 * Group load balancing.
1631 * We calculate a few balance domain wide aggregate numbers; load and weight.
1632 * Given the pictures below, and assuming each item has equal weight:
1634 * root 1 - thread
1635 * / | \ A - group
1636 * A 1 B
1637 * /|\ / \
1638 * C 2 D 3 4
1639 * | |
1640 * 5 6
1642 * load:
1643 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1644 * which equals 1/9-th of the total load.
1646 * shares:
1647 * The weight of this group on the selected cpus.
1649 * rq_weight:
1650 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1651 * B would get 2.
1653 * task_weight:
1654 * Part of the rq_weight contributed by tasks; all groups except B would
1655 * get 1, B gets 2.
1658 static inline struct aggregate_struct *
1659 aggregate(struct task_group *tg, struct sched_domain *sd)
1661 return &tg->cfs_rq[sd->first_cpu]->aggregate;
1664 typedef void (*aggregate_func)(struct task_group *, struct sched_domain *);
1667 * Iterate the full tree, calling @down when first entering a node and @up when
1668 * leaving it for the final time.
1670 static
1671 void aggregate_walk_tree(aggregate_func down, aggregate_func up,
1672 struct sched_domain *sd)
1674 struct task_group *parent, *child;
1676 rcu_read_lock();
1677 parent = &root_task_group;
1678 down:
1679 (*down)(parent, sd);
1680 list_for_each_entry_rcu(child, &parent->children, siblings) {
1681 parent = child;
1682 goto down;
1685 continue;
1687 (*up)(parent, sd);
1689 child = parent;
1690 parent = parent->parent;
1691 if (parent)
1692 goto up;
1693 rcu_read_unlock();
1697 * Calculate the aggregate runqueue weight.
1699 static
1700 void aggregate_group_weight(struct task_group *tg, struct sched_domain *sd)
1702 unsigned long rq_weight = 0;
1703 unsigned long task_weight = 0;
1704 int i;
1706 for_each_cpu_mask(i, sd->span) {
1707 rq_weight += tg->cfs_rq[i]->load.weight;
1708 task_weight += tg->cfs_rq[i]->task_weight;
1711 aggregate(tg, sd)->rq_weight = rq_weight;
1712 aggregate(tg, sd)->task_weight = task_weight;
1716 * Compute the weight of this group on the given cpus.
1718 static
1719 void aggregate_group_shares(struct task_group *tg, struct sched_domain *sd)
1721 unsigned long shares = 0;
1722 int i;
1724 for_each_cpu_mask(i, sd->span)
1725 shares += tg->cfs_rq[i]->shares;
1727 if ((!shares && aggregate(tg, sd)->rq_weight) || shares > tg->shares)
1728 shares = tg->shares;
1730 aggregate(tg, sd)->shares = shares;
1734 * Compute the load fraction assigned to this group, relies on the aggregate
1735 * weight and this group's parent's load, i.e. top-down.
1737 static
1738 void aggregate_group_load(struct task_group *tg, struct sched_domain *sd)
1740 unsigned long load;
1742 if (!tg->parent) {
1743 int i;
1745 load = 0;
1746 for_each_cpu_mask(i, sd->span)
1747 load += cpu_rq(i)->load.weight;
1749 } else {
1750 load = aggregate(tg->parent, sd)->load;
1753 * shares is our weight in the parent's rq so
1754 * shares/parent->rq_weight gives our fraction of the load
1756 load *= aggregate(tg, sd)->shares;
1757 load /= aggregate(tg->parent, sd)->rq_weight + 1;
1760 aggregate(tg, sd)->load = load;
1763 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1766 * Calculate and set the cpu's group shares.
1768 static void
1769 __update_group_shares_cpu(struct task_group *tg, struct sched_domain *sd,
1770 int tcpu)
1772 int boost = 0;
1773 unsigned long shares;
1774 unsigned long rq_weight;
1776 if (!tg->se[tcpu])
1777 return;
1779 rq_weight = tg->cfs_rq[tcpu]->load.weight;
1782 * If there are currently no tasks on the cpu pretend there is one of
1783 * average load so that when a new task gets to run here it will not
1784 * get delayed by group starvation.
1786 if (!rq_weight) {
1787 boost = 1;
1788 rq_weight = NICE_0_LOAD;
1792 * \Sum shares * rq_weight
1793 * shares = -----------------------
1794 * \Sum rq_weight
1797 shares = aggregate(tg, sd)->shares * rq_weight;
1798 shares /= aggregate(tg, sd)->rq_weight + 1;
1801 * record the actual number of shares, not the boosted amount.
1803 tg->cfs_rq[tcpu]->shares = boost ? 0 : shares;
1805 if (shares < MIN_SHARES)
1806 shares = MIN_SHARES;
1808 __set_se_shares(tg->se[tcpu], shares);
1812 * Re-adjust the weights on the cpu the task came from and on the cpu the
1813 * task went to.
1815 static void
1816 __move_group_shares(struct task_group *tg, struct sched_domain *sd,
1817 int scpu, int dcpu)
1819 unsigned long shares;
1821 shares = tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1823 __update_group_shares_cpu(tg, sd, scpu);
1824 __update_group_shares_cpu(tg, sd, dcpu);
1827 * ensure we never loose shares due to rounding errors in the
1828 * above redistribution.
1830 shares -= tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1831 if (shares)
1832 tg->cfs_rq[dcpu]->shares += shares;
1836 * Because changing a group's shares changes the weight of the super-group
1837 * we need to walk up the tree and change all shares until we hit the root.
1839 static void
1840 move_group_shares(struct task_group *tg, struct sched_domain *sd,
1841 int scpu, int dcpu)
1843 while (tg) {
1844 __move_group_shares(tg, sd, scpu, dcpu);
1845 tg = tg->parent;
1849 static
1850 void aggregate_group_set_shares(struct task_group *tg, struct sched_domain *sd)
1852 unsigned long shares = aggregate(tg, sd)->shares;
1853 int i;
1855 for_each_cpu_mask(i, sd->span) {
1856 struct rq *rq = cpu_rq(i);
1857 unsigned long flags;
1859 spin_lock_irqsave(&rq->lock, flags);
1860 __update_group_shares_cpu(tg, sd, i);
1861 spin_unlock_irqrestore(&rq->lock, flags);
1864 aggregate_group_shares(tg, sd);
1867 * ensure we never loose shares due to rounding errors in the
1868 * above redistribution.
1870 shares -= aggregate(tg, sd)->shares;
1871 if (shares) {
1872 tg->cfs_rq[sd->first_cpu]->shares += shares;
1873 aggregate(tg, sd)->shares += shares;
1878 * Calculate the accumulative weight and recursive load of each task group
1879 * while walking down the tree.
1881 static
1882 void aggregate_get_down(struct task_group *tg, struct sched_domain *sd)
1884 aggregate_group_weight(tg, sd);
1885 aggregate_group_shares(tg, sd);
1886 aggregate_group_load(tg, sd);
1890 * Rebalance the cpu shares while walking back up the tree.
1892 static
1893 void aggregate_get_up(struct task_group *tg, struct sched_domain *sd)
1895 aggregate_group_set_shares(tg, sd);
1898 static DEFINE_PER_CPU(spinlock_t, aggregate_lock);
1900 static void __init init_aggregate(void)
1902 int i;
1904 for_each_possible_cpu(i)
1905 spin_lock_init(&per_cpu(aggregate_lock, i));
1908 static int get_aggregate(struct sched_domain *sd)
1910 if (!spin_trylock(&per_cpu(aggregate_lock, sd->first_cpu)))
1911 return 0;
1913 aggregate_walk_tree(aggregate_get_down, aggregate_get_up, sd);
1914 return 1;
1917 static void put_aggregate(struct sched_domain *sd)
1919 spin_unlock(&per_cpu(aggregate_lock, sd->first_cpu));
1922 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1924 cfs_rq->shares = shares;
1927 #else
1929 static inline void init_aggregate(void)
1933 static inline int get_aggregate(struct sched_domain *sd)
1935 return 0;
1938 static inline void put_aggregate(struct sched_domain *sd)
1941 #endif
1943 #else /* CONFIG_SMP */
1945 #ifdef CONFIG_FAIR_GROUP_SCHED
1946 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1949 #endif
1951 #endif /* CONFIG_SMP */
1953 #include "sched_stats.h"
1954 #include "sched_idletask.c"
1955 #include "sched_fair.c"
1956 #include "sched_rt.c"
1957 #ifdef CONFIG_SCHED_DEBUG
1958 # include "sched_debug.c"
1959 #endif
1961 #define sched_class_highest (&rt_sched_class)
1963 static void inc_nr_running(struct rq *rq)
1965 rq->nr_running++;
1968 static void dec_nr_running(struct rq *rq)
1970 rq->nr_running--;
1973 static void set_load_weight(struct task_struct *p)
1975 if (task_has_rt_policy(p)) {
1976 p->se.load.weight = prio_to_weight[0] * 2;
1977 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1978 return;
1982 * SCHED_IDLE tasks get minimal weight:
1984 if (p->policy == SCHED_IDLE) {
1985 p->se.load.weight = WEIGHT_IDLEPRIO;
1986 p->se.load.inv_weight = WMULT_IDLEPRIO;
1987 return;
1990 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1991 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1994 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1996 sched_info_queued(p);
1997 p->sched_class->enqueue_task(rq, p, wakeup);
1998 p->se.on_rq = 1;
2001 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
2003 p->sched_class->dequeue_task(rq, p, sleep);
2004 p->se.on_rq = 0;
2008 * __normal_prio - return the priority that is based on the static prio
2010 static inline int __normal_prio(struct task_struct *p)
2012 return p->static_prio;
2016 * Calculate the expected normal priority: i.e. priority
2017 * without taking RT-inheritance into account. Might be
2018 * boosted by interactivity modifiers. Changes upon fork,
2019 * setprio syscalls, and whenever the interactivity
2020 * estimator recalculates.
2022 static inline int normal_prio(struct task_struct *p)
2024 int prio;
2026 if (task_has_rt_policy(p))
2027 prio = MAX_RT_PRIO-1 - p->rt_priority;
2028 else
2029 prio = __normal_prio(p);
2030 return prio;
2034 * Calculate the current priority, i.e. the priority
2035 * taken into account by the scheduler. This value might
2036 * be boosted by RT tasks, or might be boosted by
2037 * interactivity modifiers. Will be RT if the task got
2038 * RT-boosted. If not then it returns p->normal_prio.
2040 static int effective_prio(struct task_struct *p)
2042 p->normal_prio = normal_prio(p);
2044 * If we are RT tasks or we were boosted to RT priority,
2045 * keep the priority unchanged. Otherwise, update priority
2046 * to the normal priority:
2048 if (!rt_prio(p->prio))
2049 return p->normal_prio;
2050 return p->prio;
2054 * activate_task - move a task to the runqueue.
2056 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
2058 if (task_contributes_to_load(p))
2059 rq->nr_uninterruptible--;
2061 enqueue_task(rq, p, wakeup);
2062 inc_nr_running(rq);
2066 * deactivate_task - remove a task from the runqueue.
2068 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
2070 if (task_contributes_to_load(p))
2071 rq->nr_uninterruptible++;
2073 dequeue_task(rq, p, sleep);
2074 dec_nr_running(rq);
2078 * task_curr - is this task currently executing on a CPU?
2079 * @p: the task in question.
2081 inline int task_curr(const struct task_struct *p)
2083 return cpu_curr(task_cpu(p)) == p;
2086 /* Used instead of source_load when we know the type == 0 */
2087 unsigned long weighted_cpuload(const int cpu)
2089 return cpu_rq(cpu)->load.weight;
2092 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
2094 set_task_rq(p, cpu);
2095 #ifdef CONFIG_SMP
2097 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
2098 * successfuly executed on another CPU. We must ensure that updates of
2099 * per-task data have been completed by this moment.
2101 smp_wmb();
2102 task_thread_info(p)->cpu = cpu;
2103 #endif
2106 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2107 const struct sched_class *prev_class,
2108 int oldprio, int running)
2110 if (prev_class != p->sched_class) {
2111 if (prev_class->switched_from)
2112 prev_class->switched_from(rq, p, running);
2113 p->sched_class->switched_to(rq, p, running);
2114 } else
2115 p->sched_class->prio_changed(rq, p, oldprio, running);
2118 #ifdef CONFIG_SMP
2121 * Is this task likely cache-hot:
2123 static int
2124 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2126 s64 delta;
2129 * Buddy candidates are cache hot:
2131 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
2132 return 1;
2134 if (p->sched_class != &fair_sched_class)
2135 return 0;
2137 if (sysctl_sched_migration_cost == -1)
2138 return 1;
2139 if (sysctl_sched_migration_cost == 0)
2140 return 0;
2142 delta = now - p->se.exec_start;
2144 return delta < (s64)sysctl_sched_migration_cost;
2148 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2150 int old_cpu = task_cpu(p);
2151 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2152 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2153 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2154 u64 clock_offset;
2156 clock_offset = old_rq->clock - new_rq->clock;
2158 #ifdef CONFIG_SCHEDSTATS
2159 if (p->se.wait_start)
2160 p->se.wait_start -= clock_offset;
2161 if (p->se.sleep_start)
2162 p->se.sleep_start -= clock_offset;
2163 if (p->se.block_start)
2164 p->se.block_start -= clock_offset;
2165 if (old_cpu != new_cpu) {
2166 schedstat_inc(p, se.nr_migrations);
2167 if (task_hot(p, old_rq->clock, NULL))
2168 schedstat_inc(p, se.nr_forced2_migrations);
2170 #endif
2171 p->se.vruntime -= old_cfsrq->min_vruntime -
2172 new_cfsrq->min_vruntime;
2174 __set_task_cpu(p, new_cpu);
2177 struct migration_req {
2178 struct list_head list;
2180 struct task_struct *task;
2181 int dest_cpu;
2183 struct completion done;
2187 * The task's runqueue lock must be held.
2188 * Returns true if you have to wait for migration thread.
2190 static int
2191 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2193 struct rq *rq = task_rq(p);
2196 * If the task is not on a runqueue (and not running), then
2197 * it is sufficient to simply update the task's cpu field.
2199 if (!p->se.on_rq && !task_running(rq, p)) {
2200 set_task_cpu(p, dest_cpu);
2201 return 0;
2204 init_completion(&req->done);
2205 req->task = p;
2206 req->dest_cpu = dest_cpu;
2207 list_add(&req->list, &rq->migration_queue);
2209 return 1;
2213 * wait_task_inactive - wait for a thread to unschedule.
2215 * The caller must ensure that the task *will* unschedule sometime soon,
2216 * else this function might spin for a *long* time. This function can't
2217 * be called with interrupts off, or it may introduce deadlock with
2218 * smp_call_function() if an IPI is sent by the same process we are
2219 * waiting to become inactive.
2221 void wait_task_inactive(struct task_struct *p)
2223 unsigned long flags;
2224 int running, on_rq;
2225 struct rq *rq;
2227 for (;;) {
2229 * We do the initial early heuristics without holding
2230 * any task-queue locks at all. We'll only try to get
2231 * the runqueue lock when things look like they will
2232 * work out!
2234 rq = task_rq(p);
2237 * If the task is actively running on another CPU
2238 * still, just relax and busy-wait without holding
2239 * any locks.
2241 * NOTE! Since we don't hold any locks, it's not
2242 * even sure that "rq" stays as the right runqueue!
2243 * But we don't care, since "task_running()" will
2244 * return false if the runqueue has changed and p
2245 * is actually now running somewhere else!
2247 while (task_running(rq, p))
2248 cpu_relax();
2251 * Ok, time to look more closely! We need the rq
2252 * lock now, to be *sure*. If we're wrong, we'll
2253 * just go back and repeat.
2255 rq = task_rq_lock(p, &flags);
2256 running = task_running(rq, p);
2257 on_rq = p->se.on_rq;
2258 task_rq_unlock(rq, &flags);
2261 * Was it really running after all now that we
2262 * checked with the proper locks actually held?
2264 * Oops. Go back and try again..
2266 if (unlikely(running)) {
2267 cpu_relax();
2268 continue;
2272 * It's not enough that it's not actively running,
2273 * it must be off the runqueue _entirely_, and not
2274 * preempted!
2276 * So if it wa still runnable (but just not actively
2277 * running right now), it's preempted, and we should
2278 * yield - it could be a while.
2280 if (unlikely(on_rq)) {
2281 schedule_timeout_uninterruptible(1);
2282 continue;
2286 * Ahh, all good. It wasn't running, and it wasn't
2287 * runnable, which means that it will never become
2288 * running in the future either. We're all done!
2290 break;
2294 /***
2295 * kick_process - kick a running thread to enter/exit the kernel
2296 * @p: the to-be-kicked thread
2298 * Cause a process which is running on another CPU to enter
2299 * kernel-mode, without any delay. (to get signals handled.)
2301 * NOTE: this function doesnt have to take the runqueue lock,
2302 * because all it wants to ensure is that the remote task enters
2303 * the kernel. If the IPI races and the task has been migrated
2304 * to another CPU then no harm is done and the purpose has been
2305 * achieved as well.
2307 void kick_process(struct task_struct *p)
2309 int cpu;
2311 preempt_disable();
2312 cpu = task_cpu(p);
2313 if ((cpu != smp_processor_id()) && task_curr(p))
2314 smp_send_reschedule(cpu);
2315 preempt_enable();
2319 * Return a low guess at the load of a migration-source cpu weighted
2320 * according to the scheduling class and "nice" value.
2322 * We want to under-estimate the load of migration sources, to
2323 * balance conservatively.
2325 static unsigned long source_load(int cpu, int type)
2327 struct rq *rq = cpu_rq(cpu);
2328 unsigned long total = weighted_cpuload(cpu);
2330 if (type == 0)
2331 return total;
2333 return min(rq->cpu_load[type-1], total);
2337 * Return a high guess at the load of a migration-target cpu weighted
2338 * according to the scheduling class and "nice" value.
2340 static unsigned long target_load(int cpu, int type)
2342 struct rq *rq = cpu_rq(cpu);
2343 unsigned long total = weighted_cpuload(cpu);
2345 if (type == 0)
2346 return total;
2348 return max(rq->cpu_load[type-1], total);
2352 * Return the average load per task on the cpu's run queue
2354 static unsigned long cpu_avg_load_per_task(int cpu)
2356 struct rq *rq = cpu_rq(cpu);
2357 unsigned long total = weighted_cpuload(cpu);
2358 unsigned long n = rq->nr_running;
2360 return n ? total / n : SCHED_LOAD_SCALE;
2364 * find_idlest_group finds and returns the least busy CPU group within the
2365 * domain.
2367 static struct sched_group *
2368 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2370 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2371 unsigned long min_load = ULONG_MAX, this_load = 0;
2372 int load_idx = sd->forkexec_idx;
2373 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2375 do {
2376 unsigned long load, avg_load;
2377 int local_group;
2378 int i;
2380 /* Skip over this group if it has no CPUs allowed */
2381 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2382 continue;
2384 local_group = cpu_isset(this_cpu, group->cpumask);
2386 /* Tally up the load of all CPUs in the group */
2387 avg_load = 0;
2389 for_each_cpu_mask(i, group->cpumask) {
2390 /* Bias balancing toward cpus of our domain */
2391 if (local_group)
2392 load = source_load(i, load_idx);
2393 else
2394 load = target_load(i, load_idx);
2396 avg_load += load;
2399 /* Adjust by relative CPU power of the group */
2400 avg_load = sg_div_cpu_power(group,
2401 avg_load * SCHED_LOAD_SCALE);
2403 if (local_group) {
2404 this_load = avg_load;
2405 this = group;
2406 } else if (avg_load < min_load) {
2407 min_load = avg_load;
2408 idlest = group;
2410 } while (group = group->next, group != sd->groups);
2412 if (!idlest || 100*this_load < imbalance*min_load)
2413 return NULL;
2414 return idlest;
2418 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2420 static int
2421 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2422 cpumask_t *tmp)
2424 unsigned long load, min_load = ULONG_MAX;
2425 int idlest = -1;
2426 int i;
2428 /* Traverse only the allowed CPUs */
2429 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2431 for_each_cpu_mask(i, *tmp) {
2432 load = weighted_cpuload(i);
2434 if (load < min_load || (load == min_load && i == this_cpu)) {
2435 min_load = load;
2436 idlest = i;
2440 return idlest;
2444 * sched_balance_self: balance the current task (running on cpu) in domains
2445 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2446 * SD_BALANCE_EXEC.
2448 * Balance, ie. select the least loaded group.
2450 * Returns the target CPU number, or the same CPU if no balancing is needed.
2452 * preempt must be disabled.
2454 static int sched_balance_self(int cpu, int flag)
2456 struct task_struct *t = current;
2457 struct sched_domain *tmp, *sd = NULL;
2459 for_each_domain(cpu, tmp) {
2461 * If power savings logic is enabled for a domain, stop there.
2463 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2464 break;
2465 if (tmp->flags & flag)
2466 sd = tmp;
2469 while (sd) {
2470 cpumask_t span, tmpmask;
2471 struct sched_group *group;
2472 int new_cpu, weight;
2474 if (!(sd->flags & flag)) {
2475 sd = sd->child;
2476 continue;
2479 span = sd->span;
2480 group = find_idlest_group(sd, t, cpu);
2481 if (!group) {
2482 sd = sd->child;
2483 continue;
2486 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2487 if (new_cpu == -1 || new_cpu == cpu) {
2488 /* Now try balancing at a lower domain level of cpu */
2489 sd = sd->child;
2490 continue;
2493 /* Now try balancing at a lower domain level of new_cpu */
2494 cpu = new_cpu;
2495 sd = NULL;
2496 weight = cpus_weight(span);
2497 for_each_domain(cpu, tmp) {
2498 if (weight <= cpus_weight(tmp->span))
2499 break;
2500 if (tmp->flags & flag)
2501 sd = tmp;
2503 /* while loop will break here if sd == NULL */
2506 return cpu;
2509 #endif /* CONFIG_SMP */
2511 /***
2512 * try_to_wake_up - wake up a thread
2513 * @p: the to-be-woken-up thread
2514 * @state: the mask of task states that can be woken
2515 * @sync: do a synchronous wakeup?
2517 * Put it on the run-queue if it's not already there. The "current"
2518 * thread is always on the run-queue (except when the actual
2519 * re-schedule is in progress), and as such you're allowed to do
2520 * the simpler "current->state = TASK_RUNNING" to mark yourself
2521 * runnable without the overhead of this.
2523 * returns failure only if the task is already active.
2525 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2527 int cpu, orig_cpu, this_cpu, success = 0;
2528 unsigned long flags;
2529 long old_state;
2530 struct rq *rq;
2532 if (!sched_feat(SYNC_WAKEUPS))
2533 sync = 0;
2535 smp_wmb();
2536 rq = task_rq_lock(p, &flags);
2537 old_state = p->state;
2538 if (!(old_state & state))
2539 goto out;
2541 if (p->se.on_rq)
2542 goto out_running;
2544 cpu = task_cpu(p);
2545 orig_cpu = cpu;
2546 this_cpu = smp_processor_id();
2548 #ifdef CONFIG_SMP
2549 if (unlikely(task_running(rq, p)))
2550 goto out_activate;
2552 cpu = p->sched_class->select_task_rq(p, sync);
2553 if (cpu != orig_cpu) {
2554 set_task_cpu(p, cpu);
2555 task_rq_unlock(rq, &flags);
2556 /* might preempt at this point */
2557 rq = task_rq_lock(p, &flags);
2558 old_state = p->state;
2559 if (!(old_state & state))
2560 goto out;
2561 if (p->se.on_rq)
2562 goto out_running;
2564 this_cpu = smp_processor_id();
2565 cpu = task_cpu(p);
2568 #ifdef CONFIG_SCHEDSTATS
2569 schedstat_inc(rq, ttwu_count);
2570 if (cpu == this_cpu)
2571 schedstat_inc(rq, ttwu_local);
2572 else {
2573 struct sched_domain *sd;
2574 for_each_domain(this_cpu, sd) {
2575 if (cpu_isset(cpu, sd->span)) {
2576 schedstat_inc(sd, ttwu_wake_remote);
2577 break;
2581 #endif
2583 out_activate:
2584 #endif /* CONFIG_SMP */
2585 schedstat_inc(p, se.nr_wakeups);
2586 if (sync)
2587 schedstat_inc(p, se.nr_wakeups_sync);
2588 if (orig_cpu != cpu)
2589 schedstat_inc(p, se.nr_wakeups_migrate);
2590 if (cpu == this_cpu)
2591 schedstat_inc(p, se.nr_wakeups_local);
2592 else
2593 schedstat_inc(p, se.nr_wakeups_remote);
2594 update_rq_clock(rq);
2595 activate_task(rq, p, 1);
2596 success = 1;
2598 out_running:
2599 check_preempt_curr(rq, p);
2601 p->state = TASK_RUNNING;
2602 #ifdef CONFIG_SMP
2603 if (p->sched_class->task_wake_up)
2604 p->sched_class->task_wake_up(rq, p);
2605 #endif
2606 out:
2607 task_rq_unlock(rq, &flags);
2609 return success;
2612 int wake_up_process(struct task_struct *p)
2614 return try_to_wake_up(p, TASK_ALL, 0);
2616 EXPORT_SYMBOL(wake_up_process);
2618 int wake_up_state(struct task_struct *p, unsigned int state)
2620 return try_to_wake_up(p, state, 0);
2624 * Perform scheduler related setup for a newly forked process p.
2625 * p is forked by current.
2627 * __sched_fork() is basic setup used by init_idle() too:
2629 static void __sched_fork(struct task_struct *p)
2631 p->se.exec_start = 0;
2632 p->se.sum_exec_runtime = 0;
2633 p->se.prev_sum_exec_runtime = 0;
2634 p->se.last_wakeup = 0;
2635 p->se.avg_overlap = 0;
2637 #ifdef CONFIG_SCHEDSTATS
2638 p->se.wait_start = 0;
2639 p->se.sum_sleep_runtime = 0;
2640 p->se.sleep_start = 0;
2641 p->se.block_start = 0;
2642 p->se.sleep_max = 0;
2643 p->se.block_max = 0;
2644 p->se.exec_max = 0;
2645 p->se.slice_max = 0;
2646 p->se.wait_max = 0;
2647 #endif
2649 INIT_LIST_HEAD(&p->rt.run_list);
2650 p->se.on_rq = 0;
2651 INIT_LIST_HEAD(&p->se.group_node);
2653 #ifdef CONFIG_PREEMPT_NOTIFIERS
2654 INIT_HLIST_HEAD(&p->preempt_notifiers);
2655 #endif
2658 * We mark the process as running here, but have not actually
2659 * inserted it onto the runqueue yet. This guarantees that
2660 * nobody will actually run it, and a signal or other external
2661 * event cannot wake it up and insert it on the runqueue either.
2663 p->state = TASK_RUNNING;
2667 * fork()/clone()-time setup:
2669 void sched_fork(struct task_struct *p, int clone_flags)
2671 int cpu = get_cpu();
2673 __sched_fork(p);
2675 #ifdef CONFIG_SMP
2676 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2677 #endif
2678 set_task_cpu(p, cpu);
2681 * Make sure we do not leak PI boosting priority to the child:
2683 p->prio = current->normal_prio;
2684 if (!rt_prio(p->prio))
2685 p->sched_class = &fair_sched_class;
2687 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2688 if (likely(sched_info_on()))
2689 memset(&p->sched_info, 0, sizeof(p->sched_info));
2690 #endif
2691 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2692 p->oncpu = 0;
2693 #endif
2694 #ifdef CONFIG_PREEMPT
2695 /* Want to start with kernel preemption disabled. */
2696 task_thread_info(p)->preempt_count = 1;
2697 #endif
2698 put_cpu();
2702 * wake_up_new_task - wake up a newly created task for the first time.
2704 * This function will do some initial scheduler statistics housekeeping
2705 * that must be done for every newly created context, then puts the task
2706 * on the runqueue and wakes it.
2708 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2710 unsigned long flags;
2711 struct rq *rq;
2713 rq = task_rq_lock(p, &flags);
2714 BUG_ON(p->state != TASK_RUNNING);
2715 update_rq_clock(rq);
2717 p->prio = effective_prio(p);
2719 if (!p->sched_class->task_new || !current->se.on_rq) {
2720 activate_task(rq, p, 0);
2721 } else {
2723 * Let the scheduling class do new task startup
2724 * management (if any):
2726 p->sched_class->task_new(rq, p);
2727 inc_nr_running(rq);
2729 check_preempt_curr(rq, p);
2730 #ifdef CONFIG_SMP
2731 if (p->sched_class->task_wake_up)
2732 p->sched_class->task_wake_up(rq, p);
2733 #endif
2734 task_rq_unlock(rq, &flags);
2737 #ifdef CONFIG_PREEMPT_NOTIFIERS
2740 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2741 * @notifier: notifier struct to register
2743 void preempt_notifier_register(struct preempt_notifier *notifier)
2745 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2747 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2750 * preempt_notifier_unregister - no longer interested in preemption notifications
2751 * @notifier: notifier struct to unregister
2753 * This is safe to call from within a preemption notifier.
2755 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2757 hlist_del(&notifier->link);
2759 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2761 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2763 struct preempt_notifier *notifier;
2764 struct hlist_node *node;
2766 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2767 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2770 static void
2771 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2772 struct task_struct *next)
2774 struct preempt_notifier *notifier;
2775 struct hlist_node *node;
2777 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2778 notifier->ops->sched_out(notifier, next);
2781 #else
2783 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2787 static void
2788 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2789 struct task_struct *next)
2793 #endif
2796 * prepare_task_switch - prepare to switch tasks
2797 * @rq: the runqueue preparing to switch
2798 * @prev: the current task that is being switched out
2799 * @next: the task we are going to switch to.
2801 * This is called with the rq lock held and interrupts off. It must
2802 * be paired with a subsequent finish_task_switch after the context
2803 * switch.
2805 * prepare_task_switch sets up locking and calls architecture specific
2806 * hooks.
2808 static inline void
2809 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2810 struct task_struct *next)
2812 fire_sched_out_preempt_notifiers(prev, next);
2813 prepare_lock_switch(rq, next);
2814 prepare_arch_switch(next);
2818 * finish_task_switch - clean up after a task-switch
2819 * @rq: runqueue associated with task-switch
2820 * @prev: the thread we just switched away from.
2822 * finish_task_switch must be called after the context switch, paired
2823 * with a prepare_task_switch call before the context switch.
2824 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2825 * and do any other architecture-specific cleanup actions.
2827 * Note that we may have delayed dropping an mm in context_switch(). If
2828 * so, we finish that here outside of the runqueue lock. (Doing it
2829 * with the lock held can cause deadlocks; see schedule() for
2830 * details.)
2832 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2833 __releases(rq->lock)
2835 struct mm_struct *mm = rq->prev_mm;
2836 long prev_state;
2838 rq->prev_mm = NULL;
2841 * A task struct has one reference for the use as "current".
2842 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2843 * schedule one last time. The schedule call will never return, and
2844 * the scheduled task must drop that reference.
2845 * The test for TASK_DEAD must occur while the runqueue locks are
2846 * still held, otherwise prev could be scheduled on another cpu, die
2847 * there before we look at prev->state, and then the reference would
2848 * be dropped twice.
2849 * Manfred Spraul <manfred@colorfullife.com>
2851 prev_state = prev->state;
2852 finish_arch_switch(prev);
2853 finish_lock_switch(rq, prev);
2854 #ifdef CONFIG_SMP
2855 if (current->sched_class->post_schedule)
2856 current->sched_class->post_schedule(rq);
2857 #endif
2859 fire_sched_in_preempt_notifiers(current);
2860 if (mm)
2861 mmdrop(mm);
2862 if (unlikely(prev_state == TASK_DEAD)) {
2864 * Remove function-return probe instances associated with this
2865 * task and put them back on the free list.
2867 kprobe_flush_task(prev);
2868 put_task_struct(prev);
2873 * schedule_tail - first thing a freshly forked thread must call.
2874 * @prev: the thread we just switched away from.
2876 asmlinkage void schedule_tail(struct task_struct *prev)
2877 __releases(rq->lock)
2879 struct rq *rq = this_rq();
2881 finish_task_switch(rq, prev);
2882 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2883 /* In this case, finish_task_switch does not reenable preemption */
2884 preempt_enable();
2885 #endif
2886 if (current->set_child_tid)
2887 put_user(task_pid_vnr(current), current->set_child_tid);
2891 * context_switch - switch to the new MM and the new
2892 * thread's register state.
2894 static inline void
2895 context_switch(struct rq *rq, struct task_struct *prev,
2896 struct task_struct *next)
2898 struct mm_struct *mm, *oldmm;
2900 prepare_task_switch(rq, prev, next);
2901 mm = next->mm;
2902 oldmm = prev->active_mm;
2904 * For paravirt, this is coupled with an exit in switch_to to
2905 * combine the page table reload and the switch backend into
2906 * one hypercall.
2908 arch_enter_lazy_cpu_mode();
2910 if (unlikely(!mm)) {
2911 next->active_mm = oldmm;
2912 atomic_inc(&oldmm->mm_count);
2913 enter_lazy_tlb(oldmm, next);
2914 } else
2915 switch_mm(oldmm, mm, next);
2917 if (unlikely(!prev->mm)) {
2918 prev->active_mm = NULL;
2919 rq->prev_mm = oldmm;
2922 * Since the runqueue lock will be released by the next
2923 * task (which is an invalid locking op but in the case
2924 * of the scheduler it's an obvious special-case), so we
2925 * do an early lockdep release here:
2927 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2928 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2929 #endif
2931 /* Here we just switch the register state and the stack. */
2932 switch_to(prev, next, prev);
2934 barrier();
2936 * this_rq must be evaluated again because prev may have moved
2937 * CPUs since it called schedule(), thus the 'rq' on its stack
2938 * frame will be invalid.
2940 finish_task_switch(this_rq(), prev);
2944 * nr_running, nr_uninterruptible and nr_context_switches:
2946 * externally visible scheduler statistics: current number of runnable
2947 * threads, current number of uninterruptible-sleeping threads, total
2948 * number of context switches performed since bootup.
2950 unsigned long nr_running(void)
2952 unsigned long i, sum = 0;
2954 for_each_online_cpu(i)
2955 sum += cpu_rq(i)->nr_running;
2957 return sum;
2960 unsigned long nr_uninterruptible(void)
2962 unsigned long i, sum = 0;
2964 for_each_possible_cpu(i)
2965 sum += cpu_rq(i)->nr_uninterruptible;
2968 * Since we read the counters lockless, it might be slightly
2969 * inaccurate. Do not allow it to go below zero though:
2971 if (unlikely((long)sum < 0))
2972 sum = 0;
2974 return sum;
2977 unsigned long long nr_context_switches(void)
2979 int i;
2980 unsigned long long sum = 0;
2982 for_each_possible_cpu(i)
2983 sum += cpu_rq(i)->nr_switches;
2985 return sum;
2988 unsigned long nr_iowait(void)
2990 unsigned long i, sum = 0;
2992 for_each_possible_cpu(i)
2993 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2995 return sum;
2998 unsigned long nr_active(void)
3000 unsigned long i, running = 0, uninterruptible = 0;
3002 for_each_online_cpu(i) {
3003 running += cpu_rq(i)->nr_running;
3004 uninterruptible += cpu_rq(i)->nr_uninterruptible;
3007 if (unlikely((long)uninterruptible < 0))
3008 uninterruptible = 0;
3010 return running + uninterruptible;
3014 * Update rq->cpu_load[] statistics. This function is usually called every
3015 * scheduler tick (TICK_NSEC).
3017 static void update_cpu_load(struct rq *this_rq)
3019 unsigned long this_load = this_rq->load.weight;
3020 int i, scale;
3022 this_rq->nr_load_updates++;
3024 /* Update our load: */
3025 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3026 unsigned long old_load, new_load;
3028 /* scale is effectively 1 << i now, and >> i divides by scale */
3030 old_load = this_rq->cpu_load[i];
3031 new_load = this_load;
3033 * Round up the averaging division if load is increasing. This
3034 * prevents us from getting stuck on 9 if the load is 10, for
3035 * example.
3037 if (new_load > old_load)
3038 new_load += scale-1;
3039 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3043 #ifdef CONFIG_SMP
3046 * double_rq_lock - safely lock two runqueues
3048 * Note this does not disable interrupts like task_rq_lock,
3049 * you need to do so manually before calling.
3051 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3052 __acquires(rq1->lock)
3053 __acquires(rq2->lock)
3055 BUG_ON(!irqs_disabled());
3056 if (rq1 == rq2) {
3057 spin_lock(&rq1->lock);
3058 __acquire(rq2->lock); /* Fake it out ;) */
3059 } else {
3060 if (rq1 < rq2) {
3061 spin_lock(&rq1->lock);
3062 spin_lock(&rq2->lock);
3063 } else {
3064 spin_lock(&rq2->lock);
3065 spin_lock(&rq1->lock);
3068 update_rq_clock(rq1);
3069 update_rq_clock(rq2);
3073 * double_rq_unlock - safely unlock two runqueues
3075 * Note this does not restore interrupts like task_rq_unlock,
3076 * you need to do so manually after calling.
3078 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3079 __releases(rq1->lock)
3080 __releases(rq2->lock)
3082 spin_unlock(&rq1->lock);
3083 if (rq1 != rq2)
3084 spin_unlock(&rq2->lock);
3085 else
3086 __release(rq2->lock);
3090 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
3092 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
3093 __releases(this_rq->lock)
3094 __acquires(busiest->lock)
3095 __acquires(this_rq->lock)
3097 int ret = 0;
3099 if (unlikely(!irqs_disabled())) {
3100 /* printk() doesn't work good under rq->lock */
3101 spin_unlock(&this_rq->lock);
3102 BUG_ON(1);
3104 if (unlikely(!spin_trylock(&busiest->lock))) {
3105 if (busiest < this_rq) {
3106 spin_unlock(&this_rq->lock);
3107 spin_lock(&busiest->lock);
3108 spin_lock(&this_rq->lock);
3109 ret = 1;
3110 } else
3111 spin_lock(&busiest->lock);
3113 return ret;
3117 * If dest_cpu is allowed for this process, migrate the task to it.
3118 * This is accomplished by forcing the cpu_allowed mask to only
3119 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3120 * the cpu_allowed mask is restored.
3122 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3124 struct migration_req req;
3125 unsigned long flags;
3126 struct rq *rq;
3128 rq = task_rq_lock(p, &flags);
3129 if (!cpu_isset(dest_cpu, p->cpus_allowed)
3130 || unlikely(cpu_is_offline(dest_cpu)))
3131 goto out;
3133 /* force the process onto the specified CPU */
3134 if (migrate_task(p, dest_cpu, &req)) {
3135 /* Need to wait for migration thread (might exit: take ref). */
3136 struct task_struct *mt = rq->migration_thread;
3138 get_task_struct(mt);
3139 task_rq_unlock(rq, &flags);
3140 wake_up_process(mt);
3141 put_task_struct(mt);
3142 wait_for_completion(&req.done);
3144 return;
3146 out:
3147 task_rq_unlock(rq, &flags);
3151 * sched_exec - execve() is a valuable balancing opportunity, because at
3152 * this point the task has the smallest effective memory and cache footprint.
3154 void sched_exec(void)
3156 int new_cpu, this_cpu = get_cpu();
3157 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3158 put_cpu();
3159 if (new_cpu != this_cpu)
3160 sched_migrate_task(current, new_cpu);
3164 * pull_task - move a task from a remote runqueue to the local runqueue.
3165 * Both runqueues must be locked.
3167 static void pull_task(struct rq *src_rq, struct task_struct *p,
3168 struct rq *this_rq, int this_cpu)
3170 deactivate_task(src_rq, p, 0);
3171 set_task_cpu(p, this_cpu);
3172 activate_task(this_rq, p, 0);
3174 * Note that idle threads have a prio of MAX_PRIO, for this test
3175 * to be always true for them.
3177 check_preempt_curr(this_rq, p);
3181 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3183 static
3184 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3185 struct sched_domain *sd, enum cpu_idle_type idle,
3186 int *all_pinned)
3189 * We do not migrate tasks that are:
3190 * 1) running (obviously), or
3191 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3192 * 3) are cache-hot on their current CPU.
3194 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
3195 schedstat_inc(p, se.nr_failed_migrations_affine);
3196 return 0;
3198 *all_pinned = 0;
3200 if (task_running(rq, p)) {
3201 schedstat_inc(p, se.nr_failed_migrations_running);
3202 return 0;
3206 * Aggressive migration if:
3207 * 1) task is cache cold, or
3208 * 2) too many balance attempts have failed.
3211 if (!task_hot(p, rq->clock, sd) ||
3212 sd->nr_balance_failed > sd->cache_nice_tries) {
3213 #ifdef CONFIG_SCHEDSTATS
3214 if (task_hot(p, rq->clock, sd)) {
3215 schedstat_inc(sd, lb_hot_gained[idle]);
3216 schedstat_inc(p, se.nr_forced_migrations);
3218 #endif
3219 return 1;
3222 if (task_hot(p, rq->clock, sd)) {
3223 schedstat_inc(p, se.nr_failed_migrations_hot);
3224 return 0;
3226 return 1;
3229 static unsigned long
3230 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3231 unsigned long max_load_move, struct sched_domain *sd,
3232 enum cpu_idle_type idle, int *all_pinned,
3233 int *this_best_prio, struct rq_iterator *iterator)
3235 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
3236 struct task_struct *p;
3237 long rem_load_move = max_load_move;
3239 if (max_load_move == 0)
3240 goto out;
3242 pinned = 1;
3245 * Start the load-balancing iterator:
3247 p = iterator->start(iterator->arg);
3248 next:
3249 if (!p || loops++ > sysctl_sched_nr_migrate)
3250 goto out;
3252 * To help distribute high priority tasks across CPUs we don't
3253 * skip a task if it will be the highest priority task (i.e. smallest
3254 * prio value) on its new queue regardless of its load weight
3256 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
3257 SCHED_LOAD_SCALE_FUZZ;
3258 if ((skip_for_load && p->prio >= *this_best_prio) ||
3259 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3260 p = iterator->next(iterator->arg);
3261 goto next;
3264 pull_task(busiest, p, this_rq, this_cpu);
3265 pulled++;
3266 rem_load_move -= p->se.load.weight;
3269 * We only want to steal up to the prescribed amount of weighted load.
3271 if (rem_load_move > 0) {
3272 if (p->prio < *this_best_prio)
3273 *this_best_prio = p->prio;
3274 p = iterator->next(iterator->arg);
3275 goto next;
3277 out:
3279 * Right now, this is one of only two places pull_task() is called,
3280 * so we can safely collect pull_task() stats here rather than
3281 * inside pull_task().
3283 schedstat_add(sd, lb_gained[idle], pulled);
3285 if (all_pinned)
3286 *all_pinned = pinned;
3288 return max_load_move - rem_load_move;
3292 * move_tasks tries to move up to max_load_move weighted load from busiest to
3293 * this_rq, as part of a balancing operation within domain "sd".
3294 * Returns 1 if successful and 0 otherwise.
3296 * Called with both runqueues locked.
3298 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3299 unsigned long max_load_move,
3300 struct sched_domain *sd, enum cpu_idle_type idle,
3301 int *all_pinned)
3303 const struct sched_class *class = sched_class_highest;
3304 unsigned long total_load_moved = 0;
3305 int this_best_prio = this_rq->curr->prio;
3307 do {
3308 total_load_moved +=
3309 class->load_balance(this_rq, this_cpu, busiest,
3310 max_load_move - total_load_moved,
3311 sd, idle, all_pinned, &this_best_prio);
3312 class = class->next;
3313 } while (class && max_load_move > total_load_moved);
3315 return total_load_moved > 0;
3318 static int
3319 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3320 struct sched_domain *sd, enum cpu_idle_type idle,
3321 struct rq_iterator *iterator)
3323 struct task_struct *p = iterator->start(iterator->arg);
3324 int pinned = 0;
3326 while (p) {
3327 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3328 pull_task(busiest, p, this_rq, this_cpu);
3330 * Right now, this is only the second place pull_task()
3331 * is called, so we can safely collect pull_task()
3332 * stats here rather than inside pull_task().
3334 schedstat_inc(sd, lb_gained[idle]);
3336 return 1;
3338 p = iterator->next(iterator->arg);
3341 return 0;
3345 * move_one_task tries to move exactly one task from busiest to this_rq, as
3346 * part of active balancing operations within "domain".
3347 * Returns 1 if successful and 0 otherwise.
3349 * Called with both runqueues locked.
3351 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3352 struct sched_domain *sd, enum cpu_idle_type idle)
3354 const struct sched_class *class;
3356 for (class = sched_class_highest; class; class = class->next)
3357 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3358 return 1;
3360 return 0;
3364 * find_busiest_group finds and returns the busiest CPU group within the
3365 * domain. It calculates and returns the amount of weighted load which
3366 * should be moved to restore balance via the imbalance parameter.
3368 static struct sched_group *
3369 find_busiest_group(struct sched_domain *sd, int this_cpu,
3370 unsigned long *imbalance, enum cpu_idle_type idle,
3371 int *sd_idle, const cpumask_t *cpus, int *balance)
3373 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3374 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3375 unsigned long max_pull;
3376 unsigned long busiest_load_per_task, busiest_nr_running;
3377 unsigned long this_load_per_task, this_nr_running;
3378 int load_idx, group_imb = 0;
3379 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3380 int power_savings_balance = 1;
3381 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3382 unsigned long min_nr_running = ULONG_MAX;
3383 struct sched_group *group_min = NULL, *group_leader = NULL;
3384 #endif
3386 max_load = this_load = total_load = total_pwr = 0;
3387 busiest_load_per_task = busiest_nr_running = 0;
3388 this_load_per_task = this_nr_running = 0;
3389 if (idle == CPU_NOT_IDLE)
3390 load_idx = sd->busy_idx;
3391 else if (idle == CPU_NEWLY_IDLE)
3392 load_idx = sd->newidle_idx;
3393 else
3394 load_idx = sd->idle_idx;
3396 do {
3397 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3398 int local_group;
3399 int i;
3400 int __group_imb = 0;
3401 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3402 unsigned long sum_nr_running, sum_weighted_load;
3404 local_group = cpu_isset(this_cpu, group->cpumask);
3406 if (local_group)
3407 balance_cpu = first_cpu(group->cpumask);
3409 /* Tally up the load of all CPUs in the group */
3410 sum_weighted_load = sum_nr_running = avg_load = 0;
3411 max_cpu_load = 0;
3412 min_cpu_load = ~0UL;
3414 for_each_cpu_mask(i, group->cpumask) {
3415 struct rq *rq;
3417 if (!cpu_isset(i, *cpus))
3418 continue;
3420 rq = cpu_rq(i);
3422 if (*sd_idle && rq->nr_running)
3423 *sd_idle = 0;
3425 /* Bias balancing toward cpus of our domain */
3426 if (local_group) {
3427 if (idle_cpu(i) && !first_idle_cpu) {
3428 first_idle_cpu = 1;
3429 balance_cpu = i;
3432 load = target_load(i, load_idx);
3433 } else {
3434 load = source_load(i, load_idx);
3435 if (load > max_cpu_load)
3436 max_cpu_load = load;
3437 if (min_cpu_load > load)
3438 min_cpu_load = load;
3441 avg_load += load;
3442 sum_nr_running += rq->nr_running;
3443 sum_weighted_load += weighted_cpuload(i);
3447 * First idle cpu or the first cpu(busiest) in this sched group
3448 * is eligible for doing load balancing at this and above
3449 * domains. In the newly idle case, we will allow all the cpu's
3450 * to do the newly idle load balance.
3452 if (idle != CPU_NEWLY_IDLE && local_group &&
3453 balance_cpu != this_cpu && balance) {
3454 *balance = 0;
3455 goto ret;
3458 total_load += avg_load;
3459 total_pwr += group->__cpu_power;
3461 /* Adjust by relative CPU power of the group */
3462 avg_load = sg_div_cpu_power(group,
3463 avg_load * SCHED_LOAD_SCALE);
3465 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
3466 __group_imb = 1;
3468 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3470 if (local_group) {
3471 this_load = avg_load;
3472 this = group;
3473 this_nr_running = sum_nr_running;
3474 this_load_per_task = sum_weighted_load;
3475 } else if (avg_load > max_load &&
3476 (sum_nr_running > group_capacity || __group_imb)) {
3477 max_load = avg_load;
3478 busiest = group;
3479 busiest_nr_running = sum_nr_running;
3480 busiest_load_per_task = sum_weighted_load;
3481 group_imb = __group_imb;
3484 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3486 * Busy processors will not participate in power savings
3487 * balance.
3489 if (idle == CPU_NOT_IDLE ||
3490 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3491 goto group_next;
3494 * If the local group is idle or completely loaded
3495 * no need to do power savings balance at this domain
3497 if (local_group && (this_nr_running >= group_capacity ||
3498 !this_nr_running))
3499 power_savings_balance = 0;
3502 * If a group is already running at full capacity or idle,
3503 * don't include that group in power savings calculations
3505 if (!power_savings_balance || sum_nr_running >= group_capacity
3506 || !sum_nr_running)
3507 goto group_next;
3510 * Calculate the group which has the least non-idle load.
3511 * This is the group from where we need to pick up the load
3512 * for saving power
3514 if ((sum_nr_running < min_nr_running) ||
3515 (sum_nr_running == min_nr_running &&
3516 first_cpu(group->cpumask) <
3517 first_cpu(group_min->cpumask))) {
3518 group_min = group;
3519 min_nr_running = sum_nr_running;
3520 min_load_per_task = sum_weighted_load /
3521 sum_nr_running;
3525 * Calculate the group which is almost near its
3526 * capacity but still has some space to pick up some load
3527 * from other group and save more power
3529 if (sum_nr_running <= group_capacity - 1) {
3530 if (sum_nr_running > leader_nr_running ||
3531 (sum_nr_running == leader_nr_running &&
3532 first_cpu(group->cpumask) >
3533 first_cpu(group_leader->cpumask))) {
3534 group_leader = group;
3535 leader_nr_running = sum_nr_running;
3538 group_next:
3539 #endif
3540 group = group->next;
3541 } while (group != sd->groups);
3543 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3544 goto out_balanced;
3546 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3548 if (this_load >= avg_load ||
3549 100*max_load <= sd->imbalance_pct*this_load)
3550 goto out_balanced;
3552 busiest_load_per_task /= busiest_nr_running;
3553 if (group_imb)
3554 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3557 * We're trying to get all the cpus to the average_load, so we don't
3558 * want to push ourselves above the average load, nor do we wish to
3559 * reduce the max loaded cpu below the average load, as either of these
3560 * actions would just result in more rebalancing later, and ping-pong
3561 * tasks around. Thus we look for the minimum possible imbalance.
3562 * Negative imbalances (*we* are more loaded than anyone else) will
3563 * be counted as no imbalance for these purposes -- we can't fix that
3564 * by pulling tasks to us. Be careful of negative numbers as they'll
3565 * appear as very large values with unsigned longs.
3567 if (max_load <= busiest_load_per_task)
3568 goto out_balanced;
3571 * In the presence of smp nice balancing, certain scenarios can have
3572 * max load less than avg load(as we skip the groups at or below
3573 * its cpu_power, while calculating max_load..)
3575 if (max_load < avg_load) {
3576 *imbalance = 0;
3577 goto small_imbalance;
3580 /* Don't want to pull so many tasks that a group would go idle */
3581 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3583 /* How much load to actually move to equalise the imbalance */
3584 *imbalance = min(max_pull * busiest->__cpu_power,
3585 (avg_load - this_load) * this->__cpu_power)
3586 / SCHED_LOAD_SCALE;
3589 * if *imbalance is less than the average load per runnable task
3590 * there is no gaurantee that any tasks will be moved so we'll have
3591 * a think about bumping its value to force at least one task to be
3592 * moved
3594 if (*imbalance < busiest_load_per_task) {
3595 unsigned long tmp, pwr_now, pwr_move;
3596 unsigned int imbn;
3598 small_imbalance:
3599 pwr_move = pwr_now = 0;
3600 imbn = 2;
3601 if (this_nr_running) {
3602 this_load_per_task /= this_nr_running;
3603 if (busiest_load_per_task > this_load_per_task)
3604 imbn = 1;
3605 } else
3606 this_load_per_task = SCHED_LOAD_SCALE;
3608 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3609 busiest_load_per_task * imbn) {
3610 *imbalance = busiest_load_per_task;
3611 return busiest;
3615 * OK, we don't have enough imbalance to justify moving tasks,
3616 * however we may be able to increase total CPU power used by
3617 * moving them.
3620 pwr_now += busiest->__cpu_power *
3621 min(busiest_load_per_task, max_load);
3622 pwr_now += this->__cpu_power *
3623 min(this_load_per_task, this_load);
3624 pwr_now /= SCHED_LOAD_SCALE;
3626 /* Amount of load we'd subtract */
3627 tmp = sg_div_cpu_power(busiest,
3628 busiest_load_per_task * SCHED_LOAD_SCALE);
3629 if (max_load > tmp)
3630 pwr_move += busiest->__cpu_power *
3631 min(busiest_load_per_task, max_load - tmp);
3633 /* Amount of load we'd add */
3634 if (max_load * busiest->__cpu_power <
3635 busiest_load_per_task * SCHED_LOAD_SCALE)
3636 tmp = sg_div_cpu_power(this,
3637 max_load * busiest->__cpu_power);
3638 else
3639 tmp = sg_div_cpu_power(this,
3640 busiest_load_per_task * SCHED_LOAD_SCALE);
3641 pwr_move += this->__cpu_power *
3642 min(this_load_per_task, this_load + tmp);
3643 pwr_move /= SCHED_LOAD_SCALE;
3645 /* Move if we gain throughput */
3646 if (pwr_move > pwr_now)
3647 *imbalance = busiest_load_per_task;
3650 return busiest;
3652 out_balanced:
3653 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3654 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3655 goto ret;
3657 if (this == group_leader && group_leader != group_min) {
3658 *imbalance = min_load_per_task;
3659 return group_min;
3661 #endif
3662 ret:
3663 *imbalance = 0;
3664 return NULL;
3668 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3670 static struct rq *
3671 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3672 unsigned long imbalance, const cpumask_t *cpus)
3674 struct rq *busiest = NULL, *rq;
3675 unsigned long max_load = 0;
3676 int i;
3678 for_each_cpu_mask(i, group->cpumask) {
3679 unsigned long wl;
3681 if (!cpu_isset(i, *cpus))
3682 continue;
3684 rq = cpu_rq(i);
3685 wl = weighted_cpuload(i);
3687 if (rq->nr_running == 1 && wl > imbalance)
3688 continue;
3690 if (wl > max_load) {
3691 max_load = wl;
3692 busiest = rq;
3696 return busiest;
3700 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3701 * so long as it is large enough.
3703 #define MAX_PINNED_INTERVAL 512
3706 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3707 * tasks if there is an imbalance.
3709 static int load_balance(int this_cpu, struct rq *this_rq,
3710 struct sched_domain *sd, enum cpu_idle_type idle,
3711 int *balance, cpumask_t *cpus)
3713 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3714 struct sched_group *group;
3715 unsigned long imbalance;
3716 struct rq *busiest;
3717 unsigned long flags;
3718 int unlock_aggregate;
3720 cpus_setall(*cpus);
3722 unlock_aggregate = get_aggregate(sd);
3725 * When power savings policy is enabled for the parent domain, idle
3726 * sibling can pick up load irrespective of busy siblings. In this case,
3727 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3728 * portraying it as CPU_NOT_IDLE.
3730 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3731 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3732 sd_idle = 1;
3734 schedstat_inc(sd, lb_count[idle]);
3736 redo:
3737 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3738 cpus, balance);
3740 if (*balance == 0)
3741 goto out_balanced;
3743 if (!group) {
3744 schedstat_inc(sd, lb_nobusyg[idle]);
3745 goto out_balanced;
3748 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3749 if (!busiest) {
3750 schedstat_inc(sd, lb_nobusyq[idle]);
3751 goto out_balanced;
3754 BUG_ON(busiest == this_rq);
3756 schedstat_add(sd, lb_imbalance[idle], imbalance);
3758 ld_moved = 0;
3759 if (busiest->nr_running > 1) {
3761 * Attempt to move tasks. If find_busiest_group has found
3762 * an imbalance but busiest->nr_running <= 1, the group is
3763 * still unbalanced. ld_moved simply stays zero, so it is
3764 * correctly treated as an imbalance.
3766 local_irq_save(flags);
3767 double_rq_lock(this_rq, busiest);
3768 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3769 imbalance, sd, idle, &all_pinned);
3770 double_rq_unlock(this_rq, busiest);
3771 local_irq_restore(flags);
3774 * some other cpu did the load balance for us.
3776 if (ld_moved && this_cpu != smp_processor_id())
3777 resched_cpu(this_cpu);
3779 /* All tasks on this runqueue were pinned by CPU affinity */
3780 if (unlikely(all_pinned)) {
3781 cpu_clear(cpu_of(busiest), *cpus);
3782 if (!cpus_empty(*cpus))
3783 goto redo;
3784 goto out_balanced;
3788 if (!ld_moved) {
3789 schedstat_inc(sd, lb_failed[idle]);
3790 sd->nr_balance_failed++;
3792 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3794 spin_lock_irqsave(&busiest->lock, flags);
3796 /* don't kick the migration_thread, if the curr
3797 * task on busiest cpu can't be moved to this_cpu
3799 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3800 spin_unlock_irqrestore(&busiest->lock, flags);
3801 all_pinned = 1;
3802 goto out_one_pinned;
3805 if (!busiest->active_balance) {
3806 busiest->active_balance = 1;
3807 busiest->push_cpu = this_cpu;
3808 active_balance = 1;
3810 spin_unlock_irqrestore(&busiest->lock, flags);
3811 if (active_balance)
3812 wake_up_process(busiest->migration_thread);
3815 * We've kicked active balancing, reset the failure
3816 * counter.
3818 sd->nr_balance_failed = sd->cache_nice_tries+1;
3820 } else
3821 sd->nr_balance_failed = 0;
3823 if (likely(!active_balance)) {
3824 /* We were unbalanced, so reset the balancing interval */
3825 sd->balance_interval = sd->min_interval;
3826 } else {
3828 * If we've begun active balancing, start to back off. This
3829 * case may not be covered by the all_pinned logic if there
3830 * is only 1 task on the busy runqueue (because we don't call
3831 * move_tasks).
3833 if (sd->balance_interval < sd->max_interval)
3834 sd->balance_interval *= 2;
3837 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3838 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3839 ld_moved = -1;
3841 goto out;
3843 out_balanced:
3844 schedstat_inc(sd, lb_balanced[idle]);
3846 sd->nr_balance_failed = 0;
3848 out_one_pinned:
3849 /* tune up the balancing interval */
3850 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3851 (sd->balance_interval < sd->max_interval))
3852 sd->balance_interval *= 2;
3854 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3855 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3856 ld_moved = -1;
3857 else
3858 ld_moved = 0;
3859 out:
3860 if (unlock_aggregate)
3861 put_aggregate(sd);
3862 return ld_moved;
3866 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3867 * tasks if there is an imbalance.
3869 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3870 * this_rq is locked.
3872 static int
3873 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3874 cpumask_t *cpus)
3876 struct sched_group *group;
3877 struct rq *busiest = NULL;
3878 unsigned long imbalance;
3879 int ld_moved = 0;
3880 int sd_idle = 0;
3881 int all_pinned = 0;
3883 cpus_setall(*cpus);
3886 * When power savings policy is enabled for the parent domain, idle
3887 * sibling can pick up load irrespective of busy siblings. In this case,
3888 * let the state of idle sibling percolate up as IDLE, instead of
3889 * portraying it as CPU_NOT_IDLE.
3891 if (sd->flags & SD_SHARE_CPUPOWER &&
3892 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3893 sd_idle = 1;
3895 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3896 redo:
3897 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3898 &sd_idle, cpus, NULL);
3899 if (!group) {
3900 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3901 goto out_balanced;
3904 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3905 if (!busiest) {
3906 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3907 goto out_balanced;
3910 BUG_ON(busiest == this_rq);
3912 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3914 ld_moved = 0;
3915 if (busiest->nr_running > 1) {
3916 /* Attempt to move tasks */
3917 double_lock_balance(this_rq, busiest);
3918 /* this_rq->clock is already updated */
3919 update_rq_clock(busiest);
3920 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3921 imbalance, sd, CPU_NEWLY_IDLE,
3922 &all_pinned);
3923 spin_unlock(&busiest->lock);
3925 if (unlikely(all_pinned)) {
3926 cpu_clear(cpu_of(busiest), *cpus);
3927 if (!cpus_empty(*cpus))
3928 goto redo;
3932 if (!ld_moved) {
3933 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3934 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3935 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3936 return -1;
3937 } else
3938 sd->nr_balance_failed = 0;
3940 return ld_moved;
3942 out_balanced:
3943 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3944 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3945 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3946 return -1;
3947 sd->nr_balance_failed = 0;
3949 return 0;
3953 * idle_balance is called by schedule() if this_cpu is about to become
3954 * idle. Attempts to pull tasks from other CPUs.
3956 static void idle_balance(int this_cpu, struct rq *this_rq)
3958 struct sched_domain *sd;
3959 int pulled_task = -1;
3960 unsigned long next_balance = jiffies + HZ;
3961 cpumask_t tmpmask;
3963 for_each_domain(this_cpu, sd) {
3964 unsigned long interval;
3966 if (!(sd->flags & SD_LOAD_BALANCE))
3967 continue;
3969 if (sd->flags & SD_BALANCE_NEWIDLE)
3970 /* If we've pulled tasks over stop searching: */
3971 pulled_task = load_balance_newidle(this_cpu, this_rq,
3972 sd, &tmpmask);
3974 interval = msecs_to_jiffies(sd->balance_interval);
3975 if (time_after(next_balance, sd->last_balance + interval))
3976 next_balance = sd->last_balance + interval;
3977 if (pulled_task)
3978 break;
3980 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3982 * We are going idle. next_balance may be set based on
3983 * a busy processor. So reset next_balance.
3985 this_rq->next_balance = next_balance;
3990 * active_load_balance is run by migration threads. It pushes running tasks
3991 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3992 * running on each physical CPU where possible, and avoids physical /
3993 * logical imbalances.
3995 * Called with busiest_rq locked.
3997 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3999 int target_cpu = busiest_rq->push_cpu;
4000 struct sched_domain *sd;
4001 struct rq *target_rq;
4003 /* Is there any task to move? */
4004 if (busiest_rq->nr_running <= 1)
4005 return;
4007 target_rq = cpu_rq(target_cpu);
4010 * This condition is "impossible", if it occurs
4011 * we need to fix it. Originally reported by
4012 * Bjorn Helgaas on a 128-cpu setup.
4014 BUG_ON(busiest_rq == target_rq);
4016 /* move a task from busiest_rq to target_rq */
4017 double_lock_balance(busiest_rq, target_rq);
4018 update_rq_clock(busiest_rq);
4019 update_rq_clock(target_rq);
4021 /* Search for an sd spanning us and the target CPU. */
4022 for_each_domain(target_cpu, sd) {
4023 if ((sd->flags & SD_LOAD_BALANCE) &&
4024 cpu_isset(busiest_cpu, sd->span))
4025 break;
4028 if (likely(sd)) {
4029 schedstat_inc(sd, alb_count);
4031 if (move_one_task(target_rq, target_cpu, busiest_rq,
4032 sd, CPU_IDLE))
4033 schedstat_inc(sd, alb_pushed);
4034 else
4035 schedstat_inc(sd, alb_failed);
4037 spin_unlock(&target_rq->lock);
4040 #ifdef CONFIG_NO_HZ
4041 static struct {
4042 atomic_t load_balancer;
4043 cpumask_t cpu_mask;
4044 } nohz ____cacheline_aligned = {
4045 .load_balancer = ATOMIC_INIT(-1),
4046 .cpu_mask = CPU_MASK_NONE,
4050 * This routine will try to nominate the ilb (idle load balancing)
4051 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4052 * load balancing on behalf of all those cpus. If all the cpus in the system
4053 * go into this tickless mode, then there will be no ilb owner (as there is
4054 * no need for one) and all the cpus will sleep till the next wakeup event
4055 * arrives...
4057 * For the ilb owner, tick is not stopped. And this tick will be used
4058 * for idle load balancing. ilb owner will still be part of
4059 * nohz.cpu_mask..
4061 * While stopping the tick, this cpu will become the ilb owner if there
4062 * is no other owner. And will be the owner till that cpu becomes busy
4063 * or if all cpus in the system stop their ticks at which point
4064 * there is no need for ilb owner.
4066 * When the ilb owner becomes busy, it nominates another owner, during the
4067 * next busy scheduler_tick()
4069 int select_nohz_load_balancer(int stop_tick)
4071 int cpu = smp_processor_id();
4073 if (stop_tick) {
4074 cpu_set(cpu, nohz.cpu_mask);
4075 cpu_rq(cpu)->in_nohz_recently = 1;
4078 * If we are going offline and still the leader, give up!
4080 if (cpu_is_offline(cpu) &&
4081 atomic_read(&nohz.load_balancer) == cpu) {
4082 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4083 BUG();
4084 return 0;
4087 /* time for ilb owner also to sleep */
4088 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4089 if (atomic_read(&nohz.load_balancer) == cpu)
4090 atomic_set(&nohz.load_balancer, -1);
4091 return 0;
4094 if (atomic_read(&nohz.load_balancer) == -1) {
4095 /* make me the ilb owner */
4096 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4097 return 1;
4098 } else if (atomic_read(&nohz.load_balancer) == cpu)
4099 return 1;
4100 } else {
4101 if (!cpu_isset(cpu, nohz.cpu_mask))
4102 return 0;
4104 cpu_clear(cpu, nohz.cpu_mask);
4106 if (atomic_read(&nohz.load_balancer) == cpu)
4107 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4108 BUG();
4110 return 0;
4112 #endif
4114 static DEFINE_SPINLOCK(balancing);
4117 * It checks each scheduling domain to see if it is due to be balanced,
4118 * and initiates a balancing operation if so.
4120 * Balancing parameters are set up in arch_init_sched_domains.
4122 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4124 int balance = 1;
4125 struct rq *rq = cpu_rq(cpu);
4126 unsigned long interval;
4127 struct sched_domain *sd;
4128 /* Earliest time when we have to do rebalance again */
4129 unsigned long next_balance = jiffies + 60*HZ;
4130 int update_next_balance = 0;
4131 cpumask_t tmp;
4133 for_each_domain(cpu, sd) {
4134 if (!(sd->flags & SD_LOAD_BALANCE))
4135 continue;
4137 interval = sd->balance_interval;
4138 if (idle != CPU_IDLE)
4139 interval *= sd->busy_factor;
4141 /* scale ms to jiffies */
4142 interval = msecs_to_jiffies(interval);
4143 if (unlikely(!interval))
4144 interval = 1;
4145 if (interval > HZ*NR_CPUS/10)
4146 interval = HZ*NR_CPUS/10;
4149 if (sd->flags & SD_SERIALIZE) {
4150 if (!spin_trylock(&balancing))
4151 goto out;
4154 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4155 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
4157 * We've pulled tasks over so either we're no
4158 * longer idle, or one of our SMT siblings is
4159 * not idle.
4161 idle = CPU_NOT_IDLE;
4163 sd->last_balance = jiffies;
4165 if (sd->flags & SD_SERIALIZE)
4166 spin_unlock(&balancing);
4167 out:
4168 if (time_after(next_balance, sd->last_balance + interval)) {
4169 next_balance = sd->last_balance + interval;
4170 update_next_balance = 1;
4174 * Stop the load balance at this level. There is another
4175 * CPU in our sched group which is doing load balancing more
4176 * actively.
4178 if (!balance)
4179 break;
4183 * next_balance will be updated only when there is a need.
4184 * When the cpu is attached to null domain for ex, it will not be
4185 * updated.
4187 if (likely(update_next_balance))
4188 rq->next_balance = next_balance;
4192 * run_rebalance_domains is triggered when needed from the scheduler tick.
4193 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4194 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4196 static void run_rebalance_domains(struct softirq_action *h)
4198 int this_cpu = smp_processor_id();
4199 struct rq *this_rq = cpu_rq(this_cpu);
4200 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4201 CPU_IDLE : CPU_NOT_IDLE;
4203 rebalance_domains(this_cpu, idle);
4205 #ifdef CONFIG_NO_HZ
4207 * If this cpu is the owner for idle load balancing, then do the
4208 * balancing on behalf of the other idle cpus whose ticks are
4209 * stopped.
4211 if (this_rq->idle_at_tick &&
4212 atomic_read(&nohz.load_balancer) == this_cpu) {
4213 cpumask_t cpus = nohz.cpu_mask;
4214 struct rq *rq;
4215 int balance_cpu;
4217 cpu_clear(this_cpu, cpus);
4218 for_each_cpu_mask(balance_cpu, cpus) {
4220 * If this cpu gets work to do, stop the load balancing
4221 * work being done for other cpus. Next load
4222 * balancing owner will pick it up.
4224 if (need_resched())
4225 break;
4227 rebalance_domains(balance_cpu, CPU_IDLE);
4229 rq = cpu_rq(balance_cpu);
4230 if (time_after(this_rq->next_balance, rq->next_balance))
4231 this_rq->next_balance = rq->next_balance;
4234 #endif
4238 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4240 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4241 * idle load balancing owner or decide to stop the periodic load balancing,
4242 * if the whole system is idle.
4244 static inline void trigger_load_balance(struct rq *rq, int cpu)
4246 #ifdef CONFIG_NO_HZ
4248 * If we were in the nohz mode recently and busy at the current
4249 * scheduler tick, then check if we need to nominate new idle
4250 * load balancer.
4252 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4253 rq->in_nohz_recently = 0;
4255 if (atomic_read(&nohz.load_balancer) == cpu) {
4256 cpu_clear(cpu, nohz.cpu_mask);
4257 atomic_set(&nohz.load_balancer, -1);
4260 if (atomic_read(&nohz.load_balancer) == -1) {
4262 * simple selection for now: Nominate the
4263 * first cpu in the nohz list to be the next
4264 * ilb owner.
4266 * TBD: Traverse the sched domains and nominate
4267 * the nearest cpu in the nohz.cpu_mask.
4269 int ilb = first_cpu(nohz.cpu_mask);
4271 if (ilb < nr_cpu_ids)
4272 resched_cpu(ilb);
4277 * If this cpu is idle and doing idle load balancing for all the
4278 * cpus with ticks stopped, is it time for that to stop?
4280 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4281 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4282 resched_cpu(cpu);
4283 return;
4287 * If this cpu is idle and the idle load balancing is done by
4288 * someone else, then no need raise the SCHED_SOFTIRQ
4290 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4291 cpu_isset(cpu, nohz.cpu_mask))
4292 return;
4293 #endif
4294 if (time_after_eq(jiffies, rq->next_balance))
4295 raise_softirq(SCHED_SOFTIRQ);
4298 #else /* CONFIG_SMP */
4301 * on UP we do not need to balance between CPUs:
4303 static inline void idle_balance(int cpu, struct rq *rq)
4307 #endif
4309 DEFINE_PER_CPU(struct kernel_stat, kstat);
4311 EXPORT_PER_CPU_SYMBOL(kstat);
4314 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4315 * that have not yet been banked in case the task is currently running.
4317 unsigned long long task_sched_runtime(struct task_struct *p)
4319 unsigned long flags;
4320 u64 ns, delta_exec;
4321 struct rq *rq;
4323 rq = task_rq_lock(p, &flags);
4324 ns = p->se.sum_exec_runtime;
4325 if (task_current(rq, p)) {
4326 update_rq_clock(rq);
4327 delta_exec = rq->clock - p->se.exec_start;
4328 if ((s64)delta_exec > 0)
4329 ns += delta_exec;
4331 task_rq_unlock(rq, &flags);
4333 return ns;
4337 * Account user cpu time to a process.
4338 * @p: the process that the cpu time gets accounted to
4339 * @cputime: the cpu time spent in user space since the last update
4341 void account_user_time(struct task_struct *p, cputime_t cputime)
4343 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4344 cputime64_t tmp;
4346 p->utime = cputime_add(p->utime, cputime);
4348 /* Add user time to cpustat. */
4349 tmp = cputime_to_cputime64(cputime);
4350 if (TASK_NICE(p) > 0)
4351 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4352 else
4353 cpustat->user = cputime64_add(cpustat->user, tmp);
4357 * Account guest cpu time to a process.
4358 * @p: the process that the cpu time gets accounted to
4359 * @cputime: the cpu time spent in virtual machine since the last update
4361 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4363 cputime64_t tmp;
4364 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4366 tmp = cputime_to_cputime64(cputime);
4368 p->utime = cputime_add(p->utime, cputime);
4369 p->gtime = cputime_add(p->gtime, cputime);
4371 cpustat->user = cputime64_add(cpustat->user, tmp);
4372 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4376 * Account scaled user cpu time to a process.
4377 * @p: the process that the cpu time gets accounted to
4378 * @cputime: the cpu time spent in user space since the last update
4380 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4382 p->utimescaled = cputime_add(p->utimescaled, cputime);
4386 * Account system cpu time to a process.
4387 * @p: the process that the cpu time gets accounted to
4388 * @hardirq_offset: the offset to subtract from hardirq_count()
4389 * @cputime: the cpu time spent in kernel space since the last update
4391 void account_system_time(struct task_struct *p, int hardirq_offset,
4392 cputime_t cputime)
4394 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4395 struct rq *rq = this_rq();
4396 cputime64_t tmp;
4398 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4399 account_guest_time(p, cputime);
4400 return;
4403 p->stime = cputime_add(p->stime, cputime);
4405 /* Add system time to cpustat. */
4406 tmp = cputime_to_cputime64(cputime);
4407 if (hardirq_count() - hardirq_offset)
4408 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4409 else if (softirq_count())
4410 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4411 else if (p != rq->idle)
4412 cpustat->system = cputime64_add(cpustat->system, tmp);
4413 else if (atomic_read(&rq->nr_iowait) > 0)
4414 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4415 else
4416 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4417 /* Account for system time used */
4418 acct_update_integrals(p);
4422 * Account scaled system cpu time to a process.
4423 * @p: the process that the cpu time gets accounted to
4424 * @hardirq_offset: the offset to subtract from hardirq_count()
4425 * @cputime: the cpu time spent in kernel space since the last update
4427 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4429 p->stimescaled = cputime_add(p->stimescaled, cputime);
4433 * Account for involuntary wait time.
4434 * @p: the process from which the cpu time has been stolen
4435 * @steal: the cpu time spent in involuntary wait
4437 void account_steal_time(struct task_struct *p, cputime_t steal)
4439 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4440 cputime64_t tmp = cputime_to_cputime64(steal);
4441 struct rq *rq = this_rq();
4443 if (p == rq->idle) {
4444 p->stime = cputime_add(p->stime, steal);
4445 if (atomic_read(&rq->nr_iowait) > 0)
4446 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4447 else
4448 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4449 } else
4450 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4454 * This function gets called by the timer code, with HZ frequency.
4455 * We call it with interrupts disabled.
4457 * It also gets called by the fork code, when changing the parent's
4458 * timeslices.
4460 void scheduler_tick(void)
4462 int cpu = smp_processor_id();
4463 struct rq *rq = cpu_rq(cpu);
4464 struct task_struct *curr = rq->curr;
4465 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
4467 spin_lock(&rq->lock);
4468 __update_rq_clock(rq);
4470 * Let rq->clock advance by at least TICK_NSEC:
4472 if (unlikely(rq->clock < next_tick)) {
4473 rq->clock = next_tick;
4474 rq->clock_underflows++;
4476 rq->tick_timestamp = rq->clock;
4477 update_last_tick_seen(rq);
4478 update_cpu_load(rq);
4479 curr->sched_class->task_tick(rq, curr, 0);
4480 spin_unlock(&rq->lock);
4482 #ifdef CONFIG_SMP
4483 rq->idle_at_tick = idle_cpu(cpu);
4484 trigger_load_balance(rq, cpu);
4485 #endif
4488 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4490 void __kprobes add_preempt_count(int val)
4493 * Underflow?
4495 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4496 return;
4497 preempt_count() += val;
4499 * Spinlock count overflowing soon?
4501 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4502 PREEMPT_MASK - 10);
4504 EXPORT_SYMBOL(add_preempt_count);
4506 void __kprobes sub_preempt_count(int val)
4509 * Underflow?
4511 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4512 return;
4514 * Is the spinlock portion underflowing?
4516 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4517 !(preempt_count() & PREEMPT_MASK)))
4518 return;
4520 preempt_count() -= val;
4522 EXPORT_SYMBOL(sub_preempt_count);
4524 #endif
4527 * Print scheduling while atomic bug:
4529 static noinline void __schedule_bug(struct task_struct *prev)
4531 struct pt_regs *regs = get_irq_regs();
4533 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4534 prev->comm, prev->pid, preempt_count());
4536 debug_show_held_locks(prev);
4537 if (irqs_disabled())
4538 print_irqtrace_events(prev);
4540 if (regs)
4541 show_regs(regs);
4542 else
4543 dump_stack();
4547 * Various schedule()-time debugging checks and statistics:
4549 static inline void schedule_debug(struct task_struct *prev)
4552 * Test if we are atomic. Since do_exit() needs to call into
4553 * schedule() atomically, we ignore that path for now.
4554 * Otherwise, whine if we are scheduling when we should not be.
4556 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4557 __schedule_bug(prev);
4559 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4561 schedstat_inc(this_rq(), sched_count);
4562 #ifdef CONFIG_SCHEDSTATS
4563 if (unlikely(prev->lock_depth >= 0)) {
4564 schedstat_inc(this_rq(), bkl_count);
4565 schedstat_inc(prev, sched_info.bkl_count);
4567 #endif
4571 * Pick up the highest-prio task:
4573 static inline struct task_struct *
4574 pick_next_task(struct rq *rq, struct task_struct *prev)
4576 const struct sched_class *class;
4577 struct task_struct *p;
4580 * Optimization: we know that if all tasks are in
4581 * the fair class we can call that function directly:
4583 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4584 p = fair_sched_class.pick_next_task(rq);
4585 if (likely(p))
4586 return p;
4589 class = sched_class_highest;
4590 for ( ; ; ) {
4591 p = class->pick_next_task(rq);
4592 if (p)
4593 return p;
4595 * Will never be NULL as the idle class always
4596 * returns a non-NULL p:
4598 class = class->next;
4603 * schedule() is the main scheduler function.
4605 asmlinkage void __sched schedule(void)
4607 struct task_struct *prev, *next;
4608 unsigned long *switch_count;
4609 struct rq *rq;
4610 int cpu;
4612 need_resched:
4613 preempt_disable();
4614 cpu = smp_processor_id();
4615 rq = cpu_rq(cpu);
4616 rcu_qsctr_inc(cpu);
4617 prev = rq->curr;
4618 switch_count = &prev->nivcsw;
4620 release_kernel_lock(prev);
4621 need_resched_nonpreemptible:
4623 schedule_debug(prev);
4625 hrtick_clear(rq);
4628 * Do the rq-clock update outside the rq lock:
4630 local_irq_disable();
4631 __update_rq_clock(rq);
4632 spin_lock(&rq->lock);
4633 clear_tsk_need_resched(prev);
4635 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4636 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4637 signal_pending(prev))) {
4638 prev->state = TASK_RUNNING;
4639 } else {
4640 deactivate_task(rq, prev, 1);
4642 switch_count = &prev->nvcsw;
4645 #ifdef CONFIG_SMP
4646 if (prev->sched_class->pre_schedule)
4647 prev->sched_class->pre_schedule(rq, prev);
4648 #endif
4650 if (unlikely(!rq->nr_running))
4651 idle_balance(cpu, rq);
4653 prev->sched_class->put_prev_task(rq, prev);
4654 next = pick_next_task(rq, prev);
4656 if (likely(prev != next)) {
4657 sched_info_switch(prev, next);
4659 rq->nr_switches++;
4660 rq->curr = next;
4661 ++*switch_count;
4663 context_switch(rq, prev, next); /* unlocks the rq */
4665 * the context switch might have flipped the stack from under
4666 * us, hence refresh the local variables.
4668 cpu = smp_processor_id();
4669 rq = cpu_rq(cpu);
4670 } else
4671 spin_unlock_irq(&rq->lock);
4673 hrtick_set(rq);
4675 if (unlikely(reacquire_kernel_lock(current) < 0))
4676 goto need_resched_nonpreemptible;
4678 preempt_enable_no_resched();
4679 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4680 goto need_resched;
4682 EXPORT_SYMBOL(schedule);
4684 #ifdef CONFIG_PREEMPT
4686 * this is the entry point to schedule() from in-kernel preemption
4687 * off of preempt_enable. Kernel preemptions off return from interrupt
4688 * occur there and call schedule directly.
4690 asmlinkage void __sched preempt_schedule(void)
4692 struct thread_info *ti = current_thread_info();
4693 struct task_struct *task = current;
4694 int saved_lock_depth;
4697 * If there is a non-zero preempt_count or interrupts are disabled,
4698 * we do not want to preempt the current task. Just return..
4700 if (likely(ti->preempt_count || irqs_disabled()))
4701 return;
4703 do {
4704 add_preempt_count(PREEMPT_ACTIVE);
4707 * We keep the big kernel semaphore locked, but we
4708 * clear ->lock_depth so that schedule() doesnt
4709 * auto-release the semaphore:
4711 saved_lock_depth = task->lock_depth;
4712 task->lock_depth = -1;
4713 schedule();
4714 task->lock_depth = saved_lock_depth;
4715 sub_preempt_count(PREEMPT_ACTIVE);
4718 * Check again in case we missed a preemption opportunity
4719 * between schedule and now.
4721 barrier();
4722 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4724 EXPORT_SYMBOL(preempt_schedule);
4727 * this is the entry point to schedule() from kernel preemption
4728 * off of irq context.
4729 * Note, that this is called and return with irqs disabled. This will
4730 * protect us against recursive calling from irq.
4732 asmlinkage void __sched preempt_schedule_irq(void)
4734 struct thread_info *ti = current_thread_info();
4735 struct task_struct *task = current;
4736 int saved_lock_depth;
4738 /* Catch callers which need to be fixed */
4739 BUG_ON(ti->preempt_count || !irqs_disabled());
4741 do {
4742 add_preempt_count(PREEMPT_ACTIVE);
4745 * We keep the big kernel semaphore locked, but we
4746 * clear ->lock_depth so that schedule() doesnt
4747 * auto-release the semaphore:
4749 saved_lock_depth = task->lock_depth;
4750 task->lock_depth = -1;
4751 local_irq_enable();
4752 schedule();
4753 local_irq_disable();
4754 task->lock_depth = saved_lock_depth;
4755 sub_preempt_count(PREEMPT_ACTIVE);
4758 * Check again in case we missed a preemption opportunity
4759 * between schedule and now.
4761 barrier();
4762 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4765 #endif /* CONFIG_PREEMPT */
4767 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4768 void *key)
4770 return try_to_wake_up(curr->private, mode, sync);
4772 EXPORT_SYMBOL(default_wake_function);
4775 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4776 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4777 * number) then we wake all the non-exclusive tasks and one exclusive task.
4779 * There are circumstances in which we can try to wake a task which has already
4780 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4781 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4783 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4784 int nr_exclusive, int sync, void *key)
4786 wait_queue_t *curr, *next;
4788 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4789 unsigned flags = curr->flags;
4791 if (curr->func(curr, mode, sync, key) &&
4792 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4793 break;
4798 * __wake_up - wake up threads blocked on a waitqueue.
4799 * @q: the waitqueue
4800 * @mode: which threads
4801 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4802 * @key: is directly passed to the wakeup function
4804 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4805 int nr_exclusive, void *key)
4807 unsigned long flags;
4809 spin_lock_irqsave(&q->lock, flags);
4810 __wake_up_common(q, mode, nr_exclusive, 0, key);
4811 spin_unlock_irqrestore(&q->lock, flags);
4813 EXPORT_SYMBOL(__wake_up);
4816 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4818 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4820 __wake_up_common(q, mode, 1, 0, NULL);
4824 * __wake_up_sync - wake up threads blocked on a waitqueue.
4825 * @q: the waitqueue
4826 * @mode: which threads
4827 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4829 * The sync wakeup differs that the waker knows that it will schedule
4830 * away soon, so while the target thread will be woken up, it will not
4831 * be migrated to another CPU - ie. the two threads are 'synchronized'
4832 * with each other. This can prevent needless bouncing between CPUs.
4834 * On UP it can prevent extra preemption.
4836 void
4837 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4839 unsigned long flags;
4840 int sync = 1;
4842 if (unlikely(!q))
4843 return;
4845 if (unlikely(!nr_exclusive))
4846 sync = 0;
4848 spin_lock_irqsave(&q->lock, flags);
4849 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4850 spin_unlock_irqrestore(&q->lock, flags);
4852 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4854 void complete(struct completion *x)
4856 unsigned long flags;
4858 spin_lock_irqsave(&x->wait.lock, flags);
4859 x->done++;
4860 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4861 spin_unlock_irqrestore(&x->wait.lock, flags);
4863 EXPORT_SYMBOL(complete);
4865 void complete_all(struct completion *x)
4867 unsigned long flags;
4869 spin_lock_irqsave(&x->wait.lock, flags);
4870 x->done += UINT_MAX/2;
4871 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4872 spin_unlock_irqrestore(&x->wait.lock, flags);
4874 EXPORT_SYMBOL(complete_all);
4876 static inline long __sched
4877 do_wait_for_common(struct completion *x, long timeout, int state)
4879 if (!x->done) {
4880 DECLARE_WAITQUEUE(wait, current);
4882 wait.flags |= WQ_FLAG_EXCLUSIVE;
4883 __add_wait_queue_tail(&x->wait, &wait);
4884 do {
4885 if ((state == TASK_INTERRUPTIBLE &&
4886 signal_pending(current)) ||
4887 (state == TASK_KILLABLE &&
4888 fatal_signal_pending(current))) {
4889 __remove_wait_queue(&x->wait, &wait);
4890 return -ERESTARTSYS;
4892 __set_current_state(state);
4893 spin_unlock_irq(&x->wait.lock);
4894 timeout = schedule_timeout(timeout);
4895 spin_lock_irq(&x->wait.lock);
4896 if (!timeout) {
4897 __remove_wait_queue(&x->wait, &wait);
4898 return timeout;
4900 } while (!x->done);
4901 __remove_wait_queue(&x->wait, &wait);
4903 x->done--;
4904 return timeout;
4907 static long __sched
4908 wait_for_common(struct completion *x, long timeout, int state)
4910 might_sleep();
4912 spin_lock_irq(&x->wait.lock);
4913 timeout = do_wait_for_common(x, timeout, state);
4914 spin_unlock_irq(&x->wait.lock);
4915 return timeout;
4918 void __sched wait_for_completion(struct completion *x)
4920 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4922 EXPORT_SYMBOL(wait_for_completion);
4924 unsigned long __sched
4925 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4927 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4929 EXPORT_SYMBOL(wait_for_completion_timeout);
4931 int __sched wait_for_completion_interruptible(struct completion *x)
4933 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4934 if (t == -ERESTARTSYS)
4935 return t;
4936 return 0;
4938 EXPORT_SYMBOL(wait_for_completion_interruptible);
4940 unsigned long __sched
4941 wait_for_completion_interruptible_timeout(struct completion *x,
4942 unsigned long timeout)
4944 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4946 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4948 int __sched wait_for_completion_killable(struct completion *x)
4950 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4951 if (t == -ERESTARTSYS)
4952 return t;
4953 return 0;
4955 EXPORT_SYMBOL(wait_for_completion_killable);
4957 static long __sched
4958 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4960 unsigned long flags;
4961 wait_queue_t wait;
4963 init_waitqueue_entry(&wait, current);
4965 __set_current_state(state);
4967 spin_lock_irqsave(&q->lock, flags);
4968 __add_wait_queue(q, &wait);
4969 spin_unlock(&q->lock);
4970 timeout = schedule_timeout(timeout);
4971 spin_lock_irq(&q->lock);
4972 __remove_wait_queue(q, &wait);
4973 spin_unlock_irqrestore(&q->lock, flags);
4975 return timeout;
4978 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4980 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4982 EXPORT_SYMBOL(interruptible_sleep_on);
4984 long __sched
4985 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4987 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4989 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4991 void __sched sleep_on(wait_queue_head_t *q)
4993 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4995 EXPORT_SYMBOL(sleep_on);
4997 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4999 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5001 EXPORT_SYMBOL(sleep_on_timeout);
5003 #ifdef CONFIG_RT_MUTEXES
5006 * rt_mutex_setprio - set the current priority of a task
5007 * @p: task
5008 * @prio: prio value (kernel-internal form)
5010 * This function changes the 'effective' priority of a task. It does
5011 * not touch ->normal_prio like __setscheduler().
5013 * Used by the rt_mutex code to implement priority inheritance logic.
5015 void rt_mutex_setprio(struct task_struct *p, int prio)
5017 unsigned long flags;
5018 int oldprio, on_rq, running;
5019 struct rq *rq;
5020 const struct sched_class *prev_class = p->sched_class;
5022 BUG_ON(prio < 0 || prio > MAX_PRIO);
5024 rq = task_rq_lock(p, &flags);
5025 update_rq_clock(rq);
5027 oldprio = p->prio;
5028 on_rq = p->se.on_rq;
5029 running = task_current(rq, p);
5030 if (on_rq)
5031 dequeue_task(rq, p, 0);
5032 if (running)
5033 p->sched_class->put_prev_task(rq, p);
5035 if (rt_prio(prio))
5036 p->sched_class = &rt_sched_class;
5037 else
5038 p->sched_class = &fair_sched_class;
5040 p->prio = prio;
5042 if (running)
5043 p->sched_class->set_curr_task(rq);
5044 if (on_rq) {
5045 enqueue_task(rq, p, 0);
5047 check_class_changed(rq, p, prev_class, oldprio, running);
5049 task_rq_unlock(rq, &flags);
5052 #endif
5054 void set_user_nice(struct task_struct *p, long nice)
5056 int old_prio, delta, on_rq;
5057 unsigned long flags;
5058 struct rq *rq;
5060 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
5061 return;
5063 * We have to be careful, if called from sys_setpriority(),
5064 * the task might be in the middle of scheduling on another CPU.
5066 rq = task_rq_lock(p, &flags);
5067 update_rq_clock(rq);
5069 * The RT priorities are set via sched_setscheduler(), but we still
5070 * allow the 'normal' nice value to be set - but as expected
5071 * it wont have any effect on scheduling until the task is
5072 * SCHED_FIFO/SCHED_RR:
5074 if (task_has_rt_policy(p)) {
5075 p->static_prio = NICE_TO_PRIO(nice);
5076 goto out_unlock;
5078 on_rq = p->se.on_rq;
5079 if (on_rq)
5080 dequeue_task(rq, p, 0);
5082 p->static_prio = NICE_TO_PRIO(nice);
5083 set_load_weight(p);
5084 old_prio = p->prio;
5085 p->prio = effective_prio(p);
5086 delta = p->prio - old_prio;
5088 if (on_rq) {
5089 enqueue_task(rq, p, 0);
5091 * If the task increased its priority or is running and
5092 * lowered its priority, then reschedule its CPU:
5094 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5095 resched_task(rq->curr);
5097 out_unlock:
5098 task_rq_unlock(rq, &flags);
5100 EXPORT_SYMBOL(set_user_nice);
5103 * can_nice - check if a task can reduce its nice value
5104 * @p: task
5105 * @nice: nice value
5107 int can_nice(const struct task_struct *p, const int nice)
5109 /* convert nice value [19,-20] to rlimit style value [1,40] */
5110 int nice_rlim = 20 - nice;
5112 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5113 capable(CAP_SYS_NICE));
5116 #ifdef __ARCH_WANT_SYS_NICE
5119 * sys_nice - change the priority of the current process.
5120 * @increment: priority increment
5122 * sys_setpriority is a more generic, but much slower function that
5123 * does similar things.
5125 asmlinkage long sys_nice(int increment)
5127 long nice, retval;
5130 * Setpriority might change our priority at the same moment.
5131 * We don't have to worry. Conceptually one call occurs first
5132 * and we have a single winner.
5134 if (increment < -40)
5135 increment = -40;
5136 if (increment > 40)
5137 increment = 40;
5139 nice = PRIO_TO_NICE(current->static_prio) + increment;
5140 if (nice < -20)
5141 nice = -20;
5142 if (nice > 19)
5143 nice = 19;
5145 if (increment < 0 && !can_nice(current, nice))
5146 return -EPERM;
5148 retval = security_task_setnice(current, nice);
5149 if (retval)
5150 return retval;
5152 set_user_nice(current, nice);
5153 return 0;
5156 #endif
5159 * task_prio - return the priority value of a given task.
5160 * @p: the task in question.
5162 * This is the priority value as seen by users in /proc.
5163 * RT tasks are offset by -200. Normal tasks are centered
5164 * around 0, value goes from -16 to +15.
5166 int task_prio(const struct task_struct *p)
5168 return p->prio - MAX_RT_PRIO;
5172 * task_nice - return the nice value of a given task.
5173 * @p: the task in question.
5175 int task_nice(const struct task_struct *p)
5177 return TASK_NICE(p);
5179 EXPORT_SYMBOL(task_nice);
5182 * idle_cpu - is a given cpu idle currently?
5183 * @cpu: the processor in question.
5185 int idle_cpu(int cpu)
5187 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5191 * idle_task - return the idle task for a given cpu.
5192 * @cpu: the processor in question.
5194 struct task_struct *idle_task(int cpu)
5196 return cpu_rq(cpu)->idle;
5200 * find_process_by_pid - find a process with a matching PID value.
5201 * @pid: the pid in question.
5203 static struct task_struct *find_process_by_pid(pid_t pid)
5205 return pid ? find_task_by_vpid(pid) : current;
5208 /* Actually do priority change: must hold rq lock. */
5209 static void
5210 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5212 BUG_ON(p->se.on_rq);
5214 p->policy = policy;
5215 switch (p->policy) {
5216 case SCHED_NORMAL:
5217 case SCHED_BATCH:
5218 case SCHED_IDLE:
5219 p->sched_class = &fair_sched_class;
5220 break;
5221 case SCHED_FIFO:
5222 case SCHED_RR:
5223 p->sched_class = &rt_sched_class;
5224 break;
5227 p->rt_priority = prio;
5228 p->normal_prio = normal_prio(p);
5229 /* we are holding p->pi_lock already */
5230 p->prio = rt_mutex_getprio(p);
5231 set_load_weight(p);
5235 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5236 * @p: the task in question.
5237 * @policy: new policy.
5238 * @param: structure containing the new RT priority.
5240 * NOTE that the task may be already dead.
5242 int sched_setscheduler(struct task_struct *p, int policy,
5243 struct sched_param *param)
5245 int retval, oldprio, oldpolicy = -1, on_rq, running;
5246 unsigned long flags;
5247 const struct sched_class *prev_class = p->sched_class;
5248 struct rq *rq;
5250 /* may grab non-irq protected spin_locks */
5251 BUG_ON(in_interrupt());
5252 recheck:
5253 /* double check policy once rq lock held */
5254 if (policy < 0)
5255 policy = oldpolicy = p->policy;
5256 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5257 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5258 policy != SCHED_IDLE)
5259 return -EINVAL;
5261 * Valid priorities for SCHED_FIFO and SCHED_RR are
5262 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5263 * SCHED_BATCH and SCHED_IDLE is 0.
5265 if (param->sched_priority < 0 ||
5266 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5267 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5268 return -EINVAL;
5269 if (rt_policy(policy) != (param->sched_priority != 0))
5270 return -EINVAL;
5273 * Allow unprivileged RT tasks to decrease priority:
5275 if (!capable(CAP_SYS_NICE)) {
5276 if (rt_policy(policy)) {
5277 unsigned long rlim_rtprio;
5279 if (!lock_task_sighand(p, &flags))
5280 return -ESRCH;
5281 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5282 unlock_task_sighand(p, &flags);
5284 /* can't set/change the rt policy */
5285 if (policy != p->policy && !rlim_rtprio)
5286 return -EPERM;
5288 /* can't increase priority */
5289 if (param->sched_priority > p->rt_priority &&
5290 param->sched_priority > rlim_rtprio)
5291 return -EPERM;
5294 * Like positive nice levels, dont allow tasks to
5295 * move out of SCHED_IDLE either:
5297 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5298 return -EPERM;
5300 /* can't change other user's priorities */
5301 if ((current->euid != p->euid) &&
5302 (current->euid != p->uid))
5303 return -EPERM;
5306 #ifdef CONFIG_RT_GROUP_SCHED
5308 * Do not allow realtime tasks into groups that have no runtime
5309 * assigned.
5311 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5312 return -EPERM;
5313 #endif
5315 retval = security_task_setscheduler(p, policy, param);
5316 if (retval)
5317 return retval;
5319 * make sure no PI-waiters arrive (or leave) while we are
5320 * changing the priority of the task:
5322 spin_lock_irqsave(&p->pi_lock, flags);
5324 * To be able to change p->policy safely, the apropriate
5325 * runqueue lock must be held.
5327 rq = __task_rq_lock(p);
5328 /* recheck policy now with rq lock held */
5329 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5330 policy = oldpolicy = -1;
5331 __task_rq_unlock(rq);
5332 spin_unlock_irqrestore(&p->pi_lock, flags);
5333 goto recheck;
5335 update_rq_clock(rq);
5336 on_rq = p->se.on_rq;
5337 running = task_current(rq, p);
5338 if (on_rq)
5339 deactivate_task(rq, p, 0);
5340 if (running)
5341 p->sched_class->put_prev_task(rq, p);
5343 oldprio = p->prio;
5344 __setscheduler(rq, p, policy, param->sched_priority);
5346 if (running)
5347 p->sched_class->set_curr_task(rq);
5348 if (on_rq) {
5349 activate_task(rq, p, 0);
5351 check_class_changed(rq, p, prev_class, oldprio, running);
5353 __task_rq_unlock(rq);
5354 spin_unlock_irqrestore(&p->pi_lock, flags);
5356 rt_mutex_adjust_pi(p);
5358 return 0;
5360 EXPORT_SYMBOL_GPL(sched_setscheduler);
5362 static int
5363 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5365 struct sched_param lparam;
5366 struct task_struct *p;
5367 int retval;
5369 if (!param || pid < 0)
5370 return -EINVAL;
5371 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5372 return -EFAULT;
5374 rcu_read_lock();
5375 retval = -ESRCH;
5376 p = find_process_by_pid(pid);
5377 if (p != NULL)
5378 retval = sched_setscheduler(p, policy, &lparam);
5379 rcu_read_unlock();
5381 return retval;
5385 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5386 * @pid: the pid in question.
5387 * @policy: new policy.
5388 * @param: structure containing the new RT priority.
5390 asmlinkage long
5391 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5393 /* negative values for policy are not valid */
5394 if (policy < 0)
5395 return -EINVAL;
5397 return do_sched_setscheduler(pid, policy, param);
5401 * sys_sched_setparam - set/change the RT priority of a thread
5402 * @pid: the pid in question.
5403 * @param: structure containing the new RT priority.
5405 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5407 return do_sched_setscheduler(pid, -1, param);
5411 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5412 * @pid: the pid in question.
5414 asmlinkage long sys_sched_getscheduler(pid_t pid)
5416 struct task_struct *p;
5417 int retval;
5419 if (pid < 0)
5420 return -EINVAL;
5422 retval = -ESRCH;
5423 read_lock(&tasklist_lock);
5424 p = find_process_by_pid(pid);
5425 if (p) {
5426 retval = security_task_getscheduler(p);
5427 if (!retval)
5428 retval = p->policy;
5430 read_unlock(&tasklist_lock);
5431 return retval;
5435 * sys_sched_getscheduler - get the RT priority of a thread
5436 * @pid: the pid in question.
5437 * @param: structure containing the RT priority.
5439 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5441 struct sched_param lp;
5442 struct task_struct *p;
5443 int retval;
5445 if (!param || pid < 0)
5446 return -EINVAL;
5448 read_lock(&tasklist_lock);
5449 p = find_process_by_pid(pid);
5450 retval = -ESRCH;
5451 if (!p)
5452 goto out_unlock;
5454 retval = security_task_getscheduler(p);
5455 if (retval)
5456 goto out_unlock;
5458 lp.sched_priority = p->rt_priority;
5459 read_unlock(&tasklist_lock);
5462 * This one might sleep, we cannot do it with a spinlock held ...
5464 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5466 return retval;
5468 out_unlock:
5469 read_unlock(&tasklist_lock);
5470 return retval;
5473 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5475 cpumask_t cpus_allowed;
5476 cpumask_t new_mask = *in_mask;
5477 struct task_struct *p;
5478 int retval;
5480 get_online_cpus();
5481 read_lock(&tasklist_lock);
5483 p = find_process_by_pid(pid);
5484 if (!p) {
5485 read_unlock(&tasklist_lock);
5486 put_online_cpus();
5487 return -ESRCH;
5491 * It is not safe to call set_cpus_allowed with the
5492 * tasklist_lock held. We will bump the task_struct's
5493 * usage count and then drop tasklist_lock.
5495 get_task_struct(p);
5496 read_unlock(&tasklist_lock);
5498 retval = -EPERM;
5499 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5500 !capable(CAP_SYS_NICE))
5501 goto out_unlock;
5503 retval = security_task_setscheduler(p, 0, NULL);
5504 if (retval)
5505 goto out_unlock;
5507 cpuset_cpus_allowed(p, &cpus_allowed);
5508 cpus_and(new_mask, new_mask, cpus_allowed);
5509 again:
5510 retval = set_cpus_allowed_ptr(p, &new_mask);
5512 if (!retval) {
5513 cpuset_cpus_allowed(p, &cpus_allowed);
5514 if (!cpus_subset(new_mask, cpus_allowed)) {
5516 * We must have raced with a concurrent cpuset
5517 * update. Just reset the cpus_allowed to the
5518 * cpuset's cpus_allowed
5520 new_mask = cpus_allowed;
5521 goto again;
5524 out_unlock:
5525 put_task_struct(p);
5526 put_online_cpus();
5527 return retval;
5530 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5531 cpumask_t *new_mask)
5533 if (len < sizeof(cpumask_t)) {
5534 memset(new_mask, 0, sizeof(cpumask_t));
5535 } else if (len > sizeof(cpumask_t)) {
5536 len = sizeof(cpumask_t);
5538 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5542 * sys_sched_setaffinity - set the cpu affinity of a process
5543 * @pid: pid of the process
5544 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5545 * @user_mask_ptr: user-space pointer to the new cpu mask
5547 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5548 unsigned long __user *user_mask_ptr)
5550 cpumask_t new_mask;
5551 int retval;
5553 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5554 if (retval)
5555 return retval;
5557 return sched_setaffinity(pid, &new_mask);
5561 * Represents all cpu's present in the system
5562 * In systems capable of hotplug, this map could dynamically grow
5563 * as new cpu's are detected in the system via any platform specific
5564 * method, such as ACPI for e.g.
5567 cpumask_t cpu_present_map __read_mostly;
5568 EXPORT_SYMBOL(cpu_present_map);
5570 #ifndef CONFIG_SMP
5571 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5572 EXPORT_SYMBOL(cpu_online_map);
5574 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5575 EXPORT_SYMBOL(cpu_possible_map);
5576 #endif
5578 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5580 struct task_struct *p;
5581 int retval;
5583 get_online_cpus();
5584 read_lock(&tasklist_lock);
5586 retval = -ESRCH;
5587 p = find_process_by_pid(pid);
5588 if (!p)
5589 goto out_unlock;
5591 retval = security_task_getscheduler(p);
5592 if (retval)
5593 goto out_unlock;
5595 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5597 out_unlock:
5598 read_unlock(&tasklist_lock);
5599 put_online_cpus();
5601 return retval;
5605 * sys_sched_getaffinity - get the cpu affinity of a process
5606 * @pid: pid of the process
5607 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5608 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5610 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5611 unsigned long __user *user_mask_ptr)
5613 int ret;
5614 cpumask_t mask;
5616 if (len < sizeof(cpumask_t))
5617 return -EINVAL;
5619 ret = sched_getaffinity(pid, &mask);
5620 if (ret < 0)
5621 return ret;
5623 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5624 return -EFAULT;
5626 return sizeof(cpumask_t);
5630 * sys_sched_yield - yield the current processor to other threads.
5632 * This function yields the current CPU to other tasks. If there are no
5633 * other threads running on this CPU then this function will return.
5635 asmlinkage long sys_sched_yield(void)
5637 struct rq *rq = this_rq_lock();
5639 schedstat_inc(rq, yld_count);
5640 current->sched_class->yield_task(rq);
5643 * Since we are going to call schedule() anyway, there's
5644 * no need to preempt or enable interrupts:
5646 __release(rq->lock);
5647 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5648 _raw_spin_unlock(&rq->lock);
5649 preempt_enable_no_resched();
5651 schedule();
5653 return 0;
5656 static void __cond_resched(void)
5658 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5659 __might_sleep(__FILE__, __LINE__);
5660 #endif
5662 * The BKS might be reacquired before we have dropped
5663 * PREEMPT_ACTIVE, which could trigger a second
5664 * cond_resched() call.
5666 do {
5667 add_preempt_count(PREEMPT_ACTIVE);
5668 schedule();
5669 sub_preempt_count(PREEMPT_ACTIVE);
5670 } while (need_resched());
5673 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5674 int __sched _cond_resched(void)
5676 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5677 system_state == SYSTEM_RUNNING) {
5678 __cond_resched();
5679 return 1;
5681 return 0;
5683 EXPORT_SYMBOL(_cond_resched);
5684 #endif
5687 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5688 * call schedule, and on return reacquire the lock.
5690 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5691 * operations here to prevent schedule() from being called twice (once via
5692 * spin_unlock(), once by hand).
5694 int cond_resched_lock(spinlock_t *lock)
5696 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5697 int ret = 0;
5699 if (spin_needbreak(lock) || resched) {
5700 spin_unlock(lock);
5701 if (resched && need_resched())
5702 __cond_resched();
5703 else
5704 cpu_relax();
5705 ret = 1;
5706 spin_lock(lock);
5708 return ret;
5710 EXPORT_SYMBOL(cond_resched_lock);
5712 int __sched cond_resched_softirq(void)
5714 BUG_ON(!in_softirq());
5716 if (need_resched() && system_state == SYSTEM_RUNNING) {
5717 local_bh_enable();
5718 __cond_resched();
5719 local_bh_disable();
5720 return 1;
5722 return 0;
5724 EXPORT_SYMBOL(cond_resched_softirq);
5727 * yield - yield the current processor to other threads.
5729 * This is a shortcut for kernel-space yielding - it marks the
5730 * thread runnable and calls sys_sched_yield().
5732 void __sched yield(void)
5734 set_current_state(TASK_RUNNING);
5735 sys_sched_yield();
5737 EXPORT_SYMBOL(yield);
5740 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5741 * that process accounting knows that this is a task in IO wait state.
5743 * But don't do that if it is a deliberate, throttling IO wait (this task
5744 * has set its backing_dev_info: the queue against which it should throttle)
5746 void __sched io_schedule(void)
5748 struct rq *rq = &__raw_get_cpu_var(runqueues);
5750 delayacct_blkio_start();
5751 atomic_inc(&rq->nr_iowait);
5752 schedule();
5753 atomic_dec(&rq->nr_iowait);
5754 delayacct_blkio_end();
5756 EXPORT_SYMBOL(io_schedule);
5758 long __sched io_schedule_timeout(long timeout)
5760 struct rq *rq = &__raw_get_cpu_var(runqueues);
5761 long ret;
5763 delayacct_blkio_start();
5764 atomic_inc(&rq->nr_iowait);
5765 ret = schedule_timeout(timeout);
5766 atomic_dec(&rq->nr_iowait);
5767 delayacct_blkio_end();
5768 return ret;
5772 * sys_sched_get_priority_max - return maximum RT priority.
5773 * @policy: scheduling class.
5775 * this syscall returns the maximum rt_priority that can be used
5776 * by a given scheduling class.
5778 asmlinkage long sys_sched_get_priority_max(int policy)
5780 int ret = -EINVAL;
5782 switch (policy) {
5783 case SCHED_FIFO:
5784 case SCHED_RR:
5785 ret = MAX_USER_RT_PRIO-1;
5786 break;
5787 case SCHED_NORMAL:
5788 case SCHED_BATCH:
5789 case SCHED_IDLE:
5790 ret = 0;
5791 break;
5793 return ret;
5797 * sys_sched_get_priority_min - return minimum RT priority.
5798 * @policy: scheduling class.
5800 * this syscall returns the minimum rt_priority that can be used
5801 * by a given scheduling class.
5803 asmlinkage long sys_sched_get_priority_min(int policy)
5805 int ret = -EINVAL;
5807 switch (policy) {
5808 case SCHED_FIFO:
5809 case SCHED_RR:
5810 ret = 1;
5811 break;
5812 case SCHED_NORMAL:
5813 case SCHED_BATCH:
5814 case SCHED_IDLE:
5815 ret = 0;
5817 return ret;
5821 * sys_sched_rr_get_interval - return the default timeslice of a process.
5822 * @pid: pid of the process.
5823 * @interval: userspace pointer to the timeslice value.
5825 * this syscall writes the default timeslice value of a given process
5826 * into the user-space timespec buffer. A value of '0' means infinity.
5828 asmlinkage
5829 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5831 struct task_struct *p;
5832 unsigned int time_slice;
5833 int retval;
5834 struct timespec t;
5836 if (pid < 0)
5837 return -EINVAL;
5839 retval = -ESRCH;
5840 read_lock(&tasklist_lock);
5841 p = find_process_by_pid(pid);
5842 if (!p)
5843 goto out_unlock;
5845 retval = security_task_getscheduler(p);
5846 if (retval)
5847 goto out_unlock;
5850 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5851 * tasks that are on an otherwise idle runqueue:
5853 time_slice = 0;
5854 if (p->policy == SCHED_RR) {
5855 time_slice = DEF_TIMESLICE;
5856 } else if (p->policy != SCHED_FIFO) {
5857 struct sched_entity *se = &p->se;
5858 unsigned long flags;
5859 struct rq *rq;
5861 rq = task_rq_lock(p, &flags);
5862 if (rq->cfs.load.weight)
5863 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5864 task_rq_unlock(rq, &flags);
5866 read_unlock(&tasklist_lock);
5867 jiffies_to_timespec(time_slice, &t);
5868 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5869 return retval;
5871 out_unlock:
5872 read_unlock(&tasklist_lock);
5873 return retval;
5876 static const char stat_nam[] = "RSDTtZX";
5878 void sched_show_task(struct task_struct *p)
5880 unsigned long free = 0;
5881 unsigned state;
5883 state = p->state ? __ffs(p->state) + 1 : 0;
5884 printk(KERN_INFO "%-13.13s %c", p->comm,
5885 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5886 #if BITS_PER_LONG == 32
5887 if (state == TASK_RUNNING)
5888 printk(KERN_CONT " running ");
5889 else
5890 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5891 #else
5892 if (state == TASK_RUNNING)
5893 printk(KERN_CONT " running task ");
5894 else
5895 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5896 #endif
5897 #ifdef CONFIG_DEBUG_STACK_USAGE
5899 unsigned long *n = end_of_stack(p);
5900 while (!*n)
5901 n++;
5902 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5904 #endif
5905 printk(KERN_CONT "%5lu %5d %6d\n", free,
5906 task_pid_nr(p), task_pid_nr(p->real_parent));
5908 show_stack(p, NULL);
5911 void show_state_filter(unsigned long state_filter)
5913 struct task_struct *g, *p;
5915 #if BITS_PER_LONG == 32
5916 printk(KERN_INFO
5917 " task PC stack pid father\n");
5918 #else
5919 printk(KERN_INFO
5920 " task PC stack pid father\n");
5921 #endif
5922 read_lock(&tasklist_lock);
5923 do_each_thread(g, p) {
5925 * reset the NMI-timeout, listing all files on a slow
5926 * console might take alot of time:
5928 touch_nmi_watchdog();
5929 if (!state_filter || (p->state & state_filter))
5930 sched_show_task(p);
5931 } while_each_thread(g, p);
5933 touch_all_softlockup_watchdogs();
5935 #ifdef CONFIG_SCHED_DEBUG
5936 sysrq_sched_debug_show();
5937 #endif
5938 read_unlock(&tasklist_lock);
5940 * Only show locks if all tasks are dumped:
5942 if (state_filter == -1)
5943 debug_show_all_locks();
5946 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5948 idle->sched_class = &idle_sched_class;
5952 * init_idle - set up an idle thread for a given CPU
5953 * @idle: task in question
5954 * @cpu: cpu the idle task belongs to
5956 * NOTE: this function does not set the idle thread's NEED_RESCHED
5957 * flag, to make booting more robust.
5959 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5961 struct rq *rq = cpu_rq(cpu);
5962 unsigned long flags;
5964 __sched_fork(idle);
5965 idle->se.exec_start = sched_clock();
5967 idle->prio = idle->normal_prio = MAX_PRIO;
5968 idle->cpus_allowed = cpumask_of_cpu(cpu);
5969 __set_task_cpu(idle, cpu);
5971 spin_lock_irqsave(&rq->lock, flags);
5972 rq->curr = rq->idle = idle;
5973 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5974 idle->oncpu = 1;
5975 #endif
5976 spin_unlock_irqrestore(&rq->lock, flags);
5978 /* Set the preempt count _outside_ the spinlocks! */
5979 task_thread_info(idle)->preempt_count = 0;
5982 * The idle tasks have their own, simple scheduling class:
5984 idle->sched_class = &idle_sched_class;
5988 * In a system that switches off the HZ timer nohz_cpu_mask
5989 * indicates which cpus entered this state. This is used
5990 * in the rcu update to wait only for active cpus. For system
5991 * which do not switch off the HZ timer nohz_cpu_mask should
5992 * always be CPU_MASK_NONE.
5994 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5997 * Increase the granularity value when there are more CPUs,
5998 * because with more CPUs the 'effective latency' as visible
5999 * to users decreases. But the relationship is not linear,
6000 * so pick a second-best guess by going with the log2 of the
6001 * number of CPUs.
6003 * This idea comes from the SD scheduler of Con Kolivas:
6005 static inline void sched_init_granularity(void)
6007 unsigned int factor = 1 + ilog2(num_online_cpus());
6008 const unsigned long limit = 200000000;
6010 sysctl_sched_min_granularity *= factor;
6011 if (sysctl_sched_min_granularity > limit)
6012 sysctl_sched_min_granularity = limit;
6014 sysctl_sched_latency *= factor;
6015 if (sysctl_sched_latency > limit)
6016 sysctl_sched_latency = limit;
6018 sysctl_sched_wakeup_granularity *= factor;
6021 #ifdef CONFIG_SMP
6023 * This is how migration works:
6025 * 1) we queue a struct migration_req structure in the source CPU's
6026 * runqueue and wake up that CPU's migration thread.
6027 * 2) we down() the locked semaphore => thread blocks.
6028 * 3) migration thread wakes up (implicitly it forces the migrated
6029 * thread off the CPU)
6030 * 4) it gets the migration request and checks whether the migrated
6031 * task is still in the wrong runqueue.
6032 * 5) if it's in the wrong runqueue then the migration thread removes
6033 * it and puts it into the right queue.
6034 * 6) migration thread up()s the semaphore.
6035 * 7) we wake up and the migration is done.
6039 * Change a given task's CPU affinity. Migrate the thread to a
6040 * proper CPU and schedule it away if the CPU it's executing on
6041 * is removed from the allowed bitmask.
6043 * NOTE: the caller must have a valid reference to the task, the
6044 * task must not exit() & deallocate itself prematurely. The
6045 * call is not atomic; no spinlocks may be held.
6047 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
6049 struct migration_req req;
6050 unsigned long flags;
6051 struct rq *rq;
6052 int ret = 0;
6054 rq = task_rq_lock(p, &flags);
6055 if (!cpus_intersects(*new_mask, cpu_online_map)) {
6056 ret = -EINVAL;
6057 goto out;
6060 if (p->sched_class->set_cpus_allowed)
6061 p->sched_class->set_cpus_allowed(p, new_mask);
6062 else {
6063 p->cpus_allowed = *new_mask;
6064 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
6067 /* Can the task run on the task's current CPU? If so, we're done */
6068 if (cpu_isset(task_cpu(p), *new_mask))
6069 goto out;
6071 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
6072 /* Need help from migration thread: drop lock and wait. */
6073 task_rq_unlock(rq, &flags);
6074 wake_up_process(rq->migration_thread);
6075 wait_for_completion(&req.done);
6076 tlb_migrate_finish(p->mm);
6077 return 0;
6079 out:
6080 task_rq_unlock(rq, &flags);
6082 return ret;
6084 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6087 * Move (not current) task off this cpu, onto dest cpu. We're doing
6088 * this because either it can't run here any more (set_cpus_allowed()
6089 * away from this CPU, or CPU going down), or because we're
6090 * attempting to rebalance this task on exec (sched_exec).
6092 * So we race with normal scheduler movements, but that's OK, as long
6093 * as the task is no longer on this CPU.
6095 * Returns non-zero if task was successfully migrated.
6097 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6099 struct rq *rq_dest, *rq_src;
6100 int ret = 0, on_rq;
6102 if (unlikely(cpu_is_offline(dest_cpu)))
6103 return ret;
6105 rq_src = cpu_rq(src_cpu);
6106 rq_dest = cpu_rq(dest_cpu);
6108 double_rq_lock(rq_src, rq_dest);
6109 /* Already moved. */
6110 if (task_cpu(p) != src_cpu)
6111 goto out;
6112 /* Affinity changed (again). */
6113 if (!cpu_isset(dest_cpu, p->cpus_allowed))
6114 goto out;
6116 on_rq = p->se.on_rq;
6117 if (on_rq)
6118 deactivate_task(rq_src, p, 0);
6120 set_task_cpu(p, dest_cpu);
6121 if (on_rq) {
6122 activate_task(rq_dest, p, 0);
6123 check_preempt_curr(rq_dest, p);
6125 ret = 1;
6126 out:
6127 double_rq_unlock(rq_src, rq_dest);
6128 return ret;
6132 * migration_thread - this is a highprio system thread that performs
6133 * thread migration by bumping thread off CPU then 'pushing' onto
6134 * another runqueue.
6136 static int migration_thread(void *data)
6138 int cpu = (long)data;
6139 struct rq *rq;
6141 rq = cpu_rq(cpu);
6142 BUG_ON(rq->migration_thread != current);
6144 set_current_state(TASK_INTERRUPTIBLE);
6145 while (!kthread_should_stop()) {
6146 struct migration_req *req;
6147 struct list_head *head;
6149 spin_lock_irq(&rq->lock);
6151 if (cpu_is_offline(cpu)) {
6152 spin_unlock_irq(&rq->lock);
6153 goto wait_to_die;
6156 if (rq->active_balance) {
6157 active_load_balance(rq, cpu);
6158 rq->active_balance = 0;
6161 head = &rq->migration_queue;
6163 if (list_empty(head)) {
6164 spin_unlock_irq(&rq->lock);
6165 schedule();
6166 set_current_state(TASK_INTERRUPTIBLE);
6167 continue;
6169 req = list_entry(head->next, struct migration_req, list);
6170 list_del_init(head->next);
6172 spin_unlock(&rq->lock);
6173 __migrate_task(req->task, cpu, req->dest_cpu);
6174 local_irq_enable();
6176 complete(&req->done);
6178 __set_current_state(TASK_RUNNING);
6179 return 0;
6181 wait_to_die:
6182 /* Wait for kthread_stop */
6183 set_current_state(TASK_INTERRUPTIBLE);
6184 while (!kthread_should_stop()) {
6185 schedule();
6186 set_current_state(TASK_INTERRUPTIBLE);
6188 __set_current_state(TASK_RUNNING);
6189 return 0;
6192 #ifdef CONFIG_HOTPLUG_CPU
6194 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6196 int ret;
6198 local_irq_disable();
6199 ret = __migrate_task(p, src_cpu, dest_cpu);
6200 local_irq_enable();
6201 return ret;
6205 * Figure out where task on dead CPU should go, use force if necessary.
6206 * NOTE: interrupts should be disabled by the caller
6208 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6210 unsigned long flags;
6211 cpumask_t mask;
6212 struct rq *rq;
6213 int dest_cpu;
6215 do {
6216 /* On same node? */
6217 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6218 cpus_and(mask, mask, p->cpus_allowed);
6219 dest_cpu = any_online_cpu(mask);
6221 /* On any allowed CPU? */
6222 if (dest_cpu >= nr_cpu_ids)
6223 dest_cpu = any_online_cpu(p->cpus_allowed);
6225 /* No more Mr. Nice Guy. */
6226 if (dest_cpu >= nr_cpu_ids) {
6227 cpumask_t cpus_allowed;
6229 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6231 * Try to stay on the same cpuset, where the
6232 * current cpuset may be a subset of all cpus.
6233 * The cpuset_cpus_allowed_locked() variant of
6234 * cpuset_cpus_allowed() will not block. It must be
6235 * called within calls to cpuset_lock/cpuset_unlock.
6237 rq = task_rq_lock(p, &flags);
6238 p->cpus_allowed = cpus_allowed;
6239 dest_cpu = any_online_cpu(p->cpus_allowed);
6240 task_rq_unlock(rq, &flags);
6243 * Don't tell them about moving exiting tasks or
6244 * kernel threads (both mm NULL), since they never
6245 * leave kernel.
6247 if (p->mm && printk_ratelimit()) {
6248 printk(KERN_INFO "process %d (%s) no "
6249 "longer affine to cpu%d\n",
6250 task_pid_nr(p), p->comm, dead_cpu);
6253 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6257 * While a dead CPU has no uninterruptible tasks queued at this point,
6258 * it might still have a nonzero ->nr_uninterruptible counter, because
6259 * for performance reasons the counter is not stricly tracking tasks to
6260 * their home CPUs. So we just add the counter to another CPU's counter,
6261 * to keep the global sum constant after CPU-down:
6263 static void migrate_nr_uninterruptible(struct rq *rq_src)
6265 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6266 unsigned long flags;
6268 local_irq_save(flags);
6269 double_rq_lock(rq_src, rq_dest);
6270 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6271 rq_src->nr_uninterruptible = 0;
6272 double_rq_unlock(rq_src, rq_dest);
6273 local_irq_restore(flags);
6276 /* Run through task list and migrate tasks from the dead cpu. */
6277 static void migrate_live_tasks(int src_cpu)
6279 struct task_struct *p, *t;
6281 read_lock(&tasklist_lock);
6283 do_each_thread(t, p) {
6284 if (p == current)
6285 continue;
6287 if (task_cpu(p) == src_cpu)
6288 move_task_off_dead_cpu(src_cpu, p);
6289 } while_each_thread(t, p);
6291 read_unlock(&tasklist_lock);
6295 * Schedules idle task to be the next runnable task on current CPU.
6296 * It does so by boosting its priority to highest possible.
6297 * Used by CPU offline code.
6299 void sched_idle_next(void)
6301 int this_cpu = smp_processor_id();
6302 struct rq *rq = cpu_rq(this_cpu);
6303 struct task_struct *p = rq->idle;
6304 unsigned long flags;
6306 /* cpu has to be offline */
6307 BUG_ON(cpu_online(this_cpu));
6310 * Strictly not necessary since rest of the CPUs are stopped by now
6311 * and interrupts disabled on the current cpu.
6313 spin_lock_irqsave(&rq->lock, flags);
6315 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6317 update_rq_clock(rq);
6318 activate_task(rq, p, 0);
6320 spin_unlock_irqrestore(&rq->lock, flags);
6324 * Ensures that the idle task is using init_mm right before its cpu goes
6325 * offline.
6327 void idle_task_exit(void)
6329 struct mm_struct *mm = current->active_mm;
6331 BUG_ON(cpu_online(smp_processor_id()));
6333 if (mm != &init_mm)
6334 switch_mm(mm, &init_mm, current);
6335 mmdrop(mm);
6338 /* called under rq->lock with disabled interrupts */
6339 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6341 struct rq *rq = cpu_rq(dead_cpu);
6343 /* Must be exiting, otherwise would be on tasklist. */
6344 BUG_ON(!p->exit_state);
6346 /* Cannot have done final schedule yet: would have vanished. */
6347 BUG_ON(p->state == TASK_DEAD);
6349 get_task_struct(p);
6352 * Drop lock around migration; if someone else moves it,
6353 * that's OK. No task can be added to this CPU, so iteration is
6354 * fine.
6356 spin_unlock_irq(&rq->lock);
6357 move_task_off_dead_cpu(dead_cpu, p);
6358 spin_lock_irq(&rq->lock);
6360 put_task_struct(p);
6363 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6364 static void migrate_dead_tasks(unsigned int dead_cpu)
6366 struct rq *rq = cpu_rq(dead_cpu);
6367 struct task_struct *next;
6369 for ( ; ; ) {
6370 if (!rq->nr_running)
6371 break;
6372 update_rq_clock(rq);
6373 next = pick_next_task(rq, rq->curr);
6374 if (!next)
6375 break;
6376 migrate_dead(dead_cpu, next);
6380 #endif /* CONFIG_HOTPLUG_CPU */
6382 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6384 static struct ctl_table sd_ctl_dir[] = {
6386 .procname = "sched_domain",
6387 .mode = 0555,
6389 {0, },
6392 static struct ctl_table sd_ctl_root[] = {
6394 .ctl_name = CTL_KERN,
6395 .procname = "kernel",
6396 .mode = 0555,
6397 .child = sd_ctl_dir,
6399 {0, },
6402 static struct ctl_table *sd_alloc_ctl_entry(int n)
6404 struct ctl_table *entry =
6405 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6407 return entry;
6410 static void sd_free_ctl_entry(struct ctl_table **tablep)
6412 struct ctl_table *entry;
6415 * In the intermediate directories, both the child directory and
6416 * procname are dynamically allocated and could fail but the mode
6417 * will always be set. In the lowest directory the names are
6418 * static strings and all have proc handlers.
6420 for (entry = *tablep; entry->mode; entry++) {
6421 if (entry->child)
6422 sd_free_ctl_entry(&entry->child);
6423 if (entry->proc_handler == NULL)
6424 kfree(entry->procname);
6427 kfree(*tablep);
6428 *tablep = NULL;
6431 static void
6432 set_table_entry(struct ctl_table *entry,
6433 const char *procname, void *data, int maxlen,
6434 mode_t mode, proc_handler *proc_handler)
6436 entry->procname = procname;
6437 entry->data = data;
6438 entry->maxlen = maxlen;
6439 entry->mode = mode;
6440 entry->proc_handler = proc_handler;
6443 static struct ctl_table *
6444 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6446 struct ctl_table *table = sd_alloc_ctl_entry(12);
6448 if (table == NULL)
6449 return NULL;
6451 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6452 sizeof(long), 0644, proc_doulongvec_minmax);
6453 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6454 sizeof(long), 0644, proc_doulongvec_minmax);
6455 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6456 sizeof(int), 0644, proc_dointvec_minmax);
6457 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6458 sizeof(int), 0644, proc_dointvec_minmax);
6459 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6460 sizeof(int), 0644, proc_dointvec_minmax);
6461 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6462 sizeof(int), 0644, proc_dointvec_minmax);
6463 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6464 sizeof(int), 0644, proc_dointvec_minmax);
6465 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6466 sizeof(int), 0644, proc_dointvec_minmax);
6467 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6468 sizeof(int), 0644, proc_dointvec_minmax);
6469 set_table_entry(&table[9], "cache_nice_tries",
6470 &sd->cache_nice_tries,
6471 sizeof(int), 0644, proc_dointvec_minmax);
6472 set_table_entry(&table[10], "flags", &sd->flags,
6473 sizeof(int), 0644, proc_dointvec_minmax);
6474 /* &table[11] is terminator */
6476 return table;
6479 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6481 struct ctl_table *entry, *table;
6482 struct sched_domain *sd;
6483 int domain_num = 0, i;
6484 char buf[32];
6486 for_each_domain(cpu, sd)
6487 domain_num++;
6488 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6489 if (table == NULL)
6490 return NULL;
6492 i = 0;
6493 for_each_domain(cpu, sd) {
6494 snprintf(buf, 32, "domain%d", i);
6495 entry->procname = kstrdup(buf, GFP_KERNEL);
6496 entry->mode = 0555;
6497 entry->child = sd_alloc_ctl_domain_table(sd);
6498 entry++;
6499 i++;
6501 return table;
6504 static struct ctl_table_header *sd_sysctl_header;
6505 static void register_sched_domain_sysctl(void)
6507 int i, cpu_num = num_online_cpus();
6508 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6509 char buf[32];
6511 WARN_ON(sd_ctl_dir[0].child);
6512 sd_ctl_dir[0].child = entry;
6514 if (entry == NULL)
6515 return;
6517 for_each_online_cpu(i) {
6518 snprintf(buf, 32, "cpu%d", i);
6519 entry->procname = kstrdup(buf, GFP_KERNEL);
6520 entry->mode = 0555;
6521 entry->child = sd_alloc_ctl_cpu_table(i);
6522 entry++;
6525 WARN_ON(sd_sysctl_header);
6526 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6529 /* may be called multiple times per register */
6530 static void unregister_sched_domain_sysctl(void)
6532 if (sd_sysctl_header)
6533 unregister_sysctl_table(sd_sysctl_header);
6534 sd_sysctl_header = NULL;
6535 if (sd_ctl_dir[0].child)
6536 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6538 #else
6539 static void register_sched_domain_sysctl(void)
6542 static void unregister_sched_domain_sysctl(void)
6545 #endif
6548 * migration_call - callback that gets triggered when a CPU is added.
6549 * Here we can start up the necessary migration thread for the new CPU.
6551 static int __cpuinit
6552 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6554 struct task_struct *p;
6555 int cpu = (long)hcpu;
6556 unsigned long flags;
6557 struct rq *rq;
6559 switch (action) {
6561 case CPU_UP_PREPARE:
6562 case CPU_UP_PREPARE_FROZEN:
6563 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6564 if (IS_ERR(p))
6565 return NOTIFY_BAD;
6566 kthread_bind(p, cpu);
6567 /* Must be high prio: stop_machine expects to yield to it. */
6568 rq = task_rq_lock(p, &flags);
6569 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6570 task_rq_unlock(rq, &flags);
6571 cpu_rq(cpu)->migration_thread = p;
6572 break;
6574 case CPU_ONLINE:
6575 case CPU_ONLINE_FROZEN:
6576 /* Strictly unnecessary, as first user will wake it. */
6577 wake_up_process(cpu_rq(cpu)->migration_thread);
6579 /* Update our root-domain */
6580 rq = cpu_rq(cpu);
6581 spin_lock_irqsave(&rq->lock, flags);
6582 if (rq->rd) {
6583 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6584 cpu_set(cpu, rq->rd->online);
6586 spin_unlock_irqrestore(&rq->lock, flags);
6587 break;
6589 #ifdef CONFIG_HOTPLUG_CPU
6590 case CPU_UP_CANCELED:
6591 case CPU_UP_CANCELED_FROZEN:
6592 if (!cpu_rq(cpu)->migration_thread)
6593 break;
6594 /* Unbind it from offline cpu so it can run. Fall thru. */
6595 kthread_bind(cpu_rq(cpu)->migration_thread,
6596 any_online_cpu(cpu_online_map));
6597 kthread_stop(cpu_rq(cpu)->migration_thread);
6598 cpu_rq(cpu)->migration_thread = NULL;
6599 break;
6601 case CPU_DEAD:
6602 case CPU_DEAD_FROZEN:
6603 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6604 migrate_live_tasks(cpu);
6605 rq = cpu_rq(cpu);
6606 kthread_stop(rq->migration_thread);
6607 rq->migration_thread = NULL;
6608 /* Idle task back to normal (off runqueue, low prio) */
6609 spin_lock_irq(&rq->lock);
6610 update_rq_clock(rq);
6611 deactivate_task(rq, rq->idle, 0);
6612 rq->idle->static_prio = MAX_PRIO;
6613 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6614 rq->idle->sched_class = &idle_sched_class;
6615 migrate_dead_tasks(cpu);
6616 spin_unlock_irq(&rq->lock);
6617 cpuset_unlock();
6618 migrate_nr_uninterruptible(rq);
6619 BUG_ON(rq->nr_running != 0);
6622 * No need to migrate the tasks: it was best-effort if
6623 * they didn't take sched_hotcpu_mutex. Just wake up
6624 * the requestors.
6626 spin_lock_irq(&rq->lock);
6627 while (!list_empty(&rq->migration_queue)) {
6628 struct migration_req *req;
6630 req = list_entry(rq->migration_queue.next,
6631 struct migration_req, list);
6632 list_del_init(&req->list);
6633 complete(&req->done);
6635 spin_unlock_irq(&rq->lock);
6636 break;
6638 case CPU_DYING:
6639 case CPU_DYING_FROZEN:
6640 /* Update our root-domain */
6641 rq = cpu_rq(cpu);
6642 spin_lock_irqsave(&rq->lock, flags);
6643 if (rq->rd) {
6644 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6645 cpu_clear(cpu, rq->rd->online);
6647 spin_unlock_irqrestore(&rq->lock, flags);
6648 break;
6649 #endif
6651 return NOTIFY_OK;
6654 /* Register at highest priority so that task migration (migrate_all_tasks)
6655 * happens before everything else.
6657 static struct notifier_block __cpuinitdata migration_notifier = {
6658 .notifier_call = migration_call,
6659 .priority = 10
6662 void __init migration_init(void)
6664 void *cpu = (void *)(long)smp_processor_id();
6665 int err;
6667 /* Start one for the boot CPU: */
6668 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6669 BUG_ON(err == NOTIFY_BAD);
6670 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6671 register_cpu_notifier(&migration_notifier);
6673 #endif
6675 #ifdef CONFIG_SMP
6677 #ifdef CONFIG_SCHED_DEBUG
6679 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6680 cpumask_t *groupmask)
6682 struct sched_group *group = sd->groups;
6683 char str[256];
6685 cpulist_scnprintf(str, sizeof(str), sd->span);
6686 cpus_clear(*groupmask);
6688 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6690 if (!(sd->flags & SD_LOAD_BALANCE)) {
6691 printk("does not load-balance\n");
6692 if (sd->parent)
6693 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6694 " has parent");
6695 return -1;
6698 printk(KERN_CONT "span %s\n", str);
6700 if (!cpu_isset(cpu, sd->span)) {
6701 printk(KERN_ERR "ERROR: domain->span does not contain "
6702 "CPU%d\n", cpu);
6704 if (!cpu_isset(cpu, group->cpumask)) {
6705 printk(KERN_ERR "ERROR: domain->groups does not contain"
6706 " CPU%d\n", cpu);
6709 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6710 do {
6711 if (!group) {
6712 printk("\n");
6713 printk(KERN_ERR "ERROR: group is NULL\n");
6714 break;
6717 if (!group->__cpu_power) {
6718 printk(KERN_CONT "\n");
6719 printk(KERN_ERR "ERROR: domain->cpu_power not "
6720 "set\n");
6721 break;
6724 if (!cpus_weight(group->cpumask)) {
6725 printk(KERN_CONT "\n");
6726 printk(KERN_ERR "ERROR: empty group\n");
6727 break;
6730 if (cpus_intersects(*groupmask, group->cpumask)) {
6731 printk(KERN_CONT "\n");
6732 printk(KERN_ERR "ERROR: repeated CPUs\n");
6733 break;
6736 cpus_or(*groupmask, *groupmask, group->cpumask);
6738 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6739 printk(KERN_CONT " %s", str);
6741 group = group->next;
6742 } while (group != sd->groups);
6743 printk(KERN_CONT "\n");
6745 if (!cpus_equal(sd->span, *groupmask))
6746 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6748 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6749 printk(KERN_ERR "ERROR: parent span is not a superset "
6750 "of domain->span\n");
6751 return 0;
6754 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6756 cpumask_t *groupmask;
6757 int level = 0;
6759 if (!sd) {
6760 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6761 return;
6764 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6766 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6767 if (!groupmask) {
6768 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6769 return;
6772 for (;;) {
6773 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6774 break;
6775 level++;
6776 sd = sd->parent;
6777 if (!sd)
6778 break;
6780 kfree(groupmask);
6782 #else
6783 # define sched_domain_debug(sd, cpu) do { } while (0)
6784 #endif
6786 static int sd_degenerate(struct sched_domain *sd)
6788 if (cpus_weight(sd->span) == 1)
6789 return 1;
6791 /* Following flags need at least 2 groups */
6792 if (sd->flags & (SD_LOAD_BALANCE |
6793 SD_BALANCE_NEWIDLE |
6794 SD_BALANCE_FORK |
6795 SD_BALANCE_EXEC |
6796 SD_SHARE_CPUPOWER |
6797 SD_SHARE_PKG_RESOURCES)) {
6798 if (sd->groups != sd->groups->next)
6799 return 0;
6802 /* Following flags don't use groups */
6803 if (sd->flags & (SD_WAKE_IDLE |
6804 SD_WAKE_AFFINE |
6805 SD_WAKE_BALANCE))
6806 return 0;
6808 return 1;
6811 static int
6812 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6814 unsigned long cflags = sd->flags, pflags = parent->flags;
6816 if (sd_degenerate(parent))
6817 return 1;
6819 if (!cpus_equal(sd->span, parent->span))
6820 return 0;
6822 /* Does parent contain flags not in child? */
6823 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6824 if (cflags & SD_WAKE_AFFINE)
6825 pflags &= ~SD_WAKE_BALANCE;
6826 /* Flags needing groups don't count if only 1 group in parent */
6827 if (parent->groups == parent->groups->next) {
6828 pflags &= ~(SD_LOAD_BALANCE |
6829 SD_BALANCE_NEWIDLE |
6830 SD_BALANCE_FORK |
6831 SD_BALANCE_EXEC |
6832 SD_SHARE_CPUPOWER |
6833 SD_SHARE_PKG_RESOURCES);
6835 if (~cflags & pflags)
6836 return 0;
6838 return 1;
6841 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6843 unsigned long flags;
6844 const struct sched_class *class;
6846 spin_lock_irqsave(&rq->lock, flags);
6848 if (rq->rd) {
6849 struct root_domain *old_rd = rq->rd;
6851 for (class = sched_class_highest; class; class = class->next) {
6852 if (class->leave_domain)
6853 class->leave_domain(rq);
6856 cpu_clear(rq->cpu, old_rd->span);
6857 cpu_clear(rq->cpu, old_rd->online);
6859 if (atomic_dec_and_test(&old_rd->refcount))
6860 kfree(old_rd);
6863 atomic_inc(&rd->refcount);
6864 rq->rd = rd;
6866 cpu_set(rq->cpu, rd->span);
6867 if (cpu_isset(rq->cpu, cpu_online_map))
6868 cpu_set(rq->cpu, rd->online);
6870 for (class = sched_class_highest; class; class = class->next) {
6871 if (class->join_domain)
6872 class->join_domain(rq);
6875 spin_unlock_irqrestore(&rq->lock, flags);
6878 static void init_rootdomain(struct root_domain *rd)
6880 memset(rd, 0, sizeof(*rd));
6882 cpus_clear(rd->span);
6883 cpus_clear(rd->online);
6886 static void init_defrootdomain(void)
6888 init_rootdomain(&def_root_domain);
6889 atomic_set(&def_root_domain.refcount, 1);
6892 static struct root_domain *alloc_rootdomain(void)
6894 struct root_domain *rd;
6896 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6897 if (!rd)
6898 return NULL;
6900 init_rootdomain(rd);
6902 return rd;
6906 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6907 * hold the hotplug lock.
6909 static void
6910 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6912 struct rq *rq = cpu_rq(cpu);
6913 struct sched_domain *tmp;
6915 /* Remove the sched domains which do not contribute to scheduling. */
6916 for (tmp = sd; tmp; tmp = tmp->parent) {
6917 struct sched_domain *parent = tmp->parent;
6918 if (!parent)
6919 break;
6920 if (sd_parent_degenerate(tmp, parent)) {
6921 tmp->parent = parent->parent;
6922 if (parent->parent)
6923 parent->parent->child = tmp;
6927 if (sd && sd_degenerate(sd)) {
6928 sd = sd->parent;
6929 if (sd)
6930 sd->child = NULL;
6933 sched_domain_debug(sd, cpu);
6935 rq_attach_root(rq, rd);
6936 rcu_assign_pointer(rq->sd, sd);
6939 /* cpus with isolated domains */
6940 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6942 /* Setup the mask of cpus configured for isolated domains */
6943 static int __init isolated_cpu_setup(char *str)
6945 int ints[NR_CPUS], i;
6947 str = get_options(str, ARRAY_SIZE(ints), ints);
6948 cpus_clear(cpu_isolated_map);
6949 for (i = 1; i <= ints[0]; i++)
6950 if (ints[i] < NR_CPUS)
6951 cpu_set(ints[i], cpu_isolated_map);
6952 return 1;
6955 __setup("isolcpus=", isolated_cpu_setup);
6958 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6959 * to a function which identifies what group(along with sched group) a CPU
6960 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6961 * (due to the fact that we keep track of groups covered with a cpumask_t).
6963 * init_sched_build_groups will build a circular linked list of the groups
6964 * covered by the given span, and will set each group's ->cpumask correctly,
6965 * and ->cpu_power to 0.
6967 static void
6968 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6969 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6970 struct sched_group **sg,
6971 cpumask_t *tmpmask),
6972 cpumask_t *covered, cpumask_t *tmpmask)
6974 struct sched_group *first = NULL, *last = NULL;
6975 int i;
6977 cpus_clear(*covered);
6979 for_each_cpu_mask(i, *span) {
6980 struct sched_group *sg;
6981 int group = group_fn(i, cpu_map, &sg, tmpmask);
6982 int j;
6984 if (cpu_isset(i, *covered))
6985 continue;
6987 cpus_clear(sg->cpumask);
6988 sg->__cpu_power = 0;
6990 for_each_cpu_mask(j, *span) {
6991 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6992 continue;
6994 cpu_set(j, *covered);
6995 cpu_set(j, sg->cpumask);
6997 if (!first)
6998 first = sg;
6999 if (last)
7000 last->next = sg;
7001 last = sg;
7003 last->next = first;
7006 #define SD_NODES_PER_DOMAIN 16
7008 #ifdef CONFIG_NUMA
7011 * find_next_best_node - find the next node to include in a sched_domain
7012 * @node: node whose sched_domain we're building
7013 * @used_nodes: nodes already in the sched_domain
7015 * Find the next node to include in a given scheduling domain. Simply
7016 * finds the closest node not already in the @used_nodes map.
7018 * Should use nodemask_t.
7020 static int find_next_best_node(int node, nodemask_t *used_nodes)
7022 int i, n, val, min_val, best_node = 0;
7024 min_val = INT_MAX;
7026 for (i = 0; i < MAX_NUMNODES; i++) {
7027 /* Start at @node */
7028 n = (node + i) % MAX_NUMNODES;
7030 if (!nr_cpus_node(n))
7031 continue;
7033 /* Skip already used nodes */
7034 if (node_isset(n, *used_nodes))
7035 continue;
7037 /* Simple min distance search */
7038 val = node_distance(node, n);
7040 if (val < min_val) {
7041 min_val = val;
7042 best_node = n;
7046 node_set(best_node, *used_nodes);
7047 return best_node;
7051 * sched_domain_node_span - get a cpumask for a node's sched_domain
7052 * @node: node whose cpumask we're constructing
7053 * @span: resulting cpumask
7055 * Given a node, construct a good cpumask for its sched_domain to span. It
7056 * should be one that prevents unnecessary balancing, but also spreads tasks
7057 * out optimally.
7059 static void sched_domain_node_span(int node, cpumask_t *span)
7061 nodemask_t used_nodes;
7062 node_to_cpumask_ptr(nodemask, node);
7063 int i;
7065 cpus_clear(*span);
7066 nodes_clear(used_nodes);
7068 cpus_or(*span, *span, *nodemask);
7069 node_set(node, used_nodes);
7071 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7072 int next_node = find_next_best_node(node, &used_nodes);
7074 node_to_cpumask_ptr_next(nodemask, next_node);
7075 cpus_or(*span, *span, *nodemask);
7078 #endif
7080 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7083 * SMT sched-domains:
7085 #ifdef CONFIG_SCHED_SMT
7086 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
7087 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
7089 static int
7090 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7091 cpumask_t *unused)
7093 if (sg)
7094 *sg = &per_cpu(sched_group_cpus, cpu);
7095 return cpu;
7097 #endif
7100 * multi-core sched-domains:
7102 #ifdef CONFIG_SCHED_MC
7103 static DEFINE_PER_CPU(struct sched_domain, core_domains);
7104 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
7105 #endif
7107 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7108 static int
7109 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7110 cpumask_t *mask)
7112 int group;
7114 *mask = per_cpu(cpu_sibling_map, cpu);
7115 cpus_and(*mask, *mask, *cpu_map);
7116 group = first_cpu(*mask);
7117 if (sg)
7118 *sg = &per_cpu(sched_group_core, group);
7119 return group;
7121 #elif defined(CONFIG_SCHED_MC)
7122 static int
7123 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7124 cpumask_t *unused)
7126 if (sg)
7127 *sg = &per_cpu(sched_group_core, cpu);
7128 return cpu;
7130 #endif
7132 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7133 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7135 static int
7136 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7137 cpumask_t *mask)
7139 int group;
7140 #ifdef CONFIG_SCHED_MC
7141 *mask = cpu_coregroup_map(cpu);
7142 cpus_and(*mask, *mask, *cpu_map);
7143 group = first_cpu(*mask);
7144 #elif defined(CONFIG_SCHED_SMT)
7145 *mask = per_cpu(cpu_sibling_map, cpu);
7146 cpus_and(*mask, *mask, *cpu_map);
7147 group = first_cpu(*mask);
7148 #else
7149 group = cpu;
7150 #endif
7151 if (sg)
7152 *sg = &per_cpu(sched_group_phys, group);
7153 return group;
7156 #ifdef CONFIG_NUMA
7158 * The init_sched_build_groups can't handle what we want to do with node
7159 * groups, so roll our own. Now each node has its own list of groups which
7160 * gets dynamically allocated.
7162 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7163 static struct sched_group ***sched_group_nodes_bycpu;
7165 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7166 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7168 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7169 struct sched_group **sg, cpumask_t *nodemask)
7171 int group;
7173 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7174 cpus_and(*nodemask, *nodemask, *cpu_map);
7175 group = first_cpu(*nodemask);
7177 if (sg)
7178 *sg = &per_cpu(sched_group_allnodes, group);
7179 return group;
7182 static void init_numa_sched_groups_power(struct sched_group *group_head)
7184 struct sched_group *sg = group_head;
7185 int j;
7187 if (!sg)
7188 return;
7189 do {
7190 for_each_cpu_mask(j, sg->cpumask) {
7191 struct sched_domain *sd;
7193 sd = &per_cpu(phys_domains, j);
7194 if (j != first_cpu(sd->groups->cpumask)) {
7196 * Only add "power" once for each
7197 * physical package.
7199 continue;
7202 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7204 sg = sg->next;
7205 } while (sg != group_head);
7207 #endif
7209 #ifdef CONFIG_NUMA
7210 /* Free memory allocated for various sched_group structures */
7211 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7213 int cpu, i;
7215 for_each_cpu_mask(cpu, *cpu_map) {
7216 struct sched_group **sched_group_nodes
7217 = sched_group_nodes_bycpu[cpu];
7219 if (!sched_group_nodes)
7220 continue;
7222 for (i = 0; i < MAX_NUMNODES; i++) {
7223 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7225 *nodemask = node_to_cpumask(i);
7226 cpus_and(*nodemask, *nodemask, *cpu_map);
7227 if (cpus_empty(*nodemask))
7228 continue;
7230 if (sg == NULL)
7231 continue;
7232 sg = sg->next;
7233 next_sg:
7234 oldsg = sg;
7235 sg = sg->next;
7236 kfree(oldsg);
7237 if (oldsg != sched_group_nodes[i])
7238 goto next_sg;
7240 kfree(sched_group_nodes);
7241 sched_group_nodes_bycpu[cpu] = NULL;
7244 #else
7245 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7248 #endif
7251 * Initialize sched groups cpu_power.
7253 * cpu_power indicates the capacity of sched group, which is used while
7254 * distributing the load between different sched groups in a sched domain.
7255 * Typically cpu_power for all the groups in a sched domain will be same unless
7256 * there are asymmetries in the topology. If there are asymmetries, group
7257 * having more cpu_power will pickup more load compared to the group having
7258 * less cpu_power.
7260 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7261 * the maximum number of tasks a group can handle in the presence of other idle
7262 * or lightly loaded groups in the same sched domain.
7264 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7266 struct sched_domain *child;
7267 struct sched_group *group;
7269 WARN_ON(!sd || !sd->groups);
7271 if (cpu != first_cpu(sd->groups->cpumask))
7272 return;
7274 child = sd->child;
7276 sd->groups->__cpu_power = 0;
7279 * For perf policy, if the groups in child domain share resources
7280 * (for example cores sharing some portions of the cache hierarchy
7281 * or SMT), then set this domain groups cpu_power such that each group
7282 * can handle only one task, when there are other idle groups in the
7283 * same sched domain.
7285 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7286 (child->flags &
7287 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7288 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7289 return;
7293 * add cpu_power of each child group to this groups cpu_power
7295 group = child->groups;
7296 do {
7297 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7298 group = group->next;
7299 } while (group != child->groups);
7303 * Initializers for schedule domains
7304 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7307 #define SD_INIT(sd, type) sd_init_##type(sd)
7308 #define SD_INIT_FUNC(type) \
7309 static noinline void sd_init_##type(struct sched_domain *sd) \
7311 memset(sd, 0, sizeof(*sd)); \
7312 *sd = SD_##type##_INIT; \
7313 sd->level = SD_LV_##type; \
7316 SD_INIT_FUNC(CPU)
7317 #ifdef CONFIG_NUMA
7318 SD_INIT_FUNC(ALLNODES)
7319 SD_INIT_FUNC(NODE)
7320 #endif
7321 #ifdef CONFIG_SCHED_SMT
7322 SD_INIT_FUNC(SIBLING)
7323 #endif
7324 #ifdef CONFIG_SCHED_MC
7325 SD_INIT_FUNC(MC)
7326 #endif
7329 * To minimize stack usage kmalloc room for cpumasks and share the
7330 * space as the usage in build_sched_domains() dictates. Used only
7331 * if the amount of space is significant.
7333 struct allmasks {
7334 cpumask_t tmpmask; /* make this one first */
7335 union {
7336 cpumask_t nodemask;
7337 cpumask_t this_sibling_map;
7338 cpumask_t this_core_map;
7340 cpumask_t send_covered;
7342 #ifdef CONFIG_NUMA
7343 cpumask_t domainspan;
7344 cpumask_t covered;
7345 cpumask_t notcovered;
7346 #endif
7349 #if NR_CPUS > 128
7350 #define SCHED_CPUMASK_ALLOC 1
7351 #define SCHED_CPUMASK_FREE(v) kfree(v)
7352 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7353 #else
7354 #define SCHED_CPUMASK_ALLOC 0
7355 #define SCHED_CPUMASK_FREE(v)
7356 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7357 #endif
7359 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7360 ((unsigned long)(a) + offsetof(struct allmasks, v))
7362 static int default_relax_domain_level = -1;
7364 static int __init setup_relax_domain_level(char *str)
7366 default_relax_domain_level = simple_strtoul(str, NULL, 0);
7367 return 1;
7369 __setup("relax_domain_level=", setup_relax_domain_level);
7371 static void set_domain_attribute(struct sched_domain *sd,
7372 struct sched_domain_attr *attr)
7374 int request;
7376 if (!attr || attr->relax_domain_level < 0) {
7377 if (default_relax_domain_level < 0)
7378 return;
7379 else
7380 request = default_relax_domain_level;
7381 } else
7382 request = attr->relax_domain_level;
7383 if (request < sd->level) {
7384 /* turn off idle balance on this domain */
7385 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7386 } else {
7387 /* turn on idle balance on this domain */
7388 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7393 * Build sched domains for a given set of cpus and attach the sched domains
7394 * to the individual cpus
7396 static int __build_sched_domains(const cpumask_t *cpu_map,
7397 struct sched_domain_attr *attr)
7399 int i;
7400 struct root_domain *rd;
7401 SCHED_CPUMASK_DECLARE(allmasks);
7402 cpumask_t *tmpmask;
7403 #ifdef CONFIG_NUMA
7404 struct sched_group **sched_group_nodes = NULL;
7405 int sd_allnodes = 0;
7408 * Allocate the per-node list of sched groups
7410 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
7411 GFP_KERNEL);
7412 if (!sched_group_nodes) {
7413 printk(KERN_WARNING "Can not alloc sched group node list\n");
7414 return -ENOMEM;
7416 #endif
7418 rd = alloc_rootdomain();
7419 if (!rd) {
7420 printk(KERN_WARNING "Cannot alloc root domain\n");
7421 #ifdef CONFIG_NUMA
7422 kfree(sched_group_nodes);
7423 #endif
7424 return -ENOMEM;
7427 #if SCHED_CPUMASK_ALLOC
7428 /* get space for all scratch cpumask variables */
7429 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7430 if (!allmasks) {
7431 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7432 kfree(rd);
7433 #ifdef CONFIG_NUMA
7434 kfree(sched_group_nodes);
7435 #endif
7436 return -ENOMEM;
7438 #endif
7439 tmpmask = (cpumask_t *)allmasks;
7442 #ifdef CONFIG_NUMA
7443 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7444 #endif
7447 * Set up domains for cpus specified by the cpu_map.
7449 for_each_cpu_mask(i, *cpu_map) {
7450 struct sched_domain *sd = NULL, *p;
7451 SCHED_CPUMASK_VAR(nodemask, allmasks);
7453 *nodemask = node_to_cpumask(cpu_to_node(i));
7454 cpus_and(*nodemask, *nodemask, *cpu_map);
7456 #ifdef CONFIG_NUMA
7457 if (cpus_weight(*cpu_map) >
7458 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7459 sd = &per_cpu(allnodes_domains, i);
7460 SD_INIT(sd, ALLNODES);
7461 set_domain_attribute(sd, attr);
7462 sd->span = *cpu_map;
7463 sd->first_cpu = first_cpu(sd->span);
7464 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7465 p = sd;
7466 sd_allnodes = 1;
7467 } else
7468 p = NULL;
7470 sd = &per_cpu(node_domains, i);
7471 SD_INIT(sd, NODE);
7472 set_domain_attribute(sd, attr);
7473 sched_domain_node_span(cpu_to_node(i), &sd->span);
7474 sd->first_cpu = first_cpu(sd->span);
7475 sd->parent = p;
7476 if (p)
7477 p->child = sd;
7478 cpus_and(sd->span, sd->span, *cpu_map);
7479 #endif
7481 p = sd;
7482 sd = &per_cpu(phys_domains, i);
7483 SD_INIT(sd, CPU);
7484 set_domain_attribute(sd, attr);
7485 sd->span = *nodemask;
7486 sd->first_cpu = first_cpu(sd->span);
7487 sd->parent = p;
7488 if (p)
7489 p->child = sd;
7490 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7492 #ifdef CONFIG_SCHED_MC
7493 p = sd;
7494 sd = &per_cpu(core_domains, i);
7495 SD_INIT(sd, MC);
7496 set_domain_attribute(sd, attr);
7497 sd->span = cpu_coregroup_map(i);
7498 sd->first_cpu = first_cpu(sd->span);
7499 cpus_and(sd->span, sd->span, *cpu_map);
7500 sd->parent = p;
7501 p->child = sd;
7502 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7503 #endif
7505 #ifdef CONFIG_SCHED_SMT
7506 p = sd;
7507 sd = &per_cpu(cpu_domains, i);
7508 SD_INIT(sd, SIBLING);
7509 set_domain_attribute(sd, attr);
7510 sd->span = per_cpu(cpu_sibling_map, i);
7511 sd->first_cpu = first_cpu(sd->span);
7512 cpus_and(sd->span, sd->span, *cpu_map);
7513 sd->parent = p;
7514 p->child = sd;
7515 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7516 #endif
7519 #ifdef CONFIG_SCHED_SMT
7520 /* Set up CPU (sibling) groups */
7521 for_each_cpu_mask(i, *cpu_map) {
7522 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7523 SCHED_CPUMASK_VAR(send_covered, allmasks);
7525 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7526 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7527 if (i != first_cpu(*this_sibling_map))
7528 continue;
7530 init_sched_build_groups(this_sibling_map, cpu_map,
7531 &cpu_to_cpu_group,
7532 send_covered, tmpmask);
7534 #endif
7536 #ifdef CONFIG_SCHED_MC
7537 /* Set up multi-core groups */
7538 for_each_cpu_mask(i, *cpu_map) {
7539 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7540 SCHED_CPUMASK_VAR(send_covered, allmasks);
7542 *this_core_map = cpu_coregroup_map(i);
7543 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7544 if (i != first_cpu(*this_core_map))
7545 continue;
7547 init_sched_build_groups(this_core_map, cpu_map,
7548 &cpu_to_core_group,
7549 send_covered, tmpmask);
7551 #endif
7553 /* Set up physical groups */
7554 for (i = 0; i < MAX_NUMNODES; i++) {
7555 SCHED_CPUMASK_VAR(nodemask, allmasks);
7556 SCHED_CPUMASK_VAR(send_covered, allmasks);
7558 *nodemask = node_to_cpumask(i);
7559 cpus_and(*nodemask, *nodemask, *cpu_map);
7560 if (cpus_empty(*nodemask))
7561 continue;
7563 init_sched_build_groups(nodemask, cpu_map,
7564 &cpu_to_phys_group,
7565 send_covered, tmpmask);
7568 #ifdef CONFIG_NUMA
7569 /* Set up node groups */
7570 if (sd_allnodes) {
7571 SCHED_CPUMASK_VAR(send_covered, allmasks);
7573 init_sched_build_groups(cpu_map, cpu_map,
7574 &cpu_to_allnodes_group,
7575 send_covered, tmpmask);
7578 for (i = 0; i < MAX_NUMNODES; i++) {
7579 /* Set up node groups */
7580 struct sched_group *sg, *prev;
7581 SCHED_CPUMASK_VAR(nodemask, allmasks);
7582 SCHED_CPUMASK_VAR(domainspan, allmasks);
7583 SCHED_CPUMASK_VAR(covered, allmasks);
7584 int j;
7586 *nodemask = node_to_cpumask(i);
7587 cpus_clear(*covered);
7589 cpus_and(*nodemask, *nodemask, *cpu_map);
7590 if (cpus_empty(*nodemask)) {
7591 sched_group_nodes[i] = NULL;
7592 continue;
7595 sched_domain_node_span(i, domainspan);
7596 cpus_and(*domainspan, *domainspan, *cpu_map);
7598 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7599 if (!sg) {
7600 printk(KERN_WARNING "Can not alloc domain group for "
7601 "node %d\n", i);
7602 goto error;
7604 sched_group_nodes[i] = sg;
7605 for_each_cpu_mask(j, *nodemask) {
7606 struct sched_domain *sd;
7608 sd = &per_cpu(node_domains, j);
7609 sd->groups = sg;
7611 sg->__cpu_power = 0;
7612 sg->cpumask = *nodemask;
7613 sg->next = sg;
7614 cpus_or(*covered, *covered, *nodemask);
7615 prev = sg;
7617 for (j = 0; j < MAX_NUMNODES; j++) {
7618 SCHED_CPUMASK_VAR(notcovered, allmasks);
7619 int n = (i + j) % MAX_NUMNODES;
7620 node_to_cpumask_ptr(pnodemask, n);
7622 cpus_complement(*notcovered, *covered);
7623 cpus_and(*tmpmask, *notcovered, *cpu_map);
7624 cpus_and(*tmpmask, *tmpmask, *domainspan);
7625 if (cpus_empty(*tmpmask))
7626 break;
7628 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7629 if (cpus_empty(*tmpmask))
7630 continue;
7632 sg = kmalloc_node(sizeof(struct sched_group),
7633 GFP_KERNEL, i);
7634 if (!sg) {
7635 printk(KERN_WARNING
7636 "Can not alloc domain group for node %d\n", j);
7637 goto error;
7639 sg->__cpu_power = 0;
7640 sg->cpumask = *tmpmask;
7641 sg->next = prev->next;
7642 cpus_or(*covered, *covered, *tmpmask);
7643 prev->next = sg;
7644 prev = sg;
7647 #endif
7649 /* Calculate CPU power for physical packages and nodes */
7650 #ifdef CONFIG_SCHED_SMT
7651 for_each_cpu_mask(i, *cpu_map) {
7652 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7654 init_sched_groups_power(i, sd);
7656 #endif
7657 #ifdef CONFIG_SCHED_MC
7658 for_each_cpu_mask(i, *cpu_map) {
7659 struct sched_domain *sd = &per_cpu(core_domains, i);
7661 init_sched_groups_power(i, sd);
7663 #endif
7665 for_each_cpu_mask(i, *cpu_map) {
7666 struct sched_domain *sd = &per_cpu(phys_domains, i);
7668 init_sched_groups_power(i, sd);
7671 #ifdef CONFIG_NUMA
7672 for (i = 0; i < MAX_NUMNODES; i++)
7673 init_numa_sched_groups_power(sched_group_nodes[i]);
7675 if (sd_allnodes) {
7676 struct sched_group *sg;
7678 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7679 tmpmask);
7680 init_numa_sched_groups_power(sg);
7682 #endif
7684 /* Attach the domains */
7685 for_each_cpu_mask(i, *cpu_map) {
7686 struct sched_domain *sd;
7687 #ifdef CONFIG_SCHED_SMT
7688 sd = &per_cpu(cpu_domains, i);
7689 #elif defined(CONFIG_SCHED_MC)
7690 sd = &per_cpu(core_domains, i);
7691 #else
7692 sd = &per_cpu(phys_domains, i);
7693 #endif
7694 cpu_attach_domain(sd, rd, i);
7697 SCHED_CPUMASK_FREE((void *)allmasks);
7698 return 0;
7700 #ifdef CONFIG_NUMA
7701 error:
7702 free_sched_groups(cpu_map, tmpmask);
7703 SCHED_CPUMASK_FREE((void *)allmasks);
7704 return -ENOMEM;
7705 #endif
7708 static int build_sched_domains(const cpumask_t *cpu_map)
7710 return __build_sched_domains(cpu_map, NULL);
7713 static cpumask_t *doms_cur; /* current sched domains */
7714 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7715 static struct sched_domain_attr *dattr_cur; /* attribues of custom domains
7716 in 'doms_cur' */
7719 * Special case: If a kmalloc of a doms_cur partition (array of
7720 * cpumask_t) fails, then fallback to a single sched domain,
7721 * as determined by the single cpumask_t fallback_doms.
7723 static cpumask_t fallback_doms;
7725 void __attribute__((weak)) arch_update_cpu_topology(void)
7730 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7731 * For now this just excludes isolated cpus, but could be used to
7732 * exclude other special cases in the future.
7734 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7736 int err;
7738 arch_update_cpu_topology();
7739 ndoms_cur = 1;
7740 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7741 if (!doms_cur)
7742 doms_cur = &fallback_doms;
7743 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7744 dattr_cur = NULL;
7745 err = build_sched_domains(doms_cur);
7746 register_sched_domain_sysctl();
7748 return err;
7751 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7752 cpumask_t *tmpmask)
7754 free_sched_groups(cpu_map, tmpmask);
7758 * Detach sched domains from a group of cpus specified in cpu_map
7759 * These cpus will now be attached to the NULL domain
7761 static void detach_destroy_domains(const cpumask_t *cpu_map)
7763 cpumask_t tmpmask;
7764 int i;
7766 unregister_sched_domain_sysctl();
7768 for_each_cpu_mask(i, *cpu_map)
7769 cpu_attach_domain(NULL, &def_root_domain, i);
7770 synchronize_sched();
7771 arch_destroy_sched_domains(cpu_map, &tmpmask);
7774 /* handle null as "default" */
7775 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7776 struct sched_domain_attr *new, int idx_new)
7778 struct sched_domain_attr tmp;
7780 /* fast path */
7781 if (!new && !cur)
7782 return 1;
7784 tmp = SD_ATTR_INIT;
7785 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7786 new ? (new + idx_new) : &tmp,
7787 sizeof(struct sched_domain_attr));
7791 * Partition sched domains as specified by the 'ndoms_new'
7792 * cpumasks in the array doms_new[] of cpumasks. This compares
7793 * doms_new[] to the current sched domain partitioning, doms_cur[].
7794 * It destroys each deleted domain and builds each new domain.
7796 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7797 * The masks don't intersect (don't overlap.) We should setup one
7798 * sched domain for each mask. CPUs not in any of the cpumasks will
7799 * not be load balanced. If the same cpumask appears both in the
7800 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7801 * it as it is.
7803 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7804 * ownership of it and will kfree it when done with it. If the caller
7805 * failed the kmalloc call, then it can pass in doms_new == NULL,
7806 * and partition_sched_domains() will fallback to the single partition
7807 * 'fallback_doms'.
7809 * Call with hotplug lock held
7811 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7812 struct sched_domain_attr *dattr_new)
7814 int i, j;
7816 mutex_lock(&sched_domains_mutex);
7818 /* always unregister in case we don't destroy any domains */
7819 unregister_sched_domain_sysctl();
7821 if (doms_new == NULL) {
7822 ndoms_new = 1;
7823 doms_new = &fallback_doms;
7824 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7825 dattr_new = NULL;
7828 /* Destroy deleted domains */
7829 for (i = 0; i < ndoms_cur; i++) {
7830 for (j = 0; j < ndoms_new; j++) {
7831 if (cpus_equal(doms_cur[i], doms_new[j])
7832 && dattrs_equal(dattr_cur, i, dattr_new, j))
7833 goto match1;
7835 /* no match - a current sched domain not in new doms_new[] */
7836 detach_destroy_domains(doms_cur + i);
7837 match1:
7841 /* Build new domains */
7842 for (i = 0; i < ndoms_new; i++) {
7843 for (j = 0; j < ndoms_cur; j++) {
7844 if (cpus_equal(doms_new[i], doms_cur[j])
7845 && dattrs_equal(dattr_new, i, dattr_cur, j))
7846 goto match2;
7848 /* no match - add a new doms_new */
7849 __build_sched_domains(doms_new + i,
7850 dattr_new ? dattr_new + i : NULL);
7851 match2:
7855 /* Remember the new sched domains */
7856 if (doms_cur != &fallback_doms)
7857 kfree(doms_cur);
7858 kfree(dattr_cur); /* kfree(NULL) is safe */
7859 doms_cur = doms_new;
7860 dattr_cur = dattr_new;
7861 ndoms_cur = ndoms_new;
7863 register_sched_domain_sysctl();
7865 mutex_unlock(&sched_domains_mutex);
7868 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7869 int arch_reinit_sched_domains(void)
7871 int err;
7873 get_online_cpus();
7874 mutex_lock(&sched_domains_mutex);
7875 detach_destroy_domains(&cpu_online_map);
7876 err = arch_init_sched_domains(&cpu_online_map);
7877 mutex_unlock(&sched_domains_mutex);
7878 put_online_cpus();
7880 return err;
7883 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7885 int ret;
7887 if (buf[0] != '0' && buf[0] != '1')
7888 return -EINVAL;
7890 if (smt)
7891 sched_smt_power_savings = (buf[0] == '1');
7892 else
7893 sched_mc_power_savings = (buf[0] == '1');
7895 ret = arch_reinit_sched_domains();
7897 return ret ? ret : count;
7900 #ifdef CONFIG_SCHED_MC
7901 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7903 return sprintf(page, "%u\n", sched_mc_power_savings);
7905 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7906 const char *buf, size_t count)
7908 return sched_power_savings_store(buf, count, 0);
7910 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7911 sched_mc_power_savings_store);
7912 #endif
7914 #ifdef CONFIG_SCHED_SMT
7915 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7917 return sprintf(page, "%u\n", sched_smt_power_savings);
7919 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7920 const char *buf, size_t count)
7922 return sched_power_savings_store(buf, count, 1);
7924 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7925 sched_smt_power_savings_store);
7926 #endif
7928 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7930 int err = 0;
7932 #ifdef CONFIG_SCHED_SMT
7933 if (smt_capable())
7934 err = sysfs_create_file(&cls->kset.kobj,
7935 &attr_sched_smt_power_savings.attr);
7936 #endif
7937 #ifdef CONFIG_SCHED_MC
7938 if (!err && mc_capable())
7939 err = sysfs_create_file(&cls->kset.kobj,
7940 &attr_sched_mc_power_savings.attr);
7941 #endif
7942 return err;
7944 #endif
7947 * Force a reinitialization of the sched domains hierarchy. The domains
7948 * and groups cannot be updated in place without racing with the balancing
7949 * code, so we temporarily attach all running cpus to the NULL domain
7950 * which will prevent rebalancing while the sched domains are recalculated.
7952 static int update_sched_domains(struct notifier_block *nfb,
7953 unsigned long action, void *hcpu)
7955 switch (action) {
7956 case CPU_UP_PREPARE:
7957 case CPU_UP_PREPARE_FROZEN:
7958 case CPU_DOWN_PREPARE:
7959 case CPU_DOWN_PREPARE_FROZEN:
7960 detach_destroy_domains(&cpu_online_map);
7961 return NOTIFY_OK;
7963 case CPU_UP_CANCELED:
7964 case CPU_UP_CANCELED_FROZEN:
7965 case CPU_DOWN_FAILED:
7966 case CPU_DOWN_FAILED_FROZEN:
7967 case CPU_ONLINE:
7968 case CPU_ONLINE_FROZEN:
7969 case CPU_DEAD:
7970 case CPU_DEAD_FROZEN:
7972 * Fall through and re-initialise the domains.
7974 break;
7975 default:
7976 return NOTIFY_DONE;
7979 /* The hotplug lock is already held by cpu_up/cpu_down */
7980 arch_init_sched_domains(&cpu_online_map);
7982 return NOTIFY_OK;
7985 void __init sched_init_smp(void)
7987 cpumask_t non_isolated_cpus;
7989 #if defined(CONFIG_NUMA)
7990 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7991 GFP_KERNEL);
7992 BUG_ON(sched_group_nodes_bycpu == NULL);
7993 #endif
7994 get_online_cpus();
7995 mutex_lock(&sched_domains_mutex);
7996 arch_init_sched_domains(&cpu_online_map);
7997 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7998 if (cpus_empty(non_isolated_cpus))
7999 cpu_set(smp_processor_id(), non_isolated_cpus);
8000 mutex_unlock(&sched_domains_mutex);
8001 put_online_cpus();
8002 /* XXX: Theoretical race here - CPU may be hotplugged now */
8003 hotcpu_notifier(update_sched_domains, 0);
8004 init_hrtick();
8006 /* Move init over to a non-isolated CPU */
8007 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
8008 BUG();
8009 sched_init_granularity();
8011 #else
8012 void __init sched_init_smp(void)
8014 sched_init_granularity();
8016 #endif /* CONFIG_SMP */
8018 int in_sched_functions(unsigned long addr)
8020 return in_lock_functions(addr) ||
8021 (addr >= (unsigned long)__sched_text_start
8022 && addr < (unsigned long)__sched_text_end);
8025 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8027 cfs_rq->tasks_timeline = RB_ROOT;
8028 INIT_LIST_HEAD(&cfs_rq->tasks);
8029 #ifdef CONFIG_FAIR_GROUP_SCHED
8030 cfs_rq->rq = rq;
8031 #endif
8032 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8035 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8037 struct rt_prio_array *array;
8038 int i;
8040 array = &rt_rq->active;
8041 for (i = 0; i < MAX_RT_PRIO; i++) {
8042 INIT_LIST_HEAD(array->queue + i);
8043 __clear_bit(i, array->bitmap);
8045 /* delimiter for bitsearch: */
8046 __set_bit(MAX_RT_PRIO, array->bitmap);
8048 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8049 rt_rq->highest_prio = MAX_RT_PRIO;
8050 #endif
8051 #ifdef CONFIG_SMP
8052 rt_rq->rt_nr_migratory = 0;
8053 rt_rq->overloaded = 0;
8054 #endif
8056 rt_rq->rt_time = 0;
8057 rt_rq->rt_throttled = 0;
8058 rt_rq->rt_runtime = 0;
8059 spin_lock_init(&rt_rq->rt_runtime_lock);
8061 #ifdef CONFIG_RT_GROUP_SCHED
8062 rt_rq->rt_nr_boosted = 0;
8063 rt_rq->rq = rq;
8064 #endif
8067 #ifdef CONFIG_FAIR_GROUP_SCHED
8068 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8069 struct sched_entity *se, int cpu, int add,
8070 struct sched_entity *parent)
8072 struct rq *rq = cpu_rq(cpu);
8073 tg->cfs_rq[cpu] = cfs_rq;
8074 init_cfs_rq(cfs_rq, rq);
8075 cfs_rq->tg = tg;
8076 if (add)
8077 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8079 tg->se[cpu] = se;
8080 /* se could be NULL for init_task_group */
8081 if (!se)
8082 return;
8084 if (!parent)
8085 se->cfs_rq = &rq->cfs;
8086 else
8087 se->cfs_rq = parent->my_q;
8089 se->my_q = cfs_rq;
8090 se->load.weight = tg->shares;
8091 se->load.inv_weight = 0;
8092 se->parent = parent;
8094 #endif
8096 #ifdef CONFIG_RT_GROUP_SCHED
8097 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8098 struct sched_rt_entity *rt_se, int cpu, int add,
8099 struct sched_rt_entity *parent)
8101 struct rq *rq = cpu_rq(cpu);
8103 tg->rt_rq[cpu] = rt_rq;
8104 init_rt_rq(rt_rq, rq);
8105 rt_rq->tg = tg;
8106 rt_rq->rt_se = rt_se;
8107 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8108 if (add)
8109 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8111 tg->rt_se[cpu] = rt_se;
8112 if (!rt_se)
8113 return;
8115 if (!parent)
8116 rt_se->rt_rq = &rq->rt;
8117 else
8118 rt_se->rt_rq = parent->my_q;
8120 rt_se->rt_rq = &rq->rt;
8121 rt_se->my_q = rt_rq;
8122 rt_se->parent = parent;
8123 INIT_LIST_HEAD(&rt_se->run_list);
8125 #endif
8127 void __init sched_init(void)
8129 int i, j;
8130 unsigned long alloc_size = 0, ptr;
8132 #ifdef CONFIG_FAIR_GROUP_SCHED
8133 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8134 #endif
8135 #ifdef CONFIG_RT_GROUP_SCHED
8136 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8137 #endif
8138 #ifdef CONFIG_USER_SCHED
8139 alloc_size *= 2;
8140 #endif
8142 * As sched_init() is called before page_alloc is setup,
8143 * we use alloc_bootmem().
8145 if (alloc_size) {
8146 ptr = (unsigned long)alloc_bootmem(alloc_size);
8148 #ifdef CONFIG_FAIR_GROUP_SCHED
8149 init_task_group.se = (struct sched_entity **)ptr;
8150 ptr += nr_cpu_ids * sizeof(void **);
8152 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8153 ptr += nr_cpu_ids * sizeof(void **);
8155 #ifdef CONFIG_USER_SCHED
8156 root_task_group.se = (struct sched_entity **)ptr;
8157 ptr += nr_cpu_ids * sizeof(void **);
8159 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8160 ptr += nr_cpu_ids * sizeof(void **);
8161 #endif
8162 #endif
8163 #ifdef CONFIG_RT_GROUP_SCHED
8164 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8165 ptr += nr_cpu_ids * sizeof(void **);
8167 init_task_group.rt_rq = (struct rt_rq **)ptr;
8168 ptr += nr_cpu_ids * sizeof(void **);
8170 #ifdef CONFIG_USER_SCHED
8171 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8172 ptr += nr_cpu_ids * sizeof(void **);
8174 root_task_group.rt_rq = (struct rt_rq **)ptr;
8175 ptr += nr_cpu_ids * sizeof(void **);
8176 #endif
8177 #endif
8180 #ifdef CONFIG_SMP
8181 init_aggregate();
8182 init_defrootdomain();
8183 #endif
8185 init_rt_bandwidth(&def_rt_bandwidth,
8186 global_rt_period(), global_rt_runtime());
8188 #ifdef CONFIG_RT_GROUP_SCHED
8189 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8190 global_rt_period(), global_rt_runtime());
8191 #ifdef CONFIG_USER_SCHED
8192 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8193 global_rt_period(), RUNTIME_INF);
8194 #endif
8195 #endif
8197 #ifdef CONFIG_GROUP_SCHED
8198 list_add(&init_task_group.list, &task_groups);
8199 INIT_LIST_HEAD(&init_task_group.children);
8201 #ifdef CONFIG_USER_SCHED
8202 INIT_LIST_HEAD(&root_task_group.children);
8203 init_task_group.parent = &root_task_group;
8204 list_add(&init_task_group.siblings, &root_task_group.children);
8205 #endif
8206 #endif
8208 for_each_possible_cpu(i) {
8209 struct rq *rq;
8211 rq = cpu_rq(i);
8212 spin_lock_init(&rq->lock);
8213 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
8214 rq->nr_running = 0;
8215 rq->clock = 1;
8216 update_last_tick_seen(rq);
8217 init_cfs_rq(&rq->cfs, rq);
8218 init_rt_rq(&rq->rt, rq);
8219 #ifdef CONFIG_FAIR_GROUP_SCHED
8220 init_task_group.shares = init_task_group_load;
8221 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8222 #ifdef CONFIG_CGROUP_SCHED
8224 * How much cpu bandwidth does init_task_group get?
8226 * In case of task-groups formed thr' the cgroup filesystem, it
8227 * gets 100% of the cpu resources in the system. This overall
8228 * system cpu resource is divided among the tasks of
8229 * init_task_group and its child task-groups in a fair manner,
8230 * based on each entity's (task or task-group's) weight
8231 * (se->load.weight).
8233 * In other words, if init_task_group has 10 tasks of weight
8234 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8235 * then A0's share of the cpu resource is:
8237 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8239 * We achieve this by letting init_task_group's tasks sit
8240 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8242 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8243 #elif defined CONFIG_USER_SCHED
8244 root_task_group.shares = NICE_0_LOAD;
8245 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8247 * In case of task-groups formed thr' the user id of tasks,
8248 * init_task_group represents tasks belonging to root user.
8249 * Hence it forms a sibling of all subsequent groups formed.
8250 * In this case, init_task_group gets only a fraction of overall
8251 * system cpu resource, based on the weight assigned to root
8252 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8253 * by letting tasks of init_task_group sit in a separate cfs_rq
8254 * (init_cfs_rq) and having one entity represent this group of
8255 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8257 init_tg_cfs_entry(&init_task_group,
8258 &per_cpu(init_cfs_rq, i),
8259 &per_cpu(init_sched_entity, i), i, 1,
8260 root_task_group.se[i]);
8262 #endif
8263 #endif /* CONFIG_FAIR_GROUP_SCHED */
8265 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8266 #ifdef CONFIG_RT_GROUP_SCHED
8267 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8268 #ifdef CONFIG_CGROUP_SCHED
8269 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8270 #elif defined CONFIG_USER_SCHED
8271 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8272 init_tg_rt_entry(&init_task_group,
8273 &per_cpu(init_rt_rq, i),
8274 &per_cpu(init_sched_rt_entity, i), i, 1,
8275 root_task_group.rt_se[i]);
8276 #endif
8277 #endif
8279 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8280 rq->cpu_load[j] = 0;
8281 #ifdef CONFIG_SMP
8282 rq->sd = NULL;
8283 rq->rd = NULL;
8284 rq->active_balance = 0;
8285 rq->next_balance = jiffies;
8286 rq->push_cpu = 0;
8287 rq->cpu = i;
8288 rq->migration_thread = NULL;
8289 INIT_LIST_HEAD(&rq->migration_queue);
8290 rq_attach_root(rq, &def_root_domain);
8291 #endif
8292 init_rq_hrtick(rq);
8293 atomic_set(&rq->nr_iowait, 0);
8296 set_load_weight(&init_task);
8298 #ifdef CONFIG_PREEMPT_NOTIFIERS
8299 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8300 #endif
8302 #ifdef CONFIG_SMP
8303 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
8304 #endif
8306 #ifdef CONFIG_RT_MUTEXES
8307 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8308 #endif
8311 * The boot idle thread does lazy MMU switching as well:
8313 atomic_inc(&init_mm.mm_count);
8314 enter_lazy_tlb(&init_mm, current);
8317 * Make us the idle thread. Technically, schedule() should not be
8318 * called from this thread, however somewhere below it might be,
8319 * but because we are the idle thread, we just pick up running again
8320 * when this runqueue becomes "idle".
8322 init_idle(current, smp_processor_id());
8324 * During early bootup we pretend to be a normal task:
8326 current->sched_class = &fair_sched_class;
8328 scheduler_running = 1;
8331 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8332 void __might_sleep(char *file, int line)
8334 #ifdef in_atomic
8335 static unsigned long prev_jiffy; /* ratelimiting */
8337 if ((in_atomic() || irqs_disabled()) &&
8338 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8339 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8340 return;
8341 prev_jiffy = jiffies;
8342 printk(KERN_ERR "BUG: sleeping function called from invalid"
8343 " context at %s:%d\n", file, line);
8344 printk("in_atomic():%d, irqs_disabled():%d\n",
8345 in_atomic(), irqs_disabled());
8346 debug_show_held_locks(current);
8347 if (irqs_disabled())
8348 print_irqtrace_events(current);
8349 dump_stack();
8351 #endif
8353 EXPORT_SYMBOL(__might_sleep);
8354 #endif
8356 #ifdef CONFIG_MAGIC_SYSRQ
8357 static void normalize_task(struct rq *rq, struct task_struct *p)
8359 int on_rq;
8360 update_rq_clock(rq);
8361 on_rq = p->se.on_rq;
8362 if (on_rq)
8363 deactivate_task(rq, p, 0);
8364 __setscheduler(rq, p, SCHED_NORMAL, 0);
8365 if (on_rq) {
8366 activate_task(rq, p, 0);
8367 resched_task(rq->curr);
8371 void normalize_rt_tasks(void)
8373 struct task_struct *g, *p;
8374 unsigned long flags;
8375 struct rq *rq;
8377 read_lock_irqsave(&tasklist_lock, flags);
8378 do_each_thread(g, p) {
8380 * Only normalize user tasks:
8382 if (!p->mm)
8383 continue;
8385 p->se.exec_start = 0;
8386 #ifdef CONFIG_SCHEDSTATS
8387 p->se.wait_start = 0;
8388 p->se.sleep_start = 0;
8389 p->se.block_start = 0;
8390 #endif
8391 task_rq(p)->clock = 0;
8393 if (!rt_task(p)) {
8395 * Renice negative nice level userspace
8396 * tasks back to 0:
8398 if (TASK_NICE(p) < 0 && p->mm)
8399 set_user_nice(p, 0);
8400 continue;
8403 spin_lock(&p->pi_lock);
8404 rq = __task_rq_lock(p);
8406 normalize_task(rq, p);
8408 __task_rq_unlock(rq);
8409 spin_unlock(&p->pi_lock);
8410 } while_each_thread(g, p);
8412 read_unlock_irqrestore(&tasklist_lock, flags);
8415 #endif /* CONFIG_MAGIC_SYSRQ */
8417 #ifdef CONFIG_IA64
8419 * These functions are only useful for the IA64 MCA handling.
8421 * They can only be called when the whole system has been
8422 * stopped - every CPU needs to be quiescent, and no scheduling
8423 * activity can take place. Using them for anything else would
8424 * be a serious bug, and as a result, they aren't even visible
8425 * under any other configuration.
8429 * curr_task - return the current task for a given cpu.
8430 * @cpu: the processor in question.
8432 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8434 struct task_struct *curr_task(int cpu)
8436 return cpu_curr(cpu);
8440 * set_curr_task - set the current task for a given cpu.
8441 * @cpu: the processor in question.
8442 * @p: the task pointer to set.
8444 * Description: This function must only be used when non-maskable interrupts
8445 * are serviced on a separate stack. It allows the architecture to switch the
8446 * notion of the current task on a cpu in a non-blocking manner. This function
8447 * must be called with all CPU's synchronized, and interrupts disabled, the
8448 * and caller must save the original value of the current task (see
8449 * curr_task() above) and restore that value before reenabling interrupts and
8450 * re-starting the system.
8452 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8454 void set_curr_task(int cpu, struct task_struct *p)
8456 cpu_curr(cpu) = p;
8459 #endif
8461 #ifdef CONFIG_FAIR_GROUP_SCHED
8462 static void free_fair_sched_group(struct task_group *tg)
8464 int i;
8466 for_each_possible_cpu(i) {
8467 if (tg->cfs_rq)
8468 kfree(tg->cfs_rq[i]);
8469 if (tg->se)
8470 kfree(tg->se[i]);
8473 kfree(tg->cfs_rq);
8474 kfree(tg->se);
8477 static
8478 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8480 struct cfs_rq *cfs_rq;
8481 struct sched_entity *se, *parent_se;
8482 struct rq *rq;
8483 int i;
8485 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8486 if (!tg->cfs_rq)
8487 goto err;
8488 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8489 if (!tg->se)
8490 goto err;
8492 tg->shares = NICE_0_LOAD;
8494 for_each_possible_cpu(i) {
8495 rq = cpu_rq(i);
8497 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8498 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8499 if (!cfs_rq)
8500 goto err;
8502 se = kmalloc_node(sizeof(struct sched_entity),
8503 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8504 if (!se)
8505 goto err;
8507 parent_se = parent ? parent->se[i] : NULL;
8508 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8511 return 1;
8513 err:
8514 return 0;
8517 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8519 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8520 &cpu_rq(cpu)->leaf_cfs_rq_list);
8523 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8525 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8527 #else
8528 static inline void free_fair_sched_group(struct task_group *tg)
8532 static inline
8533 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8535 return 1;
8538 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8542 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8545 #endif
8547 #ifdef CONFIG_RT_GROUP_SCHED
8548 static void free_rt_sched_group(struct task_group *tg)
8550 int i;
8552 destroy_rt_bandwidth(&tg->rt_bandwidth);
8554 for_each_possible_cpu(i) {
8555 if (tg->rt_rq)
8556 kfree(tg->rt_rq[i]);
8557 if (tg->rt_se)
8558 kfree(tg->rt_se[i]);
8561 kfree(tg->rt_rq);
8562 kfree(tg->rt_se);
8565 static
8566 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8568 struct rt_rq *rt_rq;
8569 struct sched_rt_entity *rt_se, *parent_se;
8570 struct rq *rq;
8571 int i;
8573 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8574 if (!tg->rt_rq)
8575 goto err;
8576 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8577 if (!tg->rt_se)
8578 goto err;
8580 init_rt_bandwidth(&tg->rt_bandwidth,
8581 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8583 for_each_possible_cpu(i) {
8584 rq = cpu_rq(i);
8586 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8587 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8588 if (!rt_rq)
8589 goto err;
8591 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8592 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8593 if (!rt_se)
8594 goto err;
8596 parent_se = parent ? parent->rt_se[i] : NULL;
8597 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8600 return 1;
8602 err:
8603 return 0;
8606 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8608 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8609 &cpu_rq(cpu)->leaf_rt_rq_list);
8612 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8614 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8616 #else
8617 static inline void free_rt_sched_group(struct task_group *tg)
8621 static inline
8622 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8624 return 1;
8627 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8631 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8634 #endif
8636 #ifdef CONFIG_GROUP_SCHED
8637 static void free_sched_group(struct task_group *tg)
8639 free_fair_sched_group(tg);
8640 free_rt_sched_group(tg);
8641 kfree(tg);
8644 /* allocate runqueue etc for a new task group */
8645 struct task_group *sched_create_group(struct task_group *parent)
8647 struct task_group *tg;
8648 unsigned long flags;
8649 int i;
8651 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8652 if (!tg)
8653 return ERR_PTR(-ENOMEM);
8655 if (!alloc_fair_sched_group(tg, parent))
8656 goto err;
8658 if (!alloc_rt_sched_group(tg, parent))
8659 goto err;
8661 spin_lock_irqsave(&task_group_lock, flags);
8662 for_each_possible_cpu(i) {
8663 register_fair_sched_group(tg, i);
8664 register_rt_sched_group(tg, i);
8666 list_add_rcu(&tg->list, &task_groups);
8668 WARN_ON(!parent); /* root should already exist */
8670 tg->parent = parent;
8671 list_add_rcu(&tg->siblings, &parent->children);
8672 INIT_LIST_HEAD(&tg->children);
8673 spin_unlock_irqrestore(&task_group_lock, flags);
8675 return tg;
8677 err:
8678 free_sched_group(tg);
8679 return ERR_PTR(-ENOMEM);
8682 /* rcu callback to free various structures associated with a task group */
8683 static void free_sched_group_rcu(struct rcu_head *rhp)
8685 /* now it should be safe to free those cfs_rqs */
8686 free_sched_group(container_of(rhp, struct task_group, rcu));
8689 /* Destroy runqueue etc associated with a task group */
8690 void sched_destroy_group(struct task_group *tg)
8692 unsigned long flags;
8693 int i;
8695 spin_lock_irqsave(&task_group_lock, flags);
8696 for_each_possible_cpu(i) {
8697 unregister_fair_sched_group(tg, i);
8698 unregister_rt_sched_group(tg, i);
8700 list_del_rcu(&tg->list);
8701 list_del_rcu(&tg->siblings);
8702 spin_unlock_irqrestore(&task_group_lock, flags);
8704 /* wait for possible concurrent references to cfs_rqs complete */
8705 call_rcu(&tg->rcu, free_sched_group_rcu);
8708 /* change task's runqueue when it moves between groups.
8709 * The caller of this function should have put the task in its new group
8710 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8711 * reflect its new group.
8713 void sched_move_task(struct task_struct *tsk)
8715 int on_rq, running;
8716 unsigned long flags;
8717 struct rq *rq;
8719 rq = task_rq_lock(tsk, &flags);
8721 update_rq_clock(rq);
8723 running = task_current(rq, tsk);
8724 on_rq = tsk->se.on_rq;
8726 if (on_rq)
8727 dequeue_task(rq, tsk, 0);
8728 if (unlikely(running))
8729 tsk->sched_class->put_prev_task(rq, tsk);
8731 set_task_rq(tsk, task_cpu(tsk));
8733 #ifdef CONFIG_FAIR_GROUP_SCHED
8734 if (tsk->sched_class->moved_group)
8735 tsk->sched_class->moved_group(tsk);
8736 #endif
8738 if (unlikely(running))
8739 tsk->sched_class->set_curr_task(rq);
8740 if (on_rq)
8741 enqueue_task(rq, tsk, 0);
8743 task_rq_unlock(rq, &flags);
8745 #endif
8747 #ifdef CONFIG_FAIR_GROUP_SCHED
8748 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8750 struct cfs_rq *cfs_rq = se->cfs_rq;
8751 int on_rq;
8753 on_rq = se->on_rq;
8754 if (on_rq)
8755 dequeue_entity(cfs_rq, se, 0);
8757 se->load.weight = shares;
8758 se->load.inv_weight = 0;
8760 if (on_rq)
8761 enqueue_entity(cfs_rq, se, 0);
8764 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8766 struct cfs_rq *cfs_rq = se->cfs_rq;
8767 struct rq *rq = cfs_rq->rq;
8768 unsigned long flags;
8770 spin_lock_irqsave(&rq->lock, flags);
8771 __set_se_shares(se, shares);
8772 spin_unlock_irqrestore(&rq->lock, flags);
8775 static DEFINE_MUTEX(shares_mutex);
8777 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8779 int i;
8780 unsigned long flags;
8783 * We can't change the weight of the root cgroup.
8785 if (!tg->se[0])
8786 return -EINVAL;
8789 * A weight of 0 or 1 can cause arithmetics problems.
8790 * (The default weight is 1024 - so there's no practical
8791 * limitation from this.)
8793 if (shares < MIN_SHARES)
8794 shares = MIN_SHARES;
8796 mutex_lock(&shares_mutex);
8797 if (tg->shares == shares)
8798 goto done;
8800 spin_lock_irqsave(&task_group_lock, flags);
8801 for_each_possible_cpu(i)
8802 unregister_fair_sched_group(tg, i);
8803 list_del_rcu(&tg->siblings);
8804 spin_unlock_irqrestore(&task_group_lock, flags);
8806 /* wait for any ongoing reference to this group to finish */
8807 synchronize_sched();
8810 * Now we are free to modify the group's share on each cpu
8811 * w/o tripping rebalance_share or load_balance_fair.
8813 tg->shares = shares;
8814 for_each_possible_cpu(i) {
8816 * force a rebalance
8818 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8819 set_se_shares(tg->se[i], shares/nr_cpu_ids);
8823 * Enable load balance activity on this group, by inserting it back on
8824 * each cpu's rq->leaf_cfs_rq_list.
8826 spin_lock_irqsave(&task_group_lock, flags);
8827 for_each_possible_cpu(i)
8828 register_fair_sched_group(tg, i);
8829 list_add_rcu(&tg->siblings, &tg->parent->children);
8830 spin_unlock_irqrestore(&task_group_lock, flags);
8831 done:
8832 mutex_unlock(&shares_mutex);
8833 return 0;
8836 unsigned long sched_group_shares(struct task_group *tg)
8838 return tg->shares;
8840 #endif
8842 #ifdef CONFIG_RT_GROUP_SCHED
8844 * Ensure that the real time constraints are schedulable.
8846 static DEFINE_MUTEX(rt_constraints_mutex);
8848 static unsigned long to_ratio(u64 period, u64 runtime)
8850 if (runtime == RUNTIME_INF)
8851 return 1ULL << 16;
8853 return div64_u64(runtime << 16, period);
8856 #ifdef CONFIG_CGROUP_SCHED
8857 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8859 struct task_group *tgi, *parent = tg->parent;
8860 unsigned long total = 0;
8862 if (!parent) {
8863 if (global_rt_period() < period)
8864 return 0;
8866 return to_ratio(period, runtime) <
8867 to_ratio(global_rt_period(), global_rt_runtime());
8870 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8871 return 0;
8873 rcu_read_lock();
8874 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8875 if (tgi == tg)
8876 continue;
8878 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8879 tgi->rt_bandwidth.rt_runtime);
8881 rcu_read_unlock();
8883 return total + to_ratio(period, runtime) <
8884 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8885 parent->rt_bandwidth.rt_runtime);
8887 #elif defined CONFIG_USER_SCHED
8888 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8890 struct task_group *tgi;
8891 unsigned long total = 0;
8892 unsigned long global_ratio =
8893 to_ratio(global_rt_period(), global_rt_runtime());
8895 rcu_read_lock();
8896 list_for_each_entry_rcu(tgi, &task_groups, list) {
8897 if (tgi == tg)
8898 continue;
8900 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8901 tgi->rt_bandwidth.rt_runtime);
8903 rcu_read_unlock();
8905 return total + to_ratio(period, runtime) < global_ratio;
8907 #endif
8909 /* Must be called with tasklist_lock held */
8910 static inline int tg_has_rt_tasks(struct task_group *tg)
8912 struct task_struct *g, *p;
8913 do_each_thread(g, p) {
8914 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8915 return 1;
8916 } while_each_thread(g, p);
8917 return 0;
8920 static int tg_set_bandwidth(struct task_group *tg,
8921 u64 rt_period, u64 rt_runtime)
8923 int i, err = 0;
8925 mutex_lock(&rt_constraints_mutex);
8926 read_lock(&tasklist_lock);
8927 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8928 err = -EBUSY;
8929 goto unlock;
8931 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8932 err = -EINVAL;
8933 goto unlock;
8936 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8937 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8938 tg->rt_bandwidth.rt_runtime = rt_runtime;
8940 for_each_possible_cpu(i) {
8941 struct rt_rq *rt_rq = tg->rt_rq[i];
8943 spin_lock(&rt_rq->rt_runtime_lock);
8944 rt_rq->rt_runtime = rt_runtime;
8945 spin_unlock(&rt_rq->rt_runtime_lock);
8947 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8948 unlock:
8949 read_unlock(&tasklist_lock);
8950 mutex_unlock(&rt_constraints_mutex);
8952 return err;
8955 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8957 u64 rt_runtime, rt_period;
8959 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8960 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8961 if (rt_runtime_us < 0)
8962 rt_runtime = RUNTIME_INF;
8964 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8967 long sched_group_rt_runtime(struct task_group *tg)
8969 u64 rt_runtime_us;
8971 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8972 return -1;
8974 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8975 do_div(rt_runtime_us, NSEC_PER_USEC);
8976 return rt_runtime_us;
8979 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8981 u64 rt_runtime, rt_period;
8983 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8984 rt_runtime = tg->rt_bandwidth.rt_runtime;
8986 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8989 long sched_group_rt_period(struct task_group *tg)
8991 u64 rt_period_us;
8993 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8994 do_div(rt_period_us, NSEC_PER_USEC);
8995 return rt_period_us;
8998 static int sched_rt_global_constraints(void)
9000 int ret = 0;
9002 mutex_lock(&rt_constraints_mutex);
9003 if (!__rt_schedulable(NULL, 1, 0))
9004 ret = -EINVAL;
9005 mutex_unlock(&rt_constraints_mutex);
9007 return ret;
9009 #else
9010 static int sched_rt_global_constraints(void)
9012 unsigned long flags;
9013 int i;
9015 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9016 for_each_possible_cpu(i) {
9017 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9019 spin_lock(&rt_rq->rt_runtime_lock);
9020 rt_rq->rt_runtime = global_rt_runtime();
9021 spin_unlock(&rt_rq->rt_runtime_lock);
9023 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9025 return 0;
9027 #endif
9029 int sched_rt_handler(struct ctl_table *table, int write,
9030 struct file *filp, void __user *buffer, size_t *lenp,
9031 loff_t *ppos)
9033 int ret;
9034 int old_period, old_runtime;
9035 static DEFINE_MUTEX(mutex);
9037 mutex_lock(&mutex);
9038 old_period = sysctl_sched_rt_period;
9039 old_runtime = sysctl_sched_rt_runtime;
9041 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9043 if (!ret && write) {
9044 ret = sched_rt_global_constraints();
9045 if (ret) {
9046 sysctl_sched_rt_period = old_period;
9047 sysctl_sched_rt_runtime = old_runtime;
9048 } else {
9049 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9050 def_rt_bandwidth.rt_period =
9051 ns_to_ktime(global_rt_period());
9054 mutex_unlock(&mutex);
9056 return ret;
9059 #ifdef CONFIG_CGROUP_SCHED
9061 /* return corresponding task_group object of a cgroup */
9062 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9064 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9065 struct task_group, css);
9068 static struct cgroup_subsys_state *
9069 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9071 struct task_group *tg, *parent;
9073 if (!cgrp->parent) {
9074 /* This is early initialization for the top cgroup */
9075 init_task_group.css.cgroup = cgrp;
9076 return &init_task_group.css;
9079 parent = cgroup_tg(cgrp->parent);
9080 tg = sched_create_group(parent);
9081 if (IS_ERR(tg))
9082 return ERR_PTR(-ENOMEM);
9084 /* Bind the cgroup to task_group object we just created */
9085 tg->css.cgroup = cgrp;
9087 return &tg->css;
9090 static void
9091 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9093 struct task_group *tg = cgroup_tg(cgrp);
9095 sched_destroy_group(tg);
9098 static int
9099 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9100 struct task_struct *tsk)
9102 #ifdef CONFIG_RT_GROUP_SCHED
9103 /* Don't accept realtime tasks when there is no way for them to run */
9104 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9105 return -EINVAL;
9106 #else
9107 /* We don't support RT-tasks being in separate groups */
9108 if (tsk->sched_class != &fair_sched_class)
9109 return -EINVAL;
9110 #endif
9112 return 0;
9115 static void
9116 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9117 struct cgroup *old_cont, struct task_struct *tsk)
9119 sched_move_task(tsk);
9122 #ifdef CONFIG_FAIR_GROUP_SCHED
9123 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9124 u64 shareval)
9126 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9129 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9131 struct task_group *tg = cgroup_tg(cgrp);
9133 return (u64) tg->shares;
9135 #endif
9137 #ifdef CONFIG_RT_GROUP_SCHED
9138 static ssize_t cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9139 s64 val)
9141 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9144 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9146 return sched_group_rt_runtime(cgroup_tg(cgrp));
9149 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9150 u64 rt_period_us)
9152 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9155 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9157 return sched_group_rt_period(cgroup_tg(cgrp));
9159 #endif
9161 static struct cftype cpu_files[] = {
9162 #ifdef CONFIG_FAIR_GROUP_SCHED
9164 .name = "shares",
9165 .read_u64 = cpu_shares_read_u64,
9166 .write_u64 = cpu_shares_write_u64,
9168 #endif
9169 #ifdef CONFIG_RT_GROUP_SCHED
9171 .name = "rt_runtime_us",
9172 .read_s64 = cpu_rt_runtime_read,
9173 .write_s64 = cpu_rt_runtime_write,
9176 .name = "rt_period_us",
9177 .read_u64 = cpu_rt_period_read_uint,
9178 .write_u64 = cpu_rt_period_write_uint,
9180 #endif
9183 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9185 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9188 struct cgroup_subsys cpu_cgroup_subsys = {
9189 .name = "cpu",
9190 .create = cpu_cgroup_create,
9191 .destroy = cpu_cgroup_destroy,
9192 .can_attach = cpu_cgroup_can_attach,
9193 .attach = cpu_cgroup_attach,
9194 .populate = cpu_cgroup_populate,
9195 .subsys_id = cpu_cgroup_subsys_id,
9196 .early_init = 1,
9199 #endif /* CONFIG_CGROUP_SCHED */
9201 #ifdef CONFIG_CGROUP_CPUACCT
9204 * CPU accounting code for task groups.
9206 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9207 * (balbir@in.ibm.com).
9210 /* track cpu usage of a group of tasks */
9211 struct cpuacct {
9212 struct cgroup_subsys_state css;
9213 /* cpuusage holds pointer to a u64-type object on every cpu */
9214 u64 *cpuusage;
9217 struct cgroup_subsys cpuacct_subsys;
9219 /* return cpu accounting group corresponding to this container */
9220 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9222 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9223 struct cpuacct, css);
9226 /* return cpu accounting group to which this task belongs */
9227 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9229 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9230 struct cpuacct, css);
9233 /* create a new cpu accounting group */
9234 static struct cgroup_subsys_state *cpuacct_create(
9235 struct cgroup_subsys *ss, struct cgroup *cgrp)
9237 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9239 if (!ca)
9240 return ERR_PTR(-ENOMEM);
9242 ca->cpuusage = alloc_percpu(u64);
9243 if (!ca->cpuusage) {
9244 kfree(ca);
9245 return ERR_PTR(-ENOMEM);
9248 return &ca->css;
9251 /* destroy an existing cpu accounting group */
9252 static void
9253 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9255 struct cpuacct *ca = cgroup_ca(cgrp);
9257 free_percpu(ca->cpuusage);
9258 kfree(ca);
9261 /* return total cpu usage (in nanoseconds) of a group */
9262 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9264 struct cpuacct *ca = cgroup_ca(cgrp);
9265 u64 totalcpuusage = 0;
9266 int i;
9268 for_each_possible_cpu(i) {
9269 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9272 * Take rq->lock to make 64-bit addition safe on 32-bit
9273 * platforms.
9275 spin_lock_irq(&cpu_rq(i)->lock);
9276 totalcpuusage += *cpuusage;
9277 spin_unlock_irq(&cpu_rq(i)->lock);
9280 return totalcpuusage;
9283 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9284 u64 reset)
9286 struct cpuacct *ca = cgroup_ca(cgrp);
9287 int err = 0;
9288 int i;
9290 if (reset) {
9291 err = -EINVAL;
9292 goto out;
9295 for_each_possible_cpu(i) {
9296 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9298 spin_lock_irq(&cpu_rq(i)->lock);
9299 *cpuusage = 0;
9300 spin_unlock_irq(&cpu_rq(i)->lock);
9302 out:
9303 return err;
9306 static struct cftype files[] = {
9308 .name = "usage",
9309 .read_u64 = cpuusage_read,
9310 .write_u64 = cpuusage_write,
9314 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9316 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9320 * charge this task's execution time to its accounting group.
9322 * called with rq->lock held.
9324 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9326 struct cpuacct *ca;
9328 if (!cpuacct_subsys.active)
9329 return;
9331 ca = task_ca(tsk);
9332 if (ca) {
9333 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9335 *cpuusage += cputime;
9339 struct cgroup_subsys cpuacct_subsys = {
9340 .name = "cpuacct",
9341 .create = cpuacct_create,
9342 .destroy = cpuacct_destroy,
9343 .populate = cpuacct_populate,
9344 .subsys_id = cpuacct_subsys_id,
9346 #endif /* CONFIG_CGROUP_CPUACCT */