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