making the kernel build with up to date compilers again, see https://bbs.archlinux...
[nao-ulib.git] / kernel / 2.6.29.6-aldebaran-rt / kernel / sched.c
blobbe79f6737b234c2c62bc4bd1e1c8f67308568a04
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_SMP
568 * We add the notion of a root-domain which will be used to define per-domain
569 * variables. Each exclusive cpuset essentially defines an island domain by
570 * fully partitioning the member cpus from any other cpuset. Whenever a new
571 * exclusive cpuset is created, we also create and attach a new root-domain
572 * object.
575 struct root_domain {
576 atomic_t refcount;
577 cpumask_var_t span;
578 cpumask_var_t online;
581 * The "RT overload" flag: it gets set if a CPU has more than
582 * one runnable RT task.
584 cpumask_var_t rto_mask;
585 atomic_t rto_count;
586 #ifdef CONFIG_SMP
587 struct cpupri cpupri;
588 #endif
589 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
591 * Preferred wake up cpu nominated by sched_mc balance that will be
592 * used when most cpus are idle in the system indicating overall very
593 * low system utilisation. Triggered at POWERSAVINGS_BALANCE_WAKEUP(2)
595 unsigned int sched_mc_preferred_wakeup_cpu;
596 #endif
600 * By default the system creates a single root-domain with all cpus as
601 * members (mimicking the global state we have today).
603 static struct root_domain def_root_domain;
605 #endif
608 * This is the main, per-CPU runqueue data structure.
610 * Locking rule: those places that want to lock multiple runqueues
611 * (such as the load balancing or the thread migration code), lock
612 * acquire operations must be ordered by ascending &runqueue.
614 struct rq {
615 /* runqueue lock: */
616 raw_spinlock_t lock;
619 * nr_running and cpu_load should be in the same cacheline because
620 * remote CPUs use both these fields when doing load calculation.
622 unsigned long nr_running;
623 #define CPU_LOAD_IDX_MAX 5
624 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
625 #ifdef CONFIG_NO_HZ
626 unsigned long last_tick_seen;
627 unsigned char in_nohz_recently;
628 #endif
629 /* capture load from *all* tasks on this cpu: */
630 struct load_weight load;
631 unsigned long nr_load_updates;
632 u64 nr_switches;
633 u64 nr_migrations_in;
635 struct cfs_rq cfs;
636 struct rt_rq rt;
638 #ifdef CONFIG_FAIR_GROUP_SCHED
639 /* list of leaf cfs_rq on this cpu: */
640 struct list_head leaf_cfs_rq_list;
641 #endif
642 #ifdef CONFIG_RT_GROUP_SCHED
643 struct list_head leaf_rt_rq_list;
644 #endif
647 * This is part of a global counter where only the total sum
648 * over all CPUs matters. A task can increase this counter on
649 * one CPU and if it got migrated afterwards it may decrease
650 * it on another CPU. Always updated under the runqueue lock:
652 unsigned long nr_uninterruptible;
654 unsigned long switch_timestamp;
655 unsigned long slice_avg;
656 struct task_struct *curr, *idle;
657 unsigned long next_balance;
658 struct mm_struct *prev_mm;
660 u64 clock;
662 atomic_t nr_iowait;
664 #ifdef CONFIG_SMP
665 struct root_domain *rd;
666 struct sched_domain *sd;
668 unsigned char idle_at_tick;
669 /* For active balancing */
670 int active_balance;
671 int push_cpu;
672 /* cpu of this runqueue: */
673 int cpu;
674 int online;
676 unsigned long avg_load_per_task;
678 struct task_struct *migration_thread;
679 struct list_head migration_queue;
680 #endif
682 /* calc_load related fields */
683 unsigned long calc_load_update;
684 long calc_load_active;
686 #ifdef CONFIG_SCHED_HRTICK
687 #ifdef CONFIG_SMP
688 int hrtick_csd_pending;
689 struct call_single_data hrtick_csd;
690 #endif
691 struct hrtimer hrtick_timer;
692 #endif
694 #ifdef CONFIG_SCHEDSTATS
695 /* latency stats */
696 struct sched_info rq_sched_info;
697 unsigned long long rq_cpu_time;
698 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
700 /* sys_sched_yield() stats */
701 unsigned int yld_count;
703 /* schedule() stats */
704 unsigned int sched_switch;
705 unsigned int sched_count;
706 unsigned int sched_goidle;
708 /* try_to_wake_up() stats */
709 unsigned int ttwu_count;
710 unsigned int ttwu_local;
712 /* BKL stats */
713 unsigned int bkl_count;
715 /* RT-overload stats: */
716 unsigned long rto_schedule;
717 unsigned long rto_schedule_tail;
718 unsigned long rto_wakeup;
719 unsigned long rto_pulled;
720 unsigned long rto_pushed;
721 #endif
724 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
726 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p, int sync)
728 rq->curr->sched_class->check_preempt_curr(rq, p, sync);
731 static inline int cpu_of(struct rq *rq)
733 #ifdef CONFIG_SMP
734 return rq->cpu;
735 #else
736 return 0;
737 #endif
741 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
742 * See detach_destroy_domains: synchronize_sched for details.
744 * The domain tree of any CPU may only be accessed from within
745 * preempt-disabled sections.
747 #define for_each_domain(cpu, __sd) \
748 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
750 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
751 #define this_rq() (&__get_cpu_var(runqueues))
752 #define task_rq(p) cpu_rq(task_cpu(p))
753 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
755 inline void update_rq_clock(struct rq *rq)
757 rq->clock = sched_clock_cpu(cpu_of(rq));
760 #ifndef CONFIG_SMP
761 int task_is_current(struct task_struct *task)
763 return task_rq(task)->curr == task;
765 #endif
768 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
770 #ifdef CONFIG_SCHED_DEBUG
771 # define const_debug __read_mostly
772 #else
773 # define const_debug static const
774 #endif
777 * runqueue_is_locked
779 * Returns true if the current cpu runqueue is locked.
780 * This interface allows printk to be called with the runqueue lock
781 * held and know whether or not it is OK to wake up the klogd.
783 int runqueue_is_locked(void)
785 int cpu = get_cpu();
786 struct rq *rq = cpu_rq(cpu);
787 int ret;
789 ret = spin_is_locked(&rq->lock);
790 put_cpu();
791 return ret;
795 * Debugging: various feature bits
798 #define SCHED_FEAT(name, enabled) \
799 __SCHED_FEAT_##name ,
801 enum {
802 #include "sched_features.h"
805 #undef SCHED_FEAT
807 #define SCHED_FEAT(name, enabled) \
808 (1UL << __SCHED_FEAT_##name) * enabled |
810 const_debug unsigned int sysctl_sched_features =
811 #include "sched_features.h"
814 #undef SCHED_FEAT
816 #ifdef CONFIG_SCHED_DEBUG
817 #define SCHED_FEAT(name, enabled) \
818 #name ,
820 static __read_mostly char *sched_feat_names[] = {
821 #include "sched_features.h"
822 NULL
825 #undef SCHED_FEAT
827 static int sched_feat_show(struct seq_file *m, void *v)
829 int i;
831 for (i = 0; sched_feat_names[i]; i++) {
832 if (!(sysctl_sched_features & (1UL << i)))
833 seq_puts(m, "NO_");
834 seq_printf(m, "%s ", sched_feat_names[i]);
836 seq_puts(m, "\n");
838 return 0;
841 static ssize_t
842 sched_feat_write(struct file *filp, const char __user *ubuf,
843 size_t cnt, loff_t *ppos)
845 char buf[64];
846 char *cmp = buf;
847 int neg = 0;
848 int i;
850 if (cnt > 63)
851 cnt = 63;
853 if (copy_from_user(&buf, ubuf, cnt))
854 return -EFAULT;
856 buf[cnt] = 0;
858 if (strncmp(buf, "NO_", 3) == 0) {
859 neg = 1;
860 cmp += 3;
863 for (i = 0; sched_feat_names[i]; i++) {
864 int len = strlen(sched_feat_names[i]);
866 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
867 if (neg)
868 sysctl_sched_features &= ~(1UL << i);
869 else
870 sysctl_sched_features |= (1UL << i);
871 break;
875 if (!sched_feat_names[i])
876 return -EINVAL;
878 filp->f_pos += cnt;
880 return cnt;
883 static int sched_feat_open(struct inode *inode, struct file *filp)
885 return single_open(filp, sched_feat_show, NULL);
888 static struct file_operations sched_feat_fops = {
889 .open = sched_feat_open,
890 .write = sched_feat_write,
891 .read = seq_read,
892 .llseek = seq_lseek,
893 .release = single_release,
896 static __init int sched_init_debug(void)
898 debugfs_create_file("sched_features", 0644, NULL, NULL,
899 &sched_feat_fops);
901 return 0;
903 late_initcall(sched_init_debug);
905 #endif
907 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
910 * Number of tasks to iterate in a single balance run.
911 * Limited because this is done with IRQs disabled.
913 const_debug unsigned int sysctl_sched_nr_migrate = 32;
916 * ratelimit for updating the group shares.
917 * default: 0.25ms
919 unsigned int sysctl_sched_shares_ratelimit = 250000;
922 * Inject some fuzzyness into changing the per-cpu group shares
923 * this avoids remote rq-locks at the expense of fairness.
924 * default: 4
926 unsigned int sysctl_sched_shares_thresh = 4;
929 * period over which we measure -rt task cpu usage in us.
930 * default: 1s
932 unsigned int sysctl_sched_rt_period = 1000000;
934 static __read_mostly int scheduler_running;
937 * part of the period that we allow rt tasks to run in us.
938 * default: 0.95s
940 int sysctl_sched_rt_runtime = 950000;
942 static inline u64 global_rt_period(void)
944 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
947 static inline u64 global_rt_runtime(void)
949 if (sysctl_sched_rt_runtime < 0)
950 return RUNTIME_INF;
952 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
956 * We really dont want to do anything complex within switch_to()
957 * on PREEMPT_RT - this check enforces this.
959 #ifdef prepare_arch_switch
960 # ifdef CONFIG_PREEMPT_RT
961 # error FIXME
962 # else
963 # define _finish_arch_switch finish_arch_switch
964 # endif
965 #endif
967 #ifndef prepare_arch_switch
968 # define prepare_arch_switch(next) do { } while (0)
969 #endif
970 #ifndef finish_arch_switch
971 # define _finish_arch_switch(prev) do { } while (0)
972 #endif
974 static inline int task_current(struct rq *rq, struct task_struct *p)
976 return rq->curr == p;
979 static inline int task_running(struct rq *rq, struct task_struct *p)
981 #ifdef CONFIG_SMP
982 return p->oncpu;
983 #else
984 return task_current(rq, p);
985 #endif
988 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
989 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
991 #ifdef CONFIG_SMP
993 * We can optimise this out completely for !SMP, because the
994 * SMP rebalancing from interrupt is the only thing that cares
995 * here.
997 next->oncpu = 1;
998 #endif
1001 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
1003 #ifdef CONFIG_SMP
1005 * After ->oncpu is cleared, the task can be moved to a different CPU.
1006 * We must ensure this doesn't happen until the switch is completely
1007 * finished.
1009 smp_wmb();
1010 prev->oncpu = 0;
1011 #endif
1012 #ifdef CONFIG_DEBUG_SPINLOCK
1013 /* this is a valid case when another task releases the spinlock */
1014 rq->lock.owner = current;
1015 #endif
1017 * If we are tracking spinlock dependencies then we have to
1018 * fix up the runqueue lock - which gets 'carried over' from
1019 * prev into current:
1021 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
1023 spin_unlock(&rq->lock);
1026 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
1028 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
1030 #ifdef CONFIG_SMP
1032 * We can optimise this out completely for !SMP, because the
1033 * SMP rebalancing from interrupt is the only thing that cares
1034 * here.
1036 next->oncpu = 1;
1037 #endif
1038 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1039 spin_unlock_irq(&rq->lock);
1040 #else
1041 spin_unlock(&rq->lock);
1042 #endif
1045 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
1047 #ifdef CONFIG_SMP
1049 * After ->oncpu is cleared, the task can be moved to a different CPU.
1050 * We must ensure this doesn't happen until the switch is completely
1051 * finished.
1053 smp_wmb();
1054 prev->oncpu = 0;
1055 #endif
1056 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1057 local_irq_disable();
1058 #endif
1060 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1063 * __task_rq_lock - lock the runqueue a given task resides on.
1064 * Must be called interrupts disabled.
1066 static inline struct rq *__task_rq_lock(struct task_struct *p)
1067 __acquires(rq->lock)
1069 for (;;) {
1070 struct rq *rq = task_rq(p);
1071 spin_lock(&rq->lock);
1072 if (likely(rq == task_rq(p)))
1073 return rq;
1074 spin_unlock(&rq->lock);
1079 * task_rq_lock - lock the runqueue a given task resides on and disable
1080 * interrupts. Note the ordering: we can safely lookup the task_rq without
1081 * explicitly disabling preemption.
1083 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1084 __acquires(rq->lock)
1086 struct rq *rq;
1088 for (;;) {
1089 local_irq_save(*flags);
1090 rq = task_rq(p);
1091 spin_lock(&rq->lock);
1092 if (likely(rq == task_rq(p)))
1093 return rq;
1094 spin_unlock_irqrestore(&rq->lock, *flags);
1098 void curr_rq_lock_irq_save(unsigned long *flags)
1099 __acquires(rq->lock)
1101 struct rq *rq;
1103 local_irq_save(*flags);
1104 rq = cpu_rq(smp_processor_id());
1105 spin_lock(&rq->lock);
1108 void curr_rq_unlock_irq_restore(unsigned long *flags)
1109 __releases(rq->lock)
1111 struct rq *rq;
1113 rq = cpu_rq(smp_processor_id());
1114 spin_unlock(&rq->lock);
1115 local_irq_restore(*flags);
1118 void task_rq_unlock_wait(struct task_struct *p)
1120 struct rq *rq = task_rq(p);
1122 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
1123 spin_unlock_wait(&rq->lock);
1126 static void __task_rq_unlock(struct rq *rq)
1127 __releases(rq->lock)
1129 spin_unlock(&rq->lock);
1132 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1133 __releases(rq->lock)
1135 spin_unlock_irqrestore(&rq->lock, *flags);
1139 * this_rq_lock - lock this runqueue and disable interrupts.
1141 static struct rq *this_rq_lock(void)
1142 __acquires(rq->lock)
1144 struct rq *rq;
1146 local_irq_disable();
1147 rq = this_rq();
1148 spin_lock(&rq->lock);
1150 return rq;
1153 #ifdef CONFIG_SCHED_HRTICK
1155 * Use HR-timers to deliver accurate preemption points.
1157 * Its all a bit involved since we cannot program an hrt while holding the
1158 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1159 * reschedule event.
1161 * When we get rescheduled we reprogram the hrtick_timer outside of the
1162 * rq->lock.
1166 * Use hrtick when:
1167 * - enabled by features
1168 * - hrtimer is actually high res
1170 static inline int hrtick_enabled(struct rq *rq)
1172 if (!sched_feat(HRTICK))
1173 return 0;
1174 if (!cpu_active(cpu_of(rq)))
1175 return 0;
1176 return hrtimer_is_hres_active(&rq->hrtick_timer);
1179 static void hrtick_clear(struct rq *rq)
1181 if (hrtimer_active(&rq->hrtick_timer))
1182 hrtimer_cancel(&rq->hrtick_timer);
1186 * High-resolution timer tick.
1187 * Runs from hardirq context with interrupts disabled.
1189 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1191 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1193 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1195 spin_lock(&rq->lock);
1196 update_rq_clock(rq);
1197 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1198 spin_unlock(&rq->lock);
1200 return HRTIMER_NORESTART;
1203 #ifdef CONFIG_SMP
1205 * called from hardirq (IPI) context
1207 static void __hrtick_start(void *arg)
1209 struct rq *rq = arg;
1211 spin_lock(&rq->lock);
1212 hrtimer_restart(&rq->hrtick_timer);
1213 rq->hrtick_csd_pending = 0;
1214 spin_unlock(&rq->lock);
1218 * Called to set the hrtick timer state.
1220 * called with rq->lock held and irqs disabled
1222 static void hrtick_start(struct rq *rq, u64 delay)
1224 struct hrtimer *timer = &rq->hrtick_timer;
1225 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1227 hrtimer_set_expires(timer, time);
1229 if (rq == this_rq()) {
1230 hrtimer_restart(timer);
1231 } else if (!rq->hrtick_csd_pending) {
1232 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1233 rq->hrtick_csd_pending = 1;
1237 static int
1238 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1240 int cpu = (int)(long)hcpu;
1242 switch (action) {
1243 case CPU_UP_CANCELED:
1244 case CPU_UP_CANCELED_FROZEN:
1245 case CPU_DOWN_PREPARE:
1246 case CPU_DOWN_PREPARE_FROZEN:
1247 case CPU_DEAD:
1248 case CPU_DEAD_FROZEN:
1249 hrtick_clear(cpu_rq(cpu));
1250 return NOTIFY_OK;
1253 return NOTIFY_DONE;
1256 static __init void init_hrtick(void)
1258 hotcpu_notifier(hotplug_hrtick, 0);
1260 #else
1262 * Called to set the hrtick timer state.
1264 * called with rq->lock held and irqs disabled
1266 static void hrtick_start(struct rq *rq, u64 delay)
1268 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1269 HRTIMER_MODE_REL, 0);
1272 static inline void init_hrtick(void)
1275 #endif /* CONFIG_SMP */
1277 static void init_rq_hrtick(struct rq *rq)
1279 #ifdef CONFIG_SMP
1280 rq->hrtick_csd_pending = 0;
1282 rq->hrtick_csd.flags = 0;
1283 rq->hrtick_csd.func = __hrtick_start;
1284 rq->hrtick_csd.info = rq;
1285 #endif
1287 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1288 rq->hrtick_timer.function = hrtick;
1289 rq->hrtick_timer.irqsafe = 1;
1291 #else /* CONFIG_SCHED_HRTICK */
1292 static inline void hrtick_clear(struct rq *rq)
1296 static inline void init_rq_hrtick(struct rq *rq)
1300 static inline void init_hrtick(void)
1303 #endif /* CONFIG_SCHED_HRTICK */
1306 * resched_task - mark a task 'to be rescheduled now'.
1308 * On UP this means the setting of the need_resched flag, on SMP it
1309 * might also involve a cross-CPU call to trigger the scheduler on
1310 * the target CPU.
1312 #ifdef CONFIG_SMP
1314 #ifndef tsk_is_polling
1315 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1316 #endif
1318 static void resched_task(struct task_struct *p)
1320 int cpu;
1322 assert_spin_locked(&task_rq(p)->lock);
1324 if (test_tsk_need_resched(p))
1325 return;
1327 set_tsk_need_resched(p);
1329 cpu = task_cpu(p);
1330 if (cpu == smp_processor_id())
1331 return;
1333 /* NEED_RESCHED must be visible before we test polling */
1334 smp_mb();
1335 if (!tsk_is_polling(p))
1336 smp_send_reschedule(cpu);
1339 static void resched_cpu(int cpu)
1341 struct rq *rq = cpu_rq(cpu);
1342 unsigned long flags;
1344 if (!spin_trylock_irqsave(&rq->lock, flags))
1345 return;
1346 resched_task(cpu_curr(cpu));
1347 spin_unlock_irqrestore(&rq->lock, flags);
1350 #ifdef CONFIG_NO_HZ
1352 * When add_timer_on() enqueues a timer into the timer wheel of an
1353 * idle CPU then this timer might expire before the next timer event
1354 * which is scheduled to wake up that CPU. In case of a completely
1355 * idle system the next event might even be infinite time into the
1356 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1357 * leaves the inner idle loop so the newly added timer is taken into
1358 * account when the CPU goes back to idle and evaluates the timer
1359 * wheel for the next timer event.
1361 void wake_up_idle_cpu(int cpu)
1363 struct rq *rq = cpu_rq(cpu);
1365 if (cpu == raw_smp_processor_id())
1366 return;
1369 * This is safe, as this function is called with the timer
1370 * wheel base lock of (cpu) held. When the CPU is on the way
1371 * to idle and has not yet set rq->curr to idle then it will
1372 * be serialized on the timer wheel base lock and take the new
1373 * timer into account automatically.
1375 if (rq->curr != rq->idle)
1376 return;
1379 * We can set TIF_RESCHED on the idle task of the other CPU
1380 * lockless. The worst case is that the other CPU runs the
1381 * idle task through an additional NOOP schedule()
1383 set_tsk_need_resched(rq->idle);
1385 /* NEED_RESCHED must be visible before we test polling */
1386 smp_mb();
1387 if (!tsk_is_polling(rq->idle))
1388 smp_send_reschedule(cpu);
1390 #endif /* CONFIG_NO_HZ */
1392 #else /* !CONFIG_SMP */
1393 static void resched_task(struct task_struct *p)
1395 assert_spin_locked(&task_rq(p)->lock);
1396 set_tsk_need_resched(p);
1398 #endif /* CONFIG_SMP */
1400 #if BITS_PER_LONG == 32
1401 # define WMULT_CONST (~0UL)
1402 #else
1403 # define WMULT_CONST (1UL << 32)
1404 #endif
1406 #define WMULT_SHIFT 32
1409 * Shift right and round:
1411 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1414 * delta *= weight / lw
1416 static unsigned long
1417 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1418 struct load_weight *lw)
1420 u64 tmp;
1422 if (!lw->inv_weight) {
1423 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1424 lw->inv_weight = 1;
1425 else
1426 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1427 / (lw->weight+1);
1430 tmp = (u64)delta_exec * weight;
1432 * Check whether we'd overflow the 64-bit multiplication:
1434 if (unlikely(tmp > WMULT_CONST))
1435 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1436 WMULT_SHIFT/2);
1437 else
1438 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1440 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1443 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1445 lw->weight += inc;
1446 lw->inv_weight = 0;
1449 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1451 lw->weight -= dec;
1452 lw->inv_weight = 0;
1456 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1457 * of tasks with abnormal "nice" values across CPUs the contribution that
1458 * each task makes to its run queue's load is weighted according to its
1459 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1460 * scaled version of the new time slice allocation that they receive on time
1461 * slice expiry etc.
1464 #define WEIGHT_IDLEPRIO 3
1465 #define WMULT_IDLEPRIO 1431655765
1468 * Nice levels are multiplicative, with a gentle 10% change for every
1469 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1470 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1471 * that remained on nice 0.
1473 * The "10% effect" is relative and cumulative: from _any_ nice level,
1474 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1475 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1476 * If a task goes up by ~10% and another task goes down by ~10% then
1477 * the relative distance between them is ~25%.)
1479 static const int prio_to_weight[40] = {
1480 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1481 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1482 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1483 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1484 /* 0 */ 1024, 820, 655, 526, 423,
1485 /* 5 */ 335, 272, 215, 172, 137,
1486 /* 10 */ 110, 87, 70, 56, 45,
1487 /* 15 */ 36, 29, 23, 18, 15,
1491 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1493 * In cases where the weight does not change often, we can use the
1494 * precalculated inverse to speed up arithmetics by turning divisions
1495 * into multiplications:
1497 static const u32 prio_to_wmult[40] = {
1498 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1499 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1500 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1501 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1502 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1503 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1504 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1505 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1508 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1511 * runqueue iterator, to support SMP load-balancing between different
1512 * scheduling classes, without having to expose their internal data
1513 * structures to the load-balancing proper:
1515 struct rq_iterator {
1516 void *arg;
1517 struct task_struct *(*start)(void *);
1518 struct task_struct *(*next)(void *);
1521 #ifdef CONFIG_SMP
1522 static unsigned long
1523 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1524 unsigned long max_load_move, struct sched_domain *sd,
1525 enum cpu_idle_type idle, int *all_pinned,
1526 int *this_best_prio, struct rq_iterator *iterator);
1528 static int
1529 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1530 struct sched_domain *sd, enum cpu_idle_type idle,
1531 struct rq_iterator *iterator);
1532 #endif
1534 #ifdef CONFIG_CGROUP_CPUACCT
1535 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1536 #else
1537 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1538 #endif
1540 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1542 update_load_add(&rq->load, load);
1545 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1547 update_load_sub(&rq->load, load);
1550 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1551 typedef int (*tg_visitor)(struct task_group *, void *);
1554 * Iterate the full tree, calling @down when first entering a node and @up when
1555 * leaving it for the final time.
1557 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1559 struct task_group *parent, *child;
1560 int ret;
1562 rcu_read_lock();
1563 parent = &root_task_group;
1564 down:
1565 ret = (*down)(parent, data);
1566 if (ret)
1567 goto out_unlock;
1568 list_for_each_entry_rcu(child, &parent->children, siblings) {
1569 parent = child;
1570 goto down;
1573 continue;
1575 ret = (*up)(parent, data);
1576 if (ret)
1577 goto out_unlock;
1579 child = parent;
1580 parent = parent->parent;
1581 if (parent)
1582 goto up;
1583 out_unlock:
1584 rcu_read_unlock();
1586 return ret;
1589 static int tg_nop(struct task_group *tg, void *data)
1591 return 0;
1593 #endif
1595 #ifdef CONFIG_SMP
1596 static unsigned long source_load(int cpu, int type);
1597 static unsigned long target_load(int cpu, int type);
1598 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1600 static unsigned long cpu_avg_load_per_task(int cpu)
1602 struct rq *rq = cpu_rq(cpu);
1603 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1605 if (nr_running)
1606 rq->avg_load_per_task = rq->load.weight / nr_running;
1607 else
1608 rq->avg_load_per_task = 0;
1610 return rq->avg_load_per_task;
1613 #ifdef CONFIG_FAIR_GROUP_SCHED
1615 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1618 * Calculate and set the cpu's group shares.
1620 static void
1621 update_group_shares_cpu(struct task_group *tg, int cpu,
1622 unsigned long sd_shares, unsigned long sd_rq_weight)
1624 unsigned long shares;
1625 unsigned long rq_weight;
1627 if (!tg->se[cpu])
1628 return;
1630 rq_weight = tg->cfs_rq[cpu]->rq_weight;
1633 * \Sum shares * rq_weight
1634 * shares = -----------------------
1635 * \Sum rq_weight
1638 shares = (sd_shares * rq_weight) / sd_rq_weight;
1639 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1641 if (abs(shares - tg->se[cpu]->load.weight) >
1642 sysctl_sched_shares_thresh) {
1643 struct rq *rq = cpu_rq(cpu);
1644 unsigned long flags;
1646 spin_lock_irqsave(&rq->lock, flags);
1647 tg->cfs_rq[cpu]->shares = shares;
1649 __set_se_shares(tg->se[cpu], shares);
1650 spin_unlock_irqrestore(&rq->lock, flags);
1655 * Re-compute the task group their per cpu shares over the given domain.
1656 * This needs to be done in a bottom-up fashion because the rq weight of a
1657 * parent group depends on the shares of its child groups.
1659 static int tg_shares_up(struct task_group *tg, void *data)
1661 unsigned long weight, rq_weight = 0;
1662 unsigned long shares = 0;
1663 struct sched_domain *sd = data;
1664 int i;
1666 for_each_cpu(i, sched_domain_span(sd)) {
1668 * If there are currently no tasks on the cpu pretend there
1669 * is one of average load so that when a new task gets to
1670 * run here it will not get delayed by group starvation.
1672 weight = tg->cfs_rq[i]->load.weight;
1673 if (!weight)
1674 weight = NICE_0_LOAD;
1676 tg->cfs_rq[i]->rq_weight = weight;
1677 rq_weight += weight;
1678 shares += tg->cfs_rq[i]->shares;
1681 if ((!shares && rq_weight) || shares > tg->shares)
1682 shares = tg->shares;
1684 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1685 shares = tg->shares;
1687 for_each_cpu(i, sched_domain_span(sd))
1688 update_group_shares_cpu(tg, i, shares, rq_weight);
1690 return 0;
1694 * Compute the cpu's hierarchical load factor for each task group.
1695 * This needs to be done in a top-down fashion because the load of a child
1696 * group is a fraction of its parents load.
1698 static int tg_load_down(struct task_group *tg, void *data)
1700 unsigned long load;
1701 long cpu = (long)data;
1703 if (!tg->parent) {
1704 load = cpu_rq(cpu)->load.weight;
1705 } else {
1706 load = tg->parent->cfs_rq[cpu]->h_load;
1707 load *= tg->cfs_rq[cpu]->shares;
1708 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1711 tg->cfs_rq[cpu]->h_load = load;
1713 return 0;
1716 static void update_shares(struct sched_domain *sd)
1718 u64 now = cpu_clock(raw_smp_processor_id());
1719 s64 elapsed = now - sd->last_update;
1721 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1722 sd->last_update = now;
1723 walk_tg_tree(tg_nop, tg_shares_up, sd);
1727 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1729 spin_unlock(&rq->lock);
1730 update_shares(sd);
1731 spin_lock(&rq->lock);
1734 static void update_h_load(long cpu)
1736 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1739 #else
1741 static inline void update_shares(struct sched_domain *sd)
1745 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1749 #endif
1751 #ifdef CONFIG_PREEMPT
1754 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1755 * way at the expense of forcing extra atomic operations in all
1756 * invocations. This assures that the double_lock is acquired using the
1757 * same underlying policy as the spinlock_t on this architecture, which
1758 * reduces latency compared to the unfair variant below. However, it
1759 * also adds more overhead and therefore may reduce throughput.
1761 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1762 __releases(this_rq->lock)
1763 __acquires(busiest->lock)
1764 __acquires(this_rq->lock)
1766 spin_unlock(&this_rq->lock);
1767 double_rq_lock(this_rq, busiest);
1769 return 1;
1772 #else
1774 * Unfair double_lock_balance: Optimizes throughput at the expense of
1775 * latency by eliminating extra atomic operations when the locks are
1776 * already in proper order on entry. This favors lower cpu-ids and will
1777 * grant the double lock to lower cpus over higher ids under contention,
1778 * regardless of entry order into the function.
1780 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1781 __releases(this_rq->lock)
1782 __acquires(busiest->lock)
1783 __acquires(this_rq->lock)
1785 int ret = 0;
1787 if (unlikely(!spin_trylock(&busiest->lock))) {
1788 if (busiest < this_rq) {
1789 spin_unlock(&this_rq->lock);
1790 spin_lock(&busiest->lock);
1791 spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING);
1792 ret = 1;
1793 } else
1794 spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING);
1796 return ret;
1799 #endif /* CONFIG_PREEMPT */
1802 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1804 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1806 if (unlikely(!irqs_disabled())) {
1807 /* printk() doesn't work good under rq->lock */
1808 spin_unlock(&this_rq->lock);
1809 BUG_ON(1);
1812 return _double_lock_balance(this_rq, busiest);
1815 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1816 __releases(busiest->lock)
1818 spin_unlock(&busiest->lock);
1819 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1821 #endif
1823 #ifdef CONFIG_FAIR_GROUP_SCHED
1824 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1826 #ifdef CONFIG_SMP
1827 cfs_rq->shares = shares;
1828 #endif
1830 #endif
1832 static void calc_load_account_active(struct rq *this_rq);
1834 #include "sched_stats.h"
1835 #include "sched_idletask.c"
1836 #include "sched_fair.c"
1837 #include "sched_rt.c"
1838 #ifdef CONFIG_SCHED_DEBUG
1839 # include "sched_debug.c"
1840 #endif
1842 #define sched_class_highest (&rt_sched_class)
1843 #define for_each_class(class) \
1844 for (class = sched_class_highest; class; class = class->next)
1846 static void inc_nr_running(struct rq *rq)
1848 rq->nr_running++;
1851 static void dec_nr_running(struct rq *rq)
1853 rq->nr_running--;
1856 static void set_load_weight(struct task_struct *p)
1858 if (task_has_rt_policy(p)) {
1859 p->se.load.weight = prio_to_weight[0] * 2;
1860 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1861 return;
1865 * SCHED_IDLE tasks get minimal weight:
1867 if (p->policy == SCHED_IDLE) {
1868 p->se.load.weight = WEIGHT_IDLEPRIO;
1869 p->se.load.inv_weight = WMULT_IDLEPRIO;
1870 return;
1873 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1874 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1877 static void update_avg(u64 *avg, u64 sample)
1879 s64 diff = sample - *avg;
1880 *avg += diff >> 3;
1883 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1885 if (wakeup)
1886 p->se.start_runtime = p->se.sum_exec_runtime;
1888 sched_info_queued(p);
1889 p->sched_class->enqueue_task(rq, p, wakeup);
1890 p->se.on_rq = 1;
1893 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1895 if (sleep) {
1896 if (p->se.last_wakeup) {
1897 update_avg(&p->se.avg_overlap,
1898 p->se.sum_exec_runtime - p->se.last_wakeup);
1899 p->se.last_wakeup = 0;
1900 } else {
1901 update_avg(&p->se.avg_wakeup,
1902 sysctl_sched_wakeup_granularity);
1906 sched_info_dequeued(p);
1907 p->sched_class->dequeue_task(rq, p, sleep);
1908 p->se.on_rq = 0;
1912 * __normal_prio - return the priority that is based on the static prio
1914 static inline int __normal_prio(struct task_struct *p)
1916 return p->static_prio;
1920 * Calculate the expected normal priority: i.e. priority
1921 * without taking RT-inheritance into account. Might be
1922 * boosted by interactivity modifiers. Changes upon fork,
1923 * setprio syscalls, and whenever the interactivity
1924 * estimator recalculates.
1926 static inline int normal_prio(struct task_struct *p)
1928 int prio;
1930 if (task_has_rt_policy(p))
1931 prio = MAX_RT_PRIO-1 - p->rt_priority;
1932 else
1933 prio = __normal_prio(p);
1935 // trace_special_pid(p->pid, PRIO(p), __PRIO(prio));
1936 return prio;
1940 * Calculate the current priority, i.e. the priority
1941 * taken into account by the scheduler. This value might
1942 * be boosted by RT tasks, or might be boosted by
1943 * interactivity modifiers. Will be RT if the task got
1944 * RT-boosted. If not then it returns p->normal_prio.
1946 static int effective_prio(struct task_struct *p)
1948 p->normal_prio = normal_prio(p);
1950 * If we are RT tasks or we were boosted to RT priority,
1951 * keep the priority unchanged. Otherwise, update priority
1952 * to the normal priority:
1954 if (!rt_prio(p->prio))
1955 return p->normal_prio;
1956 return p->prio;
1960 * activate_task - move a task to the runqueue.
1962 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1964 if (task_contributes_to_load(p))
1965 rq->nr_uninterruptible--;
1967 enqueue_task(rq, p, wakeup);
1968 inc_nr_running(rq);
1972 * deactivate_task - remove a task from the runqueue.
1974 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1976 if (task_contributes_to_load(p))
1977 rq->nr_uninterruptible++;
1979 dequeue_task(rq, p, sleep);
1980 dec_nr_running(rq);
1984 * task_curr - is this task currently executing on a CPU?
1985 * @p: the task in question.
1987 inline int task_curr(const struct task_struct *p)
1989 return cpu_curr(task_cpu(p)) == p;
1992 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1994 set_task_rq(p, cpu);
1995 #ifdef CONFIG_SMP
1997 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1998 * successfuly executed on another CPU. We must ensure that updates of
1999 * per-task data have been completed by this moment.
2001 smp_wmb();
2002 task_thread_info(p)->cpu = cpu;
2003 #endif
2006 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2007 const struct sched_class *prev_class,
2008 int oldprio, int running)
2010 if (prev_class != p->sched_class) {
2011 if (prev_class->switched_from)
2012 prev_class->switched_from(rq, p, running);
2013 p->sched_class->switched_to(rq, p, running);
2014 } else
2015 p->sched_class->prio_changed(rq, p, oldprio, running);
2018 #ifdef CONFIG_SMP
2020 /* Used instead of source_load when we know the type == 0 */
2021 static unsigned long weighted_cpuload(const int cpu)
2023 return cpu_rq(cpu)->load.weight;
2027 * Is this task likely cache-hot:
2029 static int
2030 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2032 s64 delta;
2035 * Buddy candidates are cache hot:
2037 if (sched_feat(CACHE_HOT_BUDDY) &&
2038 (&p->se == cfs_rq_of(&p->se)->next ||
2039 &p->se == cfs_rq_of(&p->se)->last))
2040 return 1;
2042 if (p->sched_class != &fair_sched_class)
2043 return 0;
2045 if (sysctl_sched_migration_cost == -1)
2046 return 1;
2047 if (sysctl_sched_migration_cost == 0)
2048 return 0;
2050 delta = now - p->se.exec_start;
2052 return delta < (s64)sysctl_sched_migration_cost;
2056 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2058 int old_cpu = task_cpu(p);
2059 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2060 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2061 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2062 u64 clock_offset;
2064 clock_offset = old_rq->clock - new_rq->clock;
2066 trace_sched_migrate_task(p, task_cpu(p), new_cpu);
2068 #ifdef CONFIG_SCHEDSTATS
2069 if (p->se.wait_start)
2070 p->se.wait_start -= clock_offset;
2071 if (p->se.sleep_start)
2072 p->se.sleep_start -= clock_offset;
2073 if (p->se.block_start)
2074 p->se.block_start -= clock_offset;
2075 #endif
2076 if (old_cpu != new_cpu) {
2077 p->se.nr_migrations++;
2078 new_rq->nr_migrations_in++;
2079 #ifdef CONFIG_SCHEDSTATS
2080 if (task_hot(p, old_rq->clock, NULL))
2081 schedstat_inc(p, se.nr_forced2_migrations);
2082 #endif
2084 p->se.vruntime -= old_cfsrq->min_vruntime -
2085 new_cfsrq->min_vruntime;
2087 __set_task_cpu(p, new_cpu);
2090 struct migration_req {
2091 struct list_head list;
2093 struct task_struct *task;
2094 int dest_cpu;
2096 struct completion done;
2100 * The task's runqueue lock must be held.
2101 * Returns true if you have to wait for migration thread.
2103 static int
2104 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2106 struct rq *rq = task_rq(p);
2109 * If the task is not on a runqueue (and not running), then
2110 * it is sufficient to simply update the task's cpu field.
2112 if (!p->se.on_rq && !task_running(rq, p)) {
2113 set_task_cpu(p, dest_cpu);
2114 return 0;
2117 init_completion(&req->done);
2118 req->task = p;
2119 req->dest_cpu = dest_cpu;
2120 list_add(&req->list, &rq->migration_queue);
2122 return 1;
2126 * wait_task_inactive - wait for a thread to unschedule.
2128 * If @match_state is nonzero, it's the @p->state value just checked and
2129 * not expected to change. If it changes, i.e. @p might have woken up,
2130 * then return zero. When we succeed in waiting for @p to be off its CPU,
2131 * we return a positive number (its total switch count). If a second call
2132 * a short while later returns the same number, the caller can be sure that
2133 * @p has remained unscheduled the whole time.
2135 * The caller must ensure that the task *will* unschedule sometime soon,
2136 * else this function might spin for a *long* time. This function can't
2137 * be called with interrupts off, or it may introduce deadlock with
2138 * smp_call_function() if an IPI is sent by the same process we are
2139 * waiting to become inactive.
2141 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2143 unsigned long flags;
2144 int running, on_rq;
2145 unsigned long ncsw;
2146 struct rq *rq;
2148 for (;;) {
2150 * We do the initial early heuristics without holding
2151 * any task-queue locks at all. We'll only try to get
2152 * the runqueue lock when things look like they will
2153 * work out!
2155 rq = task_rq(p);
2158 * If the task is actively running on another CPU
2159 * still, just relax and busy-wait without holding
2160 * any locks.
2162 * NOTE! Since we don't hold any locks, it's not
2163 * even sure that "rq" stays as the right runqueue!
2164 * But we don't care, since "task_running()" will
2165 * return false if the runqueue has changed and p
2166 * is actually now running somewhere else!
2168 while (task_running(rq, p)) {
2169 if (match_state && unlikely(p->state != match_state))
2170 return 0;
2171 cpu_relax();
2175 * Ok, time to look more closely! We need the rq
2176 * lock now, to be *sure*. If we're wrong, we'll
2177 * just go back and repeat.
2179 rq = task_rq_lock(p, &flags);
2180 trace_sched_wait_task(rq, p);
2181 running = task_running(rq, p);
2182 on_rq = p->se.on_rq;
2183 ncsw = 0;
2184 if (!match_state || p->state == match_state)
2185 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2186 task_rq_unlock(rq, &flags);
2189 * If it changed from the expected state, bail out now.
2191 if (unlikely(!ncsw))
2192 break;
2195 * Was it really running after all now that we
2196 * checked with the proper locks actually held?
2198 * Oops. Go back and try again..
2200 if (unlikely(running)) {
2201 cpu_relax();
2202 continue;
2206 * It's not enough that it's not actively running,
2207 * it must be off the runqueue _entirely_, and not
2208 * preempted!
2210 * So if it was still runnable (but just not actively
2211 * running right now), it's preempted, and we should
2212 * yield - it could be a while.
2214 if (unlikely(on_rq)) {
2215 schedule_timeout_uninterruptible(1);
2216 continue;
2220 * Ahh, all good. It wasn't running, and it wasn't
2221 * runnable, which means that it will never become
2222 * running in the future either. We're all done!
2224 break;
2227 return ncsw;
2230 /***
2231 * kick_process - kick a running thread to enter/exit the kernel
2232 * @p: the to-be-kicked thread
2234 * Cause a process which is running on another CPU to enter
2235 * kernel-mode, without any delay. (to get signals handled.)
2237 * NOTE: this function doesnt have to take the runqueue lock,
2238 * because all it wants to ensure is that the remote task enters
2239 * the kernel. If the IPI races and the task has been migrated
2240 * to another CPU then no harm is done and the purpose has been
2241 * achieved as well.
2243 void kick_process(struct task_struct *p)
2245 int cpu;
2247 preempt_disable();
2248 cpu = task_cpu(p);
2249 if ((cpu != smp_processor_id()) && task_curr(p))
2250 smp_send_reschedule(cpu);
2251 preempt_enable();
2255 * Return a low guess at the load of a migration-source cpu weighted
2256 * according to the scheduling class and "nice" value.
2258 * We want to under-estimate the load of migration sources, to
2259 * balance conservatively.
2261 static unsigned long source_load(int cpu, int type)
2263 struct rq *rq = cpu_rq(cpu);
2264 unsigned long total = weighted_cpuload(cpu);
2266 if (type == 0 || !sched_feat(LB_BIAS))
2267 return total;
2269 return min(rq->cpu_load[type-1], total);
2273 * Return a high guess at the load of a migration-target cpu weighted
2274 * according to the scheduling class and "nice" value.
2276 static unsigned long target_load(int cpu, int type)
2278 struct rq *rq = cpu_rq(cpu);
2279 unsigned long total = weighted_cpuload(cpu);
2281 if (type == 0 || !sched_feat(LB_BIAS))
2282 return total;
2284 return max(rq->cpu_load[type-1], total);
2288 * find_idlest_group finds and returns the least busy CPU group within the
2289 * domain.
2291 static struct sched_group *
2292 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2294 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2295 unsigned long min_load = ULONG_MAX, this_load = 0;
2296 int load_idx = sd->forkexec_idx;
2297 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2299 do {
2300 unsigned long load, avg_load;
2301 int local_group;
2302 int i;
2304 /* Skip over this group if it has no CPUs allowed */
2305 if (!cpumask_intersects(sched_group_cpus(group),
2306 &p->cpus_allowed))
2307 continue;
2309 local_group = cpumask_test_cpu(this_cpu,
2310 sched_group_cpus(group));
2312 /* Tally up the load of all CPUs in the group */
2313 avg_load = 0;
2315 for_each_cpu(i, sched_group_cpus(group)) {
2316 /* Bias balancing toward cpus of our domain */
2317 if (local_group)
2318 load = source_load(i, load_idx);
2319 else
2320 load = target_load(i, load_idx);
2322 avg_load += load;
2325 /* Adjust by relative CPU power of the group */
2326 avg_load = sg_div_cpu_power(group,
2327 avg_load * SCHED_LOAD_SCALE);
2329 if (local_group) {
2330 this_load = avg_load;
2331 this = group;
2332 } else if (avg_load < min_load) {
2333 min_load = avg_load;
2334 idlest = group;
2336 } while (group = group->next, group != sd->groups);
2338 if (!idlest || 100*this_load < imbalance*min_load)
2339 return NULL;
2340 return idlest;
2344 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2346 static int
2347 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2349 unsigned long load, min_load = ULONG_MAX;
2350 int idlest = -1;
2351 int i;
2353 /* Traverse only the allowed CPUs */
2354 for_each_cpu_and(i, sched_group_cpus(group), &p->cpus_allowed) {
2355 load = weighted_cpuload(i);
2357 if (load < min_load || (load == min_load && i == this_cpu)) {
2358 min_load = load;
2359 idlest = i;
2363 return idlest;
2367 * sched_balance_self: balance the current task (running on cpu) in domains
2368 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2369 * SD_BALANCE_EXEC.
2371 * Balance, ie. select the least loaded group.
2373 * Returns the target CPU number, or the same CPU if no balancing is needed.
2375 * preempt must be disabled.
2377 static int sched_balance_self(int cpu, int flag)
2379 struct task_struct *t = current;
2380 struct sched_domain *tmp, *sd = NULL;
2382 for_each_domain(cpu, tmp) {
2384 * If power savings logic is enabled for a domain, stop there.
2386 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2387 break;
2388 if (tmp->flags & flag)
2389 sd = tmp;
2392 if (sd)
2393 update_shares(sd);
2395 while (sd) {
2396 struct sched_group *group;
2397 int new_cpu, weight;
2399 if (!(sd->flags & flag)) {
2400 sd = sd->child;
2401 continue;
2404 group = find_idlest_group(sd, t, cpu);
2405 if (!group) {
2406 sd = sd->child;
2407 continue;
2410 new_cpu = find_idlest_cpu(group, t, cpu);
2411 if (new_cpu == -1 || new_cpu == cpu) {
2412 /* Now try balancing at a lower domain level of cpu */
2413 sd = sd->child;
2414 continue;
2417 /* Now try balancing at a lower domain level of new_cpu */
2418 cpu = new_cpu;
2419 weight = cpumask_weight(sched_domain_span(sd));
2420 sd = NULL;
2421 for_each_domain(cpu, tmp) {
2422 if (weight <= cpumask_weight(sched_domain_span(tmp)))
2423 break;
2424 if (tmp->flags & flag)
2425 sd = tmp;
2427 /* while loop will break here if sd == NULL */
2430 return cpu;
2433 #endif /* CONFIG_SMP */
2435 #ifdef CONFIG_DEBUG_PREEMPT
2436 void notrace preempt_enable_no_resched(void)
2438 static int once = 1;
2440 barrier();
2441 dec_preempt_count();
2443 if (once && !preempt_count()) {
2444 once = 0;
2445 printk(KERN_ERR "BUG: %s:%d task might have lost a preemption check!\n",
2446 current->comm, current->pid);
2447 dump_stack();
2451 EXPORT_SYMBOL(preempt_enable_no_resched);
2452 #endif
2456 * task_oncpu_function_call - call a function on the cpu on which a task runs
2457 * @p: the task to evaluate
2458 * @func: the function to be called
2459 * @info: the function call argument
2461 * Calls the function @func when the task is currently running. This might
2462 * be on the current CPU, which just calls the function directly
2464 void task_oncpu_function_call(struct task_struct *p,
2465 void (*func) (void *info), void *info)
2467 int cpu;
2469 preempt_disable();
2470 cpu = task_cpu(p);
2471 if (task_curr(p))
2472 smp_call_function_single(cpu, func, info, 1);
2473 preempt_enable();
2476 /***
2477 * try_to_wake_up - wake up a thread
2478 * @p: the to-be-woken-up thread
2479 * @state: the mask of task states that can be woken
2480 * @sync: do a synchronous wakeup?
2482 * Put it on the run-queue if it's not already there. The "current"
2483 * thread is always on the run-queue (except when the actual
2484 * re-schedule is in progress), and as such you're allowed to do
2485 * the simpler "current->state = TASK_RUNNING" to mark yourself
2486 * runnable without the overhead of this.
2488 * returns failure only if the task is already active.
2490 static int
2491 try_to_wake_up(struct task_struct *p, unsigned int state, int sync, int mutex)
2493 int cpu, orig_cpu, this_cpu, success = 0;
2494 unsigned long flags;
2495 long old_state;
2496 struct rq *rq;
2498 if (!sched_feat(SYNC_WAKEUPS))
2499 sync = 0;
2501 #ifdef CONFIG_SMP
2502 if (sched_feat(LB_WAKEUP_UPDATE) && !root_task_group_empty()) {
2503 struct sched_domain *sd;
2505 this_cpu = raw_smp_processor_id();
2506 cpu = task_cpu(p);
2508 for_each_domain(this_cpu, sd) {
2509 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2510 update_shares(sd);
2511 break;
2515 #endif
2517 #ifdef CONFIG_PREEMPT_RT
2519 * sync wakeups can increase wakeup latencies:
2521 if (rt_task(p))
2522 sync = 0;
2523 #endif
2524 smp_wmb();
2525 rq = task_rq_lock(p, &flags);
2526 update_rq_clock(rq);
2527 old_state = p->state;
2528 if (!(old_state & state))
2529 goto out;
2531 if (p->se.on_rq)
2532 goto out_running;
2534 cpu = task_cpu(p);
2535 orig_cpu = cpu;
2536 this_cpu = smp_processor_id();
2538 #ifdef CONFIG_SMP
2539 if (unlikely(task_running(rq, p)))
2540 goto out_activate;
2542 cpu = p->sched_class->select_task_rq(p, sync);
2543 if (cpu != orig_cpu) {
2544 set_task_cpu(p, cpu);
2545 task_rq_unlock(rq, &flags);
2546 /* might preempt at this point */
2547 rq = task_rq_lock(p, &flags);
2548 old_state = p->state;
2549 if (!(old_state & state))
2550 goto out;
2551 if (p->se.on_rq)
2552 goto out_running;
2554 this_cpu = smp_processor_id();
2555 cpu = task_cpu(p);
2558 #ifdef CONFIG_SCHEDSTATS
2559 schedstat_inc(rq, ttwu_count);
2560 if (cpu == this_cpu)
2561 schedstat_inc(rq, ttwu_local);
2562 else {
2563 struct sched_domain *sd;
2564 for_each_domain(this_cpu, sd) {
2565 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2566 schedstat_inc(sd, ttwu_wake_remote);
2567 break;
2571 #endif /* CONFIG_SCHEDSTATS */
2573 out_activate:
2574 #endif /* CONFIG_SMP */
2575 schedstat_inc(p, se.nr_wakeups);
2576 if (sync)
2577 schedstat_inc(p, se.nr_wakeups_sync);
2578 if (orig_cpu != cpu)
2579 schedstat_inc(p, se.nr_wakeups_migrate);
2580 if (cpu == this_cpu)
2581 schedstat_inc(p, se.nr_wakeups_local);
2582 else
2583 schedstat_inc(p, se.nr_wakeups_remote);
2584 activate_task(rq, p, 1);
2585 success = 1;
2588 * Only attribute actual wakeups done by this task.
2590 if (!in_interrupt()) {
2591 struct sched_entity *se = &current->se;
2592 u64 sample = se->sum_exec_runtime;
2594 if (se->last_wakeup)
2595 sample -= se->last_wakeup;
2596 else
2597 sample -= se->start_runtime;
2598 update_avg(&se->avg_wakeup, sample);
2600 se->last_wakeup = se->sum_exec_runtime;
2603 out_running:
2604 trace_sched_wakeup(rq, p, success);
2605 check_preempt_curr(rq, p, sync);
2608 * For a mutex wakeup we or TASK_RUNNING_MUTEX to the task
2609 * state to preserve the original state, so a real wakeup
2610 * still can see the (UN)INTERRUPTIBLE bits in the state check
2611 * above. We dont have to worry about the | TASK_RUNNING_MUTEX
2612 * here. The waiter is serialized by the mutex lock and nobody
2613 * else can fiddle with p->state as we hold rq lock.
2615 if (mutex)
2616 p->state |= TASK_RUNNING_MUTEX;
2617 else
2618 p->state = TASK_RUNNING;
2619 #ifdef CONFIG_SMP
2620 if (p->sched_class->task_wake_up)
2621 p->sched_class->task_wake_up(rq, p);
2622 #endif
2623 out:
2624 task_rq_unlock(rq, &flags);
2626 return success;
2629 int wake_up_process(struct task_struct *p)
2631 return try_to_wake_up(p, TASK_ALL, 0, 0);
2633 EXPORT_SYMBOL(wake_up_process);
2635 int wake_up_process_sync(struct task_struct * p)
2637 return try_to_wake_up(p, TASK_ALL, 1, 0);
2639 EXPORT_SYMBOL(wake_up_process_sync);
2641 int wake_up_process_mutex(struct task_struct * p)
2643 return try_to_wake_up(p, TASK_ALL, 0, 1);
2645 EXPORT_SYMBOL(wake_up_process_mutex);
2647 int wake_up_process_mutex_sync(struct task_struct * p)
2649 return try_to_wake_up(p, TASK_ALL, 1, 1);
2651 EXPORT_SYMBOL(wake_up_process_mutex_sync);
2653 int wake_up_state(struct task_struct *p, unsigned int state)
2655 return try_to_wake_up(p, state, 0, 0);
2659 * Perform scheduler related setup for a newly forked process p.
2660 * p is forked by current.
2662 * __sched_fork() is basic setup used by init_idle() too:
2664 static void __sched_fork(struct task_struct *p)
2666 p->se.exec_start = 0;
2667 p->se.sum_exec_runtime = 0;
2668 p->se.prev_sum_exec_runtime = 0;
2669 p->se.nr_migrations = 0;
2670 p->se.last_wakeup = 0;
2671 p->se.avg_overlap = 0;
2672 p->se.start_runtime = 0;
2673 p->se.avg_wakeup = sysctl_sched_wakeup_granularity;
2675 #ifdef CONFIG_SCHEDSTATS
2676 p->se.wait_start = 0;
2677 p->se.sum_sleep_runtime = 0;
2678 p->se.sleep_start = 0;
2679 p->se.block_start = 0;
2680 p->se.sleep_max = 0;
2681 p->se.block_max = 0;
2682 p->se.exec_max = 0;
2683 p->se.slice_max = 0;
2684 p->se.wait_max = 0;
2685 #endif
2687 INIT_LIST_HEAD(&p->rt.run_list);
2688 p->se.on_rq = 0;
2689 INIT_LIST_HEAD(&p->se.group_node);
2691 #ifdef CONFIG_PREEMPT_NOTIFIERS
2692 INIT_HLIST_HEAD(&p->preempt_notifiers);
2693 #endif
2696 * We mark the process as running here, but have not actually
2697 * inserted it onto the runqueue yet. This guarantees that
2698 * nobody will actually run it, and a signal or other external
2699 * event cannot wake it up and insert it on the runqueue either.
2701 p->state = TASK_RUNNING;
2705 * fork()/clone()-time setup:
2707 void sched_fork(struct task_struct *p, int clone_flags)
2709 int cpu = get_cpu();
2711 __sched_fork(p);
2713 #ifdef CONFIG_SMP
2714 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2715 #endif
2716 set_task_cpu(p, cpu);
2719 * Make sure we do not leak PI boosting priority to the child:
2721 p->prio = current->normal_prio;
2722 if (!rt_prio(p->prio))
2723 p->sched_class = &fair_sched_class;
2725 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2726 if (likely(sched_info_on()))
2727 memset(&p->sched_info, 0, sizeof(p->sched_info));
2728 #endif
2729 #if defined(CONFIG_SMP)
2730 p->oncpu = 0;
2731 #endif
2732 #ifdef CONFIG_PREEMPT
2733 /* Want to start with kernel preemption disabled. */
2734 task_thread_info(p)->preempt_count = 1;
2735 #endif
2736 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2738 put_cpu();
2742 * wake_up_new_task - wake up a newly created task for the first time.
2744 * This function will do some initial scheduler statistics housekeeping
2745 * that must be done for every newly created context, then puts the task
2746 * on the runqueue and wakes it.
2748 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2750 unsigned long flags;
2751 struct rq *rq;
2753 rq = task_rq_lock(p, &flags);
2754 BUG_ON(p->state != TASK_RUNNING);
2755 update_rq_clock(rq);
2757 p->prio = effective_prio(p);
2759 if (!p->sched_class->task_new || !current->se.on_rq) {
2760 activate_task(rq, p, 0);
2761 } else {
2763 * Let the scheduling class do new task startup
2764 * management (if any):
2766 p->sched_class->task_new(rq, p);
2767 inc_nr_running(rq);
2769 trace_sched_wakeup_new(rq, p, 1);
2770 check_preempt_curr(rq, p, 0);
2771 #ifdef CONFIG_SMP
2772 if (p->sched_class->task_wake_up)
2773 p->sched_class->task_wake_up(rq, p);
2774 #endif
2775 task_rq_unlock(rq, &flags);
2778 #ifdef CONFIG_PREEMPT_NOTIFIERS
2781 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2782 * @notifier: notifier struct to register
2784 void preempt_notifier_register(struct preempt_notifier *notifier)
2786 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2788 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2791 * preempt_notifier_unregister - no longer interested in preemption notifications
2792 * @notifier: notifier struct to unregister
2794 * This is safe to call from within a preemption notifier.
2796 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2798 hlist_del(&notifier->link);
2800 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2802 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2804 struct preempt_notifier *notifier;
2805 struct hlist_node *node;
2807 if (hlist_empty(&curr->preempt_notifiers))
2808 return;
2811 * The KVM sched in notifier expects to be called with
2812 * interrupts enabled.
2814 local_irq_enable();
2815 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2816 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2817 local_irq_disable();
2820 static void
2821 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2822 struct task_struct *next)
2824 struct preempt_notifier *notifier;
2825 struct hlist_node *node;
2827 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2828 notifier->ops->sched_out(notifier, next);
2831 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2833 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2837 static void
2838 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2839 struct task_struct *next)
2843 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2846 * prepare_task_switch - prepare to switch tasks
2847 * @rq: the runqueue preparing to switch
2848 * @prev: the current task that is being switched out
2849 * @next: the task we are going to switch to.
2851 * This is called with the rq lock held and interrupts off. It must
2852 * be paired with a subsequent finish_task_switch after the context
2853 * switch.
2855 * prepare_task_switch sets up locking and calls architecture specific
2856 * hooks.
2858 static inline void
2859 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2860 struct task_struct *next)
2862 fire_sched_out_preempt_notifiers(prev, next);
2863 prepare_lock_switch(rq, next);
2864 prepare_arch_switch(next);
2868 * finish_task_switch - clean up after a task-switch
2869 * @rq: runqueue associated with task-switch
2870 * @prev: the thread we just switched away from.
2872 * finish_task_switch must be called after the context switch, paired
2873 * with a prepare_task_switch call before the context switch.
2874 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2875 * and do any other architecture-specific cleanup actions.
2877 * Note that we may have delayed dropping an mm in context_switch(). If
2878 * so, we finish that here outside of the runqueue lock. (Doing it
2879 * with the lock held can cause deadlocks; see schedule() for
2880 * details.)
2882 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2883 __releases(rq->lock)
2885 struct mm_struct *mm = rq->prev_mm;
2886 long prev_state;
2887 #ifdef CONFIG_SMP
2888 int post_schedule = 0;
2890 if (current->sched_class->needs_post_schedule)
2891 post_schedule = current->sched_class->needs_post_schedule(rq);
2892 #endif
2894 rq->prev_mm = NULL;
2897 * A task struct has one reference for the use as "current".
2898 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2899 * schedule one last time. The schedule call will never return, and
2900 * the scheduled task must drop that reference.
2901 * The test for TASK_DEAD must occur while the runqueue locks are
2902 * still held, otherwise prev could be scheduled on another cpu, die
2903 * there before we look at prev->state, and then the reference would
2904 * be dropped twice.
2905 * Manfred Spraul <manfred@colorfullife.com>
2907 prev_state = prev->state;
2908 _finish_arch_switch(prev);
2909 perf_counter_task_sched_in(current, cpu_of(rq));
2910 finish_lock_switch(rq, prev);
2911 #ifdef CONFIG_SMP
2912 if (post_schedule)
2913 current->sched_class->post_schedule(rq);
2914 #endif
2916 fire_sched_in_preempt_notifiers(current);
2918 * Delay the final freeing of the mm or task, so that we dont have
2919 * to do complex work from within the scheduler:
2921 if (mm)
2922 mmdrop_delayed(mm);
2923 if (unlikely(prev_state == TASK_DEAD)) {
2925 * Remove function-return probe instances associated with this
2926 * task and put them back on the free list.
2928 kprobe_flush_task(prev);
2929 put_task_struct(prev);
2934 * schedule_tail - first thing a freshly forked thread must call.
2935 * @prev: the thread we just switched away from.
2937 asmlinkage void schedule_tail(struct task_struct *prev)
2938 __releases(rq->lock)
2940 preempt_disable();
2941 finish_task_switch(this_rq(), prev);
2942 __preempt_enable_no_resched();
2943 local_irq_enable();
2944 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2945 /* In this case, finish_task_switch does not reenable preemption */
2946 preempt_enable();
2947 #else
2948 preempt_check_resched();
2949 #endif
2950 if (current->set_child_tid)
2951 put_user(task_pid_vnr(current), current->set_child_tid);
2955 * context_switch - switch to the new MM and the new
2956 * thread's register state.
2958 static inline void
2959 context_switch(struct rq *rq, struct task_struct *prev,
2960 struct task_struct *next)
2962 struct mm_struct *mm, *oldmm;
2964 prepare_task_switch(rq, prev, next);
2965 trace_sched_switch(rq, prev, next);
2966 mm = next->mm;
2967 oldmm = prev->active_mm;
2969 * For paravirt, this is coupled with an exit in switch_to to
2970 * combine the page table reload and the switch backend into
2971 * one hypercall.
2973 arch_enter_lazy_cpu_mode();
2975 if (unlikely(!mm)) {
2976 next->active_mm = oldmm;
2977 atomic_inc(&oldmm->mm_count);
2978 enter_lazy_tlb(oldmm, next);
2979 } else
2980 switch_mm(oldmm, mm, next);
2982 if (unlikely(!prev->mm)) {
2983 prev->active_mm = NULL;
2984 rq->prev_mm = oldmm;
2987 * Since the runqueue lock will be released by the next
2988 * task (which is an invalid locking op but in the case
2989 * of the scheduler it's an obvious special-case), so we
2990 * do an early lockdep release here:
2992 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2993 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2994 #endif
2996 #ifdef CURRENT_PTR
2997 barrier();
2998 *current_ptr = next;
2999 *current_ti_ptr = next->thread_info;
3000 #endif
3001 /* Here we just switch the register state and the stack. */
3002 switch_to(prev, next, prev);
3004 barrier();
3006 * this_rq must be evaluated again because prev may have moved
3007 * CPUs since it called schedule(), thus the 'rq' on its stack
3008 * frame will be invalid.
3010 finish_task_switch(this_rq(), prev);
3014 * nr_running, nr_uninterruptible and nr_context_switches:
3016 * externally visible scheduler statistics: current number of runnable
3017 * threads, current number of uninterruptible-sleeping threads, total
3018 * number of context switches performed since bootup.
3020 unsigned long nr_running(void)
3022 unsigned long i, sum = 0;
3024 for_each_online_cpu(i)
3025 sum += cpu_rq(i)->nr_running;
3027 return sum;
3030 unsigned long nr_uninterruptible(void)
3032 unsigned long i, sum = 0;
3034 for_each_possible_cpu(i)
3035 sum += cpu_rq(i)->nr_uninterruptible;
3038 * Since we read the counters lockless, it might be slightly
3039 * inaccurate. Do not allow it to go below zero though:
3041 if (unlikely((long)sum < 0))
3042 sum = 0;
3044 return sum;
3047 unsigned long nr_uninterruptible_cpu(int cpu)
3049 return cpu_rq(cpu)->nr_uninterruptible;
3052 unsigned long long nr_context_switches(void)
3054 int i;
3055 unsigned long long sum = 0;
3057 for_each_possible_cpu(i)
3058 sum += cpu_rq(i)->nr_switches;
3060 return sum;
3063 unsigned long nr_iowait(void)
3065 unsigned long i, sum = 0;
3067 for_each_possible_cpu(i)
3068 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3071 * Since we read the counters lockless, it might be slightly
3072 * inaccurate. Do not allow it to go below zero though:
3074 if (unlikely((long)sum < 0))
3075 sum = 0;
3077 return sum;
3080 /* Variables and functions for calc_load */
3081 static atomic_long_t calc_load_tasks;
3082 static unsigned long calc_load_update;
3083 unsigned long avenrun[3];
3084 EXPORT_SYMBOL(avenrun);
3087 * get_avenrun - get the load average array
3088 * @loads: pointer to dest load array
3089 * @offset: offset to add
3090 * @shift: shift count to shift the result left
3092 * These values are estimates at best, so no need for locking.
3094 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3096 loads[0] = (avenrun[0] + offset) << shift;
3097 loads[1] = (avenrun[1] + offset) << shift;
3098 loads[2] = (avenrun[2] + offset) << shift;
3101 static unsigned long
3102 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3104 load *= exp;
3105 load += active * (FIXED_1 - exp);
3106 return load >> FSHIFT;
3110 * calc_load - update the avenrun load estimates 10 ticks after the
3111 * CPUs have updated calc_load_tasks.
3113 void calc_global_load(void)
3115 unsigned long upd = calc_load_update + 10;
3116 long active;
3118 if (time_before(jiffies, upd))
3119 return;
3121 active = atomic_long_read(&calc_load_tasks);
3122 active = active > 0 ? active * FIXED_1 : 0;
3124 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3125 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3126 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3128 calc_load_update += LOAD_FREQ;
3132 * Either called from update_cpu_load() or from a cpu going idle
3134 static void calc_load_account_active(struct rq *this_rq)
3136 long nr_active, delta;
3138 nr_active = this_rq->nr_running;
3139 nr_active += (long) this_rq->nr_uninterruptible;
3141 if (nr_active != this_rq->calc_load_active) {
3142 delta = nr_active - this_rq->calc_load_active;
3143 this_rq->calc_load_active = nr_active;
3144 atomic_long_add(delta, &calc_load_tasks);
3149 * Externally visible per-cpu scheduler statistics:
3150 * cpu_nr_migrations(cpu) - number of migrations into that cpu
3152 u64 cpu_nr_migrations(int cpu)
3154 return cpu_rq(cpu)->nr_migrations_in;
3158 * Update rq->cpu_load[] statistics. This function is usually called every
3159 * scheduler tick (TICK_NSEC).
3161 static void update_cpu_load(struct rq *this_rq)
3163 unsigned long this_load = this_rq->load.weight;
3164 int i, scale;
3166 this_rq->nr_load_updates++;
3168 /* Update our load: */
3169 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3170 unsigned long old_load, new_load;
3172 /* scale is effectively 1 << i now, and >> i divides by scale */
3174 old_load = this_rq->cpu_load[i];
3175 new_load = this_load;
3177 * Round up the averaging division if load is increasing. This
3178 * prevents us from getting stuck on 9 if the load is 10, for
3179 * example.
3181 if (new_load > old_load)
3182 new_load += scale-1;
3183 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3186 if (time_after_eq(jiffies, this_rq->calc_load_update)) {
3187 this_rq->calc_load_update += LOAD_FREQ;
3188 calc_load_account_active(this_rq);
3192 #ifdef CONFIG_SMP
3195 * double_rq_lock - safely lock two runqueues
3197 * Note this does not disable interrupts like task_rq_lock,
3198 * you need to do so manually before calling.
3200 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3201 __acquires(rq1->lock)
3202 __acquires(rq2->lock)
3204 BUG_ON(!irqs_disabled());
3205 if (rq1 == rq2) {
3206 spin_lock(&rq1->lock);
3207 __acquire(rq2->lock); /* Fake it out ;) */
3208 } else {
3209 if (rq1 < rq2) {
3210 spin_lock(&rq1->lock);
3211 spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
3212 } else {
3213 spin_lock(&rq2->lock);
3214 spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
3217 update_rq_clock(rq1);
3218 update_rq_clock(rq2);
3222 * double_rq_unlock - safely unlock two runqueues
3224 * Note this does not restore interrupts like task_rq_unlock,
3225 * you need to do so manually after calling.
3227 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3228 __releases(rq1->lock)
3229 __releases(rq2->lock)
3231 spin_unlock(&rq1->lock);
3232 if (rq1 != rq2)
3233 spin_unlock(&rq2->lock);
3234 else
3235 __release(rq2->lock);
3239 * If dest_cpu is allowed for this process, migrate the task to it.
3240 * This is accomplished by forcing the cpu_allowed mask to only
3241 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3242 * the cpu_allowed mask is restored.
3244 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3246 struct migration_req req;
3247 unsigned long flags;
3248 struct rq *rq;
3250 rq = task_rq_lock(p, &flags);
3251 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed)
3252 || unlikely(!cpu_active(dest_cpu)))
3253 goto out;
3255 /* force the process onto the specified CPU */
3256 if (migrate_task(p, dest_cpu, &req)) {
3257 /* Need to wait for migration thread (might exit: take ref). */
3258 struct task_struct *mt = rq->migration_thread;
3260 get_task_struct(mt);
3261 task_rq_unlock(rq, &flags);
3262 wake_up_process(mt);
3263 put_task_struct(mt);
3264 wait_for_completion(&req.done);
3266 return;
3268 out:
3269 task_rq_unlock(rq, &flags);
3273 * sched_exec - execve() is a valuable balancing opportunity, because at
3274 * this point the task has the smallest effective memory and cache footprint.
3276 void sched_exec(void)
3278 int new_cpu, this_cpu = get_cpu();
3279 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3280 put_cpu();
3281 if (new_cpu != this_cpu)
3282 sched_migrate_task(current, new_cpu);
3286 * pull_task - move a task from a remote runqueue to the local runqueue.
3287 * Both runqueues must be locked.
3289 static void pull_task(struct rq *src_rq, struct task_struct *p,
3290 struct rq *this_rq, int this_cpu)
3292 deactivate_task(src_rq, p, 0);
3293 set_task_cpu(p, this_cpu);
3294 activate_task(this_rq, p, 0);
3296 * Note that idle threads have a prio of MAX_PRIO, for this test
3297 * to be always true for them.
3299 check_preempt_curr(this_rq, p, 0);
3303 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3305 static
3306 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3307 struct sched_domain *sd, enum cpu_idle_type idle,
3308 int *all_pinned)
3310 int tsk_cache_hot = 0;
3312 * We do not migrate tasks that are:
3313 * 1) running (obviously), or
3314 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3315 * 3) are cache-hot on their current CPU.
3317 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
3318 schedstat_inc(p, se.nr_failed_migrations_affine);
3319 return 0;
3321 *all_pinned = 0;
3323 if (task_running(rq, p)) {
3324 schedstat_inc(p, se.nr_failed_migrations_running);
3325 return 0;
3329 * Aggressive migration if:
3330 * 1) task is cache cold, or
3331 * 2) too many balance attempts have failed.
3334 tsk_cache_hot = task_hot(p, rq->clock, sd);
3335 if (!tsk_cache_hot ||
3336 sd->nr_balance_failed > sd->cache_nice_tries) {
3337 #ifdef CONFIG_SCHEDSTATS
3338 if (tsk_cache_hot) {
3339 schedstat_inc(sd, lb_hot_gained[idle]);
3340 schedstat_inc(p, se.nr_forced_migrations);
3342 #endif
3343 return 1;
3346 if (tsk_cache_hot) {
3347 schedstat_inc(p, se.nr_failed_migrations_hot);
3348 return 0;
3350 return 1;
3353 static unsigned long
3354 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3355 unsigned long max_load_move, struct sched_domain *sd,
3356 enum cpu_idle_type idle, int *all_pinned,
3357 int *this_best_prio, struct rq_iterator *iterator)
3359 int loops = 0, pulled = 0, pinned = 0;
3360 struct task_struct *p;
3361 long rem_load_move = max_load_move;
3363 if (max_load_move == 0)
3364 goto out;
3366 pinned = 1;
3369 * Start the load-balancing iterator:
3371 p = iterator->start(iterator->arg);
3372 next:
3373 if (!p || loops++ > sysctl_sched_nr_migrate)
3374 goto out;
3376 if ((p->se.load.weight >> 1) > rem_load_move ||
3377 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3378 p = iterator->next(iterator->arg);
3379 goto next;
3382 pull_task(busiest, p, this_rq, this_cpu);
3383 pulled++;
3384 rem_load_move -= p->se.load.weight;
3386 #ifdef CONFIG_PREEMPT
3388 * NEWIDLE balancing is a source of latency, so preemptible kernels
3389 * will stop after the first task is pulled to minimize the critical
3390 * section.
3392 if (idle == CPU_NEWLY_IDLE)
3393 goto out;
3394 #endif
3397 * We only want to steal up to the prescribed amount of weighted load.
3399 if (rem_load_move > 0) {
3400 if (p->prio < *this_best_prio)
3401 *this_best_prio = p->prio;
3402 p = iterator->next(iterator->arg);
3403 goto next;
3405 out:
3407 * Right now, this is one of only two places pull_task() is called,
3408 * so we can safely collect pull_task() stats here rather than
3409 * inside pull_task().
3411 schedstat_add(sd, lb_gained[idle], pulled);
3413 if (all_pinned)
3414 *all_pinned = pinned;
3416 return max_load_move - rem_load_move;
3420 * move_tasks tries to move up to max_load_move weighted load from busiest to
3421 * this_rq, as part of a balancing operation within domain "sd".
3422 * Returns 1 if successful and 0 otherwise.
3424 * Called with both runqueues locked.
3426 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3427 unsigned long max_load_move,
3428 struct sched_domain *sd, enum cpu_idle_type idle,
3429 int *all_pinned)
3431 const struct sched_class *class = sched_class_highest;
3432 unsigned long total_load_moved = 0;
3433 int this_best_prio = this_rq->curr->prio;
3435 do {
3436 total_load_moved +=
3437 class->load_balance(this_rq, this_cpu, busiest,
3438 max_load_move - total_load_moved,
3439 sd, idle, all_pinned, &this_best_prio);
3440 class = class->next;
3442 #ifdef CONFIG_PREEMPT
3444 * NEWIDLE balancing is a source of latency, so preemptible
3445 * kernels will stop after the first task is pulled to minimize
3446 * the critical section.
3448 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3449 break;
3450 #endif
3451 } while (class && max_load_move > total_load_moved);
3453 return total_load_moved > 0;
3456 static int
3457 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3458 struct sched_domain *sd, enum cpu_idle_type idle,
3459 struct rq_iterator *iterator)
3461 struct task_struct *p = iterator->start(iterator->arg);
3462 int pinned = 0;
3464 while (p) {
3465 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3466 pull_task(busiest, p, this_rq, this_cpu);
3468 * Right now, this is only the second place pull_task()
3469 * is called, so we can safely collect pull_task()
3470 * stats here rather than inside pull_task().
3472 schedstat_inc(sd, lb_gained[idle]);
3474 return 1;
3476 p = iterator->next(iterator->arg);
3479 return 0;
3483 * move_one_task tries to move exactly one task from busiest to this_rq, as
3484 * part of active balancing operations within "domain".
3485 * Returns 1 if successful and 0 otherwise.
3487 * Called with both runqueues locked.
3489 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3490 struct sched_domain *sd, enum cpu_idle_type idle)
3492 const struct sched_class *class;
3494 for (class = sched_class_highest; class; class = class->next)
3495 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3496 return 1;
3498 return 0;
3500 /********** Helpers for find_busiest_group ************************/
3502 * sd_lb_stats - Structure to store the statistics of a sched_domain
3503 * during load balancing.
3505 struct sd_lb_stats {
3506 struct sched_group *busiest; /* Busiest group in this sd */
3507 struct sched_group *this; /* Local group in this sd */
3508 unsigned long total_load; /* Total load of all groups in sd */
3509 unsigned long total_pwr; /* Total power of all groups in sd */
3510 unsigned long avg_load; /* Average load across all groups in sd */
3512 /** Statistics of this group */
3513 unsigned long this_load;
3514 unsigned long this_load_per_task;
3515 unsigned long this_nr_running;
3517 /* Statistics of the busiest group */
3518 unsigned long max_load;
3519 unsigned long busiest_load_per_task;
3520 unsigned long busiest_nr_running;
3522 int group_imb; /* Is there imbalance in this sd */
3523 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3524 int power_savings_balance; /* Is powersave balance needed for this sd */
3525 struct sched_group *group_min; /* Least loaded group in sd */
3526 struct sched_group *group_leader; /* Group which relieves group_min */
3527 unsigned long min_load_per_task; /* load_per_task in group_min */
3528 unsigned long leader_nr_running; /* Nr running of group_leader */
3529 unsigned long min_nr_running; /* Nr running of group_min */
3530 #endif
3534 * sg_lb_stats - stats of a sched_group required for load_balancing
3536 struct sg_lb_stats {
3537 unsigned long avg_load; /*Avg load across the CPUs of the group */
3538 unsigned long group_load; /* Total load over the CPUs of the group */
3539 unsigned long sum_nr_running; /* Nr tasks running in the group */
3540 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3541 unsigned long group_capacity;
3542 int group_imb; /* Is there an imbalance in the group ? */
3546 * group_first_cpu - Returns the first cpu in the cpumask of a sched_group.
3547 * @group: The group whose first cpu is to be returned.
3549 static inline unsigned int group_first_cpu(struct sched_group *group)
3551 return cpumask_first(sched_group_cpus(group));
3555 * get_sd_load_idx - Obtain the load index for a given sched domain.
3556 * @sd: The sched_domain whose load_idx is to be obtained.
3557 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3559 static inline int get_sd_load_idx(struct sched_domain *sd,
3560 enum cpu_idle_type idle)
3562 int load_idx;
3564 switch (idle) {
3565 case CPU_NOT_IDLE:
3566 load_idx = sd->busy_idx;
3567 break;
3569 case CPU_NEWLY_IDLE:
3570 load_idx = sd->newidle_idx;
3571 break;
3572 default:
3573 load_idx = sd->idle_idx;
3574 break;
3577 return load_idx;
3581 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3583 * init_sd_power_savings_stats - Initialize power savings statistics for
3584 * the given sched_domain, during load balancing.
3586 * @sd: Sched domain whose power-savings statistics are to be initialized.
3587 * @sds: Variable containing the statistics for sd.
3588 * @idle: Idle status of the CPU at which we're performing load-balancing.
3590 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3591 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3594 * Busy processors will not participate in power savings
3595 * balance.
3597 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3598 sds->power_savings_balance = 0;
3599 else {
3600 sds->power_savings_balance = 1;
3601 sds->min_nr_running = ULONG_MAX;
3602 sds->leader_nr_running = 0;
3607 * update_sd_power_savings_stats - Update the power saving stats for a
3608 * sched_domain while performing load balancing.
3610 * @group: sched_group belonging to the sched_domain under consideration.
3611 * @sds: Variable containing the statistics of the sched_domain
3612 * @local_group: Does group contain the CPU for which we're performing
3613 * load balancing ?
3614 * @sgs: Variable containing the statistics of the group.
3616 static inline void update_sd_power_savings_stats(struct sched_group *group,
3617 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3620 if (!sds->power_savings_balance)
3621 return;
3624 * If the local group is idle or completely loaded
3625 * no need to do power savings balance at this domain
3627 if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
3628 !sds->this_nr_running))
3629 sds->power_savings_balance = 0;
3632 * If a group is already running at full capacity or idle,
3633 * don't include that group in power savings calculations
3635 if (!sds->power_savings_balance ||
3636 sgs->sum_nr_running >= sgs->group_capacity ||
3637 !sgs->sum_nr_running)
3638 return;
3641 * Calculate the group which has the least non-idle load.
3642 * This is the group from where we need to pick up the load
3643 * for saving power
3645 if ((sgs->sum_nr_running < sds->min_nr_running) ||
3646 (sgs->sum_nr_running == sds->min_nr_running &&
3647 group_first_cpu(group) > group_first_cpu(sds->group_min))) {
3648 sds->group_min = group;
3649 sds->min_nr_running = sgs->sum_nr_running;
3650 sds->min_load_per_task = sgs->sum_weighted_load /
3651 sgs->sum_nr_running;
3655 * Calculate the group which is almost near its
3656 * capacity but still has some space to pick up some load
3657 * from other group and save more power
3659 if (sgs->sum_nr_running > sgs->group_capacity - 1)
3660 return;
3662 if (sgs->sum_nr_running > sds->leader_nr_running ||
3663 (sgs->sum_nr_running == sds->leader_nr_running &&
3664 group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
3665 sds->group_leader = group;
3666 sds->leader_nr_running = sgs->sum_nr_running;
3671 * check_power_save_busiest_group - Check if we have potential to perform
3672 * some power-savings balance. If yes, set the busiest group to be
3673 * the least loaded group in the sched_domain, so that it's CPUs can
3674 * be put to idle.
3676 * @sds: Variable containing the statistics of the sched_domain
3677 * under consideration.
3678 * @this_cpu: Cpu at which we're currently performing load-balancing.
3679 * @imbalance: Variable to store the imbalance.
3681 * Returns 1 if there is potential to perform power-savings balance.
3682 * Else returns 0.
3684 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3685 int this_cpu, unsigned long *imbalance)
3687 if (!sds->power_savings_balance)
3688 return 0;
3690 if (sds->this != sds->group_leader ||
3691 sds->group_leader == sds->group_min)
3692 return 0;
3694 *imbalance = sds->min_load_per_task;
3695 sds->busiest = sds->group_min;
3697 if (sched_mc_power_savings >= POWERSAVINGS_BALANCE_WAKEUP) {
3698 cpu_rq(this_cpu)->rd->sched_mc_preferred_wakeup_cpu =
3699 group_first_cpu(sds->group_leader);
3702 return 1;
3705 #else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3706 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3707 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3709 return;
3712 static inline void update_sd_power_savings_stats(struct sched_group *group,
3713 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3715 return;
3718 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3719 int this_cpu, unsigned long *imbalance)
3721 return 0;
3723 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3727 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
3728 * @group: sched_group whose statistics are to be updated.
3729 * @this_cpu: Cpu for which load balance is currently performed.
3730 * @idle: Idle status of this_cpu
3731 * @load_idx: Load index of sched_domain of this_cpu for load calc.
3732 * @sd_idle: Idle status of the sched_domain containing group.
3733 * @local_group: Does group contain this_cpu.
3734 * @cpus: Set of cpus considered for load balancing.
3735 * @balance: Should we balance.
3736 * @sgs: variable to hold the statistics for this group.
3738 static inline void update_sg_lb_stats(struct sched_group *group, int this_cpu,
3739 enum cpu_idle_type idle, int load_idx, int *sd_idle,
3740 int local_group, const struct cpumask *cpus,
3741 int *balance, struct sg_lb_stats *sgs)
3743 unsigned long load, max_cpu_load, min_cpu_load;
3744 int i;
3745 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3746 unsigned long sum_avg_load_per_task;
3747 unsigned long avg_load_per_task;
3749 if (local_group)
3750 balance_cpu = group_first_cpu(group);
3752 /* Tally up the load of all CPUs in the group */
3753 sum_avg_load_per_task = avg_load_per_task = 0;
3754 max_cpu_load = 0;
3755 min_cpu_load = ~0UL;
3757 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
3758 struct rq *rq = cpu_rq(i);
3760 if (*sd_idle && rq->nr_running)
3761 *sd_idle = 0;
3763 /* Bias balancing toward cpus of our domain */
3764 if (local_group) {
3765 if (idle_cpu(i) && !first_idle_cpu) {
3766 first_idle_cpu = 1;
3767 balance_cpu = i;
3770 load = target_load(i, load_idx);
3771 } else {
3772 load = source_load(i, load_idx);
3773 if (load > max_cpu_load)
3774 max_cpu_load = load;
3775 if (min_cpu_load > load)
3776 min_cpu_load = load;
3779 sgs->group_load += load;
3780 sgs->sum_nr_running += rq->nr_running;
3781 sgs->sum_weighted_load += weighted_cpuload(i);
3783 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3787 * First idle cpu or the first cpu(busiest) in this sched group
3788 * is eligible for doing load balancing at this and above
3789 * domains. In the newly idle case, we will allow all the cpu's
3790 * to do the newly idle load balance.
3792 if (idle != CPU_NEWLY_IDLE && local_group &&
3793 balance_cpu != this_cpu && balance) {
3794 *balance = 0;
3795 return;
3798 /* Adjust by relative CPU power of the group */
3799 sgs->avg_load = sg_div_cpu_power(group,
3800 sgs->group_load * SCHED_LOAD_SCALE);
3804 * Consider the group unbalanced when the imbalance is larger
3805 * than the average weight of two tasks.
3807 * APZ: with cgroup the avg task weight can vary wildly and
3808 * might not be a suitable number - should we keep a
3809 * normalized nr_running number somewhere that negates
3810 * the hierarchy?
3812 avg_load_per_task = sg_div_cpu_power(group,
3813 sum_avg_load_per_task * SCHED_LOAD_SCALE);
3815 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3816 sgs->group_imb = 1;
3818 sgs->group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3823 * update_sd_lb_stats - Update sched_group's statistics for load balancing.
3824 * @sd: sched_domain whose statistics are to be updated.
3825 * @this_cpu: Cpu for which load balance is currently performed.
3826 * @idle: Idle status of this_cpu
3827 * @sd_idle: Idle status of the sched_domain containing group.
3828 * @cpus: Set of cpus considered for load balancing.
3829 * @balance: Should we balance.
3830 * @sds: variable to hold the statistics for this sched_domain.
3832 static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
3833 enum cpu_idle_type idle, int *sd_idle,
3834 const struct cpumask *cpus, int *balance,
3835 struct sd_lb_stats *sds)
3837 struct sched_group *group = sd->groups;
3838 struct sg_lb_stats sgs;
3839 int load_idx;
3841 init_sd_power_savings_stats(sd, sds, idle);
3842 load_idx = get_sd_load_idx(sd, idle);
3844 do {
3845 int local_group;
3847 local_group = cpumask_test_cpu(this_cpu,
3848 sched_group_cpus(group));
3849 memset(&sgs, 0, sizeof(sgs));
3850 update_sg_lb_stats(group, this_cpu, idle, load_idx, sd_idle,
3851 local_group, cpus, balance, &sgs);
3853 if (local_group && balance && !(*balance))
3854 return;
3856 sds->total_load += sgs.group_load;
3857 sds->total_pwr += group->__cpu_power;
3859 if (local_group) {
3860 sds->this_load = sgs.avg_load;
3861 sds->this = group;
3862 sds->this_nr_running = sgs.sum_nr_running;
3863 sds->this_load_per_task = sgs.sum_weighted_load;
3864 } else if (sgs.avg_load > sds->max_load &&
3865 (sgs.sum_nr_running > sgs.group_capacity ||
3866 sgs.group_imb)) {
3867 sds->max_load = sgs.avg_load;
3868 sds->busiest = group;
3869 sds->busiest_nr_running = sgs.sum_nr_running;
3870 sds->busiest_load_per_task = sgs.sum_weighted_load;
3871 sds->group_imb = sgs.group_imb;
3874 update_sd_power_savings_stats(group, sds, local_group, &sgs);
3875 group = group->next;
3876 } while (group != sd->groups);
3881 * fix_small_imbalance - Calculate the minor imbalance that exists
3882 * amongst the groups of a sched_domain, during
3883 * load balancing.
3884 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
3885 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
3886 * @imbalance: Variable to store the imbalance.
3888 static inline void fix_small_imbalance(struct sd_lb_stats *sds,
3889 int this_cpu, unsigned long *imbalance)
3891 unsigned long tmp, pwr_now = 0, pwr_move = 0;
3892 unsigned int imbn = 2;
3894 if (sds->this_nr_running) {
3895 sds->this_load_per_task /= sds->this_nr_running;
3896 if (sds->busiest_load_per_task >
3897 sds->this_load_per_task)
3898 imbn = 1;
3899 } else
3900 sds->this_load_per_task =
3901 cpu_avg_load_per_task(this_cpu);
3903 if (sds->max_load - sds->this_load + sds->busiest_load_per_task >=
3904 sds->busiest_load_per_task * imbn) {
3905 *imbalance = sds->busiest_load_per_task;
3906 return;
3910 * OK, we don't have enough imbalance to justify moving tasks,
3911 * however we may be able to increase total CPU power used by
3912 * moving them.
3915 pwr_now += sds->busiest->__cpu_power *
3916 min(sds->busiest_load_per_task, sds->max_load);
3917 pwr_now += sds->this->__cpu_power *
3918 min(sds->this_load_per_task, sds->this_load);
3919 pwr_now /= SCHED_LOAD_SCALE;
3921 /* Amount of load we'd subtract */
3922 tmp = sg_div_cpu_power(sds->busiest,
3923 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3924 if (sds->max_load > tmp)
3925 pwr_move += sds->busiest->__cpu_power *
3926 min(sds->busiest_load_per_task, sds->max_load - tmp);
3928 /* Amount of load we'd add */
3929 if (sds->max_load * sds->busiest->__cpu_power <
3930 sds->busiest_load_per_task * SCHED_LOAD_SCALE)
3931 tmp = sg_div_cpu_power(sds->this,
3932 sds->max_load * sds->busiest->__cpu_power);
3933 else
3934 tmp = sg_div_cpu_power(sds->this,
3935 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3936 pwr_move += sds->this->__cpu_power *
3937 min(sds->this_load_per_task, sds->this_load + tmp);
3938 pwr_move /= SCHED_LOAD_SCALE;
3940 /* Move if we gain throughput */
3941 if (pwr_move > pwr_now)
3942 *imbalance = sds->busiest_load_per_task;
3946 * calculate_imbalance - Calculate the amount of imbalance present within the
3947 * groups of a given sched_domain during load balance.
3948 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
3949 * @this_cpu: Cpu for which currently load balance is being performed.
3950 * @imbalance: The variable to store the imbalance.
3952 static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
3953 unsigned long *imbalance)
3955 unsigned long max_pull;
3957 * In the presence of smp nice balancing, certain scenarios can have
3958 * max load less than avg load(as we skip the groups at or below
3959 * its cpu_power, while calculating max_load..)
3961 if (sds->max_load < sds->avg_load) {
3962 *imbalance = 0;
3963 return fix_small_imbalance(sds, this_cpu, imbalance);
3966 /* Don't want to pull so many tasks that a group would go idle */
3967 max_pull = min(sds->max_load - sds->avg_load,
3968 sds->max_load - sds->busiest_load_per_task);
3970 /* How much load to actually move to equalise the imbalance */
3971 *imbalance = min(max_pull * sds->busiest->__cpu_power,
3972 (sds->avg_load - sds->this_load) * sds->this->__cpu_power)
3973 / SCHED_LOAD_SCALE;
3976 * if *imbalance is less than the average load per runnable task
3977 * there is no gaurantee that any tasks will be moved so we'll have
3978 * a think about bumping its value to force at least one task to be
3979 * moved
3981 if (*imbalance < sds->busiest_load_per_task)
3982 return fix_small_imbalance(sds, this_cpu, imbalance);
3985 /******* find_busiest_group() helpers end here *********************/
3988 * find_busiest_group - Returns the busiest group within the sched_domain
3989 * if there is an imbalance. If there isn't an imbalance, and
3990 * the user has opted for power-savings, it returns a group whose
3991 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
3992 * such a group exists.
3994 * Also calculates the amount of weighted load which should be moved
3995 * to restore balance.
3997 * @sd: The sched_domain whose busiest group is to be returned.
3998 * @this_cpu: The cpu for which load balancing is currently being performed.
3999 * @imbalance: Variable which stores amount of weighted load which should
4000 * be moved to restore balance/put a group to idle.
4001 * @idle: The idle status of this_cpu.
4002 * @sd_idle: The idleness of sd
4003 * @cpus: The set of CPUs under consideration for load-balancing.
4004 * @balance: Pointer to a variable indicating if this_cpu
4005 * is the appropriate cpu to perform load balancing at this_level.
4007 * Returns: - the busiest group if imbalance exists.
4008 * - If no imbalance and user has opted for power-savings balance,
4009 * return the least loaded group whose CPUs can be
4010 * put to idle by rebalancing its tasks onto our group.
4012 static struct sched_group *
4013 find_busiest_group(struct sched_domain *sd, int this_cpu,
4014 unsigned long *imbalance, enum cpu_idle_type idle,
4015 int *sd_idle, const struct cpumask *cpus, int *balance)
4017 struct sd_lb_stats sds;
4019 memset(&sds, 0, sizeof(sds));
4022 * Compute the various statistics relavent for load balancing at
4023 * this level.
4025 update_sd_lb_stats(sd, this_cpu, idle, sd_idle, cpus,
4026 balance, &sds);
4028 /* Cases where imbalance does not exist from POV of this_cpu */
4029 /* 1) this_cpu is not the appropriate cpu to perform load balancing
4030 * at this level.
4031 * 2) There is no busy sibling group to pull from.
4032 * 3) This group is the busiest group.
4033 * 4) This group is more busy than the avg busieness at this
4034 * sched_domain.
4035 * 5) The imbalance is within the specified limit.
4036 * 6) Any rebalance would lead to ping-pong
4038 if (balance && !(*balance))
4039 goto ret;
4041 if (!sds.busiest || sds.busiest_nr_running == 0)
4042 goto out_balanced;
4044 if (sds.this_load >= sds.max_load)
4045 goto out_balanced;
4047 sds.avg_load = (SCHED_LOAD_SCALE * sds.total_load) / sds.total_pwr;
4049 if (sds.this_load >= sds.avg_load)
4050 goto out_balanced;
4052 if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
4053 goto out_balanced;
4055 sds.busiest_load_per_task /= sds.busiest_nr_running;
4056 if (sds.group_imb)
4057 sds.busiest_load_per_task =
4058 min(sds.busiest_load_per_task, sds.avg_load);
4061 * We're trying to get all the cpus to the average_load, so we don't
4062 * want to push ourselves above the average load, nor do we wish to
4063 * reduce the max loaded cpu below the average load, as either of these
4064 * actions would just result in more rebalancing later, and ping-pong
4065 * tasks around. Thus we look for the minimum possible imbalance.
4066 * Negative imbalances (*we* are more loaded than anyone else) will
4067 * be counted as no imbalance for these purposes -- we can't fix that
4068 * by pulling tasks to us. Be careful of negative numbers as they'll
4069 * appear as very large values with unsigned longs.
4071 if (sds.max_load <= sds.busiest_load_per_task)
4072 goto out_balanced;
4074 /* Looks like there is an imbalance. Compute it */
4075 calculate_imbalance(&sds, this_cpu, imbalance);
4076 return sds.busiest;
4078 out_balanced:
4080 * There is no obvious imbalance. But check if we can do some balancing
4081 * to save power.
4083 if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
4084 return sds.busiest;
4085 ret:
4086 *imbalance = 0;
4087 return NULL;
4091 * find_busiest_queue - find the busiest runqueue among the cpus in group.
4093 static struct rq *
4094 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
4095 unsigned long imbalance, const struct cpumask *cpus)
4097 struct rq *busiest = NULL, *rq;
4098 unsigned long max_load = 0;
4099 int i;
4101 for_each_cpu(i, sched_group_cpus(group)) {
4102 unsigned long wl;
4104 if (!cpumask_test_cpu(i, cpus))
4105 continue;
4107 rq = cpu_rq(i);
4108 wl = weighted_cpuload(i);
4110 if (rq->nr_running == 1 && wl > imbalance)
4111 continue;
4113 if (wl > max_load) {
4114 max_load = wl;
4115 busiest = rq;
4119 return busiest;
4123 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4124 * so long as it is large enough.
4126 #define MAX_PINNED_INTERVAL 512
4128 /* Working cpumask for load_balance and load_balance_newidle. */
4129 static DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
4132 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4133 * tasks if there is an imbalance.
4135 static int load_balance(int this_cpu, struct rq *this_rq,
4136 struct sched_domain *sd, enum cpu_idle_type idle,
4137 int *balance)
4139 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
4140 struct sched_group *group;
4141 unsigned long imbalance;
4142 struct rq *busiest;
4143 unsigned long flags;
4144 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4146 cpumask_setall(cpus);
4149 * When power savings policy is enabled for the parent domain, idle
4150 * sibling can pick up load irrespective of busy siblings. In this case,
4151 * let the state of idle sibling percolate up as CPU_IDLE, instead of
4152 * portraying it as CPU_NOT_IDLE.
4154 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
4155 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4156 sd_idle = 1;
4158 schedstat_inc(sd, lb_count[idle]);
4160 redo:
4161 update_shares(sd);
4162 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
4163 cpus, balance);
4165 if (*balance == 0)
4166 goto out_balanced;
4168 if (!group) {
4169 schedstat_inc(sd, lb_nobusyg[idle]);
4170 goto out_balanced;
4173 busiest = find_busiest_queue(group, idle, imbalance, cpus);
4174 if (!busiest) {
4175 schedstat_inc(sd, lb_nobusyq[idle]);
4176 goto out_balanced;
4179 BUG_ON(busiest == this_rq);
4181 schedstat_add(sd, lb_imbalance[idle], imbalance);
4183 ld_moved = 0;
4184 if (busiest->nr_running > 1) {
4186 * Attempt to move tasks. If find_busiest_group has found
4187 * an imbalance but busiest->nr_running <= 1, the group is
4188 * still unbalanced. ld_moved simply stays zero, so it is
4189 * correctly treated as an imbalance.
4191 local_irq_save(flags);
4192 double_rq_lock(this_rq, busiest);
4193 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4194 imbalance, sd, idle, &all_pinned);
4195 double_rq_unlock(this_rq, busiest);
4196 local_irq_restore(flags);
4199 * some other cpu did the load balance for us.
4201 if (ld_moved && this_cpu != smp_processor_id())
4202 resched_cpu(this_cpu);
4204 /* All tasks on this runqueue were pinned by CPU affinity */
4205 if (unlikely(all_pinned)) {
4206 cpumask_clear_cpu(cpu_of(busiest), cpus);
4207 if (!cpumask_empty(cpus))
4208 goto redo;
4209 goto out_balanced;
4213 if (!ld_moved) {
4214 schedstat_inc(sd, lb_failed[idle]);
4215 sd->nr_balance_failed++;
4217 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
4219 spin_lock_irqsave(&busiest->lock, flags);
4221 /* don't kick the migration_thread, if the curr
4222 * task on busiest cpu can't be moved to this_cpu
4224 if (!cpumask_test_cpu(this_cpu,
4225 &busiest->curr->cpus_allowed)) {
4226 spin_unlock_irqrestore(&busiest->lock, flags);
4227 all_pinned = 1;
4228 goto out_one_pinned;
4231 if (!busiest->active_balance) {
4232 busiest->active_balance = 1;
4233 busiest->push_cpu = this_cpu;
4234 active_balance = 1;
4236 spin_unlock_irqrestore(&busiest->lock, flags);
4237 if (active_balance)
4238 wake_up_process(busiest->migration_thread);
4241 * We've kicked active balancing, reset the failure
4242 * counter.
4244 sd->nr_balance_failed = sd->cache_nice_tries+1;
4246 } else
4247 sd->nr_balance_failed = 0;
4249 if (likely(!active_balance)) {
4250 /* We were unbalanced, so reset the balancing interval */
4251 sd->balance_interval = sd->min_interval;
4252 } else {
4254 * If we've begun active balancing, start to back off. This
4255 * case may not be covered by the all_pinned logic if there
4256 * is only 1 task on the busy runqueue (because we don't call
4257 * move_tasks).
4259 if (sd->balance_interval < sd->max_interval)
4260 sd->balance_interval *= 2;
4263 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4264 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4265 ld_moved = -1;
4267 goto out;
4269 out_balanced:
4270 schedstat_inc(sd, lb_balanced[idle]);
4272 sd->nr_balance_failed = 0;
4274 out_one_pinned:
4275 /* tune up the balancing interval */
4276 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
4277 (sd->balance_interval < sd->max_interval))
4278 sd->balance_interval *= 2;
4280 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4281 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4282 ld_moved = -1;
4283 else
4284 ld_moved = 0;
4285 out:
4286 if (ld_moved)
4287 update_shares(sd);
4288 return ld_moved;
4292 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4293 * tasks if there is an imbalance.
4295 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
4296 * this_rq is locked.
4298 static int
4299 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
4301 struct sched_group *group;
4302 struct rq *busiest = NULL;
4303 unsigned long imbalance;
4304 int ld_moved = 0;
4305 int sd_idle = 0;
4306 int all_pinned = 0;
4307 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4309 cpumask_setall(cpus);
4312 * When power savings policy is enabled for the parent domain, idle
4313 * sibling can pick up load irrespective of busy siblings. In this case,
4314 * let the state of idle sibling percolate up as IDLE, instead of
4315 * portraying it as CPU_NOT_IDLE.
4317 if (sd->flags & SD_SHARE_CPUPOWER &&
4318 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4319 sd_idle = 1;
4321 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
4322 redo:
4323 update_shares_locked(this_rq, sd);
4324 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
4325 &sd_idle, cpus, NULL);
4326 if (!group) {
4327 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
4328 goto out_balanced;
4331 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
4332 if (!busiest) {
4333 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
4334 goto out_balanced;
4337 BUG_ON(busiest == this_rq);
4339 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
4341 ld_moved = 0;
4342 if (busiest->nr_running > 1) {
4343 /* Attempt to move tasks */
4344 double_lock_balance(this_rq, busiest);
4345 /* this_rq->clock is already updated */
4346 update_rq_clock(busiest);
4347 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4348 imbalance, sd, CPU_NEWLY_IDLE,
4349 &all_pinned);
4350 double_unlock_balance(this_rq, busiest);
4352 if (unlikely(all_pinned)) {
4353 cpumask_clear_cpu(cpu_of(busiest), cpus);
4354 if (!cpumask_empty(cpus))
4355 goto redo;
4359 if (!ld_moved) {
4360 int active_balance = 0;
4362 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
4363 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4364 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4365 return -1;
4367 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
4368 return -1;
4370 if (sd->nr_balance_failed++ < 2)
4371 return -1;
4374 * The only task running in a non-idle cpu can be moved to this
4375 * cpu in an attempt to completely freeup the other CPU
4376 * package. The same method used to move task in load_balance()
4377 * have been extended for load_balance_newidle() to speedup
4378 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
4380 * The package power saving logic comes from
4381 * find_busiest_group(). If there are no imbalance, then
4382 * f_b_g() will return NULL. However when sched_mc={1,2} then
4383 * f_b_g() will select a group from which a running task may be
4384 * pulled to this cpu in order to make the other package idle.
4385 * If there is no opportunity to make a package idle and if
4386 * there are no imbalance, then f_b_g() will return NULL and no
4387 * action will be taken in load_balance_newidle().
4389 * Under normal task pull operation due to imbalance, there
4390 * will be more than one task in the source run queue and
4391 * move_tasks() will succeed. ld_moved will be true and this
4392 * active balance code will not be triggered.
4395 /* Lock busiest in correct order while this_rq is held */
4396 double_lock_balance(this_rq, busiest);
4399 * don't kick the migration_thread, if the curr
4400 * task on busiest cpu can't be moved to this_cpu
4402 if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
4403 double_unlock_balance(this_rq, busiest);
4404 all_pinned = 1;
4405 return ld_moved;
4408 if (!busiest->active_balance) {
4409 busiest->active_balance = 1;
4410 busiest->push_cpu = this_cpu;
4411 active_balance = 1;
4414 double_unlock_balance(this_rq, busiest);
4416 * Should not call ttwu while holding a rq->lock
4418 spin_unlock(&this_rq->lock);
4419 if (active_balance)
4420 wake_up_process(busiest->migration_thread);
4421 spin_lock(&this_rq->lock);
4423 } else
4424 sd->nr_balance_failed = 0;
4426 update_shares_locked(this_rq, sd);
4427 return ld_moved;
4429 out_balanced:
4430 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
4431 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4432 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4433 return -1;
4434 sd->nr_balance_failed = 0;
4436 return 0;
4440 * idle_balance is called by schedule() if this_cpu is about to become
4441 * idle. Attempts to pull tasks from other CPUs.
4443 static void idle_balance(int this_cpu, struct rq *this_rq)
4445 struct sched_domain *sd;
4446 int pulled_task = 0;
4447 unsigned long next_balance = jiffies + HZ;
4449 for_each_domain(this_cpu, sd) {
4450 unsigned long interval;
4452 if (!(sd->flags & SD_LOAD_BALANCE))
4453 continue;
4455 if (sd->flags & SD_BALANCE_NEWIDLE)
4456 /* If we've pulled tasks over stop searching: */
4457 pulled_task = load_balance_newidle(this_cpu, this_rq,
4458 sd);
4460 interval = msecs_to_jiffies(sd->balance_interval);
4461 if (time_after(next_balance, sd->last_balance + interval))
4462 next_balance = sd->last_balance + interval;
4463 if (pulled_task)
4464 break;
4466 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4468 * We are going idle. next_balance may be set based on
4469 * a busy processor. So reset next_balance.
4471 this_rq->next_balance = next_balance;
4476 * active_load_balance is run by migration threads. It pushes running tasks
4477 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4478 * running on each physical CPU where possible, and avoids physical /
4479 * logical imbalances.
4481 * Called with busiest_rq locked.
4483 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4485 int target_cpu = busiest_rq->push_cpu;
4486 struct sched_domain *sd;
4487 struct rq *target_rq;
4489 /* Is there any task to move? */
4490 if (busiest_rq->nr_running <= 1)
4491 return;
4493 target_rq = cpu_rq(target_cpu);
4496 * This condition is "impossible", if it occurs
4497 * we need to fix it. Originally reported by
4498 * Bjorn Helgaas on a 128-cpu setup.
4500 BUG_ON(busiest_rq == target_rq);
4502 /* move a task from busiest_rq to target_rq */
4503 double_lock_balance(busiest_rq, target_rq);
4504 update_rq_clock(busiest_rq);
4505 update_rq_clock(target_rq);
4507 /* Search for an sd spanning us and the target CPU. */
4508 for_each_domain(target_cpu, sd) {
4509 if ((sd->flags & SD_LOAD_BALANCE) &&
4510 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4511 break;
4514 if (likely(sd)) {
4515 schedstat_inc(sd, alb_count);
4517 if (move_one_task(target_rq, target_cpu, busiest_rq,
4518 sd, CPU_IDLE))
4519 schedstat_inc(sd, alb_pushed);
4520 else
4521 schedstat_inc(sd, alb_failed);
4523 double_unlock_balance(busiest_rq, target_rq);
4526 #ifdef CONFIG_NO_HZ
4527 static struct {
4528 atomic_t load_balancer;
4529 cpumask_var_t cpu_mask;
4530 } nohz ____cacheline_aligned = {
4531 .load_balancer = ATOMIC_INIT(-1),
4535 * This routine will try to nominate the ilb (idle load balancing)
4536 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4537 * load balancing on behalf of all those cpus. If all the cpus in the system
4538 * go into this tickless mode, then there will be no ilb owner (as there is
4539 * no need for one) and all the cpus will sleep till the next wakeup event
4540 * arrives...
4542 * For the ilb owner, tick is not stopped. And this tick will be used
4543 * for idle load balancing. ilb owner will still be part of
4544 * nohz.cpu_mask..
4546 * While stopping the tick, this cpu will become the ilb owner if there
4547 * is no other owner. And will be the owner till that cpu becomes busy
4548 * or if all cpus in the system stop their ticks at which point
4549 * there is no need for ilb owner.
4551 * When the ilb owner becomes busy, it nominates another owner, during the
4552 * next busy scheduler_tick()
4554 int select_nohz_load_balancer(int stop_tick)
4556 int cpu = smp_processor_id();
4558 if (stop_tick) {
4559 cpu_rq(cpu)->in_nohz_recently = 1;
4561 if (!cpu_active(cpu)) {
4562 if (atomic_read(&nohz.load_balancer) != cpu)
4563 return 0;
4566 * If we are going offline and still the leader,
4567 * give up!
4569 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4570 BUG();
4572 return 0;
4575 cpumask_set_cpu(cpu, nohz.cpu_mask);
4577 /* time for ilb owner also to sleep */
4578 if (cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4579 if (atomic_read(&nohz.load_balancer) == cpu)
4580 atomic_set(&nohz.load_balancer, -1);
4581 return 0;
4584 if (atomic_read(&nohz.load_balancer) == -1) {
4585 /* make me the ilb owner */
4586 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4587 return 1;
4588 } else if (atomic_read(&nohz.load_balancer) == cpu)
4589 return 1;
4590 } else {
4591 if (!cpumask_test_cpu(cpu, nohz.cpu_mask))
4592 return 0;
4594 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4596 if (atomic_read(&nohz.load_balancer) == cpu)
4597 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4598 BUG();
4600 return 0;
4602 #endif
4604 static DEFINE_SPINLOCK(balancing);
4607 * It checks each scheduling domain to see if it is due to be balanced,
4608 * and initiates a balancing operation if so.
4610 * Balancing parameters are set up in arch_init_sched_domains.
4612 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4614 int balance = 1;
4615 struct rq *rq = cpu_rq(cpu);
4616 unsigned long interval;
4617 struct sched_domain *sd;
4618 /* Earliest time when we have to do rebalance again */
4619 unsigned long next_balance = jiffies + 60*HZ;
4620 int update_next_balance = 0;
4621 int need_serialize;
4623 for_each_domain(cpu, sd) {
4624 if (!(sd->flags & SD_LOAD_BALANCE))
4625 continue;
4627 interval = sd->balance_interval;
4628 if (idle != CPU_IDLE)
4629 interval *= sd->busy_factor;
4631 /* scale ms to jiffies */
4632 interval = msecs_to_jiffies(interval);
4633 if (unlikely(!interval))
4634 interval = 1;
4635 if (interval > HZ*NR_CPUS/10)
4636 interval = HZ*NR_CPUS/10;
4638 need_serialize = sd->flags & SD_SERIALIZE;
4640 if (need_serialize) {
4641 if (!spin_trylock(&balancing))
4642 goto out;
4645 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4646 if (load_balance(cpu, rq, sd, idle, &balance)) {
4648 * We've pulled tasks over so either we're no
4649 * longer idle, or one of our SMT siblings is
4650 * not idle.
4652 idle = CPU_NOT_IDLE;
4654 sd->last_balance = jiffies;
4656 if (need_serialize)
4657 spin_unlock(&balancing);
4658 out:
4659 if (time_after(next_balance, sd->last_balance + interval)) {
4660 next_balance = sd->last_balance + interval;
4661 update_next_balance = 1;
4665 * Stop the load balance at this level. There is another
4666 * CPU in our sched group which is doing load balancing more
4667 * actively.
4669 if (!balance)
4670 break;
4674 * next_balance will be updated only when there is a need.
4675 * When the cpu is attached to null domain for ex, it will not be
4676 * updated.
4678 if (likely(update_next_balance))
4679 rq->next_balance = next_balance;
4683 * run_rebalance_domains is triggered when needed from the scheduler tick.
4684 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4685 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4687 static void run_rebalance_domains(struct softirq_action *h)
4689 int this_cpu = raw_smp_processor_id();
4690 struct rq *this_rq = cpu_rq(this_cpu);
4691 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4692 CPU_IDLE : CPU_NOT_IDLE;
4694 rebalance_domains(this_cpu, idle);
4696 #ifdef CONFIG_NO_HZ
4698 * If this cpu is the owner for idle load balancing, then do the
4699 * balancing on behalf of the other idle cpus whose ticks are
4700 * stopped.
4702 if (this_rq->idle_at_tick &&
4703 atomic_read(&nohz.load_balancer) == this_cpu) {
4704 struct rq *rq;
4705 int balance_cpu;
4707 for_each_cpu(balance_cpu, nohz.cpu_mask) {
4708 if (balance_cpu == this_cpu)
4709 continue;
4712 * If this cpu gets work to do, stop the load balancing
4713 * work being done for other cpus. Next load
4714 * balancing owner will pick it up.
4716 if (need_resched())
4717 break;
4719 rebalance_domains(balance_cpu, CPU_IDLE);
4721 rq = cpu_rq(balance_cpu);
4722 if (time_after(this_rq->next_balance, rq->next_balance))
4723 this_rq->next_balance = rq->next_balance;
4726 #endif
4729 static inline int on_null_domain(int cpu)
4731 return !rcu_dereference(cpu_rq(cpu)->sd);
4735 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4737 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4738 * idle load balancing owner or decide to stop the periodic load balancing,
4739 * if the whole system is idle.
4741 static inline void trigger_load_balance(struct rq *rq, int cpu)
4743 #ifdef CONFIG_NO_HZ
4745 * If we were in the nohz mode recently and busy at the current
4746 * scheduler tick, then check if we need to nominate new idle
4747 * load balancer.
4749 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4750 rq->in_nohz_recently = 0;
4752 if (atomic_read(&nohz.load_balancer) == cpu) {
4753 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4754 atomic_set(&nohz.load_balancer, -1);
4757 if (atomic_read(&nohz.load_balancer) == -1) {
4759 * simple selection for now: Nominate the
4760 * first cpu in the nohz list to be the next
4761 * ilb owner.
4763 * TBD: Traverse the sched domains and nominate
4764 * the nearest cpu in the nohz.cpu_mask.
4766 int ilb = cpumask_first(nohz.cpu_mask);
4768 if (ilb < nr_cpu_ids)
4769 resched_cpu(ilb);
4774 * If this cpu is idle and doing idle load balancing for all the
4775 * cpus with ticks stopped, is it time for that to stop?
4777 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4778 cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4779 resched_cpu(cpu);
4780 return;
4784 * If this cpu is idle and the idle load balancing is done by
4785 * someone else, then no need raise the SCHED_SOFTIRQ
4787 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4788 cpumask_test_cpu(cpu, nohz.cpu_mask))
4789 return;
4790 #endif
4791 /* Don't need to rebalance while attached to NULL domain */
4792 if (time_after_eq(jiffies, rq->next_balance) &&
4793 likely(!on_null_domain(cpu)))
4794 raise_softirq(SCHED_SOFTIRQ);
4797 #else /* CONFIG_SMP */
4800 * on UP we do not need to balance between CPUs:
4802 static inline void idle_balance(int cpu, struct rq *rq)
4806 #endif
4808 DEFINE_PER_CPU(struct kernel_stat, kstat);
4810 EXPORT_PER_CPU_SYMBOL(kstat);
4813 * Return any ns on the sched_clock that have not yet been accounted in
4814 * @p in case that task is currently running.
4816 * Called with task_rq_lock() held on @rq.
4818 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
4820 u64 ns = 0;
4822 if (task_current(rq, p)) {
4823 update_rq_clock(rq);
4824 ns = rq->clock - p->se.exec_start;
4825 if ((s64)ns < 0)
4826 ns = 0;
4829 return ns;
4832 unsigned long long __task_delta_exec(struct task_struct *p, int update)
4834 s64 delta_exec;
4835 struct rq *rq;
4837 rq = task_rq(p);
4838 WARN_ON_ONCE(!runqueue_is_locked());
4839 WARN_ON_ONCE(!task_current(rq, p));
4841 if (update)
4842 update_rq_clock(rq);
4844 delta_exec = rq->clock - p->se.exec_start;
4846 WARN_ON_ONCE(delta_exec < 0);
4848 return delta_exec;
4852 * Return any ns on the sched_clock that have not yet been banked in
4853 * @p in case that task is currently running.
4855 unsigned long long task_delta_exec(struct task_struct *p)
4857 unsigned long flags;
4858 struct rq *rq;
4859 u64 ns = 0;
4861 rq = task_rq_lock(p, &flags);
4862 ns = do_task_delta_exec(p, rq);
4863 task_rq_unlock(rq, &flags);
4865 return ns;
4869 * Return accounted runtime for the task.
4870 * In case the task is currently running, return the runtime plus current's
4871 * pending runtime that have not been accounted yet.
4873 unsigned long long task_sched_runtime(struct task_struct *p)
4875 unsigned long flags;
4876 struct rq *rq;
4877 u64 ns = 0;
4879 rq = task_rq_lock(p, &flags);
4880 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
4881 task_rq_unlock(rq, &flags);
4883 return ns;
4887 * Return sum_exec_runtime for the thread group.
4888 * In case the task is currently running, return the sum plus current's
4889 * pending runtime that have not been accounted yet.
4891 * Note that the thread group might have other running tasks as well,
4892 * so the return value not includes other pending runtime that other
4893 * running tasks might have.
4895 unsigned long long thread_group_sched_runtime(struct task_struct *p)
4897 struct task_cputime totals;
4898 unsigned long flags;
4899 struct rq *rq;
4900 u64 ns;
4902 rq = task_rq_lock(p, &flags);
4903 thread_group_cputime(p, &totals);
4904 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
4905 task_rq_unlock(rq, &flags);
4907 return ns;
4911 * Account user cpu time to a process.
4912 * @p: the process that the cpu time gets accounted to
4913 * @cputime: the cpu time spent in user space since the last update
4914 * @cputime_scaled: cputime scaled by cpu frequency
4916 void account_user_time(struct task_struct *p, cputime_t cputime,
4917 cputime_t cputime_scaled)
4919 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4920 cputime64_t tmp;
4922 /* Add user time to process. */
4923 p->utime = cputime_add(p->utime, cputime);
4924 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4925 account_group_user_time(p, cputime);
4927 /* Add user time to cpustat. */
4928 tmp = cputime_to_cputime64(cputime);
4929 if (rt_task(p))
4930 cpustat->user_rt = cputime64_add(cpustat->user_rt, tmp);
4931 else if (TASK_NICE(p) > 0)
4932 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4933 else
4934 cpustat->user = cputime64_add(cpustat->user, tmp);
4935 /* Account for user time used */
4936 acct_update_integrals(p);
4940 * Account guest cpu time to a process.
4941 * @p: the process that the cpu time gets accounted to
4942 * @cputime: the cpu time spent in virtual machine since the last update
4943 * @cputime_scaled: cputime scaled by cpu frequency
4945 static void account_guest_time(struct task_struct *p, cputime_t cputime,
4946 cputime_t cputime_scaled)
4948 cputime64_t tmp;
4949 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4951 tmp = cputime_to_cputime64(cputime);
4953 /* Add guest 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);
4957 p->gtime = cputime_add(p->gtime, cputime);
4959 /* Add guest time to cpustat. */
4960 cpustat->user = cputime64_add(cpustat->user, tmp);
4961 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4965 * Account system cpu time to a process.
4966 * @p: the process that the cpu time gets accounted to
4967 * @hardirq_offset: the offset to subtract from hardirq_count()
4968 * @cputime: the cpu time spent in kernel space since the last update
4969 * @cputime_scaled: cputime scaled by cpu frequency
4971 void account_system_time(struct task_struct *p, int hardirq_offset,
4972 cputime_t cputime, cputime_t cputime_scaled)
4974 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4975 cputime64_t tmp;
4977 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4978 account_guest_time(p, cputime, cputime_scaled);
4979 return;
4982 /* Add system time to process. */
4983 p->stime = cputime_add(p->stime, cputime);
4984 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
4985 account_group_system_time(p, cputime);
4987 /* Add system time to cpustat. */
4988 tmp = cputime_to_cputime64(cputime);
4989 if (hardirq_count() - hardirq_offset || (p->flags & PF_HARDIRQ))
4990 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4991 else if (softirq_count() || (p->flags & PF_SOFTIRQ))
4992 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4993 else if (rt_task(p))
4994 cpustat->system_rt = cputime64_add(cpustat->system_rt, tmp);
4995 else
4996 cpustat->system = cputime64_add(cpustat->system, tmp);
4998 /* Account for system time used */
4999 acct_update_integrals(p);
5003 * Account for involuntary wait time.
5004 * @steal: the cpu time spent in involuntary wait
5006 void account_steal_time(cputime_t cputime)
5008 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5009 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5011 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
5015 * Account for idle time.
5016 * @cputime: the cpu time spent in idle wait
5018 void account_idle_time(cputime_t cputime)
5020 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5021 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5022 struct rq *rq = this_rq();
5024 if (atomic_read(&rq->nr_iowait) > 0)
5025 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
5026 else
5027 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
5030 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
5033 * Account a single tick of cpu time.
5034 * @p: the process that the cpu time gets accounted to
5035 * @user_tick: indicates if the tick is a user or a system tick
5037 void account_process_tick(struct task_struct *p, int user_tick)
5039 cputime_t one_jiffy = jiffies_to_cputime(1);
5040 cputime_t one_jiffy_scaled = cputime_to_scaled(one_jiffy);
5041 struct rq *rq = this_rq();
5043 if (user_tick)
5044 account_user_time(p, one_jiffy, one_jiffy_scaled);
5045 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
5046 account_system_time(p, HARDIRQ_OFFSET, one_jiffy,
5047 one_jiffy_scaled);
5048 else
5049 account_idle_time(one_jiffy);
5053 * Account multiple ticks of steal time.
5054 * @p: the process from which the cpu time has been stolen
5055 * @ticks: number of stolen ticks
5057 void account_steal_ticks(unsigned long ticks)
5059 account_steal_time(jiffies_to_cputime(ticks));
5063 * Account multiple ticks of idle time.
5064 * @ticks: number of stolen ticks
5066 void account_idle_ticks(unsigned long ticks)
5068 account_idle_time(jiffies_to_cputime(ticks));
5071 #endif
5074 * Use precise platform statistics if available:
5076 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
5077 cputime_t task_utime(struct task_struct *p)
5079 return p->utime;
5082 cputime_t task_stime(struct task_struct *p)
5084 return p->stime;
5086 #else
5087 cputime_t task_utime(struct task_struct *p)
5089 clock_t utime = cputime_to_clock_t(p->utime),
5090 total = utime + cputime_to_clock_t(p->stime);
5091 u64 temp;
5094 * Use CFS's precise accounting:
5096 temp = (u64)nsec_to_clock_t(p->se.sum_exec_runtime);
5098 if (total) {
5099 temp *= utime;
5100 do_div(temp, total);
5102 utime = (clock_t)temp;
5104 p->prev_utime = max(p->prev_utime, clock_t_to_cputime(utime));
5105 return p->prev_utime;
5108 cputime_t task_stime(struct task_struct *p)
5110 clock_t stime;
5113 * Use CFS's precise accounting. (we subtract utime from
5114 * the total, to make sure the total observed by userspace
5115 * grows monotonically - apps rely on that):
5117 stime = nsec_to_clock_t(p->se.sum_exec_runtime) -
5118 cputime_to_clock_t(task_utime(p));
5120 if (stime >= 0)
5121 p->prev_stime = max(p->prev_stime, clock_t_to_cputime(stime));
5123 return p->prev_stime;
5125 #endif
5127 inline cputime_t task_gtime(struct task_struct *p)
5129 return p->gtime;
5133 * This function gets called by the timer code, with HZ frequency.
5134 * We call it with interrupts disabled.
5136 * It also gets called by the fork code, when changing the parent's
5137 * timeslices.
5139 void scheduler_tick(void)
5141 int cpu = smp_processor_id();
5142 struct rq *rq = cpu_rq(cpu);
5143 struct task_struct *curr = rq->curr;
5145 sched_clock_tick();
5147 BUG_ON(!irqs_disabled());
5149 spin_lock(&rq->lock);
5150 update_rq_clock(rq);
5151 update_cpu_load(rq);
5152 if (curr != rq->idle && curr->se.on_rq)
5153 curr->sched_class->task_tick(rq, curr, 0);
5154 perf_counter_task_tick(curr, cpu);
5155 spin_unlock(&rq->lock);
5157 #ifdef CONFIG_SMP
5158 rq->idle_at_tick = idle_cpu(cpu);
5159 trigger_load_balance(rq, cpu);
5160 #endif
5163 unsigned long notrace get_parent_ip(unsigned long addr)
5165 if (in_lock_functions(addr)) {
5166 addr = CALLER_ADDR2;
5167 if (in_lock_functions(addr))
5168 addr = CALLER_ADDR3;
5170 return addr;
5173 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
5174 defined(CONFIG_PREEMPT_TRACER))
5176 void __kprobes add_preempt_count(int val)
5178 #ifdef CONFIG_DEBUG_PREEMPT
5180 * Underflow?
5182 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5183 return;
5184 #endif
5185 preempt_count() += val;
5186 #ifdef CONFIG_DEBUG_PREEMPT
5188 * Spinlock count overflowing soon?
5190 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5191 PREEMPT_MASK - 10);
5192 #endif
5193 if (preempt_count() == val)
5194 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5196 EXPORT_SYMBOL(add_preempt_count);
5198 void __kprobes sub_preempt_count(int val)
5200 #ifdef CONFIG_DEBUG_PREEMPT
5202 * Underflow?
5204 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
5205 return;
5207 * Is the spinlock portion underflowing?
5209 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5210 !(preempt_count() & PREEMPT_MASK)))
5211 return;
5212 #endif
5214 if (preempt_count() == val)
5215 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5216 preempt_count() -= val;
5218 EXPORT_SYMBOL(sub_preempt_count);
5220 #endif
5223 * Print scheduling while atomic bug:
5225 static noinline void __schedule_bug(struct task_struct *prev)
5227 struct pt_regs *regs = get_irq_regs();
5229 printk(KERN_ERR "BUG: scheduling while atomic: %s/0x%08x/%d, CPU#%d\n",
5230 prev->comm, preempt_count(), prev->pid, smp_processor_id());
5232 debug_show_held_locks(prev);
5233 print_modules();
5234 if (irqs_disabled())
5235 print_irqtrace_events(prev);
5237 if (regs)
5238 show_regs(regs);
5239 else
5240 dump_stack();
5244 * Various schedule()-time debugging checks and statistics:
5246 static inline void schedule_debug(struct task_struct *prev)
5248 // WARN_ON(system_state == SYSTEM_BOOTING);
5251 * Test if we are atomic. Since do_exit() needs to call into
5252 * schedule() atomically, we ignore that path for now.
5253 * Otherwise, whine if we are scheduling when we should not be.
5255 if (unlikely(in_atomic() && !prev->exit_state))
5256 __schedule_bug(prev);
5258 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5260 schedstat_inc(this_rq(), sched_count);
5261 #ifdef CONFIG_SCHEDSTATS
5262 if (unlikely(prev->lock_depth >= 0)) {
5263 schedstat_inc(this_rq(), bkl_count);
5264 schedstat_inc(prev, sched_info.bkl_count);
5266 #endif
5269 static void put_prev_task(struct rq *rq, struct task_struct *prev)
5271 if (prev->state == TASK_RUNNING) {
5272 u64 runtime = prev->se.sum_exec_runtime;
5274 runtime -= prev->se.prev_sum_exec_runtime;
5275 runtime = min_t(u64, runtime, 2*sysctl_sched_migration_cost);
5278 * In order to avoid avg_overlap growing stale when we are
5279 * indeed overlapping and hence not getting put to sleep, grow
5280 * the avg_overlap on preemption.
5282 * We use the average preemption runtime because that
5283 * correlates to the amount of cache footprint a task can
5284 * build up.
5286 update_avg(&prev->se.avg_overlap, runtime);
5288 prev->sched_class->put_prev_task(rq, prev);
5292 * Pick up the highest-prio task:
5294 static inline struct task_struct *
5295 pick_next_task(struct rq *rq)
5297 const struct sched_class *class;
5298 struct task_struct *p;
5301 * Optimization: we know that if all tasks are in
5302 * the fair class we can call that function directly:
5304 if (likely(rq->nr_running == rq->cfs.nr_running)) {
5305 p = fair_sched_class.pick_next_task(rq);
5306 if (likely(p))
5307 return p;
5310 class = sched_class_highest;
5311 for ( ; ; ) {
5312 p = class->pick_next_task(rq);
5313 if (p)
5314 return p;
5316 * Will never be NULL as the idle class always
5317 * returns a non-NULL p:
5319 class = class->next;
5324 * schedule() is the main scheduler function.
5326 asmlinkage void __sched __schedule(void)
5328 struct task_struct *prev, *next;
5329 unsigned long *switch_count;
5330 struct rq *rq;
5331 int cpu;
5333 cpu = smp_processor_id();
5334 rq = cpu_rq(cpu);
5335 rcu_qsctr_inc(cpu);
5336 prev = rq->curr;
5337 switch_count = &prev->nivcsw;
5339 release_kernel_lock(prev);
5341 schedule_debug(prev);
5343 preempt_disable();
5345 if (sched_feat(HRTICK))
5346 hrtick_clear(rq);
5348 spin_lock_irq(&rq->lock);
5349 update_rq_clock(rq);
5350 clear_tsk_need_resched(prev);
5352 if (!(prev->state & TASK_RUNNING_MUTEX) && prev->state &&
5353 !(preempt_count() & PREEMPT_ACTIVE)) {
5354 if (unlikely(signal_pending_state(prev->state, prev)))
5355 prev->state = TASK_RUNNING;
5356 else {
5357 touch_softlockup_watchdog();
5358 deactivate_task(rq, prev, 1);
5360 switch_count = &prev->nvcsw;
5363 if (preempt_count() & PREEMPT_ACTIVE)
5364 sub_preempt_count(PREEMPT_ACTIVE);
5366 #ifdef CONFIG_SMP
5367 if (prev->sched_class->pre_schedule)
5368 prev->sched_class->pre_schedule(rq, prev);
5369 #endif
5371 if (unlikely(!rq->nr_running))
5372 idle_balance(cpu, rq);
5374 put_prev_task(rq, prev);
5375 next = pick_next_task(rq);
5377 if (likely(prev != next)) {
5378 sched_info_switch(prev, next);
5379 perf_counter_task_sched_out(prev, cpu);
5381 rq->nr_switches++;
5382 rq->curr = next;
5383 ++*switch_count;
5385 context_switch(rq, prev, next); /* unlocks the rq */
5387 * the context switch might have flipped the stack from under
5388 * us, hence refresh the local variables.
5390 cpu = smp_processor_id();
5391 rq = cpu_rq(cpu);
5392 __preempt_enable_no_resched();
5393 } else {
5394 __preempt_enable_no_resched();
5395 spin_unlock(&rq->lock);
5398 reacquire_kernel_lock(current);
5401 asmlinkage void __sched schedule(void)
5403 need_resched:
5404 local_irq_disable();
5405 __schedule();
5406 local_irq_enable();
5408 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
5409 goto need_resched;
5411 EXPORT_SYMBOL(schedule);
5413 #if defined(CONFIG_SMP) && !defined(CONFIG_PREEMPT_RT)
5415 * Look out! "owner" is an entirely speculative pointer
5416 * access and not reliable.
5418 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
5420 unsigned int cpu;
5421 struct rq *rq;
5423 if (!sched_feat(OWNER_SPIN))
5424 return 0;
5426 #ifdef CONFIG_DEBUG_PAGEALLOC
5428 * Need to access the cpu field knowing that
5429 * DEBUG_PAGEALLOC could have unmapped it if
5430 * the mutex owner just released it and exited.
5432 if (probe_kernel_address(&owner->cpu, cpu))
5433 goto out;
5434 #else
5435 cpu = owner->cpu;
5436 #endif
5439 * Even if the access succeeded (likely case),
5440 * the cpu field may no longer be valid.
5442 if (cpu >= nr_cpumask_bits)
5443 goto out;
5446 * We need to validate that we can do a
5447 * get_cpu() and that we have the percpu area.
5449 if (!cpu_online(cpu))
5450 goto out;
5452 rq = cpu_rq(cpu);
5454 for (;;) {
5456 * Owner changed, break to re-assess state.
5458 if (lock->owner != owner)
5459 break;
5462 * Is that owner really running on that cpu?
5464 if (task_thread_info(rq->curr) != owner || need_resched())
5465 return 0;
5467 cpu_relax();
5469 out:
5470 return 1;
5472 #endif
5474 #ifdef CONFIG_PREEMPT
5477 * Global flag to turn preemption off on a CONFIG_PREEMPT kernel:
5479 int kernel_preemption = 1;
5481 static int __init preempt_setup (char *str)
5483 if (!strncmp(str, "off", 3)) {
5484 if (kernel_preemption) {
5485 printk(KERN_INFO "turning off kernel preemption!\n");
5486 kernel_preemption = 0;
5488 return 1;
5490 if (!strncmp(str, "on", 2)) {
5491 if (!kernel_preemption) {
5492 printk(KERN_INFO "turning on kernel preemption!\n");
5493 kernel_preemption = 1;
5495 return 1;
5497 get_option(&str, &kernel_preemption);
5499 return 1;
5502 __setup("preempt=", preempt_setup);
5505 * this is the entry point to schedule() from in-kernel preemption
5506 * off of preempt_enable. Kernel preemptions off return from interrupt
5507 * occur there and call schedule directly.
5509 asmlinkage void __sched preempt_schedule(void)
5511 struct thread_info *ti = current_thread_info();
5512 struct task_struct *task = current;
5513 int saved_lock_depth;
5515 if (!kernel_preemption)
5516 return;
5518 * If there is a non-zero preempt_count or interrupts are disabled,
5519 * we do not want to preempt the current task. Just return..
5521 if (likely(ti->preempt_count || irqs_disabled()))
5522 return;
5524 do {
5525 local_irq_disable();
5526 add_preempt_count(PREEMPT_ACTIVE);
5529 * We keep the big kernel semaphore locked, but we
5530 * clear ->lock_depth so that schedule() doesnt
5531 * auto-release the semaphore:
5533 saved_lock_depth = task->lock_depth;
5534 task->lock_depth = -1;
5535 __schedule();
5536 task->lock_depth = saved_lock_depth;
5537 local_irq_enable();
5540 * Check again in case we missed a preemption opportunity
5541 * between schedule and now.
5543 barrier();
5544 } while (need_resched());
5546 EXPORT_SYMBOL(preempt_schedule);
5549 * this is is the entry point for the IRQ return path. Called with
5550 * interrupts disabled. To avoid infinite irq-entry recursion problems
5551 * with fast-paced IRQ sources we do all of this carefully to never
5552 * enable interrupts again.
5554 asmlinkage void __sched preempt_schedule_irq(void)
5556 struct thread_info *ti = current_thread_info();
5557 struct task_struct *task = current;
5558 int saved_lock_depth;
5560 if (!kernel_preemption)
5561 return;
5563 * If there is a non-zero preempt_count then just return.
5564 * (interrupts are disabled)
5566 if (unlikely(ti->preempt_count))
5567 return;
5569 do {
5570 local_irq_disable();
5571 add_preempt_count(PREEMPT_ACTIVE);
5574 * We keep the big kernel semaphore locked, but we
5575 * clear ->lock_depth so that schedule() doesnt
5576 * auto-release the semaphore:
5578 saved_lock_depth = task->lock_depth;
5579 task->lock_depth = -1;
5580 __schedule();
5581 local_irq_disable();
5582 task->lock_depth = saved_lock_depth;
5585 * Check again in case we missed a preemption opportunity
5586 * between schedule and now.
5588 barrier();
5589 } while (need_resched());
5592 #endif /* CONFIG_PREEMPT */
5594 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
5595 void *key)
5597 return try_to_wake_up(curr->private, mode, sync, 0);
5599 EXPORT_SYMBOL(default_wake_function);
5602 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
5603 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
5604 * number) then we wake all the non-exclusive tasks and one exclusive task.
5606 * There are circumstances in which we can try to wake a task which has already
5607 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
5608 * zero in this (rare) case, and we handle it by continuing to scan the queue.
5610 void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
5611 int nr_exclusive, int sync, void *key)
5613 wait_queue_t *curr, *next;
5615 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
5616 unsigned flags = curr->flags;
5618 if (curr->func(curr, mode, sync, key) &&
5619 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
5620 break;
5625 * __wake_up - wake up threads blocked on a waitqueue.
5626 * @q: the waitqueue
5627 * @mode: which threads
5628 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5629 * @key: is directly passed to the wakeup function
5631 void __wake_up(wait_queue_head_t *q, unsigned int mode,
5632 int nr_exclusive, void *key)
5634 unsigned long flags;
5636 spin_lock_irqsave(&q->lock, flags);
5637 __wake_up_common(q, mode, nr_exclusive, 1, key);
5638 spin_unlock_irqrestore(&q->lock, flags);
5640 EXPORT_SYMBOL(__wake_up);
5643 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
5645 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
5647 __wake_up_common(q, mode, 1, 0, NULL);
5651 * __wake_up_sync - wake up threads blocked on a waitqueue.
5652 * @q: the waitqueue
5653 * @mode: which threads
5654 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5656 * The sync wakeup differs that the waker knows that it will schedule
5657 * away soon, so while the target thread will be woken up, it will not
5658 * be migrated to another CPU - ie. the two threads are 'synchronized'
5659 * with each other. This can prevent needless bouncing between CPUs.
5661 * On UP it can prevent extra preemption.
5663 void
5664 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
5666 unsigned long flags;
5667 int sync = 1;
5669 if (unlikely(!q))
5670 return;
5672 if (unlikely(!nr_exclusive))
5673 sync = 0;
5675 spin_lock_irqsave(&q->lock, flags);
5676 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
5677 spin_unlock_irqrestore(&q->lock, flags);
5679 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
5682 * complete: - signals a single thread waiting on this completion
5683 * @x: holds the state of this particular completion
5685 * This will wake up a single thread waiting on this completion. Threads will be
5686 * awakened in the same order in which they were queued.
5688 * See also complete_all(), wait_for_completion() and related routines.
5690 void complete(struct completion *x)
5692 unsigned long flags;
5694 spin_lock_irqsave(&x->wait.lock, flags);
5695 x->done++;
5696 __wake_up_common(&x->wait, TASK_NORMAL, 1, 1, NULL);
5697 spin_unlock_irqrestore(&x->wait.lock, flags);
5699 EXPORT_SYMBOL(complete);
5702 * complete_all: - signals all threads waiting on this completion
5703 * @x: holds the state of this particular completion
5705 * This will wake up all threads waiting on this particular completion event.
5707 void complete_all(struct completion *x)
5709 unsigned long flags;
5711 spin_lock_irqsave(&x->wait.lock, flags);
5712 x->done += UINT_MAX/2;
5713 __wake_up_common(&x->wait, TASK_NORMAL, 0, 1, NULL);
5714 spin_unlock_irqrestore(&x->wait.lock, flags);
5716 EXPORT_SYMBOL(complete_all);
5718 static inline long __sched
5719 do_wait_for_common(struct completion *x, long timeout, int state)
5721 if (!x->done) {
5722 DECLARE_WAITQUEUE(wait, current);
5724 wait.flags |= WQ_FLAG_EXCLUSIVE;
5725 __add_wait_queue_tail(&x->wait, &wait);
5726 do {
5727 if (signal_pending_state(state, current)) {
5728 timeout = -ERESTARTSYS;
5729 break;
5731 __set_current_state(state);
5732 spin_unlock_irq(&x->wait.lock);
5733 timeout = schedule_timeout(timeout);
5734 spin_lock_irq(&x->wait.lock);
5735 } while (!x->done && timeout);
5736 __remove_wait_queue(&x->wait, &wait);
5737 if (!x->done)
5738 return timeout;
5740 x->done--;
5741 return timeout ?: 1;
5744 static long __sched
5745 wait_for_common(struct completion *x, long timeout, int state)
5747 might_sleep();
5749 spin_lock_irq(&x->wait.lock);
5750 timeout = do_wait_for_common(x, timeout, state);
5751 spin_unlock_irq(&x->wait.lock);
5752 return timeout;
5756 * wait_for_completion: - waits for completion of a task
5757 * @x: holds the state of this particular completion
5759 * This waits to be signaled for completion of a specific task. It is NOT
5760 * interruptible and there is no timeout.
5762 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
5763 * and interrupt capability. Also see complete().
5765 void __sched wait_for_completion(struct completion *x)
5767 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
5769 EXPORT_SYMBOL(wait_for_completion);
5772 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
5773 * @x: holds the state of this particular completion
5774 * @timeout: timeout value in jiffies
5776 * This waits for either a completion of a specific task to be signaled or for a
5777 * specified timeout to expire. The timeout is in jiffies. It is not
5778 * interruptible.
5780 unsigned long __sched
5781 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
5783 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
5785 EXPORT_SYMBOL(wait_for_completion_timeout);
5788 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
5789 * @x: holds the state of this particular completion
5791 * This waits for completion of a specific task to be signaled. It is
5792 * interruptible.
5794 int __sched wait_for_completion_interruptible(struct completion *x)
5796 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
5797 if (t == -ERESTARTSYS)
5798 return t;
5799 return 0;
5801 EXPORT_SYMBOL(wait_for_completion_interruptible);
5804 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
5805 * @x: holds the state of this particular completion
5806 * @timeout: timeout value in jiffies
5808 * This waits for either a completion of a specific task to be signaled or for a
5809 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
5811 unsigned long __sched
5812 wait_for_completion_interruptible_timeout(struct completion *x,
5813 unsigned long timeout)
5815 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
5817 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
5820 * wait_for_completion_killable: - waits for completion of a task (killable)
5821 * @x: holds the state of this particular completion
5823 * This waits to be signaled for completion of a specific task. It can be
5824 * interrupted by a kill signal.
5826 int __sched wait_for_completion_killable(struct completion *x)
5828 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
5829 if (t == -ERESTARTSYS)
5830 return t;
5831 return 0;
5833 EXPORT_SYMBOL(wait_for_completion_killable);
5836 * try_wait_for_completion - try to decrement a completion without blocking
5837 * @x: completion structure
5839 * Returns: 0 if a decrement cannot be done without blocking
5840 * 1 if a decrement succeeded.
5842 * If a completion is being used as a counting completion,
5843 * attempt to decrement the counter without blocking. This
5844 * enables us to avoid waiting if the resource the completion
5845 * is protecting is not available.
5847 bool try_wait_for_completion(struct completion *x)
5849 int ret = 1;
5851 spin_lock_irq(&x->wait.lock);
5852 if (!x->done)
5853 ret = 0;
5854 else
5855 x->done--;
5856 spin_unlock_irq(&x->wait.lock);
5857 return ret;
5859 EXPORT_SYMBOL(try_wait_for_completion);
5862 * completion_done - Test to see if a completion has any waiters
5863 * @x: completion structure
5865 * Returns: 0 if there are waiters (wait_for_completion() in progress)
5866 * 1 if there are no waiters.
5869 bool completion_done(struct completion *x)
5871 int ret = 1;
5873 spin_lock_irq(&x->wait.lock);
5874 if (!x->done)
5875 ret = 0;
5876 spin_unlock_irq(&x->wait.lock);
5877 return ret;
5879 EXPORT_SYMBOL(completion_done);
5881 static long __sched
5882 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
5884 unsigned long flags;
5885 wait_queue_t wait;
5887 init_waitqueue_entry(&wait, current);
5889 __set_current_state(state);
5891 spin_lock_irqsave(&q->lock, flags);
5892 __add_wait_queue(q, &wait);
5893 spin_unlock(&q->lock);
5894 timeout = schedule_timeout(timeout);
5895 spin_lock_irq(&q->lock);
5896 __remove_wait_queue(q, &wait);
5897 spin_unlock_irqrestore(&q->lock, flags);
5899 return timeout;
5902 void __sched interruptible_sleep_on(wait_queue_head_t *q)
5904 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5906 EXPORT_SYMBOL(interruptible_sleep_on);
5908 long __sched
5909 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
5911 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
5913 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
5915 void __sched sleep_on(wait_queue_head_t *q)
5917 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5919 EXPORT_SYMBOL(sleep_on);
5921 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
5923 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5925 EXPORT_SYMBOL(sleep_on_timeout);
5928 * task_setprio - set the current priority of a task
5929 * @p: task
5930 * @prio: prio value (kernel-internal form)
5932 * This function changes the 'effective' priority of a task. It does
5933 * not touch ->normal_prio like __setscheduler().
5935 * Used by the rt_mutex code to implement priority inheritance logic
5936 * and by rcupreempt-boost to boost priorities of tasks sleeping
5937 * with rcu locks.
5939 void task_setprio(struct task_struct *p, int prio)
5941 unsigned long flags;
5942 int oldprio, on_rq, running;
5943 struct rq *rq;
5944 const struct sched_class *prev_class = p->sched_class;
5946 BUG_ON(prio < 0 || prio > MAX_PRIO);
5948 rq = task_rq_lock(p, &flags);
5951 * Idle task boosting is a nono in general. There is one
5952 * exception, when NOHZ is active:
5954 * The idle task calls get_next_timer_interrupt() and holds
5955 * the timer wheel base->lock on the CPU and another CPU wants
5956 * to access the timer (probably to cancel it). We can safely
5957 * ignore the boosting request, as the idle CPU runs this code
5958 * with interrupts disabled and will complete the lock
5959 * protected section without being interrupted. So there is no
5960 * real need to boost.
5962 if (unlikely(p == rq->idle)) {
5963 WARN_ON(p != rq->curr);
5964 WARN_ON(p->pi_blocked_on);
5965 goto out_unlock;
5968 update_rq_clock(rq);
5970 oldprio = p->prio;
5971 on_rq = p->se.on_rq;
5972 running = task_current(rq, p);
5973 if (on_rq)
5974 dequeue_task(rq, p, 0);
5975 if (running)
5976 p->sched_class->put_prev_task(rq, p);
5978 if (rt_prio(prio))
5979 p->sched_class = &rt_sched_class;
5980 else
5981 p->sched_class = &fair_sched_class;
5983 p->prio = prio;
5985 trace_sched_task_setprio(rq, p, oldprio);
5987 if (running)
5988 p->sched_class->set_curr_task(rq);
5989 if (on_rq) {
5990 enqueue_task(rq, p, 0);
5992 check_class_changed(rq, p, prev_class, oldprio, running);
5995 out_unlock:
5996 task_rq_unlock(rq, &flags);
5999 void set_user_nice(struct task_struct *p, long nice)
6001 int old_prio, delta, on_rq;
6002 unsigned long flags;
6003 struct rq *rq;
6005 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
6006 return;
6008 * We have to be careful, if called from sys_setpriority(),
6009 * the task might be in the middle of scheduling on another CPU.
6011 rq = task_rq_lock(p, &flags);
6012 update_rq_clock(rq);
6014 * The RT priorities are set via sched_setscheduler(), but we still
6015 * allow the 'normal' nice value to be set - but as expected
6016 * it wont have any effect on scheduling until the task is
6017 * SCHED_FIFO/SCHED_RR:
6019 if (task_has_rt_policy(p)) {
6020 p->static_prio = NICE_TO_PRIO(nice);
6021 goto out_unlock;
6023 on_rq = p->se.on_rq;
6024 if (on_rq)
6025 dequeue_task(rq, p, 0);
6027 p->static_prio = NICE_TO_PRIO(nice);
6028 set_load_weight(p);
6029 old_prio = p->prio;
6030 p->prio = effective_prio(p);
6031 delta = p->prio - old_prio;
6033 if (on_rq) {
6034 enqueue_task(rq, p, 0);
6036 * If the task increased its priority or is running and
6037 * lowered its priority, then reschedule its CPU:
6039 if (delta < 0 || (delta > 0 && task_running(rq, p)))
6040 resched_task(rq->curr);
6042 out_unlock:
6043 task_rq_unlock(rq, &flags);
6045 EXPORT_SYMBOL(set_user_nice);
6048 * can_nice - check if a task can reduce its nice value
6049 * @p: task
6050 * @nice: nice value
6052 int can_nice(const struct task_struct *p, const int nice)
6054 /* convert nice value [19,-20] to rlimit style value [1,40] */
6055 int nice_rlim = 20 - nice;
6057 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
6058 capable(CAP_SYS_NICE));
6061 #ifdef __ARCH_WANT_SYS_NICE
6064 * sys_nice - change the priority of the current process.
6065 * @increment: priority increment
6067 * sys_setpriority is a more generic, but much slower function that
6068 * does similar things.
6070 SYSCALL_DEFINE1(nice, int, increment)
6072 long nice, retval;
6075 * Setpriority might change our priority at the same moment.
6076 * We don't have to worry. Conceptually one call occurs first
6077 * and we have a single winner.
6079 if (increment < -40)
6080 increment = -40;
6081 if (increment > 40)
6082 increment = 40;
6084 nice = TASK_NICE(current) + increment;
6085 if (nice < -20)
6086 nice = -20;
6087 if (nice > 19)
6088 nice = 19;
6090 if (increment < 0 && !can_nice(current, nice))
6091 return -EPERM;
6093 retval = security_task_setnice(current, nice);
6094 if (retval)
6095 return retval;
6097 set_user_nice(current, nice);
6098 return 0;
6101 #endif
6104 * task_prio - return the priority value of a given task.
6105 * @p: the task in question.
6107 * This is the priority value as seen by users in /proc.
6108 * RT tasks are offset by -200. Normal tasks are centered
6109 * around 0, value goes from -16 to +15.
6111 int task_prio(const struct task_struct *p)
6113 return p->prio - MAX_RT_PRIO;
6117 * task_nice - return the nice value of a given task.
6118 * @p: the task in question.
6120 int task_nice(const struct task_struct *p)
6122 return TASK_NICE(p);
6124 EXPORT_SYMBOL(task_nice);
6127 * idle_cpu - is a given cpu idle currently?
6128 * @cpu: the processor in question.
6130 int idle_cpu(int cpu)
6132 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
6136 * idle_task - return the idle task for a given cpu.
6137 * @cpu: the processor in question.
6139 struct task_struct *idle_task(int cpu)
6141 return cpu_rq(cpu)->idle;
6145 * find_process_by_pid - find a process with a matching PID value.
6146 * @pid: the pid in question.
6148 static struct task_struct *find_process_by_pid(pid_t pid)
6150 return pid ? find_task_by_vpid(pid) : current;
6153 /* Actually do priority change: must hold rq lock. */
6154 static void
6155 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
6157 BUG_ON(p->se.on_rq);
6159 p->policy = policy;
6160 switch (p->policy) {
6161 case SCHED_NORMAL:
6162 case SCHED_BATCH:
6163 case SCHED_IDLE:
6164 p->sched_class = &fair_sched_class;
6165 break;
6166 case SCHED_FIFO:
6167 case SCHED_RR:
6168 p->sched_class = &rt_sched_class;
6169 break;
6172 p->rt_priority = prio;
6173 p->normal_prio = normal_prio(p);
6174 /* we are holding p->pi_lock already */
6175 p->prio = rt_mutex_getprio(p);
6176 set_load_weight(p);
6180 * check the target process has a UID that matches the current process's
6182 static bool check_same_owner(struct task_struct *p)
6184 const struct cred *cred = current_cred(), *pcred;
6185 bool match;
6187 rcu_read_lock();
6188 pcred = __task_cred(p);
6189 match = (cred->euid == pcred->euid ||
6190 cred->euid == pcred->uid);
6191 rcu_read_unlock();
6192 return match;
6195 static int __sched_setscheduler(struct task_struct *p, int policy,
6196 struct sched_param *param, bool user)
6198 int retval, oldprio, oldpolicy = -1, on_rq, running;
6199 unsigned long flags;
6200 const struct sched_class *prev_class = p->sched_class;
6201 struct rq *rq;
6203 /* may grab non-irq protected spin_locks */
6204 BUG_ON(in_interrupt());
6205 recheck:
6206 /* double check policy once rq lock held */
6207 if (policy < 0)
6208 policy = oldpolicy = p->policy;
6209 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
6210 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
6211 policy != SCHED_IDLE)
6212 return -EINVAL;
6214 * Valid priorities for SCHED_FIFO and SCHED_RR are
6215 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
6216 * SCHED_BATCH and SCHED_IDLE is 0.
6218 if (param->sched_priority < 0 ||
6219 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
6220 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
6221 return -EINVAL;
6222 if (rt_policy(policy) != (param->sched_priority != 0))
6223 return -EINVAL;
6226 * Allow unprivileged RT tasks to decrease priority:
6228 if (user && !capable(CAP_SYS_NICE)) {
6229 if (rt_policy(policy)) {
6230 unsigned long rlim_rtprio;
6232 if (!lock_task_sighand(p, &flags))
6233 return -ESRCH;
6234 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
6235 unlock_task_sighand(p, &flags);
6237 /* can't set/change the rt policy */
6238 if (policy != p->policy && !rlim_rtprio)
6239 return -EPERM;
6241 /* can't increase priority */
6242 if (param->sched_priority > p->rt_priority &&
6243 param->sched_priority > rlim_rtprio)
6244 return -EPERM;
6247 * Like positive nice levels, dont allow tasks to
6248 * move out of SCHED_IDLE either:
6250 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
6251 return -EPERM;
6253 /* can't change other user's priorities */
6254 if (!check_same_owner(p))
6255 return -EPERM;
6258 if (user) {
6259 #ifdef CONFIG_RT_GROUP_SCHED
6261 * Do not allow realtime tasks into groups that have no runtime
6262 * assigned.
6264 if (rt_bandwidth_enabled() && rt_policy(policy) &&
6265 task_group(p)->rt_bandwidth.rt_runtime == 0)
6266 return -EPERM;
6267 #endif
6269 retval = security_task_setscheduler(p, policy, param);
6270 if (retval)
6271 return retval;
6275 * make sure no PI-waiters arrive (or leave) while we are
6276 * changing the priority of the task:
6278 spin_lock_irqsave(&p->pi_lock, flags);
6280 * To be able to change p->policy safely, the apropriate
6281 * runqueue lock must be held.
6283 rq = __task_rq_lock(p);
6284 /* recheck policy now with rq lock held */
6285 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
6286 policy = oldpolicy = -1;
6287 __task_rq_unlock(rq);
6288 spin_unlock_irqrestore(&p->pi_lock, flags);
6289 goto recheck;
6291 update_rq_clock(rq);
6292 on_rq = p->se.on_rq;
6293 running = task_current(rq, p);
6294 if (on_rq)
6295 deactivate_task(rq, p, 0);
6296 if (running)
6297 p->sched_class->put_prev_task(rq, p);
6299 oldprio = p->prio;
6300 __setscheduler(rq, p, policy, param->sched_priority);
6302 if (running)
6303 p->sched_class->set_curr_task(rq);
6304 if (on_rq) {
6305 activate_task(rq, p, 0);
6307 check_class_changed(rq, p, prev_class, oldprio, running);
6309 __task_rq_unlock(rq);
6310 spin_unlock_irqrestore(&p->pi_lock, flags);
6312 rt_mutex_adjust_pi(p);
6314 return 0;
6318 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
6319 * @p: the task in question.
6320 * @policy: new policy.
6321 * @param: structure containing the new RT priority.
6323 * NOTE that the task may be already dead.
6325 int sched_setscheduler(struct task_struct *p, int policy,
6326 struct sched_param *param)
6328 return __sched_setscheduler(p, policy, param, true);
6330 EXPORT_SYMBOL_GPL(sched_setscheduler);
6333 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
6334 * @p: the task in question.
6335 * @policy: new policy.
6336 * @param: structure containing the new RT priority.
6338 * Just like sched_setscheduler, only don't bother checking if the
6339 * current context has permission. For example, this is needed in
6340 * stop_machine(): we create temporary high priority worker threads,
6341 * but our caller might not have that capability.
6343 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
6344 struct sched_param *param)
6346 return __sched_setscheduler(p, policy, param, false);
6349 static int
6350 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
6352 struct sched_param lparam;
6353 struct task_struct *p;
6354 int retval;
6356 if (!param || pid < 0)
6357 return -EINVAL;
6358 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
6359 return -EFAULT;
6361 rcu_read_lock();
6362 retval = -ESRCH;
6363 p = find_process_by_pid(pid);
6364 if (p != NULL)
6365 retval = sched_setscheduler(p, policy, &lparam);
6366 rcu_read_unlock();
6368 return retval;
6372 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
6373 * @pid: the pid in question.
6374 * @policy: new policy.
6375 * @param: structure containing the new RT priority.
6377 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
6378 struct sched_param __user *, param)
6380 /* negative values for policy are not valid */
6381 if (policy < 0)
6382 return -EINVAL;
6384 return do_sched_setscheduler(pid, policy, param);
6388 * sys_sched_setparam - set/change the RT priority of a thread
6389 * @pid: the pid in question.
6390 * @param: structure containing the new RT priority.
6392 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
6394 return do_sched_setscheduler(pid, -1, param);
6398 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
6399 * @pid: the pid in question.
6401 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
6403 struct task_struct *p;
6404 int retval;
6406 if (pid < 0)
6407 return -EINVAL;
6409 retval = -ESRCH;
6410 read_lock(&tasklist_lock);
6411 p = find_process_by_pid(pid);
6412 if (p) {
6413 retval = security_task_getscheduler(p);
6414 if (!retval)
6415 retval = p->policy;
6417 read_unlock(&tasklist_lock);
6418 return retval;
6422 * sys_sched_getscheduler - get the RT priority of a thread
6423 * @pid: the pid in question.
6424 * @param: structure containing the RT priority.
6426 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
6428 struct sched_param lp;
6429 struct task_struct *p;
6430 int retval;
6432 if (!param || pid < 0)
6433 return -EINVAL;
6435 read_lock(&tasklist_lock);
6436 p = find_process_by_pid(pid);
6437 retval = -ESRCH;
6438 if (!p)
6439 goto out_unlock;
6441 retval = security_task_getscheduler(p);
6442 if (retval)
6443 goto out_unlock;
6445 lp.sched_priority = p->rt_priority;
6446 read_unlock(&tasklist_lock);
6449 * This one might sleep, we cannot do it with a spinlock held ...
6451 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
6453 return retval;
6455 out_unlock:
6456 read_unlock(&tasklist_lock);
6457 return retval;
6460 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
6462 cpumask_var_t cpus_allowed, new_mask;
6463 struct task_struct *p;
6464 int retval;
6466 get_online_cpus();
6467 read_lock(&tasklist_lock);
6469 p = find_process_by_pid(pid);
6470 if (!p) {
6471 read_unlock(&tasklist_lock);
6472 put_online_cpus();
6473 return -ESRCH;
6477 * It is not safe to call set_cpus_allowed with the
6478 * tasklist_lock held. We will bump the task_struct's
6479 * usage count and then drop tasklist_lock.
6481 get_task_struct(p);
6482 read_unlock(&tasklist_lock);
6484 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
6485 retval = -ENOMEM;
6486 goto out_put_task;
6488 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
6489 retval = -ENOMEM;
6490 goto out_free_cpus_allowed;
6492 retval = -EPERM;
6493 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
6494 goto out_unlock;
6496 retval = security_task_setscheduler(p, 0, NULL);
6497 if (retval)
6498 goto out_unlock;
6500 cpuset_cpus_allowed(p, cpus_allowed);
6501 cpumask_and(new_mask, in_mask, cpus_allowed);
6502 again:
6503 retval = set_cpus_allowed_ptr(p, new_mask);
6505 if (!retval) {
6506 cpuset_cpus_allowed(p, cpus_allowed);
6507 if (!cpumask_subset(new_mask, cpus_allowed)) {
6509 * We must have raced with a concurrent cpuset
6510 * update. Just reset the cpus_allowed to the
6511 * cpuset's cpus_allowed
6513 cpumask_copy(new_mask, cpus_allowed);
6514 goto again;
6517 out_unlock:
6518 free_cpumask_var(new_mask);
6519 out_free_cpus_allowed:
6520 free_cpumask_var(cpus_allowed);
6521 out_put_task:
6522 put_task_struct(p);
6523 put_online_cpus();
6524 return retval;
6527 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
6528 struct cpumask *new_mask)
6530 if (len < cpumask_size())
6531 cpumask_clear(new_mask);
6532 else if (len > cpumask_size())
6533 len = cpumask_size();
6535 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6539 * sys_sched_setaffinity - set the cpu affinity of a process
6540 * @pid: pid of the process
6541 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6542 * @user_mask_ptr: user-space pointer to the new cpu mask
6544 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6545 unsigned long __user *, user_mask_ptr)
6547 cpumask_var_t new_mask;
6548 int retval;
6550 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6551 return -ENOMEM;
6553 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6554 if (retval == 0)
6555 retval = sched_setaffinity(pid, new_mask);
6556 free_cpumask_var(new_mask);
6557 return retval;
6560 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6562 struct task_struct *p;
6563 int retval;
6565 get_online_cpus();
6566 read_lock(&tasklist_lock);
6568 retval = -ESRCH;
6569 p = find_process_by_pid(pid);
6570 if (!p)
6571 goto out_unlock;
6573 retval = security_task_getscheduler(p);
6574 if (retval)
6575 goto out_unlock;
6577 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
6579 out_unlock:
6580 read_unlock(&tasklist_lock);
6581 put_online_cpus();
6583 return retval;
6587 * sys_sched_getaffinity - get the cpu affinity of a process
6588 * @pid: pid of the process
6589 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6590 * @user_mask_ptr: user-space pointer to hold the current cpu mask
6592 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6593 unsigned long __user *, user_mask_ptr)
6595 int ret;
6596 cpumask_var_t mask;
6598 if (len < cpumask_size())
6599 return -EINVAL;
6601 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
6602 return -ENOMEM;
6604 ret = sched_getaffinity(pid, mask);
6605 if (ret == 0) {
6606 if (copy_to_user(user_mask_ptr, mask, cpumask_size()))
6607 ret = -EFAULT;
6608 else
6609 ret = cpumask_size();
6611 free_cpumask_var(mask);
6613 return ret;
6617 * sys_sched_yield - yield the current processor to other threads.
6619 * This function yields the current CPU to other tasks. If there are no
6620 * other threads running on this CPU then this function will return.
6622 SYSCALL_DEFINE0(sched_yield)
6624 struct rq *rq = this_rq_lock();
6626 schedstat_inc(rq, yld_count);
6627 current->sched_class->yield_task(rq);
6630 * Since we are going to call schedule() anyway, there's
6631 * no need to preempt or enable interrupts:
6633 spin_unlock_no_resched(&rq->lock);
6635 __schedule();
6637 local_irq_enable();
6638 preempt_check_resched();
6640 return 0;
6643 #if defined(CONFIG_DEBUG_SPINLOCK_SLEEP) || defined(CONFIG_DEBUG_PREEMPT)
6644 void __might_sleep(char *file, int line)
6646 #ifdef in_atomic
6647 static unsigned long prev_jiffy; /* ratelimiting */
6649 if ((!in_atomic() && !irqs_disabled()) ||
6650 system_state != SYSTEM_RUNNING || oops_in_progress)
6651 return;
6653 if (debug_direct_keyboard && hardirq_count())
6654 return;
6656 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6657 return;
6658 prev_jiffy = jiffies;
6660 printk(KERN_ERR
6661 "BUG: sleeping function called from invalid context at %s:%d\n",
6662 file, line);
6663 printk(KERN_ERR
6664 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6665 in_atomic(), irqs_disabled(),
6666 current->pid, current->comm);
6668 debug_show_held_locks(current);
6669 if (irqs_disabled())
6670 print_irqtrace_events(current);
6671 dump_stack();
6672 #endif
6674 EXPORT_SYMBOL(__might_sleep);
6675 #endif
6677 static void __cond_resched(void)
6679 #if defined(CONFIG_DEBUG_SPINLOCK_SLEEP) || defined(CONFIG_DEBUG_PREEMPT)
6680 __might_sleep(__FILE__, __LINE__);
6681 #endif
6683 * The BKS might be reacquired before we have dropped
6684 * PREEMPT_ACTIVE, which could trigger a second
6685 * cond_resched() call.
6687 do {
6688 local_irq_disable();
6689 add_preempt_count(PREEMPT_ACTIVE);
6690 __schedule();
6691 } while (need_resched());
6692 local_irq_enable();
6695 int __sched _cond_resched(void)
6697 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
6698 system_state == SYSTEM_RUNNING) {
6699 __cond_resched();
6700 return 1;
6702 return 0;
6704 EXPORT_SYMBOL(_cond_resched);
6707 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
6708 * call schedule, and on return reacquire the lock.
6710 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
6711 * operations here to prevent schedule() from being called twice (once via
6712 * spin_unlock(), once by hand).
6714 int __cond_resched_raw_spinlock(raw_spinlock_t *lock)
6716 int resched = need_resched() && system_state == SYSTEM_RUNNING;
6717 int ret = 0;
6719 if (spin_needbreak(lock) || resched) {
6720 spin_unlock_no_resched(lock);
6721 if (resched && need_resched())
6722 __cond_resched();
6723 else
6724 cpu_relax();
6725 ret = 1;
6726 spin_lock(lock);
6728 return ret;
6730 EXPORT_SYMBOL(__cond_resched_raw_spinlock);
6732 #ifdef CONFIG_PREEMPT_RT
6734 int __cond_resched_spinlock(spinlock_t *lock)
6736 int resched = need_resched() && system_state == SYSTEM_RUNNING;
6738 if (spin_needbreak(lock) || resched) {
6739 spin_unlock_no_resched(lock);
6740 __cond_resched();
6741 spin_lock(lock);
6742 return 1;
6744 return 0;
6746 EXPORT_SYMBOL(__cond_resched_spinlock);
6748 #endif
6751 * Voluntarily preempt a process context that has softirqs disabled:
6753 int __sched cond_resched_softirq(void)
6755 #ifndef CONFIG_PREEMPT_SOFTIRQS
6756 WARN_ON_ONCE(!in_softirq());
6757 if (!in_softirq())
6758 return 0;
6759 #endif
6760 if (need_resched() && system_state == SYSTEM_RUNNING) {
6761 local_bh_enable();
6762 __cond_resched();
6763 local_bh_disable();
6764 return 1;
6766 return 0;
6768 EXPORT_SYMBOL(cond_resched_softirq);
6771 * Voluntarily preempt a softirq context (possible with softirq threading):
6773 int __sched cond_resched_softirq_context(void)
6775 WARN_ON_ONCE(!in_softirq());
6777 if (softirq_need_resched() && system_state == SYSTEM_RUNNING) {
6778 raw_local_irq_disable();
6779 _local_bh_enable();
6780 raw_local_irq_enable();
6781 __cond_resched();
6782 local_bh_disable();
6783 return 1;
6785 return 0;
6787 EXPORT_SYMBOL(cond_resched_softirq_context);
6790 * Preempt a hardirq context if necessary (possible with hardirq threading):
6792 int cond_resched_hardirq_context(void)
6794 WARN_ON_ONCE(!in_irq());
6795 WARN_ON_ONCE(!irqs_disabled());
6797 if (hardirq_need_resched()) {
6798 #ifndef CONFIG_PREEMPT_RT
6799 irq_exit();
6800 #endif
6801 local_irq_enable();
6802 __cond_resched();
6803 #ifndef CONFIG_PREEMPT_RT
6804 local_irq_disable();
6805 __irq_enter();
6806 #endif
6808 return 1;
6810 return 0;
6812 EXPORT_SYMBOL(cond_resched_hardirq_context);
6814 #ifdef CONFIG_PREEMPT_VOLUNTARY
6816 int voluntary_preemption = 1;
6818 EXPORT_SYMBOL(voluntary_preemption);
6820 static int __init voluntary_preempt_setup (char *str)
6822 if (!strncmp(str, "off", 3))
6823 voluntary_preemption = 0;
6824 else
6825 get_option(&str, &voluntary_preemption);
6826 if (!voluntary_preemption)
6827 printk("turning off voluntary preemption!\n");
6829 return 1;
6832 __setup("voluntary-preempt=", voluntary_preempt_setup);
6834 #endif
6837 * yield - yield the current processor to other threads.
6839 * This is a shortcut for kernel-space yielding - it marks the
6840 * thread runnable and calls sys_sched_yield().
6842 void __sched __yield(void)
6844 set_current_state(TASK_RUNNING);
6845 sys_sched_yield();
6848 void __sched yield(void)
6850 static int once = 1;
6853 * it's a bug to rely on yield() with RT priorities. We print
6854 * the first occurance after bootup ... this will still give
6855 * us an idea about the scope of the problem, without spamming
6856 * the syslog:
6858 if (once && rt_task(current)) {
6859 once = 0;
6860 printk(KERN_ERR "BUG: %s:%d RT task yield()-ing!\n",
6861 current->comm, current->pid);
6862 dump_stack();
6864 __yield();
6866 EXPORT_SYMBOL(yield);
6869 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6870 * that process accounting knows that this is a task in IO wait state.
6872 * But don't do that if it is a deliberate, throttling IO wait (this task
6873 * has set its backing_dev_info: the queue against which it should throttle)
6875 void __sched io_schedule(void)
6877 struct rq *rq = &__raw_get_cpu_var(runqueues);
6879 delayacct_blkio_start();
6880 atomic_inc(&rq->nr_iowait);
6881 schedule();
6882 atomic_dec(&rq->nr_iowait);
6883 delayacct_blkio_end();
6885 EXPORT_SYMBOL(io_schedule);
6887 long __sched io_schedule_timeout(long timeout)
6889 struct rq *rq = &__raw_get_cpu_var(runqueues);
6890 long ret;
6892 delayacct_blkio_start();
6893 atomic_inc(&rq->nr_iowait);
6894 ret = schedule_timeout(timeout);
6895 atomic_dec(&rq->nr_iowait);
6896 delayacct_blkio_end();
6897 return ret;
6901 * sys_sched_get_priority_max - return maximum RT priority.
6902 * @policy: scheduling class.
6904 * this syscall returns the maximum rt_priority that can be used
6905 * by a given scheduling class.
6907 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6909 int ret = -EINVAL;
6911 switch (policy) {
6912 case SCHED_FIFO:
6913 case SCHED_RR:
6914 ret = MAX_USER_RT_PRIO-1;
6915 break;
6916 case SCHED_NORMAL:
6917 case SCHED_BATCH:
6918 case SCHED_IDLE:
6919 ret = 0;
6920 break;
6922 return ret;
6926 * sys_sched_get_priority_min - return minimum RT priority.
6927 * @policy: scheduling class.
6929 * this syscall returns the minimum rt_priority that can be used
6930 * by a given scheduling class.
6932 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6934 int ret = -EINVAL;
6936 switch (policy) {
6937 case SCHED_FIFO:
6938 case SCHED_RR:
6939 ret = 1;
6940 break;
6941 case SCHED_NORMAL:
6942 case SCHED_BATCH:
6943 case SCHED_IDLE:
6944 ret = 0;
6946 return ret;
6950 * sys_sched_rr_get_interval - return the default timeslice of a process.
6951 * @pid: pid of the process.
6952 * @interval: userspace pointer to the timeslice value.
6954 * this syscall writes the default timeslice value of a given process
6955 * into the user-space timespec buffer. A value of '0' means infinity.
6957 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
6958 struct timespec __user *, interval)
6960 struct task_struct *p;
6961 unsigned int time_slice;
6962 int retval;
6963 struct timespec t;
6965 if (pid < 0)
6966 return -EINVAL;
6968 retval = -ESRCH;
6969 read_lock(&tasklist_lock);
6970 p = find_process_by_pid(pid);
6971 if (!p)
6972 goto out_unlock;
6974 retval = security_task_getscheduler(p);
6975 if (retval)
6976 goto out_unlock;
6979 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
6980 * tasks that are on an otherwise idle runqueue:
6982 time_slice = 0;
6983 if (p->policy == SCHED_RR) {
6984 time_slice = DEF_TIMESLICE;
6985 } else if (p->policy != SCHED_FIFO) {
6986 struct sched_entity *se = &p->se;
6987 unsigned long flags;
6988 struct rq *rq;
6990 rq = task_rq_lock(p, &flags);
6991 if (rq->cfs.load.weight)
6992 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
6993 task_rq_unlock(rq, &flags);
6995 read_unlock(&tasklist_lock);
6996 jiffies_to_timespec(time_slice, &t);
6997 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
6998 return retval;
7000 out_unlock:
7001 read_unlock(&tasklist_lock);
7002 return retval;
7005 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
7007 void sched_show_task(struct task_struct *p)
7009 unsigned long free = 0;
7010 unsigned state;
7012 state = p->state ? __ffs(p->state) + 1 : 0;
7013 printk("%-13.13s %c (%03lx) [%p]", p->comm,
7014 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?',
7015 (unsigned long) p->state, p);
7016 #if BITS_PER_LONG == 32
7017 if (0 && (state == TASK_RUNNING))
7018 printk(KERN_CONT " running ");
7019 else
7020 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
7021 #else
7022 if (0 && (state == TASK_RUNNING))
7023 printk(KERN_CONT " running task ");
7024 else
7025 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
7026 #endif
7027 if (task_curr(p))
7028 printk("[curr] ");
7029 else if (p->se.on_rq)
7030 printk("[on rq #%d] ", task_cpu(p));
7031 #ifdef CONFIG_DEBUG_STACK_USAGE
7032 free = stack_not_used(p);
7033 #endif
7034 printk(KERN_CONT "%5lu %5d %6d\n", free,
7035 task_pid_nr(p), task_pid_nr(p->real_parent));
7037 show_stack(p, NULL);
7040 void show_state_filter(unsigned long state_filter)
7042 struct task_struct *g, *p;
7043 int do_unlock = 1;
7045 #if BITS_PER_LONG == 32
7046 printk(KERN_INFO
7047 " task PC stack pid father\n");
7048 #else
7049 printk(KERN_INFO
7050 " task PC stack pid father\n");
7051 #endif
7052 #ifdef CONFIG_PREEMPT_RT
7053 if (!read_trylock(&tasklist_lock)) {
7054 printk("hm, tasklist_lock write-locked.\n");
7055 printk("ignoring ...\n");
7056 do_unlock = 0;
7058 #else
7059 read_lock(&tasklist_lock);
7060 #endif
7062 do_each_thread(g, p) {
7064 * reset the NMI-timeout, listing all files on a slow
7065 * console might take alot of time:
7067 touch_nmi_watchdog();
7068 if (!state_filter || (p->state & state_filter))
7069 sched_show_task(p);
7070 } while_each_thread(g, p);
7072 touch_all_softlockup_watchdogs();
7074 #ifdef CONFIG_SCHED_DEBUG
7075 sysrq_sched_debug_show();
7076 #endif
7077 if (do_unlock)
7078 read_unlock(&tasklist_lock);
7080 * Only show locks if all tasks are dumped:
7082 if (state_filter == -1)
7083 debug_show_all_locks();
7086 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
7088 idle->sched_class = &idle_sched_class;
7092 * init_idle - set up an idle thread for a given CPU
7093 * @idle: task in question
7094 * @cpu: cpu the idle task belongs to
7096 * NOTE: this function does not set the idle thread's NEED_RESCHED
7097 * flag, to make booting more robust.
7099 void __cpuinit init_idle(struct task_struct *idle, int cpu)
7101 struct rq *rq = cpu_rq(cpu);
7102 unsigned long flags;
7104 spin_lock_irqsave(&rq->lock, flags);
7106 __sched_fork(idle);
7107 idle->se.exec_start = sched_clock();
7109 idle->prio = idle->normal_prio = MAX_PRIO;
7110 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
7111 __set_task_cpu(idle, cpu);
7113 rq->curr = rq->idle = idle;
7114 #if defined(CONFIG_SMP)
7115 idle->oncpu = 1;
7116 #endif
7117 spin_unlock_irqrestore(&rq->lock, flags);
7119 /* Set the preempt count _outside_ the spinlocks! */
7120 task_thread_info(idle)->preempt_count = 0;
7123 * The idle tasks have their own, simple scheduling class:
7125 idle->sched_class = &idle_sched_class;
7126 ftrace_graph_init_task(idle);
7130 * In a system that switches off the HZ timer nohz_cpu_mask
7131 * indicates which cpus entered this state. This is used
7132 * in the rcu update to wait only for active cpus. For system
7133 * which do not switch off the HZ timer nohz_cpu_mask should
7134 * always be CPU_BITS_NONE.
7136 cpumask_var_t nohz_cpu_mask;
7139 * Increase the granularity value when there are more CPUs,
7140 * because with more CPUs the 'effective latency' as visible
7141 * to users decreases. But the relationship is not linear,
7142 * so pick a second-best guess by going with the log2 of the
7143 * number of CPUs.
7145 * This idea comes from the SD scheduler of Con Kolivas:
7147 static inline void sched_init_granularity(void)
7149 unsigned int factor = 1 + ilog2(num_online_cpus());
7150 const unsigned long limit = 200000000;
7152 sysctl_sched_min_granularity *= factor;
7153 if (sysctl_sched_min_granularity > limit)
7154 sysctl_sched_min_granularity = limit;
7156 sysctl_sched_latency *= factor;
7157 if (sysctl_sched_latency > limit)
7158 sysctl_sched_latency = limit;
7160 sysctl_sched_wakeup_granularity *= factor;
7162 sysctl_sched_shares_ratelimit *= factor;
7165 #ifdef CONFIG_SMP
7167 * This is how migration works:
7169 * 1) we queue a struct migration_req structure in the source CPU's
7170 * runqueue and wake up that CPU's migration thread.
7171 * 2) we down() the locked semaphore => thread blocks.
7172 * 3) migration thread wakes up (implicitly it forces the migrated
7173 * thread off the CPU)
7174 * 4) it gets the migration request and checks whether the migrated
7175 * task is still in the wrong runqueue.
7176 * 5) if it's in the wrong runqueue then the migration thread removes
7177 * it and puts it into the right queue.
7178 * 6) migration thread up()s the semaphore.
7179 * 7) we wake up and the migration is done.
7183 * Change a given task's CPU affinity. Migrate the thread to a
7184 * proper CPU and schedule it away if the CPU it's executing on
7185 * is removed from the allowed bitmask.
7187 * NOTE: the caller must have a valid reference to the task, the
7188 * task must not exit() & deallocate itself prematurely. The
7189 * call is not atomic; no spinlocks may be held.
7191 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
7193 struct migration_req req;
7194 unsigned long flags;
7195 struct rq *rq;
7196 int ret = 0;
7198 rq = task_rq_lock(p, &flags);
7199 if (!cpumask_intersects(new_mask, cpu_online_mask)) {
7200 ret = -EINVAL;
7201 goto out;
7204 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
7205 !cpumask_equal(&p->cpus_allowed, new_mask))) {
7206 ret = -EINVAL;
7207 goto out;
7210 if (p->sched_class->set_cpus_allowed)
7211 p->sched_class->set_cpus_allowed(p, new_mask);
7212 else {
7213 cpumask_copy(&p->cpus_allowed, new_mask);
7214 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
7217 /* Can the task run on the task's current CPU? If so, we're done */
7218 if (cpumask_test_cpu(task_cpu(p), new_mask))
7219 goto out;
7221 if (migrate_task(p, cpumask_any_and(cpu_online_mask, new_mask), &req)) {
7222 /* Need help from migration thread: drop lock and wait. */
7223 task_rq_unlock(rq, &flags);
7224 wake_up_process(rq->migration_thread);
7225 wait_for_completion(&req.done);
7226 tlb_migrate_finish(p->mm);
7227 return 0;
7229 out:
7230 task_rq_unlock(rq, &flags);
7232 return ret;
7234 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
7237 * Move (not current) task off this cpu, onto dest cpu. We're doing
7238 * this because either it can't run here any more (set_cpus_allowed()
7239 * away from this CPU, or CPU going down), or because we're
7240 * attempting to rebalance this task on exec (sched_exec).
7242 * So we race with normal scheduler movements, but that's OK, as long
7243 * as the task is no longer on this CPU.
7245 * Returns non-zero if task was successfully migrated.
7247 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
7249 struct rq *rq_dest, *rq_src;
7250 unsigned long flags;
7251 int ret = 0, on_rq;
7253 if (unlikely(!cpu_active(dest_cpu)))
7254 return ret;
7257 * PREEMPT_RT: this relies on write_lock_irq(&tasklist_lock)
7258 * disabling interrupts - which on PREEMPT_RT does not do:
7260 local_irq_save(flags);
7262 rq_src = cpu_rq(src_cpu);
7263 rq_dest = cpu_rq(dest_cpu);
7265 double_rq_lock(rq_src, rq_dest);
7266 /* Already moved. */
7267 if (task_cpu(p) != src_cpu)
7268 goto done;
7269 /* Affinity changed (again). */
7270 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
7271 goto fail;
7273 on_rq = p->se.on_rq;
7274 if (on_rq)
7275 deactivate_task(rq_src, p, 0);
7277 set_task_cpu(p, dest_cpu);
7278 if (on_rq) {
7279 activate_task(rq_dest, p, 0);
7280 check_preempt_curr(rq_dest, p, 0);
7282 done:
7283 ret = 1;
7284 fail:
7285 double_rq_unlock(rq_src, rq_dest);
7286 local_irq_restore(flags);
7288 return ret;
7292 * migration_thread - this is a highprio system thread that performs
7293 * thread migration by bumping thread off CPU then 'pushing' onto
7294 * another runqueue.
7296 static int migration_thread(void *data)
7298 int cpu = (long)data;
7299 struct rq *rq;
7301 rq = cpu_rq(cpu);
7302 BUG_ON(rq->migration_thread != current);
7304 set_current_state(TASK_INTERRUPTIBLE);
7305 while (!kthread_should_stop()) {
7306 struct migration_req *req;
7307 struct list_head *head;
7309 spin_lock_irq(&rq->lock);
7311 if (cpu_is_offline(cpu)) {
7312 spin_unlock_irq(&rq->lock);
7313 goto wait_to_die;
7316 if (rq->active_balance) {
7317 active_load_balance(rq, cpu);
7318 rq->active_balance = 0;
7321 head = &rq->migration_queue;
7323 if (list_empty(head)) {
7324 spin_unlock_irq(&rq->lock);
7325 schedule();
7326 set_current_state(TASK_INTERRUPTIBLE);
7327 continue;
7329 req = list_entry(head->next, struct migration_req, list);
7330 list_del_init(head->next);
7332 spin_unlock(&rq->lock);
7333 __migrate_task(req->task, cpu, req->dest_cpu);
7334 local_irq_enable();
7336 complete(&req->done);
7338 __set_current_state(TASK_RUNNING);
7339 return 0;
7341 wait_to_die:
7342 /* Wait for kthread_stop */
7343 set_current_state(TASK_INTERRUPTIBLE);
7344 while (!kthread_should_stop()) {
7345 schedule();
7346 set_current_state(TASK_INTERRUPTIBLE);
7348 __set_current_state(TASK_RUNNING);
7349 return 0;
7352 #ifdef CONFIG_HOTPLUG_CPU
7354 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
7356 int ret;
7358 local_irq_disable();
7359 ret = __migrate_task(p, src_cpu, dest_cpu);
7360 local_irq_enable();
7361 return ret;
7365 * Figure out where task on dead CPU should go, use force if necessary.
7367 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
7369 int dest_cpu;
7370 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(dead_cpu));
7372 again:
7373 /* Look for allowed, online CPU in same node. */
7374 for_each_cpu_and(dest_cpu, nodemask, cpu_online_mask)
7375 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
7376 goto move;
7378 /* Any allowed, online CPU? */
7379 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_online_mask);
7380 if (dest_cpu < nr_cpu_ids)
7381 goto move;
7383 /* No more Mr. Nice Guy. */
7384 if (dest_cpu >= nr_cpu_ids) {
7385 cpuset_cpus_allowed_locked(p, &p->cpus_allowed);
7386 dest_cpu = cpumask_any_and(cpu_online_mask, &p->cpus_allowed);
7389 * Don't tell them about moving exiting tasks or
7390 * kernel threads (both mm NULL), since they never
7391 * leave kernel.
7393 if (p->mm && printk_ratelimit()) {
7394 printk(KERN_INFO "process %d (%s) no "
7395 "longer affine to cpu%d\n",
7396 task_pid_nr(p), p->comm, dead_cpu);
7400 move:
7401 /* It can have affinity changed while we were choosing. */
7402 if (unlikely(!__migrate_task_irq(p, dead_cpu, dest_cpu)))
7403 goto again;
7407 * While a dead CPU has no uninterruptible tasks queued at this point,
7408 * it might still have a nonzero ->nr_uninterruptible counter, because
7409 * for performance reasons the counter is not stricly tracking tasks to
7410 * their home CPUs. So we just add the counter to another CPU's counter,
7411 * to keep the global sum constant after CPU-down:
7413 static void migrate_nr_uninterruptible(struct rq *rq_src)
7415 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_online_mask));
7416 unsigned long flags;
7418 local_irq_save(flags);
7419 double_rq_lock(rq_src, rq_dest);
7420 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
7421 rq_src->nr_uninterruptible = 0;
7422 double_rq_unlock(rq_src, rq_dest);
7423 local_irq_restore(flags);
7426 /* Run through task list and migrate tasks from the dead cpu. */
7427 static void migrate_live_tasks(int src_cpu)
7429 struct task_struct *p, *t;
7431 read_lock(&tasklist_lock);
7433 do_each_thread(t, p) {
7434 if (p == current)
7435 continue;
7437 if (task_cpu(p) == src_cpu)
7438 move_task_off_dead_cpu(src_cpu, p);
7439 } while_each_thread(t, p);
7441 read_unlock(&tasklist_lock);
7445 * Schedules idle task to be the next runnable task on current CPU.
7446 * It does so by boosting its priority to highest possible.
7447 * Used by CPU offline code.
7449 void sched_idle_next(void)
7451 int this_cpu = smp_processor_id();
7452 struct rq *rq = cpu_rq(this_cpu);
7453 struct task_struct *p = rq->idle;
7454 unsigned long flags;
7456 /* cpu has to be offline */
7457 BUG_ON(cpu_online(this_cpu));
7460 * Strictly not necessary since rest of the CPUs are stopped by now
7461 * and interrupts disabled on the current cpu.
7463 spin_lock_irqsave(&rq->lock, flags);
7465 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7467 update_rq_clock(rq);
7468 activate_task(rq, p, 0);
7470 spin_unlock_irqrestore(&rq->lock, flags);
7474 * Ensures that the idle task is using init_mm right before its cpu goes
7475 * offline.
7477 void idle_task_exit(void)
7479 struct mm_struct *mm = current->active_mm;
7481 BUG_ON(cpu_online(smp_processor_id()));
7483 if (mm != &init_mm)
7484 switch_mm(mm, &init_mm, current);
7485 #ifdef CONFIG_PREEMPT_RT
7486 mmdrop_delayed(mm);
7487 #else
7488 mmdrop(mm);
7489 #endif
7492 /* called under rq->lock with disabled interrupts */
7493 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
7495 struct rq *rq = cpu_rq(dead_cpu);
7497 /* Must be exiting, otherwise would be on tasklist. */
7498 BUG_ON(!p->exit_state);
7500 /* Cannot have done final schedule yet: would have vanished. */
7501 BUG_ON(p->state == TASK_DEAD);
7503 get_task_struct(p);
7506 * Drop lock around migration; if someone else moves it,
7507 * that's OK. No task can be added to this CPU, so iteration is
7508 * fine.
7510 spin_unlock_irq(&rq->lock);
7511 move_task_off_dead_cpu(dead_cpu, p);
7512 spin_lock_irq(&rq->lock);
7514 put_task_struct(p);
7517 /* release_task() removes task from tasklist, so we won't find dead tasks. */
7518 static void migrate_dead_tasks(unsigned int dead_cpu)
7520 struct rq *rq = cpu_rq(dead_cpu);
7521 struct task_struct *next;
7523 for ( ; ; ) {
7524 if (!rq->nr_running)
7525 break;
7526 update_rq_clock(rq);
7527 next = pick_next_task(rq);
7528 if (!next)
7529 break;
7530 next->sched_class->put_prev_task(rq, next);
7531 migrate_dead(dead_cpu, next);
7537 * remove the tasks which were accounted by rq from calc_load_tasks.
7539 static void calc_global_load_remove(struct rq *rq)
7541 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
7543 #endif /* CONFIG_HOTPLUG_CPU */
7545 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
7547 static struct ctl_table sd_ctl_dir[] = {
7549 .procname = "sched_domain",
7550 .mode = 0555,
7552 {0, },
7555 static struct ctl_table sd_ctl_root[] = {
7557 .ctl_name = CTL_KERN,
7558 .procname = "kernel",
7559 .mode = 0555,
7560 .child = sd_ctl_dir,
7562 {0, },
7565 static struct ctl_table *sd_alloc_ctl_entry(int n)
7567 struct ctl_table *entry =
7568 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
7570 return entry;
7573 static void sd_free_ctl_entry(struct ctl_table **tablep)
7575 struct ctl_table *entry;
7578 * In the intermediate directories, both the child directory and
7579 * procname are dynamically allocated and could fail but the mode
7580 * will always be set. In the lowest directory the names are
7581 * static strings and all have proc handlers.
7583 for (entry = *tablep; entry->mode; entry++) {
7584 if (entry->child)
7585 sd_free_ctl_entry(&entry->child);
7586 if (entry->proc_handler == NULL)
7587 kfree(entry->procname);
7590 kfree(*tablep);
7591 *tablep = NULL;
7594 static void
7595 set_table_entry(struct ctl_table *entry,
7596 const char *procname, void *data, int maxlen,
7597 mode_t mode, proc_handler *proc_handler)
7599 entry->procname = procname;
7600 entry->data = data;
7601 entry->maxlen = maxlen;
7602 entry->mode = mode;
7603 entry->proc_handler = proc_handler;
7606 static struct ctl_table *
7607 sd_alloc_ctl_domain_table(struct sched_domain *sd)
7609 struct ctl_table *table = sd_alloc_ctl_entry(13);
7611 if (table == NULL)
7612 return NULL;
7614 set_table_entry(&table[0], "min_interval", &sd->min_interval,
7615 sizeof(long), 0644, proc_doulongvec_minmax);
7616 set_table_entry(&table[1], "max_interval", &sd->max_interval,
7617 sizeof(long), 0644, proc_doulongvec_minmax);
7618 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
7619 sizeof(int), 0644, proc_dointvec_minmax);
7620 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
7621 sizeof(int), 0644, proc_dointvec_minmax);
7622 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
7623 sizeof(int), 0644, proc_dointvec_minmax);
7624 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
7625 sizeof(int), 0644, proc_dointvec_minmax);
7626 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
7627 sizeof(int), 0644, proc_dointvec_minmax);
7628 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
7629 sizeof(int), 0644, proc_dointvec_minmax);
7630 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
7631 sizeof(int), 0644, proc_dointvec_minmax);
7632 set_table_entry(&table[9], "cache_nice_tries",
7633 &sd->cache_nice_tries,
7634 sizeof(int), 0644, proc_dointvec_minmax);
7635 set_table_entry(&table[10], "flags", &sd->flags,
7636 sizeof(int), 0644, proc_dointvec_minmax);
7637 set_table_entry(&table[11], "name", sd->name,
7638 CORENAME_MAX_SIZE, 0444, proc_dostring);
7639 /* &table[12] is terminator */
7641 return table;
7644 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
7646 struct ctl_table *entry, *table;
7647 struct sched_domain *sd;
7648 int domain_num = 0, i;
7649 char buf[32];
7651 for_each_domain(cpu, sd)
7652 domain_num++;
7653 entry = table = sd_alloc_ctl_entry(domain_num + 1);
7654 if (table == NULL)
7655 return NULL;
7657 i = 0;
7658 for_each_domain(cpu, sd) {
7659 snprintf(buf, 32, "domain%d", i);
7660 entry->procname = kstrdup(buf, GFP_KERNEL);
7661 entry->mode = 0555;
7662 entry->child = sd_alloc_ctl_domain_table(sd);
7663 entry++;
7664 i++;
7666 return table;
7669 static struct ctl_table_header *sd_sysctl_header;
7670 static void register_sched_domain_sysctl(void)
7672 int i, cpu_num = num_online_cpus();
7673 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
7674 char buf[32];
7676 WARN_ON(sd_ctl_dir[0].child);
7677 sd_ctl_dir[0].child = entry;
7679 if (entry == NULL)
7680 return;
7682 for_each_online_cpu(i) {
7683 snprintf(buf, 32, "cpu%d", i);
7684 entry->procname = kstrdup(buf, GFP_KERNEL);
7685 entry->mode = 0555;
7686 entry->child = sd_alloc_ctl_cpu_table(i);
7687 entry++;
7690 WARN_ON(sd_sysctl_header);
7691 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
7694 /* may be called multiple times per register */
7695 static void unregister_sched_domain_sysctl(void)
7697 if (sd_sysctl_header)
7698 unregister_sysctl_table(sd_sysctl_header);
7699 sd_sysctl_header = NULL;
7700 if (sd_ctl_dir[0].child)
7701 sd_free_ctl_entry(&sd_ctl_dir[0].child);
7703 #else
7704 static void register_sched_domain_sysctl(void)
7707 static void unregister_sched_domain_sysctl(void)
7710 #endif
7712 static void set_rq_online(struct rq *rq)
7714 if (!rq->online) {
7715 const struct sched_class *class;
7717 cpumask_set_cpu(rq->cpu, rq->rd->online);
7718 rq->online = 1;
7720 for_each_class(class) {
7721 if (class->rq_online)
7722 class->rq_online(rq);
7727 static void set_rq_offline(struct rq *rq)
7729 if (rq->online) {
7730 const struct sched_class *class;
7732 for_each_class(class) {
7733 if (class->rq_offline)
7734 class->rq_offline(rq);
7737 cpumask_clear_cpu(rq->cpu, rq->rd->online);
7738 rq->online = 0;
7743 * migration_call - callback that gets triggered when a CPU is added.
7744 * Here we can start up the necessary migration thread for the new CPU.
7746 static int __cpuinit
7747 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
7749 struct task_struct *p;
7750 int cpu = (long)hcpu;
7751 unsigned long flags;
7752 struct rq *rq;
7754 switch (action) {
7756 case CPU_UP_PREPARE:
7757 case CPU_UP_PREPARE_FROZEN:
7758 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
7759 if (IS_ERR(p))
7760 return NOTIFY_BAD;
7761 kthread_bind(p, cpu);
7762 /* Must be high prio: stop_machine expects to yield to it. */
7763 rq = task_rq_lock(p, &flags);
7764 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7765 task_rq_unlock(rq, &flags);
7766 cpu_rq(cpu)->migration_thread = p;
7767 break;
7769 case CPU_ONLINE:
7770 case CPU_ONLINE_FROZEN:
7771 /* Strictly unnecessary, as first user will wake it. */
7772 wake_up_process(cpu_rq(cpu)->migration_thread);
7774 /* Update our root-domain */
7775 rq = cpu_rq(cpu);
7776 spin_lock_irqsave(&rq->lock, flags);
7777 rq->calc_load_update = calc_load_update;
7778 rq->calc_load_active = 0;
7779 if (rq->rd) {
7780 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7782 set_rq_online(rq);
7784 spin_unlock_irqrestore(&rq->lock, flags);
7785 break;
7787 #ifdef CONFIG_HOTPLUG_CPU
7788 case CPU_UP_CANCELED:
7789 case CPU_UP_CANCELED_FROZEN:
7790 if (!cpu_rq(cpu)->migration_thread)
7791 break;
7792 /* Unbind it from offline cpu so it can run. Fall thru. */
7793 kthread_bind(cpu_rq(cpu)->migration_thread,
7794 cpumask_any(cpu_online_mask));
7795 kthread_stop(cpu_rq(cpu)->migration_thread);
7796 cpu_rq(cpu)->migration_thread = NULL;
7797 break;
7799 case CPU_DEAD:
7800 case CPU_DEAD_FROZEN:
7801 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
7802 migrate_live_tasks(cpu);
7803 rq = cpu_rq(cpu);
7804 kthread_stop(rq->migration_thread);
7805 rq->migration_thread = NULL;
7806 /* Idle task back to normal (off runqueue, low prio) */
7807 spin_lock_irq(&rq->lock);
7808 update_rq_clock(rq);
7809 deactivate_task(rq, rq->idle, 0);
7810 rq->idle->static_prio = MAX_PRIO;
7811 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
7812 rq->idle->sched_class = &idle_sched_class;
7813 migrate_dead_tasks(cpu);
7814 spin_unlock_irq(&rq->lock);
7815 cpuset_unlock();
7816 migrate_nr_uninterruptible(rq);
7817 BUG_ON(rq->nr_running != 0);
7818 calc_global_load_remove(rq);
7820 * No need to migrate the tasks: it was best-effort if
7821 * they didn't take sched_hotcpu_mutex. Just wake up
7822 * the requestors.
7824 spin_lock_irq(&rq->lock);
7825 while (!list_empty(&rq->migration_queue)) {
7826 struct migration_req *req;
7828 req = list_entry(rq->migration_queue.next,
7829 struct migration_req, list);
7830 list_del_init(&req->list);
7831 spin_unlock_irq(&rq->lock);
7832 complete(&req->done);
7833 spin_lock_irq(&rq->lock);
7835 spin_unlock_irq(&rq->lock);
7836 break;
7838 case CPU_DYING:
7839 case CPU_DYING_FROZEN:
7840 /* Update our root-domain */
7841 rq = cpu_rq(cpu);
7842 spin_lock_irqsave(&rq->lock, flags);
7843 if (rq->rd) {
7844 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7845 set_rq_offline(rq);
7847 spin_unlock_irqrestore(&rq->lock, flags);
7848 break;
7849 #endif
7851 return NOTIFY_OK;
7854 /* Register at highest priority so that task migration (migrate_all_tasks)
7855 * happens before everything else.
7857 static struct notifier_block __cpuinitdata migration_notifier = {
7858 .notifier_call = migration_call,
7859 .priority = 10
7862 static int __init migration_init(void)
7864 void *cpu = (void *)(long)smp_processor_id();
7865 int err;
7867 /* Start one for the boot CPU: */
7868 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
7869 BUG_ON(err == NOTIFY_BAD);
7870 migration_call(&migration_notifier, CPU_ONLINE, cpu);
7871 register_cpu_notifier(&migration_notifier);
7873 return err;
7875 early_initcall(migration_init);
7876 #endif
7878 #ifdef CONFIG_SMP
7880 #ifdef CONFIG_SCHED_DEBUG
7882 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
7883 struct cpumask *groupmask)
7885 struct sched_group *group = sd->groups;
7886 char str[256];
7888 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
7889 cpumask_clear(groupmask);
7891 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
7893 if (!(sd->flags & SD_LOAD_BALANCE)) {
7894 printk("does not load-balance\n");
7895 if (sd->parent)
7896 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
7897 " has parent");
7898 return -1;
7901 printk(KERN_CONT "span %s level %s\n", str, sd->name);
7903 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
7904 printk(KERN_ERR "ERROR: domain->span does not contain "
7905 "CPU%d\n", cpu);
7907 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
7908 printk(KERN_ERR "ERROR: domain->groups does not contain"
7909 " CPU%d\n", cpu);
7912 printk(KERN_DEBUG "%*s groups:", level + 1, "");
7913 do {
7914 if (!group) {
7915 printk("\n");
7916 printk(KERN_ERR "ERROR: group is NULL\n");
7917 break;
7920 if (!group->__cpu_power) {
7921 printk(KERN_CONT "\n");
7922 printk(KERN_ERR "ERROR: domain->cpu_power not "
7923 "set\n");
7924 break;
7927 if (!cpumask_weight(sched_group_cpus(group))) {
7928 printk(KERN_CONT "\n");
7929 printk(KERN_ERR "ERROR: empty group\n");
7930 break;
7933 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
7934 printk(KERN_CONT "\n");
7935 printk(KERN_ERR "ERROR: repeated CPUs\n");
7936 break;
7939 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
7941 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
7942 printk(KERN_CONT " %s", str);
7944 group = group->next;
7945 } while (group != sd->groups);
7946 printk(KERN_CONT "\n");
7948 if (!cpumask_equal(sched_domain_span(sd), groupmask))
7949 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
7951 if (sd->parent &&
7952 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
7953 printk(KERN_ERR "ERROR: parent span is not a superset "
7954 "of domain->span\n");
7955 return 0;
7958 static void sched_domain_debug(struct sched_domain *sd, int cpu)
7960 cpumask_var_t groupmask;
7961 int level = 0;
7963 if (!sd) {
7964 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
7965 return;
7968 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
7970 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
7971 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
7972 return;
7975 for (;;) {
7976 if (sched_domain_debug_one(sd, cpu, level, groupmask))
7977 break;
7978 level++;
7979 sd = sd->parent;
7980 if (!sd)
7981 break;
7983 free_cpumask_var(groupmask);
7985 #else /* !CONFIG_SCHED_DEBUG */
7986 # define sched_domain_debug(sd, cpu) do { } while (0)
7987 #endif /* CONFIG_SCHED_DEBUG */
7989 static int sd_degenerate(struct sched_domain *sd)
7991 if (cpumask_weight(sched_domain_span(sd)) == 1)
7992 return 1;
7994 /* Following flags need at least 2 groups */
7995 if (sd->flags & (SD_LOAD_BALANCE |
7996 SD_BALANCE_NEWIDLE |
7997 SD_BALANCE_FORK |
7998 SD_BALANCE_EXEC |
7999 SD_SHARE_CPUPOWER |
8000 SD_SHARE_PKG_RESOURCES)) {
8001 if (sd->groups != sd->groups->next)
8002 return 0;
8005 /* Following flags don't use groups */
8006 if (sd->flags & (SD_WAKE_IDLE |
8007 SD_WAKE_AFFINE |
8008 SD_WAKE_BALANCE))
8009 return 0;
8011 return 1;
8014 static int
8015 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
8017 unsigned long cflags = sd->flags, pflags = parent->flags;
8019 if (sd_degenerate(parent))
8020 return 1;
8022 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
8023 return 0;
8025 /* Does parent contain flags not in child? */
8026 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
8027 if (cflags & SD_WAKE_AFFINE)
8028 pflags &= ~SD_WAKE_BALANCE;
8029 /* Flags needing groups don't count if only 1 group in parent */
8030 if (parent->groups == parent->groups->next) {
8031 pflags &= ~(SD_LOAD_BALANCE |
8032 SD_BALANCE_NEWIDLE |
8033 SD_BALANCE_FORK |
8034 SD_BALANCE_EXEC |
8035 SD_SHARE_CPUPOWER |
8036 SD_SHARE_PKG_RESOURCES);
8037 if (nr_node_ids == 1)
8038 pflags &= ~SD_SERIALIZE;
8040 if (~cflags & pflags)
8041 return 0;
8043 return 1;
8046 static void free_rootdomain(struct root_domain *rd)
8048 cpupri_cleanup(&rd->cpupri);
8050 free_cpumask_var(rd->rto_mask);
8051 free_cpumask_var(rd->online);
8052 free_cpumask_var(rd->span);
8053 kfree(rd);
8056 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
8058 struct root_domain *old_rd = NULL;
8059 unsigned long flags;
8061 spin_lock_irqsave(&rq->lock, flags);
8063 if (rq->rd) {
8064 old_rd = rq->rd;
8066 if (cpumask_test_cpu(rq->cpu, old_rd->online))
8067 set_rq_offline(rq);
8069 cpumask_clear_cpu(rq->cpu, old_rd->span);
8072 * If we dont want to free the old_rt yet then
8073 * set old_rd to NULL to skip the freeing later
8074 * in this function:
8076 if (!atomic_dec_and_test(&old_rd->refcount))
8077 old_rd = NULL;
8080 atomic_inc(&rd->refcount);
8081 rq->rd = rd;
8083 cpumask_set_cpu(rq->cpu, rd->span);
8084 if (cpumask_test_cpu(rq->cpu, cpu_online_mask))
8085 set_rq_online(rq);
8087 spin_unlock_irqrestore(&rq->lock, flags);
8089 if (old_rd)
8090 free_rootdomain(old_rd);
8093 static int __init_refok init_rootdomain(struct root_domain *rd, bool bootmem)
8095 memset(rd, 0, sizeof(*rd));
8097 if (bootmem) {
8098 alloc_bootmem_cpumask_var(&def_root_domain.span);
8099 alloc_bootmem_cpumask_var(&def_root_domain.online);
8100 alloc_bootmem_cpumask_var(&def_root_domain.rto_mask);
8101 cpupri_init(&rd->cpupri, true);
8102 return 0;
8105 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
8106 goto out;
8107 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
8108 goto free_span;
8109 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
8110 goto free_online;
8112 if (cpupri_init(&rd->cpupri, false) != 0)
8113 goto free_rto_mask;
8114 return 0;
8116 free_rto_mask:
8117 free_cpumask_var(rd->rto_mask);
8118 free_online:
8119 free_cpumask_var(rd->online);
8120 free_span:
8121 free_cpumask_var(rd->span);
8122 out:
8123 return -ENOMEM;
8126 static void init_defrootdomain(void)
8128 init_rootdomain(&def_root_domain, true);
8130 atomic_set(&def_root_domain.refcount, 1);
8133 static struct root_domain *alloc_rootdomain(void)
8135 struct root_domain *rd;
8137 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
8138 if (!rd)
8139 return NULL;
8141 if (init_rootdomain(rd, false) != 0) {
8142 kfree(rd);
8143 return NULL;
8146 return rd;
8150 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
8151 * hold the hotplug lock.
8153 static void
8154 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
8156 struct rq *rq = cpu_rq(cpu);
8157 struct sched_domain *tmp;
8159 /* Remove the sched domains which do not contribute to scheduling. */
8160 for (tmp = sd; tmp; ) {
8161 struct sched_domain *parent = tmp->parent;
8162 if (!parent)
8163 break;
8165 if (sd_parent_degenerate(tmp, parent)) {
8166 tmp->parent = parent->parent;
8167 if (parent->parent)
8168 parent->parent->child = tmp;
8169 } else
8170 tmp = tmp->parent;
8173 if (sd && sd_degenerate(sd)) {
8174 sd = sd->parent;
8175 if (sd)
8176 sd->child = NULL;
8179 sched_domain_debug(sd, cpu);
8181 rq_attach_root(rq, rd);
8182 rcu_assign_pointer(rq->sd, sd);
8185 /* cpus with isolated domains */
8186 static cpumask_var_t cpu_isolated_map;
8188 /* Setup the mask of cpus configured for isolated domains */
8189 static int __init isolated_cpu_setup(char *str)
8191 cpulist_parse(str, cpu_isolated_map);
8192 return 1;
8195 __setup("isolcpus=", isolated_cpu_setup);
8198 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
8199 * to a function which identifies what group(along with sched group) a CPU
8200 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
8201 * (due to the fact that we keep track of groups covered with a struct cpumask).
8203 * init_sched_build_groups will build a circular linked list of the groups
8204 * covered by the given span, and will set each group's ->cpumask correctly,
8205 * and ->cpu_power to 0.
8207 static void
8208 init_sched_build_groups(const struct cpumask *span,
8209 const struct cpumask *cpu_map,
8210 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
8211 struct sched_group **sg,
8212 struct cpumask *tmpmask),
8213 struct cpumask *covered, struct cpumask *tmpmask)
8215 struct sched_group *first = NULL, *last = NULL;
8216 int i;
8218 cpumask_clear(covered);
8220 for_each_cpu(i, span) {
8221 struct sched_group *sg;
8222 int group = group_fn(i, cpu_map, &sg, tmpmask);
8223 int j;
8225 if (cpumask_test_cpu(i, covered))
8226 continue;
8228 cpumask_clear(sched_group_cpus(sg));
8229 sg->__cpu_power = 0;
8231 for_each_cpu(j, span) {
8232 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
8233 continue;
8235 cpumask_set_cpu(j, covered);
8236 cpumask_set_cpu(j, sched_group_cpus(sg));
8238 if (!first)
8239 first = sg;
8240 if (last)
8241 last->next = sg;
8242 last = sg;
8244 last->next = first;
8247 #define SD_NODES_PER_DOMAIN 16
8249 #ifdef CONFIG_NUMA
8252 * find_next_best_node - find the next node to include in a sched_domain
8253 * @node: node whose sched_domain we're building
8254 * @used_nodes: nodes already in the sched_domain
8256 * Find the next node to include in a given scheduling domain. Simply
8257 * finds the closest node not already in the @used_nodes map.
8259 * Should use nodemask_t.
8261 static int find_next_best_node(int node, nodemask_t *used_nodes)
8263 int i, n, val, min_val, best_node = 0;
8265 min_val = INT_MAX;
8267 for (i = 0; i < nr_node_ids; i++) {
8268 /* Start at @node */
8269 n = (node + i) % nr_node_ids;
8271 if (!nr_cpus_node(n))
8272 continue;
8274 /* Skip already used nodes */
8275 if (node_isset(n, *used_nodes))
8276 continue;
8278 /* Simple min distance search */
8279 val = node_distance(node, n);
8281 if (val < min_val) {
8282 min_val = val;
8283 best_node = n;
8287 node_set(best_node, *used_nodes);
8288 return best_node;
8292 * sched_domain_node_span - get a cpumask for a node's sched_domain
8293 * @node: node whose cpumask we're constructing
8294 * @span: resulting cpumask
8296 * Given a node, construct a good cpumask for its sched_domain to span. It
8297 * should be one that prevents unnecessary balancing, but also spreads tasks
8298 * out optimally.
8300 static void sched_domain_node_span(int node, struct cpumask *span)
8302 nodemask_t used_nodes;
8303 int i;
8305 cpumask_clear(span);
8306 nodes_clear(used_nodes);
8308 cpumask_or(span, span, cpumask_of_node(node));
8309 node_set(node, used_nodes);
8311 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
8312 int next_node = find_next_best_node(node, &used_nodes);
8314 cpumask_or(span, span, cpumask_of_node(next_node));
8317 #endif /* CONFIG_NUMA */
8319 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
8322 * The cpus mask in sched_group and sched_domain hangs off the end.
8323 * FIXME: use cpumask_var_t or dynamic percpu alloc to avoid wasting space
8324 * for nr_cpu_ids < CONFIG_NR_CPUS.
8326 struct static_sched_group {
8327 struct sched_group sg;
8328 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
8331 struct static_sched_domain {
8332 struct sched_domain sd;
8333 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
8337 * SMT sched-domains:
8339 #ifdef CONFIG_SCHED_SMT
8340 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
8341 static DEFINE_PER_CPU(struct static_sched_group, sched_group_cpus);
8343 static int
8344 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
8345 struct sched_group **sg, struct cpumask *unused)
8347 if (sg)
8348 *sg = &per_cpu(sched_group_cpus, cpu).sg;
8349 return cpu;
8351 #endif /* CONFIG_SCHED_SMT */
8354 * multi-core sched-domains:
8356 #ifdef CONFIG_SCHED_MC
8357 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
8358 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
8359 #endif /* CONFIG_SCHED_MC */
8361 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
8362 static int
8363 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8364 struct sched_group **sg, struct cpumask *mask)
8366 int group;
8368 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8369 group = cpumask_first(mask);
8370 if (sg)
8371 *sg = &per_cpu(sched_group_core, group).sg;
8372 return group;
8374 #elif defined(CONFIG_SCHED_MC)
8375 static int
8376 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8377 struct sched_group **sg, struct cpumask *unused)
8379 if (sg)
8380 *sg = &per_cpu(sched_group_core, cpu).sg;
8381 return cpu;
8383 #endif
8385 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
8386 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
8388 static int
8389 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
8390 struct sched_group **sg, struct cpumask *mask)
8392 int group;
8393 #ifdef CONFIG_SCHED_MC
8394 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
8395 group = cpumask_first(mask);
8396 #elif defined(CONFIG_SCHED_SMT)
8397 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8398 group = cpumask_first(mask);
8399 #else
8400 group = cpu;
8401 #endif
8402 if (sg)
8403 *sg = &per_cpu(sched_group_phys, group).sg;
8404 return group;
8407 #ifdef CONFIG_NUMA
8409 * The init_sched_build_groups can't handle what we want to do with node
8410 * groups, so roll our own. Now each node has its own list of groups which
8411 * gets dynamically allocated.
8413 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
8414 static struct sched_group ***sched_group_nodes_bycpu;
8416 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
8417 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
8419 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
8420 struct sched_group **sg,
8421 struct cpumask *nodemask)
8423 int group;
8425 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
8426 group = cpumask_first(nodemask);
8428 if (sg)
8429 *sg = &per_cpu(sched_group_allnodes, group).sg;
8430 return group;
8433 static void init_numa_sched_groups_power(struct sched_group *group_head)
8435 struct sched_group *sg = group_head;
8436 int j;
8438 if (!sg)
8439 return;
8440 do {
8441 for_each_cpu(j, sched_group_cpus(sg)) {
8442 struct sched_domain *sd;
8444 sd = &per_cpu(phys_domains, j).sd;
8445 if (j != cpumask_first(sched_group_cpus(sd->groups))) {
8447 * Only add "power" once for each
8448 * physical package.
8450 continue;
8453 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
8455 sg = sg->next;
8456 } while (sg != group_head);
8458 #endif /* CONFIG_NUMA */
8460 #ifdef CONFIG_NUMA
8461 /* Free memory allocated for various sched_group structures */
8462 static void free_sched_groups(const struct cpumask *cpu_map,
8463 struct cpumask *nodemask)
8465 int cpu, i;
8467 for_each_cpu(cpu, cpu_map) {
8468 struct sched_group **sched_group_nodes
8469 = sched_group_nodes_bycpu[cpu];
8471 if (!sched_group_nodes)
8472 continue;
8474 for (i = 0; i < nr_node_ids; i++) {
8475 struct sched_group *oldsg, *sg = sched_group_nodes[i];
8477 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8478 if (cpumask_empty(nodemask))
8479 continue;
8481 if (sg == NULL)
8482 continue;
8483 sg = sg->next;
8484 next_sg:
8485 oldsg = sg;
8486 sg = sg->next;
8487 kfree(oldsg);
8488 if (oldsg != sched_group_nodes[i])
8489 goto next_sg;
8491 kfree(sched_group_nodes);
8492 sched_group_nodes_bycpu[cpu] = NULL;
8495 #else /* !CONFIG_NUMA */
8496 static void free_sched_groups(const struct cpumask *cpu_map,
8497 struct cpumask *nodemask)
8500 #endif /* CONFIG_NUMA */
8503 * Initialize sched groups cpu_power.
8505 * cpu_power indicates the capacity of sched group, which is used while
8506 * distributing the load between different sched groups in a sched domain.
8507 * Typically cpu_power for all the groups in a sched domain will be same unless
8508 * there are asymmetries in the topology. If there are asymmetries, group
8509 * having more cpu_power will pickup more load compared to the group having
8510 * less cpu_power.
8512 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
8513 * the maximum number of tasks a group can handle in the presence of other idle
8514 * or lightly loaded groups in the same sched domain.
8516 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
8518 struct sched_domain *child;
8519 struct sched_group *group;
8521 WARN_ON(!sd || !sd->groups);
8523 if (cpu != cpumask_first(sched_group_cpus(sd->groups)))
8524 return;
8526 child = sd->child;
8528 sd->groups->__cpu_power = 0;
8531 * For perf policy, if the groups in child domain share resources
8532 * (for example cores sharing some portions of the cache hierarchy
8533 * or SMT), then set this domain groups cpu_power such that each group
8534 * can handle only one task, when there are other idle groups in the
8535 * same sched domain.
8537 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
8538 (child->flags &
8539 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
8540 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
8541 return;
8545 * add cpu_power of each child group to this groups cpu_power
8547 group = child->groups;
8548 do {
8549 sg_inc_cpu_power(sd->groups, group->__cpu_power);
8550 group = group->next;
8551 } while (group != child->groups);
8555 * Initializers for schedule domains
8556 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
8559 #ifdef CONFIG_SCHED_DEBUG
8560 # define SD_INIT_NAME(sd, type) sd->name = #type
8561 #else
8562 # define SD_INIT_NAME(sd, type) do { } while (0)
8563 #endif
8565 #define SD_INIT(sd, type) sd_init_##type(sd)
8567 #define SD_INIT_FUNC(type) \
8568 static noinline void sd_init_##type(struct sched_domain *sd) \
8570 memset(sd, 0, sizeof(*sd)); \
8571 *sd = SD_##type##_INIT; \
8572 sd->level = SD_LV_##type; \
8573 SD_INIT_NAME(sd, type); \
8576 SD_INIT_FUNC(CPU)
8577 #ifdef CONFIG_NUMA
8578 SD_INIT_FUNC(ALLNODES)
8579 SD_INIT_FUNC(NODE)
8580 #endif
8581 #ifdef CONFIG_SCHED_SMT
8582 SD_INIT_FUNC(SIBLING)
8583 #endif
8584 #ifdef CONFIG_SCHED_MC
8585 SD_INIT_FUNC(MC)
8586 #endif
8588 static int default_relax_domain_level = -1;
8590 static int __init setup_relax_domain_level(char *str)
8592 unsigned long val;
8594 val = simple_strtoul(str, NULL, 0);
8595 if (val < SD_LV_MAX)
8596 default_relax_domain_level = val;
8598 return 1;
8600 __setup("relax_domain_level=", setup_relax_domain_level);
8602 static void set_domain_attribute(struct sched_domain *sd,
8603 struct sched_domain_attr *attr)
8605 int request;
8607 if (!attr || attr->relax_domain_level < 0) {
8608 if (default_relax_domain_level < 0)
8609 return;
8610 else
8611 request = default_relax_domain_level;
8612 } else
8613 request = attr->relax_domain_level;
8614 if (request < sd->level) {
8615 /* turn off idle balance on this domain */
8616 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
8617 } else {
8618 /* turn on idle balance on this domain */
8619 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
8624 * Build sched domains for a given set of cpus and attach the sched domains
8625 * to the individual cpus
8627 static int __build_sched_domains(const struct cpumask *cpu_map,
8628 struct sched_domain_attr *attr)
8630 int i, err = -ENOMEM;
8631 struct root_domain *rd;
8632 cpumask_var_t nodemask, this_sibling_map, this_core_map, send_covered,
8633 tmpmask;
8634 #ifdef CONFIG_NUMA
8635 cpumask_var_t domainspan, covered, notcovered;
8636 struct sched_group **sched_group_nodes = NULL;
8637 int sd_allnodes = 0;
8639 if (!alloc_cpumask_var(&domainspan, GFP_KERNEL))
8640 goto out;
8641 if (!alloc_cpumask_var(&covered, GFP_KERNEL))
8642 goto free_domainspan;
8643 if (!alloc_cpumask_var(&notcovered, GFP_KERNEL))
8644 goto free_covered;
8645 #endif
8647 if (!alloc_cpumask_var(&nodemask, GFP_KERNEL))
8648 goto free_notcovered;
8649 if (!alloc_cpumask_var(&this_sibling_map, GFP_KERNEL))
8650 goto free_nodemask;
8651 if (!alloc_cpumask_var(&this_core_map, GFP_KERNEL))
8652 goto free_this_sibling_map;
8653 if (!alloc_cpumask_var(&send_covered, GFP_KERNEL))
8654 goto free_this_core_map;
8655 if (!alloc_cpumask_var(&tmpmask, GFP_KERNEL))
8656 goto free_send_covered;
8658 #ifdef CONFIG_NUMA
8660 * Allocate the per-node list of sched groups
8662 sched_group_nodes = kcalloc(nr_node_ids, sizeof(struct sched_group *),
8663 GFP_KERNEL);
8664 if (!sched_group_nodes) {
8665 printk(KERN_WARNING "Can not alloc sched group node list\n");
8666 goto free_tmpmask;
8668 #endif
8670 rd = alloc_rootdomain();
8671 if (!rd) {
8672 printk(KERN_WARNING "Cannot alloc root domain\n");
8673 goto free_sched_groups;
8676 #ifdef CONFIG_NUMA
8677 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = sched_group_nodes;
8678 #endif
8681 * Set up domains for cpus specified by the cpu_map.
8683 for_each_cpu(i, cpu_map) {
8684 struct sched_domain *sd = NULL, *p;
8686 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(i)), cpu_map);
8688 #ifdef CONFIG_NUMA
8689 if (cpumask_weight(cpu_map) >
8690 SD_NODES_PER_DOMAIN*cpumask_weight(nodemask)) {
8691 sd = &per_cpu(allnodes_domains, i).sd;
8692 SD_INIT(sd, ALLNODES);
8693 set_domain_attribute(sd, attr);
8694 cpumask_copy(sched_domain_span(sd), cpu_map);
8695 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
8696 p = sd;
8697 sd_allnodes = 1;
8698 } else
8699 p = NULL;
8701 sd = &per_cpu(node_domains, i).sd;
8702 SD_INIT(sd, NODE);
8703 set_domain_attribute(sd, attr);
8704 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
8705 sd->parent = p;
8706 if (p)
8707 p->child = sd;
8708 cpumask_and(sched_domain_span(sd),
8709 sched_domain_span(sd), cpu_map);
8710 #endif
8712 p = sd;
8713 sd = &per_cpu(phys_domains, i).sd;
8714 SD_INIT(sd, CPU);
8715 set_domain_attribute(sd, attr);
8716 cpumask_copy(sched_domain_span(sd), nodemask);
8717 sd->parent = p;
8718 if (p)
8719 p->child = sd;
8720 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
8722 #ifdef CONFIG_SCHED_MC
8723 p = sd;
8724 sd = &per_cpu(core_domains, i).sd;
8725 SD_INIT(sd, MC);
8726 set_domain_attribute(sd, attr);
8727 cpumask_and(sched_domain_span(sd), cpu_map,
8728 cpu_coregroup_mask(i));
8729 sd->parent = p;
8730 p->child = sd;
8731 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
8732 #endif
8734 #ifdef CONFIG_SCHED_SMT
8735 p = sd;
8736 sd = &per_cpu(cpu_domains, i).sd;
8737 SD_INIT(sd, SIBLING);
8738 set_domain_attribute(sd, attr);
8739 cpumask_and(sched_domain_span(sd),
8740 topology_thread_cpumask(i), cpu_map);
8741 sd->parent = p;
8742 p->child = sd;
8743 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
8744 #endif
8747 #ifdef CONFIG_SCHED_SMT
8748 /* Set up CPU (sibling) groups */
8749 for_each_cpu(i, cpu_map) {
8750 cpumask_and(this_sibling_map,
8751 topology_thread_cpumask(i), cpu_map);
8752 if (i != cpumask_first(this_sibling_map))
8753 continue;
8755 init_sched_build_groups(this_sibling_map, cpu_map,
8756 &cpu_to_cpu_group,
8757 send_covered, tmpmask);
8759 #endif
8761 #ifdef CONFIG_SCHED_MC
8762 /* Set up multi-core groups */
8763 for_each_cpu(i, cpu_map) {
8764 cpumask_and(this_core_map, cpu_coregroup_mask(i), cpu_map);
8765 if (i != cpumask_first(this_core_map))
8766 continue;
8768 init_sched_build_groups(this_core_map, cpu_map,
8769 &cpu_to_core_group,
8770 send_covered, tmpmask);
8772 #endif
8774 /* Set up physical groups */
8775 for (i = 0; i < nr_node_ids; i++) {
8776 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8777 if (cpumask_empty(nodemask))
8778 continue;
8780 init_sched_build_groups(nodemask, cpu_map,
8781 &cpu_to_phys_group,
8782 send_covered, tmpmask);
8785 #ifdef CONFIG_NUMA
8786 /* Set up node groups */
8787 if (sd_allnodes) {
8788 init_sched_build_groups(cpu_map, cpu_map,
8789 &cpu_to_allnodes_group,
8790 send_covered, tmpmask);
8793 for (i = 0; i < nr_node_ids; i++) {
8794 /* Set up node groups */
8795 struct sched_group *sg, *prev;
8796 int j;
8798 cpumask_clear(covered);
8799 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8800 if (cpumask_empty(nodemask)) {
8801 sched_group_nodes[i] = NULL;
8802 continue;
8805 sched_domain_node_span(i, domainspan);
8806 cpumask_and(domainspan, domainspan, cpu_map);
8808 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8809 GFP_KERNEL, i);
8810 if (!sg) {
8811 printk(KERN_WARNING "Can not alloc domain group for "
8812 "node %d\n", i);
8813 goto error;
8815 sched_group_nodes[i] = sg;
8816 for_each_cpu(j, nodemask) {
8817 struct sched_domain *sd;
8819 sd = &per_cpu(node_domains, j).sd;
8820 sd->groups = sg;
8822 sg->__cpu_power = 0;
8823 cpumask_copy(sched_group_cpus(sg), nodemask);
8824 sg->next = sg;
8825 cpumask_or(covered, covered, nodemask);
8826 prev = sg;
8828 for (j = 0; j < nr_node_ids; j++) {
8829 int n = (i + j) % nr_node_ids;
8831 cpumask_complement(notcovered, covered);
8832 cpumask_and(tmpmask, notcovered, cpu_map);
8833 cpumask_and(tmpmask, tmpmask, domainspan);
8834 if (cpumask_empty(tmpmask))
8835 break;
8837 cpumask_and(tmpmask, tmpmask, cpumask_of_node(n));
8838 if (cpumask_empty(tmpmask))
8839 continue;
8841 sg = kmalloc_node(sizeof(struct sched_group) +
8842 cpumask_size(),
8843 GFP_KERNEL, i);
8844 if (!sg) {
8845 printk(KERN_WARNING
8846 "Can not alloc domain group for node %d\n", j);
8847 goto error;
8849 sg->__cpu_power = 0;
8850 cpumask_copy(sched_group_cpus(sg), tmpmask);
8851 sg->next = prev->next;
8852 cpumask_or(covered, covered, tmpmask);
8853 prev->next = sg;
8854 prev = sg;
8857 #endif
8859 /* Calculate CPU power for physical packages and nodes */
8860 #ifdef CONFIG_SCHED_SMT
8861 for_each_cpu(i, cpu_map) {
8862 struct sched_domain *sd = &per_cpu(cpu_domains, i).sd;
8864 init_sched_groups_power(i, sd);
8866 #endif
8867 #ifdef CONFIG_SCHED_MC
8868 for_each_cpu(i, cpu_map) {
8869 struct sched_domain *sd = &per_cpu(core_domains, i).sd;
8871 init_sched_groups_power(i, sd);
8873 #endif
8875 for_each_cpu(i, cpu_map) {
8876 struct sched_domain *sd = &per_cpu(phys_domains, i).sd;
8878 init_sched_groups_power(i, sd);
8881 #ifdef CONFIG_NUMA
8882 for (i = 0; i < nr_node_ids; i++)
8883 init_numa_sched_groups_power(sched_group_nodes[i]);
8885 if (sd_allnodes) {
8886 struct sched_group *sg;
8888 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
8889 tmpmask);
8890 init_numa_sched_groups_power(sg);
8892 #endif
8894 /* Attach the domains */
8895 for_each_cpu(i, cpu_map) {
8896 struct sched_domain *sd;
8897 #ifdef CONFIG_SCHED_SMT
8898 sd = &per_cpu(cpu_domains, i).sd;
8899 #elif defined(CONFIG_SCHED_MC)
8900 sd = &per_cpu(core_domains, i).sd;
8901 #else
8902 sd = &per_cpu(phys_domains, i).sd;
8903 #endif
8904 cpu_attach_domain(sd, rd, i);
8907 err = 0;
8909 free_tmpmask:
8910 free_cpumask_var(tmpmask);
8911 free_send_covered:
8912 free_cpumask_var(send_covered);
8913 free_this_core_map:
8914 free_cpumask_var(this_core_map);
8915 free_this_sibling_map:
8916 free_cpumask_var(this_sibling_map);
8917 free_nodemask:
8918 free_cpumask_var(nodemask);
8919 free_notcovered:
8920 #ifdef CONFIG_NUMA
8921 free_cpumask_var(notcovered);
8922 free_covered:
8923 free_cpumask_var(covered);
8924 free_domainspan:
8925 free_cpumask_var(domainspan);
8926 out:
8927 #endif
8928 return err;
8930 free_sched_groups:
8931 #ifdef CONFIG_NUMA
8932 kfree(sched_group_nodes);
8933 #endif
8934 goto free_tmpmask;
8936 #ifdef CONFIG_NUMA
8937 error:
8938 free_sched_groups(cpu_map, tmpmask);
8939 free_rootdomain(rd);
8940 goto free_tmpmask;
8941 #endif
8944 static int build_sched_domains(const struct cpumask *cpu_map)
8946 return __build_sched_domains(cpu_map, NULL);
8949 static struct cpumask *doms_cur; /* current sched domains */
8950 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
8951 static struct sched_domain_attr *dattr_cur;
8952 /* attribues of custom domains in 'doms_cur' */
8955 * Special case: If a kmalloc of a doms_cur partition (array of
8956 * cpumask) fails, then fallback to a single sched domain,
8957 * as determined by the single cpumask fallback_doms.
8959 static cpumask_var_t fallback_doms;
8962 * arch_update_cpu_topology lets virtualized architectures update the
8963 * cpu core maps. It is supposed to return 1 if the topology changed
8964 * or 0 if it stayed the same.
8966 int __attribute__((weak)) arch_update_cpu_topology(void)
8968 return 0;
8972 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
8973 * For now this just excludes isolated cpus, but could be used to
8974 * exclude other special cases in the future.
8976 static int arch_init_sched_domains(const struct cpumask *cpu_map)
8978 int err;
8980 arch_update_cpu_topology();
8981 ndoms_cur = 1;
8982 doms_cur = kmalloc(cpumask_size(), GFP_KERNEL);
8983 if (!doms_cur)
8984 doms_cur = fallback_doms;
8985 cpumask_andnot(doms_cur, cpu_map, cpu_isolated_map);
8986 dattr_cur = NULL;
8987 err = build_sched_domains(doms_cur);
8988 register_sched_domain_sysctl();
8990 return err;
8993 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
8994 struct cpumask *tmpmask)
8996 free_sched_groups(cpu_map, tmpmask);
9000 * Detach sched domains from a group of cpus specified in cpu_map
9001 * These cpus will now be attached to the NULL domain
9003 static void detach_destroy_domains(const struct cpumask *cpu_map)
9005 /* Save because hotplug lock held. */
9006 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
9007 int i;
9009 for_each_cpu(i, cpu_map)
9010 cpu_attach_domain(NULL, &def_root_domain, i);
9011 synchronize_sched();
9012 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
9015 /* handle null as "default" */
9016 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
9017 struct sched_domain_attr *new, int idx_new)
9019 struct sched_domain_attr tmp;
9021 /* fast path */
9022 if (!new && !cur)
9023 return 1;
9025 tmp = SD_ATTR_INIT;
9026 return !memcmp(cur ? (cur + idx_cur) : &tmp,
9027 new ? (new + idx_new) : &tmp,
9028 sizeof(struct sched_domain_attr));
9032 * Partition sched domains as specified by the 'ndoms_new'
9033 * cpumasks in the array doms_new[] of cpumasks. This compares
9034 * doms_new[] to the current sched domain partitioning, doms_cur[].
9035 * It destroys each deleted domain and builds each new domain.
9037 * 'doms_new' is an array of cpumask's of length 'ndoms_new'.
9038 * The masks don't intersect (don't overlap.) We should setup one
9039 * sched domain for each mask. CPUs not in any of the cpumasks will
9040 * not be load balanced. If the same cpumask appears both in the
9041 * current 'doms_cur' domains and in the new 'doms_new', we can leave
9042 * it as it is.
9044 * The passed in 'doms_new' should be kmalloc'd. This routine takes
9045 * ownership of it and will kfree it when done with it. If the caller
9046 * failed the kmalloc call, then it can pass in doms_new == NULL &&
9047 * ndoms_new == 1, and partition_sched_domains() will fallback to
9048 * the single partition 'fallback_doms', it also forces the domains
9049 * to be rebuilt.
9051 * If doms_new == NULL it will be replaced with cpu_online_mask.
9052 * ndoms_new == 0 is a special case for destroying existing domains,
9053 * and it will not create the default domain.
9055 * Call with hotplug lock held
9057 /* FIXME: Change to struct cpumask *doms_new[] */
9058 void partition_sched_domains(int ndoms_new, struct cpumask *doms_new,
9059 struct sched_domain_attr *dattr_new)
9061 int i, j, n;
9062 int new_topology;
9064 mutex_lock(&sched_domains_mutex);
9066 /* always unregister in case we don't destroy any domains */
9067 unregister_sched_domain_sysctl();
9069 /* Let architecture update cpu core mappings. */
9070 new_topology = arch_update_cpu_topology();
9072 n = doms_new ? ndoms_new : 0;
9074 /* Destroy deleted domains */
9075 for (i = 0; i < ndoms_cur; i++) {
9076 for (j = 0; j < n && !new_topology; j++) {
9077 if (cpumask_equal(&doms_cur[i], &doms_new[j])
9078 && dattrs_equal(dattr_cur, i, dattr_new, j))
9079 goto match1;
9081 /* no match - a current sched domain not in new doms_new[] */
9082 detach_destroy_domains(doms_cur + i);
9083 match1:
9087 if (doms_new == NULL) {
9088 ndoms_cur = 0;
9089 doms_new = fallback_doms;
9090 cpumask_andnot(&doms_new[0], cpu_online_mask, cpu_isolated_map);
9091 WARN_ON_ONCE(dattr_new);
9094 /* Build new domains */
9095 for (i = 0; i < ndoms_new; i++) {
9096 for (j = 0; j < ndoms_cur && !new_topology; j++) {
9097 if (cpumask_equal(&doms_new[i], &doms_cur[j])
9098 && dattrs_equal(dattr_new, i, dattr_cur, j))
9099 goto match2;
9101 /* no match - add a new doms_new */
9102 __build_sched_domains(doms_new + i,
9103 dattr_new ? dattr_new + i : NULL);
9104 match2:
9108 /* Remember the new sched domains */
9109 if (doms_cur != fallback_doms)
9110 kfree(doms_cur);
9111 kfree(dattr_cur); /* kfree(NULL) is safe */
9112 doms_cur = doms_new;
9113 dattr_cur = dattr_new;
9114 ndoms_cur = ndoms_new;
9116 register_sched_domain_sysctl();
9118 mutex_unlock(&sched_domains_mutex);
9121 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
9122 static void arch_reinit_sched_domains(void)
9124 get_online_cpus();
9126 /* Destroy domains first to force the rebuild */
9127 partition_sched_domains(0, NULL, NULL);
9129 rebuild_sched_domains();
9130 put_online_cpus();
9133 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
9135 unsigned int level = 0;
9137 if (sscanf(buf, "%u", &level) != 1)
9138 return -EINVAL;
9141 * level is always be positive so don't check for
9142 * level < POWERSAVINGS_BALANCE_NONE which is 0
9143 * What happens on 0 or 1 byte write,
9144 * need to check for count as well?
9147 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
9148 return -EINVAL;
9150 if (smt)
9151 sched_smt_power_savings = level;
9152 else
9153 sched_mc_power_savings = level;
9155 arch_reinit_sched_domains();
9157 return count;
9160 #ifdef CONFIG_SCHED_MC
9161 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
9162 char *page)
9164 return sprintf(page, "%u\n", sched_mc_power_savings);
9166 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
9167 const char *buf, size_t count)
9169 return sched_power_savings_store(buf, count, 0);
9171 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
9172 sched_mc_power_savings_show,
9173 sched_mc_power_savings_store);
9174 #endif
9176 #ifdef CONFIG_SCHED_SMT
9177 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
9178 char *page)
9180 return sprintf(page, "%u\n", sched_smt_power_savings);
9182 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
9183 const char *buf, size_t count)
9185 return sched_power_savings_store(buf, count, 1);
9187 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
9188 sched_smt_power_savings_show,
9189 sched_smt_power_savings_store);
9190 #endif
9192 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
9194 int err = 0;
9196 #ifdef CONFIG_SCHED_SMT
9197 if (smt_capable())
9198 err = sysfs_create_file(&cls->kset.kobj,
9199 &attr_sched_smt_power_savings.attr);
9200 #endif
9201 #ifdef CONFIG_SCHED_MC
9202 if (!err && mc_capable())
9203 err = sysfs_create_file(&cls->kset.kobj,
9204 &attr_sched_mc_power_savings.attr);
9205 #endif
9206 return err;
9208 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
9210 #ifndef CONFIG_CPUSETS
9212 * Add online and remove offline CPUs from the scheduler domains.
9213 * When cpusets are enabled they take over this function.
9215 static int update_sched_domains(struct notifier_block *nfb,
9216 unsigned long action, void *hcpu)
9218 switch (action) {
9219 case CPU_ONLINE:
9220 case CPU_ONLINE_FROZEN:
9221 case CPU_DEAD:
9222 case CPU_DEAD_FROZEN:
9223 partition_sched_domains(1, NULL, NULL);
9224 return NOTIFY_OK;
9226 default:
9227 return NOTIFY_DONE;
9230 #endif
9232 static int update_runtime(struct notifier_block *nfb,
9233 unsigned long action, void *hcpu)
9235 int cpu = (int)(long)hcpu;
9237 switch (action) {
9238 case CPU_DOWN_PREPARE:
9239 case CPU_DOWN_PREPARE_FROZEN:
9240 disable_runtime(cpu_rq(cpu));
9241 return NOTIFY_OK;
9243 case CPU_DOWN_FAILED:
9244 case CPU_DOWN_FAILED_FROZEN:
9245 case CPU_ONLINE:
9246 case CPU_ONLINE_FROZEN:
9247 enable_runtime(cpu_rq(cpu));
9248 return NOTIFY_OK;
9250 default:
9251 return NOTIFY_DONE;
9255 void __init sched_init_smp(void)
9257 cpumask_var_t non_isolated_cpus;
9259 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
9261 #if defined(CONFIG_NUMA)
9262 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
9263 GFP_KERNEL);
9264 BUG_ON(sched_group_nodes_bycpu == NULL);
9265 #endif
9266 get_online_cpus();
9267 mutex_lock(&sched_domains_mutex);
9268 arch_init_sched_domains(cpu_online_mask);
9269 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
9270 if (cpumask_empty(non_isolated_cpus))
9271 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
9272 mutex_unlock(&sched_domains_mutex);
9273 put_online_cpus();
9275 #ifndef CONFIG_CPUSETS
9276 /* XXX: Theoretical race here - CPU may be hotplugged now */
9277 hotcpu_notifier(update_sched_domains, 0);
9278 #endif
9280 /* RT runtime code needs to handle some hotplug events */
9281 hotcpu_notifier(update_runtime, 0);
9283 init_hrtick();
9285 /* Move init over to a non-isolated CPU */
9286 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
9287 BUG();
9288 sched_init_granularity();
9289 free_cpumask_var(non_isolated_cpus);
9291 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
9292 init_sched_rt_class();
9294 #else
9295 void __init sched_init_smp(void)
9297 sched_init_granularity();
9299 #endif /* CONFIG_SMP */
9301 int in_sched_functions(unsigned long addr)
9303 return in_lock_functions(addr) ||
9304 (addr >= (unsigned long)__sched_text_start
9305 && addr < (unsigned long)__sched_text_end);
9308 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
9310 cfs_rq->tasks_timeline = RB_ROOT;
9311 INIT_LIST_HEAD(&cfs_rq->tasks);
9312 #ifdef CONFIG_FAIR_GROUP_SCHED
9313 cfs_rq->rq = rq;
9314 #endif
9315 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
9318 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
9320 struct rt_prio_array *array;
9321 int i;
9323 array = &rt_rq->active;
9324 for (i = 0; i < MAX_RT_PRIO; i++) {
9325 INIT_LIST_HEAD(array->queue + i);
9326 __clear_bit(i, array->bitmap);
9328 /* delimiter for bitsearch: */
9329 __set_bit(MAX_RT_PRIO, array->bitmap);
9331 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
9332 rt_rq->highest_prio.curr = MAX_RT_PRIO;
9333 #ifdef CONFIG_SMP
9334 rt_rq->highest_prio.next = MAX_RT_PRIO;
9335 #endif
9336 #endif
9337 #ifdef CONFIG_SMP
9338 rt_rq->rt_nr_migratory = 0;
9339 rt_rq->overloaded = 0;
9340 plist_head_init(&rq->rt.pushable_tasks, &rq->lock);
9341 #endif
9343 rt_rq->rt_time = 0;
9344 rt_rq->rt_throttled = 0;
9345 rt_rq->rt_runtime = 0;
9346 spin_lock_init(&rt_rq->rt_runtime_lock);
9348 #ifdef CONFIG_RT_GROUP_SCHED
9349 rt_rq->rt_nr_boosted = 0;
9350 rt_rq->rq = rq;
9351 #endif
9354 #ifdef CONFIG_FAIR_GROUP_SCHED
9355 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
9356 struct sched_entity *se, int cpu, int add,
9357 struct sched_entity *parent)
9359 struct rq *rq = cpu_rq(cpu);
9360 tg->cfs_rq[cpu] = cfs_rq;
9361 init_cfs_rq(cfs_rq, rq);
9362 cfs_rq->tg = tg;
9363 if (add)
9364 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
9366 tg->se[cpu] = se;
9367 /* se could be NULL for init_task_group */
9368 if (!se)
9369 return;
9371 if (!parent)
9372 se->cfs_rq = &rq->cfs;
9373 else
9374 se->cfs_rq = parent->my_q;
9376 se->my_q = cfs_rq;
9377 se->load.weight = tg->shares;
9378 se->load.inv_weight = 0;
9379 se->parent = parent;
9381 #endif
9383 #ifdef CONFIG_RT_GROUP_SCHED
9384 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
9385 struct sched_rt_entity *rt_se, int cpu, int add,
9386 struct sched_rt_entity *parent)
9388 struct rq *rq = cpu_rq(cpu);
9390 tg->rt_rq[cpu] = rt_rq;
9391 init_rt_rq(rt_rq, rq);
9392 rt_rq->tg = tg;
9393 rt_rq->rt_se = rt_se;
9394 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
9395 if (add)
9396 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
9398 tg->rt_se[cpu] = rt_se;
9399 if (!rt_se)
9400 return;
9402 if (!parent)
9403 rt_se->rt_rq = &rq->rt;
9404 else
9405 rt_se->rt_rq = parent->my_q;
9407 rt_se->my_q = rt_rq;
9408 rt_se->parent = parent;
9409 INIT_LIST_HEAD(&rt_se->run_list);
9411 #endif
9413 void __init sched_init(void)
9415 int i, j;
9416 unsigned long alloc_size = 0, ptr;
9418 #ifdef CONFIG_FAIR_GROUP_SCHED
9419 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9420 #endif
9421 #ifdef CONFIG_RT_GROUP_SCHED
9422 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9423 #endif
9424 #ifdef CONFIG_USER_SCHED
9425 alloc_size *= 2;
9426 #endif
9427 #ifdef CONFIG_CPUMASK_OFFSTACK
9428 alloc_size += num_possible_cpus() * cpumask_size();
9429 #endif
9431 * As sched_init() is called before page_alloc is setup,
9432 * we use alloc_bootmem().
9434 if (alloc_size) {
9435 ptr = (unsigned long)alloc_bootmem(alloc_size);
9437 #ifdef CONFIG_FAIR_GROUP_SCHED
9438 init_task_group.se = (struct sched_entity **)ptr;
9439 ptr += nr_cpu_ids * sizeof(void **);
9441 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
9442 ptr += nr_cpu_ids * sizeof(void **);
9444 #ifdef CONFIG_USER_SCHED
9445 root_task_group.se = (struct sched_entity **)ptr;
9446 ptr += nr_cpu_ids * sizeof(void **);
9448 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
9449 ptr += nr_cpu_ids * sizeof(void **);
9450 #endif /* CONFIG_USER_SCHED */
9451 #endif /* CONFIG_FAIR_GROUP_SCHED */
9452 #ifdef CONFIG_RT_GROUP_SCHED
9453 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
9454 ptr += nr_cpu_ids * sizeof(void **);
9456 init_task_group.rt_rq = (struct rt_rq **)ptr;
9457 ptr += nr_cpu_ids * sizeof(void **);
9459 #ifdef CONFIG_USER_SCHED
9460 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
9461 ptr += nr_cpu_ids * sizeof(void **);
9463 root_task_group.rt_rq = (struct rt_rq **)ptr;
9464 ptr += nr_cpu_ids * sizeof(void **);
9465 #endif /* CONFIG_USER_SCHED */
9466 #endif /* CONFIG_RT_GROUP_SCHED */
9467 #ifdef CONFIG_CPUMASK_OFFSTACK
9468 for_each_possible_cpu(i) {
9469 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
9470 ptr += cpumask_size();
9472 #endif /* CONFIG_CPUMASK_OFFSTACK */
9475 #ifdef CONFIG_SMP
9476 init_defrootdomain();
9477 #endif
9479 init_rt_bandwidth(&def_rt_bandwidth,
9480 global_rt_period(), global_rt_runtime());
9482 #ifdef CONFIG_RT_GROUP_SCHED
9483 init_rt_bandwidth(&init_task_group.rt_bandwidth,
9484 global_rt_period(), global_rt_runtime());
9485 #ifdef CONFIG_USER_SCHED
9486 init_rt_bandwidth(&root_task_group.rt_bandwidth,
9487 global_rt_period(), RUNTIME_INF);
9488 #endif /* CONFIG_USER_SCHED */
9489 #endif /* CONFIG_RT_GROUP_SCHED */
9491 #ifdef CONFIG_GROUP_SCHED
9492 list_add(&init_task_group.list, &task_groups);
9493 INIT_LIST_HEAD(&init_task_group.children);
9495 #ifdef CONFIG_USER_SCHED
9496 INIT_LIST_HEAD(&root_task_group.children);
9497 init_task_group.parent = &root_task_group;
9498 list_add(&init_task_group.siblings, &root_task_group.children);
9499 #endif /* CONFIG_USER_SCHED */
9500 #endif /* CONFIG_GROUP_SCHED */
9502 for_each_possible_cpu(i) {
9503 struct rq *rq;
9505 rq = cpu_rq(i);
9506 spin_lock_init(&rq->lock);
9507 rq->nr_running = 0;
9508 rq->calc_load_active = 0;
9509 rq->calc_load_update = jiffies + LOAD_FREQ;
9510 init_cfs_rq(&rq->cfs, rq);
9511 init_rt_rq(&rq->rt, rq);
9512 #ifdef CONFIG_FAIR_GROUP_SCHED
9513 init_task_group.shares = init_task_group_load;
9514 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9515 #ifdef CONFIG_CGROUP_SCHED
9517 * How much cpu bandwidth does init_task_group get?
9519 * In case of task-groups formed thr' the cgroup filesystem, it
9520 * gets 100% of the cpu resources in the system. This overall
9521 * system cpu resource is divided among the tasks of
9522 * init_task_group and its child task-groups in a fair manner,
9523 * based on each entity's (task or task-group's) weight
9524 * (se->load.weight).
9526 * In other words, if init_task_group has 10 tasks of weight
9527 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9528 * then A0's share of the cpu resource is:
9530 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9532 * We achieve this by letting init_task_group's tasks sit
9533 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
9535 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
9536 #elif defined CONFIG_USER_SCHED
9537 root_task_group.shares = NICE_0_LOAD;
9538 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
9540 * In case of task-groups formed thr' the user id of tasks,
9541 * init_task_group represents tasks belonging to root user.
9542 * Hence it forms a sibling of all subsequent groups formed.
9543 * In this case, init_task_group gets only a fraction of overall
9544 * system cpu resource, based on the weight assigned to root
9545 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
9546 * by letting tasks of init_task_group sit in a separate cfs_rq
9547 * (init_cfs_rq) and having one entity represent this group of
9548 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
9550 init_tg_cfs_entry(&init_task_group,
9551 &per_cpu(init_cfs_rq, i),
9552 &per_cpu(init_sched_entity, i), i, 1,
9553 root_task_group.se[i]);
9555 #endif
9556 #endif /* CONFIG_FAIR_GROUP_SCHED */
9558 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
9559 #ifdef CONFIG_RT_GROUP_SCHED
9560 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
9561 #ifdef CONFIG_CGROUP_SCHED
9562 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
9563 #elif defined CONFIG_USER_SCHED
9564 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
9565 init_tg_rt_entry(&init_task_group,
9566 &per_cpu(init_rt_rq, i),
9567 &per_cpu(init_sched_rt_entity, i), i, 1,
9568 root_task_group.rt_se[i]);
9569 #endif
9570 #endif
9572 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
9573 rq->cpu_load[j] = 0;
9574 #ifdef CONFIG_SMP
9575 rq->sd = NULL;
9576 rq->rd = NULL;
9577 rq->active_balance = 0;
9578 rq->next_balance = jiffies;
9579 rq->push_cpu = 0;
9580 rq->cpu = i;
9581 rq->online = 0;
9582 rq->migration_thread = NULL;
9583 INIT_LIST_HEAD(&rq->migration_queue);
9584 rq_attach_root(rq, &def_root_domain);
9585 #endif
9586 init_rq_hrtick(rq);
9587 atomic_set(&rq->nr_iowait, 0);
9590 set_load_weight(&init_task);
9592 #ifdef CONFIG_PREEMPT_NOTIFIERS
9593 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
9594 #endif
9596 #ifdef CONFIG_SMP
9597 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9598 #endif
9600 #ifdef CONFIG_RT_MUTEXES
9601 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
9602 #endif
9605 * The boot idle thread does lazy MMU switching as well:
9607 atomic_inc(&init_mm.mm_count);
9608 enter_lazy_tlb(&init_mm, current);
9610 #ifdef CONFIG_PREEMPT_RT
9611 printk("Real-Time Preemption Support (C) 2004-2007 Ingo Molnar\n");
9612 #endif
9614 * Make us the idle thread. Technically, schedule() should not be
9615 * called from this thread, however somewhere below it might be,
9616 * but because we are the idle thread, we just pick up running again
9617 * when this runqueue becomes "idle".
9619 init_idle(current, smp_processor_id());
9621 calc_load_update = jiffies + LOAD_FREQ;
9624 * During early bootup we pretend to be a normal task:
9626 current->sched_class = &fair_sched_class;
9628 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
9629 alloc_bootmem_cpumask_var(&nohz_cpu_mask);
9630 #ifdef CONFIG_SMP
9631 #ifdef CONFIG_NO_HZ
9632 alloc_bootmem_cpumask_var(&nohz.cpu_mask);
9633 #endif
9634 alloc_bootmem_cpumask_var(&cpu_isolated_map);
9635 #endif /* SMP */
9637 scheduler_running = 1;
9640 #ifdef CONFIG_MAGIC_SYSRQ
9641 static void normalize_task(struct rq *rq, struct task_struct *p)
9643 int on_rq;
9645 update_rq_clock(rq);
9646 on_rq = p->se.on_rq;
9647 if (on_rq)
9648 deactivate_task(rq, p, 0);
9649 __setscheduler(rq, p, SCHED_NORMAL, 0);
9650 if (on_rq) {
9651 activate_task(rq, p, 0);
9652 resched_task(rq->curr);
9656 void normalize_rt_tasks(void)
9658 struct task_struct *g, *p;
9659 unsigned long flags;
9660 struct rq *rq;
9662 read_lock_irqsave(&tasklist_lock, flags);
9663 do_each_thread(g, p) {
9665 * Only normalize user tasks:
9667 if (!p->mm)
9668 continue;
9670 p->se.exec_start = 0;
9671 #ifdef CONFIG_SCHEDSTATS
9672 p->se.wait_start = 0;
9673 p->se.sleep_start = 0;
9674 p->se.block_start = 0;
9675 #endif
9677 if (!rt_task(p)) {
9679 * Renice negative nice level userspace
9680 * tasks back to 0:
9682 if (TASK_NICE(p) < 0 && p->mm)
9683 set_user_nice(p, 0);
9684 continue;
9687 spin_lock(&p->pi_lock);
9688 rq = __task_rq_lock(p);
9690 normalize_task(rq, p);
9692 __task_rq_unlock(rq);
9693 spin_unlock(&p->pi_lock);
9694 } while_each_thread(g, p);
9696 read_unlock_irqrestore(&tasklist_lock, flags);
9699 #endif /* CONFIG_MAGIC_SYSRQ */
9701 #ifdef CONFIG_IA64
9703 * These functions are only useful for the IA64 MCA handling.
9705 * They can only be called when the whole system has been
9706 * stopped - every CPU needs to be quiescent, and no scheduling
9707 * activity can take place. Using them for anything else would
9708 * be a serious bug, and as a result, they aren't even visible
9709 * under any other configuration.
9713 * curr_task - return the current task for a given cpu.
9714 * @cpu: the processor in question.
9716 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9718 struct task_struct *curr_task(int cpu)
9720 return cpu_curr(cpu);
9724 * set_curr_task - set the current task for a given cpu.
9725 * @cpu: the processor in question.
9726 * @p: the task pointer to set.
9728 * Description: This function must only be used when non-maskable interrupts
9729 * are serviced on a separate stack. It allows the architecture to switch the
9730 * notion of the current task on a cpu in a non-blocking manner. This function
9731 * must be called with all CPU's synchronized, and interrupts disabled, the
9732 * and caller must save the original value of the current task (see
9733 * curr_task() above) and restore that value before reenabling interrupts and
9734 * re-starting the system.
9736 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9738 void set_curr_task(int cpu, struct task_struct *p)
9740 cpu_curr(cpu) = p;
9743 #endif
9745 #ifdef CONFIG_FAIR_GROUP_SCHED
9746 static void free_fair_sched_group(struct task_group *tg)
9748 int i;
9750 for_each_possible_cpu(i) {
9751 if (tg->cfs_rq)
9752 kfree(tg->cfs_rq[i]);
9753 if (tg->se)
9754 kfree(tg->se[i]);
9757 kfree(tg->cfs_rq);
9758 kfree(tg->se);
9761 static
9762 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9764 struct cfs_rq *cfs_rq;
9765 struct sched_entity *se;
9766 struct rq *rq;
9767 int i;
9769 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
9770 if (!tg->cfs_rq)
9771 goto err;
9772 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
9773 if (!tg->se)
9774 goto err;
9776 tg->shares = NICE_0_LOAD;
9778 for_each_possible_cpu(i) {
9779 rq = cpu_rq(i);
9781 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
9782 GFP_KERNEL, cpu_to_node(i));
9783 if (!cfs_rq)
9784 goto err;
9786 se = kzalloc_node(sizeof(struct sched_entity),
9787 GFP_KERNEL, cpu_to_node(i));
9788 if (!se)
9789 goto err;
9791 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
9794 return 1;
9796 err:
9797 return 0;
9800 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9802 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
9803 &cpu_rq(cpu)->leaf_cfs_rq_list);
9806 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9808 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
9810 #else /* !CONFG_FAIR_GROUP_SCHED */
9811 static inline void free_fair_sched_group(struct task_group *tg)
9815 static inline
9816 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9818 return 1;
9821 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9825 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9828 #endif /* CONFIG_FAIR_GROUP_SCHED */
9830 #ifdef CONFIG_RT_GROUP_SCHED
9831 static void free_rt_sched_group(struct task_group *tg)
9833 int i;
9835 destroy_rt_bandwidth(&tg->rt_bandwidth);
9837 for_each_possible_cpu(i) {
9838 if (tg->rt_rq)
9839 kfree(tg->rt_rq[i]);
9840 if (tg->rt_se)
9841 kfree(tg->rt_se[i]);
9844 kfree(tg->rt_rq);
9845 kfree(tg->rt_se);
9848 static
9849 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9851 struct rt_rq *rt_rq;
9852 struct sched_rt_entity *rt_se;
9853 struct rq *rq;
9854 int i;
9856 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
9857 if (!tg->rt_rq)
9858 goto err;
9859 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
9860 if (!tg->rt_se)
9861 goto err;
9863 init_rt_bandwidth(&tg->rt_bandwidth,
9864 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
9866 for_each_possible_cpu(i) {
9867 rq = cpu_rq(i);
9869 rt_rq = kzalloc_node(sizeof(struct rt_rq),
9870 GFP_KERNEL, cpu_to_node(i));
9871 if (!rt_rq)
9872 goto err;
9874 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
9875 GFP_KERNEL, cpu_to_node(i));
9876 if (!rt_se)
9877 goto err;
9879 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
9882 return 1;
9884 err:
9885 return 0;
9888 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9890 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
9891 &cpu_rq(cpu)->leaf_rt_rq_list);
9894 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9896 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
9898 #else /* !CONFIG_RT_GROUP_SCHED */
9899 static inline void free_rt_sched_group(struct task_group *tg)
9903 static inline
9904 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9906 return 1;
9909 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9913 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9916 #endif /* CONFIG_RT_GROUP_SCHED */
9918 #ifdef CONFIG_GROUP_SCHED
9919 static void free_sched_group(struct task_group *tg)
9921 free_fair_sched_group(tg);
9922 free_rt_sched_group(tg);
9923 kfree(tg);
9926 /* allocate runqueue etc for a new task group */
9927 struct task_group *sched_create_group(struct task_group *parent)
9929 struct task_group *tg;
9930 unsigned long flags;
9931 int i;
9933 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
9934 if (!tg)
9935 return ERR_PTR(-ENOMEM);
9937 if (!alloc_fair_sched_group(tg, parent))
9938 goto err;
9940 if (!alloc_rt_sched_group(tg, parent))
9941 goto err;
9943 spin_lock_irqsave(&task_group_lock, flags);
9944 for_each_possible_cpu(i) {
9945 register_fair_sched_group(tg, i);
9946 register_rt_sched_group(tg, i);
9948 list_add_rcu(&tg->list, &task_groups);
9950 WARN_ON(!parent); /* root should already exist */
9952 tg->parent = parent;
9953 INIT_LIST_HEAD(&tg->children);
9954 list_add_rcu(&tg->siblings, &parent->children);
9955 spin_unlock_irqrestore(&task_group_lock, flags);
9957 return tg;
9959 err:
9960 free_sched_group(tg);
9961 return ERR_PTR(-ENOMEM);
9964 /* rcu callback to free various structures associated with a task group */
9965 static void free_sched_group_rcu(struct rcu_head *rhp)
9967 /* now it should be safe to free those cfs_rqs */
9968 free_sched_group(container_of(rhp, struct task_group, rcu));
9971 /* Destroy runqueue etc associated with a task group */
9972 void sched_destroy_group(struct task_group *tg)
9974 unsigned long flags;
9975 int i;
9977 spin_lock_irqsave(&task_group_lock, flags);
9978 for_each_possible_cpu(i) {
9979 unregister_fair_sched_group(tg, i);
9980 unregister_rt_sched_group(tg, i);
9982 list_del_rcu(&tg->list);
9983 list_del_rcu(&tg->siblings);
9984 spin_unlock_irqrestore(&task_group_lock, flags);
9986 /* wait for possible concurrent references to cfs_rqs complete */
9987 call_rcu(&tg->rcu, free_sched_group_rcu);
9990 /* change task's runqueue when it moves between groups.
9991 * The caller of this function should have put the task in its new group
9992 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
9993 * reflect its new group.
9995 void sched_move_task(struct task_struct *tsk)
9997 int on_rq, running;
9998 unsigned long flags;
9999 struct rq *rq;
10001 rq = task_rq_lock(tsk, &flags);
10003 update_rq_clock(rq);
10005 running = task_current(rq, tsk);
10006 on_rq = tsk->se.on_rq;
10008 if (on_rq)
10009 dequeue_task(rq, tsk, 0);
10010 if (unlikely(running))
10011 tsk->sched_class->put_prev_task(rq, tsk);
10013 set_task_rq(tsk, task_cpu(tsk));
10015 #ifdef CONFIG_FAIR_GROUP_SCHED
10016 if (tsk->sched_class->moved_group)
10017 tsk->sched_class->moved_group(tsk);
10018 #endif
10020 if (unlikely(running))
10021 tsk->sched_class->set_curr_task(rq);
10022 if (on_rq)
10023 enqueue_task(rq, tsk, 0);
10025 task_rq_unlock(rq, &flags);
10027 #endif /* CONFIG_GROUP_SCHED */
10029 #ifdef CONFIG_FAIR_GROUP_SCHED
10030 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
10032 struct cfs_rq *cfs_rq = se->cfs_rq;
10033 int on_rq;
10035 on_rq = se->on_rq;
10036 if (on_rq)
10037 dequeue_entity(cfs_rq, se, 0);
10039 se->load.weight = shares;
10040 se->load.inv_weight = 0;
10042 if (on_rq)
10043 enqueue_entity(cfs_rq, se, 0);
10046 static void set_se_shares(struct sched_entity *se, unsigned long shares)
10048 struct cfs_rq *cfs_rq = se->cfs_rq;
10049 struct rq *rq = cfs_rq->rq;
10050 unsigned long flags;
10052 spin_lock_irqsave(&rq->lock, flags);
10053 __set_se_shares(se, shares);
10054 spin_unlock_irqrestore(&rq->lock, flags);
10057 static DEFINE_MUTEX(shares_mutex);
10059 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
10061 int i;
10062 unsigned long flags;
10065 * We can't change the weight of the root cgroup.
10067 if (!tg->se[0])
10068 return -EINVAL;
10070 if (shares < MIN_SHARES)
10071 shares = MIN_SHARES;
10072 else if (shares > MAX_SHARES)
10073 shares = MAX_SHARES;
10075 mutex_lock(&shares_mutex);
10076 if (tg->shares == shares)
10077 goto done;
10079 spin_lock_irqsave(&task_group_lock, flags);
10080 for_each_possible_cpu(i)
10081 unregister_fair_sched_group(tg, i);
10082 list_del_rcu(&tg->siblings);
10083 spin_unlock_irqrestore(&task_group_lock, flags);
10085 /* wait for any ongoing reference to this group to finish */
10086 synchronize_sched();
10089 * Now we are free to modify the group's share on each cpu
10090 * w/o tripping rebalance_share or load_balance_fair.
10092 tg->shares = shares;
10093 for_each_possible_cpu(i) {
10095 * force a rebalance
10097 cfs_rq_set_shares(tg->cfs_rq[i], 0);
10098 set_se_shares(tg->se[i], shares);
10102 * Enable load balance activity on this group, by inserting it back on
10103 * each cpu's rq->leaf_cfs_rq_list.
10105 spin_lock_irqsave(&task_group_lock, flags);
10106 for_each_possible_cpu(i)
10107 register_fair_sched_group(tg, i);
10108 list_add_rcu(&tg->siblings, &tg->parent->children);
10109 spin_unlock_irqrestore(&task_group_lock, flags);
10110 done:
10111 mutex_unlock(&shares_mutex);
10112 return 0;
10115 unsigned long sched_group_shares(struct task_group *tg)
10117 return tg->shares;
10119 #endif
10121 #ifdef CONFIG_RT_GROUP_SCHED
10123 * Ensure that the real time constraints are schedulable.
10125 static DEFINE_MUTEX(rt_constraints_mutex);
10127 static unsigned long to_ratio(u64 period, u64 runtime)
10129 if (runtime == RUNTIME_INF)
10130 return 1ULL << 20;
10132 return div64_u64(runtime << 20, period);
10135 /* Must be called with tasklist_lock held */
10136 static inline int tg_has_rt_tasks(struct task_group *tg)
10138 struct task_struct *g, *p;
10140 do_each_thread(g, p) {
10141 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
10142 return 1;
10143 } while_each_thread(g, p);
10145 return 0;
10148 struct rt_schedulable_data {
10149 struct task_group *tg;
10150 u64 rt_period;
10151 u64 rt_runtime;
10154 static int tg_schedulable(struct task_group *tg, void *data)
10156 struct rt_schedulable_data *d = data;
10157 struct task_group *child;
10158 unsigned long total, sum = 0;
10159 u64 period, runtime;
10161 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10162 runtime = tg->rt_bandwidth.rt_runtime;
10164 if (tg == d->tg) {
10165 period = d->rt_period;
10166 runtime = d->rt_runtime;
10169 #ifdef CONFIG_USER_SCHED
10170 if (tg == &root_task_group) {
10171 period = global_rt_period();
10172 runtime = global_rt_runtime();
10174 #endif
10177 * Cannot have more runtime than the period.
10179 if (runtime > period && runtime != RUNTIME_INF)
10180 return -EINVAL;
10183 * Ensure we don't starve existing RT tasks.
10185 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
10186 return -EBUSY;
10188 total = to_ratio(period, runtime);
10191 * Nobody can have more than the global setting allows.
10193 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
10194 return -EINVAL;
10197 * The sum of our children's runtime should not exceed our own.
10199 list_for_each_entry_rcu(child, &tg->children, siblings) {
10200 period = ktime_to_ns(child->rt_bandwidth.rt_period);
10201 runtime = child->rt_bandwidth.rt_runtime;
10203 if (child == d->tg) {
10204 period = d->rt_period;
10205 runtime = d->rt_runtime;
10208 sum += to_ratio(period, runtime);
10211 if (sum > total)
10212 return -EINVAL;
10214 return 0;
10217 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
10219 struct rt_schedulable_data data = {
10220 .tg = tg,
10221 .rt_period = period,
10222 .rt_runtime = runtime,
10225 return walk_tg_tree(tg_schedulable, tg_nop, &data);
10228 static int tg_set_bandwidth(struct task_group *tg,
10229 u64 rt_period, u64 rt_runtime)
10231 int i, err = 0;
10233 mutex_lock(&rt_constraints_mutex);
10234 read_lock(&tasklist_lock);
10235 err = __rt_schedulable(tg, rt_period, rt_runtime);
10236 if (err)
10237 goto unlock;
10239 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10240 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
10241 tg->rt_bandwidth.rt_runtime = rt_runtime;
10243 for_each_possible_cpu(i) {
10244 struct rt_rq *rt_rq = tg->rt_rq[i];
10246 spin_lock(&rt_rq->rt_runtime_lock);
10247 rt_rq->rt_runtime = rt_runtime;
10248 spin_unlock(&rt_rq->rt_runtime_lock);
10250 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10251 unlock:
10252 read_unlock(&tasklist_lock);
10253 mutex_unlock(&rt_constraints_mutex);
10255 return err;
10258 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
10260 u64 rt_runtime, rt_period;
10262 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10263 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
10264 if (rt_runtime_us < 0)
10265 rt_runtime = RUNTIME_INF;
10267 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10270 long sched_group_rt_runtime(struct task_group *tg)
10272 u64 rt_runtime_us;
10274 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
10275 return -1;
10277 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
10278 do_div(rt_runtime_us, NSEC_PER_USEC);
10279 return rt_runtime_us;
10282 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
10284 u64 rt_runtime, rt_period;
10286 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
10287 rt_runtime = tg->rt_bandwidth.rt_runtime;
10289 if (rt_period == 0)
10290 return -EINVAL;
10292 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10295 long sched_group_rt_period(struct task_group *tg)
10297 u64 rt_period_us;
10299 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
10300 do_div(rt_period_us, NSEC_PER_USEC);
10301 return rt_period_us;
10304 static int sched_rt_global_constraints(void)
10306 u64 runtime, period;
10307 int ret = 0;
10309 if (sysctl_sched_rt_period <= 0)
10310 return -EINVAL;
10312 runtime = global_rt_runtime();
10313 period = global_rt_period();
10316 * Sanity check on the sysctl variables.
10318 if (runtime > period && runtime != RUNTIME_INF)
10319 return -EINVAL;
10321 mutex_lock(&rt_constraints_mutex);
10322 read_lock(&tasklist_lock);
10323 ret = __rt_schedulable(NULL, 0, 0);
10324 read_unlock(&tasklist_lock);
10325 mutex_unlock(&rt_constraints_mutex);
10327 return ret;
10330 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
10332 /* Don't accept realtime tasks when there is no way for them to run */
10333 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
10334 return 0;
10336 return 1;
10339 #else /* !CONFIG_RT_GROUP_SCHED */
10340 static int sched_rt_global_constraints(void)
10342 unsigned long flags;
10343 int i;
10345 if (sysctl_sched_rt_period <= 0)
10346 return -EINVAL;
10348 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
10349 for_each_possible_cpu(i) {
10350 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
10352 spin_lock(&rt_rq->rt_runtime_lock);
10353 rt_rq->rt_runtime = global_rt_runtime();
10354 spin_unlock(&rt_rq->rt_runtime_lock);
10356 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
10358 return 0;
10360 #endif /* CONFIG_RT_GROUP_SCHED */
10362 int sched_rt_handler(struct ctl_table *table, int write,
10363 struct file *filp, void __user *buffer, size_t *lenp,
10364 loff_t *ppos)
10366 int ret;
10367 int old_period, old_runtime;
10368 static DEFINE_MUTEX(mutex);
10370 mutex_lock(&mutex);
10371 old_period = sysctl_sched_rt_period;
10372 old_runtime = sysctl_sched_rt_runtime;
10374 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
10376 if (!ret && write) {
10377 ret = sched_rt_global_constraints();
10378 if (ret) {
10379 sysctl_sched_rt_period = old_period;
10380 sysctl_sched_rt_runtime = old_runtime;
10381 } else {
10382 def_rt_bandwidth.rt_runtime = global_rt_runtime();
10383 def_rt_bandwidth.rt_period =
10384 ns_to_ktime(global_rt_period());
10387 mutex_unlock(&mutex);
10389 return ret;
10392 #ifdef CONFIG_CGROUP_SCHED
10394 /* return corresponding task_group object of a cgroup */
10395 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
10397 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
10398 struct task_group, css);
10401 static struct cgroup_subsys_state *
10402 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
10404 struct task_group *tg, *parent;
10406 if (!cgrp->parent) {
10407 /* This is early initialization for the top cgroup */
10408 return &init_task_group.css;
10411 parent = cgroup_tg(cgrp->parent);
10412 tg = sched_create_group(parent);
10413 if (IS_ERR(tg))
10414 return ERR_PTR(-ENOMEM);
10416 return &tg->css;
10419 static void
10420 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10422 struct task_group *tg = cgroup_tg(cgrp);
10424 sched_destroy_group(tg);
10427 static int
10428 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10429 struct task_struct *tsk)
10431 #ifdef CONFIG_RT_GROUP_SCHED
10432 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
10433 return -EINVAL;
10434 #else
10435 /* We don't support RT-tasks being in separate groups */
10436 if (tsk->sched_class != &fair_sched_class)
10437 return -EINVAL;
10438 #endif
10440 return 0;
10443 static void
10444 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10445 struct cgroup *old_cont, struct task_struct *tsk)
10447 sched_move_task(tsk);
10450 #ifdef CONFIG_FAIR_GROUP_SCHED
10451 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
10452 u64 shareval)
10454 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
10457 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
10459 struct task_group *tg = cgroup_tg(cgrp);
10461 return (u64) tg->shares;
10463 #endif /* CONFIG_FAIR_GROUP_SCHED */
10465 #ifdef CONFIG_RT_GROUP_SCHED
10466 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
10467 s64 val)
10469 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
10472 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
10474 return sched_group_rt_runtime(cgroup_tg(cgrp));
10477 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
10478 u64 rt_period_us)
10480 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
10483 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
10485 return sched_group_rt_period(cgroup_tg(cgrp));
10487 #endif /* CONFIG_RT_GROUP_SCHED */
10489 static struct cftype cpu_files[] = {
10490 #ifdef CONFIG_FAIR_GROUP_SCHED
10492 .name = "shares",
10493 .read_u64 = cpu_shares_read_u64,
10494 .write_u64 = cpu_shares_write_u64,
10496 #endif
10497 #ifdef CONFIG_RT_GROUP_SCHED
10499 .name = "rt_runtime_us",
10500 .read_s64 = cpu_rt_runtime_read,
10501 .write_s64 = cpu_rt_runtime_write,
10504 .name = "rt_period_us",
10505 .read_u64 = cpu_rt_period_read_uint,
10506 .write_u64 = cpu_rt_period_write_uint,
10508 #endif
10511 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
10513 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
10516 struct cgroup_subsys cpu_cgroup_subsys = {
10517 .name = "cpu",
10518 .create = cpu_cgroup_create,
10519 .destroy = cpu_cgroup_destroy,
10520 .can_attach = cpu_cgroup_can_attach,
10521 .attach = cpu_cgroup_attach,
10522 .populate = cpu_cgroup_populate,
10523 .subsys_id = cpu_cgroup_subsys_id,
10524 .early_init = 1,
10527 #endif /* CONFIG_CGROUP_SCHED */
10529 #ifdef CONFIG_CGROUP_CPUACCT
10532 * CPU accounting code for task groups.
10534 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
10535 * (balbir@in.ibm.com).
10538 /* track cpu usage of a group of tasks and its child groups */
10539 struct cpuacct {
10540 struct cgroup_subsys_state css;
10541 /* cpuusage holds pointer to a u64-type object on every cpu */
10542 u64 *cpuusage;
10543 struct cpuacct *parent;
10546 struct cgroup_subsys cpuacct_subsys;
10548 /* return cpu accounting group corresponding to this container */
10549 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
10551 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
10552 struct cpuacct, css);
10555 /* return cpu accounting group to which this task belongs */
10556 static inline struct cpuacct *task_ca(struct task_struct *tsk)
10558 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
10559 struct cpuacct, css);
10562 /* create a new cpu accounting group */
10563 static struct cgroup_subsys_state *cpuacct_create(
10564 struct cgroup_subsys *ss, struct cgroup *cgrp)
10566 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
10568 if (!ca)
10569 return ERR_PTR(-ENOMEM);
10571 ca->cpuusage = alloc_percpu(u64);
10572 if (!ca->cpuusage) {
10573 kfree(ca);
10574 return ERR_PTR(-ENOMEM);
10577 if (cgrp->parent)
10578 ca->parent = cgroup_ca(cgrp->parent);
10580 return &ca->css;
10583 /* destroy an existing cpu accounting group */
10584 static void
10585 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10587 struct cpuacct *ca = cgroup_ca(cgrp);
10589 free_percpu(ca->cpuusage);
10590 kfree(ca);
10593 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
10595 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10596 u64 data;
10598 #ifndef CONFIG_64BIT
10600 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
10602 spin_lock_irq(&cpu_rq(cpu)->lock);
10603 data = *cpuusage;
10604 spin_unlock_irq(&cpu_rq(cpu)->lock);
10605 #else
10606 data = *cpuusage;
10607 #endif
10609 return data;
10612 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
10614 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10616 #ifndef CONFIG_64BIT
10618 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
10620 spin_lock_irq(&cpu_rq(cpu)->lock);
10621 *cpuusage = val;
10622 spin_unlock_irq(&cpu_rq(cpu)->lock);
10623 #else
10624 *cpuusage = val;
10625 #endif
10628 /* return total cpu usage (in nanoseconds) of a group */
10629 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
10631 struct cpuacct *ca = cgroup_ca(cgrp);
10632 u64 totalcpuusage = 0;
10633 int i;
10635 for_each_present_cpu(i)
10636 totalcpuusage += cpuacct_cpuusage_read(ca, i);
10638 return totalcpuusage;
10641 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
10642 u64 reset)
10644 struct cpuacct *ca = cgroup_ca(cgrp);
10645 int err = 0;
10646 int i;
10648 if (reset) {
10649 err = -EINVAL;
10650 goto out;
10653 for_each_present_cpu(i)
10654 cpuacct_cpuusage_write(ca, i, 0);
10656 out:
10657 return err;
10660 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
10661 struct seq_file *m)
10663 struct cpuacct *ca = cgroup_ca(cgroup);
10664 u64 percpu;
10665 int i;
10667 for_each_present_cpu(i) {
10668 percpu = cpuacct_cpuusage_read(ca, i);
10669 seq_printf(m, "%llu ", (unsigned long long) percpu);
10671 seq_printf(m, "\n");
10672 return 0;
10675 static struct cftype files[] = {
10677 .name = "usage",
10678 .read_u64 = cpuusage_read,
10679 .write_u64 = cpuusage_write,
10682 .name = "usage_percpu",
10683 .read_seq_string = cpuacct_percpu_seq_read,
10688 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
10690 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
10694 * charge this task's execution time to its accounting group.
10696 * called with rq->lock held.
10698 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
10700 struct cpuacct *ca;
10701 int cpu;
10703 if (unlikely(!cpuacct_subsys.active))
10704 return;
10706 cpu = task_cpu(tsk);
10708 rcu_read_lock();
10709 ca = task_ca(tsk);
10711 do {
10712 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10713 *cpuusage += cputime;
10714 ca = ca->parent;
10715 } while (ca);
10716 rcu_read_unlock();
10719 struct cgroup_subsys cpuacct_subsys = {
10720 .name = "cpuacct",
10721 .create = cpuacct_create,
10722 .destroy = cpuacct_destroy,
10723 .populate = cpuacct_populate,
10724 .subsys_id = cpuacct_subsys_id,
10726 #endif /* CONFIG_CGROUP_CPUACCT */