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
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
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
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>
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 ],
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
);
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
);
169 #define TASK_PREEMPTS_CURR(p, rq) \
170 ((p)->prio < (rq)->curr->prio)
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)¤t_ti
;
182 EXPORT_SYMBOL(___current
);
183 EXPORT_SYMBOL(current_ti
);
186 * The scheduler itself doesnt want 'current' to be cached
187 * during context-switches:
190 # define current __current()
191 # undef current_thread_info
192 # define current_thread_info() __current_thread_info()
195 static inline int rt_policy(int policy
)
197 if (unlikely(policy
== SCHED_FIFO
|| policy
== SCHED_RR
))
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
;
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
);
236 now
= hrtimer_cb_get_time(timer
);
237 overrun
= hrtimer_forward(timer
, now
, rt_b
->rt_period
);
242 idle
= do_sched_rt_period_timer(rt_b
, overrun
);
245 return idle
? HRTIMER_NORESTART
: HRTIMER_RESTART
;
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
)
271 if (!rt_bandwidth_enabled() || rt_b
->rt_runtime
== RUNTIME_INF
)
274 if (hrtimer_active(&rt_b
->rt_period_timer
))
277 spin_lock(&rt_b
->rt_runtime_lock
);
282 if (hrtimer_active(&rt_b
->rt_period_timer
))
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
);
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>
316 static LIST_HEAD(task_groups
);
318 /* task group related information */
320 #ifdef CONFIG_CGROUP_SCHED
321 struct cgroup_subsys_state css
;
324 #ifdef CONFIG_USER_SCHED
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
;
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
;
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
;
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
);
387 static int root_task_group_empty(void)
389 return list_empty(&root_task_group
.children
);
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.)
409 #define MAX_SHARES (1UL << 18)
411 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
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
426 tg
= __task_cred(p
)->user
->tg
;
428 #elif defined(CONFIG_CGROUP_SCHED)
429 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
430 struct task_group
, css
);
432 tg
= &init_task_group
;
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
];
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
];
454 static int root_task_group_empty(void)
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
)
466 #endif /* CONFIG_GROUP_SCHED */
468 /* CFS-related fields in a runqueue */
470 struct load_weight load
;
471 unsigned long nr_running
;
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 */
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
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
;
531 /* Real-Time classes' related field in a runqueue: */
533 struct rt_prio_array active
;
534 unsigned long rt_nr_running
;
535 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
537 int curr
; /* highest queued rt task prio */
539 int next
; /* next highest */
544 unsigned long rt_nr_migratory
;
546 struct plist_head pushable_tasks
;
548 unsigned long rt_nr_uninterruptible
;
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
;
559 struct list_head leaf_rt_rq_list
;
560 struct task_group
*tg
;
561 struct sched_rt_entity
*rt_se
;
565 #ifdef CONFIG_SCHED_CBS
567 unsigned long nr_running
;
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
;
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
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
;
605 struct cpupri cpupri
;
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
;
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
;
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.
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
];
644 unsigned long last_tick_seen
;
645 unsigned char in_nohz_recently
;
647 /* capture load from *all* tasks on this cpu: */
648 struct load_weight load
;
649 unsigned long nr_load_updates
;
651 u64 nr_migrations_in
;
655 #ifdef CONFIG_SCHED_CBS
659 #ifdef CONFIG_FAIR_GROUP_SCHED
660 /* list of leaf cfs_rq on this cpu: */
661 struct list_head leaf_cfs_rq_list
;
663 #ifdef CONFIG_RT_GROUP_SCHED
664 struct list_head leaf_rt_rq_list
;
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
;
686 struct root_domain
*rd
;
687 struct sched_domain
*sd
;
689 unsigned char idle_at_tick
;
690 /* For active balancing */
693 /* cpu of this runqueue: */
697 unsigned long avg_load_per_task
;
699 struct task_struct
*migration_thread
;
700 struct list_head migration_queue
;
703 /* calc_load related fields */
704 unsigned long calc_load_update
;
705 long calc_load_active
;
707 #ifdef CONFIG_SCHED_HRTICK
709 int hrtick_csd_pending
;
710 struct call_single_data hrtick_csd
;
712 struct hrtimer hrtick_timer
;
715 #ifdef CONFIG_SCHEDSTATS
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
;
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
;
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
)
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
));
782 int task_is_current(struct task_struct
*task
)
784 return task_rq(task
)->curr
== task
;
789 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
791 #ifdef CONFIG_SCHED_DEBUG
792 # define const_debug __read_mostly
794 # define const_debug static const
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)
807 struct rq
*rq
= cpu_rq(cpu
);
810 ret
= spin_is_locked(&rq
->lock
);
816 * Debugging: various feature bits
819 #define SCHED_FEAT(name, enabled) \
820 __SCHED_FEAT_##name ,
823 #include "sched_features.h"
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"
837 #ifdef CONFIG_SCHED_DEBUG
838 #define SCHED_FEAT(name, enabled) \
841 static __read_mostly
char *sched_feat_names
[] = {
842 #include "sched_features.h"
848 static int sched_feat_show(struct seq_file
*m
, void *v
)
852 for (i
= 0; sched_feat_names
[i
]; i
++) {
853 if (!(sysctl_sched_features
& (1UL << i
)))
855 seq_printf(m
, "%s ", sched_feat_names
[i
]);
863 sched_feat_write(struct file
*filp
, const char __user
*ubuf
,
864 size_t cnt
, loff_t
*ppos
)
874 if (copy_from_user(&buf
, ubuf
, cnt
))
879 if (strncmp(buf
, "NO_", 3) == 0) {
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) {
889 sysctl_sched_features
&= ~(1UL << i
);
891 sysctl_sched_features
|= (1UL << i
);
896 if (!sched_feat_names
[i
])
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
,
914 .release
= single_release
,
917 static __init
int sched_init_debug(void)
919 debugfs_create_file("sched_features", 0644, NULL
, NULL
,
924 late_initcall(sched_init_debug
);
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.
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.
947 unsigned int sysctl_sched_shares_thresh
= 4;
950 * period over which we measure -rt task cpu usage in us.
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.
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)
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
984 # define _finish_arch_switch finish_arch_switch
988 #ifndef prepare_arch_switch
989 # define prepare_arch_switch(next) do { } while (0)
991 #ifndef finish_arch_switch
992 # define _finish_arch_switch(prev) do { } while (0)
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
)
1005 return task_current(rq
, p
);
1009 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1010 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
1014 * We can optimise this out completely for !SMP, because the
1015 * SMP rebalancing from interrupt is the only thing that cares
1022 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
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
1033 #ifdef CONFIG_DEBUG_SPINLOCK
1034 /* this is a valid case when another task releases the spinlock */
1035 rq
->lock
.owner
= current
;
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
)
1053 * We can optimise this out completely for !SMP, because the
1054 * SMP rebalancing from interrupt is the only thing that cares
1059 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1060 spin_unlock_irq(&rq
->lock
);
1062 spin_unlock(&rq
->lock
);
1066 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
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
1077 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
1078 local_irq_disable();
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
)
1091 struct rq
*rq
= task_rq(p
);
1092 spin_lock(&rq
->lock
);
1093 if (likely(rq
== task_rq(p
)))
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
)
1110 local_irq_save(*flags
);
1112 spin_lock(&rq
->lock
);
1113 if (likely(rq
== task_rq(p
)))
1115 spin_unlock_irqrestore(&rq
->lock
, *flags
);
1119 void curr_rq_lock_irq_save(unsigned long *flags
)
1120 __acquires(rq
->lock
)
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
)
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
)
1167 local_irq_disable();
1169 spin_lock(&rq
->lock
);
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
1182 * When we get rescheduled we reprogram the hrtick_timer outside of the
1188 * - enabled by features
1189 * - hrtimer is actually high res
1191 static inline int hrtick_enabled(struct rq
*rq
)
1193 if (!sched_feat(HRTICK
))
1195 if (!cpu_active(cpu_of(rq
)))
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
;
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;
1259 hotplug_hrtick(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
1261 int cpu
= (int)(long)hcpu
;
1264 case CPU_UP_CANCELED
:
1265 case CPU_UP_CANCELED_FROZEN
:
1266 case CPU_DOWN_PREPARE
:
1267 case CPU_DOWN_PREPARE_FROZEN
:
1269 case CPU_DEAD_FROZEN
:
1270 hrtick_clear(cpu_rq(cpu
));
1277 static __init
void init_hrtick(void)
1279 hotcpu_notifier(hotplug_hrtick
, 0);
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
)
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
;
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
1335 #ifndef tsk_is_polling
1336 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1339 static void resched_task(struct task_struct
*p
)
1343 assert_spin_locked(&task_rq(p
)->lock
);
1345 if (test_tsk_need_resched(p
))
1348 set_tsk_need_resched(p
);
1351 if (cpu
== smp_processor_id())
1354 /* NEED_RESCHED must be visible before we test polling */
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
))
1367 resched_task(cpu_curr(cpu
));
1368 spin_unlock_irqrestore(&rq
->lock
, flags
);
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())
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
)
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 */
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)
1424 # define WMULT_CONST (1UL << 32)
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
)
1443 if (!lw
->inv_weight
) {
1444 if (BITS_PER_LONG
> 32 && unlikely(lw
->weight
>= WMULT_CONST
))
1447 lw
->inv_weight
= 1 + (WMULT_CONST
-lw
->weight
/2)
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
,
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
)
1470 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
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
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
{
1538 struct task_struct
*(*start
)(void *);
1539 struct task_struct
*(*next
)(void *);
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
);
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
);
1555 #ifdef CONFIG_CGROUP_CPUACCT
1556 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1558 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
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
;
1584 parent
= &root_task_group
;
1586 ret
= (*down
)(parent
, data
);
1589 list_for_each_entry_rcu(child
, &parent
->children
, siblings
) {
1596 ret
= (*up
)(parent
, data
);
1601 parent
= parent
->parent
;
1610 static int tg_nop(struct task_group
*tg
, void *data
)
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
);
1627 rq
->avg_load_per_task
= rq
->load
.weight
/ nr_running
;
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.
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
;
1651 rq_weight
= tg
->cfs_rq
[cpu
]->rq_weight
;
1654 * \Sum shares * rq_weight
1655 * shares = -----------------------
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
;
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
;
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
);
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
)
1722 long cpu
= (long)data
;
1725 load
= cpu_rq(cpu
)->load
.weight
;
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
;
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
);
1752 spin_lock(&rq
->lock
);
1755 static void update_h_load(long cpu
)
1757 walk_tg_tree(tg_load_down
, tg_nop
, (void *)cpu
);
1762 static inline void update_shares(struct sched_domain
*sd
)
1766 static inline void update_shares_locked(struct rq
*rq
, struct sched_domain
*sd
)
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
);
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
)
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
);
1815 spin_lock_nested(&busiest
->lock
, SINGLE_DEPTH_NESTING
);
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
);
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_
);
1844 #ifdef CONFIG_FAIR_GROUP_SCHED
1845 static void cfs_rq_set_shares(struct cfs_rq
*cfs_rq
, unsigned long shares
)
1848 cfs_rq
->shares
= shares
;
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"
1861 #include "sched_rt.c"
1862 #ifdef CONFIG_SCHED_DEBUG
1863 # include "sched_debug.c"
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
)
1875 static void dec_nr_running(struct rq
*rq
)
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;
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
;
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
;
1907 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int 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
);
1917 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int 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;
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
);
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
)
1954 if (task_has_rt_policy(p
))
1955 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1957 prio
= __normal_prio(p
);
1959 // trace_special_pid(p->pid, PRIO(p), __PRIO(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
;
1984 * activate_task - move a task to the runqueue.
1986 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1988 if (task_contributes_to_load(p
))
1989 rq
->nr_uninterruptible
--;
1990 enqueue_task(rq
, p
, wakeup
);
1995 * deactivate_task - remove a task from the runqueue.
1997 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1999 if (task_contributes_to_load(p
))
2000 rq
->nr_uninterruptible
++;
2002 dequeue_task(rq
, p
, sleep
);
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
);
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.
2026 task_thread_info(p
)->cpu
= cpu
;
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
);
2039 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
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:
2054 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
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
))
2066 if (p
->sched_class
!= &fair_sched_class
)
2069 if (sysctl_sched_migration_cost
== -1)
2071 if (sysctl_sched_migration_cost
== 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
);
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
;
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
);
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
;
2120 struct completion done
;
2124 * The task's runqueue lock must be held.
2125 * Returns true if you have to wait for migration thread.
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
);
2141 init_completion(&req
->done
);
2143 req
->dest_cpu
= dest_cpu
;
2144 list_add(&req
->list
, &rq
->migration_queue
);
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
;
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
2182 * If the task is actively running on another CPU
2183 * still, just relax and busy-wait without holding
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
))
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
;
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
))
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
)) {
2230 * It's not enough that it's not actively running,
2231 * it must be off the runqueue _entirely_, and not
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);
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!
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
2267 void kick_process(struct task_struct
*p
)
2273 if ((cpu
!= smp_processor_id()) && task_curr(p
))
2274 smp_send_reschedule(cpu
);
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
))
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
))
2308 return max(rq
->cpu_load
[type
-1], total
);
2312 * find_idlest_group finds and returns the least busy CPU group within the
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;
2324 unsigned long load
, avg_load
;
2328 /* Skip over this group if it has no CPUs allowed */
2329 if (!cpumask_intersects(sched_group_cpus(group
),
2333 local_group
= cpumask_test_cpu(this_cpu
,
2334 sched_group_cpus(group
));
2336 /* Tally up the load of all CPUs in the group */
2339 for_each_cpu(i
, sched_group_cpus(group
)) {
2340 /* Bias balancing toward cpus of our domain */
2342 load
= source_load(i
, load_idx
);
2344 load
= target_load(i
, load_idx
);
2349 /* Adjust by relative CPU power of the group */
2350 avg_load
= sg_div_cpu_power(group
,
2351 avg_load
* SCHED_LOAD_SCALE
);
2354 this_load
= avg_load
;
2356 } else if (avg_load
< min_load
) {
2357 min_load
= avg_load
;
2360 } while (group
= group
->next
, group
!= sd
->groups
);
2362 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
2368 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2371 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
2373 unsigned long load
, min_load
= ULONG_MAX
;
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
)) {
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
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
)
2412 if (tmp
->flags
& flag
)
2420 struct sched_group
*group
;
2421 int new_cpu
, weight
;
2423 if (!(sd
->flags
& flag
)) {
2428 group
= find_idlest_group(sd
, t
, cpu
);
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 */
2441 /* Now try balancing at a lower domain level of new_cpu */
2443 weight
= cpumask_weight(sched_domain_span(sd
));
2445 for_each_domain(cpu
, tmp
) {
2446 if (weight
<= cpumask_weight(sched_domain_span(tmp
)))
2448 if (tmp
->flags
& flag
)
2451 /* while loop will break here if sd == NULL */
2457 #endif /* CONFIG_SMP */
2459 #ifdef CONFIG_DEBUG_PREEMPT
2460 void notrace
preempt_enable_no_resched(void)
2462 static int once
= 1;
2465 dec_preempt_count();
2467 if (once
&& !preempt_count()) {
2469 printk(KERN_ERR
"BUG: %s:%d task might have lost a preemption check!\n",
2470 current
->comm
, current
->pid
);
2475 EXPORT_SYMBOL(preempt_enable_no_resched
);
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
)
2496 smp_call_function_single(cpu
, func
, info
, 1);
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.
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
;
2522 if (!sched_feat(SYNC_WAKEUPS
))
2526 if (sched_feat(LB_WAKEUP_UPDATE
) && !root_task_group_empty()) {
2527 struct sched_domain
*sd
;
2529 this_cpu
= raw_smp_processor_id();
2532 for_each_domain(this_cpu
, sd
) {
2533 if (cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
2541 #ifdef CONFIG_PREEMPT_RT
2543 * sync wakeups can increase wakeup latencies:
2549 rq
= task_rq_lock(p
, &flags
);
2550 update_rq_clock(rq
);
2551 old_state
= p
->state
;
2552 if (!(old_state
& state
))
2560 this_cpu
= smp_processor_id();
2563 if (unlikely(task_running(rq
, p
)))
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
))
2578 this_cpu
= smp_processor_id();
2582 #ifdef CONFIG_SCHEDSTATS
2583 schedstat_inc(rq
, ttwu_count
);
2584 if (cpu
== this_cpu
)
2585 schedstat_inc(rq
, ttwu_local
);
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
);
2595 #endif /* CONFIG_SCHEDSTATS */
2598 #endif /* CONFIG_SMP */
2599 schedstat_inc(p
, se
.nr_wakeups
);
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
);
2607 schedstat_inc(p
, se
.nr_wakeups_remote
);
2608 activate_task(rq
, p
, 1);
2612 * Only attribute actual wakeups done by this task.
2614 if (!in_interrupt()) {
2615 struct sched_entity
*se
= ¤t
->se
;
2616 u64 sample
= se
->sum_exec_runtime
;
2618 if (se
->last_wakeup
)
2619 sample
-= se
->last_wakeup
;
2621 sample
-= se
->start_runtime
;
2622 update_avg(&se
->avg_wakeup
, sample
);
2624 se
->last_wakeup
= se
->sum_exec_runtime
;
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.
2640 p
->state
|= TASK_RUNNING_MUTEX
;
2642 p
->state
= TASK_RUNNING
;
2644 if (p
->sched_class
->task_wake_up
)
2645 p
->sched_class
->task_wake_up(rq
, p
);
2648 task_rq_unlock(rq
, &flags
);
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;
2707 p
->se
.slice_max
= 0;
2711 INIT_LIST_HEAD(&p
->rt
.run_list
);
2713 INIT_LIST_HEAD(&p
->se
.group_node
);
2715 #ifdef CONFIG_PREEMPT_NOTIFIERS
2716 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
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();
2738 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
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
;
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
));
2760 #if defined(CONFIG_SMP)
2763 #ifdef CONFIG_PREEMPT
2764 /* Want to start with kernel preemption disabled. */
2765 task_thread_info(p
)->preempt_count
= 1;
2767 plist_node_init(&p
->pushable_tasks
, MAX_PRIO
);
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
;
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);
2794 * Let the scheduling class do new task startup
2795 * management (if any):
2797 p
->sched_class
->task_new(rq
, p
);
2800 trace_sched_wakeup_new(rq
, p
, 1);
2801 check_preempt_curr(rq
, p
, 0);
2803 if (p
->sched_class
->task_wake_up
)
2804 p
->sched_class
->task_wake_up(rq
, p
);
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(¬ifier
->link
, ¤t
->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(¬ifier
->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
))
2842 * The KVM sched in notifier expects to be called with
2843 * interrupts enabled.
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();
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
)
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
2886 * prepare_task_switch sets up locking and calls architecture specific
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
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
;
2919 int post_schedule
= 0;
2921 if (current
->sched_class
->needs_post_schedule
)
2922 post_schedule
= current
->sched_class
->needs_post_schedule(rq
);
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
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
);
2944 current
->sched_class
->post_schedule(rq
);
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:
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
)
2972 finish_task_switch(this_rq(), prev
);
2973 __preempt_enable_no_resched();
2975 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2976 /* In this case, finish_task_switch does not reenable preemption */
2979 preempt_check_resched();
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.
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
);
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
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
);
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_
);
3029 *current_ptr
= next
;
3030 *current_ti_ptr
= next
->thread_info
;
3032 /* Here we just switch the register state and the stack. */
3033 switch_to(prev
, next
, prev
);
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
;
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))
3078 unsigned long nr_uninterruptible_cpu(int cpu
)
3080 return cpu_rq(cpu
)->nr_uninterruptible
;
3083 unsigned long long nr_context_switches(void)
3086 unsigned long long sum
= 0;
3088 for_each_possible_cpu(i
)
3089 sum
+= cpu_rq(i
)->nr_switches
;
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))
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
)
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;
3149 if (time_before(jiffies
, upd
))
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
;
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
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
);
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());
3237 spin_lock(&rq1
->lock
);
3238 __acquire(rq2
->lock
); /* Fake it out ;) */
3241 spin_lock(&rq1
->lock
);
3242 spin_lock_nested(&rq2
->lock
, SINGLE_DEPTH_NESTING
);
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
);
3264 spin_unlock(&rq2
->lock
);
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
;
3281 rq
= task_rq_lock(p
, &flags
);
3282 if (!cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
)
3283 || unlikely(!cpu_active(dest_cpu
)))
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
);
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
);
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?
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
,
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
);
3354 if (task_running(rq
, p
)) {
3355 schedstat_inc(p
, se
.nr_failed_migrations_running
);
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
);
3377 if (tsk_cache_hot
) {
3378 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
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)
3400 * Start the load-balancing iterator:
3402 p
= iterator
->start(iterator
->arg
);
3404 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
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
);
3413 pull_task(busiest
, p
, this_rq
, this_cpu
);
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
3423 if (idle
== CPU_NEWLY_IDLE
)
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
);
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
);
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
,
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
;
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
)
3482 } while (class && max_load_move
> total_load_moved
);
3484 return total_load_moved
> 0;
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
);
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
]);
3507 p
= iterator
->next(iterator
->arg
);
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
))
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 */
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
)
3597 load_idx
= sd
->busy_idx
;
3600 case CPU_NEWLY_IDLE
:
3601 load_idx
= sd
->newidle_idx
;
3604 load_idx
= sd
->idle_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
3628 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
3629 sds
->power_savings_balance
= 0;
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
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
)
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
)
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
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)
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
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.
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
)
3721 if (sds
->this != sds
->group_leader
||
3722 sds
->group_leader
== sds
->group_min
)
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
);
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
)
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
)
3749 static inline int check_power_save_busiest_group(struct sd_lb_stats
*sds
,
3750 int this_cpu
, unsigned long *imbalance
)
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
;
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
;
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;
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
)
3794 /* Bias balancing toward cpus of our domain */
3796 if (idle_cpu(i
) && !first_idle_cpu
) {
3801 load
= target_load(i
, load_idx
);
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
) {
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
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
)
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
;
3872 init_sd_power_savings_stats(sd
, sds
, idle
);
3873 load_idx
= get_sd_load_idx(sd
, idle
);
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
))
3887 sds
->total_load
+= sgs
.group_load
;
3888 sds
->total_pwr
+= group
->__cpu_power
;
3891 sds
->this_load
= sgs
.avg_load
;
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
||
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
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
)
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
;
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
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
);
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
) {
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
)
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
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
4056 update_sd_lb_stats(sd
, this_cpu
, idle
, sd_idle
, cpus
,
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
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
4066 * 5) The imbalance is within the specified limit.
4067 * 6) Any rebalance would lead to ping-pong
4069 if (balance
&& !(*balance
))
4072 if (!sds
.busiest
|| sds
.busiest_nr_running
== 0)
4075 if (sds
.this_load
>= sds
.max_load
)
4078 sds
.avg_load
= (SCHED_LOAD_SCALE
* sds
.total_load
) / sds
.total_pwr
;
4080 if (sds
.this_load
>= sds
.avg_load
)
4083 if (100 * sds
.max_load
<= sd
->imbalance_pct
* sds
.this_load
)
4086 sds
.busiest_load_per_task
/= sds
.busiest_nr_running
;
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
)
4105 /* Looks like there is an imbalance. Compute it */
4106 calculate_imbalance(&sds
, this_cpu
, imbalance
);
4111 * There is no obvious imbalance. But check if we can do some balancing
4114 if (check_power_save_busiest_group(&sds
, this_cpu
, imbalance
))
4122 * find_busiest_queue - find the busiest runqueue among the cpus in group.
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;
4132 for_each_cpu(i
, sched_group_cpus(group
)) {
4135 if (!cpumask_test_cpu(i
, cpus
))
4139 wl
= weighted_cpuload(i
);
4141 if (rq
->nr_running
== 1 && wl
> imbalance
)
4144 if (wl
> max_load
) {
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
,
4170 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
4171 struct sched_group
*group
;
4172 unsigned long imbalance
;
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
))
4189 schedstat_inc(sd
, lb_count
[idle
]);
4193 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
4200 schedstat_inc(sd
, lb_nobusyg
[idle
]);
4204 busiest
= find_busiest_queue(group
, idle
, imbalance
, cpus
);
4206 schedstat_inc(sd
, lb_nobusyq
[idle
]);
4210 BUG_ON(busiest
== this_rq
);
4212 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
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
))
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
);
4259 goto out_one_pinned
;
4262 if (!busiest
->active_balance
) {
4263 busiest
->active_balance
= 1;
4264 busiest
->push_cpu
= this_cpu
;
4267 spin_unlock_irqrestore(&busiest
->lock
, flags
);
4269 wake_up_process(busiest
->migration_thread
);
4272 * We've kicked active balancing, reset the failure
4275 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
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
;
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
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
))
4301 schedstat_inc(sd
, lb_balanced
[idle
]);
4303 sd
->nr_balance_failed
= 0;
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
))
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.
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
;
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
))
4352 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
4354 update_shares_locked(this_rq
, sd
);
4355 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
4356 &sd_idle
, cpus
, NULL
);
4358 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
4362 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
, cpus
);
4364 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
4368 BUG_ON(busiest
== this_rq
);
4370 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
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
,
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
))
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
))
4398 if (sched_mc_power_savings
< POWERSAVINGS_BALANCE_WAKEUP
)
4401 if (sd
->nr_balance_failed
++ < 2)
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
);
4439 if (!busiest
->active_balance
) {
4440 busiest
->active_balance
= 1;
4441 busiest
->push_cpu
= this_cpu
;
4445 double_unlock_balance(this_rq
, busiest
);
4447 * Should not call ttwu while holding a rq->lock
4449 spin_unlock(&this_rq
->lock
);
4451 wake_up_process(busiest
->migration_thread
);
4452 spin_lock(&this_rq
->lock
);
4455 sd
->nr_balance_failed
= 0;
4457 update_shares_locked(this_rq
, sd
);
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
))
4465 sd
->nr_balance_failed
= 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
))
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
,
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
;
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)
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
)))
4546 schedstat_inc(sd
, alb_count
);
4548 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
4550 schedstat_inc(sd
, alb_pushed
);
4552 schedstat_inc(sd
, alb_failed
);
4554 double_unlock_balance(busiest_rq
, target_rq
);
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
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
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();
4590 cpu_rq(cpu
)->in_nohz_recently
= 1;
4592 if (!cpu_active(cpu
)) {
4593 if (atomic_read(&nohz
.load_balancer
) != cpu
)
4597 * If we are going offline and still the leader,
4600 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
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);
4615 if (atomic_read(&nohz
.load_balancer
) == -1) {
4616 /* make me the ilb owner */
4617 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
4619 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
4622 if (!cpumask_test_cpu(cpu
, nohz
.cpu_mask
))
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
)
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
)
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;
4654 for_each_domain(cpu
, sd
) {
4655 if (!(sd
->flags
& SD_LOAD_BALANCE
))
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
))
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
))
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
4683 idle
= CPU_NOT_IDLE
;
4685 sd
->last_balance
= jiffies
;
4688 spin_unlock(&balancing
);
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
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
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
);
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
4733 if (this_rq
->idle_at_tick
&&
4734 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
4738 for_each_cpu(balance_cpu
, nohz
.cpu_mask
) {
4739 if (balance_cpu
== this_cpu
)
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.
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
;
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
)
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
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
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
)
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()) {
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
))
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
)
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
)
4853 if (task_current(rq
, p
)) {
4854 update_rq_clock(rq
);
4855 ns
= rq
->clock
- p
->se
.exec_start
;
4863 unsigned long long __task_delta_exec(struct task_struct
*p
, int update
)
4869 WARN_ON_ONCE(!runqueue_is_locked());
4870 WARN_ON_ONCE(!task_current(rq
, p
));
4873 update_rq_clock(rq
);
4875 delta_exec
= rq
->clock
- p
->se
.exec_start
;
4877 WARN_ON_ONCE(delta_exec
< 0);
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
;
4892 rq
= task_rq_lock(p
, &flags
);
4893 ns
= do_task_delta_exec(p
, rq
);
4894 task_rq_unlock(rq
, &flags
);
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
;
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
);
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
;
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
);
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
;
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
);
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
);
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
)
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
;
5008 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0)) {
5009 account_guest_time(p
, cputime
, cputime_scaled
);
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
);
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
);
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();
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
,
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
));
5105 * Use precise platform statistics if available:
5107 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
5108 cputime_t
task_utime(struct task_struct
*p
)
5113 cputime_t
task_stime(struct task_struct
*p
)
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
);
5125 * Use CFS's precise accounting:
5127 temp
= (u64
)nsec_to_clock_t(p
->se
.sum_exec_runtime
);
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
)
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
));
5152 p
->prev_stime
= max(p
->prev_stime
, clock_t_to_cputime(stime
));
5154 return p
->prev_stime
;
5158 inline cputime_t
task_gtime(struct task_struct
*p
)
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
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
;
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
);
5189 rq
->idle_at_tick
= idle_cpu(cpu
);
5190 trigger_load_balance(rq
, cpu
);
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
;
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
5213 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5216 preempt_count() += val
;
5217 #ifdef CONFIG_DEBUG_PREEMPT
5219 * Spinlock count overflowing soon?
5221 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
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
5235 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
5238 * Is the spinlock portion underflowing?
5240 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
5241 !(preempt_count() & PREEMPT_MASK
)))
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
);
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
);
5265 if (irqs_disabled())
5266 print_irqtrace_events(prev
);
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
);
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
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
);
5341 class = sched_class_highest
;
5343 p
= class->pick_next_task(rq
);
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
;
5364 cpu
= smp_processor_id();
5368 switch_count
= &prev
->nivcsw
;
5370 release_kernel_lock(prev
);
5372 schedule_debug(prev
);
5376 if (sched_feat(HRTICK
))
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
;
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
);
5398 if (prev
->sched_class
->pre_schedule
)
5399 prev
->sched_class
->pre_schedule(rq
, prev
);
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
);
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();
5423 __preempt_enable_no_resched();
5425 __preempt_enable_no_resched();
5426 spin_unlock(&rq
->lock
);
5429 reacquire_kernel_lock(current
);
5432 asmlinkage
void __sched
schedule(void)
5435 local_irq_disable();
5439 if (unlikely(test_thread_flag(TIF_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
)
5454 if (!sched_feat(OWNER_SPIN
))
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
))
5470 * Even if the access succeeded (likely case),
5471 * the cpu field may no longer be valid.
5473 if (cpu
>= nr_cpumask_bits
)
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
))
5487 * Owner changed, break to re-assess state.
5489 if (lock
->owner
!= owner
)
5493 * Is that owner really running on that cpu?
5495 if (task_thread_info(rq
->curr
) != owner
|| need_resched())
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;
5521 if (!strncmp(str
, "on", 2)) {
5522 if (!kernel_preemption
) {
5523 printk(KERN_INFO
"turning on kernel preemption!\n");
5524 kernel_preemption
= 1;
5528 get_option(&str
, &kernel_preemption
);
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
)
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()))
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;
5567 task
->lock_depth
= saved_lock_depth
;
5571 * Check again in case we missed a preemption opportunity
5572 * between schedule and now.
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
)
5594 * If there is a non-zero preempt_count then just return.
5595 * (interrupts are disabled)
5597 if (unlikely(ti
->preempt_count
))
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;
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.
5620 } while (need_resched());
5623 #endif /* CONFIG_PREEMPT */
5625 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
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
)
5656 * __wake_up - wake up threads blocked on a 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.
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.
5695 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
5697 unsigned long flags
;
5703 if (unlikely(!nr_exclusive
))
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
);
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
)
5753 DECLARE_WAITQUEUE(wait
, current
);
5755 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
5756 __add_wait_queue_tail(&x
->wait
, &wait
);
5758 if (signal_pending_state(state
, current
)) {
5759 timeout
= -ERESTARTSYS
;
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
);
5772 return timeout
?: 1;
5776 wait_for_common(struct completion
*x
, long timeout
, int state
)
5780 spin_lock_irq(&x
->wait
.lock
);
5781 timeout
= do_wait_for_common(x
, timeout
, state
);
5782 spin_unlock_irq(&x
->wait
.lock
);
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
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
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
)
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
)
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
)
5882 spin_lock_irq(&x
->wait
.lock
);
5887 spin_unlock_irq(&x
->wait
.lock
);
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
)
5904 spin_lock_irq(&x
->wait
.lock
);
5907 spin_unlock_irq(&x
->wait
.lock
);
5910 EXPORT_SYMBOL(completion_done
);
5913 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
5915 unsigned long flags
;
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
);
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
);
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
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
5970 void task_setprio(struct task_struct
*p
, int prio
)
5972 unsigned long flags
;
5973 int oldprio
, on_rq
, running
;
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
);
5999 update_rq_clock(rq
);
6002 on_rq
= p
->se
.on_rq
;
6003 running
= task_current(rq
, p
);
6005 dequeue_task(rq
, p
, 0);
6007 p
->sched_class
->put_prev_task(rq
, p
);
6010 p
->sched_class
= &rt_sched_class
;
6012 #ifdef CONFIG_SCHED_CBS
6013 if (p
->policy
== SCHED_CBS
)
6014 p
->sched_class
= &cbs_sched_class
;
6017 p
->sched_class
= &fair_sched_class
;
6021 trace_sched_task_setprio(rq
, p
, oldprio
);
6024 p
->sched_class
->set_curr_task(rq
);
6026 enqueue_task(rq
, p
, 0);
6028 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
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
;
6041 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
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
);
6059 on_rq
= p
->se
.on_rq
;
6061 dequeue_task(rq
, p
, 0);
6063 p
->static_prio
= NICE_TO_PRIO(nice
);
6066 p
->prio
= effective_prio(p
);
6067 delta
= p
->prio
- old_prio
;
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
);
6079 task_rq_unlock(rq
, &flags
);
6081 EXPORT_SYMBOL(set_user_nice
);
6084 * can_nice - check if a task can reduce its 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
)
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)
6120 nice
= TASK_NICE(current
) + increment
;
6126 if (increment
< 0 && !can_nice(current
, nice
))
6129 retval
= security_task_setnice(current
, nice
);
6133 set_user_nice(current
, nice
);
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. */
6191 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
6193 BUG_ON(p
->se
.on_rq
);
6196 switch (p
->policy
) {
6200 p
->sched_class
= &fair_sched_class
;
6204 p
->sched_class
= &rt_sched_class
;
6206 #ifdef CONFIG_SCHED_CBS
6208 p
->sched_class
= &cbs_sched_class
;
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
);
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
;
6229 pcred
= __task_cred(p
);
6230 match
= (cred
->euid
== pcred
->euid
||
6231 cred
->euid
== pcred
->uid
);
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
;
6244 /* may grab non-irq protected spin_locks */
6245 BUG_ON(in_interrupt());
6247 /* double check policy once rq lock held */
6249 policy
= oldpolicy
= p
->policy
;
6250 #ifdef CONFIG_SCHED_CBS
6251 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&& policy
!= SCHED_CBS
&&
6253 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
6256 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
6257 policy
!= SCHED_IDLE
)
6260 * Valid priorities for SCHED_FIFO and SCHED_RR are
6261 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
6262 * SCHED_BATCH and SCHED_IDLE is 0.
6264 if (param
->sched_priority
< 0 ||
6265 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
6266 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
6268 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
6272 * Allow unprivileged RT tasks to decrease priority:
6274 if (user
&& !capable(CAP_SYS_NICE
)) {
6275 if (rt_policy(policy
)) {
6276 unsigned long rlim_rtprio
;
6278 if (!lock_task_sighand(p
, &flags
))
6280 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
6281 unlock_task_sighand(p
, &flags
);
6283 /* can't set/change the rt policy */
6284 if (policy
!= p
->policy
&& !rlim_rtprio
)
6287 /* can't increase priority */
6288 if (param
->sched_priority
> p
->rt_priority
&&
6289 param
->sched_priority
> rlim_rtprio
)
6293 * Like positive nice levels, dont allow tasks to
6294 * move out of SCHED_IDLE either:
6296 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
6299 /* can't change other user's priorities */
6300 if (!check_same_owner(p
))
6305 #ifdef CONFIG_RT_GROUP_SCHED
6307 * Do not allow realtime tasks into groups that have no runtime
6310 if (rt_bandwidth_enabled() && rt_policy(policy
) &&
6311 task_group(p
)->rt_bandwidth
.rt_runtime
== 0)
6315 retval
= security_task_setscheduler(p
, policy
, param
);
6321 * make sure no PI-waiters arrive (or leave) while we are
6322 * changing the priority of the task:
6324 spin_lock_irqsave(&p
->pi_lock
, flags
);
6326 * To be able to change p->policy safely, the apropriate
6327 * runqueue lock must be held.
6329 rq
= __task_rq_lock(p
);
6330 /* recheck policy now with rq lock held */
6331 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
6332 policy
= oldpolicy
= -1;
6333 __task_rq_unlock(rq
);
6334 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
6337 update_rq_clock(rq
);
6338 on_rq
= p
->se
.on_rq
;
6339 running
= task_current(rq
, p
);
6341 deactivate_task(rq
, p
, 0);
6343 p
->sched_class
->put_prev_task(rq
, p
);
6347 #ifdef CONFIG_SCHED_CBS
6348 if (policy
== SCHED_CBS
) { /* FIXME: Move to __setscheduler()? */
6349 p
->cbs_se
.period
= timespec_to_ns(&(param
->sched_ss_repl_period
));
6350 p
->cbs_se
.max_budget
= timespec_to_ns(¶m
->sched_ss_init_budget
);
6351 p
->cbs_se
.budget
= p
->cbs_se
.max_budget
;
6352 //now=cbs_rq_of(task_cbs_rq(p))->clock;
6353 p
->cbs_se
.deadline
= 0;
6355 init_cbs_timer(&p
->cbs_se
);
6359 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
6362 p
->sched_class
->set_curr_task(rq
);
6364 activate_task(rq
, p
, 0);
6366 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
6368 __task_rq_unlock(rq
);
6369 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
6371 rt_mutex_adjust_pi(p
);
6377 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
6378 * @p: the task in question.
6379 * @policy: new policy.
6380 * @param: structure containing the new RT priority.
6382 * NOTE that the task may be already dead.
6384 int sched_setscheduler(struct task_struct
*p
, int policy
,
6385 struct sched_param
*param
)
6387 return __sched_setscheduler(p
, policy
, param
, true);
6389 EXPORT_SYMBOL_GPL(sched_setscheduler
);
6392 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
6393 * @p: the task in question.
6394 * @policy: new policy.
6395 * @param: structure containing the new RT priority.
6397 * Just like sched_setscheduler, only don't bother checking if the
6398 * current context has permission. For example, this is needed in
6399 * stop_machine(): we create temporary high priority worker threads,
6400 * but our caller might not have that capability.
6402 int sched_setscheduler_nocheck(struct task_struct
*p
, int policy
,
6403 struct sched_param
*param
)
6405 return __sched_setscheduler(p
, policy
, param
, false);
6409 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
6411 struct sched_param lparam
;
6412 struct task_struct
*p
;
6415 if (!param
|| pid
< 0)
6417 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
6422 p
= find_process_by_pid(pid
);
6424 retval
= sched_setscheduler(p
, policy
, &lparam
);
6431 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
6432 * @pid: the pid in question.
6433 * @policy: new policy.
6434 * @param: structure containing the new RT priority.
6436 SYSCALL_DEFINE3(sched_setscheduler
, pid_t
, pid
, int, policy
,
6437 struct sched_param __user
*, param
)
6439 /* negative values for policy are not valid */
6443 return do_sched_setscheduler(pid
, policy
, param
);
6447 * sys_sched_setparam - set/change the RT priority of a thread
6448 * @pid: the pid in question.
6449 * @param: structure containing the new RT priority.
6451 SYSCALL_DEFINE2(sched_setparam
, pid_t
, pid
, struct sched_param __user
*, param
)
6453 return do_sched_setscheduler(pid
, -1, param
);
6457 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
6458 * @pid: the pid in question.
6460 SYSCALL_DEFINE1(sched_getscheduler
, pid_t
, pid
)
6462 struct task_struct
*p
;
6469 read_lock(&tasklist_lock
);
6470 p
= find_process_by_pid(pid
);
6472 retval
= security_task_getscheduler(p
);
6476 read_unlock(&tasklist_lock
);
6481 * sys_sched_getscheduler - get the RT priority of a thread
6482 * @pid: the pid in question.
6483 * @param: structure containing the RT priority.
6485 SYSCALL_DEFINE2(sched_getparam
, pid_t
, pid
, struct sched_param __user
*, param
)
6487 struct sched_param lp
;
6488 struct task_struct
*p
;
6491 if (!param
|| pid
< 0)
6494 read_lock(&tasklist_lock
);
6495 p
= find_process_by_pid(pid
);
6500 retval
= security_task_getscheduler(p
);
6504 lp
.sched_priority
= p
->rt_priority
;
6505 read_unlock(&tasklist_lock
);
6508 * This one might sleep, we cannot do it with a spinlock held ...
6510 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
6515 read_unlock(&tasklist_lock
);
6519 long sched_setaffinity(pid_t pid
, const struct cpumask
*in_mask
)
6521 cpumask_var_t cpus_allowed
, new_mask
;
6522 struct task_struct
*p
;
6526 read_lock(&tasklist_lock
);
6528 p
= find_process_by_pid(pid
);
6530 read_unlock(&tasklist_lock
);
6536 * It is not safe to call set_cpus_allowed with the
6537 * tasklist_lock held. We will bump the task_struct's
6538 * usage count and then drop tasklist_lock.
6541 read_unlock(&tasklist_lock
);
6543 if (!alloc_cpumask_var(&cpus_allowed
, GFP_KERNEL
)) {
6547 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
)) {
6549 goto out_free_cpus_allowed
;
6552 if (!check_same_owner(p
) && !capable(CAP_SYS_NICE
))
6555 retval
= security_task_setscheduler(p
, 0, NULL
);
6559 cpuset_cpus_allowed(p
, cpus_allowed
);
6560 cpumask_and(new_mask
, in_mask
, cpus_allowed
);
6562 retval
= set_cpus_allowed_ptr(p
, new_mask
);
6565 cpuset_cpus_allowed(p
, cpus_allowed
);
6566 if (!cpumask_subset(new_mask
, cpus_allowed
)) {
6568 * We must have raced with a concurrent cpuset
6569 * update. Just reset the cpus_allowed to the
6570 * cpuset's cpus_allowed
6572 cpumask_copy(new_mask
, cpus_allowed
);
6577 free_cpumask_var(new_mask
);
6578 out_free_cpus_allowed
:
6579 free_cpumask_var(cpus_allowed
);
6586 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
6587 struct cpumask
*new_mask
)
6589 if (len
< cpumask_size())
6590 cpumask_clear(new_mask
);
6591 else if (len
> cpumask_size())
6592 len
= cpumask_size();
6594 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
6598 * sys_sched_setaffinity - set the cpu affinity of a process
6599 * @pid: pid of the process
6600 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6601 * @user_mask_ptr: user-space pointer to the new cpu mask
6603 SYSCALL_DEFINE3(sched_setaffinity
, pid_t
, pid
, unsigned int, len
,
6604 unsigned long __user
*, user_mask_ptr
)
6606 cpumask_var_t new_mask
;
6609 if (!alloc_cpumask_var(&new_mask
, GFP_KERNEL
))
6612 retval
= get_user_cpu_mask(user_mask_ptr
, len
, new_mask
);
6614 retval
= sched_setaffinity(pid
, new_mask
);
6615 free_cpumask_var(new_mask
);
6619 long sched_getaffinity(pid_t pid
, struct cpumask
*mask
)
6621 struct task_struct
*p
;
6625 read_lock(&tasklist_lock
);
6628 p
= find_process_by_pid(pid
);
6632 retval
= security_task_getscheduler(p
);
6636 cpumask_and(mask
, &p
->cpus_allowed
, cpu_online_mask
);
6639 read_unlock(&tasklist_lock
);
6646 * sys_sched_getaffinity - get the cpu affinity of a process
6647 * @pid: pid of the process
6648 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6649 * @user_mask_ptr: user-space pointer to hold the current cpu mask
6651 SYSCALL_DEFINE3(sched_getaffinity
, pid_t
, pid
, unsigned int, len
,
6652 unsigned long __user
*, user_mask_ptr
)
6657 if (len
< cpumask_size())
6660 if (!alloc_cpumask_var(&mask
, GFP_KERNEL
))
6663 ret
= sched_getaffinity(pid
, mask
);
6665 if (copy_to_user(user_mask_ptr
, mask
, cpumask_size()))
6668 ret
= cpumask_size();
6670 free_cpumask_var(mask
);
6676 * sys_sched_yield - yield the current processor to other threads.
6678 * This function yields the current CPU to other tasks. If there are no
6679 * other threads running on this CPU then this function will return.
6681 SYSCALL_DEFINE0(sched_yield
)
6683 struct rq
*rq
= this_rq_lock();
6685 schedstat_inc(rq
, yld_count
);
6686 current
->sched_class
->yield_task(rq
);
6689 * Since we are going to call schedule() anyway, there's
6690 * no need to preempt or enable interrupts:
6692 spin_unlock_no_resched(&rq
->lock
);
6697 preempt_check_resched();
6702 #if defined(CONFIG_DEBUG_SPINLOCK_SLEEP) || defined(CONFIG_DEBUG_PREEMPT)
6703 void __might_sleep(char *file
, int line
)
6706 static unsigned long prev_jiffy
; /* ratelimiting */
6708 if ((!in_atomic() && !irqs_disabled()) ||
6709 system_state
!= SYSTEM_RUNNING
|| oops_in_progress
)
6712 if (debug_direct_keyboard
&& hardirq_count())
6715 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
6717 prev_jiffy
= jiffies
;
6720 "BUG: sleeping function called from invalid context at %s:%d\n",
6723 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6724 in_atomic(), irqs_disabled(),
6725 current
->pid
, current
->comm
);
6727 debug_show_held_locks(current
);
6728 if (irqs_disabled())
6729 print_irqtrace_events(current
);
6733 EXPORT_SYMBOL(__might_sleep
);
6736 static void __cond_resched(void)
6738 #if defined(CONFIG_DEBUG_SPINLOCK_SLEEP) || defined(CONFIG_DEBUG_PREEMPT)
6739 __might_sleep(__FILE__
, __LINE__
);
6742 * The BKS might be reacquired before we have dropped
6743 * PREEMPT_ACTIVE, which could trigger a second
6744 * cond_resched() call.
6747 local_irq_disable();
6748 add_preempt_count(PREEMPT_ACTIVE
);
6750 } while (need_resched());
6754 int __sched
_cond_resched(void)
6756 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
6757 system_state
== SYSTEM_RUNNING
) {
6763 EXPORT_SYMBOL(_cond_resched
);
6766 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
6767 * call schedule, and on return reacquire the lock.
6769 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
6770 * operations here to prevent schedule() from being called twice (once via
6771 * spin_unlock(), once by hand).
6773 int __cond_resched_raw_spinlock(raw_spinlock_t
*lock
)
6775 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
6778 if (spin_needbreak(lock
) || resched
) {
6779 spin_unlock_no_resched(lock
);
6780 if (resched
&& need_resched())
6789 EXPORT_SYMBOL(__cond_resched_raw_spinlock
);
6791 #ifdef CONFIG_PREEMPT_RT
6793 int __cond_resched_spinlock(spinlock_t
*lock
)
6795 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
6797 if (spin_needbreak(lock
) || resched
) {
6798 spin_unlock_no_resched(lock
);
6805 EXPORT_SYMBOL(__cond_resched_spinlock
);
6810 * Voluntarily preempt a process context that has softirqs disabled:
6812 int __sched
cond_resched_softirq(void)
6814 #ifndef CONFIG_PREEMPT_SOFTIRQS
6815 WARN_ON_ONCE(!in_softirq());
6819 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
6827 EXPORT_SYMBOL(cond_resched_softirq
);
6830 * Voluntarily preempt a softirq context (possible with softirq threading):
6832 int __sched
cond_resched_softirq_context(void)
6834 WARN_ON_ONCE(!in_softirq());
6836 if (softirq_need_resched() && system_state
== SYSTEM_RUNNING
) {
6837 raw_local_irq_disable();
6839 raw_local_irq_enable();
6846 EXPORT_SYMBOL(cond_resched_softirq_context
);
6849 * Preempt a hardirq context if necessary (possible with hardirq threading):
6851 int cond_resched_hardirq_context(void)
6853 WARN_ON_ONCE(!in_irq());
6854 WARN_ON_ONCE(!irqs_disabled());
6856 if (hardirq_need_resched()) {
6857 #ifndef CONFIG_PREEMPT_RT
6862 #ifndef CONFIG_PREEMPT_RT
6863 local_irq_disable();
6871 EXPORT_SYMBOL(cond_resched_hardirq_context
);
6873 #ifdef CONFIG_PREEMPT_VOLUNTARY
6875 int voluntary_preemption
= 1;
6877 EXPORT_SYMBOL(voluntary_preemption
);
6879 static int __init
voluntary_preempt_setup (char *str
)
6881 if (!strncmp(str
, "off", 3))
6882 voluntary_preemption
= 0;
6884 get_option(&str
, &voluntary_preemption
);
6885 if (!voluntary_preemption
)
6886 printk("turning off voluntary preemption!\n");
6891 __setup("voluntary-preempt=", voluntary_preempt_setup
);
6896 * yield - yield the current processor to other threads.
6898 * This is a shortcut for kernel-space yielding - it marks the
6899 * thread runnable and calls sys_sched_yield().
6901 void __sched
__yield(void)
6903 set_current_state(TASK_RUNNING
);
6907 void __sched
yield(void)
6909 static int once
= 1;
6912 * it's a bug to rely on yield() with RT priorities. We print
6913 * the first occurance after bootup ... this will still give
6914 * us an idea about the scope of the problem, without spamming
6917 if (once
&& rt_task(current
)) {
6919 printk(KERN_ERR
"BUG: %s:%d RT task yield()-ing!\n",
6920 current
->comm
, current
->pid
);
6925 EXPORT_SYMBOL(yield
);
6928 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6929 * that process accounting knows that this is a task in IO wait state.
6931 * But don't do that if it is a deliberate, throttling IO wait (this task
6932 * has set its backing_dev_info: the queue against which it should throttle)
6934 void __sched
io_schedule(void)
6936 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
6938 delayacct_blkio_start();
6939 atomic_inc(&rq
->nr_iowait
);
6941 atomic_dec(&rq
->nr_iowait
);
6942 delayacct_blkio_end();
6944 EXPORT_SYMBOL(io_schedule
);
6946 long __sched
io_schedule_timeout(long timeout
)
6948 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
6951 delayacct_blkio_start();
6952 atomic_inc(&rq
->nr_iowait
);
6953 ret
= schedule_timeout(timeout
);
6954 atomic_dec(&rq
->nr_iowait
);
6955 delayacct_blkio_end();
6960 * sys_sched_get_priority_max - return maximum RT priority.
6961 * @policy: scheduling class.
6963 * this syscall returns the maximum rt_priority that can be used
6964 * by a given scheduling class.
6966 SYSCALL_DEFINE1(sched_get_priority_max
, int, policy
)
6973 ret
= MAX_USER_RT_PRIO
-1;
6985 * sys_sched_get_priority_min - return minimum RT priority.
6986 * @policy: scheduling class.
6988 * this syscall returns the minimum rt_priority that can be used
6989 * by a given scheduling class.
6991 SYSCALL_DEFINE1(sched_get_priority_min
, int, policy
)
7009 * sys_sched_rr_get_interval - return the default timeslice of a process.
7010 * @pid: pid of the process.
7011 * @interval: userspace pointer to the timeslice value.
7013 * this syscall writes the default timeslice value of a given process
7014 * into the user-space timespec buffer. A value of '0' means infinity.
7016 SYSCALL_DEFINE2(sched_rr_get_interval
, pid_t
, pid
,
7017 struct timespec __user
*, interval
)
7019 struct task_struct
*p
;
7020 unsigned int time_slice
;
7028 read_lock(&tasklist_lock
);
7029 p
= find_process_by_pid(pid
);
7033 retval
= security_task_getscheduler(p
);
7038 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
7039 * tasks that are on an otherwise idle runqueue:
7042 if (p
->policy
== SCHED_RR
) {
7043 time_slice
= DEF_TIMESLICE
;
7044 } else if (p
->policy
!= SCHED_FIFO
) {
7045 struct sched_entity
*se
= &p
->se
;
7046 unsigned long flags
;
7049 rq
= task_rq_lock(p
, &flags
);
7050 if (rq
->cfs
.load
.weight
)
7051 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
7052 task_rq_unlock(rq
, &flags
);
7054 read_unlock(&tasklist_lock
);
7055 jiffies_to_timespec(time_slice
, &t
);
7056 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
7060 read_unlock(&tasklist_lock
);
7064 static const char stat_nam
[] = TASK_STATE_TO_CHAR_STR
;
7066 void sched_show_task(struct task_struct
*p
)
7068 unsigned long free
= 0;
7071 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
7072 printk("%-13.13s %c (%03lx) [%p]", p
->comm
,
7073 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?',
7074 (unsigned long) p
->state
, p
);
7075 #if BITS_PER_LONG == 32
7076 if (0 && (state
== TASK_RUNNING
))
7077 printk(KERN_CONT
" running ");
7079 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
7081 if (0 && (state
== TASK_RUNNING
))
7082 printk(KERN_CONT
" running task ");
7084 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
7088 else if (p
->se
.on_rq
)
7089 printk("[on rq #%d] ", task_cpu(p
));
7090 #ifdef CONFIG_DEBUG_STACK_USAGE
7091 free
= stack_not_used(p
);
7093 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
7094 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
7096 show_stack(p
, NULL
);
7099 void show_state_filter(unsigned long state_filter
)
7101 struct task_struct
*g
, *p
;
7104 #if BITS_PER_LONG == 32
7106 " task PC stack pid father\n");
7109 " task PC stack pid father\n");
7111 #ifdef CONFIG_PREEMPT_RT
7112 if (!read_trylock(&tasklist_lock
)) {
7113 printk("hm, tasklist_lock write-locked.\n");
7114 printk("ignoring ...\n");
7118 read_lock(&tasklist_lock
);
7121 do_each_thread(g
, p
) {
7123 * reset the NMI-timeout, listing all files on a slow
7124 * console might take alot of time:
7126 touch_nmi_watchdog();
7127 if (!state_filter
|| (p
->state
& state_filter
))
7129 } while_each_thread(g
, p
);
7131 touch_all_softlockup_watchdogs();
7133 #ifdef CONFIG_SCHED_DEBUG
7134 sysrq_sched_debug_show();
7137 read_unlock(&tasklist_lock
);
7139 * Only show locks if all tasks are dumped:
7141 if (state_filter
== -1)
7142 debug_show_all_locks();
7145 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
7147 idle
->sched_class
= &idle_sched_class
;
7151 * init_idle - set up an idle thread for a given CPU
7152 * @idle: task in question
7153 * @cpu: cpu the idle task belongs to
7155 * NOTE: this function does not set the idle thread's NEED_RESCHED
7156 * flag, to make booting more robust.
7158 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
7160 struct rq
*rq
= cpu_rq(cpu
);
7161 unsigned long flags
;
7163 spin_lock_irqsave(&rq
->lock
, flags
);
7166 idle
->se
.exec_start
= sched_clock();
7168 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
7169 cpumask_copy(&idle
->cpus_allowed
, cpumask_of(cpu
));
7170 __set_task_cpu(idle
, cpu
);
7172 rq
->curr
= rq
->idle
= idle
;
7173 #if defined(CONFIG_SMP)
7176 spin_unlock_irqrestore(&rq
->lock
, flags
);
7178 /* Set the preempt count _outside_ the spinlocks! */
7179 task_thread_info(idle
)->preempt_count
= 0;
7182 * The idle tasks have their own, simple scheduling class:
7184 idle
->sched_class
= &idle_sched_class
;
7185 ftrace_graph_init_task(idle
);
7189 * In a system that switches off the HZ timer nohz_cpu_mask
7190 * indicates which cpus entered this state. This is used
7191 * in the rcu update to wait only for active cpus. For system
7192 * which do not switch off the HZ timer nohz_cpu_mask should
7193 * always be CPU_BITS_NONE.
7195 cpumask_var_t nohz_cpu_mask
;
7198 * Increase the granularity value when there are more CPUs,
7199 * because with more CPUs the 'effective latency' as visible
7200 * to users decreases. But the relationship is not linear,
7201 * so pick a second-best guess by going with the log2 of the
7204 * This idea comes from the SD scheduler of Con Kolivas:
7206 static inline void sched_init_granularity(void)
7208 unsigned int factor
= 1 + ilog2(num_online_cpus());
7209 const unsigned long limit
= 200000000;
7211 sysctl_sched_min_granularity
*= factor
;
7212 if (sysctl_sched_min_granularity
> limit
)
7213 sysctl_sched_min_granularity
= limit
;
7215 sysctl_sched_latency
*= factor
;
7216 if (sysctl_sched_latency
> limit
)
7217 sysctl_sched_latency
= limit
;
7219 sysctl_sched_wakeup_granularity
*= factor
;
7221 sysctl_sched_shares_ratelimit
*= factor
;
7226 * This is how migration works:
7228 * 1) we queue a struct migration_req structure in the source CPU's
7229 * runqueue and wake up that CPU's migration thread.
7230 * 2) we down() the locked semaphore => thread blocks.
7231 * 3) migration thread wakes up (implicitly it forces the migrated
7232 * thread off the CPU)
7233 * 4) it gets the migration request and checks whether the migrated
7234 * task is still in the wrong runqueue.
7235 * 5) if it's in the wrong runqueue then the migration thread removes
7236 * it and puts it into the right queue.
7237 * 6) migration thread up()s the semaphore.
7238 * 7) we wake up and the migration is done.
7242 * Change a given task's CPU affinity. Migrate the thread to a
7243 * proper CPU and schedule it away if the CPU it's executing on
7244 * is removed from the allowed bitmask.
7246 * NOTE: the caller must have a valid reference to the task, the
7247 * task must not exit() & deallocate itself prematurely. The
7248 * call is not atomic; no spinlocks may be held.
7250 int set_cpus_allowed_ptr(struct task_struct
*p
, const struct cpumask
*new_mask
)
7252 struct migration_req req
;
7253 unsigned long flags
;
7257 rq
= task_rq_lock(p
, &flags
);
7258 if (!cpumask_intersects(new_mask
, cpu_online_mask
)) {
7263 if (unlikely((p
->flags
& PF_THREAD_BOUND
) && p
!= current
&&
7264 !cpumask_equal(&p
->cpus_allowed
, new_mask
))) {
7269 if (p
->sched_class
->set_cpus_allowed
)
7270 p
->sched_class
->set_cpus_allowed(p
, new_mask
);
7272 cpumask_copy(&p
->cpus_allowed
, new_mask
);
7273 p
->rt
.nr_cpus_allowed
= cpumask_weight(new_mask
);
7276 /* Can the task run on the task's current CPU? If so, we're done */
7277 if (cpumask_test_cpu(task_cpu(p
), new_mask
))
7280 if (migrate_task(p
, cpumask_any_and(cpu_online_mask
, new_mask
), &req
)) {
7281 /* Need help from migration thread: drop lock and wait. */
7282 task_rq_unlock(rq
, &flags
);
7283 wake_up_process(rq
->migration_thread
);
7284 wait_for_completion(&req
.done
);
7285 tlb_migrate_finish(p
->mm
);
7289 task_rq_unlock(rq
, &flags
);
7293 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr
);
7296 * Move (not current) task off this cpu, onto dest cpu. We're doing
7297 * this because either it can't run here any more (set_cpus_allowed()
7298 * away from this CPU, or CPU going down), or because we're
7299 * attempting to rebalance this task on exec (sched_exec).
7301 * So we race with normal scheduler movements, but that's OK, as long
7302 * as the task is no longer on this CPU.
7304 * Returns non-zero if task was successfully migrated.
7306 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
7308 struct rq
*rq_dest
, *rq_src
;
7309 unsigned long flags
;
7312 if (unlikely(!cpu_active(dest_cpu
)))
7316 * PREEMPT_RT: this relies on write_lock_irq(&tasklist_lock)
7317 * disabling interrupts - which on PREEMPT_RT does not do:
7319 local_irq_save(flags
);
7321 rq_src
= cpu_rq(src_cpu
);
7322 rq_dest
= cpu_rq(dest_cpu
);
7324 double_rq_lock(rq_src
, rq_dest
);
7325 /* Already moved. */
7326 if (task_cpu(p
) != src_cpu
)
7328 /* Affinity changed (again). */
7329 if (!cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
))
7332 on_rq
= p
->se
.on_rq
;
7334 deactivate_task(rq_src
, p
, 0);
7336 set_task_cpu(p
, dest_cpu
);
7338 activate_task(rq_dest
, p
, 0);
7339 check_preempt_curr(rq_dest
, p
, 0);
7344 double_rq_unlock(rq_src
, rq_dest
);
7345 local_irq_restore(flags
);
7351 * migration_thread - this is a highprio system thread that performs
7352 * thread migration by bumping thread off CPU then 'pushing' onto
7355 static int migration_thread(void *data
)
7357 int cpu
= (long)data
;
7361 BUG_ON(rq
->migration_thread
!= current
);
7363 set_current_state(TASK_INTERRUPTIBLE
);
7364 while (!kthread_should_stop()) {
7365 struct migration_req
*req
;
7366 struct list_head
*head
;
7368 spin_lock_irq(&rq
->lock
);
7370 if (cpu_is_offline(cpu
)) {
7371 spin_unlock_irq(&rq
->lock
);
7375 if (rq
->active_balance
) {
7376 active_load_balance(rq
, cpu
);
7377 rq
->active_balance
= 0;
7380 head
= &rq
->migration_queue
;
7382 if (list_empty(head
)) {
7383 spin_unlock_irq(&rq
->lock
);
7385 set_current_state(TASK_INTERRUPTIBLE
);
7388 req
= list_entry(head
->next
, struct migration_req
, list
);
7389 list_del_init(head
->next
);
7391 spin_unlock(&rq
->lock
);
7392 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
7395 complete(&req
->done
);
7397 __set_current_state(TASK_RUNNING
);
7401 /* Wait for kthread_stop */
7402 set_current_state(TASK_INTERRUPTIBLE
);
7403 while (!kthread_should_stop()) {
7405 set_current_state(TASK_INTERRUPTIBLE
);
7407 __set_current_state(TASK_RUNNING
);
7411 #ifdef CONFIG_HOTPLUG_CPU
7413 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
7417 local_irq_disable();
7418 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
7424 * Figure out where task on dead CPU should go, use force if necessary.
7426 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
7429 const struct cpumask
*nodemask
= cpumask_of_node(cpu_to_node(dead_cpu
));
7432 /* Look for allowed, online CPU in same node. */
7433 for_each_cpu_and(dest_cpu
, nodemask
, cpu_online_mask
)
7434 if (cpumask_test_cpu(dest_cpu
, &p
->cpus_allowed
))
7437 /* Any allowed, online CPU? */
7438 dest_cpu
= cpumask_any_and(&p
->cpus_allowed
, cpu_online_mask
);
7439 if (dest_cpu
< nr_cpu_ids
)
7442 /* No more Mr. Nice Guy. */
7443 if (dest_cpu
>= nr_cpu_ids
) {
7444 cpuset_cpus_allowed_locked(p
, &p
->cpus_allowed
);
7445 dest_cpu
= cpumask_any_and(cpu_online_mask
, &p
->cpus_allowed
);
7448 * Don't tell them about moving exiting tasks or
7449 * kernel threads (both mm NULL), since they never
7452 if (p
->mm
&& printk_ratelimit()) {
7453 printk(KERN_INFO
"process %d (%s) no "
7454 "longer affine to cpu%d\n",
7455 task_pid_nr(p
), p
->comm
, dead_cpu
);
7460 /* It can have affinity changed while we were choosing. */
7461 if (unlikely(!__migrate_task_irq(p
, dead_cpu
, dest_cpu
)))
7466 * While a dead CPU has no uninterruptible tasks queued at this point,
7467 * it might still have a nonzero ->nr_uninterruptible counter, because
7468 * for performance reasons the counter is not stricly tracking tasks to
7469 * their home CPUs. So we just add the counter to another CPU's counter,
7470 * to keep the global sum constant after CPU-down:
7472 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
7474 struct rq
*rq_dest
= cpu_rq(cpumask_any(cpu_online_mask
));
7475 unsigned long flags
;
7477 local_irq_save(flags
);
7478 double_rq_lock(rq_src
, rq_dest
);
7479 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
7480 rq_src
->nr_uninterruptible
= 0;
7481 double_rq_unlock(rq_src
, rq_dest
);
7482 local_irq_restore(flags
);
7485 /* Run through task list and migrate tasks from the dead cpu. */
7486 static void migrate_live_tasks(int src_cpu
)
7488 struct task_struct
*p
, *t
;
7490 read_lock(&tasklist_lock
);
7492 do_each_thread(t
, p
) {
7496 if (task_cpu(p
) == src_cpu
)
7497 move_task_off_dead_cpu(src_cpu
, p
);
7498 } while_each_thread(t
, p
);
7500 read_unlock(&tasklist_lock
);
7504 * Schedules idle task to be the next runnable task on current CPU.
7505 * It does so by boosting its priority to highest possible.
7506 * Used by CPU offline code.
7508 void sched_idle_next(void)
7510 int this_cpu
= smp_processor_id();
7511 struct rq
*rq
= cpu_rq(this_cpu
);
7512 struct task_struct
*p
= rq
->idle
;
7513 unsigned long flags
;
7515 /* cpu has to be offline */
7516 BUG_ON(cpu_online(this_cpu
));
7519 * Strictly not necessary since rest of the CPUs are stopped by now
7520 * and interrupts disabled on the current cpu.
7522 spin_lock_irqsave(&rq
->lock
, flags
);
7524 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
7526 update_rq_clock(rq
);
7527 activate_task(rq
, p
, 0);
7529 spin_unlock_irqrestore(&rq
->lock
, flags
);
7533 * Ensures that the idle task is using init_mm right before its cpu goes
7536 void idle_task_exit(void)
7538 struct mm_struct
*mm
= current
->active_mm
;
7540 BUG_ON(cpu_online(smp_processor_id()));
7543 switch_mm(mm
, &init_mm
, current
);
7544 #ifdef CONFIG_PREEMPT_RT
7551 /* called under rq->lock with disabled interrupts */
7552 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
7554 struct rq
*rq
= cpu_rq(dead_cpu
);
7556 /* Must be exiting, otherwise would be on tasklist. */
7557 BUG_ON(!p
->exit_state
);
7559 /* Cannot have done final schedule yet: would have vanished. */
7560 BUG_ON(p
->state
== TASK_DEAD
);
7565 * Drop lock around migration; if someone else moves it,
7566 * that's OK. No task can be added to this CPU, so iteration is
7569 spin_unlock_irq(&rq
->lock
);
7570 move_task_off_dead_cpu(dead_cpu
, p
);
7571 spin_lock_irq(&rq
->lock
);
7576 /* release_task() removes task from tasklist, so we won't find dead tasks. */
7577 static void migrate_dead_tasks(unsigned int dead_cpu
)
7579 struct rq
*rq
= cpu_rq(dead_cpu
);
7580 struct task_struct
*next
;
7583 if (!rq
->nr_running
)
7585 update_rq_clock(rq
);
7586 next
= pick_next_task(rq
);
7589 next
->sched_class
->put_prev_task(rq
, next
);
7590 migrate_dead(dead_cpu
, next
);
7596 * remove the tasks which were accounted by rq from calc_load_tasks.
7598 static void calc_global_load_remove(struct rq
*rq
)
7600 atomic_long_sub(rq
->calc_load_active
, &calc_load_tasks
);
7602 #endif /* CONFIG_HOTPLUG_CPU */
7604 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
7606 static struct ctl_table sd_ctl_dir
[] = {
7608 .procname
= "sched_domain",
7614 static struct ctl_table sd_ctl_root
[] = {
7616 .ctl_name
= CTL_KERN
,
7617 .procname
= "kernel",
7619 .child
= sd_ctl_dir
,
7624 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
7626 struct ctl_table
*entry
=
7627 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
7632 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
7634 struct ctl_table
*entry
;
7637 * In the intermediate directories, both the child directory and
7638 * procname are dynamically allocated and could fail but the mode
7639 * will always be set. In the lowest directory the names are
7640 * static strings and all have proc handlers.
7642 for (entry
= *tablep
; entry
->mode
; entry
++) {
7644 sd_free_ctl_entry(&entry
->child
);
7645 if (entry
->proc_handler
== NULL
)
7646 kfree(entry
->procname
);
7654 set_table_entry(struct ctl_table
*entry
,
7655 const char *procname
, void *data
, int maxlen
,
7656 mode_t mode
, proc_handler
*proc_handler
)
7658 entry
->procname
= procname
;
7660 entry
->maxlen
= maxlen
;
7662 entry
->proc_handler
= proc_handler
;
7665 static struct ctl_table
*
7666 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
7668 struct ctl_table
*table
= sd_alloc_ctl_entry(13);
7673 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
7674 sizeof(long), 0644, proc_doulongvec_minmax
);
7675 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
7676 sizeof(long), 0644, proc_doulongvec_minmax
);
7677 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
7678 sizeof(int), 0644, proc_dointvec_minmax
);
7679 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
7680 sizeof(int), 0644, proc_dointvec_minmax
);
7681 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
7682 sizeof(int), 0644, proc_dointvec_minmax
);
7683 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
7684 sizeof(int), 0644, proc_dointvec_minmax
);
7685 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
7686 sizeof(int), 0644, proc_dointvec_minmax
);
7687 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
7688 sizeof(int), 0644, proc_dointvec_minmax
);
7689 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
7690 sizeof(int), 0644, proc_dointvec_minmax
);
7691 set_table_entry(&table
[9], "cache_nice_tries",
7692 &sd
->cache_nice_tries
,
7693 sizeof(int), 0644, proc_dointvec_minmax
);
7694 set_table_entry(&table
[10], "flags", &sd
->flags
,
7695 sizeof(int), 0644, proc_dointvec_minmax
);
7696 set_table_entry(&table
[11], "name", sd
->name
,
7697 CORENAME_MAX_SIZE
, 0444, proc_dostring
);
7698 /* &table[12] is terminator */
7703 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
7705 struct ctl_table
*entry
, *table
;
7706 struct sched_domain
*sd
;
7707 int domain_num
= 0, i
;
7710 for_each_domain(cpu
, sd
)
7712 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
7717 for_each_domain(cpu
, sd
) {
7718 snprintf(buf
, 32, "domain%d", i
);
7719 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
7721 entry
->child
= sd_alloc_ctl_domain_table(sd
);
7728 static struct ctl_table_header
*sd_sysctl_header
;
7729 static void register_sched_domain_sysctl(void)
7731 int i
, cpu_num
= num_online_cpus();
7732 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
7735 WARN_ON(sd_ctl_dir
[0].child
);
7736 sd_ctl_dir
[0].child
= entry
;
7741 for_each_online_cpu(i
) {
7742 snprintf(buf
, 32, "cpu%d", i
);
7743 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
7745 entry
->child
= sd_alloc_ctl_cpu_table(i
);
7749 WARN_ON(sd_sysctl_header
);
7750 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
7753 /* may be called multiple times per register */
7754 static void unregister_sched_domain_sysctl(void)
7756 if (sd_sysctl_header
)
7757 unregister_sysctl_table(sd_sysctl_header
);
7758 sd_sysctl_header
= NULL
;
7759 if (sd_ctl_dir
[0].child
)
7760 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
7763 static void register_sched_domain_sysctl(void)
7766 static void unregister_sched_domain_sysctl(void)
7771 static void set_rq_online(struct rq
*rq
)
7774 const struct sched_class
*class;
7776 cpumask_set_cpu(rq
->cpu
, rq
->rd
->online
);
7779 for_each_class(class) {
7780 if (class->rq_online
)
7781 class->rq_online(rq
);
7786 static void set_rq_offline(struct rq
*rq
)
7789 const struct sched_class
*class;
7791 for_each_class(class) {
7792 if (class->rq_offline
)
7793 class->rq_offline(rq
);
7796 cpumask_clear_cpu(rq
->cpu
, rq
->rd
->online
);
7802 * migration_call - callback that gets triggered when a CPU is added.
7803 * Here we can start up the necessary migration thread for the new CPU.
7805 static int __cpuinit
7806 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
7808 struct task_struct
*p
;
7809 int cpu
= (long)hcpu
;
7810 unsigned long flags
;
7815 case CPU_UP_PREPARE
:
7816 case CPU_UP_PREPARE_FROZEN
:
7817 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
7820 kthread_bind(p
, cpu
);
7821 /* Must be high prio: stop_machine expects to yield to it. */
7822 rq
= task_rq_lock(p
, &flags
);
7823 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
7824 task_rq_unlock(rq
, &flags
);
7825 cpu_rq(cpu
)->migration_thread
= p
;
7829 case CPU_ONLINE_FROZEN
:
7830 /* Strictly unnecessary, as first user will wake it. */
7831 wake_up_process(cpu_rq(cpu
)->migration_thread
);
7833 /* Update our root-domain */
7835 spin_lock_irqsave(&rq
->lock
, flags
);
7836 rq
->calc_load_update
= calc_load_update
;
7837 rq
->calc_load_active
= 0;
7839 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
7843 spin_unlock_irqrestore(&rq
->lock
, flags
);
7846 #ifdef CONFIG_HOTPLUG_CPU
7847 case CPU_UP_CANCELED
:
7848 case CPU_UP_CANCELED_FROZEN
:
7849 if (!cpu_rq(cpu
)->migration_thread
)
7851 /* Unbind it from offline cpu so it can run. Fall thru. */
7852 kthread_bind(cpu_rq(cpu
)->migration_thread
,
7853 cpumask_any(cpu_online_mask
));
7854 kthread_stop(cpu_rq(cpu
)->migration_thread
);
7855 cpu_rq(cpu
)->migration_thread
= NULL
;
7859 case CPU_DEAD_FROZEN
:
7860 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
7861 migrate_live_tasks(cpu
);
7863 kthread_stop(rq
->migration_thread
);
7864 rq
->migration_thread
= NULL
;
7865 /* Idle task back to normal (off runqueue, low prio) */
7866 spin_lock_irq(&rq
->lock
);
7867 update_rq_clock(rq
);
7868 deactivate_task(rq
, rq
->idle
, 0);
7869 rq
->idle
->static_prio
= MAX_PRIO
;
7870 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
7871 rq
->idle
->sched_class
= &idle_sched_class
;
7872 migrate_dead_tasks(cpu
);
7873 spin_unlock_irq(&rq
->lock
);
7875 migrate_nr_uninterruptible(rq
);
7876 BUG_ON(rq
->nr_running
!= 0);
7877 calc_global_load_remove(rq
);
7879 * No need to migrate the tasks: it was best-effort if
7880 * they didn't take sched_hotcpu_mutex. Just wake up
7883 spin_lock_irq(&rq
->lock
);
7884 while (!list_empty(&rq
->migration_queue
)) {
7885 struct migration_req
*req
;
7887 req
= list_entry(rq
->migration_queue
.next
,
7888 struct migration_req
, list
);
7889 list_del_init(&req
->list
);
7890 spin_unlock_irq(&rq
->lock
);
7891 complete(&req
->done
);
7892 spin_lock_irq(&rq
->lock
);
7894 spin_unlock_irq(&rq
->lock
);
7898 case CPU_DYING_FROZEN
:
7899 /* Update our root-domain */
7901 spin_lock_irqsave(&rq
->lock
, flags
);
7903 BUG_ON(!cpumask_test_cpu(cpu
, rq
->rd
->span
));
7906 spin_unlock_irqrestore(&rq
->lock
, flags
);
7913 /* Register at highest priority so that task migration (migrate_all_tasks)
7914 * happens before everything else.
7916 static struct notifier_block __cpuinitdata migration_notifier
= {
7917 .notifier_call
= migration_call
,
7921 static int __init
migration_init(void)
7923 void *cpu
= (void *)(long)smp_processor_id();
7926 /* Start one for the boot CPU: */
7927 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
7928 BUG_ON(err
== NOTIFY_BAD
);
7929 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
7930 register_cpu_notifier(&migration_notifier
);
7934 early_initcall(migration_init
);
7939 #ifdef CONFIG_SCHED_DEBUG
7941 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
,
7942 struct cpumask
*groupmask
)
7944 struct sched_group
*group
= sd
->groups
;
7947 cpulist_scnprintf(str
, sizeof(str
), sched_domain_span(sd
));
7948 cpumask_clear(groupmask
);
7950 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
7952 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
7953 printk("does not load-balance\n");
7955 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
7960 printk(KERN_CONT
"span %s level %s\n", str
, sd
->name
);
7962 if (!cpumask_test_cpu(cpu
, sched_domain_span(sd
))) {
7963 printk(KERN_ERR
"ERROR: domain->span does not contain "
7966 if (!cpumask_test_cpu(cpu
, sched_group_cpus(group
))) {
7967 printk(KERN_ERR
"ERROR: domain->groups does not contain"
7971 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
7975 printk(KERN_ERR
"ERROR: group is NULL\n");
7979 if (!group
->__cpu_power
) {
7980 printk(KERN_CONT
"\n");
7981 printk(KERN_ERR
"ERROR: domain->cpu_power not "
7986 if (!cpumask_weight(sched_group_cpus(group
))) {
7987 printk(KERN_CONT
"\n");
7988 printk(KERN_ERR
"ERROR: empty group\n");
7992 if (cpumask_intersects(groupmask
, sched_group_cpus(group
))) {
7993 printk(KERN_CONT
"\n");
7994 printk(KERN_ERR
"ERROR: repeated CPUs\n");
7998 cpumask_or(groupmask
, groupmask
, sched_group_cpus(group
));
8000 cpulist_scnprintf(str
, sizeof(str
), sched_group_cpus(group
));
8001 printk(KERN_CONT
" %s", str
);
8003 group
= group
->next
;
8004 } while (group
!= sd
->groups
);
8005 printk(KERN_CONT
"\n");
8007 if (!cpumask_equal(sched_domain_span(sd
), groupmask
))
8008 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
8011 !cpumask_subset(groupmask
, sched_domain_span(sd
->parent
)))
8012 printk(KERN_ERR
"ERROR: parent span is not a superset "
8013 "of domain->span\n");
8017 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
8019 cpumask_var_t groupmask
;
8023 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
8027 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
8029 if (!alloc_cpumask_var(&groupmask
, GFP_KERNEL
)) {
8030 printk(KERN_DEBUG
"Cannot load-balance (out of memory)\n");
8035 if (sched_domain_debug_one(sd
, cpu
, level
, groupmask
))
8042 free_cpumask_var(groupmask
);
8044 #else /* !CONFIG_SCHED_DEBUG */
8045 # define sched_domain_debug(sd, cpu) do { } while (0)
8046 #endif /* CONFIG_SCHED_DEBUG */
8048 static int sd_degenerate(struct sched_domain
*sd
)
8050 if (cpumask_weight(sched_domain_span(sd
)) == 1)
8053 /* Following flags need at least 2 groups */
8054 if (sd
->flags
& (SD_LOAD_BALANCE
|
8055 SD_BALANCE_NEWIDLE
|
8059 SD_SHARE_PKG_RESOURCES
)) {
8060 if (sd
->groups
!= sd
->groups
->next
)
8064 /* Following flags don't use groups */
8065 if (sd
->flags
& (SD_WAKE_IDLE
|
8074 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
8076 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
8078 if (sd_degenerate(parent
))
8081 if (!cpumask_equal(sched_domain_span(sd
), sched_domain_span(parent
)))
8084 /* Does parent contain flags not in child? */
8085 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
8086 if (cflags
& SD_WAKE_AFFINE
)
8087 pflags
&= ~SD_WAKE_BALANCE
;
8088 /* Flags needing groups don't count if only 1 group in parent */
8089 if (parent
->groups
== parent
->groups
->next
) {
8090 pflags
&= ~(SD_LOAD_BALANCE
|
8091 SD_BALANCE_NEWIDLE
|
8095 SD_SHARE_PKG_RESOURCES
);
8096 if (nr_node_ids
== 1)
8097 pflags
&= ~SD_SERIALIZE
;
8099 if (~cflags
& pflags
)
8105 static void free_rootdomain(struct root_domain
*rd
)
8107 cpupri_cleanup(&rd
->cpupri
);
8109 free_cpumask_var(rd
->rto_mask
);
8110 free_cpumask_var(rd
->online
);
8111 free_cpumask_var(rd
->span
);
8115 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
8117 struct root_domain
*old_rd
= NULL
;
8118 unsigned long flags
;
8120 spin_lock_irqsave(&rq
->lock
, flags
);
8125 if (cpumask_test_cpu(rq
->cpu
, old_rd
->online
))
8128 cpumask_clear_cpu(rq
->cpu
, old_rd
->span
);
8131 * If we dont want to free the old_rt yet then
8132 * set old_rd to NULL to skip the freeing later
8135 if (!atomic_dec_and_test(&old_rd
->refcount
))
8139 atomic_inc(&rd
->refcount
);
8142 cpumask_set_cpu(rq
->cpu
, rd
->span
);
8143 if (cpumask_test_cpu(rq
->cpu
, cpu_online_mask
))
8146 spin_unlock_irqrestore(&rq
->lock
, flags
);
8149 free_rootdomain(old_rd
);
8152 static int __init_refok
init_rootdomain(struct root_domain
*rd
, bool bootmem
)
8154 memset(rd
, 0, sizeof(*rd
));
8157 alloc_bootmem_cpumask_var(&def_root_domain
.span
);
8158 alloc_bootmem_cpumask_var(&def_root_domain
.online
);
8159 alloc_bootmem_cpumask_var(&def_root_domain
.rto_mask
);
8160 cpupri_init(&rd
->cpupri
, true);
8164 if (!alloc_cpumask_var(&rd
->span
, GFP_KERNEL
))
8166 if (!alloc_cpumask_var(&rd
->online
, GFP_KERNEL
))
8168 if (!alloc_cpumask_var(&rd
->rto_mask
, GFP_KERNEL
))
8171 if (cpupri_init(&rd
->cpupri
, false) != 0)
8176 free_cpumask_var(rd
->rto_mask
);
8178 free_cpumask_var(rd
->online
);
8180 free_cpumask_var(rd
->span
);
8185 static void init_defrootdomain(void)
8187 init_rootdomain(&def_root_domain
, true);
8189 atomic_set(&def_root_domain
.refcount
, 1);
8192 static struct root_domain
*alloc_rootdomain(void)
8194 struct root_domain
*rd
;
8196 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
8200 if (init_rootdomain(rd
, false) != 0) {
8209 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
8210 * hold the hotplug lock.
8213 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
8215 struct rq
*rq
= cpu_rq(cpu
);
8216 struct sched_domain
*tmp
;
8218 /* Remove the sched domains which do not contribute to scheduling. */
8219 for (tmp
= sd
; tmp
; ) {
8220 struct sched_domain
*parent
= tmp
->parent
;
8224 if (sd_parent_degenerate(tmp
, parent
)) {
8225 tmp
->parent
= parent
->parent
;
8227 parent
->parent
->child
= tmp
;
8232 if (sd
&& sd_degenerate(sd
)) {
8238 sched_domain_debug(sd
, cpu
);
8240 rq_attach_root(rq
, rd
);
8241 rcu_assign_pointer(rq
->sd
, sd
);
8244 /* cpus with isolated domains */
8245 static cpumask_var_t cpu_isolated_map
;
8247 /* Setup the mask of cpus configured for isolated domains */
8248 static int __init
isolated_cpu_setup(char *str
)
8250 cpulist_parse(str
, cpu_isolated_map
);
8254 __setup("isolcpus=", isolated_cpu_setup
);
8257 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
8258 * to a function which identifies what group(along with sched group) a CPU
8259 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
8260 * (due to the fact that we keep track of groups covered with a struct cpumask).
8262 * init_sched_build_groups will build a circular linked list of the groups
8263 * covered by the given span, and will set each group's ->cpumask correctly,
8264 * and ->cpu_power to 0.
8267 init_sched_build_groups(const struct cpumask
*span
,
8268 const struct cpumask
*cpu_map
,
8269 int (*group_fn
)(int cpu
, const struct cpumask
*cpu_map
,
8270 struct sched_group
**sg
,
8271 struct cpumask
*tmpmask
),
8272 struct cpumask
*covered
, struct cpumask
*tmpmask
)
8274 struct sched_group
*first
= NULL
, *last
= NULL
;
8277 cpumask_clear(covered
);
8279 for_each_cpu(i
, span
) {
8280 struct sched_group
*sg
;
8281 int group
= group_fn(i
, cpu_map
, &sg
, tmpmask
);
8284 if (cpumask_test_cpu(i
, covered
))
8287 cpumask_clear(sched_group_cpus(sg
));
8288 sg
->__cpu_power
= 0;
8290 for_each_cpu(j
, span
) {
8291 if (group_fn(j
, cpu_map
, NULL
, tmpmask
) != group
)
8294 cpumask_set_cpu(j
, covered
);
8295 cpumask_set_cpu(j
, sched_group_cpus(sg
));
8306 #define SD_NODES_PER_DOMAIN 16
8311 * find_next_best_node - find the next node to include in a sched_domain
8312 * @node: node whose sched_domain we're building
8313 * @used_nodes: nodes already in the sched_domain
8315 * Find the next node to include in a given scheduling domain. Simply
8316 * finds the closest node not already in the @used_nodes map.
8318 * Should use nodemask_t.
8320 static int find_next_best_node(int node
, nodemask_t
*used_nodes
)
8322 int i
, n
, val
, min_val
, best_node
= 0;
8326 for (i
= 0; i
< nr_node_ids
; i
++) {
8327 /* Start at @node */
8328 n
= (node
+ i
) % nr_node_ids
;
8330 if (!nr_cpus_node(n
))
8333 /* Skip already used nodes */
8334 if (node_isset(n
, *used_nodes
))
8337 /* Simple min distance search */
8338 val
= node_distance(node
, n
);
8340 if (val
< min_val
) {
8346 node_set(best_node
, *used_nodes
);
8351 * sched_domain_node_span - get a cpumask for a node's sched_domain
8352 * @node: node whose cpumask we're constructing
8353 * @span: resulting cpumask
8355 * Given a node, construct a good cpumask for its sched_domain to span. It
8356 * should be one that prevents unnecessary balancing, but also spreads tasks
8359 static void sched_domain_node_span(int node
, struct cpumask
*span
)
8361 nodemask_t used_nodes
;
8364 cpumask_clear(span
);
8365 nodes_clear(used_nodes
);
8367 cpumask_or(span
, span
, cpumask_of_node(node
));
8368 node_set(node
, used_nodes
);
8370 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
8371 int next_node
= find_next_best_node(node
, &used_nodes
);
8373 cpumask_or(span
, span
, cpumask_of_node(next_node
));
8376 #endif /* CONFIG_NUMA */
8378 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
8381 * The cpus mask in sched_group and sched_domain hangs off the end.
8382 * FIXME: use cpumask_var_t or dynamic percpu alloc to avoid wasting space
8383 * for nr_cpu_ids < CONFIG_NR_CPUS.
8385 struct static_sched_group
{
8386 struct sched_group sg
;
8387 DECLARE_BITMAP(cpus
, CONFIG_NR_CPUS
);
8390 struct static_sched_domain
{
8391 struct sched_domain sd
;
8392 DECLARE_BITMAP(span
, CONFIG_NR_CPUS
);
8396 * SMT sched-domains:
8398 #ifdef CONFIG_SCHED_SMT
8399 static DEFINE_PER_CPU(struct static_sched_domain
, cpu_domains
);
8400 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_cpus
);
8403 cpu_to_cpu_group(int cpu
, const struct cpumask
*cpu_map
,
8404 struct sched_group
**sg
, struct cpumask
*unused
)
8407 *sg
= &per_cpu(sched_group_cpus
, cpu
).sg
;
8410 #endif /* CONFIG_SCHED_SMT */
8413 * multi-core sched-domains:
8415 #ifdef CONFIG_SCHED_MC
8416 static DEFINE_PER_CPU(struct static_sched_domain
, core_domains
);
8417 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_core
);
8418 #endif /* CONFIG_SCHED_MC */
8420 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
8422 cpu_to_core_group(int cpu
, const struct cpumask
*cpu_map
,
8423 struct sched_group
**sg
, struct cpumask
*mask
)
8427 cpumask_and(mask
, topology_thread_cpumask(cpu
), cpu_map
);
8428 group
= cpumask_first(mask
);
8430 *sg
= &per_cpu(sched_group_core
, group
).sg
;
8433 #elif defined(CONFIG_SCHED_MC)
8435 cpu_to_core_group(int cpu
, const struct cpumask
*cpu_map
,
8436 struct sched_group
**sg
, struct cpumask
*unused
)
8439 *sg
= &per_cpu(sched_group_core
, cpu
).sg
;
8444 static DEFINE_PER_CPU(struct static_sched_domain
, phys_domains
);
8445 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_phys
);
8448 cpu_to_phys_group(int cpu
, const struct cpumask
*cpu_map
,
8449 struct sched_group
**sg
, struct cpumask
*mask
)
8452 #ifdef CONFIG_SCHED_MC
8453 cpumask_and(mask
, cpu_coregroup_mask(cpu
), cpu_map
);
8454 group
= cpumask_first(mask
);
8455 #elif defined(CONFIG_SCHED_SMT)
8456 cpumask_and(mask
, topology_thread_cpumask(cpu
), cpu_map
);
8457 group
= cpumask_first(mask
);
8462 *sg
= &per_cpu(sched_group_phys
, group
).sg
;
8468 * The init_sched_build_groups can't handle what we want to do with node
8469 * groups, so roll our own. Now each node has its own list of groups which
8470 * gets dynamically allocated.
8472 static DEFINE_PER_CPU(struct static_sched_domain
, node_domains
);
8473 static struct sched_group
***sched_group_nodes_bycpu
;
8475 static DEFINE_PER_CPU(struct static_sched_domain
, allnodes_domains
);
8476 static DEFINE_PER_CPU(struct static_sched_group
, sched_group_allnodes
);
8478 static int cpu_to_allnodes_group(int cpu
, const struct cpumask
*cpu_map
,
8479 struct sched_group
**sg
,
8480 struct cpumask
*nodemask
)
8484 cpumask_and(nodemask
, cpumask_of_node(cpu_to_node(cpu
)), cpu_map
);
8485 group
= cpumask_first(nodemask
);
8488 *sg
= &per_cpu(sched_group_allnodes
, group
).sg
;
8492 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
8494 struct sched_group
*sg
= group_head
;
8500 for_each_cpu(j
, sched_group_cpus(sg
)) {
8501 struct sched_domain
*sd
;
8503 sd
= &per_cpu(phys_domains
, j
).sd
;
8504 if (j
!= cpumask_first(sched_group_cpus(sd
->groups
))) {
8506 * Only add "power" once for each
8512 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
8515 } while (sg
!= group_head
);
8517 #endif /* CONFIG_NUMA */
8520 /* Free memory allocated for various sched_group structures */
8521 static void free_sched_groups(const struct cpumask
*cpu_map
,
8522 struct cpumask
*nodemask
)
8526 for_each_cpu(cpu
, cpu_map
) {
8527 struct sched_group
**sched_group_nodes
8528 = sched_group_nodes_bycpu
[cpu
];
8530 if (!sched_group_nodes
)
8533 for (i
= 0; i
< nr_node_ids
; i
++) {
8534 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
8536 cpumask_and(nodemask
, cpumask_of_node(i
), cpu_map
);
8537 if (cpumask_empty(nodemask
))
8547 if (oldsg
!= sched_group_nodes
[i
])
8550 kfree(sched_group_nodes
);
8551 sched_group_nodes_bycpu
[cpu
] = NULL
;
8554 #else /* !CONFIG_NUMA */
8555 static void free_sched_groups(const struct cpumask
*cpu_map
,
8556 struct cpumask
*nodemask
)
8559 #endif /* CONFIG_NUMA */
8562 * Initialize sched groups cpu_power.
8564 * cpu_power indicates the capacity of sched group, which is used while
8565 * distributing the load between different sched groups in a sched domain.
8566 * Typically cpu_power for all the groups in a sched domain will be same unless
8567 * there are asymmetries in the topology. If there are asymmetries, group
8568 * having more cpu_power will pickup more load compared to the group having
8571 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
8572 * the maximum number of tasks a group can handle in the presence of other idle
8573 * or lightly loaded groups in the same sched domain.
8575 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
8577 struct sched_domain
*child
;
8578 struct sched_group
*group
;
8580 WARN_ON(!sd
|| !sd
->groups
);
8582 if (cpu
!= cpumask_first(sched_group_cpus(sd
->groups
)))
8587 sd
->groups
->__cpu_power
= 0;
8590 * For perf policy, if the groups in child domain share resources
8591 * (for example cores sharing some portions of the cache hierarchy
8592 * or SMT), then set this domain groups cpu_power such that each group
8593 * can handle only one task, when there are other idle groups in the
8594 * same sched domain.
8596 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
8598 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
8599 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
8604 * add cpu_power of each child group to this groups cpu_power
8606 group
= child
->groups
;
8608 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
8609 group
= group
->next
;
8610 } while (group
!= child
->groups
);
8614 * Initializers for schedule domains
8615 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
8618 #ifdef CONFIG_SCHED_DEBUG
8619 # define SD_INIT_NAME(sd, type) sd->name = #type
8621 # define SD_INIT_NAME(sd, type) do { } while (0)
8624 #define SD_INIT(sd, type) sd_init_##type(sd)
8626 #define SD_INIT_FUNC(type) \
8627 static noinline void sd_init_##type(struct sched_domain *sd) \
8629 memset(sd, 0, sizeof(*sd)); \
8630 *sd = SD_##type##_INIT; \
8631 sd->level = SD_LV_##type; \
8632 SD_INIT_NAME(sd, type); \
8637 SD_INIT_FUNC(ALLNODES
)
8640 #ifdef CONFIG_SCHED_SMT
8641 SD_INIT_FUNC(SIBLING
)
8643 #ifdef CONFIG_SCHED_MC
8647 static int default_relax_domain_level
= -1;
8649 static int __init
setup_relax_domain_level(char *str
)
8653 val
= simple_strtoul(str
, NULL
, 0);
8654 if (val
< SD_LV_MAX
)
8655 default_relax_domain_level
= val
;
8659 __setup("relax_domain_level=", setup_relax_domain_level
);
8661 static void set_domain_attribute(struct sched_domain
*sd
,
8662 struct sched_domain_attr
*attr
)
8666 if (!attr
|| attr
->relax_domain_level
< 0) {
8667 if (default_relax_domain_level
< 0)
8670 request
= default_relax_domain_level
;
8672 request
= attr
->relax_domain_level
;
8673 if (request
< sd
->level
) {
8674 /* turn off idle balance on this domain */
8675 sd
->flags
&= ~(SD_WAKE_IDLE
|SD_BALANCE_NEWIDLE
);
8677 /* turn on idle balance on this domain */
8678 sd
->flags
|= (SD_WAKE_IDLE_FAR
|SD_BALANCE_NEWIDLE
);
8683 * Build sched domains for a given set of cpus and attach the sched domains
8684 * to the individual cpus
8686 static int __build_sched_domains(const struct cpumask
*cpu_map
,
8687 struct sched_domain_attr
*attr
)
8689 int i
, err
= -ENOMEM
;
8690 struct root_domain
*rd
;
8691 cpumask_var_t nodemask
, this_sibling_map
, this_core_map
, send_covered
,
8694 cpumask_var_t domainspan
, covered
, notcovered
;
8695 struct sched_group
**sched_group_nodes
= NULL
;
8696 int sd_allnodes
= 0;
8698 if (!alloc_cpumask_var(&domainspan
, GFP_KERNEL
))
8700 if (!alloc_cpumask_var(&covered
, GFP_KERNEL
))
8701 goto free_domainspan
;
8702 if (!alloc_cpumask_var(¬covered
, GFP_KERNEL
))
8706 if (!alloc_cpumask_var(&nodemask
, GFP_KERNEL
))
8707 goto free_notcovered
;
8708 if (!alloc_cpumask_var(&this_sibling_map
, GFP_KERNEL
))
8710 if (!alloc_cpumask_var(&this_core_map
, GFP_KERNEL
))
8711 goto free_this_sibling_map
;
8712 if (!alloc_cpumask_var(&send_covered
, GFP_KERNEL
))
8713 goto free_this_core_map
;
8714 if (!alloc_cpumask_var(&tmpmask
, GFP_KERNEL
))
8715 goto free_send_covered
;
8719 * Allocate the per-node list of sched groups
8721 sched_group_nodes
= kcalloc(nr_node_ids
, sizeof(struct sched_group
*),
8723 if (!sched_group_nodes
) {
8724 printk(KERN_WARNING
"Can not alloc sched group node list\n");
8729 rd
= alloc_rootdomain();
8731 printk(KERN_WARNING
"Cannot alloc root domain\n");
8732 goto free_sched_groups
;
8736 sched_group_nodes_bycpu
[cpumask_first(cpu_map
)] = sched_group_nodes
;
8740 * Set up domains for cpus specified by the cpu_map.
8742 for_each_cpu(i
, cpu_map
) {
8743 struct sched_domain
*sd
= NULL
, *p
;
8745 cpumask_and(nodemask
, cpumask_of_node(cpu_to_node(i
)), cpu_map
);
8748 if (cpumask_weight(cpu_map
) >
8749 SD_NODES_PER_DOMAIN
*cpumask_weight(nodemask
)) {
8750 sd
= &per_cpu(allnodes_domains
, i
).sd
;
8751 SD_INIT(sd
, ALLNODES
);
8752 set_domain_attribute(sd
, attr
);
8753 cpumask_copy(sched_domain_span(sd
), cpu_map
);
8754 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
8760 sd
= &per_cpu(node_domains
, i
).sd
;
8762 set_domain_attribute(sd
, attr
);
8763 sched_domain_node_span(cpu_to_node(i
), sched_domain_span(sd
));
8767 cpumask_and(sched_domain_span(sd
),
8768 sched_domain_span(sd
), cpu_map
);
8772 sd
= &per_cpu(phys_domains
, i
).sd
;
8774 set_domain_attribute(sd
, attr
);
8775 cpumask_copy(sched_domain_span(sd
), nodemask
);
8779 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
8781 #ifdef CONFIG_SCHED_MC
8783 sd
= &per_cpu(core_domains
, i
).sd
;
8785 set_domain_attribute(sd
, attr
);
8786 cpumask_and(sched_domain_span(sd
), cpu_map
,
8787 cpu_coregroup_mask(i
));
8790 cpu_to_core_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
8793 #ifdef CONFIG_SCHED_SMT
8795 sd
= &per_cpu(cpu_domains
, i
).sd
;
8796 SD_INIT(sd
, SIBLING
);
8797 set_domain_attribute(sd
, attr
);
8798 cpumask_and(sched_domain_span(sd
),
8799 topology_thread_cpumask(i
), cpu_map
);
8802 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
, tmpmask
);
8806 #ifdef CONFIG_SCHED_SMT
8807 /* Set up CPU (sibling) groups */
8808 for_each_cpu(i
, cpu_map
) {
8809 cpumask_and(this_sibling_map
,
8810 topology_thread_cpumask(i
), cpu_map
);
8811 if (i
!= cpumask_first(this_sibling_map
))
8814 init_sched_build_groups(this_sibling_map
, cpu_map
,
8816 send_covered
, tmpmask
);
8820 #ifdef CONFIG_SCHED_MC
8821 /* Set up multi-core groups */
8822 for_each_cpu(i
, cpu_map
) {
8823 cpumask_and(this_core_map
, cpu_coregroup_mask(i
), cpu_map
);
8824 if (i
!= cpumask_first(this_core_map
))
8827 init_sched_build_groups(this_core_map
, cpu_map
,
8829 send_covered
, tmpmask
);
8833 /* Set up physical groups */
8834 for (i
= 0; i
< nr_node_ids
; i
++) {
8835 cpumask_and(nodemask
, cpumask_of_node(i
), cpu_map
);
8836 if (cpumask_empty(nodemask
))
8839 init_sched_build_groups(nodemask
, cpu_map
,
8841 send_covered
, tmpmask
);
8845 /* Set up node groups */
8847 init_sched_build_groups(cpu_map
, cpu_map
,
8848 &cpu_to_allnodes_group
,
8849 send_covered
, tmpmask
);
8852 for (i
= 0; i
< nr_node_ids
; i
++) {
8853 /* Set up node groups */
8854 struct sched_group
*sg
, *prev
;
8857 cpumask_clear(covered
);
8858 cpumask_and(nodemask
, cpumask_of_node(i
), cpu_map
);
8859 if (cpumask_empty(nodemask
)) {
8860 sched_group_nodes
[i
] = NULL
;
8864 sched_domain_node_span(i
, domainspan
);
8865 cpumask_and(domainspan
, domainspan
, cpu_map
);
8867 sg
= kmalloc_node(sizeof(struct sched_group
) + cpumask_size(),
8870 printk(KERN_WARNING
"Can not alloc domain group for "
8874 sched_group_nodes
[i
] = sg
;
8875 for_each_cpu(j
, nodemask
) {
8876 struct sched_domain
*sd
;
8878 sd
= &per_cpu(node_domains
, j
).sd
;
8881 sg
->__cpu_power
= 0;
8882 cpumask_copy(sched_group_cpus(sg
), nodemask
);
8884 cpumask_or(covered
, covered
, nodemask
);
8887 for (j
= 0; j
< nr_node_ids
; j
++) {
8888 int n
= (i
+ j
) % nr_node_ids
;
8890 cpumask_complement(notcovered
, covered
);
8891 cpumask_and(tmpmask
, notcovered
, cpu_map
);
8892 cpumask_and(tmpmask
, tmpmask
, domainspan
);
8893 if (cpumask_empty(tmpmask
))
8896 cpumask_and(tmpmask
, tmpmask
, cpumask_of_node(n
));
8897 if (cpumask_empty(tmpmask
))
8900 sg
= kmalloc_node(sizeof(struct sched_group
) +
8905 "Can not alloc domain group for node %d\n", j
);
8908 sg
->__cpu_power
= 0;
8909 cpumask_copy(sched_group_cpus(sg
), tmpmask
);
8910 sg
->next
= prev
->next
;
8911 cpumask_or(covered
, covered
, tmpmask
);
8918 /* Calculate CPU power for physical packages and nodes */
8919 #ifdef CONFIG_SCHED_SMT
8920 for_each_cpu(i
, cpu_map
) {
8921 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
).sd
;
8923 init_sched_groups_power(i
, sd
);
8926 #ifdef CONFIG_SCHED_MC
8927 for_each_cpu(i
, cpu_map
) {
8928 struct sched_domain
*sd
= &per_cpu(core_domains
, i
).sd
;
8930 init_sched_groups_power(i
, sd
);
8934 for_each_cpu(i
, cpu_map
) {
8935 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
).sd
;
8937 init_sched_groups_power(i
, sd
);
8941 for (i
= 0; i
< nr_node_ids
; i
++)
8942 init_numa_sched_groups_power(sched_group_nodes
[i
]);
8945 struct sched_group
*sg
;
8947 cpu_to_allnodes_group(cpumask_first(cpu_map
), cpu_map
, &sg
,
8949 init_numa_sched_groups_power(sg
);
8953 /* Attach the domains */
8954 for_each_cpu(i
, cpu_map
) {
8955 struct sched_domain
*sd
;
8956 #ifdef CONFIG_SCHED_SMT
8957 sd
= &per_cpu(cpu_domains
, i
).sd
;
8958 #elif defined(CONFIG_SCHED_MC)
8959 sd
= &per_cpu(core_domains
, i
).sd
;
8961 sd
= &per_cpu(phys_domains
, i
).sd
;
8963 cpu_attach_domain(sd
, rd
, i
);
8969 free_cpumask_var(tmpmask
);
8971 free_cpumask_var(send_covered
);
8973 free_cpumask_var(this_core_map
);
8974 free_this_sibling_map
:
8975 free_cpumask_var(this_sibling_map
);
8977 free_cpumask_var(nodemask
);
8980 free_cpumask_var(notcovered
);
8982 free_cpumask_var(covered
);
8984 free_cpumask_var(domainspan
);
8991 kfree(sched_group_nodes
);
8997 free_sched_groups(cpu_map
, tmpmask
);
8998 free_rootdomain(rd
);
9003 static int build_sched_domains(const struct cpumask
*cpu_map
)
9005 return __build_sched_domains(cpu_map
, NULL
);
9008 static struct cpumask
*doms_cur
; /* current sched domains */
9009 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
9010 static struct sched_domain_attr
*dattr_cur
;
9011 /* attribues of custom domains in 'doms_cur' */
9014 * Special case: If a kmalloc of a doms_cur partition (array of
9015 * cpumask) fails, then fallback to a single sched domain,
9016 * as determined by the single cpumask fallback_doms.
9018 static cpumask_var_t fallback_doms
;
9021 * arch_update_cpu_topology lets virtualized architectures update the
9022 * cpu core maps. It is supposed to return 1 if the topology changed
9023 * or 0 if it stayed the same.
9025 int __attribute__((weak
)) arch_update_cpu_topology(void)
9031 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
9032 * For now this just excludes isolated cpus, but could be used to
9033 * exclude other special cases in the future.
9035 static int arch_init_sched_domains(const struct cpumask
*cpu_map
)
9039 arch_update_cpu_topology();
9041 doms_cur
= kmalloc(cpumask_size(), GFP_KERNEL
);
9043 doms_cur
= fallback_doms
;
9044 cpumask_andnot(doms_cur
, cpu_map
, cpu_isolated_map
);
9046 err
= build_sched_domains(doms_cur
);
9047 register_sched_domain_sysctl();
9052 static void arch_destroy_sched_domains(const struct cpumask
*cpu_map
,
9053 struct cpumask
*tmpmask
)
9055 free_sched_groups(cpu_map
, tmpmask
);
9059 * Detach sched domains from a group of cpus specified in cpu_map
9060 * These cpus will now be attached to the NULL domain
9062 static void detach_destroy_domains(const struct cpumask
*cpu_map
)
9064 /* Save because hotplug lock held. */
9065 static DECLARE_BITMAP(tmpmask
, CONFIG_NR_CPUS
);
9068 for_each_cpu(i
, cpu_map
)
9069 cpu_attach_domain(NULL
, &def_root_domain
, i
);
9070 synchronize_sched();
9071 arch_destroy_sched_domains(cpu_map
, to_cpumask(tmpmask
));
9074 /* handle null as "default" */
9075 static int dattrs_equal(struct sched_domain_attr
*cur
, int idx_cur
,
9076 struct sched_domain_attr
*new, int idx_new
)
9078 struct sched_domain_attr tmp
;
9085 return !memcmp(cur
? (cur
+ idx_cur
) : &tmp
,
9086 new ? (new + idx_new
) : &tmp
,
9087 sizeof(struct sched_domain_attr
));
9091 * Partition sched domains as specified by the 'ndoms_new'
9092 * cpumasks in the array doms_new[] of cpumasks. This compares
9093 * doms_new[] to the current sched domain partitioning, doms_cur[].
9094 * It destroys each deleted domain and builds each new domain.
9096 * 'doms_new' is an array of cpumask's of length 'ndoms_new'.
9097 * The masks don't intersect (don't overlap.) We should setup one
9098 * sched domain for each mask. CPUs not in any of the cpumasks will
9099 * not be load balanced. If the same cpumask appears both in the
9100 * current 'doms_cur' domains and in the new 'doms_new', we can leave
9103 * The passed in 'doms_new' should be kmalloc'd. This routine takes
9104 * ownership of it and will kfree it when done with it. If the caller
9105 * failed the kmalloc call, then it can pass in doms_new == NULL &&
9106 * ndoms_new == 1, and partition_sched_domains() will fallback to
9107 * the single partition 'fallback_doms', it also forces the domains
9110 * If doms_new == NULL it will be replaced with cpu_online_mask.
9111 * ndoms_new == 0 is a special case for destroying existing domains,
9112 * and it will not create the default domain.
9114 * Call with hotplug lock held
9116 /* FIXME: Change to struct cpumask *doms_new[] */
9117 void partition_sched_domains(int ndoms_new
, struct cpumask
*doms_new
,
9118 struct sched_domain_attr
*dattr_new
)
9123 mutex_lock(&sched_domains_mutex
);
9125 /* always unregister in case we don't destroy any domains */
9126 unregister_sched_domain_sysctl();
9128 /* Let architecture update cpu core mappings. */
9129 new_topology
= arch_update_cpu_topology();
9131 n
= doms_new
? ndoms_new
: 0;
9133 /* Destroy deleted domains */
9134 for (i
= 0; i
< ndoms_cur
; i
++) {
9135 for (j
= 0; j
< n
&& !new_topology
; j
++) {
9136 if (cpumask_equal(&doms_cur
[i
], &doms_new
[j
])
9137 && dattrs_equal(dattr_cur
, i
, dattr_new
, j
))
9140 /* no match - a current sched domain not in new doms_new[] */
9141 detach_destroy_domains(doms_cur
+ i
);
9146 if (doms_new
== NULL
) {
9148 doms_new
= fallback_doms
;
9149 cpumask_andnot(&doms_new
[0], cpu_online_mask
, cpu_isolated_map
);
9150 WARN_ON_ONCE(dattr_new
);
9153 /* Build new domains */
9154 for (i
= 0; i
< ndoms_new
; i
++) {
9155 for (j
= 0; j
< ndoms_cur
&& !new_topology
; j
++) {
9156 if (cpumask_equal(&doms_new
[i
], &doms_cur
[j
])
9157 && dattrs_equal(dattr_new
, i
, dattr_cur
, j
))
9160 /* no match - add a new doms_new */
9161 __build_sched_domains(doms_new
+ i
,
9162 dattr_new
? dattr_new
+ i
: NULL
);
9167 /* Remember the new sched domains */
9168 if (doms_cur
!= fallback_doms
)
9170 kfree(dattr_cur
); /* kfree(NULL) is safe */
9171 doms_cur
= doms_new
;
9172 dattr_cur
= dattr_new
;
9173 ndoms_cur
= ndoms_new
;
9175 register_sched_domain_sysctl();
9177 mutex_unlock(&sched_domains_mutex
);
9180 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
9181 static void arch_reinit_sched_domains(void)
9185 /* Destroy domains first to force the rebuild */
9186 partition_sched_domains(0, NULL
, NULL
);
9188 rebuild_sched_domains();
9192 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
9194 unsigned int level
= 0;
9196 if (sscanf(buf
, "%u", &level
) != 1)
9200 * level is always be positive so don't check for
9201 * level < POWERSAVINGS_BALANCE_NONE which is 0
9202 * What happens on 0 or 1 byte write,
9203 * need to check for count as well?
9206 if (level
>= MAX_POWERSAVINGS_BALANCE_LEVELS
)
9210 sched_smt_power_savings
= level
;
9212 sched_mc_power_savings
= level
;
9214 arch_reinit_sched_domains();
9219 #ifdef CONFIG_SCHED_MC
9220 static ssize_t
sched_mc_power_savings_show(struct sysdev_class
*class,
9223 return sprintf(page
, "%u\n", sched_mc_power_savings
);
9225 static ssize_t
sched_mc_power_savings_store(struct sysdev_class
*class,
9226 const char *buf
, size_t count
)
9228 return sched_power_savings_store(buf
, count
, 0);
9230 static SYSDEV_CLASS_ATTR(sched_mc_power_savings
, 0644,
9231 sched_mc_power_savings_show
,
9232 sched_mc_power_savings_store
);
9235 #ifdef CONFIG_SCHED_SMT
9236 static ssize_t
sched_smt_power_savings_show(struct sysdev_class
*dev
,
9239 return sprintf(page
, "%u\n", sched_smt_power_savings
);
9241 static ssize_t
sched_smt_power_savings_store(struct sysdev_class
*dev
,
9242 const char *buf
, size_t count
)
9244 return sched_power_savings_store(buf
, count
, 1);
9246 static SYSDEV_CLASS_ATTR(sched_smt_power_savings
, 0644,
9247 sched_smt_power_savings_show
,
9248 sched_smt_power_savings_store
);
9251 int __init
sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
9255 #ifdef CONFIG_SCHED_SMT
9257 err
= sysfs_create_file(&cls
->kset
.kobj
,
9258 &attr_sched_smt_power_savings
.attr
);
9260 #ifdef CONFIG_SCHED_MC
9261 if (!err
&& mc_capable())
9262 err
= sysfs_create_file(&cls
->kset
.kobj
,
9263 &attr_sched_mc_power_savings
.attr
);
9267 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
9269 #ifndef CONFIG_CPUSETS
9271 * Add online and remove offline CPUs from the scheduler domains.
9272 * When cpusets are enabled they take over this function.
9274 static int update_sched_domains(struct notifier_block
*nfb
,
9275 unsigned long action
, void *hcpu
)
9279 case CPU_ONLINE_FROZEN
:
9281 case CPU_DEAD_FROZEN
:
9282 partition_sched_domains(1, NULL
, NULL
);
9291 static int update_runtime(struct notifier_block
*nfb
,
9292 unsigned long action
, void *hcpu
)
9294 int cpu
= (int)(long)hcpu
;
9297 case CPU_DOWN_PREPARE
:
9298 case CPU_DOWN_PREPARE_FROZEN
:
9299 disable_runtime(cpu_rq(cpu
));
9302 case CPU_DOWN_FAILED
:
9303 case CPU_DOWN_FAILED_FROZEN
:
9305 case CPU_ONLINE_FROZEN
:
9306 enable_runtime(cpu_rq(cpu
));
9314 void __init
sched_init_smp(void)
9316 cpumask_var_t non_isolated_cpus
;
9318 alloc_cpumask_var(&non_isolated_cpus
, GFP_KERNEL
);
9320 #if defined(CONFIG_NUMA)
9321 sched_group_nodes_bycpu
= kzalloc(nr_cpu_ids
* sizeof(void **),
9323 BUG_ON(sched_group_nodes_bycpu
== NULL
);
9326 mutex_lock(&sched_domains_mutex
);
9327 arch_init_sched_domains(cpu_online_mask
);
9328 cpumask_andnot(non_isolated_cpus
, cpu_possible_mask
, cpu_isolated_map
);
9329 if (cpumask_empty(non_isolated_cpus
))
9330 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus
);
9331 mutex_unlock(&sched_domains_mutex
);
9334 #ifndef CONFIG_CPUSETS
9335 /* XXX: Theoretical race here - CPU may be hotplugged now */
9336 hotcpu_notifier(update_sched_domains
, 0);
9339 /* RT runtime code needs to handle some hotplug events */
9340 hotcpu_notifier(update_runtime
, 0);
9344 /* Move init over to a non-isolated CPU */
9345 if (set_cpus_allowed_ptr(current
, non_isolated_cpus
) < 0)
9347 sched_init_granularity();
9348 free_cpumask_var(non_isolated_cpus
);
9350 alloc_cpumask_var(&fallback_doms
, GFP_KERNEL
);
9351 init_sched_rt_class();
9354 void __init
sched_init_smp(void)
9356 sched_init_granularity();
9358 #endif /* CONFIG_SMP */
9360 int in_sched_functions(unsigned long addr
)
9362 return in_lock_functions(addr
) ||
9363 (addr
>= (unsigned long)__sched_text_start
9364 && addr
< (unsigned long)__sched_text_end
);
9367 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
9369 cfs_rq
->tasks_timeline
= RB_ROOT
;
9370 INIT_LIST_HEAD(&cfs_rq
->tasks
);
9371 #ifdef CONFIG_FAIR_GROUP_SCHED
9374 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
9377 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
9379 struct rt_prio_array
*array
;
9382 array
= &rt_rq
->active
;
9383 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
9384 INIT_LIST_HEAD(array
->queue
+ i
);
9385 __clear_bit(i
, array
->bitmap
);
9387 /* delimiter for bitsearch: */
9388 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
9390 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
9391 rt_rq
->highest_prio
.curr
= MAX_RT_PRIO
;
9393 rt_rq
->highest_prio
.next
= MAX_RT_PRIO
;
9397 rt_rq
->rt_nr_migratory
= 0;
9398 rt_rq
->overloaded
= 0;
9399 plist_head_init(&rq
->rt
.pushable_tasks
, &rq
->lock
);
9403 rt_rq
->rt_throttled
= 0;
9404 rt_rq
->rt_runtime
= 0;
9405 spin_lock_init(&rt_rq
->rt_runtime_lock
);
9407 #ifdef CONFIG_RT_GROUP_SCHED
9408 rt_rq
->rt_nr_boosted
= 0;
9413 #ifdef CONFIG_SCHED_CBS
9414 static void init_cbs_rq(struct cbs_rq
*cbs_rq
, struct rq
*rq
)
9416 cbs_rq
->tasks_timeline
= RB_ROOT
;
9417 cbs_rq
->min_deadline
= (u64
)(-(1LL << 20));
9420 #define init_cbs_rq(...)
9424 #ifdef CONFIG_FAIR_GROUP_SCHED
9425 static void init_tg_cfs_entry(struct task_group
*tg
, struct cfs_rq
*cfs_rq
,
9426 struct sched_entity
*se
, int cpu
, int add
,
9427 struct sched_entity
*parent
)
9429 struct rq
*rq
= cpu_rq(cpu
);
9430 tg
->cfs_rq
[cpu
] = cfs_rq
;
9431 init_cfs_rq(cfs_rq
, rq
);
9434 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
9437 /* se could be NULL for init_task_group */
9442 se
->cfs_rq
= &rq
->cfs
;
9444 se
->cfs_rq
= parent
->my_q
;
9447 se
->load
.weight
= tg
->shares
;
9448 se
->load
.inv_weight
= 0;
9449 se
->parent
= parent
;
9453 #ifdef CONFIG_RT_GROUP_SCHED
9454 static void init_tg_rt_entry(struct task_group
*tg
, struct rt_rq
*rt_rq
,
9455 struct sched_rt_entity
*rt_se
, int cpu
, int add
,
9456 struct sched_rt_entity
*parent
)
9458 struct rq
*rq
= cpu_rq(cpu
);
9460 tg
->rt_rq
[cpu
] = rt_rq
;
9461 init_rt_rq(rt_rq
, rq
);
9463 rt_rq
->rt_se
= rt_se
;
9464 rt_rq
->rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
9466 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
9468 tg
->rt_se
[cpu
] = rt_se
;
9473 rt_se
->rt_rq
= &rq
->rt
;
9475 rt_se
->rt_rq
= parent
->my_q
;
9477 rt_se
->my_q
= rt_rq
;
9478 rt_se
->parent
= parent
;
9479 INIT_LIST_HEAD(&rt_se
->run_list
);
9483 void __init
sched_init(void)
9486 unsigned long alloc_size
= 0, ptr
;
9488 #ifdef CONFIG_FAIR_GROUP_SCHED
9489 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
9491 #ifdef CONFIG_RT_GROUP_SCHED
9492 alloc_size
+= 2 * nr_cpu_ids
* sizeof(void **);
9494 #ifdef CONFIG_USER_SCHED
9497 #ifdef CONFIG_CPUMASK_OFFSTACK
9498 alloc_size
+= num_possible_cpus() * cpumask_size();
9501 * As sched_init() is called before page_alloc is setup,
9502 * we use alloc_bootmem().
9505 ptr
= (unsigned long)alloc_bootmem(alloc_size
);
9507 #ifdef CONFIG_FAIR_GROUP_SCHED
9508 init_task_group
.se
= (struct sched_entity
**)ptr
;
9509 ptr
+= nr_cpu_ids
* sizeof(void **);
9511 init_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
9512 ptr
+= nr_cpu_ids
* sizeof(void **);
9514 #ifdef CONFIG_USER_SCHED
9515 root_task_group
.se
= (struct sched_entity
**)ptr
;
9516 ptr
+= nr_cpu_ids
* sizeof(void **);
9518 root_task_group
.cfs_rq
= (struct cfs_rq
**)ptr
;
9519 ptr
+= nr_cpu_ids
* sizeof(void **);
9520 #endif /* CONFIG_USER_SCHED */
9521 #endif /* CONFIG_FAIR_GROUP_SCHED */
9522 #ifdef CONFIG_RT_GROUP_SCHED
9523 init_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
9524 ptr
+= nr_cpu_ids
* sizeof(void **);
9526 init_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
9527 ptr
+= nr_cpu_ids
* sizeof(void **);
9529 #ifdef CONFIG_USER_SCHED
9530 root_task_group
.rt_se
= (struct sched_rt_entity
**)ptr
;
9531 ptr
+= nr_cpu_ids
* sizeof(void **);
9533 root_task_group
.rt_rq
= (struct rt_rq
**)ptr
;
9534 ptr
+= nr_cpu_ids
* sizeof(void **);
9535 #endif /* CONFIG_USER_SCHED */
9536 #endif /* CONFIG_RT_GROUP_SCHED */
9537 #ifdef CONFIG_CPUMASK_OFFSTACK
9538 for_each_possible_cpu(i
) {
9539 per_cpu(load_balance_tmpmask
, i
) = (void *)ptr
;
9540 ptr
+= cpumask_size();
9542 #endif /* CONFIG_CPUMASK_OFFSTACK */
9546 init_defrootdomain();
9549 init_rt_bandwidth(&def_rt_bandwidth
,
9550 global_rt_period(), global_rt_runtime());
9552 #ifdef CONFIG_RT_GROUP_SCHED
9553 init_rt_bandwidth(&init_task_group
.rt_bandwidth
,
9554 global_rt_period(), global_rt_runtime());
9555 #ifdef CONFIG_USER_SCHED
9556 init_rt_bandwidth(&root_task_group
.rt_bandwidth
,
9557 global_rt_period(), RUNTIME_INF
);
9558 #endif /* CONFIG_USER_SCHED */
9559 #endif /* CONFIG_RT_GROUP_SCHED */
9561 #ifdef CONFIG_GROUP_SCHED
9562 list_add(&init_task_group
.list
, &task_groups
);
9563 INIT_LIST_HEAD(&init_task_group
.children
);
9565 #ifdef CONFIG_USER_SCHED
9566 INIT_LIST_HEAD(&root_task_group
.children
);
9567 init_task_group
.parent
= &root_task_group
;
9568 list_add(&init_task_group
.siblings
, &root_task_group
.children
);
9569 #endif /* CONFIG_USER_SCHED */
9570 #endif /* CONFIG_GROUP_SCHED */
9572 for_each_possible_cpu(i
) {
9576 spin_lock_init(&rq
->lock
);
9578 rq
->calc_load_active
= 0;
9579 rq
->calc_load_update
= jiffies
+ LOAD_FREQ
;
9580 init_cfs_rq(&rq
->cfs
, rq
);
9581 init_rt_rq(&rq
->rt
, rq
);
9582 #ifdef CONFIG_SCHED_CBS
9583 init_cbs_rq(&rq
->cbs
, rq
);
9585 #ifdef CONFIG_FAIR_GROUP_SCHED
9586 init_task_group
.shares
= init_task_group_load
;
9587 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
9588 #ifdef CONFIG_CGROUP_SCHED
9590 * How much cpu bandwidth does init_task_group get?
9592 * In case of task-groups formed thr' the cgroup filesystem, it
9593 * gets 100% of the cpu resources in the system. This overall
9594 * system cpu resource is divided among the tasks of
9595 * init_task_group and its child task-groups in a fair manner,
9596 * based on each entity's (task or task-group's) weight
9597 * (se->load.weight).
9599 * In other words, if init_task_group has 10 tasks of weight
9600 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9601 * then A0's share of the cpu resource is:
9603 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9605 * We achieve this by letting init_task_group's tasks sit
9606 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
9608 init_tg_cfs_entry(&init_task_group
, &rq
->cfs
, NULL
, i
, 1, NULL
);
9609 #elif defined CONFIG_USER_SCHED
9610 root_task_group
.shares
= NICE_0_LOAD
;
9611 init_tg_cfs_entry(&root_task_group
, &rq
->cfs
, NULL
, i
, 0, NULL
);
9613 * In case of task-groups formed thr' the user id of tasks,
9614 * init_task_group represents tasks belonging to root user.
9615 * Hence it forms a sibling of all subsequent groups formed.
9616 * In this case, init_task_group gets only a fraction of overall
9617 * system cpu resource, based on the weight assigned to root
9618 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
9619 * by letting tasks of init_task_group sit in a separate cfs_rq
9620 * (init_cfs_rq) and having one entity represent this group of
9621 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
9623 init_tg_cfs_entry(&init_task_group
,
9624 &per_cpu(init_cfs_rq
, i
),
9625 &per_cpu(init_sched_entity
, i
), i
, 1,
9626 root_task_group
.se
[i
]);
9629 #endif /* CONFIG_FAIR_GROUP_SCHED */
9631 rq
->rt
.rt_runtime
= def_rt_bandwidth
.rt_runtime
;
9632 #ifdef CONFIG_RT_GROUP_SCHED
9633 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
9634 #ifdef CONFIG_CGROUP_SCHED
9635 init_tg_rt_entry(&init_task_group
, &rq
->rt
, NULL
, i
, 1, NULL
);
9636 #elif defined CONFIG_USER_SCHED
9637 init_tg_rt_entry(&root_task_group
, &rq
->rt
, NULL
, i
, 0, NULL
);
9638 init_tg_rt_entry(&init_task_group
,
9639 &per_cpu(init_rt_rq
, i
),
9640 &per_cpu(init_sched_rt_entity
, i
), i
, 1,
9641 root_task_group
.rt_se
[i
]);
9645 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
9646 rq
->cpu_load
[j
] = 0;
9650 rq
->active_balance
= 0;
9651 rq
->next_balance
= jiffies
;
9655 rq
->migration_thread
= NULL
;
9656 INIT_LIST_HEAD(&rq
->migration_queue
);
9657 rq_attach_root(rq
, &def_root_domain
);
9660 atomic_set(&rq
->nr_iowait
, 0);
9663 set_load_weight(&init_task
);
9665 #ifdef CONFIG_PREEMPT_NOTIFIERS
9666 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
9670 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
);
9673 #ifdef CONFIG_RT_MUTEXES
9674 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
9678 * The boot idle thread does lazy MMU switching as well:
9680 atomic_inc(&init_mm
.mm_count
);
9681 enter_lazy_tlb(&init_mm
, current
);
9683 #ifdef CONFIG_PREEMPT_RT
9684 printk("Real-Time Preemption Support (C) 2004-2007 Ingo Molnar\n");
9687 * Make us the idle thread. Technically, schedule() should not be
9688 * called from this thread, however somewhere below it might be,
9689 * but because we are the idle thread, we just pick up running again
9690 * when this runqueue becomes "idle".
9692 init_idle(current
, smp_processor_id());
9694 calc_load_update
= jiffies
+ LOAD_FREQ
;
9697 * During early bootup we pretend to be a normal task:
9699 current
->sched_class
= &fair_sched_class
;
9701 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
9702 alloc_bootmem_cpumask_var(&nohz_cpu_mask
);
9705 alloc_bootmem_cpumask_var(&nohz
.cpu_mask
);
9707 alloc_bootmem_cpumask_var(&cpu_isolated_map
);
9710 scheduler_running
= 1;
9713 #ifdef CONFIG_MAGIC_SYSRQ
9714 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
9718 update_rq_clock(rq
);
9719 on_rq
= p
->se
.on_rq
;
9721 deactivate_task(rq
, p
, 0);
9722 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
9724 activate_task(rq
, p
, 0);
9725 resched_task(rq
->curr
);
9729 void normalize_rt_tasks(void)
9731 struct task_struct
*g
, *p
;
9732 unsigned long flags
;
9735 read_lock_irqsave(&tasklist_lock
, flags
);
9736 do_each_thread(g
, p
) {
9738 * Only normalize user tasks:
9743 p
->se
.exec_start
= 0;
9744 #ifdef CONFIG_SCHEDSTATS
9745 p
->se
.wait_start
= 0;
9746 p
->se
.sleep_start
= 0;
9747 p
->se
.block_start
= 0;
9752 * Renice negative nice level userspace
9755 if (TASK_NICE(p
) < 0 && p
->mm
)
9756 set_user_nice(p
, 0);
9760 spin_lock(&p
->pi_lock
);
9761 rq
= __task_rq_lock(p
);
9763 normalize_task(rq
, p
);
9765 __task_rq_unlock(rq
);
9766 spin_unlock(&p
->pi_lock
);
9767 } while_each_thread(g
, p
);
9769 read_unlock_irqrestore(&tasklist_lock
, flags
);
9772 #endif /* CONFIG_MAGIC_SYSRQ */
9776 * These functions are only useful for the IA64 MCA handling.
9778 * They can only be called when the whole system has been
9779 * stopped - every CPU needs to be quiescent, and no scheduling
9780 * activity can take place. Using them for anything else would
9781 * be a serious bug, and as a result, they aren't even visible
9782 * under any other configuration.
9786 * curr_task - return the current task for a given cpu.
9787 * @cpu: the processor in question.
9789 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9791 struct task_struct
*curr_task(int cpu
)
9793 return cpu_curr(cpu
);
9797 * set_curr_task - set the current task for a given cpu.
9798 * @cpu: the processor in question.
9799 * @p: the task pointer to set.
9801 * Description: This function must only be used when non-maskable interrupts
9802 * are serviced on a separate stack. It allows the architecture to switch the
9803 * notion of the current task on a cpu in a non-blocking manner. This function
9804 * must be called with all CPU's synchronized, and interrupts disabled, the
9805 * and caller must save the original value of the current task (see
9806 * curr_task() above) and restore that value before reenabling interrupts and
9807 * re-starting the system.
9809 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9811 void set_curr_task(int cpu
, struct task_struct
*p
)
9818 #ifdef CONFIG_FAIR_GROUP_SCHED
9819 static void free_fair_sched_group(struct task_group
*tg
)
9823 for_each_possible_cpu(i
) {
9825 kfree(tg
->cfs_rq
[i
]);
9835 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
9837 struct cfs_rq
*cfs_rq
;
9838 struct sched_entity
*se
;
9842 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * nr_cpu_ids
, GFP_KERNEL
);
9845 tg
->se
= kzalloc(sizeof(se
) * nr_cpu_ids
, GFP_KERNEL
);
9849 tg
->shares
= NICE_0_LOAD
;
9851 for_each_possible_cpu(i
) {
9854 cfs_rq
= kzalloc_node(sizeof(struct cfs_rq
),
9855 GFP_KERNEL
, cpu_to_node(i
));
9859 se
= kzalloc_node(sizeof(struct sched_entity
),
9860 GFP_KERNEL
, cpu_to_node(i
));
9864 init_tg_cfs_entry(tg
, cfs_rq
, se
, i
, 0, parent
->se
[i
]);
9873 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
9875 list_add_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
,
9876 &cpu_rq(cpu
)->leaf_cfs_rq_list
);
9879 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
9881 list_del_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
);
9883 #else /* !CONFG_FAIR_GROUP_SCHED */
9884 static inline void free_fair_sched_group(struct task_group
*tg
)
9889 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
9894 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
9898 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
9901 #endif /* CONFIG_FAIR_GROUP_SCHED */
9903 #ifdef CONFIG_RT_GROUP_SCHED
9904 static void free_rt_sched_group(struct task_group
*tg
)
9908 destroy_rt_bandwidth(&tg
->rt_bandwidth
);
9910 for_each_possible_cpu(i
) {
9912 kfree(tg
->rt_rq
[i
]);
9914 kfree(tg
->rt_se
[i
]);
9922 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
9924 struct rt_rq
*rt_rq
;
9925 struct sched_rt_entity
*rt_se
;
9929 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * nr_cpu_ids
, GFP_KERNEL
);
9932 tg
->rt_se
= kzalloc(sizeof(rt_se
) * nr_cpu_ids
, GFP_KERNEL
);
9936 init_rt_bandwidth(&tg
->rt_bandwidth
,
9937 ktime_to_ns(def_rt_bandwidth
.rt_period
), 0);
9939 for_each_possible_cpu(i
) {
9942 rt_rq
= kzalloc_node(sizeof(struct rt_rq
),
9943 GFP_KERNEL
, cpu_to_node(i
));
9947 rt_se
= kzalloc_node(sizeof(struct sched_rt_entity
),
9948 GFP_KERNEL
, cpu_to_node(i
));
9952 init_tg_rt_entry(tg
, rt_rq
, rt_se
, i
, 0, parent
->rt_se
[i
]);
9961 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
9963 list_add_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
,
9964 &cpu_rq(cpu
)->leaf_rt_rq_list
);
9967 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
9969 list_del_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
);
9971 #else /* !CONFIG_RT_GROUP_SCHED */
9972 static inline void free_rt_sched_group(struct task_group
*tg
)
9977 int alloc_rt_sched_group(struct task_group
*tg
, struct task_group
*parent
)
9982 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
9986 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
9989 #endif /* CONFIG_RT_GROUP_SCHED */
9991 #ifdef CONFIG_GROUP_SCHED
9992 static void free_sched_group(struct task_group
*tg
)
9994 free_fair_sched_group(tg
);
9995 free_rt_sched_group(tg
);
9999 /* allocate runqueue etc for a new task group */
10000 struct task_group
*sched_create_group(struct task_group
*parent
)
10002 struct task_group
*tg
;
10003 unsigned long flags
;
10006 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
10008 return ERR_PTR(-ENOMEM
);
10010 if (!alloc_fair_sched_group(tg
, parent
))
10013 if (!alloc_rt_sched_group(tg
, parent
))
10016 spin_lock_irqsave(&task_group_lock
, flags
);
10017 for_each_possible_cpu(i
) {
10018 register_fair_sched_group(tg
, i
);
10019 register_rt_sched_group(tg
, i
);
10021 list_add_rcu(&tg
->list
, &task_groups
);
10023 WARN_ON(!parent
); /* root should already exist */
10025 tg
->parent
= parent
;
10026 INIT_LIST_HEAD(&tg
->children
);
10027 list_add_rcu(&tg
->siblings
, &parent
->children
);
10028 spin_unlock_irqrestore(&task_group_lock
, flags
);
10033 free_sched_group(tg
);
10034 return ERR_PTR(-ENOMEM
);
10037 /* rcu callback to free various structures associated with a task group */
10038 static void free_sched_group_rcu(struct rcu_head
*rhp
)
10040 /* now it should be safe to free those cfs_rqs */
10041 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
10044 /* Destroy runqueue etc associated with a task group */
10045 void sched_destroy_group(struct task_group
*tg
)
10047 unsigned long flags
;
10050 spin_lock_irqsave(&task_group_lock
, flags
);
10051 for_each_possible_cpu(i
) {
10052 unregister_fair_sched_group(tg
, i
);
10053 unregister_rt_sched_group(tg
, i
);
10055 list_del_rcu(&tg
->list
);
10056 list_del_rcu(&tg
->siblings
);
10057 spin_unlock_irqrestore(&task_group_lock
, flags
);
10059 /* wait for possible concurrent references to cfs_rqs complete */
10060 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
10063 /* change task's runqueue when it moves between groups.
10064 * The caller of this function should have put the task in its new group
10065 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
10066 * reflect its new group.
10068 void sched_move_task(struct task_struct
*tsk
)
10070 int on_rq
, running
;
10071 unsigned long flags
;
10074 rq
= task_rq_lock(tsk
, &flags
);
10076 update_rq_clock(rq
);
10078 running
= task_current(rq
, tsk
);
10079 on_rq
= tsk
->se
.on_rq
;
10082 dequeue_task(rq
, tsk
, 0);
10083 if (unlikely(running
))
10084 tsk
->sched_class
->put_prev_task(rq
, tsk
);
10086 set_task_rq(tsk
, task_cpu(tsk
));
10088 #ifdef CONFIG_FAIR_GROUP_SCHED
10089 if (tsk
->sched_class
->moved_group
)
10090 tsk
->sched_class
->moved_group(tsk
);
10093 if (unlikely(running
))
10094 tsk
->sched_class
->set_curr_task(rq
);
10096 enqueue_task(rq
, tsk
, 0);
10098 task_rq_unlock(rq
, &flags
);
10100 #endif /* CONFIG_GROUP_SCHED */
10102 #ifdef CONFIG_FAIR_GROUP_SCHED
10103 static void __set_se_shares(struct sched_entity
*se
, unsigned long shares
)
10105 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
10110 dequeue_entity(cfs_rq
, se
, 0);
10112 se
->load
.weight
= shares
;
10113 se
->load
.inv_weight
= 0;
10116 enqueue_entity(cfs_rq
, se
, 0);
10119 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
10121 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
10122 struct rq
*rq
= cfs_rq
->rq
;
10123 unsigned long flags
;
10125 spin_lock_irqsave(&rq
->lock
, flags
);
10126 __set_se_shares(se
, shares
);
10127 spin_unlock_irqrestore(&rq
->lock
, flags
);
10130 static DEFINE_MUTEX(shares_mutex
);
10132 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
10135 unsigned long flags
;
10138 * We can't change the weight of the root cgroup.
10143 if (shares
< MIN_SHARES
)
10144 shares
= MIN_SHARES
;
10145 else if (shares
> MAX_SHARES
)
10146 shares
= MAX_SHARES
;
10148 mutex_lock(&shares_mutex
);
10149 if (tg
->shares
== shares
)
10152 spin_lock_irqsave(&task_group_lock
, flags
);
10153 for_each_possible_cpu(i
)
10154 unregister_fair_sched_group(tg
, i
);
10155 list_del_rcu(&tg
->siblings
);
10156 spin_unlock_irqrestore(&task_group_lock
, flags
);
10158 /* wait for any ongoing reference to this group to finish */
10159 synchronize_sched();
10162 * Now we are free to modify the group's share on each cpu
10163 * w/o tripping rebalance_share or load_balance_fair.
10165 tg
->shares
= shares
;
10166 for_each_possible_cpu(i
) {
10168 * force a rebalance
10170 cfs_rq_set_shares(tg
->cfs_rq
[i
], 0);
10171 set_se_shares(tg
->se
[i
], shares
);
10175 * Enable load balance activity on this group, by inserting it back on
10176 * each cpu's rq->leaf_cfs_rq_list.
10178 spin_lock_irqsave(&task_group_lock
, flags
);
10179 for_each_possible_cpu(i
)
10180 register_fair_sched_group(tg
, i
);
10181 list_add_rcu(&tg
->siblings
, &tg
->parent
->children
);
10182 spin_unlock_irqrestore(&task_group_lock
, flags
);
10184 mutex_unlock(&shares_mutex
);
10188 unsigned long sched_group_shares(struct task_group
*tg
)
10194 #ifdef CONFIG_RT_GROUP_SCHED
10196 * Ensure that the real time constraints are schedulable.
10198 static DEFINE_MUTEX(rt_constraints_mutex
);
10200 static unsigned long to_ratio(u64 period
, u64 runtime
)
10202 if (runtime
== RUNTIME_INF
)
10205 return div64_u64(runtime
<< 20, period
);
10208 /* Must be called with tasklist_lock held */
10209 static inline int tg_has_rt_tasks(struct task_group
*tg
)
10211 struct task_struct
*g
, *p
;
10213 do_each_thread(g
, p
) {
10214 if (rt_task(p
) && rt_rq_of_se(&p
->rt
)->tg
== tg
)
10216 } while_each_thread(g
, p
);
10221 struct rt_schedulable_data
{
10222 struct task_group
*tg
;
10227 static int tg_schedulable(struct task_group
*tg
, void *data
)
10229 struct rt_schedulable_data
*d
= data
;
10230 struct task_group
*child
;
10231 unsigned long total
, sum
= 0;
10232 u64 period
, runtime
;
10234 period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
10235 runtime
= tg
->rt_bandwidth
.rt_runtime
;
10238 period
= d
->rt_period
;
10239 runtime
= d
->rt_runtime
;
10242 #ifdef CONFIG_USER_SCHED
10243 if (tg
== &root_task_group
) {
10244 period
= global_rt_period();
10245 runtime
= global_rt_runtime();
10250 * Cannot have more runtime than the period.
10252 if (runtime
> period
&& runtime
!= RUNTIME_INF
)
10256 * Ensure we don't starve existing RT tasks.
10258 if (rt_bandwidth_enabled() && !runtime
&& tg_has_rt_tasks(tg
))
10261 total
= to_ratio(period
, runtime
);
10264 * Nobody can have more than the global setting allows.
10266 if (total
> to_ratio(global_rt_period(), global_rt_runtime()))
10270 * The sum of our children's runtime should not exceed our own.
10272 list_for_each_entry_rcu(child
, &tg
->children
, siblings
) {
10273 period
= ktime_to_ns(child
->rt_bandwidth
.rt_period
);
10274 runtime
= child
->rt_bandwidth
.rt_runtime
;
10276 if (child
== d
->tg
) {
10277 period
= d
->rt_period
;
10278 runtime
= d
->rt_runtime
;
10281 sum
+= to_ratio(period
, runtime
);
10290 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
10292 struct rt_schedulable_data data
= {
10294 .rt_period
= period
,
10295 .rt_runtime
= runtime
,
10298 return walk_tg_tree(tg_schedulable
, tg_nop
, &data
);
10301 static int tg_set_bandwidth(struct task_group
*tg
,
10302 u64 rt_period
, u64 rt_runtime
)
10306 mutex_lock(&rt_constraints_mutex
);
10307 read_lock(&tasklist_lock
);
10308 err
= __rt_schedulable(tg
, rt_period
, rt_runtime
);
10312 spin_lock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
10313 tg
->rt_bandwidth
.rt_period
= ns_to_ktime(rt_period
);
10314 tg
->rt_bandwidth
.rt_runtime
= rt_runtime
;
10316 for_each_possible_cpu(i
) {
10317 struct rt_rq
*rt_rq
= tg
->rt_rq
[i
];
10319 spin_lock(&rt_rq
->rt_runtime_lock
);
10320 rt_rq
->rt_runtime
= rt_runtime
;
10321 spin_unlock(&rt_rq
->rt_runtime_lock
);
10323 spin_unlock_irq(&tg
->rt_bandwidth
.rt_runtime_lock
);
10325 read_unlock(&tasklist_lock
);
10326 mutex_unlock(&rt_constraints_mutex
);
10331 int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
10333 u64 rt_runtime
, rt_period
;
10335 rt_period
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
10336 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
10337 if (rt_runtime_us
< 0)
10338 rt_runtime
= RUNTIME_INF
;
10340 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
10343 long sched_group_rt_runtime(struct task_group
*tg
)
10347 if (tg
->rt_bandwidth
.rt_runtime
== RUNTIME_INF
)
10350 rt_runtime_us
= tg
->rt_bandwidth
.rt_runtime
;
10351 do_div(rt_runtime_us
, NSEC_PER_USEC
);
10352 return rt_runtime_us
;
10355 int sched_group_set_rt_period(struct task_group
*tg
, long rt_period_us
)
10357 u64 rt_runtime
, rt_period
;
10359 rt_period
= (u64
)rt_period_us
* NSEC_PER_USEC
;
10360 rt_runtime
= tg
->rt_bandwidth
.rt_runtime
;
10362 if (rt_period
== 0)
10365 return tg_set_bandwidth(tg
, rt_period
, rt_runtime
);
10368 long sched_group_rt_period(struct task_group
*tg
)
10372 rt_period_us
= ktime_to_ns(tg
->rt_bandwidth
.rt_period
);
10373 do_div(rt_period_us
, NSEC_PER_USEC
);
10374 return rt_period_us
;
10377 static int sched_rt_global_constraints(void)
10379 u64 runtime
, period
;
10382 if (sysctl_sched_rt_period
<= 0)
10385 runtime
= global_rt_runtime();
10386 period
= global_rt_period();
10389 * Sanity check on the sysctl variables.
10391 if (runtime
> period
&& runtime
!= RUNTIME_INF
)
10394 mutex_lock(&rt_constraints_mutex
);
10395 read_lock(&tasklist_lock
);
10396 ret
= __rt_schedulable(NULL
, 0, 0);
10397 read_unlock(&tasklist_lock
);
10398 mutex_unlock(&rt_constraints_mutex
);
10403 int sched_rt_can_attach(struct task_group
*tg
, struct task_struct
*tsk
)
10405 /* Don't accept realtime tasks when there is no way for them to run */
10406 if (rt_task(tsk
) && tg
->rt_bandwidth
.rt_runtime
== 0)
10412 #else /* !CONFIG_RT_GROUP_SCHED */
10413 static int sched_rt_global_constraints(void)
10415 unsigned long flags
;
10418 if (sysctl_sched_rt_period
<= 0)
10421 spin_lock_irqsave(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
10422 for_each_possible_cpu(i
) {
10423 struct rt_rq
*rt_rq
= &cpu_rq(i
)->rt
;
10425 spin_lock(&rt_rq
->rt_runtime_lock
);
10426 rt_rq
->rt_runtime
= global_rt_runtime();
10427 spin_unlock(&rt_rq
->rt_runtime_lock
);
10429 spin_unlock_irqrestore(&def_rt_bandwidth
.rt_runtime_lock
, flags
);
10433 #endif /* CONFIG_RT_GROUP_SCHED */
10435 int sched_rt_handler(struct ctl_table
*table
, int write
,
10436 struct file
*filp
, void __user
*buffer
, size_t *lenp
,
10440 int old_period
, old_runtime
;
10441 static DEFINE_MUTEX(mutex
);
10443 mutex_lock(&mutex
);
10444 old_period
= sysctl_sched_rt_period
;
10445 old_runtime
= sysctl_sched_rt_runtime
;
10447 ret
= proc_dointvec(table
, write
, filp
, buffer
, lenp
, ppos
);
10449 if (!ret
&& write
) {
10450 ret
= sched_rt_global_constraints();
10452 sysctl_sched_rt_period
= old_period
;
10453 sysctl_sched_rt_runtime
= old_runtime
;
10455 def_rt_bandwidth
.rt_runtime
= global_rt_runtime();
10456 def_rt_bandwidth
.rt_period
=
10457 ns_to_ktime(global_rt_period());
10460 mutex_unlock(&mutex
);
10465 #ifdef CONFIG_CGROUP_SCHED
10467 /* return corresponding task_group object of a cgroup */
10468 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
10470 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
10471 struct task_group
, css
);
10474 static struct cgroup_subsys_state
*
10475 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
10477 struct task_group
*tg
, *parent
;
10479 if (!cgrp
->parent
) {
10480 /* This is early initialization for the top cgroup */
10481 return &init_task_group
.css
;
10484 parent
= cgroup_tg(cgrp
->parent
);
10485 tg
= sched_create_group(parent
);
10487 return ERR_PTR(-ENOMEM
);
10493 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
10495 struct task_group
*tg
= cgroup_tg(cgrp
);
10497 sched_destroy_group(tg
);
10501 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
10502 struct task_struct
*tsk
)
10504 #ifdef CONFIG_RT_GROUP_SCHED
10505 if (!sched_rt_can_attach(cgroup_tg(cgrp
), tsk
))
10508 /* We don't support RT-tasks being in separate groups */
10509 if (tsk
->sched_class
!= &fair_sched_class
)
10517 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
10518 struct cgroup
*old_cont
, struct task_struct
*tsk
)
10520 sched_move_task(tsk
);
10523 #ifdef CONFIG_FAIR_GROUP_SCHED
10524 static int cpu_shares_write_u64(struct cgroup
*cgrp
, struct cftype
*cftype
,
10527 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
10530 static u64
cpu_shares_read_u64(struct cgroup
*cgrp
, struct cftype
*cft
)
10532 struct task_group
*tg
= cgroup_tg(cgrp
);
10534 return (u64
) tg
->shares
;
10536 #endif /* CONFIG_FAIR_GROUP_SCHED */
10538 #ifdef CONFIG_RT_GROUP_SCHED
10539 static int cpu_rt_runtime_write(struct cgroup
*cgrp
, struct cftype
*cft
,
10542 return sched_group_set_rt_runtime(cgroup_tg(cgrp
), val
);
10545 static s64
cpu_rt_runtime_read(struct cgroup
*cgrp
, struct cftype
*cft
)
10547 return sched_group_rt_runtime(cgroup_tg(cgrp
));
10550 static int cpu_rt_period_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
10553 return sched_group_set_rt_period(cgroup_tg(cgrp
), rt_period_us
);
10556 static u64
cpu_rt_period_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
10558 return sched_group_rt_period(cgroup_tg(cgrp
));
10560 #endif /* CONFIG_RT_GROUP_SCHED */
10562 static struct cftype cpu_files
[] = {
10563 #ifdef CONFIG_FAIR_GROUP_SCHED
10566 .read_u64
= cpu_shares_read_u64
,
10567 .write_u64
= cpu_shares_write_u64
,
10570 #ifdef CONFIG_RT_GROUP_SCHED
10572 .name
= "rt_runtime_us",
10573 .read_s64
= cpu_rt_runtime_read
,
10574 .write_s64
= cpu_rt_runtime_write
,
10577 .name
= "rt_period_us",
10578 .read_u64
= cpu_rt_period_read_uint
,
10579 .write_u64
= cpu_rt_period_write_uint
,
10584 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
10586 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
10589 struct cgroup_subsys cpu_cgroup_subsys
= {
10591 .create
= cpu_cgroup_create
,
10592 .destroy
= cpu_cgroup_destroy
,
10593 .can_attach
= cpu_cgroup_can_attach
,
10594 .attach
= cpu_cgroup_attach
,
10595 .populate
= cpu_cgroup_populate
,
10596 .subsys_id
= cpu_cgroup_subsys_id
,
10600 #endif /* CONFIG_CGROUP_SCHED */
10602 #ifdef CONFIG_CGROUP_CPUACCT
10605 * CPU accounting code for task groups.
10607 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
10608 * (balbir@in.ibm.com).
10611 /* track cpu usage of a group of tasks and its child groups */
10613 struct cgroup_subsys_state css
;
10614 /* cpuusage holds pointer to a u64-type object on every cpu */
10616 struct cpuacct
*parent
;
10619 struct cgroup_subsys cpuacct_subsys
;
10621 /* return cpu accounting group corresponding to this container */
10622 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cgrp
)
10624 return container_of(cgroup_subsys_state(cgrp
, cpuacct_subsys_id
),
10625 struct cpuacct
, css
);
10628 /* return cpu accounting group to which this task belongs */
10629 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
10631 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
10632 struct cpuacct
, css
);
10635 /* create a new cpu accounting group */
10636 static struct cgroup_subsys_state
*cpuacct_create(
10637 struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
10639 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
10642 return ERR_PTR(-ENOMEM
);
10644 ca
->cpuusage
= alloc_percpu(u64
);
10645 if (!ca
->cpuusage
) {
10647 return ERR_PTR(-ENOMEM
);
10651 ca
->parent
= cgroup_ca(cgrp
->parent
);
10656 /* destroy an existing cpu accounting group */
10658 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
10660 struct cpuacct
*ca
= cgroup_ca(cgrp
);
10662 free_percpu(ca
->cpuusage
);
10666 static u64
cpuacct_cpuusage_read(struct cpuacct
*ca
, int cpu
)
10668 u64
*cpuusage
= per_cpu_ptr(ca
->cpuusage
, cpu
);
10671 #ifndef CONFIG_64BIT
10673 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
10675 spin_lock_irq(&cpu_rq(cpu
)->lock
);
10677 spin_unlock_irq(&cpu_rq(cpu
)->lock
);
10685 static void cpuacct_cpuusage_write(struct cpuacct
*ca
, int cpu
, u64 val
)
10687 u64
*cpuusage
= per_cpu_ptr(ca
->cpuusage
, cpu
);
10689 #ifndef CONFIG_64BIT
10691 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
10693 spin_lock_irq(&cpu_rq(cpu
)->lock
);
10695 spin_unlock_irq(&cpu_rq(cpu
)->lock
);
10701 /* return total cpu usage (in nanoseconds) of a group */
10702 static u64
cpuusage_read(struct cgroup
*cgrp
, struct cftype
*cft
)
10704 struct cpuacct
*ca
= cgroup_ca(cgrp
);
10705 u64 totalcpuusage
= 0;
10708 for_each_present_cpu(i
)
10709 totalcpuusage
+= cpuacct_cpuusage_read(ca
, i
);
10711 return totalcpuusage
;
10714 static int cpuusage_write(struct cgroup
*cgrp
, struct cftype
*cftype
,
10717 struct cpuacct
*ca
= cgroup_ca(cgrp
);
10726 for_each_present_cpu(i
)
10727 cpuacct_cpuusage_write(ca
, i
, 0);
10733 static int cpuacct_percpu_seq_read(struct cgroup
*cgroup
, struct cftype
*cft
,
10734 struct seq_file
*m
)
10736 struct cpuacct
*ca
= cgroup_ca(cgroup
);
10740 for_each_present_cpu(i
) {
10741 percpu
= cpuacct_cpuusage_read(ca
, i
);
10742 seq_printf(m
, "%llu ", (unsigned long long) percpu
);
10744 seq_printf(m
, "\n");
10748 static struct cftype files
[] = {
10751 .read_u64
= cpuusage_read
,
10752 .write_u64
= cpuusage_write
,
10755 .name
= "usage_percpu",
10756 .read_seq_string
= cpuacct_percpu_seq_read
,
10761 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
10763 return cgroup_add_files(cgrp
, ss
, files
, ARRAY_SIZE(files
));
10767 * charge this task's execution time to its accounting group.
10769 * called with rq->lock held.
10771 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
10773 struct cpuacct
*ca
;
10776 if (unlikely(!cpuacct_subsys
.active
))
10779 cpu
= task_cpu(tsk
);
10785 u64
*cpuusage
= per_cpu_ptr(ca
->cpuusage
, cpu
);
10786 *cpuusage
+= cputime
;
10792 struct cgroup_subsys cpuacct_subsys
= {
10794 .create
= cpuacct_create
,
10795 .destroy
= cpuacct_destroy
,
10796 .populate
= cpuacct_populate
,
10797 .subsys_id
= cpuacct_subsys_id
,
10799 #endif /* CONFIG_CGROUP_CPUACCT */