[ALSA] sound/pci/pcxhr/pcxhr_core.c: fix printk warning
[linux-2.6/openmoko-kernel/knife-kernel.git] / kernel / sched.c
blob0014b03adaca0af7d09d25d3b5c0df3c007b2462
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 __read_mostly char *sched_feat_names[] = {
761 #include "sched_features.h"
762 NULL
765 #undef SCHED_FEAT
767 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 spin_lock(&rq->lock);
1128 __update_rq_clock(rq);
1129 spin_unlock(&rq->lock);
1130 rq->clock_deep_idle_events++;
1132 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
1135 * We just idled delta nanoseconds (called with irqs disabled):
1137 void sched_clock_idle_wakeup_event(u64 delta_ns)
1139 struct rq *rq = cpu_rq(smp_processor_id());
1140 u64 now = sched_clock();
1142 rq->idle_clock += delta_ns;
1144 * Override the previous timestamp and ignore all
1145 * sched_clock() deltas that occured while we idled,
1146 * and use the PM-provided delta_ns to advance the
1147 * rq clock:
1149 spin_lock(&rq->lock);
1150 rq->prev_clock_raw = now;
1151 rq->clock += delta_ns;
1152 spin_unlock(&rq->lock);
1153 touch_softlockup_watchdog();
1155 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1157 static void __resched_task(struct task_struct *p, int tif_bit);
1159 static inline void resched_task(struct task_struct *p)
1161 __resched_task(p, TIF_NEED_RESCHED);
1164 #ifdef CONFIG_SCHED_HRTICK
1166 * Use HR-timers to deliver accurate preemption points.
1168 * Its all a bit involved since we cannot program an hrt while holding the
1169 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1170 * reschedule event.
1172 * When we get rescheduled we reprogram the hrtick_timer outside of the
1173 * rq->lock.
1175 static inline void resched_hrt(struct task_struct *p)
1177 __resched_task(p, TIF_HRTICK_RESCHED);
1180 static inline void resched_rq(struct rq *rq)
1182 unsigned long flags;
1184 spin_lock_irqsave(&rq->lock, flags);
1185 resched_task(rq->curr);
1186 spin_unlock_irqrestore(&rq->lock, flags);
1189 enum {
1190 HRTICK_SET, /* re-programm hrtick_timer */
1191 HRTICK_RESET, /* not a new slice */
1195 * Use hrtick when:
1196 * - enabled by features
1197 * - hrtimer is actually high res
1199 static inline int hrtick_enabled(struct rq *rq)
1201 if (!sched_feat(HRTICK))
1202 return 0;
1203 return hrtimer_is_hres_active(&rq->hrtick_timer);
1207 * Called to set the hrtick timer state.
1209 * called with rq->lock held and irqs disabled
1211 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1213 assert_spin_locked(&rq->lock);
1216 * preempt at: now + delay
1218 rq->hrtick_expire =
1219 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1221 * indicate we need to program the timer
1223 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1224 if (reset)
1225 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1228 * New slices are called from the schedule path and don't need a
1229 * forced reschedule.
1231 if (reset)
1232 resched_hrt(rq->curr);
1235 static void hrtick_clear(struct rq *rq)
1237 if (hrtimer_active(&rq->hrtick_timer))
1238 hrtimer_cancel(&rq->hrtick_timer);
1242 * Update the timer from the possible pending state.
1244 static void hrtick_set(struct rq *rq)
1246 ktime_t time;
1247 int set, reset;
1248 unsigned long flags;
1250 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1252 spin_lock_irqsave(&rq->lock, flags);
1253 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1254 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1255 time = rq->hrtick_expire;
1256 clear_thread_flag(TIF_HRTICK_RESCHED);
1257 spin_unlock_irqrestore(&rq->lock, flags);
1259 if (set) {
1260 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1261 if (reset && !hrtimer_active(&rq->hrtick_timer))
1262 resched_rq(rq);
1263 } else
1264 hrtick_clear(rq);
1268 * High-resolution timer tick.
1269 * Runs from hardirq context with interrupts disabled.
1271 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1273 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1275 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1277 spin_lock(&rq->lock);
1278 __update_rq_clock(rq);
1279 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1280 spin_unlock(&rq->lock);
1282 return HRTIMER_NORESTART;
1285 static inline void init_rq_hrtick(struct rq *rq)
1287 rq->hrtick_flags = 0;
1288 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1289 rq->hrtick_timer.function = hrtick;
1290 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1293 void hrtick_resched(void)
1295 struct rq *rq;
1296 unsigned long flags;
1298 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1299 return;
1301 local_irq_save(flags);
1302 rq = cpu_rq(smp_processor_id());
1303 hrtick_set(rq);
1304 local_irq_restore(flags);
1306 #else
1307 static inline void hrtick_clear(struct rq *rq)
1311 static inline void hrtick_set(struct rq *rq)
1315 static inline void init_rq_hrtick(struct rq *rq)
1319 void hrtick_resched(void)
1322 #endif
1325 * resched_task - mark a task 'to be rescheduled now'.
1327 * On UP this means the setting of the need_resched flag, on SMP it
1328 * might also involve a cross-CPU call to trigger the scheduler on
1329 * the target CPU.
1331 #ifdef CONFIG_SMP
1333 #ifndef tsk_is_polling
1334 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1335 #endif
1337 static void __resched_task(struct task_struct *p, int tif_bit)
1339 int cpu;
1341 assert_spin_locked(&task_rq(p)->lock);
1343 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1344 return;
1346 set_tsk_thread_flag(p, tif_bit);
1348 cpu = task_cpu(p);
1349 if (cpu == smp_processor_id())
1350 return;
1352 /* NEED_RESCHED must be visible before we test polling */
1353 smp_mb();
1354 if (!tsk_is_polling(p))
1355 smp_send_reschedule(cpu);
1358 static void resched_cpu(int cpu)
1360 struct rq *rq = cpu_rq(cpu);
1361 unsigned long flags;
1363 if (!spin_trylock_irqsave(&rq->lock, flags))
1364 return;
1365 resched_task(cpu_curr(cpu));
1366 spin_unlock_irqrestore(&rq->lock, flags);
1369 #ifdef CONFIG_NO_HZ
1371 * When add_timer_on() enqueues a timer into the timer wheel of an
1372 * idle CPU then this timer might expire before the next timer event
1373 * which is scheduled to wake up that CPU. In case of a completely
1374 * idle system the next event might even be infinite time into the
1375 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1376 * leaves the inner idle loop so the newly added timer is taken into
1377 * account when the CPU goes back to idle and evaluates the timer
1378 * wheel for the next timer event.
1380 void wake_up_idle_cpu(int cpu)
1382 struct rq *rq = cpu_rq(cpu);
1384 if (cpu == smp_processor_id())
1385 return;
1388 * This is safe, as this function is called with the timer
1389 * wheel base lock of (cpu) held. When the CPU is on the way
1390 * to idle and has not yet set rq->curr to idle then it will
1391 * be serialized on the timer wheel base lock and take the new
1392 * timer into account automatically.
1394 if (rq->curr != rq->idle)
1395 return;
1398 * We can set TIF_RESCHED on the idle task of the other CPU
1399 * lockless. The worst case is that the other CPU runs the
1400 * idle task through an additional NOOP schedule()
1402 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1404 /* NEED_RESCHED must be visible before we test polling */
1405 smp_mb();
1406 if (!tsk_is_polling(rq->idle))
1407 smp_send_reschedule(cpu);
1409 #endif
1411 #else
1412 static void __resched_task(struct task_struct *p, int tif_bit)
1414 assert_spin_locked(&task_rq(p)->lock);
1415 set_tsk_thread_flag(p, tif_bit);
1417 #endif
1419 #if BITS_PER_LONG == 32
1420 # define WMULT_CONST (~0UL)
1421 #else
1422 # define WMULT_CONST (1UL << 32)
1423 #endif
1425 #define WMULT_SHIFT 32
1428 * Shift right and round:
1430 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1433 * delta *= weight / lw
1435 static unsigned long
1436 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1437 struct load_weight *lw)
1439 u64 tmp;
1441 if (unlikely(!lw->inv_weight))
1442 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1444 tmp = (u64)delta_exec * weight;
1446 * Check whether we'd overflow the 64-bit multiplication:
1448 if (unlikely(tmp > WMULT_CONST))
1449 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1450 WMULT_SHIFT/2);
1451 else
1452 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1454 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1457 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1459 lw->weight += inc;
1460 lw->inv_weight = 0;
1463 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1465 lw->weight -= dec;
1466 lw->inv_weight = 0;
1470 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1471 * of tasks with abnormal "nice" values across CPUs the contribution that
1472 * each task makes to its run queue's load is weighted according to its
1473 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1474 * scaled version of the new time slice allocation that they receive on time
1475 * slice expiry etc.
1478 #define WEIGHT_IDLEPRIO 2
1479 #define WMULT_IDLEPRIO (1 << 31)
1482 * Nice levels are multiplicative, with a gentle 10% change for every
1483 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1484 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1485 * that remained on nice 0.
1487 * The "10% effect" is relative and cumulative: from _any_ nice level,
1488 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1489 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1490 * If a task goes up by ~10% and another task goes down by ~10% then
1491 * the relative distance between them is ~25%.)
1493 static const int prio_to_weight[40] = {
1494 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1495 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1496 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1497 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1498 /* 0 */ 1024, 820, 655, 526, 423,
1499 /* 5 */ 335, 272, 215, 172, 137,
1500 /* 10 */ 110, 87, 70, 56, 45,
1501 /* 15 */ 36, 29, 23, 18, 15,
1505 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1507 * In cases where the weight does not change often, we can use the
1508 * precalculated inverse to speed up arithmetics by turning divisions
1509 * into multiplications:
1511 static const u32 prio_to_wmult[40] = {
1512 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1513 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1514 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1515 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1516 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1517 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1518 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1519 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1522 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1525 * runqueue iterator, to support SMP load-balancing between different
1526 * scheduling classes, without having to expose their internal data
1527 * structures to the load-balancing proper:
1529 struct rq_iterator {
1530 void *arg;
1531 struct task_struct *(*start)(void *);
1532 struct task_struct *(*next)(void *);
1535 #ifdef CONFIG_SMP
1536 static unsigned long
1537 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1538 unsigned long max_load_move, struct sched_domain *sd,
1539 enum cpu_idle_type idle, int *all_pinned,
1540 int *this_best_prio, struct rq_iterator *iterator);
1542 static int
1543 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1544 struct sched_domain *sd, enum cpu_idle_type idle,
1545 struct rq_iterator *iterator);
1546 #endif
1548 #ifdef CONFIG_CGROUP_CPUACCT
1549 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1550 #else
1551 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1552 #endif
1554 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1556 update_load_add(&rq->load, load);
1559 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1561 update_load_sub(&rq->load, load);
1564 #ifdef CONFIG_SMP
1565 static unsigned long source_load(int cpu, int type);
1566 static unsigned long target_load(int cpu, int type);
1567 static unsigned long cpu_avg_load_per_task(int cpu);
1568 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1570 #ifdef CONFIG_FAIR_GROUP_SCHED
1573 * Group load balancing.
1575 * We calculate a few balance domain wide aggregate numbers; load and weight.
1576 * Given the pictures below, and assuming each item has equal weight:
1578 * root 1 - thread
1579 * / | \ A - group
1580 * A 1 B
1581 * /|\ / \
1582 * C 2 D 3 4
1583 * | |
1584 * 5 6
1586 * load:
1587 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1588 * which equals 1/9-th of the total load.
1590 * shares:
1591 * The weight of this group on the selected cpus.
1593 * rq_weight:
1594 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1595 * B would get 2.
1597 * task_weight:
1598 * Part of the rq_weight contributed by tasks; all groups except B would
1599 * get 1, B gets 2.
1602 static inline struct aggregate_struct *
1603 aggregate(struct task_group *tg, struct sched_domain *sd)
1605 return &tg->cfs_rq[sd->first_cpu]->aggregate;
1608 typedef void (*aggregate_func)(struct task_group *, struct sched_domain *);
1611 * Iterate the full tree, calling @down when first entering a node and @up when
1612 * leaving it for the final time.
1614 static
1615 void aggregate_walk_tree(aggregate_func down, aggregate_func up,
1616 struct sched_domain *sd)
1618 struct task_group *parent, *child;
1620 rcu_read_lock();
1621 parent = &root_task_group;
1622 down:
1623 (*down)(parent, sd);
1624 list_for_each_entry_rcu(child, &parent->children, siblings) {
1625 parent = child;
1626 goto down;
1629 continue;
1631 (*up)(parent, sd);
1633 child = parent;
1634 parent = parent->parent;
1635 if (parent)
1636 goto up;
1637 rcu_read_unlock();
1641 * Calculate the aggregate runqueue weight.
1643 static
1644 void aggregate_group_weight(struct task_group *tg, struct sched_domain *sd)
1646 unsigned long rq_weight = 0;
1647 unsigned long task_weight = 0;
1648 int i;
1650 for_each_cpu_mask(i, sd->span) {
1651 rq_weight += tg->cfs_rq[i]->load.weight;
1652 task_weight += tg->cfs_rq[i]->task_weight;
1655 aggregate(tg, sd)->rq_weight = rq_weight;
1656 aggregate(tg, sd)->task_weight = task_weight;
1660 * Redistribute tg->shares amongst all tg->cfs_rq[]s.
1662 static void __aggregate_redistribute_shares(struct task_group *tg)
1664 int i, max_cpu = smp_processor_id();
1665 unsigned long rq_weight = 0;
1666 unsigned long shares, max_shares = 0, shares_rem = tg->shares;
1668 for_each_possible_cpu(i)
1669 rq_weight += tg->cfs_rq[i]->load.weight;
1671 for_each_possible_cpu(i) {
1673 * divide shares proportional to the rq_weights.
1675 shares = tg->shares * tg->cfs_rq[i]->load.weight;
1676 shares /= rq_weight + 1;
1678 tg->cfs_rq[i]->shares = shares;
1680 if (shares > max_shares) {
1681 max_shares = shares;
1682 max_cpu = i;
1684 shares_rem -= shares;
1688 * Ensure it all adds up to tg->shares; we can loose a few
1689 * due to rounding down when computing the per-cpu shares.
1691 if (shares_rem)
1692 tg->cfs_rq[max_cpu]->shares += shares_rem;
1696 * Compute the weight of this group on the given cpus.
1698 static
1699 void aggregate_group_shares(struct task_group *tg, struct sched_domain *sd)
1701 unsigned long shares = 0;
1702 int i;
1704 again:
1705 for_each_cpu_mask(i, sd->span)
1706 shares += tg->cfs_rq[i]->shares;
1709 * When the span doesn't have any shares assigned, but does have
1710 * tasks to run do a machine wide rebalance (should be rare).
1712 if (unlikely(!shares && aggregate(tg, sd)->rq_weight)) {
1713 __aggregate_redistribute_shares(tg);
1714 goto again;
1717 aggregate(tg, sd)->shares = shares;
1721 * Compute the load fraction assigned to this group, relies on the aggregate
1722 * weight and this group's parent's load, i.e. top-down.
1724 static
1725 void aggregate_group_load(struct task_group *tg, struct sched_domain *sd)
1727 unsigned long load;
1729 if (!tg->parent) {
1730 int i;
1732 load = 0;
1733 for_each_cpu_mask(i, sd->span)
1734 load += cpu_rq(i)->load.weight;
1736 } else {
1737 load = aggregate(tg->parent, sd)->load;
1740 * shares is our weight in the parent's rq so
1741 * shares/parent->rq_weight gives our fraction of the load
1743 load *= aggregate(tg, sd)->shares;
1744 load /= aggregate(tg->parent, sd)->rq_weight + 1;
1747 aggregate(tg, sd)->load = load;
1750 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1753 * Calculate and set the cpu's group shares.
1755 static void
1756 __update_group_shares_cpu(struct task_group *tg, struct sched_domain *sd,
1757 int tcpu)
1759 int boost = 0;
1760 unsigned long shares;
1761 unsigned long rq_weight;
1763 if (!tg->se[tcpu])
1764 return;
1766 rq_weight = tg->cfs_rq[tcpu]->load.weight;
1769 * If there are currently no tasks on the cpu pretend there is one of
1770 * average load so that when a new task gets to run here it will not
1771 * get delayed by group starvation.
1773 if (!rq_weight) {
1774 boost = 1;
1775 rq_weight = NICE_0_LOAD;
1779 * \Sum shares * rq_weight
1780 * shares = -----------------------
1781 * \Sum rq_weight
1784 shares = aggregate(tg, sd)->shares * rq_weight;
1785 shares /= aggregate(tg, sd)->rq_weight + 1;
1788 * record the actual number of shares, not the boosted amount.
1790 tg->cfs_rq[tcpu]->shares = boost ? 0 : shares;
1792 if (shares < MIN_SHARES)
1793 shares = MIN_SHARES;
1795 __set_se_shares(tg->se[tcpu], shares);
1799 * Re-adjust the weights on the cpu the task came from and on the cpu the
1800 * task went to.
1802 static void
1803 __move_group_shares(struct task_group *tg, struct sched_domain *sd,
1804 int scpu, int dcpu)
1806 unsigned long shares;
1808 shares = tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1810 __update_group_shares_cpu(tg, sd, scpu);
1811 __update_group_shares_cpu(tg, sd, dcpu);
1814 * ensure we never loose shares due to rounding errors in the
1815 * above redistribution.
1817 shares -= tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1818 if (shares)
1819 tg->cfs_rq[dcpu]->shares += shares;
1823 * Because changing a group's shares changes the weight of the super-group
1824 * we need to walk up the tree and change all shares until we hit the root.
1826 static void
1827 move_group_shares(struct task_group *tg, struct sched_domain *sd,
1828 int scpu, int dcpu)
1830 while (tg) {
1831 __move_group_shares(tg, sd, scpu, dcpu);
1832 tg = tg->parent;
1836 static
1837 void aggregate_group_set_shares(struct task_group *tg, struct sched_domain *sd)
1839 unsigned long shares = aggregate(tg, sd)->shares;
1840 int i;
1842 for_each_cpu_mask(i, sd->span) {
1843 struct rq *rq = cpu_rq(i);
1844 unsigned long flags;
1846 spin_lock_irqsave(&rq->lock, flags);
1847 __update_group_shares_cpu(tg, sd, i);
1848 spin_unlock_irqrestore(&rq->lock, flags);
1851 aggregate_group_shares(tg, sd);
1854 * ensure we never loose shares due to rounding errors in the
1855 * above redistribution.
1857 shares -= aggregate(tg, sd)->shares;
1858 if (shares) {
1859 tg->cfs_rq[sd->first_cpu]->shares += shares;
1860 aggregate(tg, sd)->shares += shares;
1865 * Calculate the accumulative weight and recursive load of each task group
1866 * while walking down the tree.
1868 static
1869 void aggregate_get_down(struct task_group *tg, struct sched_domain *sd)
1871 aggregate_group_weight(tg, sd);
1872 aggregate_group_shares(tg, sd);
1873 aggregate_group_load(tg, sd);
1877 * Rebalance the cpu shares while walking back up the tree.
1879 static
1880 void aggregate_get_up(struct task_group *tg, struct sched_domain *sd)
1882 aggregate_group_set_shares(tg, sd);
1885 static DEFINE_PER_CPU(spinlock_t, aggregate_lock);
1887 static void __init init_aggregate(void)
1889 int i;
1891 for_each_possible_cpu(i)
1892 spin_lock_init(&per_cpu(aggregate_lock, i));
1895 static int get_aggregate(struct sched_domain *sd)
1897 if (!spin_trylock(&per_cpu(aggregate_lock, sd->first_cpu)))
1898 return 0;
1900 aggregate_walk_tree(aggregate_get_down, aggregate_get_up, sd);
1901 return 1;
1904 static void put_aggregate(struct sched_domain *sd)
1906 spin_unlock(&per_cpu(aggregate_lock, sd->first_cpu));
1909 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1911 cfs_rq->shares = shares;
1914 #else
1916 static inline void init_aggregate(void)
1920 static inline int get_aggregate(struct sched_domain *sd)
1922 return 0;
1925 static inline void put_aggregate(struct sched_domain *sd)
1928 #endif
1930 #else /* CONFIG_SMP */
1932 #ifdef CONFIG_FAIR_GROUP_SCHED
1933 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1936 #endif
1938 #endif /* CONFIG_SMP */
1940 #include "sched_stats.h"
1941 #include "sched_idletask.c"
1942 #include "sched_fair.c"
1943 #include "sched_rt.c"
1944 #ifdef CONFIG_SCHED_DEBUG
1945 # include "sched_debug.c"
1946 #endif
1948 #define sched_class_highest (&rt_sched_class)
1950 static void inc_nr_running(struct rq *rq)
1952 rq->nr_running++;
1955 static void dec_nr_running(struct rq *rq)
1957 rq->nr_running--;
1960 static void set_load_weight(struct task_struct *p)
1962 if (task_has_rt_policy(p)) {
1963 p->se.load.weight = prio_to_weight[0] * 2;
1964 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1965 return;
1969 * SCHED_IDLE tasks get minimal weight:
1971 if (p->policy == SCHED_IDLE) {
1972 p->se.load.weight = WEIGHT_IDLEPRIO;
1973 p->se.load.inv_weight = WMULT_IDLEPRIO;
1974 return;
1977 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1978 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1981 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1983 sched_info_queued(p);
1984 p->sched_class->enqueue_task(rq, p, wakeup);
1985 p->se.on_rq = 1;
1988 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1990 p->sched_class->dequeue_task(rq, p, sleep);
1991 p->se.on_rq = 0;
1995 * __normal_prio - return the priority that is based on the static prio
1997 static inline int __normal_prio(struct task_struct *p)
1999 return p->static_prio;
2003 * Calculate the expected normal priority: i.e. priority
2004 * without taking RT-inheritance into account. Might be
2005 * boosted by interactivity modifiers. Changes upon fork,
2006 * setprio syscalls, and whenever the interactivity
2007 * estimator recalculates.
2009 static inline int normal_prio(struct task_struct *p)
2011 int prio;
2013 if (task_has_rt_policy(p))
2014 prio = MAX_RT_PRIO-1 - p->rt_priority;
2015 else
2016 prio = __normal_prio(p);
2017 return prio;
2021 * Calculate the current priority, i.e. the priority
2022 * taken into account by the scheduler. This value might
2023 * be boosted by RT tasks, or might be boosted by
2024 * interactivity modifiers. Will be RT if the task got
2025 * RT-boosted. If not then it returns p->normal_prio.
2027 static int effective_prio(struct task_struct *p)
2029 p->normal_prio = normal_prio(p);
2031 * If we are RT tasks or we were boosted to RT priority,
2032 * keep the priority unchanged. Otherwise, update priority
2033 * to the normal priority:
2035 if (!rt_prio(p->prio))
2036 return p->normal_prio;
2037 return p->prio;
2041 * activate_task - move a task to the runqueue.
2043 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
2045 if (task_contributes_to_load(p))
2046 rq->nr_uninterruptible--;
2048 enqueue_task(rq, p, wakeup);
2049 inc_nr_running(rq);
2053 * deactivate_task - remove a task from the runqueue.
2055 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
2057 if (task_contributes_to_load(p))
2058 rq->nr_uninterruptible++;
2060 dequeue_task(rq, p, sleep);
2061 dec_nr_running(rq);
2065 * task_curr - is this task currently executing on a CPU?
2066 * @p: the task in question.
2068 inline int task_curr(const struct task_struct *p)
2070 return cpu_curr(task_cpu(p)) == p;
2073 /* Used instead of source_load when we know the type == 0 */
2074 unsigned long weighted_cpuload(const int cpu)
2076 return cpu_rq(cpu)->load.weight;
2079 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
2081 set_task_rq(p, cpu);
2082 #ifdef CONFIG_SMP
2084 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
2085 * successfuly executed on another CPU. We must ensure that updates of
2086 * per-task data have been completed by this moment.
2088 smp_wmb();
2089 task_thread_info(p)->cpu = cpu;
2090 #endif
2093 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2094 const struct sched_class *prev_class,
2095 int oldprio, int running)
2097 if (prev_class != p->sched_class) {
2098 if (prev_class->switched_from)
2099 prev_class->switched_from(rq, p, running);
2100 p->sched_class->switched_to(rq, p, running);
2101 } else
2102 p->sched_class->prio_changed(rq, p, oldprio, running);
2105 #ifdef CONFIG_SMP
2108 * Is this task likely cache-hot:
2110 static int
2111 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2113 s64 delta;
2116 * Buddy candidates are cache hot:
2118 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
2119 return 1;
2121 if (p->sched_class != &fair_sched_class)
2122 return 0;
2124 if (sysctl_sched_migration_cost == -1)
2125 return 1;
2126 if (sysctl_sched_migration_cost == 0)
2127 return 0;
2129 delta = now - p->se.exec_start;
2131 return delta < (s64)sysctl_sched_migration_cost;
2135 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2137 int old_cpu = task_cpu(p);
2138 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2139 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2140 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2141 u64 clock_offset;
2143 clock_offset = old_rq->clock - new_rq->clock;
2145 #ifdef CONFIG_SCHEDSTATS
2146 if (p->se.wait_start)
2147 p->se.wait_start -= clock_offset;
2148 if (p->se.sleep_start)
2149 p->se.sleep_start -= clock_offset;
2150 if (p->se.block_start)
2151 p->se.block_start -= clock_offset;
2152 if (old_cpu != new_cpu) {
2153 schedstat_inc(p, se.nr_migrations);
2154 if (task_hot(p, old_rq->clock, NULL))
2155 schedstat_inc(p, se.nr_forced2_migrations);
2157 #endif
2158 p->se.vruntime -= old_cfsrq->min_vruntime -
2159 new_cfsrq->min_vruntime;
2161 __set_task_cpu(p, new_cpu);
2164 struct migration_req {
2165 struct list_head list;
2167 struct task_struct *task;
2168 int dest_cpu;
2170 struct completion done;
2174 * The task's runqueue lock must be held.
2175 * Returns true if you have to wait for migration thread.
2177 static int
2178 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2180 struct rq *rq = task_rq(p);
2183 * If the task is not on a runqueue (and not running), then
2184 * it is sufficient to simply update the task's cpu field.
2186 if (!p->se.on_rq && !task_running(rq, p)) {
2187 set_task_cpu(p, dest_cpu);
2188 return 0;
2191 init_completion(&req->done);
2192 req->task = p;
2193 req->dest_cpu = dest_cpu;
2194 list_add(&req->list, &rq->migration_queue);
2196 return 1;
2200 * wait_task_inactive - wait for a thread to unschedule.
2202 * The caller must ensure that the task *will* unschedule sometime soon,
2203 * else this function might spin for a *long* time. This function can't
2204 * be called with interrupts off, or it may introduce deadlock with
2205 * smp_call_function() if an IPI is sent by the same process we are
2206 * waiting to become inactive.
2208 void wait_task_inactive(struct task_struct *p)
2210 unsigned long flags;
2211 int running, on_rq;
2212 struct rq *rq;
2214 for (;;) {
2216 * We do the initial early heuristics without holding
2217 * any task-queue locks at all. We'll only try to get
2218 * the runqueue lock when things look like they will
2219 * work out!
2221 rq = task_rq(p);
2224 * If the task is actively running on another CPU
2225 * still, just relax and busy-wait without holding
2226 * any locks.
2228 * NOTE! Since we don't hold any locks, it's not
2229 * even sure that "rq" stays as the right runqueue!
2230 * But we don't care, since "task_running()" will
2231 * return false if the runqueue has changed and p
2232 * is actually now running somewhere else!
2234 while (task_running(rq, p))
2235 cpu_relax();
2238 * Ok, time to look more closely! We need the rq
2239 * lock now, to be *sure*. If we're wrong, we'll
2240 * just go back and repeat.
2242 rq = task_rq_lock(p, &flags);
2243 running = task_running(rq, p);
2244 on_rq = p->se.on_rq;
2245 task_rq_unlock(rq, &flags);
2248 * Was it really running after all now that we
2249 * checked with the proper locks actually held?
2251 * Oops. Go back and try again..
2253 if (unlikely(running)) {
2254 cpu_relax();
2255 continue;
2259 * It's not enough that it's not actively running,
2260 * it must be off the runqueue _entirely_, and not
2261 * preempted!
2263 * So if it wa still runnable (but just not actively
2264 * running right now), it's preempted, and we should
2265 * yield - it could be a while.
2267 if (unlikely(on_rq)) {
2268 schedule_timeout_uninterruptible(1);
2269 continue;
2273 * Ahh, all good. It wasn't running, and it wasn't
2274 * runnable, which means that it will never become
2275 * running in the future either. We're all done!
2277 break;
2281 /***
2282 * kick_process - kick a running thread to enter/exit the kernel
2283 * @p: the to-be-kicked thread
2285 * Cause a process which is running on another CPU to enter
2286 * kernel-mode, without any delay. (to get signals handled.)
2288 * NOTE: this function doesnt have to take the runqueue lock,
2289 * because all it wants to ensure is that the remote task enters
2290 * the kernel. If the IPI races and the task has been migrated
2291 * to another CPU then no harm is done and the purpose has been
2292 * achieved as well.
2294 void kick_process(struct task_struct *p)
2296 int cpu;
2298 preempt_disable();
2299 cpu = task_cpu(p);
2300 if ((cpu != smp_processor_id()) && task_curr(p))
2301 smp_send_reschedule(cpu);
2302 preempt_enable();
2306 * Return a low guess at the load of a migration-source cpu weighted
2307 * according to the scheduling class and "nice" value.
2309 * We want to under-estimate the load of migration sources, to
2310 * balance conservatively.
2312 static unsigned long source_load(int cpu, int type)
2314 struct rq *rq = cpu_rq(cpu);
2315 unsigned long total = weighted_cpuload(cpu);
2317 if (type == 0)
2318 return total;
2320 return min(rq->cpu_load[type-1], total);
2324 * Return a high guess at the load of a migration-target cpu weighted
2325 * according to the scheduling class and "nice" value.
2327 static unsigned long target_load(int cpu, int type)
2329 struct rq *rq = cpu_rq(cpu);
2330 unsigned long total = weighted_cpuload(cpu);
2332 if (type == 0)
2333 return total;
2335 return max(rq->cpu_load[type-1], total);
2339 * Return the average load per task on the cpu's run queue
2341 static unsigned long cpu_avg_load_per_task(int cpu)
2343 struct rq *rq = cpu_rq(cpu);
2344 unsigned long total = weighted_cpuload(cpu);
2345 unsigned long n = rq->nr_running;
2347 return n ? total / n : SCHED_LOAD_SCALE;
2351 * find_idlest_group finds and returns the least busy CPU group within the
2352 * domain.
2354 static struct sched_group *
2355 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2357 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2358 unsigned long min_load = ULONG_MAX, this_load = 0;
2359 int load_idx = sd->forkexec_idx;
2360 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2362 do {
2363 unsigned long load, avg_load;
2364 int local_group;
2365 int i;
2367 /* Skip over this group if it has no CPUs allowed */
2368 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2369 continue;
2371 local_group = cpu_isset(this_cpu, group->cpumask);
2373 /* Tally up the load of all CPUs in the group */
2374 avg_load = 0;
2376 for_each_cpu_mask(i, group->cpumask) {
2377 /* Bias balancing toward cpus of our domain */
2378 if (local_group)
2379 load = source_load(i, load_idx);
2380 else
2381 load = target_load(i, load_idx);
2383 avg_load += load;
2386 /* Adjust by relative CPU power of the group */
2387 avg_load = sg_div_cpu_power(group,
2388 avg_load * SCHED_LOAD_SCALE);
2390 if (local_group) {
2391 this_load = avg_load;
2392 this = group;
2393 } else if (avg_load < min_load) {
2394 min_load = avg_load;
2395 idlest = group;
2397 } while (group = group->next, group != sd->groups);
2399 if (!idlest || 100*this_load < imbalance*min_load)
2400 return NULL;
2401 return idlest;
2405 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2407 static int
2408 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2409 cpumask_t *tmp)
2411 unsigned long load, min_load = ULONG_MAX;
2412 int idlest = -1;
2413 int i;
2415 /* Traverse only the allowed CPUs */
2416 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2418 for_each_cpu_mask(i, *tmp) {
2419 load = weighted_cpuload(i);
2421 if (load < min_load || (load == min_load && i == this_cpu)) {
2422 min_load = load;
2423 idlest = i;
2427 return idlest;
2431 * sched_balance_self: balance the current task (running on cpu) in domains
2432 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2433 * SD_BALANCE_EXEC.
2435 * Balance, ie. select the least loaded group.
2437 * Returns the target CPU number, or the same CPU if no balancing is needed.
2439 * preempt must be disabled.
2441 static int sched_balance_self(int cpu, int flag)
2443 struct task_struct *t = current;
2444 struct sched_domain *tmp, *sd = NULL;
2446 for_each_domain(cpu, tmp) {
2448 * If power savings logic is enabled for a domain, stop there.
2450 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2451 break;
2452 if (tmp->flags & flag)
2453 sd = tmp;
2456 while (sd) {
2457 cpumask_t span, tmpmask;
2458 struct sched_group *group;
2459 int new_cpu, weight;
2461 if (!(sd->flags & flag)) {
2462 sd = sd->child;
2463 continue;
2466 span = sd->span;
2467 group = find_idlest_group(sd, t, cpu);
2468 if (!group) {
2469 sd = sd->child;
2470 continue;
2473 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2474 if (new_cpu == -1 || new_cpu == cpu) {
2475 /* Now try balancing at a lower domain level of cpu */
2476 sd = sd->child;
2477 continue;
2480 /* Now try balancing at a lower domain level of new_cpu */
2481 cpu = new_cpu;
2482 sd = NULL;
2483 weight = cpus_weight(span);
2484 for_each_domain(cpu, tmp) {
2485 if (weight <= cpus_weight(tmp->span))
2486 break;
2487 if (tmp->flags & flag)
2488 sd = tmp;
2490 /* while loop will break here if sd == NULL */
2493 return cpu;
2496 #endif /* CONFIG_SMP */
2498 /***
2499 * try_to_wake_up - wake up a thread
2500 * @p: the to-be-woken-up thread
2501 * @state: the mask of task states that can be woken
2502 * @sync: do a synchronous wakeup?
2504 * Put it on the run-queue if it's not already there. The "current"
2505 * thread is always on the run-queue (except when the actual
2506 * re-schedule is in progress), and as such you're allowed to do
2507 * the simpler "current->state = TASK_RUNNING" to mark yourself
2508 * runnable without the overhead of this.
2510 * returns failure only if the task is already active.
2512 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2514 int cpu, orig_cpu, this_cpu, success = 0;
2515 unsigned long flags;
2516 long old_state;
2517 struct rq *rq;
2519 if (!sched_feat(SYNC_WAKEUPS))
2520 sync = 0;
2522 smp_wmb();
2523 rq = task_rq_lock(p, &flags);
2524 old_state = p->state;
2525 if (!(old_state & state))
2526 goto out;
2528 if (p->se.on_rq)
2529 goto out_running;
2531 cpu = task_cpu(p);
2532 orig_cpu = cpu;
2533 this_cpu = smp_processor_id();
2535 #ifdef CONFIG_SMP
2536 if (unlikely(task_running(rq, p)))
2537 goto out_activate;
2539 cpu = p->sched_class->select_task_rq(p, sync);
2540 if (cpu != orig_cpu) {
2541 set_task_cpu(p, cpu);
2542 task_rq_unlock(rq, &flags);
2543 /* might preempt at this point */
2544 rq = task_rq_lock(p, &flags);
2545 old_state = p->state;
2546 if (!(old_state & state))
2547 goto out;
2548 if (p->se.on_rq)
2549 goto out_running;
2551 this_cpu = smp_processor_id();
2552 cpu = task_cpu(p);
2555 #ifdef CONFIG_SCHEDSTATS
2556 schedstat_inc(rq, ttwu_count);
2557 if (cpu == this_cpu)
2558 schedstat_inc(rq, ttwu_local);
2559 else {
2560 struct sched_domain *sd;
2561 for_each_domain(this_cpu, sd) {
2562 if (cpu_isset(cpu, sd->span)) {
2563 schedstat_inc(sd, ttwu_wake_remote);
2564 break;
2568 #endif
2570 out_activate:
2571 #endif /* CONFIG_SMP */
2572 schedstat_inc(p, se.nr_wakeups);
2573 if (sync)
2574 schedstat_inc(p, se.nr_wakeups_sync);
2575 if (orig_cpu != cpu)
2576 schedstat_inc(p, se.nr_wakeups_migrate);
2577 if (cpu == this_cpu)
2578 schedstat_inc(p, se.nr_wakeups_local);
2579 else
2580 schedstat_inc(p, se.nr_wakeups_remote);
2581 update_rq_clock(rq);
2582 activate_task(rq, p, 1);
2583 success = 1;
2585 out_running:
2586 check_preempt_curr(rq, p);
2588 p->state = TASK_RUNNING;
2589 #ifdef CONFIG_SMP
2590 if (p->sched_class->task_wake_up)
2591 p->sched_class->task_wake_up(rq, p);
2592 #endif
2593 out:
2594 task_rq_unlock(rq, &flags);
2596 return success;
2599 int wake_up_process(struct task_struct *p)
2601 return try_to_wake_up(p, TASK_ALL, 0);
2603 EXPORT_SYMBOL(wake_up_process);
2605 int wake_up_state(struct task_struct *p, unsigned int state)
2607 return try_to_wake_up(p, state, 0);
2611 * Perform scheduler related setup for a newly forked process p.
2612 * p is forked by current.
2614 * __sched_fork() is basic setup used by init_idle() too:
2616 static void __sched_fork(struct task_struct *p)
2618 p->se.exec_start = 0;
2619 p->se.sum_exec_runtime = 0;
2620 p->se.prev_sum_exec_runtime = 0;
2621 p->se.last_wakeup = 0;
2622 p->se.avg_overlap = 0;
2624 #ifdef CONFIG_SCHEDSTATS
2625 p->se.wait_start = 0;
2626 p->se.sum_sleep_runtime = 0;
2627 p->se.sleep_start = 0;
2628 p->se.block_start = 0;
2629 p->se.sleep_max = 0;
2630 p->se.block_max = 0;
2631 p->se.exec_max = 0;
2632 p->se.slice_max = 0;
2633 p->se.wait_max = 0;
2634 #endif
2636 INIT_LIST_HEAD(&p->rt.run_list);
2637 p->se.on_rq = 0;
2638 INIT_LIST_HEAD(&p->se.group_node);
2640 #ifdef CONFIG_PREEMPT_NOTIFIERS
2641 INIT_HLIST_HEAD(&p->preempt_notifiers);
2642 #endif
2645 * We mark the process as running here, but have not actually
2646 * inserted it onto the runqueue yet. This guarantees that
2647 * nobody will actually run it, and a signal or other external
2648 * event cannot wake it up and insert it on the runqueue either.
2650 p->state = TASK_RUNNING;
2654 * fork()/clone()-time setup:
2656 void sched_fork(struct task_struct *p, int clone_flags)
2658 int cpu = get_cpu();
2660 __sched_fork(p);
2662 #ifdef CONFIG_SMP
2663 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2664 #endif
2665 set_task_cpu(p, cpu);
2668 * Make sure we do not leak PI boosting priority to the child:
2670 p->prio = current->normal_prio;
2671 if (!rt_prio(p->prio))
2672 p->sched_class = &fair_sched_class;
2674 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2675 if (likely(sched_info_on()))
2676 memset(&p->sched_info, 0, sizeof(p->sched_info));
2677 #endif
2678 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2679 p->oncpu = 0;
2680 #endif
2681 #ifdef CONFIG_PREEMPT
2682 /* Want to start with kernel preemption disabled. */
2683 task_thread_info(p)->preempt_count = 1;
2684 #endif
2685 put_cpu();
2689 * wake_up_new_task - wake up a newly created task for the first time.
2691 * This function will do some initial scheduler statistics housekeeping
2692 * that must be done for every newly created context, then puts the task
2693 * on the runqueue and wakes it.
2695 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2697 unsigned long flags;
2698 struct rq *rq;
2700 rq = task_rq_lock(p, &flags);
2701 BUG_ON(p->state != TASK_RUNNING);
2702 update_rq_clock(rq);
2704 p->prio = effective_prio(p);
2706 if (!p->sched_class->task_new || !current->se.on_rq) {
2707 activate_task(rq, p, 0);
2708 } else {
2710 * Let the scheduling class do new task startup
2711 * management (if any):
2713 p->sched_class->task_new(rq, p);
2714 inc_nr_running(rq);
2716 check_preempt_curr(rq, p);
2717 #ifdef CONFIG_SMP
2718 if (p->sched_class->task_wake_up)
2719 p->sched_class->task_wake_up(rq, p);
2720 #endif
2721 task_rq_unlock(rq, &flags);
2724 #ifdef CONFIG_PREEMPT_NOTIFIERS
2727 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2728 * @notifier: notifier struct to register
2730 void preempt_notifier_register(struct preempt_notifier *notifier)
2732 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2734 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2737 * preempt_notifier_unregister - no longer interested in preemption notifications
2738 * @notifier: notifier struct to unregister
2740 * This is safe to call from within a preemption notifier.
2742 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2744 hlist_del(&notifier->link);
2746 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2748 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2750 struct preempt_notifier *notifier;
2751 struct hlist_node *node;
2753 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2754 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2757 static void
2758 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2759 struct task_struct *next)
2761 struct preempt_notifier *notifier;
2762 struct hlist_node *node;
2764 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2765 notifier->ops->sched_out(notifier, next);
2768 #else
2770 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2774 static void
2775 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2776 struct task_struct *next)
2780 #endif
2783 * prepare_task_switch - prepare to switch tasks
2784 * @rq: the runqueue preparing to switch
2785 * @prev: the current task that is being switched out
2786 * @next: the task we are going to switch to.
2788 * This is called with the rq lock held and interrupts off. It must
2789 * be paired with a subsequent finish_task_switch after the context
2790 * switch.
2792 * prepare_task_switch sets up locking and calls architecture specific
2793 * hooks.
2795 static inline void
2796 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2797 struct task_struct *next)
2799 fire_sched_out_preempt_notifiers(prev, next);
2800 prepare_lock_switch(rq, next);
2801 prepare_arch_switch(next);
2805 * finish_task_switch - clean up after a task-switch
2806 * @rq: runqueue associated with task-switch
2807 * @prev: the thread we just switched away from.
2809 * finish_task_switch must be called after the context switch, paired
2810 * with a prepare_task_switch call before the context switch.
2811 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2812 * and do any other architecture-specific cleanup actions.
2814 * Note that we may have delayed dropping an mm in context_switch(). If
2815 * so, we finish that here outside of the runqueue lock. (Doing it
2816 * with the lock held can cause deadlocks; see schedule() for
2817 * details.)
2819 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2820 __releases(rq->lock)
2822 struct mm_struct *mm = rq->prev_mm;
2823 long prev_state;
2825 rq->prev_mm = NULL;
2828 * A task struct has one reference for the use as "current".
2829 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2830 * schedule one last time. The schedule call will never return, and
2831 * the scheduled task must drop that reference.
2832 * The test for TASK_DEAD must occur while the runqueue locks are
2833 * still held, otherwise prev could be scheduled on another cpu, die
2834 * there before we look at prev->state, and then the reference would
2835 * be dropped twice.
2836 * Manfred Spraul <manfred@colorfullife.com>
2838 prev_state = prev->state;
2839 finish_arch_switch(prev);
2840 finish_lock_switch(rq, prev);
2841 #ifdef CONFIG_SMP
2842 if (current->sched_class->post_schedule)
2843 current->sched_class->post_schedule(rq);
2844 #endif
2846 fire_sched_in_preempt_notifiers(current);
2847 if (mm)
2848 mmdrop(mm);
2849 if (unlikely(prev_state == TASK_DEAD)) {
2851 * Remove function-return probe instances associated with this
2852 * task and put them back on the free list.
2854 kprobe_flush_task(prev);
2855 put_task_struct(prev);
2860 * schedule_tail - first thing a freshly forked thread must call.
2861 * @prev: the thread we just switched away from.
2863 asmlinkage void schedule_tail(struct task_struct *prev)
2864 __releases(rq->lock)
2866 struct rq *rq = this_rq();
2868 finish_task_switch(rq, prev);
2869 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2870 /* In this case, finish_task_switch does not reenable preemption */
2871 preempt_enable();
2872 #endif
2873 if (current->set_child_tid)
2874 put_user(task_pid_vnr(current), current->set_child_tid);
2878 * context_switch - switch to the new MM and the new
2879 * thread's register state.
2881 static inline void
2882 context_switch(struct rq *rq, struct task_struct *prev,
2883 struct task_struct *next)
2885 struct mm_struct *mm, *oldmm;
2887 prepare_task_switch(rq, prev, next);
2888 mm = next->mm;
2889 oldmm = prev->active_mm;
2891 * For paravirt, this is coupled with an exit in switch_to to
2892 * combine the page table reload and the switch backend into
2893 * one hypercall.
2895 arch_enter_lazy_cpu_mode();
2897 if (unlikely(!mm)) {
2898 next->active_mm = oldmm;
2899 atomic_inc(&oldmm->mm_count);
2900 enter_lazy_tlb(oldmm, next);
2901 } else
2902 switch_mm(oldmm, mm, next);
2904 if (unlikely(!prev->mm)) {
2905 prev->active_mm = NULL;
2906 rq->prev_mm = oldmm;
2909 * Since the runqueue lock will be released by the next
2910 * task (which is an invalid locking op but in the case
2911 * of the scheduler it's an obvious special-case), so we
2912 * do an early lockdep release here:
2914 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2915 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2916 #endif
2918 /* Here we just switch the register state and the stack. */
2919 switch_to(prev, next, prev);
2921 barrier();
2923 * this_rq must be evaluated again because prev may have moved
2924 * CPUs since it called schedule(), thus the 'rq' on its stack
2925 * frame will be invalid.
2927 finish_task_switch(this_rq(), prev);
2931 * nr_running, nr_uninterruptible and nr_context_switches:
2933 * externally visible scheduler statistics: current number of runnable
2934 * threads, current number of uninterruptible-sleeping threads, total
2935 * number of context switches performed since bootup.
2937 unsigned long nr_running(void)
2939 unsigned long i, sum = 0;
2941 for_each_online_cpu(i)
2942 sum += cpu_rq(i)->nr_running;
2944 return sum;
2947 unsigned long nr_uninterruptible(void)
2949 unsigned long i, sum = 0;
2951 for_each_possible_cpu(i)
2952 sum += cpu_rq(i)->nr_uninterruptible;
2955 * Since we read the counters lockless, it might be slightly
2956 * inaccurate. Do not allow it to go below zero though:
2958 if (unlikely((long)sum < 0))
2959 sum = 0;
2961 return sum;
2964 unsigned long long nr_context_switches(void)
2966 int i;
2967 unsigned long long sum = 0;
2969 for_each_possible_cpu(i)
2970 sum += cpu_rq(i)->nr_switches;
2972 return sum;
2975 unsigned long nr_iowait(void)
2977 unsigned long i, sum = 0;
2979 for_each_possible_cpu(i)
2980 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2982 return sum;
2985 unsigned long nr_active(void)
2987 unsigned long i, running = 0, uninterruptible = 0;
2989 for_each_online_cpu(i) {
2990 running += cpu_rq(i)->nr_running;
2991 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2994 if (unlikely((long)uninterruptible < 0))
2995 uninterruptible = 0;
2997 return running + uninterruptible;
3001 * Update rq->cpu_load[] statistics. This function is usually called every
3002 * scheduler tick (TICK_NSEC).
3004 static void update_cpu_load(struct rq *this_rq)
3006 unsigned long this_load = this_rq->load.weight;
3007 int i, scale;
3009 this_rq->nr_load_updates++;
3011 /* Update our load: */
3012 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3013 unsigned long old_load, new_load;
3015 /* scale is effectively 1 << i now, and >> i divides by scale */
3017 old_load = this_rq->cpu_load[i];
3018 new_load = this_load;
3020 * Round up the averaging division if load is increasing. This
3021 * prevents us from getting stuck on 9 if the load is 10, for
3022 * example.
3024 if (new_load > old_load)
3025 new_load += scale-1;
3026 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3030 #ifdef CONFIG_SMP
3033 * double_rq_lock - safely lock two runqueues
3035 * Note this does not disable interrupts like task_rq_lock,
3036 * you need to do so manually before calling.
3038 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3039 __acquires(rq1->lock)
3040 __acquires(rq2->lock)
3042 BUG_ON(!irqs_disabled());
3043 if (rq1 == rq2) {
3044 spin_lock(&rq1->lock);
3045 __acquire(rq2->lock); /* Fake it out ;) */
3046 } else {
3047 if (rq1 < rq2) {
3048 spin_lock(&rq1->lock);
3049 spin_lock(&rq2->lock);
3050 } else {
3051 spin_lock(&rq2->lock);
3052 spin_lock(&rq1->lock);
3055 update_rq_clock(rq1);
3056 update_rq_clock(rq2);
3060 * double_rq_unlock - safely unlock two runqueues
3062 * Note this does not restore interrupts like task_rq_unlock,
3063 * you need to do so manually after calling.
3065 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3066 __releases(rq1->lock)
3067 __releases(rq2->lock)
3069 spin_unlock(&rq1->lock);
3070 if (rq1 != rq2)
3071 spin_unlock(&rq2->lock);
3072 else
3073 __release(rq2->lock);
3077 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
3079 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
3080 __releases(this_rq->lock)
3081 __acquires(busiest->lock)
3082 __acquires(this_rq->lock)
3084 int ret = 0;
3086 if (unlikely(!irqs_disabled())) {
3087 /* printk() doesn't work good under rq->lock */
3088 spin_unlock(&this_rq->lock);
3089 BUG_ON(1);
3091 if (unlikely(!spin_trylock(&busiest->lock))) {
3092 if (busiest < this_rq) {
3093 spin_unlock(&this_rq->lock);
3094 spin_lock(&busiest->lock);
3095 spin_lock(&this_rq->lock);
3096 ret = 1;
3097 } else
3098 spin_lock(&busiest->lock);
3100 return ret;
3104 * If dest_cpu is allowed for this process, migrate the task to it.
3105 * This is accomplished by forcing the cpu_allowed mask to only
3106 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3107 * the cpu_allowed mask is restored.
3109 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3111 struct migration_req req;
3112 unsigned long flags;
3113 struct rq *rq;
3115 rq = task_rq_lock(p, &flags);
3116 if (!cpu_isset(dest_cpu, p->cpus_allowed)
3117 || unlikely(cpu_is_offline(dest_cpu)))
3118 goto out;
3120 /* force the process onto the specified CPU */
3121 if (migrate_task(p, dest_cpu, &req)) {
3122 /* Need to wait for migration thread (might exit: take ref). */
3123 struct task_struct *mt = rq->migration_thread;
3125 get_task_struct(mt);
3126 task_rq_unlock(rq, &flags);
3127 wake_up_process(mt);
3128 put_task_struct(mt);
3129 wait_for_completion(&req.done);
3131 return;
3133 out:
3134 task_rq_unlock(rq, &flags);
3138 * sched_exec - execve() is a valuable balancing opportunity, because at
3139 * this point the task has the smallest effective memory and cache footprint.
3141 void sched_exec(void)
3143 int new_cpu, this_cpu = get_cpu();
3144 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3145 put_cpu();
3146 if (new_cpu != this_cpu)
3147 sched_migrate_task(current, new_cpu);
3151 * pull_task - move a task from a remote runqueue to the local runqueue.
3152 * Both runqueues must be locked.
3154 static void pull_task(struct rq *src_rq, struct task_struct *p,
3155 struct rq *this_rq, int this_cpu)
3157 deactivate_task(src_rq, p, 0);
3158 set_task_cpu(p, this_cpu);
3159 activate_task(this_rq, p, 0);
3161 * Note that idle threads have a prio of MAX_PRIO, for this test
3162 * to be always true for them.
3164 check_preempt_curr(this_rq, p);
3168 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3170 static
3171 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3172 struct sched_domain *sd, enum cpu_idle_type idle,
3173 int *all_pinned)
3176 * We do not migrate tasks that are:
3177 * 1) running (obviously), or
3178 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3179 * 3) are cache-hot on their current CPU.
3181 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
3182 schedstat_inc(p, se.nr_failed_migrations_affine);
3183 return 0;
3185 *all_pinned = 0;
3187 if (task_running(rq, p)) {
3188 schedstat_inc(p, se.nr_failed_migrations_running);
3189 return 0;
3193 * Aggressive migration if:
3194 * 1) task is cache cold, or
3195 * 2) too many balance attempts have failed.
3198 if (!task_hot(p, rq->clock, sd) ||
3199 sd->nr_balance_failed > sd->cache_nice_tries) {
3200 #ifdef CONFIG_SCHEDSTATS
3201 if (task_hot(p, rq->clock, sd)) {
3202 schedstat_inc(sd, lb_hot_gained[idle]);
3203 schedstat_inc(p, se.nr_forced_migrations);
3205 #endif
3206 return 1;
3209 if (task_hot(p, rq->clock, sd)) {
3210 schedstat_inc(p, se.nr_failed_migrations_hot);
3211 return 0;
3213 return 1;
3216 static unsigned long
3217 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3218 unsigned long max_load_move, struct sched_domain *sd,
3219 enum cpu_idle_type idle, int *all_pinned,
3220 int *this_best_prio, struct rq_iterator *iterator)
3222 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
3223 struct task_struct *p;
3224 long rem_load_move = max_load_move;
3226 if (max_load_move == 0)
3227 goto out;
3229 pinned = 1;
3232 * Start the load-balancing iterator:
3234 p = iterator->start(iterator->arg);
3235 next:
3236 if (!p || loops++ > sysctl_sched_nr_migrate)
3237 goto out;
3239 * To help distribute high priority tasks across CPUs we don't
3240 * skip a task if it will be the highest priority task (i.e. smallest
3241 * prio value) on its new queue regardless of its load weight
3243 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
3244 SCHED_LOAD_SCALE_FUZZ;
3245 if ((skip_for_load && p->prio >= *this_best_prio) ||
3246 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3247 p = iterator->next(iterator->arg);
3248 goto next;
3251 pull_task(busiest, p, this_rq, this_cpu);
3252 pulled++;
3253 rem_load_move -= p->se.load.weight;
3256 * We only want to steal up to the prescribed amount of weighted load.
3258 if (rem_load_move > 0) {
3259 if (p->prio < *this_best_prio)
3260 *this_best_prio = p->prio;
3261 p = iterator->next(iterator->arg);
3262 goto next;
3264 out:
3266 * Right now, this is one of only two places pull_task() is called,
3267 * so we can safely collect pull_task() stats here rather than
3268 * inside pull_task().
3270 schedstat_add(sd, lb_gained[idle], pulled);
3272 if (all_pinned)
3273 *all_pinned = pinned;
3275 return max_load_move - rem_load_move;
3279 * move_tasks tries to move up to max_load_move weighted load from busiest to
3280 * this_rq, as part of a balancing operation within domain "sd".
3281 * Returns 1 if successful and 0 otherwise.
3283 * Called with both runqueues locked.
3285 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3286 unsigned long max_load_move,
3287 struct sched_domain *sd, enum cpu_idle_type idle,
3288 int *all_pinned)
3290 const struct sched_class *class = sched_class_highest;
3291 unsigned long total_load_moved = 0;
3292 int this_best_prio = this_rq->curr->prio;
3294 do {
3295 total_load_moved +=
3296 class->load_balance(this_rq, this_cpu, busiest,
3297 max_load_move - total_load_moved,
3298 sd, idle, all_pinned, &this_best_prio);
3299 class = class->next;
3300 } while (class && max_load_move > total_load_moved);
3302 return total_load_moved > 0;
3305 static int
3306 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3307 struct sched_domain *sd, enum cpu_idle_type idle,
3308 struct rq_iterator *iterator)
3310 struct task_struct *p = iterator->start(iterator->arg);
3311 int pinned = 0;
3313 while (p) {
3314 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3315 pull_task(busiest, p, this_rq, this_cpu);
3317 * Right now, this is only the second place pull_task()
3318 * is called, so we can safely collect pull_task()
3319 * stats here rather than inside pull_task().
3321 schedstat_inc(sd, lb_gained[idle]);
3323 return 1;
3325 p = iterator->next(iterator->arg);
3328 return 0;
3332 * move_one_task tries to move exactly one task from busiest to this_rq, as
3333 * part of active balancing operations within "domain".
3334 * Returns 1 if successful and 0 otherwise.
3336 * Called with both runqueues locked.
3338 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3339 struct sched_domain *sd, enum cpu_idle_type idle)
3341 const struct sched_class *class;
3343 for (class = sched_class_highest; class; class = class->next)
3344 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3345 return 1;
3347 return 0;
3351 * find_busiest_group finds and returns the busiest CPU group within the
3352 * domain. It calculates and returns the amount of weighted load which
3353 * should be moved to restore balance via the imbalance parameter.
3355 static struct sched_group *
3356 find_busiest_group(struct sched_domain *sd, int this_cpu,
3357 unsigned long *imbalance, enum cpu_idle_type idle,
3358 int *sd_idle, const cpumask_t *cpus, int *balance)
3360 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3361 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3362 unsigned long max_pull;
3363 unsigned long busiest_load_per_task, busiest_nr_running;
3364 unsigned long this_load_per_task, this_nr_running;
3365 int load_idx, group_imb = 0;
3366 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3367 int power_savings_balance = 1;
3368 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3369 unsigned long min_nr_running = ULONG_MAX;
3370 struct sched_group *group_min = NULL, *group_leader = NULL;
3371 #endif
3373 max_load = this_load = total_load = total_pwr = 0;
3374 busiest_load_per_task = busiest_nr_running = 0;
3375 this_load_per_task = this_nr_running = 0;
3376 if (idle == CPU_NOT_IDLE)
3377 load_idx = sd->busy_idx;
3378 else if (idle == CPU_NEWLY_IDLE)
3379 load_idx = sd->newidle_idx;
3380 else
3381 load_idx = sd->idle_idx;
3383 do {
3384 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3385 int local_group;
3386 int i;
3387 int __group_imb = 0;
3388 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3389 unsigned long sum_nr_running, sum_weighted_load;
3391 local_group = cpu_isset(this_cpu, group->cpumask);
3393 if (local_group)
3394 balance_cpu = first_cpu(group->cpumask);
3396 /* Tally up the load of all CPUs in the group */
3397 sum_weighted_load = sum_nr_running = avg_load = 0;
3398 max_cpu_load = 0;
3399 min_cpu_load = ~0UL;
3401 for_each_cpu_mask(i, group->cpumask) {
3402 struct rq *rq;
3404 if (!cpu_isset(i, *cpus))
3405 continue;
3407 rq = cpu_rq(i);
3409 if (*sd_idle && rq->nr_running)
3410 *sd_idle = 0;
3412 /* Bias balancing toward cpus of our domain */
3413 if (local_group) {
3414 if (idle_cpu(i) && !first_idle_cpu) {
3415 first_idle_cpu = 1;
3416 balance_cpu = i;
3419 load = target_load(i, load_idx);
3420 } else {
3421 load = source_load(i, load_idx);
3422 if (load > max_cpu_load)
3423 max_cpu_load = load;
3424 if (min_cpu_load > load)
3425 min_cpu_load = load;
3428 avg_load += load;
3429 sum_nr_running += rq->nr_running;
3430 sum_weighted_load += weighted_cpuload(i);
3434 * First idle cpu or the first cpu(busiest) in this sched group
3435 * is eligible for doing load balancing at this and above
3436 * domains. In the newly idle case, we will allow all the cpu's
3437 * to do the newly idle load balance.
3439 if (idle != CPU_NEWLY_IDLE && local_group &&
3440 balance_cpu != this_cpu && balance) {
3441 *balance = 0;
3442 goto ret;
3445 total_load += avg_load;
3446 total_pwr += group->__cpu_power;
3448 /* Adjust by relative CPU power of the group */
3449 avg_load = sg_div_cpu_power(group,
3450 avg_load * SCHED_LOAD_SCALE);
3452 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
3453 __group_imb = 1;
3455 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3457 if (local_group) {
3458 this_load = avg_load;
3459 this = group;
3460 this_nr_running = sum_nr_running;
3461 this_load_per_task = sum_weighted_load;
3462 } else if (avg_load > max_load &&
3463 (sum_nr_running > group_capacity || __group_imb)) {
3464 max_load = avg_load;
3465 busiest = group;
3466 busiest_nr_running = sum_nr_running;
3467 busiest_load_per_task = sum_weighted_load;
3468 group_imb = __group_imb;
3471 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3473 * Busy processors will not participate in power savings
3474 * balance.
3476 if (idle == CPU_NOT_IDLE ||
3477 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3478 goto group_next;
3481 * If the local group is idle or completely loaded
3482 * no need to do power savings balance at this domain
3484 if (local_group && (this_nr_running >= group_capacity ||
3485 !this_nr_running))
3486 power_savings_balance = 0;
3489 * If a group is already running at full capacity or idle,
3490 * don't include that group in power savings calculations
3492 if (!power_savings_balance || sum_nr_running >= group_capacity
3493 || !sum_nr_running)
3494 goto group_next;
3497 * Calculate the group which has the least non-idle load.
3498 * This is the group from where we need to pick up the load
3499 * for saving power
3501 if ((sum_nr_running < min_nr_running) ||
3502 (sum_nr_running == min_nr_running &&
3503 first_cpu(group->cpumask) <
3504 first_cpu(group_min->cpumask))) {
3505 group_min = group;
3506 min_nr_running = sum_nr_running;
3507 min_load_per_task = sum_weighted_load /
3508 sum_nr_running;
3512 * Calculate the group which is almost near its
3513 * capacity but still has some space to pick up some load
3514 * from other group and save more power
3516 if (sum_nr_running <= group_capacity - 1) {
3517 if (sum_nr_running > leader_nr_running ||
3518 (sum_nr_running == leader_nr_running &&
3519 first_cpu(group->cpumask) >
3520 first_cpu(group_leader->cpumask))) {
3521 group_leader = group;
3522 leader_nr_running = sum_nr_running;
3525 group_next:
3526 #endif
3527 group = group->next;
3528 } while (group != sd->groups);
3530 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3531 goto out_balanced;
3533 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3535 if (this_load >= avg_load ||
3536 100*max_load <= sd->imbalance_pct*this_load)
3537 goto out_balanced;
3539 busiest_load_per_task /= busiest_nr_running;
3540 if (group_imb)
3541 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3544 * We're trying to get all the cpus to the average_load, so we don't
3545 * want to push ourselves above the average load, nor do we wish to
3546 * reduce the max loaded cpu below the average load, as either of these
3547 * actions would just result in more rebalancing later, and ping-pong
3548 * tasks around. Thus we look for the minimum possible imbalance.
3549 * Negative imbalances (*we* are more loaded than anyone else) will
3550 * be counted as no imbalance for these purposes -- we can't fix that
3551 * by pulling tasks to us. Be careful of negative numbers as they'll
3552 * appear as very large values with unsigned longs.
3554 if (max_load <= busiest_load_per_task)
3555 goto out_balanced;
3558 * In the presence of smp nice balancing, certain scenarios can have
3559 * max load less than avg load(as we skip the groups at or below
3560 * its cpu_power, while calculating max_load..)
3562 if (max_load < avg_load) {
3563 *imbalance = 0;
3564 goto small_imbalance;
3567 /* Don't want to pull so many tasks that a group would go idle */
3568 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3570 /* How much load to actually move to equalise the imbalance */
3571 *imbalance = min(max_pull * busiest->__cpu_power,
3572 (avg_load - this_load) * this->__cpu_power)
3573 / SCHED_LOAD_SCALE;
3576 * if *imbalance is less than the average load per runnable task
3577 * there is no gaurantee that any tasks will be moved so we'll have
3578 * a think about bumping its value to force at least one task to be
3579 * moved
3581 if (*imbalance < busiest_load_per_task) {
3582 unsigned long tmp, pwr_now, pwr_move;
3583 unsigned int imbn;
3585 small_imbalance:
3586 pwr_move = pwr_now = 0;
3587 imbn = 2;
3588 if (this_nr_running) {
3589 this_load_per_task /= this_nr_running;
3590 if (busiest_load_per_task > this_load_per_task)
3591 imbn = 1;
3592 } else
3593 this_load_per_task = SCHED_LOAD_SCALE;
3595 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3596 busiest_load_per_task * imbn) {
3597 *imbalance = busiest_load_per_task;
3598 return busiest;
3602 * OK, we don't have enough imbalance to justify moving tasks,
3603 * however we may be able to increase total CPU power used by
3604 * moving them.
3607 pwr_now += busiest->__cpu_power *
3608 min(busiest_load_per_task, max_load);
3609 pwr_now += this->__cpu_power *
3610 min(this_load_per_task, this_load);
3611 pwr_now /= SCHED_LOAD_SCALE;
3613 /* Amount of load we'd subtract */
3614 tmp = sg_div_cpu_power(busiest,
3615 busiest_load_per_task * SCHED_LOAD_SCALE);
3616 if (max_load > tmp)
3617 pwr_move += busiest->__cpu_power *
3618 min(busiest_load_per_task, max_load - tmp);
3620 /* Amount of load we'd add */
3621 if (max_load * busiest->__cpu_power <
3622 busiest_load_per_task * SCHED_LOAD_SCALE)
3623 tmp = sg_div_cpu_power(this,
3624 max_load * busiest->__cpu_power);
3625 else
3626 tmp = sg_div_cpu_power(this,
3627 busiest_load_per_task * SCHED_LOAD_SCALE);
3628 pwr_move += this->__cpu_power *
3629 min(this_load_per_task, this_load + tmp);
3630 pwr_move /= SCHED_LOAD_SCALE;
3632 /* Move if we gain throughput */
3633 if (pwr_move > pwr_now)
3634 *imbalance = busiest_load_per_task;
3637 return busiest;
3639 out_balanced:
3640 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3641 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3642 goto ret;
3644 if (this == group_leader && group_leader != group_min) {
3645 *imbalance = min_load_per_task;
3646 return group_min;
3648 #endif
3649 ret:
3650 *imbalance = 0;
3651 return NULL;
3655 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3657 static struct rq *
3658 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3659 unsigned long imbalance, const cpumask_t *cpus)
3661 struct rq *busiest = NULL, *rq;
3662 unsigned long max_load = 0;
3663 int i;
3665 for_each_cpu_mask(i, group->cpumask) {
3666 unsigned long wl;
3668 if (!cpu_isset(i, *cpus))
3669 continue;
3671 rq = cpu_rq(i);
3672 wl = weighted_cpuload(i);
3674 if (rq->nr_running == 1 && wl > imbalance)
3675 continue;
3677 if (wl > max_load) {
3678 max_load = wl;
3679 busiest = rq;
3683 return busiest;
3687 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3688 * so long as it is large enough.
3690 #define MAX_PINNED_INTERVAL 512
3693 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3694 * tasks if there is an imbalance.
3696 static int load_balance(int this_cpu, struct rq *this_rq,
3697 struct sched_domain *sd, enum cpu_idle_type idle,
3698 int *balance, cpumask_t *cpus)
3700 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3701 struct sched_group *group;
3702 unsigned long imbalance;
3703 struct rq *busiest;
3704 unsigned long flags;
3705 int unlock_aggregate;
3707 cpus_setall(*cpus);
3709 unlock_aggregate = get_aggregate(sd);
3712 * When power savings policy is enabled for the parent domain, idle
3713 * sibling can pick up load irrespective of busy siblings. In this case,
3714 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3715 * portraying it as CPU_NOT_IDLE.
3717 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3718 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3719 sd_idle = 1;
3721 schedstat_inc(sd, lb_count[idle]);
3723 redo:
3724 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3725 cpus, balance);
3727 if (*balance == 0)
3728 goto out_balanced;
3730 if (!group) {
3731 schedstat_inc(sd, lb_nobusyg[idle]);
3732 goto out_balanced;
3735 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3736 if (!busiest) {
3737 schedstat_inc(sd, lb_nobusyq[idle]);
3738 goto out_balanced;
3741 BUG_ON(busiest == this_rq);
3743 schedstat_add(sd, lb_imbalance[idle], imbalance);
3745 ld_moved = 0;
3746 if (busiest->nr_running > 1) {
3748 * Attempt to move tasks. If find_busiest_group has found
3749 * an imbalance but busiest->nr_running <= 1, the group is
3750 * still unbalanced. ld_moved simply stays zero, so it is
3751 * correctly treated as an imbalance.
3753 local_irq_save(flags);
3754 double_rq_lock(this_rq, busiest);
3755 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3756 imbalance, sd, idle, &all_pinned);
3757 double_rq_unlock(this_rq, busiest);
3758 local_irq_restore(flags);
3761 * some other cpu did the load balance for us.
3763 if (ld_moved && this_cpu != smp_processor_id())
3764 resched_cpu(this_cpu);
3766 /* All tasks on this runqueue were pinned by CPU affinity */
3767 if (unlikely(all_pinned)) {
3768 cpu_clear(cpu_of(busiest), *cpus);
3769 if (!cpus_empty(*cpus))
3770 goto redo;
3771 goto out_balanced;
3775 if (!ld_moved) {
3776 schedstat_inc(sd, lb_failed[idle]);
3777 sd->nr_balance_failed++;
3779 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3781 spin_lock_irqsave(&busiest->lock, flags);
3783 /* don't kick the migration_thread, if the curr
3784 * task on busiest cpu can't be moved to this_cpu
3786 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3787 spin_unlock_irqrestore(&busiest->lock, flags);
3788 all_pinned = 1;
3789 goto out_one_pinned;
3792 if (!busiest->active_balance) {
3793 busiest->active_balance = 1;
3794 busiest->push_cpu = this_cpu;
3795 active_balance = 1;
3797 spin_unlock_irqrestore(&busiest->lock, flags);
3798 if (active_balance)
3799 wake_up_process(busiest->migration_thread);
3802 * We've kicked active balancing, reset the failure
3803 * counter.
3805 sd->nr_balance_failed = sd->cache_nice_tries+1;
3807 } else
3808 sd->nr_balance_failed = 0;
3810 if (likely(!active_balance)) {
3811 /* We were unbalanced, so reset the balancing interval */
3812 sd->balance_interval = sd->min_interval;
3813 } else {
3815 * If we've begun active balancing, start to back off. This
3816 * case may not be covered by the all_pinned logic if there
3817 * is only 1 task on the busy runqueue (because we don't call
3818 * move_tasks).
3820 if (sd->balance_interval < sd->max_interval)
3821 sd->balance_interval *= 2;
3824 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3825 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3826 ld_moved = -1;
3828 goto out;
3830 out_balanced:
3831 schedstat_inc(sd, lb_balanced[idle]);
3833 sd->nr_balance_failed = 0;
3835 out_one_pinned:
3836 /* tune up the balancing interval */
3837 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3838 (sd->balance_interval < sd->max_interval))
3839 sd->balance_interval *= 2;
3841 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3842 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3843 ld_moved = -1;
3844 else
3845 ld_moved = 0;
3846 out:
3847 if (unlock_aggregate)
3848 put_aggregate(sd);
3849 return ld_moved;
3853 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3854 * tasks if there is an imbalance.
3856 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3857 * this_rq is locked.
3859 static int
3860 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3861 cpumask_t *cpus)
3863 struct sched_group *group;
3864 struct rq *busiest = NULL;
3865 unsigned long imbalance;
3866 int ld_moved = 0;
3867 int sd_idle = 0;
3868 int all_pinned = 0;
3870 cpus_setall(*cpus);
3873 * When power savings policy is enabled for the parent domain, idle
3874 * sibling can pick up load irrespective of busy siblings. In this case,
3875 * let the state of idle sibling percolate up as IDLE, instead of
3876 * portraying it as CPU_NOT_IDLE.
3878 if (sd->flags & SD_SHARE_CPUPOWER &&
3879 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3880 sd_idle = 1;
3882 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3883 redo:
3884 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3885 &sd_idle, cpus, NULL);
3886 if (!group) {
3887 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3888 goto out_balanced;
3891 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3892 if (!busiest) {
3893 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3894 goto out_balanced;
3897 BUG_ON(busiest == this_rq);
3899 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3901 ld_moved = 0;
3902 if (busiest->nr_running > 1) {
3903 /* Attempt to move tasks */
3904 double_lock_balance(this_rq, busiest);
3905 /* this_rq->clock is already updated */
3906 update_rq_clock(busiest);
3907 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3908 imbalance, sd, CPU_NEWLY_IDLE,
3909 &all_pinned);
3910 spin_unlock(&busiest->lock);
3912 if (unlikely(all_pinned)) {
3913 cpu_clear(cpu_of(busiest), *cpus);
3914 if (!cpus_empty(*cpus))
3915 goto redo;
3919 if (!ld_moved) {
3920 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3921 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3922 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3923 return -1;
3924 } else
3925 sd->nr_balance_failed = 0;
3927 return ld_moved;
3929 out_balanced:
3930 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3931 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3932 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3933 return -1;
3934 sd->nr_balance_failed = 0;
3936 return 0;
3940 * idle_balance is called by schedule() if this_cpu is about to become
3941 * idle. Attempts to pull tasks from other CPUs.
3943 static void idle_balance(int this_cpu, struct rq *this_rq)
3945 struct sched_domain *sd;
3946 int pulled_task = -1;
3947 unsigned long next_balance = jiffies + HZ;
3948 cpumask_t tmpmask;
3950 for_each_domain(this_cpu, sd) {
3951 unsigned long interval;
3953 if (!(sd->flags & SD_LOAD_BALANCE))
3954 continue;
3956 if (sd->flags & SD_BALANCE_NEWIDLE)
3957 /* If we've pulled tasks over stop searching: */
3958 pulled_task = load_balance_newidle(this_cpu, this_rq,
3959 sd, &tmpmask);
3961 interval = msecs_to_jiffies(sd->balance_interval);
3962 if (time_after(next_balance, sd->last_balance + interval))
3963 next_balance = sd->last_balance + interval;
3964 if (pulled_task)
3965 break;
3967 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3969 * We are going idle. next_balance may be set based on
3970 * a busy processor. So reset next_balance.
3972 this_rq->next_balance = next_balance;
3977 * active_load_balance is run by migration threads. It pushes running tasks
3978 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3979 * running on each physical CPU where possible, and avoids physical /
3980 * logical imbalances.
3982 * Called with busiest_rq locked.
3984 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3986 int target_cpu = busiest_rq->push_cpu;
3987 struct sched_domain *sd;
3988 struct rq *target_rq;
3990 /* Is there any task to move? */
3991 if (busiest_rq->nr_running <= 1)
3992 return;
3994 target_rq = cpu_rq(target_cpu);
3997 * This condition is "impossible", if it occurs
3998 * we need to fix it. Originally reported by
3999 * Bjorn Helgaas on a 128-cpu setup.
4001 BUG_ON(busiest_rq == target_rq);
4003 /* move a task from busiest_rq to target_rq */
4004 double_lock_balance(busiest_rq, target_rq);
4005 update_rq_clock(busiest_rq);
4006 update_rq_clock(target_rq);
4008 /* Search for an sd spanning us and the target CPU. */
4009 for_each_domain(target_cpu, sd) {
4010 if ((sd->flags & SD_LOAD_BALANCE) &&
4011 cpu_isset(busiest_cpu, sd->span))
4012 break;
4015 if (likely(sd)) {
4016 schedstat_inc(sd, alb_count);
4018 if (move_one_task(target_rq, target_cpu, busiest_rq,
4019 sd, CPU_IDLE))
4020 schedstat_inc(sd, alb_pushed);
4021 else
4022 schedstat_inc(sd, alb_failed);
4024 spin_unlock(&target_rq->lock);
4027 #ifdef CONFIG_NO_HZ
4028 static struct {
4029 atomic_t load_balancer;
4030 cpumask_t cpu_mask;
4031 } nohz ____cacheline_aligned = {
4032 .load_balancer = ATOMIC_INIT(-1),
4033 .cpu_mask = CPU_MASK_NONE,
4037 * This routine will try to nominate the ilb (idle load balancing)
4038 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4039 * load balancing on behalf of all those cpus. If all the cpus in the system
4040 * go into this tickless mode, then there will be no ilb owner (as there is
4041 * no need for one) and all the cpus will sleep till the next wakeup event
4042 * arrives...
4044 * For the ilb owner, tick is not stopped. And this tick will be used
4045 * for idle load balancing. ilb owner will still be part of
4046 * nohz.cpu_mask..
4048 * While stopping the tick, this cpu will become the ilb owner if there
4049 * is no other owner. And will be the owner till that cpu becomes busy
4050 * or if all cpus in the system stop their ticks at which point
4051 * there is no need for ilb owner.
4053 * When the ilb owner becomes busy, it nominates another owner, during the
4054 * next busy scheduler_tick()
4056 int select_nohz_load_balancer(int stop_tick)
4058 int cpu = smp_processor_id();
4060 if (stop_tick) {
4061 cpu_set(cpu, nohz.cpu_mask);
4062 cpu_rq(cpu)->in_nohz_recently = 1;
4065 * If we are going offline and still the leader, give up!
4067 if (cpu_is_offline(cpu) &&
4068 atomic_read(&nohz.load_balancer) == cpu) {
4069 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4070 BUG();
4071 return 0;
4074 /* time for ilb owner also to sleep */
4075 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4076 if (atomic_read(&nohz.load_balancer) == cpu)
4077 atomic_set(&nohz.load_balancer, -1);
4078 return 0;
4081 if (atomic_read(&nohz.load_balancer) == -1) {
4082 /* make me the ilb owner */
4083 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4084 return 1;
4085 } else if (atomic_read(&nohz.load_balancer) == cpu)
4086 return 1;
4087 } else {
4088 if (!cpu_isset(cpu, nohz.cpu_mask))
4089 return 0;
4091 cpu_clear(cpu, nohz.cpu_mask);
4093 if (atomic_read(&nohz.load_balancer) == cpu)
4094 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4095 BUG();
4097 return 0;
4099 #endif
4101 static DEFINE_SPINLOCK(balancing);
4104 * It checks each scheduling domain to see if it is due to be balanced,
4105 * and initiates a balancing operation if so.
4107 * Balancing parameters are set up in arch_init_sched_domains.
4109 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4111 int balance = 1;
4112 struct rq *rq = cpu_rq(cpu);
4113 unsigned long interval;
4114 struct sched_domain *sd;
4115 /* Earliest time when we have to do rebalance again */
4116 unsigned long next_balance = jiffies + 60*HZ;
4117 int update_next_balance = 0;
4118 cpumask_t tmp;
4120 for_each_domain(cpu, sd) {
4121 if (!(sd->flags & SD_LOAD_BALANCE))
4122 continue;
4124 interval = sd->balance_interval;
4125 if (idle != CPU_IDLE)
4126 interval *= sd->busy_factor;
4128 /* scale ms to jiffies */
4129 interval = msecs_to_jiffies(interval);
4130 if (unlikely(!interval))
4131 interval = 1;
4132 if (interval > HZ*NR_CPUS/10)
4133 interval = HZ*NR_CPUS/10;
4136 if (sd->flags & SD_SERIALIZE) {
4137 if (!spin_trylock(&balancing))
4138 goto out;
4141 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4142 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
4144 * We've pulled tasks over so either we're no
4145 * longer idle, or one of our SMT siblings is
4146 * not idle.
4148 idle = CPU_NOT_IDLE;
4150 sd->last_balance = jiffies;
4152 if (sd->flags & SD_SERIALIZE)
4153 spin_unlock(&balancing);
4154 out:
4155 if (time_after(next_balance, sd->last_balance + interval)) {
4156 next_balance = sd->last_balance + interval;
4157 update_next_balance = 1;
4161 * Stop the load balance at this level. There is another
4162 * CPU in our sched group which is doing load balancing more
4163 * actively.
4165 if (!balance)
4166 break;
4170 * next_balance will be updated only when there is a need.
4171 * When the cpu is attached to null domain for ex, it will not be
4172 * updated.
4174 if (likely(update_next_balance))
4175 rq->next_balance = next_balance;
4179 * run_rebalance_domains is triggered when needed from the scheduler tick.
4180 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4181 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4183 static void run_rebalance_domains(struct softirq_action *h)
4185 int this_cpu = smp_processor_id();
4186 struct rq *this_rq = cpu_rq(this_cpu);
4187 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4188 CPU_IDLE : CPU_NOT_IDLE;
4190 rebalance_domains(this_cpu, idle);
4192 #ifdef CONFIG_NO_HZ
4194 * If this cpu is the owner for idle load balancing, then do the
4195 * balancing on behalf of the other idle cpus whose ticks are
4196 * stopped.
4198 if (this_rq->idle_at_tick &&
4199 atomic_read(&nohz.load_balancer) == this_cpu) {
4200 cpumask_t cpus = nohz.cpu_mask;
4201 struct rq *rq;
4202 int balance_cpu;
4204 cpu_clear(this_cpu, cpus);
4205 for_each_cpu_mask(balance_cpu, cpus) {
4207 * If this cpu gets work to do, stop the load balancing
4208 * work being done for other cpus. Next load
4209 * balancing owner will pick it up.
4211 if (need_resched())
4212 break;
4214 rebalance_domains(balance_cpu, CPU_IDLE);
4216 rq = cpu_rq(balance_cpu);
4217 if (time_after(this_rq->next_balance, rq->next_balance))
4218 this_rq->next_balance = rq->next_balance;
4221 #endif
4225 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4227 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4228 * idle load balancing owner or decide to stop the periodic load balancing,
4229 * if the whole system is idle.
4231 static inline void trigger_load_balance(struct rq *rq, int cpu)
4233 #ifdef CONFIG_NO_HZ
4235 * If we were in the nohz mode recently and busy at the current
4236 * scheduler tick, then check if we need to nominate new idle
4237 * load balancer.
4239 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4240 rq->in_nohz_recently = 0;
4242 if (atomic_read(&nohz.load_balancer) == cpu) {
4243 cpu_clear(cpu, nohz.cpu_mask);
4244 atomic_set(&nohz.load_balancer, -1);
4247 if (atomic_read(&nohz.load_balancer) == -1) {
4249 * simple selection for now: Nominate the
4250 * first cpu in the nohz list to be the next
4251 * ilb owner.
4253 * TBD: Traverse the sched domains and nominate
4254 * the nearest cpu in the nohz.cpu_mask.
4256 int ilb = first_cpu(nohz.cpu_mask);
4258 if (ilb < nr_cpu_ids)
4259 resched_cpu(ilb);
4264 * If this cpu is idle and doing idle load balancing for all the
4265 * cpus with ticks stopped, is it time for that to stop?
4267 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4268 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4269 resched_cpu(cpu);
4270 return;
4274 * If this cpu is idle and the idle load balancing is done by
4275 * someone else, then no need raise the SCHED_SOFTIRQ
4277 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4278 cpu_isset(cpu, nohz.cpu_mask))
4279 return;
4280 #endif
4281 if (time_after_eq(jiffies, rq->next_balance))
4282 raise_softirq(SCHED_SOFTIRQ);
4285 #else /* CONFIG_SMP */
4288 * on UP we do not need to balance between CPUs:
4290 static inline void idle_balance(int cpu, struct rq *rq)
4294 #endif
4296 DEFINE_PER_CPU(struct kernel_stat, kstat);
4298 EXPORT_PER_CPU_SYMBOL(kstat);
4301 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4302 * that have not yet been banked in case the task is currently running.
4304 unsigned long long task_sched_runtime(struct task_struct *p)
4306 unsigned long flags;
4307 u64 ns, delta_exec;
4308 struct rq *rq;
4310 rq = task_rq_lock(p, &flags);
4311 ns = p->se.sum_exec_runtime;
4312 if (task_current(rq, p)) {
4313 update_rq_clock(rq);
4314 delta_exec = rq->clock - p->se.exec_start;
4315 if ((s64)delta_exec > 0)
4316 ns += delta_exec;
4318 task_rq_unlock(rq, &flags);
4320 return ns;
4324 * Account user cpu time to a process.
4325 * @p: the process that the cpu time gets accounted to
4326 * @cputime: the cpu time spent in user space since the last update
4328 void account_user_time(struct task_struct *p, cputime_t cputime)
4330 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4331 cputime64_t tmp;
4333 p->utime = cputime_add(p->utime, cputime);
4335 /* Add user time to cpustat. */
4336 tmp = cputime_to_cputime64(cputime);
4337 if (TASK_NICE(p) > 0)
4338 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4339 else
4340 cpustat->user = cputime64_add(cpustat->user, tmp);
4344 * Account guest cpu time to a process.
4345 * @p: the process that the cpu time gets accounted to
4346 * @cputime: the cpu time spent in virtual machine since the last update
4348 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4350 cputime64_t tmp;
4351 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4353 tmp = cputime_to_cputime64(cputime);
4355 p->utime = cputime_add(p->utime, cputime);
4356 p->gtime = cputime_add(p->gtime, cputime);
4358 cpustat->user = cputime64_add(cpustat->user, tmp);
4359 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4363 * Account scaled user cpu time to a process.
4364 * @p: the process that the cpu time gets accounted to
4365 * @cputime: the cpu time spent in user space since the last update
4367 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4369 p->utimescaled = cputime_add(p->utimescaled, cputime);
4373 * Account system cpu time to a process.
4374 * @p: the process that the cpu time gets accounted to
4375 * @hardirq_offset: the offset to subtract from hardirq_count()
4376 * @cputime: the cpu time spent in kernel space since the last update
4378 void account_system_time(struct task_struct *p, int hardirq_offset,
4379 cputime_t cputime)
4381 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4382 struct rq *rq = this_rq();
4383 cputime64_t tmp;
4385 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
4386 return account_guest_time(p, cputime);
4388 p->stime = cputime_add(p->stime, cputime);
4390 /* Add system time to cpustat. */
4391 tmp = cputime_to_cputime64(cputime);
4392 if (hardirq_count() - hardirq_offset)
4393 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4394 else if (softirq_count())
4395 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4396 else if (p != rq->idle)
4397 cpustat->system = cputime64_add(cpustat->system, tmp);
4398 else if (atomic_read(&rq->nr_iowait) > 0)
4399 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4400 else
4401 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4402 /* Account for system time used */
4403 acct_update_integrals(p);
4407 * Account scaled system cpu time to a process.
4408 * @p: the process that the cpu time gets accounted to
4409 * @hardirq_offset: the offset to subtract from hardirq_count()
4410 * @cputime: the cpu time spent in kernel space since the last update
4412 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4414 p->stimescaled = cputime_add(p->stimescaled, cputime);
4418 * Account for involuntary wait time.
4419 * @p: the process from which the cpu time has been stolen
4420 * @steal: the cpu time spent in involuntary wait
4422 void account_steal_time(struct task_struct *p, cputime_t steal)
4424 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4425 cputime64_t tmp = cputime_to_cputime64(steal);
4426 struct rq *rq = this_rq();
4428 if (p == rq->idle) {
4429 p->stime = cputime_add(p->stime, steal);
4430 if (atomic_read(&rq->nr_iowait) > 0)
4431 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4432 else
4433 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4434 } else
4435 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4439 * This function gets called by the timer code, with HZ frequency.
4440 * We call it with interrupts disabled.
4442 * It also gets called by the fork code, when changing the parent's
4443 * timeslices.
4445 void scheduler_tick(void)
4447 int cpu = smp_processor_id();
4448 struct rq *rq = cpu_rq(cpu);
4449 struct task_struct *curr = rq->curr;
4450 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
4452 spin_lock(&rq->lock);
4453 __update_rq_clock(rq);
4455 * Let rq->clock advance by at least TICK_NSEC:
4457 if (unlikely(rq->clock < next_tick)) {
4458 rq->clock = next_tick;
4459 rq->clock_underflows++;
4461 rq->tick_timestamp = rq->clock;
4462 update_last_tick_seen(rq);
4463 update_cpu_load(rq);
4464 curr->sched_class->task_tick(rq, curr, 0);
4465 spin_unlock(&rq->lock);
4467 #ifdef CONFIG_SMP
4468 rq->idle_at_tick = idle_cpu(cpu);
4469 trigger_load_balance(rq, cpu);
4470 #endif
4473 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4475 void __kprobes add_preempt_count(int val)
4478 * Underflow?
4480 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4481 return;
4482 preempt_count() += val;
4484 * Spinlock count overflowing soon?
4486 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4487 PREEMPT_MASK - 10);
4489 EXPORT_SYMBOL(add_preempt_count);
4491 void __kprobes sub_preempt_count(int val)
4494 * Underflow?
4496 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4497 return;
4499 * Is the spinlock portion underflowing?
4501 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4502 !(preempt_count() & PREEMPT_MASK)))
4503 return;
4505 preempt_count() -= val;
4507 EXPORT_SYMBOL(sub_preempt_count);
4509 #endif
4512 * Print scheduling while atomic bug:
4514 static noinline void __schedule_bug(struct task_struct *prev)
4516 struct pt_regs *regs = get_irq_regs();
4518 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4519 prev->comm, prev->pid, preempt_count());
4521 debug_show_held_locks(prev);
4522 if (irqs_disabled())
4523 print_irqtrace_events(prev);
4525 if (regs)
4526 show_regs(regs);
4527 else
4528 dump_stack();
4532 * Various schedule()-time debugging checks and statistics:
4534 static inline void schedule_debug(struct task_struct *prev)
4537 * Test if we are atomic. Since do_exit() needs to call into
4538 * schedule() atomically, we ignore that path for now.
4539 * Otherwise, whine if we are scheduling when we should not be.
4541 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4542 __schedule_bug(prev);
4544 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4546 schedstat_inc(this_rq(), sched_count);
4547 #ifdef CONFIG_SCHEDSTATS
4548 if (unlikely(prev->lock_depth >= 0)) {
4549 schedstat_inc(this_rq(), bkl_count);
4550 schedstat_inc(prev, sched_info.bkl_count);
4552 #endif
4556 * Pick up the highest-prio task:
4558 static inline struct task_struct *
4559 pick_next_task(struct rq *rq, struct task_struct *prev)
4561 const struct sched_class *class;
4562 struct task_struct *p;
4565 * Optimization: we know that if all tasks are in
4566 * the fair class we can call that function directly:
4568 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4569 p = fair_sched_class.pick_next_task(rq);
4570 if (likely(p))
4571 return p;
4574 class = sched_class_highest;
4575 for ( ; ; ) {
4576 p = class->pick_next_task(rq);
4577 if (p)
4578 return p;
4580 * Will never be NULL as the idle class always
4581 * returns a non-NULL p:
4583 class = class->next;
4588 * schedule() is the main scheduler function.
4590 asmlinkage void __sched schedule(void)
4592 struct task_struct *prev, *next;
4593 unsigned long *switch_count;
4594 struct rq *rq;
4595 int cpu;
4597 need_resched:
4598 preempt_disable();
4599 cpu = smp_processor_id();
4600 rq = cpu_rq(cpu);
4601 rcu_qsctr_inc(cpu);
4602 prev = rq->curr;
4603 switch_count = &prev->nivcsw;
4605 release_kernel_lock(prev);
4606 need_resched_nonpreemptible:
4608 schedule_debug(prev);
4610 hrtick_clear(rq);
4613 * Do the rq-clock update outside the rq lock:
4615 local_irq_disable();
4616 __update_rq_clock(rq);
4617 spin_lock(&rq->lock);
4618 clear_tsk_need_resched(prev);
4620 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4621 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4622 signal_pending(prev))) {
4623 prev->state = TASK_RUNNING;
4624 } else {
4625 deactivate_task(rq, prev, 1);
4627 switch_count = &prev->nvcsw;
4630 #ifdef CONFIG_SMP
4631 if (prev->sched_class->pre_schedule)
4632 prev->sched_class->pre_schedule(rq, prev);
4633 #endif
4635 if (unlikely(!rq->nr_running))
4636 idle_balance(cpu, rq);
4638 prev->sched_class->put_prev_task(rq, prev);
4639 next = pick_next_task(rq, prev);
4641 sched_info_switch(prev, next);
4643 if (likely(prev != next)) {
4644 rq->nr_switches++;
4645 rq->curr = next;
4646 ++*switch_count;
4648 context_switch(rq, prev, next); /* unlocks the rq */
4650 * the context switch might have flipped the stack from under
4651 * us, hence refresh the local variables.
4653 cpu = smp_processor_id();
4654 rq = cpu_rq(cpu);
4655 } else
4656 spin_unlock_irq(&rq->lock);
4658 hrtick_set(rq);
4660 if (unlikely(reacquire_kernel_lock(current) < 0))
4661 goto need_resched_nonpreemptible;
4663 preempt_enable_no_resched();
4664 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4665 goto need_resched;
4667 EXPORT_SYMBOL(schedule);
4669 #ifdef CONFIG_PREEMPT
4671 * this is the entry point to schedule() from in-kernel preemption
4672 * off of preempt_enable. Kernel preemptions off return from interrupt
4673 * occur there and call schedule directly.
4675 asmlinkage void __sched preempt_schedule(void)
4677 struct thread_info *ti = current_thread_info();
4678 struct task_struct *task = current;
4679 int saved_lock_depth;
4682 * If there is a non-zero preempt_count or interrupts are disabled,
4683 * we do not want to preempt the current task. Just return..
4685 if (likely(ti->preempt_count || irqs_disabled()))
4686 return;
4688 do {
4689 add_preempt_count(PREEMPT_ACTIVE);
4692 * We keep the big kernel semaphore locked, but we
4693 * clear ->lock_depth so that schedule() doesnt
4694 * auto-release the semaphore:
4696 saved_lock_depth = task->lock_depth;
4697 task->lock_depth = -1;
4698 schedule();
4699 task->lock_depth = saved_lock_depth;
4700 sub_preempt_count(PREEMPT_ACTIVE);
4703 * Check again in case we missed a preemption opportunity
4704 * between schedule and now.
4706 barrier();
4707 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4709 EXPORT_SYMBOL(preempt_schedule);
4712 * this is the entry point to schedule() from kernel preemption
4713 * off of irq context.
4714 * Note, that this is called and return with irqs disabled. This will
4715 * protect us against recursive calling from irq.
4717 asmlinkage void __sched preempt_schedule_irq(void)
4719 struct thread_info *ti = current_thread_info();
4720 struct task_struct *task = current;
4721 int saved_lock_depth;
4723 /* Catch callers which need to be fixed */
4724 BUG_ON(ti->preempt_count || !irqs_disabled());
4726 do {
4727 add_preempt_count(PREEMPT_ACTIVE);
4730 * We keep the big kernel semaphore locked, but we
4731 * clear ->lock_depth so that schedule() doesnt
4732 * auto-release the semaphore:
4734 saved_lock_depth = task->lock_depth;
4735 task->lock_depth = -1;
4736 local_irq_enable();
4737 schedule();
4738 local_irq_disable();
4739 task->lock_depth = saved_lock_depth;
4740 sub_preempt_count(PREEMPT_ACTIVE);
4743 * Check again in case we missed a preemption opportunity
4744 * between schedule and now.
4746 barrier();
4747 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4750 #endif /* CONFIG_PREEMPT */
4752 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4753 void *key)
4755 return try_to_wake_up(curr->private, mode, sync);
4757 EXPORT_SYMBOL(default_wake_function);
4760 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4761 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4762 * number) then we wake all the non-exclusive tasks and one exclusive task.
4764 * There are circumstances in which we can try to wake a task which has already
4765 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4766 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4768 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4769 int nr_exclusive, int sync, void *key)
4771 wait_queue_t *curr, *next;
4773 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4774 unsigned flags = curr->flags;
4776 if (curr->func(curr, mode, sync, key) &&
4777 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4778 break;
4783 * __wake_up - wake up threads blocked on a waitqueue.
4784 * @q: the waitqueue
4785 * @mode: which threads
4786 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4787 * @key: is directly passed to the wakeup function
4789 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4790 int nr_exclusive, void *key)
4792 unsigned long flags;
4794 spin_lock_irqsave(&q->lock, flags);
4795 __wake_up_common(q, mode, nr_exclusive, 0, key);
4796 spin_unlock_irqrestore(&q->lock, flags);
4798 EXPORT_SYMBOL(__wake_up);
4801 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4803 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4805 __wake_up_common(q, mode, 1, 0, NULL);
4809 * __wake_up_sync - wake up threads blocked on a waitqueue.
4810 * @q: the waitqueue
4811 * @mode: which threads
4812 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4814 * The sync wakeup differs that the waker knows that it will schedule
4815 * away soon, so while the target thread will be woken up, it will not
4816 * be migrated to another CPU - ie. the two threads are 'synchronized'
4817 * with each other. This can prevent needless bouncing between CPUs.
4819 * On UP it can prevent extra preemption.
4821 void
4822 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4824 unsigned long flags;
4825 int sync = 1;
4827 if (unlikely(!q))
4828 return;
4830 if (unlikely(!nr_exclusive))
4831 sync = 0;
4833 spin_lock_irqsave(&q->lock, flags);
4834 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4835 spin_unlock_irqrestore(&q->lock, flags);
4837 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4839 void complete(struct completion *x)
4841 unsigned long flags;
4843 spin_lock_irqsave(&x->wait.lock, flags);
4844 x->done++;
4845 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4846 spin_unlock_irqrestore(&x->wait.lock, flags);
4848 EXPORT_SYMBOL(complete);
4850 void complete_all(struct completion *x)
4852 unsigned long flags;
4854 spin_lock_irqsave(&x->wait.lock, flags);
4855 x->done += UINT_MAX/2;
4856 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4857 spin_unlock_irqrestore(&x->wait.lock, flags);
4859 EXPORT_SYMBOL(complete_all);
4861 static inline long __sched
4862 do_wait_for_common(struct completion *x, long timeout, int state)
4864 if (!x->done) {
4865 DECLARE_WAITQUEUE(wait, current);
4867 wait.flags |= WQ_FLAG_EXCLUSIVE;
4868 __add_wait_queue_tail(&x->wait, &wait);
4869 do {
4870 if ((state == TASK_INTERRUPTIBLE &&
4871 signal_pending(current)) ||
4872 (state == TASK_KILLABLE &&
4873 fatal_signal_pending(current))) {
4874 __remove_wait_queue(&x->wait, &wait);
4875 return -ERESTARTSYS;
4877 __set_current_state(state);
4878 spin_unlock_irq(&x->wait.lock);
4879 timeout = schedule_timeout(timeout);
4880 spin_lock_irq(&x->wait.lock);
4881 if (!timeout) {
4882 __remove_wait_queue(&x->wait, &wait);
4883 return timeout;
4885 } while (!x->done);
4886 __remove_wait_queue(&x->wait, &wait);
4888 x->done--;
4889 return timeout;
4892 static long __sched
4893 wait_for_common(struct completion *x, long timeout, int state)
4895 might_sleep();
4897 spin_lock_irq(&x->wait.lock);
4898 timeout = do_wait_for_common(x, timeout, state);
4899 spin_unlock_irq(&x->wait.lock);
4900 return timeout;
4903 void __sched wait_for_completion(struct completion *x)
4905 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4907 EXPORT_SYMBOL(wait_for_completion);
4909 unsigned long __sched
4910 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4912 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4914 EXPORT_SYMBOL(wait_for_completion_timeout);
4916 int __sched wait_for_completion_interruptible(struct completion *x)
4918 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4919 if (t == -ERESTARTSYS)
4920 return t;
4921 return 0;
4923 EXPORT_SYMBOL(wait_for_completion_interruptible);
4925 unsigned long __sched
4926 wait_for_completion_interruptible_timeout(struct completion *x,
4927 unsigned long timeout)
4929 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4931 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4933 int __sched wait_for_completion_killable(struct completion *x)
4935 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4936 if (t == -ERESTARTSYS)
4937 return t;
4938 return 0;
4940 EXPORT_SYMBOL(wait_for_completion_killable);
4942 static long __sched
4943 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4945 unsigned long flags;
4946 wait_queue_t wait;
4948 init_waitqueue_entry(&wait, current);
4950 __set_current_state(state);
4952 spin_lock_irqsave(&q->lock, flags);
4953 __add_wait_queue(q, &wait);
4954 spin_unlock(&q->lock);
4955 timeout = schedule_timeout(timeout);
4956 spin_lock_irq(&q->lock);
4957 __remove_wait_queue(q, &wait);
4958 spin_unlock_irqrestore(&q->lock, flags);
4960 return timeout;
4963 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4965 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4967 EXPORT_SYMBOL(interruptible_sleep_on);
4969 long __sched
4970 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4972 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4974 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4976 void __sched sleep_on(wait_queue_head_t *q)
4978 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4980 EXPORT_SYMBOL(sleep_on);
4982 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4984 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4986 EXPORT_SYMBOL(sleep_on_timeout);
4988 #ifdef CONFIG_RT_MUTEXES
4991 * rt_mutex_setprio - set the current priority of a task
4992 * @p: task
4993 * @prio: prio value (kernel-internal form)
4995 * This function changes the 'effective' priority of a task. It does
4996 * not touch ->normal_prio like __setscheduler().
4998 * Used by the rt_mutex code to implement priority inheritance logic.
5000 void rt_mutex_setprio(struct task_struct *p, int prio)
5002 unsigned long flags;
5003 int oldprio, on_rq, running;
5004 struct rq *rq;
5005 const struct sched_class *prev_class = p->sched_class;
5007 BUG_ON(prio < 0 || prio > MAX_PRIO);
5009 rq = task_rq_lock(p, &flags);
5010 update_rq_clock(rq);
5012 oldprio = p->prio;
5013 on_rq = p->se.on_rq;
5014 running = task_current(rq, p);
5015 if (on_rq)
5016 dequeue_task(rq, p, 0);
5017 if (running)
5018 p->sched_class->put_prev_task(rq, p);
5020 if (rt_prio(prio))
5021 p->sched_class = &rt_sched_class;
5022 else
5023 p->sched_class = &fair_sched_class;
5025 p->prio = prio;
5027 if (running)
5028 p->sched_class->set_curr_task(rq);
5029 if (on_rq) {
5030 enqueue_task(rq, p, 0);
5032 check_class_changed(rq, p, prev_class, oldprio, running);
5034 task_rq_unlock(rq, &flags);
5037 #endif
5039 void set_user_nice(struct task_struct *p, long nice)
5041 int old_prio, delta, on_rq;
5042 unsigned long flags;
5043 struct rq *rq;
5045 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
5046 return;
5048 * We have to be careful, if called from sys_setpriority(),
5049 * the task might be in the middle of scheduling on another CPU.
5051 rq = task_rq_lock(p, &flags);
5052 update_rq_clock(rq);
5054 * The RT priorities are set via sched_setscheduler(), but we still
5055 * allow the 'normal' nice value to be set - but as expected
5056 * it wont have any effect on scheduling until the task is
5057 * SCHED_FIFO/SCHED_RR:
5059 if (task_has_rt_policy(p)) {
5060 p->static_prio = NICE_TO_PRIO(nice);
5061 goto out_unlock;
5063 on_rq = p->se.on_rq;
5064 if (on_rq)
5065 dequeue_task(rq, p, 0);
5067 p->static_prio = NICE_TO_PRIO(nice);
5068 set_load_weight(p);
5069 old_prio = p->prio;
5070 p->prio = effective_prio(p);
5071 delta = p->prio - old_prio;
5073 if (on_rq) {
5074 enqueue_task(rq, p, 0);
5076 * If the task increased its priority or is running and
5077 * lowered its priority, then reschedule its CPU:
5079 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5080 resched_task(rq->curr);
5082 out_unlock:
5083 task_rq_unlock(rq, &flags);
5085 EXPORT_SYMBOL(set_user_nice);
5088 * can_nice - check if a task can reduce its nice value
5089 * @p: task
5090 * @nice: nice value
5092 int can_nice(const struct task_struct *p, const int nice)
5094 /* convert nice value [19,-20] to rlimit style value [1,40] */
5095 int nice_rlim = 20 - nice;
5097 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5098 capable(CAP_SYS_NICE));
5101 #ifdef __ARCH_WANT_SYS_NICE
5104 * sys_nice - change the priority of the current process.
5105 * @increment: priority increment
5107 * sys_setpriority is a more generic, but much slower function that
5108 * does similar things.
5110 asmlinkage long sys_nice(int increment)
5112 long nice, retval;
5115 * Setpriority might change our priority at the same moment.
5116 * We don't have to worry. Conceptually one call occurs first
5117 * and we have a single winner.
5119 if (increment < -40)
5120 increment = -40;
5121 if (increment > 40)
5122 increment = 40;
5124 nice = PRIO_TO_NICE(current->static_prio) + increment;
5125 if (nice < -20)
5126 nice = -20;
5127 if (nice > 19)
5128 nice = 19;
5130 if (increment < 0 && !can_nice(current, nice))
5131 return -EPERM;
5133 retval = security_task_setnice(current, nice);
5134 if (retval)
5135 return retval;
5137 set_user_nice(current, nice);
5138 return 0;
5141 #endif
5144 * task_prio - return the priority value of a given task.
5145 * @p: the task in question.
5147 * This is the priority value as seen by users in /proc.
5148 * RT tasks are offset by -200. Normal tasks are centered
5149 * around 0, value goes from -16 to +15.
5151 int task_prio(const struct task_struct *p)
5153 return p->prio - MAX_RT_PRIO;
5157 * task_nice - return the nice value of a given task.
5158 * @p: the task in question.
5160 int task_nice(const struct task_struct *p)
5162 return TASK_NICE(p);
5164 EXPORT_SYMBOL(task_nice);
5167 * idle_cpu - is a given cpu idle currently?
5168 * @cpu: the processor in question.
5170 int idle_cpu(int cpu)
5172 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5176 * idle_task - return the idle task for a given cpu.
5177 * @cpu: the processor in question.
5179 struct task_struct *idle_task(int cpu)
5181 return cpu_rq(cpu)->idle;
5185 * find_process_by_pid - find a process with a matching PID value.
5186 * @pid: the pid in question.
5188 static struct task_struct *find_process_by_pid(pid_t pid)
5190 return pid ? find_task_by_vpid(pid) : current;
5193 /* Actually do priority change: must hold rq lock. */
5194 static void
5195 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5197 BUG_ON(p->se.on_rq);
5199 p->policy = policy;
5200 switch (p->policy) {
5201 case SCHED_NORMAL:
5202 case SCHED_BATCH:
5203 case SCHED_IDLE:
5204 p->sched_class = &fair_sched_class;
5205 break;
5206 case SCHED_FIFO:
5207 case SCHED_RR:
5208 p->sched_class = &rt_sched_class;
5209 break;
5212 p->rt_priority = prio;
5213 p->normal_prio = normal_prio(p);
5214 /* we are holding p->pi_lock already */
5215 p->prio = rt_mutex_getprio(p);
5216 set_load_weight(p);
5220 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5221 * @p: the task in question.
5222 * @policy: new policy.
5223 * @param: structure containing the new RT priority.
5225 * NOTE that the task may be already dead.
5227 int sched_setscheduler(struct task_struct *p, int policy,
5228 struct sched_param *param)
5230 int retval, oldprio, oldpolicy = -1, on_rq, running;
5231 unsigned long flags;
5232 const struct sched_class *prev_class = p->sched_class;
5233 struct rq *rq;
5235 /* may grab non-irq protected spin_locks */
5236 BUG_ON(in_interrupt());
5237 recheck:
5238 /* double check policy once rq lock held */
5239 if (policy < 0)
5240 policy = oldpolicy = p->policy;
5241 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5242 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5243 policy != SCHED_IDLE)
5244 return -EINVAL;
5246 * Valid priorities for SCHED_FIFO and SCHED_RR are
5247 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5248 * SCHED_BATCH and SCHED_IDLE is 0.
5250 if (param->sched_priority < 0 ||
5251 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5252 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5253 return -EINVAL;
5254 if (rt_policy(policy) != (param->sched_priority != 0))
5255 return -EINVAL;
5258 * Allow unprivileged RT tasks to decrease priority:
5260 if (!capable(CAP_SYS_NICE)) {
5261 if (rt_policy(policy)) {
5262 unsigned long rlim_rtprio;
5264 if (!lock_task_sighand(p, &flags))
5265 return -ESRCH;
5266 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5267 unlock_task_sighand(p, &flags);
5269 /* can't set/change the rt policy */
5270 if (policy != p->policy && !rlim_rtprio)
5271 return -EPERM;
5273 /* can't increase priority */
5274 if (param->sched_priority > p->rt_priority &&
5275 param->sched_priority > rlim_rtprio)
5276 return -EPERM;
5279 * Like positive nice levels, dont allow tasks to
5280 * move out of SCHED_IDLE either:
5282 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5283 return -EPERM;
5285 /* can't change other user's priorities */
5286 if ((current->euid != p->euid) &&
5287 (current->euid != p->uid))
5288 return -EPERM;
5291 #ifdef CONFIG_RT_GROUP_SCHED
5293 * Do not allow realtime tasks into groups that have no runtime
5294 * assigned.
5296 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5297 return -EPERM;
5298 #endif
5300 retval = security_task_setscheduler(p, policy, param);
5301 if (retval)
5302 return retval;
5304 * make sure no PI-waiters arrive (or leave) while we are
5305 * changing the priority of the task:
5307 spin_lock_irqsave(&p->pi_lock, flags);
5309 * To be able to change p->policy safely, the apropriate
5310 * runqueue lock must be held.
5312 rq = __task_rq_lock(p);
5313 /* recheck policy now with rq lock held */
5314 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5315 policy = oldpolicy = -1;
5316 __task_rq_unlock(rq);
5317 spin_unlock_irqrestore(&p->pi_lock, flags);
5318 goto recheck;
5320 update_rq_clock(rq);
5321 on_rq = p->se.on_rq;
5322 running = task_current(rq, p);
5323 if (on_rq)
5324 deactivate_task(rq, p, 0);
5325 if (running)
5326 p->sched_class->put_prev_task(rq, p);
5328 oldprio = p->prio;
5329 __setscheduler(rq, p, policy, param->sched_priority);
5331 if (running)
5332 p->sched_class->set_curr_task(rq);
5333 if (on_rq) {
5334 activate_task(rq, p, 0);
5336 check_class_changed(rq, p, prev_class, oldprio, running);
5338 __task_rq_unlock(rq);
5339 spin_unlock_irqrestore(&p->pi_lock, flags);
5341 rt_mutex_adjust_pi(p);
5343 return 0;
5345 EXPORT_SYMBOL_GPL(sched_setscheduler);
5347 static int
5348 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5350 struct sched_param lparam;
5351 struct task_struct *p;
5352 int retval;
5354 if (!param || pid < 0)
5355 return -EINVAL;
5356 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5357 return -EFAULT;
5359 rcu_read_lock();
5360 retval = -ESRCH;
5361 p = find_process_by_pid(pid);
5362 if (p != NULL)
5363 retval = sched_setscheduler(p, policy, &lparam);
5364 rcu_read_unlock();
5366 return retval;
5370 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5371 * @pid: the pid in question.
5372 * @policy: new policy.
5373 * @param: structure containing the new RT priority.
5375 asmlinkage long
5376 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5378 /* negative values for policy are not valid */
5379 if (policy < 0)
5380 return -EINVAL;
5382 return do_sched_setscheduler(pid, policy, param);
5386 * sys_sched_setparam - set/change the RT priority of a thread
5387 * @pid: the pid in question.
5388 * @param: structure containing the new RT priority.
5390 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5392 return do_sched_setscheduler(pid, -1, param);
5396 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5397 * @pid: the pid in question.
5399 asmlinkage long sys_sched_getscheduler(pid_t pid)
5401 struct task_struct *p;
5402 int retval;
5404 if (pid < 0)
5405 return -EINVAL;
5407 retval = -ESRCH;
5408 read_lock(&tasklist_lock);
5409 p = find_process_by_pid(pid);
5410 if (p) {
5411 retval = security_task_getscheduler(p);
5412 if (!retval)
5413 retval = p->policy;
5415 read_unlock(&tasklist_lock);
5416 return retval;
5420 * sys_sched_getscheduler - get the RT priority of a thread
5421 * @pid: the pid in question.
5422 * @param: structure containing the RT priority.
5424 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5426 struct sched_param lp;
5427 struct task_struct *p;
5428 int retval;
5430 if (!param || pid < 0)
5431 return -EINVAL;
5433 read_lock(&tasklist_lock);
5434 p = find_process_by_pid(pid);
5435 retval = -ESRCH;
5436 if (!p)
5437 goto out_unlock;
5439 retval = security_task_getscheduler(p);
5440 if (retval)
5441 goto out_unlock;
5443 lp.sched_priority = p->rt_priority;
5444 read_unlock(&tasklist_lock);
5447 * This one might sleep, we cannot do it with a spinlock held ...
5449 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5451 return retval;
5453 out_unlock:
5454 read_unlock(&tasklist_lock);
5455 return retval;
5458 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5460 cpumask_t cpus_allowed;
5461 cpumask_t new_mask = *in_mask;
5462 struct task_struct *p;
5463 int retval;
5465 get_online_cpus();
5466 read_lock(&tasklist_lock);
5468 p = find_process_by_pid(pid);
5469 if (!p) {
5470 read_unlock(&tasklist_lock);
5471 put_online_cpus();
5472 return -ESRCH;
5476 * It is not safe to call set_cpus_allowed with the
5477 * tasklist_lock held. We will bump the task_struct's
5478 * usage count and then drop tasklist_lock.
5480 get_task_struct(p);
5481 read_unlock(&tasklist_lock);
5483 retval = -EPERM;
5484 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5485 !capable(CAP_SYS_NICE))
5486 goto out_unlock;
5488 retval = security_task_setscheduler(p, 0, NULL);
5489 if (retval)
5490 goto out_unlock;
5492 cpuset_cpus_allowed(p, &cpus_allowed);
5493 cpus_and(new_mask, new_mask, cpus_allowed);
5494 again:
5495 retval = set_cpus_allowed_ptr(p, &new_mask);
5497 if (!retval) {
5498 cpuset_cpus_allowed(p, &cpus_allowed);
5499 if (!cpus_subset(new_mask, cpus_allowed)) {
5501 * We must have raced with a concurrent cpuset
5502 * update. Just reset the cpus_allowed to the
5503 * cpuset's cpus_allowed
5505 new_mask = cpus_allowed;
5506 goto again;
5509 out_unlock:
5510 put_task_struct(p);
5511 put_online_cpus();
5512 return retval;
5515 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5516 cpumask_t *new_mask)
5518 if (len < sizeof(cpumask_t)) {
5519 memset(new_mask, 0, sizeof(cpumask_t));
5520 } else if (len > sizeof(cpumask_t)) {
5521 len = sizeof(cpumask_t);
5523 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5527 * sys_sched_setaffinity - set the cpu affinity of a process
5528 * @pid: pid of the process
5529 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5530 * @user_mask_ptr: user-space pointer to the new cpu mask
5532 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5533 unsigned long __user *user_mask_ptr)
5535 cpumask_t new_mask;
5536 int retval;
5538 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5539 if (retval)
5540 return retval;
5542 return sched_setaffinity(pid, &new_mask);
5546 * Represents all cpu's present in the system
5547 * In systems capable of hotplug, this map could dynamically grow
5548 * as new cpu's are detected in the system via any platform specific
5549 * method, such as ACPI for e.g.
5552 cpumask_t cpu_present_map __read_mostly;
5553 EXPORT_SYMBOL(cpu_present_map);
5555 #ifndef CONFIG_SMP
5556 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5557 EXPORT_SYMBOL(cpu_online_map);
5559 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5560 EXPORT_SYMBOL(cpu_possible_map);
5561 #endif
5563 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5565 struct task_struct *p;
5566 int retval;
5568 get_online_cpus();
5569 read_lock(&tasklist_lock);
5571 retval = -ESRCH;
5572 p = find_process_by_pid(pid);
5573 if (!p)
5574 goto out_unlock;
5576 retval = security_task_getscheduler(p);
5577 if (retval)
5578 goto out_unlock;
5580 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5582 out_unlock:
5583 read_unlock(&tasklist_lock);
5584 put_online_cpus();
5586 return retval;
5590 * sys_sched_getaffinity - get the cpu affinity of a process
5591 * @pid: pid of the process
5592 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5593 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5595 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5596 unsigned long __user *user_mask_ptr)
5598 int ret;
5599 cpumask_t mask;
5601 if (len < sizeof(cpumask_t))
5602 return -EINVAL;
5604 ret = sched_getaffinity(pid, &mask);
5605 if (ret < 0)
5606 return ret;
5608 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5609 return -EFAULT;
5611 return sizeof(cpumask_t);
5615 * sys_sched_yield - yield the current processor to other threads.
5617 * This function yields the current CPU to other tasks. If there are no
5618 * other threads running on this CPU then this function will return.
5620 asmlinkage long sys_sched_yield(void)
5622 struct rq *rq = this_rq_lock();
5624 schedstat_inc(rq, yld_count);
5625 current->sched_class->yield_task(rq);
5628 * Since we are going to call schedule() anyway, there's
5629 * no need to preempt or enable interrupts:
5631 __release(rq->lock);
5632 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5633 _raw_spin_unlock(&rq->lock);
5634 preempt_enable_no_resched();
5636 schedule();
5638 return 0;
5641 static void __cond_resched(void)
5643 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5644 __might_sleep(__FILE__, __LINE__);
5645 #endif
5647 * The BKS might be reacquired before we have dropped
5648 * PREEMPT_ACTIVE, which could trigger a second
5649 * cond_resched() call.
5651 do {
5652 add_preempt_count(PREEMPT_ACTIVE);
5653 schedule();
5654 sub_preempt_count(PREEMPT_ACTIVE);
5655 } while (need_resched());
5658 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5659 int __sched _cond_resched(void)
5661 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5662 system_state == SYSTEM_RUNNING) {
5663 __cond_resched();
5664 return 1;
5666 return 0;
5668 EXPORT_SYMBOL(_cond_resched);
5669 #endif
5672 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5673 * call schedule, and on return reacquire the lock.
5675 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5676 * operations here to prevent schedule() from being called twice (once via
5677 * spin_unlock(), once by hand).
5679 int cond_resched_lock(spinlock_t *lock)
5681 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5682 int ret = 0;
5684 if (spin_needbreak(lock) || resched) {
5685 spin_unlock(lock);
5686 if (resched && need_resched())
5687 __cond_resched();
5688 else
5689 cpu_relax();
5690 ret = 1;
5691 spin_lock(lock);
5693 return ret;
5695 EXPORT_SYMBOL(cond_resched_lock);
5697 int __sched cond_resched_softirq(void)
5699 BUG_ON(!in_softirq());
5701 if (need_resched() && system_state == SYSTEM_RUNNING) {
5702 local_bh_enable();
5703 __cond_resched();
5704 local_bh_disable();
5705 return 1;
5707 return 0;
5709 EXPORT_SYMBOL(cond_resched_softirq);
5712 * yield - yield the current processor to other threads.
5714 * This is a shortcut for kernel-space yielding - it marks the
5715 * thread runnable and calls sys_sched_yield().
5717 void __sched yield(void)
5719 set_current_state(TASK_RUNNING);
5720 sys_sched_yield();
5722 EXPORT_SYMBOL(yield);
5725 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5726 * that process accounting knows that this is a task in IO wait state.
5728 * But don't do that if it is a deliberate, throttling IO wait (this task
5729 * has set its backing_dev_info: the queue against which it should throttle)
5731 void __sched io_schedule(void)
5733 struct rq *rq = &__raw_get_cpu_var(runqueues);
5735 delayacct_blkio_start();
5736 atomic_inc(&rq->nr_iowait);
5737 schedule();
5738 atomic_dec(&rq->nr_iowait);
5739 delayacct_blkio_end();
5741 EXPORT_SYMBOL(io_schedule);
5743 long __sched io_schedule_timeout(long timeout)
5745 struct rq *rq = &__raw_get_cpu_var(runqueues);
5746 long ret;
5748 delayacct_blkio_start();
5749 atomic_inc(&rq->nr_iowait);
5750 ret = schedule_timeout(timeout);
5751 atomic_dec(&rq->nr_iowait);
5752 delayacct_blkio_end();
5753 return ret;
5757 * sys_sched_get_priority_max - return maximum RT priority.
5758 * @policy: scheduling class.
5760 * this syscall returns the maximum rt_priority that can be used
5761 * by a given scheduling class.
5763 asmlinkage long sys_sched_get_priority_max(int policy)
5765 int ret = -EINVAL;
5767 switch (policy) {
5768 case SCHED_FIFO:
5769 case SCHED_RR:
5770 ret = MAX_USER_RT_PRIO-1;
5771 break;
5772 case SCHED_NORMAL:
5773 case SCHED_BATCH:
5774 case SCHED_IDLE:
5775 ret = 0;
5776 break;
5778 return ret;
5782 * sys_sched_get_priority_min - return minimum RT priority.
5783 * @policy: scheduling class.
5785 * this syscall returns the minimum rt_priority that can be used
5786 * by a given scheduling class.
5788 asmlinkage long sys_sched_get_priority_min(int policy)
5790 int ret = -EINVAL;
5792 switch (policy) {
5793 case SCHED_FIFO:
5794 case SCHED_RR:
5795 ret = 1;
5796 break;
5797 case SCHED_NORMAL:
5798 case SCHED_BATCH:
5799 case SCHED_IDLE:
5800 ret = 0;
5802 return ret;
5806 * sys_sched_rr_get_interval - return the default timeslice of a process.
5807 * @pid: pid of the process.
5808 * @interval: userspace pointer to the timeslice value.
5810 * this syscall writes the default timeslice value of a given process
5811 * into the user-space timespec buffer. A value of '0' means infinity.
5813 asmlinkage
5814 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5816 struct task_struct *p;
5817 unsigned int time_slice;
5818 int retval;
5819 struct timespec t;
5821 if (pid < 0)
5822 return -EINVAL;
5824 retval = -ESRCH;
5825 read_lock(&tasklist_lock);
5826 p = find_process_by_pid(pid);
5827 if (!p)
5828 goto out_unlock;
5830 retval = security_task_getscheduler(p);
5831 if (retval)
5832 goto out_unlock;
5835 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5836 * tasks that are on an otherwise idle runqueue:
5838 time_slice = 0;
5839 if (p->policy == SCHED_RR) {
5840 time_slice = DEF_TIMESLICE;
5841 } else if (p->policy != SCHED_FIFO) {
5842 struct sched_entity *se = &p->se;
5843 unsigned long flags;
5844 struct rq *rq;
5846 rq = task_rq_lock(p, &flags);
5847 if (rq->cfs.load.weight)
5848 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5849 task_rq_unlock(rq, &flags);
5851 read_unlock(&tasklist_lock);
5852 jiffies_to_timespec(time_slice, &t);
5853 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5854 return retval;
5856 out_unlock:
5857 read_unlock(&tasklist_lock);
5858 return retval;
5861 static const char stat_nam[] = "RSDTtZX";
5863 void sched_show_task(struct task_struct *p)
5865 unsigned long free = 0;
5866 unsigned state;
5868 state = p->state ? __ffs(p->state) + 1 : 0;
5869 printk(KERN_INFO "%-13.13s %c", p->comm,
5870 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5871 #if BITS_PER_LONG == 32
5872 if (state == TASK_RUNNING)
5873 printk(KERN_CONT " running ");
5874 else
5875 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5876 #else
5877 if (state == TASK_RUNNING)
5878 printk(KERN_CONT " running task ");
5879 else
5880 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5881 #endif
5882 #ifdef CONFIG_DEBUG_STACK_USAGE
5884 unsigned long *n = end_of_stack(p);
5885 while (!*n)
5886 n++;
5887 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5889 #endif
5890 printk(KERN_CONT "%5lu %5d %6d\n", free,
5891 task_pid_nr(p), task_pid_nr(p->real_parent));
5893 show_stack(p, NULL);
5896 void show_state_filter(unsigned long state_filter)
5898 struct task_struct *g, *p;
5900 #if BITS_PER_LONG == 32
5901 printk(KERN_INFO
5902 " task PC stack pid father\n");
5903 #else
5904 printk(KERN_INFO
5905 " task PC stack pid father\n");
5906 #endif
5907 read_lock(&tasklist_lock);
5908 do_each_thread(g, p) {
5910 * reset the NMI-timeout, listing all files on a slow
5911 * console might take alot of time:
5913 touch_nmi_watchdog();
5914 if (!state_filter || (p->state & state_filter))
5915 sched_show_task(p);
5916 } while_each_thread(g, p);
5918 touch_all_softlockup_watchdogs();
5920 #ifdef CONFIG_SCHED_DEBUG
5921 sysrq_sched_debug_show();
5922 #endif
5923 read_unlock(&tasklist_lock);
5925 * Only show locks if all tasks are dumped:
5927 if (state_filter == -1)
5928 debug_show_all_locks();
5931 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5933 idle->sched_class = &idle_sched_class;
5937 * init_idle - set up an idle thread for a given CPU
5938 * @idle: task in question
5939 * @cpu: cpu the idle task belongs to
5941 * NOTE: this function does not set the idle thread's NEED_RESCHED
5942 * flag, to make booting more robust.
5944 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5946 struct rq *rq = cpu_rq(cpu);
5947 unsigned long flags;
5949 __sched_fork(idle);
5950 idle->se.exec_start = sched_clock();
5952 idle->prio = idle->normal_prio = MAX_PRIO;
5953 idle->cpus_allowed = cpumask_of_cpu(cpu);
5954 __set_task_cpu(idle, cpu);
5956 spin_lock_irqsave(&rq->lock, flags);
5957 rq->curr = rq->idle = idle;
5958 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5959 idle->oncpu = 1;
5960 #endif
5961 spin_unlock_irqrestore(&rq->lock, flags);
5963 /* Set the preempt count _outside_ the spinlocks! */
5964 task_thread_info(idle)->preempt_count = 0;
5967 * The idle tasks have their own, simple scheduling class:
5969 idle->sched_class = &idle_sched_class;
5973 * In a system that switches off the HZ timer nohz_cpu_mask
5974 * indicates which cpus entered this state. This is used
5975 * in the rcu update to wait only for active cpus. For system
5976 * which do not switch off the HZ timer nohz_cpu_mask should
5977 * always be CPU_MASK_NONE.
5979 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5982 * Increase the granularity value when there are more CPUs,
5983 * because with more CPUs the 'effective latency' as visible
5984 * to users decreases. But the relationship is not linear,
5985 * so pick a second-best guess by going with the log2 of the
5986 * number of CPUs.
5988 * This idea comes from the SD scheduler of Con Kolivas:
5990 static inline void sched_init_granularity(void)
5992 unsigned int factor = 1 + ilog2(num_online_cpus());
5993 const unsigned long limit = 200000000;
5995 sysctl_sched_min_granularity *= factor;
5996 if (sysctl_sched_min_granularity > limit)
5997 sysctl_sched_min_granularity = limit;
5999 sysctl_sched_latency *= factor;
6000 if (sysctl_sched_latency > limit)
6001 sysctl_sched_latency = limit;
6003 sysctl_sched_wakeup_granularity *= factor;
6006 #ifdef CONFIG_SMP
6008 * This is how migration works:
6010 * 1) we queue a struct migration_req structure in the source CPU's
6011 * runqueue and wake up that CPU's migration thread.
6012 * 2) we down() the locked semaphore => thread blocks.
6013 * 3) migration thread wakes up (implicitly it forces the migrated
6014 * thread off the CPU)
6015 * 4) it gets the migration request and checks whether the migrated
6016 * task is still in the wrong runqueue.
6017 * 5) if it's in the wrong runqueue then the migration thread removes
6018 * it and puts it into the right queue.
6019 * 6) migration thread up()s the semaphore.
6020 * 7) we wake up and the migration is done.
6024 * Change a given task's CPU affinity. Migrate the thread to a
6025 * proper CPU and schedule it away if the CPU it's executing on
6026 * is removed from the allowed bitmask.
6028 * NOTE: the caller must have a valid reference to the task, the
6029 * task must not exit() & deallocate itself prematurely. The
6030 * call is not atomic; no spinlocks may be held.
6032 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
6034 struct migration_req req;
6035 unsigned long flags;
6036 struct rq *rq;
6037 int ret = 0;
6039 rq = task_rq_lock(p, &flags);
6040 if (!cpus_intersects(*new_mask, cpu_online_map)) {
6041 ret = -EINVAL;
6042 goto out;
6045 if (p->sched_class->set_cpus_allowed)
6046 p->sched_class->set_cpus_allowed(p, new_mask);
6047 else {
6048 p->cpus_allowed = *new_mask;
6049 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
6052 /* Can the task run on the task's current CPU? If so, we're done */
6053 if (cpu_isset(task_cpu(p), *new_mask))
6054 goto out;
6056 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
6057 /* Need help from migration thread: drop lock and wait. */
6058 task_rq_unlock(rq, &flags);
6059 wake_up_process(rq->migration_thread);
6060 wait_for_completion(&req.done);
6061 tlb_migrate_finish(p->mm);
6062 return 0;
6064 out:
6065 task_rq_unlock(rq, &flags);
6067 return ret;
6069 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6072 * Move (not current) task off this cpu, onto dest cpu. We're doing
6073 * this because either it can't run here any more (set_cpus_allowed()
6074 * away from this CPU, or CPU going down), or because we're
6075 * attempting to rebalance this task on exec (sched_exec).
6077 * So we race with normal scheduler movements, but that's OK, as long
6078 * as the task is no longer on this CPU.
6080 * Returns non-zero if task was successfully migrated.
6082 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6084 struct rq *rq_dest, *rq_src;
6085 int ret = 0, on_rq;
6087 if (unlikely(cpu_is_offline(dest_cpu)))
6088 return ret;
6090 rq_src = cpu_rq(src_cpu);
6091 rq_dest = cpu_rq(dest_cpu);
6093 double_rq_lock(rq_src, rq_dest);
6094 /* Already moved. */
6095 if (task_cpu(p) != src_cpu)
6096 goto out;
6097 /* Affinity changed (again). */
6098 if (!cpu_isset(dest_cpu, p->cpus_allowed))
6099 goto out;
6101 on_rq = p->se.on_rq;
6102 if (on_rq)
6103 deactivate_task(rq_src, p, 0);
6105 set_task_cpu(p, dest_cpu);
6106 if (on_rq) {
6107 activate_task(rq_dest, p, 0);
6108 check_preempt_curr(rq_dest, p);
6110 ret = 1;
6111 out:
6112 double_rq_unlock(rq_src, rq_dest);
6113 return ret;
6117 * migration_thread - this is a highprio system thread that performs
6118 * thread migration by bumping thread off CPU then 'pushing' onto
6119 * another runqueue.
6121 static int migration_thread(void *data)
6123 int cpu = (long)data;
6124 struct rq *rq;
6126 rq = cpu_rq(cpu);
6127 BUG_ON(rq->migration_thread != current);
6129 set_current_state(TASK_INTERRUPTIBLE);
6130 while (!kthread_should_stop()) {
6131 struct migration_req *req;
6132 struct list_head *head;
6134 spin_lock_irq(&rq->lock);
6136 if (cpu_is_offline(cpu)) {
6137 spin_unlock_irq(&rq->lock);
6138 goto wait_to_die;
6141 if (rq->active_balance) {
6142 active_load_balance(rq, cpu);
6143 rq->active_balance = 0;
6146 head = &rq->migration_queue;
6148 if (list_empty(head)) {
6149 spin_unlock_irq(&rq->lock);
6150 schedule();
6151 set_current_state(TASK_INTERRUPTIBLE);
6152 continue;
6154 req = list_entry(head->next, struct migration_req, list);
6155 list_del_init(head->next);
6157 spin_unlock(&rq->lock);
6158 __migrate_task(req->task, cpu, req->dest_cpu);
6159 local_irq_enable();
6161 complete(&req->done);
6163 __set_current_state(TASK_RUNNING);
6164 return 0;
6166 wait_to_die:
6167 /* Wait for kthread_stop */
6168 set_current_state(TASK_INTERRUPTIBLE);
6169 while (!kthread_should_stop()) {
6170 schedule();
6171 set_current_state(TASK_INTERRUPTIBLE);
6173 __set_current_state(TASK_RUNNING);
6174 return 0;
6177 #ifdef CONFIG_HOTPLUG_CPU
6179 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6181 int ret;
6183 local_irq_disable();
6184 ret = __migrate_task(p, src_cpu, dest_cpu);
6185 local_irq_enable();
6186 return ret;
6190 * Figure out where task on dead CPU should go, use force if necessary.
6191 * NOTE: interrupts should be disabled by the caller
6193 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6195 unsigned long flags;
6196 cpumask_t mask;
6197 struct rq *rq;
6198 int dest_cpu;
6200 do {
6201 /* On same node? */
6202 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6203 cpus_and(mask, mask, p->cpus_allowed);
6204 dest_cpu = any_online_cpu(mask);
6206 /* On any allowed CPU? */
6207 if (dest_cpu >= nr_cpu_ids)
6208 dest_cpu = any_online_cpu(p->cpus_allowed);
6210 /* No more Mr. Nice Guy. */
6211 if (dest_cpu >= nr_cpu_ids) {
6212 cpumask_t cpus_allowed;
6214 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6216 * Try to stay on the same cpuset, where the
6217 * current cpuset may be a subset of all cpus.
6218 * The cpuset_cpus_allowed_locked() variant of
6219 * cpuset_cpus_allowed() will not block. It must be
6220 * called within calls to cpuset_lock/cpuset_unlock.
6222 rq = task_rq_lock(p, &flags);
6223 p->cpus_allowed = cpus_allowed;
6224 dest_cpu = any_online_cpu(p->cpus_allowed);
6225 task_rq_unlock(rq, &flags);
6228 * Don't tell them about moving exiting tasks or
6229 * kernel threads (both mm NULL), since they never
6230 * leave kernel.
6232 if (p->mm && printk_ratelimit()) {
6233 printk(KERN_INFO "process %d (%s) no "
6234 "longer affine to cpu%d\n",
6235 task_pid_nr(p), p->comm, dead_cpu);
6238 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6242 * While a dead CPU has no uninterruptible tasks queued at this point,
6243 * it might still have a nonzero ->nr_uninterruptible counter, because
6244 * for performance reasons the counter is not stricly tracking tasks to
6245 * their home CPUs. So we just add the counter to another CPU's counter,
6246 * to keep the global sum constant after CPU-down:
6248 static void migrate_nr_uninterruptible(struct rq *rq_src)
6250 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6251 unsigned long flags;
6253 local_irq_save(flags);
6254 double_rq_lock(rq_src, rq_dest);
6255 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6256 rq_src->nr_uninterruptible = 0;
6257 double_rq_unlock(rq_src, rq_dest);
6258 local_irq_restore(flags);
6261 /* Run through task list and migrate tasks from the dead cpu. */
6262 static void migrate_live_tasks(int src_cpu)
6264 struct task_struct *p, *t;
6266 read_lock(&tasklist_lock);
6268 do_each_thread(t, p) {
6269 if (p == current)
6270 continue;
6272 if (task_cpu(p) == src_cpu)
6273 move_task_off_dead_cpu(src_cpu, p);
6274 } while_each_thread(t, p);
6276 read_unlock(&tasklist_lock);
6280 * Schedules idle task to be the next runnable task on current CPU.
6281 * It does so by boosting its priority to highest possible.
6282 * Used by CPU offline code.
6284 void sched_idle_next(void)
6286 int this_cpu = smp_processor_id();
6287 struct rq *rq = cpu_rq(this_cpu);
6288 struct task_struct *p = rq->idle;
6289 unsigned long flags;
6291 /* cpu has to be offline */
6292 BUG_ON(cpu_online(this_cpu));
6295 * Strictly not necessary since rest of the CPUs are stopped by now
6296 * and interrupts disabled on the current cpu.
6298 spin_lock_irqsave(&rq->lock, flags);
6300 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6302 update_rq_clock(rq);
6303 activate_task(rq, p, 0);
6305 spin_unlock_irqrestore(&rq->lock, flags);
6309 * Ensures that the idle task is using init_mm right before its cpu goes
6310 * offline.
6312 void idle_task_exit(void)
6314 struct mm_struct *mm = current->active_mm;
6316 BUG_ON(cpu_online(smp_processor_id()));
6318 if (mm != &init_mm)
6319 switch_mm(mm, &init_mm, current);
6320 mmdrop(mm);
6323 /* called under rq->lock with disabled interrupts */
6324 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6326 struct rq *rq = cpu_rq(dead_cpu);
6328 /* Must be exiting, otherwise would be on tasklist. */
6329 BUG_ON(!p->exit_state);
6331 /* Cannot have done final schedule yet: would have vanished. */
6332 BUG_ON(p->state == TASK_DEAD);
6334 get_task_struct(p);
6337 * Drop lock around migration; if someone else moves it,
6338 * that's OK. No task can be added to this CPU, so iteration is
6339 * fine.
6341 spin_unlock_irq(&rq->lock);
6342 move_task_off_dead_cpu(dead_cpu, p);
6343 spin_lock_irq(&rq->lock);
6345 put_task_struct(p);
6348 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6349 static void migrate_dead_tasks(unsigned int dead_cpu)
6351 struct rq *rq = cpu_rq(dead_cpu);
6352 struct task_struct *next;
6354 for ( ; ; ) {
6355 if (!rq->nr_running)
6356 break;
6357 update_rq_clock(rq);
6358 next = pick_next_task(rq, rq->curr);
6359 if (!next)
6360 break;
6361 migrate_dead(dead_cpu, next);
6365 #endif /* CONFIG_HOTPLUG_CPU */
6367 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6369 static struct ctl_table sd_ctl_dir[] = {
6371 .procname = "sched_domain",
6372 .mode = 0555,
6374 {0, },
6377 static struct ctl_table sd_ctl_root[] = {
6379 .ctl_name = CTL_KERN,
6380 .procname = "kernel",
6381 .mode = 0555,
6382 .child = sd_ctl_dir,
6384 {0, },
6387 static struct ctl_table *sd_alloc_ctl_entry(int n)
6389 struct ctl_table *entry =
6390 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6392 return entry;
6395 static void sd_free_ctl_entry(struct ctl_table **tablep)
6397 struct ctl_table *entry;
6400 * In the intermediate directories, both the child directory and
6401 * procname are dynamically allocated and could fail but the mode
6402 * will always be set. In the lowest directory the names are
6403 * static strings and all have proc handlers.
6405 for (entry = *tablep; entry->mode; entry++) {
6406 if (entry->child)
6407 sd_free_ctl_entry(&entry->child);
6408 if (entry->proc_handler == NULL)
6409 kfree(entry->procname);
6412 kfree(*tablep);
6413 *tablep = NULL;
6416 static void
6417 set_table_entry(struct ctl_table *entry,
6418 const char *procname, void *data, int maxlen,
6419 mode_t mode, proc_handler *proc_handler)
6421 entry->procname = procname;
6422 entry->data = data;
6423 entry->maxlen = maxlen;
6424 entry->mode = mode;
6425 entry->proc_handler = proc_handler;
6428 static struct ctl_table *
6429 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6431 struct ctl_table *table = sd_alloc_ctl_entry(12);
6433 if (table == NULL)
6434 return NULL;
6436 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6437 sizeof(long), 0644, proc_doulongvec_minmax);
6438 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6439 sizeof(long), 0644, proc_doulongvec_minmax);
6440 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6441 sizeof(int), 0644, proc_dointvec_minmax);
6442 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6443 sizeof(int), 0644, proc_dointvec_minmax);
6444 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6445 sizeof(int), 0644, proc_dointvec_minmax);
6446 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6447 sizeof(int), 0644, proc_dointvec_minmax);
6448 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6449 sizeof(int), 0644, proc_dointvec_minmax);
6450 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6451 sizeof(int), 0644, proc_dointvec_minmax);
6452 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6453 sizeof(int), 0644, proc_dointvec_minmax);
6454 set_table_entry(&table[9], "cache_nice_tries",
6455 &sd->cache_nice_tries,
6456 sizeof(int), 0644, proc_dointvec_minmax);
6457 set_table_entry(&table[10], "flags", &sd->flags,
6458 sizeof(int), 0644, proc_dointvec_minmax);
6459 /* &table[11] is terminator */
6461 return table;
6464 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6466 struct ctl_table *entry, *table;
6467 struct sched_domain *sd;
6468 int domain_num = 0, i;
6469 char buf[32];
6471 for_each_domain(cpu, sd)
6472 domain_num++;
6473 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6474 if (table == NULL)
6475 return NULL;
6477 i = 0;
6478 for_each_domain(cpu, sd) {
6479 snprintf(buf, 32, "domain%d", i);
6480 entry->procname = kstrdup(buf, GFP_KERNEL);
6481 entry->mode = 0555;
6482 entry->child = sd_alloc_ctl_domain_table(sd);
6483 entry++;
6484 i++;
6486 return table;
6489 static struct ctl_table_header *sd_sysctl_header;
6490 static void register_sched_domain_sysctl(void)
6492 int i, cpu_num = num_online_cpus();
6493 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6494 char buf[32];
6496 WARN_ON(sd_ctl_dir[0].child);
6497 sd_ctl_dir[0].child = entry;
6499 if (entry == NULL)
6500 return;
6502 for_each_online_cpu(i) {
6503 snprintf(buf, 32, "cpu%d", i);
6504 entry->procname = kstrdup(buf, GFP_KERNEL);
6505 entry->mode = 0555;
6506 entry->child = sd_alloc_ctl_cpu_table(i);
6507 entry++;
6510 WARN_ON(sd_sysctl_header);
6511 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6514 /* may be called multiple times per register */
6515 static void unregister_sched_domain_sysctl(void)
6517 if (sd_sysctl_header)
6518 unregister_sysctl_table(sd_sysctl_header);
6519 sd_sysctl_header = NULL;
6520 if (sd_ctl_dir[0].child)
6521 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6523 #else
6524 static void register_sched_domain_sysctl(void)
6527 static void unregister_sched_domain_sysctl(void)
6530 #endif
6533 * migration_call - callback that gets triggered when a CPU is added.
6534 * Here we can start up the necessary migration thread for the new CPU.
6536 static int __cpuinit
6537 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6539 struct task_struct *p;
6540 int cpu = (long)hcpu;
6541 unsigned long flags;
6542 struct rq *rq;
6544 switch (action) {
6546 case CPU_UP_PREPARE:
6547 case CPU_UP_PREPARE_FROZEN:
6548 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6549 if (IS_ERR(p))
6550 return NOTIFY_BAD;
6551 kthread_bind(p, cpu);
6552 /* Must be high prio: stop_machine expects to yield to it. */
6553 rq = task_rq_lock(p, &flags);
6554 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6555 task_rq_unlock(rq, &flags);
6556 cpu_rq(cpu)->migration_thread = p;
6557 break;
6559 case CPU_ONLINE:
6560 case CPU_ONLINE_FROZEN:
6561 /* Strictly unnecessary, as first user will wake it. */
6562 wake_up_process(cpu_rq(cpu)->migration_thread);
6564 /* Update our root-domain */
6565 rq = cpu_rq(cpu);
6566 spin_lock_irqsave(&rq->lock, flags);
6567 if (rq->rd) {
6568 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6569 cpu_set(cpu, rq->rd->online);
6571 spin_unlock_irqrestore(&rq->lock, flags);
6572 break;
6574 #ifdef CONFIG_HOTPLUG_CPU
6575 case CPU_UP_CANCELED:
6576 case CPU_UP_CANCELED_FROZEN:
6577 if (!cpu_rq(cpu)->migration_thread)
6578 break;
6579 /* Unbind it from offline cpu so it can run. Fall thru. */
6580 kthread_bind(cpu_rq(cpu)->migration_thread,
6581 any_online_cpu(cpu_online_map));
6582 kthread_stop(cpu_rq(cpu)->migration_thread);
6583 cpu_rq(cpu)->migration_thread = NULL;
6584 break;
6586 case CPU_DEAD:
6587 case CPU_DEAD_FROZEN:
6588 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6589 migrate_live_tasks(cpu);
6590 rq = cpu_rq(cpu);
6591 kthread_stop(rq->migration_thread);
6592 rq->migration_thread = NULL;
6593 /* Idle task back to normal (off runqueue, low prio) */
6594 spin_lock_irq(&rq->lock);
6595 update_rq_clock(rq);
6596 deactivate_task(rq, rq->idle, 0);
6597 rq->idle->static_prio = MAX_PRIO;
6598 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6599 rq->idle->sched_class = &idle_sched_class;
6600 migrate_dead_tasks(cpu);
6601 spin_unlock_irq(&rq->lock);
6602 cpuset_unlock();
6603 migrate_nr_uninterruptible(rq);
6604 BUG_ON(rq->nr_running != 0);
6607 * No need to migrate the tasks: it was best-effort if
6608 * they didn't take sched_hotcpu_mutex. Just wake up
6609 * the requestors.
6611 spin_lock_irq(&rq->lock);
6612 while (!list_empty(&rq->migration_queue)) {
6613 struct migration_req *req;
6615 req = list_entry(rq->migration_queue.next,
6616 struct migration_req, list);
6617 list_del_init(&req->list);
6618 complete(&req->done);
6620 spin_unlock_irq(&rq->lock);
6621 break;
6623 case CPU_DYING:
6624 case CPU_DYING_FROZEN:
6625 /* Update our root-domain */
6626 rq = cpu_rq(cpu);
6627 spin_lock_irqsave(&rq->lock, flags);
6628 if (rq->rd) {
6629 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6630 cpu_clear(cpu, rq->rd->online);
6632 spin_unlock_irqrestore(&rq->lock, flags);
6633 break;
6634 #endif
6636 return NOTIFY_OK;
6639 /* Register at highest priority so that task migration (migrate_all_tasks)
6640 * happens before everything else.
6642 static struct notifier_block __cpuinitdata migration_notifier = {
6643 .notifier_call = migration_call,
6644 .priority = 10
6647 void __init migration_init(void)
6649 void *cpu = (void *)(long)smp_processor_id();
6650 int err;
6652 /* Start one for the boot CPU: */
6653 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6654 BUG_ON(err == NOTIFY_BAD);
6655 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6656 register_cpu_notifier(&migration_notifier);
6658 #endif
6660 #ifdef CONFIG_SMP
6662 #ifdef CONFIG_SCHED_DEBUG
6664 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6665 cpumask_t *groupmask)
6667 struct sched_group *group = sd->groups;
6668 char str[256];
6670 cpulist_scnprintf(str, sizeof(str), sd->span);
6671 cpus_clear(*groupmask);
6673 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6675 if (!(sd->flags & SD_LOAD_BALANCE)) {
6676 printk("does not load-balance\n");
6677 if (sd->parent)
6678 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6679 " has parent");
6680 return -1;
6683 printk(KERN_CONT "span %s\n", str);
6685 if (!cpu_isset(cpu, sd->span)) {
6686 printk(KERN_ERR "ERROR: domain->span does not contain "
6687 "CPU%d\n", cpu);
6689 if (!cpu_isset(cpu, group->cpumask)) {
6690 printk(KERN_ERR "ERROR: domain->groups does not contain"
6691 " CPU%d\n", cpu);
6694 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6695 do {
6696 if (!group) {
6697 printk("\n");
6698 printk(KERN_ERR "ERROR: group is NULL\n");
6699 break;
6702 if (!group->__cpu_power) {
6703 printk(KERN_CONT "\n");
6704 printk(KERN_ERR "ERROR: domain->cpu_power not "
6705 "set\n");
6706 break;
6709 if (!cpus_weight(group->cpumask)) {
6710 printk(KERN_CONT "\n");
6711 printk(KERN_ERR "ERROR: empty group\n");
6712 break;
6715 if (cpus_intersects(*groupmask, group->cpumask)) {
6716 printk(KERN_CONT "\n");
6717 printk(KERN_ERR "ERROR: repeated CPUs\n");
6718 break;
6721 cpus_or(*groupmask, *groupmask, group->cpumask);
6723 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6724 printk(KERN_CONT " %s", str);
6726 group = group->next;
6727 } while (group != sd->groups);
6728 printk(KERN_CONT "\n");
6730 if (!cpus_equal(sd->span, *groupmask))
6731 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6733 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6734 printk(KERN_ERR "ERROR: parent span is not a superset "
6735 "of domain->span\n");
6736 return 0;
6739 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6741 cpumask_t *groupmask;
6742 int level = 0;
6744 if (!sd) {
6745 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6746 return;
6749 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6751 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6752 if (!groupmask) {
6753 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6754 return;
6757 for (;;) {
6758 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6759 break;
6760 level++;
6761 sd = sd->parent;
6762 if (!sd)
6763 break;
6765 kfree(groupmask);
6767 #else
6768 # define sched_domain_debug(sd, cpu) do { } while (0)
6769 #endif
6771 static int sd_degenerate(struct sched_domain *sd)
6773 if (cpus_weight(sd->span) == 1)
6774 return 1;
6776 /* Following flags need at least 2 groups */
6777 if (sd->flags & (SD_LOAD_BALANCE |
6778 SD_BALANCE_NEWIDLE |
6779 SD_BALANCE_FORK |
6780 SD_BALANCE_EXEC |
6781 SD_SHARE_CPUPOWER |
6782 SD_SHARE_PKG_RESOURCES)) {
6783 if (sd->groups != sd->groups->next)
6784 return 0;
6787 /* Following flags don't use groups */
6788 if (sd->flags & (SD_WAKE_IDLE |
6789 SD_WAKE_AFFINE |
6790 SD_WAKE_BALANCE))
6791 return 0;
6793 return 1;
6796 static int
6797 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6799 unsigned long cflags = sd->flags, pflags = parent->flags;
6801 if (sd_degenerate(parent))
6802 return 1;
6804 if (!cpus_equal(sd->span, parent->span))
6805 return 0;
6807 /* Does parent contain flags not in child? */
6808 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6809 if (cflags & SD_WAKE_AFFINE)
6810 pflags &= ~SD_WAKE_BALANCE;
6811 /* Flags needing groups don't count if only 1 group in parent */
6812 if (parent->groups == parent->groups->next) {
6813 pflags &= ~(SD_LOAD_BALANCE |
6814 SD_BALANCE_NEWIDLE |
6815 SD_BALANCE_FORK |
6816 SD_BALANCE_EXEC |
6817 SD_SHARE_CPUPOWER |
6818 SD_SHARE_PKG_RESOURCES);
6820 if (~cflags & pflags)
6821 return 0;
6823 return 1;
6826 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6828 unsigned long flags;
6829 const struct sched_class *class;
6831 spin_lock_irqsave(&rq->lock, flags);
6833 if (rq->rd) {
6834 struct root_domain *old_rd = rq->rd;
6836 for (class = sched_class_highest; class; class = class->next) {
6837 if (class->leave_domain)
6838 class->leave_domain(rq);
6841 cpu_clear(rq->cpu, old_rd->span);
6842 cpu_clear(rq->cpu, old_rd->online);
6844 if (atomic_dec_and_test(&old_rd->refcount))
6845 kfree(old_rd);
6848 atomic_inc(&rd->refcount);
6849 rq->rd = rd;
6851 cpu_set(rq->cpu, rd->span);
6852 if (cpu_isset(rq->cpu, cpu_online_map))
6853 cpu_set(rq->cpu, rd->online);
6855 for (class = sched_class_highest; class; class = class->next) {
6856 if (class->join_domain)
6857 class->join_domain(rq);
6860 spin_unlock_irqrestore(&rq->lock, flags);
6863 static void init_rootdomain(struct root_domain *rd)
6865 memset(rd, 0, sizeof(*rd));
6867 cpus_clear(rd->span);
6868 cpus_clear(rd->online);
6871 static void init_defrootdomain(void)
6873 init_rootdomain(&def_root_domain);
6874 atomic_set(&def_root_domain.refcount, 1);
6877 static struct root_domain *alloc_rootdomain(void)
6879 struct root_domain *rd;
6881 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6882 if (!rd)
6883 return NULL;
6885 init_rootdomain(rd);
6887 return rd;
6891 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6892 * hold the hotplug lock.
6894 static void
6895 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6897 struct rq *rq = cpu_rq(cpu);
6898 struct sched_domain *tmp;
6900 /* Remove the sched domains which do not contribute to scheduling. */
6901 for (tmp = sd; tmp; tmp = tmp->parent) {
6902 struct sched_domain *parent = tmp->parent;
6903 if (!parent)
6904 break;
6905 if (sd_parent_degenerate(tmp, parent)) {
6906 tmp->parent = parent->parent;
6907 if (parent->parent)
6908 parent->parent->child = tmp;
6912 if (sd && sd_degenerate(sd)) {
6913 sd = sd->parent;
6914 if (sd)
6915 sd->child = NULL;
6918 sched_domain_debug(sd, cpu);
6920 rq_attach_root(rq, rd);
6921 rcu_assign_pointer(rq->sd, sd);
6924 /* cpus with isolated domains */
6925 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6927 /* Setup the mask of cpus configured for isolated domains */
6928 static int __init isolated_cpu_setup(char *str)
6930 int ints[NR_CPUS], i;
6932 str = get_options(str, ARRAY_SIZE(ints), ints);
6933 cpus_clear(cpu_isolated_map);
6934 for (i = 1; i <= ints[0]; i++)
6935 if (ints[i] < NR_CPUS)
6936 cpu_set(ints[i], cpu_isolated_map);
6937 return 1;
6940 __setup("isolcpus=", isolated_cpu_setup);
6943 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6944 * to a function which identifies what group(along with sched group) a CPU
6945 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6946 * (due to the fact that we keep track of groups covered with a cpumask_t).
6948 * init_sched_build_groups will build a circular linked list of the groups
6949 * covered by the given span, and will set each group's ->cpumask correctly,
6950 * and ->cpu_power to 0.
6952 static void
6953 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6954 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6955 struct sched_group **sg,
6956 cpumask_t *tmpmask),
6957 cpumask_t *covered, cpumask_t *tmpmask)
6959 struct sched_group *first = NULL, *last = NULL;
6960 int i;
6962 cpus_clear(*covered);
6964 for_each_cpu_mask(i, *span) {
6965 struct sched_group *sg;
6966 int group = group_fn(i, cpu_map, &sg, tmpmask);
6967 int j;
6969 if (cpu_isset(i, *covered))
6970 continue;
6972 cpus_clear(sg->cpumask);
6973 sg->__cpu_power = 0;
6975 for_each_cpu_mask(j, *span) {
6976 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6977 continue;
6979 cpu_set(j, *covered);
6980 cpu_set(j, sg->cpumask);
6982 if (!first)
6983 first = sg;
6984 if (last)
6985 last->next = sg;
6986 last = sg;
6988 last->next = first;
6991 #define SD_NODES_PER_DOMAIN 16
6993 #ifdef CONFIG_NUMA
6996 * find_next_best_node - find the next node to include in a sched_domain
6997 * @node: node whose sched_domain we're building
6998 * @used_nodes: nodes already in the sched_domain
7000 * Find the next node to include in a given scheduling domain. Simply
7001 * finds the closest node not already in the @used_nodes map.
7003 * Should use nodemask_t.
7005 static int find_next_best_node(int node, nodemask_t *used_nodes)
7007 int i, n, val, min_val, best_node = 0;
7009 min_val = INT_MAX;
7011 for (i = 0; i < MAX_NUMNODES; i++) {
7012 /* Start at @node */
7013 n = (node + i) % MAX_NUMNODES;
7015 if (!nr_cpus_node(n))
7016 continue;
7018 /* Skip already used nodes */
7019 if (node_isset(n, *used_nodes))
7020 continue;
7022 /* Simple min distance search */
7023 val = node_distance(node, n);
7025 if (val < min_val) {
7026 min_val = val;
7027 best_node = n;
7031 node_set(best_node, *used_nodes);
7032 return best_node;
7036 * sched_domain_node_span - get a cpumask for a node's sched_domain
7037 * @node: node whose cpumask we're constructing
7038 * @span: resulting cpumask
7040 * Given a node, construct a good cpumask for its sched_domain to span. It
7041 * should be one that prevents unnecessary balancing, but also spreads tasks
7042 * out optimally.
7044 static void sched_domain_node_span(int node, cpumask_t *span)
7046 nodemask_t used_nodes;
7047 node_to_cpumask_ptr(nodemask, node);
7048 int i;
7050 cpus_clear(*span);
7051 nodes_clear(used_nodes);
7053 cpus_or(*span, *span, *nodemask);
7054 node_set(node, used_nodes);
7056 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7057 int next_node = find_next_best_node(node, &used_nodes);
7059 node_to_cpumask_ptr_next(nodemask, next_node);
7060 cpus_or(*span, *span, *nodemask);
7063 #endif
7065 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7068 * SMT sched-domains:
7070 #ifdef CONFIG_SCHED_SMT
7071 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
7072 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
7074 static int
7075 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7076 cpumask_t *unused)
7078 if (sg)
7079 *sg = &per_cpu(sched_group_cpus, cpu);
7080 return cpu;
7082 #endif
7085 * multi-core sched-domains:
7087 #ifdef CONFIG_SCHED_MC
7088 static DEFINE_PER_CPU(struct sched_domain, core_domains);
7089 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
7090 #endif
7092 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7093 static int
7094 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7095 cpumask_t *mask)
7097 int group;
7099 *mask = per_cpu(cpu_sibling_map, cpu);
7100 cpus_and(*mask, *mask, *cpu_map);
7101 group = first_cpu(*mask);
7102 if (sg)
7103 *sg = &per_cpu(sched_group_core, group);
7104 return group;
7106 #elif defined(CONFIG_SCHED_MC)
7107 static int
7108 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7109 cpumask_t *unused)
7111 if (sg)
7112 *sg = &per_cpu(sched_group_core, cpu);
7113 return cpu;
7115 #endif
7117 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7118 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7120 static int
7121 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7122 cpumask_t *mask)
7124 int group;
7125 #ifdef CONFIG_SCHED_MC
7126 *mask = cpu_coregroup_map(cpu);
7127 cpus_and(*mask, *mask, *cpu_map);
7128 group = first_cpu(*mask);
7129 #elif defined(CONFIG_SCHED_SMT)
7130 *mask = per_cpu(cpu_sibling_map, cpu);
7131 cpus_and(*mask, *mask, *cpu_map);
7132 group = first_cpu(*mask);
7133 #else
7134 group = cpu;
7135 #endif
7136 if (sg)
7137 *sg = &per_cpu(sched_group_phys, group);
7138 return group;
7141 #ifdef CONFIG_NUMA
7143 * The init_sched_build_groups can't handle what we want to do with node
7144 * groups, so roll our own. Now each node has its own list of groups which
7145 * gets dynamically allocated.
7147 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7148 static struct sched_group ***sched_group_nodes_bycpu;
7150 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7151 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7153 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7154 struct sched_group **sg, cpumask_t *nodemask)
7156 int group;
7158 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7159 cpus_and(*nodemask, *nodemask, *cpu_map);
7160 group = first_cpu(*nodemask);
7162 if (sg)
7163 *sg = &per_cpu(sched_group_allnodes, group);
7164 return group;
7167 static void init_numa_sched_groups_power(struct sched_group *group_head)
7169 struct sched_group *sg = group_head;
7170 int j;
7172 if (!sg)
7173 return;
7174 do {
7175 for_each_cpu_mask(j, sg->cpumask) {
7176 struct sched_domain *sd;
7178 sd = &per_cpu(phys_domains, j);
7179 if (j != first_cpu(sd->groups->cpumask)) {
7181 * Only add "power" once for each
7182 * physical package.
7184 continue;
7187 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7189 sg = sg->next;
7190 } while (sg != group_head);
7192 #endif
7194 #ifdef CONFIG_NUMA
7195 /* Free memory allocated for various sched_group structures */
7196 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7198 int cpu, i;
7200 for_each_cpu_mask(cpu, *cpu_map) {
7201 struct sched_group **sched_group_nodes
7202 = sched_group_nodes_bycpu[cpu];
7204 if (!sched_group_nodes)
7205 continue;
7207 for (i = 0; i < MAX_NUMNODES; i++) {
7208 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7210 *nodemask = node_to_cpumask(i);
7211 cpus_and(*nodemask, *nodemask, *cpu_map);
7212 if (cpus_empty(*nodemask))
7213 continue;
7215 if (sg == NULL)
7216 continue;
7217 sg = sg->next;
7218 next_sg:
7219 oldsg = sg;
7220 sg = sg->next;
7221 kfree(oldsg);
7222 if (oldsg != sched_group_nodes[i])
7223 goto next_sg;
7225 kfree(sched_group_nodes);
7226 sched_group_nodes_bycpu[cpu] = NULL;
7229 #else
7230 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7233 #endif
7236 * Initialize sched groups cpu_power.
7238 * cpu_power indicates the capacity of sched group, which is used while
7239 * distributing the load between different sched groups in a sched domain.
7240 * Typically cpu_power for all the groups in a sched domain will be same unless
7241 * there are asymmetries in the topology. If there are asymmetries, group
7242 * having more cpu_power will pickup more load compared to the group having
7243 * less cpu_power.
7245 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7246 * the maximum number of tasks a group can handle in the presence of other idle
7247 * or lightly loaded groups in the same sched domain.
7249 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7251 struct sched_domain *child;
7252 struct sched_group *group;
7254 WARN_ON(!sd || !sd->groups);
7256 if (cpu != first_cpu(sd->groups->cpumask))
7257 return;
7259 child = sd->child;
7261 sd->groups->__cpu_power = 0;
7264 * For perf policy, if the groups in child domain share resources
7265 * (for example cores sharing some portions of the cache hierarchy
7266 * or SMT), then set this domain groups cpu_power such that each group
7267 * can handle only one task, when there are other idle groups in the
7268 * same sched domain.
7270 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7271 (child->flags &
7272 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7273 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7274 return;
7278 * add cpu_power of each child group to this groups cpu_power
7280 group = child->groups;
7281 do {
7282 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7283 group = group->next;
7284 } while (group != child->groups);
7288 * Initializers for schedule domains
7289 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7292 #define SD_INIT(sd, type) sd_init_##type(sd)
7293 #define SD_INIT_FUNC(type) \
7294 static noinline void sd_init_##type(struct sched_domain *sd) \
7296 memset(sd, 0, sizeof(*sd)); \
7297 *sd = SD_##type##_INIT; \
7298 sd->level = SD_LV_##type; \
7301 SD_INIT_FUNC(CPU)
7302 #ifdef CONFIG_NUMA
7303 SD_INIT_FUNC(ALLNODES)
7304 SD_INIT_FUNC(NODE)
7305 #endif
7306 #ifdef CONFIG_SCHED_SMT
7307 SD_INIT_FUNC(SIBLING)
7308 #endif
7309 #ifdef CONFIG_SCHED_MC
7310 SD_INIT_FUNC(MC)
7311 #endif
7314 * To minimize stack usage kmalloc room for cpumasks and share the
7315 * space as the usage in build_sched_domains() dictates. Used only
7316 * if the amount of space is significant.
7318 struct allmasks {
7319 cpumask_t tmpmask; /* make this one first */
7320 union {
7321 cpumask_t nodemask;
7322 cpumask_t this_sibling_map;
7323 cpumask_t this_core_map;
7325 cpumask_t send_covered;
7327 #ifdef CONFIG_NUMA
7328 cpumask_t domainspan;
7329 cpumask_t covered;
7330 cpumask_t notcovered;
7331 #endif
7334 #if NR_CPUS > 128
7335 #define SCHED_CPUMASK_ALLOC 1
7336 #define SCHED_CPUMASK_FREE(v) kfree(v)
7337 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7338 #else
7339 #define SCHED_CPUMASK_ALLOC 0
7340 #define SCHED_CPUMASK_FREE(v)
7341 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7342 #endif
7344 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7345 ((unsigned long)(a) + offsetof(struct allmasks, v))
7347 static int default_relax_domain_level = -1;
7349 static int __init setup_relax_domain_level(char *str)
7351 default_relax_domain_level = simple_strtoul(str, NULL, 0);
7352 return 1;
7354 __setup("relax_domain_level=", setup_relax_domain_level);
7356 static void set_domain_attribute(struct sched_domain *sd,
7357 struct sched_domain_attr *attr)
7359 int request;
7361 if (!attr || attr->relax_domain_level < 0) {
7362 if (default_relax_domain_level < 0)
7363 return;
7364 else
7365 request = default_relax_domain_level;
7366 } else
7367 request = attr->relax_domain_level;
7368 if (request < sd->level) {
7369 /* turn off idle balance on this domain */
7370 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7371 } else {
7372 /* turn on idle balance on this domain */
7373 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7378 * Build sched domains for a given set of cpus and attach the sched domains
7379 * to the individual cpus
7381 static int __build_sched_domains(const cpumask_t *cpu_map,
7382 struct sched_domain_attr *attr)
7384 int i;
7385 struct root_domain *rd;
7386 SCHED_CPUMASK_DECLARE(allmasks);
7387 cpumask_t *tmpmask;
7388 #ifdef CONFIG_NUMA
7389 struct sched_group **sched_group_nodes = NULL;
7390 int sd_allnodes = 0;
7393 * Allocate the per-node list of sched groups
7395 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
7396 GFP_KERNEL);
7397 if (!sched_group_nodes) {
7398 printk(KERN_WARNING "Can not alloc sched group node list\n");
7399 return -ENOMEM;
7401 #endif
7403 rd = alloc_rootdomain();
7404 if (!rd) {
7405 printk(KERN_WARNING "Cannot alloc root domain\n");
7406 #ifdef CONFIG_NUMA
7407 kfree(sched_group_nodes);
7408 #endif
7409 return -ENOMEM;
7412 #if SCHED_CPUMASK_ALLOC
7413 /* get space for all scratch cpumask variables */
7414 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7415 if (!allmasks) {
7416 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7417 kfree(rd);
7418 #ifdef CONFIG_NUMA
7419 kfree(sched_group_nodes);
7420 #endif
7421 return -ENOMEM;
7423 #endif
7424 tmpmask = (cpumask_t *)allmasks;
7427 #ifdef CONFIG_NUMA
7428 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7429 #endif
7432 * Set up domains for cpus specified by the cpu_map.
7434 for_each_cpu_mask(i, *cpu_map) {
7435 struct sched_domain *sd = NULL, *p;
7436 SCHED_CPUMASK_VAR(nodemask, allmasks);
7438 *nodemask = node_to_cpumask(cpu_to_node(i));
7439 cpus_and(*nodemask, *nodemask, *cpu_map);
7441 #ifdef CONFIG_NUMA
7442 if (cpus_weight(*cpu_map) >
7443 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7444 sd = &per_cpu(allnodes_domains, i);
7445 SD_INIT(sd, ALLNODES);
7446 set_domain_attribute(sd, attr);
7447 sd->span = *cpu_map;
7448 sd->first_cpu = first_cpu(sd->span);
7449 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7450 p = sd;
7451 sd_allnodes = 1;
7452 } else
7453 p = NULL;
7455 sd = &per_cpu(node_domains, i);
7456 SD_INIT(sd, NODE);
7457 set_domain_attribute(sd, attr);
7458 sched_domain_node_span(cpu_to_node(i), &sd->span);
7459 sd->first_cpu = first_cpu(sd->span);
7460 sd->parent = p;
7461 if (p)
7462 p->child = sd;
7463 cpus_and(sd->span, sd->span, *cpu_map);
7464 #endif
7466 p = sd;
7467 sd = &per_cpu(phys_domains, i);
7468 SD_INIT(sd, CPU);
7469 set_domain_attribute(sd, attr);
7470 sd->span = *nodemask;
7471 sd->first_cpu = first_cpu(sd->span);
7472 sd->parent = p;
7473 if (p)
7474 p->child = sd;
7475 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7477 #ifdef CONFIG_SCHED_MC
7478 p = sd;
7479 sd = &per_cpu(core_domains, i);
7480 SD_INIT(sd, MC);
7481 set_domain_attribute(sd, attr);
7482 sd->span = cpu_coregroup_map(i);
7483 sd->first_cpu = first_cpu(sd->span);
7484 cpus_and(sd->span, sd->span, *cpu_map);
7485 sd->parent = p;
7486 p->child = sd;
7487 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7488 #endif
7490 #ifdef CONFIG_SCHED_SMT
7491 p = sd;
7492 sd = &per_cpu(cpu_domains, i);
7493 SD_INIT(sd, SIBLING);
7494 set_domain_attribute(sd, attr);
7495 sd->span = per_cpu(cpu_sibling_map, i);
7496 sd->first_cpu = first_cpu(sd->span);
7497 cpus_and(sd->span, sd->span, *cpu_map);
7498 sd->parent = p;
7499 p->child = sd;
7500 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7501 #endif
7504 #ifdef CONFIG_SCHED_SMT
7505 /* Set up CPU (sibling) groups */
7506 for_each_cpu_mask(i, *cpu_map) {
7507 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7508 SCHED_CPUMASK_VAR(send_covered, allmasks);
7510 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7511 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7512 if (i != first_cpu(*this_sibling_map))
7513 continue;
7515 init_sched_build_groups(this_sibling_map, cpu_map,
7516 &cpu_to_cpu_group,
7517 send_covered, tmpmask);
7519 #endif
7521 #ifdef CONFIG_SCHED_MC
7522 /* Set up multi-core groups */
7523 for_each_cpu_mask(i, *cpu_map) {
7524 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7525 SCHED_CPUMASK_VAR(send_covered, allmasks);
7527 *this_core_map = cpu_coregroup_map(i);
7528 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7529 if (i != first_cpu(*this_core_map))
7530 continue;
7532 init_sched_build_groups(this_core_map, cpu_map,
7533 &cpu_to_core_group,
7534 send_covered, tmpmask);
7536 #endif
7538 /* Set up physical groups */
7539 for (i = 0; i < MAX_NUMNODES; i++) {
7540 SCHED_CPUMASK_VAR(nodemask, allmasks);
7541 SCHED_CPUMASK_VAR(send_covered, allmasks);
7543 *nodemask = node_to_cpumask(i);
7544 cpus_and(*nodemask, *nodemask, *cpu_map);
7545 if (cpus_empty(*nodemask))
7546 continue;
7548 init_sched_build_groups(nodemask, cpu_map,
7549 &cpu_to_phys_group,
7550 send_covered, tmpmask);
7553 #ifdef CONFIG_NUMA
7554 /* Set up node groups */
7555 if (sd_allnodes) {
7556 SCHED_CPUMASK_VAR(send_covered, allmasks);
7558 init_sched_build_groups(cpu_map, cpu_map,
7559 &cpu_to_allnodes_group,
7560 send_covered, tmpmask);
7563 for (i = 0; i < MAX_NUMNODES; i++) {
7564 /* Set up node groups */
7565 struct sched_group *sg, *prev;
7566 SCHED_CPUMASK_VAR(nodemask, allmasks);
7567 SCHED_CPUMASK_VAR(domainspan, allmasks);
7568 SCHED_CPUMASK_VAR(covered, allmasks);
7569 int j;
7571 *nodemask = node_to_cpumask(i);
7572 cpus_clear(*covered);
7574 cpus_and(*nodemask, *nodemask, *cpu_map);
7575 if (cpus_empty(*nodemask)) {
7576 sched_group_nodes[i] = NULL;
7577 continue;
7580 sched_domain_node_span(i, domainspan);
7581 cpus_and(*domainspan, *domainspan, *cpu_map);
7583 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7584 if (!sg) {
7585 printk(KERN_WARNING "Can not alloc domain group for "
7586 "node %d\n", i);
7587 goto error;
7589 sched_group_nodes[i] = sg;
7590 for_each_cpu_mask(j, *nodemask) {
7591 struct sched_domain *sd;
7593 sd = &per_cpu(node_domains, j);
7594 sd->groups = sg;
7596 sg->__cpu_power = 0;
7597 sg->cpumask = *nodemask;
7598 sg->next = sg;
7599 cpus_or(*covered, *covered, *nodemask);
7600 prev = sg;
7602 for (j = 0; j < MAX_NUMNODES; j++) {
7603 SCHED_CPUMASK_VAR(notcovered, allmasks);
7604 int n = (i + j) % MAX_NUMNODES;
7605 node_to_cpumask_ptr(pnodemask, n);
7607 cpus_complement(*notcovered, *covered);
7608 cpus_and(*tmpmask, *notcovered, *cpu_map);
7609 cpus_and(*tmpmask, *tmpmask, *domainspan);
7610 if (cpus_empty(*tmpmask))
7611 break;
7613 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7614 if (cpus_empty(*tmpmask))
7615 continue;
7617 sg = kmalloc_node(sizeof(struct sched_group),
7618 GFP_KERNEL, i);
7619 if (!sg) {
7620 printk(KERN_WARNING
7621 "Can not alloc domain group for node %d\n", j);
7622 goto error;
7624 sg->__cpu_power = 0;
7625 sg->cpumask = *tmpmask;
7626 sg->next = prev->next;
7627 cpus_or(*covered, *covered, *tmpmask);
7628 prev->next = sg;
7629 prev = sg;
7632 #endif
7634 /* Calculate CPU power for physical packages and nodes */
7635 #ifdef CONFIG_SCHED_SMT
7636 for_each_cpu_mask(i, *cpu_map) {
7637 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7639 init_sched_groups_power(i, sd);
7641 #endif
7642 #ifdef CONFIG_SCHED_MC
7643 for_each_cpu_mask(i, *cpu_map) {
7644 struct sched_domain *sd = &per_cpu(core_domains, i);
7646 init_sched_groups_power(i, sd);
7648 #endif
7650 for_each_cpu_mask(i, *cpu_map) {
7651 struct sched_domain *sd = &per_cpu(phys_domains, i);
7653 init_sched_groups_power(i, sd);
7656 #ifdef CONFIG_NUMA
7657 for (i = 0; i < MAX_NUMNODES; i++)
7658 init_numa_sched_groups_power(sched_group_nodes[i]);
7660 if (sd_allnodes) {
7661 struct sched_group *sg;
7663 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7664 tmpmask);
7665 init_numa_sched_groups_power(sg);
7667 #endif
7669 /* Attach the domains */
7670 for_each_cpu_mask(i, *cpu_map) {
7671 struct sched_domain *sd;
7672 #ifdef CONFIG_SCHED_SMT
7673 sd = &per_cpu(cpu_domains, i);
7674 #elif defined(CONFIG_SCHED_MC)
7675 sd = &per_cpu(core_domains, i);
7676 #else
7677 sd = &per_cpu(phys_domains, i);
7678 #endif
7679 cpu_attach_domain(sd, rd, i);
7682 SCHED_CPUMASK_FREE((void *)allmasks);
7683 return 0;
7685 #ifdef CONFIG_NUMA
7686 error:
7687 free_sched_groups(cpu_map, tmpmask);
7688 SCHED_CPUMASK_FREE((void *)allmasks);
7689 return -ENOMEM;
7690 #endif
7693 static int build_sched_domains(const cpumask_t *cpu_map)
7695 return __build_sched_domains(cpu_map, NULL);
7698 static cpumask_t *doms_cur; /* current sched domains */
7699 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7700 static struct sched_domain_attr *dattr_cur; /* attribues of custom domains
7701 in 'doms_cur' */
7704 * Special case: If a kmalloc of a doms_cur partition (array of
7705 * cpumask_t) fails, then fallback to a single sched domain,
7706 * as determined by the single cpumask_t fallback_doms.
7708 static cpumask_t fallback_doms;
7710 void __attribute__((weak)) arch_update_cpu_topology(void)
7715 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7716 * For now this just excludes isolated cpus, but could be used to
7717 * exclude other special cases in the future.
7719 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7721 int err;
7723 arch_update_cpu_topology();
7724 ndoms_cur = 1;
7725 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7726 if (!doms_cur)
7727 doms_cur = &fallback_doms;
7728 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7729 dattr_cur = NULL;
7730 err = build_sched_domains(doms_cur);
7731 register_sched_domain_sysctl();
7733 return err;
7736 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7737 cpumask_t *tmpmask)
7739 free_sched_groups(cpu_map, tmpmask);
7743 * Detach sched domains from a group of cpus specified in cpu_map
7744 * These cpus will now be attached to the NULL domain
7746 static void detach_destroy_domains(const cpumask_t *cpu_map)
7748 cpumask_t tmpmask;
7749 int i;
7751 unregister_sched_domain_sysctl();
7753 for_each_cpu_mask(i, *cpu_map)
7754 cpu_attach_domain(NULL, &def_root_domain, i);
7755 synchronize_sched();
7756 arch_destroy_sched_domains(cpu_map, &tmpmask);
7759 /* handle null as "default" */
7760 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7761 struct sched_domain_attr *new, int idx_new)
7763 struct sched_domain_attr tmp;
7765 /* fast path */
7766 if (!new && !cur)
7767 return 1;
7769 tmp = SD_ATTR_INIT;
7770 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7771 new ? (new + idx_new) : &tmp,
7772 sizeof(struct sched_domain_attr));
7776 * Partition sched domains as specified by the 'ndoms_new'
7777 * cpumasks in the array doms_new[] of cpumasks. This compares
7778 * doms_new[] to the current sched domain partitioning, doms_cur[].
7779 * It destroys each deleted domain and builds each new domain.
7781 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7782 * The masks don't intersect (don't overlap.) We should setup one
7783 * sched domain for each mask. CPUs not in any of the cpumasks will
7784 * not be load balanced. If the same cpumask appears both in the
7785 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7786 * it as it is.
7788 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7789 * ownership of it and will kfree it when done with it. If the caller
7790 * failed the kmalloc call, then it can pass in doms_new == NULL,
7791 * and partition_sched_domains() will fallback to the single partition
7792 * 'fallback_doms'.
7794 * Call with hotplug lock held
7796 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7797 struct sched_domain_attr *dattr_new)
7799 int i, j;
7801 lock_doms_cur();
7803 /* always unregister in case we don't destroy any domains */
7804 unregister_sched_domain_sysctl();
7806 if (doms_new == NULL) {
7807 ndoms_new = 1;
7808 doms_new = &fallback_doms;
7809 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7810 dattr_new = NULL;
7813 /* Destroy deleted domains */
7814 for (i = 0; i < ndoms_cur; i++) {
7815 for (j = 0; j < ndoms_new; j++) {
7816 if (cpus_equal(doms_cur[i], doms_new[j])
7817 && dattrs_equal(dattr_cur, i, dattr_new, j))
7818 goto match1;
7820 /* no match - a current sched domain not in new doms_new[] */
7821 detach_destroy_domains(doms_cur + i);
7822 match1:
7826 /* Build new domains */
7827 for (i = 0; i < ndoms_new; i++) {
7828 for (j = 0; j < ndoms_cur; j++) {
7829 if (cpus_equal(doms_new[i], doms_cur[j])
7830 && dattrs_equal(dattr_new, i, dattr_cur, j))
7831 goto match2;
7833 /* no match - add a new doms_new */
7834 __build_sched_domains(doms_new + i,
7835 dattr_new ? dattr_new + i : NULL);
7836 match2:
7840 /* Remember the new sched domains */
7841 if (doms_cur != &fallback_doms)
7842 kfree(doms_cur);
7843 kfree(dattr_cur); /* kfree(NULL) is safe */
7844 doms_cur = doms_new;
7845 dattr_cur = dattr_new;
7846 ndoms_cur = ndoms_new;
7848 register_sched_domain_sysctl();
7850 unlock_doms_cur();
7853 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7854 int arch_reinit_sched_domains(void)
7856 int err;
7858 get_online_cpus();
7859 detach_destroy_domains(&cpu_online_map);
7860 err = arch_init_sched_domains(&cpu_online_map);
7861 put_online_cpus();
7863 return err;
7866 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7868 int ret;
7870 if (buf[0] != '0' && buf[0] != '1')
7871 return -EINVAL;
7873 if (smt)
7874 sched_smt_power_savings = (buf[0] == '1');
7875 else
7876 sched_mc_power_savings = (buf[0] == '1');
7878 ret = arch_reinit_sched_domains();
7880 return ret ? ret : count;
7883 #ifdef CONFIG_SCHED_MC
7884 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7886 return sprintf(page, "%u\n", sched_mc_power_savings);
7888 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7889 const char *buf, size_t count)
7891 return sched_power_savings_store(buf, count, 0);
7893 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7894 sched_mc_power_savings_store);
7895 #endif
7897 #ifdef CONFIG_SCHED_SMT
7898 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7900 return sprintf(page, "%u\n", sched_smt_power_savings);
7902 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7903 const char *buf, size_t count)
7905 return sched_power_savings_store(buf, count, 1);
7907 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7908 sched_smt_power_savings_store);
7909 #endif
7911 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7913 int err = 0;
7915 #ifdef CONFIG_SCHED_SMT
7916 if (smt_capable())
7917 err = sysfs_create_file(&cls->kset.kobj,
7918 &attr_sched_smt_power_savings.attr);
7919 #endif
7920 #ifdef CONFIG_SCHED_MC
7921 if (!err && mc_capable())
7922 err = sysfs_create_file(&cls->kset.kobj,
7923 &attr_sched_mc_power_savings.attr);
7924 #endif
7925 return err;
7927 #endif
7930 * Force a reinitialization of the sched domains hierarchy. The domains
7931 * and groups cannot be updated in place without racing with the balancing
7932 * code, so we temporarily attach all running cpus to the NULL domain
7933 * which will prevent rebalancing while the sched domains are recalculated.
7935 static int update_sched_domains(struct notifier_block *nfb,
7936 unsigned long action, void *hcpu)
7938 switch (action) {
7939 case CPU_UP_PREPARE:
7940 case CPU_UP_PREPARE_FROZEN:
7941 case CPU_DOWN_PREPARE:
7942 case CPU_DOWN_PREPARE_FROZEN:
7943 detach_destroy_domains(&cpu_online_map);
7944 return NOTIFY_OK;
7946 case CPU_UP_CANCELED:
7947 case CPU_UP_CANCELED_FROZEN:
7948 case CPU_DOWN_FAILED:
7949 case CPU_DOWN_FAILED_FROZEN:
7950 case CPU_ONLINE:
7951 case CPU_ONLINE_FROZEN:
7952 case CPU_DEAD:
7953 case CPU_DEAD_FROZEN:
7955 * Fall through and re-initialise the domains.
7957 break;
7958 default:
7959 return NOTIFY_DONE;
7962 /* The hotplug lock is already held by cpu_up/cpu_down */
7963 arch_init_sched_domains(&cpu_online_map);
7965 return NOTIFY_OK;
7968 void __init sched_init_smp(void)
7970 cpumask_t non_isolated_cpus;
7972 #if defined(CONFIG_NUMA)
7973 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7974 GFP_KERNEL);
7975 BUG_ON(sched_group_nodes_bycpu == NULL);
7976 #endif
7977 get_online_cpus();
7978 arch_init_sched_domains(&cpu_online_map);
7979 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7980 if (cpus_empty(non_isolated_cpus))
7981 cpu_set(smp_processor_id(), non_isolated_cpus);
7982 put_online_cpus();
7983 /* XXX: Theoretical race here - CPU may be hotplugged now */
7984 hotcpu_notifier(update_sched_domains, 0);
7986 /* Move init over to a non-isolated CPU */
7987 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
7988 BUG();
7989 sched_init_granularity();
7991 #else
7992 void __init sched_init_smp(void)
7994 #if defined(CONFIG_NUMA)
7995 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7996 GFP_KERNEL);
7997 BUG_ON(sched_group_nodes_bycpu == NULL);
7998 #endif
7999 sched_init_granularity();
8001 #endif /* CONFIG_SMP */
8003 int in_sched_functions(unsigned long addr)
8005 return in_lock_functions(addr) ||
8006 (addr >= (unsigned long)__sched_text_start
8007 && addr < (unsigned long)__sched_text_end);
8010 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8012 cfs_rq->tasks_timeline = RB_ROOT;
8013 INIT_LIST_HEAD(&cfs_rq->tasks);
8014 #ifdef CONFIG_FAIR_GROUP_SCHED
8015 cfs_rq->rq = rq;
8016 #endif
8017 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8020 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8022 struct rt_prio_array *array;
8023 int i;
8025 array = &rt_rq->active;
8026 for (i = 0; i < MAX_RT_PRIO; i++) {
8027 INIT_LIST_HEAD(array->queue + i);
8028 __clear_bit(i, array->bitmap);
8030 /* delimiter for bitsearch: */
8031 __set_bit(MAX_RT_PRIO, array->bitmap);
8033 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8034 rt_rq->highest_prio = MAX_RT_PRIO;
8035 #endif
8036 #ifdef CONFIG_SMP
8037 rt_rq->rt_nr_migratory = 0;
8038 rt_rq->overloaded = 0;
8039 #endif
8041 rt_rq->rt_time = 0;
8042 rt_rq->rt_throttled = 0;
8043 rt_rq->rt_runtime = 0;
8044 spin_lock_init(&rt_rq->rt_runtime_lock);
8046 #ifdef CONFIG_RT_GROUP_SCHED
8047 rt_rq->rt_nr_boosted = 0;
8048 rt_rq->rq = rq;
8049 #endif
8052 #ifdef CONFIG_FAIR_GROUP_SCHED
8053 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8054 struct sched_entity *se, int cpu, int add,
8055 struct sched_entity *parent)
8057 struct rq *rq = cpu_rq(cpu);
8058 tg->cfs_rq[cpu] = cfs_rq;
8059 init_cfs_rq(cfs_rq, rq);
8060 cfs_rq->tg = tg;
8061 if (add)
8062 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8064 tg->se[cpu] = se;
8065 /* se could be NULL for init_task_group */
8066 if (!se)
8067 return;
8069 if (!parent)
8070 se->cfs_rq = &rq->cfs;
8071 else
8072 se->cfs_rq = parent->my_q;
8074 se->my_q = cfs_rq;
8075 se->load.weight = tg->shares;
8076 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
8077 se->parent = parent;
8079 #endif
8081 #ifdef CONFIG_RT_GROUP_SCHED
8082 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8083 struct sched_rt_entity *rt_se, int cpu, int add,
8084 struct sched_rt_entity *parent)
8086 struct rq *rq = cpu_rq(cpu);
8088 tg->rt_rq[cpu] = rt_rq;
8089 init_rt_rq(rt_rq, rq);
8090 rt_rq->tg = tg;
8091 rt_rq->rt_se = rt_se;
8092 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8093 if (add)
8094 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8096 tg->rt_se[cpu] = rt_se;
8097 if (!rt_se)
8098 return;
8100 if (!parent)
8101 rt_se->rt_rq = &rq->rt;
8102 else
8103 rt_se->rt_rq = parent->my_q;
8105 rt_se->rt_rq = &rq->rt;
8106 rt_se->my_q = rt_rq;
8107 rt_se->parent = parent;
8108 INIT_LIST_HEAD(&rt_se->run_list);
8110 #endif
8112 void __init sched_init(void)
8114 int i, j;
8115 unsigned long alloc_size = 0, ptr;
8117 #ifdef CONFIG_FAIR_GROUP_SCHED
8118 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8119 #endif
8120 #ifdef CONFIG_RT_GROUP_SCHED
8121 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8122 #endif
8123 #ifdef CONFIG_USER_SCHED
8124 alloc_size *= 2;
8125 #endif
8127 * As sched_init() is called before page_alloc is setup,
8128 * we use alloc_bootmem().
8130 if (alloc_size) {
8131 ptr = (unsigned long)alloc_bootmem_low(alloc_size);
8133 #ifdef CONFIG_FAIR_GROUP_SCHED
8134 init_task_group.se = (struct sched_entity **)ptr;
8135 ptr += nr_cpu_ids * sizeof(void **);
8137 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8138 ptr += nr_cpu_ids * sizeof(void **);
8140 #ifdef CONFIG_USER_SCHED
8141 root_task_group.se = (struct sched_entity **)ptr;
8142 ptr += nr_cpu_ids * sizeof(void **);
8144 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8145 ptr += nr_cpu_ids * sizeof(void **);
8146 #endif
8147 #endif
8148 #ifdef CONFIG_RT_GROUP_SCHED
8149 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8150 ptr += nr_cpu_ids * sizeof(void **);
8152 init_task_group.rt_rq = (struct rt_rq **)ptr;
8153 ptr += nr_cpu_ids * sizeof(void **);
8155 #ifdef CONFIG_USER_SCHED
8156 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8157 ptr += nr_cpu_ids * sizeof(void **);
8159 root_task_group.rt_rq = (struct rt_rq **)ptr;
8160 ptr += nr_cpu_ids * sizeof(void **);
8161 #endif
8162 #endif
8165 #ifdef CONFIG_SMP
8166 init_aggregate();
8167 init_defrootdomain();
8168 #endif
8170 init_rt_bandwidth(&def_rt_bandwidth,
8171 global_rt_period(), global_rt_runtime());
8173 #ifdef CONFIG_RT_GROUP_SCHED
8174 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8175 global_rt_period(), global_rt_runtime());
8176 #ifdef CONFIG_USER_SCHED
8177 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8178 global_rt_period(), RUNTIME_INF);
8179 #endif
8180 #endif
8182 #ifdef CONFIG_GROUP_SCHED
8183 list_add(&init_task_group.list, &task_groups);
8184 INIT_LIST_HEAD(&init_task_group.children);
8186 #ifdef CONFIG_USER_SCHED
8187 INIT_LIST_HEAD(&root_task_group.children);
8188 init_task_group.parent = &root_task_group;
8189 list_add(&init_task_group.siblings, &root_task_group.children);
8190 #endif
8191 #endif
8193 for_each_possible_cpu(i) {
8194 struct rq *rq;
8196 rq = cpu_rq(i);
8197 spin_lock_init(&rq->lock);
8198 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
8199 rq->nr_running = 0;
8200 rq->clock = 1;
8201 update_last_tick_seen(rq);
8202 init_cfs_rq(&rq->cfs, rq);
8203 init_rt_rq(&rq->rt, rq);
8204 #ifdef CONFIG_FAIR_GROUP_SCHED
8205 init_task_group.shares = init_task_group_load;
8206 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8207 #ifdef CONFIG_CGROUP_SCHED
8209 * How much cpu bandwidth does init_task_group get?
8211 * In case of task-groups formed thr' the cgroup filesystem, it
8212 * gets 100% of the cpu resources in the system. This overall
8213 * system cpu resource is divided among the tasks of
8214 * init_task_group and its child task-groups in a fair manner,
8215 * based on each entity's (task or task-group's) weight
8216 * (se->load.weight).
8218 * In other words, if init_task_group has 10 tasks of weight
8219 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8220 * then A0's share of the cpu resource is:
8222 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8224 * We achieve this by letting init_task_group's tasks sit
8225 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8227 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8228 #elif defined CONFIG_USER_SCHED
8229 root_task_group.shares = NICE_0_LOAD;
8230 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8232 * In case of task-groups formed thr' the user id of tasks,
8233 * init_task_group represents tasks belonging to root user.
8234 * Hence it forms a sibling of all subsequent groups formed.
8235 * In this case, init_task_group gets only a fraction of overall
8236 * system cpu resource, based on the weight assigned to root
8237 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8238 * by letting tasks of init_task_group sit in a separate cfs_rq
8239 * (init_cfs_rq) and having one entity represent this group of
8240 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8242 init_tg_cfs_entry(&init_task_group,
8243 &per_cpu(init_cfs_rq, i),
8244 &per_cpu(init_sched_entity, i), i, 1,
8245 root_task_group.se[i]);
8247 #endif
8248 #endif /* CONFIG_FAIR_GROUP_SCHED */
8250 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8251 #ifdef CONFIG_RT_GROUP_SCHED
8252 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8253 #ifdef CONFIG_CGROUP_SCHED
8254 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8255 #elif defined CONFIG_USER_SCHED
8256 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8257 init_tg_rt_entry(&init_task_group,
8258 &per_cpu(init_rt_rq, i),
8259 &per_cpu(init_sched_rt_entity, i), i, 1,
8260 root_task_group.rt_se[i]);
8261 #endif
8262 #endif
8264 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8265 rq->cpu_load[j] = 0;
8266 #ifdef CONFIG_SMP
8267 rq->sd = NULL;
8268 rq->rd = NULL;
8269 rq->active_balance = 0;
8270 rq->next_balance = jiffies;
8271 rq->push_cpu = 0;
8272 rq->cpu = i;
8273 rq->migration_thread = NULL;
8274 INIT_LIST_HEAD(&rq->migration_queue);
8275 rq_attach_root(rq, &def_root_domain);
8276 #endif
8277 init_rq_hrtick(rq);
8278 atomic_set(&rq->nr_iowait, 0);
8281 set_load_weight(&init_task);
8283 #ifdef CONFIG_PREEMPT_NOTIFIERS
8284 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8285 #endif
8287 #ifdef CONFIG_SMP
8288 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
8289 #endif
8291 #ifdef CONFIG_RT_MUTEXES
8292 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8293 #endif
8296 * The boot idle thread does lazy MMU switching as well:
8298 atomic_inc(&init_mm.mm_count);
8299 enter_lazy_tlb(&init_mm, current);
8302 * Make us the idle thread. Technically, schedule() should not be
8303 * called from this thread, however somewhere below it might be,
8304 * but because we are the idle thread, we just pick up running again
8305 * when this runqueue becomes "idle".
8307 init_idle(current, smp_processor_id());
8309 * During early bootup we pretend to be a normal task:
8311 current->sched_class = &fair_sched_class;
8313 scheduler_running = 1;
8316 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8317 void __might_sleep(char *file, int line)
8319 #ifdef in_atomic
8320 static unsigned long prev_jiffy; /* ratelimiting */
8322 if ((in_atomic() || irqs_disabled()) &&
8323 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8324 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8325 return;
8326 prev_jiffy = jiffies;
8327 printk(KERN_ERR "BUG: sleeping function called from invalid"
8328 " context at %s:%d\n", file, line);
8329 printk("in_atomic():%d, irqs_disabled():%d\n",
8330 in_atomic(), irqs_disabled());
8331 debug_show_held_locks(current);
8332 if (irqs_disabled())
8333 print_irqtrace_events(current);
8334 dump_stack();
8336 #endif
8338 EXPORT_SYMBOL(__might_sleep);
8339 #endif
8341 #ifdef CONFIG_MAGIC_SYSRQ
8342 static void normalize_task(struct rq *rq, struct task_struct *p)
8344 int on_rq;
8345 update_rq_clock(rq);
8346 on_rq = p->se.on_rq;
8347 if (on_rq)
8348 deactivate_task(rq, p, 0);
8349 __setscheduler(rq, p, SCHED_NORMAL, 0);
8350 if (on_rq) {
8351 activate_task(rq, p, 0);
8352 resched_task(rq->curr);
8356 void normalize_rt_tasks(void)
8358 struct task_struct *g, *p;
8359 unsigned long flags;
8360 struct rq *rq;
8362 read_lock_irqsave(&tasklist_lock, flags);
8363 do_each_thread(g, p) {
8365 * Only normalize user tasks:
8367 if (!p->mm)
8368 continue;
8370 p->se.exec_start = 0;
8371 #ifdef CONFIG_SCHEDSTATS
8372 p->se.wait_start = 0;
8373 p->se.sleep_start = 0;
8374 p->se.block_start = 0;
8375 #endif
8376 task_rq(p)->clock = 0;
8378 if (!rt_task(p)) {
8380 * Renice negative nice level userspace
8381 * tasks back to 0:
8383 if (TASK_NICE(p) < 0 && p->mm)
8384 set_user_nice(p, 0);
8385 continue;
8388 spin_lock(&p->pi_lock);
8389 rq = __task_rq_lock(p);
8391 normalize_task(rq, p);
8393 __task_rq_unlock(rq);
8394 spin_unlock(&p->pi_lock);
8395 } while_each_thread(g, p);
8397 read_unlock_irqrestore(&tasklist_lock, flags);
8400 #endif /* CONFIG_MAGIC_SYSRQ */
8402 #ifdef CONFIG_IA64
8404 * These functions are only useful for the IA64 MCA handling.
8406 * They can only be called when the whole system has been
8407 * stopped - every CPU needs to be quiescent, and no scheduling
8408 * activity can take place. Using them for anything else would
8409 * be a serious bug, and as a result, they aren't even visible
8410 * under any other configuration.
8414 * curr_task - return the current task for a given cpu.
8415 * @cpu: the processor in question.
8417 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8419 struct task_struct *curr_task(int cpu)
8421 return cpu_curr(cpu);
8425 * set_curr_task - set the current task for a given cpu.
8426 * @cpu: the processor in question.
8427 * @p: the task pointer to set.
8429 * Description: This function must only be used when non-maskable interrupts
8430 * are serviced on a separate stack. It allows the architecture to switch the
8431 * notion of the current task on a cpu in a non-blocking manner. This function
8432 * must be called with all CPU's synchronized, and interrupts disabled, the
8433 * and caller must save the original value of the current task (see
8434 * curr_task() above) and restore that value before reenabling interrupts and
8435 * re-starting the system.
8437 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8439 void set_curr_task(int cpu, struct task_struct *p)
8441 cpu_curr(cpu) = p;
8444 #endif
8446 #ifdef CONFIG_FAIR_GROUP_SCHED
8447 static void free_fair_sched_group(struct task_group *tg)
8449 int i;
8451 for_each_possible_cpu(i) {
8452 if (tg->cfs_rq)
8453 kfree(tg->cfs_rq[i]);
8454 if (tg->se)
8455 kfree(tg->se[i]);
8458 kfree(tg->cfs_rq);
8459 kfree(tg->se);
8462 static
8463 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8465 struct cfs_rq *cfs_rq;
8466 struct sched_entity *se, *parent_se;
8467 struct rq *rq;
8468 int i;
8470 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8471 if (!tg->cfs_rq)
8472 goto err;
8473 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8474 if (!tg->se)
8475 goto err;
8477 tg->shares = NICE_0_LOAD;
8479 for_each_possible_cpu(i) {
8480 rq = cpu_rq(i);
8482 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8483 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8484 if (!cfs_rq)
8485 goto err;
8487 se = kmalloc_node(sizeof(struct sched_entity),
8488 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8489 if (!se)
8490 goto err;
8492 parent_se = parent ? parent->se[i] : NULL;
8493 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8496 return 1;
8498 err:
8499 return 0;
8502 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8504 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8505 &cpu_rq(cpu)->leaf_cfs_rq_list);
8508 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8510 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8512 #else
8513 static inline void free_fair_sched_group(struct task_group *tg)
8517 static inline
8518 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8520 return 1;
8523 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8527 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8530 #endif
8532 #ifdef CONFIG_RT_GROUP_SCHED
8533 static void free_rt_sched_group(struct task_group *tg)
8535 int i;
8537 destroy_rt_bandwidth(&tg->rt_bandwidth);
8539 for_each_possible_cpu(i) {
8540 if (tg->rt_rq)
8541 kfree(tg->rt_rq[i]);
8542 if (tg->rt_se)
8543 kfree(tg->rt_se[i]);
8546 kfree(tg->rt_rq);
8547 kfree(tg->rt_se);
8550 static
8551 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8553 struct rt_rq *rt_rq;
8554 struct sched_rt_entity *rt_se, *parent_se;
8555 struct rq *rq;
8556 int i;
8558 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8559 if (!tg->rt_rq)
8560 goto err;
8561 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8562 if (!tg->rt_se)
8563 goto err;
8565 init_rt_bandwidth(&tg->rt_bandwidth,
8566 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8568 for_each_possible_cpu(i) {
8569 rq = cpu_rq(i);
8571 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8572 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8573 if (!rt_rq)
8574 goto err;
8576 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8577 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8578 if (!rt_se)
8579 goto err;
8581 parent_se = parent ? parent->rt_se[i] : NULL;
8582 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8585 return 1;
8587 err:
8588 return 0;
8591 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8593 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8594 &cpu_rq(cpu)->leaf_rt_rq_list);
8597 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8599 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8601 #else
8602 static inline void free_rt_sched_group(struct task_group *tg)
8606 static inline
8607 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8609 return 1;
8612 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8616 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8619 #endif
8621 #ifdef CONFIG_GROUP_SCHED
8622 static void free_sched_group(struct task_group *tg)
8624 free_fair_sched_group(tg);
8625 free_rt_sched_group(tg);
8626 kfree(tg);
8629 /* allocate runqueue etc for a new task group */
8630 struct task_group *sched_create_group(struct task_group *parent)
8632 struct task_group *tg;
8633 unsigned long flags;
8634 int i;
8636 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8637 if (!tg)
8638 return ERR_PTR(-ENOMEM);
8640 if (!alloc_fair_sched_group(tg, parent))
8641 goto err;
8643 if (!alloc_rt_sched_group(tg, parent))
8644 goto err;
8646 spin_lock_irqsave(&task_group_lock, flags);
8647 for_each_possible_cpu(i) {
8648 register_fair_sched_group(tg, i);
8649 register_rt_sched_group(tg, i);
8651 list_add_rcu(&tg->list, &task_groups);
8653 WARN_ON(!parent); /* root should already exist */
8655 tg->parent = parent;
8656 list_add_rcu(&tg->siblings, &parent->children);
8657 INIT_LIST_HEAD(&tg->children);
8658 spin_unlock_irqrestore(&task_group_lock, flags);
8660 return tg;
8662 err:
8663 free_sched_group(tg);
8664 return ERR_PTR(-ENOMEM);
8667 /* rcu callback to free various structures associated with a task group */
8668 static void free_sched_group_rcu(struct rcu_head *rhp)
8670 /* now it should be safe to free those cfs_rqs */
8671 free_sched_group(container_of(rhp, struct task_group, rcu));
8674 /* Destroy runqueue etc associated with a task group */
8675 void sched_destroy_group(struct task_group *tg)
8677 unsigned long flags;
8678 int i;
8680 spin_lock_irqsave(&task_group_lock, flags);
8681 for_each_possible_cpu(i) {
8682 unregister_fair_sched_group(tg, i);
8683 unregister_rt_sched_group(tg, i);
8685 list_del_rcu(&tg->list);
8686 list_del_rcu(&tg->siblings);
8687 spin_unlock_irqrestore(&task_group_lock, flags);
8689 /* wait for possible concurrent references to cfs_rqs complete */
8690 call_rcu(&tg->rcu, free_sched_group_rcu);
8693 /* change task's runqueue when it moves between groups.
8694 * The caller of this function should have put the task in its new group
8695 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8696 * reflect its new group.
8698 void sched_move_task(struct task_struct *tsk)
8700 int on_rq, running;
8701 unsigned long flags;
8702 struct rq *rq;
8704 rq = task_rq_lock(tsk, &flags);
8706 update_rq_clock(rq);
8708 running = task_current(rq, tsk);
8709 on_rq = tsk->se.on_rq;
8711 if (on_rq)
8712 dequeue_task(rq, tsk, 0);
8713 if (unlikely(running))
8714 tsk->sched_class->put_prev_task(rq, tsk);
8716 set_task_rq(tsk, task_cpu(tsk));
8718 #ifdef CONFIG_FAIR_GROUP_SCHED
8719 if (tsk->sched_class->moved_group)
8720 tsk->sched_class->moved_group(tsk);
8721 #endif
8723 if (unlikely(running))
8724 tsk->sched_class->set_curr_task(rq);
8725 if (on_rq)
8726 enqueue_task(rq, tsk, 0);
8728 task_rq_unlock(rq, &flags);
8730 #endif
8732 #ifdef CONFIG_FAIR_GROUP_SCHED
8733 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8735 struct cfs_rq *cfs_rq = se->cfs_rq;
8736 int on_rq;
8738 on_rq = se->on_rq;
8739 if (on_rq)
8740 dequeue_entity(cfs_rq, se, 0);
8742 se->load.weight = shares;
8743 se->load.inv_weight = div64_64((1ULL<<32), shares);
8745 if (on_rq)
8746 enqueue_entity(cfs_rq, se, 0);
8749 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8751 struct cfs_rq *cfs_rq = se->cfs_rq;
8752 struct rq *rq = cfs_rq->rq;
8753 unsigned long flags;
8755 spin_lock_irqsave(&rq->lock, flags);
8756 __set_se_shares(se, shares);
8757 spin_unlock_irqrestore(&rq->lock, flags);
8760 static DEFINE_MUTEX(shares_mutex);
8762 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8764 int i;
8765 unsigned long flags;
8768 * We can't change the weight of the root cgroup.
8770 if (!tg->se[0])
8771 return -EINVAL;
8774 * A weight of 0 or 1 can cause arithmetics problems.
8775 * (The default weight is 1024 - so there's no practical
8776 * limitation from this.)
8778 if (shares < MIN_SHARES)
8779 shares = MIN_SHARES;
8781 mutex_lock(&shares_mutex);
8782 if (tg->shares == shares)
8783 goto done;
8785 spin_lock_irqsave(&task_group_lock, flags);
8786 for_each_possible_cpu(i)
8787 unregister_fair_sched_group(tg, i);
8788 list_del_rcu(&tg->siblings);
8789 spin_unlock_irqrestore(&task_group_lock, flags);
8791 /* wait for any ongoing reference to this group to finish */
8792 synchronize_sched();
8795 * Now we are free to modify the group's share on each cpu
8796 * w/o tripping rebalance_share or load_balance_fair.
8798 tg->shares = shares;
8799 for_each_possible_cpu(i) {
8801 * force a rebalance
8803 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8804 set_se_shares(tg->se[i], shares/nr_cpu_ids);
8808 * Enable load balance activity on this group, by inserting it back on
8809 * each cpu's rq->leaf_cfs_rq_list.
8811 spin_lock_irqsave(&task_group_lock, flags);
8812 for_each_possible_cpu(i)
8813 register_fair_sched_group(tg, i);
8814 list_add_rcu(&tg->siblings, &tg->parent->children);
8815 spin_unlock_irqrestore(&task_group_lock, flags);
8816 done:
8817 mutex_unlock(&shares_mutex);
8818 return 0;
8821 unsigned long sched_group_shares(struct task_group *tg)
8823 return tg->shares;
8825 #endif
8827 #ifdef CONFIG_RT_GROUP_SCHED
8829 * Ensure that the real time constraints are schedulable.
8831 static DEFINE_MUTEX(rt_constraints_mutex);
8833 static unsigned long to_ratio(u64 period, u64 runtime)
8835 if (runtime == RUNTIME_INF)
8836 return 1ULL << 16;
8838 return div64_64(runtime << 16, period);
8841 #ifdef CONFIG_CGROUP_SCHED
8842 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8844 struct task_group *tgi, *parent = tg->parent;
8845 unsigned long total = 0;
8847 if (!parent) {
8848 if (global_rt_period() < period)
8849 return 0;
8851 return to_ratio(period, runtime) <
8852 to_ratio(global_rt_period(), global_rt_runtime());
8855 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8856 return 0;
8858 rcu_read_lock();
8859 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8860 if (tgi == tg)
8861 continue;
8863 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8864 tgi->rt_bandwidth.rt_runtime);
8866 rcu_read_unlock();
8868 return total + to_ratio(period, runtime) <
8869 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8870 parent->rt_bandwidth.rt_runtime);
8872 #elif defined CONFIG_USER_SCHED
8873 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8875 struct task_group *tgi;
8876 unsigned long total = 0;
8877 unsigned long global_ratio =
8878 to_ratio(global_rt_period(), global_rt_runtime());
8880 rcu_read_lock();
8881 list_for_each_entry_rcu(tgi, &task_groups, list) {
8882 if (tgi == tg)
8883 continue;
8885 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8886 tgi->rt_bandwidth.rt_runtime);
8888 rcu_read_unlock();
8890 return total + to_ratio(period, runtime) < global_ratio;
8892 #endif
8894 /* Must be called with tasklist_lock held */
8895 static inline int tg_has_rt_tasks(struct task_group *tg)
8897 struct task_struct *g, *p;
8898 do_each_thread(g, p) {
8899 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8900 return 1;
8901 } while_each_thread(g, p);
8902 return 0;
8905 static int tg_set_bandwidth(struct task_group *tg,
8906 u64 rt_period, u64 rt_runtime)
8908 int i, err = 0;
8910 mutex_lock(&rt_constraints_mutex);
8911 read_lock(&tasklist_lock);
8912 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8913 err = -EBUSY;
8914 goto unlock;
8916 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8917 err = -EINVAL;
8918 goto unlock;
8921 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8922 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8923 tg->rt_bandwidth.rt_runtime = rt_runtime;
8925 for_each_possible_cpu(i) {
8926 struct rt_rq *rt_rq = tg->rt_rq[i];
8928 spin_lock(&rt_rq->rt_runtime_lock);
8929 rt_rq->rt_runtime = rt_runtime;
8930 spin_unlock(&rt_rq->rt_runtime_lock);
8932 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8933 unlock:
8934 read_unlock(&tasklist_lock);
8935 mutex_unlock(&rt_constraints_mutex);
8937 return err;
8940 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8942 u64 rt_runtime, rt_period;
8944 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8945 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8946 if (rt_runtime_us < 0)
8947 rt_runtime = RUNTIME_INF;
8949 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8952 long sched_group_rt_runtime(struct task_group *tg)
8954 u64 rt_runtime_us;
8956 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8957 return -1;
8959 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8960 do_div(rt_runtime_us, NSEC_PER_USEC);
8961 return rt_runtime_us;
8964 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8966 u64 rt_runtime, rt_period;
8968 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8969 rt_runtime = tg->rt_bandwidth.rt_runtime;
8971 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8974 long sched_group_rt_period(struct task_group *tg)
8976 u64 rt_period_us;
8978 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8979 do_div(rt_period_us, NSEC_PER_USEC);
8980 return rt_period_us;
8983 static int sched_rt_global_constraints(void)
8985 int ret = 0;
8987 mutex_lock(&rt_constraints_mutex);
8988 if (!__rt_schedulable(NULL, 1, 0))
8989 ret = -EINVAL;
8990 mutex_unlock(&rt_constraints_mutex);
8992 return ret;
8994 #else
8995 static int sched_rt_global_constraints(void)
8997 unsigned long flags;
8998 int i;
9000 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9001 for_each_possible_cpu(i) {
9002 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9004 spin_lock(&rt_rq->rt_runtime_lock);
9005 rt_rq->rt_runtime = global_rt_runtime();
9006 spin_unlock(&rt_rq->rt_runtime_lock);
9008 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9010 return 0;
9012 #endif
9014 int sched_rt_handler(struct ctl_table *table, int write,
9015 struct file *filp, void __user *buffer, size_t *lenp,
9016 loff_t *ppos)
9018 int ret;
9019 int old_period, old_runtime;
9020 static DEFINE_MUTEX(mutex);
9022 mutex_lock(&mutex);
9023 old_period = sysctl_sched_rt_period;
9024 old_runtime = sysctl_sched_rt_runtime;
9026 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9028 if (!ret && write) {
9029 ret = sched_rt_global_constraints();
9030 if (ret) {
9031 sysctl_sched_rt_period = old_period;
9032 sysctl_sched_rt_runtime = old_runtime;
9033 } else {
9034 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9035 def_rt_bandwidth.rt_period =
9036 ns_to_ktime(global_rt_period());
9039 mutex_unlock(&mutex);
9041 return ret;
9044 #ifdef CONFIG_CGROUP_SCHED
9046 /* return corresponding task_group object of a cgroup */
9047 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9049 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9050 struct task_group, css);
9053 static struct cgroup_subsys_state *
9054 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9056 struct task_group *tg, *parent;
9058 if (!cgrp->parent) {
9059 /* This is early initialization for the top cgroup */
9060 init_task_group.css.cgroup = cgrp;
9061 return &init_task_group.css;
9064 parent = cgroup_tg(cgrp->parent);
9065 tg = sched_create_group(parent);
9066 if (IS_ERR(tg))
9067 return ERR_PTR(-ENOMEM);
9069 /* Bind the cgroup to task_group object we just created */
9070 tg->css.cgroup = cgrp;
9072 return &tg->css;
9075 static void
9076 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9078 struct task_group *tg = cgroup_tg(cgrp);
9080 sched_destroy_group(tg);
9083 static int
9084 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9085 struct task_struct *tsk)
9087 #ifdef CONFIG_RT_GROUP_SCHED
9088 /* Don't accept realtime tasks when there is no way for them to run */
9089 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9090 return -EINVAL;
9091 #else
9092 /* We don't support RT-tasks being in separate groups */
9093 if (tsk->sched_class != &fair_sched_class)
9094 return -EINVAL;
9095 #endif
9097 return 0;
9100 static void
9101 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9102 struct cgroup *old_cont, struct task_struct *tsk)
9104 sched_move_task(tsk);
9107 #ifdef CONFIG_FAIR_GROUP_SCHED
9108 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9109 u64 shareval)
9111 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9114 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
9116 struct task_group *tg = cgroup_tg(cgrp);
9118 return (u64) tg->shares;
9120 #endif
9122 #ifdef CONFIG_RT_GROUP_SCHED
9123 static ssize_t cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9124 struct file *file,
9125 const char __user *userbuf,
9126 size_t nbytes, loff_t *unused_ppos)
9128 char buffer[64];
9129 int retval = 0;
9130 s64 val;
9131 char *end;
9133 if (!nbytes)
9134 return -EINVAL;
9135 if (nbytes >= sizeof(buffer))
9136 return -E2BIG;
9137 if (copy_from_user(buffer, userbuf, nbytes))
9138 return -EFAULT;
9140 buffer[nbytes] = 0; /* nul-terminate */
9142 /* strip newline if necessary */
9143 if (nbytes && (buffer[nbytes-1] == '\n'))
9144 buffer[nbytes-1] = 0;
9145 val = simple_strtoll(buffer, &end, 0);
9146 if (*end)
9147 return -EINVAL;
9149 /* Pass to subsystem */
9150 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9151 if (!retval)
9152 retval = nbytes;
9153 return retval;
9156 static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
9157 struct file *file,
9158 char __user *buf, size_t nbytes,
9159 loff_t *ppos)
9161 char tmp[64];
9162 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
9163 int len = sprintf(tmp, "%ld\n", val);
9165 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
9168 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9169 u64 rt_period_us)
9171 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9174 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9176 return sched_group_rt_period(cgroup_tg(cgrp));
9178 #endif
9180 static struct cftype cpu_files[] = {
9181 #ifdef CONFIG_FAIR_GROUP_SCHED
9183 .name = "shares",
9184 .read_uint = cpu_shares_read_uint,
9185 .write_uint = cpu_shares_write_uint,
9187 #endif
9188 #ifdef CONFIG_RT_GROUP_SCHED
9190 .name = "rt_runtime_us",
9191 .read = cpu_rt_runtime_read,
9192 .write = cpu_rt_runtime_write,
9195 .name = "rt_period_us",
9196 .read_uint = cpu_rt_period_read_uint,
9197 .write_uint = cpu_rt_period_write_uint,
9199 #endif
9202 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9204 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9207 struct cgroup_subsys cpu_cgroup_subsys = {
9208 .name = "cpu",
9209 .create = cpu_cgroup_create,
9210 .destroy = cpu_cgroup_destroy,
9211 .can_attach = cpu_cgroup_can_attach,
9212 .attach = cpu_cgroup_attach,
9213 .populate = cpu_cgroup_populate,
9214 .subsys_id = cpu_cgroup_subsys_id,
9215 .early_init = 1,
9218 #endif /* CONFIG_CGROUP_SCHED */
9220 #ifdef CONFIG_CGROUP_CPUACCT
9223 * CPU accounting code for task groups.
9225 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9226 * (balbir@in.ibm.com).
9229 /* track cpu usage of a group of tasks */
9230 struct cpuacct {
9231 struct cgroup_subsys_state css;
9232 /* cpuusage holds pointer to a u64-type object on every cpu */
9233 u64 *cpuusage;
9236 struct cgroup_subsys cpuacct_subsys;
9238 /* return cpu accounting group corresponding to this container */
9239 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9241 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9242 struct cpuacct, css);
9245 /* return cpu accounting group to which this task belongs */
9246 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9248 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9249 struct cpuacct, css);
9252 /* create a new cpu accounting group */
9253 static struct cgroup_subsys_state *cpuacct_create(
9254 struct cgroup_subsys *ss, struct cgroup *cgrp)
9256 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9258 if (!ca)
9259 return ERR_PTR(-ENOMEM);
9261 ca->cpuusage = alloc_percpu(u64);
9262 if (!ca->cpuusage) {
9263 kfree(ca);
9264 return ERR_PTR(-ENOMEM);
9267 return &ca->css;
9270 /* destroy an existing cpu accounting group */
9271 static void
9272 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9274 struct cpuacct *ca = cgroup_ca(cgrp);
9276 free_percpu(ca->cpuusage);
9277 kfree(ca);
9280 /* return total cpu usage (in nanoseconds) of a group */
9281 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9283 struct cpuacct *ca = cgroup_ca(cgrp);
9284 u64 totalcpuusage = 0;
9285 int i;
9287 for_each_possible_cpu(i) {
9288 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9291 * Take rq->lock to make 64-bit addition safe on 32-bit
9292 * platforms.
9294 spin_lock_irq(&cpu_rq(i)->lock);
9295 totalcpuusage += *cpuusage;
9296 spin_unlock_irq(&cpu_rq(i)->lock);
9299 return totalcpuusage;
9302 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9303 u64 reset)
9305 struct cpuacct *ca = cgroup_ca(cgrp);
9306 int err = 0;
9307 int i;
9309 if (reset) {
9310 err = -EINVAL;
9311 goto out;
9314 for_each_possible_cpu(i) {
9315 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9317 spin_lock_irq(&cpu_rq(i)->lock);
9318 *cpuusage = 0;
9319 spin_unlock_irq(&cpu_rq(i)->lock);
9321 out:
9322 return err;
9325 static struct cftype files[] = {
9327 .name = "usage",
9328 .read_uint = cpuusage_read,
9329 .write_uint = cpuusage_write,
9333 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9335 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9339 * charge this task's execution time to its accounting group.
9341 * called with rq->lock held.
9343 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9345 struct cpuacct *ca;
9347 if (!cpuacct_subsys.active)
9348 return;
9350 ca = task_ca(tsk);
9351 if (ca) {
9352 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9354 *cpuusage += cputime;
9358 struct cgroup_subsys cpuacct_subsys = {
9359 .name = "cpuacct",
9360 .create = cpuacct_create,
9361 .destroy = cpuacct_destroy,
9362 .populate = cpuacct_populate,
9363 .subsys_id = cpuacct_subsys_id,
9365 #endif /* CONFIG_CGROUP_CPUACCT */