Now it works.
[cbs-scheduler.git] / kernel / sched.c
blob05c3501e5ab65dfaf50aadb5d76a6ad2da5d46d4
1 /*
2 * kernel/sched.c
4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
7 * Copyright (C) 2004 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
9 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
10 * make semaphores SMP safe
11 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * by Andrea Arcangeli
13 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
14 * hybrid priority-list and round-robin design with
15 * an array-switch method of distributing timeslices
16 * and per-CPU runqueues. Cleanups and useful suggestions
17 * by Davide Libenzi, preemptible kernel bits by Robert Love.
18 * 2003-09-03 Interactivity tuning by Con Kolivas.
19 * 2004-04-02 Scheduler domains code by Nick Piggin
20 * 2004-10-13 Real-Time Preemption support by Ingo Molnar
21 * 2007-04-15 Work begun on replacing all interactivity tuning with a
22 * fair scheduling design by Con Kolivas.
23 * 2007-05-05 Load balancing (smp-nice) and other improvements
24 * by Peter Williams
25 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
26 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
27 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
28 * Thomas Gleixner, Mike Kravetz
31 #include <linux/mm.h>
32 #include <linux/module.h>
33 #include <linux/nmi.h>
34 #include <linux/init.h>
35 #include <linux/uaccess.h>
36 #include <linux/highmem.h>
37 #include <linux/smp_lock.h>
38 #include <asm/mmu_context.h>
39 #include <linux/interrupt.h>
40 #include <linux/capability.h>
41 #include <linux/completion.h>
42 #include <linux/kernel_stat.h>
43 #include <linux/debug_locks.h>
44 #include <linux/security.h>
45 #include <linux/notifier.h>
46 #include <linux/profile.h>
47 #include <linux/freezer.h>
48 #include <linux/vmalloc.h>
49 #include <linux/blkdev.h>
50 #include <linux/delay.h>
51 #include <linux/pid_namespace.h>
52 #include <linux/smp.h>
53 #include <linux/threads.h>
54 #include <linux/timer.h>
55 #include <linux/rcupdate.h>
56 #include <linux/cpu.h>
57 #include <linux/cpuset.h>
58 #include <linux/percpu.h>
59 #include <linux/kthread.h>
60 #include <linux/proc_fs.h>
61 #include <linux/seq_file.h>
62 #include <linux/sysctl.h>
63 #include <linux/syscalls.h>
64 #include <linux/times.h>
65 #include <linux/kallsyms.h>
66 #include <linux/tsacct_kern.h>
67 #include <linux/kprobes.h>
68 #include <linux/delayacct.h>
69 #include <linux/reciprocal_div.h>
70 #include <linux/unistd.h>
71 #include <linux/pagemap.h>
72 #include <linux/hrtimer.h>
73 #include <linux/tick.h>
74 #include <linux/bootmem.h>
75 #include <linux/debugfs.h>
76 #include <linux/ctype.h>
77 #include <linux/ftrace.h>
78 #include <trace/sched.h>
80 #include <asm/tlb.h>
81 #include <asm/irq_regs.h>
83 #include "sched_cpupri.h"
86 * Convert user-nice values [ -20 ... 0 ... 19 ]
87 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
88 * and back.
90 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
91 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
92 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
95 * 'User priority' is the nice value converted to something we
96 * can work with better when scaling various scheduler parameters,
97 * it's a [ 0 ... 39 ] range.
99 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
100 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
101 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
104 * Helpers for converting nanosecond timing to jiffy resolution
106 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
108 #define NICE_0_LOAD SCHED_LOAD_SCALE
109 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
111 #if (BITS_PER_LONG < 64)
112 #define JIFFIES_TO_NS64(TIME) \
113 ((unsigned long long)(TIME) * ((unsigned long) (1000000000 / HZ)))
115 #define NS64_TO_JIFFIES(TIME) \
116 ((((unsigned long long)((TIME)) >> BITS_PER_LONG) * \
117 (1 + NS_TO_JIFFIES(~0UL))) + NS_TO_JIFFIES((unsigned long)(TIME)))
118 #else /* BITS_PER_LONG < 64 */
120 #define NS64_TO_JIFFIES(TIME) NS_TO_JIFFIES(TIME)
121 #define JIFFIES_TO_NS64(TIME) JIFFIES_TO_NS(TIME)
123 #endif /* BITS_PER_LONG < 64 */
126 * These are the 'tuning knobs' of the scheduler:
128 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
129 * Timeslices get refilled after they expire.
131 #define DEF_TIMESLICE (100 * HZ / 1000)
134 * single value that denotes runtime == period, ie unlimited time.
136 #define RUNTIME_INF ((u64)~0ULL)
138 DEFINE_TRACE(sched_wait_task);
139 DEFINE_TRACE(sched_wakeup);
140 DEFINE_TRACE(sched_wakeup_new);
141 DEFINE_TRACE(sched_switch);
142 DEFINE_TRACE(sched_migrate_task);
143 DEFINE_TRACE(sched_task_setprio);
145 #ifdef CONFIG_SMP
147 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
150 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
151 * Since cpu_power is a 'constant', we can use a reciprocal divide.
153 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
155 return reciprocal_divide(load, sg->reciprocal_cpu_power);
159 * Each time a sched group cpu_power is changed,
160 * we must compute its reciprocal value
162 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
164 sg->__cpu_power += val;
165 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
167 #endif
169 #define TASK_PREEMPTS_CURR(p, rq) \
170 ((p)->prio < (rq)->curr->prio)
173 * Tweaks for current
176 #ifdef CURRENT_PTR
177 struct task_struct * const ___current = &init_task;
178 struct task_struct ** const current_ptr = (struct task_struct ** const)&___current;
179 struct thread_info * const current_ti = &init_thread_union.thread_info;
180 struct thread_info ** const current_ti_ptr = (struct thread_info ** const)&current_ti;
182 EXPORT_SYMBOL(___current);
183 EXPORT_SYMBOL(current_ti);
186 * The scheduler itself doesnt want 'current' to be cached
187 * during context-switches:
189 # undef current
190 # define current __current()
191 # undef current_thread_info
192 # define current_thread_info() __current_thread_info()
193 #endif
195 static inline int rt_policy(int policy)
197 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
198 return 1;
199 return 0;
202 static inline int task_has_rt_policy(struct task_struct *p)
204 return rt_policy(p->policy);
208 * This is the priority-queue data structure of the RT scheduling class:
210 struct rt_prio_array {
211 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
212 struct list_head queue[MAX_RT_PRIO];
215 struct rt_bandwidth {
216 /* nests inside the rq lock: */
217 raw_spinlock_t rt_runtime_lock;
218 ktime_t rt_period;
219 u64 rt_runtime;
220 struct hrtimer rt_period_timer;
223 static struct rt_bandwidth def_rt_bandwidth;
225 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
227 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
229 struct rt_bandwidth *rt_b =
230 container_of(timer, struct rt_bandwidth, rt_period_timer);
231 ktime_t now;
232 int overrun;
233 int idle = 0;
235 for (;;) {
236 now = hrtimer_cb_get_time(timer);
237 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
239 if (!overrun)
240 break;
242 idle = do_sched_rt_period_timer(rt_b, overrun);
245 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
248 static
249 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
251 rt_b->rt_period = ns_to_ktime(period);
252 rt_b->rt_runtime = runtime;
254 spin_lock_init(&rt_b->rt_runtime_lock);
256 hrtimer_init(&rt_b->rt_period_timer,
257 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
258 rt_b->rt_period_timer.irqsafe = 1;
259 rt_b->rt_period_timer.function = sched_rt_period_timer;
262 static inline int rt_bandwidth_enabled(void)
264 return sysctl_sched_rt_runtime >= 0;
267 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
269 ktime_t now;
271 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
272 return;
274 if (hrtimer_active(&rt_b->rt_period_timer))
275 return;
277 spin_lock(&rt_b->rt_runtime_lock);
278 for (;;) {
279 unsigned long delta;
280 ktime_t soft, hard;
282 if (hrtimer_active(&rt_b->rt_period_timer))
283 break;
285 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
286 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
288 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
289 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
290 delta = ktime_to_ns(ktime_sub(hard, soft));
291 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
292 HRTIMER_MODE_ABS, 0);
294 spin_unlock(&rt_b->rt_runtime_lock);
297 #ifdef CONFIG_RT_GROUP_SCHED
298 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
300 hrtimer_cancel(&rt_b->rt_period_timer);
302 #endif
305 * sched_domains_mutex serializes calls to arch_init_sched_domains,
306 * detach_destroy_domains and partition_sched_domains.
308 static DEFINE_MUTEX(sched_domains_mutex);
310 #ifdef CONFIG_GROUP_SCHED
312 #include <linux/cgroup.h>
314 struct cfs_rq;
316 static LIST_HEAD(task_groups);
318 /* task group related information */
319 struct task_group {
320 #ifdef CONFIG_CGROUP_SCHED
321 struct cgroup_subsys_state css;
322 #endif
324 #ifdef CONFIG_USER_SCHED
325 uid_t uid;
326 #endif
328 #ifdef CONFIG_FAIR_GROUP_SCHED
329 /* schedulable entities of this group on each cpu */
330 struct sched_entity **se;
331 /* runqueue "owned" by this group on each cpu */
332 struct cfs_rq **cfs_rq;
333 unsigned long shares;
334 #endif
336 #ifdef CONFIG_RT_GROUP_SCHED
337 struct sched_rt_entity **rt_se;
338 struct rt_rq **rt_rq;
340 struct rt_bandwidth rt_bandwidth;
341 #endif
343 struct rcu_head rcu;
344 struct list_head list;
346 struct task_group *parent;
347 struct list_head siblings;
348 struct list_head children;
351 #ifdef CONFIG_USER_SCHED
353 /* Helper function to pass uid information to create_sched_user() */
354 void set_tg_uid(struct user_struct *user)
356 user->tg->uid = user->uid;
360 * Root task group.
361 * Every UID task group (including init_task_group aka UID-0) will
362 * be a child to this group.
364 struct task_group root_task_group;
366 #ifdef CONFIG_FAIR_GROUP_SCHED
367 /* Default task group's sched entity on each cpu */
368 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
369 /* Default task group's cfs_rq on each cpu */
370 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
371 #endif /* CONFIG_FAIR_GROUP_SCHED */
373 #ifdef CONFIG_RT_GROUP_SCHED
374 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
375 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
376 #endif /* CONFIG_RT_GROUP_SCHED */
377 #else /* !CONFIG_USER_SCHED */
378 #define root_task_group init_task_group
379 #endif /* CONFIG_USER_SCHED */
381 /* task_group_lock serializes add/remove of task groups and also changes to
382 * a task group's cpu shares.
384 static DEFINE_SPINLOCK(task_group_lock);
386 #ifdef CONFIG_SMP
387 static int root_task_group_empty(void)
389 return list_empty(&root_task_group.children);
391 #endif
393 #ifdef CONFIG_FAIR_GROUP_SCHED
394 #ifdef CONFIG_USER_SCHED
395 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
396 #else /* !CONFIG_USER_SCHED */
397 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
398 #endif /* CONFIG_USER_SCHED */
401 * A weight of 0 or 1 can cause arithmetics problems.
402 * A weight of a cfs_rq is the sum of weights of which entities
403 * are queued on this cfs_rq, so a weight of a entity should not be
404 * too large, so as the shares value of a task group.
405 * (The default weight is 1024 - so there's no practical
406 * limitation from this.)
408 #define MIN_SHARES 2
409 #define MAX_SHARES (1UL << 18)
411 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
412 #endif
414 /* Default task group.
415 * Every task in system belong to this group at bootup.
417 struct task_group init_task_group;
419 /* return group to which a task belongs */
420 static inline struct task_group *task_group(struct task_struct *p)
422 struct task_group *tg;
424 #ifdef CONFIG_USER_SCHED
425 rcu_read_lock();
426 tg = __task_cred(p)->user->tg;
427 rcu_read_unlock();
428 #elif defined(CONFIG_CGROUP_SCHED)
429 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
430 struct task_group, css);
431 #else
432 tg = &init_task_group;
433 #endif
434 return tg;
437 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
438 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
440 #ifdef CONFIG_FAIR_GROUP_SCHED
441 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
442 p->se.parent = task_group(p)->se[cpu];
443 #endif
445 #ifdef CONFIG_RT_GROUP_SCHED
446 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
447 p->rt.parent = task_group(p)->rt_se[cpu];
448 #endif
451 #else
453 #ifdef CONFIG_SMP
454 static int root_task_group_empty(void)
456 return 1;
458 #endif
460 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
461 static inline struct task_group *task_group(struct task_struct *p)
463 return NULL;
466 #endif /* CONFIG_GROUP_SCHED */
468 /* CFS-related fields in a runqueue */
469 struct cfs_rq {
470 struct load_weight load;
471 unsigned long nr_running;
473 u64 exec_clock;
474 u64 min_vruntime;
476 struct rb_root tasks_timeline;
477 struct rb_node *rb_leftmost;
479 struct list_head tasks;
480 struct list_head *balance_iterator;
483 * 'curr' points to currently running entity on this cfs_rq.
484 * It is set to NULL otherwise (i.e when none are currently running).
486 struct sched_entity *curr, *next, *last;
488 unsigned int nr_spread_over;
490 #ifdef CONFIG_FAIR_GROUP_SCHED
491 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
494 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
495 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
496 * (like users, containers etc.)
498 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
499 * list is used during load balance.
501 struct list_head leaf_cfs_rq_list;
502 struct task_group *tg; /* group that "owns" this runqueue */
504 #ifdef CONFIG_SMP
506 * the part of load.weight contributed by tasks
508 unsigned long task_weight;
511 * h_load = weight * f(tg)
513 * Where f(tg) is the recursive weight fraction assigned to
514 * this group.
516 unsigned long h_load;
519 * this cpu's part of tg->shares
521 unsigned long shares;
524 * load.weight at the time we set shares
526 unsigned long rq_weight;
527 #endif
528 #endif
531 /* Real-Time classes' related field in a runqueue: */
532 struct rt_rq {
533 struct rt_prio_array active;
534 unsigned long rt_nr_running;
535 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
536 struct {
537 int curr; /* highest queued rt task prio */
538 #ifdef CONFIG_SMP
539 int next; /* next highest */
540 #endif
541 } highest_prio;
542 #endif
543 #ifdef CONFIG_SMP
544 unsigned long rt_nr_migratory;
545 int overloaded;
546 struct plist_head pushable_tasks;
547 #endif
548 unsigned long rt_nr_uninterruptible;
549 int rt_throttled;
550 u64 rt_time;
551 u64 rt_runtime;
552 /* Nests inside the rq lock: */
553 raw_spinlock_t rt_runtime_lock;
555 #ifdef CONFIG_RT_GROUP_SCHED
556 unsigned long rt_nr_boosted;
558 struct rq *rq;
559 struct list_head leaf_rt_rq_list;
560 struct task_group *tg;
561 struct sched_rt_entity *rt_se;
562 #endif
565 #ifdef CONFIG_SCHED_CBS
566 struct cbs_rq {
567 unsigned long nr_running;
569 u64 min_deadline;
571 struct rb_root tasks_timeline;
572 struct rb_node *rb_leftmost;
575 * 'curr' points to currently running entity on this cfs_rq.
576 * It is set to NULL otherwise (i.e when none are currently running).
578 struct sched_cbs_entity *curr;
580 #endif
583 #ifdef CONFIG_SMP
586 * We add the notion of a root-domain which will be used to define per-domain
587 * variables. Each exclusive cpuset essentially defines an island domain by
588 * fully partitioning the member cpus from any other cpuset. Whenever a new
589 * exclusive cpuset is created, we also create and attach a new root-domain
590 * object.
593 struct root_domain {
594 atomic_t refcount;
595 cpumask_var_t span;
596 cpumask_var_t online;
599 * The "RT overload" flag: it gets set if a CPU has more than
600 * one runnable RT task.
602 cpumask_var_t rto_mask;
603 atomic_t rto_count;
604 #ifdef CONFIG_SMP
605 struct cpupri cpupri;
606 #endif
607 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
609 * Preferred wake up cpu nominated by sched_mc balance that will be
610 * used when most cpus are idle in the system indicating overall very
611 * low system utilisation. Triggered at POWERSAVINGS_BALANCE_WAKEUP(2)
613 unsigned int sched_mc_preferred_wakeup_cpu;
614 #endif
618 * By default the system creates a single root-domain with all cpus as
619 * members (mimicking the global state we have today).
621 static struct root_domain def_root_domain;
623 #endif
626 * This is the main, per-CPU runqueue data structure.
628 * Locking rule: those places that want to lock multiple runqueues
629 * (such as the load balancing or the thread migration code), lock
630 * acquire operations must be ordered by ascending &runqueue.
632 struct rq {
633 /* runqueue lock: */
634 raw_spinlock_t lock;
637 * nr_running and cpu_load should be in the same cacheline because
638 * remote CPUs use both these fields when doing load calculation.
640 unsigned long nr_running;
641 #define CPU_LOAD_IDX_MAX 5
642 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
643 #ifdef CONFIG_NO_HZ
644 unsigned long last_tick_seen;
645 unsigned char in_nohz_recently;
646 #endif
647 /* capture load from *all* tasks on this cpu: */
648 struct load_weight load;
649 unsigned long nr_load_updates;
650 u64 nr_switches;
651 u64 nr_migrations_in;
653 struct cfs_rq cfs;
654 struct rt_rq rt;
655 #ifdef CONFIG_SCHED_CBS
656 struct cbs_rq cbs;
657 #endif
659 #ifdef CONFIG_FAIR_GROUP_SCHED
660 /* list of leaf cfs_rq on this cpu: */
661 struct list_head leaf_cfs_rq_list;
662 #endif
663 #ifdef CONFIG_RT_GROUP_SCHED
664 struct list_head leaf_rt_rq_list;
665 #endif
668 * This is part of a global counter where only the total sum
669 * over all CPUs matters. A task can increase this counter on
670 * one CPU and if it got migrated afterwards it may decrease
671 * it on another CPU. Always updated under the runqueue lock:
673 unsigned long nr_uninterruptible;
675 unsigned long switch_timestamp;
676 unsigned long slice_avg;
677 struct task_struct *curr, *idle;
678 unsigned long next_balance;
679 struct mm_struct *prev_mm;
681 u64 clock;
683 atomic_t nr_iowait;
685 #ifdef CONFIG_SMP
686 struct root_domain *rd;
687 struct sched_domain *sd;
689 unsigned char idle_at_tick;
690 /* For active balancing */
691 int active_balance;
692 int push_cpu;
693 /* cpu of this runqueue: */
694 int cpu;
695 int online;
697 unsigned long avg_load_per_task;
699 struct task_struct *migration_thread;
700 struct list_head migration_queue;
701 #endif
703 /* calc_load related fields */
704 unsigned long calc_load_update;
705 long calc_load_active;
707 #ifdef CONFIG_SCHED_HRTICK
708 #ifdef CONFIG_SMP
709 int hrtick_csd_pending;
710 struct call_single_data hrtick_csd;
711 #endif
712 struct hrtimer hrtick_timer;
713 #endif
715 #ifdef CONFIG_SCHEDSTATS
716 /* latency stats */
717 struct sched_info rq_sched_info;
718 unsigned long long rq_cpu_time;
719 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
721 /* sys_sched_yield() stats */
722 unsigned int yld_count;
724 /* schedule() stats */
725 unsigned int sched_switch;
726 unsigned int sched_count;
727 unsigned int sched_goidle;
729 /* try_to_wake_up() stats */
730 unsigned int ttwu_count;
731 unsigned int ttwu_local;
733 /* BKL stats */
734 unsigned int bkl_count;
736 /* RT-overload stats: */
737 unsigned long rto_schedule;
738 unsigned long rto_schedule_tail;
739 unsigned long rto_wakeup;
740 unsigned long rto_pulled;
741 unsigned long rto_pushed;
742 #endif
745 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
747 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p, int sync)
749 rq->curr->sched_class->check_preempt_curr(rq, p, sync);
752 static inline int cpu_of(struct rq *rq)
754 #ifdef CONFIG_SMP
755 return rq->cpu;
756 #else
757 return 0;
758 #endif
762 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
763 * See detach_destroy_domains: synchronize_sched for details.
765 * The domain tree of any CPU may only be accessed from within
766 * preempt-disabled sections.
768 #define for_each_domain(cpu, __sd) \
769 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
771 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
772 #define this_rq() (&__get_cpu_var(runqueues))
773 #define task_rq(p) cpu_rq(task_cpu(p))
774 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
776 inline void update_rq_clock(struct rq *rq)
778 rq->clock = sched_clock_cpu(cpu_of(rq));
781 #ifndef CONFIG_SMP
782 int task_is_current(struct task_struct *task)
784 return task_rq(task)->curr == task;
786 #endif
789 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
791 #ifdef CONFIG_SCHED_DEBUG
792 # define const_debug __read_mostly
793 #else
794 # define const_debug static const
795 #endif
798 * runqueue_is_locked
800 * Returns true if the current cpu runqueue is locked.
801 * This interface allows printk to be called with the runqueue lock
802 * held and know whether or not it is OK to wake up the klogd.
804 int runqueue_is_locked(void)
806 int cpu = get_cpu();
807 struct rq *rq = cpu_rq(cpu);
808 int ret;
810 ret = spin_is_locked(&rq->lock);
811 put_cpu();
812 return ret;
816 * Debugging: various feature bits
819 #define SCHED_FEAT(name, enabled) \
820 __SCHED_FEAT_##name ,
822 enum {
823 #include "sched_features.h"
826 #undef SCHED_FEAT
828 #define SCHED_FEAT(name, enabled) \
829 (1UL << __SCHED_FEAT_##name) * enabled |
831 const_debug unsigned int sysctl_sched_features =
832 #include "sched_features.h"
835 #undef SCHED_FEAT
837 #ifdef CONFIG_SCHED_DEBUG
838 #define SCHED_FEAT(name, enabled) \
839 #name ,
841 static __read_mostly char *sched_feat_names[] = {
842 #include "sched_features.h"
843 NULL
846 #undef SCHED_FEAT
848 static int sched_feat_show(struct seq_file *m, void *v)
850 int i;
852 for (i = 0; sched_feat_names[i]; i++) {
853 if (!(sysctl_sched_features & (1UL << i)))
854 seq_puts(m, "NO_");
855 seq_printf(m, "%s ", sched_feat_names[i]);
857 seq_puts(m, "\n");
859 return 0;
862 static ssize_t
863 sched_feat_write(struct file *filp, const char __user *ubuf,
864 size_t cnt, loff_t *ppos)
866 char buf[64];
867 char *cmp = buf;
868 int neg = 0;
869 int i;
871 if (cnt > 63)
872 cnt = 63;
874 if (copy_from_user(&buf, ubuf, cnt))
875 return -EFAULT;
877 buf[cnt] = 0;
879 if (strncmp(buf, "NO_", 3) == 0) {
880 neg = 1;
881 cmp += 3;
884 for (i = 0; sched_feat_names[i]; i++) {
885 int len = strlen(sched_feat_names[i]);
887 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
888 if (neg)
889 sysctl_sched_features &= ~(1UL << i);
890 else
891 sysctl_sched_features |= (1UL << i);
892 break;
896 if (!sched_feat_names[i])
897 return -EINVAL;
899 filp->f_pos += cnt;
901 return cnt;
904 static int sched_feat_open(struct inode *inode, struct file *filp)
906 return single_open(filp, sched_feat_show, NULL);
909 static struct file_operations sched_feat_fops = {
910 .open = sched_feat_open,
911 .write = sched_feat_write,
912 .read = seq_read,
913 .llseek = seq_lseek,
914 .release = single_release,
917 static __init int sched_init_debug(void)
919 debugfs_create_file("sched_features", 0644, NULL, NULL,
920 &sched_feat_fops);
922 return 0;
924 late_initcall(sched_init_debug);
926 #endif
928 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
931 * Number of tasks to iterate in a single balance run.
932 * Limited because this is done with IRQs disabled.
934 const_debug unsigned int sysctl_sched_nr_migrate = 32;
937 * ratelimit for updating the group shares.
938 * default: 0.25ms
940 unsigned int sysctl_sched_shares_ratelimit = 250000;
943 * Inject some fuzzyness into changing the per-cpu group shares
944 * this avoids remote rq-locks at the expense of fairness.
945 * default: 4
947 unsigned int sysctl_sched_shares_thresh = 4;
950 * period over which we measure -rt task cpu usage in us.
951 * default: 1s
953 unsigned int sysctl_sched_rt_period = 1000000;
955 static __read_mostly int scheduler_running;
958 * part of the period that we allow rt tasks to run in us.
959 * default: 0.95s
961 int sysctl_sched_rt_runtime = 950000;
963 static inline u64 global_rt_period(void)
965 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
968 static inline u64 global_rt_runtime(void)
970 if (sysctl_sched_rt_runtime < 0)
971 return RUNTIME_INF;
973 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
977 * We really dont want to do anything complex within switch_to()
978 * on PREEMPT_RT - this check enforces this.
980 #ifdef prepare_arch_switch
981 # ifdef CONFIG_PREEMPT_RT
982 # error FIXME
983 # else
984 # define _finish_arch_switch finish_arch_switch
985 # endif
986 #endif
988 #ifndef prepare_arch_switch
989 # define prepare_arch_switch(next) do { } while (0)
990 #endif
991 #ifndef finish_arch_switch
992 # define _finish_arch_switch(prev) do { } while (0)
993 #endif
995 static inline int task_current(struct rq *rq, struct task_struct *p)
997 return rq->curr == p;
1000 static inline int task_running(struct rq *rq, struct task_struct *p)
1002 #ifdef CONFIG_SMP
1003 return p->oncpu;
1004 #else
1005 return task_current(rq, p);
1006 #endif
1009 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1010 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
1012 #ifdef CONFIG_SMP
1014 * We can optimise this out completely for !SMP, because the
1015 * SMP rebalancing from interrupt is the only thing that cares
1016 * here.
1018 next->oncpu = 1;
1019 #endif
1022 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
1024 #ifdef CONFIG_SMP
1026 * After ->oncpu is cleared, the task can be moved to a different CPU.
1027 * We must ensure this doesn't happen until the switch is completely
1028 * finished.
1030 smp_wmb();
1031 prev->oncpu = 0;
1032 #endif
1033 #ifdef CONFIG_DEBUG_SPINLOCK
1034 /* this is a valid case when another task releases the spinlock */
1035 rq->lock.owner = current;
1036 #endif
1038 * If we are tracking spinlock dependencies then we have to
1039 * fix up the runqueue lock - which gets 'carried over' from
1040 * prev into current:
1042 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
1044 spin_unlock(&rq->lock);
1047 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
1049 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
1051 #ifdef CONFIG_SMP
1053 * We can optimise this out completely for !SMP, because the
1054 * SMP rebalancing from interrupt is the only thing that cares
1055 * here.
1057 next->oncpu = 1;
1058 #endif
1059 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1060 spin_unlock_irq(&rq->lock);
1061 #else
1062 spin_unlock(&rq->lock);
1063 #endif
1066 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
1068 #ifdef CONFIG_SMP
1070 * After ->oncpu is cleared, the task can be moved to a different CPU.
1071 * We must ensure this doesn't happen until the switch is completely
1072 * finished.
1074 smp_wmb();
1075 prev->oncpu = 0;
1076 #endif
1077 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1078 local_irq_disable();
1079 #endif
1081 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1084 * __task_rq_lock - lock the runqueue a given task resides on.
1085 * Must be called interrupts disabled.
1087 static inline struct rq *__task_rq_lock(struct task_struct *p)
1088 __acquires(rq->lock)
1090 for (;;) {
1091 struct rq *rq = task_rq(p);
1092 spin_lock(&rq->lock);
1093 if (likely(rq == task_rq(p)))
1094 return rq;
1095 spin_unlock(&rq->lock);
1100 * task_rq_lock - lock the runqueue a given task resides on and disable
1101 * interrupts. Note the ordering: we can safely lookup the task_rq without
1102 * explicitly disabling preemption.
1104 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1105 __acquires(rq->lock)
1107 struct rq *rq;
1109 for (;;) {
1110 local_irq_save(*flags);
1111 rq = task_rq(p);
1112 spin_lock(&rq->lock);
1113 if (likely(rq == task_rq(p)))
1114 return rq;
1115 spin_unlock_irqrestore(&rq->lock, *flags);
1119 void curr_rq_lock_irq_save(unsigned long *flags)
1120 __acquires(rq->lock)
1122 struct rq *rq;
1124 local_irq_save(*flags);
1125 rq = cpu_rq(smp_processor_id());
1126 spin_lock(&rq->lock);
1129 void curr_rq_unlock_irq_restore(unsigned long *flags)
1130 __releases(rq->lock)
1132 struct rq *rq;
1134 rq = cpu_rq(smp_processor_id());
1135 spin_unlock(&rq->lock);
1136 local_irq_restore(*flags);
1139 void task_rq_unlock_wait(struct task_struct *p)
1141 struct rq *rq = task_rq(p);
1143 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
1144 spin_unlock_wait(&rq->lock);
1147 static void __task_rq_unlock(struct rq *rq)
1148 __releases(rq->lock)
1150 spin_unlock(&rq->lock);
1153 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1154 __releases(rq->lock)
1156 spin_unlock_irqrestore(&rq->lock, *flags);
1160 * this_rq_lock - lock this runqueue and disable interrupts.
1162 static struct rq *this_rq_lock(void)
1163 __acquires(rq->lock)
1165 struct rq *rq;
1167 local_irq_disable();
1168 rq = this_rq();
1169 spin_lock(&rq->lock);
1171 return rq;
1174 #ifdef CONFIG_SCHED_HRTICK
1176 * Use HR-timers to deliver accurate preemption points.
1178 * Its all a bit involved since we cannot program an hrt while holding the
1179 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1180 * reschedule event.
1182 * When we get rescheduled we reprogram the hrtick_timer outside of the
1183 * rq->lock.
1187 * Use hrtick when:
1188 * - enabled by features
1189 * - hrtimer is actually high res
1191 static inline int hrtick_enabled(struct rq *rq)
1193 if (!sched_feat(HRTICK))
1194 return 0;
1195 if (!cpu_active(cpu_of(rq)))
1196 return 0;
1197 return hrtimer_is_hres_active(&rq->hrtick_timer);
1200 static void hrtick_clear(struct rq *rq)
1202 if (hrtimer_active(&rq->hrtick_timer))
1203 hrtimer_cancel(&rq->hrtick_timer);
1207 * High-resolution timer tick.
1208 * Runs from hardirq context with interrupts disabled.
1210 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1212 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1214 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1216 spin_lock(&rq->lock);
1217 update_rq_clock(rq);
1218 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1219 spin_unlock(&rq->lock);
1221 return HRTIMER_NORESTART;
1224 #ifdef CONFIG_SMP
1226 * called from hardirq (IPI) context
1228 static void __hrtick_start(void *arg)
1230 struct rq *rq = arg;
1232 spin_lock(&rq->lock);
1233 hrtimer_restart(&rq->hrtick_timer);
1234 rq->hrtick_csd_pending = 0;
1235 spin_unlock(&rq->lock);
1239 * Called to set the hrtick timer state.
1241 * called with rq->lock held and irqs disabled
1243 static void hrtick_start(struct rq *rq, u64 delay)
1245 struct hrtimer *timer = &rq->hrtick_timer;
1246 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1248 hrtimer_set_expires(timer, time);
1250 if (rq == this_rq()) {
1251 hrtimer_restart(timer);
1252 } else if (!rq->hrtick_csd_pending) {
1253 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1254 rq->hrtick_csd_pending = 1;
1258 static int
1259 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1261 int cpu = (int)(long)hcpu;
1263 switch (action) {
1264 case CPU_UP_CANCELED:
1265 case CPU_UP_CANCELED_FROZEN:
1266 case CPU_DOWN_PREPARE:
1267 case CPU_DOWN_PREPARE_FROZEN:
1268 case CPU_DEAD:
1269 case CPU_DEAD_FROZEN:
1270 hrtick_clear(cpu_rq(cpu));
1271 return NOTIFY_OK;
1274 return NOTIFY_DONE;
1277 static __init void init_hrtick(void)
1279 hotcpu_notifier(hotplug_hrtick, 0);
1281 #else
1283 * Called to set the hrtick timer state.
1285 * called with rq->lock held and irqs disabled
1287 static void hrtick_start(struct rq *rq, u64 delay)
1289 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1290 HRTIMER_MODE_REL, 0);
1293 static inline void init_hrtick(void)
1296 #endif /* CONFIG_SMP */
1298 static void init_rq_hrtick(struct rq *rq)
1300 #ifdef CONFIG_SMP
1301 rq->hrtick_csd_pending = 0;
1303 rq->hrtick_csd.flags = 0;
1304 rq->hrtick_csd.func = __hrtick_start;
1305 rq->hrtick_csd.info = rq;
1306 #endif
1308 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1309 rq->hrtick_timer.function = hrtick;
1310 rq->hrtick_timer.irqsafe = 1;
1312 #else /* CONFIG_SCHED_HRTICK */
1313 static inline void hrtick_clear(struct rq *rq)
1317 static inline void init_rq_hrtick(struct rq *rq)
1321 static inline void init_hrtick(void)
1324 #endif /* CONFIG_SCHED_HRTICK */
1327 * resched_task - mark a task 'to be rescheduled now'.
1329 * On UP this means the setting of the need_resched flag, on SMP it
1330 * might also involve a cross-CPU call to trigger the scheduler on
1331 * the target CPU.
1333 #ifdef CONFIG_SMP
1335 #ifndef tsk_is_polling
1336 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1337 #endif
1339 static void resched_task(struct task_struct *p)
1341 int cpu;
1343 assert_spin_locked(&task_rq(p)->lock);
1345 if (test_tsk_need_resched(p))
1346 return;
1348 set_tsk_need_resched(p);
1350 cpu = task_cpu(p);
1351 if (cpu == smp_processor_id())
1352 return;
1354 /* NEED_RESCHED must be visible before we test polling */
1355 smp_mb();
1356 if (!tsk_is_polling(p))
1357 smp_send_reschedule(cpu);
1360 static void resched_cpu(int cpu)
1362 struct rq *rq = cpu_rq(cpu);
1363 unsigned long flags;
1365 if (!spin_trylock_irqsave(&rq->lock, flags))
1366 return;
1367 resched_task(cpu_curr(cpu));
1368 spin_unlock_irqrestore(&rq->lock, flags);
1371 #ifdef CONFIG_NO_HZ
1373 * When add_timer_on() enqueues a timer into the timer wheel of an
1374 * idle CPU then this timer might expire before the next timer event
1375 * which is scheduled to wake up that CPU. In case of a completely
1376 * idle system the next event might even be infinite time into the
1377 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1378 * leaves the inner idle loop so the newly added timer is taken into
1379 * account when the CPU goes back to idle and evaluates the timer
1380 * wheel for the next timer event.
1382 void wake_up_idle_cpu(int cpu)
1384 struct rq *rq = cpu_rq(cpu);
1386 if (cpu == raw_smp_processor_id())
1387 return;
1390 * This is safe, as this function is called with the timer
1391 * wheel base lock of (cpu) held. When the CPU is on the way
1392 * to idle and has not yet set rq->curr to idle then it will
1393 * be serialized on the timer wheel base lock and take the new
1394 * timer into account automatically.
1396 if (rq->curr != rq->idle)
1397 return;
1400 * We can set TIF_RESCHED on the idle task of the other CPU
1401 * lockless. The worst case is that the other CPU runs the
1402 * idle task through an additional NOOP schedule()
1404 set_tsk_need_resched(rq->idle);
1406 /* NEED_RESCHED must be visible before we test polling */
1407 smp_mb();
1408 if (!tsk_is_polling(rq->idle))
1409 smp_send_reschedule(cpu);
1411 #endif /* CONFIG_NO_HZ */
1413 #else /* !CONFIG_SMP */
1414 static void resched_task(struct task_struct *p)
1416 assert_spin_locked(&task_rq(p)->lock);
1417 set_tsk_need_resched(p);
1419 #endif /* CONFIG_SMP */
1421 #if BITS_PER_LONG == 32
1422 # define WMULT_CONST (~0UL)
1423 #else
1424 # define WMULT_CONST (1UL << 32)
1425 #endif
1427 #define WMULT_SHIFT 32
1430 * Shift right and round:
1432 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1435 * delta *= weight / lw
1437 static unsigned long
1438 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1439 struct load_weight *lw)
1441 u64 tmp;
1443 if (!lw->inv_weight) {
1444 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1445 lw->inv_weight = 1;
1446 else
1447 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1448 / (lw->weight+1);
1451 tmp = (u64)delta_exec * weight;
1453 * Check whether we'd overflow the 64-bit multiplication:
1455 if (unlikely(tmp > WMULT_CONST))
1456 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1457 WMULT_SHIFT/2);
1458 else
1459 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1461 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1464 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1466 lw->weight += inc;
1467 lw->inv_weight = 0;
1470 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1472 lw->weight -= dec;
1473 lw->inv_weight = 0;
1477 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1478 * of tasks with abnormal "nice" values across CPUs the contribution that
1479 * each task makes to its run queue's load is weighted according to its
1480 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1481 * scaled version of the new time slice allocation that they receive on time
1482 * slice expiry etc.
1485 #define WEIGHT_IDLEPRIO 3
1486 #define WMULT_IDLEPRIO 1431655765
1489 * Nice levels are multiplicative, with a gentle 10% change for every
1490 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1491 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1492 * that remained on nice 0.
1494 * The "10% effect" is relative and cumulative: from _any_ nice level,
1495 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1496 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1497 * If a task goes up by ~10% and another task goes down by ~10% then
1498 * the relative distance between them is ~25%.)
1500 static const int prio_to_weight[40] = {
1501 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1502 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1503 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1504 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1505 /* 0 */ 1024, 820, 655, 526, 423,
1506 /* 5 */ 335, 272, 215, 172, 137,
1507 /* 10 */ 110, 87, 70, 56, 45,
1508 /* 15 */ 36, 29, 23, 18, 15,
1512 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1514 * In cases where the weight does not change often, we can use the
1515 * precalculated inverse to speed up arithmetics by turning divisions
1516 * into multiplications:
1518 static const u32 prio_to_wmult[40] = {
1519 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1520 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1521 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1522 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1523 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1524 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1525 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1526 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1529 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1532 * runqueue iterator, to support SMP load-balancing between different
1533 * scheduling classes, without having to expose their internal data
1534 * structures to the load-balancing proper:
1536 struct rq_iterator {
1537 void *arg;
1538 struct task_struct *(*start)(void *);
1539 struct task_struct *(*next)(void *);
1542 #ifdef CONFIG_SMP
1543 static unsigned long
1544 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1545 unsigned long max_load_move, struct sched_domain *sd,
1546 enum cpu_idle_type idle, int *all_pinned,
1547 int *this_best_prio, struct rq_iterator *iterator);
1549 static int
1550 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1551 struct sched_domain *sd, enum cpu_idle_type idle,
1552 struct rq_iterator *iterator);
1553 #endif
1555 #ifdef CONFIG_CGROUP_CPUACCT
1556 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1557 #else
1558 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1559 #endif
1561 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1563 update_load_add(&rq->load, load);
1566 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1568 update_load_sub(&rq->load, load);
1571 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1572 typedef int (*tg_visitor)(struct task_group *, void *);
1575 * Iterate the full tree, calling @down when first entering a node and @up when
1576 * leaving it for the final time.
1578 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1580 struct task_group *parent, *child;
1581 int ret;
1583 rcu_read_lock();
1584 parent = &root_task_group;
1585 down:
1586 ret = (*down)(parent, data);
1587 if (ret)
1588 goto out_unlock;
1589 list_for_each_entry_rcu(child, &parent->children, siblings) {
1590 parent = child;
1591 goto down;
1594 continue;
1596 ret = (*up)(parent, data);
1597 if (ret)
1598 goto out_unlock;
1600 child = parent;
1601 parent = parent->parent;
1602 if (parent)
1603 goto up;
1604 out_unlock:
1605 rcu_read_unlock();
1607 return ret;
1610 static int tg_nop(struct task_group *tg, void *data)
1612 return 0;
1614 #endif
1616 #ifdef CONFIG_SMP
1617 static unsigned long source_load(int cpu, int type);
1618 static unsigned long target_load(int cpu, int type);
1619 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1621 static unsigned long cpu_avg_load_per_task(int cpu)
1623 struct rq *rq = cpu_rq(cpu);
1624 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1626 if (nr_running)
1627 rq->avg_load_per_task = rq->load.weight / nr_running;
1628 else
1629 rq->avg_load_per_task = 0;
1631 return rq->avg_load_per_task;
1634 #ifdef CONFIG_FAIR_GROUP_SCHED
1636 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1639 * Calculate and set the cpu's group shares.
1641 static void
1642 update_group_shares_cpu(struct task_group *tg, int cpu,
1643 unsigned long sd_shares, unsigned long sd_rq_weight)
1645 unsigned long shares;
1646 unsigned long rq_weight;
1648 if (!tg->se[cpu])
1649 return;
1651 rq_weight = tg->cfs_rq[cpu]->rq_weight;
1654 * \Sum shares * rq_weight
1655 * shares = -----------------------
1656 * \Sum rq_weight
1659 shares = (sd_shares * rq_weight) / sd_rq_weight;
1660 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1662 if (abs(shares - tg->se[cpu]->load.weight) >
1663 sysctl_sched_shares_thresh) {
1664 struct rq *rq = cpu_rq(cpu);
1665 unsigned long flags;
1667 spin_lock_irqsave(&rq->lock, flags);
1668 tg->cfs_rq[cpu]->shares = shares;
1670 __set_se_shares(tg->se[cpu], shares);
1671 spin_unlock_irqrestore(&rq->lock, flags);
1676 * Re-compute the task group their per cpu shares over the given domain.
1677 * This needs to be done in a bottom-up fashion because the rq weight of a
1678 * parent group depends on the shares of its child groups.
1680 static int tg_shares_up(struct task_group *tg, void *data)
1682 unsigned long weight, rq_weight = 0;
1683 unsigned long shares = 0;
1684 struct sched_domain *sd = data;
1685 int i;
1687 for_each_cpu(i, sched_domain_span(sd)) {
1689 * If there are currently no tasks on the cpu pretend there
1690 * is one of average load so that when a new task gets to
1691 * run here it will not get delayed by group starvation.
1693 weight = tg->cfs_rq[i]->load.weight;
1694 if (!weight)
1695 weight = NICE_0_LOAD;
1697 tg->cfs_rq[i]->rq_weight = weight;
1698 rq_weight += weight;
1699 shares += tg->cfs_rq[i]->shares;
1702 if ((!shares && rq_weight) || shares > tg->shares)
1703 shares = tg->shares;
1705 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1706 shares = tg->shares;
1708 for_each_cpu(i, sched_domain_span(sd))
1709 update_group_shares_cpu(tg, i, shares, rq_weight);
1711 return 0;
1715 * Compute the cpu's hierarchical load factor for each task group.
1716 * This needs to be done in a top-down fashion because the load of a child
1717 * group is a fraction of its parents load.
1719 static int tg_load_down(struct task_group *tg, void *data)
1721 unsigned long load;
1722 long cpu = (long)data;
1724 if (!tg->parent) {
1725 load = cpu_rq(cpu)->load.weight;
1726 } else {
1727 load = tg->parent->cfs_rq[cpu]->h_load;
1728 load *= tg->cfs_rq[cpu]->shares;
1729 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1732 tg->cfs_rq[cpu]->h_load = load;
1734 return 0;
1737 static void update_shares(struct sched_domain *sd)
1739 u64 now = cpu_clock(raw_smp_processor_id());
1740 s64 elapsed = now - sd->last_update;
1742 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1743 sd->last_update = now;
1744 walk_tg_tree(tg_nop, tg_shares_up, sd);
1748 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1750 spin_unlock(&rq->lock);
1751 update_shares(sd);
1752 spin_lock(&rq->lock);
1755 static void update_h_load(long cpu)
1757 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1760 #else
1762 static inline void update_shares(struct sched_domain *sd)
1766 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1770 #endif
1772 #ifdef CONFIG_PREEMPT
1775 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1776 * way at the expense of forcing extra atomic operations in all
1777 * invocations. This assures that the double_lock is acquired using the
1778 * same underlying policy as the spinlock_t on this architecture, which
1779 * reduces latency compared to the unfair variant below. However, it
1780 * also adds more overhead and therefore may reduce throughput.
1782 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1783 __releases(this_rq->lock)
1784 __acquires(busiest->lock)
1785 __acquires(this_rq->lock)
1787 spin_unlock(&this_rq->lock);
1788 double_rq_lock(this_rq, busiest);
1790 return 1;
1793 #else
1795 * Unfair double_lock_balance: Optimizes throughput at the expense of
1796 * latency by eliminating extra atomic operations when the locks are
1797 * already in proper order on entry. This favors lower cpu-ids and will
1798 * grant the double lock to lower cpus over higher ids under contention,
1799 * regardless of entry order into the function.
1801 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1802 __releases(this_rq->lock)
1803 __acquires(busiest->lock)
1804 __acquires(this_rq->lock)
1806 int ret = 0;
1808 if (unlikely(!spin_trylock(&busiest->lock))) {
1809 if (busiest < this_rq) {
1810 spin_unlock(&this_rq->lock);
1811 spin_lock(&busiest->lock);
1812 spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING);
1813 ret = 1;
1814 } else
1815 spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING);
1817 return ret;
1820 #endif /* CONFIG_PREEMPT */
1823 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1825 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1827 if (unlikely(!irqs_disabled())) {
1828 /* printk() doesn't work good under rq->lock */
1829 spin_unlock(&this_rq->lock);
1830 BUG_ON(1);
1833 return _double_lock_balance(this_rq, busiest);
1836 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1837 __releases(busiest->lock)
1839 spin_unlock(&busiest->lock);
1840 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1842 #endif
1844 #ifdef CONFIG_FAIR_GROUP_SCHED
1845 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1847 #ifdef CONFIG_SMP
1848 cfs_rq->shares = shares;
1849 #endif
1851 #endif
1853 static void calc_load_account_active(struct rq *this_rq);
1855 #include "sched_stats.h"
1856 #include "sched_idletask.c"
1857 #include "sched_fair.c"
1858 #ifdef CONFIG_SCHED_CBS
1859 #include "sched_cbs.c"
1860 #endif
1861 #include "sched_rt.c"
1862 #ifdef CONFIG_SCHED_DEBUG
1863 # include "sched_debug.c"
1864 #endif
1866 #define sched_class_highest (&rt_sched_class)
1867 #define for_each_class(class) \
1868 for (class = sched_class_highest; class; class = class->next)
1870 static void inc_nr_running(struct rq *rq)
1872 rq->nr_running++;
1875 static void dec_nr_running(struct rq *rq)
1877 rq->nr_running--;
1880 static void set_load_weight(struct task_struct *p)
1882 if (task_has_rt_policy(p)) {
1883 p->se.load.weight = prio_to_weight[0] * 2;
1884 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1885 return;
1889 * SCHED_IDLE tasks get minimal weight:
1891 if (p->policy == SCHED_IDLE) {
1892 p->se.load.weight = WEIGHT_IDLEPRIO;
1893 p->se.load.inv_weight = WMULT_IDLEPRIO;
1894 return;
1897 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1898 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1901 static void update_avg(u64 *avg, u64 sample)
1903 s64 diff = sample - *avg;
1904 *avg += diff >> 3;
1907 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1909 if (wakeup)
1910 p->se.start_runtime = p->se.sum_exec_runtime;
1912 sched_info_queued(p);
1913 p->sched_class->enqueue_task(rq, p, wakeup);
1914 p->se.on_rq = 1;
1917 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1919 if (sleep) {
1920 if (p->se.last_wakeup) {
1921 update_avg(&p->se.avg_overlap,
1922 p->se.sum_exec_runtime - p->se.last_wakeup);
1923 p->se.last_wakeup = 0;
1924 } else {
1925 update_avg(&p->se.avg_wakeup,
1926 sysctl_sched_wakeup_granularity);
1930 sched_info_dequeued(p);
1931 p->sched_class->dequeue_task(rq, p, sleep);
1932 p->se.on_rq = 0;
1936 * __normal_prio - return the priority that is based on the static prio
1938 static inline int __normal_prio(struct task_struct *p)
1940 return p->static_prio;
1944 * Calculate the expected normal priority: i.e. priority
1945 * without taking RT-inheritance into account. Might be
1946 * boosted by interactivity modifiers. Changes upon fork,
1947 * setprio syscalls, and whenever the interactivity
1948 * estimator recalculates.
1950 static inline int normal_prio(struct task_struct *p)
1952 int prio;
1954 if (task_has_rt_policy(p))
1955 prio = MAX_RT_PRIO-1 - p->rt_priority;
1956 else
1957 prio = __normal_prio(p);
1959 // trace_special_pid(p->pid, PRIO(p), __PRIO(prio));
1960 return prio;
1964 * Calculate the current priority, i.e. the priority
1965 * taken into account by the scheduler. This value might
1966 * be boosted by RT tasks, or might be boosted by
1967 * interactivity modifiers. Will be RT if the task got
1968 * RT-boosted. If not then it returns p->normal_prio.
1970 static int effective_prio(struct task_struct *p)
1972 p->normal_prio = normal_prio(p);
1974 * If we are RT tasks or we were boosted to RT priority,
1975 * keep the priority unchanged. Otherwise, update priority
1976 * to the normal priority:
1978 if (!rt_prio(p->prio))
1979 return p->normal_prio;
1980 return p->prio;
1984 * activate_task - move a task to the runqueue.
1986 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1988 if (task_contributes_to_load(p))
1989 rq->nr_uninterruptible--;
1990 enqueue_task(rq, p, wakeup);
1991 inc_nr_running(rq);
1995 * deactivate_task - remove a task from the runqueue.
1997 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1999 if (task_contributes_to_load(p))
2000 rq->nr_uninterruptible++;
2002 dequeue_task(rq, p, sleep);
2003 dec_nr_running(rq);
2008 * task_curr - is this task currently executing on a CPU?
2009 * @p: the task in question.
2011 inline int task_curr(const struct task_struct *p)
2013 return cpu_curr(task_cpu(p)) == p;
2016 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
2018 set_task_rq(p, cpu);
2019 #ifdef CONFIG_SMP
2021 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
2022 * successfuly executed on another CPU. We must ensure that updates of
2023 * per-task data have been completed by this moment.
2025 smp_wmb();
2026 task_thread_info(p)->cpu = cpu;
2027 #endif
2030 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2031 const struct sched_class *prev_class,
2032 int oldprio, int running)
2034 if (prev_class != p->sched_class) {
2035 if (prev_class->switched_from)
2036 prev_class->switched_from(rq, p, running);
2037 p->sched_class->switched_to(rq, p, running);
2038 } else
2039 p->sched_class->prio_changed(rq, p, oldprio, running);
2042 #ifdef CONFIG_SMP
2044 /* Used instead of source_load when we know the type == 0 */
2045 static unsigned long weighted_cpuload(const int cpu)
2047 return cpu_rq(cpu)->load.weight;
2051 * Is this task likely cache-hot:
2053 static int
2054 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2056 s64 delta;
2059 * Buddy candidates are cache hot:
2061 if (sched_feat(CACHE_HOT_BUDDY) &&
2062 (&p->se == cfs_rq_of(&p->se)->next ||
2063 &p->se == cfs_rq_of(&p->se)->last))
2064 return 1;
2066 if (p->sched_class != &fair_sched_class)
2067 return 0;
2069 if (sysctl_sched_migration_cost == -1)
2070 return 1;
2071 if (sysctl_sched_migration_cost == 0)
2072 return 0;
2074 delta = now - p->se.exec_start;
2076 return delta < (s64)sysctl_sched_migration_cost;
2080 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2082 int old_cpu = task_cpu(p);
2083 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2084 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2085 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2086 u64 clock_offset;
2088 clock_offset = old_rq->clock - new_rq->clock;
2090 trace_sched_migrate_task(p, task_cpu(p), new_cpu);
2092 #ifdef CONFIG_SCHEDSTATS
2093 if (p->se.wait_start)
2094 p->se.wait_start -= clock_offset;
2095 if (p->se.sleep_start)
2096 p->se.sleep_start -= clock_offset;
2097 if (p->se.block_start)
2098 p->se.block_start -= clock_offset;
2099 #endif
2100 if (old_cpu != new_cpu) {
2101 p->se.nr_migrations++;
2102 new_rq->nr_migrations_in++;
2103 #ifdef CONFIG_SCHEDSTATS
2104 if (task_hot(p, old_rq->clock, NULL))
2105 schedstat_inc(p, se.nr_forced2_migrations);
2106 #endif
2108 p->se.vruntime -= old_cfsrq->min_vruntime -
2109 new_cfsrq->min_vruntime;
2111 __set_task_cpu(p, new_cpu);
2114 struct migration_req {
2115 struct list_head list;
2117 struct task_struct *task;
2118 int dest_cpu;
2120 struct completion done;
2124 * The task's runqueue lock must be held.
2125 * Returns true if you have to wait for migration thread.
2127 static int
2128 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2130 struct rq *rq = task_rq(p);
2133 * If the task is not on a runqueue (and not running), then
2134 * it is sufficient to simply update the task's cpu field.
2136 if (!p->se.on_rq && !task_running(rq, p)) {
2137 set_task_cpu(p, dest_cpu);
2138 return 0;
2141 init_completion(&req->done);
2142 req->task = p;
2143 req->dest_cpu = dest_cpu;
2144 list_add(&req->list, &rq->migration_queue);
2146 return 1;
2150 * wait_task_inactive - wait for a thread to unschedule.
2152 * If @match_state is nonzero, it's the @p->state value just checked and
2153 * not expected to change. If it changes, i.e. @p might have woken up,
2154 * then return zero. When we succeed in waiting for @p to be off its CPU,
2155 * we return a positive number (its total switch count). If a second call
2156 * a short while later returns the same number, the caller can be sure that
2157 * @p has remained unscheduled the whole time.
2159 * The caller must ensure that the task *will* unschedule sometime soon,
2160 * else this function might spin for a *long* time. This function can't
2161 * be called with interrupts off, or it may introduce deadlock with
2162 * smp_call_function() if an IPI is sent by the same process we are
2163 * waiting to become inactive.
2165 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2167 unsigned long flags;
2168 int running, on_rq;
2169 unsigned long ncsw;
2170 struct rq *rq;
2172 for (;;) {
2174 * We do the initial early heuristics without holding
2175 * any task-queue locks at all. We'll only try to get
2176 * the runqueue lock when things look like they will
2177 * work out!
2179 rq = task_rq(p);
2182 * If the task is actively running on another CPU
2183 * still, just relax and busy-wait without holding
2184 * any locks.
2186 * NOTE! Since we don't hold any locks, it's not
2187 * even sure that "rq" stays as the right runqueue!
2188 * But we don't care, since "task_running()" will
2189 * return false if the runqueue has changed and p
2190 * is actually now running somewhere else!
2192 while (task_running(rq, p)) {
2193 if (match_state && unlikely(p->state != match_state))
2194 return 0;
2195 cpu_relax();
2199 * Ok, time to look more closely! We need the rq
2200 * lock now, to be *sure*. If we're wrong, we'll
2201 * just go back and repeat.
2203 rq = task_rq_lock(p, &flags);
2204 trace_sched_wait_task(rq, p);
2205 running = task_running(rq, p);
2206 on_rq = p->se.on_rq;
2207 ncsw = 0;
2208 if (!match_state || p->state == match_state)
2209 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2210 task_rq_unlock(rq, &flags);
2213 * If it changed from the expected state, bail out now.
2215 if (unlikely(!ncsw))
2216 break;
2219 * Was it really running after all now that we
2220 * checked with the proper locks actually held?
2222 * Oops. Go back and try again..
2224 if (unlikely(running)) {
2225 cpu_relax();
2226 continue;
2230 * It's not enough that it's not actively running,
2231 * it must be off the runqueue _entirely_, and not
2232 * preempted!
2234 * So if it was still runnable (but just not actively
2235 * running right now), it's preempted, and we should
2236 * yield - it could be a while.
2238 if (unlikely(on_rq)) {
2239 schedule_timeout_uninterruptible(1);
2240 continue;
2244 * Ahh, all good. It wasn't running, and it wasn't
2245 * runnable, which means that it will never become
2246 * running in the future either. We're all done!
2248 break;
2251 return ncsw;
2254 /***
2255 * kick_process - kick a running thread to enter/exit the kernel
2256 * @p: the to-be-kicked thread
2258 * Cause a process which is running on another CPU to enter
2259 * kernel-mode, without any delay. (to get signals handled.)
2261 * NOTE: this function doesnt have to take the runqueue lock,
2262 * because all it wants to ensure is that the remote task enters
2263 * the kernel. If the IPI races and the task has been migrated
2264 * to another CPU then no harm is done and the purpose has been
2265 * achieved as well.
2267 void kick_process(struct task_struct *p)
2269 int cpu;
2271 preempt_disable();
2272 cpu = task_cpu(p);
2273 if ((cpu != smp_processor_id()) && task_curr(p))
2274 smp_send_reschedule(cpu);
2275 preempt_enable();
2279 * Return a low guess at the load of a migration-source cpu weighted
2280 * according to the scheduling class and "nice" value.
2282 * We want to under-estimate the load of migration sources, to
2283 * balance conservatively.
2285 static unsigned long source_load(int cpu, int type)
2287 struct rq *rq = cpu_rq(cpu);
2288 unsigned long total = weighted_cpuload(cpu);
2290 if (type == 0 || !sched_feat(LB_BIAS))
2291 return total;
2293 return min(rq->cpu_load[type-1], total);
2297 * Return a high guess at the load of a migration-target cpu weighted
2298 * according to the scheduling class and "nice" value.
2300 static unsigned long target_load(int cpu, int type)
2302 struct rq *rq = cpu_rq(cpu);
2303 unsigned long total = weighted_cpuload(cpu);
2305 if (type == 0 || !sched_feat(LB_BIAS))
2306 return total;
2308 return max(rq->cpu_load[type-1], total);
2312 * find_idlest_group finds and returns the least busy CPU group within the
2313 * domain.
2315 static struct sched_group *
2316 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2318 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2319 unsigned long min_load = ULONG_MAX, this_load = 0;
2320 int load_idx = sd->forkexec_idx;
2321 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2323 do {
2324 unsigned long load, avg_load;
2325 int local_group;
2326 int i;
2328 /* Skip over this group if it has no CPUs allowed */
2329 if (!cpumask_intersects(sched_group_cpus(group),
2330 &p->cpus_allowed))
2331 continue;
2333 local_group = cpumask_test_cpu(this_cpu,
2334 sched_group_cpus(group));
2336 /* Tally up the load of all CPUs in the group */
2337 avg_load = 0;
2339 for_each_cpu(i, sched_group_cpus(group)) {
2340 /* Bias balancing toward cpus of our domain */
2341 if (local_group)
2342 load = source_load(i, load_idx);
2343 else
2344 load = target_load(i, load_idx);
2346 avg_load += load;
2349 /* Adjust by relative CPU power of the group */
2350 avg_load = sg_div_cpu_power(group,
2351 avg_load * SCHED_LOAD_SCALE);
2353 if (local_group) {
2354 this_load = avg_load;
2355 this = group;
2356 } else if (avg_load < min_load) {
2357 min_load = avg_load;
2358 idlest = group;
2360 } while (group = group->next, group != sd->groups);
2362 if (!idlest || 100*this_load < imbalance*min_load)
2363 return NULL;
2364 return idlest;
2368 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2370 static int
2371 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2373 unsigned long load, min_load = ULONG_MAX;
2374 int idlest = -1;
2375 int i;
2377 /* Traverse only the allowed CPUs */
2378 for_each_cpu_and(i, sched_group_cpus(group), &p->cpus_allowed) {
2379 load = weighted_cpuload(i);
2381 if (load < min_load || (load == min_load && i == this_cpu)) {
2382 min_load = load;
2383 idlest = i;
2387 return idlest;
2391 * sched_balance_self: balance the current task (running on cpu) in domains
2392 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2393 * SD_BALANCE_EXEC.
2395 * Balance, ie. select the least loaded group.
2397 * Returns the target CPU number, or the same CPU if no balancing is needed.
2399 * preempt must be disabled.
2401 static int sched_balance_self(int cpu, int flag)
2403 struct task_struct *t = current;
2404 struct sched_domain *tmp, *sd = NULL;
2406 for_each_domain(cpu, tmp) {
2408 * If power savings logic is enabled for a domain, stop there.
2410 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2411 break;
2412 if (tmp->flags & flag)
2413 sd = tmp;
2416 if (sd)
2417 update_shares(sd);
2419 while (sd) {
2420 struct sched_group *group;
2421 int new_cpu, weight;
2423 if (!(sd->flags & flag)) {
2424 sd = sd->child;
2425 continue;
2428 group = find_idlest_group(sd, t, cpu);
2429 if (!group) {
2430 sd = sd->child;
2431 continue;
2434 new_cpu = find_idlest_cpu(group, t, cpu);
2435 if (new_cpu == -1 || new_cpu == cpu) {
2436 /* Now try balancing at a lower domain level of cpu */
2437 sd = sd->child;
2438 continue;
2441 /* Now try balancing at a lower domain level of new_cpu */
2442 cpu = new_cpu;
2443 weight = cpumask_weight(sched_domain_span(sd));
2444 sd = NULL;
2445 for_each_domain(cpu, tmp) {
2446 if (weight <= cpumask_weight(sched_domain_span(tmp)))
2447 break;
2448 if (tmp->flags & flag)
2449 sd = tmp;
2451 /* while loop will break here if sd == NULL */
2454 return cpu;
2457 #endif /* CONFIG_SMP */
2459 #ifdef CONFIG_DEBUG_PREEMPT
2460 void notrace preempt_enable_no_resched(void)
2462 static int once = 1;
2464 barrier();
2465 dec_preempt_count();
2467 if (once && !preempt_count()) {
2468 once = 0;
2469 printk(KERN_ERR "BUG: %s:%d task might have lost a preemption check!\n",
2470 current->comm, current->pid);
2471 dump_stack();
2475 EXPORT_SYMBOL(preempt_enable_no_resched);
2476 #endif
2480 * task_oncpu_function_call - call a function on the cpu on which a task runs
2481 * @p: the task to evaluate
2482 * @func: the function to be called
2483 * @info: the function call argument
2485 * Calls the function @func when the task is currently running. This might
2486 * be on the current CPU, which just calls the function directly
2488 void task_oncpu_function_call(struct task_struct *p,
2489 void (*func) (void *info), void *info)
2491 int cpu;
2493 preempt_disable();
2494 cpu = task_cpu(p);
2495 if (task_curr(p))
2496 smp_call_function_single(cpu, func, info, 1);
2497 preempt_enable();
2500 /***
2501 * try_to_wake_up - wake up a thread
2502 * @p: the to-be-woken-up thread
2503 * @state: the mask of task states that can be woken
2504 * @sync: do a synchronous wakeup?
2506 * Put it on the run-queue if it's not already there. The "current"
2507 * thread is always on the run-queue (except when the actual
2508 * re-schedule is in progress), and as such you're allowed to do
2509 * the simpler "current->state = TASK_RUNNING" to mark yourself
2510 * runnable without the overhead of this.
2512 * returns failure only if the task is already active.
2514 static int
2515 try_to_wake_up(struct task_struct *p, unsigned int state, int sync, int mutex)
2517 int cpu, orig_cpu, this_cpu, success = 0;
2518 unsigned long flags;
2519 long old_state;
2520 struct rq *rq;
2522 if (!sched_feat(SYNC_WAKEUPS))
2523 sync = 0;
2525 #ifdef CONFIG_SMP
2526 if (sched_feat(LB_WAKEUP_UPDATE) && !root_task_group_empty()) {
2527 struct sched_domain *sd;
2529 this_cpu = raw_smp_processor_id();
2530 cpu = task_cpu(p);
2532 for_each_domain(this_cpu, sd) {
2533 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2534 update_shares(sd);
2535 break;
2539 #endif
2541 #ifdef CONFIG_PREEMPT_RT
2543 * sync wakeups can increase wakeup latencies:
2545 if (rt_task(p))
2546 sync = 0;
2547 #endif
2548 smp_wmb();
2549 rq = task_rq_lock(p, &flags);
2550 update_rq_clock(rq);
2551 old_state = p->state;
2552 if (!(old_state & state))
2553 goto out;
2555 if (p->se.on_rq)
2556 goto out_running;
2558 cpu = task_cpu(p);
2559 orig_cpu = cpu;
2560 this_cpu = smp_processor_id();
2562 #ifdef CONFIG_SMP
2563 if (unlikely(task_running(rq, p)))
2564 goto out_activate;
2566 cpu = p->sched_class->select_task_rq(p, sync);
2567 if (cpu != orig_cpu) {
2568 set_task_cpu(p, cpu);
2569 task_rq_unlock(rq, &flags);
2570 /* might preempt at this point */
2571 rq = task_rq_lock(p, &flags);
2572 old_state = p->state;
2573 if (!(old_state & state))
2574 goto out;
2575 if (p->se.on_rq)
2576 goto out_running;
2578 this_cpu = smp_processor_id();
2579 cpu = task_cpu(p);
2582 #ifdef CONFIG_SCHEDSTATS
2583 schedstat_inc(rq, ttwu_count);
2584 if (cpu == this_cpu)
2585 schedstat_inc(rq, ttwu_local);
2586 else {
2587 struct sched_domain *sd;
2588 for_each_domain(this_cpu, sd) {
2589 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2590 schedstat_inc(sd, ttwu_wake_remote);
2591 break;
2595 #endif /* CONFIG_SCHEDSTATS */
2597 out_activate:
2598 #endif /* CONFIG_SMP */
2599 schedstat_inc(p, se.nr_wakeups);
2600 if (sync)
2601 schedstat_inc(p, se.nr_wakeups_sync);
2602 if (orig_cpu != cpu)
2603 schedstat_inc(p, se.nr_wakeups_migrate);
2604 if (cpu == this_cpu)
2605 schedstat_inc(p, se.nr_wakeups_local);
2606 else
2607 schedstat_inc(p, se.nr_wakeups_remote);
2608 activate_task(rq, p, 1);
2609 success = 1;
2612 * Only attribute actual wakeups done by this task.
2614 if (!in_interrupt()) {
2615 struct sched_entity *se = &current->se;
2616 u64 sample = se->sum_exec_runtime;
2618 if (se->last_wakeup)
2619 sample -= se->last_wakeup;
2620 else
2621 sample -= se->start_runtime;
2622 update_avg(&se->avg_wakeup, sample);
2624 se->last_wakeup = se->sum_exec_runtime;
2627 out_running:
2628 trace_sched_wakeup(rq, p, success);
2629 check_preempt_curr(rq, p, sync);
2632 * For a mutex wakeup we or TASK_RUNNING_MUTEX to the task
2633 * state to preserve the original state, so a real wakeup
2634 * still can see the (UN)INTERRUPTIBLE bits in the state check
2635 * above. We dont have to worry about the | TASK_RUNNING_MUTEX
2636 * here. The waiter is serialized by the mutex lock and nobody
2637 * else can fiddle with p->state as we hold rq lock.
2639 if (mutex)
2640 p->state |= TASK_RUNNING_MUTEX;
2641 else
2642 p->state = TASK_RUNNING;
2643 #ifdef CONFIG_SMP
2644 if (p->sched_class->task_wake_up)
2645 p->sched_class->task_wake_up(rq, p);
2646 #endif
2647 out:
2648 task_rq_unlock(rq, &flags);
2650 return success;
2653 int wake_up_process(struct task_struct *p)
2655 return try_to_wake_up(p, TASK_ALL, 0, 0);
2657 EXPORT_SYMBOL(wake_up_process);
2659 int wake_up_process_sync(struct task_struct * p)
2661 return try_to_wake_up(p, TASK_ALL, 1, 0);
2663 EXPORT_SYMBOL(wake_up_process_sync);
2665 int wake_up_process_mutex(struct task_struct * p)
2667 return try_to_wake_up(p, TASK_ALL, 0, 1);
2669 EXPORT_SYMBOL(wake_up_process_mutex);
2671 int wake_up_process_mutex_sync(struct task_struct * p)
2673 return try_to_wake_up(p, TASK_ALL, 1, 1);
2675 EXPORT_SYMBOL(wake_up_process_mutex_sync);
2677 int wake_up_state(struct task_struct *p, unsigned int state)
2679 return try_to_wake_up(p, state, 0, 0);
2683 * Perform scheduler related setup for a newly forked process p.
2684 * p is forked by current.
2686 * __sched_fork() is basic setup used by init_idle() too:
2688 static void __sched_fork(struct task_struct *p)
2690 p->se.exec_start = 0;
2691 p->se.sum_exec_runtime = 0;
2692 p->se.prev_sum_exec_runtime = 0;
2693 p->se.nr_migrations = 0;
2694 p->se.last_wakeup = 0;
2695 p->se.avg_overlap = 0;
2696 p->se.start_runtime = 0;
2697 p->se.avg_wakeup = sysctl_sched_wakeup_granularity;
2699 #ifdef CONFIG_SCHEDSTATS
2700 p->se.wait_start = 0;
2701 p->se.sum_sleep_runtime = 0;
2702 p->se.sleep_start = 0;
2703 p->se.block_start = 0;
2704 p->se.sleep_max = 0;
2705 p->se.block_max = 0;
2706 p->se.exec_max = 0;
2707 p->se.slice_max = 0;
2708 p->se.wait_max = 0;
2709 #endif
2711 INIT_LIST_HEAD(&p->rt.run_list);
2712 p->se.on_rq = 0;
2713 INIT_LIST_HEAD(&p->se.group_node);
2715 #ifdef CONFIG_PREEMPT_NOTIFIERS
2716 INIT_HLIST_HEAD(&p->preempt_notifiers);
2717 #endif
2720 * We mark the process as running here, but have not actually
2721 * inserted it onto the runqueue yet. This guarantees that
2722 * nobody will actually run it, and a signal or other external
2723 * event cannot wake it up and insert it on the runqueue either.
2725 p->state = TASK_RUNNING;
2729 * fork()/clone()-time setup:
2731 void sched_fork(struct task_struct *p, int clone_flags)
2733 int cpu = get_cpu();
2735 __sched_fork(p);
2737 #ifdef CONFIG_SMP
2738 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2739 #endif
2740 set_task_cpu(p, cpu);
2743 * Make sure we do not leak PI boosting priority to the child:
2745 p->prio = current->normal_prio;
2746 if (!rt_prio(p->prio)) {
2747 p->sched_class = &fair_sched_class;
2748 #ifdef CONFIG_SCHED_CBS
2749 if (p->policy == SCHED_CBS)
2750 p->sched_class = &cbs_sched_class;
2751 else
2752 #endif
2753 p->sched_class = &fair_sched_class;
2756 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2757 if (likely(sched_info_on()))
2758 memset(&p->sched_info, 0, sizeof(p->sched_info));
2759 #endif
2760 #if defined(CONFIG_SMP)
2761 p->oncpu = 0;
2762 #endif
2763 #ifdef CONFIG_PREEMPT
2764 /* Want to start with kernel preemption disabled. */
2765 task_thread_info(p)->preempt_count = 1;
2766 #endif
2767 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2769 put_cpu();
2773 * wake_up_new_task - wake up a newly created task for the first time.
2775 * This function will do some initial scheduler statistics housekeeping
2776 * that must be done for every newly created context, then puts the task
2777 * on the runqueue and wakes it.
2779 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2781 unsigned long flags;
2782 struct rq *rq;
2784 rq = task_rq_lock(p, &flags);
2785 BUG_ON(p->state != TASK_RUNNING);
2786 update_rq_clock(rq);
2788 p->prio = effective_prio(p);
2790 if (!p->sched_class->task_new || !current->se.on_rq) {
2791 activate_task(rq, p, 0);
2792 } else {
2794 * Let the scheduling class do new task startup
2795 * management (if any):
2797 p->sched_class->task_new(rq, p);
2798 inc_nr_running(rq);
2800 trace_sched_wakeup_new(rq, p, 1);
2801 check_preempt_curr(rq, p, 0);
2802 #ifdef CONFIG_SMP
2803 if (p->sched_class->task_wake_up)
2804 p->sched_class->task_wake_up(rq, p);
2805 #endif
2806 task_rq_unlock(rq, &flags);
2809 #ifdef CONFIG_PREEMPT_NOTIFIERS
2812 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2813 * @notifier: notifier struct to register
2815 void preempt_notifier_register(struct preempt_notifier *notifier)
2817 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2819 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2822 * preempt_notifier_unregister - no longer interested in preemption notifications
2823 * @notifier: notifier struct to unregister
2825 * This is safe to call from within a preemption notifier.
2827 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2829 hlist_del(&notifier->link);
2831 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2833 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2835 struct preempt_notifier *notifier;
2836 struct hlist_node *node;
2838 if (hlist_empty(&curr->preempt_notifiers))
2839 return;
2842 * The KVM sched in notifier expects to be called with
2843 * interrupts enabled.
2845 local_irq_enable();
2846 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2847 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2848 local_irq_disable();
2851 static void
2852 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2853 struct task_struct *next)
2855 struct preempt_notifier *notifier;
2856 struct hlist_node *node;
2858 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2859 notifier->ops->sched_out(notifier, next);
2862 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2864 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2868 static void
2869 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2870 struct task_struct *next)
2874 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2877 * prepare_task_switch - prepare to switch tasks
2878 * @rq: the runqueue preparing to switch
2879 * @prev: the current task that is being switched out
2880 * @next: the task we are going to switch to.
2882 * This is called with the rq lock held and interrupts off. It must
2883 * be paired with a subsequent finish_task_switch after the context
2884 * switch.
2886 * prepare_task_switch sets up locking and calls architecture specific
2887 * hooks.
2889 static inline void
2890 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2891 struct task_struct *next)
2893 fire_sched_out_preempt_notifiers(prev, next);
2894 prepare_lock_switch(rq, next);
2895 prepare_arch_switch(next);
2899 * finish_task_switch - clean up after a task-switch
2900 * @rq: runqueue associated with task-switch
2901 * @prev: the thread we just switched away from.
2903 * finish_task_switch must be called after the context switch, paired
2904 * with a prepare_task_switch call before the context switch.
2905 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2906 * and do any other architecture-specific cleanup actions.
2908 * Note that we may have delayed dropping an mm in context_switch(). If
2909 * so, we finish that here outside of the runqueue lock. (Doing it
2910 * with the lock held can cause deadlocks; see schedule() for
2911 * details.)
2913 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2914 __releases(rq->lock)
2916 struct mm_struct *mm = rq->prev_mm;
2917 long prev_state;
2918 #ifdef CONFIG_SMP
2919 int post_schedule = 0;
2921 if (current->sched_class->needs_post_schedule)
2922 post_schedule = current->sched_class->needs_post_schedule(rq);
2923 #endif
2925 rq->prev_mm = NULL;
2928 * A task struct has one reference for the use as "current".
2929 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2930 * schedule one last time. The schedule call will never return, and
2931 * the scheduled task must drop that reference.
2932 * The test for TASK_DEAD must occur while the runqueue locks are
2933 * still held, otherwise prev could be scheduled on another cpu, die
2934 * there before we look at prev->state, and then the reference would
2935 * be dropped twice.
2936 * Manfred Spraul <manfred@colorfullife.com>
2938 prev_state = prev->state;
2939 _finish_arch_switch(prev);
2940 perf_counter_task_sched_in(current, cpu_of(rq));
2941 finish_lock_switch(rq, prev);
2942 #ifdef CONFIG_SMP
2943 if (post_schedule)
2944 current->sched_class->post_schedule(rq);
2945 #endif
2947 fire_sched_in_preempt_notifiers(current);
2949 * Delay the final freeing of the mm or task, so that we dont have
2950 * to do complex work from within the scheduler:
2952 if (mm)
2953 mmdrop_delayed(mm);
2954 if (unlikely(prev_state == TASK_DEAD)) {
2956 * Remove function-return probe instances associated with this
2957 * task and put them back on the free list.
2959 kprobe_flush_task(prev);
2960 put_task_struct(prev);
2965 * schedule_tail - first thing a freshly forked thread must call.
2966 * @prev: the thread we just switched away from.
2968 asmlinkage void schedule_tail(struct task_struct *prev)
2969 __releases(rq->lock)
2971 preempt_disable();
2972 finish_task_switch(this_rq(), prev);
2973 __preempt_enable_no_resched();
2974 local_irq_enable();
2975 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2976 /* In this case, finish_task_switch does not reenable preemption */
2977 preempt_enable();
2978 #else
2979 preempt_check_resched();
2980 #endif
2981 if (current->set_child_tid)
2982 put_user(task_pid_vnr(current), current->set_child_tid);
2986 * context_switch - switch to the new MM and the new
2987 * thread's register state.
2989 static inline void
2990 context_switch(struct rq *rq, struct task_struct *prev,
2991 struct task_struct *next)
2993 struct mm_struct *mm, *oldmm;
2995 prepare_task_switch(rq, prev, next);
2996 trace_sched_switch(rq, prev, next);
2997 mm = next->mm;
2998 oldmm = prev->active_mm;
3000 * For paravirt, this is coupled with an exit in switch_to to
3001 * combine the page table reload and the switch backend into
3002 * one hypercall.
3004 arch_enter_lazy_cpu_mode();
3006 if (unlikely(!mm)) {
3007 next->active_mm = oldmm;
3008 atomic_inc(&oldmm->mm_count);
3009 enter_lazy_tlb(oldmm, next);
3010 } else
3011 switch_mm(oldmm, mm, next);
3013 if (unlikely(!prev->mm)) {
3014 prev->active_mm = NULL;
3015 rq->prev_mm = oldmm;
3018 * Since the runqueue lock will be released by the next
3019 * task (which is an invalid locking op but in the case
3020 * of the scheduler it's an obvious special-case), so we
3021 * do an early lockdep release here:
3023 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
3024 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3025 #endif
3027 #ifdef CURRENT_PTR
3028 barrier();
3029 *current_ptr = next;
3030 *current_ti_ptr = next->thread_info;
3031 #endif
3032 /* Here we just switch the register state and the stack. */
3033 switch_to(prev, next, prev);
3035 barrier();
3037 * this_rq must be evaluated again because prev may have moved
3038 * CPUs since it called schedule(), thus the 'rq' on its stack
3039 * frame will be invalid.
3041 finish_task_switch(this_rq(), prev);
3045 * nr_running, nr_uninterruptible and nr_context_switches:
3047 * externally visible scheduler statistics: current number of runnable
3048 * threads, current number of uninterruptible-sleeping threads, total
3049 * number of context switches performed since bootup.
3051 unsigned long nr_running(void)
3053 unsigned long i, sum = 0;
3055 for_each_online_cpu(i)
3056 sum += cpu_rq(i)->nr_running;
3058 return sum;
3061 unsigned long nr_uninterruptible(void)
3063 unsigned long i, sum = 0;
3065 for_each_possible_cpu(i)
3066 sum += cpu_rq(i)->nr_uninterruptible;
3069 * Since we read the counters lockless, it might be slightly
3070 * inaccurate. Do not allow it to go below zero though:
3072 if (unlikely((long)sum < 0))
3073 sum = 0;
3075 return sum;
3078 unsigned long nr_uninterruptible_cpu(int cpu)
3080 return cpu_rq(cpu)->nr_uninterruptible;
3083 unsigned long long nr_context_switches(void)
3085 int i;
3086 unsigned long long sum = 0;
3088 for_each_possible_cpu(i)
3089 sum += cpu_rq(i)->nr_switches;
3091 return sum;
3094 unsigned long nr_iowait(void)
3096 unsigned long i, sum = 0;
3098 for_each_possible_cpu(i)
3099 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3102 * Since we read the counters lockless, it might be slightly
3103 * inaccurate. Do not allow it to go below zero though:
3105 if (unlikely((long)sum < 0))
3106 sum = 0;
3108 return sum;
3111 /* Variables and functions for calc_load */
3112 static atomic_long_t calc_load_tasks;
3113 static unsigned long calc_load_update;
3114 unsigned long avenrun[3];
3115 EXPORT_SYMBOL(avenrun);
3118 * get_avenrun - get the load average array
3119 * @loads: pointer to dest load array
3120 * @offset: offset to add
3121 * @shift: shift count to shift the result left
3123 * These values are estimates at best, so no need for locking.
3125 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3127 loads[0] = (avenrun[0] + offset) << shift;
3128 loads[1] = (avenrun[1] + offset) << shift;
3129 loads[2] = (avenrun[2] + offset) << shift;
3132 static unsigned long
3133 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3135 load *= exp;
3136 load += active * (FIXED_1 - exp);
3137 return load >> FSHIFT;
3141 * calc_load - update the avenrun load estimates 10 ticks after the
3142 * CPUs have updated calc_load_tasks.
3144 void calc_global_load(void)
3146 unsigned long upd = calc_load_update + 10;
3147 long active;
3149 if (time_before(jiffies, upd))
3150 return;
3152 active = atomic_long_read(&calc_load_tasks);
3153 active = active > 0 ? active * FIXED_1 : 0;
3155 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3156 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3157 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3159 calc_load_update += LOAD_FREQ;
3163 * Either called from update_cpu_load() or from a cpu going idle
3165 static void calc_load_account_active(struct rq *this_rq)
3167 long nr_active, delta;
3169 nr_active = this_rq->nr_running;
3170 nr_active += (long) this_rq->nr_uninterruptible;
3172 if (nr_active != this_rq->calc_load_active) {
3173 delta = nr_active - this_rq->calc_load_active;
3174 this_rq->calc_load_active = nr_active;
3175 atomic_long_add(delta, &calc_load_tasks);
3180 * Externally visible per-cpu scheduler statistics:
3181 * cpu_nr_migrations(cpu) - number of migrations into that cpu
3183 u64 cpu_nr_migrations(int cpu)
3185 return cpu_rq(cpu)->nr_migrations_in;
3189 * Update rq->cpu_load[] statistics. This function is usually called every
3190 * scheduler tick (TICK_NSEC).
3192 static void update_cpu_load(struct rq *this_rq)
3194 unsigned long this_load = this_rq->load.weight;
3195 int i, scale;
3197 this_rq->nr_load_updates++;
3199 /* Update our load: */
3200 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3201 unsigned long old_load, new_load;
3203 /* scale is effectively 1 << i now, and >> i divides by scale */
3205 old_load = this_rq->cpu_load[i];
3206 new_load = this_load;
3208 * Round up the averaging division if load is increasing. This
3209 * prevents us from getting stuck on 9 if the load is 10, for
3210 * example.
3212 if (new_load > old_load)
3213 new_load += scale-1;
3214 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3217 if (time_after_eq(jiffies, this_rq->calc_load_update)) {
3218 this_rq->calc_load_update += LOAD_FREQ;
3219 calc_load_account_active(this_rq);
3223 #ifdef CONFIG_SMP
3226 * double_rq_lock - safely lock two runqueues
3228 * Note this does not disable interrupts like task_rq_lock,
3229 * you need to do so manually before calling.
3231 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3232 __acquires(rq1->lock)
3233 __acquires(rq2->lock)
3235 BUG_ON(!irqs_disabled());
3236 if (rq1 == rq2) {
3237 spin_lock(&rq1->lock);
3238 __acquire(rq2->lock); /* Fake it out ;) */
3239 } else {
3240 if (rq1 < rq2) {
3241 spin_lock(&rq1->lock);
3242 spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
3243 } else {
3244 spin_lock(&rq2->lock);
3245 spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
3248 update_rq_clock(rq1);
3249 update_rq_clock(rq2);
3253 * double_rq_unlock - safely unlock two runqueues
3255 * Note this does not restore interrupts like task_rq_unlock,
3256 * you need to do so manually after calling.
3258 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3259 __releases(rq1->lock)
3260 __releases(rq2->lock)
3262 spin_unlock(&rq1->lock);
3263 if (rq1 != rq2)
3264 spin_unlock(&rq2->lock);
3265 else
3266 __release(rq2->lock);
3270 * If dest_cpu is allowed for this process, migrate the task to it.
3271 * This is accomplished by forcing the cpu_allowed mask to only
3272 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3273 * the cpu_allowed mask is restored.
3275 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3277 struct migration_req req;
3278 unsigned long flags;
3279 struct rq *rq;
3281 rq = task_rq_lock(p, &flags);
3282 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed)
3283 || unlikely(!cpu_active(dest_cpu)))
3284 goto out;
3286 /* force the process onto the specified CPU */
3287 if (migrate_task(p, dest_cpu, &req)) {
3288 /* Need to wait for migration thread (might exit: take ref). */
3289 struct task_struct *mt = rq->migration_thread;
3291 get_task_struct(mt);
3292 task_rq_unlock(rq, &flags);
3293 wake_up_process(mt);
3294 put_task_struct(mt);
3295 wait_for_completion(&req.done);
3297 return;
3299 out:
3300 task_rq_unlock(rq, &flags);
3304 * sched_exec - execve() is a valuable balancing opportunity, because at
3305 * this point the task has the smallest effective memory and cache footprint.
3307 void sched_exec(void)
3309 int new_cpu, this_cpu = get_cpu();
3310 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3311 put_cpu();
3312 if (new_cpu != this_cpu)
3313 sched_migrate_task(current, new_cpu);
3317 * pull_task - move a task from a remote runqueue to the local runqueue.
3318 * Both runqueues must be locked.
3320 static void pull_task(struct rq *src_rq, struct task_struct *p,
3321 struct rq *this_rq, int this_cpu)
3323 deactivate_task(src_rq, p, 0);
3324 set_task_cpu(p, this_cpu);
3325 activate_task(this_rq, p, 0);
3327 * Note that idle threads have a prio of MAX_PRIO, for this test
3328 * to be always true for them.
3330 check_preempt_curr(this_rq, p, 0);
3334 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3336 static
3337 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3338 struct sched_domain *sd, enum cpu_idle_type idle,
3339 int *all_pinned)
3341 int tsk_cache_hot = 0;
3343 * We do not migrate tasks that are:
3344 * 1) running (obviously), or
3345 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3346 * 3) are cache-hot on their current CPU.
3348 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
3349 schedstat_inc(p, se.nr_failed_migrations_affine);
3350 return 0;
3352 *all_pinned = 0;
3354 if (task_running(rq, p)) {
3355 schedstat_inc(p, se.nr_failed_migrations_running);
3356 return 0;
3360 * Aggressive migration if:
3361 * 1) task is cache cold, or
3362 * 2) too many balance attempts have failed.
3365 tsk_cache_hot = task_hot(p, rq->clock, sd);
3366 if (!tsk_cache_hot ||
3367 sd->nr_balance_failed > sd->cache_nice_tries) {
3368 #ifdef CONFIG_SCHEDSTATS
3369 if (tsk_cache_hot) {
3370 schedstat_inc(sd, lb_hot_gained[idle]);
3371 schedstat_inc(p, se.nr_forced_migrations);
3373 #endif
3374 return 1;
3377 if (tsk_cache_hot) {
3378 schedstat_inc(p, se.nr_failed_migrations_hot);
3379 return 0;
3381 return 1;
3384 static unsigned long
3385 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3386 unsigned long max_load_move, struct sched_domain *sd,
3387 enum cpu_idle_type idle, int *all_pinned,
3388 int *this_best_prio, struct rq_iterator *iterator)
3390 int loops = 0, pulled = 0, pinned = 0;
3391 struct task_struct *p;
3392 long rem_load_move = max_load_move;
3394 if (max_load_move == 0)
3395 goto out;
3397 pinned = 1;
3400 * Start the load-balancing iterator:
3402 p = iterator->start(iterator->arg);
3403 next:
3404 if (!p || loops++ > sysctl_sched_nr_migrate)
3405 goto out;
3407 if ((p->se.load.weight >> 1) > rem_load_move ||
3408 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3409 p = iterator->next(iterator->arg);
3410 goto next;
3413 pull_task(busiest, p, this_rq, this_cpu);
3414 pulled++;
3415 rem_load_move -= p->se.load.weight;
3417 #ifdef CONFIG_PREEMPT
3419 * NEWIDLE balancing is a source of latency, so preemptible kernels
3420 * will stop after the first task is pulled to minimize the critical
3421 * section.
3423 if (idle == CPU_NEWLY_IDLE)
3424 goto out;
3425 #endif
3428 * We only want to steal up to the prescribed amount of weighted load.
3430 if (rem_load_move > 0) {
3431 if (p->prio < *this_best_prio)
3432 *this_best_prio = p->prio;
3433 p = iterator->next(iterator->arg);
3434 goto next;
3436 out:
3438 * Right now, this is one of only two places pull_task() is called,
3439 * so we can safely collect pull_task() stats here rather than
3440 * inside pull_task().
3442 schedstat_add(sd, lb_gained[idle], pulled);
3444 if (all_pinned)
3445 *all_pinned = pinned;
3447 return max_load_move - rem_load_move;
3451 * move_tasks tries to move up to max_load_move weighted load from busiest to
3452 * this_rq, as part of a balancing operation within domain "sd".
3453 * Returns 1 if successful and 0 otherwise.
3455 * Called with both runqueues locked.
3457 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3458 unsigned long max_load_move,
3459 struct sched_domain *sd, enum cpu_idle_type idle,
3460 int *all_pinned)
3462 const struct sched_class *class = sched_class_highest;
3463 unsigned long total_load_moved = 0;
3464 int this_best_prio = this_rq->curr->prio;
3466 do {
3467 total_load_moved +=
3468 class->load_balance(this_rq, this_cpu, busiest,
3469 max_load_move - total_load_moved,
3470 sd, idle, all_pinned, &this_best_prio);
3471 class = class->next;
3473 #ifdef CONFIG_PREEMPT
3475 * NEWIDLE balancing is a source of latency, so preemptible
3476 * kernels will stop after the first task is pulled to minimize
3477 * the critical section.
3479 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3480 break;
3481 #endif
3482 } while (class && max_load_move > total_load_moved);
3484 return total_load_moved > 0;
3487 static int
3488 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3489 struct sched_domain *sd, enum cpu_idle_type idle,
3490 struct rq_iterator *iterator)
3492 struct task_struct *p = iterator->start(iterator->arg);
3493 int pinned = 0;
3495 while (p) {
3496 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3497 pull_task(busiest, p, this_rq, this_cpu);
3499 * Right now, this is only the second place pull_task()
3500 * is called, so we can safely collect pull_task()
3501 * stats here rather than inside pull_task().
3503 schedstat_inc(sd, lb_gained[idle]);
3505 return 1;
3507 p = iterator->next(iterator->arg);
3510 return 0;
3514 * move_one_task tries to move exactly one task from busiest to this_rq, as
3515 * part of active balancing operations within "domain".
3516 * Returns 1 if successful and 0 otherwise.
3518 * Called with both runqueues locked.
3520 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3521 struct sched_domain *sd, enum cpu_idle_type idle)
3523 const struct sched_class *class;
3525 for (class = sched_class_highest; class; class = class->next)
3526 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3527 return 1;
3529 return 0;
3531 /********** Helpers for find_busiest_group ************************/
3533 * sd_lb_stats - Structure to store the statistics of a sched_domain
3534 * during load balancing.
3536 struct sd_lb_stats {
3537 struct sched_group *busiest; /* Busiest group in this sd */
3538 struct sched_group *this; /* Local group in this sd */
3539 unsigned long total_load; /* Total load of all groups in sd */
3540 unsigned long total_pwr; /* Total power of all groups in sd */
3541 unsigned long avg_load; /* Average load across all groups in sd */
3543 /** Statistics of this group */
3544 unsigned long this_load;
3545 unsigned long this_load_per_task;
3546 unsigned long this_nr_running;
3548 /* Statistics of the busiest group */
3549 unsigned long max_load;
3550 unsigned long busiest_load_per_task;
3551 unsigned long busiest_nr_running;
3553 int group_imb; /* Is there imbalance in this sd */
3554 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3555 int power_savings_balance; /* Is powersave balance needed for this sd */
3556 struct sched_group *group_min; /* Least loaded group in sd */
3557 struct sched_group *group_leader; /* Group which relieves group_min */
3558 unsigned long min_load_per_task; /* load_per_task in group_min */
3559 unsigned long leader_nr_running; /* Nr running of group_leader */
3560 unsigned long min_nr_running; /* Nr running of group_min */
3561 #endif
3565 * sg_lb_stats - stats of a sched_group required for load_balancing
3567 struct sg_lb_stats {
3568 unsigned long avg_load; /*Avg load across the CPUs of the group */
3569 unsigned long group_load; /* Total load over the CPUs of the group */
3570 unsigned long sum_nr_running; /* Nr tasks running in the group */
3571 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3572 unsigned long group_capacity;
3573 int group_imb; /* Is there an imbalance in the group ? */
3577 * group_first_cpu - Returns the first cpu in the cpumask of a sched_group.
3578 * @group: The group whose first cpu is to be returned.
3580 static inline unsigned int group_first_cpu(struct sched_group *group)
3582 return cpumask_first(sched_group_cpus(group));
3586 * get_sd_load_idx - Obtain the load index for a given sched domain.
3587 * @sd: The sched_domain whose load_idx is to be obtained.
3588 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3590 static inline int get_sd_load_idx(struct sched_domain *sd,
3591 enum cpu_idle_type idle)
3593 int load_idx;
3595 switch (idle) {
3596 case CPU_NOT_IDLE:
3597 load_idx = sd->busy_idx;
3598 break;
3600 case CPU_NEWLY_IDLE:
3601 load_idx = sd->newidle_idx;
3602 break;
3603 default:
3604 load_idx = sd->idle_idx;
3605 break;
3608 return load_idx;
3612 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3614 * init_sd_power_savings_stats - Initialize power savings statistics for
3615 * the given sched_domain, during load balancing.
3617 * @sd: Sched domain whose power-savings statistics are to be initialized.
3618 * @sds: Variable containing the statistics for sd.
3619 * @idle: Idle status of the CPU at which we're performing load-balancing.
3621 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3622 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3625 * Busy processors will not participate in power savings
3626 * balance.
3628 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3629 sds->power_savings_balance = 0;
3630 else {
3631 sds->power_savings_balance = 1;
3632 sds->min_nr_running = ULONG_MAX;
3633 sds->leader_nr_running = 0;
3638 * update_sd_power_savings_stats - Update the power saving stats for a
3639 * sched_domain while performing load balancing.
3641 * @group: sched_group belonging to the sched_domain under consideration.
3642 * @sds: Variable containing the statistics of the sched_domain
3643 * @local_group: Does group contain the CPU for which we're performing
3644 * load balancing ?
3645 * @sgs: Variable containing the statistics of the group.
3647 static inline void update_sd_power_savings_stats(struct sched_group *group,
3648 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3651 if (!sds->power_savings_balance)
3652 return;
3655 * If the local group is idle or completely loaded
3656 * no need to do power savings balance at this domain
3658 if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
3659 !sds->this_nr_running))
3660 sds->power_savings_balance = 0;
3663 * If a group is already running at full capacity or idle,
3664 * don't include that group in power savings calculations
3666 if (!sds->power_savings_balance ||
3667 sgs->sum_nr_running >= sgs->group_capacity ||
3668 !sgs->sum_nr_running)
3669 return;
3672 * Calculate the group which has the least non-idle load.
3673 * This is the group from where we need to pick up the load
3674 * for saving power
3676 if ((sgs->sum_nr_running < sds->min_nr_running) ||
3677 (sgs->sum_nr_running == sds->min_nr_running &&
3678 group_first_cpu(group) > group_first_cpu(sds->group_min))) {
3679 sds->group_min = group;
3680 sds->min_nr_running = sgs->sum_nr_running;
3681 sds->min_load_per_task = sgs->sum_weighted_load /
3682 sgs->sum_nr_running;
3686 * Calculate the group which is almost near its
3687 * capacity but still has some space to pick up some load
3688 * from other group and save more power
3690 if (sgs->sum_nr_running > sgs->group_capacity - 1)
3691 return;
3693 if (sgs->sum_nr_running > sds->leader_nr_running ||
3694 (sgs->sum_nr_running == sds->leader_nr_running &&
3695 group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
3696 sds->group_leader = group;
3697 sds->leader_nr_running = sgs->sum_nr_running;
3702 * check_power_save_busiest_group - Check if we have potential to perform
3703 * some power-savings balance. If yes, set the busiest group to be
3704 * the least loaded group in the sched_domain, so that it's CPUs can
3705 * be put to idle.
3707 * @sds: Variable containing the statistics of the sched_domain
3708 * under consideration.
3709 * @this_cpu: Cpu at which we're currently performing load-balancing.
3710 * @imbalance: Variable to store the imbalance.
3712 * Returns 1 if there is potential to perform power-savings balance.
3713 * Else returns 0.
3715 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3716 int this_cpu, unsigned long *imbalance)
3718 if (!sds->power_savings_balance)
3719 return 0;
3721 if (sds->this != sds->group_leader ||
3722 sds->group_leader == sds->group_min)
3723 return 0;
3725 *imbalance = sds->min_load_per_task;
3726 sds->busiest = sds->group_min;
3728 if (sched_mc_power_savings >= POWERSAVINGS_BALANCE_WAKEUP) {
3729 cpu_rq(this_cpu)->rd->sched_mc_preferred_wakeup_cpu =
3730 group_first_cpu(sds->group_leader);
3733 return 1;
3736 #else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3737 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3738 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3740 return;
3743 static inline void update_sd_power_savings_stats(struct sched_group *group,
3744 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3746 return;
3749 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3750 int this_cpu, unsigned long *imbalance)
3752 return 0;
3754 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3758 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
3759 * @group: sched_group whose statistics are to be updated.
3760 * @this_cpu: Cpu for which load balance is currently performed.
3761 * @idle: Idle status of this_cpu
3762 * @load_idx: Load index of sched_domain of this_cpu for load calc.
3763 * @sd_idle: Idle status of the sched_domain containing group.
3764 * @local_group: Does group contain this_cpu.
3765 * @cpus: Set of cpus considered for load balancing.
3766 * @balance: Should we balance.
3767 * @sgs: variable to hold the statistics for this group.
3769 static inline void update_sg_lb_stats(struct sched_group *group, int this_cpu,
3770 enum cpu_idle_type idle, int load_idx, int *sd_idle,
3771 int local_group, const struct cpumask *cpus,
3772 int *balance, struct sg_lb_stats *sgs)
3774 unsigned long load, max_cpu_load, min_cpu_load;
3775 int i;
3776 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3777 unsigned long sum_avg_load_per_task;
3778 unsigned long avg_load_per_task;
3780 if (local_group)
3781 balance_cpu = group_first_cpu(group);
3783 /* Tally up the load of all CPUs in the group */
3784 sum_avg_load_per_task = avg_load_per_task = 0;
3785 max_cpu_load = 0;
3786 min_cpu_load = ~0UL;
3788 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
3789 struct rq *rq = cpu_rq(i);
3791 if (*sd_idle && rq->nr_running)
3792 *sd_idle = 0;
3794 /* Bias balancing toward cpus of our domain */
3795 if (local_group) {
3796 if (idle_cpu(i) && !first_idle_cpu) {
3797 first_idle_cpu = 1;
3798 balance_cpu = i;
3801 load = target_load(i, load_idx);
3802 } else {
3803 load = source_load(i, load_idx);
3804 if (load > max_cpu_load)
3805 max_cpu_load = load;
3806 if (min_cpu_load > load)
3807 min_cpu_load = load;
3810 sgs->group_load += load;
3811 sgs->sum_nr_running += rq->nr_running;
3812 sgs->sum_weighted_load += weighted_cpuload(i);
3814 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3818 * First idle cpu or the first cpu(busiest) in this sched group
3819 * is eligible for doing load balancing at this and above
3820 * domains. In the newly idle case, we will allow all the cpu's
3821 * to do the newly idle load balance.
3823 if (idle != CPU_NEWLY_IDLE && local_group &&
3824 balance_cpu != this_cpu && balance) {
3825 *balance = 0;
3826 return;
3829 /* Adjust by relative CPU power of the group */
3830 sgs->avg_load = sg_div_cpu_power(group,
3831 sgs->group_load * SCHED_LOAD_SCALE);
3835 * Consider the group unbalanced when the imbalance is larger
3836 * than the average weight of two tasks.
3838 * APZ: with cgroup the avg task weight can vary wildly and
3839 * might not be a suitable number - should we keep a
3840 * normalized nr_running number somewhere that negates
3841 * the hierarchy?
3843 avg_load_per_task = sg_div_cpu_power(group,
3844 sum_avg_load_per_task * SCHED_LOAD_SCALE);
3846 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3847 sgs->group_imb = 1;
3849 sgs->group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3854 * update_sd_lb_stats - Update sched_group's statistics for load balancing.
3855 * @sd: sched_domain whose statistics are to be updated.
3856 * @this_cpu: Cpu for which load balance is currently performed.
3857 * @idle: Idle status of this_cpu
3858 * @sd_idle: Idle status of the sched_domain containing group.
3859 * @cpus: Set of cpus considered for load balancing.
3860 * @balance: Should we balance.
3861 * @sds: variable to hold the statistics for this sched_domain.
3863 static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
3864 enum cpu_idle_type idle, int *sd_idle,
3865 const struct cpumask *cpus, int *balance,
3866 struct sd_lb_stats *sds)
3868 struct sched_group *group = sd->groups;
3869 struct sg_lb_stats sgs;
3870 int load_idx;
3872 init_sd_power_savings_stats(sd, sds, idle);
3873 load_idx = get_sd_load_idx(sd, idle);
3875 do {
3876 int local_group;
3878 local_group = cpumask_test_cpu(this_cpu,
3879 sched_group_cpus(group));
3880 memset(&sgs, 0, sizeof(sgs));
3881 update_sg_lb_stats(group, this_cpu, idle, load_idx, sd_idle,
3882 local_group, cpus, balance, &sgs);
3884 if (local_group && balance && !(*balance))
3885 return;
3887 sds->total_load += sgs.group_load;
3888 sds->total_pwr += group->__cpu_power;
3890 if (local_group) {
3891 sds->this_load = sgs.avg_load;
3892 sds->this = group;
3893 sds->this_nr_running = sgs.sum_nr_running;
3894 sds->this_load_per_task = sgs.sum_weighted_load;
3895 } else if (sgs.avg_load > sds->max_load &&
3896 (sgs.sum_nr_running > sgs.group_capacity ||
3897 sgs.group_imb)) {
3898 sds->max_load = sgs.avg_load;
3899 sds->busiest = group;
3900 sds->busiest_nr_running = sgs.sum_nr_running;
3901 sds->busiest_load_per_task = sgs.sum_weighted_load;
3902 sds->group_imb = sgs.group_imb;
3905 update_sd_power_savings_stats(group, sds, local_group, &sgs);
3906 group = group->next;
3907 } while (group != sd->groups);
3912 * fix_small_imbalance - Calculate the minor imbalance that exists
3913 * amongst the groups of a sched_domain, during
3914 * load balancing.
3915 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
3916 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
3917 * @imbalance: Variable to store the imbalance.
3919 static inline void fix_small_imbalance(struct sd_lb_stats *sds,
3920 int this_cpu, unsigned long *imbalance)
3922 unsigned long tmp, pwr_now = 0, pwr_move = 0;
3923 unsigned int imbn = 2;
3925 if (sds->this_nr_running) {
3926 sds->this_load_per_task /= sds->this_nr_running;
3927 if (sds->busiest_load_per_task >
3928 sds->this_load_per_task)
3929 imbn = 1;
3930 } else
3931 sds->this_load_per_task =
3932 cpu_avg_load_per_task(this_cpu);
3934 if (sds->max_load - sds->this_load + sds->busiest_load_per_task >=
3935 sds->busiest_load_per_task * imbn) {
3936 *imbalance = sds->busiest_load_per_task;
3937 return;
3941 * OK, we don't have enough imbalance to justify moving tasks,
3942 * however we may be able to increase total CPU power used by
3943 * moving them.
3946 pwr_now += sds->busiest->__cpu_power *
3947 min(sds->busiest_load_per_task, sds->max_load);
3948 pwr_now += sds->this->__cpu_power *
3949 min(sds->this_load_per_task, sds->this_load);
3950 pwr_now /= SCHED_LOAD_SCALE;
3952 /* Amount of load we'd subtract */
3953 tmp = sg_div_cpu_power(sds->busiest,
3954 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3955 if (sds->max_load > tmp)
3956 pwr_move += sds->busiest->__cpu_power *
3957 min(sds->busiest_load_per_task, sds->max_load - tmp);
3959 /* Amount of load we'd add */
3960 if (sds->max_load * sds->busiest->__cpu_power <
3961 sds->busiest_load_per_task * SCHED_LOAD_SCALE)
3962 tmp = sg_div_cpu_power(sds->this,
3963 sds->max_load * sds->busiest->__cpu_power);
3964 else
3965 tmp = sg_div_cpu_power(sds->this,
3966 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3967 pwr_move += sds->this->__cpu_power *
3968 min(sds->this_load_per_task, sds->this_load + tmp);
3969 pwr_move /= SCHED_LOAD_SCALE;
3971 /* Move if we gain throughput */
3972 if (pwr_move > pwr_now)
3973 *imbalance = sds->busiest_load_per_task;
3977 * calculate_imbalance - Calculate the amount of imbalance present within the
3978 * groups of a given sched_domain during load balance.
3979 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
3980 * @this_cpu: Cpu for which currently load balance is being performed.
3981 * @imbalance: The variable to store the imbalance.
3983 static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
3984 unsigned long *imbalance)
3986 unsigned long max_pull;
3988 * In the presence of smp nice balancing, certain scenarios can have
3989 * max load less than avg load(as we skip the groups at or below
3990 * its cpu_power, while calculating max_load..)
3992 if (sds->max_load < sds->avg_load) {
3993 *imbalance = 0;
3994 return fix_small_imbalance(sds, this_cpu, imbalance);
3997 /* Don't want to pull so many tasks that a group would go idle */
3998 max_pull = min(sds->max_load - sds->avg_load,
3999 sds->max_load - sds->busiest_load_per_task);
4001 /* How much load to actually move to equalise the imbalance */
4002 *imbalance = min(max_pull * sds->busiest->__cpu_power,
4003 (sds->avg_load - sds->this_load) * sds->this->__cpu_power)
4004 / SCHED_LOAD_SCALE;
4007 * if *imbalance is less than the average load per runnable task
4008 * there is no gaurantee that any tasks will be moved so we'll have
4009 * a think about bumping its value to force at least one task to be
4010 * moved
4012 if (*imbalance < sds->busiest_load_per_task)
4013 return fix_small_imbalance(sds, this_cpu, imbalance);
4016 /******* find_busiest_group() helpers end here *********************/
4019 * find_busiest_group - Returns the busiest group within the sched_domain
4020 * if there is an imbalance. If there isn't an imbalance, and
4021 * the user has opted for power-savings, it returns a group whose
4022 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
4023 * such a group exists.
4025 * Also calculates the amount of weighted load which should be moved
4026 * to restore balance.
4028 * @sd: The sched_domain whose busiest group is to be returned.
4029 * @this_cpu: The cpu for which load balancing is currently being performed.
4030 * @imbalance: Variable which stores amount of weighted load which should
4031 * be moved to restore balance/put a group to idle.
4032 * @idle: The idle status of this_cpu.
4033 * @sd_idle: The idleness of sd
4034 * @cpus: The set of CPUs under consideration for load-balancing.
4035 * @balance: Pointer to a variable indicating if this_cpu
4036 * is the appropriate cpu to perform load balancing at this_level.
4038 * Returns: - the busiest group if imbalance exists.
4039 * - If no imbalance and user has opted for power-savings balance,
4040 * return the least loaded group whose CPUs can be
4041 * put to idle by rebalancing its tasks onto our group.
4043 static struct sched_group *
4044 find_busiest_group(struct sched_domain *sd, int this_cpu,
4045 unsigned long *imbalance, enum cpu_idle_type idle,
4046 int *sd_idle, const struct cpumask *cpus, int *balance)
4048 struct sd_lb_stats sds;
4050 memset(&sds, 0, sizeof(sds));
4053 * Compute the various statistics relavent for load balancing at
4054 * this level.
4056 update_sd_lb_stats(sd, this_cpu, idle, sd_idle, cpus,
4057 balance, &sds);
4059 /* Cases where imbalance does not exist from POV of this_cpu */
4060 /* 1) this_cpu is not the appropriate cpu to perform load balancing
4061 * at this level.
4062 * 2) There is no busy sibling group to pull from.
4063 * 3) This group is the busiest group.
4064 * 4) This group is more busy than the avg busieness at this
4065 * sched_domain.
4066 * 5) The imbalance is within the specified limit.
4067 * 6) Any rebalance would lead to ping-pong
4069 if (balance && !(*balance))
4070 goto ret;
4072 if (!sds.busiest || sds.busiest_nr_running == 0)
4073 goto out_balanced;
4075 if (sds.this_load >= sds.max_load)
4076 goto out_balanced;
4078 sds.avg_load = (SCHED_LOAD_SCALE * sds.total_load) / sds.total_pwr;
4080 if (sds.this_load >= sds.avg_load)
4081 goto out_balanced;
4083 if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
4084 goto out_balanced;
4086 sds.busiest_load_per_task /= sds.busiest_nr_running;
4087 if (sds.group_imb)
4088 sds.busiest_load_per_task =
4089 min(sds.busiest_load_per_task, sds.avg_load);
4092 * We're trying to get all the cpus to the average_load, so we don't
4093 * want to push ourselves above the average load, nor do we wish to
4094 * reduce the max loaded cpu below the average load, as either of these
4095 * actions would just result in more rebalancing later, and ping-pong
4096 * tasks around. Thus we look for the minimum possible imbalance.
4097 * Negative imbalances (*we* are more loaded than anyone else) will
4098 * be counted as no imbalance for these purposes -- we can't fix that
4099 * by pulling tasks to us. Be careful of negative numbers as they'll
4100 * appear as very large values with unsigned longs.
4102 if (sds.max_load <= sds.busiest_load_per_task)
4103 goto out_balanced;
4105 /* Looks like there is an imbalance. Compute it */
4106 calculate_imbalance(&sds, this_cpu, imbalance);
4107 return sds.busiest;
4109 out_balanced:
4111 * There is no obvious imbalance. But check if we can do some balancing
4112 * to save power.
4114 if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
4115 return sds.busiest;
4116 ret:
4117 *imbalance = 0;
4118 return NULL;
4122 * find_busiest_queue - find the busiest runqueue among the cpus in group.
4124 static struct rq *
4125 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
4126 unsigned long imbalance, const struct cpumask *cpus)
4128 struct rq *busiest = NULL, *rq;
4129 unsigned long max_load = 0;
4130 int i;
4132 for_each_cpu(i, sched_group_cpus(group)) {
4133 unsigned long wl;
4135 if (!cpumask_test_cpu(i, cpus))
4136 continue;
4138 rq = cpu_rq(i);
4139 wl = weighted_cpuload(i);
4141 if (rq->nr_running == 1 && wl > imbalance)
4142 continue;
4144 if (wl > max_load) {
4145 max_load = wl;
4146 busiest = rq;
4150 return busiest;
4154 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4155 * so long as it is large enough.
4157 #define MAX_PINNED_INTERVAL 512
4159 /* Working cpumask for load_balance and load_balance_newidle. */
4160 static DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
4163 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4164 * tasks if there is an imbalance.
4166 static int load_balance(int this_cpu, struct rq *this_rq,
4167 struct sched_domain *sd, enum cpu_idle_type idle,
4168 int *balance)
4170 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
4171 struct sched_group *group;
4172 unsigned long imbalance;
4173 struct rq *busiest;
4174 unsigned long flags;
4175 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4177 cpumask_setall(cpus);
4180 * When power savings policy is enabled for the parent domain, idle
4181 * sibling can pick up load irrespective of busy siblings. In this case,
4182 * let the state of idle sibling percolate up as CPU_IDLE, instead of
4183 * portraying it as CPU_NOT_IDLE.
4185 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
4186 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4187 sd_idle = 1;
4189 schedstat_inc(sd, lb_count[idle]);
4191 redo:
4192 update_shares(sd);
4193 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
4194 cpus, balance);
4196 if (*balance == 0)
4197 goto out_balanced;
4199 if (!group) {
4200 schedstat_inc(sd, lb_nobusyg[idle]);
4201 goto out_balanced;
4204 busiest = find_busiest_queue(group, idle, imbalance, cpus);
4205 if (!busiest) {
4206 schedstat_inc(sd, lb_nobusyq[idle]);
4207 goto out_balanced;
4210 BUG_ON(busiest == this_rq);
4212 schedstat_add(sd, lb_imbalance[idle], imbalance);
4214 ld_moved = 0;
4215 if (busiest->nr_running > 1) {
4217 * Attempt to move tasks. If find_busiest_group has found
4218 * an imbalance but busiest->nr_running <= 1, the group is
4219 * still unbalanced. ld_moved simply stays zero, so it is
4220 * correctly treated as an imbalance.
4222 local_irq_save(flags);
4223 double_rq_lock(this_rq, busiest);
4224 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4225 imbalance, sd, idle, &all_pinned);
4226 double_rq_unlock(this_rq, busiest);
4227 local_irq_restore(flags);
4230 * some other cpu did the load balance for us.
4232 if (ld_moved && this_cpu != smp_processor_id())
4233 resched_cpu(this_cpu);
4235 /* All tasks on this runqueue were pinned by CPU affinity */
4236 if (unlikely(all_pinned)) {
4237 cpumask_clear_cpu(cpu_of(busiest), cpus);
4238 if (!cpumask_empty(cpus))
4239 goto redo;
4240 goto out_balanced;
4244 if (!ld_moved) {
4245 schedstat_inc(sd, lb_failed[idle]);
4246 sd->nr_balance_failed++;
4248 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
4250 spin_lock_irqsave(&busiest->lock, flags);
4252 /* don't kick the migration_thread, if the curr
4253 * task on busiest cpu can't be moved to this_cpu
4255 if (!cpumask_test_cpu(this_cpu,
4256 &busiest->curr->cpus_allowed)) {
4257 spin_unlock_irqrestore(&busiest->lock, flags);
4258 all_pinned = 1;
4259 goto out_one_pinned;
4262 if (!busiest->active_balance) {
4263 busiest->active_balance = 1;
4264 busiest->push_cpu = this_cpu;
4265 active_balance = 1;
4267 spin_unlock_irqrestore(&busiest->lock, flags);
4268 if (active_balance)
4269 wake_up_process(busiest->migration_thread);
4272 * We've kicked active balancing, reset the failure
4273 * counter.
4275 sd->nr_balance_failed = sd->cache_nice_tries+1;
4277 } else
4278 sd->nr_balance_failed = 0;
4280 if (likely(!active_balance)) {
4281 /* We were unbalanced, so reset the balancing interval */
4282 sd->balance_interval = sd->min_interval;
4283 } else {
4285 * If we've begun active balancing, start to back off. This
4286 * case may not be covered by the all_pinned logic if there
4287 * is only 1 task on the busy runqueue (because we don't call
4288 * move_tasks).
4290 if (sd->balance_interval < sd->max_interval)
4291 sd->balance_interval *= 2;
4294 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4295 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4296 ld_moved = -1;
4298 goto out;
4300 out_balanced:
4301 schedstat_inc(sd, lb_balanced[idle]);
4303 sd->nr_balance_failed = 0;
4305 out_one_pinned:
4306 /* tune up the balancing interval */
4307 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
4308 (sd->balance_interval < sd->max_interval))
4309 sd->balance_interval *= 2;
4311 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4312 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4313 ld_moved = -1;
4314 else
4315 ld_moved = 0;
4316 out:
4317 if (ld_moved)
4318 update_shares(sd);
4319 return ld_moved;
4323 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4324 * tasks if there is an imbalance.
4326 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
4327 * this_rq is locked.
4329 static int
4330 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
4332 struct sched_group *group;
4333 struct rq *busiest = NULL;
4334 unsigned long imbalance;
4335 int ld_moved = 0;
4336 int sd_idle = 0;
4337 int all_pinned = 0;
4338 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4340 cpumask_setall(cpus);
4343 * When power savings policy is enabled for the parent domain, idle
4344 * sibling can pick up load irrespective of busy siblings. In this case,
4345 * let the state of idle sibling percolate up as IDLE, instead of
4346 * portraying it as CPU_NOT_IDLE.
4348 if (sd->flags & SD_SHARE_CPUPOWER &&
4349 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4350 sd_idle = 1;
4352 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
4353 redo:
4354 update_shares_locked(this_rq, sd);
4355 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
4356 &sd_idle, cpus, NULL);
4357 if (!group) {
4358 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
4359 goto out_balanced;
4362 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
4363 if (!busiest) {
4364 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
4365 goto out_balanced;
4368 BUG_ON(busiest == this_rq);
4370 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
4372 ld_moved = 0;
4373 if (busiest->nr_running > 1) {
4374 /* Attempt to move tasks */
4375 double_lock_balance(this_rq, busiest);
4376 /* this_rq->clock is already updated */
4377 update_rq_clock(busiest);
4378 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4379 imbalance, sd, CPU_NEWLY_IDLE,
4380 &all_pinned);
4381 double_unlock_balance(this_rq, busiest);
4383 if (unlikely(all_pinned)) {
4384 cpumask_clear_cpu(cpu_of(busiest), cpus);
4385 if (!cpumask_empty(cpus))
4386 goto redo;
4390 if (!ld_moved) {
4391 int active_balance = 0;
4393 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
4394 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4395 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4396 return -1;
4398 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
4399 return -1;
4401 if (sd->nr_balance_failed++ < 2)
4402 return -1;
4405 * The only task running in a non-idle cpu can be moved to this
4406 * cpu in an attempt to completely freeup the other CPU
4407 * package. The same method used to move task in load_balance()
4408 * have been extended for load_balance_newidle() to speedup
4409 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
4411 * The package power saving logic comes from
4412 * find_busiest_group(). If there are no imbalance, then
4413 * f_b_g() will return NULL. However when sched_mc={1,2} then
4414 * f_b_g() will select a group from which a running task may be
4415 * pulled to this cpu in order to make the other package idle.
4416 * If there is no opportunity to make a package idle and if
4417 * there are no imbalance, then f_b_g() will return NULL and no
4418 * action will be taken in load_balance_newidle().
4420 * Under normal task pull operation due to imbalance, there
4421 * will be more than one task in the source run queue and
4422 * move_tasks() will succeed. ld_moved will be true and this
4423 * active balance code will not be triggered.
4426 /* Lock busiest in correct order while this_rq is held */
4427 double_lock_balance(this_rq, busiest);
4430 * don't kick the migration_thread, if the curr
4431 * task on busiest cpu can't be moved to this_cpu
4433 if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
4434 double_unlock_balance(this_rq, busiest);
4435 all_pinned = 1;
4436 return ld_moved;
4439 if (!busiest->active_balance) {
4440 busiest->active_balance = 1;
4441 busiest->push_cpu = this_cpu;
4442 active_balance = 1;
4445 double_unlock_balance(this_rq, busiest);
4447 * Should not call ttwu while holding a rq->lock
4449 spin_unlock(&this_rq->lock);
4450 if (active_balance)
4451 wake_up_process(busiest->migration_thread);
4452 spin_lock(&this_rq->lock);
4454 } else
4455 sd->nr_balance_failed = 0;
4457 update_shares_locked(this_rq, sd);
4458 return ld_moved;
4460 out_balanced:
4461 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
4462 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4463 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4464 return -1;
4465 sd->nr_balance_failed = 0;
4467 return 0;
4471 * idle_balance is called by schedule() if this_cpu is about to become
4472 * idle. Attempts to pull tasks from other CPUs.
4474 static void idle_balance(int this_cpu, struct rq *this_rq)
4476 struct sched_domain *sd;
4477 int pulled_task = 0;
4478 unsigned long next_balance = jiffies + HZ;
4480 for_each_domain(this_cpu, sd) {
4481 unsigned long interval;
4483 if (!(sd->flags & SD_LOAD_BALANCE))
4484 continue;
4486 if (sd->flags & SD_BALANCE_NEWIDLE)
4487 /* If we've pulled tasks over stop searching: */
4488 pulled_task = load_balance_newidle(this_cpu, this_rq,
4489 sd);
4491 interval = msecs_to_jiffies(sd->balance_interval);
4492 if (time_after(next_balance, sd->last_balance + interval))
4493 next_balance = sd->last_balance + interval;
4494 if (pulled_task)
4495 break;
4497 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4499 * We are going idle. next_balance may be set based on
4500 * a busy processor. So reset next_balance.
4502 this_rq->next_balance = next_balance;
4507 * active_load_balance is run by migration threads. It pushes running tasks
4508 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4509 * running on each physical CPU where possible, and avoids physical /
4510 * logical imbalances.
4512 * Called with busiest_rq locked.
4514 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4516 int target_cpu = busiest_rq->push_cpu;
4517 struct sched_domain *sd;
4518 struct rq *target_rq;
4520 /* Is there any task to move? */
4521 if (busiest_rq->nr_running <= 1)
4522 return;
4524 target_rq = cpu_rq(target_cpu);
4527 * This condition is "impossible", if it occurs
4528 * we need to fix it. Originally reported by
4529 * Bjorn Helgaas on a 128-cpu setup.
4531 BUG_ON(busiest_rq == target_rq);
4533 /* move a task from busiest_rq to target_rq */
4534 double_lock_balance(busiest_rq, target_rq);
4535 update_rq_clock(busiest_rq);
4536 update_rq_clock(target_rq);
4538 /* Search for an sd spanning us and the target CPU. */
4539 for_each_domain(target_cpu, sd) {
4540 if ((sd->flags & SD_LOAD_BALANCE) &&
4541 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4542 break;
4545 if (likely(sd)) {
4546 schedstat_inc(sd, alb_count);
4548 if (move_one_task(target_rq, target_cpu, busiest_rq,
4549 sd, CPU_IDLE))
4550 schedstat_inc(sd, alb_pushed);
4551 else
4552 schedstat_inc(sd, alb_failed);
4554 double_unlock_balance(busiest_rq, target_rq);
4557 #ifdef CONFIG_NO_HZ
4558 static struct {
4559 atomic_t load_balancer;
4560 cpumask_var_t cpu_mask;
4561 } nohz ____cacheline_aligned = {
4562 .load_balancer = ATOMIC_INIT(-1),
4566 * This routine will try to nominate the ilb (idle load balancing)
4567 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4568 * load balancing on behalf of all those cpus. If all the cpus in the system
4569 * go into this tickless mode, then there will be no ilb owner (as there is
4570 * no need for one) and all the cpus will sleep till the next wakeup event
4571 * arrives...
4573 * For the ilb owner, tick is not stopped. And this tick will be used
4574 * for idle load balancing. ilb owner will still be part of
4575 * nohz.cpu_mask..
4577 * While stopping the tick, this cpu will become the ilb owner if there
4578 * is no other owner. And will be the owner till that cpu becomes busy
4579 * or if all cpus in the system stop their ticks at which point
4580 * there is no need for ilb owner.
4582 * When the ilb owner becomes busy, it nominates another owner, during the
4583 * next busy scheduler_tick()
4585 int select_nohz_load_balancer(int stop_tick)
4587 int cpu = smp_processor_id();
4589 if (stop_tick) {
4590 cpu_rq(cpu)->in_nohz_recently = 1;
4592 if (!cpu_active(cpu)) {
4593 if (atomic_read(&nohz.load_balancer) != cpu)
4594 return 0;
4597 * If we are going offline and still the leader,
4598 * give up!
4600 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4601 BUG();
4603 return 0;
4606 cpumask_set_cpu(cpu, nohz.cpu_mask);
4608 /* time for ilb owner also to sleep */
4609 if (cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4610 if (atomic_read(&nohz.load_balancer) == cpu)
4611 atomic_set(&nohz.load_balancer, -1);
4612 return 0;
4615 if (atomic_read(&nohz.load_balancer) == -1) {
4616 /* make me the ilb owner */
4617 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4618 return 1;
4619 } else if (atomic_read(&nohz.load_balancer) == cpu)
4620 return 1;
4621 } else {
4622 if (!cpumask_test_cpu(cpu, nohz.cpu_mask))
4623 return 0;
4625 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4627 if (atomic_read(&nohz.load_balancer) == cpu)
4628 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4629 BUG();
4631 return 0;
4633 #endif
4635 static DEFINE_SPINLOCK(balancing);
4638 * It checks each scheduling domain to see if it is due to be balanced,
4639 * and initiates a balancing operation if so.
4641 * Balancing parameters are set up in arch_init_sched_domains.
4643 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4645 int balance = 1;
4646 struct rq *rq = cpu_rq(cpu);
4647 unsigned long interval;
4648 struct sched_domain *sd;
4649 /* Earliest time when we have to do rebalance again */
4650 unsigned long next_balance = jiffies + 60*HZ;
4651 int update_next_balance = 0;
4652 int need_serialize;
4654 for_each_domain(cpu, sd) {
4655 if (!(sd->flags & SD_LOAD_BALANCE))
4656 continue;
4658 interval = sd->balance_interval;
4659 if (idle != CPU_IDLE)
4660 interval *= sd->busy_factor;
4662 /* scale ms to jiffies */
4663 interval = msecs_to_jiffies(interval);
4664 if (unlikely(!interval))
4665 interval = 1;
4666 if (interval > HZ*NR_CPUS/10)
4667 interval = HZ*NR_CPUS/10;
4669 need_serialize = sd->flags & SD_SERIALIZE;
4671 if (need_serialize) {
4672 if (!spin_trylock(&balancing))
4673 goto out;
4676 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4677 if (load_balance(cpu, rq, sd, idle, &balance)) {
4679 * We've pulled tasks over so either we're no
4680 * longer idle, or one of our SMT siblings is
4681 * not idle.
4683 idle = CPU_NOT_IDLE;
4685 sd->last_balance = jiffies;
4687 if (need_serialize)
4688 spin_unlock(&balancing);
4689 out:
4690 if (time_after(next_balance, sd->last_balance + interval)) {
4691 next_balance = sd->last_balance + interval;
4692 update_next_balance = 1;
4696 * Stop the load balance at this level. There is another
4697 * CPU in our sched group which is doing load balancing more
4698 * actively.
4700 if (!balance)
4701 break;
4705 * next_balance will be updated only when there is a need.
4706 * When the cpu is attached to null domain for ex, it will not be
4707 * updated.
4709 if (likely(update_next_balance))
4710 rq->next_balance = next_balance;
4714 * run_rebalance_domains is triggered when needed from the scheduler tick.
4715 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4716 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4718 static void run_rebalance_domains(struct softirq_action *h)
4720 int this_cpu = raw_smp_processor_id();
4721 struct rq *this_rq = cpu_rq(this_cpu);
4722 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4723 CPU_IDLE : CPU_NOT_IDLE;
4725 rebalance_domains(this_cpu, idle);
4727 #ifdef CONFIG_NO_HZ
4729 * If this cpu is the owner for idle load balancing, then do the
4730 * balancing on behalf of the other idle cpus whose ticks are
4731 * stopped.
4733 if (this_rq->idle_at_tick &&
4734 atomic_read(&nohz.load_balancer) == this_cpu) {
4735 struct rq *rq;
4736 int balance_cpu;
4738 for_each_cpu(balance_cpu, nohz.cpu_mask) {
4739 if (balance_cpu == this_cpu)
4740 continue;
4743 * If this cpu gets work to do, stop the load balancing
4744 * work being done for other cpus. Next load
4745 * balancing owner will pick it up.
4747 if (need_resched())
4748 break;
4750 rebalance_domains(balance_cpu, CPU_IDLE);
4752 rq = cpu_rq(balance_cpu);
4753 if (time_after(this_rq->next_balance, rq->next_balance))
4754 this_rq->next_balance = rq->next_balance;
4757 #endif
4760 static inline int on_null_domain(int cpu)
4762 return !rcu_dereference(cpu_rq(cpu)->sd);
4766 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4768 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4769 * idle load balancing owner or decide to stop the periodic load balancing,
4770 * if the whole system is idle.
4772 static inline void trigger_load_balance(struct rq *rq, int cpu)
4774 #ifdef CONFIG_NO_HZ
4776 * If we were in the nohz mode recently and busy at the current
4777 * scheduler tick, then check if we need to nominate new idle
4778 * load balancer.
4780 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4781 rq->in_nohz_recently = 0;
4783 if (atomic_read(&nohz.load_balancer) == cpu) {
4784 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4785 atomic_set(&nohz.load_balancer, -1);
4788 if (atomic_read(&nohz.load_balancer) == -1) {
4790 * simple selection for now: Nominate the
4791 * first cpu in the nohz list to be the next
4792 * ilb owner.
4794 * TBD: Traverse the sched domains and nominate
4795 * the nearest cpu in the nohz.cpu_mask.
4797 int ilb = cpumask_first(nohz.cpu_mask);
4799 if (ilb < nr_cpu_ids)
4800 resched_cpu(ilb);
4805 * If this cpu is idle and doing idle load balancing for all the
4806 * cpus with ticks stopped, is it time for that to stop?
4808 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4809 cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4810 resched_cpu(cpu);
4811 return;
4815 * If this cpu is idle and the idle load balancing is done by
4816 * someone else, then no need raise the SCHED_SOFTIRQ
4818 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4819 cpumask_test_cpu(cpu, nohz.cpu_mask))
4820 return;
4821 #endif
4822 /* Don't need to rebalance while attached to NULL domain */
4823 if (time_after_eq(jiffies, rq->next_balance) &&
4824 likely(!on_null_domain(cpu)))
4825 raise_softirq(SCHED_SOFTIRQ);
4828 #else /* CONFIG_SMP */
4831 * on UP we do not need to balance between CPUs:
4833 static inline void idle_balance(int cpu, struct rq *rq)
4837 #endif
4839 DEFINE_PER_CPU(struct kernel_stat, kstat);
4841 EXPORT_PER_CPU_SYMBOL(kstat);
4844 * Return any ns on the sched_clock that have not yet been accounted in
4845 * @p in case that task is currently running.
4847 * Called with task_rq_lock() held on @rq.
4849 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
4851 u64 ns = 0;
4853 if (task_current(rq, p)) {
4854 update_rq_clock(rq);
4855 ns = rq->clock - p->se.exec_start;
4856 if ((s64)ns < 0)
4857 ns = 0;
4860 return ns;
4863 unsigned long long __task_delta_exec(struct task_struct *p, int update)
4865 s64 delta_exec;
4866 struct rq *rq;
4868 rq = task_rq(p);
4869 WARN_ON_ONCE(!runqueue_is_locked());
4870 WARN_ON_ONCE(!task_current(rq, p));
4872 if (update)
4873 update_rq_clock(rq);
4875 delta_exec = rq->clock - p->se.exec_start;
4877 WARN_ON_ONCE(delta_exec < 0);
4879 return delta_exec;
4883 * Return any ns on the sched_clock that have not yet been banked in
4884 * @p in case that task is currently running.
4886 unsigned long long task_delta_exec(struct task_struct *p)
4888 unsigned long flags;
4889 struct rq *rq;
4890 u64 ns = 0;
4892 rq = task_rq_lock(p, &flags);
4893 ns = do_task_delta_exec(p, rq);
4894 task_rq_unlock(rq, &flags);
4896 return ns;
4900 * Return accounted runtime for the task.
4901 * In case the task is currently running, return the runtime plus current's
4902 * pending runtime that have not been accounted yet.
4904 unsigned long long task_sched_runtime(struct task_struct *p)
4906 unsigned long flags;
4907 struct rq *rq;
4908 u64 ns = 0;
4910 rq = task_rq_lock(p, &flags);
4911 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
4912 task_rq_unlock(rq, &flags);
4914 return ns;
4918 * Return sum_exec_runtime for the thread group.
4919 * In case the task is currently running, return the sum plus current's
4920 * pending runtime that have not been accounted yet.
4922 * Note that the thread group might have other running tasks as well,
4923 * so the return value not includes other pending runtime that other
4924 * running tasks might have.
4926 unsigned long long thread_group_sched_runtime(struct task_struct *p)
4928 struct task_cputime totals;
4929 unsigned long flags;
4930 struct rq *rq;
4931 u64 ns;
4933 rq = task_rq_lock(p, &flags);
4934 thread_group_cputime(p, &totals);
4935 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
4936 task_rq_unlock(rq, &flags);
4938 return ns;
4942 * Account user cpu time to a process.
4943 * @p: the process that the cpu time gets accounted to
4944 * @cputime: the cpu time spent in user space since the last update
4945 * @cputime_scaled: cputime scaled by cpu frequency
4947 void account_user_time(struct task_struct *p, cputime_t cputime,
4948 cputime_t cputime_scaled)
4950 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4951 cputime64_t tmp;
4953 /* Add user time to process. */
4954 p->utime = cputime_add(p->utime, cputime);
4955 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4956 account_group_user_time(p, cputime);
4958 /* Add user time to cpustat. */
4959 tmp = cputime_to_cputime64(cputime);
4960 if (rt_task(p))
4961 cpustat->user_rt = cputime64_add(cpustat->user_rt, tmp);
4962 else if (TASK_NICE(p) > 0)
4963 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4964 else
4965 cpustat->user = cputime64_add(cpustat->user, tmp);
4966 /* Account for user time used */
4967 acct_update_integrals(p);
4971 * Account guest cpu time to a process.
4972 * @p: the process that the cpu time gets accounted to
4973 * @cputime: the cpu time spent in virtual machine since the last update
4974 * @cputime_scaled: cputime scaled by cpu frequency
4976 static void account_guest_time(struct task_struct *p, cputime_t cputime,
4977 cputime_t cputime_scaled)
4979 cputime64_t tmp;
4980 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4982 tmp = cputime_to_cputime64(cputime);
4984 /* Add guest time to process. */
4985 p->utime = cputime_add(p->utime, cputime);
4986 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4987 account_group_user_time(p, cputime);
4988 p->gtime = cputime_add(p->gtime, cputime);
4990 /* Add guest time to cpustat. */
4991 cpustat->user = cputime64_add(cpustat->user, tmp);
4992 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4996 * Account system cpu time to a process.
4997 * @p: the process that the cpu time gets accounted to
4998 * @hardirq_offset: the offset to subtract from hardirq_count()
4999 * @cputime: the cpu time spent in kernel space since the last update
5000 * @cputime_scaled: cputime scaled by cpu frequency
5002 void account_system_time(struct task_struct *p, int hardirq_offset,
5003 cputime_t cputime, cputime_t cputime_scaled)
5005 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5006 cputime64_t tmp;
5008 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
5009 account_guest_time(p, cputime, cputime_scaled);
5010 return;
5013 /* Add system time to process. */
5014 p->stime = cputime_add(p->stime, cputime);
5015 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
5016 account_group_system_time(p, cputime);
5018 /* Add system time to cpustat. */
5019 tmp = cputime_to_cputime64(cputime);
5020 if (hardirq_count() - hardirq_offset || (p->flags & PF_HARDIRQ))
5021 cpustat->irq = cputime64_add(cpustat->irq, tmp);
5022 else if (softirq_count() || (p->flags & PF_SOFTIRQ))
5023 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
5024 else if (rt_task(p))
5025 cpustat->system_rt = cputime64_add(cpustat->system_rt, tmp);
5026 else
5027 cpustat->system = cputime64_add(cpustat->system, tmp);
5029 /* Account for system time used */
5030 acct_update_integrals(p);
5034 * Account for involuntary wait time.
5035 * @steal: the cpu time spent in involuntary wait
5037 void account_steal_time(cputime_t cputime)
5039 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5040 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5042 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
5046 * Account for idle time.
5047 * @cputime: the cpu time spent in idle wait
5049 void account_idle_time(cputime_t cputime)
5051 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5052 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5053 struct rq *rq = this_rq();
5055 if (atomic_read(&rq->nr_iowait) > 0)
5056 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
5057 else
5058 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
5061 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
5064 * Account a single tick of cpu time.
5065 * @p: the process that the cpu time gets accounted to
5066 * @user_tick: indicates if the tick is a user or a system tick
5068 void account_process_tick(struct task_struct *p, int user_tick)
5070 cputime_t one_jiffy = jiffies_to_cputime(1);
5071 cputime_t one_jiffy_scaled = cputime_to_scaled(one_jiffy);
5072 struct rq *rq = this_rq();
5074 if (user_tick)
5075 account_user_time(p, one_jiffy, one_jiffy_scaled);
5076 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
5077 account_system_time(p, HARDIRQ_OFFSET, one_jiffy,
5078 one_jiffy_scaled);
5079 else
5080 account_idle_time(one_jiffy);
5084 * Account multiple ticks of steal time.
5085 * @p: the process from which the cpu time has been stolen
5086 * @ticks: number of stolen ticks
5088 void account_steal_ticks(unsigned long ticks)
5090 account_steal_time(jiffies_to_cputime(ticks));
5094 * Account multiple ticks of idle time.
5095 * @ticks: number of stolen ticks
5097 void account_idle_ticks(unsigned long ticks)
5099 account_idle_time(jiffies_to_cputime(ticks));
5102 #endif
5105 * Use precise platform statistics if available:
5107 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
5108 cputime_t task_utime(struct task_struct *p)
5110 return p->utime;
5113 cputime_t task_stime(struct task_struct *p)
5115 return p->stime;
5117 #else
5118 cputime_t task_utime(struct task_struct *p)
5120 clock_t utime = cputime_to_clock_t(p->utime),
5121 total = utime + cputime_to_clock_t(p->stime);
5122 u64 temp;
5125 * Use CFS's precise accounting:
5127 temp = (u64)nsec_to_clock_t(p->se.sum_exec_runtime);
5129 if (total) {
5130 temp *= utime;
5131 do_div(temp, total);
5133 utime = (clock_t)temp;
5135 p->prev_utime = max(p->prev_utime, clock_t_to_cputime(utime));
5136 return p->prev_utime;
5139 cputime_t task_stime(struct task_struct *p)
5141 clock_t stime;
5144 * Use CFS's precise accounting. (we subtract utime from
5145 * the total, to make sure the total observed by userspace
5146 * grows monotonically - apps rely on that):
5148 stime = nsec_to_clock_t(p->se.sum_exec_runtime) -
5149 cputime_to_clock_t(task_utime(p));
5151 if (stime >= 0)
5152 p->prev_stime = max(p->prev_stime, clock_t_to_cputime(stime));
5154 return p->prev_stime;
5156 #endif
5158 inline cputime_t task_gtime(struct task_struct *p)
5160 return p->gtime;
5164 * This function gets called by the timer code, with HZ frequency.
5165 * We call it with interrupts disabled.
5167 * It also gets called by the fork code, when changing the parent's
5168 * timeslices.
5170 void scheduler_tick(void)
5172 int cpu = smp_processor_id();
5173 struct rq *rq = cpu_rq(cpu);
5174 struct task_struct *curr = rq->curr;
5176 sched_clock_tick();
5178 BUG_ON(!irqs_disabled());
5180 spin_lock(&rq->lock);
5181 update_rq_clock(rq);
5182 update_cpu_load(rq);
5183 if (curr != rq->idle && curr->se.on_rq)
5184 curr->sched_class->task_tick(rq, curr, 0);
5185 perf_counter_task_tick(curr, cpu);
5186 spin_unlock(&rq->lock);
5188 #ifdef CONFIG_SMP
5189 rq->idle_at_tick = idle_cpu(cpu);
5190 trigger_load_balance(rq, cpu);
5191 #endif
5194 unsigned long notrace get_parent_ip(unsigned long addr)
5196 if (in_lock_functions(addr)) {
5197 addr = CALLER_ADDR2;
5198 if (in_lock_functions(addr))
5199 addr = CALLER_ADDR3;
5201 return addr;
5204 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
5205 defined(CONFIG_PREEMPT_TRACER))
5207 void __kprobes add_preempt_count(int val)
5209 #ifdef CONFIG_DEBUG_PREEMPT
5211 * Underflow?
5213 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5214 return;
5215 #endif
5216 preempt_count() += val;
5217 #ifdef CONFIG_DEBUG_PREEMPT
5219 * Spinlock count overflowing soon?
5221 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5222 PREEMPT_MASK - 10);
5223 #endif
5224 if (preempt_count() == val)
5225 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5227 EXPORT_SYMBOL(add_preempt_count);
5229 void __kprobes sub_preempt_count(int val)
5231 #ifdef CONFIG_DEBUG_PREEMPT
5233 * Underflow?
5235 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
5236 return;
5238 * Is the spinlock portion underflowing?
5240 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5241 !(preempt_count() & PREEMPT_MASK)))
5242 return;
5243 #endif
5245 if (preempt_count() == val)
5246 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5247 preempt_count() -= val;
5249 EXPORT_SYMBOL(sub_preempt_count);
5251 #endif
5254 * Print scheduling while atomic bug:
5256 static noinline void __schedule_bug(struct task_struct *prev)
5258 struct pt_regs *regs = get_irq_regs();
5260 printk(KERN_ERR "BUG: scheduling while atomic: %s/0x%08x/%d, CPU#%d\n",
5261 prev->comm, preempt_count(), prev->pid, smp_processor_id());
5263 debug_show_held_locks(prev);
5264 print_modules();
5265 if (irqs_disabled())
5266 print_irqtrace_events(prev);
5268 if (regs)
5269 show_regs(regs);
5270 else
5271 dump_stack();
5275 * Various schedule()-time debugging checks and statistics:
5277 static inline void schedule_debug(struct task_struct *prev)
5279 // WARN_ON(system_state == SYSTEM_BOOTING);
5282 * Test if we are atomic. Since do_exit() needs to call into
5283 * schedule() atomically, we ignore that path for now.
5284 * Otherwise, whine if we are scheduling when we should not be.
5286 if (unlikely(in_atomic() && !prev->exit_state))
5287 __schedule_bug(prev);
5289 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5291 schedstat_inc(this_rq(), sched_count);
5292 #ifdef CONFIG_SCHEDSTATS
5293 if (unlikely(prev->lock_depth >= 0)) {
5294 schedstat_inc(this_rq(), bkl_count);
5295 schedstat_inc(prev, sched_info.bkl_count);
5297 #endif
5300 static void put_prev_task(struct rq *rq, struct task_struct *prev)
5302 if (prev->state == TASK_RUNNING) {
5303 u64 runtime = prev->se.sum_exec_runtime;
5305 runtime -= prev->se.prev_sum_exec_runtime;
5306 runtime = min_t(u64, runtime, 2*sysctl_sched_migration_cost);
5309 * In order to avoid avg_overlap growing stale when we are
5310 * indeed overlapping and hence not getting put to sleep, grow
5311 * the avg_overlap on preemption.
5313 * We use the average preemption runtime because that
5314 * correlates to the amount of cache footprint a task can
5315 * build up.
5317 update_avg(&prev->se.avg_overlap, runtime);
5319 prev->sched_class->put_prev_task(rq, prev);
5323 * Pick up the highest-prio task:
5325 static inline struct task_struct *
5326 pick_next_task(struct rq *rq)
5328 const struct sched_class *class;
5329 struct task_struct *p;
5332 * Optimization: we know that if all tasks are in
5333 * the fair class we can call that function directly:
5335 if (likely(rq->nr_running == rq->cfs.nr_running)) {
5336 p = fair_sched_class.pick_next_task(rq);
5337 if (likely(p))
5338 return p;
5341 class = sched_class_highest;
5342 for ( ; ; ) {
5343 p = class->pick_next_task(rq);
5344 if (p)
5345 return p;
5347 * Will never be NULL as the idle class always
5348 * returns a non-NULL p:
5350 class = class->next;
5355 * schedule() is the main scheduler function.
5357 asmlinkage void __sched __schedule(void)
5359 struct task_struct *prev, *next;
5360 unsigned long *switch_count;
5361 struct rq *rq;
5362 int cpu;
5364 cpu = smp_processor_id();
5365 rq = cpu_rq(cpu);
5366 rcu_qsctr_inc(cpu);
5367 prev = rq->curr;
5368 switch_count = &prev->nivcsw;
5370 release_kernel_lock(prev);
5372 schedule_debug(prev);
5374 preempt_disable();
5376 if (sched_feat(HRTICK))
5377 hrtick_clear(rq);
5379 spin_lock_irq(&rq->lock);
5380 update_rq_clock(rq);
5381 clear_tsk_need_resched(prev);
5383 if (!(prev->state & TASK_RUNNING_MUTEX) && prev->state &&
5384 !(preempt_count() & PREEMPT_ACTIVE)) {
5385 if (unlikely(signal_pending_state(prev->state, prev)))
5386 prev->state = TASK_RUNNING;
5387 else {
5388 touch_softlockup_watchdog();
5389 deactivate_task(rq, prev, 1);
5391 switch_count = &prev->nvcsw;
5394 if (preempt_count() & PREEMPT_ACTIVE)
5395 sub_preempt_count(PREEMPT_ACTIVE);
5397 #ifdef CONFIG_SMP
5398 if (prev->sched_class->pre_schedule)
5399 prev->sched_class->pre_schedule(rq, prev);
5400 #endif
5402 if (unlikely(!rq->nr_running))
5403 idle_balance(cpu, rq);
5405 put_prev_task(rq, prev);
5406 next = pick_next_task(rq);
5408 if (likely(prev != next)) {
5409 sched_info_switch(prev, next);
5410 perf_counter_task_sched_out(prev, cpu);
5412 rq->nr_switches++;
5413 rq->curr = next;
5414 ++*switch_count;
5416 context_switch(rq, prev, next); /* unlocks the rq */
5418 * the context switch might have flipped the stack from under
5419 * us, hence refresh the local variables.
5421 cpu = smp_processor_id();
5422 rq = cpu_rq(cpu);
5423 __preempt_enable_no_resched();
5424 } else {
5425 __preempt_enable_no_resched();
5426 spin_unlock(&rq->lock);
5429 reacquire_kernel_lock(current);
5432 asmlinkage void __sched schedule(void)
5434 need_resched:
5435 local_irq_disable();
5436 __schedule();
5437 local_irq_enable();
5439 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
5440 goto need_resched;
5442 EXPORT_SYMBOL(schedule);
5444 #if defined(CONFIG_SMP) && !defined(CONFIG_PREEMPT_RT)
5446 * Look out! "owner" is an entirely speculative pointer
5447 * access and not reliable.
5449 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
5451 unsigned int cpu;
5452 struct rq *rq;
5454 if (!sched_feat(OWNER_SPIN))
5455 return 0;
5457 #ifdef CONFIG_DEBUG_PAGEALLOC
5459 * Need to access the cpu field knowing that
5460 * DEBUG_PAGEALLOC could have unmapped it if
5461 * the mutex owner just released it and exited.
5463 if (probe_kernel_address(&owner->cpu, cpu))
5464 goto out;
5465 #else
5466 cpu = owner->cpu;
5467 #endif
5470 * Even if the access succeeded (likely case),
5471 * the cpu field may no longer be valid.
5473 if (cpu >= nr_cpumask_bits)
5474 goto out;
5477 * We need to validate that we can do a
5478 * get_cpu() and that we have the percpu area.
5480 if (!cpu_online(cpu))
5481 goto out;
5483 rq = cpu_rq(cpu);
5485 for (;;) {
5487 * Owner changed, break to re-assess state.
5489 if (lock->owner != owner)
5490 break;
5493 * Is that owner really running on that cpu?
5495 if (task_thread_info(rq->curr) != owner || need_resched())
5496 return 0;
5498 cpu_relax();
5500 out:
5501 return 1;
5503 #endif
5505 #ifdef CONFIG_PREEMPT
5508 * Global flag to turn preemption off on a CONFIG_PREEMPT kernel:
5510 int kernel_preemption = 1;
5512 static int __init preempt_setup (char *str)
5514 if (!strncmp(str, "off", 3)) {
5515 if (kernel_preemption) {
5516 printk(KERN_INFO "turning off kernel preemption!\n");
5517 kernel_preemption = 0;
5519 return 1;
5521 if (!strncmp(str, "on", 2)) {
5522 if (!kernel_preemption) {
5523 printk(KERN_INFO "turning on kernel preemption!\n");
5524 kernel_preemption = 1;
5526 return 1;
5528 get_option(&str, &kernel_preemption);
5530 return 1;
5533 __setup("preempt=", preempt_setup);
5536 * this is the entry point to schedule() from in-kernel preemption
5537 * off of preempt_enable. Kernel preemptions off return from interrupt
5538 * occur there and call schedule directly.
5540 asmlinkage void __sched preempt_schedule(void)
5542 struct thread_info *ti = current_thread_info();
5543 struct task_struct *task = current;
5544 int saved_lock_depth;
5546 if (!kernel_preemption)
5547 return;
5549 * If there is a non-zero preempt_count or interrupts are disabled,
5550 * we do not want to preempt the current task. Just return..
5552 if (likely(ti->preempt_count || irqs_disabled()))
5553 return;
5555 do {
5556 local_irq_disable();
5557 add_preempt_count(PREEMPT_ACTIVE);
5560 * We keep the big kernel semaphore locked, but we
5561 * clear ->lock_depth so that schedule() doesnt
5562 * auto-release the semaphore:
5564 saved_lock_depth = task->lock_depth;
5565 task->lock_depth = -1;
5566 __schedule();
5567 task->lock_depth = saved_lock_depth;
5568 local_irq_enable();
5571 * Check again in case we missed a preemption opportunity
5572 * between schedule and now.
5574 barrier();
5575 } while (need_resched());
5577 EXPORT_SYMBOL(preempt_schedule);
5580 * this is is the entry point for the IRQ return path. Called with
5581 * interrupts disabled. To avoid infinite irq-entry recursion problems
5582 * with fast-paced IRQ sources we do all of this carefully to never
5583 * enable interrupts again.
5585 asmlinkage void __sched preempt_schedule_irq(void)
5587 struct thread_info *ti = current_thread_info();
5588 struct task_struct *task = current;
5589 int saved_lock_depth;
5591 if (!kernel_preemption)
5592 return;
5594 * If there is a non-zero preempt_count then just return.
5595 * (interrupts are disabled)
5597 if (unlikely(ti->preempt_count))
5598 return;
5600 do {
5601 local_irq_disable();
5602 add_preempt_count(PREEMPT_ACTIVE);
5605 * We keep the big kernel semaphore locked, but we
5606 * clear ->lock_depth so that schedule() doesnt
5607 * auto-release the semaphore:
5609 saved_lock_depth = task->lock_depth;
5610 task->lock_depth = -1;
5611 __schedule();
5612 local_irq_disable();
5613 task->lock_depth = saved_lock_depth;
5616 * Check again in case we missed a preemption opportunity
5617 * between schedule and now.
5619 barrier();
5620 } while (need_resched());
5623 #endif /* CONFIG_PREEMPT */
5625 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
5626 void *key)
5628 return try_to_wake_up(curr->private, mode, sync, 0);
5630 EXPORT_SYMBOL(default_wake_function);
5633 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
5634 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
5635 * number) then we wake all the non-exclusive tasks and one exclusive task.
5637 * There are circumstances in which we can try to wake a task which has already
5638 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
5639 * zero in this (rare) case, and we handle it by continuing to scan the queue.
5641 void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
5642 int nr_exclusive, int sync, void *key)
5644 wait_queue_t *curr, *next;
5646 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
5647 unsigned flags = curr->flags;
5649 if (curr->func(curr, mode, sync, key) &&
5650 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
5651 break;
5656 * __wake_up - wake up threads blocked on a waitqueue.
5657 * @q: the waitqueue
5658 * @mode: which threads
5659 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5660 * @key: is directly passed to the wakeup function
5662 void __wake_up(wait_queue_head_t *q, unsigned int mode,
5663 int nr_exclusive, void *key)
5665 unsigned long flags;
5667 spin_lock_irqsave(&q->lock, flags);
5668 __wake_up_common(q, mode, nr_exclusive, 1, key);
5669 spin_unlock_irqrestore(&q->lock, flags);
5671 EXPORT_SYMBOL(__wake_up);
5674 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
5676 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
5678 __wake_up_common(q, mode, 1, 0, NULL);
5682 * __wake_up_sync - wake up threads blocked on a waitqueue.
5683 * @q: the waitqueue
5684 * @mode: which threads
5685 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5687 * The sync wakeup differs that the waker knows that it will schedule
5688 * away soon, so while the target thread will be woken up, it will not
5689 * be migrated to another CPU - ie. the two threads are 'synchronized'
5690 * with each other. This can prevent needless bouncing between CPUs.
5692 * On UP it can prevent extra preemption.
5694 void
5695 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
5697 unsigned long flags;
5698 int sync = 1;
5700 if (unlikely(!q))
5701 return;
5703 if (unlikely(!nr_exclusive))
5704 sync = 0;
5706 spin_lock_irqsave(&q->lock, flags);
5707 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
5708 spin_unlock_irqrestore(&q->lock, flags);
5710 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
5713 * complete: - signals a single thread waiting on this completion
5714 * @x: holds the state of this particular completion
5716 * This will wake up a single thread waiting on this completion. Threads will be
5717 * awakened in the same order in which they were queued.
5719 * See also complete_all(), wait_for_completion() and related routines.
5721 void complete(struct completion *x)
5723 unsigned long flags;
5725 spin_lock_irqsave(&x->wait.lock, flags);
5726 x->done++;
5727 __wake_up_common(&x->wait, TASK_NORMAL, 1, 1, NULL);
5728 spin_unlock_irqrestore(&x->wait.lock, flags);
5730 EXPORT_SYMBOL(complete);
5733 * complete_all: - signals all threads waiting on this completion
5734 * @x: holds the state of this particular completion
5736 * This will wake up all threads waiting on this particular completion event.
5738 void complete_all(struct completion *x)
5740 unsigned long flags;
5742 spin_lock_irqsave(&x->wait.lock, flags);
5743 x->done += UINT_MAX/2;
5744 __wake_up_common(&x->wait, TASK_NORMAL, 0, 1, NULL);
5745 spin_unlock_irqrestore(&x->wait.lock, flags);
5747 EXPORT_SYMBOL(complete_all);
5749 static inline long __sched
5750 do_wait_for_common(struct completion *x, long timeout, int state)
5752 if (!x->done) {
5753 DECLARE_WAITQUEUE(wait, current);
5755 wait.flags |= WQ_FLAG_EXCLUSIVE;
5756 __add_wait_queue_tail(&x->wait, &wait);
5757 do {
5758 if (signal_pending_state(state, current)) {
5759 timeout = -ERESTARTSYS;
5760 break;
5762 __set_current_state(state);
5763 spin_unlock_irq(&x->wait.lock);
5764 timeout = schedule_timeout(timeout);
5765 spin_lock_irq(&x->wait.lock);
5766 } while (!x->done && timeout);
5767 __remove_wait_queue(&x->wait, &wait);
5768 if (!x->done)
5769 return timeout;
5771 x->done--;
5772 return timeout ?: 1;
5775 static long __sched
5776 wait_for_common(struct completion *x, long timeout, int state)
5778 might_sleep();
5780 spin_lock_irq(&x->wait.lock);
5781 timeout = do_wait_for_common(x, timeout, state);
5782 spin_unlock_irq(&x->wait.lock);
5783 return timeout;
5787 * wait_for_completion: - waits for completion of a task
5788 * @x: holds the state of this particular completion
5790 * This waits to be signaled for completion of a specific task. It is NOT
5791 * interruptible and there is no timeout.
5793 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
5794 * and interrupt capability. Also see complete().
5796 void __sched wait_for_completion(struct completion *x)
5798 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
5800 EXPORT_SYMBOL(wait_for_completion);
5803 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
5804 * @x: holds the state of this particular completion
5805 * @timeout: timeout value in jiffies
5807 * This waits for either a completion of a specific task to be signaled or for a
5808 * specified timeout to expire. The timeout is in jiffies. It is not
5809 * interruptible.
5811 unsigned long __sched
5812 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
5814 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
5816 EXPORT_SYMBOL(wait_for_completion_timeout);
5819 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
5820 * @x: holds the state of this particular completion
5822 * This waits for completion of a specific task to be signaled. It is
5823 * interruptible.
5825 int __sched wait_for_completion_interruptible(struct completion *x)
5827 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
5828 if (t == -ERESTARTSYS)
5829 return t;
5830 return 0;
5832 EXPORT_SYMBOL(wait_for_completion_interruptible);
5835 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
5836 * @x: holds the state of this particular completion
5837 * @timeout: timeout value in jiffies
5839 * This waits for either a completion of a specific task to be signaled or for a
5840 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
5842 unsigned long __sched
5843 wait_for_completion_interruptible_timeout(struct completion *x,
5844 unsigned long timeout)
5846 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
5848 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
5851 * wait_for_completion_killable: - waits for completion of a task (killable)
5852 * @x: holds the state of this particular completion
5854 * This waits to be signaled for completion of a specific task. It can be
5855 * interrupted by a kill signal.
5857 int __sched wait_for_completion_killable(struct completion *x)
5859 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
5860 if (t == -ERESTARTSYS)
5861 return t;
5862 return 0;
5864 EXPORT_SYMBOL(wait_for_completion_killable);
5867 * try_wait_for_completion - try to decrement a completion without blocking
5868 * @x: completion structure
5870 * Returns: 0 if a decrement cannot be done without blocking
5871 * 1 if a decrement succeeded.
5873 * If a completion is being used as a counting completion,
5874 * attempt to decrement the counter without blocking. This
5875 * enables us to avoid waiting if the resource the completion
5876 * is protecting is not available.
5878 bool try_wait_for_completion(struct completion *x)
5880 int ret = 1;
5882 spin_lock_irq(&x->wait.lock);
5883 if (!x->done)
5884 ret = 0;
5885 else
5886 x->done--;
5887 spin_unlock_irq(&x->wait.lock);
5888 return ret;
5890 EXPORT_SYMBOL(try_wait_for_completion);
5893 * completion_done - Test to see if a completion has any waiters
5894 * @x: completion structure
5896 * Returns: 0 if there are waiters (wait_for_completion() in progress)
5897 * 1 if there are no waiters.
5900 bool completion_done(struct completion *x)
5902 int ret = 1;
5904 spin_lock_irq(&x->wait.lock);
5905 if (!x->done)
5906 ret = 0;
5907 spin_unlock_irq(&x->wait.lock);
5908 return ret;
5910 EXPORT_SYMBOL(completion_done);
5912 static long __sched
5913 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
5915 unsigned long flags;
5916 wait_queue_t wait;
5918 init_waitqueue_entry(&wait, current);
5920 __set_current_state(state);
5922 spin_lock_irqsave(&q->lock, flags);
5923 __add_wait_queue(q, &wait);
5924 spin_unlock(&q->lock);
5925 timeout = schedule_timeout(timeout);
5926 spin_lock_irq(&q->lock);
5927 __remove_wait_queue(q, &wait);
5928 spin_unlock_irqrestore(&q->lock, flags);
5930 return timeout;
5933 void __sched interruptible_sleep_on(wait_queue_head_t *q)
5935 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5937 EXPORT_SYMBOL(interruptible_sleep_on);
5939 long __sched
5940 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
5942 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
5944 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
5946 void __sched sleep_on(wait_queue_head_t *q)
5948 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5950 EXPORT_SYMBOL(sleep_on);
5952 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
5954 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5956 EXPORT_SYMBOL(sleep_on_timeout);
5959 * task_setprio - set the current priority of a task
5960 * @p: task
5961 * @prio: prio value (kernel-internal form)
5963 * This function changes the 'effective' priority of a task. It does
5964 * not touch ->normal_prio like __setscheduler().
5966 * Used by the rt_mutex code to implement priority inheritance logic
5967 * and by rcupreempt-boost to boost priorities of tasks sleeping
5968 * with rcu locks.
5970 void task_setprio(struct task_struct *p, int prio)
5972 unsigned long flags;
5973 int oldprio, on_rq, running;
5974 struct rq *rq;
5975 const struct sched_class *prev_class = p->sched_class;
5977 BUG_ON(prio < 0 || prio > MAX_PRIO);
5979 rq = task_rq_lock(p, &flags);
5982 * Idle task boosting is a nono in general. There is one
5983 * exception, when NOHZ is active:
5985 * The idle task calls get_next_timer_interrupt() and holds
5986 * the timer wheel base->lock on the CPU and another CPU wants
5987 * to access the timer (probably to cancel it). We can safely
5988 * ignore the boosting request, as the idle CPU runs this code
5989 * with interrupts disabled and will complete the lock
5990 * protected section without being interrupted. So there is no
5991 * real need to boost.
5993 if (unlikely(p == rq->idle)) {
5994 WARN_ON(p != rq->curr);
5995 WARN_ON(p->pi_blocked_on);
5996 goto out_unlock;
5999 update_rq_clock(rq);
6001 oldprio = p->prio;
6002 on_rq = p->se.on_rq;
6003 running = task_current(rq, p);
6004 if (on_rq)
6005 dequeue_task(rq, p, 0);
6006 if (running)
6007 p->sched_class->put_prev_task(rq, p);
6009 if (rt_prio(prio))
6010 p->sched_class = &rt_sched_class;
6011 else {
6012 #ifdef CONFIG_SCHED_CBS
6013 if (p->policy == SCHED_CBS)
6014 p->sched_class = &cbs_sched_class;
6015 else
6016 #endif
6017 p->sched_class = &fair_sched_class;
6019 p->prio = prio;
6021 trace_sched_task_setprio(rq, p, oldprio);
6023 if (running)
6024 p->sched_class->set_curr_task(rq);
6025 if (on_rq) {
6026 enqueue_task(rq, p, 0);
6028 check_class_changed(rq, p, prev_class, oldprio, running);
6031 out_unlock:
6032 task_rq_unlock(rq, &flags);
6035 void set_user_nice(struct task_struct *p, long nice)
6037 int old_prio, delta, on_rq;
6038 unsigned long flags;
6039 struct rq *rq;
6041 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
6042 return;
6044 * We have to be careful, if called from sys_setpriority(),
6045 * the task might be in the middle of scheduling on another CPU.
6047 rq = task_rq_lock(p, &flags);
6048 update_rq_clock(rq);
6050 * The RT priorities are set via sched_setscheduler(), but we still
6051 * allow the 'normal' nice value to be set - but as expected
6052 * it wont have any effect on scheduling until the task is
6053 * SCHED_FIFO/SCHED_RR:
6055 if (task_has_rt_policy(p)) {
6056 p->static_prio = NICE_TO_PRIO(nice);
6057 goto out_unlock;
6059 on_rq = p->se.on_rq;
6060 if (on_rq)
6061 dequeue_task(rq, p, 0);
6063 p->static_prio = NICE_TO_PRIO(nice);
6064 set_load_weight(p);
6065 old_prio = p->prio;
6066 p->prio = effective_prio(p);
6067 delta = p->prio - old_prio;
6069 if (on_rq) {
6070 enqueue_task(rq, p, 0);
6072 * If the task increased its priority or is running and
6073 * lowered its priority, then reschedule its CPU:
6075 if (delta < 0 || (delta > 0 && task_running(rq, p)))
6076 resched_task(rq->curr);
6078 out_unlock:
6079 task_rq_unlock(rq, &flags);
6081 EXPORT_SYMBOL(set_user_nice);
6084 * can_nice - check if a task can reduce its nice value
6085 * @p: task
6086 * @nice: nice value
6088 int can_nice(const struct task_struct *p, const int nice)
6090 /* convert nice value [19,-20] to rlimit style value [1,40] */
6091 int nice_rlim = 20 - nice;
6093 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
6094 capable(CAP_SYS_NICE));
6097 #ifdef __ARCH_WANT_SYS_NICE
6100 * sys_nice - change the priority of the current process.
6101 * @increment: priority increment
6103 * sys_setpriority is a more generic, but much slower function that
6104 * does similar things.
6106 SYSCALL_DEFINE1(nice, int, increment)
6108 long nice, retval;
6111 * Setpriority might change our priority at the same moment.
6112 * We don't have to worry. Conceptually one call occurs first
6113 * and we have a single winner.
6115 if (increment < -40)
6116 increment = -40;
6117 if (increment > 40)
6118 increment = 40;
6120 nice = TASK_NICE(current) + increment;
6121 if (nice < -20)
6122 nice = -20;
6123 if (nice > 19)
6124 nice = 19;
6126 if (increment < 0 && !can_nice(current, nice))
6127 return -EPERM;
6129 retval = security_task_setnice(current, nice);
6130 if (retval)
6131 return retval;
6133 set_user_nice(current, nice);
6134 return 0;
6137 #endif
6140 * task_prio - return the priority value of a given task.
6141 * @p: the task in question.
6143 * This is the priority value as seen by users in /proc.
6144 * RT tasks are offset by -200. Normal tasks are centered
6145 * around 0, value goes from -16 to +15.
6147 int task_prio(const struct task_struct *p)
6149 return p->prio - MAX_RT_PRIO;
6153 * task_nice - return the nice value of a given task.
6154 * @p: the task in question.
6156 int task_nice(const struct task_struct *p)
6158 return TASK_NICE(p);
6160 EXPORT_SYMBOL(task_nice);
6163 * idle_cpu - is a given cpu idle currently?
6164 * @cpu: the processor in question.
6166 int idle_cpu(int cpu)
6168 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
6172 * idle_task - return the idle task for a given cpu.
6173 * @cpu: the processor in question.
6175 struct task_struct *idle_task(int cpu)
6177 return cpu_rq(cpu)->idle;
6181 * find_process_by_pid - find a process with a matching PID value.
6182 * @pid: the pid in question.
6184 static struct task_struct *find_process_by_pid(pid_t pid)
6186 return pid ? find_task_by_vpid(pid) : current;
6189 /* Actually do priority change: must hold rq lock. */
6190 static void
6191 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
6193 BUG_ON(p->se.on_rq);
6195 p->policy = policy;
6196 switch (p->policy) {
6197 case SCHED_NORMAL:
6198 case SCHED_BATCH:
6199 case SCHED_IDLE:
6200 p->sched_class = &fair_sched_class;
6201 break;
6202 case SCHED_FIFO:
6203 case SCHED_RR:
6204 p->sched_class = &rt_sched_class;
6205 break;
6206 #ifdef CONFIG_SCHED_CBS
6207 case SCHED_CBS:
6208 p->sched_class = &cbs_sched_class;
6209 break;
6210 #endif
6213 p->rt_priority = prio;
6214 p->normal_prio = normal_prio(p);
6215 /* we are holding p->pi_lock already */
6216 p->prio = rt_mutex_getprio(p);
6217 set_load_weight(p);
6221 * check the target process has a UID that matches the current process's
6223 static bool check_same_owner(struct task_struct *p)
6225 const struct cred *cred = current_cred(), *pcred;
6226 bool match;
6228 rcu_read_lock();
6229 pcred = __task_cred(p);
6230 match = (cred->euid == pcred->euid ||
6231 cred->euid == pcred->uid);
6232 rcu_read_unlock();
6233 return match;
6236 static int __sched_setscheduler(struct task_struct *p, int policy,
6237 struct sched_param *param, bool user)
6239 int retval, oldprio, oldpolicy = -1, on_rq, running;
6240 unsigned long flags;
6241 const struct sched_class *prev_class = p->sched_class;
6242 struct rq *rq;
6244 /* may grab non-irq protected spin_locks */
6245 BUG_ON(in_interrupt());
6246 recheck:
6247 /* double check policy once rq lock held */
6248 if (policy < 0)
6249 policy = oldpolicy = p->policy;
6250 #ifdef CONFIG_SCHED_CBS
6251 else if (policy != SCHED_FIFO && policy != SCHED_RR && policy != SCHED_CBS &&
6252 #else
6253 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
6255 #endif
6256 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
6257 policy != SCHED_IDLE)
6258 return -EINVAL;
6260 * Valid priorities for SCHED_FIFO and SCHED_RR are
6261 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
6262 * SCHED_BATCH and SCHED_IDLE is 0.
6264 if (param->sched_priority < 0 ||
6265 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
6266 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
6267 return -EINVAL;
6268 if (rt_policy(policy) != (param->sched_priority != 0))
6269 return -EINVAL;
6272 * Allow unprivileged RT tasks to decrease priority:
6274 if (user && !capable(CAP_SYS_NICE)) {
6275 if (rt_policy(policy)) {
6276 unsigned long rlim_rtprio;
6278 if (!lock_task_sighand(p, &flags))
6279 return -ESRCH;
6280 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
6281 unlock_task_sighand(p, &flags);
6283 /* can't set/change the rt policy */
6284 if (policy != p->policy && !rlim_rtprio)
6285 return -EPERM;
6287 /* can't increase priority */
6288 if (param->sched_priority > p->rt_priority &&
6289 param->sched_priority > rlim_rtprio)
6290 return -EPERM;
6293 * Like positive nice levels, dont allow tasks to
6294 * move out of SCHED_IDLE either:
6296 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
6297 return -EPERM;
6299 /* can't change other user's priorities */
6300 if (!check_same_owner(p))
6301 return -EPERM;
6304 if (user) {
6305 #ifdef CONFIG_RT_GROUP_SCHED
6307 * Do not allow realtime tasks into groups that have no runtime
6308 * assigned.
6310 if (rt_bandwidth_enabled() && rt_policy(policy) &&
6311 task_group(p)->rt_bandwidth.rt_runtime == 0)
6312 return -EPERM;
6313 #endif
6315 retval = security_task_setscheduler(p, policy, param);
6316 if (retval)
6317 return retval;
6321 * make sure no PI-waiters arrive (or leave) while we are
6322 * changing the priority of the task:
6324 spin_lock_irqsave(&p->pi_lock, flags);
6326 * To be able to change p->policy safely, the apropriate
6327 * runqueue lock must be held.
6329 rq = __task_rq_lock(p);
6330 /* recheck policy now with rq lock held */
6331 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
6332 policy = oldpolicy = -1;
6333 __task_rq_unlock(rq);
6334 spin_unlock_irqrestore(&p->pi_lock, flags);
6335 goto recheck;
6337 update_rq_clock(rq);
6338 on_rq = p->se.on_rq;
6339 running = task_current(rq, p);
6340 if (on_rq)
6341 deactivate_task(rq, p, 0);
6342 if (running)
6343 p->sched_class->put_prev_task(rq, p);
6345 oldprio = p->prio;
6347 #ifdef CONFIG_SCHED_CBS
6348 if (policy == SCHED_CBS) { /* FIXME: Move to __setscheduler()? */
6349 p->cbs_se.period = timespec_to_ns(&(param->sched_ss_repl_period));
6350 p->cbs_se.max_budget = timespec_to_ns(&param->sched_ss_init_budget);
6351 p->cbs_se.budget = p->cbs_se.max_budget;
6352 //now=cbs_rq_of(task_cbs_rq(p))->clock;
6353 p->cbs_se.deadline = 0;
6355 init_cbs_timer(&p->cbs_se);
6357 #endif
6359 __setscheduler(rq, p, policy, param->sched_priority);
6361 if (running)
6362 p->sched_class->set_curr_task(rq);
6363 if (on_rq) {
6364 activate_task(rq, p, 0);
6366 check_class_changed(rq, p, prev_class, oldprio, running);
6368 __task_rq_unlock(rq);
6369 spin_unlock_irqrestore(&p->pi_lock, flags);
6371 rt_mutex_adjust_pi(p);
6373 return 0;
6377 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
6378 * @p: the task in question.
6379 * @policy: new policy.
6380 * @param: structure containing the new RT priority.
6382 * NOTE that the task may be already dead.
6384 int sched_setscheduler(struct task_struct *p, int policy,
6385 struct sched_param *param)
6387 return __sched_setscheduler(p, policy, param, true);
6389 EXPORT_SYMBOL_GPL(sched_setscheduler);
6392 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
6393 * @p: the task in question.
6394 * @policy: new policy.
6395 * @param: structure containing the new RT priority.
6397 * Just like sched_setscheduler, only don't bother checking if the
6398 * current context has permission. For example, this is needed in
6399 * stop_machine(): we create temporary high priority worker threads,
6400 * but our caller might not have that capability.
6402 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
6403 struct sched_param *param)
6405 return __sched_setscheduler(p, policy, param, false);
6408 static int
6409 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
6411 struct sched_param lparam;
6412 struct task_struct *p;
6413 int retval;
6415 if (!param || pid < 0)
6416 return -EINVAL;
6417 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
6418 return -EFAULT;
6420 rcu_read_lock();
6421 retval = -ESRCH;
6422 p = find_process_by_pid(pid);
6423 if (p != NULL)
6424 retval = sched_setscheduler(p, policy, &lparam);
6425 rcu_read_unlock();
6427 return retval;
6431 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
6432 * @pid: the pid in question.
6433 * @policy: new policy.
6434 * @param: structure containing the new RT priority.
6436 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
6437 struct sched_param __user *, param)
6439 /* negative values for policy are not valid */
6440 if (policy < 0)
6441 return -EINVAL;
6443 return do_sched_setscheduler(pid, policy, param);
6447 * sys_sched_setparam - set/change the RT priority of a thread
6448 * @pid: the pid in question.
6449 * @param: structure containing the new RT priority.
6451 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
6453 return do_sched_setscheduler(pid, -1, param);
6457 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
6458 * @pid: the pid in question.
6460 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
6462 struct task_struct *p;
6463 int retval;
6465 if (pid < 0)
6466 return -EINVAL;
6468 retval = -ESRCH;
6469 read_lock(&tasklist_lock);
6470 p = find_process_by_pid(pid);
6471 if (p) {
6472 retval = security_task_getscheduler(p);
6473 if (!retval)
6474 retval = p->policy;
6476 read_unlock(&tasklist_lock);
6477 return retval;
6481 * sys_sched_getscheduler - get the RT priority of a thread
6482 * @pid: the pid in question.
6483 * @param: structure containing the RT priority.
6485 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
6487 struct sched_param lp;
6488 struct task_struct *p;
6489 int retval;
6491 if (!param || pid < 0)
6492 return -EINVAL;
6494 read_lock(&tasklist_lock);
6495 p = find_process_by_pid(pid);
6496 retval = -ESRCH;
6497 if (!p)
6498 goto out_unlock;
6500 retval = security_task_getscheduler(p);
6501 if (retval)
6502 goto out_unlock;
6504 lp.sched_priority = p->rt_priority;
6505 read_unlock(&tasklist_lock);
6508 * This one might sleep, we cannot do it with a spinlock held ...
6510 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
6512 return retval;
6514 out_unlock:
6515 read_unlock(&tasklist_lock);
6516 return retval;
6519 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
6521 cpumask_var_t cpus_allowed, new_mask;
6522 struct task_struct *p;
6523 int retval;
6525 get_online_cpus();
6526 read_lock(&tasklist_lock);
6528 p = find_process_by_pid(pid);
6529 if (!p) {
6530 read_unlock(&tasklist_lock);
6531 put_online_cpus();
6532 return -ESRCH;
6536 * It is not safe to call set_cpus_allowed with the
6537 * tasklist_lock held. We will bump the task_struct's
6538 * usage count and then drop tasklist_lock.
6540 get_task_struct(p);
6541 read_unlock(&tasklist_lock);
6543 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
6544 retval = -ENOMEM;
6545 goto out_put_task;
6547 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
6548 retval = -ENOMEM;
6549 goto out_free_cpus_allowed;
6551 retval = -EPERM;
6552 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
6553 goto out_unlock;
6555 retval = security_task_setscheduler(p, 0, NULL);
6556 if (retval)
6557 goto out_unlock;
6559 cpuset_cpus_allowed(p, cpus_allowed);
6560 cpumask_and(new_mask, in_mask, cpus_allowed);
6561 again:
6562 retval = set_cpus_allowed_ptr(p, new_mask);
6564 if (!retval) {
6565 cpuset_cpus_allowed(p, cpus_allowed);
6566 if (!cpumask_subset(new_mask, cpus_allowed)) {
6568 * We must have raced with a concurrent cpuset
6569 * update. Just reset the cpus_allowed to the
6570 * cpuset's cpus_allowed
6572 cpumask_copy(new_mask, cpus_allowed);
6573 goto again;
6576 out_unlock:
6577 free_cpumask_var(new_mask);
6578 out_free_cpus_allowed:
6579 free_cpumask_var(cpus_allowed);
6580 out_put_task:
6581 put_task_struct(p);
6582 put_online_cpus();
6583 return retval;
6586 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
6587 struct cpumask *new_mask)
6589 if (len < cpumask_size())
6590 cpumask_clear(new_mask);
6591 else if (len > cpumask_size())
6592 len = cpumask_size();
6594 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6598 * sys_sched_setaffinity - set the cpu affinity of a process
6599 * @pid: pid of the process
6600 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6601 * @user_mask_ptr: user-space pointer to the new cpu mask
6603 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6604 unsigned long __user *, user_mask_ptr)
6606 cpumask_var_t new_mask;
6607 int retval;
6609 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6610 return -ENOMEM;
6612 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6613 if (retval == 0)
6614 retval = sched_setaffinity(pid, new_mask);
6615 free_cpumask_var(new_mask);
6616 return retval;
6619 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6621 struct task_struct *p;
6622 int retval;
6624 get_online_cpus();
6625 read_lock(&tasklist_lock);
6627 retval = -ESRCH;
6628 p = find_process_by_pid(pid);
6629 if (!p)
6630 goto out_unlock;
6632 retval = security_task_getscheduler(p);
6633 if (retval)
6634 goto out_unlock;
6636 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
6638 out_unlock:
6639 read_unlock(&tasklist_lock);
6640 put_online_cpus();
6642 return retval;
6646 * sys_sched_getaffinity - get the cpu affinity of a process
6647 * @pid: pid of the process
6648 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6649 * @user_mask_ptr: user-space pointer to hold the current cpu mask
6651 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6652 unsigned long __user *, user_mask_ptr)
6654 int ret;
6655 cpumask_var_t mask;
6657 if (len < cpumask_size())
6658 return -EINVAL;
6660 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
6661 return -ENOMEM;
6663 ret = sched_getaffinity(pid, mask);
6664 if (ret == 0) {
6665 if (copy_to_user(user_mask_ptr, mask, cpumask_size()))
6666 ret = -EFAULT;
6667 else
6668 ret = cpumask_size();
6670 free_cpumask_var(mask);
6672 return ret;
6676 * sys_sched_yield - yield the current processor to other threads.
6678 * This function yields the current CPU to other tasks. If there are no
6679 * other threads running on this CPU then this function will return.
6681 SYSCALL_DEFINE0(sched_yield)
6683 struct rq *rq = this_rq_lock();
6685 schedstat_inc(rq, yld_count);
6686 current->sched_class->yield_task(rq);
6689 * Since we are going to call schedule() anyway, there's
6690 * no need to preempt or enable interrupts:
6692 spin_unlock_no_resched(&rq->lock);
6694 __schedule();
6696 local_irq_enable();
6697 preempt_check_resched();
6699 return 0;
6702 #if defined(CONFIG_DEBUG_SPINLOCK_SLEEP) || defined(CONFIG_DEBUG_PREEMPT)
6703 void __might_sleep(char *file, int line)
6705 #ifdef in_atomic
6706 static unsigned long prev_jiffy; /* ratelimiting */
6708 if ((!in_atomic() && !irqs_disabled()) ||
6709 system_state != SYSTEM_RUNNING || oops_in_progress)
6710 return;
6712 if (debug_direct_keyboard && hardirq_count())
6713 return;
6715 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6716 return;
6717 prev_jiffy = jiffies;
6719 printk(KERN_ERR
6720 "BUG: sleeping function called from invalid context at %s:%d\n",
6721 file, line);
6722 printk(KERN_ERR
6723 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6724 in_atomic(), irqs_disabled(),
6725 current->pid, current->comm);
6727 debug_show_held_locks(current);
6728 if (irqs_disabled())
6729 print_irqtrace_events(current);
6730 dump_stack();
6731 #endif
6733 EXPORT_SYMBOL(__might_sleep);
6734 #endif
6736 static void __cond_resched(void)
6738 #if defined(CONFIG_DEBUG_SPINLOCK_SLEEP) || defined(CONFIG_DEBUG_PREEMPT)
6739 __might_sleep(__FILE__, __LINE__);
6740 #endif
6742 * The BKS might be reacquired before we have dropped
6743 * PREEMPT_ACTIVE, which could trigger a second
6744 * cond_resched() call.
6746 do {
6747 local_irq_disable();
6748 add_preempt_count(PREEMPT_ACTIVE);
6749 __schedule();
6750 } while (need_resched());
6751 local_irq_enable();
6754 int __sched _cond_resched(void)
6756 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
6757 system_state == SYSTEM_RUNNING) {
6758 __cond_resched();
6759 return 1;
6761 return 0;
6763 EXPORT_SYMBOL(_cond_resched);
6766 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
6767 * call schedule, and on return reacquire the lock.
6769 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
6770 * operations here to prevent schedule() from being called twice (once via
6771 * spin_unlock(), once by hand).
6773 int __cond_resched_raw_spinlock(raw_spinlock_t *lock)
6775 int resched = need_resched() && system_state == SYSTEM_RUNNING;
6776 int ret = 0;
6778 if (spin_needbreak(lock) || resched) {
6779 spin_unlock_no_resched(lock);
6780 if (resched && need_resched())
6781 __cond_resched();
6782 else
6783 cpu_relax();
6784 ret = 1;
6785 spin_lock(lock);
6787 return ret;
6789 EXPORT_SYMBOL(__cond_resched_raw_spinlock);
6791 #ifdef CONFIG_PREEMPT_RT
6793 int __cond_resched_spinlock(spinlock_t *lock)
6795 int resched = need_resched() && system_state == SYSTEM_RUNNING;
6797 if (spin_needbreak(lock) || resched) {
6798 spin_unlock_no_resched(lock);
6799 __cond_resched();
6800 spin_lock(lock);
6801 return 1;
6803 return 0;
6805 EXPORT_SYMBOL(__cond_resched_spinlock);
6807 #endif
6810 * Voluntarily preempt a process context that has softirqs disabled:
6812 int __sched cond_resched_softirq(void)
6814 #ifndef CONFIG_PREEMPT_SOFTIRQS
6815 WARN_ON_ONCE(!in_softirq());
6816 if (!in_softirq())
6817 return 0;
6818 #endif
6819 if (need_resched() && system_state == SYSTEM_RUNNING) {
6820 local_bh_enable();
6821 __cond_resched();
6822 local_bh_disable();
6823 return 1;
6825 return 0;
6827 EXPORT_SYMBOL(cond_resched_softirq);
6830 * Voluntarily preempt a softirq context (possible with softirq threading):
6832 int __sched cond_resched_softirq_context(void)
6834 WARN_ON_ONCE(!in_softirq());
6836 if (softirq_need_resched() && system_state == SYSTEM_RUNNING) {
6837 raw_local_irq_disable();
6838 _local_bh_enable();
6839 raw_local_irq_enable();
6840 __cond_resched();
6841 local_bh_disable();
6842 return 1;
6844 return 0;
6846 EXPORT_SYMBOL(cond_resched_softirq_context);
6849 * Preempt a hardirq context if necessary (possible with hardirq threading):
6851 int cond_resched_hardirq_context(void)
6853 WARN_ON_ONCE(!in_irq());
6854 WARN_ON_ONCE(!irqs_disabled());
6856 if (hardirq_need_resched()) {
6857 #ifndef CONFIG_PREEMPT_RT
6858 irq_exit();
6859 #endif
6860 local_irq_enable();
6861 __cond_resched();
6862 #ifndef CONFIG_PREEMPT_RT
6863 local_irq_disable();
6864 __irq_enter();
6865 #endif
6867 return 1;
6869 return 0;
6871 EXPORT_SYMBOL(cond_resched_hardirq_context);
6873 #ifdef CONFIG_PREEMPT_VOLUNTARY
6875 int voluntary_preemption = 1;
6877 EXPORT_SYMBOL(voluntary_preemption);
6879 static int __init voluntary_preempt_setup (char *str)
6881 if (!strncmp(str, "off", 3))
6882 voluntary_preemption = 0;
6883 else
6884 get_option(&str, &voluntary_preemption);
6885 if (!voluntary_preemption)
6886 printk("turning off voluntary preemption!\n");
6888 return 1;
6891 __setup("voluntary-preempt=", voluntary_preempt_setup);
6893 #endif
6896 * yield - yield the current processor to other threads.
6898 * This is a shortcut for kernel-space yielding - it marks the
6899 * thread runnable and calls sys_sched_yield().
6901 void __sched __yield(void)
6903 set_current_state(TASK_RUNNING);
6904 sys_sched_yield();
6907 void __sched yield(void)
6909 static int once = 1;
6912 * it's a bug to rely on yield() with RT priorities. We print
6913 * the first occurance after bootup ... this will still give
6914 * us an idea about the scope of the problem, without spamming
6915 * the syslog:
6917 if (once && rt_task(current)) {
6918 once = 0;
6919 printk(KERN_ERR "BUG: %s:%d RT task yield()-ing!\n",
6920 current->comm, current->pid);
6921 dump_stack();
6923 __yield();
6925 EXPORT_SYMBOL(yield);
6928 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6929 * that process accounting knows that this is a task in IO wait state.
6931 * But don't do that if it is a deliberate, throttling IO wait (this task
6932 * has set its backing_dev_info: the queue against which it should throttle)
6934 void __sched io_schedule(void)
6936 struct rq *rq = &__raw_get_cpu_var(runqueues);
6938 delayacct_blkio_start();
6939 atomic_inc(&rq->nr_iowait);
6940 schedule();
6941 atomic_dec(&rq->nr_iowait);
6942 delayacct_blkio_end();
6944 EXPORT_SYMBOL(io_schedule);
6946 long __sched io_schedule_timeout(long timeout)
6948 struct rq *rq = &__raw_get_cpu_var(runqueues);
6949 long ret;
6951 delayacct_blkio_start();
6952 atomic_inc(&rq->nr_iowait);
6953 ret = schedule_timeout(timeout);
6954 atomic_dec(&rq->nr_iowait);
6955 delayacct_blkio_end();
6956 return ret;
6960 * sys_sched_get_priority_max - return maximum RT priority.
6961 * @policy: scheduling class.
6963 * this syscall returns the maximum rt_priority that can be used
6964 * by a given scheduling class.
6966 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6968 int ret = -EINVAL;
6970 switch (policy) {
6971 case SCHED_FIFO:
6972 case SCHED_RR:
6973 ret = MAX_USER_RT_PRIO-1;
6974 break;
6975 case SCHED_NORMAL:
6976 case SCHED_BATCH:
6977 case SCHED_IDLE:
6978 ret = 0;
6979 break;
6981 return ret;
6985 * sys_sched_get_priority_min - return minimum RT priority.
6986 * @policy: scheduling class.
6988 * this syscall returns the minimum rt_priority that can be used
6989 * by a given scheduling class.
6991 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6993 int ret = -EINVAL;
6995 switch (policy) {
6996 case SCHED_FIFO:
6997 case SCHED_RR:
6998 ret = 1;
6999 break;
7000 case SCHED_NORMAL:
7001 case SCHED_BATCH:
7002 case SCHED_IDLE:
7003 ret = 0;
7005 return ret;
7009 * sys_sched_rr_get_interval - return the default timeslice of a process.
7010 * @pid: pid of the process.
7011 * @interval: userspace pointer to the timeslice value.
7013 * this syscall writes the default timeslice value of a given process
7014 * into the user-space timespec buffer. A value of '0' means infinity.
7016 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
7017 struct timespec __user *, interval)
7019 struct task_struct *p;
7020 unsigned int time_slice;
7021 int retval;
7022 struct timespec t;
7024 if (pid < 0)
7025 return -EINVAL;
7027 retval = -ESRCH;
7028 read_lock(&tasklist_lock);
7029 p = find_process_by_pid(pid);
7030 if (!p)
7031 goto out_unlock;
7033 retval = security_task_getscheduler(p);
7034 if (retval)
7035 goto out_unlock;
7038 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
7039 * tasks that are on an otherwise idle runqueue:
7041 time_slice = 0;
7042 if (p->policy == SCHED_RR) {
7043 time_slice = DEF_TIMESLICE;
7044 } else if (p->policy != SCHED_FIFO) {
7045 struct sched_entity *se = &p->se;
7046 unsigned long flags;
7047 struct rq *rq;
7049 rq = task_rq_lock(p, &flags);
7050 if (rq->cfs.load.weight)
7051 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
7052 task_rq_unlock(rq, &flags);
7054 read_unlock(&tasklist_lock);
7055 jiffies_to_timespec(time_slice, &t);
7056 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
7057 return retval;
7059 out_unlock:
7060 read_unlock(&tasklist_lock);
7061 return retval;
7064 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
7066 void sched_show_task(struct task_struct *p)
7068 unsigned long free = 0;
7069 unsigned state;
7071 state = p->state ? __ffs(p->state) + 1 : 0;
7072 printk("%-13.13s %c (%03lx) [%p]", p->comm,
7073 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?',
7074 (unsigned long) p->state, p);
7075 #if BITS_PER_LONG == 32
7076 if (0 && (state == TASK_RUNNING))
7077 printk(KERN_CONT " running ");
7078 else
7079 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
7080 #else
7081 if (0 && (state == TASK_RUNNING))
7082 printk(KERN_CONT " running task ");
7083 else
7084 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
7085 #endif
7086 if (task_curr(p))
7087 printk("[curr] ");
7088 else if (p->se.on_rq)
7089 printk("[on rq #%d] ", task_cpu(p));
7090 #ifdef CONFIG_DEBUG_STACK_USAGE
7091 free = stack_not_used(p);
7092 #endif
7093 printk(KERN_CONT "%5lu %5d %6d\n", free,
7094 task_pid_nr(p), task_pid_nr(p->real_parent));
7096 show_stack(p, NULL);
7099 void show_state_filter(unsigned long state_filter)
7101 struct task_struct *g, *p;
7102 int do_unlock = 1;
7104 #if BITS_PER_LONG == 32
7105 printk(KERN_INFO
7106 " task PC stack pid father\n");
7107 #else
7108 printk(KERN_INFO
7109 " task PC stack pid father\n");
7110 #endif
7111 #ifdef CONFIG_PREEMPT_RT
7112 if (!read_trylock(&tasklist_lock)) {
7113 printk("hm, tasklist_lock write-locked.\n");
7114 printk("ignoring ...\n");
7115 do_unlock = 0;
7117 #else
7118 read_lock(&tasklist_lock);
7119 #endif
7121 do_each_thread(g, p) {
7123 * reset the NMI-timeout, listing all files on a slow
7124 * console might take alot of time:
7126 touch_nmi_watchdog();
7127 if (!state_filter || (p->state & state_filter))
7128 sched_show_task(p);
7129 } while_each_thread(g, p);
7131 touch_all_softlockup_watchdogs();
7133 #ifdef CONFIG_SCHED_DEBUG
7134 sysrq_sched_debug_show();
7135 #endif
7136 if (do_unlock)
7137 read_unlock(&tasklist_lock);
7139 * Only show locks if all tasks are dumped:
7141 if (state_filter == -1)
7142 debug_show_all_locks();
7145 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
7147 idle->sched_class = &idle_sched_class;
7151 * init_idle - set up an idle thread for a given CPU
7152 * @idle: task in question
7153 * @cpu: cpu the idle task belongs to
7155 * NOTE: this function does not set the idle thread's NEED_RESCHED
7156 * flag, to make booting more robust.
7158 void __cpuinit init_idle(struct task_struct *idle, int cpu)
7160 struct rq *rq = cpu_rq(cpu);
7161 unsigned long flags;
7163 spin_lock_irqsave(&rq->lock, flags);
7165 __sched_fork(idle);
7166 idle->se.exec_start = sched_clock();
7168 idle->prio = idle->normal_prio = MAX_PRIO;
7169 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
7170 __set_task_cpu(idle, cpu);
7172 rq->curr = rq->idle = idle;
7173 #if defined(CONFIG_SMP)
7174 idle->oncpu = 1;
7175 #endif
7176 spin_unlock_irqrestore(&rq->lock, flags);
7178 /* Set the preempt count _outside_ the spinlocks! */
7179 task_thread_info(idle)->preempt_count = 0;
7182 * The idle tasks have their own, simple scheduling class:
7184 idle->sched_class = &idle_sched_class;
7185 ftrace_graph_init_task(idle);
7189 * In a system that switches off the HZ timer nohz_cpu_mask
7190 * indicates which cpus entered this state. This is used
7191 * in the rcu update to wait only for active cpus. For system
7192 * which do not switch off the HZ timer nohz_cpu_mask should
7193 * always be CPU_BITS_NONE.
7195 cpumask_var_t nohz_cpu_mask;
7198 * Increase the granularity value when there are more CPUs,
7199 * because with more CPUs the 'effective latency' as visible
7200 * to users decreases. But the relationship is not linear,
7201 * so pick a second-best guess by going with the log2 of the
7202 * number of CPUs.
7204 * This idea comes from the SD scheduler of Con Kolivas:
7206 static inline void sched_init_granularity(void)
7208 unsigned int factor = 1 + ilog2(num_online_cpus());
7209 const unsigned long limit = 200000000;
7211 sysctl_sched_min_granularity *= factor;
7212 if (sysctl_sched_min_granularity > limit)
7213 sysctl_sched_min_granularity = limit;
7215 sysctl_sched_latency *= factor;
7216 if (sysctl_sched_latency > limit)
7217 sysctl_sched_latency = limit;
7219 sysctl_sched_wakeup_granularity *= factor;
7221 sysctl_sched_shares_ratelimit *= factor;
7224 #ifdef CONFIG_SMP
7226 * This is how migration works:
7228 * 1) we queue a struct migration_req structure in the source CPU's
7229 * runqueue and wake up that CPU's migration thread.
7230 * 2) we down() the locked semaphore => thread blocks.
7231 * 3) migration thread wakes up (implicitly it forces the migrated
7232 * thread off the CPU)
7233 * 4) it gets the migration request and checks whether the migrated
7234 * task is still in the wrong runqueue.
7235 * 5) if it's in the wrong runqueue then the migration thread removes
7236 * it and puts it into the right queue.
7237 * 6) migration thread up()s the semaphore.
7238 * 7) we wake up and the migration is done.
7242 * Change a given task's CPU affinity. Migrate the thread to a
7243 * proper CPU and schedule it away if the CPU it's executing on
7244 * is removed from the allowed bitmask.
7246 * NOTE: the caller must have a valid reference to the task, the
7247 * task must not exit() & deallocate itself prematurely. The
7248 * call is not atomic; no spinlocks may be held.
7250 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
7252 struct migration_req req;
7253 unsigned long flags;
7254 struct rq *rq;
7255 int ret = 0;
7257 rq = task_rq_lock(p, &flags);
7258 if (!cpumask_intersects(new_mask, cpu_online_mask)) {
7259 ret = -EINVAL;
7260 goto out;
7263 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
7264 !cpumask_equal(&p->cpus_allowed, new_mask))) {
7265 ret = -EINVAL;
7266 goto out;
7269 if (p->sched_class->set_cpus_allowed)
7270 p->sched_class->set_cpus_allowed(p, new_mask);
7271 else {
7272 cpumask_copy(&p->cpus_allowed, new_mask);
7273 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
7276 /* Can the task run on the task's current CPU? If so, we're done */
7277 if (cpumask_test_cpu(task_cpu(p), new_mask))
7278 goto out;
7280 if (migrate_task(p, cpumask_any_and(cpu_online_mask, new_mask), &req)) {
7281 /* Need help from migration thread: drop lock and wait. */
7282 task_rq_unlock(rq, &flags);
7283 wake_up_process(rq->migration_thread);
7284 wait_for_completion(&req.done);
7285 tlb_migrate_finish(p->mm);
7286 return 0;
7288 out:
7289 task_rq_unlock(rq, &flags);
7291 return ret;
7293 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
7296 * Move (not current) task off this cpu, onto dest cpu. We're doing
7297 * this because either it can't run here any more (set_cpus_allowed()
7298 * away from this CPU, or CPU going down), or because we're
7299 * attempting to rebalance this task on exec (sched_exec).
7301 * So we race with normal scheduler movements, but that's OK, as long
7302 * as the task is no longer on this CPU.
7304 * Returns non-zero if task was successfully migrated.
7306 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
7308 struct rq *rq_dest, *rq_src;
7309 unsigned long flags;
7310 int ret = 0, on_rq;
7312 if (unlikely(!cpu_active(dest_cpu)))
7313 return ret;
7316 * PREEMPT_RT: this relies on write_lock_irq(&tasklist_lock)
7317 * disabling interrupts - which on PREEMPT_RT does not do:
7319 local_irq_save(flags);
7321 rq_src = cpu_rq(src_cpu);
7322 rq_dest = cpu_rq(dest_cpu);
7324 double_rq_lock(rq_src, rq_dest);
7325 /* Already moved. */
7326 if (task_cpu(p) != src_cpu)
7327 goto done;
7328 /* Affinity changed (again). */
7329 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
7330 goto fail;
7332 on_rq = p->se.on_rq;
7333 if (on_rq)
7334 deactivate_task(rq_src, p, 0);
7336 set_task_cpu(p, dest_cpu);
7337 if (on_rq) {
7338 activate_task(rq_dest, p, 0);
7339 check_preempt_curr(rq_dest, p, 0);
7341 done:
7342 ret = 1;
7343 fail:
7344 double_rq_unlock(rq_src, rq_dest);
7345 local_irq_restore(flags);
7347 return ret;
7351 * migration_thread - this is a highprio system thread that performs
7352 * thread migration by bumping thread off CPU then 'pushing' onto
7353 * another runqueue.
7355 static int migration_thread(void *data)
7357 int cpu = (long)data;
7358 struct rq *rq;
7360 rq = cpu_rq(cpu);
7361 BUG_ON(rq->migration_thread != current);
7363 set_current_state(TASK_INTERRUPTIBLE);
7364 while (!kthread_should_stop()) {
7365 struct migration_req *req;
7366 struct list_head *head;
7368 spin_lock_irq(&rq->lock);
7370 if (cpu_is_offline(cpu)) {
7371 spin_unlock_irq(&rq->lock);
7372 goto wait_to_die;
7375 if (rq->active_balance) {
7376 active_load_balance(rq, cpu);
7377 rq->active_balance = 0;
7380 head = &rq->migration_queue;
7382 if (list_empty(head)) {
7383 spin_unlock_irq(&rq->lock);
7384 schedule();
7385 set_current_state(TASK_INTERRUPTIBLE);
7386 continue;
7388 req = list_entry(head->next, struct migration_req, list);
7389 list_del_init(head->next);
7391 spin_unlock(&rq->lock);
7392 __migrate_task(req->task, cpu, req->dest_cpu);
7393 local_irq_enable();
7395 complete(&req->done);
7397 __set_current_state(TASK_RUNNING);
7398 return 0;
7400 wait_to_die:
7401 /* Wait for kthread_stop */
7402 set_current_state(TASK_INTERRUPTIBLE);
7403 while (!kthread_should_stop()) {
7404 schedule();
7405 set_current_state(TASK_INTERRUPTIBLE);
7407 __set_current_state(TASK_RUNNING);
7408 return 0;
7411 #ifdef CONFIG_HOTPLUG_CPU
7413 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
7415 int ret;
7417 local_irq_disable();
7418 ret = __migrate_task(p, src_cpu, dest_cpu);
7419 local_irq_enable();
7420 return ret;
7424 * Figure out where task on dead CPU should go, use force if necessary.
7426 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
7428 int dest_cpu;
7429 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(dead_cpu));
7431 again:
7432 /* Look for allowed, online CPU in same node. */
7433 for_each_cpu_and(dest_cpu, nodemask, cpu_online_mask)
7434 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
7435 goto move;
7437 /* Any allowed, online CPU? */
7438 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_online_mask);
7439 if (dest_cpu < nr_cpu_ids)
7440 goto move;
7442 /* No more Mr. Nice Guy. */
7443 if (dest_cpu >= nr_cpu_ids) {
7444 cpuset_cpus_allowed_locked(p, &p->cpus_allowed);
7445 dest_cpu = cpumask_any_and(cpu_online_mask, &p->cpus_allowed);
7448 * Don't tell them about moving exiting tasks or
7449 * kernel threads (both mm NULL), since they never
7450 * leave kernel.
7452 if (p->mm && printk_ratelimit()) {
7453 printk(KERN_INFO "process %d (%s) no "
7454 "longer affine to cpu%d\n",
7455 task_pid_nr(p), p->comm, dead_cpu);
7459 move:
7460 /* It can have affinity changed while we were choosing. */
7461 if (unlikely(!__migrate_task_irq(p, dead_cpu, dest_cpu)))
7462 goto again;
7466 * While a dead CPU has no uninterruptible tasks queued at this point,
7467 * it might still have a nonzero ->nr_uninterruptible counter, because
7468 * for performance reasons the counter is not stricly tracking tasks to
7469 * their home CPUs. So we just add the counter to another CPU's counter,
7470 * to keep the global sum constant after CPU-down:
7472 static void migrate_nr_uninterruptible(struct rq *rq_src)
7474 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_online_mask));
7475 unsigned long flags;
7477 local_irq_save(flags);
7478 double_rq_lock(rq_src, rq_dest);
7479 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
7480 rq_src->nr_uninterruptible = 0;
7481 double_rq_unlock(rq_src, rq_dest);
7482 local_irq_restore(flags);
7485 /* Run through task list and migrate tasks from the dead cpu. */
7486 static void migrate_live_tasks(int src_cpu)
7488 struct task_struct *p, *t;
7490 read_lock(&tasklist_lock);
7492 do_each_thread(t, p) {
7493 if (p == current)
7494 continue;
7496 if (task_cpu(p) == src_cpu)
7497 move_task_off_dead_cpu(src_cpu, p);
7498 } while_each_thread(t, p);
7500 read_unlock(&tasklist_lock);
7504 * Schedules idle task to be the next runnable task on current CPU.
7505 * It does so by boosting its priority to highest possible.
7506 * Used by CPU offline code.
7508 void sched_idle_next(void)
7510 int this_cpu = smp_processor_id();
7511 struct rq *rq = cpu_rq(this_cpu);
7512 struct task_struct *p = rq->idle;
7513 unsigned long flags;
7515 /* cpu has to be offline */
7516 BUG_ON(cpu_online(this_cpu));
7519 * Strictly not necessary since rest of the CPUs are stopped by now
7520 * and interrupts disabled on the current cpu.
7522 spin_lock_irqsave(&rq->lock, flags);
7524 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7526 update_rq_clock(rq);
7527 activate_task(rq, p, 0);
7529 spin_unlock_irqrestore(&rq->lock, flags);
7533 * Ensures that the idle task is using init_mm right before its cpu goes
7534 * offline.
7536 void idle_task_exit(void)
7538 struct mm_struct *mm = current->active_mm;
7540 BUG_ON(cpu_online(smp_processor_id()));
7542 if (mm != &init_mm)
7543 switch_mm(mm, &init_mm, current);
7544 #ifdef CONFIG_PREEMPT_RT
7545 mmdrop_delayed(mm);
7546 #else
7547 mmdrop(mm);
7548 #endif
7551 /* called under rq->lock with disabled interrupts */
7552 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
7554 struct rq *rq = cpu_rq(dead_cpu);
7556 /* Must be exiting, otherwise would be on tasklist. */
7557 BUG_ON(!p->exit_state);
7559 /* Cannot have done final schedule yet: would have vanished. */
7560 BUG_ON(p->state == TASK_DEAD);
7562 get_task_struct(p);
7565 * Drop lock around migration; if someone else moves it,
7566 * that's OK. No task can be added to this CPU, so iteration is
7567 * fine.
7569 spin_unlock_irq(&rq->lock);
7570 move_task_off_dead_cpu(dead_cpu, p);
7571 spin_lock_irq(&rq->lock);
7573 put_task_struct(p);
7576 /* release_task() removes task from tasklist, so we won't find dead tasks. */
7577 static void migrate_dead_tasks(unsigned int dead_cpu)
7579 struct rq *rq = cpu_rq(dead_cpu);
7580 struct task_struct *next;
7582 for ( ; ; ) {
7583 if (!rq->nr_running)
7584 break;
7585 update_rq_clock(rq);
7586 next = pick_next_task(rq);
7587 if (!next)
7588 break;
7589 next->sched_class->put_prev_task(rq, next);
7590 migrate_dead(dead_cpu, next);
7596 * remove the tasks which were accounted by rq from calc_load_tasks.
7598 static void calc_global_load_remove(struct rq *rq)
7600 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
7602 #endif /* CONFIG_HOTPLUG_CPU */
7604 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
7606 static struct ctl_table sd_ctl_dir[] = {
7608 .procname = "sched_domain",
7609 .mode = 0555,
7611 {0, },
7614 static struct ctl_table sd_ctl_root[] = {
7616 .ctl_name = CTL_KERN,
7617 .procname = "kernel",
7618 .mode = 0555,
7619 .child = sd_ctl_dir,
7621 {0, },
7624 static struct ctl_table *sd_alloc_ctl_entry(int n)
7626 struct ctl_table *entry =
7627 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
7629 return entry;
7632 static void sd_free_ctl_entry(struct ctl_table **tablep)
7634 struct ctl_table *entry;
7637 * In the intermediate directories, both the child directory and
7638 * procname are dynamically allocated and could fail but the mode
7639 * will always be set. In the lowest directory the names are
7640 * static strings and all have proc handlers.
7642 for (entry = *tablep; entry->mode; entry++) {
7643 if (entry->child)
7644 sd_free_ctl_entry(&entry->child);
7645 if (entry->proc_handler == NULL)
7646 kfree(entry->procname);
7649 kfree(*tablep);
7650 *tablep = NULL;
7653 static void
7654 set_table_entry(struct ctl_table *entry,
7655 const char *procname, void *data, int maxlen,
7656 mode_t mode, proc_handler *proc_handler)
7658 entry->procname = procname;
7659 entry->data = data;
7660 entry->maxlen = maxlen;
7661 entry->mode = mode;
7662 entry->proc_handler = proc_handler;
7665 static struct ctl_table *
7666 sd_alloc_ctl_domain_table(struct sched_domain *sd)
7668 struct ctl_table *table = sd_alloc_ctl_entry(13);
7670 if (table == NULL)
7671 return NULL;
7673 set_table_entry(&table[0], "min_interval", &sd->min_interval,
7674 sizeof(long), 0644, proc_doulongvec_minmax);
7675 set_table_entry(&table[1], "max_interval", &sd->max_interval,
7676 sizeof(long), 0644, proc_doulongvec_minmax);
7677 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
7678 sizeof(int), 0644, proc_dointvec_minmax);
7679 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
7680 sizeof(int), 0644, proc_dointvec_minmax);
7681 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
7682 sizeof(int), 0644, proc_dointvec_minmax);
7683 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
7684 sizeof(int), 0644, proc_dointvec_minmax);
7685 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
7686 sizeof(int), 0644, proc_dointvec_minmax);
7687 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
7688 sizeof(int), 0644, proc_dointvec_minmax);
7689 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
7690 sizeof(int), 0644, proc_dointvec_minmax);
7691 set_table_entry(&table[9], "cache_nice_tries",
7692 &sd->cache_nice_tries,
7693 sizeof(int), 0644, proc_dointvec_minmax);
7694 set_table_entry(&table[10], "flags", &sd->flags,
7695 sizeof(int), 0644, proc_dointvec_minmax);
7696 set_table_entry(&table[11], "name", sd->name,
7697 CORENAME_MAX_SIZE, 0444, proc_dostring);
7698 /* &table[12] is terminator */
7700 return table;
7703 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
7705 struct ctl_table *entry, *table;
7706 struct sched_domain *sd;
7707 int domain_num = 0, i;
7708 char buf[32];
7710 for_each_domain(cpu, sd)
7711 domain_num++;
7712 entry = table = sd_alloc_ctl_entry(domain_num + 1);
7713 if (table == NULL)
7714 return NULL;
7716 i = 0;
7717 for_each_domain(cpu, sd) {
7718 snprintf(buf, 32, "domain%d", i);
7719 entry->procname = kstrdup(buf, GFP_KERNEL);
7720 entry->mode = 0555;
7721 entry->child = sd_alloc_ctl_domain_table(sd);
7722 entry++;
7723 i++;
7725 return table;
7728 static struct ctl_table_header *sd_sysctl_header;
7729 static void register_sched_domain_sysctl(void)
7731 int i, cpu_num = num_online_cpus();
7732 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
7733 char buf[32];
7735 WARN_ON(sd_ctl_dir[0].child);
7736 sd_ctl_dir[0].child = entry;
7738 if (entry == NULL)
7739 return;
7741 for_each_online_cpu(i) {
7742 snprintf(buf, 32, "cpu%d", i);
7743 entry->procname = kstrdup(buf, GFP_KERNEL);
7744 entry->mode = 0555;
7745 entry->child = sd_alloc_ctl_cpu_table(i);
7746 entry++;
7749 WARN_ON(sd_sysctl_header);
7750 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
7753 /* may be called multiple times per register */
7754 static void unregister_sched_domain_sysctl(void)
7756 if (sd_sysctl_header)
7757 unregister_sysctl_table(sd_sysctl_header);
7758 sd_sysctl_header = NULL;
7759 if (sd_ctl_dir[0].child)
7760 sd_free_ctl_entry(&sd_ctl_dir[0].child);
7762 #else
7763 static void register_sched_domain_sysctl(void)
7766 static void unregister_sched_domain_sysctl(void)
7769 #endif
7771 static void set_rq_online(struct rq *rq)
7773 if (!rq->online) {
7774 const struct sched_class *class;
7776 cpumask_set_cpu(rq->cpu, rq->rd->online);
7777 rq->online = 1;
7779 for_each_class(class) {
7780 if (class->rq_online)
7781 class->rq_online(rq);
7786 static void set_rq_offline(struct rq *rq)
7788 if (rq->online) {
7789 const struct sched_class *class;
7791 for_each_class(class) {
7792 if (class->rq_offline)
7793 class->rq_offline(rq);
7796 cpumask_clear_cpu(rq->cpu, rq->rd->online);
7797 rq->online = 0;
7802 * migration_call - callback that gets triggered when a CPU is added.
7803 * Here we can start up the necessary migration thread for the new CPU.
7805 static int __cpuinit
7806 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
7808 struct task_struct *p;
7809 int cpu = (long)hcpu;
7810 unsigned long flags;
7811 struct rq *rq;
7813 switch (action) {
7815 case CPU_UP_PREPARE:
7816 case CPU_UP_PREPARE_FROZEN:
7817 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
7818 if (IS_ERR(p))
7819 return NOTIFY_BAD;
7820 kthread_bind(p, cpu);
7821 /* Must be high prio: stop_machine expects to yield to it. */
7822 rq = task_rq_lock(p, &flags);
7823 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7824 task_rq_unlock(rq, &flags);
7825 cpu_rq(cpu)->migration_thread = p;
7826 break;
7828 case CPU_ONLINE:
7829 case CPU_ONLINE_FROZEN:
7830 /* Strictly unnecessary, as first user will wake it. */
7831 wake_up_process(cpu_rq(cpu)->migration_thread);
7833 /* Update our root-domain */
7834 rq = cpu_rq(cpu);
7835 spin_lock_irqsave(&rq->lock, flags);
7836 rq->calc_load_update = calc_load_update;
7837 rq->calc_load_active = 0;
7838 if (rq->rd) {
7839 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7841 set_rq_online(rq);
7843 spin_unlock_irqrestore(&rq->lock, flags);
7844 break;
7846 #ifdef CONFIG_HOTPLUG_CPU
7847 case CPU_UP_CANCELED:
7848 case CPU_UP_CANCELED_FROZEN:
7849 if (!cpu_rq(cpu)->migration_thread)
7850 break;
7851 /* Unbind it from offline cpu so it can run. Fall thru. */
7852 kthread_bind(cpu_rq(cpu)->migration_thread,
7853 cpumask_any(cpu_online_mask));
7854 kthread_stop(cpu_rq(cpu)->migration_thread);
7855 cpu_rq(cpu)->migration_thread = NULL;
7856 break;
7858 case CPU_DEAD:
7859 case CPU_DEAD_FROZEN:
7860 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
7861 migrate_live_tasks(cpu);
7862 rq = cpu_rq(cpu);
7863 kthread_stop(rq->migration_thread);
7864 rq->migration_thread = NULL;
7865 /* Idle task back to normal (off runqueue, low prio) */
7866 spin_lock_irq(&rq->lock);
7867 update_rq_clock(rq);
7868 deactivate_task(rq, rq->idle, 0);
7869 rq->idle->static_prio = MAX_PRIO;
7870 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
7871 rq->idle->sched_class = &idle_sched_class;
7872 migrate_dead_tasks(cpu);
7873 spin_unlock_irq(&rq->lock);
7874 cpuset_unlock();
7875 migrate_nr_uninterruptible(rq);
7876 BUG_ON(rq->nr_running != 0);
7877 calc_global_load_remove(rq);
7879 * No need to migrate the tasks: it was best-effort if
7880 * they didn't take sched_hotcpu_mutex. Just wake up
7881 * the requestors.
7883 spin_lock_irq(&rq->lock);
7884 while (!list_empty(&rq->migration_queue)) {
7885 struct migration_req *req;
7887 req = list_entry(rq->migration_queue.next,
7888 struct migration_req, list);
7889 list_del_init(&req->list);
7890 spin_unlock_irq(&rq->lock);
7891 complete(&req->done);
7892 spin_lock_irq(&rq->lock);
7894 spin_unlock_irq(&rq->lock);
7895 break;
7897 case CPU_DYING:
7898 case CPU_DYING_FROZEN:
7899 /* Update our root-domain */
7900 rq = cpu_rq(cpu);
7901 spin_lock_irqsave(&rq->lock, flags);
7902 if (rq->rd) {
7903 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7904 set_rq_offline(rq);
7906 spin_unlock_irqrestore(&rq->lock, flags);
7907 break;
7908 #endif
7910 return NOTIFY_OK;
7913 /* Register at highest priority so that task migration (migrate_all_tasks)
7914 * happens before everything else.
7916 static struct notifier_block __cpuinitdata migration_notifier = {
7917 .notifier_call = migration_call,
7918 .priority = 10
7921 static int __init migration_init(void)
7923 void *cpu = (void *)(long)smp_processor_id();
7924 int err;
7926 /* Start one for the boot CPU: */
7927 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
7928 BUG_ON(err == NOTIFY_BAD);
7929 migration_call(&migration_notifier, CPU_ONLINE, cpu);
7930 register_cpu_notifier(&migration_notifier);
7932 return err;
7934 early_initcall(migration_init);
7935 #endif
7937 #ifdef CONFIG_SMP
7939 #ifdef CONFIG_SCHED_DEBUG
7941 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
7942 struct cpumask *groupmask)
7944 struct sched_group *group = sd->groups;
7945 char str[256];
7947 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
7948 cpumask_clear(groupmask);
7950 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
7952 if (!(sd->flags & SD_LOAD_BALANCE)) {
7953 printk("does not load-balance\n");
7954 if (sd->parent)
7955 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
7956 " has parent");
7957 return -1;
7960 printk(KERN_CONT "span %s level %s\n", str, sd->name);
7962 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
7963 printk(KERN_ERR "ERROR: domain->span does not contain "
7964 "CPU%d\n", cpu);
7966 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
7967 printk(KERN_ERR "ERROR: domain->groups does not contain"
7968 " CPU%d\n", cpu);
7971 printk(KERN_DEBUG "%*s groups:", level + 1, "");
7972 do {
7973 if (!group) {
7974 printk("\n");
7975 printk(KERN_ERR "ERROR: group is NULL\n");
7976 break;
7979 if (!group->__cpu_power) {
7980 printk(KERN_CONT "\n");
7981 printk(KERN_ERR "ERROR: domain->cpu_power not "
7982 "set\n");
7983 break;
7986 if (!cpumask_weight(sched_group_cpus(group))) {
7987 printk(KERN_CONT "\n");
7988 printk(KERN_ERR "ERROR: empty group\n");
7989 break;
7992 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
7993 printk(KERN_CONT "\n");
7994 printk(KERN_ERR "ERROR: repeated CPUs\n");
7995 break;
7998 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
8000 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
8001 printk(KERN_CONT " %s", str);
8003 group = group->next;
8004 } while (group != sd->groups);
8005 printk(KERN_CONT "\n");
8007 if (!cpumask_equal(sched_domain_span(sd), groupmask))
8008 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
8010 if (sd->parent &&
8011 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
8012 printk(KERN_ERR "ERROR: parent span is not a superset "
8013 "of domain->span\n");
8014 return 0;
8017 static void sched_domain_debug(struct sched_domain *sd, int cpu)
8019 cpumask_var_t groupmask;
8020 int level = 0;
8022 if (!sd) {
8023 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
8024 return;
8027 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
8029 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
8030 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
8031 return;
8034 for (;;) {
8035 if (sched_domain_debug_one(sd, cpu, level, groupmask))
8036 break;
8037 level++;
8038 sd = sd->parent;
8039 if (!sd)
8040 break;
8042 free_cpumask_var(groupmask);
8044 #else /* !CONFIG_SCHED_DEBUG */
8045 # define sched_domain_debug(sd, cpu) do { } while (0)
8046 #endif /* CONFIG_SCHED_DEBUG */
8048 static int sd_degenerate(struct sched_domain *sd)
8050 if (cpumask_weight(sched_domain_span(sd)) == 1)
8051 return 1;
8053 /* Following flags need at least 2 groups */
8054 if (sd->flags & (SD_LOAD_BALANCE |
8055 SD_BALANCE_NEWIDLE |
8056 SD_BALANCE_FORK |
8057 SD_BALANCE_EXEC |
8058 SD_SHARE_CPUPOWER |
8059 SD_SHARE_PKG_RESOURCES)) {
8060 if (sd->groups != sd->groups->next)
8061 return 0;
8064 /* Following flags don't use groups */
8065 if (sd->flags & (SD_WAKE_IDLE |
8066 SD_WAKE_AFFINE |
8067 SD_WAKE_BALANCE))
8068 return 0;
8070 return 1;
8073 static int
8074 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
8076 unsigned long cflags = sd->flags, pflags = parent->flags;
8078 if (sd_degenerate(parent))
8079 return 1;
8081 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
8082 return 0;
8084 /* Does parent contain flags not in child? */
8085 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
8086 if (cflags & SD_WAKE_AFFINE)
8087 pflags &= ~SD_WAKE_BALANCE;
8088 /* Flags needing groups don't count if only 1 group in parent */
8089 if (parent->groups == parent->groups->next) {
8090 pflags &= ~(SD_LOAD_BALANCE |
8091 SD_BALANCE_NEWIDLE |
8092 SD_BALANCE_FORK |
8093 SD_BALANCE_EXEC |
8094 SD_SHARE_CPUPOWER |
8095 SD_SHARE_PKG_RESOURCES);
8096 if (nr_node_ids == 1)
8097 pflags &= ~SD_SERIALIZE;
8099 if (~cflags & pflags)
8100 return 0;
8102 return 1;
8105 static void free_rootdomain(struct root_domain *rd)
8107 cpupri_cleanup(&rd->cpupri);
8109 free_cpumask_var(rd->rto_mask);
8110 free_cpumask_var(rd->online);
8111 free_cpumask_var(rd->span);
8112 kfree(rd);
8115 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
8117 struct root_domain *old_rd = NULL;
8118 unsigned long flags;
8120 spin_lock_irqsave(&rq->lock, flags);
8122 if (rq->rd) {
8123 old_rd = rq->rd;
8125 if (cpumask_test_cpu(rq->cpu, old_rd->online))
8126 set_rq_offline(rq);
8128 cpumask_clear_cpu(rq->cpu, old_rd->span);
8131 * If we dont want to free the old_rt yet then
8132 * set old_rd to NULL to skip the freeing later
8133 * in this function:
8135 if (!atomic_dec_and_test(&old_rd->refcount))
8136 old_rd = NULL;
8139 atomic_inc(&rd->refcount);
8140 rq->rd = rd;
8142 cpumask_set_cpu(rq->cpu, rd->span);
8143 if (cpumask_test_cpu(rq->cpu, cpu_online_mask))
8144 set_rq_online(rq);
8146 spin_unlock_irqrestore(&rq->lock, flags);
8148 if (old_rd)
8149 free_rootdomain(old_rd);
8152 static int __init_refok init_rootdomain(struct root_domain *rd, bool bootmem)
8154 memset(rd, 0, sizeof(*rd));
8156 if (bootmem) {
8157 alloc_bootmem_cpumask_var(&def_root_domain.span);
8158 alloc_bootmem_cpumask_var(&def_root_domain.online);
8159 alloc_bootmem_cpumask_var(&def_root_domain.rto_mask);
8160 cpupri_init(&rd->cpupri, true);
8161 return 0;
8164 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
8165 goto out;
8166 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
8167 goto free_span;
8168 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
8169 goto free_online;
8171 if (cpupri_init(&rd->cpupri, false) != 0)
8172 goto free_rto_mask;
8173 return 0;
8175 free_rto_mask:
8176 free_cpumask_var(rd->rto_mask);
8177 free_online:
8178 free_cpumask_var(rd->online);
8179 free_span:
8180 free_cpumask_var(rd->span);
8181 out:
8182 return -ENOMEM;
8185 static void init_defrootdomain(void)
8187 init_rootdomain(&def_root_domain, true);
8189 atomic_set(&def_root_domain.refcount, 1);
8192 static struct root_domain *alloc_rootdomain(void)
8194 struct root_domain *rd;
8196 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
8197 if (!rd)
8198 return NULL;
8200 if (init_rootdomain(rd, false) != 0) {
8201 kfree(rd);
8202 return NULL;
8205 return rd;
8209 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
8210 * hold the hotplug lock.
8212 static void
8213 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
8215 struct rq *rq = cpu_rq(cpu);
8216 struct sched_domain *tmp;
8218 /* Remove the sched domains which do not contribute to scheduling. */
8219 for (tmp = sd; tmp; ) {
8220 struct sched_domain *parent = tmp->parent;
8221 if (!parent)
8222 break;
8224 if (sd_parent_degenerate(tmp, parent)) {
8225 tmp->parent = parent->parent;
8226 if (parent->parent)
8227 parent->parent->child = tmp;
8228 } else
8229 tmp = tmp->parent;
8232 if (sd && sd_degenerate(sd)) {
8233 sd = sd->parent;
8234 if (sd)
8235 sd->child = NULL;
8238 sched_domain_debug(sd, cpu);
8240 rq_attach_root(rq, rd);
8241 rcu_assign_pointer(rq->sd, sd);
8244 /* cpus with isolated domains */
8245 static cpumask_var_t cpu_isolated_map;
8247 /* Setup the mask of cpus configured for isolated domains */
8248 static int __init isolated_cpu_setup(char *str)
8250 cpulist_parse(str, cpu_isolated_map);
8251 return 1;
8254 __setup("isolcpus=", isolated_cpu_setup);
8257 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
8258 * to a function which identifies what group(along with sched group) a CPU
8259 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
8260 * (due to the fact that we keep track of groups covered with a struct cpumask).
8262 * init_sched_build_groups will build a circular linked list of the groups
8263 * covered by the given span, and will set each group's ->cpumask correctly,
8264 * and ->cpu_power to 0.
8266 static void
8267 init_sched_build_groups(const struct cpumask *span,
8268 const struct cpumask *cpu_map,
8269 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
8270 struct sched_group **sg,
8271 struct cpumask *tmpmask),
8272 struct cpumask *covered, struct cpumask *tmpmask)
8274 struct sched_group *first = NULL, *last = NULL;
8275 int i;
8277 cpumask_clear(covered);
8279 for_each_cpu(i, span) {
8280 struct sched_group *sg;
8281 int group = group_fn(i, cpu_map, &sg, tmpmask);
8282 int j;
8284 if (cpumask_test_cpu(i, covered))
8285 continue;
8287 cpumask_clear(sched_group_cpus(sg));
8288 sg->__cpu_power = 0;
8290 for_each_cpu(j, span) {
8291 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
8292 continue;
8294 cpumask_set_cpu(j, covered);
8295 cpumask_set_cpu(j, sched_group_cpus(sg));
8297 if (!first)
8298 first = sg;
8299 if (last)
8300 last->next = sg;
8301 last = sg;
8303 last->next = first;
8306 #define SD_NODES_PER_DOMAIN 16
8308 #ifdef CONFIG_NUMA
8311 * find_next_best_node - find the next node to include in a sched_domain
8312 * @node: node whose sched_domain we're building
8313 * @used_nodes: nodes already in the sched_domain
8315 * Find the next node to include in a given scheduling domain. Simply
8316 * finds the closest node not already in the @used_nodes map.
8318 * Should use nodemask_t.
8320 static int find_next_best_node(int node, nodemask_t *used_nodes)
8322 int i, n, val, min_val, best_node = 0;
8324 min_val = INT_MAX;
8326 for (i = 0; i < nr_node_ids; i++) {
8327 /* Start at @node */
8328 n = (node + i) % nr_node_ids;
8330 if (!nr_cpus_node(n))
8331 continue;
8333 /* Skip already used nodes */
8334 if (node_isset(n, *used_nodes))
8335 continue;
8337 /* Simple min distance search */
8338 val = node_distance(node, n);
8340 if (val < min_val) {
8341 min_val = val;
8342 best_node = n;
8346 node_set(best_node, *used_nodes);
8347 return best_node;
8351 * sched_domain_node_span - get a cpumask for a node's sched_domain
8352 * @node: node whose cpumask we're constructing
8353 * @span: resulting cpumask
8355 * Given a node, construct a good cpumask for its sched_domain to span. It
8356 * should be one that prevents unnecessary balancing, but also spreads tasks
8357 * out optimally.
8359 static void sched_domain_node_span(int node, struct cpumask *span)
8361 nodemask_t used_nodes;
8362 int i;
8364 cpumask_clear(span);
8365 nodes_clear(used_nodes);
8367 cpumask_or(span, span, cpumask_of_node(node));
8368 node_set(node, used_nodes);
8370 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
8371 int next_node = find_next_best_node(node, &used_nodes);
8373 cpumask_or(span, span, cpumask_of_node(next_node));
8376 #endif /* CONFIG_NUMA */
8378 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
8381 * The cpus mask in sched_group and sched_domain hangs off the end.
8382 * FIXME: use cpumask_var_t or dynamic percpu alloc to avoid wasting space
8383 * for nr_cpu_ids < CONFIG_NR_CPUS.
8385 struct static_sched_group {
8386 struct sched_group sg;
8387 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
8390 struct static_sched_domain {
8391 struct sched_domain sd;
8392 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
8396 * SMT sched-domains:
8398 #ifdef CONFIG_SCHED_SMT
8399 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
8400 static DEFINE_PER_CPU(struct static_sched_group, sched_group_cpus);
8402 static int
8403 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
8404 struct sched_group **sg, struct cpumask *unused)
8406 if (sg)
8407 *sg = &per_cpu(sched_group_cpus, cpu).sg;
8408 return cpu;
8410 #endif /* CONFIG_SCHED_SMT */
8413 * multi-core sched-domains:
8415 #ifdef CONFIG_SCHED_MC
8416 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
8417 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
8418 #endif /* CONFIG_SCHED_MC */
8420 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
8421 static int
8422 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8423 struct sched_group **sg, struct cpumask *mask)
8425 int group;
8427 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8428 group = cpumask_first(mask);
8429 if (sg)
8430 *sg = &per_cpu(sched_group_core, group).sg;
8431 return group;
8433 #elif defined(CONFIG_SCHED_MC)
8434 static int
8435 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8436 struct sched_group **sg, struct cpumask *unused)
8438 if (sg)
8439 *sg = &per_cpu(sched_group_core, cpu).sg;
8440 return cpu;
8442 #endif
8444 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
8445 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
8447 static int
8448 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
8449 struct sched_group **sg, struct cpumask *mask)
8451 int group;
8452 #ifdef CONFIG_SCHED_MC
8453 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
8454 group = cpumask_first(mask);
8455 #elif defined(CONFIG_SCHED_SMT)
8456 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8457 group = cpumask_first(mask);
8458 #else
8459 group = cpu;
8460 #endif
8461 if (sg)
8462 *sg = &per_cpu(sched_group_phys, group).sg;
8463 return group;
8466 #ifdef CONFIG_NUMA
8468 * The init_sched_build_groups can't handle what we want to do with node
8469 * groups, so roll our own. Now each node has its own list of groups which
8470 * gets dynamically allocated.
8472 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
8473 static struct sched_group ***sched_group_nodes_bycpu;
8475 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
8476 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
8478 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
8479 struct sched_group **sg,
8480 struct cpumask *nodemask)
8482 int group;
8484 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
8485 group = cpumask_first(nodemask);
8487 if (sg)
8488 *sg = &per_cpu(sched_group_allnodes, group).sg;
8489 return group;
8492 static void init_numa_sched_groups_power(struct sched_group *group_head)
8494 struct sched_group *sg = group_head;
8495 int j;
8497 if (!sg)
8498 return;
8499 do {
8500 for_each_cpu(j, sched_group_cpus(sg)) {
8501 struct sched_domain *sd;
8503 sd = &per_cpu(phys_domains, j).sd;
8504 if (j != cpumask_first(sched_group_cpus(sd->groups))) {
8506 * Only add "power" once for each
8507 * physical package.
8509 continue;
8512 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
8514 sg = sg->next;
8515 } while (sg != group_head);
8517 #endif /* CONFIG_NUMA */
8519 #ifdef CONFIG_NUMA
8520 /* Free memory allocated for various sched_group structures */
8521 static void free_sched_groups(const struct cpumask *cpu_map,
8522 struct cpumask *nodemask)
8524 int cpu, i;
8526 for_each_cpu(cpu, cpu_map) {
8527 struct sched_group **sched_group_nodes
8528 = sched_group_nodes_bycpu[cpu];
8530 if (!sched_group_nodes)
8531 continue;
8533 for (i = 0; i < nr_node_ids; i++) {
8534 struct sched_group *oldsg, *sg = sched_group_nodes[i];
8536 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8537 if (cpumask_empty(nodemask))
8538 continue;
8540 if (sg == NULL)
8541 continue;
8542 sg = sg->next;
8543 next_sg:
8544 oldsg = sg;
8545 sg = sg->next;
8546 kfree(oldsg);
8547 if (oldsg != sched_group_nodes[i])
8548 goto next_sg;
8550 kfree(sched_group_nodes);
8551 sched_group_nodes_bycpu[cpu] = NULL;
8554 #else /* !CONFIG_NUMA */
8555 static void free_sched_groups(const struct cpumask *cpu_map,
8556 struct cpumask *nodemask)
8559 #endif /* CONFIG_NUMA */
8562 * Initialize sched groups cpu_power.
8564 * cpu_power indicates the capacity of sched group, which is used while
8565 * distributing the load between different sched groups in a sched domain.
8566 * Typically cpu_power for all the groups in a sched domain will be same unless
8567 * there are asymmetries in the topology. If there are asymmetries, group
8568 * having more cpu_power will pickup more load compared to the group having
8569 * less cpu_power.
8571 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
8572 * the maximum number of tasks a group can handle in the presence of other idle
8573 * or lightly loaded groups in the same sched domain.
8575 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
8577 struct sched_domain *child;
8578 struct sched_group *group;
8580 WARN_ON(!sd || !sd->groups);
8582 if (cpu != cpumask_first(sched_group_cpus(sd->groups)))
8583 return;
8585 child = sd->child;
8587 sd->groups->__cpu_power = 0;
8590 * For perf policy, if the groups in child domain share resources
8591 * (for example cores sharing some portions of the cache hierarchy
8592 * or SMT), then set this domain groups cpu_power such that each group
8593 * can handle only one task, when there are other idle groups in the
8594 * same sched domain.
8596 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
8597 (child->flags &
8598 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
8599 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
8600 return;
8604 * add cpu_power of each child group to this groups cpu_power
8606 group = child->groups;
8607 do {
8608 sg_inc_cpu_power(sd->groups, group->__cpu_power);
8609 group = group->next;
8610 } while (group != child->groups);
8614 * Initializers for schedule domains
8615 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
8618 #ifdef CONFIG_SCHED_DEBUG
8619 # define SD_INIT_NAME(sd, type) sd->name = #type
8620 #else
8621 # define SD_INIT_NAME(sd, type) do { } while (0)
8622 #endif
8624 #define SD_INIT(sd, type) sd_init_##type(sd)
8626 #define SD_INIT_FUNC(type) \
8627 static noinline void sd_init_##type(struct sched_domain *sd) \
8629 memset(sd, 0, sizeof(*sd)); \
8630 *sd = SD_##type##_INIT; \
8631 sd->level = SD_LV_##type; \
8632 SD_INIT_NAME(sd, type); \
8635 SD_INIT_FUNC(CPU)
8636 #ifdef CONFIG_NUMA
8637 SD_INIT_FUNC(ALLNODES)
8638 SD_INIT_FUNC(NODE)
8639 #endif
8640 #ifdef CONFIG_SCHED_SMT
8641 SD_INIT_FUNC(SIBLING)
8642 #endif
8643 #ifdef CONFIG_SCHED_MC
8644 SD_INIT_FUNC(MC)
8645 #endif
8647 static int default_relax_domain_level = -1;
8649 static int __init setup_relax_domain_level(char *str)
8651 unsigned long val;
8653 val = simple_strtoul(str, NULL, 0);
8654 if (val < SD_LV_MAX)
8655 default_relax_domain_level = val;
8657 return 1;
8659 __setup("relax_domain_level=", setup_relax_domain_level);
8661 static void set_domain_attribute(struct sched_domain *sd,
8662 struct sched_domain_attr *attr)
8664 int request;
8666 if (!attr || attr->relax_domain_level < 0) {
8667 if (default_relax_domain_level < 0)
8668 return;
8669 else
8670 request = default_relax_domain_level;
8671 } else
8672 request = attr->relax_domain_level;
8673 if (request < sd->level) {
8674 /* turn off idle balance on this domain */
8675 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
8676 } else {
8677 /* turn on idle balance on this domain */
8678 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
8683 * Build sched domains for a given set of cpus and attach the sched domains
8684 * to the individual cpus
8686 static int __build_sched_domains(const struct cpumask *cpu_map,
8687 struct sched_domain_attr *attr)
8689 int i, err = -ENOMEM;
8690 struct root_domain *rd;
8691 cpumask_var_t nodemask, this_sibling_map, this_core_map, send_covered,
8692 tmpmask;
8693 #ifdef CONFIG_NUMA
8694 cpumask_var_t domainspan, covered, notcovered;
8695 struct sched_group **sched_group_nodes = NULL;
8696 int sd_allnodes = 0;
8698 if (!alloc_cpumask_var(&domainspan, GFP_KERNEL))
8699 goto out;
8700 if (!alloc_cpumask_var(&covered, GFP_KERNEL))
8701 goto free_domainspan;
8702 if (!alloc_cpumask_var(&notcovered, GFP_KERNEL))
8703 goto free_covered;
8704 #endif
8706 if (!alloc_cpumask_var(&nodemask, GFP_KERNEL))
8707 goto free_notcovered;
8708 if (!alloc_cpumask_var(&this_sibling_map, GFP_KERNEL))
8709 goto free_nodemask;
8710 if (!alloc_cpumask_var(&this_core_map, GFP_KERNEL))
8711 goto free_this_sibling_map;
8712 if (!alloc_cpumask_var(&send_covered, GFP_KERNEL))
8713 goto free_this_core_map;
8714 if (!alloc_cpumask_var(&tmpmask, GFP_KERNEL))
8715 goto free_send_covered;
8717 #ifdef CONFIG_NUMA
8719 * Allocate the per-node list of sched groups
8721 sched_group_nodes = kcalloc(nr_node_ids, sizeof(struct sched_group *),
8722 GFP_KERNEL);
8723 if (!sched_group_nodes) {
8724 printk(KERN_WARNING "Can not alloc sched group node list\n");
8725 goto free_tmpmask;
8727 #endif
8729 rd = alloc_rootdomain();
8730 if (!rd) {
8731 printk(KERN_WARNING "Cannot alloc root domain\n");
8732 goto free_sched_groups;
8735 #ifdef CONFIG_NUMA
8736 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = sched_group_nodes;
8737 #endif
8740 * Set up domains for cpus specified by the cpu_map.
8742 for_each_cpu(i, cpu_map) {
8743 struct sched_domain *sd = NULL, *p;
8745 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(i)), cpu_map);
8747 #ifdef CONFIG_NUMA
8748 if (cpumask_weight(cpu_map) >
8749 SD_NODES_PER_DOMAIN*cpumask_weight(nodemask)) {
8750 sd = &per_cpu(allnodes_domains, i).sd;
8751 SD_INIT(sd, ALLNODES);
8752 set_domain_attribute(sd, attr);
8753 cpumask_copy(sched_domain_span(sd), cpu_map);
8754 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
8755 p = sd;
8756 sd_allnodes = 1;
8757 } else
8758 p = NULL;
8760 sd = &per_cpu(node_domains, i).sd;
8761 SD_INIT(sd, NODE);
8762 set_domain_attribute(sd, attr);
8763 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
8764 sd->parent = p;
8765 if (p)
8766 p->child = sd;
8767 cpumask_and(sched_domain_span(sd),
8768 sched_domain_span(sd), cpu_map);
8769 #endif
8771 p = sd;
8772 sd = &per_cpu(phys_domains, i).sd;
8773 SD_INIT(sd, CPU);
8774 set_domain_attribute(sd, attr);
8775 cpumask_copy(sched_domain_span(sd), nodemask);
8776 sd->parent = p;
8777 if (p)
8778 p->child = sd;
8779 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
8781 #ifdef CONFIG_SCHED_MC
8782 p = sd;
8783 sd = &per_cpu(core_domains, i).sd;
8784 SD_INIT(sd, MC);
8785 set_domain_attribute(sd, attr);
8786 cpumask_and(sched_domain_span(sd), cpu_map,
8787 cpu_coregroup_mask(i));
8788 sd->parent = p;
8789 p->child = sd;
8790 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
8791 #endif
8793 #ifdef CONFIG_SCHED_SMT
8794 p = sd;
8795 sd = &per_cpu(cpu_domains, i).sd;
8796 SD_INIT(sd, SIBLING);
8797 set_domain_attribute(sd, attr);
8798 cpumask_and(sched_domain_span(sd),
8799 topology_thread_cpumask(i), cpu_map);
8800 sd->parent = p;
8801 p->child = sd;
8802 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
8803 #endif
8806 #ifdef CONFIG_SCHED_SMT
8807 /* Set up CPU (sibling) groups */
8808 for_each_cpu(i, cpu_map) {
8809 cpumask_and(this_sibling_map,
8810 topology_thread_cpumask(i), cpu_map);
8811 if (i != cpumask_first(this_sibling_map))
8812 continue;
8814 init_sched_build_groups(this_sibling_map, cpu_map,
8815 &cpu_to_cpu_group,
8816 send_covered, tmpmask);
8818 #endif
8820 #ifdef CONFIG_SCHED_MC
8821 /* Set up multi-core groups */
8822 for_each_cpu(i, cpu_map) {
8823 cpumask_and(this_core_map, cpu_coregroup_mask(i), cpu_map);
8824 if (i != cpumask_first(this_core_map))
8825 continue;
8827 init_sched_build_groups(this_core_map, cpu_map,
8828 &cpu_to_core_group,
8829 send_covered, tmpmask);
8831 #endif
8833 /* Set up physical groups */
8834 for (i = 0; i < nr_node_ids; i++) {
8835 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8836 if (cpumask_empty(nodemask))
8837 continue;
8839 init_sched_build_groups(nodemask, cpu_map,
8840 &cpu_to_phys_group,
8841 send_covered, tmpmask);
8844 #ifdef CONFIG_NUMA
8845 /* Set up node groups */
8846 if (sd_allnodes) {
8847 init_sched_build_groups(cpu_map, cpu_map,
8848 &cpu_to_allnodes_group,
8849 send_covered, tmpmask);
8852 for (i = 0; i < nr_node_ids; i++) {
8853 /* Set up node groups */
8854 struct sched_group *sg, *prev;
8855 int j;
8857 cpumask_clear(covered);
8858 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8859 if (cpumask_empty(nodemask)) {
8860 sched_group_nodes[i] = NULL;
8861 continue;
8864 sched_domain_node_span(i, domainspan);
8865 cpumask_and(domainspan, domainspan, cpu_map);
8867 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8868 GFP_KERNEL, i);
8869 if (!sg) {
8870 printk(KERN_WARNING "Can not alloc domain group for "
8871 "node %d\n", i);
8872 goto error;
8874 sched_group_nodes[i] = sg;
8875 for_each_cpu(j, nodemask) {
8876 struct sched_domain *sd;
8878 sd = &per_cpu(node_domains, j).sd;
8879 sd->groups = sg;
8881 sg->__cpu_power = 0;
8882 cpumask_copy(sched_group_cpus(sg), nodemask);
8883 sg->next = sg;
8884 cpumask_or(covered, covered, nodemask);
8885 prev = sg;
8887 for (j = 0; j < nr_node_ids; j++) {
8888 int n = (i + j) % nr_node_ids;
8890 cpumask_complement(notcovered, covered);
8891 cpumask_and(tmpmask, notcovered, cpu_map);
8892 cpumask_and(tmpmask, tmpmask, domainspan);
8893 if (cpumask_empty(tmpmask))
8894 break;
8896 cpumask_and(tmpmask, tmpmask, cpumask_of_node(n));
8897 if (cpumask_empty(tmpmask))
8898 continue;
8900 sg = kmalloc_node(sizeof(struct sched_group) +
8901 cpumask_size(),
8902 GFP_KERNEL, i);
8903 if (!sg) {
8904 printk(KERN_WARNING
8905 "Can not alloc domain group for node %d\n", j);
8906 goto error;
8908 sg->__cpu_power = 0;
8909 cpumask_copy(sched_group_cpus(sg), tmpmask);
8910 sg->next = prev->next;
8911 cpumask_or(covered, covered, tmpmask);
8912 prev->next = sg;
8913 prev = sg;
8916 #endif
8918 /* Calculate CPU power for physical packages and nodes */
8919 #ifdef CONFIG_SCHED_SMT
8920 for_each_cpu(i, cpu_map) {
8921 struct sched_domain *sd = &per_cpu(cpu_domains, i).sd;
8923 init_sched_groups_power(i, sd);
8925 #endif
8926 #ifdef CONFIG_SCHED_MC
8927 for_each_cpu(i, cpu_map) {
8928 struct sched_domain *sd = &per_cpu(core_domains, i).sd;
8930 init_sched_groups_power(i, sd);
8932 #endif
8934 for_each_cpu(i, cpu_map) {
8935 struct sched_domain *sd = &per_cpu(phys_domains, i).sd;
8937 init_sched_groups_power(i, sd);
8940 #ifdef CONFIG_NUMA
8941 for (i = 0; i < nr_node_ids; i++)
8942 init_numa_sched_groups_power(sched_group_nodes[i]);
8944 if (sd_allnodes) {
8945 struct sched_group *sg;
8947 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
8948 tmpmask);
8949 init_numa_sched_groups_power(sg);
8951 #endif
8953 /* Attach the domains */
8954 for_each_cpu(i, cpu_map) {
8955 struct sched_domain *sd;
8956 #ifdef CONFIG_SCHED_SMT
8957 sd = &per_cpu(cpu_domains, i).sd;
8958 #elif defined(CONFIG_SCHED_MC)
8959 sd = &per_cpu(core_domains, i).sd;
8960 #else
8961 sd = &per_cpu(phys_domains, i).sd;
8962 #endif
8963 cpu_attach_domain(sd, rd, i);
8966 err = 0;
8968 free_tmpmask:
8969 free_cpumask_var(tmpmask);
8970 free_send_covered:
8971 free_cpumask_var(send_covered);
8972 free_this_core_map:
8973 free_cpumask_var(this_core_map);
8974 free_this_sibling_map:
8975 free_cpumask_var(this_sibling_map);
8976 free_nodemask:
8977 free_cpumask_var(nodemask);
8978 free_notcovered:
8979 #ifdef CONFIG_NUMA
8980 free_cpumask_var(notcovered);
8981 free_covered:
8982 free_cpumask_var(covered);
8983 free_domainspan:
8984 free_cpumask_var(domainspan);
8985 out:
8986 #endif
8987 return err;
8989 free_sched_groups:
8990 #ifdef CONFIG_NUMA
8991 kfree(sched_group_nodes);
8992 #endif
8993 goto free_tmpmask;
8995 #ifdef CONFIG_NUMA
8996 error:
8997 free_sched_groups(cpu_map, tmpmask);
8998 free_rootdomain(rd);
8999 goto free_tmpmask;
9000 #endif
9003 static int build_sched_domains(const struct cpumask *cpu_map)
9005 return __build_sched_domains(cpu_map, NULL);
9008 static struct cpumask *doms_cur; /* current sched domains */
9009 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
9010 static struct sched_domain_attr *dattr_cur;
9011 /* attribues of custom domains in 'doms_cur' */
9014 * Special case: If a kmalloc of a doms_cur partition (array of
9015 * cpumask) fails, then fallback to a single sched domain,
9016 * as determined by the single cpumask fallback_doms.
9018 static cpumask_var_t fallback_doms;
9021 * arch_update_cpu_topology lets virtualized architectures update the
9022 * cpu core maps. It is supposed to return 1 if the topology changed
9023 * or 0 if it stayed the same.
9025 int __attribute__((weak)) arch_update_cpu_topology(void)
9027 return 0;
9031 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
9032 * For now this just excludes isolated cpus, but could be used to
9033 * exclude other special cases in the future.
9035 static int arch_init_sched_domains(const struct cpumask *cpu_map)
9037 int err;
9039 arch_update_cpu_topology();
9040 ndoms_cur = 1;
9041 doms_cur = kmalloc(cpumask_size(), GFP_KERNEL);
9042 if (!doms_cur)
9043 doms_cur = fallback_doms;
9044 cpumask_andnot(doms_cur, cpu_map, cpu_isolated_map);
9045 dattr_cur = NULL;
9046 err = build_sched_domains(doms_cur);
9047 register_sched_domain_sysctl();
9049 return err;
9052 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
9053 struct cpumask *tmpmask)
9055 free_sched_groups(cpu_map, tmpmask);
9059 * Detach sched domains from a group of cpus specified in cpu_map
9060 * These cpus will now be attached to the NULL domain
9062 static void detach_destroy_domains(const struct cpumask *cpu_map)
9064 /* Save because hotplug lock held. */
9065 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
9066 int i;
9068 for_each_cpu(i, cpu_map)
9069 cpu_attach_domain(NULL, &def_root_domain, i);
9070 synchronize_sched();
9071 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
9074 /* handle null as "default" */
9075 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
9076 struct sched_domain_attr *new, int idx_new)
9078 struct sched_domain_attr tmp;
9080 /* fast path */
9081 if (!new && !cur)
9082 return 1;
9084 tmp = SD_ATTR_INIT;
9085 return !memcmp(cur ? (cur + idx_cur) : &tmp,
9086 new ? (new + idx_new) : &tmp,
9087 sizeof(struct sched_domain_attr));
9091 * Partition sched domains as specified by the 'ndoms_new'
9092 * cpumasks in the array doms_new[] of cpumasks. This compares
9093 * doms_new[] to the current sched domain partitioning, doms_cur[].
9094 * It destroys each deleted domain and builds each new domain.
9096 * 'doms_new' is an array of cpumask's of length 'ndoms_new'.
9097 * The masks don't intersect (don't overlap.) We should setup one
9098 * sched domain for each mask. CPUs not in any of the cpumasks will
9099 * not be load balanced. If the same cpumask appears both in the
9100 * current 'doms_cur' domains and in the new 'doms_new', we can leave
9101 * it as it is.
9103 * The passed in 'doms_new' should be kmalloc'd. This routine takes
9104 * ownership of it and will kfree it when done with it. If the caller
9105 * failed the kmalloc call, then it can pass in doms_new == NULL &&
9106 * ndoms_new == 1, and partition_sched_domains() will fallback to
9107 * the single partition 'fallback_doms', it also forces the domains
9108 * to be rebuilt.
9110 * If doms_new == NULL it will be replaced with cpu_online_mask.
9111 * ndoms_new == 0 is a special case for destroying existing domains,
9112 * and it will not create the default domain.
9114 * Call with hotplug lock held
9116 /* FIXME: Change to struct cpumask *doms_new[] */
9117 void partition_sched_domains(int ndoms_new, struct cpumask *doms_new,
9118 struct sched_domain_attr *dattr_new)
9120 int i, j, n;
9121 int new_topology;
9123 mutex_lock(&sched_domains_mutex);
9125 /* always unregister in case we don't destroy any domains */
9126 unregister_sched_domain_sysctl();
9128 /* Let architecture update cpu core mappings. */
9129 new_topology = arch_update_cpu_topology();
9131 n = doms_new ? ndoms_new : 0;
9133 /* Destroy deleted domains */
9134 for (i = 0; i < ndoms_cur; i++) {
9135 for (j = 0; j < n && !new_topology; j++) {
9136 if (cpumask_equal(&doms_cur[i], &doms_new[j])
9137 && dattrs_equal(dattr_cur, i, dattr_new, j))
9138 goto match1;
9140 /* no match - a current sched domain not in new doms_new[] */
9141 detach_destroy_domains(doms_cur + i);
9142 match1:
9146 if (doms_new == NULL) {
9147 ndoms_cur = 0;
9148 doms_new = fallback_doms;
9149 cpumask_andnot(&doms_new[0], cpu_online_mask, cpu_isolated_map);
9150 WARN_ON_ONCE(dattr_new);
9153 /* Build new domains */
9154 for (i = 0; i < ndoms_new; i++) {
9155 for (j = 0; j < ndoms_cur && !new_topology; j++) {
9156 if (cpumask_equal(&doms_new[i], &doms_cur[j])
9157 && dattrs_equal(dattr_new, i, dattr_cur, j))
9158 goto match2;
9160 /* no match - add a new doms_new */
9161 __build_sched_domains(doms_new + i,
9162 dattr_new ? dattr_new + i : NULL);
9163 match2:
9167 /* Remember the new sched domains */
9168 if (doms_cur != fallback_doms)
9169 kfree(doms_cur);
9170 kfree(dattr_cur); /* kfree(NULL) is safe */
9171 doms_cur = doms_new;
9172 dattr_cur = dattr_new;
9173 ndoms_cur = ndoms_new;
9175 register_sched_domain_sysctl();
9177 mutex_unlock(&sched_domains_mutex);
9180 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
9181 static void arch_reinit_sched_domains(void)
9183 get_online_cpus();
9185 /* Destroy domains first to force the rebuild */
9186 partition_sched_domains(0, NULL, NULL);
9188 rebuild_sched_domains();
9189 put_online_cpus();
9192 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
9194 unsigned int level = 0;
9196 if (sscanf(buf, "%u", &level) != 1)
9197 return -EINVAL;
9200 * level is always be positive so don't check for
9201 * level < POWERSAVINGS_BALANCE_NONE which is 0
9202 * What happens on 0 or 1 byte write,
9203 * need to check for count as well?
9206 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
9207 return -EINVAL;
9209 if (smt)
9210 sched_smt_power_savings = level;
9211 else
9212 sched_mc_power_savings = level;
9214 arch_reinit_sched_domains();
9216 return count;
9219 #ifdef CONFIG_SCHED_MC
9220 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
9221 char *page)
9223 return sprintf(page, "%u\n", sched_mc_power_savings);
9225 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
9226 const char *buf, size_t count)
9228 return sched_power_savings_store(buf, count, 0);
9230 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
9231 sched_mc_power_savings_show,
9232 sched_mc_power_savings_store);
9233 #endif
9235 #ifdef CONFIG_SCHED_SMT
9236 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
9237 char *page)
9239 return sprintf(page, "%u\n", sched_smt_power_savings);
9241 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
9242 const char *buf, size_t count)
9244 return sched_power_savings_store(buf, count, 1);
9246 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
9247 sched_smt_power_savings_show,
9248 sched_smt_power_savings_store);
9249 #endif
9251 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
9253 int err = 0;
9255 #ifdef CONFIG_SCHED_SMT
9256 if (smt_capable())
9257 err = sysfs_create_file(&cls->kset.kobj,
9258 &attr_sched_smt_power_savings.attr);
9259 #endif
9260 #ifdef CONFIG_SCHED_MC
9261 if (!err && mc_capable())
9262 err = sysfs_create_file(&cls->kset.kobj,
9263 &attr_sched_mc_power_savings.attr);
9264 #endif
9265 return err;
9267 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
9269 #ifndef CONFIG_CPUSETS
9271 * Add online and remove offline CPUs from the scheduler domains.
9272 * When cpusets are enabled they take over this function.
9274 static int update_sched_domains(struct notifier_block *nfb,
9275 unsigned long action, void *hcpu)
9277 switch (action) {
9278 case CPU_ONLINE:
9279 case CPU_ONLINE_FROZEN:
9280 case CPU_DEAD:
9281 case CPU_DEAD_FROZEN:
9282 partition_sched_domains(1, NULL, NULL);
9283 return NOTIFY_OK;
9285 default:
9286 return NOTIFY_DONE;
9289 #endif
9291 static int update_runtime(struct notifier_block *nfb,
9292 unsigned long action, void *hcpu)
9294 int cpu = (int)(long)hcpu;
9296 switch (action) {
9297 case CPU_DOWN_PREPARE:
9298 case CPU_DOWN_PREPARE_FROZEN:
9299 disable_runtime(cpu_rq(cpu));
9300 return NOTIFY_OK;
9302 case CPU_DOWN_FAILED:
9303 case CPU_DOWN_FAILED_FROZEN:
9304 case CPU_ONLINE:
9305 case CPU_ONLINE_FROZEN:
9306 enable_runtime(cpu_rq(cpu));
9307 return NOTIFY_OK;
9309 default:
9310 return NOTIFY_DONE;
9314 void __init sched_init_smp(void)
9316 cpumask_var_t non_isolated_cpus;
9318 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
9320 #if defined(CONFIG_NUMA)
9321 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
9322 GFP_KERNEL);
9323 BUG_ON(sched_group_nodes_bycpu == NULL);
9324 #endif
9325 get_online_cpus();
9326 mutex_lock(&sched_domains_mutex);
9327 arch_init_sched_domains(cpu_online_mask);
9328 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
9329 if (cpumask_empty(non_isolated_cpus))
9330 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
9331 mutex_unlock(&sched_domains_mutex);
9332 put_online_cpus();
9334 #ifndef CONFIG_CPUSETS
9335 /* XXX: Theoretical race here - CPU may be hotplugged now */
9336 hotcpu_notifier(update_sched_domains, 0);
9337 #endif
9339 /* RT runtime code needs to handle some hotplug events */
9340 hotcpu_notifier(update_runtime, 0);
9342 init_hrtick();
9344 /* Move init over to a non-isolated CPU */
9345 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
9346 BUG();
9347 sched_init_granularity();
9348 free_cpumask_var(non_isolated_cpus);
9350 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
9351 init_sched_rt_class();
9353 #else
9354 void __init sched_init_smp(void)
9356 sched_init_granularity();
9358 #endif /* CONFIG_SMP */
9360 int in_sched_functions(unsigned long addr)
9362 return in_lock_functions(addr) ||
9363 (addr >= (unsigned long)__sched_text_start
9364 && addr < (unsigned long)__sched_text_end);
9367 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
9369 cfs_rq->tasks_timeline = RB_ROOT;
9370 INIT_LIST_HEAD(&cfs_rq->tasks);
9371 #ifdef CONFIG_FAIR_GROUP_SCHED
9372 cfs_rq->rq = rq;
9373 #endif
9374 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
9377 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
9379 struct rt_prio_array *array;
9380 int i;
9382 array = &rt_rq->active;
9383 for (i = 0; i < MAX_RT_PRIO; i++) {
9384 INIT_LIST_HEAD(array->queue + i);
9385 __clear_bit(i, array->bitmap);
9387 /* delimiter for bitsearch: */
9388 __set_bit(MAX_RT_PRIO, array->bitmap);
9390 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
9391 rt_rq->highest_prio.curr = MAX_RT_PRIO;
9392 #ifdef CONFIG_SMP
9393 rt_rq->highest_prio.next = MAX_RT_PRIO;
9394 #endif
9395 #endif
9396 #ifdef CONFIG_SMP
9397 rt_rq->rt_nr_migratory = 0;
9398 rt_rq->overloaded = 0;
9399 plist_head_init(&rq->rt.pushable_tasks, &rq->lock);
9400 #endif
9402 rt_rq->rt_time = 0;
9403 rt_rq->rt_throttled = 0;
9404 rt_rq->rt_runtime = 0;
9405 spin_lock_init(&rt_rq->rt_runtime_lock);
9407 #ifdef CONFIG_RT_GROUP_SCHED
9408 rt_rq->rt_nr_boosted = 0;
9409 rt_rq->rq = rq;
9410 #endif
9413 #ifdef CONFIG_SCHED_CBS
9414 static void init_cbs_rq(struct cbs_rq *cbs_rq, struct rq *rq)
9416 cbs_rq->tasks_timeline = RB_ROOT;
9417 cbs_rq->min_deadline = (u64)(-(1LL << 20));
9419 #else
9420 #define init_cbs_rq(...)
9421 #endif
9424 #ifdef CONFIG_FAIR_GROUP_SCHED
9425 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
9426 struct sched_entity *se, int cpu, int add,
9427 struct sched_entity *parent)
9429 struct rq *rq = cpu_rq(cpu);
9430 tg->cfs_rq[cpu] = cfs_rq;
9431 init_cfs_rq(cfs_rq, rq);
9432 cfs_rq->tg = tg;
9433 if (add)
9434 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
9436 tg->se[cpu] = se;
9437 /* se could be NULL for init_task_group */
9438 if (!se)
9439 return;
9441 if (!parent)
9442 se->cfs_rq = &rq->cfs;
9443 else
9444 se->cfs_rq = parent->my_q;
9446 se->my_q = cfs_rq;
9447 se->load.weight = tg->shares;
9448 se->load.inv_weight = 0;
9449 se->parent = parent;
9451 #endif
9453 #ifdef CONFIG_RT_GROUP_SCHED
9454 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
9455 struct sched_rt_entity *rt_se, int cpu, int add,
9456 struct sched_rt_entity *parent)
9458 struct rq *rq = cpu_rq(cpu);
9460 tg->rt_rq[cpu] = rt_rq;
9461 init_rt_rq(rt_rq, rq);
9462 rt_rq->tg = tg;
9463 rt_rq->rt_se = rt_se;
9464 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
9465 if (add)
9466 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
9468 tg->rt_se[cpu] = rt_se;
9469 if (!rt_se)
9470 return;
9472 if (!parent)
9473 rt_se->rt_rq = &rq->rt;
9474 else
9475 rt_se->rt_rq = parent->my_q;
9477 rt_se->my_q = rt_rq;
9478 rt_se->parent = parent;
9479 INIT_LIST_HEAD(&rt_se->run_list);
9481 #endif
9483 void __init sched_init(void)
9485 int i, j;
9486 unsigned long alloc_size = 0, ptr;
9488 #ifdef CONFIG_FAIR_GROUP_SCHED
9489 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9490 #endif
9491 #ifdef CONFIG_RT_GROUP_SCHED
9492 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9493 #endif
9494 #ifdef CONFIG_USER_SCHED
9495 alloc_size *= 2;
9496 #endif
9497 #ifdef CONFIG_CPUMASK_OFFSTACK
9498 alloc_size += num_possible_cpus() * cpumask_size();
9499 #endif
9501 * As sched_init() is called before page_alloc is setup,
9502 * we use alloc_bootmem().
9504 if (alloc_size) {
9505 ptr = (unsigned long)alloc_bootmem(alloc_size);
9507 #ifdef CONFIG_FAIR_GROUP_SCHED
9508 init_task_group.se = (struct sched_entity **)ptr;
9509 ptr += nr_cpu_ids * sizeof(void **);
9511 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
9512 ptr += nr_cpu_ids * sizeof(void **);
9514 #ifdef CONFIG_USER_SCHED
9515 root_task_group.se = (struct sched_entity **)ptr;
9516 ptr += nr_cpu_ids * sizeof(void **);
9518 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
9519 ptr += nr_cpu_ids * sizeof(void **);
9520 #endif /* CONFIG_USER_SCHED */
9521 #endif /* CONFIG_FAIR_GROUP_SCHED */
9522 #ifdef CONFIG_RT_GROUP_SCHED
9523 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
9524 ptr += nr_cpu_ids * sizeof(void **);
9526 init_task_group.rt_rq = (struct rt_rq **)ptr;
9527 ptr += nr_cpu_ids * sizeof(void **);
9529 #ifdef CONFIG_USER_SCHED
9530 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
9531 ptr += nr_cpu_ids * sizeof(void **);
9533 root_task_group.rt_rq = (struct rt_rq **)ptr;
9534 ptr += nr_cpu_ids * sizeof(void **);
9535 #endif /* CONFIG_USER_SCHED */
9536 #endif /* CONFIG_RT_GROUP_SCHED */
9537 #ifdef CONFIG_CPUMASK_OFFSTACK
9538 for_each_possible_cpu(i) {
9539 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
9540 ptr += cpumask_size();
9542 #endif /* CONFIG_CPUMASK_OFFSTACK */
9545 #ifdef CONFIG_SMP
9546 init_defrootdomain();
9547 #endif
9549 init_rt_bandwidth(&def_rt_bandwidth,
9550 global_rt_period(), global_rt_runtime());
9552 #ifdef CONFIG_RT_GROUP_SCHED
9553 init_rt_bandwidth(&init_task_group.rt_bandwidth,
9554 global_rt_period(), global_rt_runtime());
9555 #ifdef CONFIG_USER_SCHED
9556 init_rt_bandwidth(&root_task_group.rt_bandwidth,
9557 global_rt_period(), RUNTIME_INF);
9558 #endif /* CONFIG_USER_SCHED */
9559 #endif /* CONFIG_RT_GROUP_SCHED */
9561 #ifdef CONFIG_GROUP_SCHED
9562 list_add(&init_task_group.list, &task_groups);
9563 INIT_LIST_HEAD(&init_task_group.children);
9565 #ifdef CONFIG_USER_SCHED
9566 INIT_LIST_HEAD(&root_task_group.children);
9567 init_task_group.parent = &root_task_group;
9568 list_add(&init_task_group.siblings, &root_task_group.children);
9569 #endif /* CONFIG_USER_SCHED */
9570 #endif /* CONFIG_GROUP_SCHED */
9572 for_each_possible_cpu(i) {
9573 struct rq *rq;
9575 rq = cpu_rq(i);
9576 spin_lock_init(&rq->lock);
9577 rq->nr_running = 0;
9578 rq->calc_load_active = 0;
9579 rq->calc_load_update = jiffies + LOAD_FREQ;
9580 init_cfs_rq(&rq->cfs, rq);
9581 init_rt_rq(&rq->rt, rq);
9582 #ifdef CONFIG_SCHED_CBS
9583 init_cbs_rq(&rq->cbs, rq);
9584 #endif
9585 #ifdef CONFIG_FAIR_GROUP_SCHED
9586 init_task_group.shares = init_task_group_load;
9587 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9588 #ifdef CONFIG_CGROUP_SCHED
9590 * How much cpu bandwidth does init_task_group get?
9592 * In case of task-groups formed thr' the cgroup filesystem, it
9593 * gets 100% of the cpu resources in the system. This overall
9594 * system cpu resource is divided among the tasks of
9595 * init_task_group and its child task-groups in a fair manner,
9596 * based on each entity's (task or task-group's) weight
9597 * (se->load.weight).
9599 * In other words, if init_task_group has 10 tasks of weight
9600 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9601 * then A0's share of the cpu resource is:
9603 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9605 * We achieve this by letting init_task_group's tasks sit
9606 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
9608 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
9609 #elif defined CONFIG_USER_SCHED
9610 root_task_group.shares = NICE_0_LOAD;
9611 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
9613 * In case of task-groups formed thr' the user id of tasks,
9614 * init_task_group represents tasks belonging to root user.
9615 * Hence it forms a sibling of all subsequent groups formed.
9616 * In this case, init_task_group gets only a fraction of overall
9617 * system cpu resource, based on the weight assigned to root
9618 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
9619 * by letting tasks of init_task_group sit in a separate cfs_rq
9620 * (init_cfs_rq) and having one entity represent this group of
9621 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
9623 init_tg_cfs_entry(&init_task_group,
9624 &per_cpu(init_cfs_rq, i),
9625 &per_cpu(init_sched_entity, i), i, 1,
9626 root_task_group.se[i]);
9628 #endif
9629 #endif /* CONFIG_FAIR_GROUP_SCHED */
9631 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
9632 #ifdef CONFIG_RT_GROUP_SCHED
9633 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
9634 #ifdef CONFIG_CGROUP_SCHED
9635 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
9636 #elif defined CONFIG_USER_SCHED
9637 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
9638 init_tg_rt_entry(&init_task_group,
9639 &per_cpu(init_rt_rq, i),
9640 &per_cpu(init_sched_rt_entity, i), i, 1,
9641 root_task_group.rt_se[i]);
9642 #endif
9643 #endif
9645 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
9646 rq->cpu_load[j] = 0;
9647 #ifdef CONFIG_SMP
9648 rq->sd = NULL;
9649 rq->rd = NULL;
9650 rq->active_balance = 0;
9651 rq->next_balance = jiffies;
9652 rq->push_cpu = 0;
9653 rq->cpu = i;
9654 rq->online = 0;
9655 rq->migration_thread = NULL;
9656 INIT_LIST_HEAD(&rq->migration_queue);
9657 rq_attach_root(rq, &def_root_domain);
9658 #endif
9659 init_rq_hrtick(rq);
9660 atomic_set(&rq->nr_iowait, 0);
9663 set_load_weight(&init_task);
9665 #ifdef CONFIG_PREEMPT_NOTIFIERS
9666 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
9667 #endif
9669 #ifdef CONFIG_SMP
9670 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9671 #endif
9673 #ifdef CONFIG_RT_MUTEXES
9674 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
9675 #endif
9678 * The boot idle thread does lazy MMU switching as well:
9680 atomic_inc(&init_mm.mm_count);
9681 enter_lazy_tlb(&init_mm, current);
9683 #ifdef CONFIG_PREEMPT_RT
9684 printk("Real-Time Preemption Support (C) 2004-2007 Ingo Molnar\n");
9685 #endif
9687 * Make us the idle thread. Technically, schedule() should not be
9688 * called from this thread, however somewhere below it might be,
9689 * but because we are the idle thread, we just pick up running again
9690 * when this runqueue becomes "idle".
9692 init_idle(current, smp_processor_id());
9694 calc_load_update = jiffies + LOAD_FREQ;
9697 * During early bootup we pretend to be a normal task:
9699 current->sched_class = &fair_sched_class;
9701 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
9702 alloc_bootmem_cpumask_var(&nohz_cpu_mask);
9703 #ifdef CONFIG_SMP
9704 #ifdef CONFIG_NO_HZ
9705 alloc_bootmem_cpumask_var(&nohz.cpu_mask);
9706 #endif
9707 alloc_bootmem_cpumask_var(&cpu_isolated_map);
9708 #endif /* SMP */
9710 scheduler_running = 1;
9713 #ifdef CONFIG_MAGIC_SYSRQ
9714 static void normalize_task(struct rq *rq, struct task_struct *p)
9716 int on_rq;
9718 update_rq_clock(rq);
9719 on_rq = p->se.on_rq;
9720 if (on_rq)
9721 deactivate_task(rq, p, 0);
9722 __setscheduler(rq, p, SCHED_NORMAL, 0);
9723 if (on_rq) {
9724 activate_task(rq, p, 0);
9725 resched_task(rq->curr);
9729 void normalize_rt_tasks(void)
9731 struct task_struct *g, *p;
9732 unsigned long flags;
9733 struct rq *rq;
9735 read_lock_irqsave(&tasklist_lock, flags);
9736 do_each_thread(g, p) {
9738 * Only normalize user tasks:
9740 if (!p->mm)
9741 continue;
9743 p->se.exec_start = 0;
9744 #ifdef CONFIG_SCHEDSTATS
9745 p->se.wait_start = 0;
9746 p->se.sleep_start = 0;
9747 p->se.block_start = 0;
9748 #endif
9750 if (!rt_task(p)) {
9752 * Renice negative nice level userspace
9753 * tasks back to 0:
9755 if (TASK_NICE(p) < 0 && p->mm)
9756 set_user_nice(p, 0);
9757 continue;
9760 spin_lock(&p->pi_lock);
9761 rq = __task_rq_lock(p);
9763 normalize_task(rq, p);
9765 __task_rq_unlock(rq);
9766 spin_unlock(&p->pi_lock);
9767 } while_each_thread(g, p);
9769 read_unlock_irqrestore(&tasklist_lock, flags);
9772 #endif /* CONFIG_MAGIC_SYSRQ */
9774 #ifdef CONFIG_IA64
9776 * These functions are only useful for the IA64 MCA handling.
9778 * They can only be called when the whole system has been
9779 * stopped - every CPU needs to be quiescent, and no scheduling
9780 * activity can take place. Using them for anything else would
9781 * be a serious bug, and as a result, they aren't even visible
9782 * under any other configuration.
9786 * curr_task - return the current task for a given cpu.
9787 * @cpu: the processor in question.
9789 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9791 struct task_struct *curr_task(int cpu)
9793 return cpu_curr(cpu);
9797 * set_curr_task - set the current task for a given cpu.
9798 * @cpu: the processor in question.
9799 * @p: the task pointer to set.
9801 * Description: This function must only be used when non-maskable interrupts
9802 * are serviced on a separate stack. It allows the architecture to switch the
9803 * notion of the current task on a cpu in a non-blocking manner. This function
9804 * must be called with all CPU's synchronized, and interrupts disabled, the
9805 * and caller must save the original value of the current task (see
9806 * curr_task() above) and restore that value before reenabling interrupts and
9807 * re-starting the system.
9809 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9811 void set_curr_task(int cpu, struct task_struct *p)
9813 cpu_curr(cpu) = p;
9816 #endif
9818 #ifdef CONFIG_FAIR_GROUP_SCHED
9819 static void free_fair_sched_group(struct task_group *tg)
9821 int i;
9823 for_each_possible_cpu(i) {
9824 if (tg->cfs_rq)
9825 kfree(tg->cfs_rq[i]);
9826 if (tg->se)
9827 kfree(tg->se[i]);
9830 kfree(tg->cfs_rq);
9831 kfree(tg->se);
9834 static
9835 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9837 struct cfs_rq *cfs_rq;
9838 struct sched_entity *se;
9839 struct rq *rq;
9840 int i;
9842 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
9843 if (!tg->cfs_rq)
9844 goto err;
9845 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
9846 if (!tg->se)
9847 goto err;
9849 tg->shares = NICE_0_LOAD;
9851 for_each_possible_cpu(i) {
9852 rq = cpu_rq(i);
9854 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
9855 GFP_KERNEL, cpu_to_node(i));
9856 if (!cfs_rq)
9857 goto err;
9859 se = kzalloc_node(sizeof(struct sched_entity),
9860 GFP_KERNEL, cpu_to_node(i));
9861 if (!se)
9862 goto err;
9864 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
9867 return 1;
9869 err:
9870 return 0;
9873 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9875 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
9876 &cpu_rq(cpu)->leaf_cfs_rq_list);
9879 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9881 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
9883 #else /* !CONFG_FAIR_GROUP_SCHED */
9884 static inline void free_fair_sched_group(struct task_group *tg)
9888 static inline
9889 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9891 return 1;
9894 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9898 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9901 #endif /* CONFIG_FAIR_GROUP_SCHED */
9903 #ifdef CONFIG_RT_GROUP_SCHED
9904 static void free_rt_sched_group(struct task_group *tg)
9906 int i;
9908 destroy_rt_bandwidth(&tg->rt_bandwidth);
9910 for_each_possible_cpu(i) {
9911 if (tg->rt_rq)
9912 kfree(tg->rt_rq[i]);
9913 if (tg->rt_se)
9914 kfree(tg->rt_se[i]);
9917 kfree(tg->rt_rq);
9918 kfree(tg->rt_se);
9921 static
9922 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9924 struct rt_rq *rt_rq;
9925 struct sched_rt_entity *rt_se;
9926 struct rq *rq;
9927 int i;
9929 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
9930 if (!tg->rt_rq)
9931 goto err;
9932 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
9933 if (!tg->rt_se)
9934 goto err;
9936 init_rt_bandwidth(&tg->rt_bandwidth,
9937 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
9939 for_each_possible_cpu(i) {
9940 rq = cpu_rq(i);
9942 rt_rq = kzalloc_node(sizeof(struct rt_rq),
9943 GFP_KERNEL, cpu_to_node(i));
9944 if (!rt_rq)
9945 goto err;
9947 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
9948 GFP_KERNEL, cpu_to_node(i));
9949 if (!rt_se)
9950 goto err;
9952 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
9955 return 1;
9957 err:
9958 return 0;
9961 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9963 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
9964 &cpu_rq(cpu)->leaf_rt_rq_list);
9967 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9969 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
9971 #else /* !CONFIG_RT_GROUP_SCHED */
9972 static inline void free_rt_sched_group(struct task_group *tg)
9976 static inline
9977 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9979 return 1;
9982 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9986 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9989 #endif /* CONFIG_RT_GROUP_SCHED */
9991 #ifdef CONFIG_GROUP_SCHED
9992 static void free_sched_group(struct task_group *tg)
9994 free_fair_sched_group(tg);
9995 free_rt_sched_group(tg);
9996 kfree(tg);
9999 /* allocate runqueue etc for a new task group */
10000 struct task_group *sched_create_group(struct task_group *parent)
10002 struct task_group *tg;
10003 unsigned long flags;
10004 int i;
10006 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
10007 if (!tg)
10008 return ERR_PTR(-ENOMEM);
10010 if (!alloc_fair_sched_group(tg, parent))
10011 goto err;
10013 if (!alloc_rt_sched_group(tg, parent))
10014 goto err;
10016 spin_lock_irqsave(&task_group_lock, flags);
10017 for_each_possible_cpu(i) {
10018 register_fair_sched_group(tg, i);
10019 register_rt_sched_group(tg, i);
10021 list_add_rcu(&tg->list, &task_groups);
10023 WARN_ON(!parent); /* root should already exist */
10025 tg->parent = parent;
10026 INIT_LIST_HEAD(&tg->children);
10027 list_add_rcu(&tg->siblings, &parent->children);
10028 spin_unlock_irqrestore(&task_group_lock, flags);
10030 return tg;
10032 err:
10033 free_sched_group(tg);
10034 return ERR_PTR(-ENOMEM);
10037 /* rcu callback to free various structures associated with a task group */
10038 static void free_sched_group_rcu(struct rcu_head *rhp)
10040 /* now it should be safe to free those cfs_rqs */
10041 free_sched_group(container_of(rhp, struct task_group, rcu));
10044 /* Destroy runqueue etc associated with a task group */
10045 void sched_destroy_group(struct task_group *tg)
10047 unsigned long flags;
10048 int i;
10050 spin_lock_irqsave(&task_group_lock, flags);
10051 for_each_possible_cpu(i) {
10052 unregister_fair_sched_group(tg, i);
10053 unregister_rt_sched_group(tg, i);
10055 list_del_rcu(&tg->list);
10056 list_del_rcu(&tg->siblings);
10057 spin_unlock_irqrestore(&task_group_lock, flags);
10059 /* wait for possible concurrent references to cfs_rqs complete */
10060 call_rcu(&tg->rcu, free_sched_group_rcu);
10063 /* change task's runqueue when it moves between groups.
10064 * The caller of this function should have put the task in its new group
10065 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
10066 * reflect its new group.
10068 void sched_move_task(struct task_struct *tsk)
10070 int on_rq, running;
10071 unsigned long flags;
10072 struct rq *rq;
10074 rq = task_rq_lock(tsk, &flags);
10076 update_rq_clock(rq);
10078 running = task_current(rq, tsk);
10079 on_rq = tsk->se.on_rq;
10081 if (on_rq)
10082 dequeue_task(rq, tsk, 0);
10083 if (unlikely(running))
10084 tsk->sched_class->put_prev_task(rq, tsk);
10086 set_task_rq(tsk, task_cpu(tsk));
10088 #ifdef CONFIG_FAIR_GROUP_SCHED
10089 if (tsk->sched_class->moved_group)
10090 tsk->sched_class->moved_group(tsk);
10091 #endif
10093 if (unlikely(running))
10094 tsk->sched_class->set_curr_task(rq);
10095 if (on_rq)
10096 enqueue_task(rq, tsk, 0);
10098 task_rq_unlock(rq, &flags);
10100 #endif /* CONFIG_GROUP_SCHED */
10102 #ifdef CONFIG_FAIR_GROUP_SCHED
10103 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
10105 struct cfs_rq *cfs_rq = se->cfs_rq;
10106 int on_rq;
10108 on_rq = se->on_rq;
10109 if (on_rq)
10110 dequeue_entity(cfs_rq, se, 0);
10112 se->load.weight = shares;
10113 se->load.inv_weight = 0;
10115 if (on_rq)
10116 enqueue_entity(cfs_rq, se, 0);
10119 static void set_se_shares(struct sched_entity *se, unsigned long shares)
10121 struct cfs_rq *cfs_rq = se->cfs_rq;
10122 struct rq *rq = cfs_rq->rq;
10123 unsigned long flags;
10125 spin_lock_irqsave(&rq->lock, flags);
10126 __set_se_shares(se, shares);
10127 spin_unlock_irqrestore(&rq->lock, flags);
10130 static DEFINE_MUTEX(shares_mutex);
10132 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
10134 int i;
10135 unsigned long flags;
10138 * We can't change the weight of the root cgroup.
10140 if (!tg->se[0])
10141 return -EINVAL;
10143 if (shares < MIN_SHARES)
10144 shares = MIN_SHARES;
10145 else if (shares > MAX_SHARES)
10146 shares = MAX_SHARES;
10148 mutex_lock(&shares_mutex);
10149 if (tg->shares == shares)
10150 goto done;
10152 spin_lock_irqsave(&task_group_lock, flags);
10153 for_each_possible_cpu(i)
10154 unregister_fair_sched_group(tg, i);
10155 list_del_rcu(&tg->siblings);
10156 spin_unlock_irqrestore(&task_group_lock, flags);
10158 /* wait for any ongoing reference to this group to finish */
10159 synchronize_sched();
10162 * Now we are free to modify the group's share on each cpu
10163 * w/o tripping rebalance_share or load_balance_fair.
10165 tg->shares = shares;
10166 for_each_possible_cpu(i) {
10168 * force a rebalance
10170 cfs_rq_set_shares(tg->cfs_rq[i], 0);
10171 set_se_shares(tg->se[i], shares);
10175 * Enable load balance activity on this group, by inserting it back on
10176 * each cpu's rq->leaf_cfs_rq_list.
10178 spin_lock_irqsave(&task_group_lock, flags);
10179 for_each_possible_cpu(i)
10180 register_fair_sched_group(tg, i);
10181 list_add_rcu(&tg->siblings, &tg->parent->children);
10182 spin_unlock_irqrestore(&task_group_lock, flags);
10183 done:
10184 mutex_unlock(&shares_mutex);
10185 return 0;
10188 unsigned long sched_group_shares(struct task_group *tg)
10190 return tg->shares;
10192 #endif
10194 #ifdef CONFIG_RT_GROUP_SCHED
10196 * Ensure that the real time constraints are schedulable.
10198 static DEFINE_MUTEX(rt_constraints_mutex);
10200 static unsigned long to_ratio(u64 period, u64 runtime)
10202 if (runtime == RUNTIME_INF)
10203 return 1ULL << 20;
10205 return div64_u64(runtime << 20, period);
10208 /* Must be called with tasklist_lock held */
10209 static inline int tg_has_rt_tasks(struct task_group *tg)
10211 struct task_struct *g, *p;
10213 do_each_thread(g, p) {
10214 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
10215 return 1;
10216 } while_each_thread(g, p);
10218 return 0;
10221 struct rt_schedulable_data {
10222 struct task_group *tg;
10223 u64 rt_period;
10224 u64 rt_runtime;
10227 static int tg_schedulable(struct task_group *tg, void *data)
10229 struct rt_schedulable_data *d = data;
10230 struct task_group *child;
10231 unsigned long total, sum = 0;
10232 u64 period, runtime;
10234 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10235 runtime = tg->rt_bandwidth.rt_runtime;
10237 if (tg == d->tg) {
10238 period = d->rt_period;
10239 runtime = d->rt_runtime;
10242 #ifdef CONFIG_USER_SCHED
10243 if (tg == &root_task_group) {
10244 period = global_rt_period();
10245 runtime = global_rt_runtime();
10247 #endif
10250 * Cannot have more runtime than the period.
10252 if (runtime > period && runtime != RUNTIME_INF)
10253 return -EINVAL;
10256 * Ensure we don't starve existing RT tasks.
10258 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
10259 return -EBUSY;
10261 total = to_ratio(period, runtime);
10264 * Nobody can have more than the global setting allows.
10266 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
10267 return -EINVAL;
10270 * The sum of our children's runtime should not exceed our own.
10272 list_for_each_entry_rcu(child, &tg->children, siblings) {
10273 period = ktime_to_ns(child->rt_bandwidth.rt_period);
10274 runtime = child->rt_bandwidth.rt_runtime;
10276 if (child == d->tg) {
10277 period = d->rt_period;
10278 runtime = d->rt_runtime;
10281 sum += to_ratio(period, runtime);
10284 if (sum > total)
10285 return -EINVAL;
10287 return 0;
10290 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
10292 struct rt_schedulable_data data = {
10293 .tg = tg,
10294 .rt_period = period,
10295 .rt_runtime = runtime,
10298 return walk_tg_tree(tg_schedulable, tg_nop, &data);
10301 static int tg_set_bandwidth(struct task_group *tg,
10302 u64 rt_period, u64 rt_runtime)
10304 int i, err = 0;
10306 mutex_lock(&rt_constraints_mutex);
10307 read_lock(&tasklist_lock);
10308 err = __rt_schedulable(tg, rt_period, rt_runtime);
10309 if (err)
10310 goto unlock;
10312 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10313 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
10314 tg->rt_bandwidth.rt_runtime = rt_runtime;
10316 for_each_possible_cpu(i) {
10317 struct rt_rq *rt_rq = tg->rt_rq[i];
10319 spin_lock(&rt_rq->rt_runtime_lock);
10320 rt_rq->rt_runtime = rt_runtime;
10321 spin_unlock(&rt_rq->rt_runtime_lock);
10323 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10324 unlock:
10325 read_unlock(&tasklist_lock);
10326 mutex_unlock(&rt_constraints_mutex);
10328 return err;
10331 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
10333 u64 rt_runtime, rt_period;
10335 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10336 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
10337 if (rt_runtime_us < 0)
10338 rt_runtime = RUNTIME_INF;
10340 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10343 long sched_group_rt_runtime(struct task_group *tg)
10345 u64 rt_runtime_us;
10347 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
10348 return -1;
10350 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
10351 do_div(rt_runtime_us, NSEC_PER_USEC);
10352 return rt_runtime_us;
10355 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
10357 u64 rt_runtime, rt_period;
10359 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
10360 rt_runtime = tg->rt_bandwidth.rt_runtime;
10362 if (rt_period == 0)
10363 return -EINVAL;
10365 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10368 long sched_group_rt_period(struct task_group *tg)
10370 u64 rt_period_us;
10372 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
10373 do_div(rt_period_us, NSEC_PER_USEC);
10374 return rt_period_us;
10377 static int sched_rt_global_constraints(void)
10379 u64 runtime, period;
10380 int ret = 0;
10382 if (sysctl_sched_rt_period <= 0)
10383 return -EINVAL;
10385 runtime = global_rt_runtime();
10386 period = global_rt_period();
10389 * Sanity check on the sysctl variables.
10391 if (runtime > period && runtime != RUNTIME_INF)
10392 return -EINVAL;
10394 mutex_lock(&rt_constraints_mutex);
10395 read_lock(&tasklist_lock);
10396 ret = __rt_schedulable(NULL, 0, 0);
10397 read_unlock(&tasklist_lock);
10398 mutex_unlock(&rt_constraints_mutex);
10400 return ret;
10403 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
10405 /* Don't accept realtime tasks when there is no way for them to run */
10406 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
10407 return 0;
10409 return 1;
10412 #else /* !CONFIG_RT_GROUP_SCHED */
10413 static int sched_rt_global_constraints(void)
10415 unsigned long flags;
10416 int i;
10418 if (sysctl_sched_rt_period <= 0)
10419 return -EINVAL;
10421 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
10422 for_each_possible_cpu(i) {
10423 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
10425 spin_lock(&rt_rq->rt_runtime_lock);
10426 rt_rq->rt_runtime = global_rt_runtime();
10427 spin_unlock(&rt_rq->rt_runtime_lock);
10429 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
10431 return 0;
10433 #endif /* CONFIG_RT_GROUP_SCHED */
10435 int sched_rt_handler(struct ctl_table *table, int write,
10436 struct file *filp, void __user *buffer, size_t *lenp,
10437 loff_t *ppos)
10439 int ret;
10440 int old_period, old_runtime;
10441 static DEFINE_MUTEX(mutex);
10443 mutex_lock(&mutex);
10444 old_period = sysctl_sched_rt_period;
10445 old_runtime = sysctl_sched_rt_runtime;
10447 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
10449 if (!ret && write) {
10450 ret = sched_rt_global_constraints();
10451 if (ret) {
10452 sysctl_sched_rt_period = old_period;
10453 sysctl_sched_rt_runtime = old_runtime;
10454 } else {
10455 def_rt_bandwidth.rt_runtime = global_rt_runtime();
10456 def_rt_bandwidth.rt_period =
10457 ns_to_ktime(global_rt_period());
10460 mutex_unlock(&mutex);
10462 return ret;
10465 #ifdef CONFIG_CGROUP_SCHED
10467 /* return corresponding task_group object of a cgroup */
10468 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
10470 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
10471 struct task_group, css);
10474 static struct cgroup_subsys_state *
10475 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
10477 struct task_group *tg, *parent;
10479 if (!cgrp->parent) {
10480 /* This is early initialization for the top cgroup */
10481 return &init_task_group.css;
10484 parent = cgroup_tg(cgrp->parent);
10485 tg = sched_create_group(parent);
10486 if (IS_ERR(tg))
10487 return ERR_PTR(-ENOMEM);
10489 return &tg->css;
10492 static void
10493 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10495 struct task_group *tg = cgroup_tg(cgrp);
10497 sched_destroy_group(tg);
10500 static int
10501 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10502 struct task_struct *tsk)
10504 #ifdef CONFIG_RT_GROUP_SCHED
10505 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
10506 return -EINVAL;
10507 #else
10508 /* We don't support RT-tasks being in separate groups */
10509 if (tsk->sched_class != &fair_sched_class)
10510 return -EINVAL;
10511 #endif
10513 return 0;
10516 static void
10517 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10518 struct cgroup *old_cont, struct task_struct *tsk)
10520 sched_move_task(tsk);
10523 #ifdef CONFIG_FAIR_GROUP_SCHED
10524 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
10525 u64 shareval)
10527 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
10530 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
10532 struct task_group *tg = cgroup_tg(cgrp);
10534 return (u64) tg->shares;
10536 #endif /* CONFIG_FAIR_GROUP_SCHED */
10538 #ifdef CONFIG_RT_GROUP_SCHED
10539 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
10540 s64 val)
10542 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
10545 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
10547 return sched_group_rt_runtime(cgroup_tg(cgrp));
10550 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
10551 u64 rt_period_us)
10553 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
10556 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
10558 return sched_group_rt_period(cgroup_tg(cgrp));
10560 #endif /* CONFIG_RT_GROUP_SCHED */
10562 static struct cftype cpu_files[] = {
10563 #ifdef CONFIG_FAIR_GROUP_SCHED
10565 .name = "shares",
10566 .read_u64 = cpu_shares_read_u64,
10567 .write_u64 = cpu_shares_write_u64,
10569 #endif
10570 #ifdef CONFIG_RT_GROUP_SCHED
10572 .name = "rt_runtime_us",
10573 .read_s64 = cpu_rt_runtime_read,
10574 .write_s64 = cpu_rt_runtime_write,
10577 .name = "rt_period_us",
10578 .read_u64 = cpu_rt_period_read_uint,
10579 .write_u64 = cpu_rt_period_write_uint,
10581 #endif
10584 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
10586 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
10589 struct cgroup_subsys cpu_cgroup_subsys = {
10590 .name = "cpu",
10591 .create = cpu_cgroup_create,
10592 .destroy = cpu_cgroup_destroy,
10593 .can_attach = cpu_cgroup_can_attach,
10594 .attach = cpu_cgroup_attach,
10595 .populate = cpu_cgroup_populate,
10596 .subsys_id = cpu_cgroup_subsys_id,
10597 .early_init = 1,
10600 #endif /* CONFIG_CGROUP_SCHED */
10602 #ifdef CONFIG_CGROUP_CPUACCT
10605 * CPU accounting code for task groups.
10607 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
10608 * (balbir@in.ibm.com).
10611 /* track cpu usage of a group of tasks and its child groups */
10612 struct cpuacct {
10613 struct cgroup_subsys_state css;
10614 /* cpuusage holds pointer to a u64-type object on every cpu */
10615 u64 *cpuusage;
10616 struct cpuacct *parent;
10619 struct cgroup_subsys cpuacct_subsys;
10621 /* return cpu accounting group corresponding to this container */
10622 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
10624 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
10625 struct cpuacct, css);
10628 /* return cpu accounting group to which this task belongs */
10629 static inline struct cpuacct *task_ca(struct task_struct *tsk)
10631 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
10632 struct cpuacct, css);
10635 /* create a new cpu accounting group */
10636 static struct cgroup_subsys_state *cpuacct_create(
10637 struct cgroup_subsys *ss, struct cgroup *cgrp)
10639 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
10641 if (!ca)
10642 return ERR_PTR(-ENOMEM);
10644 ca->cpuusage = alloc_percpu(u64);
10645 if (!ca->cpuusage) {
10646 kfree(ca);
10647 return ERR_PTR(-ENOMEM);
10650 if (cgrp->parent)
10651 ca->parent = cgroup_ca(cgrp->parent);
10653 return &ca->css;
10656 /* destroy an existing cpu accounting group */
10657 static void
10658 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10660 struct cpuacct *ca = cgroup_ca(cgrp);
10662 free_percpu(ca->cpuusage);
10663 kfree(ca);
10666 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
10668 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10669 u64 data;
10671 #ifndef CONFIG_64BIT
10673 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
10675 spin_lock_irq(&cpu_rq(cpu)->lock);
10676 data = *cpuusage;
10677 spin_unlock_irq(&cpu_rq(cpu)->lock);
10678 #else
10679 data = *cpuusage;
10680 #endif
10682 return data;
10685 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
10687 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10689 #ifndef CONFIG_64BIT
10691 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
10693 spin_lock_irq(&cpu_rq(cpu)->lock);
10694 *cpuusage = val;
10695 spin_unlock_irq(&cpu_rq(cpu)->lock);
10696 #else
10697 *cpuusage = val;
10698 #endif
10701 /* return total cpu usage (in nanoseconds) of a group */
10702 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
10704 struct cpuacct *ca = cgroup_ca(cgrp);
10705 u64 totalcpuusage = 0;
10706 int i;
10708 for_each_present_cpu(i)
10709 totalcpuusage += cpuacct_cpuusage_read(ca, i);
10711 return totalcpuusage;
10714 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
10715 u64 reset)
10717 struct cpuacct *ca = cgroup_ca(cgrp);
10718 int err = 0;
10719 int i;
10721 if (reset) {
10722 err = -EINVAL;
10723 goto out;
10726 for_each_present_cpu(i)
10727 cpuacct_cpuusage_write(ca, i, 0);
10729 out:
10730 return err;
10733 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
10734 struct seq_file *m)
10736 struct cpuacct *ca = cgroup_ca(cgroup);
10737 u64 percpu;
10738 int i;
10740 for_each_present_cpu(i) {
10741 percpu = cpuacct_cpuusage_read(ca, i);
10742 seq_printf(m, "%llu ", (unsigned long long) percpu);
10744 seq_printf(m, "\n");
10745 return 0;
10748 static struct cftype files[] = {
10750 .name = "usage",
10751 .read_u64 = cpuusage_read,
10752 .write_u64 = cpuusage_write,
10755 .name = "usage_percpu",
10756 .read_seq_string = cpuacct_percpu_seq_read,
10761 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
10763 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
10767 * charge this task's execution time to its accounting group.
10769 * called with rq->lock held.
10771 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
10773 struct cpuacct *ca;
10774 int cpu;
10776 if (unlikely(!cpuacct_subsys.active))
10777 return;
10779 cpu = task_cpu(tsk);
10781 rcu_read_lock();
10782 ca = task_ca(tsk);
10784 do {
10785 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10786 *cpuusage += cputime;
10787 ca = ca->parent;
10788 } while (ca);
10789 rcu_read_unlock();
10792 struct cgroup_subsys cpuacct_subsys = {
10793 .name = "cpuacct",
10794 .create = cpuacct_create,
10795 .destroy = cpuacct_destroy,
10796 .populate = cpuacct_populate,
10797 .subsys_id = cpuacct_subsys_id,
10799 #endif /* CONFIG_CGROUP_CPUACCT */