sched: fair-group: fix a Div0 error of the fair group scheduler
[linux-2.6/linux-loongson.git] / kernel / sched.c
blobf98f75f3c708414d14d60f49a6cc81a5c79d25e3
1 /*
2 * kernel/sched.c
4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/kthread.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/bootmem.h>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
74 #include <asm/tlb.h>
75 #include <asm/irq_regs.h>
78 * Scheduler clock - returns current time in nanosec units.
79 * This is default implementation.
80 * Architectures and sub-architectures can override this.
82 unsigned long long __attribute__((weak)) sched_clock(void)
84 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
88 * Convert user-nice values [ -20 ... 0 ... 19 ]
89 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
90 * and back.
92 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
93 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
94 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
97 * 'User priority' is the nice value converted to something we
98 * can work with better when scaling various scheduler parameters,
99 * it's a [ 0 ... 39 ] range.
101 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
102 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
103 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
106 * Helpers for converting nanosecond timing to jiffy resolution
108 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
110 #define NICE_0_LOAD SCHED_LOAD_SCALE
111 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
114 * These are the 'tuning knobs' of the scheduler:
116 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
117 * Timeslices get refilled after they expire.
119 #define DEF_TIMESLICE (100 * HZ / 1000)
122 * single value that denotes runtime == period, ie unlimited time.
124 #define RUNTIME_INF ((u64)~0ULL)
126 #ifdef CONFIG_SMP
128 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
129 * Since cpu_power is a 'constant', we can use a reciprocal divide.
131 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
133 return reciprocal_divide(load, sg->reciprocal_cpu_power);
137 * Each time a sched group cpu_power is changed,
138 * we must compute its reciprocal value
140 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
142 sg->__cpu_power += val;
143 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
145 #endif
147 static inline int rt_policy(int policy)
149 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
150 return 1;
151 return 0;
154 static inline int task_has_rt_policy(struct task_struct *p)
156 return rt_policy(p->policy);
160 * This is the priority-queue data structure of the RT scheduling class:
162 struct rt_prio_array {
163 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
164 struct list_head queue[MAX_RT_PRIO];
167 struct rt_bandwidth {
168 /* nests inside the rq lock: */
169 spinlock_t rt_runtime_lock;
170 ktime_t rt_period;
171 u64 rt_runtime;
172 struct hrtimer rt_period_timer;
175 static struct rt_bandwidth def_rt_bandwidth;
177 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
179 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
181 struct rt_bandwidth *rt_b =
182 container_of(timer, struct rt_bandwidth, rt_period_timer);
183 ktime_t now;
184 int overrun;
185 int idle = 0;
187 for (;;) {
188 now = hrtimer_cb_get_time(timer);
189 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
191 if (!overrun)
192 break;
194 idle = do_sched_rt_period_timer(rt_b, overrun);
197 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
200 static
201 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
203 rt_b->rt_period = ns_to_ktime(period);
204 rt_b->rt_runtime = runtime;
206 spin_lock_init(&rt_b->rt_runtime_lock);
208 hrtimer_init(&rt_b->rt_period_timer,
209 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
210 rt_b->rt_period_timer.function = sched_rt_period_timer;
211 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
214 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
216 ktime_t now;
218 if (rt_b->rt_runtime == RUNTIME_INF)
219 return;
221 if (hrtimer_active(&rt_b->rt_period_timer))
222 return;
224 spin_lock(&rt_b->rt_runtime_lock);
225 for (;;) {
226 if (hrtimer_active(&rt_b->rt_period_timer))
227 break;
229 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
230 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
231 hrtimer_start(&rt_b->rt_period_timer,
232 rt_b->rt_period_timer.expires,
233 HRTIMER_MODE_ABS);
235 spin_unlock(&rt_b->rt_runtime_lock);
238 #ifdef CONFIG_RT_GROUP_SCHED
239 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
241 hrtimer_cancel(&rt_b->rt_period_timer);
243 #endif
246 * sched_domains_mutex serializes calls to arch_init_sched_domains,
247 * detach_destroy_domains and partition_sched_domains.
249 static DEFINE_MUTEX(sched_domains_mutex);
251 #ifdef CONFIG_GROUP_SCHED
253 #include <linux/cgroup.h>
255 struct cfs_rq;
257 static LIST_HEAD(task_groups);
259 /* task group related information */
260 struct task_group {
261 #ifdef CONFIG_CGROUP_SCHED
262 struct cgroup_subsys_state css;
263 #endif
265 #ifdef CONFIG_FAIR_GROUP_SCHED
266 /* schedulable entities of this group on each cpu */
267 struct sched_entity **se;
268 /* runqueue "owned" by this group on each cpu */
269 struct cfs_rq **cfs_rq;
270 unsigned long shares;
271 #endif
273 #ifdef CONFIG_RT_GROUP_SCHED
274 struct sched_rt_entity **rt_se;
275 struct rt_rq **rt_rq;
277 struct rt_bandwidth rt_bandwidth;
278 #endif
280 struct rcu_head rcu;
281 struct list_head list;
283 struct task_group *parent;
284 struct list_head siblings;
285 struct list_head children;
288 #ifdef CONFIG_USER_SCHED
291 * Root task group.
292 * Every UID task group (including init_task_group aka UID-0) will
293 * be a child to this group.
295 struct task_group root_task_group;
297 #ifdef CONFIG_FAIR_GROUP_SCHED
298 /* Default task group's sched entity on each cpu */
299 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
300 /* Default task group's cfs_rq on each cpu */
301 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
302 #endif
304 #ifdef CONFIG_RT_GROUP_SCHED
305 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
306 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
307 #endif
308 #else
309 #define root_task_group init_task_group
310 #endif
312 /* task_group_lock serializes add/remove of task groups and also changes to
313 * a task group's cpu shares.
315 static DEFINE_SPINLOCK(task_group_lock);
317 #ifdef CONFIG_FAIR_GROUP_SCHED
318 #ifdef CONFIG_USER_SCHED
319 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
320 #else
321 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
322 #endif
325 * A weight of 0, 1 or ULONG_MAX can cause arithmetics problems.
326 * (The default weight is 1024 - so there's no practical
327 * limitation from this.)
329 #define MIN_SHARES 2
330 #define MAX_SHARES (ULONG_MAX - 1)
332 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
333 #endif
335 /* Default task group.
336 * Every task in system belong to this group at bootup.
338 struct task_group init_task_group;
340 /* return group to which a task belongs */
341 static inline struct task_group *task_group(struct task_struct *p)
343 struct task_group *tg;
345 #ifdef CONFIG_USER_SCHED
346 tg = p->user->tg;
347 #elif defined(CONFIG_CGROUP_SCHED)
348 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
349 struct task_group, css);
350 #else
351 tg = &init_task_group;
352 #endif
353 return tg;
356 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
357 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
359 #ifdef CONFIG_FAIR_GROUP_SCHED
360 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
361 p->se.parent = task_group(p)->se[cpu];
362 #endif
364 #ifdef CONFIG_RT_GROUP_SCHED
365 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
366 p->rt.parent = task_group(p)->rt_se[cpu];
367 #endif
370 #else
372 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
374 #endif /* CONFIG_GROUP_SCHED */
376 /* CFS-related fields in a runqueue */
377 struct cfs_rq {
378 struct load_weight load;
379 unsigned long nr_running;
381 u64 exec_clock;
382 u64 min_vruntime;
384 struct rb_root tasks_timeline;
385 struct rb_node *rb_leftmost;
387 struct list_head tasks;
388 struct list_head *balance_iterator;
391 * 'curr' points to currently running entity on this cfs_rq.
392 * It is set to NULL otherwise (i.e when none are currently running).
394 struct sched_entity *curr, *next;
396 unsigned long nr_spread_over;
398 #ifdef CONFIG_FAIR_GROUP_SCHED
399 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
402 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
403 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
404 * (like users, containers etc.)
406 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
407 * list is used during load balance.
409 struct list_head leaf_cfs_rq_list;
410 struct task_group *tg; /* group that "owns" this runqueue */
412 #ifdef CONFIG_SMP
413 unsigned long task_weight;
414 unsigned long shares;
416 * We need space to build a sched_domain wide view of the full task
417 * group tree, in order to avoid depending on dynamic memory allocation
418 * during the load balancing we place this in the per cpu task group
419 * hierarchy. This limits the load balancing to one instance per cpu,
420 * but more should not be needed anyway.
422 struct aggregate_struct {
424 * load = weight(cpus) * f(tg)
426 * Where f(tg) is the recursive weight fraction assigned to
427 * this group.
429 unsigned long load;
432 * part of the group weight distributed to this span.
434 unsigned long shares;
437 * The sum of all runqueue weights within this span.
439 unsigned long rq_weight;
442 * Weight contributed by tasks; this is the part we can
443 * influence by moving tasks around.
445 unsigned long task_weight;
446 } aggregate;
447 #endif
448 #endif
451 /* Real-Time classes' related field in a runqueue: */
452 struct rt_rq {
453 struct rt_prio_array active;
454 unsigned long rt_nr_running;
455 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
456 int highest_prio; /* highest queued rt task prio */
457 #endif
458 #ifdef CONFIG_SMP
459 unsigned long rt_nr_migratory;
460 int overloaded;
461 #endif
462 int rt_throttled;
463 u64 rt_time;
464 u64 rt_runtime;
465 /* Nests inside the rq lock: */
466 spinlock_t rt_runtime_lock;
468 #ifdef CONFIG_RT_GROUP_SCHED
469 unsigned long rt_nr_boosted;
471 struct rq *rq;
472 struct list_head leaf_rt_rq_list;
473 struct task_group *tg;
474 struct sched_rt_entity *rt_se;
475 #endif
478 #ifdef CONFIG_SMP
481 * We add the notion of a root-domain which will be used to define per-domain
482 * variables. Each exclusive cpuset essentially defines an island domain by
483 * fully partitioning the member cpus from any other cpuset. Whenever a new
484 * exclusive cpuset is created, we also create and attach a new root-domain
485 * object.
488 struct root_domain {
489 atomic_t refcount;
490 cpumask_t span;
491 cpumask_t online;
494 * The "RT overload" flag: it gets set if a CPU has more than
495 * one runnable RT task.
497 cpumask_t rto_mask;
498 atomic_t rto_count;
502 * By default the system creates a single root-domain with all cpus as
503 * members (mimicking the global state we have today).
505 static struct root_domain def_root_domain;
507 #endif
510 * This is the main, per-CPU runqueue data structure.
512 * Locking rule: those places that want to lock multiple runqueues
513 * (such as the load balancing or the thread migration code), lock
514 * acquire operations must be ordered by ascending &runqueue.
516 struct rq {
517 /* runqueue lock: */
518 spinlock_t lock;
521 * nr_running and cpu_load should be in the same cacheline because
522 * remote CPUs use both these fields when doing load calculation.
524 unsigned long nr_running;
525 #define CPU_LOAD_IDX_MAX 5
526 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
527 unsigned char idle_at_tick;
528 #ifdef CONFIG_NO_HZ
529 unsigned long last_tick_seen;
530 unsigned char in_nohz_recently;
531 #endif
532 /* capture load from *all* tasks on this cpu: */
533 struct load_weight load;
534 unsigned long nr_load_updates;
535 u64 nr_switches;
537 struct cfs_rq cfs;
538 struct rt_rq rt;
540 #ifdef CONFIG_FAIR_GROUP_SCHED
541 /* list of leaf cfs_rq on this cpu: */
542 struct list_head leaf_cfs_rq_list;
543 #endif
544 #ifdef CONFIG_RT_GROUP_SCHED
545 struct list_head leaf_rt_rq_list;
546 #endif
549 * This is part of a global counter where only the total sum
550 * over all CPUs matters. A task can increase this counter on
551 * one CPU and if it got migrated afterwards it may decrease
552 * it on another CPU. Always updated under the runqueue lock:
554 unsigned long nr_uninterruptible;
556 struct task_struct *curr, *idle;
557 unsigned long next_balance;
558 struct mm_struct *prev_mm;
560 u64 clock, prev_clock_raw;
561 s64 clock_max_delta;
563 unsigned int clock_warps, clock_overflows, clock_underflows;
564 u64 idle_clock;
565 unsigned int clock_deep_idle_events;
566 u64 tick_timestamp;
568 atomic_t nr_iowait;
570 #ifdef CONFIG_SMP
571 struct root_domain *rd;
572 struct sched_domain *sd;
574 /* For active balancing */
575 int active_balance;
576 int push_cpu;
577 /* cpu of this runqueue: */
578 int cpu;
580 struct task_struct *migration_thread;
581 struct list_head migration_queue;
582 #endif
584 #ifdef CONFIG_SCHED_HRTICK
585 unsigned long hrtick_flags;
586 ktime_t hrtick_expire;
587 struct hrtimer hrtick_timer;
588 #endif
590 #ifdef CONFIG_SCHEDSTATS
591 /* latency stats */
592 struct sched_info rq_sched_info;
594 /* sys_sched_yield() stats */
595 unsigned int yld_exp_empty;
596 unsigned int yld_act_empty;
597 unsigned int yld_both_empty;
598 unsigned int yld_count;
600 /* schedule() stats */
601 unsigned int sched_switch;
602 unsigned int sched_count;
603 unsigned int sched_goidle;
605 /* try_to_wake_up() stats */
606 unsigned int ttwu_count;
607 unsigned int ttwu_local;
609 /* BKL stats */
610 unsigned int bkl_count;
611 #endif
612 struct lock_class_key rq_lock_key;
615 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
617 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
619 rq->curr->sched_class->check_preempt_curr(rq, p);
622 static inline int cpu_of(struct rq *rq)
624 #ifdef CONFIG_SMP
625 return rq->cpu;
626 #else
627 return 0;
628 #endif
631 #ifdef CONFIG_NO_HZ
632 static inline bool nohz_on(int cpu)
634 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
637 static inline u64 max_skipped_ticks(struct rq *rq)
639 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
642 static inline void update_last_tick_seen(struct rq *rq)
644 rq->last_tick_seen = jiffies;
646 #else
647 static inline u64 max_skipped_ticks(struct rq *rq)
649 return 1;
652 static inline void update_last_tick_seen(struct rq *rq)
655 #endif
658 * Update the per-runqueue clock, as finegrained as the platform can give
659 * us, but without assuming monotonicity, etc.:
661 static void __update_rq_clock(struct rq *rq)
663 u64 prev_raw = rq->prev_clock_raw;
664 u64 now = sched_clock();
665 s64 delta = now - prev_raw;
666 u64 clock = rq->clock;
668 #ifdef CONFIG_SCHED_DEBUG
669 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
670 #endif
672 * Protect against sched_clock() occasionally going backwards:
674 if (unlikely(delta < 0)) {
675 clock++;
676 rq->clock_warps++;
677 } else {
679 * Catch too large forward jumps too:
681 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
682 u64 max_time = rq->tick_timestamp + max_jump;
684 if (unlikely(clock + delta > max_time)) {
685 if (clock < max_time)
686 clock = max_time;
687 else
688 clock++;
689 rq->clock_overflows++;
690 } else {
691 if (unlikely(delta > rq->clock_max_delta))
692 rq->clock_max_delta = delta;
693 clock += delta;
697 rq->prev_clock_raw = now;
698 rq->clock = clock;
701 static void update_rq_clock(struct rq *rq)
703 if (likely(smp_processor_id() == cpu_of(rq)))
704 __update_rq_clock(rq);
708 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
709 * See detach_destroy_domains: synchronize_sched for details.
711 * The domain tree of any CPU may only be accessed from within
712 * preempt-disabled sections.
714 #define for_each_domain(cpu, __sd) \
715 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
717 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
718 #define this_rq() (&__get_cpu_var(runqueues))
719 #define task_rq(p) cpu_rq(task_cpu(p))
720 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
723 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
725 #ifdef CONFIG_SCHED_DEBUG
726 # define const_debug __read_mostly
727 #else
728 # define const_debug static const
729 #endif
732 * Debugging: various feature bits
735 #define SCHED_FEAT(name, enabled) \
736 __SCHED_FEAT_##name ,
738 enum {
739 #include "sched_features.h"
742 #undef SCHED_FEAT
744 #define SCHED_FEAT(name, enabled) \
745 (1UL << __SCHED_FEAT_##name) * enabled |
747 const_debug unsigned int sysctl_sched_features =
748 #include "sched_features.h"
751 #undef SCHED_FEAT
753 #ifdef CONFIG_SCHED_DEBUG
754 #define SCHED_FEAT(name, enabled) \
755 #name ,
757 static __read_mostly char *sched_feat_names[] = {
758 #include "sched_features.h"
759 NULL
762 #undef SCHED_FEAT
764 static int sched_feat_open(struct inode *inode, struct file *filp)
766 filp->private_data = inode->i_private;
767 return 0;
770 static ssize_t
771 sched_feat_read(struct file *filp, char __user *ubuf,
772 size_t cnt, loff_t *ppos)
774 char *buf;
775 int r = 0;
776 int len = 0;
777 int i;
779 for (i = 0; sched_feat_names[i]; i++) {
780 len += strlen(sched_feat_names[i]);
781 len += 4;
784 buf = kmalloc(len + 2, GFP_KERNEL);
785 if (!buf)
786 return -ENOMEM;
788 for (i = 0; sched_feat_names[i]; i++) {
789 if (sysctl_sched_features & (1UL << i))
790 r += sprintf(buf + r, "%s ", sched_feat_names[i]);
791 else
792 r += sprintf(buf + r, "NO_%s ", sched_feat_names[i]);
795 r += sprintf(buf + r, "\n");
796 WARN_ON(r >= len + 2);
798 r = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
800 kfree(buf);
802 return r;
805 static ssize_t
806 sched_feat_write(struct file *filp, const char __user *ubuf,
807 size_t cnt, loff_t *ppos)
809 char buf[64];
810 char *cmp = buf;
811 int neg = 0;
812 int i;
814 if (cnt > 63)
815 cnt = 63;
817 if (copy_from_user(&buf, ubuf, cnt))
818 return -EFAULT;
820 buf[cnt] = 0;
822 if (strncmp(buf, "NO_", 3) == 0) {
823 neg = 1;
824 cmp += 3;
827 for (i = 0; sched_feat_names[i]; i++) {
828 int len = strlen(sched_feat_names[i]);
830 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
831 if (neg)
832 sysctl_sched_features &= ~(1UL << i);
833 else
834 sysctl_sched_features |= (1UL << i);
835 break;
839 if (!sched_feat_names[i])
840 return -EINVAL;
842 filp->f_pos += cnt;
844 return cnt;
847 static struct file_operations sched_feat_fops = {
848 .open = sched_feat_open,
849 .read = sched_feat_read,
850 .write = sched_feat_write,
853 static __init int sched_init_debug(void)
855 debugfs_create_file("sched_features", 0644, NULL, NULL,
856 &sched_feat_fops);
858 return 0;
860 late_initcall(sched_init_debug);
862 #endif
864 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
867 * Number of tasks to iterate in a single balance run.
868 * Limited because this is done with IRQs disabled.
870 const_debug unsigned int sysctl_sched_nr_migrate = 32;
873 * period over which we measure -rt task cpu usage in us.
874 * default: 1s
876 unsigned int sysctl_sched_rt_period = 1000000;
878 static __read_mostly int scheduler_running;
881 * part of the period that we allow rt tasks to run in us.
882 * default: 0.95s
884 int sysctl_sched_rt_runtime = 950000;
886 static inline u64 global_rt_period(void)
888 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
891 static inline u64 global_rt_runtime(void)
893 if (sysctl_sched_rt_period < 0)
894 return RUNTIME_INF;
896 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
899 unsigned long long time_sync_thresh = 100000;
901 static DEFINE_PER_CPU(unsigned long long, time_offset);
902 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
905 * Global lock which we take every now and then to synchronize
906 * the CPUs time. This method is not warp-safe, but it's good
907 * enough to synchronize slowly diverging time sources and thus
908 * it's good enough for tracing:
910 static DEFINE_SPINLOCK(time_sync_lock);
911 static unsigned long long prev_global_time;
913 static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
915 unsigned long flags;
917 spin_lock_irqsave(&time_sync_lock, flags);
919 if (time < prev_global_time) {
920 per_cpu(time_offset, cpu) += prev_global_time - time;
921 time = prev_global_time;
922 } else {
923 prev_global_time = time;
926 spin_unlock_irqrestore(&time_sync_lock, flags);
928 return time;
931 static unsigned long long __cpu_clock(int cpu)
933 unsigned long long now;
934 unsigned long flags;
935 struct rq *rq;
938 * Only call sched_clock() if the scheduler has already been
939 * initialized (some code might call cpu_clock() very early):
941 if (unlikely(!scheduler_running))
942 return 0;
944 local_irq_save(flags);
945 rq = cpu_rq(cpu);
946 update_rq_clock(rq);
947 now = rq->clock;
948 local_irq_restore(flags);
950 return now;
954 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
955 * clock constructed from sched_clock():
957 unsigned long long cpu_clock(int cpu)
959 unsigned long long prev_cpu_time, time, delta_time;
961 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
962 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
963 delta_time = time-prev_cpu_time;
965 if (unlikely(delta_time > time_sync_thresh))
966 time = __sync_cpu_clock(time, cpu);
968 return time;
970 EXPORT_SYMBOL_GPL(cpu_clock);
972 #ifndef prepare_arch_switch
973 # define prepare_arch_switch(next) do { } while (0)
974 #endif
975 #ifndef finish_arch_switch
976 # define finish_arch_switch(prev) do { } while (0)
977 #endif
979 static inline int task_current(struct rq *rq, struct task_struct *p)
981 return rq->curr == p;
984 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
985 static inline int task_running(struct rq *rq, struct task_struct *p)
987 return task_current(rq, p);
990 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
994 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
996 #ifdef CONFIG_DEBUG_SPINLOCK
997 /* this is a valid case when another task releases the spinlock */
998 rq->lock.owner = current;
999 #endif
1001 * If we are tracking spinlock dependencies then we have to
1002 * fix up the runqueue lock - which gets 'carried over' from
1003 * prev into current:
1005 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
1007 spin_unlock_irq(&rq->lock);
1010 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
1011 static inline int task_running(struct rq *rq, struct task_struct *p)
1013 #ifdef CONFIG_SMP
1014 return p->oncpu;
1015 #else
1016 return task_current(rq, p);
1017 #endif
1020 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
1022 #ifdef CONFIG_SMP
1024 * We can optimise this out completely for !SMP, because the
1025 * SMP rebalancing from interrupt is the only thing that cares
1026 * here.
1028 next->oncpu = 1;
1029 #endif
1030 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1031 spin_unlock_irq(&rq->lock);
1032 #else
1033 spin_unlock(&rq->lock);
1034 #endif
1037 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
1039 #ifdef CONFIG_SMP
1041 * After ->oncpu is cleared, the task can be moved to a different CPU.
1042 * We must ensure this doesn't happen until the switch is completely
1043 * finished.
1045 smp_wmb();
1046 prev->oncpu = 0;
1047 #endif
1048 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1049 local_irq_enable();
1050 #endif
1052 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1055 * __task_rq_lock - lock the runqueue a given task resides on.
1056 * Must be called interrupts disabled.
1058 static inline struct rq *__task_rq_lock(struct task_struct *p)
1059 __acquires(rq->lock)
1061 for (;;) {
1062 struct rq *rq = task_rq(p);
1063 spin_lock(&rq->lock);
1064 if (likely(rq == task_rq(p)))
1065 return rq;
1066 spin_unlock(&rq->lock);
1071 * task_rq_lock - lock the runqueue a given task resides on and disable
1072 * interrupts. Note the ordering: we can safely lookup the task_rq without
1073 * explicitly disabling preemption.
1075 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1076 __acquires(rq->lock)
1078 struct rq *rq;
1080 for (;;) {
1081 local_irq_save(*flags);
1082 rq = task_rq(p);
1083 spin_lock(&rq->lock);
1084 if (likely(rq == task_rq(p)))
1085 return rq;
1086 spin_unlock_irqrestore(&rq->lock, *flags);
1090 static void __task_rq_unlock(struct rq *rq)
1091 __releases(rq->lock)
1093 spin_unlock(&rq->lock);
1096 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1097 __releases(rq->lock)
1099 spin_unlock_irqrestore(&rq->lock, *flags);
1103 * this_rq_lock - lock this runqueue and disable interrupts.
1105 static struct rq *this_rq_lock(void)
1106 __acquires(rq->lock)
1108 struct rq *rq;
1110 local_irq_disable();
1111 rq = this_rq();
1112 spin_lock(&rq->lock);
1114 return rq;
1118 * We are going deep-idle (irqs are disabled):
1120 void sched_clock_idle_sleep_event(void)
1122 struct rq *rq = cpu_rq(smp_processor_id());
1124 WARN_ON(!irqs_disabled());
1125 spin_lock(&rq->lock);
1126 __update_rq_clock(rq);
1127 spin_unlock(&rq->lock);
1128 rq->clock_deep_idle_events++;
1130 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
1133 * We just idled delta nanoseconds (called with irqs disabled):
1135 void sched_clock_idle_wakeup_event(u64 delta_ns)
1137 struct rq *rq = cpu_rq(smp_processor_id());
1138 u64 now = sched_clock();
1140 WARN_ON(!irqs_disabled());
1141 rq->idle_clock += delta_ns;
1143 * Override the previous timestamp and ignore all
1144 * sched_clock() deltas that occured while we idled,
1145 * and use the PM-provided delta_ns to advance the
1146 * rq clock:
1148 spin_lock(&rq->lock);
1149 rq->prev_clock_raw = now;
1150 rq->clock += delta_ns;
1151 spin_unlock(&rq->lock);
1152 touch_softlockup_watchdog();
1154 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1156 static void __resched_task(struct task_struct *p, int tif_bit);
1158 static inline void resched_task(struct task_struct *p)
1160 __resched_task(p, TIF_NEED_RESCHED);
1163 #ifdef CONFIG_SCHED_HRTICK
1165 * Use HR-timers to deliver accurate preemption points.
1167 * Its all a bit involved since we cannot program an hrt while holding the
1168 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1169 * reschedule event.
1171 * When we get rescheduled we reprogram the hrtick_timer outside of the
1172 * rq->lock.
1174 static inline void resched_hrt(struct task_struct *p)
1176 __resched_task(p, TIF_HRTICK_RESCHED);
1179 static inline void resched_rq(struct rq *rq)
1181 unsigned long flags;
1183 spin_lock_irqsave(&rq->lock, flags);
1184 resched_task(rq->curr);
1185 spin_unlock_irqrestore(&rq->lock, flags);
1188 enum {
1189 HRTICK_SET, /* re-programm hrtick_timer */
1190 HRTICK_RESET, /* not a new slice */
1191 HRTICK_BLOCK, /* stop hrtick operations */
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 if (unlikely(test_bit(HRTICK_BLOCK, &rq->hrtick_flags)))
1204 return 0;
1205 return hrtimer_is_hres_active(&rq->hrtick_timer);
1209 * Called to set the hrtick timer state.
1211 * called with rq->lock held and irqs disabled
1213 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1215 assert_spin_locked(&rq->lock);
1218 * preempt at: now + delay
1220 rq->hrtick_expire =
1221 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1223 * indicate we need to program the timer
1225 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1226 if (reset)
1227 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1230 * New slices are called from the schedule path and don't need a
1231 * forced reschedule.
1233 if (reset)
1234 resched_hrt(rq->curr);
1237 static void hrtick_clear(struct rq *rq)
1239 if (hrtimer_active(&rq->hrtick_timer))
1240 hrtimer_cancel(&rq->hrtick_timer);
1244 * Update the timer from the possible pending state.
1246 static void hrtick_set(struct rq *rq)
1248 ktime_t time;
1249 int set, reset;
1250 unsigned long flags;
1252 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1254 spin_lock_irqsave(&rq->lock, flags);
1255 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1256 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1257 time = rq->hrtick_expire;
1258 clear_thread_flag(TIF_HRTICK_RESCHED);
1259 spin_unlock_irqrestore(&rq->lock, flags);
1261 if (set) {
1262 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1263 if (reset && !hrtimer_active(&rq->hrtick_timer))
1264 resched_rq(rq);
1265 } else
1266 hrtick_clear(rq);
1270 * High-resolution timer tick.
1271 * Runs from hardirq context with interrupts disabled.
1273 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1275 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1277 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1279 spin_lock(&rq->lock);
1280 __update_rq_clock(rq);
1281 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1282 spin_unlock(&rq->lock);
1284 return HRTIMER_NORESTART;
1287 static void hotplug_hrtick_disable(int cpu)
1289 struct rq *rq = cpu_rq(cpu);
1290 unsigned long flags;
1292 spin_lock_irqsave(&rq->lock, flags);
1293 rq->hrtick_flags = 0;
1294 __set_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1295 spin_unlock_irqrestore(&rq->lock, flags);
1297 hrtick_clear(rq);
1300 static void hotplug_hrtick_enable(int cpu)
1302 struct rq *rq = cpu_rq(cpu);
1303 unsigned long flags;
1305 spin_lock_irqsave(&rq->lock, flags);
1306 __clear_bit(HRTICK_BLOCK, &rq->hrtick_flags);
1307 spin_unlock_irqrestore(&rq->lock, flags);
1310 static int
1311 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1313 int cpu = (int)(long)hcpu;
1315 switch (action) {
1316 case CPU_UP_CANCELED:
1317 case CPU_UP_CANCELED_FROZEN:
1318 case CPU_DOWN_PREPARE:
1319 case CPU_DOWN_PREPARE_FROZEN:
1320 case CPU_DEAD:
1321 case CPU_DEAD_FROZEN:
1322 hotplug_hrtick_disable(cpu);
1323 return NOTIFY_OK;
1325 case CPU_UP_PREPARE:
1326 case CPU_UP_PREPARE_FROZEN:
1327 case CPU_DOWN_FAILED:
1328 case CPU_DOWN_FAILED_FROZEN:
1329 case CPU_ONLINE:
1330 case CPU_ONLINE_FROZEN:
1331 hotplug_hrtick_enable(cpu);
1332 return NOTIFY_OK;
1335 return NOTIFY_DONE;
1338 static void init_hrtick(void)
1340 hotcpu_notifier(hotplug_hrtick, 0);
1343 static void init_rq_hrtick(struct rq *rq)
1345 rq->hrtick_flags = 0;
1346 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1347 rq->hrtick_timer.function = hrtick;
1348 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1351 void hrtick_resched(void)
1353 struct rq *rq;
1354 unsigned long flags;
1356 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1357 return;
1359 local_irq_save(flags);
1360 rq = cpu_rq(smp_processor_id());
1361 hrtick_set(rq);
1362 local_irq_restore(flags);
1364 #else
1365 static inline void hrtick_clear(struct rq *rq)
1369 static inline void hrtick_set(struct rq *rq)
1373 static inline void init_rq_hrtick(struct rq *rq)
1377 void hrtick_resched(void)
1381 static inline void init_hrtick(void)
1384 #endif
1387 * resched_task - mark a task 'to be rescheduled now'.
1389 * On UP this means the setting of the need_resched flag, on SMP it
1390 * might also involve a cross-CPU call to trigger the scheduler on
1391 * the target CPU.
1393 #ifdef CONFIG_SMP
1395 #ifndef tsk_is_polling
1396 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1397 #endif
1399 static void __resched_task(struct task_struct *p, int tif_bit)
1401 int cpu;
1403 assert_spin_locked(&task_rq(p)->lock);
1405 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1406 return;
1408 set_tsk_thread_flag(p, tif_bit);
1410 cpu = task_cpu(p);
1411 if (cpu == smp_processor_id())
1412 return;
1414 /* NEED_RESCHED must be visible before we test polling */
1415 smp_mb();
1416 if (!tsk_is_polling(p))
1417 smp_send_reschedule(cpu);
1420 static void resched_cpu(int cpu)
1422 struct rq *rq = cpu_rq(cpu);
1423 unsigned long flags;
1425 if (!spin_trylock_irqsave(&rq->lock, flags))
1426 return;
1427 resched_task(cpu_curr(cpu));
1428 spin_unlock_irqrestore(&rq->lock, flags);
1431 #ifdef CONFIG_NO_HZ
1433 * When add_timer_on() enqueues a timer into the timer wheel of an
1434 * idle CPU then this timer might expire before the next timer event
1435 * which is scheduled to wake up that CPU. In case of a completely
1436 * idle system the next event might even be infinite time into the
1437 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1438 * leaves the inner idle loop so the newly added timer is taken into
1439 * account when the CPU goes back to idle and evaluates the timer
1440 * wheel for the next timer event.
1442 void wake_up_idle_cpu(int cpu)
1444 struct rq *rq = cpu_rq(cpu);
1446 if (cpu == smp_processor_id())
1447 return;
1450 * This is safe, as this function is called with the timer
1451 * wheel base lock of (cpu) held. When the CPU is on the way
1452 * to idle and has not yet set rq->curr to idle then it will
1453 * be serialized on the timer wheel base lock and take the new
1454 * timer into account automatically.
1456 if (rq->curr != rq->idle)
1457 return;
1460 * We can set TIF_RESCHED on the idle task of the other CPU
1461 * lockless. The worst case is that the other CPU runs the
1462 * idle task through an additional NOOP schedule()
1464 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1466 /* NEED_RESCHED must be visible before we test polling */
1467 smp_mb();
1468 if (!tsk_is_polling(rq->idle))
1469 smp_send_reschedule(cpu);
1471 #endif
1473 #else
1474 static void __resched_task(struct task_struct *p, int tif_bit)
1476 assert_spin_locked(&task_rq(p)->lock);
1477 set_tsk_thread_flag(p, tif_bit);
1479 #endif
1481 #if BITS_PER_LONG == 32
1482 # define WMULT_CONST (~0UL)
1483 #else
1484 # define WMULT_CONST (1UL << 32)
1485 #endif
1487 #define WMULT_SHIFT 32
1490 * Shift right and round:
1492 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1495 * delta *= weight / lw
1497 static unsigned long
1498 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1499 struct load_weight *lw)
1501 u64 tmp;
1503 if (!lw->inv_weight)
1504 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)/(lw->weight+1);
1506 tmp = (u64)delta_exec * weight;
1508 * Check whether we'd overflow the 64-bit multiplication:
1510 if (unlikely(tmp > WMULT_CONST))
1511 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1512 WMULT_SHIFT/2);
1513 else
1514 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1516 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1519 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1521 lw->weight += inc;
1522 lw->inv_weight = 0;
1525 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1527 lw->weight -= dec;
1528 lw->inv_weight = 0;
1532 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1533 * of tasks with abnormal "nice" values across CPUs the contribution that
1534 * each task makes to its run queue's load is weighted according to its
1535 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1536 * scaled version of the new time slice allocation that they receive on time
1537 * slice expiry etc.
1540 #define WEIGHT_IDLEPRIO 2
1541 #define WMULT_IDLEPRIO (1 << 31)
1544 * Nice levels are multiplicative, with a gentle 10% change for every
1545 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1546 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1547 * that remained on nice 0.
1549 * The "10% effect" is relative and cumulative: from _any_ nice level,
1550 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1551 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1552 * If a task goes up by ~10% and another task goes down by ~10% then
1553 * the relative distance between them is ~25%.)
1555 static const int prio_to_weight[40] = {
1556 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1557 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1558 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1559 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1560 /* 0 */ 1024, 820, 655, 526, 423,
1561 /* 5 */ 335, 272, 215, 172, 137,
1562 /* 10 */ 110, 87, 70, 56, 45,
1563 /* 15 */ 36, 29, 23, 18, 15,
1567 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1569 * In cases where the weight does not change often, we can use the
1570 * precalculated inverse to speed up arithmetics by turning divisions
1571 * into multiplications:
1573 static const u32 prio_to_wmult[40] = {
1574 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1575 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1576 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1577 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1578 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1579 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1580 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1581 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1584 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1587 * runqueue iterator, to support SMP load-balancing between different
1588 * scheduling classes, without having to expose their internal data
1589 * structures to the load-balancing proper:
1591 struct rq_iterator {
1592 void *arg;
1593 struct task_struct *(*start)(void *);
1594 struct task_struct *(*next)(void *);
1597 #ifdef CONFIG_SMP
1598 static unsigned long
1599 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1600 unsigned long max_load_move, struct sched_domain *sd,
1601 enum cpu_idle_type idle, int *all_pinned,
1602 int *this_best_prio, struct rq_iterator *iterator);
1604 static int
1605 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1606 struct sched_domain *sd, enum cpu_idle_type idle,
1607 struct rq_iterator *iterator);
1608 #endif
1610 #ifdef CONFIG_CGROUP_CPUACCT
1611 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1612 #else
1613 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1614 #endif
1616 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1618 update_load_add(&rq->load, load);
1621 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1623 update_load_sub(&rq->load, load);
1626 #ifdef CONFIG_SMP
1627 static unsigned long source_load(int cpu, int type);
1628 static unsigned long target_load(int cpu, int type);
1629 static unsigned long cpu_avg_load_per_task(int cpu);
1630 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1632 #ifdef CONFIG_FAIR_GROUP_SCHED
1635 * Group load balancing.
1637 * We calculate a few balance domain wide aggregate numbers; load and weight.
1638 * Given the pictures below, and assuming each item has equal weight:
1640 * root 1 - thread
1641 * / | \ A - group
1642 * A 1 B
1643 * /|\ / \
1644 * C 2 D 3 4
1645 * | |
1646 * 5 6
1648 * load:
1649 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1650 * which equals 1/9-th of the total load.
1652 * shares:
1653 * The weight of this group on the selected cpus.
1655 * rq_weight:
1656 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1657 * B would get 2.
1659 * task_weight:
1660 * Part of the rq_weight contributed by tasks; all groups except B would
1661 * get 1, B gets 2.
1664 static inline struct aggregate_struct *
1665 aggregate(struct task_group *tg, struct sched_domain *sd)
1667 return &tg->cfs_rq[sd->first_cpu]->aggregate;
1670 typedef void (*aggregate_func)(struct task_group *, struct sched_domain *);
1673 * Iterate the full tree, calling @down when first entering a node and @up when
1674 * leaving it for the final time.
1676 static
1677 void aggregate_walk_tree(aggregate_func down, aggregate_func up,
1678 struct sched_domain *sd)
1680 struct task_group *parent, *child;
1682 rcu_read_lock();
1683 parent = &root_task_group;
1684 down:
1685 (*down)(parent, sd);
1686 list_for_each_entry_rcu(child, &parent->children, siblings) {
1687 parent = child;
1688 goto down;
1691 continue;
1693 (*up)(parent, sd);
1695 child = parent;
1696 parent = parent->parent;
1697 if (parent)
1698 goto up;
1699 rcu_read_unlock();
1703 * Calculate the aggregate runqueue weight.
1705 static
1706 void aggregate_group_weight(struct task_group *tg, struct sched_domain *sd)
1708 unsigned long rq_weight = 0;
1709 unsigned long task_weight = 0;
1710 int i;
1712 for_each_cpu_mask(i, sd->span) {
1713 rq_weight += tg->cfs_rq[i]->load.weight;
1714 task_weight += tg->cfs_rq[i]->task_weight;
1717 aggregate(tg, sd)->rq_weight = rq_weight;
1718 aggregate(tg, sd)->task_weight = task_weight;
1722 * Compute the weight of this group on the given cpus.
1724 static
1725 void aggregate_group_shares(struct task_group *tg, struct sched_domain *sd)
1727 unsigned long shares = 0;
1728 int i;
1730 for_each_cpu_mask(i, sd->span)
1731 shares += tg->cfs_rq[i]->shares;
1733 if ((!shares && aggregate(tg, sd)->rq_weight) || shares > tg->shares)
1734 shares = tg->shares;
1736 aggregate(tg, sd)->shares = shares;
1740 * Compute the load fraction assigned to this group, relies on the aggregate
1741 * weight and this group's parent's load, i.e. top-down.
1743 static
1744 void aggregate_group_load(struct task_group *tg, struct sched_domain *sd)
1746 unsigned long load;
1748 if (!tg->parent) {
1749 int i;
1751 load = 0;
1752 for_each_cpu_mask(i, sd->span)
1753 load += cpu_rq(i)->load.weight;
1755 } else {
1756 load = aggregate(tg->parent, sd)->load;
1759 * shares is our weight in the parent's rq so
1760 * shares/parent->rq_weight gives our fraction of the load
1762 load *= aggregate(tg, sd)->shares;
1763 load /= aggregate(tg->parent, sd)->rq_weight + 1;
1766 aggregate(tg, sd)->load = load;
1769 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1772 * Calculate and set the cpu's group shares.
1774 static void
1775 __update_group_shares_cpu(struct task_group *tg, struct sched_domain *sd,
1776 int tcpu)
1778 int boost = 0;
1779 unsigned long shares;
1780 unsigned long rq_weight;
1782 if (!tg->se[tcpu])
1783 return;
1785 rq_weight = tg->cfs_rq[tcpu]->load.weight;
1788 * If there are currently no tasks on the cpu pretend there is one of
1789 * average load so that when a new task gets to run here it will not
1790 * get delayed by group starvation.
1792 if (!rq_weight) {
1793 boost = 1;
1794 rq_weight = NICE_0_LOAD;
1798 * \Sum shares * rq_weight
1799 * shares = -----------------------
1800 * \Sum rq_weight
1803 shares = aggregate(tg, sd)->shares * rq_weight;
1804 shares /= aggregate(tg, sd)->rq_weight + 1;
1807 * record the actual number of shares, not the boosted amount.
1809 tg->cfs_rq[tcpu]->shares = boost ? 0 : shares;
1811 if (shares < MIN_SHARES)
1812 shares = MIN_SHARES;
1813 else if (shares > MAX_SHARES)
1814 shares = MAX_SHARES;
1816 __set_se_shares(tg->se[tcpu], shares);
1820 * Re-adjust the weights on the cpu the task came from and on the cpu the
1821 * task went to.
1823 static void
1824 __move_group_shares(struct task_group *tg, struct sched_domain *sd,
1825 int scpu, int dcpu)
1827 unsigned long shares;
1829 shares = tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1831 __update_group_shares_cpu(tg, sd, scpu);
1832 __update_group_shares_cpu(tg, sd, dcpu);
1835 * ensure we never loose shares due to rounding errors in the
1836 * above redistribution.
1838 shares -= tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1839 if (shares)
1840 tg->cfs_rq[dcpu]->shares += shares;
1844 * Because changing a group's shares changes the weight of the super-group
1845 * we need to walk up the tree and change all shares until we hit the root.
1847 static void
1848 move_group_shares(struct task_group *tg, struct sched_domain *sd,
1849 int scpu, int dcpu)
1851 while (tg) {
1852 __move_group_shares(tg, sd, scpu, dcpu);
1853 tg = tg->parent;
1857 static
1858 void aggregate_group_set_shares(struct task_group *tg, struct sched_domain *sd)
1860 unsigned long shares = aggregate(tg, sd)->shares;
1861 int i;
1863 for_each_cpu_mask(i, sd->span) {
1864 struct rq *rq = cpu_rq(i);
1865 unsigned long flags;
1867 spin_lock_irqsave(&rq->lock, flags);
1868 __update_group_shares_cpu(tg, sd, i);
1869 spin_unlock_irqrestore(&rq->lock, flags);
1872 aggregate_group_shares(tg, sd);
1875 * ensure we never loose shares due to rounding errors in the
1876 * above redistribution.
1878 shares -= aggregate(tg, sd)->shares;
1879 if (shares) {
1880 tg->cfs_rq[sd->first_cpu]->shares += shares;
1881 aggregate(tg, sd)->shares += shares;
1886 * Calculate the accumulative weight and recursive load of each task group
1887 * while walking down the tree.
1889 static
1890 void aggregate_get_down(struct task_group *tg, struct sched_domain *sd)
1892 aggregate_group_weight(tg, sd);
1893 aggregate_group_shares(tg, sd);
1894 aggregate_group_load(tg, sd);
1898 * Rebalance the cpu shares while walking back up the tree.
1900 static
1901 void aggregate_get_up(struct task_group *tg, struct sched_domain *sd)
1903 aggregate_group_set_shares(tg, sd);
1906 static DEFINE_PER_CPU(spinlock_t, aggregate_lock);
1908 static void __init init_aggregate(void)
1910 int i;
1912 for_each_possible_cpu(i)
1913 spin_lock_init(&per_cpu(aggregate_lock, i));
1916 static int get_aggregate(struct sched_domain *sd)
1918 if (!spin_trylock(&per_cpu(aggregate_lock, sd->first_cpu)))
1919 return 0;
1921 aggregate_walk_tree(aggregate_get_down, aggregate_get_up, sd);
1922 return 1;
1925 static void put_aggregate(struct sched_domain *sd)
1927 spin_unlock(&per_cpu(aggregate_lock, sd->first_cpu));
1930 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1932 cfs_rq->shares = shares;
1935 #else
1937 static inline void init_aggregate(void)
1941 static inline int get_aggregate(struct sched_domain *sd)
1943 return 0;
1946 static inline void put_aggregate(struct sched_domain *sd)
1949 #endif
1951 #else /* CONFIG_SMP */
1953 #ifdef CONFIG_FAIR_GROUP_SCHED
1954 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1957 #endif
1959 #endif /* CONFIG_SMP */
1961 #include "sched_stats.h"
1962 #include "sched_idletask.c"
1963 #include "sched_fair.c"
1964 #include "sched_rt.c"
1965 #ifdef CONFIG_SCHED_DEBUG
1966 # include "sched_debug.c"
1967 #endif
1969 #define sched_class_highest (&rt_sched_class)
1971 static void inc_nr_running(struct rq *rq)
1973 rq->nr_running++;
1976 static void dec_nr_running(struct rq *rq)
1978 rq->nr_running--;
1981 static void set_load_weight(struct task_struct *p)
1983 if (task_has_rt_policy(p)) {
1984 p->se.load.weight = prio_to_weight[0] * 2;
1985 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1986 return;
1990 * SCHED_IDLE tasks get minimal weight:
1992 if (p->policy == SCHED_IDLE) {
1993 p->se.load.weight = WEIGHT_IDLEPRIO;
1994 p->se.load.inv_weight = WMULT_IDLEPRIO;
1995 return;
1998 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1999 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
2002 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
2004 sched_info_queued(p);
2005 p->sched_class->enqueue_task(rq, p, wakeup);
2006 p->se.on_rq = 1;
2009 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
2011 p->sched_class->dequeue_task(rq, p, sleep);
2012 p->se.on_rq = 0;
2016 * __normal_prio - return the priority that is based on the static prio
2018 static inline int __normal_prio(struct task_struct *p)
2020 return p->static_prio;
2024 * Calculate the expected normal priority: i.e. priority
2025 * without taking RT-inheritance into account. Might be
2026 * boosted by interactivity modifiers. Changes upon fork,
2027 * setprio syscalls, and whenever the interactivity
2028 * estimator recalculates.
2030 static inline int normal_prio(struct task_struct *p)
2032 int prio;
2034 if (task_has_rt_policy(p))
2035 prio = MAX_RT_PRIO-1 - p->rt_priority;
2036 else
2037 prio = __normal_prio(p);
2038 return prio;
2042 * Calculate the current priority, i.e. the priority
2043 * taken into account by the scheduler. This value might
2044 * be boosted by RT tasks, or might be boosted by
2045 * interactivity modifiers. Will be RT if the task got
2046 * RT-boosted. If not then it returns p->normal_prio.
2048 static int effective_prio(struct task_struct *p)
2050 p->normal_prio = normal_prio(p);
2052 * If we are RT tasks or we were boosted to RT priority,
2053 * keep the priority unchanged. Otherwise, update priority
2054 * to the normal priority:
2056 if (!rt_prio(p->prio))
2057 return p->normal_prio;
2058 return p->prio;
2062 * activate_task - move a task to the runqueue.
2064 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
2066 if (task_contributes_to_load(p))
2067 rq->nr_uninterruptible--;
2069 enqueue_task(rq, p, wakeup);
2070 inc_nr_running(rq);
2074 * deactivate_task - remove a task from the runqueue.
2076 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
2078 if (task_contributes_to_load(p))
2079 rq->nr_uninterruptible++;
2081 dequeue_task(rq, p, sleep);
2082 dec_nr_running(rq);
2086 * task_curr - is this task currently executing on a CPU?
2087 * @p: the task in question.
2089 inline int task_curr(const struct task_struct *p)
2091 return cpu_curr(task_cpu(p)) == p;
2094 /* Used instead of source_load when we know the type == 0 */
2095 unsigned long weighted_cpuload(const int cpu)
2097 return cpu_rq(cpu)->load.weight;
2100 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
2102 set_task_rq(p, cpu);
2103 #ifdef CONFIG_SMP
2105 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
2106 * successfuly executed on another CPU. We must ensure that updates of
2107 * per-task data have been completed by this moment.
2109 smp_wmb();
2110 task_thread_info(p)->cpu = cpu;
2111 #endif
2114 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2115 const struct sched_class *prev_class,
2116 int oldprio, int running)
2118 if (prev_class != p->sched_class) {
2119 if (prev_class->switched_from)
2120 prev_class->switched_from(rq, p, running);
2121 p->sched_class->switched_to(rq, p, running);
2122 } else
2123 p->sched_class->prio_changed(rq, p, oldprio, running);
2126 #ifdef CONFIG_SMP
2129 * Is this task likely cache-hot:
2131 static int
2132 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2134 s64 delta;
2137 * Buddy candidates are cache hot:
2139 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
2140 return 1;
2142 if (p->sched_class != &fair_sched_class)
2143 return 0;
2145 if (sysctl_sched_migration_cost == -1)
2146 return 1;
2147 if (sysctl_sched_migration_cost == 0)
2148 return 0;
2150 delta = now - p->se.exec_start;
2152 return delta < (s64)sysctl_sched_migration_cost;
2156 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2158 int old_cpu = task_cpu(p);
2159 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2160 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2161 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2162 u64 clock_offset;
2164 clock_offset = old_rq->clock - new_rq->clock;
2166 #ifdef CONFIG_SCHEDSTATS
2167 if (p->se.wait_start)
2168 p->se.wait_start -= clock_offset;
2169 if (p->se.sleep_start)
2170 p->se.sleep_start -= clock_offset;
2171 if (p->se.block_start)
2172 p->se.block_start -= clock_offset;
2173 if (old_cpu != new_cpu) {
2174 schedstat_inc(p, se.nr_migrations);
2175 if (task_hot(p, old_rq->clock, NULL))
2176 schedstat_inc(p, se.nr_forced2_migrations);
2178 #endif
2179 p->se.vruntime -= old_cfsrq->min_vruntime -
2180 new_cfsrq->min_vruntime;
2182 __set_task_cpu(p, new_cpu);
2185 struct migration_req {
2186 struct list_head list;
2188 struct task_struct *task;
2189 int dest_cpu;
2191 struct completion done;
2195 * The task's runqueue lock must be held.
2196 * Returns true if you have to wait for migration thread.
2198 static int
2199 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2201 struct rq *rq = task_rq(p);
2204 * If the task is not on a runqueue (and not running), then
2205 * it is sufficient to simply update the task's cpu field.
2207 if (!p->se.on_rq && !task_running(rq, p)) {
2208 set_task_cpu(p, dest_cpu);
2209 return 0;
2212 init_completion(&req->done);
2213 req->task = p;
2214 req->dest_cpu = dest_cpu;
2215 list_add(&req->list, &rq->migration_queue);
2217 return 1;
2221 * wait_task_inactive - wait for a thread to unschedule.
2223 * The caller must ensure that the task *will* unschedule sometime soon,
2224 * else this function might spin for a *long* time. This function can't
2225 * be called with interrupts off, or it may introduce deadlock with
2226 * smp_call_function() if an IPI is sent by the same process we are
2227 * waiting to become inactive.
2229 void wait_task_inactive(struct task_struct *p)
2231 unsigned long flags;
2232 int running, on_rq;
2233 struct rq *rq;
2235 for (;;) {
2237 * We do the initial early heuristics without holding
2238 * any task-queue locks at all. We'll only try to get
2239 * the runqueue lock when things look like they will
2240 * work out!
2242 rq = task_rq(p);
2245 * If the task is actively running on another CPU
2246 * still, just relax and busy-wait without holding
2247 * any locks.
2249 * NOTE! Since we don't hold any locks, it's not
2250 * even sure that "rq" stays as the right runqueue!
2251 * But we don't care, since "task_running()" will
2252 * return false if the runqueue has changed and p
2253 * is actually now running somewhere else!
2255 while (task_running(rq, p))
2256 cpu_relax();
2259 * Ok, time to look more closely! We need the rq
2260 * lock now, to be *sure*. If we're wrong, we'll
2261 * just go back and repeat.
2263 rq = task_rq_lock(p, &flags);
2264 running = task_running(rq, p);
2265 on_rq = p->se.on_rq;
2266 task_rq_unlock(rq, &flags);
2269 * Was it really running after all now that we
2270 * checked with the proper locks actually held?
2272 * Oops. Go back and try again..
2274 if (unlikely(running)) {
2275 cpu_relax();
2276 continue;
2280 * It's not enough that it's not actively running,
2281 * it must be off the runqueue _entirely_, and not
2282 * preempted!
2284 * So if it wa still runnable (but just not actively
2285 * running right now), it's preempted, and we should
2286 * yield - it could be a while.
2288 if (unlikely(on_rq)) {
2289 schedule_timeout_uninterruptible(1);
2290 continue;
2294 * Ahh, all good. It wasn't running, and it wasn't
2295 * runnable, which means that it will never become
2296 * running in the future either. We're all done!
2298 break;
2302 /***
2303 * kick_process - kick a running thread to enter/exit the kernel
2304 * @p: the to-be-kicked thread
2306 * Cause a process which is running on another CPU to enter
2307 * kernel-mode, without any delay. (to get signals handled.)
2309 * NOTE: this function doesnt have to take the runqueue lock,
2310 * because all it wants to ensure is that the remote task enters
2311 * the kernel. If the IPI races and the task has been migrated
2312 * to another CPU then no harm is done and the purpose has been
2313 * achieved as well.
2315 void kick_process(struct task_struct *p)
2317 int cpu;
2319 preempt_disable();
2320 cpu = task_cpu(p);
2321 if ((cpu != smp_processor_id()) && task_curr(p))
2322 smp_send_reschedule(cpu);
2323 preempt_enable();
2327 * Return a low guess at the load of a migration-source cpu weighted
2328 * according to the scheduling class and "nice" value.
2330 * We want to under-estimate the load of migration sources, to
2331 * balance conservatively.
2333 static unsigned long source_load(int cpu, int type)
2335 struct rq *rq = cpu_rq(cpu);
2336 unsigned long total = weighted_cpuload(cpu);
2338 if (type == 0)
2339 return total;
2341 return min(rq->cpu_load[type-1], total);
2345 * Return a high guess at the load of a migration-target cpu weighted
2346 * according to the scheduling class and "nice" value.
2348 static unsigned long target_load(int cpu, int type)
2350 struct rq *rq = cpu_rq(cpu);
2351 unsigned long total = weighted_cpuload(cpu);
2353 if (type == 0)
2354 return total;
2356 return max(rq->cpu_load[type-1], total);
2360 * Return the average load per task on the cpu's run queue
2362 static unsigned long cpu_avg_load_per_task(int cpu)
2364 struct rq *rq = cpu_rq(cpu);
2365 unsigned long total = weighted_cpuload(cpu);
2366 unsigned long n = rq->nr_running;
2368 return n ? total / n : SCHED_LOAD_SCALE;
2372 * find_idlest_group finds and returns the least busy CPU group within the
2373 * domain.
2375 static struct sched_group *
2376 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2378 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2379 unsigned long min_load = ULONG_MAX, this_load = 0;
2380 int load_idx = sd->forkexec_idx;
2381 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2383 do {
2384 unsigned long load, avg_load;
2385 int local_group;
2386 int i;
2388 /* Skip over this group if it has no CPUs allowed */
2389 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2390 continue;
2392 local_group = cpu_isset(this_cpu, group->cpumask);
2394 /* Tally up the load of all CPUs in the group */
2395 avg_load = 0;
2397 for_each_cpu_mask(i, group->cpumask) {
2398 /* Bias balancing toward cpus of our domain */
2399 if (local_group)
2400 load = source_load(i, load_idx);
2401 else
2402 load = target_load(i, load_idx);
2404 avg_load += load;
2407 /* Adjust by relative CPU power of the group */
2408 avg_load = sg_div_cpu_power(group,
2409 avg_load * SCHED_LOAD_SCALE);
2411 if (local_group) {
2412 this_load = avg_load;
2413 this = group;
2414 } else if (avg_load < min_load) {
2415 min_load = avg_load;
2416 idlest = group;
2418 } while (group = group->next, group != sd->groups);
2420 if (!idlest || 100*this_load < imbalance*min_load)
2421 return NULL;
2422 return idlest;
2426 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2428 static int
2429 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2430 cpumask_t *tmp)
2432 unsigned long load, min_load = ULONG_MAX;
2433 int idlest = -1;
2434 int i;
2436 /* Traverse only the allowed CPUs */
2437 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2439 for_each_cpu_mask(i, *tmp) {
2440 load = weighted_cpuload(i);
2442 if (load < min_load || (load == min_load && i == this_cpu)) {
2443 min_load = load;
2444 idlest = i;
2448 return idlest;
2452 * sched_balance_self: balance the current task (running on cpu) in domains
2453 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2454 * SD_BALANCE_EXEC.
2456 * Balance, ie. select the least loaded group.
2458 * Returns the target CPU number, or the same CPU if no balancing is needed.
2460 * preempt must be disabled.
2462 static int sched_balance_self(int cpu, int flag)
2464 struct task_struct *t = current;
2465 struct sched_domain *tmp, *sd = NULL;
2467 for_each_domain(cpu, tmp) {
2469 * If power savings logic is enabled for a domain, stop there.
2471 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2472 break;
2473 if (tmp->flags & flag)
2474 sd = tmp;
2477 while (sd) {
2478 cpumask_t span, tmpmask;
2479 struct sched_group *group;
2480 int new_cpu, weight;
2482 if (!(sd->flags & flag)) {
2483 sd = sd->child;
2484 continue;
2487 span = sd->span;
2488 group = find_idlest_group(sd, t, cpu);
2489 if (!group) {
2490 sd = sd->child;
2491 continue;
2494 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2495 if (new_cpu == -1 || new_cpu == cpu) {
2496 /* Now try balancing at a lower domain level of cpu */
2497 sd = sd->child;
2498 continue;
2501 /* Now try balancing at a lower domain level of new_cpu */
2502 cpu = new_cpu;
2503 sd = NULL;
2504 weight = cpus_weight(span);
2505 for_each_domain(cpu, tmp) {
2506 if (weight <= cpus_weight(tmp->span))
2507 break;
2508 if (tmp->flags & flag)
2509 sd = tmp;
2511 /* while loop will break here if sd == NULL */
2514 return cpu;
2517 #endif /* CONFIG_SMP */
2519 /***
2520 * try_to_wake_up - wake up a thread
2521 * @p: the to-be-woken-up thread
2522 * @state: the mask of task states that can be woken
2523 * @sync: do a synchronous wakeup?
2525 * Put it on the run-queue if it's not already there. The "current"
2526 * thread is always on the run-queue (except when the actual
2527 * re-schedule is in progress), and as such you're allowed to do
2528 * the simpler "current->state = TASK_RUNNING" to mark yourself
2529 * runnable without the overhead of this.
2531 * returns failure only if the task is already active.
2533 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2535 int cpu, orig_cpu, this_cpu, success = 0;
2536 unsigned long flags;
2537 long old_state;
2538 struct rq *rq;
2540 if (!sched_feat(SYNC_WAKEUPS))
2541 sync = 0;
2543 smp_wmb();
2544 rq = task_rq_lock(p, &flags);
2545 old_state = p->state;
2546 if (!(old_state & state))
2547 goto out;
2549 if (p->se.on_rq)
2550 goto out_running;
2552 cpu = task_cpu(p);
2553 orig_cpu = cpu;
2554 this_cpu = smp_processor_id();
2556 #ifdef CONFIG_SMP
2557 if (unlikely(task_running(rq, p)))
2558 goto out_activate;
2560 cpu = p->sched_class->select_task_rq(p, sync);
2561 if (cpu != orig_cpu) {
2562 set_task_cpu(p, cpu);
2563 task_rq_unlock(rq, &flags);
2564 /* might preempt at this point */
2565 rq = task_rq_lock(p, &flags);
2566 old_state = p->state;
2567 if (!(old_state & state))
2568 goto out;
2569 if (p->se.on_rq)
2570 goto out_running;
2572 this_cpu = smp_processor_id();
2573 cpu = task_cpu(p);
2576 #ifdef CONFIG_SCHEDSTATS
2577 schedstat_inc(rq, ttwu_count);
2578 if (cpu == this_cpu)
2579 schedstat_inc(rq, ttwu_local);
2580 else {
2581 struct sched_domain *sd;
2582 for_each_domain(this_cpu, sd) {
2583 if (cpu_isset(cpu, sd->span)) {
2584 schedstat_inc(sd, ttwu_wake_remote);
2585 break;
2589 #endif
2591 out_activate:
2592 #endif /* CONFIG_SMP */
2593 schedstat_inc(p, se.nr_wakeups);
2594 if (sync)
2595 schedstat_inc(p, se.nr_wakeups_sync);
2596 if (orig_cpu != cpu)
2597 schedstat_inc(p, se.nr_wakeups_migrate);
2598 if (cpu == this_cpu)
2599 schedstat_inc(p, se.nr_wakeups_local);
2600 else
2601 schedstat_inc(p, se.nr_wakeups_remote);
2602 update_rq_clock(rq);
2603 activate_task(rq, p, 1);
2604 success = 1;
2606 out_running:
2607 check_preempt_curr(rq, p);
2609 p->state = TASK_RUNNING;
2610 #ifdef CONFIG_SMP
2611 if (p->sched_class->task_wake_up)
2612 p->sched_class->task_wake_up(rq, p);
2613 #endif
2614 out:
2615 task_rq_unlock(rq, &flags);
2617 return success;
2620 int wake_up_process(struct task_struct *p)
2622 return try_to_wake_up(p, TASK_ALL, 0);
2624 EXPORT_SYMBOL(wake_up_process);
2626 int wake_up_state(struct task_struct *p, unsigned int state)
2628 return try_to_wake_up(p, state, 0);
2632 * Perform scheduler related setup for a newly forked process p.
2633 * p is forked by current.
2635 * __sched_fork() is basic setup used by init_idle() too:
2637 static void __sched_fork(struct task_struct *p)
2639 p->se.exec_start = 0;
2640 p->se.sum_exec_runtime = 0;
2641 p->se.prev_sum_exec_runtime = 0;
2642 p->se.last_wakeup = 0;
2643 p->se.avg_overlap = 0;
2645 #ifdef CONFIG_SCHEDSTATS
2646 p->se.wait_start = 0;
2647 p->se.sum_sleep_runtime = 0;
2648 p->se.sleep_start = 0;
2649 p->se.block_start = 0;
2650 p->se.sleep_max = 0;
2651 p->se.block_max = 0;
2652 p->se.exec_max = 0;
2653 p->se.slice_max = 0;
2654 p->se.wait_max = 0;
2655 #endif
2657 INIT_LIST_HEAD(&p->rt.run_list);
2658 p->se.on_rq = 0;
2659 INIT_LIST_HEAD(&p->se.group_node);
2661 #ifdef CONFIG_PREEMPT_NOTIFIERS
2662 INIT_HLIST_HEAD(&p->preempt_notifiers);
2663 #endif
2666 * We mark the process as running here, but have not actually
2667 * inserted it onto the runqueue yet. This guarantees that
2668 * nobody will actually run it, and a signal or other external
2669 * event cannot wake it up and insert it on the runqueue either.
2671 p->state = TASK_RUNNING;
2675 * fork()/clone()-time setup:
2677 void sched_fork(struct task_struct *p, int clone_flags)
2679 int cpu = get_cpu();
2681 __sched_fork(p);
2683 #ifdef CONFIG_SMP
2684 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2685 #endif
2686 set_task_cpu(p, cpu);
2689 * Make sure we do not leak PI boosting priority to the child:
2691 p->prio = current->normal_prio;
2692 if (!rt_prio(p->prio))
2693 p->sched_class = &fair_sched_class;
2695 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2696 if (likely(sched_info_on()))
2697 memset(&p->sched_info, 0, sizeof(p->sched_info));
2698 #endif
2699 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2700 p->oncpu = 0;
2701 #endif
2702 #ifdef CONFIG_PREEMPT
2703 /* Want to start with kernel preemption disabled. */
2704 task_thread_info(p)->preempt_count = 1;
2705 #endif
2706 put_cpu();
2710 * wake_up_new_task - wake up a newly created task for the first time.
2712 * This function will do some initial scheduler statistics housekeeping
2713 * that must be done for every newly created context, then puts the task
2714 * on the runqueue and wakes it.
2716 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2718 unsigned long flags;
2719 struct rq *rq;
2721 rq = task_rq_lock(p, &flags);
2722 BUG_ON(p->state != TASK_RUNNING);
2723 update_rq_clock(rq);
2725 p->prio = effective_prio(p);
2727 if (!p->sched_class->task_new || !current->se.on_rq) {
2728 activate_task(rq, p, 0);
2729 } else {
2731 * Let the scheduling class do new task startup
2732 * management (if any):
2734 p->sched_class->task_new(rq, p);
2735 inc_nr_running(rq);
2737 check_preempt_curr(rq, p);
2738 #ifdef CONFIG_SMP
2739 if (p->sched_class->task_wake_up)
2740 p->sched_class->task_wake_up(rq, p);
2741 #endif
2742 task_rq_unlock(rq, &flags);
2745 #ifdef CONFIG_PREEMPT_NOTIFIERS
2748 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2749 * @notifier: notifier struct to register
2751 void preempt_notifier_register(struct preempt_notifier *notifier)
2753 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2755 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2758 * preempt_notifier_unregister - no longer interested in preemption notifications
2759 * @notifier: notifier struct to unregister
2761 * This is safe to call from within a preemption notifier.
2763 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2765 hlist_del(&notifier->link);
2767 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2769 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2771 struct preempt_notifier *notifier;
2772 struct hlist_node *node;
2774 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2775 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2778 static void
2779 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2780 struct task_struct *next)
2782 struct preempt_notifier *notifier;
2783 struct hlist_node *node;
2785 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2786 notifier->ops->sched_out(notifier, next);
2789 #else
2791 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2795 static void
2796 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2797 struct task_struct *next)
2801 #endif
2804 * prepare_task_switch - prepare to switch tasks
2805 * @rq: the runqueue preparing to switch
2806 * @prev: the current task that is being switched out
2807 * @next: the task we are going to switch to.
2809 * This is called with the rq lock held and interrupts off. It must
2810 * be paired with a subsequent finish_task_switch after the context
2811 * switch.
2813 * prepare_task_switch sets up locking and calls architecture specific
2814 * hooks.
2816 static inline void
2817 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2818 struct task_struct *next)
2820 fire_sched_out_preempt_notifiers(prev, next);
2821 prepare_lock_switch(rq, next);
2822 prepare_arch_switch(next);
2826 * finish_task_switch - clean up after a task-switch
2827 * @rq: runqueue associated with task-switch
2828 * @prev: the thread we just switched away from.
2830 * finish_task_switch must be called after the context switch, paired
2831 * with a prepare_task_switch call before the context switch.
2832 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2833 * and do any other architecture-specific cleanup actions.
2835 * Note that we may have delayed dropping an mm in context_switch(). If
2836 * so, we finish that here outside of the runqueue lock. (Doing it
2837 * with the lock held can cause deadlocks; see schedule() for
2838 * details.)
2840 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2841 __releases(rq->lock)
2843 struct mm_struct *mm = rq->prev_mm;
2844 long prev_state;
2846 rq->prev_mm = NULL;
2849 * A task struct has one reference for the use as "current".
2850 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2851 * schedule one last time. The schedule call will never return, and
2852 * the scheduled task must drop that reference.
2853 * The test for TASK_DEAD must occur while the runqueue locks are
2854 * still held, otherwise prev could be scheduled on another cpu, die
2855 * there before we look at prev->state, and then the reference would
2856 * be dropped twice.
2857 * Manfred Spraul <manfred@colorfullife.com>
2859 prev_state = prev->state;
2860 finish_arch_switch(prev);
2861 finish_lock_switch(rq, prev);
2862 #ifdef CONFIG_SMP
2863 if (current->sched_class->post_schedule)
2864 current->sched_class->post_schedule(rq);
2865 #endif
2867 fire_sched_in_preempt_notifiers(current);
2868 if (mm)
2869 mmdrop(mm);
2870 if (unlikely(prev_state == TASK_DEAD)) {
2872 * Remove function-return probe instances associated with this
2873 * task and put them back on the free list.
2875 kprobe_flush_task(prev);
2876 put_task_struct(prev);
2881 * schedule_tail - first thing a freshly forked thread must call.
2882 * @prev: the thread we just switched away from.
2884 asmlinkage void schedule_tail(struct task_struct *prev)
2885 __releases(rq->lock)
2887 struct rq *rq = this_rq();
2889 finish_task_switch(rq, prev);
2890 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2891 /* In this case, finish_task_switch does not reenable preemption */
2892 preempt_enable();
2893 #endif
2894 if (current->set_child_tid)
2895 put_user(task_pid_vnr(current), current->set_child_tid);
2899 * context_switch - switch to the new MM and the new
2900 * thread's register state.
2902 static inline void
2903 context_switch(struct rq *rq, struct task_struct *prev,
2904 struct task_struct *next)
2906 struct mm_struct *mm, *oldmm;
2908 prepare_task_switch(rq, prev, next);
2909 mm = next->mm;
2910 oldmm = prev->active_mm;
2912 * For paravirt, this is coupled with an exit in switch_to to
2913 * combine the page table reload and the switch backend into
2914 * one hypercall.
2916 arch_enter_lazy_cpu_mode();
2918 if (unlikely(!mm)) {
2919 next->active_mm = oldmm;
2920 atomic_inc(&oldmm->mm_count);
2921 enter_lazy_tlb(oldmm, next);
2922 } else
2923 switch_mm(oldmm, mm, next);
2925 if (unlikely(!prev->mm)) {
2926 prev->active_mm = NULL;
2927 rq->prev_mm = oldmm;
2930 * Since the runqueue lock will be released by the next
2931 * task (which is an invalid locking op but in the case
2932 * of the scheduler it's an obvious special-case), so we
2933 * do an early lockdep release here:
2935 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2936 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2937 #endif
2939 /* Here we just switch the register state and the stack. */
2940 switch_to(prev, next, prev);
2942 barrier();
2944 * this_rq must be evaluated again because prev may have moved
2945 * CPUs since it called schedule(), thus the 'rq' on its stack
2946 * frame will be invalid.
2948 finish_task_switch(this_rq(), prev);
2952 * nr_running, nr_uninterruptible and nr_context_switches:
2954 * externally visible scheduler statistics: current number of runnable
2955 * threads, current number of uninterruptible-sleeping threads, total
2956 * number of context switches performed since bootup.
2958 unsigned long nr_running(void)
2960 unsigned long i, sum = 0;
2962 for_each_online_cpu(i)
2963 sum += cpu_rq(i)->nr_running;
2965 return sum;
2968 unsigned long nr_uninterruptible(void)
2970 unsigned long i, sum = 0;
2972 for_each_possible_cpu(i)
2973 sum += cpu_rq(i)->nr_uninterruptible;
2976 * Since we read the counters lockless, it might be slightly
2977 * inaccurate. Do not allow it to go below zero though:
2979 if (unlikely((long)sum < 0))
2980 sum = 0;
2982 return sum;
2985 unsigned long long nr_context_switches(void)
2987 int i;
2988 unsigned long long sum = 0;
2990 for_each_possible_cpu(i)
2991 sum += cpu_rq(i)->nr_switches;
2993 return sum;
2996 unsigned long nr_iowait(void)
2998 unsigned long i, sum = 0;
3000 for_each_possible_cpu(i)
3001 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3003 return sum;
3006 unsigned long nr_active(void)
3008 unsigned long i, running = 0, uninterruptible = 0;
3010 for_each_online_cpu(i) {
3011 running += cpu_rq(i)->nr_running;
3012 uninterruptible += cpu_rq(i)->nr_uninterruptible;
3015 if (unlikely((long)uninterruptible < 0))
3016 uninterruptible = 0;
3018 return running + uninterruptible;
3022 * Update rq->cpu_load[] statistics. This function is usually called every
3023 * scheduler tick (TICK_NSEC).
3025 static void update_cpu_load(struct rq *this_rq)
3027 unsigned long this_load = this_rq->load.weight;
3028 int i, scale;
3030 this_rq->nr_load_updates++;
3032 /* Update our load: */
3033 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3034 unsigned long old_load, new_load;
3036 /* scale is effectively 1 << i now, and >> i divides by scale */
3038 old_load = this_rq->cpu_load[i];
3039 new_load = this_load;
3041 * Round up the averaging division if load is increasing. This
3042 * prevents us from getting stuck on 9 if the load is 10, for
3043 * example.
3045 if (new_load > old_load)
3046 new_load += scale-1;
3047 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3051 #ifdef CONFIG_SMP
3054 * double_rq_lock - safely lock two runqueues
3056 * Note this does not disable interrupts like task_rq_lock,
3057 * you need to do so manually before calling.
3059 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3060 __acquires(rq1->lock)
3061 __acquires(rq2->lock)
3063 BUG_ON(!irqs_disabled());
3064 if (rq1 == rq2) {
3065 spin_lock(&rq1->lock);
3066 __acquire(rq2->lock); /* Fake it out ;) */
3067 } else {
3068 if (rq1 < rq2) {
3069 spin_lock(&rq1->lock);
3070 spin_lock(&rq2->lock);
3071 } else {
3072 spin_lock(&rq2->lock);
3073 spin_lock(&rq1->lock);
3076 update_rq_clock(rq1);
3077 update_rq_clock(rq2);
3081 * double_rq_unlock - safely unlock two runqueues
3083 * Note this does not restore interrupts like task_rq_unlock,
3084 * you need to do so manually after calling.
3086 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3087 __releases(rq1->lock)
3088 __releases(rq2->lock)
3090 spin_unlock(&rq1->lock);
3091 if (rq1 != rq2)
3092 spin_unlock(&rq2->lock);
3093 else
3094 __release(rq2->lock);
3098 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
3100 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
3101 __releases(this_rq->lock)
3102 __acquires(busiest->lock)
3103 __acquires(this_rq->lock)
3105 int ret = 0;
3107 if (unlikely(!irqs_disabled())) {
3108 /* printk() doesn't work good under rq->lock */
3109 spin_unlock(&this_rq->lock);
3110 BUG_ON(1);
3112 if (unlikely(!spin_trylock(&busiest->lock))) {
3113 if (busiest < this_rq) {
3114 spin_unlock(&this_rq->lock);
3115 spin_lock(&busiest->lock);
3116 spin_lock(&this_rq->lock);
3117 ret = 1;
3118 } else
3119 spin_lock(&busiest->lock);
3121 return ret;
3125 * If dest_cpu is allowed for this process, migrate the task to it.
3126 * This is accomplished by forcing the cpu_allowed mask to only
3127 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3128 * the cpu_allowed mask is restored.
3130 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3132 struct migration_req req;
3133 unsigned long flags;
3134 struct rq *rq;
3136 rq = task_rq_lock(p, &flags);
3137 if (!cpu_isset(dest_cpu, p->cpus_allowed)
3138 || unlikely(cpu_is_offline(dest_cpu)))
3139 goto out;
3141 /* force the process onto the specified CPU */
3142 if (migrate_task(p, dest_cpu, &req)) {
3143 /* Need to wait for migration thread (might exit: take ref). */
3144 struct task_struct *mt = rq->migration_thread;
3146 get_task_struct(mt);
3147 task_rq_unlock(rq, &flags);
3148 wake_up_process(mt);
3149 put_task_struct(mt);
3150 wait_for_completion(&req.done);
3152 return;
3154 out:
3155 task_rq_unlock(rq, &flags);
3159 * sched_exec - execve() is a valuable balancing opportunity, because at
3160 * this point the task has the smallest effective memory and cache footprint.
3162 void sched_exec(void)
3164 int new_cpu, this_cpu = get_cpu();
3165 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3166 put_cpu();
3167 if (new_cpu != this_cpu)
3168 sched_migrate_task(current, new_cpu);
3172 * pull_task - move a task from a remote runqueue to the local runqueue.
3173 * Both runqueues must be locked.
3175 static void pull_task(struct rq *src_rq, struct task_struct *p,
3176 struct rq *this_rq, int this_cpu)
3178 deactivate_task(src_rq, p, 0);
3179 set_task_cpu(p, this_cpu);
3180 activate_task(this_rq, p, 0);
3182 * Note that idle threads have a prio of MAX_PRIO, for this test
3183 * to be always true for them.
3185 check_preempt_curr(this_rq, p);
3189 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3191 static
3192 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3193 struct sched_domain *sd, enum cpu_idle_type idle,
3194 int *all_pinned)
3197 * We do not migrate tasks that are:
3198 * 1) running (obviously), or
3199 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3200 * 3) are cache-hot on their current CPU.
3202 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
3203 schedstat_inc(p, se.nr_failed_migrations_affine);
3204 return 0;
3206 *all_pinned = 0;
3208 if (task_running(rq, p)) {
3209 schedstat_inc(p, se.nr_failed_migrations_running);
3210 return 0;
3214 * Aggressive migration if:
3215 * 1) task is cache cold, or
3216 * 2) too many balance attempts have failed.
3219 if (!task_hot(p, rq->clock, sd) ||
3220 sd->nr_balance_failed > sd->cache_nice_tries) {
3221 #ifdef CONFIG_SCHEDSTATS
3222 if (task_hot(p, rq->clock, sd)) {
3223 schedstat_inc(sd, lb_hot_gained[idle]);
3224 schedstat_inc(p, se.nr_forced_migrations);
3226 #endif
3227 return 1;
3230 if (task_hot(p, rq->clock, sd)) {
3231 schedstat_inc(p, se.nr_failed_migrations_hot);
3232 return 0;
3234 return 1;
3237 static unsigned long
3238 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3239 unsigned long max_load_move, struct sched_domain *sd,
3240 enum cpu_idle_type idle, int *all_pinned,
3241 int *this_best_prio, struct rq_iterator *iterator)
3243 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
3244 struct task_struct *p;
3245 long rem_load_move = max_load_move;
3247 if (max_load_move == 0)
3248 goto out;
3250 pinned = 1;
3253 * Start the load-balancing iterator:
3255 p = iterator->start(iterator->arg);
3256 next:
3257 if (!p || loops++ > sysctl_sched_nr_migrate)
3258 goto out;
3260 * To help distribute high priority tasks across CPUs we don't
3261 * skip a task if it will be the highest priority task (i.e. smallest
3262 * prio value) on its new queue regardless of its load weight
3264 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
3265 SCHED_LOAD_SCALE_FUZZ;
3266 if ((skip_for_load && p->prio >= *this_best_prio) ||
3267 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3268 p = iterator->next(iterator->arg);
3269 goto next;
3272 pull_task(busiest, p, this_rq, this_cpu);
3273 pulled++;
3274 rem_load_move -= p->se.load.weight;
3277 * We only want to steal up to the prescribed amount of weighted load.
3279 if (rem_load_move > 0) {
3280 if (p->prio < *this_best_prio)
3281 *this_best_prio = p->prio;
3282 p = iterator->next(iterator->arg);
3283 goto next;
3285 out:
3287 * Right now, this is one of only two places pull_task() is called,
3288 * so we can safely collect pull_task() stats here rather than
3289 * inside pull_task().
3291 schedstat_add(sd, lb_gained[idle], pulled);
3293 if (all_pinned)
3294 *all_pinned = pinned;
3296 return max_load_move - rem_load_move;
3300 * move_tasks tries to move up to max_load_move weighted load from busiest to
3301 * this_rq, as part of a balancing operation within domain "sd".
3302 * Returns 1 if successful and 0 otherwise.
3304 * Called with both runqueues locked.
3306 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3307 unsigned long max_load_move,
3308 struct sched_domain *sd, enum cpu_idle_type idle,
3309 int *all_pinned)
3311 const struct sched_class *class = sched_class_highest;
3312 unsigned long total_load_moved = 0;
3313 int this_best_prio = this_rq->curr->prio;
3315 do {
3316 total_load_moved +=
3317 class->load_balance(this_rq, this_cpu, busiest,
3318 max_load_move - total_load_moved,
3319 sd, idle, all_pinned, &this_best_prio);
3320 class = class->next;
3321 } while (class && max_load_move > total_load_moved);
3323 return total_load_moved > 0;
3326 static int
3327 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3328 struct sched_domain *sd, enum cpu_idle_type idle,
3329 struct rq_iterator *iterator)
3331 struct task_struct *p = iterator->start(iterator->arg);
3332 int pinned = 0;
3334 while (p) {
3335 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3336 pull_task(busiest, p, this_rq, this_cpu);
3338 * Right now, this is only the second place pull_task()
3339 * is called, so we can safely collect pull_task()
3340 * stats here rather than inside pull_task().
3342 schedstat_inc(sd, lb_gained[idle]);
3344 return 1;
3346 p = iterator->next(iterator->arg);
3349 return 0;
3353 * move_one_task tries to move exactly one task from busiest to this_rq, as
3354 * part of active balancing operations within "domain".
3355 * Returns 1 if successful and 0 otherwise.
3357 * Called with both runqueues locked.
3359 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3360 struct sched_domain *sd, enum cpu_idle_type idle)
3362 const struct sched_class *class;
3364 for (class = sched_class_highest; class; class = class->next)
3365 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3366 return 1;
3368 return 0;
3372 * find_busiest_group finds and returns the busiest CPU group within the
3373 * domain. It calculates and returns the amount of weighted load which
3374 * should be moved to restore balance via the imbalance parameter.
3376 static struct sched_group *
3377 find_busiest_group(struct sched_domain *sd, int this_cpu,
3378 unsigned long *imbalance, enum cpu_idle_type idle,
3379 int *sd_idle, const cpumask_t *cpus, int *balance)
3381 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3382 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3383 unsigned long max_pull;
3384 unsigned long busiest_load_per_task, busiest_nr_running;
3385 unsigned long this_load_per_task, this_nr_running;
3386 int load_idx, group_imb = 0;
3387 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3388 int power_savings_balance = 1;
3389 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3390 unsigned long min_nr_running = ULONG_MAX;
3391 struct sched_group *group_min = NULL, *group_leader = NULL;
3392 #endif
3394 max_load = this_load = total_load = total_pwr = 0;
3395 busiest_load_per_task = busiest_nr_running = 0;
3396 this_load_per_task = this_nr_running = 0;
3397 if (idle == CPU_NOT_IDLE)
3398 load_idx = sd->busy_idx;
3399 else if (idle == CPU_NEWLY_IDLE)
3400 load_idx = sd->newidle_idx;
3401 else
3402 load_idx = sd->idle_idx;
3404 do {
3405 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3406 int local_group;
3407 int i;
3408 int __group_imb = 0;
3409 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3410 unsigned long sum_nr_running, sum_weighted_load;
3412 local_group = cpu_isset(this_cpu, group->cpumask);
3414 if (local_group)
3415 balance_cpu = first_cpu(group->cpumask);
3417 /* Tally up the load of all CPUs in the group */
3418 sum_weighted_load = sum_nr_running = avg_load = 0;
3419 max_cpu_load = 0;
3420 min_cpu_load = ~0UL;
3422 for_each_cpu_mask(i, group->cpumask) {
3423 struct rq *rq;
3425 if (!cpu_isset(i, *cpus))
3426 continue;
3428 rq = cpu_rq(i);
3430 if (*sd_idle && rq->nr_running)
3431 *sd_idle = 0;
3433 /* Bias balancing toward cpus of our domain */
3434 if (local_group) {
3435 if (idle_cpu(i) && !first_idle_cpu) {
3436 first_idle_cpu = 1;
3437 balance_cpu = i;
3440 load = target_load(i, load_idx);
3441 } else {
3442 load = source_load(i, load_idx);
3443 if (load > max_cpu_load)
3444 max_cpu_load = load;
3445 if (min_cpu_load > load)
3446 min_cpu_load = load;
3449 avg_load += load;
3450 sum_nr_running += rq->nr_running;
3451 sum_weighted_load += weighted_cpuload(i);
3455 * First idle cpu or the first cpu(busiest) in this sched group
3456 * is eligible for doing load balancing at this and above
3457 * domains. In the newly idle case, we will allow all the cpu's
3458 * to do the newly idle load balance.
3460 if (idle != CPU_NEWLY_IDLE && local_group &&
3461 balance_cpu != this_cpu && balance) {
3462 *balance = 0;
3463 goto ret;
3466 total_load += avg_load;
3467 total_pwr += group->__cpu_power;
3469 /* Adjust by relative CPU power of the group */
3470 avg_load = sg_div_cpu_power(group,
3471 avg_load * SCHED_LOAD_SCALE);
3473 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
3474 __group_imb = 1;
3476 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3478 if (local_group) {
3479 this_load = avg_load;
3480 this = group;
3481 this_nr_running = sum_nr_running;
3482 this_load_per_task = sum_weighted_load;
3483 } else if (avg_load > max_load &&
3484 (sum_nr_running > group_capacity || __group_imb)) {
3485 max_load = avg_load;
3486 busiest = group;
3487 busiest_nr_running = sum_nr_running;
3488 busiest_load_per_task = sum_weighted_load;
3489 group_imb = __group_imb;
3492 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3494 * Busy processors will not participate in power savings
3495 * balance.
3497 if (idle == CPU_NOT_IDLE ||
3498 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3499 goto group_next;
3502 * If the local group is idle or completely loaded
3503 * no need to do power savings balance at this domain
3505 if (local_group && (this_nr_running >= group_capacity ||
3506 !this_nr_running))
3507 power_savings_balance = 0;
3510 * If a group is already running at full capacity or idle,
3511 * don't include that group in power savings calculations
3513 if (!power_savings_balance || sum_nr_running >= group_capacity
3514 || !sum_nr_running)
3515 goto group_next;
3518 * Calculate the group which has the least non-idle load.
3519 * This is the group from where we need to pick up the load
3520 * for saving power
3522 if ((sum_nr_running < min_nr_running) ||
3523 (sum_nr_running == min_nr_running &&
3524 first_cpu(group->cpumask) <
3525 first_cpu(group_min->cpumask))) {
3526 group_min = group;
3527 min_nr_running = sum_nr_running;
3528 min_load_per_task = sum_weighted_load /
3529 sum_nr_running;
3533 * Calculate the group which is almost near its
3534 * capacity but still has some space to pick up some load
3535 * from other group and save more power
3537 if (sum_nr_running <= group_capacity - 1) {
3538 if (sum_nr_running > leader_nr_running ||
3539 (sum_nr_running == leader_nr_running &&
3540 first_cpu(group->cpumask) >
3541 first_cpu(group_leader->cpumask))) {
3542 group_leader = group;
3543 leader_nr_running = sum_nr_running;
3546 group_next:
3547 #endif
3548 group = group->next;
3549 } while (group != sd->groups);
3551 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3552 goto out_balanced;
3554 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3556 if (this_load >= avg_load ||
3557 100*max_load <= sd->imbalance_pct*this_load)
3558 goto out_balanced;
3560 busiest_load_per_task /= busiest_nr_running;
3561 if (group_imb)
3562 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3565 * We're trying to get all the cpus to the average_load, so we don't
3566 * want to push ourselves above the average load, nor do we wish to
3567 * reduce the max loaded cpu below the average load, as either of these
3568 * actions would just result in more rebalancing later, and ping-pong
3569 * tasks around. Thus we look for the minimum possible imbalance.
3570 * Negative imbalances (*we* are more loaded than anyone else) will
3571 * be counted as no imbalance for these purposes -- we can't fix that
3572 * by pulling tasks to us. Be careful of negative numbers as they'll
3573 * appear as very large values with unsigned longs.
3575 if (max_load <= busiest_load_per_task)
3576 goto out_balanced;
3579 * In the presence of smp nice balancing, certain scenarios can have
3580 * max load less than avg load(as we skip the groups at or below
3581 * its cpu_power, while calculating max_load..)
3583 if (max_load < avg_load) {
3584 *imbalance = 0;
3585 goto small_imbalance;
3588 /* Don't want to pull so many tasks that a group would go idle */
3589 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3591 /* How much load to actually move to equalise the imbalance */
3592 *imbalance = min(max_pull * busiest->__cpu_power,
3593 (avg_load - this_load) * this->__cpu_power)
3594 / SCHED_LOAD_SCALE;
3597 * if *imbalance is less than the average load per runnable task
3598 * there is no gaurantee that any tasks will be moved so we'll have
3599 * a think about bumping its value to force at least one task to be
3600 * moved
3602 if (*imbalance < busiest_load_per_task) {
3603 unsigned long tmp, pwr_now, pwr_move;
3604 unsigned int imbn;
3606 small_imbalance:
3607 pwr_move = pwr_now = 0;
3608 imbn = 2;
3609 if (this_nr_running) {
3610 this_load_per_task /= this_nr_running;
3611 if (busiest_load_per_task > this_load_per_task)
3612 imbn = 1;
3613 } else
3614 this_load_per_task = SCHED_LOAD_SCALE;
3616 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3617 busiest_load_per_task * imbn) {
3618 *imbalance = busiest_load_per_task;
3619 return busiest;
3623 * OK, we don't have enough imbalance to justify moving tasks,
3624 * however we may be able to increase total CPU power used by
3625 * moving them.
3628 pwr_now += busiest->__cpu_power *
3629 min(busiest_load_per_task, max_load);
3630 pwr_now += this->__cpu_power *
3631 min(this_load_per_task, this_load);
3632 pwr_now /= SCHED_LOAD_SCALE;
3634 /* Amount of load we'd subtract */
3635 tmp = sg_div_cpu_power(busiest,
3636 busiest_load_per_task * SCHED_LOAD_SCALE);
3637 if (max_load > tmp)
3638 pwr_move += busiest->__cpu_power *
3639 min(busiest_load_per_task, max_load - tmp);
3641 /* Amount of load we'd add */
3642 if (max_load * busiest->__cpu_power <
3643 busiest_load_per_task * SCHED_LOAD_SCALE)
3644 tmp = sg_div_cpu_power(this,
3645 max_load * busiest->__cpu_power);
3646 else
3647 tmp = sg_div_cpu_power(this,
3648 busiest_load_per_task * SCHED_LOAD_SCALE);
3649 pwr_move += this->__cpu_power *
3650 min(this_load_per_task, this_load + tmp);
3651 pwr_move /= SCHED_LOAD_SCALE;
3653 /* Move if we gain throughput */
3654 if (pwr_move > pwr_now)
3655 *imbalance = busiest_load_per_task;
3658 return busiest;
3660 out_balanced:
3661 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3662 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3663 goto ret;
3665 if (this == group_leader && group_leader != group_min) {
3666 *imbalance = min_load_per_task;
3667 return group_min;
3669 #endif
3670 ret:
3671 *imbalance = 0;
3672 return NULL;
3676 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3678 static struct rq *
3679 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3680 unsigned long imbalance, const cpumask_t *cpus)
3682 struct rq *busiest = NULL, *rq;
3683 unsigned long max_load = 0;
3684 int i;
3686 for_each_cpu_mask(i, group->cpumask) {
3687 unsigned long wl;
3689 if (!cpu_isset(i, *cpus))
3690 continue;
3692 rq = cpu_rq(i);
3693 wl = weighted_cpuload(i);
3695 if (rq->nr_running == 1 && wl > imbalance)
3696 continue;
3698 if (wl > max_load) {
3699 max_load = wl;
3700 busiest = rq;
3704 return busiest;
3708 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3709 * so long as it is large enough.
3711 #define MAX_PINNED_INTERVAL 512
3714 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3715 * tasks if there is an imbalance.
3717 static int load_balance(int this_cpu, struct rq *this_rq,
3718 struct sched_domain *sd, enum cpu_idle_type idle,
3719 int *balance, cpumask_t *cpus)
3721 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3722 struct sched_group *group;
3723 unsigned long imbalance;
3724 struct rq *busiest;
3725 unsigned long flags;
3726 int unlock_aggregate;
3728 cpus_setall(*cpus);
3730 unlock_aggregate = get_aggregate(sd);
3733 * When power savings policy is enabled for the parent domain, idle
3734 * sibling can pick up load irrespective of busy siblings. In this case,
3735 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3736 * portraying it as CPU_NOT_IDLE.
3738 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3739 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3740 sd_idle = 1;
3742 schedstat_inc(sd, lb_count[idle]);
3744 redo:
3745 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3746 cpus, balance);
3748 if (*balance == 0)
3749 goto out_balanced;
3751 if (!group) {
3752 schedstat_inc(sd, lb_nobusyg[idle]);
3753 goto out_balanced;
3756 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3757 if (!busiest) {
3758 schedstat_inc(sd, lb_nobusyq[idle]);
3759 goto out_balanced;
3762 BUG_ON(busiest == this_rq);
3764 schedstat_add(sd, lb_imbalance[idle], imbalance);
3766 ld_moved = 0;
3767 if (busiest->nr_running > 1) {
3769 * Attempt to move tasks. If find_busiest_group has found
3770 * an imbalance but busiest->nr_running <= 1, the group is
3771 * still unbalanced. ld_moved simply stays zero, so it is
3772 * correctly treated as an imbalance.
3774 local_irq_save(flags);
3775 double_rq_lock(this_rq, busiest);
3776 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3777 imbalance, sd, idle, &all_pinned);
3778 double_rq_unlock(this_rq, busiest);
3779 local_irq_restore(flags);
3782 * some other cpu did the load balance for us.
3784 if (ld_moved && this_cpu != smp_processor_id())
3785 resched_cpu(this_cpu);
3787 /* All tasks on this runqueue were pinned by CPU affinity */
3788 if (unlikely(all_pinned)) {
3789 cpu_clear(cpu_of(busiest), *cpus);
3790 if (!cpus_empty(*cpus))
3791 goto redo;
3792 goto out_balanced;
3796 if (!ld_moved) {
3797 schedstat_inc(sd, lb_failed[idle]);
3798 sd->nr_balance_failed++;
3800 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3802 spin_lock_irqsave(&busiest->lock, flags);
3804 /* don't kick the migration_thread, if the curr
3805 * task on busiest cpu can't be moved to this_cpu
3807 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3808 spin_unlock_irqrestore(&busiest->lock, flags);
3809 all_pinned = 1;
3810 goto out_one_pinned;
3813 if (!busiest->active_balance) {
3814 busiest->active_balance = 1;
3815 busiest->push_cpu = this_cpu;
3816 active_balance = 1;
3818 spin_unlock_irqrestore(&busiest->lock, flags);
3819 if (active_balance)
3820 wake_up_process(busiest->migration_thread);
3823 * We've kicked active balancing, reset the failure
3824 * counter.
3826 sd->nr_balance_failed = sd->cache_nice_tries+1;
3828 } else
3829 sd->nr_balance_failed = 0;
3831 if (likely(!active_balance)) {
3832 /* We were unbalanced, so reset the balancing interval */
3833 sd->balance_interval = sd->min_interval;
3834 } else {
3836 * If we've begun active balancing, start to back off. This
3837 * case may not be covered by the all_pinned logic if there
3838 * is only 1 task on the busy runqueue (because we don't call
3839 * move_tasks).
3841 if (sd->balance_interval < sd->max_interval)
3842 sd->balance_interval *= 2;
3845 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3846 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3847 ld_moved = -1;
3849 goto out;
3851 out_balanced:
3852 schedstat_inc(sd, lb_balanced[idle]);
3854 sd->nr_balance_failed = 0;
3856 out_one_pinned:
3857 /* tune up the balancing interval */
3858 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3859 (sd->balance_interval < sd->max_interval))
3860 sd->balance_interval *= 2;
3862 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3863 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3864 ld_moved = -1;
3865 else
3866 ld_moved = 0;
3867 out:
3868 if (unlock_aggregate)
3869 put_aggregate(sd);
3870 return ld_moved;
3874 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3875 * tasks if there is an imbalance.
3877 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3878 * this_rq is locked.
3880 static int
3881 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3882 cpumask_t *cpus)
3884 struct sched_group *group;
3885 struct rq *busiest = NULL;
3886 unsigned long imbalance;
3887 int ld_moved = 0;
3888 int sd_idle = 0;
3889 int all_pinned = 0;
3891 cpus_setall(*cpus);
3894 * When power savings policy is enabled for the parent domain, idle
3895 * sibling can pick up load irrespective of busy siblings. In this case,
3896 * let the state of idle sibling percolate up as IDLE, instead of
3897 * portraying it as CPU_NOT_IDLE.
3899 if (sd->flags & SD_SHARE_CPUPOWER &&
3900 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3901 sd_idle = 1;
3903 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3904 redo:
3905 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3906 &sd_idle, cpus, NULL);
3907 if (!group) {
3908 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3909 goto out_balanced;
3912 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3913 if (!busiest) {
3914 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3915 goto out_balanced;
3918 BUG_ON(busiest == this_rq);
3920 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3922 ld_moved = 0;
3923 if (busiest->nr_running > 1) {
3924 /* Attempt to move tasks */
3925 double_lock_balance(this_rq, busiest);
3926 /* this_rq->clock is already updated */
3927 update_rq_clock(busiest);
3928 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3929 imbalance, sd, CPU_NEWLY_IDLE,
3930 &all_pinned);
3931 spin_unlock(&busiest->lock);
3933 if (unlikely(all_pinned)) {
3934 cpu_clear(cpu_of(busiest), *cpus);
3935 if (!cpus_empty(*cpus))
3936 goto redo;
3940 if (!ld_moved) {
3941 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3942 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3943 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3944 return -1;
3945 } else
3946 sd->nr_balance_failed = 0;
3948 return ld_moved;
3950 out_balanced:
3951 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3952 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3953 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3954 return -1;
3955 sd->nr_balance_failed = 0;
3957 return 0;
3961 * idle_balance is called by schedule() if this_cpu is about to become
3962 * idle. Attempts to pull tasks from other CPUs.
3964 static void idle_balance(int this_cpu, struct rq *this_rq)
3966 struct sched_domain *sd;
3967 int pulled_task = -1;
3968 unsigned long next_balance = jiffies + HZ;
3969 cpumask_t tmpmask;
3971 for_each_domain(this_cpu, sd) {
3972 unsigned long interval;
3974 if (!(sd->flags & SD_LOAD_BALANCE))
3975 continue;
3977 if (sd->flags & SD_BALANCE_NEWIDLE)
3978 /* If we've pulled tasks over stop searching: */
3979 pulled_task = load_balance_newidle(this_cpu, this_rq,
3980 sd, &tmpmask);
3982 interval = msecs_to_jiffies(sd->balance_interval);
3983 if (time_after(next_balance, sd->last_balance + interval))
3984 next_balance = sd->last_balance + interval;
3985 if (pulled_task)
3986 break;
3988 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3990 * We are going idle. next_balance may be set based on
3991 * a busy processor. So reset next_balance.
3993 this_rq->next_balance = next_balance;
3998 * active_load_balance is run by migration threads. It pushes running tasks
3999 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4000 * running on each physical CPU where possible, and avoids physical /
4001 * logical imbalances.
4003 * Called with busiest_rq locked.
4005 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4007 int target_cpu = busiest_rq->push_cpu;
4008 struct sched_domain *sd;
4009 struct rq *target_rq;
4011 /* Is there any task to move? */
4012 if (busiest_rq->nr_running <= 1)
4013 return;
4015 target_rq = cpu_rq(target_cpu);
4018 * This condition is "impossible", if it occurs
4019 * we need to fix it. Originally reported by
4020 * Bjorn Helgaas on a 128-cpu setup.
4022 BUG_ON(busiest_rq == target_rq);
4024 /* move a task from busiest_rq to target_rq */
4025 double_lock_balance(busiest_rq, target_rq);
4026 update_rq_clock(busiest_rq);
4027 update_rq_clock(target_rq);
4029 /* Search for an sd spanning us and the target CPU. */
4030 for_each_domain(target_cpu, sd) {
4031 if ((sd->flags & SD_LOAD_BALANCE) &&
4032 cpu_isset(busiest_cpu, sd->span))
4033 break;
4036 if (likely(sd)) {
4037 schedstat_inc(sd, alb_count);
4039 if (move_one_task(target_rq, target_cpu, busiest_rq,
4040 sd, CPU_IDLE))
4041 schedstat_inc(sd, alb_pushed);
4042 else
4043 schedstat_inc(sd, alb_failed);
4045 spin_unlock(&target_rq->lock);
4048 #ifdef CONFIG_NO_HZ
4049 static struct {
4050 atomic_t load_balancer;
4051 cpumask_t cpu_mask;
4052 } nohz ____cacheline_aligned = {
4053 .load_balancer = ATOMIC_INIT(-1),
4054 .cpu_mask = CPU_MASK_NONE,
4058 * This routine will try to nominate the ilb (idle load balancing)
4059 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4060 * load balancing on behalf of all those cpus. If all the cpus in the system
4061 * go into this tickless mode, then there will be no ilb owner (as there is
4062 * no need for one) and all the cpus will sleep till the next wakeup event
4063 * arrives...
4065 * For the ilb owner, tick is not stopped. And this tick will be used
4066 * for idle load balancing. ilb owner will still be part of
4067 * nohz.cpu_mask..
4069 * While stopping the tick, this cpu will become the ilb owner if there
4070 * is no other owner. And will be the owner till that cpu becomes busy
4071 * or if all cpus in the system stop their ticks at which point
4072 * there is no need for ilb owner.
4074 * When the ilb owner becomes busy, it nominates another owner, during the
4075 * next busy scheduler_tick()
4077 int select_nohz_load_balancer(int stop_tick)
4079 int cpu = smp_processor_id();
4081 if (stop_tick) {
4082 cpu_set(cpu, nohz.cpu_mask);
4083 cpu_rq(cpu)->in_nohz_recently = 1;
4086 * If we are going offline and still the leader, give up!
4088 if (cpu_is_offline(cpu) &&
4089 atomic_read(&nohz.load_balancer) == cpu) {
4090 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4091 BUG();
4092 return 0;
4095 /* time for ilb owner also to sleep */
4096 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4097 if (atomic_read(&nohz.load_balancer) == cpu)
4098 atomic_set(&nohz.load_balancer, -1);
4099 return 0;
4102 if (atomic_read(&nohz.load_balancer) == -1) {
4103 /* make me the ilb owner */
4104 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4105 return 1;
4106 } else if (atomic_read(&nohz.load_balancer) == cpu)
4107 return 1;
4108 } else {
4109 if (!cpu_isset(cpu, nohz.cpu_mask))
4110 return 0;
4112 cpu_clear(cpu, nohz.cpu_mask);
4114 if (atomic_read(&nohz.load_balancer) == cpu)
4115 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4116 BUG();
4118 return 0;
4120 #endif
4122 static DEFINE_SPINLOCK(balancing);
4125 * It checks each scheduling domain to see if it is due to be balanced,
4126 * and initiates a balancing operation if so.
4128 * Balancing parameters are set up in arch_init_sched_domains.
4130 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4132 int balance = 1;
4133 struct rq *rq = cpu_rq(cpu);
4134 unsigned long interval;
4135 struct sched_domain *sd;
4136 /* Earliest time when we have to do rebalance again */
4137 unsigned long next_balance = jiffies + 60*HZ;
4138 int update_next_balance = 0;
4139 cpumask_t tmp;
4141 for_each_domain(cpu, sd) {
4142 if (!(sd->flags & SD_LOAD_BALANCE))
4143 continue;
4145 interval = sd->balance_interval;
4146 if (idle != CPU_IDLE)
4147 interval *= sd->busy_factor;
4149 /* scale ms to jiffies */
4150 interval = msecs_to_jiffies(interval);
4151 if (unlikely(!interval))
4152 interval = 1;
4153 if (interval > HZ*NR_CPUS/10)
4154 interval = HZ*NR_CPUS/10;
4157 if (sd->flags & SD_SERIALIZE) {
4158 if (!spin_trylock(&balancing))
4159 goto out;
4162 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4163 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
4165 * We've pulled tasks over so either we're no
4166 * longer idle, or one of our SMT siblings is
4167 * not idle.
4169 idle = CPU_NOT_IDLE;
4171 sd->last_balance = jiffies;
4173 if (sd->flags & SD_SERIALIZE)
4174 spin_unlock(&balancing);
4175 out:
4176 if (time_after(next_balance, sd->last_balance + interval)) {
4177 next_balance = sd->last_balance + interval;
4178 update_next_balance = 1;
4182 * Stop the load balance at this level. There is another
4183 * CPU in our sched group which is doing load balancing more
4184 * actively.
4186 if (!balance)
4187 break;
4191 * next_balance will be updated only when there is a need.
4192 * When the cpu is attached to null domain for ex, it will not be
4193 * updated.
4195 if (likely(update_next_balance))
4196 rq->next_balance = next_balance;
4200 * run_rebalance_domains is triggered when needed from the scheduler tick.
4201 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4202 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4204 static void run_rebalance_domains(struct softirq_action *h)
4206 int this_cpu = smp_processor_id();
4207 struct rq *this_rq = cpu_rq(this_cpu);
4208 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4209 CPU_IDLE : CPU_NOT_IDLE;
4211 rebalance_domains(this_cpu, idle);
4213 #ifdef CONFIG_NO_HZ
4215 * If this cpu is the owner for idle load balancing, then do the
4216 * balancing on behalf of the other idle cpus whose ticks are
4217 * stopped.
4219 if (this_rq->idle_at_tick &&
4220 atomic_read(&nohz.load_balancer) == this_cpu) {
4221 cpumask_t cpus = nohz.cpu_mask;
4222 struct rq *rq;
4223 int balance_cpu;
4225 cpu_clear(this_cpu, cpus);
4226 for_each_cpu_mask(balance_cpu, cpus) {
4228 * If this cpu gets work to do, stop the load balancing
4229 * work being done for other cpus. Next load
4230 * balancing owner will pick it up.
4232 if (need_resched())
4233 break;
4235 rebalance_domains(balance_cpu, CPU_IDLE);
4237 rq = cpu_rq(balance_cpu);
4238 if (time_after(this_rq->next_balance, rq->next_balance))
4239 this_rq->next_balance = rq->next_balance;
4242 #endif
4246 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4248 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4249 * idle load balancing owner or decide to stop the periodic load balancing,
4250 * if the whole system is idle.
4252 static inline void trigger_load_balance(struct rq *rq, int cpu)
4254 #ifdef CONFIG_NO_HZ
4256 * If we were in the nohz mode recently and busy at the current
4257 * scheduler tick, then check if we need to nominate new idle
4258 * load balancer.
4260 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4261 rq->in_nohz_recently = 0;
4263 if (atomic_read(&nohz.load_balancer) == cpu) {
4264 cpu_clear(cpu, nohz.cpu_mask);
4265 atomic_set(&nohz.load_balancer, -1);
4268 if (atomic_read(&nohz.load_balancer) == -1) {
4270 * simple selection for now: Nominate the
4271 * first cpu in the nohz list to be the next
4272 * ilb owner.
4274 * TBD: Traverse the sched domains and nominate
4275 * the nearest cpu in the nohz.cpu_mask.
4277 int ilb = first_cpu(nohz.cpu_mask);
4279 if (ilb < nr_cpu_ids)
4280 resched_cpu(ilb);
4285 * If this cpu is idle and doing idle load balancing for all the
4286 * cpus with ticks stopped, is it time for that to stop?
4288 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4289 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4290 resched_cpu(cpu);
4291 return;
4295 * If this cpu is idle and the idle load balancing is done by
4296 * someone else, then no need raise the SCHED_SOFTIRQ
4298 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4299 cpu_isset(cpu, nohz.cpu_mask))
4300 return;
4301 #endif
4302 if (time_after_eq(jiffies, rq->next_balance))
4303 raise_softirq(SCHED_SOFTIRQ);
4306 #else /* CONFIG_SMP */
4309 * on UP we do not need to balance between CPUs:
4311 static inline void idle_balance(int cpu, struct rq *rq)
4315 #endif
4317 DEFINE_PER_CPU(struct kernel_stat, kstat);
4319 EXPORT_PER_CPU_SYMBOL(kstat);
4322 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4323 * that have not yet been banked in case the task is currently running.
4325 unsigned long long task_sched_runtime(struct task_struct *p)
4327 unsigned long flags;
4328 u64 ns, delta_exec;
4329 struct rq *rq;
4331 rq = task_rq_lock(p, &flags);
4332 ns = p->se.sum_exec_runtime;
4333 if (task_current(rq, p)) {
4334 update_rq_clock(rq);
4335 delta_exec = rq->clock - p->se.exec_start;
4336 if ((s64)delta_exec > 0)
4337 ns += delta_exec;
4339 task_rq_unlock(rq, &flags);
4341 return ns;
4345 * Account user cpu time to a process.
4346 * @p: the process that the cpu time gets accounted to
4347 * @cputime: the cpu time spent in user space since the last update
4349 void account_user_time(struct task_struct *p, cputime_t cputime)
4351 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4352 cputime64_t tmp;
4354 p->utime = cputime_add(p->utime, cputime);
4356 /* Add user time to cpustat. */
4357 tmp = cputime_to_cputime64(cputime);
4358 if (TASK_NICE(p) > 0)
4359 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4360 else
4361 cpustat->user = cputime64_add(cpustat->user, tmp);
4365 * Account guest cpu time to a process.
4366 * @p: the process that the cpu time gets accounted to
4367 * @cputime: the cpu time spent in virtual machine since the last update
4369 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4371 cputime64_t tmp;
4372 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4374 tmp = cputime_to_cputime64(cputime);
4376 p->utime = cputime_add(p->utime, cputime);
4377 p->gtime = cputime_add(p->gtime, cputime);
4379 cpustat->user = cputime64_add(cpustat->user, tmp);
4380 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4384 * Account scaled user cpu time to a process.
4385 * @p: the process that the cpu time gets accounted to
4386 * @cputime: the cpu time spent in user space since the last update
4388 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4390 p->utimescaled = cputime_add(p->utimescaled, cputime);
4394 * Account system cpu time to a process.
4395 * @p: the process that the cpu time gets accounted to
4396 * @hardirq_offset: the offset to subtract from hardirq_count()
4397 * @cputime: the cpu time spent in kernel space since the last update
4399 void account_system_time(struct task_struct *p, int hardirq_offset,
4400 cputime_t cputime)
4402 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4403 struct rq *rq = this_rq();
4404 cputime64_t tmp;
4406 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4407 account_guest_time(p, cputime);
4408 return;
4411 p->stime = cputime_add(p->stime, cputime);
4413 /* Add system time to cpustat. */
4414 tmp = cputime_to_cputime64(cputime);
4415 if (hardirq_count() - hardirq_offset)
4416 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4417 else if (softirq_count())
4418 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4419 else if (p != rq->idle)
4420 cpustat->system = cputime64_add(cpustat->system, tmp);
4421 else if (atomic_read(&rq->nr_iowait) > 0)
4422 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4423 else
4424 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4425 /* Account for system time used */
4426 acct_update_integrals(p);
4430 * Account scaled system cpu time to a process.
4431 * @p: the process that the cpu time gets accounted to
4432 * @hardirq_offset: the offset to subtract from hardirq_count()
4433 * @cputime: the cpu time spent in kernel space since the last update
4435 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4437 p->stimescaled = cputime_add(p->stimescaled, cputime);
4441 * Account for involuntary wait time.
4442 * @p: the process from which the cpu time has been stolen
4443 * @steal: the cpu time spent in involuntary wait
4445 void account_steal_time(struct task_struct *p, cputime_t steal)
4447 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4448 cputime64_t tmp = cputime_to_cputime64(steal);
4449 struct rq *rq = this_rq();
4451 if (p == rq->idle) {
4452 p->stime = cputime_add(p->stime, steal);
4453 if (atomic_read(&rq->nr_iowait) > 0)
4454 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4455 else
4456 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4457 } else
4458 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4462 * This function gets called by the timer code, with HZ frequency.
4463 * We call it with interrupts disabled.
4465 * It also gets called by the fork code, when changing the parent's
4466 * timeslices.
4468 void scheduler_tick(void)
4470 int cpu = smp_processor_id();
4471 struct rq *rq = cpu_rq(cpu);
4472 struct task_struct *curr = rq->curr;
4473 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
4475 spin_lock(&rq->lock);
4476 __update_rq_clock(rq);
4478 * Let rq->clock advance by at least TICK_NSEC:
4480 if (unlikely(rq->clock < next_tick)) {
4481 rq->clock = next_tick;
4482 rq->clock_underflows++;
4484 rq->tick_timestamp = rq->clock;
4485 update_last_tick_seen(rq);
4486 update_cpu_load(rq);
4487 curr->sched_class->task_tick(rq, curr, 0);
4488 spin_unlock(&rq->lock);
4490 #ifdef CONFIG_SMP
4491 rq->idle_at_tick = idle_cpu(cpu);
4492 trigger_load_balance(rq, cpu);
4493 #endif
4496 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4498 void __kprobes add_preempt_count(int val)
4501 * Underflow?
4503 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4504 return;
4505 preempt_count() += val;
4507 * Spinlock count overflowing soon?
4509 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4510 PREEMPT_MASK - 10);
4512 EXPORT_SYMBOL(add_preempt_count);
4514 void __kprobes sub_preempt_count(int val)
4517 * Underflow?
4519 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4520 return;
4522 * Is the spinlock portion underflowing?
4524 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4525 !(preempt_count() & PREEMPT_MASK)))
4526 return;
4528 preempt_count() -= val;
4530 EXPORT_SYMBOL(sub_preempt_count);
4532 #endif
4535 * Print scheduling while atomic bug:
4537 static noinline void __schedule_bug(struct task_struct *prev)
4539 struct pt_regs *regs = get_irq_regs();
4541 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4542 prev->comm, prev->pid, preempt_count());
4544 debug_show_held_locks(prev);
4545 if (irqs_disabled())
4546 print_irqtrace_events(prev);
4548 if (regs)
4549 show_regs(regs);
4550 else
4551 dump_stack();
4555 * Various schedule()-time debugging checks and statistics:
4557 static inline void schedule_debug(struct task_struct *prev)
4560 * Test if we are atomic. Since do_exit() needs to call into
4561 * schedule() atomically, we ignore that path for now.
4562 * Otherwise, whine if we are scheduling when we should not be.
4564 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4565 __schedule_bug(prev);
4567 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4569 schedstat_inc(this_rq(), sched_count);
4570 #ifdef CONFIG_SCHEDSTATS
4571 if (unlikely(prev->lock_depth >= 0)) {
4572 schedstat_inc(this_rq(), bkl_count);
4573 schedstat_inc(prev, sched_info.bkl_count);
4575 #endif
4579 * Pick up the highest-prio task:
4581 static inline struct task_struct *
4582 pick_next_task(struct rq *rq, struct task_struct *prev)
4584 const struct sched_class *class;
4585 struct task_struct *p;
4588 * Optimization: we know that if all tasks are in
4589 * the fair class we can call that function directly:
4591 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4592 p = fair_sched_class.pick_next_task(rq);
4593 if (likely(p))
4594 return p;
4597 class = sched_class_highest;
4598 for ( ; ; ) {
4599 p = class->pick_next_task(rq);
4600 if (p)
4601 return p;
4603 * Will never be NULL as the idle class always
4604 * returns a non-NULL p:
4606 class = class->next;
4611 * schedule() is the main scheduler function.
4613 asmlinkage void __sched schedule(void)
4615 struct task_struct *prev, *next;
4616 unsigned long *switch_count;
4617 struct rq *rq;
4618 int cpu;
4620 need_resched:
4621 preempt_disable();
4622 cpu = smp_processor_id();
4623 rq = cpu_rq(cpu);
4624 rcu_qsctr_inc(cpu);
4625 prev = rq->curr;
4626 switch_count = &prev->nivcsw;
4628 release_kernel_lock(prev);
4629 need_resched_nonpreemptible:
4631 schedule_debug(prev);
4633 hrtick_clear(rq);
4636 * Do the rq-clock update outside the rq lock:
4638 local_irq_disable();
4639 __update_rq_clock(rq);
4640 spin_lock(&rq->lock);
4641 clear_tsk_need_resched(prev);
4643 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4644 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4645 signal_pending(prev))) {
4646 prev->state = TASK_RUNNING;
4647 } else {
4648 deactivate_task(rq, prev, 1);
4650 switch_count = &prev->nvcsw;
4653 #ifdef CONFIG_SMP
4654 if (prev->sched_class->pre_schedule)
4655 prev->sched_class->pre_schedule(rq, prev);
4656 #endif
4658 if (unlikely(!rq->nr_running))
4659 idle_balance(cpu, rq);
4661 prev->sched_class->put_prev_task(rq, prev);
4662 next = pick_next_task(rq, prev);
4664 if (likely(prev != next)) {
4665 sched_info_switch(prev, next);
4667 rq->nr_switches++;
4668 rq->curr = next;
4669 ++*switch_count;
4671 context_switch(rq, prev, next); /* unlocks the rq */
4673 * the context switch might have flipped the stack from under
4674 * us, hence refresh the local variables.
4676 cpu = smp_processor_id();
4677 rq = cpu_rq(cpu);
4678 } else
4679 spin_unlock_irq(&rq->lock);
4681 hrtick_set(rq);
4683 if (unlikely(reacquire_kernel_lock(current) < 0))
4684 goto need_resched_nonpreemptible;
4686 preempt_enable_no_resched();
4687 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4688 goto need_resched;
4690 EXPORT_SYMBOL(schedule);
4692 #ifdef CONFIG_PREEMPT
4694 * this is the entry point to schedule() from in-kernel preemption
4695 * off of preempt_enable. Kernel preemptions off return from interrupt
4696 * occur there and call schedule directly.
4698 asmlinkage void __sched preempt_schedule(void)
4700 struct thread_info *ti = current_thread_info();
4701 struct task_struct *task = current;
4702 int saved_lock_depth;
4705 * If there is a non-zero preempt_count or interrupts are disabled,
4706 * we do not want to preempt the current task. Just return..
4708 if (likely(ti->preempt_count || irqs_disabled()))
4709 return;
4711 do {
4712 add_preempt_count(PREEMPT_ACTIVE);
4715 * We keep the big kernel semaphore locked, but we
4716 * clear ->lock_depth so that schedule() doesnt
4717 * auto-release the semaphore:
4719 saved_lock_depth = task->lock_depth;
4720 task->lock_depth = -1;
4721 schedule();
4722 task->lock_depth = saved_lock_depth;
4723 sub_preempt_count(PREEMPT_ACTIVE);
4726 * Check again in case we missed a preemption opportunity
4727 * between schedule and now.
4729 barrier();
4730 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4732 EXPORT_SYMBOL(preempt_schedule);
4735 * this is the entry point to schedule() from kernel preemption
4736 * off of irq context.
4737 * Note, that this is called and return with irqs disabled. This will
4738 * protect us against recursive calling from irq.
4740 asmlinkage void __sched preempt_schedule_irq(void)
4742 struct thread_info *ti = current_thread_info();
4743 struct task_struct *task = current;
4744 int saved_lock_depth;
4746 /* Catch callers which need to be fixed */
4747 BUG_ON(ti->preempt_count || !irqs_disabled());
4749 do {
4750 add_preempt_count(PREEMPT_ACTIVE);
4753 * We keep the big kernel semaphore locked, but we
4754 * clear ->lock_depth so that schedule() doesnt
4755 * auto-release the semaphore:
4757 saved_lock_depth = task->lock_depth;
4758 task->lock_depth = -1;
4759 local_irq_enable();
4760 schedule();
4761 local_irq_disable();
4762 task->lock_depth = saved_lock_depth;
4763 sub_preempt_count(PREEMPT_ACTIVE);
4766 * Check again in case we missed a preemption opportunity
4767 * between schedule and now.
4769 barrier();
4770 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4773 #endif /* CONFIG_PREEMPT */
4775 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4776 void *key)
4778 return try_to_wake_up(curr->private, mode, sync);
4780 EXPORT_SYMBOL(default_wake_function);
4783 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4784 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4785 * number) then we wake all the non-exclusive tasks and one exclusive task.
4787 * There are circumstances in which we can try to wake a task which has already
4788 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4789 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4791 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4792 int nr_exclusive, int sync, void *key)
4794 wait_queue_t *curr, *next;
4796 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4797 unsigned flags = curr->flags;
4799 if (curr->func(curr, mode, sync, key) &&
4800 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4801 break;
4806 * __wake_up - wake up threads blocked on a waitqueue.
4807 * @q: the waitqueue
4808 * @mode: which threads
4809 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4810 * @key: is directly passed to the wakeup function
4812 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4813 int nr_exclusive, void *key)
4815 unsigned long flags;
4817 spin_lock_irqsave(&q->lock, flags);
4818 __wake_up_common(q, mode, nr_exclusive, 0, key);
4819 spin_unlock_irqrestore(&q->lock, flags);
4821 EXPORT_SYMBOL(__wake_up);
4824 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4826 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4828 __wake_up_common(q, mode, 1, 0, NULL);
4832 * __wake_up_sync - wake up threads blocked on a waitqueue.
4833 * @q: the waitqueue
4834 * @mode: which threads
4835 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4837 * The sync wakeup differs that the waker knows that it will schedule
4838 * away soon, so while the target thread will be woken up, it will not
4839 * be migrated to another CPU - ie. the two threads are 'synchronized'
4840 * with each other. This can prevent needless bouncing between CPUs.
4842 * On UP it can prevent extra preemption.
4844 void
4845 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4847 unsigned long flags;
4848 int sync = 1;
4850 if (unlikely(!q))
4851 return;
4853 if (unlikely(!nr_exclusive))
4854 sync = 0;
4856 spin_lock_irqsave(&q->lock, flags);
4857 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4858 spin_unlock_irqrestore(&q->lock, flags);
4860 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4862 void complete(struct completion *x)
4864 unsigned long flags;
4866 spin_lock_irqsave(&x->wait.lock, flags);
4867 x->done++;
4868 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4869 spin_unlock_irqrestore(&x->wait.lock, flags);
4871 EXPORT_SYMBOL(complete);
4873 void complete_all(struct completion *x)
4875 unsigned long flags;
4877 spin_lock_irqsave(&x->wait.lock, flags);
4878 x->done += UINT_MAX/2;
4879 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4880 spin_unlock_irqrestore(&x->wait.lock, flags);
4882 EXPORT_SYMBOL(complete_all);
4884 static inline long __sched
4885 do_wait_for_common(struct completion *x, long timeout, int state)
4887 if (!x->done) {
4888 DECLARE_WAITQUEUE(wait, current);
4890 wait.flags |= WQ_FLAG_EXCLUSIVE;
4891 __add_wait_queue_tail(&x->wait, &wait);
4892 do {
4893 if ((state == TASK_INTERRUPTIBLE &&
4894 signal_pending(current)) ||
4895 (state == TASK_KILLABLE &&
4896 fatal_signal_pending(current))) {
4897 __remove_wait_queue(&x->wait, &wait);
4898 return -ERESTARTSYS;
4900 __set_current_state(state);
4901 spin_unlock_irq(&x->wait.lock);
4902 timeout = schedule_timeout(timeout);
4903 spin_lock_irq(&x->wait.lock);
4904 if (!timeout) {
4905 __remove_wait_queue(&x->wait, &wait);
4906 return timeout;
4908 } while (!x->done);
4909 __remove_wait_queue(&x->wait, &wait);
4911 x->done--;
4912 return timeout;
4915 static long __sched
4916 wait_for_common(struct completion *x, long timeout, int state)
4918 might_sleep();
4920 spin_lock_irq(&x->wait.lock);
4921 timeout = do_wait_for_common(x, timeout, state);
4922 spin_unlock_irq(&x->wait.lock);
4923 return timeout;
4926 void __sched wait_for_completion(struct completion *x)
4928 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4930 EXPORT_SYMBOL(wait_for_completion);
4932 unsigned long __sched
4933 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4935 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4937 EXPORT_SYMBOL(wait_for_completion_timeout);
4939 int __sched wait_for_completion_interruptible(struct completion *x)
4941 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4942 if (t == -ERESTARTSYS)
4943 return t;
4944 return 0;
4946 EXPORT_SYMBOL(wait_for_completion_interruptible);
4948 unsigned long __sched
4949 wait_for_completion_interruptible_timeout(struct completion *x,
4950 unsigned long timeout)
4952 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4954 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4956 int __sched wait_for_completion_killable(struct completion *x)
4958 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4959 if (t == -ERESTARTSYS)
4960 return t;
4961 return 0;
4963 EXPORT_SYMBOL(wait_for_completion_killable);
4965 static long __sched
4966 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4968 unsigned long flags;
4969 wait_queue_t wait;
4971 init_waitqueue_entry(&wait, current);
4973 __set_current_state(state);
4975 spin_lock_irqsave(&q->lock, flags);
4976 __add_wait_queue(q, &wait);
4977 spin_unlock(&q->lock);
4978 timeout = schedule_timeout(timeout);
4979 spin_lock_irq(&q->lock);
4980 __remove_wait_queue(q, &wait);
4981 spin_unlock_irqrestore(&q->lock, flags);
4983 return timeout;
4986 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4988 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4990 EXPORT_SYMBOL(interruptible_sleep_on);
4992 long __sched
4993 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4995 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4997 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4999 void __sched sleep_on(wait_queue_head_t *q)
5001 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5003 EXPORT_SYMBOL(sleep_on);
5005 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
5007 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5009 EXPORT_SYMBOL(sleep_on_timeout);
5011 #ifdef CONFIG_RT_MUTEXES
5014 * rt_mutex_setprio - set the current priority of a task
5015 * @p: task
5016 * @prio: prio value (kernel-internal form)
5018 * This function changes the 'effective' priority of a task. It does
5019 * not touch ->normal_prio like __setscheduler().
5021 * Used by the rt_mutex code to implement priority inheritance logic.
5023 void rt_mutex_setprio(struct task_struct *p, int prio)
5025 unsigned long flags;
5026 int oldprio, on_rq, running;
5027 struct rq *rq;
5028 const struct sched_class *prev_class = p->sched_class;
5030 BUG_ON(prio < 0 || prio > MAX_PRIO);
5032 rq = task_rq_lock(p, &flags);
5033 update_rq_clock(rq);
5035 oldprio = p->prio;
5036 on_rq = p->se.on_rq;
5037 running = task_current(rq, p);
5038 if (on_rq)
5039 dequeue_task(rq, p, 0);
5040 if (running)
5041 p->sched_class->put_prev_task(rq, p);
5043 if (rt_prio(prio))
5044 p->sched_class = &rt_sched_class;
5045 else
5046 p->sched_class = &fair_sched_class;
5048 p->prio = prio;
5050 if (running)
5051 p->sched_class->set_curr_task(rq);
5052 if (on_rq) {
5053 enqueue_task(rq, p, 0);
5055 check_class_changed(rq, p, prev_class, oldprio, running);
5057 task_rq_unlock(rq, &flags);
5060 #endif
5062 void set_user_nice(struct task_struct *p, long nice)
5064 int old_prio, delta, on_rq;
5065 unsigned long flags;
5066 struct rq *rq;
5068 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
5069 return;
5071 * We have to be careful, if called from sys_setpriority(),
5072 * the task might be in the middle of scheduling on another CPU.
5074 rq = task_rq_lock(p, &flags);
5075 update_rq_clock(rq);
5077 * The RT priorities are set via sched_setscheduler(), but we still
5078 * allow the 'normal' nice value to be set - but as expected
5079 * it wont have any effect on scheduling until the task is
5080 * SCHED_FIFO/SCHED_RR:
5082 if (task_has_rt_policy(p)) {
5083 p->static_prio = NICE_TO_PRIO(nice);
5084 goto out_unlock;
5086 on_rq = p->se.on_rq;
5087 if (on_rq)
5088 dequeue_task(rq, p, 0);
5090 p->static_prio = NICE_TO_PRIO(nice);
5091 set_load_weight(p);
5092 old_prio = p->prio;
5093 p->prio = effective_prio(p);
5094 delta = p->prio - old_prio;
5096 if (on_rq) {
5097 enqueue_task(rq, p, 0);
5099 * If the task increased its priority or is running and
5100 * lowered its priority, then reschedule its CPU:
5102 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5103 resched_task(rq->curr);
5105 out_unlock:
5106 task_rq_unlock(rq, &flags);
5108 EXPORT_SYMBOL(set_user_nice);
5111 * can_nice - check if a task can reduce its nice value
5112 * @p: task
5113 * @nice: nice value
5115 int can_nice(const struct task_struct *p, const int nice)
5117 /* convert nice value [19,-20] to rlimit style value [1,40] */
5118 int nice_rlim = 20 - nice;
5120 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5121 capable(CAP_SYS_NICE));
5124 #ifdef __ARCH_WANT_SYS_NICE
5127 * sys_nice - change the priority of the current process.
5128 * @increment: priority increment
5130 * sys_setpriority is a more generic, but much slower function that
5131 * does similar things.
5133 asmlinkage long sys_nice(int increment)
5135 long nice, retval;
5138 * Setpriority might change our priority at the same moment.
5139 * We don't have to worry. Conceptually one call occurs first
5140 * and we have a single winner.
5142 if (increment < -40)
5143 increment = -40;
5144 if (increment > 40)
5145 increment = 40;
5147 nice = PRIO_TO_NICE(current->static_prio) + increment;
5148 if (nice < -20)
5149 nice = -20;
5150 if (nice > 19)
5151 nice = 19;
5153 if (increment < 0 && !can_nice(current, nice))
5154 return -EPERM;
5156 retval = security_task_setnice(current, nice);
5157 if (retval)
5158 return retval;
5160 set_user_nice(current, nice);
5161 return 0;
5164 #endif
5167 * task_prio - return the priority value of a given task.
5168 * @p: the task in question.
5170 * This is the priority value as seen by users in /proc.
5171 * RT tasks are offset by -200. Normal tasks are centered
5172 * around 0, value goes from -16 to +15.
5174 int task_prio(const struct task_struct *p)
5176 return p->prio - MAX_RT_PRIO;
5180 * task_nice - return the nice value of a given task.
5181 * @p: the task in question.
5183 int task_nice(const struct task_struct *p)
5185 return TASK_NICE(p);
5187 EXPORT_SYMBOL(task_nice);
5190 * idle_cpu - is a given cpu idle currently?
5191 * @cpu: the processor in question.
5193 int idle_cpu(int cpu)
5195 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5199 * idle_task - return the idle task for a given cpu.
5200 * @cpu: the processor in question.
5202 struct task_struct *idle_task(int cpu)
5204 return cpu_rq(cpu)->idle;
5208 * find_process_by_pid - find a process with a matching PID value.
5209 * @pid: the pid in question.
5211 static struct task_struct *find_process_by_pid(pid_t pid)
5213 return pid ? find_task_by_vpid(pid) : current;
5216 /* Actually do priority change: must hold rq lock. */
5217 static void
5218 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5220 BUG_ON(p->se.on_rq);
5222 p->policy = policy;
5223 switch (p->policy) {
5224 case SCHED_NORMAL:
5225 case SCHED_BATCH:
5226 case SCHED_IDLE:
5227 p->sched_class = &fair_sched_class;
5228 break;
5229 case SCHED_FIFO:
5230 case SCHED_RR:
5231 p->sched_class = &rt_sched_class;
5232 break;
5235 p->rt_priority = prio;
5236 p->normal_prio = normal_prio(p);
5237 /* we are holding p->pi_lock already */
5238 p->prio = rt_mutex_getprio(p);
5239 set_load_weight(p);
5243 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5244 * @p: the task in question.
5245 * @policy: new policy.
5246 * @param: structure containing the new RT priority.
5248 * NOTE that the task may be already dead.
5250 int sched_setscheduler(struct task_struct *p, int policy,
5251 struct sched_param *param)
5253 int retval, oldprio, oldpolicy = -1, on_rq, running;
5254 unsigned long flags;
5255 const struct sched_class *prev_class = p->sched_class;
5256 struct rq *rq;
5258 /* may grab non-irq protected spin_locks */
5259 BUG_ON(in_interrupt());
5260 recheck:
5261 /* double check policy once rq lock held */
5262 if (policy < 0)
5263 policy = oldpolicy = p->policy;
5264 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5265 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5266 policy != SCHED_IDLE)
5267 return -EINVAL;
5269 * Valid priorities for SCHED_FIFO and SCHED_RR are
5270 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5271 * SCHED_BATCH and SCHED_IDLE is 0.
5273 if (param->sched_priority < 0 ||
5274 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5275 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5276 return -EINVAL;
5277 if (rt_policy(policy) != (param->sched_priority != 0))
5278 return -EINVAL;
5281 * Allow unprivileged RT tasks to decrease priority:
5283 if (!capable(CAP_SYS_NICE)) {
5284 if (rt_policy(policy)) {
5285 unsigned long rlim_rtprio;
5287 if (!lock_task_sighand(p, &flags))
5288 return -ESRCH;
5289 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5290 unlock_task_sighand(p, &flags);
5292 /* can't set/change the rt policy */
5293 if (policy != p->policy && !rlim_rtprio)
5294 return -EPERM;
5296 /* can't increase priority */
5297 if (param->sched_priority > p->rt_priority &&
5298 param->sched_priority > rlim_rtprio)
5299 return -EPERM;
5302 * Like positive nice levels, dont allow tasks to
5303 * move out of SCHED_IDLE either:
5305 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5306 return -EPERM;
5308 /* can't change other user's priorities */
5309 if ((current->euid != p->euid) &&
5310 (current->euid != p->uid))
5311 return -EPERM;
5314 #ifdef CONFIG_RT_GROUP_SCHED
5316 * Do not allow realtime tasks into groups that have no runtime
5317 * assigned.
5319 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5320 return -EPERM;
5321 #endif
5323 retval = security_task_setscheduler(p, policy, param);
5324 if (retval)
5325 return retval;
5327 * make sure no PI-waiters arrive (or leave) while we are
5328 * changing the priority of the task:
5330 spin_lock_irqsave(&p->pi_lock, flags);
5332 * To be able to change p->policy safely, the apropriate
5333 * runqueue lock must be held.
5335 rq = __task_rq_lock(p);
5336 /* recheck policy now with rq lock held */
5337 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5338 policy = oldpolicy = -1;
5339 __task_rq_unlock(rq);
5340 spin_unlock_irqrestore(&p->pi_lock, flags);
5341 goto recheck;
5343 update_rq_clock(rq);
5344 on_rq = p->se.on_rq;
5345 running = task_current(rq, p);
5346 if (on_rq)
5347 deactivate_task(rq, p, 0);
5348 if (running)
5349 p->sched_class->put_prev_task(rq, p);
5351 oldprio = p->prio;
5352 __setscheduler(rq, p, policy, param->sched_priority);
5354 if (running)
5355 p->sched_class->set_curr_task(rq);
5356 if (on_rq) {
5357 activate_task(rq, p, 0);
5359 check_class_changed(rq, p, prev_class, oldprio, running);
5361 __task_rq_unlock(rq);
5362 spin_unlock_irqrestore(&p->pi_lock, flags);
5364 rt_mutex_adjust_pi(p);
5366 return 0;
5368 EXPORT_SYMBOL_GPL(sched_setscheduler);
5370 static int
5371 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5373 struct sched_param lparam;
5374 struct task_struct *p;
5375 int retval;
5377 if (!param || pid < 0)
5378 return -EINVAL;
5379 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5380 return -EFAULT;
5382 rcu_read_lock();
5383 retval = -ESRCH;
5384 p = find_process_by_pid(pid);
5385 if (p != NULL)
5386 retval = sched_setscheduler(p, policy, &lparam);
5387 rcu_read_unlock();
5389 return retval;
5393 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5394 * @pid: the pid in question.
5395 * @policy: new policy.
5396 * @param: structure containing the new RT priority.
5398 asmlinkage long
5399 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5401 /* negative values for policy are not valid */
5402 if (policy < 0)
5403 return -EINVAL;
5405 return do_sched_setscheduler(pid, policy, param);
5409 * sys_sched_setparam - set/change the RT priority of a thread
5410 * @pid: the pid in question.
5411 * @param: structure containing the new RT priority.
5413 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5415 return do_sched_setscheduler(pid, -1, param);
5419 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5420 * @pid: the pid in question.
5422 asmlinkage long sys_sched_getscheduler(pid_t pid)
5424 struct task_struct *p;
5425 int retval;
5427 if (pid < 0)
5428 return -EINVAL;
5430 retval = -ESRCH;
5431 read_lock(&tasklist_lock);
5432 p = find_process_by_pid(pid);
5433 if (p) {
5434 retval = security_task_getscheduler(p);
5435 if (!retval)
5436 retval = p->policy;
5438 read_unlock(&tasklist_lock);
5439 return retval;
5443 * sys_sched_getscheduler - get the RT priority of a thread
5444 * @pid: the pid in question.
5445 * @param: structure containing the RT priority.
5447 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5449 struct sched_param lp;
5450 struct task_struct *p;
5451 int retval;
5453 if (!param || pid < 0)
5454 return -EINVAL;
5456 read_lock(&tasklist_lock);
5457 p = find_process_by_pid(pid);
5458 retval = -ESRCH;
5459 if (!p)
5460 goto out_unlock;
5462 retval = security_task_getscheduler(p);
5463 if (retval)
5464 goto out_unlock;
5466 lp.sched_priority = p->rt_priority;
5467 read_unlock(&tasklist_lock);
5470 * This one might sleep, we cannot do it with a spinlock held ...
5472 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5474 return retval;
5476 out_unlock:
5477 read_unlock(&tasklist_lock);
5478 return retval;
5481 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5483 cpumask_t cpus_allowed;
5484 cpumask_t new_mask = *in_mask;
5485 struct task_struct *p;
5486 int retval;
5488 get_online_cpus();
5489 read_lock(&tasklist_lock);
5491 p = find_process_by_pid(pid);
5492 if (!p) {
5493 read_unlock(&tasklist_lock);
5494 put_online_cpus();
5495 return -ESRCH;
5499 * It is not safe to call set_cpus_allowed with the
5500 * tasklist_lock held. We will bump the task_struct's
5501 * usage count and then drop tasklist_lock.
5503 get_task_struct(p);
5504 read_unlock(&tasklist_lock);
5506 retval = -EPERM;
5507 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5508 !capable(CAP_SYS_NICE))
5509 goto out_unlock;
5511 retval = security_task_setscheduler(p, 0, NULL);
5512 if (retval)
5513 goto out_unlock;
5515 cpuset_cpus_allowed(p, &cpus_allowed);
5516 cpus_and(new_mask, new_mask, cpus_allowed);
5517 again:
5518 retval = set_cpus_allowed_ptr(p, &new_mask);
5520 if (!retval) {
5521 cpuset_cpus_allowed(p, &cpus_allowed);
5522 if (!cpus_subset(new_mask, cpus_allowed)) {
5524 * We must have raced with a concurrent cpuset
5525 * update. Just reset the cpus_allowed to the
5526 * cpuset's cpus_allowed
5528 new_mask = cpus_allowed;
5529 goto again;
5532 out_unlock:
5533 put_task_struct(p);
5534 put_online_cpus();
5535 return retval;
5538 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5539 cpumask_t *new_mask)
5541 if (len < sizeof(cpumask_t)) {
5542 memset(new_mask, 0, sizeof(cpumask_t));
5543 } else if (len > sizeof(cpumask_t)) {
5544 len = sizeof(cpumask_t);
5546 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5550 * sys_sched_setaffinity - set the cpu affinity of a process
5551 * @pid: pid of the process
5552 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5553 * @user_mask_ptr: user-space pointer to the new cpu mask
5555 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5556 unsigned long __user *user_mask_ptr)
5558 cpumask_t new_mask;
5559 int retval;
5561 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5562 if (retval)
5563 return retval;
5565 return sched_setaffinity(pid, &new_mask);
5569 * Represents all cpu's present in the system
5570 * In systems capable of hotplug, this map could dynamically grow
5571 * as new cpu's are detected in the system via any platform specific
5572 * method, such as ACPI for e.g.
5575 cpumask_t cpu_present_map __read_mostly;
5576 EXPORT_SYMBOL(cpu_present_map);
5578 #ifndef CONFIG_SMP
5579 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5580 EXPORT_SYMBOL(cpu_online_map);
5582 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5583 EXPORT_SYMBOL(cpu_possible_map);
5584 #endif
5586 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5588 struct task_struct *p;
5589 int retval;
5591 get_online_cpus();
5592 read_lock(&tasklist_lock);
5594 retval = -ESRCH;
5595 p = find_process_by_pid(pid);
5596 if (!p)
5597 goto out_unlock;
5599 retval = security_task_getscheduler(p);
5600 if (retval)
5601 goto out_unlock;
5603 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5605 out_unlock:
5606 read_unlock(&tasklist_lock);
5607 put_online_cpus();
5609 return retval;
5613 * sys_sched_getaffinity - get the cpu affinity of a process
5614 * @pid: pid of the process
5615 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5616 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5618 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5619 unsigned long __user *user_mask_ptr)
5621 int ret;
5622 cpumask_t mask;
5624 if (len < sizeof(cpumask_t))
5625 return -EINVAL;
5627 ret = sched_getaffinity(pid, &mask);
5628 if (ret < 0)
5629 return ret;
5631 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5632 return -EFAULT;
5634 return sizeof(cpumask_t);
5638 * sys_sched_yield - yield the current processor to other threads.
5640 * This function yields the current CPU to other tasks. If there are no
5641 * other threads running on this CPU then this function will return.
5643 asmlinkage long sys_sched_yield(void)
5645 struct rq *rq = this_rq_lock();
5647 schedstat_inc(rq, yld_count);
5648 current->sched_class->yield_task(rq);
5651 * Since we are going to call schedule() anyway, there's
5652 * no need to preempt or enable interrupts:
5654 __release(rq->lock);
5655 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5656 _raw_spin_unlock(&rq->lock);
5657 preempt_enable_no_resched();
5659 schedule();
5661 return 0;
5664 static void __cond_resched(void)
5666 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5667 __might_sleep(__FILE__, __LINE__);
5668 #endif
5670 * The BKS might be reacquired before we have dropped
5671 * PREEMPT_ACTIVE, which could trigger a second
5672 * cond_resched() call.
5674 do {
5675 add_preempt_count(PREEMPT_ACTIVE);
5676 schedule();
5677 sub_preempt_count(PREEMPT_ACTIVE);
5678 } while (need_resched());
5681 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5682 int __sched _cond_resched(void)
5684 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5685 system_state == SYSTEM_RUNNING) {
5686 __cond_resched();
5687 return 1;
5689 return 0;
5691 EXPORT_SYMBOL(_cond_resched);
5692 #endif
5695 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5696 * call schedule, and on return reacquire the lock.
5698 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5699 * operations here to prevent schedule() from being called twice (once via
5700 * spin_unlock(), once by hand).
5702 int cond_resched_lock(spinlock_t *lock)
5704 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5705 int ret = 0;
5707 if (spin_needbreak(lock) || resched) {
5708 spin_unlock(lock);
5709 if (resched && need_resched())
5710 __cond_resched();
5711 else
5712 cpu_relax();
5713 ret = 1;
5714 spin_lock(lock);
5716 return ret;
5718 EXPORT_SYMBOL(cond_resched_lock);
5720 int __sched cond_resched_softirq(void)
5722 BUG_ON(!in_softirq());
5724 if (need_resched() && system_state == SYSTEM_RUNNING) {
5725 local_bh_enable();
5726 __cond_resched();
5727 local_bh_disable();
5728 return 1;
5730 return 0;
5732 EXPORT_SYMBOL(cond_resched_softirq);
5735 * yield - yield the current processor to other threads.
5737 * This is a shortcut for kernel-space yielding - it marks the
5738 * thread runnable and calls sys_sched_yield().
5740 void __sched yield(void)
5742 set_current_state(TASK_RUNNING);
5743 sys_sched_yield();
5745 EXPORT_SYMBOL(yield);
5748 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5749 * that process accounting knows that this is a task in IO wait state.
5751 * But don't do that if it is a deliberate, throttling IO wait (this task
5752 * has set its backing_dev_info: the queue against which it should throttle)
5754 void __sched io_schedule(void)
5756 struct rq *rq = &__raw_get_cpu_var(runqueues);
5758 delayacct_blkio_start();
5759 atomic_inc(&rq->nr_iowait);
5760 schedule();
5761 atomic_dec(&rq->nr_iowait);
5762 delayacct_blkio_end();
5764 EXPORT_SYMBOL(io_schedule);
5766 long __sched io_schedule_timeout(long timeout)
5768 struct rq *rq = &__raw_get_cpu_var(runqueues);
5769 long ret;
5771 delayacct_blkio_start();
5772 atomic_inc(&rq->nr_iowait);
5773 ret = schedule_timeout(timeout);
5774 atomic_dec(&rq->nr_iowait);
5775 delayacct_blkio_end();
5776 return ret;
5780 * sys_sched_get_priority_max - return maximum RT priority.
5781 * @policy: scheduling class.
5783 * this syscall returns the maximum rt_priority that can be used
5784 * by a given scheduling class.
5786 asmlinkage long sys_sched_get_priority_max(int policy)
5788 int ret = -EINVAL;
5790 switch (policy) {
5791 case SCHED_FIFO:
5792 case SCHED_RR:
5793 ret = MAX_USER_RT_PRIO-1;
5794 break;
5795 case SCHED_NORMAL:
5796 case SCHED_BATCH:
5797 case SCHED_IDLE:
5798 ret = 0;
5799 break;
5801 return ret;
5805 * sys_sched_get_priority_min - return minimum RT priority.
5806 * @policy: scheduling class.
5808 * this syscall returns the minimum rt_priority that can be used
5809 * by a given scheduling class.
5811 asmlinkage long sys_sched_get_priority_min(int policy)
5813 int ret = -EINVAL;
5815 switch (policy) {
5816 case SCHED_FIFO:
5817 case SCHED_RR:
5818 ret = 1;
5819 break;
5820 case SCHED_NORMAL:
5821 case SCHED_BATCH:
5822 case SCHED_IDLE:
5823 ret = 0;
5825 return ret;
5829 * sys_sched_rr_get_interval - return the default timeslice of a process.
5830 * @pid: pid of the process.
5831 * @interval: userspace pointer to the timeslice value.
5833 * this syscall writes the default timeslice value of a given process
5834 * into the user-space timespec buffer. A value of '0' means infinity.
5836 asmlinkage
5837 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5839 struct task_struct *p;
5840 unsigned int time_slice;
5841 int retval;
5842 struct timespec t;
5844 if (pid < 0)
5845 return -EINVAL;
5847 retval = -ESRCH;
5848 read_lock(&tasklist_lock);
5849 p = find_process_by_pid(pid);
5850 if (!p)
5851 goto out_unlock;
5853 retval = security_task_getscheduler(p);
5854 if (retval)
5855 goto out_unlock;
5858 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5859 * tasks that are on an otherwise idle runqueue:
5861 time_slice = 0;
5862 if (p->policy == SCHED_RR) {
5863 time_slice = DEF_TIMESLICE;
5864 } else if (p->policy != SCHED_FIFO) {
5865 struct sched_entity *se = &p->se;
5866 unsigned long flags;
5867 struct rq *rq;
5869 rq = task_rq_lock(p, &flags);
5870 if (rq->cfs.load.weight)
5871 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5872 task_rq_unlock(rq, &flags);
5874 read_unlock(&tasklist_lock);
5875 jiffies_to_timespec(time_slice, &t);
5876 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5877 return retval;
5879 out_unlock:
5880 read_unlock(&tasklist_lock);
5881 return retval;
5884 static const char stat_nam[] = "RSDTtZX";
5886 void sched_show_task(struct task_struct *p)
5888 unsigned long free = 0;
5889 unsigned state;
5891 state = p->state ? __ffs(p->state) + 1 : 0;
5892 printk(KERN_INFO "%-13.13s %c", p->comm,
5893 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5894 #if BITS_PER_LONG == 32
5895 if (state == TASK_RUNNING)
5896 printk(KERN_CONT " running ");
5897 else
5898 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5899 #else
5900 if (state == TASK_RUNNING)
5901 printk(KERN_CONT " running task ");
5902 else
5903 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5904 #endif
5905 #ifdef CONFIG_DEBUG_STACK_USAGE
5907 unsigned long *n = end_of_stack(p);
5908 while (!*n)
5909 n++;
5910 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5912 #endif
5913 printk(KERN_CONT "%5lu %5d %6d\n", free,
5914 task_pid_nr(p), task_pid_nr(p->real_parent));
5916 show_stack(p, NULL);
5919 void show_state_filter(unsigned long state_filter)
5921 struct task_struct *g, *p;
5923 #if BITS_PER_LONG == 32
5924 printk(KERN_INFO
5925 " task PC stack pid father\n");
5926 #else
5927 printk(KERN_INFO
5928 " task PC stack pid father\n");
5929 #endif
5930 read_lock(&tasklist_lock);
5931 do_each_thread(g, p) {
5933 * reset the NMI-timeout, listing all files on a slow
5934 * console might take alot of time:
5936 touch_nmi_watchdog();
5937 if (!state_filter || (p->state & state_filter))
5938 sched_show_task(p);
5939 } while_each_thread(g, p);
5941 touch_all_softlockup_watchdogs();
5943 #ifdef CONFIG_SCHED_DEBUG
5944 sysrq_sched_debug_show();
5945 #endif
5946 read_unlock(&tasklist_lock);
5948 * Only show locks if all tasks are dumped:
5950 if (state_filter == -1)
5951 debug_show_all_locks();
5954 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5956 idle->sched_class = &idle_sched_class;
5960 * init_idle - set up an idle thread for a given CPU
5961 * @idle: task in question
5962 * @cpu: cpu the idle task belongs to
5964 * NOTE: this function does not set the idle thread's NEED_RESCHED
5965 * flag, to make booting more robust.
5967 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5969 struct rq *rq = cpu_rq(cpu);
5970 unsigned long flags;
5972 __sched_fork(idle);
5973 idle->se.exec_start = sched_clock();
5975 idle->prio = idle->normal_prio = MAX_PRIO;
5976 idle->cpus_allowed = cpumask_of_cpu(cpu);
5977 __set_task_cpu(idle, cpu);
5979 spin_lock_irqsave(&rq->lock, flags);
5980 rq->curr = rq->idle = idle;
5981 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5982 idle->oncpu = 1;
5983 #endif
5984 spin_unlock_irqrestore(&rq->lock, flags);
5986 /* Set the preempt count _outside_ the spinlocks! */
5987 task_thread_info(idle)->preempt_count = 0;
5990 * The idle tasks have their own, simple scheduling class:
5992 idle->sched_class = &idle_sched_class;
5996 * In a system that switches off the HZ timer nohz_cpu_mask
5997 * indicates which cpus entered this state. This is used
5998 * in the rcu update to wait only for active cpus. For system
5999 * which do not switch off the HZ timer nohz_cpu_mask should
6000 * always be CPU_MASK_NONE.
6002 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
6005 * Increase the granularity value when there are more CPUs,
6006 * because with more CPUs the 'effective latency' as visible
6007 * to users decreases. But the relationship is not linear,
6008 * so pick a second-best guess by going with the log2 of the
6009 * number of CPUs.
6011 * This idea comes from the SD scheduler of Con Kolivas:
6013 static inline void sched_init_granularity(void)
6015 unsigned int factor = 1 + ilog2(num_online_cpus());
6016 const unsigned long limit = 200000000;
6018 sysctl_sched_min_granularity *= factor;
6019 if (sysctl_sched_min_granularity > limit)
6020 sysctl_sched_min_granularity = limit;
6022 sysctl_sched_latency *= factor;
6023 if (sysctl_sched_latency > limit)
6024 sysctl_sched_latency = limit;
6026 sysctl_sched_wakeup_granularity *= factor;
6029 #ifdef CONFIG_SMP
6031 * This is how migration works:
6033 * 1) we queue a struct migration_req structure in the source CPU's
6034 * runqueue and wake up that CPU's migration thread.
6035 * 2) we down() the locked semaphore => thread blocks.
6036 * 3) migration thread wakes up (implicitly it forces the migrated
6037 * thread off the CPU)
6038 * 4) it gets the migration request and checks whether the migrated
6039 * task is still in the wrong runqueue.
6040 * 5) if it's in the wrong runqueue then the migration thread removes
6041 * it and puts it into the right queue.
6042 * 6) migration thread up()s the semaphore.
6043 * 7) we wake up and the migration is done.
6047 * Change a given task's CPU affinity. Migrate the thread to a
6048 * proper CPU and schedule it away if the CPU it's executing on
6049 * is removed from the allowed bitmask.
6051 * NOTE: the caller must have a valid reference to the task, the
6052 * task must not exit() & deallocate itself prematurely. The
6053 * call is not atomic; no spinlocks may be held.
6055 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
6057 struct migration_req req;
6058 unsigned long flags;
6059 struct rq *rq;
6060 int ret = 0;
6062 rq = task_rq_lock(p, &flags);
6063 if (!cpus_intersects(*new_mask, cpu_online_map)) {
6064 ret = -EINVAL;
6065 goto out;
6068 if (p->sched_class->set_cpus_allowed)
6069 p->sched_class->set_cpus_allowed(p, new_mask);
6070 else {
6071 p->cpus_allowed = *new_mask;
6072 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
6075 /* Can the task run on the task's current CPU? If so, we're done */
6076 if (cpu_isset(task_cpu(p), *new_mask))
6077 goto out;
6079 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
6080 /* Need help from migration thread: drop lock and wait. */
6081 task_rq_unlock(rq, &flags);
6082 wake_up_process(rq->migration_thread);
6083 wait_for_completion(&req.done);
6084 tlb_migrate_finish(p->mm);
6085 return 0;
6087 out:
6088 task_rq_unlock(rq, &flags);
6090 return ret;
6092 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6095 * Move (not current) task off this cpu, onto dest cpu. We're doing
6096 * this because either it can't run here any more (set_cpus_allowed()
6097 * away from this CPU, or CPU going down), or because we're
6098 * attempting to rebalance this task on exec (sched_exec).
6100 * So we race with normal scheduler movements, but that's OK, as long
6101 * as the task is no longer on this CPU.
6103 * Returns non-zero if task was successfully migrated.
6105 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6107 struct rq *rq_dest, *rq_src;
6108 int ret = 0, on_rq;
6110 if (unlikely(cpu_is_offline(dest_cpu)))
6111 return ret;
6113 rq_src = cpu_rq(src_cpu);
6114 rq_dest = cpu_rq(dest_cpu);
6116 double_rq_lock(rq_src, rq_dest);
6117 /* Already moved. */
6118 if (task_cpu(p) != src_cpu)
6119 goto out;
6120 /* Affinity changed (again). */
6121 if (!cpu_isset(dest_cpu, p->cpus_allowed))
6122 goto out;
6124 on_rq = p->se.on_rq;
6125 if (on_rq)
6126 deactivate_task(rq_src, p, 0);
6128 set_task_cpu(p, dest_cpu);
6129 if (on_rq) {
6130 activate_task(rq_dest, p, 0);
6131 check_preempt_curr(rq_dest, p);
6133 ret = 1;
6134 out:
6135 double_rq_unlock(rq_src, rq_dest);
6136 return ret;
6140 * migration_thread - this is a highprio system thread that performs
6141 * thread migration by bumping thread off CPU then 'pushing' onto
6142 * another runqueue.
6144 static int migration_thread(void *data)
6146 int cpu = (long)data;
6147 struct rq *rq;
6149 rq = cpu_rq(cpu);
6150 BUG_ON(rq->migration_thread != current);
6152 set_current_state(TASK_INTERRUPTIBLE);
6153 while (!kthread_should_stop()) {
6154 struct migration_req *req;
6155 struct list_head *head;
6157 spin_lock_irq(&rq->lock);
6159 if (cpu_is_offline(cpu)) {
6160 spin_unlock_irq(&rq->lock);
6161 goto wait_to_die;
6164 if (rq->active_balance) {
6165 active_load_balance(rq, cpu);
6166 rq->active_balance = 0;
6169 head = &rq->migration_queue;
6171 if (list_empty(head)) {
6172 spin_unlock_irq(&rq->lock);
6173 schedule();
6174 set_current_state(TASK_INTERRUPTIBLE);
6175 continue;
6177 req = list_entry(head->next, struct migration_req, list);
6178 list_del_init(head->next);
6180 spin_unlock(&rq->lock);
6181 __migrate_task(req->task, cpu, req->dest_cpu);
6182 local_irq_enable();
6184 complete(&req->done);
6186 __set_current_state(TASK_RUNNING);
6187 return 0;
6189 wait_to_die:
6190 /* Wait for kthread_stop */
6191 set_current_state(TASK_INTERRUPTIBLE);
6192 while (!kthread_should_stop()) {
6193 schedule();
6194 set_current_state(TASK_INTERRUPTIBLE);
6196 __set_current_state(TASK_RUNNING);
6197 return 0;
6200 #ifdef CONFIG_HOTPLUG_CPU
6202 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6204 int ret;
6206 local_irq_disable();
6207 ret = __migrate_task(p, src_cpu, dest_cpu);
6208 local_irq_enable();
6209 return ret;
6213 * Figure out where task on dead CPU should go, use force if necessary.
6214 * NOTE: interrupts should be disabled by the caller
6216 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6218 unsigned long flags;
6219 cpumask_t mask;
6220 struct rq *rq;
6221 int dest_cpu;
6223 do {
6224 /* On same node? */
6225 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6226 cpus_and(mask, mask, p->cpus_allowed);
6227 dest_cpu = any_online_cpu(mask);
6229 /* On any allowed CPU? */
6230 if (dest_cpu >= nr_cpu_ids)
6231 dest_cpu = any_online_cpu(p->cpus_allowed);
6233 /* No more Mr. Nice Guy. */
6234 if (dest_cpu >= nr_cpu_ids) {
6235 cpumask_t cpus_allowed;
6237 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6239 * Try to stay on the same cpuset, where the
6240 * current cpuset may be a subset of all cpus.
6241 * The cpuset_cpus_allowed_locked() variant of
6242 * cpuset_cpus_allowed() will not block. It must be
6243 * called within calls to cpuset_lock/cpuset_unlock.
6245 rq = task_rq_lock(p, &flags);
6246 p->cpus_allowed = cpus_allowed;
6247 dest_cpu = any_online_cpu(p->cpus_allowed);
6248 task_rq_unlock(rq, &flags);
6251 * Don't tell them about moving exiting tasks or
6252 * kernel threads (both mm NULL), since they never
6253 * leave kernel.
6255 if (p->mm && printk_ratelimit()) {
6256 printk(KERN_INFO "process %d (%s) no "
6257 "longer affine to cpu%d\n",
6258 task_pid_nr(p), p->comm, dead_cpu);
6261 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6265 * While a dead CPU has no uninterruptible tasks queued at this point,
6266 * it might still have a nonzero ->nr_uninterruptible counter, because
6267 * for performance reasons the counter is not stricly tracking tasks to
6268 * their home CPUs. So we just add the counter to another CPU's counter,
6269 * to keep the global sum constant after CPU-down:
6271 static void migrate_nr_uninterruptible(struct rq *rq_src)
6273 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6274 unsigned long flags;
6276 local_irq_save(flags);
6277 double_rq_lock(rq_src, rq_dest);
6278 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6279 rq_src->nr_uninterruptible = 0;
6280 double_rq_unlock(rq_src, rq_dest);
6281 local_irq_restore(flags);
6284 /* Run through task list and migrate tasks from the dead cpu. */
6285 static void migrate_live_tasks(int src_cpu)
6287 struct task_struct *p, *t;
6289 read_lock(&tasklist_lock);
6291 do_each_thread(t, p) {
6292 if (p == current)
6293 continue;
6295 if (task_cpu(p) == src_cpu)
6296 move_task_off_dead_cpu(src_cpu, p);
6297 } while_each_thread(t, p);
6299 read_unlock(&tasklist_lock);
6303 * Schedules idle task to be the next runnable task on current CPU.
6304 * It does so by boosting its priority to highest possible.
6305 * Used by CPU offline code.
6307 void sched_idle_next(void)
6309 int this_cpu = smp_processor_id();
6310 struct rq *rq = cpu_rq(this_cpu);
6311 struct task_struct *p = rq->idle;
6312 unsigned long flags;
6314 /* cpu has to be offline */
6315 BUG_ON(cpu_online(this_cpu));
6318 * Strictly not necessary since rest of the CPUs are stopped by now
6319 * and interrupts disabled on the current cpu.
6321 spin_lock_irqsave(&rq->lock, flags);
6323 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6325 update_rq_clock(rq);
6326 activate_task(rq, p, 0);
6328 spin_unlock_irqrestore(&rq->lock, flags);
6332 * Ensures that the idle task is using init_mm right before its cpu goes
6333 * offline.
6335 void idle_task_exit(void)
6337 struct mm_struct *mm = current->active_mm;
6339 BUG_ON(cpu_online(smp_processor_id()));
6341 if (mm != &init_mm)
6342 switch_mm(mm, &init_mm, current);
6343 mmdrop(mm);
6346 /* called under rq->lock with disabled interrupts */
6347 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6349 struct rq *rq = cpu_rq(dead_cpu);
6351 /* Must be exiting, otherwise would be on tasklist. */
6352 BUG_ON(!p->exit_state);
6354 /* Cannot have done final schedule yet: would have vanished. */
6355 BUG_ON(p->state == TASK_DEAD);
6357 get_task_struct(p);
6360 * Drop lock around migration; if someone else moves it,
6361 * that's OK. No task can be added to this CPU, so iteration is
6362 * fine.
6364 spin_unlock_irq(&rq->lock);
6365 move_task_off_dead_cpu(dead_cpu, p);
6366 spin_lock_irq(&rq->lock);
6368 put_task_struct(p);
6371 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6372 static void migrate_dead_tasks(unsigned int dead_cpu)
6374 struct rq *rq = cpu_rq(dead_cpu);
6375 struct task_struct *next;
6377 for ( ; ; ) {
6378 if (!rq->nr_running)
6379 break;
6380 update_rq_clock(rq);
6381 next = pick_next_task(rq, rq->curr);
6382 if (!next)
6383 break;
6384 migrate_dead(dead_cpu, next);
6388 #endif /* CONFIG_HOTPLUG_CPU */
6390 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6392 static struct ctl_table sd_ctl_dir[] = {
6394 .procname = "sched_domain",
6395 .mode = 0555,
6397 {0, },
6400 static struct ctl_table sd_ctl_root[] = {
6402 .ctl_name = CTL_KERN,
6403 .procname = "kernel",
6404 .mode = 0555,
6405 .child = sd_ctl_dir,
6407 {0, },
6410 static struct ctl_table *sd_alloc_ctl_entry(int n)
6412 struct ctl_table *entry =
6413 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6415 return entry;
6418 static void sd_free_ctl_entry(struct ctl_table **tablep)
6420 struct ctl_table *entry;
6423 * In the intermediate directories, both the child directory and
6424 * procname are dynamically allocated and could fail but the mode
6425 * will always be set. In the lowest directory the names are
6426 * static strings and all have proc handlers.
6428 for (entry = *tablep; entry->mode; entry++) {
6429 if (entry->child)
6430 sd_free_ctl_entry(&entry->child);
6431 if (entry->proc_handler == NULL)
6432 kfree(entry->procname);
6435 kfree(*tablep);
6436 *tablep = NULL;
6439 static void
6440 set_table_entry(struct ctl_table *entry,
6441 const char *procname, void *data, int maxlen,
6442 mode_t mode, proc_handler *proc_handler)
6444 entry->procname = procname;
6445 entry->data = data;
6446 entry->maxlen = maxlen;
6447 entry->mode = mode;
6448 entry->proc_handler = proc_handler;
6451 static struct ctl_table *
6452 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6454 struct ctl_table *table = sd_alloc_ctl_entry(12);
6456 if (table == NULL)
6457 return NULL;
6459 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6460 sizeof(long), 0644, proc_doulongvec_minmax);
6461 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6462 sizeof(long), 0644, proc_doulongvec_minmax);
6463 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6464 sizeof(int), 0644, proc_dointvec_minmax);
6465 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6466 sizeof(int), 0644, proc_dointvec_minmax);
6467 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6468 sizeof(int), 0644, proc_dointvec_minmax);
6469 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6470 sizeof(int), 0644, proc_dointvec_minmax);
6471 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6472 sizeof(int), 0644, proc_dointvec_minmax);
6473 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6474 sizeof(int), 0644, proc_dointvec_minmax);
6475 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6476 sizeof(int), 0644, proc_dointvec_minmax);
6477 set_table_entry(&table[9], "cache_nice_tries",
6478 &sd->cache_nice_tries,
6479 sizeof(int), 0644, proc_dointvec_minmax);
6480 set_table_entry(&table[10], "flags", &sd->flags,
6481 sizeof(int), 0644, proc_dointvec_minmax);
6482 /* &table[11] is terminator */
6484 return table;
6487 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6489 struct ctl_table *entry, *table;
6490 struct sched_domain *sd;
6491 int domain_num = 0, i;
6492 char buf[32];
6494 for_each_domain(cpu, sd)
6495 domain_num++;
6496 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6497 if (table == NULL)
6498 return NULL;
6500 i = 0;
6501 for_each_domain(cpu, sd) {
6502 snprintf(buf, 32, "domain%d", i);
6503 entry->procname = kstrdup(buf, GFP_KERNEL);
6504 entry->mode = 0555;
6505 entry->child = sd_alloc_ctl_domain_table(sd);
6506 entry++;
6507 i++;
6509 return table;
6512 static struct ctl_table_header *sd_sysctl_header;
6513 static void register_sched_domain_sysctl(void)
6515 int i, cpu_num = num_online_cpus();
6516 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6517 char buf[32];
6519 WARN_ON(sd_ctl_dir[0].child);
6520 sd_ctl_dir[0].child = entry;
6522 if (entry == NULL)
6523 return;
6525 for_each_online_cpu(i) {
6526 snprintf(buf, 32, "cpu%d", i);
6527 entry->procname = kstrdup(buf, GFP_KERNEL);
6528 entry->mode = 0555;
6529 entry->child = sd_alloc_ctl_cpu_table(i);
6530 entry++;
6533 WARN_ON(sd_sysctl_header);
6534 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6537 /* may be called multiple times per register */
6538 static void unregister_sched_domain_sysctl(void)
6540 if (sd_sysctl_header)
6541 unregister_sysctl_table(sd_sysctl_header);
6542 sd_sysctl_header = NULL;
6543 if (sd_ctl_dir[0].child)
6544 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6546 #else
6547 static void register_sched_domain_sysctl(void)
6550 static void unregister_sched_domain_sysctl(void)
6553 #endif
6556 * migration_call - callback that gets triggered when a CPU is added.
6557 * Here we can start up the necessary migration thread for the new CPU.
6559 static int __cpuinit
6560 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6562 struct task_struct *p;
6563 int cpu = (long)hcpu;
6564 unsigned long flags;
6565 struct rq *rq;
6567 switch (action) {
6569 case CPU_UP_PREPARE:
6570 case CPU_UP_PREPARE_FROZEN:
6571 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6572 if (IS_ERR(p))
6573 return NOTIFY_BAD;
6574 kthread_bind(p, cpu);
6575 /* Must be high prio: stop_machine expects to yield to it. */
6576 rq = task_rq_lock(p, &flags);
6577 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6578 task_rq_unlock(rq, &flags);
6579 cpu_rq(cpu)->migration_thread = p;
6580 break;
6582 case CPU_ONLINE:
6583 case CPU_ONLINE_FROZEN:
6584 /* Strictly unnecessary, as first user will wake it. */
6585 wake_up_process(cpu_rq(cpu)->migration_thread);
6587 /* Update our root-domain */
6588 rq = cpu_rq(cpu);
6589 spin_lock_irqsave(&rq->lock, flags);
6590 if (rq->rd) {
6591 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6592 cpu_set(cpu, rq->rd->online);
6594 spin_unlock_irqrestore(&rq->lock, flags);
6595 break;
6597 #ifdef CONFIG_HOTPLUG_CPU
6598 case CPU_UP_CANCELED:
6599 case CPU_UP_CANCELED_FROZEN:
6600 if (!cpu_rq(cpu)->migration_thread)
6601 break;
6602 /* Unbind it from offline cpu so it can run. Fall thru. */
6603 kthread_bind(cpu_rq(cpu)->migration_thread,
6604 any_online_cpu(cpu_online_map));
6605 kthread_stop(cpu_rq(cpu)->migration_thread);
6606 cpu_rq(cpu)->migration_thread = NULL;
6607 break;
6609 case CPU_DEAD:
6610 case CPU_DEAD_FROZEN:
6611 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6612 migrate_live_tasks(cpu);
6613 rq = cpu_rq(cpu);
6614 kthread_stop(rq->migration_thread);
6615 rq->migration_thread = NULL;
6616 /* Idle task back to normal (off runqueue, low prio) */
6617 spin_lock_irq(&rq->lock);
6618 update_rq_clock(rq);
6619 deactivate_task(rq, rq->idle, 0);
6620 rq->idle->static_prio = MAX_PRIO;
6621 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6622 rq->idle->sched_class = &idle_sched_class;
6623 migrate_dead_tasks(cpu);
6624 spin_unlock_irq(&rq->lock);
6625 cpuset_unlock();
6626 migrate_nr_uninterruptible(rq);
6627 BUG_ON(rq->nr_running != 0);
6630 * No need to migrate the tasks: it was best-effort if
6631 * they didn't take sched_hotcpu_mutex. Just wake up
6632 * the requestors.
6634 spin_lock_irq(&rq->lock);
6635 while (!list_empty(&rq->migration_queue)) {
6636 struct migration_req *req;
6638 req = list_entry(rq->migration_queue.next,
6639 struct migration_req, list);
6640 list_del_init(&req->list);
6641 complete(&req->done);
6643 spin_unlock_irq(&rq->lock);
6644 break;
6646 case CPU_DYING:
6647 case CPU_DYING_FROZEN:
6648 /* Update our root-domain */
6649 rq = cpu_rq(cpu);
6650 spin_lock_irqsave(&rq->lock, flags);
6651 if (rq->rd) {
6652 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6653 cpu_clear(cpu, rq->rd->online);
6655 spin_unlock_irqrestore(&rq->lock, flags);
6656 break;
6657 #endif
6659 return NOTIFY_OK;
6662 /* Register at highest priority so that task migration (migrate_all_tasks)
6663 * happens before everything else.
6665 static struct notifier_block __cpuinitdata migration_notifier = {
6666 .notifier_call = migration_call,
6667 .priority = 10
6670 void __init migration_init(void)
6672 void *cpu = (void *)(long)smp_processor_id();
6673 int err;
6675 /* Start one for the boot CPU: */
6676 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6677 BUG_ON(err == NOTIFY_BAD);
6678 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6679 register_cpu_notifier(&migration_notifier);
6681 #endif
6683 #ifdef CONFIG_SMP
6685 #ifdef CONFIG_SCHED_DEBUG
6687 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6688 cpumask_t *groupmask)
6690 struct sched_group *group = sd->groups;
6691 char str[256];
6693 cpulist_scnprintf(str, sizeof(str), sd->span);
6694 cpus_clear(*groupmask);
6696 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6698 if (!(sd->flags & SD_LOAD_BALANCE)) {
6699 printk("does not load-balance\n");
6700 if (sd->parent)
6701 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6702 " has parent");
6703 return -1;
6706 printk(KERN_CONT "span %s\n", str);
6708 if (!cpu_isset(cpu, sd->span)) {
6709 printk(KERN_ERR "ERROR: domain->span does not contain "
6710 "CPU%d\n", cpu);
6712 if (!cpu_isset(cpu, group->cpumask)) {
6713 printk(KERN_ERR "ERROR: domain->groups does not contain"
6714 " CPU%d\n", cpu);
6717 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6718 do {
6719 if (!group) {
6720 printk("\n");
6721 printk(KERN_ERR "ERROR: group is NULL\n");
6722 break;
6725 if (!group->__cpu_power) {
6726 printk(KERN_CONT "\n");
6727 printk(KERN_ERR "ERROR: domain->cpu_power not "
6728 "set\n");
6729 break;
6732 if (!cpus_weight(group->cpumask)) {
6733 printk(KERN_CONT "\n");
6734 printk(KERN_ERR "ERROR: empty group\n");
6735 break;
6738 if (cpus_intersects(*groupmask, group->cpumask)) {
6739 printk(KERN_CONT "\n");
6740 printk(KERN_ERR "ERROR: repeated CPUs\n");
6741 break;
6744 cpus_or(*groupmask, *groupmask, group->cpumask);
6746 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6747 printk(KERN_CONT " %s", str);
6749 group = group->next;
6750 } while (group != sd->groups);
6751 printk(KERN_CONT "\n");
6753 if (!cpus_equal(sd->span, *groupmask))
6754 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6756 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6757 printk(KERN_ERR "ERROR: parent span is not a superset "
6758 "of domain->span\n");
6759 return 0;
6762 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6764 cpumask_t *groupmask;
6765 int level = 0;
6767 if (!sd) {
6768 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6769 return;
6772 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6774 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6775 if (!groupmask) {
6776 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6777 return;
6780 for (;;) {
6781 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6782 break;
6783 level++;
6784 sd = sd->parent;
6785 if (!sd)
6786 break;
6788 kfree(groupmask);
6790 #else
6791 # define sched_domain_debug(sd, cpu) do { } while (0)
6792 #endif
6794 static int sd_degenerate(struct sched_domain *sd)
6796 if (cpus_weight(sd->span) == 1)
6797 return 1;
6799 /* Following flags need at least 2 groups */
6800 if (sd->flags & (SD_LOAD_BALANCE |
6801 SD_BALANCE_NEWIDLE |
6802 SD_BALANCE_FORK |
6803 SD_BALANCE_EXEC |
6804 SD_SHARE_CPUPOWER |
6805 SD_SHARE_PKG_RESOURCES)) {
6806 if (sd->groups != sd->groups->next)
6807 return 0;
6810 /* Following flags don't use groups */
6811 if (sd->flags & (SD_WAKE_IDLE |
6812 SD_WAKE_AFFINE |
6813 SD_WAKE_BALANCE))
6814 return 0;
6816 return 1;
6819 static int
6820 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6822 unsigned long cflags = sd->flags, pflags = parent->flags;
6824 if (sd_degenerate(parent))
6825 return 1;
6827 if (!cpus_equal(sd->span, parent->span))
6828 return 0;
6830 /* Does parent contain flags not in child? */
6831 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6832 if (cflags & SD_WAKE_AFFINE)
6833 pflags &= ~SD_WAKE_BALANCE;
6834 /* Flags needing groups don't count if only 1 group in parent */
6835 if (parent->groups == parent->groups->next) {
6836 pflags &= ~(SD_LOAD_BALANCE |
6837 SD_BALANCE_NEWIDLE |
6838 SD_BALANCE_FORK |
6839 SD_BALANCE_EXEC |
6840 SD_SHARE_CPUPOWER |
6841 SD_SHARE_PKG_RESOURCES);
6843 if (~cflags & pflags)
6844 return 0;
6846 return 1;
6849 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6851 unsigned long flags;
6852 const struct sched_class *class;
6854 spin_lock_irqsave(&rq->lock, flags);
6856 if (rq->rd) {
6857 struct root_domain *old_rd = rq->rd;
6859 for (class = sched_class_highest; class; class = class->next) {
6860 if (class->leave_domain)
6861 class->leave_domain(rq);
6864 cpu_clear(rq->cpu, old_rd->span);
6865 cpu_clear(rq->cpu, old_rd->online);
6867 if (atomic_dec_and_test(&old_rd->refcount))
6868 kfree(old_rd);
6871 atomic_inc(&rd->refcount);
6872 rq->rd = rd;
6874 cpu_set(rq->cpu, rd->span);
6875 if (cpu_isset(rq->cpu, cpu_online_map))
6876 cpu_set(rq->cpu, rd->online);
6878 for (class = sched_class_highest; class; class = class->next) {
6879 if (class->join_domain)
6880 class->join_domain(rq);
6883 spin_unlock_irqrestore(&rq->lock, flags);
6886 static void init_rootdomain(struct root_domain *rd)
6888 memset(rd, 0, sizeof(*rd));
6890 cpus_clear(rd->span);
6891 cpus_clear(rd->online);
6894 static void init_defrootdomain(void)
6896 init_rootdomain(&def_root_domain);
6897 atomic_set(&def_root_domain.refcount, 1);
6900 static struct root_domain *alloc_rootdomain(void)
6902 struct root_domain *rd;
6904 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6905 if (!rd)
6906 return NULL;
6908 init_rootdomain(rd);
6910 return rd;
6914 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6915 * hold the hotplug lock.
6917 static void
6918 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6920 struct rq *rq = cpu_rq(cpu);
6921 struct sched_domain *tmp;
6923 /* Remove the sched domains which do not contribute to scheduling. */
6924 for (tmp = sd; tmp; tmp = tmp->parent) {
6925 struct sched_domain *parent = tmp->parent;
6926 if (!parent)
6927 break;
6928 if (sd_parent_degenerate(tmp, parent)) {
6929 tmp->parent = parent->parent;
6930 if (parent->parent)
6931 parent->parent->child = tmp;
6935 if (sd && sd_degenerate(sd)) {
6936 sd = sd->parent;
6937 if (sd)
6938 sd->child = NULL;
6941 sched_domain_debug(sd, cpu);
6943 rq_attach_root(rq, rd);
6944 rcu_assign_pointer(rq->sd, sd);
6947 /* cpus with isolated domains */
6948 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6950 /* Setup the mask of cpus configured for isolated domains */
6951 static int __init isolated_cpu_setup(char *str)
6953 int ints[NR_CPUS], i;
6955 str = get_options(str, ARRAY_SIZE(ints), ints);
6956 cpus_clear(cpu_isolated_map);
6957 for (i = 1; i <= ints[0]; i++)
6958 if (ints[i] < NR_CPUS)
6959 cpu_set(ints[i], cpu_isolated_map);
6960 return 1;
6963 __setup("isolcpus=", isolated_cpu_setup);
6966 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6967 * to a function which identifies what group(along with sched group) a CPU
6968 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6969 * (due to the fact that we keep track of groups covered with a cpumask_t).
6971 * init_sched_build_groups will build a circular linked list of the groups
6972 * covered by the given span, and will set each group's ->cpumask correctly,
6973 * and ->cpu_power to 0.
6975 static void
6976 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6977 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6978 struct sched_group **sg,
6979 cpumask_t *tmpmask),
6980 cpumask_t *covered, cpumask_t *tmpmask)
6982 struct sched_group *first = NULL, *last = NULL;
6983 int i;
6985 cpus_clear(*covered);
6987 for_each_cpu_mask(i, *span) {
6988 struct sched_group *sg;
6989 int group = group_fn(i, cpu_map, &sg, tmpmask);
6990 int j;
6992 if (cpu_isset(i, *covered))
6993 continue;
6995 cpus_clear(sg->cpumask);
6996 sg->__cpu_power = 0;
6998 for_each_cpu_mask(j, *span) {
6999 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
7000 continue;
7002 cpu_set(j, *covered);
7003 cpu_set(j, sg->cpumask);
7005 if (!first)
7006 first = sg;
7007 if (last)
7008 last->next = sg;
7009 last = sg;
7011 last->next = first;
7014 #define SD_NODES_PER_DOMAIN 16
7016 #ifdef CONFIG_NUMA
7019 * find_next_best_node - find the next node to include in a sched_domain
7020 * @node: node whose sched_domain we're building
7021 * @used_nodes: nodes already in the sched_domain
7023 * Find the next node to include in a given scheduling domain. Simply
7024 * finds the closest node not already in the @used_nodes map.
7026 * Should use nodemask_t.
7028 static int find_next_best_node(int node, nodemask_t *used_nodes)
7030 int i, n, val, min_val, best_node = 0;
7032 min_val = INT_MAX;
7034 for (i = 0; i < MAX_NUMNODES; i++) {
7035 /* Start at @node */
7036 n = (node + i) % MAX_NUMNODES;
7038 if (!nr_cpus_node(n))
7039 continue;
7041 /* Skip already used nodes */
7042 if (node_isset(n, *used_nodes))
7043 continue;
7045 /* Simple min distance search */
7046 val = node_distance(node, n);
7048 if (val < min_val) {
7049 min_val = val;
7050 best_node = n;
7054 node_set(best_node, *used_nodes);
7055 return best_node;
7059 * sched_domain_node_span - get a cpumask for a node's sched_domain
7060 * @node: node whose cpumask we're constructing
7061 * @span: resulting cpumask
7063 * Given a node, construct a good cpumask for its sched_domain to span. It
7064 * should be one that prevents unnecessary balancing, but also spreads tasks
7065 * out optimally.
7067 static void sched_domain_node_span(int node, cpumask_t *span)
7069 nodemask_t used_nodes;
7070 node_to_cpumask_ptr(nodemask, node);
7071 int i;
7073 cpus_clear(*span);
7074 nodes_clear(used_nodes);
7076 cpus_or(*span, *span, *nodemask);
7077 node_set(node, used_nodes);
7079 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7080 int next_node = find_next_best_node(node, &used_nodes);
7082 node_to_cpumask_ptr_next(nodemask, next_node);
7083 cpus_or(*span, *span, *nodemask);
7086 #endif
7088 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7091 * SMT sched-domains:
7093 #ifdef CONFIG_SCHED_SMT
7094 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
7095 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
7097 static int
7098 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7099 cpumask_t *unused)
7101 if (sg)
7102 *sg = &per_cpu(sched_group_cpus, cpu);
7103 return cpu;
7105 #endif
7108 * multi-core sched-domains:
7110 #ifdef CONFIG_SCHED_MC
7111 static DEFINE_PER_CPU(struct sched_domain, core_domains);
7112 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
7113 #endif
7115 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7116 static int
7117 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7118 cpumask_t *mask)
7120 int group;
7122 *mask = per_cpu(cpu_sibling_map, cpu);
7123 cpus_and(*mask, *mask, *cpu_map);
7124 group = first_cpu(*mask);
7125 if (sg)
7126 *sg = &per_cpu(sched_group_core, group);
7127 return group;
7129 #elif defined(CONFIG_SCHED_MC)
7130 static int
7131 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7132 cpumask_t *unused)
7134 if (sg)
7135 *sg = &per_cpu(sched_group_core, cpu);
7136 return cpu;
7138 #endif
7140 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7141 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7143 static int
7144 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7145 cpumask_t *mask)
7147 int group;
7148 #ifdef CONFIG_SCHED_MC
7149 *mask = cpu_coregroup_map(cpu);
7150 cpus_and(*mask, *mask, *cpu_map);
7151 group = first_cpu(*mask);
7152 #elif defined(CONFIG_SCHED_SMT)
7153 *mask = per_cpu(cpu_sibling_map, cpu);
7154 cpus_and(*mask, *mask, *cpu_map);
7155 group = first_cpu(*mask);
7156 #else
7157 group = cpu;
7158 #endif
7159 if (sg)
7160 *sg = &per_cpu(sched_group_phys, group);
7161 return group;
7164 #ifdef CONFIG_NUMA
7166 * The init_sched_build_groups can't handle what we want to do with node
7167 * groups, so roll our own. Now each node has its own list of groups which
7168 * gets dynamically allocated.
7170 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7171 static struct sched_group ***sched_group_nodes_bycpu;
7173 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7174 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7176 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7177 struct sched_group **sg, cpumask_t *nodemask)
7179 int group;
7181 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7182 cpus_and(*nodemask, *nodemask, *cpu_map);
7183 group = first_cpu(*nodemask);
7185 if (sg)
7186 *sg = &per_cpu(sched_group_allnodes, group);
7187 return group;
7190 static void init_numa_sched_groups_power(struct sched_group *group_head)
7192 struct sched_group *sg = group_head;
7193 int j;
7195 if (!sg)
7196 return;
7197 do {
7198 for_each_cpu_mask(j, sg->cpumask) {
7199 struct sched_domain *sd;
7201 sd = &per_cpu(phys_domains, j);
7202 if (j != first_cpu(sd->groups->cpumask)) {
7204 * Only add "power" once for each
7205 * physical package.
7207 continue;
7210 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7212 sg = sg->next;
7213 } while (sg != group_head);
7215 #endif
7217 #ifdef CONFIG_NUMA
7218 /* Free memory allocated for various sched_group structures */
7219 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7221 int cpu, i;
7223 for_each_cpu_mask(cpu, *cpu_map) {
7224 struct sched_group **sched_group_nodes
7225 = sched_group_nodes_bycpu[cpu];
7227 if (!sched_group_nodes)
7228 continue;
7230 for (i = 0; i < MAX_NUMNODES; i++) {
7231 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7233 *nodemask = node_to_cpumask(i);
7234 cpus_and(*nodemask, *nodemask, *cpu_map);
7235 if (cpus_empty(*nodemask))
7236 continue;
7238 if (sg == NULL)
7239 continue;
7240 sg = sg->next;
7241 next_sg:
7242 oldsg = sg;
7243 sg = sg->next;
7244 kfree(oldsg);
7245 if (oldsg != sched_group_nodes[i])
7246 goto next_sg;
7248 kfree(sched_group_nodes);
7249 sched_group_nodes_bycpu[cpu] = NULL;
7252 #else
7253 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7256 #endif
7259 * Initialize sched groups cpu_power.
7261 * cpu_power indicates the capacity of sched group, which is used while
7262 * distributing the load between different sched groups in a sched domain.
7263 * Typically cpu_power for all the groups in a sched domain will be same unless
7264 * there are asymmetries in the topology. If there are asymmetries, group
7265 * having more cpu_power will pickup more load compared to the group having
7266 * less cpu_power.
7268 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7269 * the maximum number of tasks a group can handle in the presence of other idle
7270 * or lightly loaded groups in the same sched domain.
7272 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7274 struct sched_domain *child;
7275 struct sched_group *group;
7277 WARN_ON(!sd || !sd->groups);
7279 if (cpu != first_cpu(sd->groups->cpumask))
7280 return;
7282 child = sd->child;
7284 sd->groups->__cpu_power = 0;
7287 * For perf policy, if the groups in child domain share resources
7288 * (for example cores sharing some portions of the cache hierarchy
7289 * or SMT), then set this domain groups cpu_power such that each group
7290 * can handle only one task, when there are other idle groups in the
7291 * same sched domain.
7293 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7294 (child->flags &
7295 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7296 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7297 return;
7301 * add cpu_power of each child group to this groups cpu_power
7303 group = child->groups;
7304 do {
7305 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7306 group = group->next;
7307 } while (group != child->groups);
7311 * Initializers for schedule domains
7312 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7315 #define SD_INIT(sd, type) sd_init_##type(sd)
7316 #define SD_INIT_FUNC(type) \
7317 static noinline void sd_init_##type(struct sched_domain *sd) \
7319 memset(sd, 0, sizeof(*sd)); \
7320 *sd = SD_##type##_INIT; \
7321 sd->level = SD_LV_##type; \
7324 SD_INIT_FUNC(CPU)
7325 #ifdef CONFIG_NUMA
7326 SD_INIT_FUNC(ALLNODES)
7327 SD_INIT_FUNC(NODE)
7328 #endif
7329 #ifdef CONFIG_SCHED_SMT
7330 SD_INIT_FUNC(SIBLING)
7331 #endif
7332 #ifdef CONFIG_SCHED_MC
7333 SD_INIT_FUNC(MC)
7334 #endif
7337 * To minimize stack usage kmalloc room for cpumasks and share the
7338 * space as the usage in build_sched_domains() dictates. Used only
7339 * if the amount of space is significant.
7341 struct allmasks {
7342 cpumask_t tmpmask; /* make this one first */
7343 union {
7344 cpumask_t nodemask;
7345 cpumask_t this_sibling_map;
7346 cpumask_t this_core_map;
7348 cpumask_t send_covered;
7350 #ifdef CONFIG_NUMA
7351 cpumask_t domainspan;
7352 cpumask_t covered;
7353 cpumask_t notcovered;
7354 #endif
7357 #if NR_CPUS > 128
7358 #define SCHED_CPUMASK_ALLOC 1
7359 #define SCHED_CPUMASK_FREE(v) kfree(v)
7360 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7361 #else
7362 #define SCHED_CPUMASK_ALLOC 0
7363 #define SCHED_CPUMASK_FREE(v)
7364 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7365 #endif
7367 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7368 ((unsigned long)(a) + offsetof(struct allmasks, v))
7370 static int default_relax_domain_level = -1;
7372 static int __init setup_relax_domain_level(char *str)
7374 default_relax_domain_level = simple_strtoul(str, NULL, 0);
7375 return 1;
7377 __setup("relax_domain_level=", setup_relax_domain_level);
7379 static void set_domain_attribute(struct sched_domain *sd,
7380 struct sched_domain_attr *attr)
7382 int request;
7384 if (!attr || attr->relax_domain_level < 0) {
7385 if (default_relax_domain_level < 0)
7386 return;
7387 else
7388 request = default_relax_domain_level;
7389 } else
7390 request = attr->relax_domain_level;
7391 if (request < sd->level) {
7392 /* turn off idle balance on this domain */
7393 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7394 } else {
7395 /* turn on idle balance on this domain */
7396 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7401 * Build sched domains for a given set of cpus and attach the sched domains
7402 * to the individual cpus
7404 static int __build_sched_domains(const cpumask_t *cpu_map,
7405 struct sched_domain_attr *attr)
7407 int i;
7408 struct root_domain *rd;
7409 SCHED_CPUMASK_DECLARE(allmasks);
7410 cpumask_t *tmpmask;
7411 #ifdef CONFIG_NUMA
7412 struct sched_group **sched_group_nodes = NULL;
7413 int sd_allnodes = 0;
7416 * Allocate the per-node list of sched groups
7418 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
7419 GFP_KERNEL);
7420 if (!sched_group_nodes) {
7421 printk(KERN_WARNING "Can not alloc sched group node list\n");
7422 return -ENOMEM;
7424 #endif
7426 rd = alloc_rootdomain();
7427 if (!rd) {
7428 printk(KERN_WARNING "Cannot alloc root domain\n");
7429 #ifdef CONFIG_NUMA
7430 kfree(sched_group_nodes);
7431 #endif
7432 return -ENOMEM;
7435 #if SCHED_CPUMASK_ALLOC
7436 /* get space for all scratch cpumask variables */
7437 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7438 if (!allmasks) {
7439 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7440 kfree(rd);
7441 #ifdef CONFIG_NUMA
7442 kfree(sched_group_nodes);
7443 #endif
7444 return -ENOMEM;
7446 #endif
7447 tmpmask = (cpumask_t *)allmasks;
7450 #ifdef CONFIG_NUMA
7451 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7452 #endif
7455 * Set up domains for cpus specified by the cpu_map.
7457 for_each_cpu_mask(i, *cpu_map) {
7458 struct sched_domain *sd = NULL, *p;
7459 SCHED_CPUMASK_VAR(nodemask, allmasks);
7461 *nodemask = node_to_cpumask(cpu_to_node(i));
7462 cpus_and(*nodemask, *nodemask, *cpu_map);
7464 #ifdef CONFIG_NUMA
7465 if (cpus_weight(*cpu_map) >
7466 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7467 sd = &per_cpu(allnodes_domains, i);
7468 SD_INIT(sd, ALLNODES);
7469 set_domain_attribute(sd, attr);
7470 sd->span = *cpu_map;
7471 sd->first_cpu = first_cpu(sd->span);
7472 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7473 p = sd;
7474 sd_allnodes = 1;
7475 } else
7476 p = NULL;
7478 sd = &per_cpu(node_domains, i);
7479 SD_INIT(sd, NODE);
7480 set_domain_attribute(sd, attr);
7481 sched_domain_node_span(cpu_to_node(i), &sd->span);
7482 sd->first_cpu = first_cpu(sd->span);
7483 sd->parent = p;
7484 if (p)
7485 p->child = sd;
7486 cpus_and(sd->span, sd->span, *cpu_map);
7487 #endif
7489 p = sd;
7490 sd = &per_cpu(phys_domains, i);
7491 SD_INIT(sd, CPU);
7492 set_domain_attribute(sd, attr);
7493 sd->span = *nodemask;
7494 sd->first_cpu = first_cpu(sd->span);
7495 sd->parent = p;
7496 if (p)
7497 p->child = sd;
7498 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7500 #ifdef CONFIG_SCHED_MC
7501 p = sd;
7502 sd = &per_cpu(core_domains, i);
7503 SD_INIT(sd, MC);
7504 set_domain_attribute(sd, attr);
7505 sd->span = cpu_coregroup_map(i);
7506 sd->first_cpu = first_cpu(sd->span);
7507 cpus_and(sd->span, sd->span, *cpu_map);
7508 sd->parent = p;
7509 p->child = sd;
7510 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7511 #endif
7513 #ifdef CONFIG_SCHED_SMT
7514 p = sd;
7515 sd = &per_cpu(cpu_domains, i);
7516 SD_INIT(sd, SIBLING);
7517 set_domain_attribute(sd, attr);
7518 sd->span = per_cpu(cpu_sibling_map, i);
7519 sd->first_cpu = first_cpu(sd->span);
7520 cpus_and(sd->span, sd->span, *cpu_map);
7521 sd->parent = p;
7522 p->child = sd;
7523 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7524 #endif
7527 #ifdef CONFIG_SCHED_SMT
7528 /* Set up CPU (sibling) groups */
7529 for_each_cpu_mask(i, *cpu_map) {
7530 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7531 SCHED_CPUMASK_VAR(send_covered, allmasks);
7533 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7534 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7535 if (i != first_cpu(*this_sibling_map))
7536 continue;
7538 init_sched_build_groups(this_sibling_map, cpu_map,
7539 &cpu_to_cpu_group,
7540 send_covered, tmpmask);
7542 #endif
7544 #ifdef CONFIG_SCHED_MC
7545 /* Set up multi-core groups */
7546 for_each_cpu_mask(i, *cpu_map) {
7547 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7548 SCHED_CPUMASK_VAR(send_covered, allmasks);
7550 *this_core_map = cpu_coregroup_map(i);
7551 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7552 if (i != first_cpu(*this_core_map))
7553 continue;
7555 init_sched_build_groups(this_core_map, cpu_map,
7556 &cpu_to_core_group,
7557 send_covered, tmpmask);
7559 #endif
7561 /* Set up physical groups */
7562 for (i = 0; i < MAX_NUMNODES; i++) {
7563 SCHED_CPUMASK_VAR(nodemask, allmasks);
7564 SCHED_CPUMASK_VAR(send_covered, allmasks);
7566 *nodemask = node_to_cpumask(i);
7567 cpus_and(*nodemask, *nodemask, *cpu_map);
7568 if (cpus_empty(*nodemask))
7569 continue;
7571 init_sched_build_groups(nodemask, cpu_map,
7572 &cpu_to_phys_group,
7573 send_covered, tmpmask);
7576 #ifdef CONFIG_NUMA
7577 /* Set up node groups */
7578 if (sd_allnodes) {
7579 SCHED_CPUMASK_VAR(send_covered, allmasks);
7581 init_sched_build_groups(cpu_map, cpu_map,
7582 &cpu_to_allnodes_group,
7583 send_covered, tmpmask);
7586 for (i = 0; i < MAX_NUMNODES; i++) {
7587 /* Set up node groups */
7588 struct sched_group *sg, *prev;
7589 SCHED_CPUMASK_VAR(nodemask, allmasks);
7590 SCHED_CPUMASK_VAR(domainspan, allmasks);
7591 SCHED_CPUMASK_VAR(covered, allmasks);
7592 int j;
7594 *nodemask = node_to_cpumask(i);
7595 cpus_clear(*covered);
7597 cpus_and(*nodemask, *nodemask, *cpu_map);
7598 if (cpus_empty(*nodemask)) {
7599 sched_group_nodes[i] = NULL;
7600 continue;
7603 sched_domain_node_span(i, domainspan);
7604 cpus_and(*domainspan, *domainspan, *cpu_map);
7606 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7607 if (!sg) {
7608 printk(KERN_WARNING "Can not alloc domain group for "
7609 "node %d\n", i);
7610 goto error;
7612 sched_group_nodes[i] = sg;
7613 for_each_cpu_mask(j, *nodemask) {
7614 struct sched_domain *sd;
7616 sd = &per_cpu(node_domains, j);
7617 sd->groups = sg;
7619 sg->__cpu_power = 0;
7620 sg->cpumask = *nodemask;
7621 sg->next = sg;
7622 cpus_or(*covered, *covered, *nodemask);
7623 prev = sg;
7625 for (j = 0; j < MAX_NUMNODES; j++) {
7626 SCHED_CPUMASK_VAR(notcovered, allmasks);
7627 int n = (i + j) % MAX_NUMNODES;
7628 node_to_cpumask_ptr(pnodemask, n);
7630 cpus_complement(*notcovered, *covered);
7631 cpus_and(*tmpmask, *notcovered, *cpu_map);
7632 cpus_and(*tmpmask, *tmpmask, *domainspan);
7633 if (cpus_empty(*tmpmask))
7634 break;
7636 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7637 if (cpus_empty(*tmpmask))
7638 continue;
7640 sg = kmalloc_node(sizeof(struct sched_group),
7641 GFP_KERNEL, i);
7642 if (!sg) {
7643 printk(KERN_WARNING
7644 "Can not alloc domain group for node %d\n", j);
7645 goto error;
7647 sg->__cpu_power = 0;
7648 sg->cpumask = *tmpmask;
7649 sg->next = prev->next;
7650 cpus_or(*covered, *covered, *tmpmask);
7651 prev->next = sg;
7652 prev = sg;
7655 #endif
7657 /* Calculate CPU power for physical packages and nodes */
7658 #ifdef CONFIG_SCHED_SMT
7659 for_each_cpu_mask(i, *cpu_map) {
7660 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7662 init_sched_groups_power(i, sd);
7664 #endif
7665 #ifdef CONFIG_SCHED_MC
7666 for_each_cpu_mask(i, *cpu_map) {
7667 struct sched_domain *sd = &per_cpu(core_domains, i);
7669 init_sched_groups_power(i, sd);
7671 #endif
7673 for_each_cpu_mask(i, *cpu_map) {
7674 struct sched_domain *sd = &per_cpu(phys_domains, i);
7676 init_sched_groups_power(i, sd);
7679 #ifdef CONFIG_NUMA
7680 for (i = 0; i < MAX_NUMNODES; i++)
7681 init_numa_sched_groups_power(sched_group_nodes[i]);
7683 if (sd_allnodes) {
7684 struct sched_group *sg;
7686 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7687 tmpmask);
7688 init_numa_sched_groups_power(sg);
7690 #endif
7692 /* Attach the domains */
7693 for_each_cpu_mask(i, *cpu_map) {
7694 struct sched_domain *sd;
7695 #ifdef CONFIG_SCHED_SMT
7696 sd = &per_cpu(cpu_domains, i);
7697 #elif defined(CONFIG_SCHED_MC)
7698 sd = &per_cpu(core_domains, i);
7699 #else
7700 sd = &per_cpu(phys_domains, i);
7701 #endif
7702 cpu_attach_domain(sd, rd, i);
7705 SCHED_CPUMASK_FREE((void *)allmasks);
7706 return 0;
7708 #ifdef CONFIG_NUMA
7709 error:
7710 free_sched_groups(cpu_map, tmpmask);
7711 SCHED_CPUMASK_FREE((void *)allmasks);
7712 return -ENOMEM;
7713 #endif
7716 static int build_sched_domains(const cpumask_t *cpu_map)
7718 return __build_sched_domains(cpu_map, NULL);
7721 static cpumask_t *doms_cur; /* current sched domains */
7722 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7723 static struct sched_domain_attr *dattr_cur; /* attribues of custom domains
7724 in 'doms_cur' */
7727 * Special case: If a kmalloc of a doms_cur partition (array of
7728 * cpumask_t) fails, then fallback to a single sched domain,
7729 * as determined by the single cpumask_t fallback_doms.
7731 static cpumask_t fallback_doms;
7733 void __attribute__((weak)) arch_update_cpu_topology(void)
7738 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7739 * For now this just excludes isolated cpus, but could be used to
7740 * exclude other special cases in the future.
7742 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7744 int err;
7746 arch_update_cpu_topology();
7747 ndoms_cur = 1;
7748 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7749 if (!doms_cur)
7750 doms_cur = &fallback_doms;
7751 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7752 dattr_cur = NULL;
7753 err = build_sched_domains(doms_cur);
7754 register_sched_domain_sysctl();
7756 return err;
7759 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7760 cpumask_t *tmpmask)
7762 free_sched_groups(cpu_map, tmpmask);
7766 * Detach sched domains from a group of cpus specified in cpu_map
7767 * These cpus will now be attached to the NULL domain
7769 static void detach_destroy_domains(const cpumask_t *cpu_map)
7771 cpumask_t tmpmask;
7772 int i;
7774 unregister_sched_domain_sysctl();
7776 for_each_cpu_mask(i, *cpu_map)
7777 cpu_attach_domain(NULL, &def_root_domain, i);
7778 synchronize_sched();
7779 arch_destroy_sched_domains(cpu_map, &tmpmask);
7782 /* handle null as "default" */
7783 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7784 struct sched_domain_attr *new, int idx_new)
7786 struct sched_domain_attr tmp;
7788 /* fast path */
7789 if (!new && !cur)
7790 return 1;
7792 tmp = SD_ATTR_INIT;
7793 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7794 new ? (new + idx_new) : &tmp,
7795 sizeof(struct sched_domain_attr));
7799 * Partition sched domains as specified by the 'ndoms_new'
7800 * cpumasks in the array doms_new[] of cpumasks. This compares
7801 * doms_new[] to the current sched domain partitioning, doms_cur[].
7802 * It destroys each deleted domain and builds each new domain.
7804 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7805 * The masks don't intersect (don't overlap.) We should setup one
7806 * sched domain for each mask. CPUs not in any of the cpumasks will
7807 * not be load balanced. If the same cpumask appears both in the
7808 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7809 * it as it is.
7811 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7812 * ownership of it and will kfree it when done with it. If the caller
7813 * failed the kmalloc call, then it can pass in doms_new == NULL,
7814 * and partition_sched_domains() will fallback to the single partition
7815 * 'fallback_doms'.
7817 * Call with hotplug lock held
7819 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7820 struct sched_domain_attr *dattr_new)
7822 int i, j;
7824 mutex_lock(&sched_domains_mutex);
7826 /* always unregister in case we don't destroy any domains */
7827 unregister_sched_domain_sysctl();
7829 if (doms_new == NULL) {
7830 ndoms_new = 1;
7831 doms_new = &fallback_doms;
7832 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7833 dattr_new = NULL;
7836 /* Destroy deleted domains */
7837 for (i = 0; i < ndoms_cur; i++) {
7838 for (j = 0; j < ndoms_new; j++) {
7839 if (cpus_equal(doms_cur[i], doms_new[j])
7840 && dattrs_equal(dattr_cur, i, dattr_new, j))
7841 goto match1;
7843 /* no match - a current sched domain not in new doms_new[] */
7844 detach_destroy_domains(doms_cur + i);
7845 match1:
7849 /* Build new domains */
7850 for (i = 0; i < ndoms_new; i++) {
7851 for (j = 0; j < ndoms_cur; j++) {
7852 if (cpus_equal(doms_new[i], doms_cur[j])
7853 && dattrs_equal(dattr_new, i, dattr_cur, j))
7854 goto match2;
7856 /* no match - add a new doms_new */
7857 __build_sched_domains(doms_new + i,
7858 dattr_new ? dattr_new + i : NULL);
7859 match2:
7863 /* Remember the new sched domains */
7864 if (doms_cur != &fallback_doms)
7865 kfree(doms_cur);
7866 kfree(dattr_cur); /* kfree(NULL) is safe */
7867 doms_cur = doms_new;
7868 dattr_cur = dattr_new;
7869 ndoms_cur = ndoms_new;
7871 register_sched_domain_sysctl();
7873 mutex_unlock(&sched_domains_mutex);
7876 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7877 int arch_reinit_sched_domains(void)
7879 int err;
7881 get_online_cpus();
7882 mutex_lock(&sched_domains_mutex);
7883 detach_destroy_domains(&cpu_online_map);
7884 err = arch_init_sched_domains(&cpu_online_map);
7885 mutex_unlock(&sched_domains_mutex);
7886 put_online_cpus();
7888 return err;
7891 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7893 int ret;
7895 if (buf[0] != '0' && buf[0] != '1')
7896 return -EINVAL;
7898 if (smt)
7899 sched_smt_power_savings = (buf[0] == '1');
7900 else
7901 sched_mc_power_savings = (buf[0] == '1');
7903 ret = arch_reinit_sched_domains();
7905 return ret ? ret : count;
7908 #ifdef CONFIG_SCHED_MC
7909 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7911 return sprintf(page, "%u\n", sched_mc_power_savings);
7913 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7914 const char *buf, size_t count)
7916 return sched_power_savings_store(buf, count, 0);
7918 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7919 sched_mc_power_savings_store);
7920 #endif
7922 #ifdef CONFIG_SCHED_SMT
7923 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7925 return sprintf(page, "%u\n", sched_smt_power_savings);
7927 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7928 const char *buf, size_t count)
7930 return sched_power_savings_store(buf, count, 1);
7932 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7933 sched_smt_power_savings_store);
7934 #endif
7936 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7938 int err = 0;
7940 #ifdef CONFIG_SCHED_SMT
7941 if (smt_capable())
7942 err = sysfs_create_file(&cls->kset.kobj,
7943 &attr_sched_smt_power_savings.attr);
7944 #endif
7945 #ifdef CONFIG_SCHED_MC
7946 if (!err && mc_capable())
7947 err = sysfs_create_file(&cls->kset.kobj,
7948 &attr_sched_mc_power_savings.attr);
7949 #endif
7950 return err;
7952 #endif
7955 * Force a reinitialization of the sched domains hierarchy. The domains
7956 * and groups cannot be updated in place without racing with the balancing
7957 * code, so we temporarily attach all running cpus to the NULL domain
7958 * which will prevent rebalancing while the sched domains are recalculated.
7960 static int update_sched_domains(struct notifier_block *nfb,
7961 unsigned long action, void *hcpu)
7963 switch (action) {
7964 case CPU_UP_PREPARE:
7965 case CPU_UP_PREPARE_FROZEN:
7966 case CPU_DOWN_PREPARE:
7967 case CPU_DOWN_PREPARE_FROZEN:
7968 detach_destroy_domains(&cpu_online_map);
7969 return NOTIFY_OK;
7971 case CPU_UP_CANCELED:
7972 case CPU_UP_CANCELED_FROZEN:
7973 case CPU_DOWN_FAILED:
7974 case CPU_DOWN_FAILED_FROZEN:
7975 case CPU_ONLINE:
7976 case CPU_ONLINE_FROZEN:
7977 case CPU_DEAD:
7978 case CPU_DEAD_FROZEN:
7980 * Fall through and re-initialise the domains.
7982 break;
7983 default:
7984 return NOTIFY_DONE;
7987 /* The hotplug lock is already held by cpu_up/cpu_down */
7988 arch_init_sched_domains(&cpu_online_map);
7990 return NOTIFY_OK;
7993 void __init sched_init_smp(void)
7995 cpumask_t non_isolated_cpus;
7997 #if defined(CONFIG_NUMA)
7998 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7999 GFP_KERNEL);
8000 BUG_ON(sched_group_nodes_bycpu == NULL);
8001 #endif
8002 get_online_cpus();
8003 mutex_lock(&sched_domains_mutex);
8004 arch_init_sched_domains(&cpu_online_map);
8005 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
8006 if (cpus_empty(non_isolated_cpus))
8007 cpu_set(smp_processor_id(), non_isolated_cpus);
8008 mutex_unlock(&sched_domains_mutex);
8009 put_online_cpus();
8010 /* XXX: Theoretical race here - CPU may be hotplugged now */
8011 hotcpu_notifier(update_sched_domains, 0);
8012 init_hrtick();
8014 /* Move init over to a non-isolated CPU */
8015 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
8016 BUG();
8017 sched_init_granularity();
8019 #else
8020 void __init sched_init_smp(void)
8022 sched_init_granularity();
8024 #endif /* CONFIG_SMP */
8026 int in_sched_functions(unsigned long addr)
8028 return in_lock_functions(addr) ||
8029 (addr >= (unsigned long)__sched_text_start
8030 && addr < (unsigned long)__sched_text_end);
8033 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8035 cfs_rq->tasks_timeline = RB_ROOT;
8036 INIT_LIST_HEAD(&cfs_rq->tasks);
8037 #ifdef CONFIG_FAIR_GROUP_SCHED
8038 cfs_rq->rq = rq;
8039 #endif
8040 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8043 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8045 struct rt_prio_array *array;
8046 int i;
8048 array = &rt_rq->active;
8049 for (i = 0; i < MAX_RT_PRIO; i++) {
8050 INIT_LIST_HEAD(array->queue + i);
8051 __clear_bit(i, array->bitmap);
8053 /* delimiter for bitsearch: */
8054 __set_bit(MAX_RT_PRIO, array->bitmap);
8056 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8057 rt_rq->highest_prio = MAX_RT_PRIO;
8058 #endif
8059 #ifdef CONFIG_SMP
8060 rt_rq->rt_nr_migratory = 0;
8061 rt_rq->overloaded = 0;
8062 #endif
8064 rt_rq->rt_time = 0;
8065 rt_rq->rt_throttled = 0;
8066 rt_rq->rt_runtime = 0;
8067 spin_lock_init(&rt_rq->rt_runtime_lock);
8069 #ifdef CONFIG_RT_GROUP_SCHED
8070 rt_rq->rt_nr_boosted = 0;
8071 rt_rq->rq = rq;
8072 #endif
8075 #ifdef CONFIG_FAIR_GROUP_SCHED
8076 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8077 struct sched_entity *se, int cpu, int add,
8078 struct sched_entity *parent)
8080 struct rq *rq = cpu_rq(cpu);
8081 tg->cfs_rq[cpu] = cfs_rq;
8082 init_cfs_rq(cfs_rq, rq);
8083 cfs_rq->tg = tg;
8084 if (add)
8085 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8087 tg->se[cpu] = se;
8088 /* se could be NULL for init_task_group */
8089 if (!se)
8090 return;
8092 if (!parent)
8093 se->cfs_rq = &rq->cfs;
8094 else
8095 se->cfs_rq = parent->my_q;
8097 se->my_q = cfs_rq;
8098 se->load.weight = tg->shares;
8099 se->load.inv_weight = 0;
8100 se->parent = parent;
8102 #endif
8104 #ifdef CONFIG_RT_GROUP_SCHED
8105 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8106 struct sched_rt_entity *rt_se, int cpu, int add,
8107 struct sched_rt_entity *parent)
8109 struct rq *rq = cpu_rq(cpu);
8111 tg->rt_rq[cpu] = rt_rq;
8112 init_rt_rq(rt_rq, rq);
8113 rt_rq->tg = tg;
8114 rt_rq->rt_se = rt_se;
8115 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8116 if (add)
8117 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8119 tg->rt_se[cpu] = rt_se;
8120 if (!rt_se)
8121 return;
8123 if (!parent)
8124 rt_se->rt_rq = &rq->rt;
8125 else
8126 rt_se->rt_rq = parent->my_q;
8128 rt_se->rt_rq = &rq->rt;
8129 rt_se->my_q = rt_rq;
8130 rt_se->parent = parent;
8131 INIT_LIST_HEAD(&rt_se->run_list);
8133 #endif
8135 void __init sched_init(void)
8137 int i, j;
8138 unsigned long alloc_size = 0, ptr;
8140 #ifdef CONFIG_FAIR_GROUP_SCHED
8141 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8142 #endif
8143 #ifdef CONFIG_RT_GROUP_SCHED
8144 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8145 #endif
8146 #ifdef CONFIG_USER_SCHED
8147 alloc_size *= 2;
8148 #endif
8150 * As sched_init() is called before page_alloc is setup,
8151 * we use alloc_bootmem().
8153 if (alloc_size) {
8154 ptr = (unsigned long)alloc_bootmem(alloc_size);
8156 #ifdef CONFIG_FAIR_GROUP_SCHED
8157 init_task_group.se = (struct sched_entity **)ptr;
8158 ptr += nr_cpu_ids * sizeof(void **);
8160 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8161 ptr += nr_cpu_ids * sizeof(void **);
8163 #ifdef CONFIG_USER_SCHED
8164 root_task_group.se = (struct sched_entity **)ptr;
8165 ptr += nr_cpu_ids * sizeof(void **);
8167 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8168 ptr += nr_cpu_ids * sizeof(void **);
8169 #endif
8170 #endif
8171 #ifdef CONFIG_RT_GROUP_SCHED
8172 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8173 ptr += nr_cpu_ids * sizeof(void **);
8175 init_task_group.rt_rq = (struct rt_rq **)ptr;
8176 ptr += nr_cpu_ids * sizeof(void **);
8178 #ifdef CONFIG_USER_SCHED
8179 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8180 ptr += nr_cpu_ids * sizeof(void **);
8182 root_task_group.rt_rq = (struct rt_rq **)ptr;
8183 ptr += nr_cpu_ids * sizeof(void **);
8184 #endif
8185 #endif
8188 #ifdef CONFIG_SMP
8189 init_aggregate();
8190 init_defrootdomain();
8191 #endif
8193 init_rt_bandwidth(&def_rt_bandwidth,
8194 global_rt_period(), global_rt_runtime());
8196 #ifdef CONFIG_RT_GROUP_SCHED
8197 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8198 global_rt_period(), global_rt_runtime());
8199 #ifdef CONFIG_USER_SCHED
8200 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8201 global_rt_period(), RUNTIME_INF);
8202 #endif
8203 #endif
8205 #ifdef CONFIG_GROUP_SCHED
8206 list_add(&init_task_group.list, &task_groups);
8207 INIT_LIST_HEAD(&init_task_group.children);
8209 #ifdef CONFIG_USER_SCHED
8210 INIT_LIST_HEAD(&root_task_group.children);
8211 init_task_group.parent = &root_task_group;
8212 list_add(&init_task_group.siblings, &root_task_group.children);
8213 #endif
8214 #endif
8216 for_each_possible_cpu(i) {
8217 struct rq *rq;
8219 rq = cpu_rq(i);
8220 spin_lock_init(&rq->lock);
8221 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
8222 rq->nr_running = 0;
8223 rq->clock = 1;
8224 update_last_tick_seen(rq);
8225 init_cfs_rq(&rq->cfs, rq);
8226 init_rt_rq(&rq->rt, rq);
8227 #ifdef CONFIG_FAIR_GROUP_SCHED
8228 init_task_group.shares = init_task_group_load;
8229 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8230 #ifdef CONFIG_CGROUP_SCHED
8232 * How much cpu bandwidth does init_task_group get?
8234 * In case of task-groups formed thr' the cgroup filesystem, it
8235 * gets 100% of the cpu resources in the system. This overall
8236 * system cpu resource is divided among the tasks of
8237 * init_task_group and its child task-groups in a fair manner,
8238 * based on each entity's (task or task-group's) weight
8239 * (se->load.weight).
8241 * In other words, if init_task_group has 10 tasks of weight
8242 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8243 * then A0's share of the cpu resource is:
8245 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8247 * We achieve this by letting init_task_group's tasks sit
8248 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8250 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8251 #elif defined CONFIG_USER_SCHED
8252 root_task_group.shares = NICE_0_LOAD;
8253 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8255 * In case of task-groups formed thr' the user id of tasks,
8256 * init_task_group represents tasks belonging to root user.
8257 * Hence it forms a sibling of all subsequent groups formed.
8258 * In this case, init_task_group gets only a fraction of overall
8259 * system cpu resource, based on the weight assigned to root
8260 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8261 * by letting tasks of init_task_group sit in a separate cfs_rq
8262 * (init_cfs_rq) and having one entity represent this group of
8263 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8265 init_tg_cfs_entry(&init_task_group,
8266 &per_cpu(init_cfs_rq, i),
8267 &per_cpu(init_sched_entity, i), i, 1,
8268 root_task_group.se[i]);
8270 #endif
8271 #endif /* CONFIG_FAIR_GROUP_SCHED */
8273 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8274 #ifdef CONFIG_RT_GROUP_SCHED
8275 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8276 #ifdef CONFIG_CGROUP_SCHED
8277 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8278 #elif defined CONFIG_USER_SCHED
8279 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8280 init_tg_rt_entry(&init_task_group,
8281 &per_cpu(init_rt_rq, i),
8282 &per_cpu(init_sched_rt_entity, i), i, 1,
8283 root_task_group.rt_se[i]);
8284 #endif
8285 #endif
8287 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8288 rq->cpu_load[j] = 0;
8289 #ifdef CONFIG_SMP
8290 rq->sd = NULL;
8291 rq->rd = NULL;
8292 rq->active_balance = 0;
8293 rq->next_balance = jiffies;
8294 rq->push_cpu = 0;
8295 rq->cpu = i;
8296 rq->migration_thread = NULL;
8297 INIT_LIST_HEAD(&rq->migration_queue);
8298 rq_attach_root(rq, &def_root_domain);
8299 #endif
8300 init_rq_hrtick(rq);
8301 atomic_set(&rq->nr_iowait, 0);
8304 set_load_weight(&init_task);
8306 #ifdef CONFIG_PREEMPT_NOTIFIERS
8307 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8308 #endif
8310 #ifdef CONFIG_SMP
8311 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
8312 #endif
8314 #ifdef CONFIG_RT_MUTEXES
8315 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8316 #endif
8319 * The boot idle thread does lazy MMU switching as well:
8321 atomic_inc(&init_mm.mm_count);
8322 enter_lazy_tlb(&init_mm, current);
8325 * Make us the idle thread. Technically, schedule() should not be
8326 * called from this thread, however somewhere below it might be,
8327 * but because we are the idle thread, we just pick up running again
8328 * when this runqueue becomes "idle".
8330 init_idle(current, smp_processor_id());
8332 * During early bootup we pretend to be a normal task:
8334 current->sched_class = &fair_sched_class;
8336 scheduler_running = 1;
8339 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8340 void __might_sleep(char *file, int line)
8342 #ifdef in_atomic
8343 static unsigned long prev_jiffy; /* ratelimiting */
8345 if ((in_atomic() || irqs_disabled()) &&
8346 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8347 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8348 return;
8349 prev_jiffy = jiffies;
8350 printk(KERN_ERR "BUG: sleeping function called from invalid"
8351 " context at %s:%d\n", file, line);
8352 printk("in_atomic():%d, irqs_disabled():%d\n",
8353 in_atomic(), irqs_disabled());
8354 debug_show_held_locks(current);
8355 if (irqs_disabled())
8356 print_irqtrace_events(current);
8357 dump_stack();
8359 #endif
8361 EXPORT_SYMBOL(__might_sleep);
8362 #endif
8364 #ifdef CONFIG_MAGIC_SYSRQ
8365 static void normalize_task(struct rq *rq, struct task_struct *p)
8367 int on_rq;
8368 update_rq_clock(rq);
8369 on_rq = p->se.on_rq;
8370 if (on_rq)
8371 deactivate_task(rq, p, 0);
8372 __setscheduler(rq, p, SCHED_NORMAL, 0);
8373 if (on_rq) {
8374 activate_task(rq, p, 0);
8375 resched_task(rq->curr);
8379 void normalize_rt_tasks(void)
8381 struct task_struct *g, *p;
8382 unsigned long flags;
8383 struct rq *rq;
8385 read_lock_irqsave(&tasklist_lock, flags);
8386 do_each_thread(g, p) {
8388 * Only normalize user tasks:
8390 if (!p->mm)
8391 continue;
8393 p->se.exec_start = 0;
8394 #ifdef CONFIG_SCHEDSTATS
8395 p->se.wait_start = 0;
8396 p->se.sleep_start = 0;
8397 p->se.block_start = 0;
8398 #endif
8399 task_rq(p)->clock = 0;
8401 if (!rt_task(p)) {
8403 * Renice negative nice level userspace
8404 * tasks back to 0:
8406 if (TASK_NICE(p) < 0 && p->mm)
8407 set_user_nice(p, 0);
8408 continue;
8411 spin_lock(&p->pi_lock);
8412 rq = __task_rq_lock(p);
8414 normalize_task(rq, p);
8416 __task_rq_unlock(rq);
8417 spin_unlock(&p->pi_lock);
8418 } while_each_thread(g, p);
8420 read_unlock_irqrestore(&tasklist_lock, flags);
8423 #endif /* CONFIG_MAGIC_SYSRQ */
8425 #ifdef CONFIG_IA64
8427 * These functions are only useful for the IA64 MCA handling.
8429 * They can only be called when the whole system has been
8430 * stopped - every CPU needs to be quiescent, and no scheduling
8431 * activity can take place. Using them for anything else would
8432 * be a serious bug, and as a result, they aren't even visible
8433 * under any other configuration.
8437 * curr_task - return the current task for a given cpu.
8438 * @cpu: the processor in question.
8440 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8442 struct task_struct *curr_task(int cpu)
8444 return cpu_curr(cpu);
8448 * set_curr_task - set the current task for a given cpu.
8449 * @cpu: the processor in question.
8450 * @p: the task pointer to set.
8452 * Description: This function must only be used when non-maskable interrupts
8453 * are serviced on a separate stack. It allows the architecture to switch the
8454 * notion of the current task on a cpu in a non-blocking manner. This function
8455 * must be called with all CPU's synchronized, and interrupts disabled, the
8456 * and caller must save the original value of the current task (see
8457 * curr_task() above) and restore that value before reenabling interrupts and
8458 * re-starting the system.
8460 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8462 void set_curr_task(int cpu, struct task_struct *p)
8464 cpu_curr(cpu) = p;
8467 #endif
8469 #ifdef CONFIG_FAIR_GROUP_SCHED
8470 static void free_fair_sched_group(struct task_group *tg)
8472 int i;
8474 for_each_possible_cpu(i) {
8475 if (tg->cfs_rq)
8476 kfree(tg->cfs_rq[i]);
8477 if (tg->se)
8478 kfree(tg->se[i]);
8481 kfree(tg->cfs_rq);
8482 kfree(tg->se);
8485 static
8486 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8488 struct cfs_rq *cfs_rq;
8489 struct sched_entity *se, *parent_se;
8490 struct rq *rq;
8491 int i;
8493 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8494 if (!tg->cfs_rq)
8495 goto err;
8496 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8497 if (!tg->se)
8498 goto err;
8500 tg->shares = NICE_0_LOAD;
8502 for_each_possible_cpu(i) {
8503 rq = cpu_rq(i);
8505 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8506 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8507 if (!cfs_rq)
8508 goto err;
8510 se = kmalloc_node(sizeof(struct sched_entity),
8511 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8512 if (!se)
8513 goto err;
8515 parent_se = parent ? parent->se[i] : NULL;
8516 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8519 return 1;
8521 err:
8522 return 0;
8525 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8527 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8528 &cpu_rq(cpu)->leaf_cfs_rq_list);
8531 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8533 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8535 #else
8536 static inline void free_fair_sched_group(struct task_group *tg)
8540 static inline
8541 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8543 return 1;
8546 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8550 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8553 #endif
8555 #ifdef CONFIG_RT_GROUP_SCHED
8556 static void free_rt_sched_group(struct task_group *tg)
8558 int i;
8560 destroy_rt_bandwidth(&tg->rt_bandwidth);
8562 for_each_possible_cpu(i) {
8563 if (tg->rt_rq)
8564 kfree(tg->rt_rq[i]);
8565 if (tg->rt_se)
8566 kfree(tg->rt_se[i]);
8569 kfree(tg->rt_rq);
8570 kfree(tg->rt_se);
8573 static
8574 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8576 struct rt_rq *rt_rq;
8577 struct sched_rt_entity *rt_se, *parent_se;
8578 struct rq *rq;
8579 int i;
8581 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8582 if (!tg->rt_rq)
8583 goto err;
8584 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8585 if (!tg->rt_se)
8586 goto err;
8588 init_rt_bandwidth(&tg->rt_bandwidth,
8589 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8591 for_each_possible_cpu(i) {
8592 rq = cpu_rq(i);
8594 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8595 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8596 if (!rt_rq)
8597 goto err;
8599 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8600 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8601 if (!rt_se)
8602 goto err;
8604 parent_se = parent ? parent->rt_se[i] : NULL;
8605 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8608 return 1;
8610 err:
8611 return 0;
8614 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8616 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8617 &cpu_rq(cpu)->leaf_rt_rq_list);
8620 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8622 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8624 #else
8625 static inline void free_rt_sched_group(struct task_group *tg)
8629 static inline
8630 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8632 return 1;
8635 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8639 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8642 #endif
8644 #ifdef CONFIG_GROUP_SCHED
8645 static void free_sched_group(struct task_group *tg)
8647 free_fair_sched_group(tg);
8648 free_rt_sched_group(tg);
8649 kfree(tg);
8652 /* allocate runqueue etc for a new task group */
8653 struct task_group *sched_create_group(struct task_group *parent)
8655 struct task_group *tg;
8656 unsigned long flags;
8657 int i;
8659 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8660 if (!tg)
8661 return ERR_PTR(-ENOMEM);
8663 if (!alloc_fair_sched_group(tg, parent))
8664 goto err;
8666 if (!alloc_rt_sched_group(tg, parent))
8667 goto err;
8669 spin_lock_irqsave(&task_group_lock, flags);
8670 for_each_possible_cpu(i) {
8671 register_fair_sched_group(tg, i);
8672 register_rt_sched_group(tg, i);
8674 list_add_rcu(&tg->list, &task_groups);
8676 WARN_ON(!parent); /* root should already exist */
8678 tg->parent = parent;
8679 list_add_rcu(&tg->siblings, &parent->children);
8680 INIT_LIST_HEAD(&tg->children);
8681 spin_unlock_irqrestore(&task_group_lock, flags);
8683 return tg;
8685 err:
8686 free_sched_group(tg);
8687 return ERR_PTR(-ENOMEM);
8690 /* rcu callback to free various structures associated with a task group */
8691 static void free_sched_group_rcu(struct rcu_head *rhp)
8693 /* now it should be safe to free those cfs_rqs */
8694 free_sched_group(container_of(rhp, struct task_group, rcu));
8697 /* Destroy runqueue etc associated with a task group */
8698 void sched_destroy_group(struct task_group *tg)
8700 unsigned long flags;
8701 int i;
8703 spin_lock_irqsave(&task_group_lock, flags);
8704 for_each_possible_cpu(i) {
8705 unregister_fair_sched_group(tg, i);
8706 unregister_rt_sched_group(tg, i);
8708 list_del_rcu(&tg->list);
8709 list_del_rcu(&tg->siblings);
8710 spin_unlock_irqrestore(&task_group_lock, flags);
8712 /* wait for possible concurrent references to cfs_rqs complete */
8713 call_rcu(&tg->rcu, free_sched_group_rcu);
8716 /* change task's runqueue when it moves between groups.
8717 * The caller of this function should have put the task in its new group
8718 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8719 * reflect its new group.
8721 void sched_move_task(struct task_struct *tsk)
8723 int on_rq, running;
8724 unsigned long flags;
8725 struct rq *rq;
8727 rq = task_rq_lock(tsk, &flags);
8729 update_rq_clock(rq);
8731 running = task_current(rq, tsk);
8732 on_rq = tsk->se.on_rq;
8734 if (on_rq)
8735 dequeue_task(rq, tsk, 0);
8736 if (unlikely(running))
8737 tsk->sched_class->put_prev_task(rq, tsk);
8739 set_task_rq(tsk, task_cpu(tsk));
8741 #ifdef CONFIG_FAIR_GROUP_SCHED
8742 if (tsk->sched_class->moved_group)
8743 tsk->sched_class->moved_group(tsk);
8744 #endif
8746 if (unlikely(running))
8747 tsk->sched_class->set_curr_task(rq);
8748 if (on_rq)
8749 enqueue_task(rq, tsk, 0);
8751 task_rq_unlock(rq, &flags);
8753 #endif
8755 #ifdef CONFIG_FAIR_GROUP_SCHED
8756 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8758 struct cfs_rq *cfs_rq = se->cfs_rq;
8759 int on_rq;
8761 on_rq = se->on_rq;
8762 if (on_rq)
8763 dequeue_entity(cfs_rq, se, 0);
8765 se->load.weight = shares;
8766 se->load.inv_weight = 0;
8768 if (on_rq)
8769 enqueue_entity(cfs_rq, se, 0);
8772 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8774 struct cfs_rq *cfs_rq = se->cfs_rq;
8775 struct rq *rq = cfs_rq->rq;
8776 unsigned long flags;
8778 spin_lock_irqsave(&rq->lock, flags);
8779 __set_se_shares(se, shares);
8780 spin_unlock_irqrestore(&rq->lock, flags);
8783 static DEFINE_MUTEX(shares_mutex);
8785 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8787 int i;
8788 unsigned long flags;
8791 * We can't change the weight of the root cgroup.
8793 if (!tg->se[0])
8794 return -EINVAL;
8796 if (shares < MIN_SHARES)
8797 shares = MIN_SHARES;
8798 else if (shares > MAX_SHARES)
8799 shares = MAX_SHARES;
8801 mutex_lock(&shares_mutex);
8802 if (tg->shares == shares)
8803 goto done;
8805 spin_lock_irqsave(&task_group_lock, flags);
8806 for_each_possible_cpu(i)
8807 unregister_fair_sched_group(tg, i);
8808 list_del_rcu(&tg->siblings);
8809 spin_unlock_irqrestore(&task_group_lock, flags);
8811 /* wait for any ongoing reference to this group to finish */
8812 synchronize_sched();
8815 * Now we are free to modify the group's share on each cpu
8816 * w/o tripping rebalance_share or load_balance_fair.
8818 tg->shares = shares;
8819 for_each_possible_cpu(i) {
8821 * force a rebalance
8823 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8824 set_se_shares(tg->se[i], shares);
8828 * Enable load balance activity on this group, by inserting it back on
8829 * each cpu's rq->leaf_cfs_rq_list.
8831 spin_lock_irqsave(&task_group_lock, flags);
8832 for_each_possible_cpu(i)
8833 register_fair_sched_group(tg, i);
8834 list_add_rcu(&tg->siblings, &tg->parent->children);
8835 spin_unlock_irqrestore(&task_group_lock, flags);
8836 done:
8837 mutex_unlock(&shares_mutex);
8838 return 0;
8841 unsigned long sched_group_shares(struct task_group *tg)
8843 return tg->shares;
8845 #endif
8847 #ifdef CONFIG_RT_GROUP_SCHED
8849 * Ensure that the real time constraints are schedulable.
8851 static DEFINE_MUTEX(rt_constraints_mutex);
8853 static unsigned long to_ratio(u64 period, u64 runtime)
8855 if (runtime == RUNTIME_INF)
8856 return 1ULL << 16;
8858 return div64_u64(runtime << 16, period);
8861 #ifdef CONFIG_CGROUP_SCHED
8862 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8864 struct task_group *tgi, *parent = tg->parent;
8865 unsigned long total = 0;
8867 if (!parent) {
8868 if (global_rt_period() < period)
8869 return 0;
8871 return to_ratio(period, runtime) <
8872 to_ratio(global_rt_period(), global_rt_runtime());
8875 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8876 return 0;
8878 rcu_read_lock();
8879 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8880 if (tgi == tg)
8881 continue;
8883 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8884 tgi->rt_bandwidth.rt_runtime);
8886 rcu_read_unlock();
8888 return total + to_ratio(period, runtime) <
8889 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8890 parent->rt_bandwidth.rt_runtime);
8892 #elif defined CONFIG_USER_SCHED
8893 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8895 struct task_group *tgi;
8896 unsigned long total = 0;
8897 unsigned long global_ratio =
8898 to_ratio(global_rt_period(), global_rt_runtime());
8900 rcu_read_lock();
8901 list_for_each_entry_rcu(tgi, &task_groups, list) {
8902 if (tgi == tg)
8903 continue;
8905 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8906 tgi->rt_bandwidth.rt_runtime);
8908 rcu_read_unlock();
8910 return total + to_ratio(period, runtime) < global_ratio;
8912 #endif
8914 /* Must be called with tasklist_lock held */
8915 static inline int tg_has_rt_tasks(struct task_group *tg)
8917 struct task_struct *g, *p;
8918 do_each_thread(g, p) {
8919 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8920 return 1;
8921 } while_each_thread(g, p);
8922 return 0;
8925 static int tg_set_bandwidth(struct task_group *tg,
8926 u64 rt_period, u64 rt_runtime)
8928 int i, err = 0;
8930 mutex_lock(&rt_constraints_mutex);
8931 read_lock(&tasklist_lock);
8932 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8933 err = -EBUSY;
8934 goto unlock;
8936 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8937 err = -EINVAL;
8938 goto unlock;
8941 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8942 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8943 tg->rt_bandwidth.rt_runtime = rt_runtime;
8945 for_each_possible_cpu(i) {
8946 struct rt_rq *rt_rq = tg->rt_rq[i];
8948 spin_lock(&rt_rq->rt_runtime_lock);
8949 rt_rq->rt_runtime = rt_runtime;
8950 spin_unlock(&rt_rq->rt_runtime_lock);
8952 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8953 unlock:
8954 read_unlock(&tasklist_lock);
8955 mutex_unlock(&rt_constraints_mutex);
8957 return err;
8960 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8962 u64 rt_runtime, rt_period;
8964 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8965 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8966 if (rt_runtime_us < 0)
8967 rt_runtime = RUNTIME_INF;
8969 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8972 long sched_group_rt_runtime(struct task_group *tg)
8974 u64 rt_runtime_us;
8976 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8977 return -1;
8979 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8980 do_div(rt_runtime_us, NSEC_PER_USEC);
8981 return rt_runtime_us;
8984 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8986 u64 rt_runtime, rt_period;
8988 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8989 rt_runtime = tg->rt_bandwidth.rt_runtime;
8991 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8994 long sched_group_rt_period(struct task_group *tg)
8996 u64 rt_period_us;
8998 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8999 do_div(rt_period_us, NSEC_PER_USEC);
9000 return rt_period_us;
9003 static int sched_rt_global_constraints(void)
9005 int ret = 0;
9007 mutex_lock(&rt_constraints_mutex);
9008 if (!__rt_schedulable(NULL, 1, 0))
9009 ret = -EINVAL;
9010 mutex_unlock(&rt_constraints_mutex);
9012 return ret;
9014 #else
9015 static int sched_rt_global_constraints(void)
9017 unsigned long flags;
9018 int i;
9020 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9021 for_each_possible_cpu(i) {
9022 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9024 spin_lock(&rt_rq->rt_runtime_lock);
9025 rt_rq->rt_runtime = global_rt_runtime();
9026 spin_unlock(&rt_rq->rt_runtime_lock);
9028 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9030 return 0;
9032 #endif
9034 int sched_rt_handler(struct ctl_table *table, int write,
9035 struct file *filp, void __user *buffer, size_t *lenp,
9036 loff_t *ppos)
9038 int ret;
9039 int old_period, old_runtime;
9040 static DEFINE_MUTEX(mutex);
9042 mutex_lock(&mutex);
9043 old_period = sysctl_sched_rt_period;
9044 old_runtime = sysctl_sched_rt_runtime;
9046 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9048 if (!ret && write) {
9049 ret = sched_rt_global_constraints();
9050 if (ret) {
9051 sysctl_sched_rt_period = old_period;
9052 sysctl_sched_rt_runtime = old_runtime;
9053 } else {
9054 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9055 def_rt_bandwidth.rt_period =
9056 ns_to_ktime(global_rt_period());
9059 mutex_unlock(&mutex);
9061 return ret;
9064 #ifdef CONFIG_CGROUP_SCHED
9066 /* return corresponding task_group object of a cgroup */
9067 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9069 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9070 struct task_group, css);
9073 static struct cgroup_subsys_state *
9074 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9076 struct task_group *tg, *parent;
9078 if (!cgrp->parent) {
9079 /* This is early initialization for the top cgroup */
9080 init_task_group.css.cgroup = cgrp;
9081 return &init_task_group.css;
9084 parent = cgroup_tg(cgrp->parent);
9085 tg = sched_create_group(parent);
9086 if (IS_ERR(tg))
9087 return ERR_PTR(-ENOMEM);
9089 /* Bind the cgroup to task_group object we just created */
9090 tg->css.cgroup = cgrp;
9092 return &tg->css;
9095 static void
9096 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9098 struct task_group *tg = cgroup_tg(cgrp);
9100 sched_destroy_group(tg);
9103 static int
9104 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9105 struct task_struct *tsk)
9107 #ifdef CONFIG_RT_GROUP_SCHED
9108 /* Don't accept realtime tasks when there is no way for them to run */
9109 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9110 return -EINVAL;
9111 #else
9112 /* We don't support RT-tasks being in separate groups */
9113 if (tsk->sched_class != &fair_sched_class)
9114 return -EINVAL;
9115 #endif
9117 return 0;
9120 static void
9121 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9122 struct cgroup *old_cont, struct task_struct *tsk)
9124 sched_move_task(tsk);
9127 #ifdef CONFIG_FAIR_GROUP_SCHED
9128 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9129 u64 shareval)
9131 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9134 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9136 struct task_group *tg = cgroup_tg(cgrp);
9138 return (u64) tg->shares;
9140 #endif
9142 #ifdef CONFIG_RT_GROUP_SCHED
9143 static ssize_t cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9144 s64 val)
9146 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9149 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9151 return sched_group_rt_runtime(cgroup_tg(cgrp));
9154 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9155 u64 rt_period_us)
9157 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9160 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9162 return sched_group_rt_period(cgroup_tg(cgrp));
9164 #endif
9166 static struct cftype cpu_files[] = {
9167 #ifdef CONFIG_FAIR_GROUP_SCHED
9169 .name = "shares",
9170 .read_u64 = cpu_shares_read_u64,
9171 .write_u64 = cpu_shares_write_u64,
9173 #endif
9174 #ifdef CONFIG_RT_GROUP_SCHED
9176 .name = "rt_runtime_us",
9177 .read_s64 = cpu_rt_runtime_read,
9178 .write_s64 = cpu_rt_runtime_write,
9181 .name = "rt_period_us",
9182 .read_u64 = cpu_rt_period_read_uint,
9183 .write_u64 = cpu_rt_period_write_uint,
9185 #endif
9188 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9190 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9193 struct cgroup_subsys cpu_cgroup_subsys = {
9194 .name = "cpu",
9195 .create = cpu_cgroup_create,
9196 .destroy = cpu_cgroup_destroy,
9197 .can_attach = cpu_cgroup_can_attach,
9198 .attach = cpu_cgroup_attach,
9199 .populate = cpu_cgroup_populate,
9200 .subsys_id = cpu_cgroup_subsys_id,
9201 .early_init = 1,
9204 #endif /* CONFIG_CGROUP_SCHED */
9206 #ifdef CONFIG_CGROUP_CPUACCT
9209 * CPU accounting code for task groups.
9211 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9212 * (balbir@in.ibm.com).
9215 /* track cpu usage of a group of tasks */
9216 struct cpuacct {
9217 struct cgroup_subsys_state css;
9218 /* cpuusage holds pointer to a u64-type object on every cpu */
9219 u64 *cpuusage;
9222 struct cgroup_subsys cpuacct_subsys;
9224 /* return cpu accounting group corresponding to this container */
9225 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9227 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9228 struct cpuacct, css);
9231 /* return cpu accounting group to which this task belongs */
9232 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9234 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9235 struct cpuacct, css);
9238 /* create a new cpu accounting group */
9239 static struct cgroup_subsys_state *cpuacct_create(
9240 struct cgroup_subsys *ss, struct cgroup *cgrp)
9242 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9244 if (!ca)
9245 return ERR_PTR(-ENOMEM);
9247 ca->cpuusage = alloc_percpu(u64);
9248 if (!ca->cpuusage) {
9249 kfree(ca);
9250 return ERR_PTR(-ENOMEM);
9253 return &ca->css;
9256 /* destroy an existing cpu accounting group */
9257 static void
9258 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9260 struct cpuacct *ca = cgroup_ca(cgrp);
9262 free_percpu(ca->cpuusage);
9263 kfree(ca);
9266 /* return total cpu usage (in nanoseconds) of a group */
9267 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9269 struct cpuacct *ca = cgroup_ca(cgrp);
9270 u64 totalcpuusage = 0;
9271 int i;
9273 for_each_possible_cpu(i) {
9274 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9277 * Take rq->lock to make 64-bit addition safe on 32-bit
9278 * platforms.
9280 spin_lock_irq(&cpu_rq(i)->lock);
9281 totalcpuusage += *cpuusage;
9282 spin_unlock_irq(&cpu_rq(i)->lock);
9285 return totalcpuusage;
9288 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9289 u64 reset)
9291 struct cpuacct *ca = cgroup_ca(cgrp);
9292 int err = 0;
9293 int i;
9295 if (reset) {
9296 err = -EINVAL;
9297 goto out;
9300 for_each_possible_cpu(i) {
9301 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9303 spin_lock_irq(&cpu_rq(i)->lock);
9304 *cpuusage = 0;
9305 spin_unlock_irq(&cpu_rq(i)->lock);
9307 out:
9308 return err;
9311 static struct cftype files[] = {
9313 .name = "usage",
9314 .read_u64 = cpuusage_read,
9315 .write_u64 = cpuusage_write,
9319 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9321 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9325 * charge this task's execution time to its accounting group.
9327 * called with rq->lock held.
9329 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9331 struct cpuacct *ca;
9333 if (!cpuacct_subsys.active)
9334 return;
9336 ca = task_ca(tsk);
9337 if (ca) {
9338 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9340 *cpuusage += cputime;
9344 struct cgroup_subsys cpuacct_subsys = {
9345 .name = "cpuacct",
9346 .create = cpuacct_create,
9347 .destroy = cpuacct_destroy,
9348 .populate = cpuacct_populate,
9349 .subsys_id = cpuacct_subsys_id,
9351 #endif /* CONFIG_CGROUP_CPUACCT */