sched: fix hrtick_start_fair and CPU-Hotplug
[linux-2.6/mini2440.git] / kernel / sched.c
blobbee9cbe13c1548aec429b298f41f448d3f3266c6
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
245 #ifdef CONFIG_GROUP_SCHED
247 #include <linux/cgroup.h>
249 struct cfs_rq;
251 static LIST_HEAD(task_groups);
253 /* task group related information */
254 struct task_group {
255 #ifdef CONFIG_CGROUP_SCHED
256 struct cgroup_subsys_state css;
257 #endif
259 #ifdef CONFIG_FAIR_GROUP_SCHED
260 /* schedulable entities of this group on each cpu */
261 struct sched_entity **se;
262 /* runqueue "owned" by this group on each cpu */
263 struct cfs_rq **cfs_rq;
264 unsigned long shares;
265 #endif
267 #ifdef CONFIG_RT_GROUP_SCHED
268 struct sched_rt_entity **rt_se;
269 struct rt_rq **rt_rq;
271 struct rt_bandwidth rt_bandwidth;
272 #endif
274 struct rcu_head rcu;
275 struct list_head list;
277 struct task_group *parent;
278 struct list_head siblings;
279 struct list_head children;
282 #ifdef CONFIG_USER_SCHED
285 * Root task group.
286 * Every UID task group (including init_task_group aka UID-0) will
287 * be a child to this group.
289 struct task_group root_task_group;
291 #ifdef CONFIG_FAIR_GROUP_SCHED
292 /* Default task group's sched entity on each cpu */
293 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
294 /* Default task group's cfs_rq on each cpu */
295 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
296 #endif
298 #ifdef CONFIG_RT_GROUP_SCHED
299 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
300 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
301 #endif
302 #else
303 #define root_task_group init_task_group
304 #endif
306 /* task_group_lock serializes add/remove of task groups and also changes to
307 * a task group's cpu shares.
309 static DEFINE_SPINLOCK(task_group_lock);
311 /* doms_cur_mutex serializes access to doms_cur[] array */
312 static DEFINE_MUTEX(doms_cur_mutex);
314 #ifdef CONFIG_FAIR_GROUP_SCHED
315 #ifdef CONFIG_USER_SCHED
316 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
317 #else
318 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
319 #endif
321 #define MIN_SHARES 2
323 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
324 #endif
326 /* Default task group.
327 * Every task in system belong to this group at bootup.
329 struct task_group init_task_group;
331 /* return group to which a task belongs */
332 static inline struct task_group *task_group(struct task_struct *p)
334 struct task_group *tg;
336 #ifdef CONFIG_USER_SCHED
337 tg = p->user->tg;
338 #elif defined(CONFIG_CGROUP_SCHED)
339 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
340 struct task_group, css);
341 #else
342 tg = &init_task_group;
343 #endif
344 return tg;
347 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
348 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
350 #ifdef CONFIG_FAIR_GROUP_SCHED
351 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
352 p->se.parent = task_group(p)->se[cpu];
353 #endif
355 #ifdef CONFIG_RT_GROUP_SCHED
356 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
357 p->rt.parent = task_group(p)->rt_se[cpu];
358 #endif
361 static inline void lock_doms_cur(void)
363 mutex_lock(&doms_cur_mutex);
366 static inline void unlock_doms_cur(void)
368 mutex_unlock(&doms_cur_mutex);
371 #else
373 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
374 static inline void lock_doms_cur(void) { }
375 static inline void unlock_doms_cur(void) { }
377 #endif /* CONFIG_GROUP_SCHED */
379 /* CFS-related fields in a runqueue */
380 struct cfs_rq {
381 struct load_weight load;
382 unsigned long nr_running;
384 u64 exec_clock;
385 u64 min_vruntime;
387 struct rb_root tasks_timeline;
388 struct rb_node *rb_leftmost;
390 struct list_head tasks;
391 struct list_head *balance_iterator;
394 * 'curr' points to currently running entity on this cfs_rq.
395 * It is set to NULL otherwise (i.e when none are currently running).
397 struct sched_entity *curr, *next;
399 unsigned long nr_spread_over;
401 #ifdef CONFIG_FAIR_GROUP_SCHED
402 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
405 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
406 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
407 * (like users, containers etc.)
409 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
410 * list is used during load balance.
412 struct list_head leaf_cfs_rq_list;
413 struct task_group *tg; /* group that "owns" this runqueue */
415 #ifdef CONFIG_SMP
416 unsigned long task_weight;
417 unsigned long shares;
419 * We need space to build a sched_domain wide view of the full task
420 * group tree, in order to avoid depending on dynamic memory allocation
421 * during the load balancing we place this in the per cpu task group
422 * hierarchy. This limits the load balancing to one instance per cpu,
423 * but more should not be needed anyway.
425 struct aggregate_struct {
427 * load = weight(cpus) * f(tg)
429 * Where f(tg) is the recursive weight fraction assigned to
430 * this group.
432 unsigned long load;
435 * part of the group weight distributed to this span.
437 unsigned long shares;
440 * The sum of all runqueue weights within this span.
442 unsigned long rq_weight;
445 * Weight contributed by tasks; this is the part we can
446 * influence by moving tasks around.
448 unsigned long task_weight;
449 } aggregate;
450 #endif
451 #endif
454 /* Real-Time classes' related field in a runqueue: */
455 struct rt_rq {
456 struct rt_prio_array active;
457 unsigned long rt_nr_running;
458 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
459 int highest_prio; /* highest queued rt task prio */
460 #endif
461 #ifdef CONFIG_SMP
462 unsigned long rt_nr_migratory;
463 int overloaded;
464 #endif
465 int rt_throttled;
466 u64 rt_time;
467 u64 rt_runtime;
468 /* Nests inside the rq lock: */
469 spinlock_t rt_runtime_lock;
471 #ifdef CONFIG_RT_GROUP_SCHED
472 unsigned long rt_nr_boosted;
474 struct rq *rq;
475 struct list_head leaf_rt_rq_list;
476 struct task_group *tg;
477 struct sched_rt_entity *rt_se;
478 #endif
481 #ifdef CONFIG_SMP
484 * We add the notion of a root-domain which will be used to define per-domain
485 * variables. Each exclusive cpuset essentially defines an island domain by
486 * fully partitioning the member cpus from any other cpuset. Whenever a new
487 * exclusive cpuset is created, we also create and attach a new root-domain
488 * object.
491 struct root_domain {
492 atomic_t refcount;
493 cpumask_t span;
494 cpumask_t online;
497 * The "RT overload" flag: it gets set if a CPU has more than
498 * one runnable RT task.
500 cpumask_t rto_mask;
501 atomic_t rto_count;
505 * By default the system creates a single root-domain with all cpus as
506 * members (mimicking the global state we have today).
508 static struct root_domain def_root_domain;
510 #endif
513 * This is the main, per-CPU runqueue data structure.
515 * Locking rule: those places that want to lock multiple runqueues
516 * (such as the load balancing or the thread migration code), lock
517 * acquire operations must be ordered by ascending &runqueue.
519 struct rq {
520 /* runqueue lock: */
521 spinlock_t lock;
524 * nr_running and cpu_load should be in the same cacheline because
525 * remote CPUs use both these fields when doing load calculation.
527 unsigned long nr_running;
528 #define CPU_LOAD_IDX_MAX 5
529 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
530 unsigned char idle_at_tick;
531 #ifdef CONFIG_NO_HZ
532 unsigned long last_tick_seen;
533 unsigned char in_nohz_recently;
534 #endif
535 /* capture load from *all* tasks on this cpu: */
536 struct load_weight load;
537 unsigned long nr_load_updates;
538 u64 nr_switches;
540 struct cfs_rq cfs;
541 struct rt_rq rt;
543 #ifdef CONFIG_FAIR_GROUP_SCHED
544 /* list of leaf cfs_rq on this cpu: */
545 struct list_head leaf_cfs_rq_list;
546 #endif
547 #ifdef CONFIG_RT_GROUP_SCHED
548 struct list_head leaf_rt_rq_list;
549 #endif
552 * This is part of a global counter where only the total sum
553 * over all CPUs matters. A task can increase this counter on
554 * one CPU and if it got migrated afterwards it may decrease
555 * it on another CPU. Always updated under the runqueue lock:
557 unsigned long nr_uninterruptible;
559 struct task_struct *curr, *idle;
560 unsigned long next_balance;
561 struct mm_struct *prev_mm;
563 u64 clock, prev_clock_raw;
564 s64 clock_max_delta;
566 unsigned int clock_warps, clock_overflows, clock_underflows;
567 u64 idle_clock;
568 unsigned int clock_deep_idle_events;
569 u64 tick_timestamp;
571 atomic_t nr_iowait;
573 #ifdef CONFIG_SMP
574 struct root_domain *rd;
575 struct sched_domain *sd;
577 /* For active balancing */
578 int active_balance;
579 int push_cpu;
580 /* cpu of this runqueue: */
581 int cpu;
583 struct task_struct *migration_thread;
584 struct list_head migration_queue;
585 #endif
587 #ifdef CONFIG_SCHED_HRTICK
588 unsigned long hrtick_flags;
589 ktime_t hrtick_expire;
590 struct hrtimer hrtick_timer;
591 #endif
593 #ifdef CONFIG_SCHEDSTATS
594 /* latency stats */
595 struct sched_info rq_sched_info;
597 /* sys_sched_yield() stats */
598 unsigned int yld_exp_empty;
599 unsigned int yld_act_empty;
600 unsigned int yld_both_empty;
601 unsigned int yld_count;
603 /* schedule() stats */
604 unsigned int sched_switch;
605 unsigned int sched_count;
606 unsigned int sched_goidle;
608 /* try_to_wake_up() stats */
609 unsigned int ttwu_count;
610 unsigned int ttwu_local;
612 /* BKL stats */
613 unsigned int bkl_count;
614 #endif
615 struct lock_class_key rq_lock_key;
618 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
620 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
622 rq->curr->sched_class->check_preempt_curr(rq, p);
625 static inline int cpu_of(struct rq *rq)
627 #ifdef CONFIG_SMP
628 return rq->cpu;
629 #else
630 return 0;
631 #endif
634 #ifdef CONFIG_NO_HZ
635 static inline bool nohz_on(int cpu)
637 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
640 static inline u64 max_skipped_ticks(struct rq *rq)
642 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
645 static inline void update_last_tick_seen(struct rq *rq)
647 rq->last_tick_seen = jiffies;
649 #else
650 static inline u64 max_skipped_ticks(struct rq *rq)
652 return 1;
655 static inline void update_last_tick_seen(struct rq *rq)
658 #endif
661 * Update the per-runqueue clock, as finegrained as the platform can give
662 * us, but without assuming monotonicity, etc.:
664 static void __update_rq_clock(struct rq *rq)
666 u64 prev_raw = rq->prev_clock_raw;
667 u64 now = sched_clock();
668 s64 delta = now - prev_raw;
669 u64 clock = rq->clock;
671 #ifdef CONFIG_SCHED_DEBUG
672 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
673 #endif
675 * Protect against sched_clock() occasionally going backwards:
677 if (unlikely(delta < 0)) {
678 clock++;
679 rq->clock_warps++;
680 } else {
682 * Catch too large forward jumps too:
684 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
685 u64 max_time = rq->tick_timestamp + max_jump;
687 if (unlikely(clock + delta > max_time)) {
688 if (clock < max_time)
689 clock = max_time;
690 else
691 clock++;
692 rq->clock_overflows++;
693 } else {
694 if (unlikely(delta > rq->clock_max_delta))
695 rq->clock_max_delta = delta;
696 clock += delta;
700 rq->prev_clock_raw = now;
701 rq->clock = clock;
704 static void update_rq_clock(struct rq *rq)
706 if (likely(smp_processor_id() == cpu_of(rq)))
707 __update_rq_clock(rq);
711 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
712 * See detach_destroy_domains: synchronize_sched for details.
714 * The domain tree of any CPU may only be accessed from within
715 * preempt-disabled sections.
717 #define for_each_domain(cpu, __sd) \
718 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
720 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
721 #define this_rq() (&__get_cpu_var(runqueues))
722 #define task_rq(p) cpu_rq(task_cpu(p))
723 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
726 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
728 #ifdef CONFIG_SCHED_DEBUG
729 # define const_debug __read_mostly
730 #else
731 # define const_debug static const
732 #endif
735 * Debugging: various feature bits
738 #define SCHED_FEAT(name, enabled) \
739 __SCHED_FEAT_##name ,
741 enum {
742 #include "sched_features.h"
745 #undef SCHED_FEAT
747 #define SCHED_FEAT(name, enabled) \
748 (1UL << __SCHED_FEAT_##name) * enabled |
750 const_debug unsigned int sysctl_sched_features =
751 #include "sched_features.h"
754 #undef SCHED_FEAT
756 #ifdef CONFIG_SCHED_DEBUG
757 #define SCHED_FEAT(name, enabled) \
758 #name ,
760 static __read_mostly char *sched_feat_names[] = {
761 #include "sched_features.h"
762 NULL
765 #undef SCHED_FEAT
767 static int sched_feat_open(struct inode *inode, struct file *filp)
769 filp->private_data = inode->i_private;
770 return 0;
773 static ssize_t
774 sched_feat_read(struct file *filp, char __user *ubuf,
775 size_t cnt, loff_t *ppos)
777 char *buf;
778 int r = 0;
779 int len = 0;
780 int i;
782 for (i = 0; sched_feat_names[i]; i++) {
783 len += strlen(sched_feat_names[i]);
784 len += 4;
787 buf = kmalloc(len + 2, GFP_KERNEL);
788 if (!buf)
789 return -ENOMEM;
791 for (i = 0; sched_feat_names[i]; i++) {
792 if (sysctl_sched_features & (1UL << i))
793 r += sprintf(buf + r, "%s ", sched_feat_names[i]);
794 else
795 r += sprintf(buf + r, "NO_%s ", sched_feat_names[i]);
798 r += sprintf(buf + r, "\n");
799 WARN_ON(r >= len + 2);
801 r = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
803 kfree(buf);
805 return r;
808 static ssize_t
809 sched_feat_write(struct file *filp, const char __user *ubuf,
810 size_t cnt, loff_t *ppos)
812 char buf[64];
813 char *cmp = buf;
814 int neg = 0;
815 int i;
817 if (cnt > 63)
818 cnt = 63;
820 if (copy_from_user(&buf, ubuf, cnt))
821 return -EFAULT;
823 buf[cnt] = 0;
825 if (strncmp(buf, "NO_", 3) == 0) {
826 neg = 1;
827 cmp += 3;
830 for (i = 0; sched_feat_names[i]; i++) {
831 int len = strlen(sched_feat_names[i]);
833 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
834 if (neg)
835 sysctl_sched_features &= ~(1UL << i);
836 else
837 sysctl_sched_features |= (1UL << i);
838 break;
842 if (!sched_feat_names[i])
843 return -EINVAL;
845 filp->f_pos += cnt;
847 return cnt;
850 static struct file_operations sched_feat_fops = {
851 .open = sched_feat_open,
852 .read = sched_feat_read,
853 .write = sched_feat_write,
856 static __init int sched_init_debug(void)
858 debugfs_create_file("sched_features", 0644, NULL, NULL,
859 &sched_feat_fops);
861 return 0;
863 late_initcall(sched_init_debug);
865 #endif
867 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
870 * Number of tasks to iterate in a single balance run.
871 * Limited because this is done with IRQs disabled.
873 const_debug unsigned int sysctl_sched_nr_migrate = 32;
876 * period over which we measure -rt task cpu usage in us.
877 * default: 1s
879 unsigned int sysctl_sched_rt_period = 1000000;
881 static __read_mostly int scheduler_running;
884 * part of the period that we allow rt tasks to run in us.
885 * default: 0.95s
887 int sysctl_sched_rt_runtime = 950000;
889 static inline u64 global_rt_period(void)
891 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
894 static inline u64 global_rt_runtime(void)
896 if (sysctl_sched_rt_period < 0)
897 return RUNTIME_INF;
899 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
902 static const unsigned long long time_sync_thresh = 100000;
904 static DEFINE_PER_CPU(unsigned long long, time_offset);
905 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
908 * Global lock which we take every now and then to synchronize
909 * the CPUs time. This method is not warp-safe, but it's good
910 * enough to synchronize slowly diverging time sources and thus
911 * it's good enough for tracing:
913 static DEFINE_SPINLOCK(time_sync_lock);
914 static unsigned long long prev_global_time;
916 static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
918 unsigned long flags;
920 spin_lock_irqsave(&time_sync_lock, flags);
922 if (time < prev_global_time) {
923 per_cpu(time_offset, cpu) += prev_global_time - time;
924 time = prev_global_time;
925 } else {
926 prev_global_time = time;
929 spin_unlock_irqrestore(&time_sync_lock, flags);
931 return time;
934 static unsigned long long __cpu_clock(int cpu)
936 unsigned long long now;
937 unsigned long flags;
938 struct rq *rq;
941 * Only call sched_clock() if the scheduler has already been
942 * initialized (some code might call cpu_clock() very early):
944 if (unlikely(!scheduler_running))
945 return 0;
947 local_irq_save(flags);
948 rq = cpu_rq(cpu);
949 update_rq_clock(rq);
950 now = rq->clock;
951 local_irq_restore(flags);
953 return now;
957 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
958 * clock constructed from sched_clock():
960 unsigned long long cpu_clock(int cpu)
962 unsigned long long prev_cpu_time, time, delta_time;
964 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
965 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
966 delta_time = time-prev_cpu_time;
968 if (unlikely(delta_time > time_sync_thresh))
969 time = __sync_cpu_clock(time, cpu);
971 return time;
973 EXPORT_SYMBOL_GPL(cpu_clock);
975 #ifndef prepare_arch_switch
976 # define prepare_arch_switch(next) do { } while (0)
977 #endif
978 #ifndef finish_arch_switch
979 # define finish_arch_switch(prev) do { } while (0)
980 #endif
982 static inline int task_current(struct rq *rq, struct task_struct *p)
984 return rq->curr == p;
987 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
988 static inline int task_running(struct rq *rq, struct task_struct *p)
990 return task_current(rq, p);
993 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
997 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
999 #ifdef CONFIG_DEBUG_SPINLOCK
1000 /* this is a valid case when another task releases the spinlock */
1001 rq->lock.owner = current;
1002 #endif
1004 * If we are tracking spinlock dependencies then we have to
1005 * fix up the runqueue lock - which gets 'carried over' from
1006 * prev into current:
1008 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
1010 spin_unlock_irq(&rq->lock);
1013 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
1014 static inline int task_running(struct rq *rq, struct task_struct *p)
1016 #ifdef CONFIG_SMP
1017 return p->oncpu;
1018 #else
1019 return task_current(rq, p);
1020 #endif
1023 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
1025 #ifdef CONFIG_SMP
1027 * We can optimise this out completely for !SMP, because the
1028 * SMP rebalancing from interrupt is the only thing that cares
1029 * here.
1031 next->oncpu = 1;
1032 #endif
1033 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1034 spin_unlock_irq(&rq->lock);
1035 #else
1036 spin_unlock(&rq->lock);
1037 #endif
1040 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
1042 #ifdef CONFIG_SMP
1044 * After ->oncpu is cleared, the task can be moved to a different CPU.
1045 * We must ensure this doesn't happen until the switch is completely
1046 * finished.
1048 smp_wmb();
1049 prev->oncpu = 0;
1050 #endif
1051 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1052 local_irq_enable();
1053 #endif
1055 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1058 * __task_rq_lock - lock the runqueue a given task resides on.
1059 * Must be called interrupts disabled.
1061 static inline struct rq *__task_rq_lock(struct task_struct *p)
1062 __acquires(rq->lock)
1064 for (;;) {
1065 struct rq *rq = task_rq(p);
1066 spin_lock(&rq->lock);
1067 if (likely(rq == task_rq(p)))
1068 return rq;
1069 spin_unlock(&rq->lock);
1074 * task_rq_lock - lock the runqueue a given task resides on and disable
1075 * interrupts. Note the ordering: we can safely lookup the task_rq without
1076 * explicitly disabling preemption.
1078 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1079 __acquires(rq->lock)
1081 struct rq *rq;
1083 for (;;) {
1084 local_irq_save(*flags);
1085 rq = task_rq(p);
1086 spin_lock(&rq->lock);
1087 if (likely(rq == task_rq(p)))
1088 return rq;
1089 spin_unlock_irqrestore(&rq->lock, *flags);
1093 static void __task_rq_unlock(struct rq *rq)
1094 __releases(rq->lock)
1096 spin_unlock(&rq->lock);
1099 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1100 __releases(rq->lock)
1102 spin_unlock_irqrestore(&rq->lock, *flags);
1106 * this_rq_lock - lock this runqueue and disable interrupts.
1108 static struct rq *this_rq_lock(void)
1109 __acquires(rq->lock)
1111 struct rq *rq;
1113 local_irq_disable();
1114 rq = this_rq();
1115 spin_lock(&rq->lock);
1117 return rq;
1121 * We are going deep-idle (irqs are disabled):
1123 void sched_clock_idle_sleep_event(void)
1125 struct rq *rq = cpu_rq(smp_processor_id());
1127 WARN_ON(!irqs_disabled());
1128 spin_lock(&rq->lock);
1129 __update_rq_clock(rq);
1130 spin_unlock(&rq->lock);
1131 rq->clock_deep_idle_events++;
1133 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
1136 * We just idled delta nanoseconds (called with irqs disabled):
1138 void sched_clock_idle_wakeup_event(u64 delta_ns)
1140 struct rq *rq = cpu_rq(smp_processor_id());
1141 u64 now = sched_clock();
1143 WARN_ON(!irqs_disabled());
1144 rq->idle_clock += delta_ns;
1146 * Override the previous timestamp and ignore all
1147 * sched_clock() deltas that occured while we idled,
1148 * and use the PM-provided delta_ns to advance the
1149 * rq clock:
1151 spin_lock(&rq->lock);
1152 rq->prev_clock_raw = now;
1153 rq->clock += delta_ns;
1154 spin_unlock(&rq->lock);
1155 touch_softlockup_watchdog();
1157 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1159 static void __resched_task(struct task_struct *p, int tif_bit);
1161 static inline void resched_task(struct task_struct *p)
1163 __resched_task(p, TIF_NEED_RESCHED);
1166 #ifdef CONFIG_SCHED_HRTICK
1168 * Use HR-timers to deliver accurate preemption points.
1170 * Its all a bit involved since we cannot program an hrt while holding the
1171 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1172 * reschedule event.
1174 * When we get rescheduled we reprogram the hrtick_timer outside of the
1175 * rq->lock.
1177 static inline void resched_hrt(struct task_struct *p)
1179 __resched_task(p, TIF_HRTICK_RESCHED);
1182 static inline void resched_rq(struct rq *rq)
1184 unsigned long flags;
1186 spin_lock_irqsave(&rq->lock, flags);
1187 resched_task(rq->curr);
1188 spin_unlock_irqrestore(&rq->lock, flags);
1191 enum {
1192 HRTICK_SET, /* re-programm hrtick_timer */
1193 HRTICK_RESET, /* not a new slice */
1194 HRTICK_BLOCK, /* stop hrtick operations */
1198 * Use hrtick when:
1199 * - enabled by features
1200 * - hrtimer is actually high res
1202 static inline int hrtick_enabled(struct rq *rq)
1204 if (!sched_feat(HRTICK))
1205 return 0;
1206 if (unlikely(test_bit(HRTICK_BLOCK, &rq->hrtick_flags)))
1207 return 0;
1208 return hrtimer_is_hres_active(&rq->hrtick_timer);
1212 * Called to set the hrtick timer state.
1214 * called with rq->lock held and irqs disabled
1216 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1218 assert_spin_locked(&rq->lock);
1221 * preempt at: now + delay
1223 rq->hrtick_expire =
1224 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1226 * indicate we need to program the timer
1228 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1229 if (reset)
1230 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1233 * New slices are called from the schedule path and don't need a
1234 * forced reschedule.
1236 if (reset)
1237 resched_hrt(rq->curr);
1240 static void hrtick_clear(struct rq *rq)
1242 if (hrtimer_active(&rq->hrtick_timer))
1243 hrtimer_cancel(&rq->hrtick_timer);
1247 * Update the timer from the possible pending state.
1249 static void hrtick_set(struct rq *rq)
1251 ktime_t time;
1252 int set, reset;
1253 unsigned long flags;
1255 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1257 spin_lock_irqsave(&rq->lock, flags);
1258 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1259 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1260 time = rq->hrtick_expire;
1261 clear_thread_flag(TIF_HRTICK_RESCHED);
1262 spin_unlock_irqrestore(&rq->lock, flags);
1264 if (set) {
1265 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1266 if (reset && !hrtimer_active(&rq->hrtick_timer))
1267 resched_rq(rq);
1268 } else
1269 hrtick_clear(rq);
1273 * High-resolution timer tick.
1274 * Runs from hardirq context with interrupts disabled.
1276 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1278 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1280 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1282 spin_lock(&rq->lock);
1283 __update_rq_clock(rq);
1284 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1285 spin_unlock(&rq->lock);
1287 return HRTIMER_NORESTART;
1290 static void hotplug_hrtick_disable(int cpu)
1292 struct rq *rq = cpu_rq(cpu);
1293 unsigned long flags;
1295 spin_lock_irqsave(&rq->lock, flags);
1296 rq->hrtick_flags = 0;
1297 __set_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1298 spin_unlock_irqrestore(&rq->lock, flags);
1300 hrtick_clear(rq);
1303 static void hotplug_hrtick_enable(int cpu)
1305 struct rq *rq = cpu_rq(cpu);
1306 unsigned long flags;
1308 spin_lock_irqsave(&rq->lock, flags);
1309 __clear_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1310 spin_unlock_irqrestore(&rq->lock, flags);
1313 static int
1314 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1316 int cpu = (int)(long)hcpu;
1318 switch (action) {
1319 case CPU_UP_CANCELED:
1320 case CPU_UP_CANCELED_FROZEN:
1321 case CPU_DOWN_PREPARE:
1322 case CPU_DOWN_PREPARE_FROZEN:
1323 case CPU_DEAD:
1324 case CPU_DEAD_FROZEN:
1325 hotplug_hrtick_disable(cpu);
1326 return NOTIFY_OK;
1328 case CPU_UP_PREPARE:
1329 case CPU_UP_PREPARE_FROZEN:
1330 case CPU_DOWN_FAILED:
1331 case CPU_DOWN_FAILED_FROZEN:
1332 case CPU_ONLINE:
1333 case CPU_ONLINE_FROZEN:
1334 hotplug_hrtick_enable(cpu);
1335 return NOTIFY_OK;
1338 return NOTIFY_DONE;
1341 static void init_hrtick(void)
1343 hotcpu_notifier(hotplug_hrtick, 0);
1346 static void init_rq_hrtick(struct rq *rq)
1348 rq->hrtick_flags = 0;
1349 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1350 rq->hrtick_timer.function = hrtick;
1351 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1354 void hrtick_resched(void)
1356 struct rq *rq;
1357 unsigned long flags;
1359 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1360 return;
1362 local_irq_save(flags);
1363 rq = cpu_rq(smp_processor_id());
1364 hrtick_set(rq);
1365 local_irq_restore(flags);
1367 #else
1368 static inline void hrtick_clear(struct rq *rq)
1372 static inline void hrtick_set(struct rq *rq)
1376 static inline void init_rq_hrtick(struct rq *rq)
1380 void hrtick_resched(void)
1384 static inline void init_hrtick(void)
1387 #endif
1390 * resched_task - mark a task 'to be rescheduled now'.
1392 * On UP this means the setting of the need_resched flag, on SMP it
1393 * might also involve a cross-CPU call to trigger the scheduler on
1394 * the target CPU.
1396 #ifdef CONFIG_SMP
1398 #ifndef tsk_is_polling
1399 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1400 #endif
1402 static void __resched_task(struct task_struct *p, int tif_bit)
1404 int cpu;
1406 assert_spin_locked(&task_rq(p)->lock);
1408 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1409 return;
1411 set_tsk_thread_flag(p, tif_bit);
1413 cpu = task_cpu(p);
1414 if (cpu == smp_processor_id())
1415 return;
1417 /* NEED_RESCHED must be visible before we test polling */
1418 smp_mb();
1419 if (!tsk_is_polling(p))
1420 smp_send_reschedule(cpu);
1423 static void resched_cpu(int cpu)
1425 struct rq *rq = cpu_rq(cpu);
1426 unsigned long flags;
1428 if (!spin_trylock_irqsave(&rq->lock, flags))
1429 return;
1430 resched_task(cpu_curr(cpu));
1431 spin_unlock_irqrestore(&rq->lock, flags);
1434 #ifdef CONFIG_NO_HZ
1436 * When add_timer_on() enqueues a timer into the timer wheel of an
1437 * idle CPU then this timer might expire before the next timer event
1438 * which is scheduled to wake up that CPU. In case of a completely
1439 * idle system the next event might even be infinite time into the
1440 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1441 * leaves the inner idle loop so the newly added timer is taken into
1442 * account when the CPU goes back to idle and evaluates the timer
1443 * wheel for the next timer event.
1445 void wake_up_idle_cpu(int cpu)
1447 struct rq *rq = cpu_rq(cpu);
1449 if (cpu == smp_processor_id())
1450 return;
1453 * This is safe, as this function is called with the timer
1454 * wheel base lock of (cpu) held. When the CPU is on the way
1455 * to idle and has not yet set rq->curr to idle then it will
1456 * be serialized on the timer wheel base lock and take the new
1457 * timer into account automatically.
1459 if (rq->curr != rq->idle)
1460 return;
1463 * We can set TIF_RESCHED on the idle task of the other CPU
1464 * lockless. The worst case is that the other CPU runs the
1465 * idle task through an additional NOOP schedule()
1467 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1469 /* NEED_RESCHED must be visible before we test polling */
1470 smp_mb();
1471 if (!tsk_is_polling(rq->idle))
1472 smp_send_reschedule(cpu);
1474 #endif
1476 #else
1477 static void __resched_task(struct task_struct *p, int tif_bit)
1479 assert_spin_locked(&task_rq(p)->lock);
1480 set_tsk_thread_flag(p, tif_bit);
1482 #endif
1484 #if BITS_PER_LONG == 32
1485 # define WMULT_CONST (~0UL)
1486 #else
1487 # define WMULT_CONST (1UL << 32)
1488 #endif
1490 #define WMULT_SHIFT 32
1493 * Shift right and round:
1495 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1498 * delta *= weight / lw
1500 static unsigned long
1501 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1502 struct load_weight *lw)
1504 u64 tmp;
1506 if (!lw->inv_weight)
1507 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)/(lw->weight+1);
1509 tmp = (u64)delta_exec * weight;
1511 * Check whether we'd overflow the 64-bit multiplication:
1513 if (unlikely(tmp > WMULT_CONST))
1514 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1515 WMULT_SHIFT/2);
1516 else
1517 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1519 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1522 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1524 lw->weight += inc;
1525 lw->inv_weight = 0;
1528 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1530 lw->weight -= dec;
1531 lw->inv_weight = 0;
1535 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1536 * of tasks with abnormal "nice" values across CPUs the contribution that
1537 * each task makes to its run queue's load is weighted according to its
1538 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1539 * scaled version of the new time slice allocation that they receive on time
1540 * slice expiry etc.
1543 #define WEIGHT_IDLEPRIO 2
1544 #define WMULT_IDLEPRIO (1 << 31)
1547 * Nice levels are multiplicative, with a gentle 10% change for every
1548 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1549 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1550 * that remained on nice 0.
1552 * The "10% effect" is relative and cumulative: from _any_ nice level,
1553 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1554 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1555 * If a task goes up by ~10% and another task goes down by ~10% then
1556 * the relative distance between them is ~25%.)
1558 static const int prio_to_weight[40] = {
1559 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1560 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1561 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1562 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1563 /* 0 */ 1024, 820, 655, 526, 423,
1564 /* 5 */ 335, 272, 215, 172, 137,
1565 /* 10 */ 110, 87, 70, 56, 45,
1566 /* 15 */ 36, 29, 23, 18, 15,
1570 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1572 * In cases where the weight does not change often, we can use the
1573 * precalculated inverse to speed up arithmetics by turning divisions
1574 * into multiplications:
1576 static const u32 prio_to_wmult[40] = {
1577 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1578 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1579 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1580 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1581 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1582 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1583 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1584 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1587 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1590 * runqueue iterator, to support SMP load-balancing between different
1591 * scheduling classes, without having to expose their internal data
1592 * structures to the load-balancing proper:
1594 struct rq_iterator {
1595 void *arg;
1596 struct task_struct *(*start)(void *);
1597 struct task_struct *(*next)(void *);
1600 #ifdef CONFIG_SMP
1601 static unsigned long
1602 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1603 unsigned long max_load_move, struct sched_domain *sd,
1604 enum cpu_idle_type idle, int *all_pinned,
1605 int *this_best_prio, struct rq_iterator *iterator);
1607 static int
1608 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1609 struct sched_domain *sd, enum cpu_idle_type idle,
1610 struct rq_iterator *iterator);
1611 #endif
1613 #ifdef CONFIG_CGROUP_CPUACCT
1614 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1615 #else
1616 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1617 #endif
1619 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1621 update_load_add(&rq->load, load);
1624 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1626 update_load_sub(&rq->load, load);
1629 #ifdef CONFIG_SMP
1630 static unsigned long source_load(int cpu, int type);
1631 static unsigned long target_load(int cpu, int type);
1632 static unsigned long cpu_avg_load_per_task(int cpu);
1633 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1635 #ifdef CONFIG_FAIR_GROUP_SCHED
1638 * Group load balancing.
1640 * We calculate a few balance domain wide aggregate numbers; load and weight.
1641 * Given the pictures below, and assuming each item has equal weight:
1643 * root 1 - thread
1644 * / | \ A - group
1645 * A 1 B
1646 * /|\ / \
1647 * C 2 D 3 4
1648 * | |
1649 * 5 6
1651 * load:
1652 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1653 * which equals 1/9-th of the total load.
1655 * shares:
1656 * The weight of this group on the selected cpus.
1658 * rq_weight:
1659 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1660 * B would get 2.
1662 * task_weight:
1663 * Part of the rq_weight contributed by tasks; all groups except B would
1664 * get 1, B gets 2.
1667 static inline struct aggregate_struct *
1668 aggregate(struct task_group *tg, struct sched_domain *sd)
1670 return &tg->cfs_rq[sd->first_cpu]->aggregate;
1673 typedef void (*aggregate_func)(struct task_group *, struct sched_domain *);
1676 * Iterate the full tree, calling @down when first entering a node and @up when
1677 * leaving it for the final time.
1679 static
1680 void aggregate_walk_tree(aggregate_func down, aggregate_func up,
1681 struct sched_domain *sd)
1683 struct task_group *parent, *child;
1685 rcu_read_lock();
1686 parent = &root_task_group;
1687 down:
1688 (*down)(parent, sd);
1689 list_for_each_entry_rcu(child, &parent->children, siblings) {
1690 parent = child;
1691 goto down;
1694 continue;
1696 (*up)(parent, sd);
1698 child = parent;
1699 parent = parent->parent;
1700 if (parent)
1701 goto up;
1702 rcu_read_unlock();
1706 * Calculate the aggregate runqueue weight.
1708 static
1709 void aggregate_group_weight(struct task_group *tg, struct sched_domain *sd)
1711 unsigned long rq_weight = 0;
1712 unsigned long task_weight = 0;
1713 int i;
1715 for_each_cpu_mask(i, sd->span) {
1716 rq_weight += tg->cfs_rq[i]->load.weight;
1717 task_weight += tg->cfs_rq[i]->task_weight;
1720 aggregate(tg, sd)->rq_weight = rq_weight;
1721 aggregate(tg, sd)->task_weight = task_weight;
1725 * Compute the weight of this group on the given cpus.
1727 static
1728 void aggregate_group_shares(struct task_group *tg, struct sched_domain *sd)
1730 unsigned long shares = 0;
1731 int i;
1733 for_each_cpu_mask(i, sd->span)
1734 shares += tg->cfs_rq[i]->shares;
1736 if ((!shares && aggregate(tg, sd)->rq_weight) || shares > tg->shares)
1737 shares = tg->shares;
1739 aggregate(tg, sd)->shares = shares;
1743 * Compute the load fraction assigned to this group, relies on the aggregate
1744 * weight and this group's parent's load, i.e. top-down.
1746 static
1747 void aggregate_group_load(struct task_group *tg, struct sched_domain *sd)
1749 unsigned long load;
1751 if (!tg->parent) {
1752 int i;
1754 load = 0;
1755 for_each_cpu_mask(i, sd->span)
1756 load += cpu_rq(i)->load.weight;
1758 } else {
1759 load = aggregate(tg->parent, sd)->load;
1762 * shares is our weight in the parent's rq so
1763 * shares/parent->rq_weight gives our fraction of the load
1765 load *= aggregate(tg, sd)->shares;
1766 load /= aggregate(tg->parent, sd)->rq_weight + 1;
1769 aggregate(tg, sd)->load = load;
1772 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1775 * Calculate and set the cpu's group shares.
1777 static void
1778 __update_group_shares_cpu(struct task_group *tg, struct sched_domain *sd,
1779 int tcpu)
1781 int boost = 0;
1782 unsigned long shares;
1783 unsigned long rq_weight;
1785 if (!tg->se[tcpu])
1786 return;
1788 rq_weight = tg->cfs_rq[tcpu]->load.weight;
1791 * If there are currently no tasks on the cpu pretend there is one of
1792 * average load so that when a new task gets to run here it will not
1793 * get delayed by group starvation.
1795 if (!rq_weight) {
1796 boost = 1;
1797 rq_weight = NICE_0_LOAD;
1801 * \Sum shares * rq_weight
1802 * shares = -----------------------
1803 * \Sum rq_weight
1806 shares = aggregate(tg, sd)->shares * rq_weight;
1807 shares /= aggregate(tg, sd)->rq_weight + 1;
1810 * record the actual number of shares, not the boosted amount.
1812 tg->cfs_rq[tcpu]->shares = boost ? 0 : shares;
1814 if (shares < MIN_SHARES)
1815 shares = MIN_SHARES;
1817 __set_se_shares(tg->se[tcpu], shares);
1821 * Re-adjust the weights on the cpu the task came from and on the cpu the
1822 * task went to.
1824 static void
1825 __move_group_shares(struct task_group *tg, struct sched_domain *sd,
1826 int scpu, int dcpu)
1828 unsigned long shares;
1830 shares = tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1832 __update_group_shares_cpu(tg, sd, scpu);
1833 __update_group_shares_cpu(tg, sd, dcpu);
1836 * ensure we never loose shares due to rounding errors in the
1837 * above redistribution.
1839 shares -= tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1840 if (shares)
1841 tg->cfs_rq[dcpu]->shares += shares;
1845 * Because changing a group's shares changes the weight of the super-group
1846 * we need to walk up the tree and change all shares until we hit the root.
1848 static void
1849 move_group_shares(struct task_group *tg, struct sched_domain *sd,
1850 int scpu, int dcpu)
1852 while (tg) {
1853 __move_group_shares(tg, sd, scpu, dcpu);
1854 tg = tg->parent;
1858 static
1859 void aggregate_group_set_shares(struct task_group *tg, struct sched_domain *sd)
1861 unsigned long shares = aggregate(tg, sd)->shares;
1862 int i;
1864 for_each_cpu_mask(i, sd->span) {
1865 struct rq *rq = cpu_rq(i);
1866 unsigned long flags;
1868 spin_lock_irqsave(&rq->lock, flags);
1869 __update_group_shares_cpu(tg, sd, i);
1870 spin_unlock_irqrestore(&rq->lock, flags);
1873 aggregate_group_shares(tg, sd);
1876 * ensure we never loose shares due to rounding errors in the
1877 * above redistribution.
1879 shares -= aggregate(tg, sd)->shares;
1880 if (shares) {
1881 tg->cfs_rq[sd->first_cpu]->shares += shares;
1882 aggregate(tg, sd)->shares += shares;
1887 * Calculate the accumulative weight and recursive load of each task group
1888 * while walking down the tree.
1890 static
1891 void aggregate_get_down(struct task_group *tg, struct sched_domain *sd)
1893 aggregate_group_weight(tg, sd);
1894 aggregate_group_shares(tg, sd);
1895 aggregate_group_load(tg, sd);
1899 * Rebalance the cpu shares while walking back up the tree.
1901 static
1902 void aggregate_get_up(struct task_group *tg, struct sched_domain *sd)
1904 aggregate_group_set_shares(tg, sd);
1907 static DEFINE_PER_CPU(spinlock_t, aggregate_lock);
1909 static void __init init_aggregate(void)
1911 int i;
1913 for_each_possible_cpu(i)
1914 spin_lock_init(&per_cpu(aggregate_lock, i));
1917 static int get_aggregate(struct sched_domain *sd)
1919 if (!spin_trylock(&per_cpu(aggregate_lock, sd->first_cpu)))
1920 return 0;
1922 aggregate_walk_tree(aggregate_get_down, aggregate_get_up, sd);
1923 return 1;
1926 static void put_aggregate(struct sched_domain *sd)
1928 spin_unlock(&per_cpu(aggregate_lock, sd->first_cpu));
1931 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1933 cfs_rq->shares = shares;
1936 #else
1938 static inline void init_aggregate(void)
1942 static inline int get_aggregate(struct sched_domain *sd)
1944 return 0;
1947 static inline void put_aggregate(struct sched_domain *sd)
1950 #endif
1952 #else /* CONFIG_SMP */
1954 #ifdef CONFIG_FAIR_GROUP_SCHED
1955 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1958 #endif
1960 #endif /* CONFIG_SMP */
1962 #include "sched_stats.h"
1963 #include "sched_idletask.c"
1964 #include "sched_fair.c"
1965 #include "sched_rt.c"
1966 #ifdef CONFIG_SCHED_DEBUG
1967 # include "sched_debug.c"
1968 #endif
1970 #define sched_class_highest (&rt_sched_class)
1972 static void inc_nr_running(struct rq *rq)
1974 rq->nr_running++;
1977 static void dec_nr_running(struct rq *rq)
1979 rq->nr_running--;
1982 static void set_load_weight(struct task_struct *p)
1984 if (task_has_rt_policy(p)) {
1985 p->se.load.weight = prio_to_weight[0] * 2;
1986 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1987 return;
1991 * SCHED_IDLE tasks get minimal weight:
1993 if (p->policy == SCHED_IDLE) {
1994 p->se.load.weight = WEIGHT_IDLEPRIO;
1995 p->se.load.inv_weight = WMULT_IDLEPRIO;
1996 return;
1999 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
2000 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
2003 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
2005 sched_info_queued(p);
2006 p->sched_class->enqueue_task(rq, p, wakeup);
2007 p->se.on_rq = 1;
2010 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
2012 p->sched_class->dequeue_task(rq, p, sleep);
2013 p->se.on_rq = 0;
2017 * __normal_prio - return the priority that is based on the static prio
2019 static inline int __normal_prio(struct task_struct *p)
2021 return p->static_prio;
2025 * Calculate the expected normal priority: i.e. priority
2026 * without taking RT-inheritance into account. Might be
2027 * boosted by interactivity modifiers. Changes upon fork,
2028 * setprio syscalls, and whenever the interactivity
2029 * estimator recalculates.
2031 static inline int normal_prio(struct task_struct *p)
2033 int prio;
2035 if (task_has_rt_policy(p))
2036 prio = MAX_RT_PRIO-1 - p->rt_priority;
2037 else
2038 prio = __normal_prio(p);
2039 return prio;
2043 * Calculate the current priority, i.e. the priority
2044 * taken into account by the scheduler. This value might
2045 * be boosted by RT tasks, or might be boosted by
2046 * interactivity modifiers. Will be RT if the task got
2047 * RT-boosted. If not then it returns p->normal_prio.
2049 static int effective_prio(struct task_struct *p)
2051 p->normal_prio = normal_prio(p);
2053 * If we are RT tasks or we were boosted to RT priority,
2054 * keep the priority unchanged. Otherwise, update priority
2055 * to the normal priority:
2057 if (!rt_prio(p->prio))
2058 return p->normal_prio;
2059 return p->prio;
2063 * activate_task - move a task to the runqueue.
2065 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
2067 if (task_contributes_to_load(p))
2068 rq->nr_uninterruptible--;
2070 enqueue_task(rq, p, wakeup);
2071 inc_nr_running(rq);
2075 * deactivate_task - remove a task from the runqueue.
2077 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
2079 if (task_contributes_to_load(p))
2080 rq->nr_uninterruptible++;
2082 dequeue_task(rq, p, sleep);
2083 dec_nr_running(rq);
2087 * task_curr - is this task currently executing on a CPU?
2088 * @p: the task in question.
2090 inline int task_curr(const struct task_struct *p)
2092 return cpu_curr(task_cpu(p)) == p;
2095 /* Used instead of source_load when we know the type == 0 */
2096 unsigned long weighted_cpuload(const int cpu)
2098 return cpu_rq(cpu)->load.weight;
2101 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
2103 set_task_rq(p, cpu);
2104 #ifdef CONFIG_SMP
2106 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
2107 * successfuly executed on another CPU. We must ensure that updates of
2108 * per-task data have been completed by this moment.
2110 smp_wmb();
2111 task_thread_info(p)->cpu = cpu;
2112 #endif
2115 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2116 const struct sched_class *prev_class,
2117 int oldprio, int running)
2119 if (prev_class != p->sched_class) {
2120 if (prev_class->switched_from)
2121 prev_class->switched_from(rq, p, running);
2122 p->sched_class->switched_to(rq, p, running);
2123 } else
2124 p->sched_class->prio_changed(rq, p, oldprio, running);
2127 #ifdef CONFIG_SMP
2130 * Is this task likely cache-hot:
2132 static int
2133 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2135 s64 delta;
2138 * Buddy candidates are cache hot:
2140 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
2141 return 1;
2143 if (p->sched_class != &fair_sched_class)
2144 return 0;
2146 if (sysctl_sched_migration_cost == -1)
2147 return 1;
2148 if (sysctl_sched_migration_cost == 0)
2149 return 0;
2151 delta = now - p->se.exec_start;
2153 return delta < (s64)sysctl_sched_migration_cost;
2157 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2159 int old_cpu = task_cpu(p);
2160 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2161 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2162 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2163 u64 clock_offset;
2165 clock_offset = old_rq->clock - new_rq->clock;
2167 #ifdef CONFIG_SCHEDSTATS
2168 if (p->se.wait_start)
2169 p->se.wait_start -= clock_offset;
2170 if (p->se.sleep_start)
2171 p->se.sleep_start -= clock_offset;
2172 if (p->se.block_start)
2173 p->se.block_start -= clock_offset;
2174 if (old_cpu != new_cpu) {
2175 schedstat_inc(p, se.nr_migrations);
2176 if (task_hot(p, old_rq->clock, NULL))
2177 schedstat_inc(p, se.nr_forced2_migrations);
2179 #endif
2180 p->se.vruntime -= old_cfsrq->min_vruntime -
2181 new_cfsrq->min_vruntime;
2183 __set_task_cpu(p, new_cpu);
2186 struct migration_req {
2187 struct list_head list;
2189 struct task_struct *task;
2190 int dest_cpu;
2192 struct completion done;
2196 * The task's runqueue lock must be held.
2197 * Returns true if you have to wait for migration thread.
2199 static int
2200 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2202 struct rq *rq = task_rq(p);
2205 * If the task is not on a runqueue (and not running), then
2206 * it is sufficient to simply update the task's cpu field.
2208 if (!p->se.on_rq && !task_running(rq, p)) {
2209 set_task_cpu(p, dest_cpu);
2210 return 0;
2213 init_completion(&req->done);
2214 req->task = p;
2215 req->dest_cpu = dest_cpu;
2216 list_add(&req->list, &rq->migration_queue);
2218 return 1;
2222 * wait_task_inactive - wait for a thread to unschedule.
2224 * The caller must ensure that the task *will* unschedule sometime soon,
2225 * else this function might spin for a *long* time. This function can't
2226 * be called with interrupts off, or it may introduce deadlock with
2227 * smp_call_function() if an IPI is sent by the same process we are
2228 * waiting to become inactive.
2230 void wait_task_inactive(struct task_struct *p)
2232 unsigned long flags;
2233 int running, on_rq;
2234 struct rq *rq;
2236 for (;;) {
2238 * We do the initial early heuristics without holding
2239 * any task-queue locks at all. We'll only try to get
2240 * the runqueue lock when things look like they will
2241 * work out!
2243 rq = task_rq(p);
2246 * If the task is actively running on another CPU
2247 * still, just relax and busy-wait without holding
2248 * any locks.
2250 * NOTE! Since we don't hold any locks, it's not
2251 * even sure that "rq" stays as the right runqueue!
2252 * But we don't care, since "task_running()" will
2253 * return false if the runqueue has changed and p
2254 * is actually now running somewhere else!
2256 while (task_running(rq, p))
2257 cpu_relax();
2260 * Ok, time to look more closely! We need the rq
2261 * lock now, to be *sure*. If we're wrong, we'll
2262 * just go back and repeat.
2264 rq = task_rq_lock(p, &flags);
2265 running = task_running(rq, p);
2266 on_rq = p->se.on_rq;
2267 task_rq_unlock(rq, &flags);
2270 * Was it really running after all now that we
2271 * checked with the proper locks actually held?
2273 * Oops. Go back and try again..
2275 if (unlikely(running)) {
2276 cpu_relax();
2277 continue;
2281 * It's not enough that it's not actively running,
2282 * it must be off the runqueue _entirely_, and not
2283 * preempted!
2285 * So if it wa still runnable (but just not actively
2286 * running right now), it's preempted, and we should
2287 * yield - it could be a while.
2289 if (unlikely(on_rq)) {
2290 schedule_timeout_uninterruptible(1);
2291 continue;
2295 * Ahh, all good. It wasn't running, and it wasn't
2296 * runnable, which means that it will never become
2297 * running in the future either. We're all done!
2299 break;
2303 /***
2304 * kick_process - kick a running thread to enter/exit the kernel
2305 * @p: the to-be-kicked thread
2307 * Cause a process which is running on another CPU to enter
2308 * kernel-mode, without any delay. (to get signals handled.)
2310 * NOTE: this function doesnt have to take the runqueue lock,
2311 * because all it wants to ensure is that the remote task enters
2312 * the kernel. If the IPI races and the task has been migrated
2313 * to another CPU then no harm is done and the purpose has been
2314 * achieved as well.
2316 void kick_process(struct task_struct *p)
2318 int cpu;
2320 preempt_disable();
2321 cpu = task_cpu(p);
2322 if ((cpu != smp_processor_id()) && task_curr(p))
2323 smp_send_reschedule(cpu);
2324 preempt_enable();
2328 * Return a low guess at the load of a migration-source cpu weighted
2329 * according to the scheduling class and "nice" value.
2331 * We want to under-estimate the load of migration sources, to
2332 * balance conservatively.
2334 static unsigned long source_load(int cpu, int type)
2336 struct rq *rq = cpu_rq(cpu);
2337 unsigned long total = weighted_cpuload(cpu);
2339 if (type == 0)
2340 return total;
2342 return min(rq->cpu_load[type-1], total);
2346 * Return a high guess at the load of a migration-target cpu weighted
2347 * according to the scheduling class and "nice" value.
2349 static unsigned long target_load(int cpu, int type)
2351 struct rq *rq = cpu_rq(cpu);
2352 unsigned long total = weighted_cpuload(cpu);
2354 if (type == 0)
2355 return total;
2357 return max(rq->cpu_load[type-1], total);
2361 * Return the average load per task on the cpu's run queue
2363 static unsigned long cpu_avg_load_per_task(int cpu)
2365 struct rq *rq = cpu_rq(cpu);
2366 unsigned long total = weighted_cpuload(cpu);
2367 unsigned long n = rq->nr_running;
2369 return n ? total / n : SCHED_LOAD_SCALE;
2373 * find_idlest_group finds and returns the least busy CPU group within the
2374 * domain.
2376 static struct sched_group *
2377 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2379 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2380 unsigned long min_load = ULONG_MAX, this_load = 0;
2381 int load_idx = sd->forkexec_idx;
2382 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2384 do {
2385 unsigned long load, avg_load;
2386 int local_group;
2387 int i;
2389 /* Skip over this group if it has no CPUs allowed */
2390 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2391 continue;
2393 local_group = cpu_isset(this_cpu, group->cpumask);
2395 /* Tally up the load of all CPUs in the group */
2396 avg_load = 0;
2398 for_each_cpu_mask(i, group->cpumask) {
2399 /* Bias balancing toward cpus of our domain */
2400 if (local_group)
2401 load = source_load(i, load_idx);
2402 else
2403 load = target_load(i, load_idx);
2405 avg_load += load;
2408 /* Adjust by relative CPU power of the group */
2409 avg_load = sg_div_cpu_power(group,
2410 avg_load * SCHED_LOAD_SCALE);
2412 if (local_group) {
2413 this_load = avg_load;
2414 this = group;
2415 } else if (avg_load < min_load) {
2416 min_load = avg_load;
2417 idlest = group;
2419 } while (group = group->next, group != sd->groups);
2421 if (!idlest || 100*this_load < imbalance*min_load)
2422 return NULL;
2423 return idlest;
2427 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2429 static int
2430 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2431 cpumask_t *tmp)
2433 unsigned long load, min_load = ULONG_MAX;
2434 int idlest = -1;
2435 int i;
2437 /* Traverse only the allowed CPUs */
2438 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2440 for_each_cpu_mask(i, *tmp) {
2441 load = weighted_cpuload(i);
2443 if (load < min_load || (load == min_load && i == this_cpu)) {
2444 min_load = load;
2445 idlest = i;
2449 return idlest;
2453 * sched_balance_self: balance the current task (running on cpu) in domains
2454 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2455 * SD_BALANCE_EXEC.
2457 * Balance, ie. select the least loaded group.
2459 * Returns the target CPU number, or the same CPU if no balancing is needed.
2461 * preempt must be disabled.
2463 static int sched_balance_self(int cpu, int flag)
2465 struct task_struct *t = current;
2466 struct sched_domain *tmp, *sd = NULL;
2468 for_each_domain(cpu, tmp) {
2470 * If power savings logic is enabled for a domain, stop there.
2472 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2473 break;
2474 if (tmp->flags & flag)
2475 sd = tmp;
2478 while (sd) {
2479 cpumask_t span, tmpmask;
2480 struct sched_group *group;
2481 int new_cpu, weight;
2483 if (!(sd->flags & flag)) {
2484 sd = sd->child;
2485 continue;
2488 span = sd->span;
2489 group = find_idlest_group(sd, t, cpu);
2490 if (!group) {
2491 sd = sd->child;
2492 continue;
2495 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2496 if (new_cpu == -1 || new_cpu == cpu) {
2497 /* Now try balancing at a lower domain level of cpu */
2498 sd = sd->child;
2499 continue;
2502 /* Now try balancing at a lower domain level of new_cpu */
2503 cpu = new_cpu;
2504 sd = NULL;
2505 weight = cpus_weight(span);
2506 for_each_domain(cpu, tmp) {
2507 if (weight <= cpus_weight(tmp->span))
2508 break;
2509 if (tmp->flags & flag)
2510 sd = tmp;
2512 /* while loop will break here if sd == NULL */
2515 return cpu;
2518 #endif /* CONFIG_SMP */
2520 /***
2521 * try_to_wake_up - wake up a thread
2522 * @p: the to-be-woken-up thread
2523 * @state: the mask of task states that can be woken
2524 * @sync: do a synchronous wakeup?
2526 * Put it on the run-queue if it's not already there. The "current"
2527 * thread is always on the run-queue (except when the actual
2528 * re-schedule is in progress), and as such you're allowed to do
2529 * the simpler "current->state = TASK_RUNNING" to mark yourself
2530 * runnable without the overhead of this.
2532 * returns failure only if the task is already active.
2534 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2536 int cpu, orig_cpu, this_cpu, success = 0;
2537 unsigned long flags;
2538 long old_state;
2539 struct rq *rq;
2541 if (!sched_feat(SYNC_WAKEUPS))
2542 sync = 0;
2544 smp_wmb();
2545 rq = task_rq_lock(p, &flags);
2546 old_state = p->state;
2547 if (!(old_state & state))
2548 goto out;
2550 if (p->se.on_rq)
2551 goto out_running;
2553 cpu = task_cpu(p);
2554 orig_cpu = cpu;
2555 this_cpu = smp_processor_id();
2557 #ifdef CONFIG_SMP
2558 if (unlikely(task_running(rq, p)))
2559 goto out_activate;
2561 cpu = p->sched_class->select_task_rq(p, sync);
2562 if (cpu != orig_cpu) {
2563 set_task_cpu(p, cpu);
2564 task_rq_unlock(rq, &flags);
2565 /* might preempt at this point */
2566 rq = task_rq_lock(p, &flags);
2567 old_state = p->state;
2568 if (!(old_state & state))
2569 goto out;
2570 if (p->se.on_rq)
2571 goto out_running;
2573 this_cpu = smp_processor_id();
2574 cpu = task_cpu(p);
2577 #ifdef CONFIG_SCHEDSTATS
2578 schedstat_inc(rq, ttwu_count);
2579 if (cpu == this_cpu)
2580 schedstat_inc(rq, ttwu_local);
2581 else {
2582 struct sched_domain *sd;
2583 for_each_domain(this_cpu, sd) {
2584 if (cpu_isset(cpu, sd->span)) {
2585 schedstat_inc(sd, ttwu_wake_remote);
2586 break;
2590 #endif
2592 out_activate:
2593 #endif /* CONFIG_SMP */
2594 schedstat_inc(p, se.nr_wakeups);
2595 if (sync)
2596 schedstat_inc(p, se.nr_wakeups_sync);
2597 if (orig_cpu != cpu)
2598 schedstat_inc(p, se.nr_wakeups_migrate);
2599 if (cpu == this_cpu)
2600 schedstat_inc(p, se.nr_wakeups_local);
2601 else
2602 schedstat_inc(p, se.nr_wakeups_remote);
2603 update_rq_clock(rq);
2604 activate_task(rq, p, 1);
2605 success = 1;
2607 out_running:
2608 check_preempt_curr(rq, p);
2610 p->state = TASK_RUNNING;
2611 #ifdef CONFIG_SMP
2612 if (p->sched_class->task_wake_up)
2613 p->sched_class->task_wake_up(rq, p);
2614 #endif
2615 out:
2616 task_rq_unlock(rq, &flags);
2618 return success;
2621 int wake_up_process(struct task_struct *p)
2623 return try_to_wake_up(p, TASK_ALL, 0);
2625 EXPORT_SYMBOL(wake_up_process);
2627 int wake_up_state(struct task_struct *p, unsigned int state)
2629 return try_to_wake_up(p, state, 0);
2633 * Perform scheduler related setup for a newly forked process p.
2634 * p is forked by current.
2636 * __sched_fork() is basic setup used by init_idle() too:
2638 static void __sched_fork(struct task_struct *p)
2640 p->se.exec_start = 0;
2641 p->se.sum_exec_runtime = 0;
2642 p->se.prev_sum_exec_runtime = 0;
2643 p->se.last_wakeup = 0;
2644 p->se.avg_overlap = 0;
2646 #ifdef CONFIG_SCHEDSTATS
2647 p->se.wait_start = 0;
2648 p->se.sum_sleep_runtime = 0;
2649 p->se.sleep_start = 0;
2650 p->se.block_start = 0;
2651 p->se.sleep_max = 0;
2652 p->se.block_max = 0;
2653 p->se.exec_max = 0;
2654 p->se.slice_max = 0;
2655 p->se.wait_max = 0;
2656 #endif
2658 INIT_LIST_HEAD(&p->rt.run_list);
2659 p->se.on_rq = 0;
2660 INIT_LIST_HEAD(&p->se.group_node);
2662 #ifdef CONFIG_PREEMPT_NOTIFIERS
2663 INIT_HLIST_HEAD(&p->preempt_notifiers);
2664 #endif
2667 * We mark the process as running here, but have not actually
2668 * inserted it onto the runqueue yet. This guarantees that
2669 * nobody will actually run it, and a signal or other external
2670 * event cannot wake it up and insert it on the runqueue either.
2672 p->state = TASK_RUNNING;
2676 * fork()/clone()-time setup:
2678 void sched_fork(struct task_struct *p, int clone_flags)
2680 int cpu = get_cpu();
2682 __sched_fork(p);
2684 #ifdef CONFIG_SMP
2685 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2686 #endif
2687 set_task_cpu(p, cpu);
2690 * Make sure we do not leak PI boosting priority to the child:
2692 p->prio = current->normal_prio;
2693 if (!rt_prio(p->prio))
2694 p->sched_class = &fair_sched_class;
2696 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2697 if (likely(sched_info_on()))
2698 memset(&p->sched_info, 0, sizeof(p->sched_info));
2699 #endif
2700 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2701 p->oncpu = 0;
2702 #endif
2703 #ifdef CONFIG_PREEMPT
2704 /* Want to start with kernel preemption disabled. */
2705 task_thread_info(p)->preempt_count = 1;
2706 #endif
2707 put_cpu();
2711 * wake_up_new_task - wake up a newly created task for the first time.
2713 * This function will do some initial scheduler statistics housekeeping
2714 * that must be done for every newly created context, then puts the task
2715 * on the runqueue and wakes it.
2717 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2719 unsigned long flags;
2720 struct rq *rq;
2722 rq = task_rq_lock(p, &flags);
2723 BUG_ON(p->state != TASK_RUNNING);
2724 update_rq_clock(rq);
2726 p->prio = effective_prio(p);
2728 if (!p->sched_class->task_new || !current->se.on_rq) {
2729 activate_task(rq, p, 0);
2730 } else {
2732 * Let the scheduling class do new task startup
2733 * management (if any):
2735 p->sched_class->task_new(rq, p);
2736 inc_nr_running(rq);
2738 check_preempt_curr(rq, p);
2739 #ifdef CONFIG_SMP
2740 if (p->sched_class->task_wake_up)
2741 p->sched_class->task_wake_up(rq, p);
2742 #endif
2743 task_rq_unlock(rq, &flags);
2746 #ifdef CONFIG_PREEMPT_NOTIFIERS
2749 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2750 * @notifier: notifier struct to register
2752 void preempt_notifier_register(struct preempt_notifier *notifier)
2754 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2756 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2759 * preempt_notifier_unregister - no longer interested in preemption notifications
2760 * @notifier: notifier struct to unregister
2762 * This is safe to call from within a preemption notifier.
2764 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2766 hlist_del(&notifier->link);
2768 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2770 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2772 struct preempt_notifier *notifier;
2773 struct hlist_node *node;
2775 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2776 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2779 static void
2780 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2781 struct task_struct *next)
2783 struct preempt_notifier *notifier;
2784 struct hlist_node *node;
2786 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2787 notifier->ops->sched_out(notifier, next);
2790 #else
2792 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2796 static void
2797 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2798 struct task_struct *next)
2802 #endif
2805 * prepare_task_switch - prepare to switch tasks
2806 * @rq: the runqueue preparing to switch
2807 * @prev: the current task that is being switched out
2808 * @next: the task we are going to switch to.
2810 * This is called with the rq lock held and interrupts off. It must
2811 * be paired with a subsequent finish_task_switch after the context
2812 * switch.
2814 * prepare_task_switch sets up locking and calls architecture specific
2815 * hooks.
2817 static inline void
2818 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2819 struct task_struct *next)
2821 fire_sched_out_preempt_notifiers(prev, next);
2822 prepare_lock_switch(rq, next);
2823 prepare_arch_switch(next);
2827 * finish_task_switch - clean up after a task-switch
2828 * @rq: runqueue associated with task-switch
2829 * @prev: the thread we just switched away from.
2831 * finish_task_switch must be called after the context switch, paired
2832 * with a prepare_task_switch call before the context switch.
2833 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2834 * and do any other architecture-specific cleanup actions.
2836 * Note that we may have delayed dropping an mm in context_switch(). If
2837 * so, we finish that here outside of the runqueue lock. (Doing it
2838 * with the lock held can cause deadlocks; see schedule() for
2839 * details.)
2841 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2842 __releases(rq->lock)
2844 struct mm_struct *mm = rq->prev_mm;
2845 long prev_state;
2847 rq->prev_mm = NULL;
2850 * A task struct has one reference for the use as "current".
2851 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2852 * schedule one last time. The schedule call will never return, and
2853 * the scheduled task must drop that reference.
2854 * The test for TASK_DEAD must occur while the runqueue locks are
2855 * still held, otherwise prev could be scheduled on another cpu, die
2856 * there before we look at prev->state, and then the reference would
2857 * be dropped twice.
2858 * Manfred Spraul <manfred@colorfullife.com>
2860 prev_state = prev->state;
2861 finish_arch_switch(prev);
2862 finish_lock_switch(rq, prev);
2863 #ifdef CONFIG_SMP
2864 if (current->sched_class->post_schedule)
2865 current->sched_class->post_schedule(rq);
2866 #endif
2868 fire_sched_in_preempt_notifiers(current);
2869 if (mm)
2870 mmdrop(mm);
2871 if (unlikely(prev_state == TASK_DEAD)) {
2873 * Remove function-return probe instances associated with this
2874 * task and put them back on the free list.
2876 kprobe_flush_task(prev);
2877 put_task_struct(prev);
2882 * schedule_tail - first thing a freshly forked thread must call.
2883 * @prev: the thread we just switched away from.
2885 asmlinkage void schedule_tail(struct task_struct *prev)
2886 __releases(rq->lock)
2888 struct rq *rq = this_rq();
2890 finish_task_switch(rq, prev);
2891 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2892 /* In this case, finish_task_switch does not reenable preemption */
2893 preempt_enable();
2894 #endif
2895 if (current->set_child_tid)
2896 put_user(task_pid_vnr(current), current->set_child_tid);
2900 * context_switch - switch to the new MM and the new
2901 * thread's register state.
2903 static inline void
2904 context_switch(struct rq *rq, struct task_struct *prev,
2905 struct task_struct *next)
2907 struct mm_struct *mm, *oldmm;
2909 prepare_task_switch(rq, prev, next);
2910 mm = next->mm;
2911 oldmm = prev->active_mm;
2913 * For paravirt, this is coupled with an exit in switch_to to
2914 * combine the page table reload and the switch backend into
2915 * one hypercall.
2917 arch_enter_lazy_cpu_mode();
2919 if (unlikely(!mm)) {
2920 next->active_mm = oldmm;
2921 atomic_inc(&oldmm->mm_count);
2922 enter_lazy_tlb(oldmm, next);
2923 } else
2924 switch_mm(oldmm, mm, next);
2926 if (unlikely(!prev->mm)) {
2927 prev->active_mm = NULL;
2928 rq->prev_mm = oldmm;
2931 * Since the runqueue lock will be released by the next
2932 * task (which is an invalid locking op but in the case
2933 * of the scheduler it's an obvious special-case), so we
2934 * do an early lockdep release here:
2936 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2937 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2938 #endif
2940 /* Here we just switch the register state and the stack. */
2941 switch_to(prev, next, prev);
2943 barrier();
2945 * this_rq must be evaluated again because prev may have moved
2946 * CPUs since it called schedule(), thus the 'rq' on its stack
2947 * frame will be invalid.
2949 finish_task_switch(this_rq(), prev);
2953 * nr_running, nr_uninterruptible and nr_context_switches:
2955 * externally visible scheduler statistics: current number of runnable
2956 * threads, current number of uninterruptible-sleeping threads, total
2957 * number of context switches performed since bootup.
2959 unsigned long nr_running(void)
2961 unsigned long i, sum = 0;
2963 for_each_online_cpu(i)
2964 sum += cpu_rq(i)->nr_running;
2966 return sum;
2969 unsigned long nr_uninterruptible(void)
2971 unsigned long i, sum = 0;
2973 for_each_possible_cpu(i)
2974 sum += cpu_rq(i)->nr_uninterruptible;
2977 * Since we read the counters lockless, it might be slightly
2978 * inaccurate. Do not allow it to go below zero though:
2980 if (unlikely((long)sum < 0))
2981 sum = 0;
2983 return sum;
2986 unsigned long long nr_context_switches(void)
2988 int i;
2989 unsigned long long sum = 0;
2991 for_each_possible_cpu(i)
2992 sum += cpu_rq(i)->nr_switches;
2994 return sum;
2997 unsigned long nr_iowait(void)
2999 unsigned long i, sum = 0;
3001 for_each_possible_cpu(i)
3002 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3004 return sum;
3007 unsigned long nr_active(void)
3009 unsigned long i, running = 0, uninterruptible = 0;
3011 for_each_online_cpu(i) {
3012 running += cpu_rq(i)->nr_running;
3013 uninterruptible += cpu_rq(i)->nr_uninterruptible;
3016 if (unlikely((long)uninterruptible < 0))
3017 uninterruptible = 0;
3019 return running + uninterruptible;
3023 * Update rq->cpu_load[] statistics. This function is usually called every
3024 * scheduler tick (TICK_NSEC).
3026 static void update_cpu_load(struct rq *this_rq)
3028 unsigned long this_load = this_rq->load.weight;
3029 int i, scale;
3031 this_rq->nr_load_updates++;
3033 /* Update our load: */
3034 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3035 unsigned long old_load, new_load;
3037 /* scale is effectively 1 << i now, and >> i divides by scale */
3039 old_load = this_rq->cpu_load[i];
3040 new_load = this_load;
3042 * Round up the averaging division if load is increasing. This
3043 * prevents us from getting stuck on 9 if the load is 10, for
3044 * example.
3046 if (new_load > old_load)
3047 new_load += scale-1;
3048 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3052 #ifdef CONFIG_SMP
3055 * double_rq_lock - safely lock two runqueues
3057 * Note this does not disable interrupts like task_rq_lock,
3058 * you need to do so manually before calling.
3060 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3061 __acquires(rq1->lock)
3062 __acquires(rq2->lock)
3064 BUG_ON(!irqs_disabled());
3065 if (rq1 == rq2) {
3066 spin_lock(&rq1->lock);
3067 __acquire(rq2->lock); /* Fake it out ;) */
3068 } else {
3069 if (rq1 < rq2) {
3070 spin_lock(&rq1->lock);
3071 spin_lock(&rq2->lock);
3072 } else {
3073 spin_lock(&rq2->lock);
3074 spin_lock(&rq1->lock);
3077 update_rq_clock(rq1);
3078 update_rq_clock(rq2);
3082 * double_rq_unlock - safely unlock two runqueues
3084 * Note this does not restore interrupts like task_rq_unlock,
3085 * you need to do so manually after calling.
3087 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3088 __releases(rq1->lock)
3089 __releases(rq2->lock)
3091 spin_unlock(&rq1->lock);
3092 if (rq1 != rq2)
3093 spin_unlock(&rq2->lock);
3094 else
3095 __release(rq2->lock);
3099 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
3101 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
3102 __releases(this_rq->lock)
3103 __acquires(busiest->lock)
3104 __acquires(this_rq->lock)
3106 int ret = 0;
3108 if (unlikely(!irqs_disabled())) {
3109 /* printk() doesn't work good under rq->lock */
3110 spin_unlock(&this_rq->lock);
3111 BUG_ON(1);
3113 if (unlikely(!spin_trylock(&busiest->lock))) {
3114 if (busiest < this_rq) {
3115 spin_unlock(&this_rq->lock);
3116 spin_lock(&busiest->lock);
3117 spin_lock(&this_rq->lock);
3118 ret = 1;
3119 } else
3120 spin_lock(&busiest->lock);
3122 return ret;
3126 * If dest_cpu is allowed for this process, migrate the task to it.
3127 * This is accomplished by forcing the cpu_allowed mask to only
3128 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3129 * the cpu_allowed mask is restored.
3131 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3133 struct migration_req req;
3134 unsigned long flags;
3135 struct rq *rq;
3137 rq = task_rq_lock(p, &flags);
3138 if (!cpu_isset(dest_cpu, p->cpus_allowed)
3139 || unlikely(cpu_is_offline(dest_cpu)))
3140 goto out;
3142 /* force the process onto the specified CPU */
3143 if (migrate_task(p, dest_cpu, &req)) {
3144 /* Need to wait for migration thread (might exit: take ref). */
3145 struct task_struct *mt = rq->migration_thread;
3147 get_task_struct(mt);
3148 task_rq_unlock(rq, &flags);
3149 wake_up_process(mt);
3150 put_task_struct(mt);
3151 wait_for_completion(&req.done);
3153 return;
3155 out:
3156 task_rq_unlock(rq, &flags);
3160 * sched_exec - execve() is a valuable balancing opportunity, because at
3161 * this point the task has the smallest effective memory and cache footprint.
3163 void sched_exec(void)
3165 int new_cpu, this_cpu = get_cpu();
3166 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3167 put_cpu();
3168 if (new_cpu != this_cpu)
3169 sched_migrate_task(current, new_cpu);
3173 * pull_task - move a task from a remote runqueue to the local runqueue.
3174 * Both runqueues must be locked.
3176 static void pull_task(struct rq *src_rq, struct task_struct *p,
3177 struct rq *this_rq, int this_cpu)
3179 deactivate_task(src_rq, p, 0);
3180 set_task_cpu(p, this_cpu);
3181 activate_task(this_rq, p, 0);
3183 * Note that idle threads have a prio of MAX_PRIO, for this test
3184 * to be always true for them.
3186 check_preempt_curr(this_rq, p);
3190 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3192 static
3193 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3194 struct sched_domain *sd, enum cpu_idle_type idle,
3195 int *all_pinned)
3198 * We do not migrate tasks that are:
3199 * 1) running (obviously), or
3200 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3201 * 3) are cache-hot on their current CPU.
3203 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
3204 schedstat_inc(p, se.nr_failed_migrations_affine);
3205 return 0;
3207 *all_pinned = 0;
3209 if (task_running(rq, p)) {
3210 schedstat_inc(p, se.nr_failed_migrations_running);
3211 return 0;
3215 * Aggressive migration if:
3216 * 1) task is cache cold, or
3217 * 2) too many balance attempts have failed.
3220 if (!task_hot(p, rq->clock, sd) ||
3221 sd->nr_balance_failed > sd->cache_nice_tries) {
3222 #ifdef CONFIG_SCHEDSTATS
3223 if (task_hot(p, rq->clock, sd)) {
3224 schedstat_inc(sd, lb_hot_gained[idle]);
3225 schedstat_inc(p, se.nr_forced_migrations);
3227 #endif
3228 return 1;
3231 if (task_hot(p, rq->clock, sd)) {
3232 schedstat_inc(p, se.nr_failed_migrations_hot);
3233 return 0;
3235 return 1;
3238 static unsigned long
3239 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3240 unsigned long max_load_move, struct sched_domain *sd,
3241 enum cpu_idle_type idle, int *all_pinned,
3242 int *this_best_prio, struct rq_iterator *iterator)
3244 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
3245 struct task_struct *p;
3246 long rem_load_move = max_load_move;
3248 if (max_load_move == 0)
3249 goto out;
3251 pinned = 1;
3254 * Start the load-balancing iterator:
3256 p = iterator->start(iterator->arg);
3257 next:
3258 if (!p || loops++ > sysctl_sched_nr_migrate)
3259 goto out;
3261 * To help distribute high priority tasks across CPUs we don't
3262 * skip a task if it will be the highest priority task (i.e. smallest
3263 * prio value) on its new queue regardless of its load weight
3265 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
3266 SCHED_LOAD_SCALE_FUZZ;
3267 if ((skip_for_load && p->prio >= *this_best_prio) ||
3268 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3269 p = iterator->next(iterator->arg);
3270 goto next;
3273 pull_task(busiest, p, this_rq, this_cpu);
3274 pulled++;
3275 rem_load_move -= p->se.load.weight;
3278 * We only want to steal up to the prescribed amount of weighted load.
3280 if (rem_load_move > 0) {
3281 if (p->prio < *this_best_prio)
3282 *this_best_prio = p->prio;
3283 p = iterator->next(iterator->arg);
3284 goto next;
3286 out:
3288 * Right now, this is one of only two places pull_task() is called,
3289 * so we can safely collect pull_task() stats here rather than
3290 * inside pull_task().
3292 schedstat_add(sd, lb_gained[idle], pulled);
3294 if (all_pinned)
3295 *all_pinned = pinned;
3297 return max_load_move - rem_load_move;
3301 * move_tasks tries to move up to max_load_move weighted load from busiest to
3302 * this_rq, as part of a balancing operation within domain "sd".
3303 * Returns 1 if successful and 0 otherwise.
3305 * Called with both runqueues locked.
3307 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3308 unsigned long max_load_move,
3309 struct sched_domain *sd, enum cpu_idle_type idle,
3310 int *all_pinned)
3312 const struct sched_class *class = sched_class_highest;
3313 unsigned long total_load_moved = 0;
3314 int this_best_prio = this_rq->curr->prio;
3316 do {
3317 total_load_moved +=
3318 class->load_balance(this_rq, this_cpu, busiest,
3319 max_load_move - total_load_moved,
3320 sd, idle, all_pinned, &this_best_prio);
3321 class = class->next;
3322 } while (class && max_load_move > total_load_moved);
3324 return total_load_moved > 0;
3327 static int
3328 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3329 struct sched_domain *sd, enum cpu_idle_type idle,
3330 struct rq_iterator *iterator)
3332 struct task_struct *p = iterator->start(iterator->arg);
3333 int pinned = 0;
3335 while (p) {
3336 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3337 pull_task(busiest, p, this_rq, this_cpu);
3339 * Right now, this is only the second place pull_task()
3340 * is called, so we can safely collect pull_task()
3341 * stats here rather than inside pull_task().
3343 schedstat_inc(sd, lb_gained[idle]);
3345 return 1;
3347 p = iterator->next(iterator->arg);
3350 return 0;
3354 * move_one_task tries to move exactly one task from busiest to this_rq, as
3355 * part of active balancing operations within "domain".
3356 * Returns 1 if successful and 0 otherwise.
3358 * Called with both runqueues locked.
3360 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3361 struct sched_domain *sd, enum cpu_idle_type idle)
3363 const struct sched_class *class;
3365 for (class = sched_class_highest; class; class = class->next)
3366 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3367 return 1;
3369 return 0;
3373 * find_busiest_group finds and returns the busiest CPU group within the
3374 * domain. It calculates and returns the amount of weighted load which
3375 * should be moved to restore balance via the imbalance parameter.
3377 static struct sched_group *
3378 find_busiest_group(struct sched_domain *sd, int this_cpu,
3379 unsigned long *imbalance, enum cpu_idle_type idle,
3380 int *sd_idle, const cpumask_t *cpus, int *balance)
3382 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3383 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3384 unsigned long max_pull;
3385 unsigned long busiest_load_per_task, busiest_nr_running;
3386 unsigned long this_load_per_task, this_nr_running;
3387 int load_idx, group_imb = 0;
3388 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3389 int power_savings_balance = 1;
3390 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3391 unsigned long min_nr_running = ULONG_MAX;
3392 struct sched_group *group_min = NULL, *group_leader = NULL;
3393 #endif
3395 max_load = this_load = total_load = total_pwr = 0;
3396 busiest_load_per_task = busiest_nr_running = 0;
3397 this_load_per_task = this_nr_running = 0;
3398 if (idle == CPU_NOT_IDLE)
3399 load_idx = sd->busy_idx;
3400 else if (idle == CPU_NEWLY_IDLE)
3401 load_idx = sd->newidle_idx;
3402 else
3403 load_idx = sd->idle_idx;
3405 do {
3406 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3407 int local_group;
3408 int i;
3409 int __group_imb = 0;
3410 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3411 unsigned long sum_nr_running, sum_weighted_load;
3413 local_group = cpu_isset(this_cpu, group->cpumask);
3415 if (local_group)
3416 balance_cpu = first_cpu(group->cpumask);
3418 /* Tally up the load of all CPUs in the group */
3419 sum_weighted_load = sum_nr_running = avg_load = 0;
3420 max_cpu_load = 0;
3421 min_cpu_load = ~0UL;
3423 for_each_cpu_mask(i, group->cpumask) {
3424 struct rq *rq;
3426 if (!cpu_isset(i, *cpus))
3427 continue;
3429 rq = cpu_rq(i);
3431 if (*sd_idle && rq->nr_running)
3432 *sd_idle = 0;
3434 /* Bias balancing toward cpus of our domain */
3435 if (local_group) {
3436 if (idle_cpu(i) && !first_idle_cpu) {
3437 first_idle_cpu = 1;
3438 balance_cpu = i;
3441 load = target_load(i, load_idx);
3442 } else {
3443 load = source_load(i, load_idx);
3444 if (load > max_cpu_load)
3445 max_cpu_load = load;
3446 if (min_cpu_load > load)
3447 min_cpu_load = load;
3450 avg_load += load;
3451 sum_nr_running += rq->nr_running;
3452 sum_weighted_load += weighted_cpuload(i);
3456 * First idle cpu or the first cpu(busiest) in this sched group
3457 * is eligible for doing load balancing at this and above
3458 * domains. In the newly idle case, we will allow all the cpu's
3459 * to do the newly idle load balance.
3461 if (idle != CPU_NEWLY_IDLE && local_group &&
3462 balance_cpu != this_cpu && balance) {
3463 *balance = 0;
3464 goto ret;
3467 total_load += avg_load;
3468 total_pwr += group->__cpu_power;
3470 /* Adjust by relative CPU power of the group */
3471 avg_load = sg_div_cpu_power(group,
3472 avg_load * SCHED_LOAD_SCALE);
3474 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
3475 __group_imb = 1;
3477 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3479 if (local_group) {
3480 this_load = avg_load;
3481 this = group;
3482 this_nr_running = sum_nr_running;
3483 this_load_per_task = sum_weighted_load;
3484 } else if (avg_load > max_load &&
3485 (sum_nr_running > group_capacity || __group_imb)) {
3486 max_load = avg_load;
3487 busiest = group;
3488 busiest_nr_running = sum_nr_running;
3489 busiest_load_per_task = sum_weighted_load;
3490 group_imb = __group_imb;
3493 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3495 * Busy processors will not participate in power savings
3496 * balance.
3498 if (idle == CPU_NOT_IDLE ||
3499 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3500 goto group_next;
3503 * If the local group is idle or completely loaded
3504 * no need to do power savings balance at this domain
3506 if (local_group && (this_nr_running >= group_capacity ||
3507 !this_nr_running))
3508 power_savings_balance = 0;
3511 * If a group is already running at full capacity or idle,
3512 * don't include that group in power savings calculations
3514 if (!power_savings_balance || sum_nr_running >= group_capacity
3515 || !sum_nr_running)
3516 goto group_next;
3519 * Calculate the group which has the least non-idle load.
3520 * This is the group from where we need to pick up the load
3521 * for saving power
3523 if ((sum_nr_running < min_nr_running) ||
3524 (sum_nr_running == min_nr_running &&
3525 first_cpu(group->cpumask) <
3526 first_cpu(group_min->cpumask))) {
3527 group_min = group;
3528 min_nr_running = sum_nr_running;
3529 min_load_per_task = sum_weighted_load /
3530 sum_nr_running;
3534 * Calculate the group which is almost near its
3535 * capacity but still has some space to pick up some load
3536 * from other group and save more power
3538 if (sum_nr_running <= group_capacity - 1) {
3539 if (sum_nr_running > leader_nr_running ||
3540 (sum_nr_running == leader_nr_running &&
3541 first_cpu(group->cpumask) >
3542 first_cpu(group_leader->cpumask))) {
3543 group_leader = group;
3544 leader_nr_running = sum_nr_running;
3547 group_next:
3548 #endif
3549 group = group->next;
3550 } while (group != sd->groups);
3552 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3553 goto out_balanced;
3555 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3557 if (this_load >= avg_load ||
3558 100*max_load <= sd->imbalance_pct*this_load)
3559 goto out_balanced;
3561 busiest_load_per_task /= busiest_nr_running;
3562 if (group_imb)
3563 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3566 * We're trying to get all the cpus to the average_load, so we don't
3567 * want to push ourselves above the average load, nor do we wish to
3568 * reduce the max loaded cpu below the average load, as either of these
3569 * actions would just result in more rebalancing later, and ping-pong
3570 * tasks around. Thus we look for the minimum possible imbalance.
3571 * Negative imbalances (*we* are more loaded than anyone else) will
3572 * be counted as no imbalance for these purposes -- we can't fix that
3573 * by pulling tasks to us. Be careful of negative numbers as they'll
3574 * appear as very large values with unsigned longs.
3576 if (max_load <= busiest_load_per_task)
3577 goto out_balanced;
3580 * In the presence of smp nice balancing, certain scenarios can have
3581 * max load less than avg load(as we skip the groups at or below
3582 * its cpu_power, while calculating max_load..)
3584 if (max_load < avg_load) {
3585 *imbalance = 0;
3586 goto small_imbalance;
3589 /* Don't want to pull so many tasks that a group would go idle */
3590 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3592 /* How much load to actually move to equalise the imbalance */
3593 *imbalance = min(max_pull * busiest->__cpu_power,
3594 (avg_load - this_load) * this->__cpu_power)
3595 / SCHED_LOAD_SCALE;
3598 * if *imbalance is less than the average load per runnable task
3599 * there is no gaurantee that any tasks will be moved so we'll have
3600 * a think about bumping its value to force at least one task to be
3601 * moved
3603 if (*imbalance < busiest_load_per_task) {
3604 unsigned long tmp, pwr_now, pwr_move;
3605 unsigned int imbn;
3607 small_imbalance:
3608 pwr_move = pwr_now = 0;
3609 imbn = 2;
3610 if (this_nr_running) {
3611 this_load_per_task /= this_nr_running;
3612 if (busiest_load_per_task > this_load_per_task)
3613 imbn = 1;
3614 } else
3615 this_load_per_task = SCHED_LOAD_SCALE;
3617 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3618 busiest_load_per_task * imbn) {
3619 *imbalance = busiest_load_per_task;
3620 return busiest;
3624 * OK, we don't have enough imbalance to justify moving tasks,
3625 * however we may be able to increase total CPU power used by
3626 * moving them.
3629 pwr_now += busiest->__cpu_power *
3630 min(busiest_load_per_task, max_load);
3631 pwr_now += this->__cpu_power *
3632 min(this_load_per_task, this_load);
3633 pwr_now /= SCHED_LOAD_SCALE;
3635 /* Amount of load we'd subtract */
3636 tmp = sg_div_cpu_power(busiest,
3637 busiest_load_per_task * SCHED_LOAD_SCALE);
3638 if (max_load > tmp)
3639 pwr_move += busiest->__cpu_power *
3640 min(busiest_load_per_task, max_load - tmp);
3642 /* Amount of load we'd add */
3643 if (max_load * busiest->__cpu_power <
3644 busiest_load_per_task * SCHED_LOAD_SCALE)
3645 tmp = sg_div_cpu_power(this,
3646 max_load * busiest->__cpu_power);
3647 else
3648 tmp = sg_div_cpu_power(this,
3649 busiest_load_per_task * SCHED_LOAD_SCALE);
3650 pwr_move += this->__cpu_power *
3651 min(this_load_per_task, this_load + tmp);
3652 pwr_move /= SCHED_LOAD_SCALE;
3654 /* Move if we gain throughput */
3655 if (pwr_move > pwr_now)
3656 *imbalance = busiest_load_per_task;
3659 return busiest;
3661 out_balanced:
3662 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3663 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3664 goto ret;
3666 if (this == group_leader && group_leader != group_min) {
3667 *imbalance = min_load_per_task;
3668 return group_min;
3670 #endif
3671 ret:
3672 *imbalance = 0;
3673 return NULL;
3677 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3679 static struct rq *
3680 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3681 unsigned long imbalance, const cpumask_t *cpus)
3683 struct rq *busiest = NULL, *rq;
3684 unsigned long max_load = 0;
3685 int i;
3687 for_each_cpu_mask(i, group->cpumask) {
3688 unsigned long wl;
3690 if (!cpu_isset(i, *cpus))
3691 continue;
3693 rq = cpu_rq(i);
3694 wl = weighted_cpuload(i);
3696 if (rq->nr_running == 1 && wl > imbalance)
3697 continue;
3699 if (wl > max_load) {
3700 max_load = wl;
3701 busiest = rq;
3705 return busiest;
3709 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3710 * so long as it is large enough.
3712 #define MAX_PINNED_INTERVAL 512
3715 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3716 * tasks if there is an imbalance.
3718 static int load_balance(int this_cpu, struct rq *this_rq,
3719 struct sched_domain *sd, enum cpu_idle_type idle,
3720 int *balance, cpumask_t *cpus)
3722 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3723 struct sched_group *group;
3724 unsigned long imbalance;
3725 struct rq *busiest;
3726 unsigned long flags;
3727 int unlock_aggregate;
3729 cpus_setall(*cpus);
3731 unlock_aggregate = get_aggregate(sd);
3734 * When power savings policy is enabled for the parent domain, idle
3735 * sibling can pick up load irrespective of busy siblings. In this case,
3736 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3737 * portraying it as CPU_NOT_IDLE.
3739 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3740 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3741 sd_idle = 1;
3743 schedstat_inc(sd, lb_count[idle]);
3745 redo:
3746 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3747 cpus, balance);
3749 if (*balance == 0)
3750 goto out_balanced;
3752 if (!group) {
3753 schedstat_inc(sd, lb_nobusyg[idle]);
3754 goto out_balanced;
3757 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3758 if (!busiest) {
3759 schedstat_inc(sd, lb_nobusyq[idle]);
3760 goto out_balanced;
3763 BUG_ON(busiest == this_rq);
3765 schedstat_add(sd, lb_imbalance[idle], imbalance);
3767 ld_moved = 0;
3768 if (busiest->nr_running > 1) {
3770 * Attempt to move tasks. If find_busiest_group has found
3771 * an imbalance but busiest->nr_running <= 1, the group is
3772 * still unbalanced. ld_moved simply stays zero, so it is
3773 * correctly treated as an imbalance.
3775 local_irq_save(flags);
3776 double_rq_lock(this_rq, busiest);
3777 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3778 imbalance, sd, idle, &all_pinned);
3779 double_rq_unlock(this_rq, busiest);
3780 local_irq_restore(flags);
3783 * some other cpu did the load balance for us.
3785 if (ld_moved && this_cpu != smp_processor_id())
3786 resched_cpu(this_cpu);
3788 /* All tasks on this runqueue were pinned by CPU affinity */
3789 if (unlikely(all_pinned)) {
3790 cpu_clear(cpu_of(busiest), *cpus);
3791 if (!cpus_empty(*cpus))
3792 goto redo;
3793 goto out_balanced;
3797 if (!ld_moved) {
3798 schedstat_inc(sd, lb_failed[idle]);
3799 sd->nr_balance_failed++;
3801 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3803 spin_lock_irqsave(&busiest->lock, flags);
3805 /* don't kick the migration_thread, if the curr
3806 * task on busiest cpu can't be moved to this_cpu
3808 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3809 spin_unlock_irqrestore(&busiest->lock, flags);
3810 all_pinned = 1;
3811 goto out_one_pinned;
3814 if (!busiest->active_balance) {
3815 busiest->active_balance = 1;
3816 busiest->push_cpu = this_cpu;
3817 active_balance = 1;
3819 spin_unlock_irqrestore(&busiest->lock, flags);
3820 if (active_balance)
3821 wake_up_process(busiest->migration_thread);
3824 * We've kicked active balancing, reset the failure
3825 * counter.
3827 sd->nr_balance_failed = sd->cache_nice_tries+1;
3829 } else
3830 sd->nr_balance_failed = 0;
3832 if (likely(!active_balance)) {
3833 /* We were unbalanced, so reset the balancing interval */
3834 sd->balance_interval = sd->min_interval;
3835 } else {
3837 * If we've begun active balancing, start to back off. This
3838 * case may not be covered by the all_pinned logic if there
3839 * is only 1 task on the busy runqueue (because we don't call
3840 * move_tasks).
3842 if (sd->balance_interval < sd->max_interval)
3843 sd->balance_interval *= 2;
3846 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3847 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3848 ld_moved = -1;
3850 goto out;
3852 out_balanced:
3853 schedstat_inc(sd, lb_balanced[idle]);
3855 sd->nr_balance_failed = 0;
3857 out_one_pinned:
3858 /* tune up the balancing interval */
3859 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3860 (sd->balance_interval < sd->max_interval))
3861 sd->balance_interval *= 2;
3863 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3864 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3865 ld_moved = -1;
3866 else
3867 ld_moved = 0;
3868 out:
3869 if (unlock_aggregate)
3870 put_aggregate(sd);
3871 return ld_moved;
3875 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3876 * tasks if there is an imbalance.
3878 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3879 * this_rq is locked.
3881 static int
3882 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3883 cpumask_t *cpus)
3885 struct sched_group *group;
3886 struct rq *busiest = NULL;
3887 unsigned long imbalance;
3888 int ld_moved = 0;
3889 int sd_idle = 0;
3890 int all_pinned = 0;
3892 cpus_setall(*cpus);
3895 * When power savings policy is enabled for the parent domain, idle
3896 * sibling can pick up load irrespective of busy siblings. In this case,
3897 * let the state of idle sibling percolate up as IDLE, instead of
3898 * portraying it as CPU_NOT_IDLE.
3900 if (sd->flags & SD_SHARE_CPUPOWER &&
3901 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3902 sd_idle = 1;
3904 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3905 redo:
3906 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3907 &sd_idle, cpus, NULL);
3908 if (!group) {
3909 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3910 goto out_balanced;
3913 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3914 if (!busiest) {
3915 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3916 goto out_balanced;
3919 BUG_ON(busiest == this_rq);
3921 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3923 ld_moved = 0;
3924 if (busiest->nr_running > 1) {
3925 /* Attempt to move tasks */
3926 double_lock_balance(this_rq, busiest);
3927 /* this_rq->clock is already updated */
3928 update_rq_clock(busiest);
3929 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3930 imbalance, sd, CPU_NEWLY_IDLE,
3931 &all_pinned);
3932 spin_unlock(&busiest->lock);
3934 if (unlikely(all_pinned)) {
3935 cpu_clear(cpu_of(busiest), *cpus);
3936 if (!cpus_empty(*cpus))
3937 goto redo;
3941 if (!ld_moved) {
3942 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3943 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3944 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3945 return -1;
3946 } else
3947 sd->nr_balance_failed = 0;
3949 return ld_moved;
3951 out_balanced:
3952 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3953 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3954 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3955 return -1;
3956 sd->nr_balance_failed = 0;
3958 return 0;
3962 * idle_balance is called by schedule() if this_cpu is about to become
3963 * idle. Attempts to pull tasks from other CPUs.
3965 static void idle_balance(int this_cpu, struct rq *this_rq)
3967 struct sched_domain *sd;
3968 int pulled_task = -1;
3969 unsigned long next_balance = jiffies + HZ;
3970 cpumask_t tmpmask;
3972 for_each_domain(this_cpu, sd) {
3973 unsigned long interval;
3975 if (!(sd->flags & SD_LOAD_BALANCE))
3976 continue;
3978 if (sd->flags & SD_BALANCE_NEWIDLE)
3979 /* If we've pulled tasks over stop searching: */
3980 pulled_task = load_balance_newidle(this_cpu, this_rq,
3981 sd, &tmpmask);
3983 interval = msecs_to_jiffies(sd->balance_interval);
3984 if (time_after(next_balance, sd->last_balance + interval))
3985 next_balance = sd->last_balance + interval;
3986 if (pulled_task)
3987 break;
3989 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3991 * We are going idle. next_balance may be set based on
3992 * a busy processor. So reset next_balance.
3994 this_rq->next_balance = next_balance;
3999 * active_load_balance is run by migration threads. It pushes running tasks
4000 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4001 * running on each physical CPU where possible, and avoids physical /
4002 * logical imbalances.
4004 * Called with busiest_rq locked.
4006 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4008 int target_cpu = busiest_rq->push_cpu;
4009 struct sched_domain *sd;
4010 struct rq *target_rq;
4012 /* Is there any task to move? */
4013 if (busiest_rq->nr_running <= 1)
4014 return;
4016 target_rq = cpu_rq(target_cpu);
4019 * This condition is "impossible", if it occurs
4020 * we need to fix it. Originally reported by
4021 * Bjorn Helgaas on a 128-cpu setup.
4023 BUG_ON(busiest_rq == target_rq);
4025 /* move a task from busiest_rq to target_rq */
4026 double_lock_balance(busiest_rq, target_rq);
4027 update_rq_clock(busiest_rq);
4028 update_rq_clock(target_rq);
4030 /* Search for an sd spanning us and the target CPU. */
4031 for_each_domain(target_cpu, sd) {
4032 if ((sd->flags & SD_LOAD_BALANCE) &&
4033 cpu_isset(busiest_cpu, sd->span))
4034 break;
4037 if (likely(sd)) {
4038 schedstat_inc(sd, alb_count);
4040 if (move_one_task(target_rq, target_cpu, busiest_rq,
4041 sd, CPU_IDLE))
4042 schedstat_inc(sd, alb_pushed);
4043 else
4044 schedstat_inc(sd, alb_failed);
4046 spin_unlock(&target_rq->lock);
4049 #ifdef CONFIG_NO_HZ
4050 static struct {
4051 atomic_t load_balancer;
4052 cpumask_t cpu_mask;
4053 } nohz ____cacheline_aligned = {
4054 .load_balancer = ATOMIC_INIT(-1),
4055 .cpu_mask = CPU_MASK_NONE,
4059 * This routine will try to nominate the ilb (idle load balancing)
4060 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4061 * load balancing on behalf of all those cpus. If all the cpus in the system
4062 * go into this tickless mode, then there will be no ilb owner (as there is
4063 * no need for one) and all the cpus will sleep till the next wakeup event
4064 * arrives...
4066 * For the ilb owner, tick is not stopped. And this tick will be used
4067 * for idle load balancing. ilb owner will still be part of
4068 * nohz.cpu_mask..
4070 * While stopping the tick, this cpu will become the ilb owner if there
4071 * is no other owner. And will be the owner till that cpu becomes busy
4072 * or if all cpus in the system stop their ticks at which point
4073 * there is no need for ilb owner.
4075 * When the ilb owner becomes busy, it nominates another owner, during the
4076 * next busy scheduler_tick()
4078 int select_nohz_load_balancer(int stop_tick)
4080 int cpu = smp_processor_id();
4082 if (stop_tick) {
4083 cpu_set(cpu, nohz.cpu_mask);
4084 cpu_rq(cpu)->in_nohz_recently = 1;
4087 * If we are going offline and still the leader, give up!
4089 if (cpu_is_offline(cpu) &&
4090 atomic_read(&nohz.load_balancer) == cpu) {
4091 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4092 BUG();
4093 return 0;
4096 /* time for ilb owner also to sleep */
4097 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4098 if (atomic_read(&nohz.load_balancer) == cpu)
4099 atomic_set(&nohz.load_balancer, -1);
4100 return 0;
4103 if (atomic_read(&nohz.load_balancer) == -1) {
4104 /* make me the ilb owner */
4105 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4106 return 1;
4107 } else if (atomic_read(&nohz.load_balancer) == cpu)
4108 return 1;
4109 } else {
4110 if (!cpu_isset(cpu, nohz.cpu_mask))
4111 return 0;
4113 cpu_clear(cpu, nohz.cpu_mask);
4115 if (atomic_read(&nohz.load_balancer) == cpu)
4116 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4117 BUG();
4119 return 0;
4121 #endif
4123 static DEFINE_SPINLOCK(balancing);
4126 * It checks each scheduling domain to see if it is due to be balanced,
4127 * and initiates a balancing operation if so.
4129 * Balancing parameters are set up in arch_init_sched_domains.
4131 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4133 int balance = 1;
4134 struct rq *rq = cpu_rq(cpu);
4135 unsigned long interval;
4136 struct sched_domain *sd;
4137 /* Earliest time when we have to do rebalance again */
4138 unsigned long next_balance = jiffies + 60*HZ;
4139 int update_next_balance = 0;
4140 cpumask_t tmp;
4142 for_each_domain(cpu, sd) {
4143 if (!(sd->flags & SD_LOAD_BALANCE))
4144 continue;
4146 interval = sd->balance_interval;
4147 if (idle != CPU_IDLE)
4148 interval *= sd->busy_factor;
4150 /* scale ms to jiffies */
4151 interval = msecs_to_jiffies(interval);
4152 if (unlikely(!interval))
4153 interval = 1;
4154 if (interval > HZ*NR_CPUS/10)
4155 interval = HZ*NR_CPUS/10;
4158 if (sd->flags & SD_SERIALIZE) {
4159 if (!spin_trylock(&balancing))
4160 goto out;
4163 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4164 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
4166 * We've pulled tasks over so either we're no
4167 * longer idle, or one of our SMT siblings is
4168 * not idle.
4170 idle = CPU_NOT_IDLE;
4172 sd->last_balance = jiffies;
4174 if (sd->flags & SD_SERIALIZE)
4175 spin_unlock(&balancing);
4176 out:
4177 if (time_after(next_balance, sd->last_balance + interval)) {
4178 next_balance = sd->last_balance + interval;
4179 update_next_balance = 1;
4183 * Stop the load balance at this level. There is another
4184 * CPU in our sched group which is doing load balancing more
4185 * actively.
4187 if (!balance)
4188 break;
4192 * next_balance will be updated only when there is a need.
4193 * When the cpu is attached to null domain for ex, it will not be
4194 * updated.
4196 if (likely(update_next_balance))
4197 rq->next_balance = next_balance;
4201 * run_rebalance_domains is triggered when needed from the scheduler tick.
4202 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4203 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4205 static void run_rebalance_domains(struct softirq_action *h)
4207 int this_cpu = smp_processor_id();
4208 struct rq *this_rq = cpu_rq(this_cpu);
4209 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4210 CPU_IDLE : CPU_NOT_IDLE;
4212 rebalance_domains(this_cpu, idle);
4214 #ifdef CONFIG_NO_HZ
4216 * If this cpu is the owner for idle load balancing, then do the
4217 * balancing on behalf of the other idle cpus whose ticks are
4218 * stopped.
4220 if (this_rq->idle_at_tick &&
4221 atomic_read(&nohz.load_balancer) == this_cpu) {
4222 cpumask_t cpus = nohz.cpu_mask;
4223 struct rq *rq;
4224 int balance_cpu;
4226 cpu_clear(this_cpu, cpus);
4227 for_each_cpu_mask(balance_cpu, cpus) {
4229 * If this cpu gets work to do, stop the load balancing
4230 * work being done for other cpus. Next load
4231 * balancing owner will pick it up.
4233 if (need_resched())
4234 break;
4236 rebalance_domains(balance_cpu, CPU_IDLE);
4238 rq = cpu_rq(balance_cpu);
4239 if (time_after(this_rq->next_balance, rq->next_balance))
4240 this_rq->next_balance = rq->next_balance;
4243 #endif
4247 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4249 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4250 * idle load balancing owner or decide to stop the periodic load balancing,
4251 * if the whole system is idle.
4253 static inline void trigger_load_balance(struct rq *rq, int cpu)
4255 #ifdef CONFIG_NO_HZ
4257 * If we were in the nohz mode recently and busy at the current
4258 * scheduler tick, then check if we need to nominate new idle
4259 * load balancer.
4261 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4262 rq->in_nohz_recently = 0;
4264 if (atomic_read(&nohz.load_balancer) == cpu) {
4265 cpu_clear(cpu, nohz.cpu_mask);
4266 atomic_set(&nohz.load_balancer, -1);
4269 if (atomic_read(&nohz.load_balancer) == -1) {
4271 * simple selection for now: Nominate the
4272 * first cpu in the nohz list to be the next
4273 * ilb owner.
4275 * TBD: Traverse the sched domains and nominate
4276 * the nearest cpu in the nohz.cpu_mask.
4278 int ilb = first_cpu(nohz.cpu_mask);
4280 if (ilb < nr_cpu_ids)
4281 resched_cpu(ilb);
4286 * If this cpu is idle and doing idle load balancing for all the
4287 * cpus with ticks stopped, is it time for that to stop?
4289 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4290 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4291 resched_cpu(cpu);
4292 return;
4296 * If this cpu is idle and the idle load balancing is done by
4297 * someone else, then no need raise the SCHED_SOFTIRQ
4299 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4300 cpu_isset(cpu, nohz.cpu_mask))
4301 return;
4302 #endif
4303 if (time_after_eq(jiffies, rq->next_balance))
4304 raise_softirq(SCHED_SOFTIRQ);
4307 #else /* CONFIG_SMP */
4310 * on UP we do not need to balance between CPUs:
4312 static inline void idle_balance(int cpu, struct rq *rq)
4316 #endif
4318 DEFINE_PER_CPU(struct kernel_stat, kstat);
4320 EXPORT_PER_CPU_SYMBOL(kstat);
4323 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4324 * that have not yet been banked in case the task is currently running.
4326 unsigned long long task_sched_runtime(struct task_struct *p)
4328 unsigned long flags;
4329 u64 ns, delta_exec;
4330 struct rq *rq;
4332 rq = task_rq_lock(p, &flags);
4333 ns = p->se.sum_exec_runtime;
4334 if (task_current(rq, p)) {
4335 update_rq_clock(rq);
4336 delta_exec = rq->clock - p->se.exec_start;
4337 if ((s64)delta_exec > 0)
4338 ns += delta_exec;
4340 task_rq_unlock(rq, &flags);
4342 return ns;
4346 * Account user cpu time to a process.
4347 * @p: the process that the cpu time gets accounted to
4348 * @cputime: the cpu time spent in user space since the last update
4350 void account_user_time(struct task_struct *p, cputime_t cputime)
4352 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4353 cputime64_t tmp;
4355 p->utime = cputime_add(p->utime, cputime);
4357 /* Add user time to cpustat. */
4358 tmp = cputime_to_cputime64(cputime);
4359 if (TASK_NICE(p) > 0)
4360 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4361 else
4362 cpustat->user = cputime64_add(cpustat->user, tmp);
4366 * Account guest cpu time to a process.
4367 * @p: the process that the cpu time gets accounted to
4368 * @cputime: the cpu time spent in virtual machine since the last update
4370 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4372 cputime64_t tmp;
4373 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4375 tmp = cputime_to_cputime64(cputime);
4377 p->utime = cputime_add(p->utime, cputime);
4378 p->gtime = cputime_add(p->gtime, cputime);
4380 cpustat->user = cputime64_add(cpustat->user, tmp);
4381 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4385 * Account scaled user cpu time to a process.
4386 * @p: the process that the cpu time gets accounted to
4387 * @cputime: the cpu time spent in user space since the last update
4389 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4391 p->utimescaled = cputime_add(p->utimescaled, cputime);
4395 * Account system cpu time to a process.
4396 * @p: the process that the cpu time gets accounted to
4397 * @hardirq_offset: the offset to subtract from hardirq_count()
4398 * @cputime: the cpu time spent in kernel space since the last update
4400 void account_system_time(struct task_struct *p, int hardirq_offset,
4401 cputime_t cputime)
4403 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4404 struct rq *rq = this_rq();
4405 cputime64_t tmp;
4407 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4408 account_guest_time(p, cputime);
4409 return;
4412 p->stime = cputime_add(p->stime, cputime);
4414 /* Add system time to cpustat. */
4415 tmp = cputime_to_cputime64(cputime);
4416 if (hardirq_count() - hardirq_offset)
4417 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4418 else if (softirq_count())
4419 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4420 else if (p != rq->idle)
4421 cpustat->system = cputime64_add(cpustat->system, tmp);
4422 else if (atomic_read(&rq->nr_iowait) > 0)
4423 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4424 else
4425 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4426 /* Account for system time used */
4427 acct_update_integrals(p);
4431 * Account scaled system cpu time to a process.
4432 * @p: the process that the cpu time gets accounted to
4433 * @hardirq_offset: the offset to subtract from hardirq_count()
4434 * @cputime: the cpu time spent in kernel space since the last update
4436 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4438 p->stimescaled = cputime_add(p->stimescaled, cputime);
4442 * Account for involuntary wait time.
4443 * @p: the process from which the cpu time has been stolen
4444 * @steal: the cpu time spent in involuntary wait
4446 void account_steal_time(struct task_struct *p, cputime_t steal)
4448 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4449 cputime64_t tmp = cputime_to_cputime64(steal);
4450 struct rq *rq = this_rq();
4452 if (p == rq->idle) {
4453 p->stime = cputime_add(p->stime, steal);
4454 if (atomic_read(&rq->nr_iowait) > 0)
4455 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4456 else
4457 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4458 } else
4459 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4463 * This function gets called by the timer code, with HZ frequency.
4464 * We call it with interrupts disabled.
4466 * It also gets called by the fork code, when changing the parent's
4467 * timeslices.
4469 void scheduler_tick(void)
4471 int cpu = smp_processor_id();
4472 struct rq *rq = cpu_rq(cpu);
4473 struct task_struct *curr = rq->curr;
4474 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
4476 spin_lock(&rq->lock);
4477 __update_rq_clock(rq);
4479 * Let rq->clock advance by at least TICK_NSEC:
4481 if (unlikely(rq->clock < next_tick)) {
4482 rq->clock = next_tick;
4483 rq->clock_underflows++;
4485 rq->tick_timestamp = rq->clock;
4486 update_last_tick_seen(rq);
4487 update_cpu_load(rq);
4488 curr->sched_class->task_tick(rq, curr, 0);
4489 spin_unlock(&rq->lock);
4491 #ifdef CONFIG_SMP
4492 rq->idle_at_tick = idle_cpu(cpu);
4493 trigger_load_balance(rq, cpu);
4494 #endif
4497 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4499 void __kprobes add_preempt_count(int val)
4502 * Underflow?
4504 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4505 return;
4506 preempt_count() += val;
4508 * Spinlock count overflowing soon?
4510 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4511 PREEMPT_MASK - 10);
4513 EXPORT_SYMBOL(add_preempt_count);
4515 void __kprobes sub_preempt_count(int val)
4518 * Underflow?
4520 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4521 return;
4523 * Is the spinlock portion underflowing?
4525 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4526 !(preempt_count() & PREEMPT_MASK)))
4527 return;
4529 preempt_count() -= val;
4531 EXPORT_SYMBOL(sub_preempt_count);
4533 #endif
4536 * Print scheduling while atomic bug:
4538 static noinline void __schedule_bug(struct task_struct *prev)
4540 struct pt_regs *regs = get_irq_regs();
4542 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4543 prev->comm, prev->pid, preempt_count());
4545 debug_show_held_locks(prev);
4546 if (irqs_disabled())
4547 print_irqtrace_events(prev);
4549 if (regs)
4550 show_regs(regs);
4551 else
4552 dump_stack();
4556 * Various schedule()-time debugging checks and statistics:
4558 static inline void schedule_debug(struct task_struct *prev)
4561 * Test if we are atomic. Since do_exit() needs to call into
4562 * schedule() atomically, we ignore that path for now.
4563 * Otherwise, whine if we are scheduling when we should not be.
4565 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4566 __schedule_bug(prev);
4568 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4570 schedstat_inc(this_rq(), sched_count);
4571 #ifdef CONFIG_SCHEDSTATS
4572 if (unlikely(prev->lock_depth >= 0)) {
4573 schedstat_inc(this_rq(), bkl_count);
4574 schedstat_inc(prev, sched_info.bkl_count);
4576 #endif
4580 * Pick up the highest-prio task:
4582 static inline struct task_struct *
4583 pick_next_task(struct rq *rq, struct task_struct *prev)
4585 const struct sched_class *class;
4586 struct task_struct *p;
4589 * Optimization: we know that if all tasks are in
4590 * the fair class we can call that function directly:
4592 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4593 p = fair_sched_class.pick_next_task(rq);
4594 if (likely(p))
4595 return p;
4598 class = sched_class_highest;
4599 for ( ; ; ) {
4600 p = class->pick_next_task(rq);
4601 if (p)
4602 return p;
4604 * Will never be NULL as the idle class always
4605 * returns a non-NULL p:
4607 class = class->next;
4612 * schedule() is the main scheduler function.
4614 asmlinkage void __sched schedule(void)
4616 struct task_struct *prev, *next;
4617 unsigned long *switch_count;
4618 struct rq *rq;
4619 int cpu;
4621 need_resched:
4622 preempt_disable();
4623 cpu = smp_processor_id();
4624 rq = cpu_rq(cpu);
4625 rcu_qsctr_inc(cpu);
4626 prev = rq->curr;
4627 switch_count = &prev->nivcsw;
4629 release_kernel_lock(prev);
4630 need_resched_nonpreemptible:
4632 schedule_debug(prev);
4634 hrtick_clear(rq);
4637 * Do the rq-clock update outside the rq lock:
4639 local_irq_disable();
4640 __update_rq_clock(rq);
4641 spin_lock(&rq->lock);
4642 clear_tsk_need_resched(prev);
4644 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4645 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4646 signal_pending(prev))) {
4647 prev->state = TASK_RUNNING;
4648 } else {
4649 deactivate_task(rq, prev, 1);
4651 switch_count = &prev->nvcsw;
4654 #ifdef CONFIG_SMP
4655 if (prev->sched_class->pre_schedule)
4656 prev->sched_class->pre_schedule(rq, prev);
4657 #endif
4659 if (unlikely(!rq->nr_running))
4660 idle_balance(cpu, rq);
4662 prev->sched_class->put_prev_task(rq, prev);
4663 next = pick_next_task(rq, prev);
4665 sched_info_switch(prev, next);
4667 if (likely(prev != next)) {
4668 rq->nr_switches++;
4669 rq->curr = next;
4670 ++*switch_count;
4672 context_switch(rq, prev, next); /* unlocks the rq */
4674 * the context switch might have flipped the stack from under
4675 * us, hence refresh the local variables.
4677 cpu = smp_processor_id();
4678 rq = cpu_rq(cpu);
4679 } else
4680 spin_unlock_irq(&rq->lock);
4682 hrtick_set(rq);
4684 if (unlikely(reacquire_kernel_lock(current) < 0))
4685 goto need_resched_nonpreemptible;
4687 preempt_enable_no_resched();
4688 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4689 goto need_resched;
4691 EXPORT_SYMBOL(schedule);
4693 #ifdef CONFIG_PREEMPT
4695 * this is the entry point to schedule() from in-kernel preemption
4696 * off of preempt_enable. Kernel preemptions off return from interrupt
4697 * occur there and call schedule directly.
4699 asmlinkage void __sched preempt_schedule(void)
4701 struct thread_info *ti = current_thread_info();
4702 struct task_struct *task = current;
4703 int saved_lock_depth;
4706 * If there is a non-zero preempt_count or interrupts are disabled,
4707 * we do not want to preempt the current task. Just return..
4709 if (likely(ti->preempt_count || irqs_disabled()))
4710 return;
4712 do {
4713 add_preempt_count(PREEMPT_ACTIVE);
4716 * We keep the big kernel semaphore locked, but we
4717 * clear ->lock_depth so that schedule() doesnt
4718 * auto-release the semaphore:
4720 saved_lock_depth = task->lock_depth;
4721 task->lock_depth = -1;
4722 schedule();
4723 task->lock_depth = saved_lock_depth;
4724 sub_preempt_count(PREEMPT_ACTIVE);
4727 * Check again in case we missed a preemption opportunity
4728 * between schedule and now.
4730 barrier();
4731 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4733 EXPORT_SYMBOL(preempt_schedule);
4736 * this is the entry point to schedule() from kernel preemption
4737 * off of irq context.
4738 * Note, that this is called and return with irqs disabled. This will
4739 * protect us against recursive calling from irq.
4741 asmlinkage void __sched preempt_schedule_irq(void)
4743 struct thread_info *ti = current_thread_info();
4744 struct task_struct *task = current;
4745 int saved_lock_depth;
4747 /* Catch callers which need to be fixed */
4748 BUG_ON(ti->preempt_count || !irqs_disabled());
4750 do {
4751 add_preempt_count(PREEMPT_ACTIVE);
4754 * We keep the big kernel semaphore locked, but we
4755 * clear ->lock_depth so that schedule() doesnt
4756 * auto-release the semaphore:
4758 saved_lock_depth = task->lock_depth;
4759 task->lock_depth = -1;
4760 local_irq_enable();
4761 schedule();
4762 local_irq_disable();
4763 task->lock_depth = saved_lock_depth;
4764 sub_preempt_count(PREEMPT_ACTIVE);
4767 * Check again in case we missed a preemption opportunity
4768 * between schedule and now.
4770 barrier();
4771 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4774 #endif /* CONFIG_PREEMPT */
4776 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4777 void *key)
4779 return try_to_wake_up(curr->private, mode, sync);
4781 EXPORT_SYMBOL(default_wake_function);
4784 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4785 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4786 * number) then we wake all the non-exclusive tasks and one exclusive task.
4788 * There are circumstances in which we can try to wake a task which has already
4789 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4790 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4792 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4793 int nr_exclusive, int sync, void *key)
4795 wait_queue_t *curr, *next;
4797 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4798 unsigned flags = curr->flags;
4800 if (curr->func(curr, mode, sync, key) &&
4801 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4802 break;
4807 * __wake_up - wake up threads blocked on a waitqueue.
4808 * @q: the waitqueue
4809 * @mode: which threads
4810 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4811 * @key: is directly passed to the wakeup function
4813 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4814 int nr_exclusive, void *key)
4816 unsigned long flags;
4818 spin_lock_irqsave(&q->lock, flags);
4819 __wake_up_common(q, mode, nr_exclusive, 0, key);
4820 spin_unlock_irqrestore(&q->lock, flags);
4822 EXPORT_SYMBOL(__wake_up);
4825 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4827 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4829 __wake_up_common(q, mode, 1, 0, NULL);
4833 * __wake_up_sync - wake up threads blocked on a waitqueue.
4834 * @q: the waitqueue
4835 * @mode: which threads
4836 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4838 * The sync wakeup differs that the waker knows that it will schedule
4839 * away soon, so while the target thread will be woken up, it will not
4840 * be migrated to another CPU - ie. the two threads are 'synchronized'
4841 * with each other. This can prevent needless bouncing between CPUs.
4843 * On UP it can prevent extra preemption.
4845 void
4846 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4848 unsigned long flags;
4849 int sync = 1;
4851 if (unlikely(!q))
4852 return;
4854 if (unlikely(!nr_exclusive))
4855 sync = 0;
4857 spin_lock_irqsave(&q->lock, flags);
4858 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4859 spin_unlock_irqrestore(&q->lock, flags);
4861 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4863 void complete(struct completion *x)
4865 unsigned long flags;
4867 spin_lock_irqsave(&x->wait.lock, flags);
4868 x->done++;
4869 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4870 spin_unlock_irqrestore(&x->wait.lock, flags);
4872 EXPORT_SYMBOL(complete);
4874 void complete_all(struct completion *x)
4876 unsigned long flags;
4878 spin_lock_irqsave(&x->wait.lock, flags);
4879 x->done += UINT_MAX/2;
4880 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4881 spin_unlock_irqrestore(&x->wait.lock, flags);
4883 EXPORT_SYMBOL(complete_all);
4885 static inline long __sched
4886 do_wait_for_common(struct completion *x, long timeout, int state)
4888 if (!x->done) {
4889 DECLARE_WAITQUEUE(wait, current);
4891 wait.flags |= WQ_FLAG_EXCLUSIVE;
4892 __add_wait_queue_tail(&x->wait, &wait);
4893 do {
4894 if ((state == TASK_INTERRUPTIBLE &&
4895 signal_pending(current)) ||
4896 (state == TASK_KILLABLE &&
4897 fatal_signal_pending(current))) {
4898 __remove_wait_queue(&x->wait, &wait);
4899 return -ERESTARTSYS;
4901 __set_current_state(state);
4902 spin_unlock_irq(&x->wait.lock);
4903 timeout = schedule_timeout(timeout);
4904 spin_lock_irq(&x->wait.lock);
4905 if (!timeout) {
4906 __remove_wait_queue(&x->wait, &wait);
4907 return timeout;
4909 } while (!x->done);
4910 __remove_wait_queue(&x->wait, &wait);
4912 x->done--;
4913 return timeout;
4916 static long __sched
4917 wait_for_common(struct completion *x, long timeout, int state)
4919 might_sleep();
4921 spin_lock_irq(&x->wait.lock);
4922 timeout = do_wait_for_common(x, timeout, state);
4923 spin_unlock_irq(&x->wait.lock);
4924 return timeout;
4927 void __sched wait_for_completion(struct completion *x)
4929 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4931 EXPORT_SYMBOL(wait_for_completion);
4933 unsigned long __sched
4934 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4936 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4938 EXPORT_SYMBOL(wait_for_completion_timeout);
4940 int __sched wait_for_completion_interruptible(struct completion *x)
4942 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4943 if (t == -ERESTARTSYS)
4944 return t;
4945 return 0;
4947 EXPORT_SYMBOL(wait_for_completion_interruptible);
4949 unsigned long __sched
4950 wait_for_completion_interruptible_timeout(struct completion *x,
4951 unsigned long timeout)
4953 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4955 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4957 int __sched wait_for_completion_killable(struct completion *x)
4959 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4960 if (t == -ERESTARTSYS)
4961 return t;
4962 return 0;
4964 EXPORT_SYMBOL(wait_for_completion_killable);
4966 static long __sched
4967 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4969 unsigned long flags;
4970 wait_queue_t wait;
4972 init_waitqueue_entry(&wait, current);
4974 __set_current_state(state);
4976 spin_lock_irqsave(&q->lock, flags);
4977 __add_wait_queue(q, &wait);
4978 spin_unlock(&q->lock);
4979 timeout = schedule_timeout(timeout);
4980 spin_lock_irq(&q->lock);
4981 __remove_wait_queue(q, &wait);
4982 spin_unlock_irqrestore(&q->lock, flags);
4984 return timeout;
4987 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4989 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4991 EXPORT_SYMBOL(interruptible_sleep_on);
4993 long __sched
4994 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4996 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4998 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
5000 void __sched sleep_on(wait_queue_head_t *q)
5002 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5004 EXPORT_SYMBOL(sleep_on);
5006 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
5008 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5010 EXPORT_SYMBOL(sleep_on_timeout);
5012 #ifdef CONFIG_RT_MUTEXES
5015 * rt_mutex_setprio - set the current priority of a task
5016 * @p: task
5017 * @prio: prio value (kernel-internal form)
5019 * This function changes the 'effective' priority of a task. It does
5020 * not touch ->normal_prio like __setscheduler().
5022 * Used by the rt_mutex code to implement priority inheritance logic.
5024 void rt_mutex_setprio(struct task_struct *p, int prio)
5026 unsigned long flags;
5027 int oldprio, on_rq, running;
5028 struct rq *rq;
5029 const struct sched_class *prev_class = p->sched_class;
5031 BUG_ON(prio < 0 || prio > MAX_PRIO);
5033 rq = task_rq_lock(p, &flags);
5034 update_rq_clock(rq);
5036 oldprio = p->prio;
5037 on_rq = p->se.on_rq;
5038 running = task_current(rq, p);
5039 if (on_rq)
5040 dequeue_task(rq, p, 0);
5041 if (running)
5042 p->sched_class->put_prev_task(rq, p);
5044 if (rt_prio(prio))
5045 p->sched_class = &rt_sched_class;
5046 else
5047 p->sched_class = &fair_sched_class;
5049 p->prio = prio;
5051 if (running)
5052 p->sched_class->set_curr_task(rq);
5053 if (on_rq) {
5054 enqueue_task(rq, p, 0);
5056 check_class_changed(rq, p, prev_class, oldprio, running);
5058 task_rq_unlock(rq, &flags);
5061 #endif
5063 void set_user_nice(struct task_struct *p, long nice)
5065 int old_prio, delta, on_rq;
5066 unsigned long flags;
5067 struct rq *rq;
5069 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
5070 return;
5072 * We have to be careful, if called from sys_setpriority(),
5073 * the task might be in the middle of scheduling on another CPU.
5075 rq = task_rq_lock(p, &flags);
5076 update_rq_clock(rq);
5078 * The RT priorities are set via sched_setscheduler(), but we still
5079 * allow the 'normal' nice value to be set - but as expected
5080 * it wont have any effect on scheduling until the task is
5081 * SCHED_FIFO/SCHED_RR:
5083 if (task_has_rt_policy(p)) {
5084 p->static_prio = NICE_TO_PRIO(nice);
5085 goto out_unlock;
5087 on_rq = p->se.on_rq;
5088 if (on_rq)
5089 dequeue_task(rq, p, 0);
5091 p->static_prio = NICE_TO_PRIO(nice);
5092 set_load_weight(p);
5093 old_prio = p->prio;
5094 p->prio = effective_prio(p);
5095 delta = p->prio - old_prio;
5097 if (on_rq) {
5098 enqueue_task(rq, p, 0);
5100 * If the task increased its priority or is running and
5101 * lowered its priority, then reschedule its CPU:
5103 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5104 resched_task(rq->curr);
5106 out_unlock:
5107 task_rq_unlock(rq, &flags);
5109 EXPORT_SYMBOL(set_user_nice);
5112 * can_nice - check if a task can reduce its nice value
5113 * @p: task
5114 * @nice: nice value
5116 int can_nice(const struct task_struct *p, const int nice)
5118 /* convert nice value [19,-20] to rlimit style value [1,40] */
5119 int nice_rlim = 20 - nice;
5121 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5122 capable(CAP_SYS_NICE));
5125 #ifdef __ARCH_WANT_SYS_NICE
5128 * sys_nice - change the priority of the current process.
5129 * @increment: priority increment
5131 * sys_setpriority is a more generic, but much slower function that
5132 * does similar things.
5134 asmlinkage long sys_nice(int increment)
5136 long nice, retval;
5139 * Setpriority might change our priority at the same moment.
5140 * We don't have to worry. Conceptually one call occurs first
5141 * and we have a single winner.
5143 if (increment < -40)
5144 increment = -40;
5145 if (increment > 40)
5146 increment = 40;
5148 nice = PRIO_TO_NICE(current->static_prio) + increment;
5149 if (nice < -20)
5150 nice = -20;
5151 if (nice > 19)
5152 nice = 19;
5154 if (increment < 0 && !can_nice(current, nice))
5155 return -EPERM;
5157 retval = security_task_setnice(current, nice);
5158 if (retval)
5159 return retval;
5161 set_user_nice(current, nice);
5162 return 0;
5165 #endif
5168 * task_prio - return the priority value of a given task.
5169 * @p: the task in question.
5171 * This is the priority value as seen by users in /proc.
5172 * RT tasks are offset by -200. Normal tasks are centered
5173 * around 0, value goes from -16 to +15.
5175 int task_prio(const struct task_struct *p)
5177 return p->prio - MAX_RT_PRIO;
5181 * task_nice - return the nice value of a given task.
5182 * @p: the task in question.
5184 int task_nice(const struct task_struct *p)
5186 return TASK_NICE(p);
5188 EXPORT_SYMBOL(task_nice);
5191 * idle_cpu - is a given cpu idle currently?
5192 * @cpu: the processor in question.
5194 int idle_cpu(int cpu)
5196 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5200 * idle_task - return the idle task for a given cpu.
5201 * @cpu: the processor in question.
5203 struct task_struct *idle_task(int cpu)
5205 return cpu_rq(cpu)->idle;
5209 * find_process_by_pid - find a process with a matching PID value.
5210 * @pid: the pid in question.
5212 static struct task_struct *find_process_by_pid(pid_t pid)
5214 return pid ? find_task_by_vpid(pid) : current;
5217 /* Actually do priority change: must hold rq lock. */
5218 static void
5219 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5221 BUG_ON(p->se.on_rq);
5223 p->policy = policy;
5224 switch (p->policy) {
5225 case SCHED_NORMAL:
5226 case SCHED_BATCH:
5227 case SCHED_IDLE:
5228 p->sched_class = &fair_sched_class;
5229 break;
5230 case SCHED_FIFO:
5231 case SCHED_RR:
5232 p->sched_class = &rt_sched_class;
5233 break;
5236 p->rt_priority = prio;
5237 p->normal_prio = normal_prio(p);
5238 /* we are holding p->pi_lock already */
5239 p->prio = rt_mutex_getprio(p);
5240 set_load_weight(p);
5244 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5245 * @p: the task in question.
5246 * @policy: new policy.
5247 * @param: structure containing the new RT priority.
5249 * NOTE that the task may be already dead.
5251 int sched_setscheduler(struct task_struct *p, int policy,
5252 struct sched_param *param)
5254 int retval, oldprio, oldpolicy = -1, on_rq, running;
5255 unsigned long flags;
5256 const struct sched_class *prev_class = p->sched_class;
5257 struct rq *rq;
5259 /* may grab non-irq protected spin_locks */
5260 BUG_ON(in_interrupt());
5261 recheck:
5262 /* double check policy once rq lock held */
5263 if (policy < 0)
5264 policy = oldpolicy = p->policy;
5265 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5266 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5267 policy != SCHED_IDLE)
5268 return -EINVAL;
5270 * Valid priorities for SCHED_FIFO and SCHED_RR are
5271 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5272 * SCHED_BATCH and SCHED_IDLE is 0.
5274 if (param->sched_priority < 0 ||
5275 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5276 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5277 return -EINVAL;
5278 if (rt_policy(policy) != (param->sched_priority != 0))
5279 return -EINVAL;
5282 * Allow unprivileged RT tasks to decrease priority:
5284 if (!capable(CAP_SYS_NICE)) {
5285 if (rt_policy(policy)) {
5286 unsigned long rlim_rtprio;
5288 if (!lock_task_sighand(p, &flags))
5289 return -ESRCH;
5290 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5291 unlock_task_sighand(p, &flags);
5293 /* can't set/change the rt policy */
5294 if (policy != p->policy && !rlim_rtprio)
5295 return -EPERM;
5297 /* can't increase priority */
5298 if (param->sched_priority > p->rt_priority &&
5299 param->sched_priority > rlim_rtprio)
5300 return -EPERM;
5303 * Like positive nice levels, dont allow tasks to
5304 * move out of SCHED_IDLE either:
5306 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5307 return -EPERM;
5309 /* can't change other user's priorities */
5310 if ((current->euid != p->euid) &&
5311 (current->euid != p->uid))
5312 return -EPERM;
5315 #ifdef CONFIG_RT_GROUP_SCHED
5317 * Do not allow realtime tasks into groups that have no runtime
5318 * assigned.
5320 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5321 return -EPERM;
5322 #endif
5324 retval = security_task_setscheduler(p, policy, param);
5325 if (retval)
5326 return retval;
5328 * make sure no PI-waiters arrive (or leave) while we are
5329 * changing the priority of the task:
5331 spin_lock_irqsave(&p->pi_lock, flags);
5333 * To be able to change p->policy safely, the apropriate
5334 * runqueue lock must be held.
5336 rq = __task_rq_lock(p);
5337 /* recheck policy now with rq lock held */
5338 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5339 policy = oldpolicy = -1;
5340 __task_rq_unlock(rq);
5341 spin_unlock_irqrestore(&p->pi_lock, flags);
5342 goto recheck;
5344 update_rq_clock(rq);
5345 on_rq = p->se.on_rq;
5346 running = task_current(rq, p);
5347 if (on_rq)
5348 deactivate_task(rq, p, 0);
5349 if (running)
5350 p->sched_class->put_prev_task(rq, p);
5352 oldprio = p->prio;
5353 __setscheduler(rq, p, policy, param->sched_priority);
5355 if (running)
5356 p->sched_class->set_curr_task(rq);
5357 if (on_rq) {
5358 activate_task(rq, p, 0);
5360 check_class_changed(rq, p, prev_class, oldprio, running);
5362 __task_rq_unlock(rq);
5363 spin_unlock_irqrestore(&p->pi_lock, flags);
5365 rt_mutex_adjust_pi(p);
5367 return 0;
5369 EXPORT_SYMBOL_GPL(sched_setscheduler);
5371 static int
5372 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5374 struct sched_param lparam;
5375 struct task_struct *p;
5376 int retval;
5378 if (!param || pid < 0)
5379 return -EINVAL;
5380 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5381 return -EFAULT;
5383 rcu_read_lock();
5384 retval = -ESRCH;
5385 p = find_process_by_pid(pid);
5386 if (p != NULL)
5387 retval = sched_setscheduler(p, policy, &lparam);
5388 rcu_read_unlock();
5390 return retval;
5394 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5395 * @pid: the pid in question.
5396 * @policy: new policy.
5397 * @param: structure containing the new RT priority.
5399 asmlinkage long
5400 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5402 /* negative values for policy are not valid */
5403 if (policy < 0)
5404 return -EINVAL;
5406 return do_sched_setscheduler(pid, policy, param);
5410 * sys_sched_setparam - set/change the RT priority of a thread
5411 * @pid: the pid in question.
5412 * @param: structure containing the new RT priority.
5414 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5416 return do_sched_setscheduler(pid, -1, param);
5420 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5421 * @pid: the pid in question.
5423 asmlinkage long sys_sched_getscheduler(pid_t pid)
5425 struct task_struct *p;
5426 int retval;
5428 if (pid < 0)
5429 return -EINVAL;
5431 retval = -ESRCH;
5432 read_lock(&tasklist_lock);
5433 p = find_process_by_pid(pid);
5434 if (p) {
5435 retval = security_task_getscheduler(p);
5436 if (!retval)
5437 retval = p->policy;
5439 read_unlock(&tasklist_lock);
5440 return retval;
5444 * sys_sched_getscheduler - get the RT priority of a thread
5445 * @pid: the pid in question.
5446 * @param: structure containing the RT priority.
5448 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5450 struct sched_param lp;
5451 struct task_struct *p;
5452 int retval;
5454 if (!param || pid < 0)
5455 return -EINVAL;
5457 read_lock(&tasklist_lock);
5458 p = find_process_by_pid(pid);
5459 retval = -ESRCH;
5460 if (!p)
5461 goto out_unlock;
5463 retval = security_task_getscheduler(p);
5464 if (retval)
5465 goto out_unlock;
5467 lp.sched_priority = p->rt_priority;
5468 read_unlock(&tasklist_lock);
5471 * This one might sleep, we cannot do it with a spinlock held ...
5473 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5475 return retval;
5477 out_unlock:
5478 read_unlock(&tasklist_lock);
5479 return retval;
5482 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5484 cpumask_t cpus_allowed;
5485 cpumask_t new_mask = *in_mask;
5486 struct task_struct *p;
5487 int retval;
5489 get_online_cpus();
5490 read_lock(&tasklist_lock);
5492 p = find_process_by_pid(pid);
5493 if (!p) {
5494 read_unlock(&tasklist_lock);
5495 put_online_cpus();
5496 return -ESRCH;
5500 * It is not safe to call set_cpus_allowed with the
5501 * tasklist_lock held. We will bump the task_struct's
5502 * usage count and then drop tasklist_lock.
5504 get_task_struct(p);
5505 read_unlock(&tasklist_lock);
5507 retval = -EPERM;
5508 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5509 !capable(CAP_SYS_NICE))
5510 goto out_unlock;
5512 retval = security_task_setscheduler(p, 0, NULL);
5513 if (retval)
5514 goto out_unlock;
5516 cpuset_cpus_allowed(p, &cpus_allowed);
5517 cpus_and(new_mask, new_mask, cpus_allowed);
5518 again:
5519 retval = set_cpus_allowed_ptr(p, &new_mask);
5521 if (!retval) {
5522 cpuset_cpus_allowed(p, &cpus_allowed);
5523 if (!cpus_subset(new_mask, cpus_allowed)) {
5525 * We must have raced with a concurrent cpuset
5526 * update. Just reset the cpus_allowed to the
5527 * cpuset's cpus_allowed
5529 new_mask = cpus_allowed;
5530 goto again;
5533 out_unlock:
5534 put_task_struct(p);
5535 put_online_cpus();
5536 return retval;
5539 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5540 cpumask_t *new_mask)
5542 if (len < sizeof(cpumask_t)) {
5543 memset(new_mask, 0, sizeof(cpumask_t));
5544 } else if (len > sizeof(cpumask_t)) {
5545 len = sizeof(cpumask_t);
5547 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5551 * sys_sched_setaffinity - set the cpu affinity of a process
5552 * @pid: pid of the process
5553 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5554 * @user_mask_ptr: user-space pointer to the new cpu mask
5556 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5557 unsigned long __user *user_mask_ptr)
5559 cpumask_t new_mask;
5560 int retval;
5562 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5563 if (retval)
5564 return retval;
5566 return sched_setaffinity(pid, &new_mask);
5570 * Represents all cpu's present in the system
5571 * In systems capable of hotplug, this map could dynamically grow
5572 * as new cpu's are detected in the system via any platform specific
5573 * method, such as ACPI for e.g.
5576 cpumask_t cpu_present_map __read_mostly;
5577 EXPORT_SYMBOL(cpu_present_map);
5579 #ifndef CONFIG_SMP
5580 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5581 EXPORT_SYMBOL(cpu_online_map);
5583 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5584 EXPORT_SYMBOL(cpu_possible_map);
5585 #endif
5587 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5589 struct task_struct *p;
5590 int retval;
5592 get_online_cpus();
5593 read_lock(&tasklist_lock);
5595 retval = -ESRCH;
5596 p = find_process_by_pid(pid);
5597 if (!p)
5598 goto out_unlock;
5600 retval = security_task_getscheduler(p);
5601 if (retval)
5602 goto out_unlock;
5604 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5606 out_unlock:
5607 read_unlock(&tasklist_lock);
5608 put_online_cpus();
5610 return retval;
5614 * sys_sched_getaffinity - get the cpu affinity of a process
5615 * @pid: pid of the process
5616 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5617 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5619 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5620 unsigned long __user *user_mask_ptr)
5622 int ret;
5623 cpumask_t mask;
5625 if (len < sizeof(cpumask_t))
5626 return -EINVAL;
5628 ret = sched_getaffinity(pid, &mask);
5629 if (ret < 0)
5630 return ret;
5632 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5633 return -EFAULT;
5635 return sizeof(cpumask_t);
5639 * sys_sched_yield - yield the current processor to other threads.
5641 * This function yields the current CPU to other tasks. If there are no
5642 * other threads running on this CPU then this function will return.
5644 asmlinkage long sys_sched_yield(void)
5646 struct rq *rq = this_rq_lock();
5648 schedstat_inc(rq, yld_count);
5649 current->sched_class->yield_task(rq);
5652 * Since we are going to call schedule() anyway, there's
5653 * no need to preempt or enable interrupts:
5655 __release(rq->lock);
5656 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5657 _raw_spin_unlock(&rq->lock);
5658 preempt_enable_no_resched();
5660 schedule();
5662 return 0;
5665 static void __cond_resched(void)
5667 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5668 __might_sleep(__FILE__, __LINE__);
5669 #endif
5671 * The BKS might be reacquired before we have dropped
5672 * PREEMPT_ACTIVE, which could trigger a second
5673 * cond_resched() call.
5675 do {
5676 add_preempt_count(PREEMPT_ACTIVE);
5677 schedule();
5678 sub_preempt_count(PREEMPT_ACTIVE);
5679 } while (need_resched());
5682 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5683 int __sched _cond_resched(void)
5685 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5686 system_state == SYSTEM_RUNNING) {
5687 __cond_resched();
5688 return 1;
5690 return 0;
5692 EXPORT_SYMBOL(_cond_resched);
5693 #endif
5696 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5697 * call schedule, and on return reacquire the lock.
5699 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5700 * operations here to prevent schedule() from being called twice (once via
5701 * spin_unlock(), once by hand).
5703 int cond_resched_lock(spinlock_t *lock)
5705 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5706 int ret = 0;
5708 if (spin_needbreak(lock) || resched) {
5709 spin_unlock(lock);
5710 if (resched && need_resched())
5711 __cond_resched();
5712 else
5713 cpu_relax();
5714 ret = 1;
5715 spin_lock(lock);
5717 return ret;
5719 EXPORT_SYMBOL(cond_resched_lock);
5721 int __sched cond_resched_softirq(void)
5723 BUG_ON(!in_softirq());
5725 if (need_resched() && system_state == SYSTEM_RUNNING) {
5726 local_bh_enable();
5727 __cond_resched();
5728 local_bh_disable();
5729 return 1;
5731 return 0;
5733 EXPORT_SYMBOL(cond_resched_softirq);
5736 * yield - yield the current processor to other threads.
5738 * This is a shortcut for kernel-space yielding - it marks the
5739 * thread runnable and calls sys_sched_yield().
5741 void __sched yield(void)
5743 set_current_state(TASK_RUNNING);
5744 sys_sched_yield();
5746 EXPORT_SYMBOL(yield);
5749 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5750 * that process accounting knows that this is a task in IO wait state.
5752 * But don't do that if it is a deliberate, throttling IO wait (this task
5753 * has set its backing_dev_info: the queue against which it should throttle)
5755 void __sched io_schedule(void)
5757 struct rq *rq = &__raw_get_cpu_var(runqueues);
5759 delayacct_blkio_start();
5760 atomic_inc(&rq->nr_iowait);
5761 schedule();
5762 atomic_dec(&rq->nr_iowait);
5763 delayacct_blkio_end();
5765 EXPORT_SYMBOL(io_schedule);
5767 long __sched io_schedule_timeout(long timeout)
5769 struct rq *rq = &__raw_get_cpu_var(runqueues);
5770 long ret;
5772 delayacct_blkio_start();
5773 atomic_inc(&rq->nr_iowait);
5774 ret = schedule_timeout(timeout);
5775 atomic_dec(&rq->nr_iowait);
5776 delayacct_blkio_end();
5777 return ret;
5781 * sys_sched_get_priority_max - return maximum RT priority.
5782 * @policy: scheduling class.
5784 * this syscall returns the maximum rt_priority that can be used
5785 * by a given scheduling class.
5787 asmlinkage long sys_sched_get_priority_max(int policy)
5789 int ret = -EINVAL;
5791 switch (policy) {
5792 case SCHED_FIFO:
5793 case SCHED_RR:
5794 ret = MAX_USER_RT_PRIO-1;
5795 break;
5796 case SCHED_NORMAL:
5797 case SCHED_BATCH:
5798 case SCHED_IDLE:
5799 ret = 0;
5800 break;
5802 return ret;
5806 * sys_sched_get_priority_min - return minimum RT priority.
5807 * @policy: scheduling class.
5809 * this syscall returns the minimum rt_priority that can be used
5810 * by a given scheduling class.
5812 asmlinkage long sys_sched_get_priority_min(int policy)
5814 int ret = -EINVAL;
5816 switch (policy) {
5817 case SCHED_FIFO:
5818 case SCHED_RR:
5819 ret = 1;
5820 break;
5821 case SCHED_NORMAL:
5822 case SCHED_BATCH:
5823 case SCHED_IDLE:
5824 ret = 0;
5826 return ret;
5830 * sys_sched_rr_get_interval - return the default timeslice of a process.
5831 * @pid: pid of the process.
5832 * @interval: userspace pointer to the timeslice value.
5834 * this syscall writes the default timeslice value of a given process
5835 * into the user-space timespec buffer. A value of '0' means infinity.
5837 asmlinkage
5838 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5840 struct task_struct *p;
5841 unsigned int time_slice;
5842 int retval;
5843 struct timespec t;
5845 if (pid < 0)
5846 return -EINVAL;
5848 retval = -ESRCH;
5849 read_lock(&tasklist_lock);
5850 p = find_process_by_pid(pid);
5851 if (!p)
5852 goto out_unlock;
5854 retval = security_task_getscheduler(p);
5855 if (retval)
5856 goto out_unlock;
5859 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5860 * tasks that are on an otherwise idle runqueue:
5862 time_slice = 0;
5863 if (p->policy == SCHED_RR) {
5864 time_slice = DEF_TIMESLICE;
5865 } else if (p->policy != SCHED_FIFO) {
5866 struct sched_entity *se = &p->se;
5867 unsigned long flags;
5868 struct rq *rq;
5870 rq = task_rq_lock(p, &flags);
5871 if (rq->cfs.load.weight)
5872 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5873 task_rq_unlock(rq, &flags);
5875 read_unlock(&tasklist_lock);
5876 jiffies_to_timespec(time_slice, &t);
5877 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5878 return retval;
5880 out_unlock:
5881 read_unlock(&tasklist_lock);
5882 return retval;
5885 static const char stat_nam[] = "RSDTtZX";
5887 void sched_show_task(struct task_struct *p)
5889 unsigned long free = 0;
5890 unsigned state;
5892 state = p->state ? __ffs(p->state) + 1 : 0;
5893 printk(KERN_INFO "%-13.13s %c", p->comm,
5894 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5895 #if BITS_PER_LONG == 32
5896 if (state == TASK_RUNNING)
5897 printk(KERN_CONT " running ");
5898 else
5899 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5900 #else
5901 if (state == TASK_RUNNING)
5902 printk(KERN_CONT " running task ");
5903 else
5904 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5905 #endif
5906 #ifdef CONFIG_DEBUG_STACK_USAGE
5908 unsigned long *n = end_of_stack(p);
5909 while (!*n)
5910 n++;
5911 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5913 #endif
5914 printk(KERN_CONT "%5lu %5d %6d\n", free,
5915 task_pid_nr(p), task_pid_nr(p->real_parent));
5917 show_stack(p, NULL);
5920 void show_state_filter(unsigned long state_filter)
5922 struct task_struct *g, *p;
5924 #if BITS_PER_LONG == 32
5925 printk(KERN_INFO
5926 " task PC stack pid father\n");
5927 #else
5928 printk(KERN_INFO
5929 " task PC stack pid father\n");
5930 #endif
5931 read_lock(&tasklist_lock);
5932 do_each_thread(g, p) {
5934 * reset the NMI-timeout, listing all files on a slow
5935 * console might take alot of time:
5937 touch_nmi_watchdog();
5938 if (!state_filter || (p->state & state_filter))
5939 sched_show_task(p);
5940 } while_each_thread(g, p);
5942 touch_all_softlockup_watchdogs();
5944 #ifdef CONFIG_SCHED_DEBUG
5945 sysrq_sched_debug_show();
5946 #endif
5947 read_unlock(&tasklist_lock);
5949 * Only show locks if all tasks are dumped:
5951 if (state_filter == -1)
5952 debug_show_all_locks();
5955 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5957 idle->sched_class = &idle_sched_class;
5961 * init_idle - set up an idle thread for a given CPU
5962 * @idle: task in question
5963 * @cpu: cpu the idle task belongs to
5965 * NOTE: this function does not set the idle thread's NEED_RESCHED
5966 * flag, to make booting more robust.
5968 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5970 struct rq *rq = cpu_rq(cpu);
5971 unsigned long flags;
5973 __sched_fork(idle);
5974 idle->se.exec_start = sched_clock();
5976 idle->prio = idle->normal_prio = MAX_PRIO;
5977 idle->cpus_allowed = cpumask_of_cpu(cpu);
5978 __set_task_cpu(idle, cpu);
5980 spin_lock_irqsave(&rq->lock, flags);
5981 rq->curr = rq->idle = idle;
5982 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5983 idle->oncpu = 1;
5984 #endif
5985 spin_unlock_irqrestore(&rq->lock, flags);
5987 /* Set the preempt count _outside_ the spinlocks! */
5988 task_thread_info(idle)->preempt_count = 0;
5991 * The idle tasks have their own, simple scheduling class:
5993 idle->sched_class = &idle_sched_class;
5997 * In a system that switches off the HZ timer nohz_cpu_mask
5998 * indicates which cpus entered this state. This is used
5999 * in the rcu update to wait only for active cpus. For system
6000 * which do not switch off the HZ timer nohz_cpu_mask should
6001 * always be CPU_MASK_NONE.
6003 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
6006 * Increase the granularity value when there are more CPUs,
6007 * because with more CPUs the 'effective latency' as visible
6008 * to users decreases. But the relationship is not linear,
6009 * so pick a second-best guess by going with the log2 of the
6010 * number of CPUs.
6012 * This idea comes from the SD scheduler of Con Kolivas:
6014 static inline void sched_init_granularity(void)
6016 unsigned int factor = 1 + ilog2(num_online_cpus());
6017 const unsigned long limit = 200000000;
6019 sysctl_sched_min_granularity *= factor;
6020 if (sysctl_sched_min_granularity > limit)
6021 sysctl_sched_min_granularity = limit;
6023 sysctl_sched_latency *= factor;
6024 if (sysctl_sched_latency > limit)
6025 sysctl_sched_latency = limit;
6027 sysctl_sched_wakeup_granularity *= factor;
6030 #ifdef CONFIG_SMP
6032 * This is how migration works:
6034 * 1) we queue a struct migration_req structure in the source CPU's
6035 * runqueue and wake up that CPU's migration thread.
6036 * 2) we down() the locked semaphore => thread blocks.
6037 * 3) migration thread wakes up (implicitly it forces the migrated
6038 * thread off the CPU)
6039 * 4) it gets the migration request and checks whether the migrated
6040 * task is still in the wrong runqueue.
6041 * 5) if it's in the wrong runqueue then the migration thread removes
6042 * it and puts it into the right queue.
6043 * 6) migration thread up()s the semaphore.
6044 * 7) we wake up and the migration is done.
6048 * Change a given task's CPU affinity. Migrate the thread to a
6049 * proper CPU and schedule it away if the CPU it's executing on
6050 * is removed from the allowed bitmask.
6052 * NOTE: the caller must have a valid reference to the task, the
6053 * task must not exit() & deallocate itself prematurely. The
6054 * call is not atomic; no spinlocks may be held.
6056 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
6058 struct migration_req req;
6059 unsigned long flags;
6060 struct rq *rq;
6061 int ret = 0;
6063 rq = task_rq_lock(p, &flags);
6064 if (!cpus_intersects(*new_mask, cpu_online_map)) {
6065 ret = -EINVAL;
6066 goto out;
6069 if (p->sched_class->set_cpus_allowed)
6070 p->sched_class->set_cpus_allowed(p, new_mask);
6071 else {
6072 p->cpus_allowed = *new_mask;
6073 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
6076 /* Can the task run on the task's current CPU? If so, we're done */
6077 if (cpu_isset(task_cpu(p), *new_mask))
6078 goto out;
6080 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
6081 /* Need help from migration thread: drop lock and wait. */
6082 task_rq_unlock(rq, &flags);
6083 wake_up_process(rq->migration_thread);
6084 wait_for_completion(&req.done);
6085 tlb_migrate_finish(p->mm);
6086 return 0;
6088 out:
6089 task_rq_unlock(rq, &flags);
6091 return ret;
6093 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6096 * Move (not current) task off this cpu, onto dest cpu. We're doing
6097 * this because either it can't run here any more (set_cpus_allowed()
6098 * away from this CPU, or CPU going down), or because we're
6099 * attempting to rebalance this task on exec (sched_exec).
6101 * So we race with normal scheduler movements, but that's OK, as long
6102 * as the task is no longer on this CPU.
6104 * Returns non-zero if task was successfully migrated.
6106 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6108 struct rq *rq_dest, *rq_src;
6109 int ret = 0, on_rq;
6111 if (unlikely(cpu_is_offline(dest_cpu)))
6112 return ret;
6114 rq_src = cpu_rq(src_cpu);
6115 rq_dest = cpu_rq(dest_cpu);
6117 double_rq_lock(rq_src, rq_dest);
6118 /* Already moved. */
6119 if (task_cpu(p) != src_cpu)
6120 goto out;
6121 /* Affinity changed (again). */
6122 if (!cpu_isset(dest_cpu, p->cpus_allowed))
6123 goto out;
6125 on_rq = p->se.on_rq;
6126 if (on_rq)
6127 deactivate_task(rq_src, p, 0);
6129 set_task_cpu(p, dest_cpu);
6130 if (on_rq) {
6131 activate_task(rq_dest, p, 0);
6132 check_preempt_curr(rq_dest, p);
6134 ret = 1;
6135 out:
6136 double_rq_unlock(rq_src, rq_dest);
6137 return ret;
6141 * migration_thread - this is a highprio system thread that performs
6142 * thread migration by bumping thread off CPU then 'pushing' onto
6143 * another runqueue.
6145 static int migration_thread(void *data)
6147 int cpu = (long)data;
6148 struct rq *rq;
6150 rq = cpu_rq(cpu);
6151 BUG_ON(rq->migration_thread != current);
6153 set_current_state(TASK_INTERRUPTIBLE);
6154 while (!kthread_should_stop()) {
6155 struct migration_req *req;
6156 struct list_head *head;
6158 spin_lock_irq(&rq->lock);
6160 if (cpu_is_offline(cpu)) {
6161 spin_unlock_irq(&rq->lock);
6162 goto wait_to_die;
6165 if (rq->active_balance) {
6166 active_load_balance(rq, cpu);
6167 rq->active_balance = 0;
6170 head = &rq->migration_queue;
6172 if (list_empty(head)) {
6173 spin_unlock_irq(&rq->lock);
6174 schedule();
6175 set_current_state(TASK_INTERRUPTIBLE);
6176 continue;
6178 req = list_entry(head->next, struct migration_req, list);
6179 list_del_init(head->next);
6181 spin_unlock(&rq->lock);
6182 __migrate_task(req->task, cpu, req->dest_cpu);
6183 local_irq_enable();
6185 complete(&req->done);
6187 __set_current_state(TASK_RUNNING);
6188 return 0;
6190 wait_to_die:
6191 /* Wait for kthread_stop */
6192 set_current_state(TASK_INTERRUPTIBLE);
6193 while (!kthread_should_stop()) {
6194 schedule();
6195 set_current_state(TASK_INTERRUPTIBLE);
6197 __set_current_state(TASK_RUNNING);
6198 return 0;
6201 #ifdef CONFIG_HOTPLUG_CPU
6203 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6205 int ret;
6207 local_irq_disable();
6208 ret = __migrate_task(p, src_cpu, dest_cpu);
6209 local_irq_enable();
6210 return ret;
6214 * Figure out where task on dead CPU should go, use force if necessary.
6215 * NOTE: interrupts should be disabled by the caller
6217 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6219 unsigned long flags;
6220 cpumask_t mask;
6221 struct rq *rq;
6222 int dest_cpu;
6224 do {
6225 /* On same node? */
6226 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6227 cpus_and(mask, mask, p->cpus_allowed);
6228 dest_cpu = any_online_cpu(mask);
6230 /* On any allowed CPU? */
6231 if (dest_cpu >= nr_cpu_ids)
6232 dest_cpu = any_online_cpu(p->cpus_allowed);
6234 /* No more Mr. Nice Guy. */
6235 if (dest_cpu >= nr_cpu_ids) {
6236 cpumask_t cpus_allowed;
6238 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6240 * Try to stay on the same cpuset, where the
6241 * current cpuset may be a subset of all cpus.
6242 * The cpuset_cpus_allowed_locked() variant of
6243 * cpuset_cpus_allowed() will not block. It must be
6244 * called within calls to cpuset_lock/cpuset_unlock.
6246 rq = task_rq_lock(p, &flags);
6247 p->cpus_allowed = cpus_allowed;
6248 dest_cpu = any_online_cpu(p->cpus_allowed);
6249 task_rq_unlock(rq, &flags);
6252 * Don't tell them about moving exiting tasks or
6253 * kernel threads (both mm NULL), since they never
6254 * leave kernel.
6256 if (p->mm && printk_ratelimit()) {
6257 printk(KERN_INFO "process %d (%s) no "
6258 "longer affine to cpu%d\n",
6259 task_pid_nr(p), p->comm, dead_cpu);
6262 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6266 * While a dead CPU has no uninterruptible tasks queued at this point,
6267 * it might still have a nonzero ->nr_uninterruptible counter, because
6268 * for performance reasons the counter is not stricly tracking tasks to
6269 * their home CPUs. So we just add the counter to another CPU's counter,
6270 * to keep the global sum constant after CPU-down:
6272 static void migrate_nr_uninterruptible(struct rq *rq_src)
6274 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6275 unsigned long flags;
6277 local_irq_save(flags);
6278 double_rq_lock(rq_src, rq_dest);
6279 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6280 rq_src->nr_uninterruptible = 0;
6281 double_rq_unlock(rq_src, rq_dest);
6282 local_irq_restore(flags);
6285 /* Run through task list and migrate tasks from the dead cpu. */
6286 static void migrate_live_tasks(int src_cpu)
6288 struct task_struct *p, *t;
6290 read_lock(&tasklist_lock);
6292 do_each_thread(t, p) {
6293 if (p == current)
6294 continue;
6296 if (task_cpu(p) == src_cpu)
6297 move_task_off_dead_cpu(src_cpu, p);
6298 } while_each_thread(t, p);
6300 read_unlock(&tasklist_lock);
6304 * Schedules idle task to be the next runnable task on current CPU.
6305 * It does so by boosting its priority to highest possible.
6306 * Used by CPU offline code.
6308 void sched_idle_next(void)
6310 int this_cpu = smp_processor_id();
6311 struct rq *rq = cpu_rq(this_cpu);
6312 struct task_struct *p = rq->idle;
6313 unsigned long flags;
6315 /* cpu has to be offline */
6316 BUG_ON(cpu_online(this_cpu));
6319 * Strictly not necessary since rest of the CPUs are stopped by now
6320 * and interrupts disabled on the current cpu.
6322 spin_lock_irqsave(&rq->lock, flags);
6324 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6326 update_rq_clock(rq);
6327 activate_task(rq, p, 0);
6329 spin_unlock_irqrestore(&rq->lock, flags);
6333 * Ensures that the idle task is using init_mm right before its cpu goes
6334 * offline.
6336 void idle_task_exit(void)
6338 struct mm_struct *mm = current->active_mm;
6340 BUG_ON(cpu_online(smp_processor_id()));
6342 if (mm != &init_mm)
6343 switch_mm(mm, &init_mm, current);
6344 mmdrop(mm);
6347 /* called under rq->lock with disabled interrupts */
6348 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6350 struct rq *rq = cpu_rq(dead_cpu);
6352 /* Must be exiting, otherwise would be on tasklist. */
6353 BUG_ON(!p->exit_state);
6355 /* Cannot have done final schedule yet: would have vanished. */
6356 BUG_ON(p->state == TASK_DEAD);
6358 get_task_struct(p);
6361 * Drop lock around migration; if someone else moves it,
6362 * that's OK. No task can be added to this CPU, so iteration is
6363 * fine.
6365 spin_unlock_irq(&rq->lock);
6366 move_task_off_dead_cpu(dead_cpu, p);
6367 spin_lock_irq(&rq->lock);
6369 put_task_struct(p);
6372 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6373 static void migrate_dead_tasks(unsigned int dead_cpu)
6375 struct rq *rq = cpu_rq(dead_cpu);
6376 struct task_struct *next;
6378 for ( ; ; ) {
6379 if (!rq->nr_running)
6380 break;
6381 update_rq_clock(rq);
6382 next = pick_next_task(rq, rq->curr);
6383 if (!next)
6384 break;
6385 migrate_dead(dead_cpu, next);
6389 #endif /* CONFIG_HOTPLUG_CPU */
6391 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6393 static struct ctl_table sd_ctl_dir[] = {
6395 .procname = "sched_domain",
6396 .mode = 0555,
6398 {0, },
6401 static struct ctl_table sd_ctl_root[] = {
6403 .ctl_name = CTL_KERN,
6404 .procname = "kernel",
6405 .mode = 0555,
6406 .child = sd_ctl_dir,
6408 {0, },
6411 static struct ctl_table *sd_alloc_ctl_entry(int n)
6413 struct ctl_table *entry =
6414 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6416 return entry;
6419 static void sd_free_ctl_entry(struct ctl_table **tablep)
6421 struct ctl_table *entry;
6424 * In the intermediate directories, both the child directory and
6425 * procname are dynamically allocated and could fail but the mode
6426 * will always be set. In the lowest directory the names are
6427 * static strings and all have proc handlers.
6429 for (entry = *tablep; entry->mode; entry++) {
6430 if (entry->child)
6431 sd_free_ctl_entry(&entry->child);
6432 if (entry->proc_handler == NULL)
6433 kfree(entry->procname);
6436 kfree(*tablep);
6437 *tablep = NULL;
6440 static void
6441 set_table_entry(struct ctl_table *entry,
6442 const char *procname, void *data, int maxlen,
6443 mode_t mode, proc_handler *proc_handler)
6445 entry->procname = procname;
6446 entry->data = data;
6447 entry->maxlen = maxlen;
6448 entry->mode = mode;
6449 entry->proc_handler = proc_handler;
6452 static struct ctl_table *
6453 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6455 struct ctl_table *table = sd_alloc_ctl_entry(12);
6457 if (table == NULL)
6458 return NULL;
6460 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6461 sizeof(long), 0644, proc_doulongvec_minmax);
6462 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6463 sizeof(long), 0644, proc_doulongvec_minmax);
6464 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6465 sizeof(int), 0644, proc_dointvec_minmax);
6466 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6467 sizeof(int), 0644, proc_dointvec_minmax);
6468 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6469 sizeof(int), 0644, proc_dointvec_minmax);
6470 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6471 sizeof(int), 0644, proc_dointvec_minmax);
6472 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6473 sizeof(int), 0644, proc_dointvec_minmax);
6474 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6475 sizeof(int), 0644, proc_dointvec_minmax);
6476 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6477 sizeof(int), 0644, proc_dointvec_minmax);
6478 set_table_entry(&table[9], "cache_nice_tries",
6479 &sd->cache_nice_tries,
6480 sizeof(int), 0644, proc_dointvec_minmax);
6481 set_table_entry(&table[10], "flags", &sd->flags,
6482 sizeof(int), 0644, proc_dointvec_minmax);
6483 /* &table[11] is terminator */
6485 return table;
6488 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6490 struct ctl_table *entry, *table;
6491 struct sched_domain *sd;
6492 int domain_num = 0, i;
6493 char buf[32];
6495 for_each_domain(cpu, sd)
6496 domain_num++;
6497 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6498 if (table == NULL)
6499 return NULL;
6501 i = 0;
6502 for_each_domain(cpu, sd) {
6503 snprintf(buf, 32, "domain%d", i);
6504 entry->procname = kstrdup(buf, GFP_KERNEL);
6505 entry->mode = 0555;
6506 entry->child = sd_alloc_ctl_domain_table(sd);
6507 entry++;
6508 i++;
6510 return table;
6513 static struct ctl_table_header *sd_sysctl_header;
6514 static void register_sched_domain_sysctl(void)
6516 int i, cpu_num = num_online_cpus();
6517 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6518 char buf[32];
6520 WARN_ON(sd_ctl_dir[0].child);
6521 sd_ctl_dir[0].child = entry;
6523 if (entry == NULL)
6524 return;
6526 for_each_online_cpu(i) {
6527 snprintf(buf, 32, "cpu%d", i);
6528 entry->procname = kstrdup(buf, GFP_KERNEL);
6529 entry->mode = 0555;
6530 entry->child = sd_alloc_ctl_cpu_table(i);
6531 entry++;
6534 WARN_ON(sd_sysctl_header);
6535 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6538 /* may be called multiple times per register */
6539 static void unregister_sched_domain_sysctl(void)
6541 if (sd_sysctl_header)
6542 unregister_sysctl_table(sd_sysctl_header);
6543 sd_sysctl_header = NULL;
6544 if (sd_ctl_dir[0].child)
6545 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6547 #else
6548 static void register_sched_domain_sysctl(void)
6551 static void unregister_sched_domain_sysctl(void)
6554 #endif
6557 * migration_call - callback that gets triggered when a CPU is added.
6558 * Here we can start up the necessary migration thread for the new CPU.
6560 static int __cpuinit
6561 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6563 struct task_struct *p;
6564 int cpu = (long)hcpu;
6565 unsigned long flags;
6566 struct rq *rq;
6568 switch (action) {
6570 case CPU_UP_PREPARE:
6571 case CPU_UP_PREPARE_FROZEN:
6572 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6573 if (IS_ERR(p))
6574 return NOTIFY_BAD;
6575 kthread_bind(p, cpu);
6576 /* Must be high prio: stop_machine expects to yield to it. */
6577 rq = task_rq_lock(p, &flags);
6578 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6579 task_rq_unlock(rq, &flags);
6580 cpu_rq(cpu)->migration_thread = p;
6581 break;
6583 case CPU_ONLINE:
6584 case CPU_ONLINE_FROZEN:
6585 /* Strictly unnecessary, as first user will wake it. */
6586 wake_up_process(cpu_rq(cpu)->migration_thread);
6588 /* Update our root-domain */
6589 rq = cpu_rq(cpu);
6590 spin_lock_irqsave(&rq->lock, flags);
6591 if (rq->rd) {
6592 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6593 cpu_set(cpu, rq->rd->online);
6595 spin_unlock_irqrestore(&rq->lock, flags);
6596 break;
6598 #ifdef CONFIG_HOTPLUG_CPU
6599 case CPU_UP_CANCELED:
6600 case CPU_UP_CANCELED_FROZEN:
6601 if (!cpu_rq(cpu)->migration_thread)
6602 break;
6603 /* Unbind it from offline cpu so it can run. Fall thru. */
6604 kthread_bind(cpu_rq(cpu)->migration_thread,
6605 any_online_cpu(cpu_online_map));
6606 kthread_stop(cpu_rq(cpu)->migration_thread);
6607 cpu_rq(cpu)->migration_thread = NULL;
6608 break;
6610 case CPU_DEAD:
6611 case CPU_DEAD_FROZEN:
6612 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6613 migrate_live_tasks(cpu);
6614 rq = cpu_rq(cpu);
6615 kthread_stop(rq->migration_thread);
6616 rq->migration_thread = NULL;
6617 /* Idle task back to normal (off runqueue, low prio) */
6618 spin_lock_irq(&rq->lock);
6619 update_rq_clock(rq);
6620 deactivate_task(rq, rq->idle, 0);
6621 rq->idle->static_prio = MAX_PRIO;
6622 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6623 rq->idle->sched_class = &idle_sched_class;
6624 migrate_dead_tasks(cpu);
6625 spin_unlock_irq(&rq->lock);
6626 cpuset_unlock();
6627 migrate_nr_uninterruptible(rq);
6628 BUG_ON(rq->nr_running != 0);
6631 * No need to migrate the tasks: it was best-effort if
6632 * they didn't take sched_hotcpu_mutex. Just wake up
6633 * the requestors.
6635 spin_lock_irq(&rq->lock);
6636 while (!list_empty(&rq->migration_queue)) {
6637 struct migration_req *req;
6639 req = list_entry(rq->migration_queue.next,
6640 struct migration_req, list);
6641 list_del_init(&req->list);
6642 complete(&req->done);
6644 spin_unlock_irq(&rq->lock);
6645 break;
6647 case CPU_DYING:
6648 case CPU_DYING_FROZEN:
6649 /* Update our root-domain */
6650 rq = cpu_rq(cpu);
6651 spin_lock_irqsave(&rq->lock, flags);
6652 if (rq->rd) {
6653 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6654 cpu_clear(cpu, rq->rd->online);
6656 spin_unlock_irqrestore(&rq->lock, flags);
6657 break;
6658 #endif
6660 return NOTIFY_OK;
6663 /* Register at highest priority so that task migration (migrate_all_tasks)
6664 * happens before everything else.
6666 static struct notifier_block __cpuinitdata migration_notifier = {
6667 .notifier_call = migration_call,
6668 .priority = 10
6671 void __init migration_init(void)
6673 void *cpu = (void *)(long)smp_processor_id();
6674 int err;
6676 /* Start one for the boot CPU: */
6677 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6678 BUG_ON(err == NOTIFY_BAD);
6679 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6680 register_cpu_notifier(&migration_notifier);
6682 #endif
6684 #ifdef CONFIG_SMP
6686 #ifdef CONFIG_SCHED_DEBUG
6688 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6689 cpumask_t *groupmask)
6691 struct sched_group *group = sd->groups;
6692 char str[256];
6694 cpulist_scnprintf(str, sizeof(str), sd->span);
6695 cpus_clear(*groupmask);
6697 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6699 if (!(sd->flags & SD_LOAD_BALANCE)) {
6700 printk("does not load-balance\n");
6701 if (sd->parent)
6702 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6703 " has parent");
6704 return -1;
6707 printk(KERN_CONT "span %s\n", str);
6709 if (!cpu_isset(cpu, sd->span)) {
6710 printk(KERN_ERR "ERROR: domain->span does not contain "
6711 "CPU%d\n", cpu);
6713 if (!cpu_isset(cpu, group->cpumask)) {
6714 printk(KERN_ERR "ERROR: domain->groups does not contain"
6715 " CPU%d\n", cpu);
6718 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6719 do {
6720 if (!group) {
6721 printk("\n");
6722 printk(KERN_ERR "ERROR: group is NULL\n");
6723 break;
6726 if (!group->__cpu_power) {
6727 printk(KERN_CONT "\n");
6728 printk(KERN_ERR "ERROR: domain->cpu_power not "
6729 "set\n");
6730 break;
6733 if (!cpus_weight(group->cpumask)) {
6734 printk(KERN_CONT "\n");
6735 printk(KERN_ERR "ERROR: empty group\n");
6736 break;
6739 if (cpus_intersects(*groupmask, group->cpumask)) {
6740 printk(KERN_CONT "\n");
6741 printk(KERN_ERR "ERROR: repeated CPUs\n");
6742 break;
6745 cpus_or(*groupmask, *groupmask, group->cpumask);
6747 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6748 printk(KERN_CONT " %s", str);
6750 group = group->next;
6751 } while (group != sd->groups);
6752 printk(KERN_CONT "\n");
6754 if (!cpus_equal(sd->span, *groupmask))
6755 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6757 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6758 printk(KERN_ERR "ERROR: parent span is not a superset "
6759 "of domain->span\n");
6760 return 0;
6763 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6765 cpumask_t *groupmask;
6766 int level = 0;
6768 if (!sd) {
6769 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6770 return;
6773 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6775 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6776 if (!groupmask) {
6777 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6778 return;
6781 for (;;) {
6782 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6783 break;
6784 level++;
6785 sd = sd->parent;
6786 if (!sd)
6787 break;
6789 kfree(groupmask);
6791 #else
6792 # define sched_domain_debug(sd, cpu) do { } while (0)
6793 #endif
6795 static int sd_degenerate(struct sched_domain *sd)
6797 if (cpus_weight(sd->span) == 1)
6798 return 1;
6800 /* Following flags need at least 2 groups */
6801 if (sd->flags & (SD_LOAD_BALANCE |
6802 SD_BALANCE_NEWIDLE |
6803 SD_BALANCE_FORK |
6804 SD_BALANCE_EXEC |
6805 SD_SHARE_CPUPOWER |
6806 SD_SHARE_PKG_RESOURCES)) {
6807 if (sd->groups != sd->groups->next)
6808 return 0;
6811 /* Following flags don't use groups */
6812 if (sd->flags & (SD_WAKE_IDLE |
6813 SD_WAKE_AFFINE |
6814 SD_WAKE_BALANCE))
6815 return 0;
6817 return 1;
6820 static int
6821 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6823 unsigned long cflags = sd->flags, pflags = parent->flags;
6825 if (sd_degenerate(parent))
6826 return 1;
6828 if (!cpus_equal(sd->span, parent->span))
6829 return 0;
6831 /* Does parent contain flags not in child? */
6832 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6833 if (cflags & SD_WAKE_AFFINE)
6834 pflags &= ~SD_WAKE_BALANCE;
6835 /* Flags needing groups don't count if only 1 group in parent */
6836 if (parent->groups == parent->groups->next) {
6837 pflags &= ~(SD_LOAD_BALANCE |
6838 SD_BALANCE_NEWIDLE |
6839 SD_BALANCE_FORK |
6840 SD_BALANCE_EXEC |
6841 SD_SHARE_CPUPOWER |
6842 SD_SHARE_PKG_RESOURCES);
6844 if (~cflags & pflags)
6845 return 0;
6847 return 1;
6850 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6852 unsigned long flags;
6853 const struct sched_class *class;
6855 spin_lock_irqsave(&rq->lock, flags);
6857 if (rq->rd) {
6858 struct root_domain *old_rd = rq->rd;
6860 for (class = sched_class_highest; class; class = class->next) {
6861 if (class->leave_domain)
6862 class->leave_domain(rq);
6865 cpu_clear(rq->cpu, old_rd->span);
6866 cpu_clear(rq->cpu, old_rd->online);
6868 if (atomic_dec_and_test(&old_rd->refcount))
6869 kfree(old_rd);
6872 atomic_inc(&rd->refcount);
6873 rq->rd = rd;
6875 cpu_set(rq->cpu, rd->span);
6876 if (cpu_isset(rq->cpu, cpu_online_map))
6877 cpu_set(rq->cpu, rd->online);
6879 for (class = sched_class_highest; class; class = class->next) {
6880 if (class->join_domain)
6881 class->join_domain(rq);
6884 spin_unlock_irqrestore(&rq->lock, flags);
6887 static void init_rootdomain(struct root_domain *rd)
6889 memset(rd, 0, sizeof(*rd));
6891 cpus_clear(rd->span);
6892 cpus_clear(rd->online);
6895 static void init_defrootdomain(void)
6897 init_rootdomain(&def_root_domain);
6898 atomic_set(&def_root_domain.refcount, 1);
6901 static struct root_domain *alloc_rootdomain(void)
6903 struct root_domain *rd;
6905 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6906 if (!rd)
6907 return NULL;
6909 init_rootdomain(rd);
6911 return rd;
6915 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6916 * hold the hotplug lock.
6918 static void
6919 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6921 struct rq *rq = cpu_rq(cpu);
6922 struct sched_domain *tmp;
6924 /* Remove the sched domains which do not contribute to scheduling. */
6925 for (tmp = sd; tmp; tmp = tmp->parent) {
6926 struct sched_domain *parent = tmp->parent;
6927 if (!parent)
6928 break;
6929 if (sd_parent_degenerate(tmp, parent)) {
6930 tmp->parent = parent->parent;
6931 if (parent->parent)
6932 parent->parent->child = tmp;
6936 if (sd && sd_degenerate(sd)) {
6937 sd = sd->parent;
6938 if (sd)
6939 sd->child = NULL;
6942 sched_domain_debug(sd, cpu);
6944 rq_attach_root(rq, rd);
6945 rcu_assign_pointer(rq->sd, sd);
6948 /* cpus with isolated domains */
6949 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6951 /* Setup the mask of cpus configured for isolated domains */
6952 static int __init isolated_cpu_setup(char *str)
6954 int ints[NR_CPUS], i;
6956 str = get_options(str, ARRAY_SIZE(ints), ints);
6957 cpus_clear(cpu_isolated_map);
6958 for (i = 1; i <= ints[0]; i++)
6959 if (ints[i] < NR_CPUS)
6960 cpu_set(ints[i], cpu_isolated_map);
6961 return 1;
6964 __setup("isolcpus=", isolated_cpu_setup);
6967 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6968 * to a function which identifies what group(along with sched group) a CPU
6969 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6970 * (due to the fact that we keep track of groups covered with a cpumask_t).
6972 * init_sched_build_groups will build a circular linked list of the groups
6973 * covered by the given span, and will set each group's ->cpumask correctly,
6974 * and ->cpu_power to 0.
6976 static void
6977 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6978 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6979 struct sched_group **sg,
6980 cpumask_t *tmpmask),
6981 cpumask_t *covered, cpumask_t *tmpmask)
6983 struct sched_group *first = NULL, *last = NULL;
6984 int i;
6986 cpus_clear(*covered);
6988 for_each_cpu_mask(i, *span) {
6989 struct sched_group *sg;
6990 int group = group_fn(i, cpu_map, &sg, tmpmask);
6991 int j;
6993 if (cpu_isset(i, *covered))
6994 continue;
6996 cpus_clear(sg->cpumask);
6997 sg->__cpu_power = 0;
6999 for_each_cpu_mask(j, *span) {
7000 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
7001 continue;
7003 cpu_set(j, *covered);
7004 cpu_set(j, sg->cpumask);
7006 if (!first)
7007 first = sg;
7008 if (last)
7009 last->next = sg;
7010 last = sg;
7012 last->next = first;
7015 #define SD_NODES_PER_DOMAIN 16
7017 #ifdef CONFIG_NUMA
7020 * find_next_best_node - find the next node to include in a sched_domain
7021 * @node: node whose sched_domain we're building
7022 * @used_nodes: nodes already in the sched_domain
7024 * Find the next node to include in a given scheduling domain. Simply
7025 * finds the closest node not already in the @used_nodes map.
7027 * Should use nodemask_t.
7029 static int find_next_best_node(int node, nodemask_t *used_nodes)
7031 int i, n, val, min_val, best_node = 0;
7033 min_val = INT_MAX;
7035 for (i = 0; i < MAX_NUMNODES; i++) {
7036 /* Start at @node */
7037 n = (node + i) % MAX_NUMNODES;
7039 if (!nr_cpus_node(n))
7040 continue;
7042 /* Skip already used nodes */
7043 if (node_isset(n, *used_nodes))
7044 continue;
7046 /* Simple min distance search */
7047 val = node_distance(node, n);
7049 if (val < min_val) {
7050 min_val = val;
7051 best_node = n;
7055 node_set(best_node, *used_nodes);
7056 return best_node;
7060 * sched_domain_node_span - get a cpumask for a node's sched_domain
7061 * @node: node whose cpumask we're constructing
7062 * @span: resulting cpumask
7064 * Given a node, construct a good cpumask for its sched_domain to span. It
7065 * should be one that prevents unnecessary balancing, but also spreads tasks
7066 * out optimally.
7068 static void sched_domain_node_span(int node, cpumask_t *span)
7070 nodemask_t used_nodes;
7071 node_to_cpumask_ptr(nodemask, node);
7072 int i;
7074 cpus_clear(*span);
7075 nodes_clear(used_nodes);
7077 cpus_or(*span, *span, *nodemask);
7078 node_set(node, used_nodes);
7080 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7081 int next_node = find_next_best_node(node, &used_nodes);
7083 node_to_cpumask_ptr_next(nodemask, next_node);
7084 cpus_or(*span, *span, *nodemask);
7087 #endif
7089 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7092 * SMT sched-domains:
7094 #ifdef CONFIG_SCHED_SMT
7095 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
7096 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
7098 static int
7099 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7100 cpumask_t *unused)
7102 if (sg)
7103 *sg = &per_cpu(sched_group_cpus, cpu);
7104 return cpu;
7106 #endif
7109 * multi-core sched-domains:
7111 #ifdef CONFIG_SCHED_MC
7112 static DEFINE_PER_CPU(struct sched_domain, core_domains);
7113 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
7114 #endif
7116 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7117 static int
7118 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7119 cpumask_t *mask)
7121 int group;
7123 *mask = per_cpu(cpu_sibling_map, cpu);
7124 cpus_and(*mask, *mask, *cpu_map);
7125 group = first_cpu(*mask);
7126 if (sg)
7127 *sg = &per_cpu(sched_group_core, group);
7128 return group;
7130 #elif defined(CONFIG_SCHED_MC)
7131 static int
7132 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7133 cpumask_t *unused)
7135 if (sg)
7136 *sg = &per_cpu(sched_group_core, cpu);
7137 return cpu;
7139 #endif
7141 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7142 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7144 static int
7145 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7146 cpumask_t *mask)
7148 int group;
7149 #ifdef CONFIG_SCHED_MC
7150 *mask = cpu_coregroup_map(cpu);
7151 cpus_and(*mask, *mask, *cpu_map);
7152 group = first_cpu(*mask);
7153 #elif defined(CONFIG_SCHED_SMT)
7154 *mask = per_cpu(cpu_sibling_map, cpu);
7155 cpus_and(*mask, *mask, *cpu_map);
7156 group = first_cpu(*mask);
7157 #else
7158 group = cpu;
7159 #endif
7160 if (sg)
7161 *sg = &per_cpu(sched_group_phys, group);
7162 return group;
7165 #ifdef CONFIG_NUMA
7167 * The init_sched_build_groups can't handle what we want to do with node
7168 * groups, so roll our own. Now each node has its own list of groups which
7169 * gets dynamically allocated.
7171 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7172 static struct sched_group ***sched_group_nodes_bycpu;
7174 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7175 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7177 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7178 struct sched_group **sg, cpumask_t *nodemask)
7180 int group;
7182 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7183 cpus_and(*nodemask, *nodemask, *cpu_map);
7184 group = first_cpu(*nodemask);
7186 if (sg)
7187 *sg = &per_cpu(sched_group_allnodes, group);
7188 return group;
7191 static void init_numa_sched_groups_power(struct sched_group *group_head)
7193 struct sched_group *sg = group_head;
7194 int j;
7196 if (!sg)
7197 return;
7198 do {
7199 for_each_cpu_mask(j, sg->cpumask) {
7200 struct sched_domain *sd;
7202 sd = &per_cpu(phys_domains, j);
7203 if (j != first_cpu(sd->groups->cpumask)) {
7205 * Only add "power" once for each
7206 * physical package.
7208 continue;
7211 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7213 sg = sg->next;
7214 } while (sg != group_head);
7216 #endif
7218 #ifdef CONFIG_NUMA
7219 /* Free memory allocated for various sched_group structures */
7220 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7222 int cpu, i;
7224 for_each_cpu_mask(cpu, *cpu_map) {
7225 struct sched_group **sched_group_nodes
7226 = sched_group_nodes_bycpu[cpu];
7228 if (!sched_group_nodes)
7229 continue;
7231 for (i = 0; i < MAX_NUMNODES; i++) {
7232 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7234 *nodemask = node_to_cpumask(i);
7235 cpus_and(*nodemask, *nodemask, *cpu_map);
7236 if (cpus_empty(*nodemask))
7237 continue;
7239 if (sg == NULL)
7240 continue;
7241 sg = sg->next;
7242 next_sg:
7243 oldsg = sg;
7244 sg = sg->next;
7245 kfree(oldsg);
7246 if (oldsg != sched_group_nodes[i])
7247 goto next_sg;
7249 kfree(sched_group_nodes);
7250 sched_group_nodes_bycpu[cpu] = NULL;
7253 #else
7254 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7257 #endif
7260 * Initialize sched groups cpu_power.
7262 * cpu_power indicates the capacity of sched group, which is used while
7263 * distributing the load between different sched groups in a sched domain.
7264 * Typically cpu_power for all the groups in a sched domain will be same unless
7265 * there are asymmetries in the topology. If there are asymmetries, group
7266 * having more cpu_power will pickup more load compared to the group having
7267 * less cpu_power.
7269 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7270 * the maximum number of tasks a group can handle in the presence of other idle
7271 * or lightly loaded groups in the same sched domain.
7273 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7275 struct sched_domain *child;
7276 struct sched_group *group;
7278 WARN_ON(!sd || !sd->groups);
7280 if (cpu != first_cpu(sd->groups->cpumask))
7281 return;
7283 child = sd->child;
7285 sd->groups->__cpu_power = 0;
7288 * For perf policy, if the groups in child domain share resources
7289 * (for example cores sharing some portions of the cache hierarchy
7290 * or SMT), then set this domain groups cpu_power such that each group
7291 * can handle only one task, when there are other idle groups in the
7292 * same sched domain.
7294 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7295 (child->flags &
7296 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7297 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7298 return;
7302 * add cpu_power of each child group to this groups cpu_power
7304 group = child->groups;
7305 do {
7306 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7307 group = group->next;
7308 } while (group != child->groups);
7312 * Initializers for schedule domains
7313 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7316 #define SD_INIT(sd, type) sd_init_##type(sd)
7317 #define SD_INIT_FUNC(type) \
7318 static noinline void sd_init_##type(struct sched_domain *sd) \
7320 memset(sd, 0, sizeof(*sd)); \
7321 *sd = SD_##type##_INIT; \
7322 sd->level = SD_LV_##type; \
7325 SD_INIT_FUNC(CPU)
7326 #ifdef CONFIG_NUMA
7327 SD_INIT_FUNC(ALLNODES)
7328 SD_INIT_FUNC(NODE)
7329 #endif
7330 #ifdef CONFIG_SCHED_SMT
7331 SD_INIT_FUNC(SIBLING)
7332 #endif
7333 #ifdef CONFIG_SCHED_MC
7334 SD_INIT_FUNC(MC)
7335 #endif
7338 * To minimize stack usage kmalloc room for cpumasks and share the
7339 * space as the usage in build_sched_domains() dictates. Used only
7340 * if the amount of space is significant.
7342 struct allmasks {
7343 cpumask_t tmpmask; /* make this one first */
7344 union {
7345 cpumask_t nodemask;
7346 cpumask_t this_sibling_map;
7347 cpumask_t this_core_map;
7349 cpumask_t send_covered;
7351 #ifdef CONFIG_NUMA
7352 cpumask_t domainspan;
7353 cpumask_t covered;
7354 cpumask_t notcovered;
7355 #endif
7358 #if NR_CPUS > 128
7359 #define SCHED_CPUMASK_ALLOC 1
7360 #define SCHED_CPUMASK_FREE(v) kfree(v)
7361 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7362 #else
7363 #define SCHED_CPUMASK_ALLOC 0
7364 #define SCHED_CPUMASK_FREE(v)
7365 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7366 #endif
7368 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7369 ((unsigned long)(a) + offsetof(struct allmasks, v))
7371 static int default_relax_domain_level = -1;
7373 static int __init setup_relax_domain_level(char *str)
7375 default_relax_domain_level = simple_strtoul(str, NULL, 0);
7376 return 1;
7378 __setup("relax_domain_level=", setup_relax_domain_level);
7380 static void set_domain_attribute(struct sched_domain *sd,
7381 struct sched_domain_attr *attr)
7383 int request;
7385 if (!attr || attr->relax_domain_level < 0) {
7386 if (default_relax_domain_level < 0)
7387 return;
7388 else
7389 request = default_relax_domain_level;
7390 } else
7391 request = attr->relax_domain_level;
7392 if (request < sd->level) {
7393 /* turn off idle balance on this domain */
7394 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7395 } else {
7396 /* turn on idle balance on this domain */
7397 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7402 * Build sched domains for a given set of cpus and attach the sched domains
7403 * to the individual cpus
7405 static int __build_sched_domains(const cpumask_t *cpu_map,
7406 struct sched_domain_attr *attr)
7408 int i;
7409 struct root_domain *rd;
7410 SCHED_CPUMASK_DECLARE(allmasks);
7411 cpumask_t *tmpmask;
7412 #ifdef CONFIG_NUMA
7413 struct sched_group **sched_group_nodes = NULL;
7414 int sd_allnodes = 0;
7417 * Allocate the per-node list of sched groups
7419 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
7420 GFP_KERNEL);
7421 if (!sched_group_nodes) {
7422 printk(KERN_WARNING "Can not alloc sched group node list\n");
7423 return -ENOMEM;
7425 #endif
7427 rd = alloc_rootdomain();
7428 if (!rd) {
7429 printk(KERN_WARNING "Cannot alloc root domain\n");
7430 #ifdef CONFIG_NUMA
7431 kfree(sched_group_nodes);
7432 #endif
7433 return -ENOMEM;
7436 #if SCHED_CPUMASK_ALLOC
7437 /* get space for all scratch cpumask variables */
7438 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7439 if (!allmasks) {
7440 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7441 kfree(rd);
7442 #ifdef CONFIG_NUMA
7443 kfree(sched_group_nodes);
7444 #endif
7445 return -ENOMEM;
7447 #endif
7448 tmpmask = (cpumask_t *)allmasks;
7451 #ifdef CONFIG_NUMA
7452 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7453 #endif
7456 * Set up domains for cpus specified by the cpu_map.
7458 for_each_cpu_mask(i, *cpu_map) {
7459 struct sched_domain *sd = NULL, *p;
7460 SCHED_CPUMASK_VAR(nodemask, allmasks);
7462 *nodemask = node_to_cpumask(cpu_to_node(i));
7463 cpus_and(*nodemask, *nodemask, *cpu_map);
7465 #ifdef CONFIG_NUMA
7466 if (cpus_weight(*cpu_map) >
7467 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7468 sd = &per_cpu(allnodes_domains, i);
7469 SD_INIT(sd, ALLNODES);
7470 set_domain_attribute(sd, attr);
7471 sd->span = *cpu_map;
7472 sd->first_cpu = first_cpu(sd->span);
7473 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7474 p = sd;
7475 sd_allnodes = 1;
7476 } else
7477 p = NULL;
7479 sd = &per_cpu(node_domains, i);
7480 SD_INIT(sd, NODE);
7481 set_domain_attribute(sd, attr);
7482 sched_domain_node_span(cpu_to_node(i), &sd->span);
7483 sd->first_cpu = first_cpu(sd->span);
7484 sd->parent = p;
7485 if (p)
7486 p->child = sd;
7487 cpus_and(sd->span, sd->span, *cpu_map);
7488 #endif
7490 p = sd;
7491 sd = &per_cpu(phys_domains, i);
7492 SD_INIT(sd, CPU);
7493 set_domain_attribute(sd, attr);
7494 sd->span = *nodemask;
7495 sd->first_cpu = first_cpu(sd->span);
7496 sd->parent = p;
7497 if (p)
7498 p->child = sd;
7499 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7501 #ifdef CONFIG_SCHED_MC
7502 p = sd;
7503 sd = &per_cpu(core_domains, i);
7504 SD_INIT(sd, MC);
7505 set_domain_attribute(sd, attr);
7506 sd->span = cpu_coregroup_map(i);
7507 sd->first_cpu = first_cpu(sd->span);
7508 cpus_and(sd->span, sd->span, *cpu_map);
7509 sd->parent = p;
7510 p->child = sd;
7511 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7512 #endif
7514 #ifdef CONFIG_SCHED_SMT
7515 p = sd;
7516 sd = &per_cpu(cpu_domains, i);
7517 SD_INIT(sd, SIBLING);
7518 set_domain_attribute(sd, attr);
7519 sd->span = per_cpu(cpu_sibling_map, i);
7520 sd->first_cpu = first_cpu(sd->span);
7521 cpus_and(sd->span, sd->span, *cpu_map);
7522 sd->parent = p;
7523 p->child = sd;
7524 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7525 #endif
7528 #ifdef CONFIG_SCHED_SMT
7529 /* Set up CPU (sibling) groups */
7530 for_each_cpu_mask(i, *cpu_map) {
7531 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7532 SCHED_CPUMASK_VAR(send_covered, allmasks);
7534 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7535 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7536 if (i != first_cpu(*this_sibling_map))
7537 continue;
7539 init_sched_build_groups(this_sibling_map, cpu_map,
7540 &cpu_to_cpu_group,
7541 send_covered, tmpmask);
7543 #endif
7545 #ifdef CONFIG_SCHED_MC
7546 /* Set up multi-core groups */
7547 for_each_cpu_mask(i, *cpu_map) {
7548 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7549 SCHED_CPUMASK_VAR(send_covered, allmasks);
7551 *this_core_map = cpu_coregroup_map(i);
7552 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7553 if (i != first_cpu(*this_core_map))
7554 continue;
7556 init_sched_build_groups(this_core_map, cpu_map,
7557 &cpu_to_core_group,
7558 send_covered, tmpmask);
7560 #endif
7562 /* Set up physical groups */
7563 for (i = 0; i < MAX_NUMNODES; i++) {
7564 SCHED_CPUMASK_VAR(nodemask, allmasks);
7565 SCHED_CPUMASK_VAR(send_covered, allmasks);
7567 *nodemask = node_to_cpumask(i);
7568 cpus_and(*nodemask, *nodemask, *cpu_map);
7569 if (cpus_empty(*nodemask))
7570 continue;
7572 init_sched_build_groups(nodemask, cpu_map,
7573 &cpu_to_phys_group,
7574 send_covered, tmpmask);
7577 #ifdef CONFIG_NUMA
7578 /* Set up node groups */
7579 if (sd_allnodes) {
7580 SCHED_CPUMASK_VAR(send_covered, allmasks);
7582 init_sched_build_groups(cpu_map, cpu_map,
7583 &cpu_to_allnodes_group,
7584 send_covered, tmpmask);
7587 for (i = 0; i < MAX_NUMNODES; i++) {
7588 /* Set up node groups */
7589 struct sched_group *sg, *prev;
7590 SCHED_CPUMASK_VAR(nodemask, allmasks);
7591 SCHED_CPUMASK_VAR(domainspan, allmasks);
7592 SCHED_CPUMASK_VAR(covered, allmasks);
7593 int j;
7595 *nodemask = node_to_cpumask(i);
7596 cpus_clear(*covered);
7598 cpus_and(*nodemask, *nodemask, *cpu_map);
7599 if (cpus_empty(*nodemask)) {
7600 sched_group_nodes[i] = NULL;
7601 continue;
7604 sched_domain_node_span(i, domainspan);
7605 cpus_and(*domainspan, *domainspan, *cpu_map);
7607 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7608 if (!sg) {
7609 printk(KERN_WARNING "Can not alloc domain group for "
7610 "node %d\n", i);
7611 goto error;
7613 sched_group_nodes[i] = sg;
7614 for_each_cpu_mask(j, *nodemask) {
7615 struct sched_domain *sd;
7617 sd = &per_cpu(node_domains, j);
7618 sd->groups = sg;
7620 sg->__cpu_power = 0;
7621 sg->cpumask = *nodemask;
7622 sg->next = sg;
7623 cpus_or(*covered, *covered, *nodemask);
7624 prev = sg;
7626 for (j = 0; j < MAX_NUMNODES; j++) {
7627 SCHED_CPUMASK_VAR(notcovered, allmasks);
7628 int n = (i + j) % MAX_NUMNODES;
7629 node_to_cpumask_ptr(pnodemask, n);
7631 cpus_complement(*notcovered, *covered);
7632 cpus_and(*tmpmask, *notcovered, *cpu_map);
7633 cpus_and(*tmpmask, *tmpmask, *domainspan);
7634 if (cpus_empty(*tmpmask))
7635 break;
7637 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7638 if (cpus_empty(*tmpmask))
7639 continue;
7641 sg = kmalloc_node(sizeof(struct sched_group),
7642 GFP_KERNEL, i);
7643 if (!sg) {
7644 printk(KERN_WARNING
7645 "Can not alloc domain group for node %d\n", j);
7646 goto error;
7648 sg->__cpu_power = 0;
7649 sg->cpumask = *tmpmask;
7650 sg->next = prev->next;
7651 cpus_or(*covered, *covered, *tmpmask);
7652 prev->next = sg;
7653 prev = sg;
7656 #endif
7658 /* Calculate CPU power for physical packages and nodes */
7659 #ifdef CONFIG_SCHED_SMT
7660 for_each_cpu_mask(i, *cpu_map) {
7661 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7663 init_sched_groups_power(i, sd);
7665 #endif
7666 #ifdef CONFIG_SCHED_MC
7667 for_each_cpu_mask(i, *cpu_map) {
7668 struct sched_domain *sd = &per_cpu(core_domains, i);
7670 init_sched_groups_power(i, sd);
7672 #endif
7674 for_each_cpu_mask(i, *cpu_map) {
7675 struct sched_domain *sd = &per_cpu(phys_domains, i);
7677 init_sched_groups_power(i, sd);
7680 #ifdef CONFIG_NUMA
7681 for (i = 0; i < MAX_NUMNODES; i++)
7682 init_numa_sched_groups_power(sched_group_nodes[i]);
7684 if (sd_allnodes) {
7685 struct sched_group *sg;
7687 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7688 tmpmask);
7689 init_numa_sched_groups_power(sg);
7691 #endif
7693 /* Attach the domains */
7694 for_each_cpu_mask(i, *cpu_map) {
7695 struct sched_domain *sd;
7696 #ifdef CONFIG_SCHED_SMT
7697 sd = &per_cpu(cpu_domains, i);
7698 #elif defined(CONFIG_SCHED_MC)
7699 sd = &per_cpu(core_domains, i);
7700 #else
7701 sd = &per_cpu(phys_domains, i);
7702 #endif
7703 cpu_attach_domain(sd, rd, i);
7706 SCHED_CPUMASK_FREE((void *)allmasks);
7707 return 0;
7709 #ifdef CONFIG_NUMA
7710 error:
7711 free_sched_groups(cpu_map, tmpmask);
7712 SCHED_CPUMASK_FREE((void *)allmasks);
7713 return -ENOMEM;
7714 #endif
7717 static int build_sched_domains(const cpumask_t *cpu_map)
7719 return __build_sched_domains(cpu_map, NULL);
7722 static cpumask_t *doms_cur; /* current sched domains */
7723 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7724 static struct sched_domain_attr *dattr_cur; /* attribues of custom domains
7725 in 'doms_cur' */
7728 * Special case: If a kmalloc of a doms_cur partition (array of
7729 * cpumask_t) fails, then fallback to a single sched domain,
7730 * as determined by the single cpumask_t fallback_doms.
7732 static cpumask_t fallback_doms;
7734 void __attribute__((weak)) arch_update_cpu_topology(void)
7739 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7740 * For now this just excludes isolated cpus, but could be used to
7741 * exclude other special cases in the future.
7743 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7745 int err;
7747 arch_update_cpu_topology();
7748 ndoms_cur = 1;
7749 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7750 if (!doms_cur)
7751 doms_cur = &fallback_doms;
7752 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7753 dattr_cur = NULL;
7754 err = build_sched_domains(doms_cur);
7755 register_sched_domain_sysctl();
7757 return err;
7760 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7761 cpumask_t *tmpmask)
7763 free_sched_groups(cpu_map, tmpmask);
7767 * Detach sched domains from a group of cpus specified in cpu_map
7768 * These cpus will now be attached to the NULL domain
7770 static void detach_destroy_domains(const cpumask_t *cpu_map)
7772 cpumask_t tmpmask;
7773 int i;
7775 unregister_sched_domain_sysctl();
7777 for_each_cpu_mask(i, *cpu_map)
7778 cpu_attach_domain(NULL, &def_root_domain, i);
7779 synchronize_sched();
7780 arch_destroy_sched_domains(cpu_map, &tmpmask);
7783 /* handle null as "default" */
7784 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7785 struct sched_domain_attr *new, int idx_new)
7787 struct sched_domain_attr tmp;
7789 /* fast path */
7790 if (!new && !cur)
7791 return 1;
7793 tmp = SD_ATTR_INIT;
7794 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7795 new ? (new + idx_new) : &tmp,
7796 sizeof(struct sched_domain_attr));
7800 * Partition sched domains as specified by the 'ndoms_new'
7801 * cpumasks in the array doms_new[] of cpumasks. This compares
7802 * doms_new[] to the current sched domain partitioning, doms_cur[].
7803 * It destroys each deleted domain and builds each new domain.
7805 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7806 * The masks don't intersect (don't overlap.) We should setup one
7807 * sched domain for each mask. CPUs not in any of the cpumasks will
7808 * not be load balanced. If the same cpumask appears both in the
7809 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7810 * it as it is.
7812 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7813 * ownership of it and will kfree it when done with it. If the caller
7814 * failed the kmalloc call, then it can pass in doms_new == NULL,
7815 * and partition_sched_domains() will fallback to the single partition
7816 * 'fallback_doms'.
7818 * Call with hotplug lock held
7820 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7821 struct sched_domain_attr *dattr_new)
7823 int i, j;
7825 lock_doms_cur();
7827 /* always unregister in case we don't destroy any domains */
7828 unregister_sched_domain_sysctl();
7830 if (doms_new == NULL) {
7831 ndoms_new = 1;
7832 doms_new = &fallback_doms;
7833 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7834 dattr_new = NULL;
7837 /* Destroy deleted domains */
7838 for (i = 0; i < ndoms_cur; i++) {
7839 for (j = 0; j < ndoms_new; j++) {
7840 if (cpus_equal(doms_cur[i], doms_new[j])
7841 && dattrs_equal(dattr_cur, i, dattr_new, j))
7842 goto match1;
7844 /* no match - a current sched domain not in new doms_new[] */
7845 detach_destroy_domains(doms_cur + i);
7846 match1:
7850 /* Build new domains */
7851 for (i = 0; i < ndoms_new; i++) {
7852 for (j = 0; j < ndoms_cur; j++) {
7853 if (cpus_equal(doms_new[i], doms_cur[j])
7854 && dattrs_equal(dattr_new, i, dattr_cur, j))
7855 goto match2;
7857 /* no match - add a new doms_new */
7858 __build_sched_domains(doms_new + i,
7859 dattr_new ? dattr_new + i : NULL);
7860 match2:
7864 /* Remember the new sched domains */
7865 if (doms_cur != &fallback_doms)
7866 kfree(doms_cur);
7867 kfree(dattr_cur); /* kfree(NULL) is safe */
7868 doms_cur = doms_new;
7869 dattr_cur = dattr_new;
7870 ndoms_cur = ndoms_new;
7872 register_sched_domain_sysctl();
7874 unlock_doms_cur();
7877 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7878 int arch_reinit_sched_domains(void)
7880 int err;
7882 get_online_cpus();
7883 detach_destroy_domains(&cpu_online_map);
7884 err = arch_init_sched_domains(&cpu_online_map);
7885 put_online_cpus();
7887 return err;
7890 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7892 int ret;
7894 if (buf[0] != '0' && buf[0] != '1')
7895 return -EINVAL;
7897 if (smt)
7898 sched_smt_power_savings = (buf[0] == '1');
7899 else
7900 sched_mc_power_savings = (buf[0] == '1');
7902 ret = arch_reinit_sched_domains();
7904 return ret ? ret : count;
7907 #ifdef CONFIG_SCHED_MC
7908 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7910 return sprintf(page, "%u\n", sched_mc_power_savings);
7912 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7913 const char *buf, size_t count)
7915 return sched_power_savings_store(buf, count, 0);
7917 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7918 sched_mc_power_savings_store);
7919 #endif
7921 #ifdef CONFIG_SCHED_SMT
7922 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7924 return sprintf(page, "%u\n", sched_smt_power_savings);
7926 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7927 const char *buf, size_t count)
7929 return sched_power_savings_store(buf, count, 1);
7931 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7932 sched_smt_power_savings_store);
7933 #endif
7935 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7937 int err = 0;
7939 #ifdef CONFIG_SCHED_SMT
7940 if (smt_capable())
7941 err = sysfs_create_file(&cls->kset.kobj,
7942 &attr_sched_smt_power_savings.attr);
7943 #endif
7944 #ifdef CONFIG_SCHED_MC
7945 if (!err && mc_capable())
7946 err = sysfs_create_file(&cls->kset.kobj,
7947 &attr_sched_mc_power_savings.attr);
7948 #endif
7949 return err;
7951 #endif
7954 * Force a reinitialization of the sched domains hierarchy. The domains
7955 * and groups cannot be updated in place without racing with the balancing
7956 * code, so we temporarily attach all running cpus to the NULL domain
7957 * which will prevent rebalancing while the sched domains are recalculated.
7959 static int update_sched_domains(struct notifier_block *nfb,
7960 unsigned long action, void *hcpu)
7962 switch (action) {
7963 case CPU_UP_PREPARE:
7964 case CPU_UP_PREPARE_FROZEN:
7965 case CPU_DOWN_PREPARE:
7966 case CPU_DOWN_PREPARE_FROZEN:
7967 detach_destroy_domains(&cpu_online_map);
7968 return NOTIFY_OK;
7970 case CPU_UP_CANCELED:
7971 case CPU_UP_CANCELED_FROZEN:
7972 case CPU_DOWN_FAILED:
7973 case CPU_DOWN_FAILED_FROZEN:
7974 case CPU_ONLINE:
7975 case CPU_ONLINE_FROZEN:
7976 case CPU_DEAD:
7977 case CPU_DEAD_FROZEN:
7979 * Fall through and re-initialise the domains.
7981 break;
7982 default:
7983 return NOTIFY_DONE;
7986 /* The hotplug lock is already held by cpu_up/cpu_down */
7987 arch_init_sched_domains(&cpu_online_map);
7989 return NOTIFY_OK;
7992 void __init sched_init_smp(void)
7994 cpumask_t non_isolated_cpus;
7996 #if defined(CONFIG_NUMA)
7997 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7998 GFP_KERNEL);
7999 BUG_ON(sched_group_nodes_bycpu == NULL);
8000 #endif
8001 get_online_cpus();
8002 arch_init_sched_domains(&cpu_online_map);
8003 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
8004 if (cpus_empty(non_isolated_cpus))
8005 cpu_set(smp_processor_id(), non_isolated_cpus);
8006 put_online_cpus();
8007 /* XXX: Theoretical race here - CPU may be hotplugged now */
8008 hotcpu_notifier(update_sched_domains, 0);
8009 init_hrtick();
8011 /* Move init over to a non-isolated CPU */
8012 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
8013 BUG();
8014 sched_init_granularity();
8016 #else
8017 void __init sched_init_smp(void)
8019 sched_init_granularity();
8021 #endif /* CONFIG_SMP */
8023 int in_sched_functions(unsigned long addr)
8025 return in_lock_functions(addr) ||
8026 (addr >= (unsigned long)__sched_text_start
8027 && addr < (unsigned long)__sched_text_end);
8030 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8032 cfs_rq->tasks_timeline = RB_ROOT;
8033 INIT_LIST_HEAD(&cfs_rq->tasks);
8034 #ifdef CONFIG_FAIR_GROUP_SCHED
8035 cfs_rq->rq = rq;
8036 #endif
8037 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8040 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8042 struct rt_prio_array *array;
8043 int i;
8045 array = &rt_rq->active;
8046 for (i = 0; i < MAX_RT_PRIO; i++) {
8047 INIT_LIST_HEAD(array->queue + i);
8048 __clear_bit(i, array->bitmap);
8050 /* delimiter for bitsearch: */
8051 __set_bit(MAX_RT_PRIO, array->bitmap);
8053 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8054 rt_rq->highest_prio = MAX_RT_PRIO;
8055 #endif
8056 #ifdef CONFIG_SMP
8057 rt_rq->rt_nr_migratory = 0;
8058 rt_rq->overloaded = 0;
8059 #endif
8061 rt_rq->rt_time = 0;
8062 rt_rq->rt_throttled = 0;
8063 rt_rq->rt_runtime = 0;
8064 spin_lock_init(&rt_rq->rt_runtime_lock);
8066 #ifdef CONFIG_RT_GROUP_SCHED
8067 rt_rq->rt_nr_boosted = 0;
8068 rt_rq->rq = rq;
8069 #endif
8072 #ifdef CONFIG_FAIR_GROUP_SCHED
8073 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8074 struct sched_entity *se, int cpu, int add,
8075 struct sched_entity *parent)
8077 struct rq *rq = cpu_rq(cpu);
8078 tg->cfs_rq[cpu] = cfs_rq;
8079 init_cfs_rq(cfs_rq, rq);
8080 cfs_rq->tg = tg;
8081 if (add)
8082 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8084 tg->se[cpu] = se;
8085 /* se could be NULL for init_task_group */
8086 if (!se)
8087 return;
8089 if (!parent)
8090 se->cfs_rq = &rq->cfs;
8091 else
8092 se->cfs_rq = parent->my_q;
8094 se->my_q = cfs_rq;
8095 se->load.weight = tg->shares;
8096 se->load.inv_weight = 0;
8097 se->parent = parent;
8099 #endif
8101 #ifdef CONFIG_RT_GROUP_SCHED
8102 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8103 struct sched_rt_entity *rt_se, int cpu, int add,
8104 struct sched_rt_entity *parent)
8106 struct rq *rq = cpu_rq(cpu);
8108 tg->rt_rq[cpu] = rt_rq;
8109 init_rt_rq(rt_rq, rq);
8110 rt_rq->tg = tg;
8111 rt_rq->rt_se = rt_se;
8112 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8113 if (add)
8114 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8116 tg->rt_se[cpu] = rt_se;
8117 if (!rt_se)
8118 return;
8120 if (!parent)
8121 rt_se->rt_rq = &rq->rt;
8122 else
8123 rt_se->rt_rq = parent->my_q;
8125 rt_se->rt_rq = &rq->rt;
8126 rt_se->my_q = rt_rq;
8127 rt_se->parent = parent;
8128 INIT_LIST_HEAD(&rt_se->run_list);
8130 #endif
8132 void __init sched_init(void)
8134 int i, j;
8135 unsigned long alloc_size = 0, ptr;
8137 #ifdef CONFIG_FAIR_GROUP_SCHED
8138 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8139 #endif
8140 #ifdef CONFIG_RT_GROUP_SCHED
8141 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8142 #endif
8143 #ifdef CONFIG_USER_SCHED
8144 alloc_size *= 2;
8145 #endif
8147 * As sched_init() is called before page_alloc is setup,
8148 * we use alloc_bootmem().
8150 if (alloc_size) {
8151 ptr = (unsigned long)alloc_bootmem(alloc_size);
8153 #ifdef CONFIG_FAIR_GROUP_SCHED
8154 init_task_group.se = (struct sched_entity **)ptr;
8155 ptr += nr_cpu_ids * sizeof(void **);
8157 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8158 ptr += nr_cpu_ids * sizeof(void **);
8160 #ifdef CONFIG_USER_SCHED
8161 root_task_group.se = (struct sched_entity **)ptr;
8162 ptr += nr_cpu_ids * sizeof(void **);
8164 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8165 ptr += nr_cpu_ids * sizeof(void **);
8166 #endif
8167 #endif
8168 #ifdef CONFIG_RT_GROUP_SCHED
8169 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8170 ptr += nr_cpu_ids * sizeof(void **);
8172 init_task_group.rt_rq = (struct rt_rq **)ptr;
8173 ptr += nr_cpu_ids * sizeof(void **);
8175 #ifdef CONFIG_USER_SCHED
8176 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8177 ptr += nr_cpu_ids * sizeof(void **);
8179 root_task_group.rt_rq = (struct rt_rq **)ptr;
8180 ptr += nr_cpu_ids * sizeof(void **);
8181 #endif
8182 #endif
8185 #ifdef CONFIG_SMP
8186 init_aggregate();
8187 init_defrootdomain();
8188 #endif
8190 init_rt_bandwidth(&def_rt_bandwidth,
8191 global_rt_period(), global_rt_runtime());
8193 #ifdef CONFIG_RT_GROUP_SCHED
8194 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8195 global_rt_period(), global_rt_runtime());
8196 #ifdef CONFIG_USER_SCHED
8197 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8198 global_rt_period(), RUNTIME_INF);
8199 #endif
8200 #endif
8202 #ifdef CONFIG_GROUP_SCHED
8203 list_add(&init_task_group.list, &task_groups);
8204 INIT_LIST_HEAD(&init_task_group.children);
8206 #ifdef CONFIG_USER_SCHED
8207 INIT_LIST_HEAD(&root_task_group.children);
8208 init_task_group.parent = &root_task_group;
8209 list_add(&init_task_group.siblings, &root_task_group.children);
8210 #endif
8211 #endif
8213 for_each_possible_cpu(i) {
8214 struct rq *rq;
8216 rq = cpu_rq(i);
8217 spin_lock_init(&rq->lock);
8218 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
8219 rq->nr_running = 0;
8220 rq->clock = 1;
8221 update_last_tick_seen(rq);
8222 init_cfs_rq(&rq->cfs, rq);
8223 init_rt_rq(&rq->rt, rq);
8224 #ifdef CONFIG_FAIR_GROUP_SCHED
8225 init_task_group.shares = init_task_group_load;
8226 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8227 #ifdef CONFIG_CGROUP_SCHED
8229 * How much cpu bandwidth does init_task_group get?
8231 * In case of task-groups formed thr' the cgroup filesystem, it
8232 * gets 100% of the cpu resources in the system. This overall
8233 * system cpu resource is divided among the tasks of
8234 * init_task_group and its child task-groups in a fair manner,
8235 * based on each entity's (task or task-group's) weight
8236 * (se->load.weight).
8238 * In other words, if init_task_group has 10 tasks of weight
8239 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8240 * then A0's share of the cpu resource is:
8242 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8244 * We achieve this by letting init_task_group's tasks sit
8245 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8247 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8248 #elif defined CONFIG_USER_SCHED
8249 root_task_group.shares = NICE_0_LOAD;
8250 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8252 * In case of task-groups formed thr' the user id of tasks,
8253 * init_task_group represents tasks belonging to root user.
8254 * Hence it forms a sibling of all subsequent groups formed.
8255 * In this case, init_task_group gets only a fraction of overall
8256 * system cpu resource, based on the weight assigned to root
8257 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8258 * by letting tasks of init_task_group sit in a separate cfs_rq
8259 * (init_cfs_rq) and having one entity represent this group of
8260 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8262 init_tg_cfs_entry(&init_task_group,
8263 &per_cpu(init_cfs_rq, i),
8264 &per_cpu(init_sched_entity, i), i, 1,
8265 root_task_group.se[i]);
8267 #endif
8268 #endif /* CONFIG_FAIR_GROUP_SCHED */
8270 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8271 #ifdef CONFIG_RT_GROUP_SCHED
8272 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8273 #ifdef CONFIG_CGROUP_SCHED
8274 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8275 #elif defined CONFIG_USER_SCHED
8276 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8277 init_tg_rt_entry(&init_task_group,
8278 &per_cpu(init_rt_rq, i),
8279 &per_cpu(init_sched_rt_entity, i), i, 1,
8280 root_task_group.rt_se[i]);
8281 #endif
8282 #endif
8284 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8285 rq->cpu_load[j] = 0;
8286 #ifdef CONFIG_SMP
8287 rq->sd = NULL;
8288 rq->rd = NULL;
8289 rq->active_balance = 0;
8290 rq->next_balance = jiffies;
8291 rq->push_cpu = 0;
8292 rq->cpu = i;
8293 rq->migration_thread = NULL;
8294 INIT_LIST_HEAD(&rq->migration_queue);
8295 rq_attach_root(rq, &def_root_domain);
8296 #endif
8297 init_rq_hrtick(rq);
8298 atomic_set(&rq->nr_iowait, 0);
8301 set_load_weight(&init_task);
8303 #ifdef CONFIG_PREEMPT_NOTIFIERS
8304 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8305 #endif
8307 #ifdef CONFIG_SMP
8308 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
8309 #endif
8311 #ifdef CONFIG_RT_MUTEXES
8312 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8313 #endif
8316 * The boot idle thread does lazy MMU switching as well:
8318 atomic_inc(&init_mm.mm_count);
8319 enter_lazy_tlb(&init_mm, current);
8322 * Make us the idle thread. Technically, schedule() should not be
8323 * called from this thread, however somewhere below it might be,
8324 * but because we are the idle thread, we just pick up running again
8325 * when this runqueue becomes "idle".
8327 init_idle(current, smp_processor_id());
8329 * During early bootup we pretend to be a normal task:
8331 current->sched_class = &fair_sched_class;
8333 scheduler_running = 1;
8336 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8337 void __might_sleep(char *file, int line)
8339 #ifdef in_atomic
8340 static unsigned long prev_jiffy; /* ratelimiting */
8342 if ((in_atomic() || irqs_disabled()) &&
8343 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8344 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8345 return;
8346 prev_jiffy = jiffies;
8347 printk(KERN_ERR "BUG: sleeping function called from invalid"
8348 " context at %s:%d\n", file, line);
8349 printk("in_atomic():%d, irqs_disabled():%d\n",
8350 in_atomic(), irqs_disabled());
8351 debug_show_held_locks(current);
8352 if (irqs_disabled())
8353 print_irqtrace_events(current);
8354 dump_stack();
8356 #endif
8358 EXPORT_SYMBOL(__might_sleep);
8359 #endif
8361 #ifdef CONFIG_MAGIC_SYSRQ
8362 static void normalize_task(struct rq *rq, struct task_struct *p)
8364 int on_rq;
8365 update_rq_clock(rq);
8366 on_rq = p->se.on_rq;
8367 if (on_rq)
8368 deactivate_task(rq, p, 0);
8369 __setscheduler(rq, p, SCHED_NORMAL, 0);
8370 if (on_rq) {
8371 activate_task(rq, p, 0);
8372 resched_task(rq->curr);
8376 void normalize_rt_tasks(void)
8378 struct task_struct *g, *p;
8379 unsigned long flags;
8380 struct rq *rq;
8382 read_lock_irqsave(&tasklist_lock, flags);
8383 do_each_thread(g, p) {
8385 * Only normalize user tasks:
8387 if (!p->mm)
8388 continue;
8390 p->se.exec_start = 0;
8391 #ifdef CONFIG_SCHEDSTATS
8392 p->se.wait_start = 0;
8393 p->se.sleep_start = 0;
8394 p->se.block_start = 0;
8395 #endif
8396 task_rq(p)->clock = 0;
8398 if (!rt_task(p)) {
8400 * Renice negative nice level userspace
8401 * tasks back to 0:
8403 if (TASK_NICE(p) < 0 && p->mm)
8404 set_user_nice(p, 0);
8405 continue;
8408 spin_lock(&p->pi_lock);
8409 rq = __task_rq_lock(p);
8411 normalize_task(rq, p);
8413 __task_rq_unlock(rq);
8414 spin_unlock(&p->pi_lock);
8415 } while_each_thread(g, p);
8417 read_unlock_irqrestore(&tasklist_lock, flags);
8420 #endif /* CONFIG_MAGIC_SYSRQ */
8422 #ifdef CONFIG_IA64
8424 * These functions are only useful for the IA64 MCA handling.
8426 * They can only be called when the whole system has been
8427 * stopped - every CPU needs to be quiescent, and no scheduling
8428 * activity can take place. Using them for anything else would
8429 * be a serious bug, and as a result, they aren't even visible
8430 * under any other configuration.
8434 * curr_task - return the current task for a given cpu.
8435 * @cpu: the processor in question.
8437 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8439 struct task_struct *curr_task(int cpu)
8441 return cpu_curr(cpu);
8445 * set_curr_task - set the current task for a given cpu.
8446 * @cpu: the processor in question.
8447 * @p: the task pointer to set.
8449 * Description: This function must only be used when non-maskable interrupts
8450 * are serviced on a separate stack. It allows the architecture to switch the
8451 * notion of the current task on a cpu in a non-blocking manner. This function
8452 * must be called with all CPU's synchronized, and interrupts disabled, the
8453 * and caller must save the original value of the current task (see
8454 * curr_task() above) and restore that value before reenabling interrupts and
8455 * re-starting the system.
8457 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8459 void set_curr_task(int cpu, struct task_struct *p)
8461 cpu_curr(cpu) = p;
8464 #endif
8466 #ifdef CONFIG_FAIR_GROUP_SCHED
8467 static void free_fair_sched_group(struct task_group *tg)
8469 int i;
8471 for_each_possible_cpu(i) {
8472 if (tg->cfs_rq)
8473 kfree(tg->cfs_rq[i]);
8474 if (tg->se)
8475 kfree(tg->se[i]);
8478 kfree(tg->cfs_rq);
8479 kfree(tg->se);
8482 static
8483 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8485 struct cfs_rq *cfs_rq;
8486 struct sched_entity *se, *parent_se;
8487 struct rq *rq;
8488 int i;
8490 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8491 if (!tg->cfs_rq)
8492 goto err;
8493 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8494 if (!tg->se)
8495 goto err;
8497 tg->shares = NICE_0_LOAD;
8499 for_each_possible_cpu(i) {
8500 rq = cpu_rq(i);
8502 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8503 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8504 if (!cfs_rq)
8505 goto err;
8507 se = kmalloc_node(sizeof(struct sched_entity),
8508 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8509 if (!se)
8510 goto err;
8512 parent_se = parent ? parent->se[i] : NULL;
8513 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8516 return 1;
8518 err:
8519 return 0;
8522 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8524 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8525 &cpu_rq(cpu)->leaf_cfs_rq_list);
8528 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8530 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8532 #else
8533 static inline void free_fair_sched_group(struct task_group *tg)
8537 static inline
8538 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8540 return 1;
8543 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8547 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8550 #endif
8552 #ifdef CONFIG_RT_GROUP_SCHED
8553 static void free_rt_sched_group(struct task_group *tg)
8555 int i;
8557 destroy_rt_bandwidth(&tg->rt_bandwidth);
8559 for_each_possible_cpu(i) {
8560 if (tg->rt_rq)
8561 kfree(tg->rt_rq[i]);
8562 if (tg->rt_se)
8563 kfree(tg->rt_se[i]);
8566 kfree(tg->rt_rq);
8567 kfree(tg->rt_se);
8570 static
8571 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8573 struct rt_rq *rt_rq;
8574 struct sched_rt_entity *rt_se, *parent_se;
8575 struct rq *rq;
8576 int i;
8578 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8579 if (!tg->rt_rq)
8580 goto err;
8581 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8582 if (!tg->rt_se)
8583 goto err;
8585 init_rt_bandwidth(&tg->rt_bandwidth,
8586 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8588 for_each_possible_cpu(i) {
8589 rq = cpu_rq(i);
8591 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8592 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8593 if (!rt_rq)
8594 goto err;
8596 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8597 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8598 if (!rt_se)
8599 goto err;
8601 parent_se = parent ? parent->rt_se[i] : NULL;
8602 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8605 return 1;
8607 err:
8608 return 0;
8611 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8613 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8614 &cpu_rq(cpu)->leaf_rt_rq_list);
8617 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8619 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8621 #else
8622 static inline void free_rt_sched_group(struct task_group *tg)
8626 static inline
8627 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8629 return 1;
8632 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8636 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8639 #endif
8641 #ifdef CONFIG_GROUP_SCHED
8642 static void free_sched_group(struct task_group *tg)
8644 free_fair_sched_group(tg);
8645 free_rt_sched_group(tg);
8646 kfree(tg);
8649 /* allocate runqueue etc for a new task group */
8650 struct task_group *sched_create_group(struct task_group *parent)
8652 struct task_group *tg;
8653 unsigned long flags;
8654 int i;
8656 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8657 if (!tg)
8658 return ERR_PTR(-ENOMEM);
8660 if (!alloc_fair_sched_group(tg, parent))
8661 goto err;
8663 if (!alloc_rt_sched_group(tg, parent))
8664 goto err;
8666 spin_lock_irqsave(&task_group_lock, flags);
8667 for_each_possible_cpu(i) {
8668 register_fair_sched_group(tg, i);
8669 register_rt_sched_group(tg, i);
8671 list_add_rcu(&tg->list, &task_groups);
8673 WARN_ON(!parent); /* root should already exist */
8675 tg->parent = parent;
8676 list_add_rcu(&tg->siblings, &parent->children);
8677 INIT_LIST_HEAD(&tg->children);
8678 spin_unlock_irqrestore(&task_group_lock, flags);
8680 return tg;
8682 err:
8683 free_sched_group(tg);
8684 return ERR_PTR(-ENOMEM);
8687 /* rcu callback to free various structures associated with a task group */
8688 static void free_sched_group_rcu(struct rcu_head *rhp)
8690 /* now it should be safe to free those cfs_rqs */
8691 free_sched_group(container_of(rhp, struct task_group, rcu));
8694 /* Destroy runqueue etc associated with a task group */
8695 void sched_destroy_group(struct task_group *tg)
8697 unsigned long flags;
8698 int i;
8700 spin_lock_irqsave(&task_group_lock, flags);
8701 for_each_possible_cpu(i) {
8702 unregister_fair_sched_group(tg, i);
8703 unregister_rt_sched_group(tg, i);
8705 list_del_rcu(&tg->list);
8706 list_del_rcu(&tg->siblings);
8707 spin_unlock_irqrestore(&task_group_lock, flags);
8709 /* wait for possible concurrent references to cfs_rqs complete */
8710 call_rcu(&tg->rcu, free_sched_group_rcu);
8713 /* change task's runqueue when it moves between groups.
8714 * The caller of this function should have put the task in its new group
8715 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8716 * reflect its new group.
8718 void sched_move_task(struct task_struct *tsk)
8720 int on_rq, running;
8721 unsigned long flags;
8722 struct rq *rq;
8724 rq = task_rq_lock(tsk, &flags);
8726 update_rq_clock(rq);
8728 running = task_current(rq, tsk);
8729 on_rq = tsk->se.on_rq;
8731 if (on_rq)
8732 dequeue_task(rq, tsk, 0);
8733 if (unlikely(running))
8734 tsk->sched_class->put_prev_task(rq, tsk);
8736 set_task_rq(tsk, task_cpu(tsk));
8738 #ifdef CONFIG_FAIR_GROUP_SCHED
8739 if (tsk->sched_class->moved_group)
8740 tsk->sched_class->moved_group(tsk);
8741 #endif
8743 if (unlikely(running))
8744 tsk->sched_class->set_curr_task(rq);
8745 if (on_rq)
8746 enqueue_task(rq, tsk, 0);
8748 task_rq_unlock(rq, &flags);
8750 #endif
8752 #ifdef CONFIG_FAIR_GROUP_SCHED
8753 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8755 struct cfs_rq *cfs_rq = se->cfs_rq;
8756 int on_rq;
8758 on_rq = se->on_rq;
8759 if (on_rq)
8760 dequeue_entity(cfs_rq, se, 0);
8762 se->load.weight = shares;
8763 se->load.inv_weight = 0;
8765 if (on_rq)
8766 enqueue_entity(cfs_rq, se, 0);
8769 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8771 struct cfs_rq *cfs_rq = se->cfs_rq;
8772 struct rq *rq = cfs_rq->rq;
8773 unsigned long flags;
8775 spin_lock_irqsave(&rq->lock, flags);
8776 __set_se_shares(se, shares);
8777 spin_unlock_irqrestore(&rq->lock, flags);
8780 static DEFINE_MUTEX(shares_mutex);
8782 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8784 int i;
8785 unsigned long flags;
8788 * We can't change the weight of the root cgroup.
8790 if (!tg->se[0])
8791 return -EINVAL;
8794 * A weight of 0 or 1 can cause arithmetics problems.
8795 * (The default weight is 1024 - so there's no practical
8796 * limitation from this.)
8798 if (shares < MIN_SHARES)
8799 shares = MIN_SHARES;
8801 mutex_lock(&shares_mutex);
8802 if (tg->shares == shares)
8803 goto done;
8805 spin_lock_irqsave(&task_group_lock, flags);
8806 for_each_possible_cpu(i)
8807 unregister_fair_sched_group(tg, i);
8808 list_del_rcu(&tg->siblings);
8809 spin_unlock_irqrestore(&task_group_lock, flags);
8811 /* wait for any ongoing reference to this group to finish */
8812 synchronize_sched();
8815 * Now we are free to modify the group's share on each cpu
8816 * w/o tripping rebalance_share or load_balance_fair.
8818 tg->shares = shares;
8819 for_each_possible_cpu(i) {
8821 * force a rebalance
8823 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8824 set_se_shares(tg->se[i], shares/nr_cpu_ids);
8828 * Enable load balance activity on this group, by inserting it back on
8829 * each cpu's rq->leaf_cfs_rq_list.
8831 spin_lock_irqsave(&task_group_lock, flags);
8832 for_each_possible_cpu(i)
8833 register_fair_sched_group(tg, i);
8834 list_add_rcu(&tg->siblings, &tg->parent->children);
8835 spin_unlock_irqrestore(&task_group_lock, flags);
8836 done:
8837 mutex_unlock(&shares_mutex);
8838 return 0;
8841 unsigned long sched_group_shares(struct task_group *tg)
8843 return tg->shares;
8845 #endif
8847 #ifdef CONFIG_RT_GROUP_SCHED
8849 * Ensure that the real time constraints are schedulable.
8851 static DEFINE_MUTEX(rt_constraints_mutex);
8853 static unsigned long to_ratio(u64 period, u64 runtime)
8855 if (runtime == RUNTIME_INF)
8856 return 1ULL << 16;
8858 return div64_u64(runtime << 16, period);
8861 #ifdef CONFIG_CGROUP_SCHED
8862 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8864 struct task_group *tgi, *parent = tg->parent;
8865 unsigned long total = 0;
8867 if (!parent) {
8868 if (global_rt_period() < period)
8869 return 0;
8871 return to_ratio(period, runtime) <
8872 to_ratio(global_rt_period(), global_rt_runtime());
8875 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8876 return 0;
8878 rcu_read_lock();
8879 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8880 if (tgi == tg)
8881 continue;
8883 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8884 tgi->rt_bandwidth.rt_runtime);
8886 rcu_read_unlock();
8888 return total + to_ratio(period, runtime) <
8889 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8890 parent->rt_bandwidth.rt_runtime);
8892 #elif defined CONFIG_USER_SCHED
8893 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8895 struct task_group *tgi;
8896 unsigned long total = 0;
8897 unsigned long global_ratio =
8898 to_ratio(global_rt_period(), global_rt_runtime());
8900 rcu_read_lock();
8901 list_for_each_entry_rcu(tgi, &task_groups, list) {
8902 if (tgi == tg)
8903 continue;
8905 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8906 tgi->rt_bandwidth.rt_runtime);
8908 rcu_read_unlock();
8910 return total + to_ratio(period, runtime) < global_ratio;
8912 #endif
8914 /* Must be called with tasklist_lock held */
8915 static inline int tg_has_rt_tasks(struct task_group *tg)
8917 struct task_struct *g, *p;
8918 do_each_thread(g, p) {
8919 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8920 return 1;
8921 } while_each_thread(g, p);
8922 return 0;
8925 static int tg_set_bandwidth(struct task_group *tg,
8926 u64 rt_period, u64 rt_runtime)
8928 int i, err = 0;
8930 mutex_lock(&rt_constraints_mutex);
8931 read_lock(&tasklist_lock);
8932 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8933 err = -EBUSY;
8934 goto unlock;
8936 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8937 err = -EINVAL;
8938 goto unlock;
8941 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8942 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8943 tg->rt_bandwidth.rt_runtime = rt_runtime;
8945 for_each_possible_cpu(i) {
8946 struct rt_rq *rt_rq = tg->rt_rq[i];
8948 spin_lock(&rt_rq->rt_runtime_lock);
8949 rt_rq->rt_runtime = rt_runtime;
8950 spin_unlock(&rt_rq->rt_runtime_lock);
8952 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8953 unlock:
8954 read_unlock(&tasklist_lock);
8955 mutex_unlock(&rt_constraints_mutex);
8957 return err;
8960 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8962 u64 rt_runtime, rt_period;
8964 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8965 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8966 if (rt_runtime_us < 0)
8967 rt_runtime = RUNTIME_INF;
8969 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8972 long sched_group_rt_runtime(struct task_group *tg)
8974 u64 rt_runtime_us;
8976 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8977 return -1;
8979 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8980 do_div(rt_runtime_us, NSEC_PER_USEC);
8981 return rt_runtime_us;
8984 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8986 u64 rt_runtime, rt_period;
8988 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8989 rt_runtime = tg->rt_bandwidth.rt_runtime;
8991 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8994 long sched_group_rt_period(struct task_group *tg)
8996 u64 rt_period_us;
8998 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8999 do_div(rt_period_us, NSEC_PER_USEC);
9000 return rt_period_us;
9003 static int sched_rt_global_constraints(void)
9005 int ret = 0;
9007 mutex_lock(&rt_constraints_mutex);
9008 if (!__rt_schedulable(NULL, 1, 0))
9009 ret = -EINVAL;
9010 mutex_unlock(&rt_constraints_mutex);
9012 return ret;
9014 #else
9015 static int sched_rt_global_constraints(void)
9017 unsigned long flags;
9018 int i;
9020 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9021 for_each_possible_cpu(i) {
9022 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9024 spin_lock(&rt_rq->rt_runtime_lock);
9025 rt_rq->rt_runtime = global_rt_runtime();
9026 spin_unlock(&rt_rq->rt_runtime_lock);
9028 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9030 return 0;
9032 #endif
9034 int sched_rt_handler(struct ctl_table *table, int write,
9035 struct file *filp, void __user *buffer, size_t *lenp,
9036 loff_t *ppos)
9038 int ret;
9039 int old_period, old_runtime;
9040 static DEFINE_MUTEX(mutex);
9042 mutex_lock(&mutex);
9043 old_period = sysctl_sched_rt_period;
9044 old_runtime = sysctl_sched_rt_runtime;
9046 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9048 if (!ret && write) {
9049 ret = sched_rt_global_constraints();
9050 if (ret) {
9051 sysctl_sched_rt_period = old_period;
9052 sysctl_sched_rt_runtime = old_runtime;
9053 } else {
9054 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9055 def_rt_bandwidth.rt_period =
9056 ns_to_ktime(global_rt_period());
9059 mutex_unlock(&mutex);
9061 return ret;
9064 #ifdef CONFIG_CGROUP_SCHED
9066 /* return corresponding task_group object of a cgroup */
9067 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9069 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9070 struct task_group, css);
9073 static struct cgroup_subsys_state *
9074 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9076 struct task_group *tg, *parent;
9078 if (!cgrp->parent) {
9079 /* This is early initialization for the top cgroup */
9080 init_task_group.css.cgroup = cgrp;
9081 return &init_task_group.css;
9084 parent = cgroup_tg(cgrp->parent);
9085 tg = sched_create_group(parent);
9086 if (IS_ERR(tg))
9087 return ERR_PTR(-ENOMEM);
9089 /* Bind the cgroup to task_group object we just created */
9090 tg->css.cgroup = cgrp;
9092 return &tg->css;
9095 static void
9096 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9098 struct task_group *tg = cgroup_tg(cgrp);
9100 sched_destroy_group(tg);
9103 static int
9104 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9105 struct task_struct *tsk)
9107 #ifdef CONFIG_RT_GROUP_SCHED
9108 /* Don't accept realtime tasks when there is no way for them to run */
9109 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9110 return -EINVAL;
9111 #else
9112 /* We don't support RT-tasks being in separate groups */
9113 if (tsk->sched_class != &fair_sched_class)
9114 return -EINVAL;
9115 #endif
9117 return 0;
9120 static void
9121 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9122 struct cgroup *old_cont, struct task_struct *tsk)
9124 sched_move_task(tsk);
9127 #ifdef CONFIG_FAIR_GROUP_SCHED
9128 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9129 u64 shareval)
9131 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9134 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9136 struct task_group *tg = cgroup_tg(cgrp);
9138 return (u64) tg->shares;
9140 #endif
9142 #ifdef CONFIG_RT_GROUP_SCHED
9143 static ssize_t cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9144 s64 val)
9146 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9149 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9151 return sched_group_rt_runtime(cgroup_tg(cgrp));
9154 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9155 u64 rt_period_us)
9157 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9160 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9162 return sched_group_rt_period(cgroup_tg(cgrp));
9164 #endif
9166 static struct cftype cpu_files[] = {
9167 #ifdef CONFIG_FAIR_GROUP_SCHED
9169 .name = "shares",
9170 .read_u64 = cpu_shares_read_u64,
9171 .write_u64 = cpu_shares_write_u64,
9173 #endif
9174 #ifdef CONFIG_RT_GROUP_SCHED
9176 .name = "rt_runtime_us",
9177 .read_s64 = cpu_rt_runtime_read,
9178 .write_s64 = cpu_rt_runtime_write,
9181 .name = "rt_period_us",
9182 .read_u64 = cpu_rt_period_read_uint,
9183 .write_u64 = cpu_rt_period_write_uint,
9185 #endif
9188 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9190 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9193 struct cgroup_subsys cpu_cgroup_subsys = {
9194 .name = "cpu",
9195 .create = cpu_cgroup_create,
9196 .destroy = cpu_cgroup_destroy,
9197 .can_attach = cpu_cgroup_can_attach,
9198 .attach = cpu_cgroup_attach,
9199 .populate = cpu_cgroup_populate,
9200 .subsys_id = cpu_cgroup_subsys_id,
9201 .early_init = 1,
9204 #endif /* CONFIG_CGROUP_SCHED */
9206 #ifdef CONFIG_CGROUP_CPUACCT
9209 * CPU accounting code for task groups.
9211 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9212 * (balbir@in.ibm.com).
9215 /* track cpu usage of a group of tasks */
9216 struct cpuacct {
9217 struct cgroup_subsys_state css;
9218 /* cpuusage holds pointer to a u64-type object on every cpu */
9219 u64 *cpuusage;
9222 struct cgroup_subsys cpuacct_subsys;
9224 /* return cpu accounting group corresponding to this container */
9225 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9227 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9228 struct cpuacct, css);
9231 /* return cpu accounting group to which this task belongs */
9232 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9234 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9235 struct cpuacct, css);
9238 /* create a new cpu accounting group */
9239 static struct cgroup_subsys_state *cpuacct_create(
9240 struct cgroup_subsys *ss, struct cgroup *cgrp)
9242 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9244 if (!ca)
9245 return ERR_PTR(-ENOMEM);
9247 ca->cpuusage = alloc_percpu(u64);
9248 if (!ca->cpuusage) {
9249 kfree(ca);
9250 return ERR_PTR(-ENOMEM);
9253 return &ca->css;
9256 /* destroy an existing cpu accounting group */
9257 static void
9258 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9260 struct cpuacct *ca = cgroup_ca(cgrp);
9262 free_percpu(ca->cpuusage);
9263 kfree(ca);
9266 /* return total cpu usage (in nanoseconds) of a group */
9267 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9269 struct cpuacct *ca = cgroup_ca(cgrp);
9270 u64 totalcpuusage = 0;
9271 int i;
9273 for_each_possible_cpu(i) {
9274 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9277 * Take rq->lock to make 64-bit addition safe on 32-bit
9278 * platforms.
9280 spin_lock_irq(&cpu_rq(i)->lock);
9281 totalcpuusage += *cpuusage;
9282 spin_unlock_irq(&cpu_rq(i)->lock);
9285 return totalcpuusage;
9288 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9289 u64 reset)
9291 struct cpuacct *ca = cgroup_ca(cgrp);
9292 int err = 0;
9293 int i;
9295 if (reset) {
9296 err = -EINVAL;
9297 goto out;
9300 for_each_possible_cpu(i) {
9301 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9303 spin_lock_irq(&cpu_rq(i)->lock);
9304 *cpuusage = 0;
9305 spin_unlock_irq(&cpu_rq(i)->lock);
9307 out:
9308 return err;
9311 static struct cftype files[] = {
9313 .name = "usage",
9314 .read_u64 = cpuusage_read,
9315 .write_u64 = cpuusage_write,
9319 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9321 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9325 * charge this task's execution time to its accounting group.
9327 * called with rq->lock held.
9329 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9331 struct cpuacct *ca;
9333 if (!cpuacct_subsys.active)
9334 return;
9336 ca = task_ca(tsk);
9337 if (ca) {
9338 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9340 *cpuusage += cputime;
9344 struct cgroup_subsys cpuacct_subsys = {
9345 .name = "cpuacct",
9346 .create = cpuacct_create,
9347 .destroy = cpuacct_destroy,
9348 .populate = cpuacct_populate,
9349 .subsys_id = cpuacct_subsys_id,
9351 #endif /* CONFIG_CGROUP_CPUACCT */