sched: group scheduling code cleanup
[deliverable/linux.git] / kernel / sched.c
CommitLineData
1da177e4
LT
1/*
2 * kernel/sched.c
3 *
4 * Kernel scheduler and related syscalls
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
7 *
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
c31f2e8a
IM
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
1da177e4
LT
25 */
26
27#include <linux/mm.h>
28#include <linux/module.h>
29#include <linux/nmi.h>
30#include <linux/init.h>
dff06c15 31#include <linux/uaccess.h>
1da177e4
LT
32#include <linux/highmem.h>
33#include <linux/smp_lock.h>
34#include <asm/mmu_context.h>
35#include <linux/interrupt.h>
c59ede7b 36#include <linux/capability.h>
1da177e4
LT
37#include <linux/completion.h>
38#include <linux/kernel_stat.h>
9a11b49a 39#include <linux/debug_locks.h>
1da177e4
LT
40#include <linux/security.h>
41#include <linux/notifier.h>
42#include <linux/profile.h>
7dfb7103 43#include <linux/freezer.h>
198e2f18 44#include <linux/vmalloc.h>
1da177e4
LT
45#include <linux/blkdev.h>
46#include <linux/delay.h>
b488893a 47#include <linux/pid_namespace.h>
1da177e4
LT
48#include <linux/smp.h>
49#include <linux/threads.h>
50#include <linux/timer.h>
51#include <linux/rcupdate.h>
52#include <linux/cpu.h>
53#include <linux/cpuset.h>
54#include <linux/percpu.h>
55#include <linux/kthread.h>
56#include <linux/seq_file.h>
e692ab53 57#include <linux/sysctl.h>
1da177e4
LT
58#include <linux/syscalls.h>
59#include <linux/times.h>
8f0ab514 60#include <linux/tsacct_kern.h>
c6fd91f0 61#include <linux/kprobes.h>
0ff92245 62#include <linux/delayacct.h>
5517d86b 63#include <linux/reciprocal_div.h>
dff06c15 64#include <linux/unistd.h>
f5ff8422 65#include <linux/pagemap.h>
1da177e4 66
5517d86b 67#include <asm/tlb.h>
838225b4 68#include <asm/irq_regs.h>
1da177e4 69
b035b6de
AD
70/*
71 * Scheduler clock - returns current time in nanosec units.
72 * This is default implementation.
73 * Architectures and sub-architectures can override this.
74 */
75unsigned long long __attribute__((weak)) sched_clock(void)
76{
d6322faf 77 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
b035b6de
AD
78}
79
1da177e4
LT
80/*
81 * Convert user-nice values [ -20 ... 0 ... 19 ]
82 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
83 * and back.
84 */
85#define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
86#define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
87#define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
88
89/*
90 * 'User priority' is the nice value converted to something we
91 * can work with better when scaling various scheduler parameters,
92 * it's a [ 0 ... 39 ] range.
93 */
94#define USER_PRIO(p) ((p)-MAX_RT_PRIO)
95#define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
96#define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
97
98/*
99 * Some helpers for converting nanosecond timing to jiffy resolution
100 */
d6322faf
ED
101#define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
102#define JIFFIES_TO_NS(TIME) ((TIME) * (NSEC_PER_SEC / HZ))
1da177e4 103
6aa645ea
IM
104#define NICE_0_LOAD SCHED_LOAD_SCALE
105#define NICE_0_SHIFT SCHED_LOAD_SHIFT
106
1da177e4
LT
107/*
108 * These are the 'tuning knobs' of the scheduler:
109 *
a4ec24b4 110 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
1da177e4
LT
111 * Timeslices get refilled after they expire.
112 */
1da177e4 113#define DEF_TIMESLICE (100 * HZ / 1000)
2dd73a4f 114
5517d86b
ED
115#ifdef CONFIG_SMP
116/*
117 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
118 * Since cpu_power is a 'constant', we can use a reciprocal divide.
119 */
120static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
121{
122 return reciprocal_divide(load, sg->reciprocal_cpu_power);
123}
124
125/*
126 * Each time a sched group cpu_power is changed,
127 * we must compute its reciprocal value
128 */
129static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
130{
131 sg->__cpu_power += val;
132 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
133}
134#endif
135
e05606d3
IM
136static inline int rt_policy(int policy)
137{
138 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
139 return 1;
140 return 0;
141}
142
143static inline int task_has_rt_policy(struct task_struct *p)
144{
145 return rt_policy(p->policy);
146}
147
1da177e4 148/*
6aa645ea 149 * This is the priority-queue data structure of the RT scheduling class:
1da177e4 150 */
6aa645ea
IM
151struct rt_prio_array {
152 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
153 struct list_head queue[MAX_RT_PRIO];
154};
155
29f59db3
SV
156#ifdef CONFIG_FAIR_GROUP_SCHED
157
68318b8e
SV
158#include <linux/cgroup.h>
159
29f59db3
SV
160struct cfs_rq;
161
162/* task group related information */
4cf86d77 163struct task_group {
68318b8e
SV
164#ifdef CONFIG_FAIR_CGROUP_SCHED
165 struct cgroup_subsys_state css;
166#endif
29f59db3
SV
167 /* schedulable entities of this group on each cpu */
168 struct sched_entity **se;
169 /* runqueue "owned" by this group on each cpu */
170 struct cfs_rq **cfs_rq;
171 unsigned long shares;
5cb350ba
DG
172 /* spinlock to serialize modification to shares */
173 spinlock_t lock;
ae8393e5 174 struct rcu_head rcu;
29f59db3
SV
175};
176
177/* Default task group's sched entity on each cpu */
178static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
179/* Default task group's cfs_rq on each cpu */
180static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
181
9b5b7751
SV
182static struct sched_entity *init_sched_entity_p[NR_CPUS];
183static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
29f59db3
SV
184
185/* Default task group.
3a252015 186 * Every task in system belong to this group at bootup.
29f59db3 187 */
4cf86d77 188struct task_group init_task_group = {
3a252015
IM
189 .se = init_sched_entity_p,
190 .cfs_rq = init_cfs_rq_p,
191};
9b5b7751 192
24e377a8 193#ifdef CONFIG_FAIR_USER_SCHED
93f992cc 194# define INIT_TASK_GROUP_LOAD 2*NICE_0_LOAD
24e377a8 195#else
93f992cc 196# define INIT_TASK_GROUP_LOAD NICE_0_LOAD
24e377a8
SV
197#endif
198
93f992cc 199static int init_task_group_load = INIT_TASK_GROUP_LOAD;
29f59db3
SV
200
201/* return group to which a task belongs */
4cf86d77 202static inline struct task_group *task_group(struct task_struct *p)
29f59db3 203{
4cf86d77 204 struct task_group *tg;
9b5b7751 205
24e377a8
SV
206#ifdef CONFIG_FAIR_USER_SCHED
207 tg = p->user->tg;
68318b8e
SV
208#elif defined(CONFIG_FAIR_CGROUP_SCHED)
209 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
210 struct task_group, css);
24e377a8 211#else
41a2d6cf 212 tg = &init_task_group;
24e377a8 213#endif
9b5b7751 214 return tg;
29f59db3
SV
215}
216
217/* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
ce96b5ac 218static inline void set_task_cfs_rq(struct task_struct *p, unsigned int cpu)
29f59db3 219{
ce96b5ac
DA
220 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
221 p->se.parent = task_group(p)->se[cpu];
29f59db3
SV
222}
223
224#else
225
ce96b5ac 226static inline void set_task_cfs_rq(struct task_struct *p, unsigned int cpu) { }
29f59db3
SV
227
228#endif /* CONFIG_FAIR_GROUP_SCHED */
229
6aa645ea
IM
230/* CFS-related fields in a runqueue */
231struct cfs_rq {
232 struct load_weight load;
233 unsigned long nr_running;
234
6aa645ea 235 u64 exec_clock;
e9acbff6 236 u64 min_vruntime;
6aa645ea
IM
237
238 struct rb_root tasks_timeline;
239 struct rb_node *rb_leftmost;
240 struct rb_node *rb_load_balance_curr;
6aa645ea
IM
241 /* 'curr' points to currently running entity on this cfs_rq.
242 * It is set to NULL otherwise (i.e when none are currently running).
243 */
244 struct sched_entity *curr;
ddc97297
PZ
245
246 unsigned long nr_spread_over;
247
62160e3f 248#ifdef CONFIG_FAIR_GROUP_SCHED
6aa645ea
IM
249 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
250
41a2d6cf
IM
251 /*
252 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
6aa645ea
IM
253 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
254 * (like users, containers etc.)
255 *
256 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
257 * list is used during load balance.
258 */
41a2d6cf
IM
259 struct list_head leaf_cfs_rq_list;
260 struct task_group *tg; /* group that "owns" this runqueue */
6aa645ea
IM
261#endif
262};
1da177e4 263
6aa645ea
IM
264/* Real-Time classes' related field in a runqueue: */
265struct rt_rq {
266 struct rt_prio_array active;
267 int rt_load_balance_idx;
268 struct list_head *rt_load_balance_head, *rt_load_balance_curr;
269};
270
1da177e4
LT
271/*
272 * This is the main, per-CPU runqueue data structure.
273 *
274 * Locking rule: those places that want to lock multiple runqueues
275 * (such as the load balancing or the thread migration code), lock
276 * acquire operations must be ordered by ascending &runqueue.
277 */
70b97a7f 278struct rq {
d8016491
IM
279 /* runqueue lock: */
280 spinlock_t lock;
1da177e4
LT
281
282 /*
283 * nr_running and cpu_load should be in the same cacheline because
284 * remote CPUs use both these fields when doing load calculation.
285 */
286 unsigned long nr_running;
6aa645ea
IM
287 #define CPU_LOAD_IDX_MAX 5
288 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
bdecea3a 289 unsigned char idle_at_tick;
46cb4b7c
SS
290#ifdef CONFIG_NO_HZ
291 unsigned char in_nohz_recently;
292#endif
d8016491
IM
293 /* capture load from *all* tasks on this cpu: */
294 struct load_weight load;
6aa645ea
IM
295 unsigned long nr_load_updates;
296 u64 nr_switches;
297
298 struct cfs_rq cfs;
299#ifdef CONFIG_FAIR_GROUP_SCHED
d8016491
IM
300 /* list of leaf cfs_rq on this cpu: */
301 struct list_head leaf_cfs_rq_list;
1da177e4 302#endif
41a2d6cf 303 struct rt_rq rt;
1da177e4
LT
304
305 /*
306 * This is part of a global counter where only the total sum
307 * over all CPUs matters. A task can increase this counter on
308 * one CPU and if it got migrated afterwards it may decrease
309 * it on another CPU. Always updated under the runqueue lock:
310 */
311 unsigned long nr_uninterruptible;
312
36c8b586 313 struct task_struct *curr, *idle;
c9819f45 314 unsigned long next_balance;
1da177e4 315 struct mm_struct *prev_mm;
6aa645ea 316
6aa645ea
IM
317 u64 clock, prev_clock_raw;
318 s64 clock_max_delta;
319
320 unsigned int clock_warps, clock_overflows;
2aa44d05
IM
321 u64 idle_clock;
322 unsigned int clock_deep_idle_events;
529c7726 323 u64 tick_timestamp;
6aa645ea 324
1da177e4
LT
325 atomic_t nr_iowait;
326
327#ifdef CONFIG_SMP
328 struct sched_domain *sd;
329
330 /* For active balancing */
331 int active_balance;
332 int push_cpu;
d8016491
IM
333 /* cpu of this runqueue: */
334 int cpu;
1da177e4 335
36c8b586 336 struct task_struct *migration_thread;
1da177e4
LT
337 struct list_head migration_queue;
338#endif
339
340#ifdef CONFIG_SCHEDSTATS
341 /* latency stats */
342 struct sched_info rq_sched_info;
343
344 /* sys_sched_yield() stats */
480b9434
KC
345 unsigned int yld_exp_empty;
346 unsigned int yld_act_empty;
347 unsigned int yld_both_empty;
348 unsigned int yld_count;
1da177e4
LT
349
350 /* schedule() stats */
480b9434
KC
351 unsigned int sched_switch;
352 unsigned int sched_count;
353 unsigned int sched_goidle;
1da177e4
LT
354
355 /* try_to_wake_up() stats */
480b9434
KC
356 unsigned int ttwu_count;
357 unsigned int ttwu_local;
b8efb561
IM
358
359 /* BKL stats */
480b9434 360 unsigned int bkl_count;
1da177e4 361#endif
fcb99371 362 struct lock_class_key rq_lock_key;
1da177e4
LT
363};
364
f34e3b61 365static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
5be9361c 366static DEFINE_MUTEX(sched_hotcpu_mutex);
1da177e4 367
dd41f596
IM
368static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
369{
370 rq->curr->sched_class->check_preempt_curr(rq, p);
371}
372
0a2966b4
CL
373static inline int cpu_of(struct rq *rq)
374{
375#ifdef CONFIG_SMP
376 return rq->cpu;
377#else
378 return 0;
379#endif
380}
381
20d315d4 382/*
b04a0f4c
IM
383 * Update the per-runqueue clock, as finegrained as the platform can give
384 * us, but without assuming monotonicity, etc.:
20d315d4 385 */
b04a0f4c 386static void __update_rq_clock(struct rq *rq)
20d315d4
IM
387{
388 u64 prev_raw = rq->prev_clock_raw;
389 u64 now = sched_clock();
390 s64 delta = now - prev_raw;
391 u64 clock = rq->clock;
392
b04a0f4c
IM
393#ifdef CONFIG_SCHED_DEBUG
394 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
395#endif
20d315d4
IM
396 /*
397 * Protect against sched_clock() occasionally going backwards:
398 */
399 if (unlikely(delta < 0)) {
400 clock++;
401 rq->clock_warps++;
402 } else {
403 /*
404 * Catch too large forward jumps too:
405 */
529c7726
IM
406 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
407 if (clock < rq->tick_timestamp + TICK_NSEC)
408 clock = rq->tick_timestamp + TICK_NSEC;
409 else
410 clock++;
20d315d4
IM
411 rq->clock_overflows++;
412 } else {
413 if (unlikely(delta > rq->clock_max_delta))
414 rq->clock_max_delta = delta;
415 clock += delta;
416 }
417 }
418
419 rq->prev_clock_raw = now;
420 rq->clock = clock;
b04a0f4c 421}
20d315d4 422
b04a0f4c
IM
423static void update_rq_clock(struct rq *rq)
424{
425 if (likely(smp_processor_id() == cpu_of(rq)))
426 __update_rq_clock(rq);
20d315d4
IM
427}
428
674311d5
NP
429/*
430 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
1a20ff27 431 * See detach_destroy_domains: synchronize_sched for details.
674311d5
NP
432 *
433 * The domain tree of any CPU may only be accessed from within
434 * preempt-disabled sections.
435 */
48f24c4d
IM
436#define for_each_domain(cpu, __sd) \
437 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
1da177e4
LT
438
439#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
440#define this_rq() (&__get_cpu_var(runqueues))
441#define task_rq(p) cpu_rq(task_cpu(p))
442#define cpu_curr(cpu) (cpu_rq(cpu)->curr)
443
bf5c91ba
IM
444/*
445 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
446 */
447#ifdef CONFIG_SCHED_DEBUG
448# define const_debug __read_mostly
449#else
450# define const_debug static const
451#endif
452
453/*
454 * Debugging: various feature bits
455 */
456enum {
bbdba7c0 457 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
9612633a
IM
458 SCHED_FEAT_WAKEUP_PREEMPT = 2,
459 SCHED_FEAT_START_DEBIT = 4,
41a2d6cf
IM
460 SCHED_FEAT_TREE_AVG = 8,
461 SCHED_FEAT_APPROX_AVG = 16,
bf5c91ba
IM
462};
463
464const_debug unsigned int sysctl_sched_features =
8401f775 465 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
9612633a 466 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
8401f775
IM
467 SCHED_FEAT_START_DEBIT * 1 |
468 SCHED_FEAT_TREE_AVG * 0 |
9612633a 469 SCHED_FEAT_APPROX_AVG * 0;
bf5c91ba
IM
470
471#define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
472
b82d9fdd
PZ
473/*
474 * Number of tasks to iterate in a single balance run.
475 * Limited because this is done with IRQs disabled.
476 */
477const_debug unsigned int sysctl_sched_nr_migrate = 32;
478
e436d800
IM
479/*
480 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
481 * clock constructed from sched_clock():
482 */
483unsigned long long cpu_clock(int cpu)
484{
e436d800
IM
485 unsigned long long now;
486 unsigned long flags;
b04a0f4c 487 struct rq *rq;
e436d800 488
2cd4d0ea 489 local_irq_save(flags);
b04a0f4c 490 rq = cpu_rq(cpu);
8ced5f69
IM
491 /*
492 * Only call sched_clock() if the scheduler has already been
493 * initialized (some code might call cpu_clock() very early):
494 */
495 if (rq->idle)
496 update_rq_clock(rq);
b04a0f4c 497 now = rq->clock;
2cd4d0ea 498 local_irq_restore(flags);
e436d800
IM
499
500 return now;
501}
a58f6f25 502EXPORT_SYMBOL_GPL(cpu_clock);
e436d800 503
1da177e4 504#ifndef prepare_arch_switch
4866cde0
NP
505# define prepare_arch_switch(next) do { } while (0)
506#endif
507#ifndef finish_arch_switch
508# define finish_arch_switch(prev) do { } while (0)
509#endif
510
051a1d1a
DA
511static inline int task_current(struct rq *rq, struct task_struct *p)
512{
513 return rq->curr == p;
514}
515
4866cde0 516#ifndef __ARCH_WANT_UNLOCKED_CTXSW
70b97a7f 517static inline int task_running(struct rq *rq, struct task_struct *p)
4866cde0 518{
051a1d1a 519 return task_current(rq, p);
4866cde0
NP
520}
521
70b97a7f 522static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
4866cde0
NP
523{
524}
525
70b97a7f 526static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
4866cde0 527{
da04c035
IM
528#ifdef CONFIG_DEBUG_SPINLOCK
529 /* this is a valid case when another task releases the spinlock */
530 rq->lock.owner = current;
531#endif
8a25d5de
IM
532 /*
533 * If we are tracking spinlock dependencies then we have to
534 * fix up the runqueue lock - which gets 'carried over' from
535 * prev into current:
536 */
537 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
538
4866cde0
NP
539 spin_unlock_irq(&rq->lock);
540}
541
542#else /* __ARCH_WANT_UNLOCKED_CTXSW */
70b97a7f 543static inline int task_running(struct rq *rq, struct task_struct *p)
4866cde0
NP
544{
545#ifdef CONFIG_SMP
546 return p->oncpu;
547#else
051a1d1a 548 return task_current(rq, p);
4866cde0
NP
549#endif
550}
551
70b97a7f 552static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
4866cde0
NP
553{
554#ifdef CONFIG_SMP
555 /*
556 * We can optimise this out completely for !SMP, because the
557 * SMP rebalancing from interrupt is the only thing that cares
558 * here.
559 */
560 next->oncpu = 1;
561#endif
562#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
563 spin_unlock_irq(&rq->lock);
564#else
565 spin_unlock(&rq->lock);
566#endif
567}
568
70b97a7f 569static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
4866cde0
NP
570{
571#ifdef CONFIG_SMP
572 /*
573 * After ->oncpu is cleared, the task can be moved to a different CPU.
574 * We must ensure this doesn't happen until the switch is completely
575 * finished.
576 */
577 smp_wmb();
578 prev->oncpu = 0;
579#endif
580#ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
581 local_irq_enable();
1da177e4 582#endif
4866cde0
NP
583}
584#endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1da177e4 585
b29739f9
IM
586/*
587 * __task_rq_lock - lock the runqueue a given task resides on.
588 * Must be called interrupts disabled.
589 */
70b97a7f 590static inline struct rq *__task_rq_lock(struct task_struct *p)
b29739f9
IM
591 __acquires(rq->lock)
592{
3a5c359a
AK
593 for (;;) {
594 struct rq *rq = task_rq(p);
595 spin_lock(&rq->lock);
596 if (likely(rq == task_rq(p)))
597 return rq;
b29739f9 598 spin_unlock(&rq->lock);
b29739f9 599 }
b29739f9
IM
600}
601
1da177e4
LT
602/*
603 * task_rq_lock - lock the runqueue a given task resides on and disable
41a2d6cf 604 * interrupts. Note the ordering: we can safely lookup the task_rq without
1da177e4
LT
605 * explicitly disabling preemption.
606 */
70b97a7f 607static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1da177e4
LT
608 __acquires(rq->lock)
609{
70b97a7f 610 struct rq *rq;
1da177e4 611
3a5c359a
AK
612 for (;;) {
613 local_irq_save(*flags);
614 rq = task_rq(p);
615 spin_lock(&rq->lock);
616 if (likely(rq == task_rq(p)))
617 return rq;
1da177e4 618 spin_unlock_irqrestore(&rq->lock, *flags);
1da177e4 619 }
1da177e4
LT
620}
621
a9957449 622static void __task_rq_unlock(struct rq *rq)
b29739f9
IM
623 __releases(rq->lock)
624{
625 spin_unlock(&rq->lock);
626}
627
70b97a7f 628static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1da177e4
LT
629 __releases(rq->lock)
630{
631 spin_unlock_irqrestore(&rq->lock, *flags);
632}
633
1da177e4 634/*
cc2a73b5 635 * this_rq_lock - lock this runqueue and disable interrupts.
1da177e4 636 */
a9957449 637static struct rq *this_rq_lock(void)
1da177e4
LT
638 __acquires(rq->lock)
639{
70b97a7f 640 struct rq *rq;
1da177e4
LT
641
642 local_irq_disable();
643 rq = this_rq();
644 spin_lock(&rq->lock);
645
646 return rq;
647}
648
1b9f19c2 649/*
2aa44d05 650 * We are going deep-idle (irqs are disabled):
1b9f19c2 651 */
2aa44d05 652void sched_clock_idle_sleep_event(void)
1b9f19c2 653{
2aa44d05
IM
654 struct rq *rq = cpu_rq(smp_processor_id());
655
656 spin_lock(&rq->lock);
657 __update_rq_clock(rq);
658 spin_unlock(&rq->lock);
659 rq->clock_deep_idle_events++;
660}
661EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
662
663/*
664 * We just idled delta nanoseconds (called with irqs disabled):
665 */
666void sched_clock_idle_wakeup_event(u64 delta_ns)
667{
668 struct rq *rq = cpu_rq(smp_processor_id());
669 u64 now = sched_clock();
1b9f19c2 670
2bacec8c 671 touch_softlockup_watchdog();
2aa44d05
IM
672 rq->idle_clock += delta_ns;
673 /*
674 * Override the previous timestamp and ignore all
675 * sched_clock() deltas that occured while we idled,
676 * and use the PM-provided delta_ns to advance the
677 * rq clock:
678 */
679 spin_lock(&rq->lock);
680 rq->prev_clock_raw = now;
681 rq->clock += delta_ns;
682 spin_unlock(&rq->lock);
1b9f19c2 683}
2aa44d05 684EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1b9f19c2 685
c24d20db
IM
686/*
687 * resched_task - mark a task 'to be rescheduled now'.
688 *
689 * On UP this means the setting of the need_resched flag, on SMP it
690 * might also involve a cross-CPU call to trigger the scheduler on
691 * the target CPU.
692 */
693#ifdef CONFIG_SMP
694
695#ifndef tsk_is_polling
696#define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
697#endif
698
699static void resched_task(struct task_struct *p)
700{
701 int cpu;
702
703 assert_spin_locked(&task_rq(p)->lock);
704
705 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
706 return;
707
708 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
709
710 cpu = task_cpu(p);
711 if (cpu == smp_processor_id())
712 return;
713
714 /* NEED_RESCHED must be visible before we test polling */
715 smp_mb();
716 if (!tsk_is_polling(p))
717 smp_send_reschedule(cpu);
718}
719
720static void resched_cpu(int cpu)
721{
722 struct rq *rq = cpu_rq(cpu);
723 unsigned long flags;
724
725 if (!spin_trylock_irqsave(&rq->lock, flags))
726 return;
727 resched_task(cpu_curr(cpu));
728 spin_unlock_irqrestore(&rq->lock, flags);
729}
730#else
731static inline void resched_task(struct task_struct *p)
732{
733 assert_spin_locked(&task_rq(p)->lock);
734 set_tsk_need_resched(p);
735}
736#endif
737
45bf76df
IM
738#if BITS_PER_LONG == 32
739# define WMULT_CONST (~0UL)
740#else
741# define WMULT_CONST (1UL << 32)
742#endif
743
744#define WMULT_SHIFT 32
745
194081eb
IM
746/*
747 * Shift right and round:
748 */
cf2ab469 749#define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
194081eb 750
cb1c4fc9 751static unsigned long
45bf76df
IM
752calc_delta_mine(unsigned long delta_exec, unsigned long weight,
753 struct load_weight *lw)
754{
755 u64 tmp;
756
757 if (unlikely(!lw->inv_weight))
194081eb 758 lw->inv_weight = (WMULT_CONST - lw->weight/2) / lw->weight + 1;
45bf76df
IM
759
760 tmp = (u64)delta_exec * weight;
761 /*
762 * Check whether we'd overflow the 64-bit multiplication:
763 */
194081eb 764 if (unlikely(tmp > WMULT_CONST))
cf2ab469 765 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
194081eb
IM
766 WMULT_SHIFT/2);
767 else
cf2ab469 768 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
45bf76df 769
ecf691da 770 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
45bf76df
IM
771}
772
773static inline unsigned long
774calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
775{
776 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
777}
778
1091985b 779static inline void update_load_add(struct load_weight *lw, unsigned long inc)
45bf76df
IM
780{
781 lw->weight += inc;
45bf76df
IM
782}
783
1091985b 784static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
45bf76df
IM
785{
786 lw->weight -= dec;
45bf76df
IM
787}
788
2dd73a4f
PW
789/*
790 * To aid in avoiding the subversion of "niceness" due to uneven distribution
791 * of tasks with abnormal "nice" values across CPUs the contribution that
792 * each task makes to its run queue's load is weighted according to its
41a2d6cf 793 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
2dd73a4f
PW
794 * scaled version of the new time slice allocation that they receive on time
795 * slice expiry etc.
796 */
797
dd41f596
IM
798#define WEIGHT_IDLEPRIO 2
799#define WMULT_IDLEPRIO (1 << 31)
800
801/*
802 * Nice levels are multiplicative, with a gentle 10% change for every
803 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
804 * nice 1, it will get ~10% less CPU time than another CPU-bound task
805 * that remained on nice 0.
806 *
807 * The "10% effect" is relative and cumulative: from _any_ nice level,
808 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
f9153ee6
IM
809 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
810 * If a task goes up by ~10% and another task goes down by ~10% then
811 * the relative distance between them is ~25%.)
dd41f596
IM
812 */
813static const int prio_to_weight[40] = {
254753dc
IM
814 /* -20 */ 88761, 71755, 56483, 46273, 36291,
815 /* -15 */ 29154, 23254, 18705, 14949, 11916,
816 /* -10 */ 9548, 7620, 6100, 4904, 3906,
817 /* -5 */ 3121, 2501, 1991, 1586, 1277,
818 /* 0 */ 1024, 820, 655, 526, 423,
819 /* 5 */ 335, 272, 215, 172, 137,
820 /* 10 */ 110, 87, 70, 56, 45,
821 /* 15 */ 36, 29, 23, 18, 15,
dd41f596
IM
822};
823
5714d2de
IM
824/*
825 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
826 *
827 * In cases where the weight does not change often, we can use the
828 * precalculated inverse to speed up arithmetics by turning divisions
829 * into multiplications:
830 */
dd41f596 831static const u32 prio_to_wmult[40] = {
254753dc
IM
832 /* -20 */ 48388, 59856, 76040, 92818, 118348,
833 /* -15 */ 147320, 184698, 229616, 287308, 360437,
834 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
835 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
836 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
837 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
838 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
839 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
dd41f596 840};
2dd73a4f 841
dd41f596
IM
842static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
843
844/*
845 * runqueue iterator, to support SMP load-balancing between different
846 * scheduling classes, without having to expose their internal data
847 * structures to the load-balancing proper:
848 */
849struct rq_iterator {
850 void *arg;
851 struct task_struct *(*start)(void *);
852 struct task_struct *(*next)(void *);
853};
854
e1d1484f
PW
855#ifdef CONFIG_SMP
856static unsigned long
857balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
858 unsigned long max_load_move, struct sched_domain *sd,
859 enum cpu_idle_type idle, int *all_pinned,
860 int *this_best_prio, struct rq_iterator *iterator);
861
862static int
863iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
864 struct sched_domain *sd, enum cpu_idle_type idle,
865 struct rq_iterator *iterator);
e1d1484f 866#endif
dd41f596 867
d842de87
SV
868#ifdef CONFIG_CGROUP_CPUACCT
869static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
870#else
871static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
872#endif
873
dd41f596 874#include "sched_stats.h"
dd41f596 875#include "sched_idletask.c"
5522d5d5
IM
876#include "sched_fair.c"
877#include "sched_rt.c"
dd41f596
IM
878#ifdef CONFIG_SCHED_DEBUG
879# include "sched_debug.c"
880#endif
881
882#define sched_class_highest (&rt_sched_class)
883
29b4b623 884static inline void inc_load(struct rq *rq, const struct task_struct *p)
9c217245 885{
495eca49 886 update_load_add(&rq->load, p->se.load.weight);
9c217245
IM
887}
888
79b5dddf 889static inline void dec_load(struct rq *rq, const struct task_struct *p)
9c217245 890{
495eca49 891 update_load_sub(&rq->load, p->se.load.weight);
9c217245
IM
892}
893
e5fa2237 894static void inc_nr_running(struct task_struct *p, struct rq *rq)
9c217245
IM
895{
896 rq->nr_running++;
29b4b623 897 inc_load(rq, p);
9c217245
IM
898}
899
db53181e 900static void dec_nr_running(struct task_struct *p, struct rq *rq)
9c217245
IM
901{
902 rq->nr_running--;
79b5dddf 903 dec_load(rq, p);
9c217245
IM
904}
905
45bf76df
IM
906static void set_load_weight(struct task_struct *p)
907{
908 if (task_has_rt_policy(p)) {
dd41f596
IM
909 p->se.load.weight = prio_to_weight[0] * 2;
910 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
911 return;
912 }
45bf76df 913
dd41f596
IM
914 /*
915 * SCHED_IDLE tasks get minimal weight:
916 */
917 if (p->policy == SCHED_IDLE) {
918 p->se.load.weight = WEIGHT_IDLEPRIO;
919 p->se.load.inv_weight = WMULT_IDLEPRIO;
920 return;
921 }
71f8bd46 922
dd41f596
IM
923 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
924 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
71f8bd46
IM
925}
926
8159f87e 927static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
71f8bd46 928{
dd41f596 929 sched_info_queued(p);
fd390f6a 930 p->sched_class->enqueue_task(rq, p, wakeup);
dd41f596 931 p->se.on_rq = 1;
71f8bd46
IM
932}
933
69be72c1 934static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
71f8bd46 935{
f02231e5 936 p->sched_class->dequeue_task(rq, p, sleep);
dd41f596 937 p->se.on_rq = 0;
71f8bd46
IM
938}
939
14531189 940/*
dd41f596 941 * __normal_prio - return the priority that is based on the static prio
14531189 942 */
14531189
IM
943static inline int __normal_prio(struct task_struct *p)
944{
dd41f596 945 return p->static_prio;
14531189
IM
946}
947
b29739f9
IM
948/*
949 * Calculate the expected normal priority: i.e. priority
950 * without taking RT-inheritance into account. Might be
951 * boosted by interactivity modifiers. Changes upon fork,
952 * setprio syscalls, and whenever the interactivity
953 * estimator recalculates.
954 */
36c8b586 955static inline int normal_prio(struct task_struct *p)
b29739f9
IM
956{
957 int prio;
958
e05606d3 959 if (task_has_rt_policy(p))
b29739f9
IM
960 prio = MAX_RT_PRIO-1 - p->rt_priority;
961 else
962 prio = __normal_prio(p);
963 return prio;
964}
965
966/*
967 * Calculate the current priority, i.e. the priority
968 * taken into account by the scheduler. This value might
969 * be boosted by RT tasks, or might be boosted by
970 * interactivity modifiers. Will be RT if the task got
971 * RT-boosted. If not then it returns p->normal_prio.
972 */
36c8b586 973static int effective_prio(struct task_struct *p)
b29739f9
IM
974{
975 p->normal_prio = normal_prio(p);
976 /*
977 * If we are RT tasks or we were boosted to RT priority,
978 * keep the priority unchanged. Otherwise, update priority
979 * to the normal priority:
980 */
981 if (!rt_prio(p->prio))
982 return p->normal_prio;
983 return p->prio;
984}
985
1da177e4 986/*
dd41f596 987 * activate_task - move a task to the runqueue.
1da177e4 988 */
dd41f596 989static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1da177e4 990{
dd41f596
IM
991 if (p->state == TASK_UNINTERRUPTIBLE)
992 rq->nr_uninterruptible--;
1da177e4 993
8159f87e 994 enqueue_task(rq, p, wakeup);
e5fa2237 995 inc_nr_running(p, rq);
1da177e4
LT
996}
997
1da177e4
LT
998/*
999 * deactivate_task - remove a task from the runqueue.
1000 */
2e1cb74a 1001static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1da177e4 1002{
dd41f596
IM
1003 if (p->state == TASK_UNINTERRUPTIBLE)
1004 rq->nr_uninterruptible++;
1005
69be72c1 1006 dequeue_task(rq, p, sleep);
db53181e 1007 dec_nr_running(p, rq);
1da177e4
LT
1008}
1009
1da177e4
LT
1010/**
1011 * task_curr - is this task currently executing on a CPU?
1012 * @p: the task in question.
1013 */
36c8b586 1014inline int task_curr(const struct task_struct *p)
1da177e4
LT
1015{
1016 return cpu_curr(task_cpu(p)) == p;
1017}
1018
2dd73a4f
PW
1019/* Used instead of source_load when we know the type == 0 */
1020unsigned long weighted_cpuload(const int cpu)
1021{
495eca49 1022 return cpu_rq(cpu)->load.weight;
dd41f596
IM
1023}
1024
1025static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1026{
ce96b5ac 1027 set_task_cfs_rq(p, cpu);
dd41f596 1028#ifdef CONFIG_SMP
ce96b5ac
DA
1029 /*
1030 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1031 * successfuly executed on another CPU. We must ensure that updates of
1032 * per-task data have been completed by this moment.
1033 */
1034 smp_wmb();
dd41f596 1035 task_thread_info(p)->cpu = cpu;
dd41f596 1036#endif
2dd73a4f
PW
1037}
1038
1da177e4 1039#ifdef CONFIG_SMP
c65cc870 1040
cc367732
IM
1041/*
1042 * Is this task likely cache-hot:
1043 */
1044static inline int
1045task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1046{
1047 s64 delta;
1048
1049 if (p->sched_class != &fair_sched_class)
1050 return 0;
1051
6bc1665b
IM
1052 if (sysctl_sched_migration_cost == -1)
1053 return 1;
1054 if (sysctl_sched_migration_cost == 0)
1055 return 0;
1056
cc367732
IM
1057 delta = now - p->se.exec_start;
1058
1059 return delta < (s64)sysctl_sched_migration_cost;
1060}
1061
1062
dd41f596 1063void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 1064{
dd41f596
IM
1065 int old_cpu = task_cpu(p);
1066 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2830cf8c
SV
1067 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1068 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
bbdba7c0 1069 u64 clock_offset;
dd41f596
IM
1070
1071 clock_offset = old_rq->clock - new_rq->clock;
6cfb0d5d
IM
1072
1073#ifdef CONFIG_SCHEDSTATS
1074 if (p->se.wait_start)
1075 p->se.wait_start -= clock_offset;
dd41f596
IM
1076 if (p->se.sleep_start)
1077 p->se.sleep_start -= clock_offset;
1078 if (p->se.block_start)
1079 p->se.block_start -= clock_offset;
cc367732
IM
1080 if (old_cpu != new_cpu) {
1081 schedstat_inc(p, se.nr_migrations);
1082 if (task_hot(p, old_rq->clock, NULL))
1083 schedstat_inc(p, se.nr_forced2_migrations);
1084 }
6cfb0d5d 1085#endif
2830cf8c
SV
1086 p->se.vruntime -= old_cfsrq->min_vruntime -
1087 new_cfsrq->min_vruntime;
dd41f596
IM
1088
1089 __set_task_cpu(p, new_cpu);
c65cc870
IM
1090}
1091
70b97a7f 1092struct migration_req {
1da177e4 1093 struct list_head list;
1da177e4 1094
36c8b586 1095 struct task_struct *task;
1da177e4
LT
1096 int dest_cpu;
1097
1da177e4 1098 struct completion done;
70b97a7f 1099};
1da177e4
LT
1100
1101/*
1102 * The task's runqueue lock must be held.
1103 * Returns true if you have to wait for migration thread.
1104 */
36c8b586 1105static int
70b97a7f 1106migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1da177e4 1107{
70b97a7f 1108 struct rq *rq = task_rq(p);
1da177e4
LT
1109
1110 /*
1111 * If the task is not on a runqueue (and not running), then
1112 * it is sufficient to simply update the task's cpu field.
1113 */
dd41f596 1114 if (!p->se.on_rq && !task_running(rq, p)) {
1da177e4
LT
1115 set_task_cpu(p, dest_cpu);
1116 return 0;
1117 }
1118
1119 init_completion(&req->done);
1da177e4
LT
1120 req->task = p;
1121 req->dest_cpu = dest_cpu;
1122 list_add(&req->list, &rq->migration_queue);
48f24c4d 1123
1da177e4
LT
1124 return 1;
1125}
1126
1127/*
1128 * wait_task_inactive - wait for a thread to unschedule.
1129 *
1130 * The caller must ensure that the task *will* unschedule sometime soon,
1131 * else this function might spin for a *long* time. This function can't
1132 * be called with interrupts off, or it may introduce deadlock with
1133 * smp_call_function() if an IPI is sent by the same process we are
1134 * waiting to become inactive.
1135 */
36c8b586 1136void wait_task_inactive(struct task_struct *p)
1da177e4
LT
1137{
1138 unsigned long flags;
dd41f596 1139 int running, on_rq;
70b97a7f 1140 struct rq *rq;
1da177e4 1141
3a5c359a
AK
1142 for (;;) {
1143 /*
1144 * We do the initial early heuristics without holding
1145 * any task-queue locks at all. We'll only try to get
1146 * the runqueue lock when things look like they will
1147 * work out!
1148 */
1149 rq = task_rq(p);
fa490cfd 1150
3a5c359a
AK
1151 /*
1152 * If the task is actively running on another CPU
1153 * still, just relax and busy-wait without holding
1154 * any locks.
1155 *
1156 * NOTE! Since we don't hold any locks, it's not
1157 * even sure that "rq" stays as the right runqueue!
1158 * But we don't care, since "task_running()" will
1159 * return false if the runqueue has changed and p
1160 * is actually now running somewhere else!
1161 */
1162 while (task_running(rq, p))
1163 cpu_relax();
fa490cfd 1164
3a5c359a
AK
1165 /*
1166 * Ok, time to look more closely! We need the rq
1167 * lock now, to be *sure*. If we're wrong, we'll
1168 * just go back and repeat.
1169 */
1170 rq = task_rq_lock(p, &flags);
1171 running = task_running(rq, p);
1172 on_rq = p->se.on_rq;
1173 task_rq_unlock(rq, &flags);
fa490cfd 1174
3a5c359a
AK
1175 /*
1176 * Was it really running after all now that we
1177 * checked with the proper locks actually held?
1178 *
1179 * Oops. Go back and try again..
1180 */
1181 if (unlikely(running)) {
1182 cpu_relax();
1183 continue;
1184 }
fa490cfd 1185
3a5c359a
AK
1186 /*
1187 * It's not enough that it's not actively running,
1188 * it must be off the runqueue _entirely_, and not
1189 * preempted!
1190 *
1191 * So if it wa still runnable (but just not actively
1192 * running right now), it's preempted, and we should
1193 * yield - it could be a while.
1194 */
1195 if (unlikely(on_rq)) {
1196 schedule_timeout_uninterruptible(1);
1197 continue;
1198 }
fa490cfd 1199
3a5c359a
AK
1200 /*
1201 * Ahh, all good. It wasn't running, and it wasn't
1202 * runnable, which means that it will never become
1203 * running in the future either. We're all done!
1204 */
1205 break;
1206 }
1da177e4
LT
1207}
1208
1209/***
1210 * kick_process - kick a running thread to enter/exit the kernel
1211 * @p: the to-be-kicked thread
1212 *
1213 * Cause a process which is running on another CPU to enter
1214 * kernel-mode, without any delay. (to get signals handled.)
1215 *
1216 * NOTE: this function doesnt have to take the runqueue lock,
1217 * because all it wants to ensure is that the remote task enters
1218 * the kernel. If the IPI races and the task has been migrated
1219 * to another CPU then no harm is done and the purpose has been
1220 * achieved as well.
1221 */
36c8b586 1222void kick_process(struct task_struct *p)
1da177e4
LT
1223{
1224 int cpu;
1225
1226 preempt_disable();
1227 cpu = task_cpu(p);
1228 if ((cpu != smp_processor_id()) && task_curr(p))
1229 smp_send_reschedule(cpu);
1230 preempt_enable();
1231}
1232
1233/*
2dd73a4f
PW
1234 * Return a low guess at the load of a migration-source cpu weighted
1235 * according to the scheduling class and "nice" value.
1da177e4
LT
1236 *
1237 * We want to under-estimate the load of migration sources, to
1238 * balance conservatively.
1239 */
a9957449 1240static unsigned long source_load(int cpu, int type)
1da177e4 1241{
70b97a7f 1242 struct rq *rq = cpu_rq(cpu);
dd41f596 1243 unsigned long total = weighted_cpuload(cpu);
2dd73a4f 1244
3b0bd9bc 1245 if (type == 0)
dd41f596 1246 return total;
b910472d 1247
dd41f596 1248 return min(rq->cpu_load[type-1], total);
1da177e4
LT
1249}
1250
1251/*
2dd73a4f
PW
1252 * Return a high guess at the load of a migration-target cpu weighted
1253 * according to the scheduling class and "nice" value.
1da177e4 1254 */
a9957449 1255static unsigned long target_load(int cpu, int type)
1da177e4 1256{
70b97a7f 1257 struct rq *rq = cpu_rq(cpu);
dd41f596 1258 unsigned long total = weighted_cpuload(cpu);
2dd73a4f 1259
7897986b 1260 if (type == 0)
dd41f596 1261 return total;
3b0bd9bc 1262
dd41f596 1263 return max(rq->cpu_load[type-1], total);
2dd73a4f
PW
1264}
1265
1266/*
1267 * Return the average load per task on the cpu's run queue
1268 */
1269static inline unsigned long cpu_avg_load_per_task(int cpu)
1270{
70b97a7f 1271 struct rq *rq = cpu_rq(cpu);
dd41f596 1272 unsigned long total = weighted_cpuload(cpu);
2dd73a4f
PW
1273 unsigned long n = rq->nr_running;
1274
dd41f596 1275 return n ? total / n : SCHED_LOAD_SCALE;
1da177e4
LT
1276}
1277
147cbb4b
NP
1278/*
1279 * find_idlest_group finds and returns the least busy CPU group within the
1280 * domain.
1281 */
1282static struct sched_group *
1283find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1284{
1285 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1286 unsigned long min_load = ULONG_MAX, this_load = 0;
1287 int load_idx = sd->forkexec_idx;
1288 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1289
1290 do {
1291 unsigned long load, avg_load;
1292 int local_group;
1293 int i;
1294
da5a5522
BD
1295 /* Skip over this group if it has no CPUs allowed */
1296 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
3a5c359a 1297 continue;
da5a5522 1298
147cbb4b 1299 local_group = cpu_isset(this_cpu, group->cpumask);
147cbb4b
NP
1300
1301 /* Tally up the load of all CPUs in the group */
1302 avg_load = 0;
1303
1304 for_each_cpu_mask(i, group->cpumask) {
1305 /* Bias balancing toward cpus of our domain */
1306 if (local_group)
1307 load = source_load(i, load_idx);
1308 else
1309 load = target_load(i, load_idx);
1310
1311 avg_load += load;
1312 }
1313
1314 /* Adjust by relative CPU power of the group */
5517d86b
ED
1315 avg_load = sg_div_cpu_power(group,
1316 avg_load * SCHED_LOAD_SCALE);
147cbb4b
NP
1317
1318 if (local_group) {
1319 this_load = avg_load;
1320 this = group;
1321 } else if (avg_load < min_load) {
1322 min_load = avg_load;
1323 idlest = group;
1324 }
3a5c359a 1325 } while (group = group->next, group != sd->groups);
147cbb4b
NP
1326
1327 if (!idlest || 100*this_load < imbalance*min_load)
1328 return NULL;
1329 return idlest;
1330}
1331
1332/*
0feaece9 1333 * find_idlest_cpu - find the idlest cpu among the cpus in group.
147cbb4b 1334 */
95cdf3b7
IM
1335static int
1336find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
147cbb4b 1337{
da5a5522 1338 cpumask_t tmp;
147cbb4b
NP
1339 unsigned long load, min_load = ULONG_MAX;
1340 int idlest = -1;
1341 int i;
1342
da5a5522
BD
1343 /* Traverse only the allowed CPUs */
1344 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1345
1346 for_each_cpu_mask(i, tmp) {
2dd73a4f 1347 load = weighted_cpuload(i);
147cbb4b
NP
1348
1349 if (load < min_load || (load == min_load && i == this_cpu)) {
1350 min_load = load;
1351 idlest = i;
1352 }
1353 }
1354
1355 return idlest;
1356}
1357
476d139c
NP
1358/*
1359 * sched_balance_self: balance the current task (running on cpu) in domains
1360 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1361 * SD_BALANCE_EXEC.
1362 *
1363 * Balance, ie. select the least loaded group.
1364 *
1365 * Returns the target CPU number, or the same CPU if no balancing is needed.
1366 *
1367 * preempt must be disabled.
1368 */
1369static int sched_balance_self(int cpu, int flag)
1370{
1371 struct task_struct *t = current;
1372 struct sched_domain *tmp, *sd = NULL;
147cbb4b 1373
c96d145e 1374 for_each_domain(cpu, tmp) {
9761eea8
IM
1375 /*
1376 * If power savings logic is enabled for a domain, stop there.
1377 */
5c45bf27
SS
1378 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1379 break;
476d139c
NP
1380 if (tmp->flags & flag)
1381 sd = tmp;
c96d145e 1382 }
476d139c
NP
1383
1384 while (sd) {
1385 cpumask_t span;
1386 struct sched_group *group;
1a848870
SS
1387 int new_cpu, weight;
1388
1389 if (!(sd->flags & flag)) {
1390 sd = sd->child;
1391 continue;
1392 }
476d139c
NP
1393
1394 span = sd->span;
1395 group = find_idlest_group(sd, t, cpu);
1a848870
SS
1396 if (!group) {
1397 sd = sd->child;
1398 continue;
1399 }
476d139c 1400
da5a5522 1401 new_cpu = find_idlest_cpu(group, t, cpu);
1a848870
SS
1402 if (new_cpu == -1 || new_cpu == cpu) {
1403 /* Now try balancing at a lower domain level of cpu */
1404 sd = sd->child;
1405 continue;
1406 }
476d139c 1407
1a848870 1408 /* Now try balancing at a lower domain level of new_cpu */
476d139c 1409 cpu = new_cpu;
476d139c
NP
1410 sd = NULL;
1411 weight = cpus_weight(span);
1412 for_each_domain(cpu, tmp) {
1413 if (weight <= cpus_weight(tmp->span))
1414 break;
1415 if (tmp->flags & flag)
1416 sd = tmp;
1417 }
1418 /* while loop will break here if sd == NULL */
1419 }
1420
1421 return cpu;
1422}
1423
1424#endif /* CONFIG_SMP */
1da177e4
LT
1425
1426/*
1427 * wake_idle() will wake a task on an idle cpu if task->cpu is
1428 * not idle and an idle cpu is available. The span of cpus to
1429 * search starts with cpus closest then further out as needed,
1430 * so we always favor a closer, idle cpu.
1431 *
1432 * Returns the CPU we should wake onto.
1433 */
1434#if defined(ARCH_HAS_SCHED_WAKE_IDLE)
36c8b586 1435static int wake_idle(int cpu, struct task_struct *p)
1da177e4
LT
1436{
1437 cpumask_t tmp;
1438 struct sched_domain *sd;
1439 int i;
1440
4953198b
SS
1441 /*
1442 * If it is idle, then it is the best cpu to run this task.
1443 *
1444 * This cpu is also the best, if it has more than one task already.
1445 * Siblings must be also busy(in most cases) as they didn't already
1446 * pickup the extra load from this cpu and hence we need not check
1447 * sibling runqueue info. This will avoid the checks and cache miss
1448 * penalities associated with that.
1449 */
1450 if (idle_cpu(cpu) || cpu_rq(cpu)->nr_running > 1)
1da177e4
LT
1451 return cpu;
1452
1453 for_each_domain(cpu, sd) {
1454 if (sd->flags & SD_WAKE_IDLE) {
e0f364f4 1455 cpus_and(tmp, sd->span, p->cpus_allowed);
1da177e4 1456 for_each_cpu_mask(i, tmp) {
cc367732
IM
1457 if (idle_cpu(i)) {
1458 if (i != task_cpu(p)) {
1459 schedstat_inc(p,
1460 se.nr_wakeups_idle);
1461 }
1da177e4 1462 return i;
cc367732 1463 }
1da177e4 1464 }
9761eea8 1465 } else {
e0f364f4 1466 break;
9761eea8 1467 }
1da177e4
LT
1468 }
1469 return cpu;
1470}
1471#else
36c8b586 1472static inline int wake_idle(int cpu, struct task_struct *p)
1da177e4
LT
1473{
1474 return cpu;
1475}
1476#endif
1477
1478/***
1479 * try_to_wake_up - wake up a thread
1480 * @p: the to-be-woken-up thread
1481 * @state: the mask of task states that can be woken
1482 * @sync: do a synchronous wakeup?
1483 *
1484 * Put it on the run-queue if it's not already there. The "current"
1485 * thread is always on the run-queue (except when the actual
1486 * re-schedule is in progress), and as such you're allowed to do
1487 * the simpler "current->state = TASK_RUNNING" to mark yourself
1488 * runnable without the overhead of this.
1489 *
1490 * returns failure only if the task is already active.
1491 */
36c8b586 1492static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1da177e4 1493{
cc367732 1494 int cpu, orig_cpu, this_cpu, success = 0;
1da177e4
LT
1495 unsigned long flags;
1496 long old_state;
70b97a7f 1497 struct rq *rq;
1da177e4 1498#ifdef CONFIG_SMP
7897986b 1499 struct sched_domain *sd, *this_sd = NULL;
70b97a7f 1500 unsigned long load, this_load;
1da177e4
LT
1501 int new_cpu;
1502#endif
1503
1504 rq = task_rq_lock(p, &flags);
1505 old_state = p->state;
1506 if (!(old_state & state))
1507 goto out;
1508
dd41f596 1509 if (p->se.on_rq)
1da177e4
LT
1510 goto out_running;
1511
1512 cpu = task_cpu(p);
cc367732 1513 orig_cpu = cpu;
1da177e4
LT
1514 this_cpu = smp_processor_id();
1515
1516#ifdef CONFIG_SMP
1517 if (unlikely(task_running(rq, p)))
1518 goto out_activate;
1519
7897986b
NP
1520 new_cpu = cpu;
1521
2d72376b 1522 schedstat_inc(rq, ttwu_count);
1da177e4
LT
1523 if (cpu == this_cpu) {
1524 schedstat_inc(rq, ttwu_local);
7897986b
NP
1525 goto out_set_cpu;
1526 }
1527
1528 for_each_domain(this_cpu, sd) {
1529 if (cpu_isset(cpu, sd->span)) {
1530 schedstat_inc(sd, ttwu_wake_remote);
1531 this_sd = sd;
1532 break;
1da177e4
LT
1533 }
1534 }
1da177e4 1535
7897986b 1536 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1da177e4
LT
1537 goto out_set_cpu;
1538
1da177e4 1539 /*
7897986b 1540 * Check for affine wakeup and passive balancing possibilities.
1da177e4 1541 */
7897986b
NP
1542 if (this_sd) {
1543 int idx = this_sd->wake_idx;
1544 unsigned int imbalance;
1da177e4 1545
a3f21bce
NP
1546 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1547
7897986b
NP
1548 load = source_load(cpu, idx);
1549 this_load = target_load(this_cpu, idx);
1da177e4 1550
7897986b
NP
1551 new_cpu = this_cpu; /* Wake to this CPU if we can */
1552
a3f21bce
NP
1553 if (this_sd->flags & SD_WAKE_AFFINE) {
1554 unsigned long tl = this_load;
33859f7f
MOS
1555 unsigned long tl_per_task;
1556
71e20f18
IM
1557 /*
1558 * Attract cache-cold tasks on sync wakeups:
1559 */
1560 if (sync && !task_hot(p, rq->clock, this_sd))
1561 goto out_set_cpu;
1562
cc367732 1563 schedstat_inc(p, se.nr_wakeups_affine_attempts);
33859f7f 1564 tl_per_task = cpu_avg_load_per_task(this_cpu);
2dd73a4f 1565
1da177e4 1566 /*
a3f21bce
NP
1567 * If sync wakeup then subtract the (maximum possible)
1568 * effect of the currently running task from the load
1569 * of the current CPU:
1da177e4 1570 */
a3f21bce 1571 if (sync)
dd41f596 1572 tl -= current->se.load.weight;
a3f21bce
NP
1573
1574 if ((tl <= load &&
2dd73a4f 1575 tl + target_load(cpu, idx) <= tl_per_task) ||
dd41f596 1576 100*(tl + p->se.load.weight) <= imbalance*load) {
a3f21bce
NP
1577 /*
1578 * This domain has SD_WAKE_AFFINE and
1579 * p is cache cold in this domain, and
1580 * there is no bad imbalance.
1581 */
1582 schedstat_inc(this_sd, ttwu_move_affine);
cc367732 1583 schedstat_inc(p, se.nr_wakeups_affine);
a3f21bce
NP
1584 goto out_set_cpu;
1585 }
1586 }
1587
1588 /*
1589 * Start passive balancing when half the imbalance_pct
1590 * limit is reached.
1591 */
1592 if (this_sd->flags & SD_WAKE_BALANCE) {
1593 if (imbalance*this_load <= 100*load) {
1594 schedstat_inc(this_sd, ttwu_move_balance);
cc367732 1595 schedstat_inc(p, se.nr_wakeups_passive);
a3f21bce
NP
1596 goto out_set_cpu;
1597 }
1da177e4
LT
1598 }
1599 }
1600
1601 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1602out_set_cpu:
1603 new_cpu = wake_idle(new_cpu, p);
1604 if (new_cpu != cpu) {
1605 set_task_cpu(p, new_cpu);
1606 task_rq_unlock(rq, &flags);
1607 /* might preempt at this point */
1608 rq = task_rq_lock(p, &flags);
1609 old_state = p->state;
1610 if (!(old_state & state))
1611 goto out;
dd41f596 1612 if (p->se.on_rq)
1da177e4
LT
1613 goto out_running;
1614
1615 this_cpu = smp_processor_id();
1616 cpu = task_cpu(p);
1617 }
1618
1619out_activate:
1620#endif /* CONFIG_SMP */
cc367732
IM
1621 schedstat_inc(p, se.nr_wakeups);
1622 if (sync)
1623 schedstat_inc(p, se.nr_wakeups_sync);
1624 if (orig_cpu != cpu)
1625 schedstat_inc(p, se.nr_wakeups_migrate);
1626 if (cpu == this_cpu)
1627 schedstat_inc(p, se.nr_wakeups_local);
1628 else
1629 schedstat_inc(p, se.nr_wakeups_remote);
2daa3577 1630 update_rq_clock(rq);
dd41f596 1631 activate_task(rq, p, 1);
9c63d9c0 1632 check_preempt_curr(rq, p);
1da177e4
LT
1633 success = 1;
1634
1635out_running:
1636 p->state = TASK_RUNNING;
1637out:
1638 task_rq_unlock(rq, &flags);
1639
1640 return success;
1641}
1642
36c8b586 1643int fastcall wake_up_process(struct task_struct *p)
1da177e4
LT
1644{
1645 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1646 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1647}
1da177e4
LT
1648EXPORT_SYMBOL(wake_up_process);
1649
36c8b586 1650int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
1651{
1652 return try_to_wake_up(p, state, 0);
1653}
1654
1da177e4
LT
1655/*
1656 * Perform scheduler related setup for a newly forked process p.
1657 * p is forked by current.
dd41f596
IM
1658 *
1659 * __sched_fork() is basic setup used by init_idle() too:
1660 */
1661static void __sched_fork(struct task_struct *p)
1662{
dd41f596
IM
1663 p->se.exec_start = 0;
1664 p->se.sum_exec_runtime = 0;
f6cf891c 1665 p->se.prev_sum_exec_runtime = 0;
6cfb0d5d
IM
1666
1667#ifdef CONFIG_SCHEDSTATS
1668 p->se.wait_start = 0;
dd41f596
IM
1669 p->se.sum_sleep_runtime = 0;
1670 p->se.sleep_start = 0;
dd41f596
IM
1671 p->se.block_start = 0;
1672 p->se.sleep_max = 0;
1673 p->se.block_max = 0;
1674 p->se.exec_max = 0;
eba1ed4b 1675 p->se.slice_max = 0;
dd41f596 1676 p->se.wait_max = 0;
6cfb0d5d 1677#endif
476d139c 1678
dd41f596
IM
1679 INIT_LIST_HEAD(&p->run_list);
1680 p->se.on_rq = 0;
476d139c 1681
e107be36
AK
1682#ifdef CONFIG_PREEMPT_NOTIFIERS
1683 INIT_HLIST_HEAD(&p->preempt_notifiers);
1684#endif
1685
1da177e4
LT
1686 /*
1687 * We mark the process as running here, but have not actually
1688 * inserted it onto the runqueue yet. This guarantees that
1689 * nobody will actually run it, and a signal or other external
1690 * event cannot wake it up and insert it on the runqueue either.
1691 */
1692 p->state = TASK_RUNNING;
dd41f596
IM
1693}
1694
1695/*
1696 * fork()/clone()-time setup:
1697 */
1698void sched_fork(struct task_struct *p, int clone_flags)
1699{
1700 int cpu = get_cpu();
1701
1702 __sched_fork(p);
1703
1704#ifdef CONFIG_SMP
1705 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1706#endif
02e4bac2 1707 set_task_cpu(p, cpu);
b29739f9
IM
1708
1709 /*
1710 * Make sure we do not leak PI boosting priority to the child:
1711 */
1712 p->prio = current->normal_prio;
2ddbf952
HS
1713 if (!rt_prio(p->prio))
1714 p->sched_class = &fair_sched_class;
b29739f9 1715
52f17b6c 1716#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
dd41f596 1717 if (likely(sched_info_on()))
52f17b6c 1718 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 1719#endif
d6077cb8 1720#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4866cde0
NP
1721 p->oncpu = 0;
1722#endif
1da177e4 1723#ifdef CONFIG_PREEMPT
4866cde0 1724 /* Want to start with kernel preemption disabled. */
a1261f54 1725 task_thread_info(p)->preempt_count = 1;
1da177e4 1726#endif
476d139c 1727 put_cpu();
1da177e4
LT
1728}
1729
1730/*
1731 * wake_up_new_task - wake up a newly created task for the first time.
1732 *
1733 * This function will do some initial scheduler statistics housekeeping
1734 * that must be done for every newly created context, then puts the task
1735 * on the runqueue and wakes it.
1736 */
36c8b586 1737void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1da177e4
LT
1738{
1739 unsigned long flags;
dd41f596 1740 struct rq *rq;
1da177e4
LT
1741
1742 rq = task_rq_lock(p, &flags);
147cbb4b 1743 BUG_ON(p->state != TASK_RUNNING);
a8e504d2 1744 update_rq_clock(rq);
1da177e4
LT
1745
1746 p->prio = effective_prio(p);
1747
b9dca1e0 1748 if (!p->sched_class->task_new || !current->se.on_rq) {
dd41f596 1749 activate_task(rq, p, 0);
1da177e4 1750 } else {
1da177e4 1751 /*
dd41f596
IM
1752 * Let the scheduling class do new task startup
1753 * management (if any):
1da177e4 1754 */
ee0827d8 1755 p->sched_class->task_new(rq, p);
e5fa2237 1756 inc_nr_running(p, rq);
1da177e4 1757 }
dd41f596
IM
1758 check_preempt_curr(rq, p);
1759 task_rq_unlock(rq, &flags);
1da177e4
LT
1760}
1761
e107be36
AK
1762#ifdef CONFIG_PREEMPT_NOTIFIERS
1763
1764/**
421cee29
RD
1765 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
1766 * @notifier: notifier struct to register
e107be36
AK
1767 */
1768void preempt_notifier_register(struct preempt_notifier *notifier)
1769{
1770 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1771}
1772EXPORT_SYMBOL_GPL(preempt_notifier_register);
1773
1774/**
1775 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 1776 * @notifier: notifier struct to unregister
e107be36
AK
1777 *
1778 * This is safe to call from within a preemption notifier.
1779 */
1780void preempt_notifier_unregister(struct preempt_notifier *notifier)
1781{
1782 hlist_del(&notifier->link);
1783}
1784EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1785
1786static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1787{
1788 struct preempt_notifier *notifier;
1789 struct hlist_node *node;
1790
1791 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1792 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1793}
1794
1795static void
1796fire_sched_out_preempt_notifiers(struct task_struct *curr,
1797 struct task_struct *next)
1798{
1799 struct preempt_notifier *notifier;
1800 struct hlist_node *node;
1801
1802 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1803 notifier->ops->sched_out(notifier, next);
1804}
1805
1806#else
1807
1808static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1809{
1810}
1811
1812static void
1813fire_sched_out_preempt_notifiers(struct task_struct *curr,
1814 struct task_struct *next)
1815{
1816}
1817
1818#endif
1819
4866cde0
NP
1820/**
1821 * prepare_task_switch - prepare to switch tasks
1822 * @rq: the runqueue preparing to switch
421cee29 1823 * @prev: the current task that is being switched out
4866cde0
NP
1824 * @next: the task we are going to switch to.
1825 *
1826 * This is called with the rq lock held and interrupts off. It must
1827 * be paired with a subsequent finish_task_switch after the context
1828 * switch.
1829 *
1830 * prepare_task_switch sets up locking and calls architecture specific
1831 * hooks.
1832 */
e107be36
AK
1833static inline void
1834prepare_task_switch(struct rq *rq, struct task_struct *prev,
1835 struct task_struct *next)
4866cde0 1836{
e107be36 1837 fire_sched_out_preempt_notifiers(prev, next);
4866cde0
NP
1838 prepare_lock_switch(rq, next);
1839 prepare_arch_switch(next);
1840}
1841
1da177e4
LT
1842/**
1843 * finish_task_switch - clean up after a task-switch
344babaa 1844 * @rq: runqueue associated with task-switch
1da177e4
LT
1845 * @prev: the thread we just switched away from.
1846 *
4866cde0
NP
1847 * finish_task_switch must be called after the context switch, paired
1848 * with a prepare_task_switch call before the context switch.
1849 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1850 * and do any other architecture-specific cleanup actions.
1da177e4
LT
1851 *
1852 * Note that we may have delayed dropping an mm in context_switch(). If
41a2d6cf 1853 * so, we finish that here outside of the runqueue lock. (Doing it
1da177e4
LT
1854 * with the lock held can cause deadlocks; see schedule() for
1855 * details.)
1856 */
a9957449 1857static void finish_task_switch(struct rq *rq, struct task_struct *prev)
1da177e4
LT
1858 __releases(rq->lock)
1859{
1da177e4 1860 struct mm_struct *mm = rq->prev_mm;
55a101f8 1861 long prev_state;
1da177e4
LT
1862
1863 rq->prev_mm = NULL;
1864
1865 /*
1866 * A task struct has one reference for the use as "current".
c394cc9f 1867 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
1868 * schedule one last time. The schedule call will never return, and
1869 * the scheduled task must drop that reference.
c394cc9f 1870 * The test for TASK_DEAD must occur while the runqueue locks are
1da177e4
LT
1871 * still held, otherwise prev could be scheduled on another cpu, die
1872 * there before we look at prev->state, and then the reference would
1873 * be dropped twice.
1874 * Manfred Spraul <manfred@colorfullife.com>
1875 */
55a101f8 1876 prev_state = prev->state;
4866cde0
NP
1877 finish_arch_switch(prev);
1878 finish_lock_switch(rq, prev);
e107be36 1879 fire_sched_in_preempt_notifiers(current);
1da177e4
LT
1880 if (mm)
1881 mmdrop(mm);
c394cc9f 1882 if (unlikely(prev_state == TASK_DEAD)) {
c6fd91f0 1883 /*
1884 * Remove function-return probe instances associated with this
1885 * task and put them back on the free list.
9761eea8 1886 */
c6fd91f0 1887 kprobe_flush_task(prev);
1da177e4 1888 put_task_struct(prev);
c6fd91f0 1889 }
1da177e4
LT
1890}
1891
1892/**
1893 * schedule_tail - first thing a freshly forked thread must call.
1894 * @prev: the thread we just switched away from.
1895 */
36c8b586 1896asmlinkage void schedule_tail(struct task_struct *prev)
1da177e4
LT
1897 __releases(rq->lock)
1898{
70b97a7f
IM
1899 struct rq *rq = this_rq();
1900
4866cde0
NP
1901 finish_task_switch(rq, prev);
1902#ifdef __ARCH_WANT_UNLOCKED_CTXSW
1903 /* In this case, finish_task_switch does not reenable preemption */
1904 preempt_enable();
1905#endif
1da177e4 1906 if (current->set_child_tid)
b488893a 1907 put_user(task_pid_vnr(current), current->set_child_tid);
1da177e4
LT
1908}
1909
1910/*
1911 * context_switch - switch to the new MM and the new
1912 * thread's register state.
1913 */
dd41f596 1914static inline void
70b97a7f 1915context_switch(struct rq *rq, struct task_struct *prev,
36c8b586 1916 struct task_struct *next)
1da177e4 1917{
dd41f596 1918 struct mm_struct *mm, *oldmm;
1da177e4 1919
e107be36 1920 prepare_task_switch(rq, prev, next);
dd41f596
IM
1921 mm = next->mm;
1922 oldmm = prev->active_mm;
9226d125
ZA
1923 /*
1924 * For paravirt, this is coupled with an exit in switch_to to
1925 * combine the page table reload and the switch backend into
1926 * one hypercall.
1927 */
1928 arch_enter_lazy_cpu_mode();
1929
dd41f596 1930 if (unlikely(!mm)) {
1da177e4
LT
1931 next->active_mm = oldmm;
1932 atomic_inc(&oldmm->mm_count);
1933 enter_lazy_tlb(oldmm, next);
1934 } else
1935 switch_mm(oldmm, mm, next);
1936
dd41f596 1937 if (unlikely(!prev->mm)) {
1da177e4 1938 prev->active_mm = NULL;
1da177e4
LT
1939 rq->prev_mm = oldmm;
1940 }
3a5f5e48
IM
1941 /*
1942 * Since the runqueue lock will be released by the next
1943 * task (which is an invalid locking op but in the case
1944 * of the scheduler it's an obvious special-case), so we
1945 * do an early lockdep release here:
1946 */
1947#ifndef __ARCH_WANT_UNLOCKED_CTXSW
8a25d5de 1948 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3a5f5e48 1949#endif
1da177e4
LT
1950
1951 /* Here we just switch the register state and the stack. */
1952 switch_to(prev, next, prev);
1953
dd41f596
IM
1954 barrier();
1955 /*
1956 * this_rq must be evaluated again because prev may have moved
1957 * CPUs since it called schedule(), thus the 'rq' on its stack
1958 * frame will be invalid.
1959 */
1960 finish_task_switch(this_rq(), prev);
1da177e4
LT
1961}
1962
1963/*
1964 * nr_running, nr_uninterruptible and nr_context_switches:
1965 *
1966 * externally visible scheduler statistics: current number of runnable
1967 * threads, current number of uninterruptible-sleeping threads, total
1968 * number of context switches performed since bootup.
1969 */
1970unsigned long nr_running(void)
1971{
1972 unsigned long i, sum = 0;
1973
1974 for_each_online_cpu(i)
1975 sum += cpu_rq(i)->nr_running;
1976
1977 return sum;
1978}
1979
1980unsigned long nr_uninterruptible(void)
1981{
1982 unsigned long i, sum = 0;
1983
0a945022 1984 for_each_possible_cpu(i)
1da177e4
LT
1985 sum += cpu_rq(i)->nr_uninterruptible;
1986
1987 /*
1988 * Since we read the counters lockless, it might be slightly
1989 * inaccurate. Do not allow it to go below zero though:
1990 */
1991 if (unlikely((long)sum < 0))
1992 sum = 0;
1993
1994 return sum;
1995}
1996
1997unsigned long long nr_context_switches(void)
1998{
cc94abfc
SR
1999 int i;
2000 unsigned long long sum = 0;
1da177e4 2001
0a945022 2002 for_each_possible_cpu(i)
1da177e4
LT
2003 sum += cpu_rq(i)->nr_switches;
2004
2005 return sum;
2006}
2007
2008unsigned long nr_iowait(void)
2009{
2010 unsigned long i, sum = 0;
2011
0a945022 2012 for_each_possible_cpu(i)
1da177e4
LT
2013 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2014
2015 return sum;
2016}
2017
db1b1fef
JS
2018unsigned long nr_active(void)
2019{
2020 unsigned long i, running = 0, uninterruptible = 0;
2021
2022 for_each_online_cpu(i) {
2023 running += cpu_rq(i)->nr_running;
2024 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2025 }
2026
2027 if (unlikely((long)uninterruptible < 0))
2028 uninterruptible = 0;
2029
2030 return running + uninterruptible;
2031}
2032
48f24c4d 2033/*
dd41f596
IM
2034 * Update rq->cpu_load[] statistics. This function is usually called every
2035 * scheduler tick (TICK_NSEC).
48f24c4d 2036 */
dd41f596 2037static void update_cpu_load(struct rq *this_rq)
48f24c4d 2038{
495eca49 2039 unsigned long this_load = this_rq->load.weight;
dd41f596
IM
2040 int i, scale;
2041
2042 this_rq->nr_load_updates++;
dd41f596
IM
2043
2044 /* Update our load: */
2045 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2046 unsigned long old_load, new_load;
2047
2048 /* scale is effectively 1 << i now, and >> i divides by scale */
2049
2050 old_load = this_rq->cpu_load[i];
2051 new_load = this_load;
a25707f3
IM
2052 /*
2053 * Round up the averaging division if load is increasing. This
2054 * prevents us from getting stuck on 9 if the load is 10, for
2055 * example.
2056 */
2057 if (new_load > old_load)
2058 new_load += scale-1;
dd41f596
IM
2059 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2060 }
48f24c4d
IM
2061}
2062
dd41f596
IM
2063#ifdef CONFIG_SMP
2064
1da177e4
LT
2065/*
2066 * double_rq_lock - safely lock two runqueues
2067 *
2068 * Note this does not disable interrupts like task_rq_lock,
2069 * you need to do so manually before calling.
2070 */
70b97a7f 2071static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1da177e4
LT
2072 __acquires(rq1->lock)
2073 __acquires(rq2->lock)
2074{
054b9108 2075 BUG_ON(!irqs_disabled());
1da177e4
LT
2076 if (rq1 == rq2) {
2077 spin_lock(&rq1->lock);
2078 __acquire(rq2->lock); /* Fake it out ;) */
2079 } else {
c96d145e 2080 if (rq1 < rq2) {
1da177e4
LT
2081 spin_lock(&rq1->lock);
2082 spin_lock(&rq2->lock);
2083 } else {
2084 spin_lock(&rq2->lock);
2085 spin_lock(&rq1->lock);
2086 }
2087 }
6e82a3be
IM
2088 update_rq_clock(rq1);
2089 update_rq_clock(rq2);
1da177e4
LT
2090}
2091
2092/*
2093 * double_rq_unlock - safely unlock two runqueues
2094 *
2095 * Note this does not restore interrupts like task_rq_unlock,
2096 * you need to do so manually after calling.
2097 */
70b97a7f 2098static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1da177e4
LT
2099 __releases(rq1->lock)
2100 __releases(rq2->lock)
2101{
2102 spin_unlock(&rq1->lock);
2103 if (rq1 != rq2)
2104 spin_unlock(&rq2->lock);
2105 else
2106 __release(rq2->lock);
2107}
2108
2109/*
2110 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2111 */
70b97a7f 2112static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
1da177e4
LT
2113 __releases(this_rq->lock)
2114 __acquires(busiest->lock)
2115 __acquires(this_rq->lock)
2116{
054b9108
KK
2117 if (unlikely(!irqs_disabled())) {
2118 /* printk() doesn't work good under rq->lock */
2119 spin_unlock(&this_rq->lock);
2120 BUG_ON(1);
2121 }
1da177e4 2122 if (unlikely(!spin_trylock(&busiest->lock))) {
c96d145e 2123 if (busiest < this_rq) {
1da177e4
LT
2124 spin_unlock(&this_rq->lock);
2125 spin_lock(&busiest->lock);
2126 spin_lock(&this_rq->lock);
2127 } else
2128 spin_lock(&busiest->lock);
2129 }
2130}
2131
1da177e4
LT
2132/*
2133 * If dest_cpu is allowed for this process, migrate the task to it.
2134 * This is accomplished by forcing the cpu_allowed mask to only
41a2d6cf 2135 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1da177e4
LT
2136 * the cpu_allowed mask is restored.
2137 */
36c8b586 2138static void sched_migrate_task(struct task_struct *p, int dest_cpu)
1da177e4 2139{
70b97a7f 2140 struct migration_req req;
1da177e4 2141 unsigned long flags;
70b97a7f 2142 struct rq *rq;
1da177e4
LT
2143
2144 rq = task_rq_lock(p, &flags);
2145 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2146 || unlikely(cpu_is_offline(dest_cpu)))
2147 goto out;
2148
2149 /* force the process onto the specified CPU */
2150 if (migrate_task(p, dest_cpu, &req)) {
2151 /* Need to wait for migration thread (might exit: take ref). */
2152 struct task_struct *mt = rq->migration_thread;
36c8b586 2153
1da177e4
LT
2154 get_task_struct(mt);
2155 task_rq_unlock(rq, &flags);
2156 wake_up_process(mt);
2157 put_task_struct(mt);
2158 wait_for_completion(&req.done);
36c8b586 2159
1da177e4
LT
2160 return;
2161 }
2162out:
2163 task_rq_unlock(rq, &flags);
2164}
2165
2166/*
476d139c
NP
2167 * sched_exec - execve() is a valuable balancing opportunity, because at
2168 * this point the task has the smallest effective memory and cache footprint.
1da177e4
LT
2169 */
2170void sched_exec(void)
2171{
1da177e4 2172 int new_cpu, this_cpu = get_cpu();
476d139c 2173 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1da177e4 2174 put_cpu();
476d139c
NP
2175 if (new_cpu != this_cpu)
2176 sched_migrate_task(current, new_cpu);
1da177e4
LT
2177}
2178
2179/*
2180 * pull_task - move a task from a remote runqueue to the local runqueue.
2181 * Both runqueues must be locked.
2182 */
dd41f596
IM
2183static void pull_task(struct rq *src_rq, struct task_struct *p,
2184 struct rq *this_rq, int this_cpu)
1da177e4 2185{
2e1cb74a 2186 deactivate_task(src_rq, p, 0);
1da177e4 2187 set_task_cpu(p, this_cpu);
dd41f596 2188 activate_task(this_rq, p, 0);
1da177e4
LT
2189 /*
2190 * Note that idle threads have a prio of MAX_PRIO, for this test
2191 * to be always true for them.
2192 */
dd41f596 2193 check_preempt_curr(this_rq, p);
1da177e4
LT
2194}
2195
2196/*
2197 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2198 */
858119e1 2199static
70b97a7f 2200int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
d15bcfdb 2201 struct sched_domain *sd, enum cpu_idle_type idle,
95cdf3b7 2202 int *all_pinned)
1da177e4
LT
2203{
2204 /*
2205 * We do not migrate tasks that are:
2206 * 1) running (obviously), or
2207 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2208 * 3) are cache-hot on their current CPU.
2209 */
cc367732
IM
2210 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2211 schedstat_inc(p, se.nr_failed_migrations_affine);
1da177e4 2212 return 0;
cc367732 2213 }
81026794
NP
2214 *all_pinned = 0;
2215
cc367732
IM
2216 if (task_running(rq, p)) {
2217 schedstat_inc(p, se.nr_failed_migrations_running);
81026794 2218 return 0;
cc367732 2219 }
1da177e4 2220
da84d961
IM
2221 /*
2222 * Aggressive migration if:
2223 * 1) task is cache cold, or
2224 * 2) too many balance attempts have failed.
2225 */
2226
6bc1665b
IM
2227 if (!task_hot(p, rq->clock, sd) ||
2228 sd->nr_balance_failed > sd->cache_nice_tries) {
da84d961 2229#ifdef CONFIG_SCHEDSTATS
cc367732 2230 if (task_hot(p, rq->clock, sd)) {
da84d961 2231 schedstat_inc(sd, lb_hot_gained[idle]);
cc367732
IM
2232 schedstat_inc(p, se.nr_forced_migrations);
2233 }
da84d961
IM
2234#endif
2235 return 1;
2236 }
2237
cc367732
IM
2238 if (task_hot(p, rq->clock, sd)) {
2239 schedstat_inc(p, se.nr_failed_migrations_hot);
da84d961 2240 return 0;
cc367732 2241 }
1da177e4
LT
2242 return 1;
2243}
2244
e1d1484f
PW
2245static unsigned long
2246balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2247 unsigned long max_load_move, struct sched_domain *sd,
2248 enum cpu_idle_type idle, int *all_pinned,
2249 int *this_best_prio, struct rq_iterator *iterator)
1da177e4 2250{
b82d9fdd 2251 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
dd41f596
IM
2252 struct task_struct *p;
2253 long rem_load_move = max_load_move;
1da177e4 2254
e1d1484f 2255 if (max_load_move == 0)
1da177e4
LT
2256 goto out;
2257
81026794
NP
2258 pinned = 1;
2259
1da177e4 2260 /*
dd41f596 2261 * Start the load-balancing iterator:
1da177e4 2262 */
dd41f596
IM
2263 p = iterator->start(iterator->arg);
2264next:
b82d9fdd 2265 if (!p || loops++ > sysctl_sched_nr_migrate)
1da177e4 2266 goto out;
50ddd969 2267 /*
b82d9fdd 2268 * To help distribute high priority tasks across CPUs we don't
50ddd969
PW
2269 * skip a task if it will be the highest priority task (i.e. smallest
2270 * prio value) on its new queue regardless of its load weight
2271 */
dd41f596
IM
2272 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2273 SCHED_LOAD_SCALE_FUZZ;
a4ac01c3 2274 if ((skip_for_load && p->prio >= *this_best_prio) ||
dd41f596 2275 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
dd41f596
IM
2276 p = iterator->next(iterator->arg);
2277 goto next;
1da177e4
LT
2278 }
2279
dd41f596 2280 pull_task(busiest, p, this_rq, this_cpu);
1da177e4 2281 pulled++;
dd41f596 2282 rem_load_move -= p->se.load.weight;
1da177e4 2283
2dd73a4f 2284 /*
b82d9fdd 2285 * We only want to steal up to the prescribed amount of weighted load.
2dd73a4f 2286 */
e1d1484f 2287 if (rem_load_move > 0) {
a4ac01c3
PW
2288 if (p->prio < *this_best_prio)
2289 *this_best_prio = p->prio;
dd41f596
IM
2290 p = iterator->next(iterator->arg);
2291 goto next;
1da177e4
LT
2292 }
2293out:
2294 /*
e1d1484f 2295 * Right now, this is one of only two places pull_task() is called,
1da177e4
LT
2296 * so we can safely collect pull_task() stats here rather than
2297 * inside pull_task().
2298 */
2299 schedstat_add(sd, lb_gained[idle], pulled);
81026794
NP
2300
2301 if (all_pinned)
2302 *all_pinned = pinned;
e1d1484f
PW
2303
2304 return max_load_move - rem_load_move;
1da177e4
LT
2305}
2306
dd41f596 2307/*
43010659
PW
2308 * move_tasks tries to move up to max_load_move weighted load from busiest to
2309 * this_rq, as part of a balancing operation within domain "sd".
2310 * Returns 1 if successful and 0 otherwise.
dd41f596
IM
2311 *
2312 * Called with both runqueues locked.
2313 */
2314static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
43010659 2315 unsigned long max_load_move,
dd41f596
IM
2316 struct sched_domain *sd, enum cpu_idle_type idle,
2317 int *all_pinned)
2318{
5522d5d5 2319 const struct sched_class *class = sched_class_highest;
43010659 2320 unsigned long total_load_moved = 0;
a4ac01c3 2321 int this_best_prio = this_rq->curr->prio;
dd41f596
IM
2322
2323 do {
43010659
PW
2324 total_load_moved +=
2325 class->load_balance(this_rq, this_cpu, busiest,
e1d1484f 2326 max_load_move - total_load_moved,
a4ac01c3 2327 sd, idle, all_pinned, &this_best_prio);
dd41f596 2328 class = class->next;
43010659 2329 } while (class && max_load_move > total_load_moved);
dd41f596 2330
43010659
PW
2331 return total_load_moved > 0;
2332}
2333
e1d1484f
PW
2334static int
2335iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2336 struct sched_domain *sd, enum cpu_idle_type idle,
2337 struct rq_iterator *iterator)
2338{
2339 struct task_struct *p = iterator->start(iterator->arg);
2340 int pinned = 0;
2341
2342 while (p) {
2343 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2344 pull_task(busiest, p, this_rq, this_cpu);
2345 /*
2346 * Right now, this is only the second place pull_task()
2347 * is called, so we can safely collect pull_task()
2348 * stats here rather than inside pull_task().
2349 */
2350 schedstat_inc(sd, lb_gained[idle]);
2351
2352 return 1;
2353 }
2354 p = iterator->next(iterator->arg);
2355 }
2356
2357 return 0;
2358}
2359
43010659
PW
2360/*
2361 * move_one_task tries to move exactly one task from busiest to this_rq, as
2362 * part of active balancing operations within "domain".
2363 * Returns 1 if successful and 0 otherwise.
2364 *
2365 * Called with both runqueues locked.
2366 */
2367static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2368 struct sched_domain *sd, enum cpu_idle_type idle)
2369{
5522d5d5 2370 const struct sched_class *class;
43010659
PW
2371
2372 for (class = sched_class_highest; class; class = class->next)
e1d1484f 2373 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
43010659
PW
2374 return 1;
2375
2376 return 0;
dd41f596
IM
2377}
2378
1da177e4
LT
2379/*
2380 * find_busiest_group finds and returns the busiest CPU group within the
48f24c4d
IM
2381 * domain. It calculates and returns the amount of weighted load which
2382 * should be moved to restore balance via the imbalance parameter.
1da177e4
LT
2383 */
2384static struct sched_group *
2385find_busiest_group(struct sched_domain *sd, int this_cpu,
dd41f596
IM
2386 unsigned long *imbalance, enum cpu_idle_type idle,
2387 int *sd_idle, cpumask_t *cpus, int *balance)
1da177e4
LT
2388{
2389 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2390 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
0c117f1b 2391 unsigned long max_pull;
2dd73a4f
PW
2392 unsigned long busiest_load_per_task, busiest_nr_running;
2393 unsigned long this_load_per_task, this_nr_running;
908a7c1b 2394 int load_idx, group_imb = 0;
5c45bf27
SS
2395#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2396 int power_savings_balance = 1;
2397 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2398 unsigned long min_nr_running = ULONG_MAX;
2399 struct sched_group *group_min = NULL, *group_leader = NULL;
2400#endif
1da177e4
LT
2401
2402 max_load = this_load = total_load = total_pwr = 0;
2dd73a4f
PW
2403 busiest_load_per_task = busiest_nr_running = 0;
2404 this_load_per_task = this_nr_running = 0;
d15bcfdb 2405 if (idle == CPU_NOT_IDLE)
7897986b 2406 load_idx = sd->busy_idx;
d15bcfdb 2407 else if (idle == CPU_NEWLY_IDLE)
7897986b
NP
2408 load_idx = sd->newidle_idx;
2409 else
2410 load_idx = sd->idle_idx;
1da177e4
LT
2411
2412 do {
908a7c1b 2413 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
1da177e4
LT
2414 int local_group;
2415 int i;
908a7c1b 2416 int __group_imb = 0;
783609c6 2417 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2dd73a4f 2418 unsigned long sum_nr_running, sum_weighted_load;
1da177e4
LT
2419
2420 local_group = cpu_isset(this_cpu, group->cpumask);
2421
783609c6
SS
2422 if (local_group)
2423 balance_cpu = first_cpu(group->cpumask);
2424
1da177e4 2425 /* Tally up the load of all CPUs in the group */
2dd73a4f 2426 sum_weighted_load = sum_nr_running = avg_load = 0;
908a7c1b
KC
2427 max_cpu_load = 0;
2428 min_cpu_load = ~0UL;
1da177e4
LT
2429
2430 for_each_cpu_mask(i, group->cpumask) {
0a2966b4
CL
2431 struct rq *rq;
2432
2433 if (!cpu_isset(i, *cpus))
2434 continue;
2435
2436 rq = cpu_rq(i);
2dd73a4f 2437
9439aab8 2438 if (*sd_idle && rq->nr_running)
5969fe06
NP
2439 *sd_idle = 0;
2440
1da177e4 2441 /* Bias balancing toward cpus of our domain */
783609c6
SS
2442 if (local_group) {
2443 if (idle_cpu(i) && !first_idle_cpu) {
2444 first_idle_cpu = 1;
2445 balance_cpu = i;
2446 }
2447
a2000572 2448 load = target_load(i, load_idx);
908a7c1b 2449 } else {
a2000572 2450 load = source_load(i, load_idx);
908a7c1b
KC
2451 if (load > max_cpu_load)
2452 max_cpu_load = load;
2453 if (min_cpu_load > load)
2454 min_cpu_load = load;
2455 }
1da177e4
LT
2456
2457 avg_load += load;
2dd73a4f 2458 sum_nr_running += rq->nr_running;
dd41f596 2459 sum_weighted_load += weighted_cpuload(i);
1da177e4
LT
2460 }
2461
783609c6
SS
2462 /*
2463 * First idle cpu or the first cpu(busiest) in this sched group
2464 * is eligible for doing load balancing at this and above
9439aab8
SS
2465 * domains. In the newly idle case, we will allow all the cpu's
2466 * to do the newly idle load balance.
783609c6 2467 */
9439aab8
SS
2468 if (idle != CPU_NEWLY_IDLE && local_group &&
2469 balance_cpu != this_cpu && balance) {
783609c6
SS
2470 *balance = 0;
2471 goto ret;
2472 }
2473
1da177e4 2474 total_load += avg_load;
5517d86b 2475 total_pwr += group->__cpu_power;
1da177e4
LT
2476
2477 /* Adjust by relative CPU power of the group */
5517d86b
ED
2478 avg_load = sg_div_cpu_power(group,
2479 avg_load * SCHED_LOAD_SCALE);
1da177e4 2480
908a7c1b
KC
2481 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2482 __group_imb = 1;
2483
5517d86b 2484 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
5c45bf27 2485
1da177e4
LT
2486 if (local_group) {
2487 this_load = avg_load;
2488 this = group;
2dd73a4f
PW
2489 this_nr_running = sum_nr_running;
2490 this_load_per_task = sum_weighted_load;
2491 } else if (avg_load > max_load &&
908a7c1b 2492 (sum_nr_running > group_capacity || __group_imb)) {
1da177e4
LT
2493 max_load = avg_load;
2494 busiest = group;
2dd73a4f
PW
2495 busiest_nr_running = sum_nr_running;
2496 busiest_load_per_task = sum_weighted_load;
908a7c1b 2497 group_imb = __group_imb;
1da177e4 2498 }
5c45bf27
SS
2499
2500#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2501 /*
2502 * Busy processors will not participate in power savings
2503 * balance.
2504 */
dd41f596
IM
2505 if (idle == CPU_NOT_IDLE ||
2506 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2507 goto group_next;
5c45bf27
SS
2508
2509 /*
2510 * If the local group is idle or completely loaded
2511 * no need to do power savings balance at this domain
2512 */
2513 if (local_group && (this_nr_running >= group_capacity ||
2514 !this_nr_running))
2515 power_savings_balance = 0;
2516
dd41f596 2517 /*
5c45bf27
SS
2518 * If a group is already running at full capacity or idle,
2519 * don't include that group in power savings calculations
dd41f596
IM
2520 */
2521 if (!power_savings_balance || sum_nr_running >= group_capacity
5c45bf27 2522 || !sum_nr_running)
dd41f596 2523 goto group_next;
5c45bf27 2524
dd41f596 2525 /*
5c45bf27 2526 * Calculate the group which has the least non-idle load.
dd41f596
IM
2527 * This is the group from where we need to pick up the load
2528 * for saving power
2529 */
2530 if ((sum_nr_running < min_nr_running) ||
2531 (sum_nr_running == min_nr_running &&
5c45bf27
SS
2532 first_cpu(group->cpumask) <
2533 first_cpu(group_min->cpumask))) {
dd41f596
IM
2534 group_min = group;
2535 min_nr_running = sum_nr_running;
5c45bf27
SS
2536 min_load_per_task = sum_weighted_load /
2537 sum_nr_running;
dd41f596 2538 }
5c45bf27 2539
dd41f596 2540 /*
5c45bf27 2541 * Calculate the group which is almost near its
dd41f596
IM
2542 * capacity but still has some space to pick up some load
2543 * from other group and save more power
2544 */
2545 if (sum_nr_running <= group_capacity - 1) {
2546 if (sum_nr_running > leader_nr_running ||
2547 (sum_nr_running == leader_nr_running &&
2548 first_cpu(group->cpumask) >
2549 first_cpu(group_leader->cpumask))) {
2550 group_leader = group;
2551 leader_nr_running = sum_nr_running;
2552 }
48f24c4d 2553 }
5c45bf27
SS
2554group_next:
2555#endif
1da177e4
LT
2556 group = group->next;
2557 } while (group != sd->groups);
2558
2dd73a4f 2559 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
1da177e4
LT
2560 goto out_balanced;
2561
2562 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2563
2564 if (this_load >= avg_load ||
2565 100*max_load <= sd->imbalance_pct*this_load)
2566 goto out_balanced;
2567
2dd73a4f 2568 busiest_load_per_task /= busiest_nr_running;
908a7c1b
KC
2569 if (group_imb)
2570 busiest_load_per_task = min(busiest_load_per_task, avg_load);
2571
1da177e4
LT
2572 /*
2573 * We're trying to get all the cpus to the average_load, so we don't
2574 * want to push ourselves above the average load, nor do we wish to
2575 * reduce the max loaded cpu below the average load, as either of these
2576 * actions would just result in more rebalancing later, and ping-pong
2577 * tasks around. Thus we look for the minimum possible imbalance.
2578 * Negative imbalances (*we* are more loaded than anyone else) will
2579 * be counted as no imbalance for these purposes -- we can't fix that
41a2d6cf 2580 * by pulling tasks to us. Be careful of negative numbers as they'll
1da177e4
LT
2581 * appear as very large values with unsigned longs.
2582 */
2dd73a4f
PW
2583 if (max_load <= busiest_load_per_task)
2584 goto out_balanced;
2585
2586 /*
2587 * In the presence of smp nice balancing, certain scenarios can have
2588 * max load less than avg load(as we skip the groups at or below
2589 * its cpu_power, while calculating max_load..)
2590 */
2591 if (max_load < avg_load) {
2592 *imbalance = 0;
2593 goto small_imbalance;
2594 }
0c117f1b
SS
2595
2596 /* Don't want to pull so many tasks that a group would go idle */
2dd73a4f 2597 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
0c117f1b 2598
1da177e4 2599 /* How much load to actually move to equalise the imbalance */
5517d86b
ED
2600 *imbalance = min(max_pull * busiest->__cpu_power,
2601 (avg_load - this_load) * this->__cpu_power)
1da177e4
LT
2602 / SCHED_LOAD_SCALE;
2603
2dd73a4f
PW
2604 /*
2605 * if *imbalance is less than the average load per runnable task
2606 * there is no gaurantee that any tasks will be moved so we'll have
2607 * a think about bumping its value to force at least one task to be
2608 * moved
2609 */
7fd0d2dd 2610 if (*imbalance < busiest_load_per_task) {
48f24c4d 2611 unsigned long tmp, pwr_now, pwr_move;
2dd73a4f
PW
2612 unsigned int imbn;
2613
2614small_imbalance:
2615 pwr_move = pwr_now = 0;
2616 imbn = 2;
2617 if (this_nr_running) {
2618 this_load_per_task /= this_nr_running;
2619 if (busiest_load_per_task > this_load_per_task)
2620 imbn = 1;
2621 } else
2622 this_load_per_task = SCHED_LOAD_SCALE;
1da177e4 2623
dd41f596
IM
2624 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2625 busiest_load_per_task * imbn) {
2dd73a4f 2626 *imbalance = busiest_load_per_task;
1da177e4
LT
2627 return busiest;
2628 }
2629
2630 /*
2631 * OK, we don't have enough imbalance to justify moving tasks,
2632 * however we may be able to increase total CPU power used by
2633 * moving them.
2634 */
2635
5517d86b
ED
2636 pwr_now += busiest->__cpu_power *
2637 min(busiest_load_per_task, max_load);
2638 pwr_now += this->__cpu_power *
2639 min(this_load_per_task, this_load);
1da177e4
LT
2640 pwr_now /= SCHED_LOAD_SCALE;
2641
2642 /* Amount of load we'd subtract */
5517d86b
ED
2643 tmp = sg_div_cpu_power(busiest,
2644 busiest_load_per_task * SCHED_LOAD_SCALE);
1da177e4 2645 if (max_load > tmp)
5517d86b 2646 pwr_move += busiest->__cpu_power *
2dd73a4f 2647 min(busiest_load_per_task, max_load - tmp);
1da177e4
LT
2648
2649 /* Amount of load we'd add */
5517d86b 2650 if (max_load * busiest->__cpu_power <
33859f7f 2651 busiest_load_per_task * SCHED_LOAD_SCALE)
5517d86b
ED
2652 tmp = sg_div_cpu_power(this,
2653 max_load * busiest->__cpu_power);
1da177e4 2654 else
5517d86b
ED
2655 tmp = sg_div_cpu_power(this,
2656 busiest_load_per_task * SCHED_LOAD_SCALE);
2657 pwr_move += this->__cpu_power *
2658 min(this_load_per_task, this_load + tmp);
1da177e4
LT
2659 pwr_move /= SCHED_LOAD_SCALE;
2660
2661 /* Move if we gain throughput */
7fd0d2dd
SS
2662 if (pwr_move > pwr_now)
2663 *imbalance = busiest_load_per_task;
1da177e4
LT
2664 }
2665
1da177e4
LT
2666 return busiest;
2667
2668out_balanced:
5c45bf27 2669#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
d15bcfdb 2670 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
5c45bf27 2671 goto ret;
1da177e4 2672
5c45bf27
SS
2673 if (this == group_leader && group_leader != group_min) {
2674 *imbalance = min_load_per_task;
2675 return group_min;
2676 }
5c45bf27 2677#endif
783609c6 2678ret:
1da177e4
LT
2679 *imbalance = 0;
2680 return NULL;
2681}
2682
2683/*
2684 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2685 */
70b97a7f 2686static struct rq *
d15bcfdb 2687find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
0a2966b4 2688 unsigned long imbalance, cpumask_t *cpus)
1da177e4 2689{
70b97a7f 2690 struct rq *busiest = NULL, *rq;
2dd73a4f 2691 unsigned long max_load = 0;
1da177e4
LT
2692 int i;
2693
2694 for_each_cpu_mask(i, group->cpumask) {
dd41f596 2695 unsigned long wl;
0a2966b4
CL
2696
2697 if (!cpu_isset(i, *cpus))
2698 continue;
2699
48f24c4d 2700 rq = cpu_rq(i);
dd41f596 2701 wl = weighted_cpuload(i);
2dd73a4f 2702
dd41f596 2703 if (rq->nr_running == 1 && wl > imbalance)
2dd73a4f 2704 continue;
1da177e4 2705
dd41f596
IM
2706 if (wl > max_load) {
2707 max_load = wl;
48f24c4d 2708 busiest = rq;
1da177e4
LT
2709 }
2710 }
2711
2712 return busiest;
2713}
2714
77391d71
NP
2715/*
2716 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2717 * so long as it is large enough.
2718 */
2719#define MAX_PINNED_INTERVAL 512
2720
1da177e4
LT
2721/*
2722 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2723 * tasks if there is an imbalance.
1da177e4 2724 */
70b97a7f 2725static int load_balance(int this_cpu, struct rq *this_rq,
d15bcfdb 2726 struct sched_domain *sd, enum cpu_idle_type idle,
783609c6 2727 int *balance)
1da177e4 2728{
43010659 2729 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
1da177e4 2730 struct sched_group *group;
1da177e4 2731 unsigned long imbalance;
70b97a7f 2732 struct rq *busiest;
0a2966b4 2733 cpumask_t cpus = CPU_MASK_ALL;
fe2eea3f 2734 unsigned long flags;
5969fe06 2735
89c4710e
SS
2736 /*
2737 * When power savings policy is enabled for the parent domain, idle
2738 * sibling can pick up load irrespective of busy siblings. In this case,
dd41f596 2739 * let the state of idle sibling percolate up as CPU_IDLE, instead of
d15bcfdb 2740 * portraying it as CPU_NOT_IDLE.
89c4710e 2741 */
d15bcfdb 2742 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2743 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2744 sd_idle = 1;
1da177e4 2745
2d72376b 2746 schedstat_inc(sd, lb_count[idle]);
1da177e4 2747
0a2966b4
CL
2748redo:
2749 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
783609c6
SS
2750 &cpus, balance);
2751
06066714 2752 if (*balance == 0)
783609c6 2753 goto out_balanced;
783609c6 2754
1da177e4
LT
2755 if (!group) {
2756 schedstat_inc(sd, lb_nobusyg[idle]);
2757 goto out_balanced;
2758 }
2759
0a2966b4 2760 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
1da177e4
LT
2761 if (!busiest) {
2762 schedstat_inc(sd, lb_nobusyq[idle]);
2763 goto out_balanced;
2764 }
2765
db935dbd 2766 BUG_ON(busiest == this_rq);
1da177e4
LT
2767
2768 schedstat_add(sd, lb_imbalance[idle], imbalance);
2769
43010659 2770 ld_moved = 0;
1da177e4
LT
2771 if (busiest->nr_running > 1) {
2772 /*
2773 * Attempt to move tasks. If find_busiest_group has found
2774 * an imbalance but busiest->nr_running <= 1, the group is
43010659 2775 * still unbalanced. ld_moved simply stays zero, so it is
1da177e4
LT
2776 * correctly treated as an imbalance.
2777 */
fe2eea3f 2778 local_irq_save(flags);
e17224bf 2779 double_rq_lock(this_rq, busiest);
43010659 2780 ld_moved = move_tasks(this_rq, this_cpu, busiest,
48f24c4d 2781 imbalance, sd, idle, &all_pinned);
e17224bf 2782 double_rq_unlock(this_rq, busiest);
fe2eea3f 2783 local_irq_restore(flags);
81026794 2784
46cb4b7c
SS
2785 /*
2786 * some other cpu did the load balance for us.
2787 */
43010659 2788 if (ld_moved && this_cpu != smp_processor_id())
46cb4b7c
SS
2789 resched_cpu(this_cpu);
2790
81026794 2791 /* All tasks on this runqueue were pinned by CPU affinity */
0a2966b4
CL
2792 if (unlikely(all_pinned)) {
2793 cpu_clear(cpu_of(busiest), cpus);
2794 if (!cpus_empty(cpus))
2795 goto redo;
81026794 2796 goto out_balanced;
0a2966b4 2797 }
1da177e4 2798 }
81026794 2799
43010659 2800 if (!ld_moved) {
1da177e4
LT
2801 schedstat_inc(sd, lb_failed[idle]);
2802 sd->nr_balance_failed++;
2803
2804 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1da177e4 2805
fe2eea3f 2806 spin_lock_irqsave(&busiest->lock, flags);
fa3b6ddc
SS
2807
2808 /* don't kick the migration_thread, if the curr
2809 * task on busiest cpu can't be moved to this_cpu
2810 */
2811 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
fe2eea3f 2812 spin_unlock_irqrestore(&busiest->lock, flags);
fa3b6ddc
SS
2813 all_pinned = 1;
2814 goto out_one_pinned;
2815 }
2816
1da177e4
LT
2817 if (!busiest->active_balance) {
2818 busiest->active_balance = 1;
2819 busiest->push_cpu = this_cpu;
81026794 2820 active_balance = 1;
1da177e4 2821 }
fe2eea3f 2822 spin_unlock_irqrestore(&busiest->lock, flags);
81026794 2823 if (active_balance)
1da177e4
LT
2824 wake_up_process(busiest->migration_thread);
2825
2826 /*
2827 * We've kicked active balancing, reset the failure
2828 * counter.
2829 */
39507451 2830 sd->nr_balance_failed = sd->cache_nice_tries+1;
1da177e4 2831 }
81026794 2832 } else
1da177e4
LT
2833 sd->nr_balance_failed = 0;
2834
81026794 2835 if (likely(!active_balance)) {
1da177e4
LT
2836 /* We were unbalanced, so reset the balancing interval */
2837 sd->balance_interval = sd->min_interval;
81026794
NP
2838 } else {
2839 /*
2840 * If we've begun active balancing, start to back off. This
2841 * case may not be covered by the all_pinned logic if there
2842 * is only 1 task on the busy runqueue (because we don't call
2843 * move_tasks).
2844 */
2845 if (sd->balance_interval < sd->max_interval)
2846 sd->balance_interval *= 2;
1da177e4
LT
2847 }
2848
43010659 2849 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2850 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2851 return -1;
43010659 2852 return ld_moved;
1da177e4
LT
2853
2854out_balanced:
1da177e4
LT
2855 schedstat_inc(sd, lb_balanced[idle]);
2856
16cfb1c0 2857 sd->nr_balance_failed = 0;
fa3b6ddc
SS
2858
2859out_one_pinned:
1da177e4 2860 /* tune up the balancing interval */
77391d71
NP
2861 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2862 (sd->balance_interval < sd->max_interval))
1da177e4
LT
2863 sd->balance_interval *= 2;
2864
48f24c4d 2865 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2866 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2867 return -1;
1da177e4
LT
2868 return 0;
2869}
2870
2871/*
2872 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2873 * tasks if there is an imbalance.
2874 *
d15bcfdb 2875 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
1da177e4
LT
2876 * this_rq is locked.
2877 */
48f24c4d 2878static int
70b97a7f 2879load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
1da177e4
LT
2880{
2881 struct sched_group *group;
70b97a7f 2882 struct rq *busiest = NULL;
1da177e4 2883 unsigned long imbalance;
43010659 2884 int ld_moved = 0;
5969fe06 2885 int sd_idle = 0;
969bb4e4 2886 int all_pinned = 0;
0a2966b4 2887 cpumask_t cpus = CPU_MASK_ALL;
5969fe06 2888
89c4710e
SS
2889 /*
2890 * When power savings policy is enabled for the parent domain, idle
2891 * sibling can pick up load irrespective of busy siblings. In this case,
2892 * let the state of idle sibling percolate up as IDLE, instead of
d15bcfdb 2893 * portraying it as CPU_NOT_IDLE.
89c4710e
SS
2894 */
2895 if (sd->flags & SD_SHARE_CPUPOWER &&
2896 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2897 sd_idle = 1;
1da177e4 2898
2d72376b 2899 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
0a2966b4 2900redo:
d15bcfdb 2901 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
783609c6 2902 &sd_idle, &cpus, NULL);
1da177e4 2903 if (!group) {
d15bcfdb 2904 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
16cfb1c0 2905 goto out_balanced;
1da177e4
LT
2906 }
2907
d15bcfdb 2908 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
0a2966b4 2909 &cpus);
db935dbd 2910 if (!busiest) {
d15bcfdb 2911 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
16cfb1c0 2912 goto out_balanced;
1da177e4
LT
2913 }
2914
db935dbd
NP
2915 BUG_ON(busiest == this_rq);
2916
d15bcfdb 2917 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
d6d5cfaf 2918
43010659 2919 ld_moved = 0;
d6d5cfaf
NP
2920 if (busiest->nr_running > 1) {
2921 /* Attempt to move tasks */
2922 double_lock_balance(this_rq, busiest);
6e82a3be
IM
2923 /* this_rq->clock is already updated */
2924 update_rq_clock(busiest);
43010659 2925 ld_moved = move_tasks(this_rq, this_cpu, busiest,
969bb4e4
SS
2926 imbalance, sd, CPU_NEWLY_IDLE,
2927 &all_pinned);
d6d5cfaf 2928 spin_unlock(&busiest->lock);
0a2966b4 2929
969bb4e4 2930 if (unlikely(all_pinned)) {
0a2966b4
CL
2931 cpu_clear(cpu_of(busiest), cpus);
2932 if (!cpus_empty(cpus))
2933 goto redo;
2934 }
d6d5cfaf
NP
2935 }
2936
43010659 2937 if (!ld_moved) {
d15bcfdb 2938 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
89c4710e
SS
2939 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2940 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06
NP
2941 return -1;
2942 } else
16cfb1c0 2943 sd->nr_balance_failed = 0;
1da177e4 2944
43010659 2945 return ld_moved;
16cfb1c0
NP
2946
2947out_balanced:
d15bcfdb 2948 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
48f24c4d 2949 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2950 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2951 return -1;
16cfb1c0 2952 sd->nr_balance_failed = 0;
48f24c4d 2953
16cfb1c0 2954 return 0;
1da177e4
LT
2955}
2956
2957/*
2958 * idle_balance is called by schedule() if this_cpu is about to become
2959 * idle. Attempts to pull tasks from other CPUs.
2960 */
70b97a7f 2961static void idle_balance(int this_cpu, struct rq *this_rq)
1da177e4
LT
2962{
2963 struct sched_domain *sd;
dd41f596
IM
2964 int pulled_task = -1;
2965 unsigned long next_balance = jiffies + HZ;
1da177e4
LT
2966
2967 for_each_domain(this_cpu, sd) {
92c4ca5c
CL
2968 unsigned long interval;
2969
2970 if (!(sd->flags & SD_LOAD_BALANCE))
2971 continue;
2972
2973 if (sd->flags & SD_BALANCE_NEWIDLE)
48f24c4d 2974 /* If we've pulled tasks over stop searching: */
1bd77f2d 2975 pulled_task = load_balance_newidle(this_cpu,
92c4ca5c
CL
2976 this_rq, sd);
2977
2978 interval = msecs_to_jiffies(sd->balance_interval);
2979 if (time_after(next_balance, sd->last_balance + interval))
2980 next_balance = sd->last_balance + interval;
2981 if (pulled_task)
2982 break;
1da177e4 2983 }
dd41f596 2984 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
1bd77f2d
CL
2985 /*
2986 * We are going idle. next_balance may be set based on
2987 * a busy processor. So reset next_balance.
2988 */
2989 this_rq->next_balance = next_balance;
dd41f596 2990 }
1da177e4
LT
2991}
2992
2993/*
2994 * active_load_balance is run by migration threads. It pushes running tasks
2995 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2996 * running on each physical CPU where possible, and avoids physical /
2997 * logical imbalances.
2998 *
2999 * Called with busiest_rq locked.
3000 */
70b97a7f 3001static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
1da177e4 3002{
39507451 3003 int target_cpu = busiest_rq->push_cpu;
70b97a7f
IM
3004 struct sched_domain *sd;
3005 struct rq *target_rq;
39507451 3006
48f24c4d 3007 /* Is there any task to move? */
39507451 3008 if (busiest_rq->nr_running <= 1)
39507451
NP
3009 return;
3010
3011 target_rq = cpu_rq(target_cpu);
1da177e4
LT
3012
3013 /*
39507451 3014 * This condition is "impossible", if it occurs
41a2d6cf 3015 * we need to fix it. Originally reported by
39507451 3016 * Bjorn Helgaas on a 128-cpu setup.
1da177e4 3017 */
39507451 3018 BUG_ON(busiest_rq == target_rq);
1da177e4 3019
39507451
NP
3020 /* move a task from busiest_rq to target_rq */
3021 double_lock_balance(busiest_rq, target_rq);
6e82a3be
IM
3022 update_rq_clock(busiest_rq);
3023 update_rq_clock(target_rq);
39507451
NP
3024
3025 /* Search for an sd spanning us and the target CPU. */
c96d145e 3026 for_each_domain(target_cpu, sd) {
39507451 3027 if ((sd->flags & SD_LOAD_BALANCE) &&
48f24c4d 3028 cpu_isset(busiest_cpu, sd->span))
39507451 3029 break;
c96d145e 3030 }
39507451 3031
48f24c4d 3032 if (likely(sd)) {
2d72376b 3033 schedstat_inc(sd, alb_count);
39507451 3034
43010659
PW
3035 if (move_one_task(target_rq, target_cpu, busiest_rq,
3036 sd, CPU_IDLE))
48f24c4d
IM
3037 schedstat_inc(sd, alb_pushed);
3038 else
3039 schedstat_inc(sd, alb_failed);
3040 }
39507451 3041 spin_unlock(&target_rq->lock);
1da177e4
LT
3042}
3043
46cb4b7c
SS
3044#ifdef CONFIG_NO_HZ
3045static struct {
3046 atomic_t load_balancer;
41a2d6cf 3047 cpumask_t cpu_mask;
46cb4b7c
SS
3048} nohz ____cacheline_aligned = {
3049 .load_balancer = ATOMIC_INIT(-1),
3050 .cpu_mask = CPU_MASK_NONE,
3051};
3052
7835b98b 3053/*
46cb4b7c
SS
3054 * This routine will try to nominate the ilb (idle load balancing)
3055 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3056 * load balancing on behalf of all those cpus. If all the cpus in the system
3057 * go into this tickless mode, then there will be no ilb owner (as there is
3058 * no need for one) and all the cpus will sleep till the next wakeup event
3059 * arrives...
3060 *
3061 * For the ilb owner, tick is not stopped. And this tick will be used
3062 * for idle load balancing. ilb owner will still be part of
3063 * nohz.cpu_mask..
7835b98b 3064 *
46cb4b7c
SS
3065 * While stopping the tick, this cpu will become the ilb owner if there
3066 * is no other owner. And will be the owner till that cpu becomes busy
3067 * or if all cpus in the system stop their ticks at which point
3068 * there is no need for ilb owner.
3069 *
3070 * When the ilb owner becomes busy, it nominates another owner, during the
3071 * next busy scheduler_tick()
3072 */
3073int select_nohz_load_balancer(int stop_tick)
3074{
3075 int cpu = smp_processor_id();
3076
3077 if (stop_tick) {
3078 cpu_set(cpu, nohz.cpu_mask);
3079 cpu_rq(cpu)->in_nohz_recently = 1;
3080
3081 /*
3082 * If we are going offline and still the leader, give up!
3083 */
3084 if (cpu_is_offline(cpu) &&
3085 atomic_read(&nohz.load_balancer) == cpu) {
3086 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3087 BUG();
3088 return 0;
3089 }
3090
3091 /* time for ilb owner also to sleep */
3092 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3093 if (atomic_read(&nohz.load_balancer) == cpu)
3094 atomic_set(&nohz.load_balancer, -1);
3095 return 0;
3096 }
3097
3098 if (atomic_read(&nohz.load_balancer) == -1) {
3099 /* make me the ilb owner */
3100 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3101 return 1;
3102 } else if (atomic_read(&nohz.load_balancer) == cpu)
3103 return 1;
3104 } else {
3105 if (!cpu_isset(cpu, nohz.cpu_mask))
3106 return 0;
3107
3108 cpu_clear(cpu, nohz.cpu_mask);
3109
3110 if (atomic_read(&nohz.load_balancer) == cpu)
3111 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3112 BUG();
3113 }
3114 return 0;
3115}
3116#endif
3117
3118static DEFINE_SPINLOCK(balancing);
3119
3120/*
7835b98b
CL
3121 * It checks each scheduling domain to see if it is due to be balanced,
3122 * and initiates a balancing operation if so.
3123 *
3124 * Balancing parameters are set up in arch_init_sched_domains.
3125 */
a9957449 3126static void rebalance_domains(int cpu, enum cpu_idle_type idle)
7835b98b 3127{
46cb4b7c
SS
3128 int balance = 1;
3129 struct rq *rq = cpu_rq(cpu);
7835b98b
CL
3130 unsigned long interval;
3131 struct sched_domain *sd;
46cb4b7c 3132 /* Earliest time when we have to do rebalance again */
c9819f45 3133 unsigned long next_balance = jiffies + 60*HZ;
f549da84 3134 int update_next_balance = 0;
1da177e4 3135
46cb4b7c 3136 for_each_domain(cpu, sd) {
1da177e4
LT
3137 if (!(sd->flags & SD_LOAD_BALANCE))
3138 continue;
3139
3140 interval = sd->balance_interval;
d15bcfdb 3141 if (idle != CPU_IDLE)
1da177e4
LT
3142 interval *= sd->busy_factor;
3143
3144 /* scale ms to jiffies */
3145 interval = msecs_to_jiffies(interval);
3146 if (unlikely(!interval))
3147 interval = 1;
dd41f596
IM
3148 if (interval > HZ*NR_CPUS/10)
3149 interval = HZ*NR_CPUS/10;
3150
1da177e4 3151
08c183f3
CL
3152 if (sd->flags & SD_SERIALIZE) {
3153 if (!spin_trylock(&balancing))
3154 goto out;
3155 }
3156
c9819f45 3157 if (time_after_eq(jiffies, sd->last_balance + interval)) {
46cb4b7c 3158 if (load_balance(cpu, rq, sd, idle, &balance)) {
fa3b6ddc
SS
3159 /*
3160 * We've pulled tasks over so either we're no
5969fe06
NP
3161 * longer idle, or one of our SMT siblings is
3162 * not idle.
3163 */
d15bcfdb 3164 idle = CPU_NOT_IDLE;
1da177e4 3165 }
1bd77f2d 3166 sd->last_balance = jiffies;
1da177e4 3167 }
08c183f3
CL
3168 if (sd->flags & SD_SERIALIZE)
3169 spin_unlock(&balancing);
3170out:
f549da84 3171 if (time_after(next_balance, sd->last_balance + interval)) {
c9819f45 3172 next_balance = sd->last_balance + interval;
f549da84
SS
3173 update_next_balance = 1;
3174 }
783609c6
SS
3175
3176 /*
3177 * Stop the load balance at this level. There is another
3178 * CPU in our sched group which is doing load balancing more
3179 * actively.
3180 */
3181 if (!balance)
3182 break;
1da177e4 3183 }
f549da84
SS
3184
3185 /*
3186 * next_balance will be updated only when there is a need.
3187 * When the cpu is attached to null domain for ex, it will not be
3188 * updated.
3189 */
3190 if (likely(update_next_balance))
3191 rq->next_balance = next_balance;
46cb4b7c
SS
3192}
3193
3194/*
3195 * run_rebalance_domains is triggered when needed from the scheduler tick.
3196 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3197 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3198 */
3199static void run_rebalance_domains(struct softirq_action *h)
3200{
dd41f596
IM
3201 int this_cpu = smp_processor_id();
3202 struct rq *this_rq = cpu_rq(this_cpu);
3203 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3204 CPU_IDLE : CPU_NOT_IDLE;
46cb4b7c 3205
dd41f596 3206 rebalance_domains(this_cpu, idle);
46cb4b7c
SS
3207
3208#ifdef CONFIG_NO_HZ
3209 /*
3210 * If this cpu is the owner for idle load balancing, then do the
3211 * balancing on behalf of the other idle cpus whose ticks are
3212 * stopped.
3213 */
dd41f596
IM
3214 if (this_rq->idle_at_tick &&
3215 atomic_read(&nohz.load_balancer) == this_cpu) {
46cb4b7c
SS
3216 cpumask_t cpus = nohz.cpu_mask;
3217 struct rq *rq;
3218 int balance_cpu;
3219
dd41f596 3220 cpu_clear(this_cpu, cpus);
46cb4b7c
SS
3221 for_each_cpu_mask(balance_cpu, cpus) {
3222 /*
3223 * If this cpu gets work to do, stop the load balancing
3224 * work being done for other cpus. Next load
3225 * balancing owner will pick it up.
3226 */
3227 if (need_resched())
3228 break;
3229
de0cf899 3230 rebalance_domains(balance_cpu, CPU_IDLE);
46cb4b7c
SS
3231
3232 rq = cpu_rq(balance_cpu);
dd41f596
IM
3233 if (time_after(this_rq->next_balance, rq->next_balance))
3234 this_rq->next_balance = rq->next_balance;
46cb4b7c
SS
3235 }
3236 }
3237#endif
3238}
3239
3240/*
3241 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3242 *
3243 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3244 * idle load balancing owner or decide to stop the periodic load balancing,
3245 * if the whole system is idle.
3246 */
dd41f596 3247static inline void trigger_load_balance(struct rq *rq, int cpu)
46cb4b7c 3248{
46cb4b7c
SS
3249#ifdef CONFIG_NO_HZ
3250 /*
3251 * If we were in the nohz mode recently and busy at the current
3252 * scheduler tick, then check if we need to nominate new idle
3253 * load balancer.
3254 */
3255 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3256 rq->in_nohz_recently = 0;
3257
3258 if (atomic_read(&nohz.load_balancer) == cpu) {
3259 cpu_clear(cpu, nohz.cpu_mask);
3260 atomic_set(&nohz.load_balancer, -1);
3261 }
3262
3263 if (atomic_read(&nohz.load_balancer) == -1) {
3264 /*
3265 * simple selection for now: Nominate the
3266 * first cpu in the nohz list to be the next
3267 * ilb owner.
3268 *
3269 * TBD: Traverse the sched domains and nominate
3270 * the nearest cpu in the nohz.cpu_mask.
3271 */
3272 int ilb = first_cpu(nohz.cpu_mask);
3273
3274 if (ilb != NR_CPUS)
3275 resched_cpu(ilb);
3276 }
3277 }
3278
3279 /*
3280 * If this cpu is idle and doing idle load balancing for all the
3281 * cpus with ticks stopped, is it time for that to stop?
3282 */
3283 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3284 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3285 resched_cpu(cpu);
3286 return;
3287 }
3288
3289 /*
3290 * If this cpu is idle and the idle load balancing is done by
3291 * someone else, then no need raise the SCHED_SOFTIRQ
3292 */
3293 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3294 cpu_isset(cpu, nohz.cpu_mask))
3295 return;
3296#endif
3297 if (time_after_eq(jiffies, rq->next_balance))
3298 raise_softirq(SCHED_SOFTIRQ);
1da177e4 3299}
dd41f596
IM
3300
3301#else /* CONFIG_SMP */
3302
1da177e4
LT
3303/*
3304 * on UP we do not need to balance between CPUs:
3305 */
70b97a7f 3306static inline void idle_balance(int cpu, struct rq *rq)
1da177e4
LT
3307{
3308}
dd41f596 3309
1da177e4
LT
3310#endif
3311
1da177e4
LT
3312DEFINE_PER_CPU(struct kernel_stat, kstat);
3313
3314EXPORT_PER_CPU_SYMBOL(kstat);
3315
3316/*
41b86e9c
IM
3317 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3318 * that have not yet been banked in case the task is currently running.
1da177e4 3319 */
41b86e9c 3320unsigned long long task_sched_runtime(struct task_struct *p)
1da177e4 3321{
1da177e4 3322 unsigned long flags;
41b86e9c
IM
3323 u64 ns, delta_exec;
3324 struct rq *rq;
48f24c4d 3325
41b86e9c
IM
3326 rq = task_rq_lock(p, &flags);
3327 ns = p->se.sum_exec_runtime;
051a1d1a 3328 if (task_current(rq, p)) {
a8e504d2
IM
3329 update_rq_clock(rq);
3330 delta_exec = rq->clock - p->se.exec_start;
41b86e9c
IM
3331 if ((s64)delta_exec > 0)
3332 ns += delta_exec;
3333 }
3334 task_rq_unlock(rq, &flags);
48f24c4d 3335
1da177e4
LT
3336 return ns;
3337}
3338
1da177e4
LT
3339/*
3340 * Account user cpu time to a process.
3341 * @p: the process that the cpu time gets accounted to
1da177e4
LT
3342 * @cputime: the cpu time spent in user space since the last update
3343 */
3344void account_user_time(struct task_struct *p, cputime_t cputime)
3345{
3346 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3347 cputime64_t tmp;
3348
3349 p->utime = cputime_add(p->utime, cputime);
3350
3351 /* Add user time to cpustat. */
3352 tmp = cputime_to_cputime64(cputime);
3353 if (TASK_NICE(p) > 0)
3354 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3355 else
3356 cpustat->user = cputime64_add(cpustat->user, tmp);
3357}
3358
94886b84
LV
3359/*
3360 * Account guest cpu time to a process.
3361 * @p: the process that the cpu time gets accounted to
3362 * @cputime: the cpu time spent in virtual machine since the last update
3363 */
f7402e03 3364static void account_guest_time(struct task_struct *p, cputime_t cputime)
94886b84
LV
3365{
3366 cputime64_t tmp;
3367 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3368
3369 tmp = cputime_to_cputime64(cputime);
3370
3371 p->utime = cputime_add(p->utime, cputime);
3372 p->gtime = cputime_add(p->gtime, cputime);
3373
3374 cpustat->user = cputime64_add(cpustat->user, tmp);
3375 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3376}
3377
c66f08be
MN
3378/*
3379 * Account scaled user cpu time to a process.
3380 * @p: the process that the cpu time gets accounted to
3381 * @cputime: the cpu time spent in user space since the last update
3382 */
3383void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3384{
3385 p->utimescaled = cputime_add(p->utimescaled, cputime);
3386}
3387
1da177e4
LT
3388/*
3389 * Account system cpu time to a process.
3390 * @p: the process that the cpu time gets accounted to
3391 * @hardirq_offset: the offset to subtract from hardirq_count()
3392 * @cputime: the cpu time spent in kernel space since the last update
3393 */
3394void account_system_time(struct task_struct *p, int hardirq_offset,
3395 cputime_t cputime)
3396{
3397 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
70b97a7f 3398 struct rq *rq = this_rq();
1da177e4
LT
3399 cputime64_t tmp;
3400
9778385d
CB
3401 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3402 return account_guest_time(p, cputime);
94886b84 3403
1da177e4
LT
3404 p->stime = cputime_add(p->stime, cputime);
3405
3406 /* Add system time to cpustat. */
3407 tmp = cputime_to_cputime64(cputime);
3408 if (hardirq_count() - hardirq_offset)
3409 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3410 else if (softirq_count())
3411 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
cfb52856 3412 else if (p != rq->idle)
1da177e4 3413 cpustat->system = cputime64_add(cpustat->system, tmp);
cfb52856 3414 else if (atomic_read(&rq->nr_iowait) > 0)
1da177e4
LT
3415 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3416 else
3417 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3418 /* Account for system time used */
3419 acct_update_integrals(p);
1da177e4
LT
3420}
3421
c66f08be
MN
3422/*
3423 * Account scaled system cpu time to a process.
3424 * @p: the process that the cpu time gets accounted to
3425 * @hardirq_offset: the offset to subtract from hardirq_count()
3426 * @cputime: the cpu time spent in kernel space since the last update
3427 */
3428void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3429{
3430 p->stimescaled = cputime_add(p->stimescaled, cputime);
3431}
3432
1da177e4
LT
3433/*
3434 * Account for involuntary wait time.
3435 * @p: the process from which the cpu time has been stolen
3436 * @steal: the cpu time spent in involuntary wait
3437 */
3438void account_steal_time(struct task_struct *p, cputime_t steal)
3439{
3440 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3441 cputime64_t tmp = cputime_to_cputime64(steal);
70b97a7f 3442 struct rq *rq = this_rq();
1da177e4
LT
3443
3444 if (p == rq->idle) {
3445 p->stime = cputime_add(p->stime, steal);
3446 if (atomic_read(&rq->nr_iowait) > 0)
3447 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3448 else
3449 cpustat->idle = cputime64_add(cpustat->idle, tmp);
cfb52856 3450 } else
1da177e4
LT
3451 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3452}
3453
7835b98b
CL
3454/*
3455 * This function gets called by the timer code, with HZ frequency.
3456 * We call it with interrupts disabled.
3457 *
3458 * It also gets called by the fork code, when changing the parent's
3459 * timeslices.
3460 */
3461void scheduler_tick(void)
3462{
7835b98b
CL
3463 int cpu = smp_processor_id();
3464 struct rq *rq = cpu_rq(cpu);
dd41f596 3465 struct task_struct *curr = rq->curr;
529c7726 3466 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
dd41f596
IM
3467
3468 spin_lock(&rq->lock);
546fe3c9 3469 __update_rq_clock(rq);
529c7726
IM
3470 /*
3471 * Let rq->clock advance by at least TICK_NSEC:
3472 */
3473 if (unlikely(rq->clock < next_tick))
3474 rq->clock = next_tick;
3475 rq->tick_timestamp = rq->clock;
f1a438d8 3476 update_cpu_load(rq);
dd41f596
IM
3477 if (curr != rq->idle) /* FIXME: needed? */
3478 curr->sched_class->task_tick(rq, curr);
dd41f596 3479 spin_unlock(&rq->lock);
7835b98b 3480
e418e1c2 3481#ifdef CONFIG_SMP
dd41f596
IM
3482 rq->idle_at_tick = idle_cpu(cpu);
3483 trigger_load_balance(rq, cpu);
e418e1c2 3484#endif
1da177e4
LT
3485}
3486
1da177e4
LT
3487#if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3488
3489void fastcall add_preempt_count(int val)
3490{
3491 /*
3492 * Underflow?
3493 */
9a11b49a
IM
3494 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3495 return;
1da177e4
LT
3496 preempt_count() += val;
3497 /*
3498 * Spinlock count overflowing soon?
3499 */
33859f7f
MOS
3500 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3501 PREEMPT_MASK - 10);
1da177e4
LT
3502}
3503EXPORT_SYMBOL(add_preempt_count);
3504
3505void fastcall sub_preempt_count(int val)
3506{
3507 /*
3508 * Underflow?
3509 */
9a11b49a
IM
3510 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3511 return;
1da177e4
LT
3512 /*
3513 * Is the spinlock portion underflowing?
3514 */
9a11b49a
IM
3515 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3516 !(preempt_count() & PREEMPT_MASK)))
3517 return;
3518
1da177e4
LT
3519 preempt_count() -= val;
3520}
3521EXPORT_SYMBOL(sub_preempt_count);
3522
3523#endif
3524
3525/*
dd41f596 3526 * Print scheduling while atomic bug:
1da177e4 3527 */
dd41f596 3528static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 3529{
838225b4
SS
3530 struct pt_regs *regs = get_irq_regs();
3531
3532 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3533 prev->comm, prev->pid, preempt_count());
3534
dd41f596
IM
3535 debug_show_held_locks(prev);
3536 if (irqs_disabled())
3537 print_irqtrace_events(prev);
838225b4
SS
3538
3539 if (regs)
3540 show_regs(regs);
3541 else
3542 dump_stack();
dd41f596 3543}
1da177e4 3544
dd41f596
IM
3545/*
3546 * Various schedule()-time debugging checks and statistics:
3547 */
3548static inline void schedule_debug(struct task_struct *prev)
3549{
1da177e4 3550 /*
41a2d6cf 3551 * Test if we are atomic. Since do_exit() needs to call into
1da177e4
LT
3552 * schedule() atomically, we ignore that path for now.
3553 * Otherwise, whine if we are scheduling when we should not be.
3554 */
dd41f596
IM
3555 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3556 __schedule_bug(prev);
3557
1da177e4
LT
3558 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3559
2d72376b 3560 schedstat_inc(this_rq(), sched_count);
b8efb561
IM
3561#ifdef CONFIG_SCHEDSTATS
3562 if (unlikely(prev->lock_depth >= 0)) {
2d72376b
IM
3563 schedstat_inc(this_rq(), bkl_count);
3564 schedstat_inc(prev, sched_info.bkl_count);
b8efb561
IM
3565 }
3566#endif
dd41f596
IM
3567}
3568
3569/*
3570 * Pick up the highest-prio task:
3571 */
3572static inline struct task_struct *
ff95f3df 3573pick_next_task(struct rq *rq, struct task_struct *prev)
dd41f596 3574{
5522d5d5 3575 const struct sched_class *class;
dd41f596 3576 struct task_struct *p;
1da177e4
LT
3577
3578 /*
dd41f596
IM
3579 * Optimization: we know that if all tasks are in
3580 * the fair class we can call that function directly:
1da177e4 3581 */
dd41f596 3582 if (likely(rq->nr_running == rq->cfs.nr_running)) {
fb8d4724 3583 p = fair_sched_class.pick_next_task(rq);
dd41f596
IM
3584 if (likely(p))
3585 return p;
1da177e4
LT
3586 }
3587
dd41f596
IM
3588 class = sched_class_highest;
3589 for ( ; ; ) {
fb8d4724 3590 p = class->pick_next_task(rq);
dd41f596
IM
3591 if (p)
3592 return p;
3593 /*
3594 * Will never be NULL as the idle class always
3595 * returns a non-NULL p:
3596 */
3597 class = class->next;
3598 }
3599}
1da177e4 3600
dd41f596
IM
3601/*
3602 * schedule() is the main scheduler function.
3603 */
3604asmlinkage void __sched schedule(void)
3605{
3606 struct task_struct *prev, *next;
3607 long *switch_count;
3608 struct rq *rq;
dd41f596
IM
3609 int cpu;
3610
3611need_resched:
3612 preempt_disable();
3613 cpu = smp_processor_id();
3614 rq = cpu_rq(cpu);
3615 rcu_qsctr_inc(cpu);
3616 prev = rq->curr;
3617 switch_count = &prev->nivcsw;
3618
3619 release_kernel_lock(prev);
3620need_resched_nonpreemptible:
3621
3622 schedule_debug(prev);
1da177e4 3623
1e819950
IM
3624 /*
3625 * Do the rq-clock update outside the rq lock:
3626 */
3627 local_irq_disable();
c1b3da3e 3628 __update_rq_clock(rq);
1e819950
IM
3629 spin_lock(&rq->lock);
3630 clear_tsk_need_resched(prev);
1da177e4 3631
1da177e4 3632 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
1da177e4 3633 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
dd41f596 3634 unlikely(signal_pending(prev)))) {
1da177e4 3635 prev->state = TASK_RUNNING;
dd41f596 3636 } else {
2e1cb74a 3637 deactivate_task(rq, prev, 1);
1da177e4 3638 }
dd41f596 3639 switch_count = &prev->nvcsw;
1da177e4
LT
3640 }
3641
dd41f596 3642 if (unlikely(!rq->nr_running))
1da177e4 3643 idle_balance(cpu, rq);
1da177e4 3644
31ee529c 3645 prev->sched_class->put_prev_task(rq, prev);
ff95f3df 3646 next = pick_next_task(rq, prev);
1da177e4
LT
3647
3648 sched_info_switch(prev, next);
dd41f596 3649
1da177e4 3650 if (likely(prev != next)) {
1da177e4
LT
3651 rq->nr_switches++;
3652 rq->curr = next;
3653 ++*switch_count;
3654
dd41f596 3655 context_switch(rq, prev, next); /* unlocks the rq */
1da177e4
LT
3656 } else
3657 spin_unlock_irq(&rq->lock);
3658
dd41f596
IM
3659 if (unlikely(reacquire_kernel_lock(current) < 0)) {
3660 cpu = smp_processor_id();
3661 rq = cpu_rq(cpu);
1da177e4 3662 goto need_resched_nonpreemptible;
dd41f596 3663 }
1da177e4
LT
3664 preempt_enable_no_resched();
3665 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3666 goto need_resched;
3667}
1da177e4
LT
3668EXPORT_SYMBOL(schedule);
3669
3670#ifdef CONFIG_PREEMPT
3671/*
2ed6e34f 3672 * this is the entry point to schedule() from in-kernel preemption
41a2d6cf 3673 * off of preempt_enable. Kernel preemptions off return from interrupt
1da177e4
LT
3674 * occur there and call schedule directly.
3675 */
3676asmlinkage void __sched preempt_schedule(void)
3677{
3678 struct thread_info *ti = current_thread_info();
3679#ifdef CONFIG_PREEMPT_BKL
3680 struct task_struct *task = current;
3681 int saved_lock_depth;
3682#endif
3683 /*
3684 * If there is a non-zero preempt_count or interrupts are disabled,
41a2d6cf 3685 * we do not want to preempt the current task. Just return..
1da177e4 3686 */
beed33a8 3687 if (likely(ti->preempt_count || irqs_disabled()))
1da177e4
LT
3688 return;
3689
3a5c359a
AK
3690 do {
3691 add_preempt_count(PREEMPT_ACTIVE);
3692
3693 /*
3694 * We keep the big kernel semaphore locked, but we
3695 * clear ->lock_depth so that schedule() doesnt
3696 * auto-release the semaphore:
3697 */
1da177e4 3698#ifdef CONFIG_PREEMPT_BKL
3a5c359a
AK
3699 saved_lock_depth = task->lock_depth;
3700 task->lock_depth = -1;
1da177e4 3701#endif
3a5c359a 3702 schedule();
1da177e4 3703#ifdef CONFIG_PREEMPT_BKL
3a5c359a 3704 task->lock_depth = saved_lock_depth;
1da177e4 3705#endif
3a5c359a 3706 sub_preempt_count(PREEMPT_ACTIVE);
1da177e4 3707
3a5c359a
AK
3708 /*
3709 * Check again in case we missed a preemption opportunity
3710 * between schedule and now.
3711 */
3712 barrier();
3713 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
1da177e4 3714}
1da177e4
LT
3715EXPORT_SYMBOL(preempt_schedule);
3716
3717/*
2ed6e34f 3718 * this is the entry point to schedule() from kernel preemption
1da177e4
LT
3719 * off of irq context.
3720 * Note, that this is called and return with irqs disabled. This will
3721 * protect us against recursive calling from irq.
3722 */
3723asmlinkage void __sched preempt_schedule_irq(void)
3724{
3725 struct thread_info *ti = current_thread_info();
3726#ifdef CONFIG_PREEMPT_BKL
3727 struct task_struct *task = current;
3728 int saved_lock_depth;
3729#endif
2ed6e34f 3730 /* Catch callers which need to be fixed */
1da177e4
LT
3731 BUG_ON(ti->preempt_count || !irqs_disabled());
3732
3a5c359a
AK
3733 do {
3734 add_preempt_count(PREEMPT_ACTIVE);
3735
3736 /*
3737 * We keep the big kernel semaphore locked, but we
3738 * clear ->lock_depth so that schedule() doesnt
3739 * auto-release the semaphore:
3740 */
1da177e4 3741#ifdef CONFIG_PREEMPT_BKL
3a5c359a
AK
3742 saved_lock_depth = task->lock_depth;
3743 task->lock_depth = -1;
1da177e4 3744#endif
3a5c359a
AK
3745 local_irq_enable();
3746 schedule();
3747 local_irq_disable();
1da177e4 3748#ifdef CONFIG_PREEMPT_BKL
3a5c359a 3749 task->lock_depth = saved_lock_depth;
1da177e4 3750#endif
3a5c359a 3751 sub_preempt_count(PREEMPT_ACTIVE);
1da177e4 3752
3a5c359a
AK
3753 /*
3754 * Check again in case we missed a preemption opportunity
3755 * between schedule and now.
3756 */
3757 barrier();
3758 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
1da177e4
LT
3759}
3760
3761#endif /* CONFIG_PREEMPT */
3762
95cdf3b7
IM
3763int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3764 void *key)
1da177e4 3765{
48f24c4d 3766 return try_to_wake_up(curr->private, mode, sync);
1da177e4 3767}
1da177e4
LT
3768EXPORT_SYMBOL(default_wake_function);
3769
3770/*
41a2d6cf
IM
3771 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3772 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
1da177e4
LT
3773 * number) then we wake all the non-exclusive tasks and one exclusive task.
3774 *
3775 * There are circumstances in which we can try to wake a task which has already
41a2d6cf 3776 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
1da177e4
LT
3777 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3778 */
3779static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3780 int nr_exclusive, int sync, void *key)
3781{
2e45874c 3782 wait_queue_t *curr, *next;
1da177e4 3783
2e45874c 3784 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
48f24c4d
IM
3785 unsigned flags = curr->flags;
3786
1da177e4 3787 if (curr->func(curr, mode, sync, key) &&
48f24c4d 3788 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
1da177e4
LT
3789 break;
3790 }
3791}
3792
3793/**
3794 * __wake_up - wake up threads blocked on a waitqueue.
3795 * @q: the waitqueue
3796 * @mode: which threads
3797 * @nr_exclusive: how many wake-one or wake-many threads to wake up
67be2dd1 3798 * @key: is directly passed to the wakeup function
1da177e4
LT
3799 */
3800void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
95cdf3b7 3801 int nr_exclusive, void *key)
1da177e4
LT
3802{
3803 unsigned long flags;
3804
3805 spin_lock_irqsave(&q->lock, flags);
3806 __wake_up_common(q, mode, nr_exclusive, 0, key);
3807 spin_unlock_irqrestore(&q->lock, flags);
3808}
1da177e4
LT
3809EXPORT_SYMBOL(__wake_up);
3810
3811/*
3812 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3813 */
3814void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3815{
3816 __wake_up_common(q, mode, 1, 0, NULL);
3817}
3818
3819/**
67be2dd1 3820 * __wake_up_sync - wake up threads blocked on a waitqueue.
1da177e4
LT
3821 * @q: the waitqueue
3822 * @mode: which threads
3823 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3824 *
3825 * The sync wakeup differs that the waker knows that it will schedule
3826 * away soon, so while the target thread will be woken up, it will not
3827 * be migrated to another CPU - ie. the two threads are 'synchronized'
3828 * with each other. This can prevent needless bouncing between CPUs.
3829 *
3830 * On UP it can prevent extra preemption.
3831 */
95cdf3b7
IM
3832void fastcall
3833__wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
1da177e4
LT
3834{
3835 unsigned long flags;
3836 int sync = 1;
3837
3838 if (unlikely(!q))
3839 return;
3840
3841 if (unlikely(!nr_exclusive))
3842 sync = 0;
3843
3844 spin_lock_irqsave(&q->lock, flags);
3845 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3846 spin_unlock_irqrestore(&q->lock, flags);
3847}
3848EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3849
b15136e9 3850void complete(struct completion *x)
1da177e4
LT
3851{
3852 unsigned long flags;
3853
3854 spin_lock_irqsave(&x->wait.lock, flags);
3855 x->done++;
3856 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3857 1, 0, NULL);
3858 spin_unlock_irqrestore(&x->wait.lock, flags);
3859}
3860EXPORT_SYMBOL(complete);
3861
b15136e9 3862void complete_all(struct completion *x)
1da177e4
LT
3863{
3864 unsigned long flags;
3865
3866 spin_lock_irqsave(&x->wait.lock, flags);
3867 x->done += UINT_MAX/2;
3868 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3869 0, 0, NULL);
3870 spin_unlock_irqrestore(&x->wait.lock, flags);
3871}
3872EXPORT_SYMBOL(complete_all);
3873
8cbbe86d
AK
3874static inline long __sched
3875do_wait_for_common(struct completion *x, long timeout, int state)
1da177e4 3876{
1da177e4
LT
3877 if (!x->done) {
3878 DECLARE_WAITQUEUE(wait, current);
3879
3880 wait.flags |= WQ_FLAG_EXCLUSIVE;
3881 __add_wait_queue_tail(&x->wait, &wait);
3882 do {
8cbbe86d
AK
3883 if (state == TASK_INTERRUPTIBLE &&
3884 signal_pending(current)) {
3885 __remove_wait_queue(&x->wait, &wait);
3886 return -ERESTARTSYS;
3887 }
3888 __set_current_state(state);
1da177e4
LT
3889 spin_unlock_irq(&x->wait.lock);
3890 timeout = schedule_timeout(timeout);
3891 spin_lock_irq(&x->wait.lock);
3892 if (!timeout) {
3893 __remove_wait_queue(&x->wait, &wait);
8cbbe86d 3894 return timeout;
1da177e4
LT
3895 }
3896 } while (!x->done);
3897 __remove_wait_queue(&x->wait, &wait);
3898 }
3899 x->done--;
1da177e4
LT
3900 return timeout;
3901}
1da177e4 3902
8cbbe86d
AK
3903static long __sched
3904wait_for_common(struct completion *x, long timeout, int state)
1da177e4 3905{
1da177e4
LT
3906 might_sleep();
3907
3908 spin_lock_irq(&x->wait.lock);
8cbbe86d 3909 timeout = do_wait_for_common(x, timeout, state);
1da177e4 3910 spin_unlock_irq(&x->wait.lock);
8cbbe86d
AK
3911 return timeout;
3912}
1da177e4 3913
b15136e9 3914void __sched wait_for_completion(struct completion *x)
8cbbe86d
AK
3915{
3916 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
1da177e4 3917}
8cbbe86d 3918EXPORT_SYMBOL(wait_for_completion);
1da177e4 3919
b15136e9 3920unsigned long __sched
8cbbe86d 3921wait_for_completion_timeout(struct completion *x, unsigned long timeout)
1da177e4 3922{
8cbbe86d 3923 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
1da177e4 3924}
8cbbe86d 3925EXPORT_SYMBOL(wait_for_completion_timeout);
1da177e4 3926
8cbbe86d 3927int __sched wait_for_completion_interruptible(struct completion *x)
0fec171c 3928{
51e97990
AK
3929 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
3930 if (t == -ERESTARTSYS)
3931 return t;
3932 return 0;
0fec171c 3933}
8cbbe86d 3934EXPORT_SYMBOL(wait_for_completion_interruptible);
1da177e4 3935
b15136e9 3936unsigned long __sched
8cbbe86d
AK
3937wait_for_completion_interruptible_timeout(struct completion *x,
3938 unsigned long timeout)
0fec171c 3939{
8cbbe86d 3940 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
0fec171c 3941}
8cbbe86d 3942EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
1da177e4 3943
8cbbe86d
AK
3944static long __sched
3945sleep_on_common(wait_queue_head_t *q, int state, long timeout)
1da177e4 3946{
0fec171c
IM
3947 unsigned long flags;
3948 wait_queue_t wait;
3949
3950 init_waitqueue_entry(&wait, current);
1da177e4 3951
8cbbe86d 3952 __set_current_state(state);
1da177e4 3953
8cbbe86d
AK
3954 spin_lock_irqsave(&q->lock, flags);
3955 __add_wait_queue(q, &wait);
3956 spin_unlock(&q->lock);
3957 timeout = schedule_timeout(timeout);
3958 spin_lock_irq(&q->lock);
3959 __remove_wait_queue(q, &wait);
3960 spin_unlock_irqrestore(&q->lock, flags);
3961
3962 return timeout;
3963}
3964
3965void __sched interruptible_sleep_on(wait_queue_head_t *q)
3966{
3967 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
1da177e4 3968}
1da177e4
LT
3969EXPORT_SYMBOL(interruptible_sleep_on);
3970
0fec171c 3971long __sched
95cdf3b7 3972interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3973{
8cbbe86d 3974 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
1da177e4 3975}
1da177e4
LT
3976EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3977
0fec171c 3978void __sched sleep_on(wait_queue_head_t *q)
1da177e4 3979{
8cbbe86d 3980 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
1da177e4 3981}
1da177e4
LT
3982EXPORT_SYMBOL(sleep_on);
3983
0fec171c 3984long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3985{
8cbbe86d 3986 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
1da177e4 3987}
1da177e4
LT
3988EXPORT_SYMBOL(sleep_on_timeout);
3989
b29739f9
IM
3990#ifdef CONFIG_RT_MUTEXES
3991
3992/*
3993 * rt_mutex_setprio - set the current priority of a task
3994 * @p: task
3995 * @prio: prio value (kernel-internal form)
3996 *
3997 * This function changes the 'effective' priority of a task. It does
3998 * not touch ->normal_prio like __setscheduler().
3999 *
4000 * Used by the rt_mutex code to implement priority inheritance logic.
4001 */
36c8b586 4002void rt_mutex_setprio(struct task_struct *p, int prio)
b29739f9
IM
4003{
4004 unsigned long flags;
83b699ed 4005 int oldprio, on_rq, running;
70b97a7f 4006 struct rq *rq;
b29739f9
IM
4007
4008 BUG_ON(prio < 0 || prio > MAX_PRIO);
4009
4010 rq = task_rq_lock(p, &flags);
a8e504d2 4011 update_rq_clock(rq);
b29739f9 4012
d5f9f942 4013 oldprio = p->prio;
dd41f596 4014 on_rq = p->se.on_rq;
051a1d1a 4015 running = task_current(rq, p);
83b699ed 4016 if (on_rq) {
69be72c1 4017 dequeue_task(rq, p, 0);
83b699ed
SV
4018 if (running)
4019 p->sched_class->put_prev_task(rq, p);
4020 }
dd41f596
IM
4021
4022 if (rt_prio(prio))
4023 p->sched_class = &rt_sched_class;
4024 else
4025 p->sched_class = &fair_sched_class;
4026
b29739f9
IM
4027 p->prio = prio;
4028
dd41f596 4029 if (on_rq) {
83b699ed
SV
4030 if (running)
4031 p->sched_class->set_curr_task(rq);
8159f87e 4032 enqueue_task(rq, p, 0);
b29739f9
IM
4033 /*
4034 * Reschedule if we are currently running on this runqueue and
d5f9f942
AM
4035 * our priority decreased, or if we are not currently running on
4036 * this runqueue and our priority is higher than the current's
b29739f9 4037 */
83b699ed 4038 if (running) {
d5f9f942
AM
4039 if (p->prio > oldprio)
4040 resched_task(rq->curr);
dd41f596
IM
4041 } else {
4042 check_preempt_curr(rq, p);
4043 }
b29739f9
IM
4044 }
4045 task_rq_unlock(rq, &flags);
4046}
4047
4048#endif
4049
36c8b586 4050void set_user_nice(struct task_struct *p, long nice)
1da177e4 4051{
dd41f596 4052 int old_prio, delta, on_rq;
1da177e4 4053 unsigned long flags;
70b97a7f 4054 struct rq *rq;
1da177e4
LT
4055
4056 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4057 return;
4058 /*
4059 * We have to be careful, if called from sys_setpriority(),
4060 * the task might be in the middle of scheduling on another CPU.
4061 */
4062 rq = task_rq_lock(p, &flags);
a8e504d2 4063 update_rq_clock(rq);
1da177e4
LT
4064 /*
4065 * The RT priorities are set via sched_setscheduler(), but we still
4066 * allow the 'normal' nice value to be set - but as expected
4067 * it wont have any effect on scheduling until the task is
dd41f596 4068 * SCHED_FIFO/SCHED_RR:
1da177e4 4069 */
e05606d3 4070 if (task_has_rt_policy(p)) {
1da177e4
LT
4071 p->static_prio = NICE_TO_PRIO(nice);
4072 goto out_unlock;
4073 }
dd41f596
IM
4074 on_rq = p->se.on_rq;
4075 if (on_rq) {
69be72c1 4076 dequeue_task(rq, p, 0);
79b5dddf 4077 dec_load(rq, p);
2dd73a4f 4078 }
1da177e4 4079
1da177e4 4080 p->static_prio = NICE_TO_PRIO(nice);
2dd73a4f 4081 set_load_weight(p);
b29739f9
IM
4082 old_prio = p->prio;
4083 p->prio = effective_prio(p);
4084 delta = p->prio - old_prio;
1da177e4 4085
dd41f596 4086 if (on_rq) {
8159f87e 4087 enqueue_task(rq, p, 0);
29b4b623 4088 inc_load(rq, p);
1da177e4 4089 /*
d5f9f942
AM
4090 * If the task increased its priority or is running and
4091 * lowered its priority, then reschedule its CPU:
1da177e4 4092 */
d5f9f942 4093 if (delta < 0 || (delta > 0 && task_running(rq, p)))
1da177e4
LT
4094 resched_task(rq->curr);
4095 }
4096out_unlock:
4097 task_rq_unlock(rq, &flags);
4098}
1da177e4
LT
4099EXPORT_SYMBOL(set_user_nice);
4100
e43379f1
MM
4101/*
4102 * can_nice - check if a task can reduce its nice value
4103 * @p: task
4104 * @nice: nice value
4105 */
36c8b586 4106int can_nice(const struct task_struct *p, const int nice)
e43379f1 4107{
024f4747
MM
4108 /* convert nice value [19,-20] to rlimit style value [1,40] */
4109 int nice_rlim = 20 - nice;
48f24c4d 4110
e43379f1
MM
4111 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4112 capable(CAP_SYS_NICE));
4113}
4114
1da177e4
LT
4115#ifdef __ARCH_WANT_SYS_NICE
4116
4117/*
4118 * sys_nice - change the priority of the current process.
4119 * @increment: priority increment
4120 *
4121 * sys_setpriority is a more generic, but much slower function that
4122 * does similar things.
4123 */
4124asmlinkage long sys_nice(int increment)
4125{
48f24c4d 4126 long nice, retval;
1da177e4
LT
4127
4128 /*
4129 * Setpriority might change our priority at the same moment.
4130 * We don't have to worry. Conceptually one call occurs first
4131 * and we have a single winner.
4132 */
e43379f1
MM
4133 if (increment < -40)
4134 increment = -40;
1da177e4
LT
4135 if (increment > 40)
4136 increment = 40;
4137
4138 nice = PRIO_TO_NICE(current->static_prio) + increment;
4139 if (nice < -20)
4140 nice = -20;
4141 if (nice > 19)
4142 nice = 19;
4143
e43379f1
MM
4144 if (increment < 0 && !can_nice(current, nice))
4145 return -EPERM;
4146
1da177e4
LT
4147 retval = security_task_setnice(current, nice);
4148 if (retval)
4149 return retval;
4150
4151 set_user_nice(current, nice);
4152 return 0;
4153}
4154
4155#endif
4156
4157/**
4158 * task_prio - return the priority value of a given task.
4159 * @p: the task in question.
4160 *
4161 * This is the priority value as seen by users in /proc.
4162 * RT tasks are offset by -200. Normal tasks are centered
4163 * around 0, value goes from -16 to +15.
4164 */
36c8b586 4165int task_prio(const struct task_struct *p)
1da177e4
LT
4166{
4167 return p->prio - MAX_RT_PRIO;
4168}
4169
4170/**
4171 * task_nice - return the nice value of a given task.
4172 * @p: the task in question.
4173 */
36c8b586 4174int task_nice(const struct task_struct *p)
1da177e4
LT
4175{
4176 return TASK_NICE(p);
4177}
1da177e4 4178EXPORT_SYMBOL_GPL(task_nice);
1da177e4
LT
4179
4180/**
4181 * idle_cpu - is a given cpu idle currently?
4182 * @cpu: the processor in question.
4183 */
4184int idle_cpu(int cpu)
4185{
4186 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4187}
4188
1da177e4
LT
4189/**
4190 * idle_task - return the idle task for a given cpu.
4191 * @cpu: the processor in question.
4192 */
36c8b586 4193struct task_struct *idle_task(int cpu)
1da177e4
LT
4194{
4195 return cpu_rq(cpu)->idle;
4196}
4197
4198/**
4199 * find_process_by_pid - find a process with a matching PID value.
4200 * @pid: the pid in question.
4201 */
a9957449 4202static struct task_struct *find_process_by_pid(pid_t pid)
1da177e4 4203{
228ebcbe 4204 return pid ? find_task_by_vpid(pid) : current;
1da177e4
LT
4205}
4206
4207/* Actually do priority change: must hold rq lock. */
dd41f596
IM
4208static void
4209__setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
1da177e4 4210{
dd41f596 4211 BUG_ON(p->se.on_rq);
48f24c4d 4212
1da177e4 4213 p->policy = policy;
dd41f596
IM
4214 switch (p->policy) {
4215 case SCHED_NORMAL:
4216 case SCHED_BATCH:
4217 case SCHED_IDLE:
4218 p->sched_class = &fair_sched_class;
4219 break;
4220 case SCHED_FIFO:
4221 case SCHED_RR:
4222 p->sched_class = &rt_sched_class;
4223 break;
4224 }
4225
1da177e4 4226 p->rt_priority = prio;
b29739f9
IM
4227 p->normal_prio = normal_prio(p);
4228 /* we are holding p->pi_lock already */
4229 p->prio = rt_mutex_getprio(p);
2dd73a4f 4230 set_load_weight(p);
1da177e4
LT
4231}
4232
4233/**
72fd4a35 4234 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
1da177e4
LT
4235 * @p: the task in question.
4236 * @policy: new policy.
4237 * @param: structure containing the new RT priority.
5fe1d75f 4238 *
72fd4a35 4239 * NOTE that the task may be already dead.
1da177e4 4240 */
95cdf3b7
IM
4241int sched_setscheduler(struct task_struct *p, int policy,
4242 struct sched_param *param)
1da177e4 4243{
83b699ed 4244 int retval, oldprio, oldpolicy = -1, on_rq, running;
1da177e4 4245 unsigned long flags;
70b97a7f 4246 struct rq *rq;
1da177e4 4247
66e5393a
SR
4248 /* may grab non-irq protected spin_locks */
4249 BUG_ON(in_interrupt());
1da177e4
LT
4250recheck:
4251 /* double check policy once rq lock held */
4252 if (policy < 0)
4253 policy = oldpolicy = p->policy;
4254 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
dd41f596
IM
4255 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4256 policy != SCHED_IDLE)
b0a9499c 4257 return -EINVAL;
1da177e4
LT
4258 /*
4259 * Valid priorities for SCHED_FIFO and SCHED_RR are
dd41f596
IM
4260 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4261 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4
LT
4262 */
4263 if (param->sched_priority < 0 ||
95cdf3b7 4264 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
d46523ea 4265 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
1da177e4 4266 return -EINVAL;
e05606d3 4267 if (rt_policy(policy) != (param->sched_priority != 0))
1da177e4
LT
4268 return -EINVAL;
4269
37e4ab3f
OC
4270 /*
4271 * Allow unprivileged RT tasks to decrease priority:
4272 */
4273 if (!capable(CAP_SYS_NICE)) {
e05606d3 4274 if (rt_policy(policy)) {
8dc3e909 4275 unsigned long rlim_rtprio;
8dc3e909
ON
4276
4277 if (!lock_task_sighand(p, &flags))
4278 return -ESRCH;
4279 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4280 unlock_task_sighand(p, &flags);
4281
4282 /* can't set/change the rt policy */
4283 if (policy != p->policy && !rlim_rtprio)
4284 return -EPERM;
4285
4286 /* can't increase priority */
4287 if (param->sched_priority > p->rt_priority &&
4288 param->sched_priority > rlim_rtprio)
4289 return -EPERM;
4290 }
dd41f596
IM
4291 /*
4292 * Like positive nice levels, dont allow tasks to
4293 * move out of SCHED_IDLE either:
4294 */
4295 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4296 return -EPERM;
5fe1d75f 4297
37e4ab3f
OC
4298 /* can't change other user's priorities */
4299 if ((current->euid != p->euid) &&
4300 (current->euid != p->uid))
4301 return -EPERM;
4302 }
1da177e4
LT
4303
4304 retval = security_task_setscheduler(p, policy, param);
4305 if (retval)
4306 return retval;
b29739f9
IM
4307 /*
4308 * make sure no PI-waiters arrive (or leave) while we are
4309 * changing the priority of the task:
4310 */
4311 spin_lock_irqsave(&p->pi_lock, flags);
1da177e4
LT
4312 /*
4313 * To be able to change p->policy safely, the apropriate
4314 * runqueue lock must be held.
4315 */
b29739f9 4316 rq = __task_rq_lock(p);
1da177e4
LT
4317 /* recheck policy now with rq lock held */
4318 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4319 policy = oldpolicy = -1;
b29739f9
IM
4320 __task_rq_unlock(rq);
4321 spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
4322 goto recheck;
4323 }
2daa3577 4324 update_rq_clock(rq);
dd41f596 4325 on_rq = p->se.on_rq;
051a1d1a 4326 running = task_current(rq, p);
83b699ed 4327 if (on_rq) {
2e1cb74a 4328 deactivate_task(rq, p, 0);
83b699ed
SV
4329 if (running)
4330 p->sched_class->put_prev_task(rq, p);
4331 }
f6b53205 4332
1da177e4 4333 oldprio = p->prio;
dd41f596 4334 __setscheduler(rq, p, policy, param->sched_priority);
f6b53205 4335
dd41f596 4336 if (on_rq) {
83b699ed
SV
4337 if (running)
4338 p->sched_class->set_curr_task(rq);
dd41f596 4339 activate_task(rq, p, 0);
1da177e4
LT
4340 /*
4341 * Reschedule if we are currently running on this runqueue and
d5f9f942
AM
4342 * our priority decreased, or if we are not currently running on
4343 * this runqueue and our priority is higher than the current's
1da177e4 4344 */
83b699ed 4345 if (running) {
d5f9f942
AM
4346 if (p->prio > oldprio)
4347 resched_task(rq->curr);
dd41f596
IM
4348 } else {
4349 check_preempt_curr(rq, p);
4350 }
1da177e4 4351 }
b29739f9
IM
4352 __task_rq_unlock(rq);
4353 spin_unlock_irqrestore(&p->pi_lock, flags);
4354
95e02ca9
TG
4355 rt_mutex_adjust_pi(p);
4356
1da177e4
LT
4357 return 0;
4358}
4359EXPORT_SYMBOL_GPL(sched_setscheduler);
4360
95cdf3b7
IM
4361static int
4362do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 4363{
1da177e4
LT
4364 struct sched_param lparam;
4365 struct task_struct *p;
36c8b586 4366 int retval;
1da177e4
LT
4367
4368 if (!param || pid < 0)
4369 return -EINVAL;
4370 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4371 return -EFAULT;
5fe1d75f
ON
4372
4373 rcu_read_lock();
4374 retval = -ESRCH;
1da177e4 4375 p = find_process_by_pid(pid);
5fe1d75f
ON
4376 if (p != NULL)
4377 retval = sched_setscheduler(p, policy, &lparam);
4378 rcu_read_unlock();
36c8b586 4379
1da177e4
LT
4380 return retval;
4381}
4382
4383/**
4384 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4385 * @pid: the pid in question.
4386 * @policy: new policy.
4387 * @param: structure containing the new RT priority.
4388 */
41a2d6cf
IM
4389asmlinkage long
4390sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 4391{
c21761f1
JB
4392 /* negative values for policy are not valid */
4393 if (policy < 0)
4394 return -EINVAL;
4395
1da177e4
LT
4396 return do_sched_setscheduler(pid, policy, param);
4397}
4398
4399/**
4400 * sys_sched_setparam - set/change the RT priority of a thread
4401 * @pid: the pid in question.
4402 * @param: structure containing the new RT priority.
4403 */
4404asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4405{
4406 return do_sched_setscheduler(pid, -1, param);
4407}
4408
4409/**
4410 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4411 * @pid: the pid in question.
4412 */
4413asmlinkage long sys_sched_getscheduler(pid_t pid)
4414{
36c8b586 4415 struct task_struct *p;
3a5c359a 4416 int retval;
1da177e4
LT
4417
4418 if (pid < 0)
3a5c359a 4419 return -EINVAL;
1da177e4
LT
4420
4421 retval = -ESRCH;
4422 read_lock(&tasklist_lock);
4423 p = find_process_by_pid(pid);
4424 if (p) {
4425 retval = security_task_getscheduler(p);
4426 if (!retval)
4427 retval = p->policy;
4428 }
4429 read_unlock(&tasklist_lock);
1da177e4
LT
4430 return retval;
4431}
4432
4433/**
4434 * sys_sched_getscheduler - get the RT priority of a thread
4435 * @pid: the pid in question.
4436 * @param: structure containing the RT priority.
4437 */
4438asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4439{
4440 struct sched_param lp;
36c8b586 4441 struct task_struct *p;
3a5c359a 4442 int retval;
1da177e4
LT
4443
4444 if (!param || pid < 0)
3a5c359a 4445 return -EINVAL;
1da177e4
LT
4446
4447 read_lock(&tasklist_lock);
4448 p = find_process_by_pid(pid);
4449 retval = -ESRCH;
4450 if (!p)
4451 goto out_unlock;
4452
4453 retval = security_task_getscheduler(p);
4454 if (retval)
4455 goto out_unlock;
4456
4457 lp.sched_priority = p->rt_priority;
4458 read_unlock(&tasklist_lock);
4459
4460 /*
4461 * This one might sleep, we cannot do it with a spinlock held ...
4462 */
4463 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4464
1da177e4
LT
4465 return retval;
4466
4467out_unlock:
4468 read_unlock(&tasklist_lock);
4469 return retval;
4470}
4471
4472long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4473{
1da177e4 4474 cpumask_t cpus_allowed;
36c8b586
IM
4475 struct task_struct *p;
4476 int retval;
1da177e4 4477
5be9361c 4478 mutex_lock(&sched_hotcpu_mutex);
1da177e4
LT
4479 read_lock(&tasklist_lock);
4480
4481 p = find_process_by_pid(pid);
4482 if (!p) {
4483 read_unlock(&tasklist_lock);
5be9361c 4484 mutex_unlock(&sched_hotcpu_mutex);
1da177e4
LT
4485 return -ESRCH;
4486 }
4487
4488 /*
4489 * It is not safe to call set_cpus_allowed with the
41a2d6cf 4490 * tasklist_lock held. We will bump the task_struct's
1da177e4
LT
4491 * usage count and then drop tasklist_lock.
4492 */
4493 get_task_struct(p);
4494 read_unlock(&tasklist_lock);
4495
4496 retval = -EPERM;
4497 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4498 !capable(CAP_SYS_NICE))
4499 goto out_unlock;
4500
e7834f8f
DQ
4501 retval = security_task_setscheduler(p, 0, NULL);
4502 if (retval)
4503 goto out_unlock;
4504
1da177e4
LT
4505 cpus_allowed = cpuset_cpus_allowed(p);
4506 cpus_and(new_mask, new_mask, cpus_allowed);
8707d8b8 4507 again:
1da177e4
LT
4508 retval = set_cpus_allowed(p, new_mask);
4509
8707d8b8
PM
4510 if (!retval) {
4511 cpus_allowed = cpuset_cpus_allowed(p);
4512 if (!cpus_subset(new_mask, cpus_allowed)) {
4513 /*
4514 * We must have raced with a concurrent cpuset
4515 * update. Just reset the cpus_allowed to the
4516 * cpuset's cpus_allowed
4517 */
4518 new_mask = cpus_allowed;
4519 goto again;
4520 }
4521 }
1da177e4
LT
4522out_unlock:
4523 put_task_struct(p);
5be9361c 4524 mutex_unlock(&sched_hotcpu_mutex);
1da177e4
LT
4525 return retval;
4526}
4527
4528static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4529 cpumask_t *new_mask)
4530{
4531 if (len < sizeof(cpumask_t)) {
4532 memset(new_mask, 0, sizeof(cpumask_t));
4533 } else if (len > sizeof(cpumask_t)) {
4534 len = sizeof(cpumask_t);
4535 }
4536 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4537}
4538
4539/**
4540 * sys_sched_setaffinity - set the cpu affinity of a process
4541 * @pid: pid of the process
4542 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4543 * @user_mask_ptr: user-space pointer to the new cpu mask
4544 */
4545asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4546 unsigned long __user *user_mask_ptr)
4547{
4548 cpumask_t new_mask;
4549 int retval;
4550
4551 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4552 if (retval)
4553 return retval;
4554
4555 return sched_setaffinity(pid, new_mask);
4556}
4557
4558/*
4559 * Represents all cpu's present in the system
4560 * In systems capable of hotplug, this map could dynamically grow
4561 * as new cpu's are detected in the system via any platform specific
4562 * method, such as ACPI for e.g.
4563 */
4564
4cef0c61 4565cpumask_t cpu_present_map __read_mostly;
1da177e4
LT
4566EXPORT_SYMBOL(cpu_present_map);
4567
4568#ifndef CONFIG_SMP
4cef0c61 4569cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
e16b38f7
GB
4570EXPORT_SYMBOL(cpu_online_map);
4571
4cef0c61 4572cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
e16b38f7 4573EXPORT_SYMBOL(cpu_possible_map);
1da177e4
LT
4574#endif
4575
4576long sched_getaffinity(pid_t pid, cpumask_t *mask)
4577{
36c8b586 4578 struct task_struct *p;
1da177e4 4579 int retval;
1da177e4 4580
5be9361c 4581 mutex_lock(&sched_hotcpu_mutex);
1da177e4
LT
4582 read_lock(&tasklist_lock);
4583
4584 retval = -ESRCH;
4585 p = find_process_by_pid(pid);
4586 if (!p)
4587 goto out_unlock;
4588
e7834f8f
DQ
4589 retval = security_task_getscheduler(p);
4590 if (retval)
4591 goto out_unlock;
4592
2f7016d9 4593 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
1da177e4
LT
4594
4595out_unlock:
4596 read_unlock(&tasklist_lock);
5be9361c 4597 mutex_unlock(&sched_hotcpu_mutex);
1da177e4 4598
9531b62f 4599 return retval;
1da177e4
LT
4600}
4601
4602/**
4603 * sys_sched_getaffinity - get the cpu affinity of a process
4604 * @pid: pid of the process
4605 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4606 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4607 */
4608asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4609 unsigned long __user *user_mask_ptr)
4610{
4611 int ret;
4612 cpumask_t mask;
4613
4614 if (len < sizeof(cpumask_t))
4615 return -EINVAL;
4616
4617 ret = sched_getaffinity(pid, &mask);
4618 if (ret < 0)
4619 return ret;
4620
4621 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4622 return -EFAULT;
4623
4624 return sizeof(cpumask_t);
4625}
4626
4627/**
4628 * sys_sched_yield - yield the current processor to other threads.
4629 *
dd41f596
IM
4630 * This function yields the current CPU to other tasks. If there are no
4631 * other threads running on this CPU then this function will return.
1da177e4
LT
4632 */
4633asmlinkage long sys_sched_yield(void)
4634{
70b97a7f 4635 struct rq *rq = this_rq_lock();
1da177e4 4636
2d72376b 4637 schedstat_inc(rq, yld_count);
4530d7ab 4638 current->sched_class->yield_task(rq);
1da177e4
LT
4639
4640 /*
4641 * Since we are going to call schedule() anyway, there's
4642 * no need to preempt or enable interrupts:
4643 */
4644 __release(rq->lock);
8a25d5de 4645 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1da177e4
LT
4646 _raw_spin_unlock(&rq->lock);
4647 preempt_enable_no_resched();
4648
4649 schedule();
4650
4651 return 0;
4652}
4653
e7b38404 4654static void __cond_resched(void)
1da177e4 4655{
8e0a43d8
IM
4656#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4657 __might_sleep(__FILE__, __LINE__);
4658#endif
5bbcfd90
IM
4659 /*
4660 * The BKS might be reacquired before we have dropped
4661 * PREEMPT_ACTIVE, which could trigger a second
4662 * cond_resched() call.
4663 */
1da177e4
LT
4664 do {
4665 add_preempt_count(PREEMPT_ACTIVE);
4666 schedule();
4667 sub_preempt_count(PREEMPT_ACTIVE);
4668 } while (need_resched());
4669}
4670
4671int __sched cond_resched(void)
4672{
9414232f
IM
4673 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
4674 system_state == SYSTEM_RUNNING) {
1da177e4
LT
4675 __cond_resched();
4676 return 1;
4677 }
4678 return 0;
4679}
1da177e4
LT
4680EXPORT_SYMBOL(cond_resched);
4681
4682/*
4683 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4684 * call schedule, and on return reacquire the lock.
4685 *
41a2d6cf 4686 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
1da177e4
LT
4687 * operations here to prevent schedule() from being called twice (once via
4688 * spin_unlock(), once by hand).
4689 */
95cdf3b7 4690int cond_resched_lock(spinlock_t *lock)
1da177e4 4691{
6df3cecb
JK
4692 int ret = 0;
4693
1da177e4
LT
4694 if (need_lockbreak(lock)) {
4695 spin_unlock(lock);
4696 cpu_relax();
6df3cecb 4697 ret = 1;
1da177e4
LT
4698 spin_lock(lock);
4699 }
9414232f 4700 if (need_resched() && system_state == SYSTEM_RUNNING) {
8a25d5de 4701 spin_release(&lock->dep_map, 1, _THIS_IP_);
1da177e4
LT
4702 _raw_spin_unlock(lock);
4703 preempt_enable_no_resched();
4704 __cond_resched();
6df3cecb 4705 ret = 1;
1da177e4 4706 spin_lock(lock);
1da177e4 4707 }
6df3cecb 4708 return ret;
1da177e4 4709}
1da177e4
LT
4710EXPORT_SYMBOL(cond_resched_lock);
4711
4712int __sched cond_resched_softirq(void)
4713{
4714 BUG_ON(!in_softirq());
4715
9414232f 4716 if (need_resched() && system_state == SYSTEM_RUNNING) {
98d82567 4717 local_bh_enable();
1da177e4
LT
4718 __cond_resched();
4719 local_bh_disable();
4720 return 1;
4721 }
4722 return 0;
4723}
1da177e4
LT
4724EXPORT_SYMBOL(cond_resched_softirq);
4725
1da177e4
LT
4726/**
4727 * yield - yield the current processor to other threads.
4728 *
72fd4a35 4729 * This is a shortcut for kernel-space yielding - it marks the
1da177e4
LT
4730 * thread runnable and calls sys_sched_yield().
4731 */
4732void __sched yield(void)
4733{
4734 set_current_state(TASK_RUNNING);
4735 sys_sched_yield();
4736}
1da177e4
LT
4737EXPORT_SYMBOL(yield);
4738
4739/*
41a2d6cf 4740 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
1da177e4
LT
4741 * that process accounting knows that this is a task in IO wait state.
4742 *
4743 * But don't do that if it is a deliberate, throttling IO wait (this task
4744 * has set its backing_dev_info: the queue against which it should throttle)
4745 */
4746void __sched io_schedule(void)
4747{
70b97a7f 4748 struct rq *rq = &__raw_get_cpu_var(runqueues);
1da177e4 4749
0ff92245 4750 delayacct_blkio_start();
1da177e4
LT
4751 atomic_inc(&rq->nr_iowait);
4752 schedule();
4753 atomic_dec(&rq->nr_iowait);
0ff92245 4754 delayacct_blkio_end();
1da177e4 4755}
1da177e4
LT
4756EXPORT_SYMBOL(io_schedule);
4757
4758long __sched io_schedule_timeout(long timeout)
4759{
70b97a7f 4760 struct rq *rq = &__raw_get_cpu_var(runqueues);
1da177e4
LT
4761 long ret;
4762
0ff92245 4763 delayacct_blkio_start();
1da177e4
LT
4764 atomic_inc(&rq->nr_iowait);
4765 ret = schedule_timeout(timeout);
4766 atomic_dec(&rq->nr_iowait);
0ff92245 4767 delayacct_blkio_end();
1da177e4
LT
4768 return ret;
4769}
4770
4771/**
4772 * sys_sched_get_priority_max - return maximum RT priority.
4773 * @policy: scheduling class.
4774 *
4775 * this syscall returns the maximum rt_priority that can be used
4776 * by a given scheduling class.
4777 */
4778asmlinkage long sys_sched_get_priority_max(int policy)
4779{
4780 int ret = -EINVAL;
4781
4782 switch (policy) {
4783 case SCHED_FIFO:
4784 case SCHED_RR:
4785 ret = MAX_USER_RT_PRIO-1;
4786 break;
4787 case SCHED_NORMAL:
b0a9499c 4788 case SCHED_BATCH:
dd41f596 4789 case SCHED_IDLE:
1da177e4
LT
4790 ret = 0;
4791 break;
4792 }
4793 return ret;
4794}
4795
4796/**
4797 * sys_sched_get_priority_min - return minimum RT priority.
4798 * @policy: scheduling class.
4799 *
4800 * this syscall returns the minimum rt_priority that can be used
4801 * by a given scheduling class.
4802 */
4803asmlinkage long sys_sched_get_priority_min(int policy)
4804{
4805 int ret = -EINVAL;
4806
4807 switch (policy) {
4808 case SCHED_FIFO:
4809 case SCHED_RR:
4810 ret = 1;
4811 break;
4812 case SCHED_NORMAL:
b0a9499c 4813 case SCHED_BATCH:
dd41f596 4814 case SCHED_IDLE:
1da177e4
LT
4815 ret = 0;
4816 }
4817 return ret;
4818}
4819
4820/**
4821 * sys_sched_rr_get_interval - return the default timeslice of a process.
4822 * @pid: pid of the process.
4823 * @interval: userspace pointer to the timeslice value.
4824 *
4825 * this syscall writes the default timeslice value of a given process
4826 * into the user-space timespec buffer. A value of '0' means infinity.
4827 */
4828asmlinkage
4829long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4830{
36c8b586 4831 struct task_struct *p;
a4ec24b4 4832 unsigned int time_slice;
3a5c359a 4833 int retval;
1da177e4 4834 struct timespec t;
1da177e4
LT
4835
4836 if (pid < 0)
3a5c359a 4837 return -EINVAL;
1da177e4
LT
4838
4839 retval = -ESRCH;
4840 read_lock(&tasklist_lock);
4841 p = find_process_by_pid(pid);
4842 if (!p)
4843 goto out_unlock;
4844
4845 retval = security_task_getscheduler(p);
4846 if (retval)
4847 goto out_unlock;
4848
77034937
IM
4849 /*
4850 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
4851 * tasks that are on an otherwise idle runqueue:
4852 */
4853 time_slice = 0;
4854 if (p->policy == SCHED_RR) {
a4ec24b4 4855 time_slice = DEF_TIMESLICE;
77034937 4856 } else {
a4ec24b4
DA
4857 struct sched_entity *se = &p->se;
4858 unsigned long flags;
4859 struct rq *rq;
4860
4861 rq = task_rq_lock(p, &flags);
77034937
IM
4862 if (rq->cfs.load.weight)
4863 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
a4ec24b4
DA
4864 task_rq_unlock(rq, &flags);
4865 }
1da177e4 4866 read_unlock(&tasklist_lock);
a4ec24b4 4867 jiffies_to_timespec(time_slice, &t);
1da177e4 4868 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
1da177e4 4869 return retval;
3a5c359a 4870
1da177e4
LT
4871out_unlock:
4872 read_unlock(&tasklist_lock);
4873 return retval;
4874}
4875
2ed6e34f 4876static const char stat_nam[] = "RSDTtZX";
36c8b586
IM
4877
4878static void show_task(struct task_struct *p)
1da177e4 4879{
1da177e4 4880 unsigned long free = 0;
36c8b586 4881 unsigned state;
1da177e4 4882
1da177e4 4883 state = p->state ? __ffs(p->state) + 1 : 0;
cc4ea795 4884 printk(KERN_INFO "%-13.13s %c", p->comm,
2ed6e34f 4885 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4bd77321 4886#if BITS_PER_LONG == 32
1da177e4 4887 if (state == TASK_RUNNING)
cc4ea795 4888 printk(KERN_CONT " running ");
1da177e4 4889 else
cc4ea795 4890 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
1da177e4
LT
4891#else
4892 if (state == TASK_RUNNING)
cc4ea795 4893 printk(KERN_CONT " running task ");
1da177e4 4894 else
cc4ea795 4895 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
1da177e4
LT
4896#endif
4897#ifdef CONFIG_DEBUG_STACK_USAGE
4898 {
10ebffde 4899 unsigned long *n = end_of_stack(p);
1da177e4
LT
4900 while (!*n)
4901 n++;
10ebffde 4902 free = (unsigned long)n - (unsigned long)end_of_stack(p);
1da177e4
LT
4903 }
4904#endif
ba25f9dc 4905 printk(KERN_CONT "%5lu %5d %6d\n", free,
fcfd50af 4906 task_pid_nr(p), task_pid_nr(p->real_parent));
1da177e4
LT
4907
4908 if (state != TASK_RUNNING)
4909 show_stack(p, NULL);
4910}
4911
e59e2ae2 4912void show_state_filter(unsigned long state_filter)
1da177e4 4913{
36c8b586 4914 struct task_struct *g, *p;
1da177e4 4915
4bd77321
IM
4916#if BITS_PER_LONG == 32
4917 printk(KERN_INFO
4918 " task PC stack pid father\n");
1da177e4 4919#else
4bd77321
IM
4920 printk(KERN_INFO
4921 " task PC stack pid father\n");
1da177e4
LT
4922#endif
4923 read_lock(&tasklist_lock);
4924 do_each_thread(g, p) {
4925 /*
4926 * reset the NMI-timeout, listing all files on a slow
4927 * console might take alot of time:
4928 */
4929 touch_nmi_watchdog();
39bc89fd 4930 if (!state_filter || (p->state & state_filter))
e59e2ae2 4931 show_task(p);
1da177e4
LT
4932 } while_each_thread(g, p);
4933
04c9167f
JF
4934 touch_all_softlockup_watchdogs();
4935
dd41f596
IM
4936#ifdef CONFIG_SCHED_DEBUG
4937 sysrq_sched_debug_show();
4938#endif
1da177e4 4939 read_unlock(&tasklist_lock);
e59e2ae2
IM
4940 /*
4941 * Only show locks if all tasks are dumped:
4942 */
4943 if (state_filter == -1)
4944 debug_show_all_locks();
1da177e4
LT
4945}
4946
1df21055
IM
4947void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4948{
dd41f596 4949 idle->sched_class = &idle_sched_class;
1df21055
IM
4950}
4951
f340c0d1
IM
4952/**
4953 * init_idle - set up an idle thread for a given CPU
4954 * @idle: task in question
4955 * @cpu: cpu the idle task belongs to
4956 *
4957 * NOTE: this function does not set the idle thread's NEED_RESCHED
4958 * flag, to make booting more robust.
4959 */
5c1e1767 4960void __cpuinit init_idle(struct task_struct *idle, int cpu)
1da177e4 4961{
70b97a7f 4962 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
4963 unsigned long flags;
4964
dd41f596
IM
4965 __sched_fork(idle);
4966 idle->se.exec_start = sched_clock();
4967
b29739f9 4968 idle->prio = idle->normal_prio = MAX_PRIO;
1da177e4 4969 idle->cpus_allowed = cpumask_of_cpu(cpu);
dd41f596 4970 __set_task_cpu(idle, cpu);
1da177e4
LT
4971
4972 spin_lock_irqsave(&rq->lock, flags);
4973 rq->curr = rq->idle = idle;
4866cde0
NP
4974#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4975 idle->oncpu = 1;
4976#endif
1da177e4
LT
4977 spin_unlock_irqrestore(&rq->lock, flags);
4978
4979 /* Set the preempt count _outside_ the spinlocks! */
4980#if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
a1261f54 4981 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
1da177e4 4982#else
a1261f54 4983 task_thread_info(idle)->preempt_count = 0;
1da177e4 4984#endif
dd41f596
IM
4985 /*
4986 * The idle tasks have their own, simple scheduling class:
4987 */
4988 idle->sched_class = &idle_sched_class;
1da177e4
LT
4989}
4990
4991/*
4992 * In a system that switches off the HZ timer nohz_cpu_mask
4993 * indicates which cpus entered this state. This is used
4994 * in the rcu update to wait only for active cpus. For system
4995 * which do not switch off the HZ timer nohz_cpu_mask should
4996 * always be CPU_MASK_NONE.
4997 */
4998cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4999
19978ca6
IM
5000/*
5001 * Increase the granularity value when there are more CPUs,
5002 * because with more CPUs the 'effective latency' as visible
5003 * to users decreases. But the relationship is not linear,
5004 * so pick a second-best guess by going with the log2 of the
5005 * number of CPUs.
5006 *
5007 * This idea comes from the SD scheduler of Con Kolivas:
5008 */
5009static inline void sched_init_granularity(void)
5010{
5011 unsigned int factor = 1 + ilog2(num_online_cpus());
5012 const unsigned long limit = 200000000;
5013
5014 sysctl_sched_min_granularity *= factor;
5015 if (sysctl_sched_min_granularity > limit)
5016 sysctl_sched_min_granularity = limit;
5017
5018 sysctl_sched_latency *= factor;
5019 if (sysctl_sched_latency > limit)
5020 sysctl_sched_latency = limit;
5021
5022 sysctl_sched_wakeup_granularity *= factor;
5023 sysctl_sched_batch_wakeup_granularity *= factor;
5024}
5025
1da177e4
LT
5026#ifdef CONFIG_SMP
5027/*
5028 * This is how migration works:
5029 *
70b97a7f 5030 * 1) we queue a struct migration_req structure in the source CPU's
1da177e4
LT
5031 * runqueue and wake up that CPU's migration thread.
5032 * 2) we down() the locked semaphore => thread blocks.
5033 * 3) migration thread wakes up (implicitly it forces the migrated
5034 * thread off the CPU)
5035 * 4) it gets the migration request and checks whether the migrated
5036 * task is still in the wrong runqueue.
5037 * 5) if it's in the wrong runqueue then the migration thread removes
5038 * it and puts it into the right queue.
5039 * 6) migration thread up()s the semaphore.
5040 * 7) we wake up and the migration is done.
5041 */
5042
5043/*
5044 * Change a given task's CPU affinity. Migrate the thread to a
5045 * proper CPU and schedule it away if the CPU it's executing on
5046 * is removed from the allowed bitmask.
5047 *
5048 * NOTE: the caller must have a valid reference to the task, the
41a2d6cf 5049 * task must not exit() & deallocate itself prematurely. The
1da177e4
LT
5050 * call is not atomic; no spinlocks may be held.
5051 */
36c8b586 5052int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
1da177e4 5053{
70b97a7f 5054 struct migration_req req;
1da177e4 5055 unsigned long flags;
70b97a7f 5056 struct rq *rq;
48f24c4d 5057 int ret = 0;
1da177e4
LT
5058
5059 rq = task_rq_lock(p, &flags);
5060 if (!cpus_intersects(new_mask, cpu_online_map)) {
5061 ret = -EINVAL;
5062 goto out;
5063 }
5064
5065 p->cpus_allowed = new_mask;
5066 /* Can the task run on the task's current CPU? If so, we're done */
5067 if (cpu_isset(task_cpu(p), new_mask))
5068 goto out;
5069
5070 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5071 /* Need help from migration thread: drop lock and wait. */
5072 task_rq_unlock(rq, &flags);
5073 wake_up_process(rq->migration_thread);
5074 wait_for_completion(&req.done);
5075 tlb_migrate_finish(p->mm);
5076 return 0;
5077 }
5078out:
5079 task_rq_unlock(rq, &flags);
48f24c4d 5080
1da177e4
LT
5081 return ret;
5082}
1da177e4
LT
5083EXPORT_SYMBOL_GPL(set_cpus_allowed);
5084
5085/*
41a2d6cf 5086 * Move (not current) task off this cpu, onto dest cpu. We're doing
1da177e4
LT
5087 * this because either it can't run here any more (set_cpus_allowed()
5088 * away from this CPU, or CPU going down), or because we're
5089 * attempting to rebalance this task on exec (sched_exec).
5090 *
5091 * So we race with normal scheduler movements, but that's OK, as long
5092 * as the task is no longer on this CPU.
efc30814
KK
5093 *
5094 * Returns non-zero if task was successfully migrated.
1da177e4 5095 */
efc30814 5096static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
1da177e4 5097{
70b97a7f 5098 struct rq *rq_dest, *rq_src;
dd41f596 5099 int ret = 0, on_rq;
1da177e4
LT
5100
5101 if (unlikely(cpu_is_offline(dest_cpu)))
efc30814 5102 return ret;
1da177e4
LT
5103
5104 rq_src = cpu_rq(src_cpu);
5105 rq_dest = cpu_rq(dest_cpu);
5106
5107 double_rq_lock(rq_src, rq_dest);
5108 /* Already moved. */
5109 if (task_cpu(p) != src_cpu)
5110 goto out;
5111 /* Affinity changed (again). */
5112 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5113 goto out;
5114
dd41f596 5115 on_rq = p->se.on_rq;
6e82a3be 5116 if (on_rq)
2e1cb74a 5117 deactivate_task(rq_src, p, 0);
6e82a3be 5118
1da177e4 5119 set_task_cpu(p, dest_cpu);
dd41f596
IM
5120 if (on_rq) {
5121 activate_task(rq_dest, p, 0);
5122 check_preempt_curr(rq_dest, p);
1da177e4 5123 }
efc30814 5124 ret = 1;
1da177e4
LT
5125out:
5126 double_rq_unlock(rq_src, rq_dest);
efc30814 5127 return ret;
1da177e4
LT
5128}
5129
5130/*
5131 * migration_thread - this is a highprio system thread that performs
5132 * thread migration by bumping thread off CPU then 'pushing' onto
5133 * another runqueue.
5134 */
95cdf3b7 5135static int migration_thread(void *data)
1da177e4 5136{
1da177e4 5137 int cpu = (long)data;
70b97a7f 5138 struct rq *rq;
1da177e4
LT
5139
5140 rq = cpu_rq(cpu);
5141 BUG_ON(rq->migration_thread != current);
5142
5143 set_current_state(TASK_INTERRUPTIBLE);
5144 while (!kthread_should_stop()) {
70b97a7f 5145 struct migration_req *req;
1da177e4 5146 struct list_head *head;
1da177e4 5147
1da177e4
LT
5148 spin_lock_irq(&rq->lock);
5149
5150 if (cpu_is_offline(cpu)) {
5151 spin_unlock_irq(&rq->lock);
5152 goto wait_to_die;
5153 }
5154
5155 if (rq->active_balance) {
5156 active_load_balance(rq, cpu);
5157 rq->active_balance = 0;
5158 }
5159
5160 head = &rq->migration_queue;
5161
5162 if (list_empty(head)) {
5163 spin_unlock_irq(&rq->lock);
5164 schedule();
5165 set_current_state(TASK_INTERRUPTIBLE);
5166 continue;
5167 }
70b97a7f 5168 req = list_entry(head->next, struct migration_req, list);
1da177e4
LT
5169 list_del_init(head->next);
5170
674311d5
NP
5171 spin_unlock(&rq->lock);
5172 __migrate_task(req->task, cpu, req->dest_cpu);
5173 local_irq_enable();
1da177e4
LT
5174
5175 complete(&req->done);
5176 }
5177 __set_current_state(TASK_RUNNING);
5178 return 0;
5179
5180wait_to_die:
5181 /* Wait for kthread_stop */
5182 set_current_state(TASK_INTERRUPTIBLE);
5183 while (!kthread_should_stop()) {
5184 schedule();
5185 set_current_state(TASK_INTERRUPTIBLE);
5186 }
5187 __set_current_state(TASK_RUNNING);
5188 return 0;
5189}
5190
5191#ifdef CONFIG_HOTPLUG_CPU
f7b4cddc
ON
5192
5193static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5194{
5195 int ret;
5196
5197 local_irq_disable();
5198 ret = __migrate_task(p, src_cpu, dest_cpu);
5199 local_irq_enable();
5200 return ret;
5201}
5202
054b9108 5203/*
3a4fa0a2 5204 * Figure out where task on dead CPU should go, use force if necessary.
054b9108
KK
5205 * NOTE: interrupts should be disabled by the caller
5206 */
48f24c4d 5207static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
1da177e4 5208{
efc30814 5209 unsigned long flags;
1da177e4 5210 cpumask_t mask;
70b97a7f
IM
5211 struct rq *rq;
5212 int dest_cpu;
1da177e4 5213
3a5c359a
AK
5214 do {
5215 /* On same node? */
5216 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5217 cpus_and(mask, mask, p->cpus_allowed);
5218 dest_cpu = any_online_cpu(mask);
5219
5220 /* On any allowed CPU? */
5221 if (dest_cpu == NR_CPUS)
5222 dest_cpu = any_online_cpu(p->cpus_allowed);
5223
5224 /* No more Mr. Nice Guy. */
5225 if (dest_cpu == NR_CPUS) {
470fd646
CW
5226 cpumask_t cpus_allowed = cpuset_cpus_allowed_locked(p);
5227 /*
5228 * Try to stay on the same cpuset, where the
5229 * current cpuset may be a subset of all cpus.
5230 * The cpuset_cpus_allowed_locked() variant of
41a2d6cf 5231 * cpuset_cpus_allowed() will not block. It must be
470fd646
CW
5232 * called within calls to cpuset_lock/cpuset_unlock.
5233 */
3a5c359a 5234 rq = task_rq_lock(p, &flags);
470fd646 5235 p->cpus_allowed = cpus_allowed;
3a5c359a
AK
5236 dest_cpu = any_online_cpu(p->cpus_allowed);
5237 task_rq_unlock(rq, &flags);
1da177e4 5238
3a5c359a
AK
5239 /*
5240 * Don't tell them about moving exiting tasks or
5241 * kernel threads (both mm NULL), since they never
5242 * leave kernel.
5243 */
41a2d6cf 5244 if (p->mm && printk_ratelimit()) {
3a5c359a
AK
5245 printk(KERN_INFO "process %d (%s) no "
5246 "longer affine to cpu%d\n",
41a2d6cf
IM
5247 task_pid_nr(p), p->comm, dead_cpu);
5248 }
3a5c359a 5249 }
f7b4cddc 5250 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
1da177e4
LT
5251}
5252
5253/*
5254 * While a dead CPU has no uninterruptible tasks queued at this point,
5255 * it might still have a nonzero ->nr_uninterruptible counter, because
5256 * for performance reasons the counter is not stricly tracking tasks to
5257 * their home CPUs. So we just add the counter to another CPU's counter,
5258 * to keep the global sum constant after CPU-down:
5259 */
70b97a7f 5260static void migrate_nr_uninterruptible(struct rq *rq_src)
1da177e4 5261{
70b97a7f 5262 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
1da177e4
LT
5263 unsigned long flags;
5264
5265 local_irq_save(flags);
5266 double_rq_lock(rq_src, rq_dest);
5267 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5268 rq_src->nr_uninterruptible = 0;
5269 double_rq_unlock(rq_src, rq_dest);
5270 local_irq_restore(flags);
5271}
5272
5273/* Run through task list and migrate tasks from the dead cpu. */
5274static void migrate_live_tasks(int src_cpu)
5275{
48f24c4d 5276 struct task_struct *p, *t;
1da177e4 5277
f7b4cddc 5278 read_lock(&tasklist_lock);
1da177e4 5279
48f24c4d
IM
5280 do_each_thread(t, p) {
5281 if (p == current)
1da177e4
LT
5282 continue;
5283
48f24c4d
IM
5284 if (task_cpu(p) == src_cpu)
5285 move_task_off_dead_cpu(src_cpu, p);
5286 } while_each_thread(t, p);
1da177e4 5287
f7b4cddc 5288 read_unlock(&tasklist_lock);
1da177e4
LT
5289}
5290
dd41f596
IM
5291/*
5292 * Schedules idle task to be the next runnable task on current CPU.
94bc9a7b
DA
5293 * It does so by boosting its priority to highest possible.
5294 * Used by CPU offline code.
1da177e4
LT
5295 */
5296void sched_idle_next(void)
5297{
48f24c4d 5298 int this_cpu = smp_processor_id();
70b97a7f 5299 struct rq *rq = cpu_rq(this_cpu);
1da177e4
LT
5300 struct task_struct *p = rq->idle;
5301 unsigned long flags;
5302
5303 /* cpu has to be offline */
48f24c4d 5304 BUG_ON(cpu_online(this_cpu));
1da177e4 5305
48f24c4d
IM
5306 /*
5307 * Strictly not necessary since rest of the CPUs are stopped by now
5308 * and interrupts disabled on the current cpu.
1da177e4
LT
5309 */
5310 spin_lock_irqsave(&rq->lock, flags);
5311
dd41f596 5312 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
48f24c4d 5313
94bc9a7b
DA
5314 update_rq_clock(rq);
5315 activate_task(rq, p, 0);
1da177e4
LT
5316
5317 spin_unlock_irqrestore(&rq->lock, flags);
5318}
5319
48f24c4d
IM
5320/*
5321 * Ensures that the idle task is using init_mm right before its cpu goes
1da177e4
LT
5322 * offline.
5323 */
5324void idle_task_exit(void)
5325{
5326 struct mm_struct *mm = current->active_mm;
5327
5328 BUG_ON(cpu_online(smp_processor_id()));
5329
5330 if (mm != &init_mm)
5331 switch_mm(mm, &init_mm, current);
5332 mmdrop(mm);
5333}
5334
054b9108 5335/* called under rq->lock with disabled interrupts */
36c8b586 5336static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
1da177e4 5337{
70b97a7f 5338 struct rq *rq = cpu_rq(dead_cpu);
1da177e4
LT
5339
5340 /* Must be exiting, otherwise would be on tasklist. */
270f722d 5341 BUG_ON(!p->exit_state);
1da177e4
LT
5342
5343 /* Cannot have done final schedule yet: would have vanished. */
c394cc9f 5344 BUG_ON(p->state == TASK_DEAD);
1da177e4 5345
48f24c4d 5346 get_task_struct(p);
1da177e4
LT
5347
5348 /*
5349 * Drop lock around migration; if someone else moves it,
41a2d6cf 5350 * that's OK. No task can be added to this CPU, so iteration is
1da177e4
LT
5351 * fine.
5352 */
f7b4cddc 5353 spin_unlock_irq(&rq->lock);
48f24c4d 5354 move_task_off_dead_cpu(dead_cpu, p);
f7b4cddc 5355 spin_lock_irq(&rq->lock);
1da177e4 5356
48f24c4d 5357 put_task_struct(p);
1da177e4
LT
5358}
5359
5360/* release_task() removes task from tasklist, so we won't find dead tasks. */
5361static void migrate_dead_tasks(unsigned int dead_cpu)
5362{
70b97a7f 5363 struct rq *rq = cpu_rq(dead_cpu);
dd41f596 5364 struct task_struct *next;
48f24c4d 5365
dd41f596
IM
5366 for ( ; ; ) {
5367 if (!rq->nr_running)
5368 break;
a8e504d2 5369 update_rq_clock(rq);
ff95f3df 5370 next = pick_next_task(rq, rq->curr);
dd41f596
IM
5371 if (!next)
5372 break;
5373 migrate_dead(dead_cpu, next);
e692ab53 5374
1da177e4
LT
5375 }
5376}
5377#endif /* CONFIG_HOTPLUG_CPU */
5378
e692ab53
NP
5379#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5380
5381static struct ctl_table sd_ctl_dir[] = {
e0361851
AD
5382 {
5383 .procname = "sched_domain",
c57baf1e 5384 .mode = 0555,
e0361851 5385 },
38605cae 5386 {0, },
e692ab53
NP
5387};
5388
5389static struct ctl_table sd_ctl_root[] = {
e0361851 5390 {
c57baf1e 5391 .ctl_name = CTL_KERN,
e0361851 5392 .procname = "kernel",
c57baf1e 5393 .mode = 0555,
e0361851
AD
5394 .child = sd_ctl_dir,
5395 },
38605cae 5396 {0, },
e692ab53
NP
5397};
5398
5399static struct ctl_table *sd_alloc_ctl_entry(int n)
5400{
5401 struct ctl_table *entry =
5cf9f062 5402 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
e692ab53 5403
e692ab53
NP
5404 return entry;
5405}
5406
6382bc90
MM
5407static void sd_free_ctl_entry(struct ctl_table **tablep)
5408{
cd790076 5409 struct ctl_table *entry;
6382bc90 5410
cd790076
MM
5411 /*
5412 * In the intermediate directories, both the child directory and
5413 * procname are dynamically allocated and could fail but the mode
41a2d6cf 5414 * will always be set. In the lowest directory the names are
cd790076
MM
5415 * static strings and all have proc handlers.
5416 */
5417 for (entry = *tablep; entry->mode; entry++) {
6382bc90
MM
5418 if (entry->child)
5419 sd_free_ctl_entry(&entry->child);
cd790076
MM
5420 if (entry->proc_handler == NULL)
5421 kfree(entry->procname);
5422 }
6382bc90
MM
5423
5424 kfree(*tablep);
5425 *tablep = NULL;
5426}
5427
e692ab53 5428static void
e0361851 5429set_table_entry(struct ctl_table *entry,
e692ab53
NP
5430 const char *procname, void *data, int maxlen,
5431 mode_t mode, proc_handler *proc_handler)
5432{
e692ab53
NP
5433 entry->procname = procname;
5434 entry->data = data;
5435 entry->maxlen = maxlen;
5436 entry->mode = mode;
5437 entry->proc_handler = proc_handler;
5438}
5439
5440static struct ctl_table *
5441sd_alloc_ctl_domain_table(struct sched_domain *sd)
5442{
ace8b3d6 5443 struct ctl_table *table = sd_alloc_ctl_entry(12);
e692ab53 5444
ad1cdc1d
MM
5445 if (table == NULL)
5446 return NULL;
5447
e0361851 5448 set_table_entry(&table[0], "min_interval", &sd->min_interval,
e692ab53 5449 sizeof(long), 0644, proc_doulongvec_minmax);
e0361851 5450 set_table_entry(&table[1], "max_interval", &sd->max_interval,
e692ab53 5451 sizeof(long), 0644, proc_doulongvec_minmax);
e0361851 5452 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
e692ab53 5453 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5454 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
e692ab53 5455 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5456 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
e692ab53 5457 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5458 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
e692ab53 5459 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5460 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
e692ab53 5461 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5462 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
e692ab53 5463 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5464 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
e692ab53 5465 sizeof(int), 0644, proc_dointvec_minmax);
ace8b3d6 5466 set_table_entry(&table[9], "cache_nice_tries",
e692ab53
NP
5467 &sd->cache_nice_tries,
5468 sizeof(int), 0644, proc_dointvec_minmax);
ace8b3d6 5469 set_table_entry(&table[10], "flags", &sd->flags,
e692ab53 5470 sizeof(int), 0644, proc_dointvec_minmax);
6323469f 5471 /* &table[11] is terminator */
e692ab53
NP
5472
5473 return table;
5474}
5475
9a4e7159 5476static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
e692ab53
NP
5477{
5478 struct ctl_table *entry, *table;
5479 struct sched_domain *sd;
5480 int domain_num = 0, i;
5481 char buf[32];
5482
5483 for_each_domain(cpu, sd)
5484 domain_num++;
5485 entry = table = sd_alloc_ctl_entry(domain_num + 1);
ad1cdc1d
MM
5486 if (table == NULL)
5487 return NULL;
e692ab53
NP
5488
5489 i = 0;
5490 for_each_domain(cpu, sd) {
5491 snprintf(buf, 32, "domain%d", i);
e692ab53 5492 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5493 entry->mode = 0555;
e692ab53
NP
5494 entry->child = sd_alloc_ctl_domain_table(sd);
5495 entry++;
5496 i++;
5497 }
5498 return table;
5499}
5500
5501static struct ctl_table_header *sd_sysctl_header;
6382bc90 5502static void register_sched_domain_sysctl(void)
e692ab53
NP
5503{
5504 int i, cpu_num = num_online_cpus();
5505 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5506 char buf[32];
5507
7378547f
MM
5508 WARN_ON(sd_ctl_dir[0].child);
5509 sd_ctl_dir[0].child = entry;
5510
ad1cdc1d
MM
5511 if (entry == NULL)
5512 return;
5513
97b6ea7b 5514 for_each_online_cpu(i) {
e692ab53 5515 snprintf(buf, 32, "cpu%d", i);
e692ab53 5516 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5517 entry->mode = 0555;
e692ab53 5518 entry->child = sd_alloc_ctl_cpu_table(i);
97b6ea7b 5519 entry++;
e692ab53 5520 }
7378547f
MM
5521
5522 WARN_ON(sd_sysctl_header);
e692ab53
NP
5523 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5524}
6382bc90 5525
7378547f 5526/* may be called multiple times per register */
6382bc90
MM
5527static void unregister_sched_domain_sysctl(void)
5528{
7378547f
MM
5529 if (sd_sysctl_header)
5530 unregister_sysctl_table(sd_sysctl_header);
6382bc90 5531 sd_sysctl_header = NULL;
7378547f
MM
5532 if (sd_ctl_dir[0].child)
5533 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6382bc90 5534}
e692ab53 5535#else
6382bc90
MM
5536static void register_sched_domain_sysctl(void)
5537{
5538}
5539static void unregister_sched_domain_sysctl(void)
e692ab53
NP
5540{
5541}
5542#endif
5543
1da177e4
LT
5544/*
5545 * migration_call - callback that gets triggered when a CPU is added.
5546 * Here we can start up the necessary migration thread for the new CPU.
5547 */
48f24c4d
IM
5548static int __cpuinit
5549migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
1da177e4 5550{
1da177e4 5551 struct task_struct *p;
48f24c4d 5552 int cpu = (long)hcpu;
1da177e4 5553 unsigned long flags;
70b97a7f 5554 struct rq *rq;
1da177e4
LT
5555
5556 switch (action) {
5be9361c
GS
5557 case CPU_LOCK_ACQUIRE:
5558 mutex_lock(&sched_hotcpu_mutex);
5559 break;
5560
1da177e4 5561 case CPU_UP_PREPARE:
8bb78442 5562 case CPU_UP_PREPARE_FROZEN:
dd41f596 5563 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
1da177e4
LT
5564 if (IS_ERR(p))
5565 return NOTIFY_BAD;
1da177e4
LT
5566 kthread_bind(p, cpu);
5567 /* Must be high prio: stop_machine expects to yield to it. */
5568 rq = task_rq_lock(p, &flags);
dd41f596 5569 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
1da177e4
LT
5570 task_rq_unlock(rq, &flags);
5571 cpu_rq(cpu)->migration_thread = p;
5572 break;
48f24c4d 5573
1da177e4 5574 case CPU_ONLINE:
8bb78442 5575 case CPU_ONLINE_FROZEN:
3a4fa0a2 5576 /* Strictly unnecessary, as first user will wake it. */
1da177e4
LT
5577 wake_up_process(cpu_rq(cpu)->migration_thread);
5578 break;
48f24c4d 5579
1da177e4
LT
5580#ifdef CONFIG_HOTPLUG_CPU
5581 case CPU_UP_CANCELED:
8bb78442 5582 case CPU_UP_CANCELED_FROZEN:
fc75cdfa
HC
5583 if (!cpu_rq(cpu)->migration_thread)
5584 break;
41a2d6cf 5585 /* Unbind it from offline cpu so it can run. Fall thru. */
a4c4af7c
HC
5586 kthread_bind(cpu_rq(cpu)->migration_thread,
5587 any_online_cpu(cpu_online_map));
1da177e4
LT
5588 kthread_stop(cpu_rq(cpu)->migration_thread);
5589 cpu_rq(cpu)->migration_thread = NULL;
5590 break;
48f24c4d 5591
1da177e4 5592 case CPU_DEAD:
8bb78442 5593 case CPU_DEAD_FROZEN:
470fd646 5594 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
1da177e4
LT
5595 migrate_live_tasks(cpu);
5596 rq = cpu_rq(cpu);
5597 kthread_stop(rq->migration_thread);
5598 rq->migration_thread = NULL;
5599 /* Idle task back to normal (off runqueue, low prio) */
d2da272a 5600 spin_lock_irq(&rq->lock);
a8e504d2 5601 update_rq_clock(rq);
2e1cb74a 5602 deactivate_task(rq, rq->idle, 0);
1da177e4 5603 rq->idle->static_prio = MAX_PRIO;
dd41f596
IM
5604 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5605 rq->idle->sched_class = &idle_sched_class;
1da177e4 5606 migrate_dead_tasks(cpu);
d2da272a 5607 spin_unlock_irq(&rq->lock);
470fd646 5608 cpuset_unlock();
1da177e4
LT
5609 migrate_nr_uninterruptible(rq);
5610 BUG_ON(rq->nr_running != 0);
5611
41a2d6cf
IM
5612 /*
5613 * No need to migrate the tasks: it was best-effort if
5614 * they didn't take sched_hotcpu_mutex. Just wake up
5615 * the requestors.
5616 */
1da177e4
LT
5617 spin_lock_irq(&rq->lock);
5618 while (!list_empty(&rq->migration_queue)) {
70b97a7f
IM
5619 struct migration_req *req;
5620
1da177e4 5621 req = list_entry(rq->migration_queue.next,
70b97a7f 5622 struct migration_req, list);
1da177e4
LT
5623 list_del_init(&req->list);
5624 complete(&req->done);
5625 }
5626 spin_unlock_irq(&rq->lock);
5627 break;
5628#endif
5be9361c
GS
5629 case CPU_LOCK_RELEASE:
5630 mutex_unlock(&sched_hotcpu_mutex);
5631 break;
1da177e4
LT
5632 }
5633 return NOTIFY_OK;
5634}
5635
5636/* Register at highest priority so that task migration (migrate_all_tasks)
5637 * happens before everything else.
5638 */
26c2143b 5639static struct notifier_block __cpuinitdata migration_notifier = {
1da177e4
LT
5640 .notifier_call = migration_call,
5641 .priority = 10
5642};
5643
e6fe6649 5644void __init migration_init(void)
1da177e4
LT
5645{
5646 void *cpu = (void *)(long)smp_processor_id();
07dccf33 5647 int err;
48f24c4d
IM
5648
5649 /* Start one for the boot CPU: */
07dccf33
AM
5650 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5651 BUG_ON(err == NOTIFY_BAD);
1da177e4
LT
5652 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5653 register_cpu_notifier(&migration_notifier);
1da177e4
LT
5654}
5655#endif
5656
5657#ifdef CONFIG_SMP
476f3534
CL
5658
5659/* Number of possible processor ids */
5660int nr_cpu_ids __read_mostly = NR_CPUS;
5661EXPORT_SYMBOL(nr_cpu_ids);
5662
3e9830dc 5663#ifdef CONFIG_SCHED_DEBUG
4dcf6aff
IM
5664
5665static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level)
1da177e4 5666{
4dcf6aff
IM
5667 struct sched_group *group = sd->groups;
5668 cpumask_t groupmask;
5669 char str[NR_CPUS];
1da177e4 5670
4dcf6aff
IM
5671 cpumask_scnprintf(str, NR_CPUS, sd->span);
5672 cpus_clear(groupmask);
5673
5674 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5675
5676 if (!(sd->flags & SD_LOAD_BALANCE)) {
5677 printk("does not load-balance\n");
5678 if (sd->parent)
5679 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5680 " has parent");
5681 return -1;
41c7ce9a
NP
5682 }
5683
4dcf6aff
IM
5684 printk(KERN_CONT "span %s\n", str);
5685
5686 if (!cpu_isset(cpu, sd->span)) {
5687 printk(KERN_ERR "ERROR: domain->span does not contain "
5688 "CPU%d\n", cpu);
5689 }
5690 if (!cpu_isset(cpu, group->cpumask)) {
5691 printk(KERN_ERR "ERROR: domain->groups does not contain"
5692 " CPU%d\n", cpu);
5693 }
1da177e4 5694
4dcf6aff 5695 printk(KERN_DEBUG "%*s groups:", level + 1, "");
1da177e4 5696 do {
4dcf6aff
IM
5697 if (!group) {
5698 printk("\n");
5699 printk(KERN_ERR "ERROR: group is NULL\n");
1da177e4
LT
5700 break;
5701 }
5702
4dcf6aff
IM
5703 if (!group->__cpu_power) {
5704 printk(KERN_CONT "\n");
5705 printk(KERN_ERR "ERROR: domain->cpu_power not "
5706 "set\n");
5707 break;
5708 }
1da177e4 5709
4dcf6aff
IM
5710 if (!cpus_weight(group->cpumask)) {
5711 printk(KERN_CONT "\n");
5712 printk(KERN_ERR "ERROR: empty group\n");
5713 break;
5714 }
1da177e4 5715
4dcf6aff
IM
5716 if (cpus_intersects(groupmask, group->cpumask)) {
5717 printk(KERN_CONT "\n");
5718 printk(KERN_ERR "ERROR: repeated CPUs\n");
5719 break;
5720 }
1da177e4 5721
4dcf6aff 5722 cpus_or(groupmask, groupmask, group->cpumask);
1da177e4 5723
4dcf6aff
IM
5724 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5725 printk(KERN_CONT " %s", str);
1da177e4 5726
4dcf6aff
IM
5727 group = group->next;
5728 } while (group != sd->groups);
5729 printk(KERN_CONT "\n");
1da177e4 5730
4dcf6aff
IM
5731 if (!cpus_equal(sd->span, groupmask))
5732 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
1da177e4 5733
4dcf6aff
IM
5734 if (sd->parent && !cpus_subset(groupmask, sd->parent->span))
5735 printk(KERN_ERR "ERROR: parent span is not a superset "
5736 "of domain->span\n");
5737 return 0;
5738}
1da177e4 5739
4dcf6aff
IM
5740static void sched_domain_debug(struct sched_domain *sd, int cpu)
5741{
5742 int level = 0;
1da177e4 5743
4dcf6aff
IM
5744 if (!sd) {
5745 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5746 return;
5747 }
1da177e4 5748
4dcf6aff
IM
5749 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5750
5751 for (;;) {
5752 if (sched_domain_debug_one(sd, cpu, level))
5753 break;
1da177e4
LT
5754 level++;
5755 sd = sd->parent;
33859f7f 5756 if (!sd)
4dcf6aff
IM
5757 break;
5758 }
1da177e4
LT
5759}
5760#else
48f24c4d 5761# define sched_domain_debug(sd, cpu) do { } while (0)
1da177e4
LT
5762#endif
5763
1a20ff27 5764static int sd_degenerate(struct sched_domain *sd)
245af2c7
SS
5765{
5766 if (cpus_weight(sd->span) == 1)
5767 return 1;
5768
5769 /* Following flags need at least 2 groups */
5770 if (sd->flags & (SD_LOAD_BALANCE |
5771 SD_BALANCE_NEWIDLE |
5772 SD_BALANCE_FORK |
89c4710e
SS
5773 SD_BALANCE_EXEC |
5774 SD_SHARE_CPUPOWER |
5775 SD_SHARE_PKG_RESOURCES)) {
245af2c7
SS
5776 if (sd->groups != sd->groups->next)
5777 return 0;
5778 }
5779
5780 /* Following flags don't use groups */
5781 if (sd->flags & (SD_WAKE_IDLE |
5782 SD_WAKE_AFFINE |
5783 SD_WAKE_BALANCE))
5784 return 0;
5785
5786 return 1;
5787}
5788
48f24c4d
IM
5789static int
5790sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
245af2c7
SS
5791{
5792 unsigned long cflags = sd->flags, pflags = parent->flags;
5793
5794 if (sd_degenerate(parent))
5795 return 1;
5796
5797 if (!cpus_equal(sd->span, parent->span))
5798 return 0;
5799
5800 /* Does parent contain flags not in child? */
5801 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5802 if (cflags & SD_WAKE_AFFINE)
5803 pflags &= ~SD_WAKE_BALANCE;
5804 /* Flags needing groups don't count if only 1 group in parent */
5805 if (parent->groups == parent->groups->next) {
5806 pflags &= ~(SD_LOAD_BALANCE |
5807 SD_BALANCE_NEWIDLE |
5808 SD_BALANCE_FORK |
89c4710e
SS
5809 SD_BALANCE_EXEC |
5810 SD_SHARE_CPUPOWER |
5811 SD_SHARE_PKG_RESOURCES);
245af2c7
SS
5812 }
5813 if (~cflags & pflags)
5814 return 0;
5815
5816 return 1;
5817}
5818
1da177e4
LT
5819/*
5820 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5821 * hold the hotplug lock.
5822 */
9c1cfda2 5823static void cpu_attach_domain(struct sched_domain *sd, int cpu)
1da177e4 5824{
70b97a7f 5825 struct rq *rq = cpu_rq(cpu);
245af2c7
SS
5826 struct sched_domain *tmp;
5827
5828 /* Remove the sched domains which do not contribute to scheduling. */
5829 for (tmp = sd; tmp; tmp = tmp->parent) {
5830 struct sched_domain *parent = tmp->parent;
5831 if (!parent)
5832 break;
1a848870 5833 if (sd_parent_degenerate(tmp, parent)) {
245af2c7 5834 tmp->parent = parent->parent;
1a848870
SS
5835 if (parent->parent)
5836 parent->parent->child = tmp;
5837 }
245af2c7
SS
5838 }
5839
1a848870 5840 if (sd && sd_degenerate(sd)) {
245af2c7 5841 sd = sd->parent;
1a848870
SS
5842 if (sd)
5843 sd->child = NULL;
5844 }
1da177e4
LT
5845
5846 sched_domain_debug(sd, cpu);
5847
674311d5 5848 rcu_assign_pointer(rq->sd, sd);
1da177e4
LT
5849}
5850
5851/* cpus with isolated domains */
67af63a6 5852static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
1da177e4
LT
5853
5854/* Setup the mask of cpus configured for isolated domains */
5855static int __init isolated_cpu_setup(char *str)
5856{
5857 int ints[NR_CPUS], i;
5858
5859 str = get_options(str, ARRAY_SIZE(ints), ints);
5860 cpus_clear(cpu_isolated_map);
5861 for (i = 1; i <= ints[0]; i++)
5862 if (ints[i] < NR_CPUS)
5863 cpu_set(ints[i], cpu_isolated_map);
5864 return 1;
5865}
5866
8927f494 5867__setup("isolcpus=", isolated_cpu_setup);
1da177e4
LT
5868
5869/*
6711cab4
SS
5870 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
5871 * to a function which identifies what group(along with sched group) a CPU
5872 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
5873 * (due to the fact that we keep track of groups covered with a cpumask_t).
1da177e4
LT
5874 *
5875 * init_sched_build_groups will build a circular linked list of the groups
5876 * covered by the given span, and will set each group's ->cpumask correctly,
5877 * and ->cpu_power to 0.
5878 */
a616058b 5879static void
6711cab4
SS
5880init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
5881 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
5882 struct sched_group **sg))
1da177e4
LT
5883{
5884 struct sched_group *first = NULL, *last = NULL;
5885 cpumask_t covered = CPU_MASK_NONE;
5886 int i;
5887
5888 for_each_cpu_mask(i, span) {
6711cab4
SS
5889 struct sched_group *sg;
5890 int group = group_fn(i, cpu_map, &sg);
1da177e4
LT
5891 int j;
5892
5893 if (cpu_isset(i, covered))
5894 continue;
5895
5896 sg->cpumask = CPU_MASK_NONE;
5517d86b 5897 sg->__cpu_power = 0;
1da177e4
LT
5898
5899 for_each_cpu_mask(j, span) {
6711cab4 5900 if (group_fn(j, cpu_map, NULL) != group)
1da177e4
LT
5901 continue;
5902
5903 cpu_set(j, covered);
5904 cpu_set(j, sg->cpumask);
5905 }
5906 if (!first)
5907 first = sg;
5908 if (last)
5909 last->next = sg;
5910 last = sg;
5911 }
5912 last->next = first;
5913}
5914
9c1cfda2 5915#define SD_NODES_PER_DOMAIN 16
1da177e4 5916
9c1cfda2 5917#ifdef CONFIG_NUMA
198e2f18 5918
9c1cfda2
JH
5919/**
5920 * find_next_best_node - find the next node to include in a sched_domain
5921 * @node: node whose sched_domain we're building
5922 * @used_nodes: nodes already in the sched_domain
5923 *
41a2d6cf 5924 * Find the next node to include in a given scheduling domain. Simply
9c1cfda2
JH
5925 * finds the closest node not already in the @used_nodes map.
5926 *
5927 * Should use nodemask_t.
5928 */
5929static int find_next_best_node(int node, unsigned long *used_nodes)
5930{
5931 int i, n, val, min_val, best_node = 0;
5932
5933 min_val = INT_MAX;
5934
5935 for (i = 0; i < MAX_NUMNODES; i++) {
5936 /* Start at @node */
5937 n = (node + i) % MAX_NUMNODES;
5938
5939 if (!nr_cpus_node(n))
5940 continue;
5941
5942 /* Skip already used nodes */
5943 if (test_bit(n, used_nodes))
5944 continue;
5945
5946 /* Simple min distance search */
5947 val = node_distance(node, n);
5948
5949 if (val < min_val) {
5950 min_val = val;
5951 best_node = n;
5952 }
5953 }
5954
5955 set_bit(best_node, used_nodes);
5956 return best_node;
5957}
5958
5959/**
5960 * sched_domain_node_span - get a cpumask for a node's sched_domain
5961 * @node: node whose cpumask we're constructing
5962 * @size: number of nodes to include in this span
5963 *
41a2d6cf 5964 * Given a node, construct a good cpumask for its sched_domain to span. It
9c1cfda2
JH
5965 * should be one that prevents unnecessary balancing, but also spreads tasks
5966 * out optimally.
5967 */
5968static cpumask_t sched_domain_node_span(int node)
5969{
9c1cfda2 5970 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
48f24c4d
IM
5971 cpumask_t span, nodemask;
5972 int i;
9c1cfda2
JH
5973
5974 cpus_clear(span);
5975 bitmap_zero(used_nodes, MAX_NUMNODES);
5976
5977 nodemask = node_to_cpumask(node);
5978 cpus_or(span, span, nodemask);
5979 set_bit(node, used_nodes);
5980
5981 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5982 int next_node = find_next_best_node(node, used_nodes);
48f24c4d 5983
9c1cfda2
JH
5984 nodemask = node_to_cpumask(next_node);
5985 cpus_or(span, span, nodemask);
5986 }
5987
5988 return span;
5989}
5990#endif
5991
5c45bf27 5992int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
48f24c4d 5993
9c1cfda2 5994/*
48f24c4d 5995 * SMT sched-domains:
9c1cfda2 5996 */
1da177e4
LT
5997#ifdef CONFIG_SCHED_SMT
5998static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6711cab4 5999static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
48f24c4d 6000
41a2d6cf
IM
6001static int
6002cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
1da177e4 6003{
6711cab4
SS
6004 if (sg)
6005 *sg = &per_cpu(sched_group_cpus, cpu);
1da177e4
LT
6006 return cpu;
6007}
6008#endif
6009
48f24c4d
IM
6010/*
6011 * multi-core sched-domains:
6012 */
1e9f28fa
SS
6013#ifdef CONFIG_SCHED_MC
6014static DEFINE_PER_CPU(struct sched_domain, core_domains);
6711cab4 6015static DEFINE_PER_CPU(struct sched_group, sched_group_core);
1e9f28fa
SS
6016#endif
6017
6018#if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
41a2d6cf
IM
6019static int
6020cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
1e9f28fa 6021{
6711cab4 6022 int group;
d5a7430d 6023 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
a616058b 6024 cpus_and(mask, mask, *cpu_map);
6711cab4
SS
6025 group = first_cpu(mask);
6026 if (sg)
6027 *sg = &per_cpu(sched_group_core, group);
6028 return group;
1e9f28fa
SS
6029}
6030#elif defined(CONFIG_SCHED_MC)
41a2d6cf
IM
6031static int
6032cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
1e9f28fa 6033{
6711cab4
SS
6034 if (sg)
6035 *sg = &per_cpu(sched_group_core, cpu);
1e9f28fa
SS
6036 return cpu;
6037}
6038#endif
6039
1da177e4 6040static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6711cab4 6041static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
48f24c4d 6042
41a2d6cf
IM
6043static int
6044cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
1da177e4 6045{
6711cab4 6046 int group;
48f24c4d 6047#ifdef CONFIG_SCHED_MC
1e9f28fa 6048 cpumask_t mask = cpu_coregroup_map(cpu);
a616058b 6049 cpus_and(mask, mask, *cpu_map);
6711cab4 6050 group = first_cpu(mask);
1e9f28fa 6051#elif defined(CONFIG_SCHED_SMT)
d5a7430d 6052 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
a616058b 6053 cpus_and(mask, mask, *cpu_map);
6711cab4 6054 group = first_cpu(mask);
1da177e4 6055#else
6711cab4 6056 group = cpu;
1da177e4 6057#endif
6711cab4
SS
6058 if (sg)
6059 *sg = &per_cpu(sched_group_phys, group);
6060 return group;
1da177e4
LT
6061}
6062
6063#ifdef CONFIG_NUMA
1da177e4 6064/*
9c1cfda2
JH
6065 * The init_sched_build_groups can't handle what we want to do with node
6066 * groups, so roll our own. Now each node has its own list of groups which
6067 * gets dynamically allocated.
1da177e4 6068 */
9c1cfda2 6069static DEFINE_PER_CPU(struct sched_domain, node_domains);
d1b55138 6070static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
1da177e4 6071
9c1cfda2 6072static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6711cab4 6073static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
9c1cfda2 6074
6711cab4
SS
6075static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6076 struct sched_group **sg)
9c1cfda2 6077{
6711cab4
SS
6078 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6079 int group;
6080
6081 cpus_and(nodemask, nodemask, *cpu_map);
6082 group = first_cpu(nodemask);
6083
6084 if (sg)
6085 *sg = &per_cpu(sched_group_allnodes, group);
6086 return group;
1da177e4 6087}
6711cab4 6088
08069033
SS
6089static void init_numa_sched_groups_power(struct sched_group *group_head)
6090{
6091 struct sched_group *sg = group_head;
6092 int j;
6093
6094 if (!sg)
6095 return;
3a5c359a
AK
6096 do {
6097 for_each_cpu_mask(j, sg->cpumask) {
6098 struct sched_domain *sd;
08069033 6099
3a5c359a
AK
6100 sd = &per_cpu(phys_domains, j);
6101 if (j != first_cpu(sd->groups->cpumask)) {
6102 /*
6103 * Only add "power" once for each
6104 * physical package.
6105 */
6106 continue;
6107 }
08069033 6108
3a5c359a
AK
6109 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6110 }
6111 sg = sg->next;
6112 } while (sg != group_head);
08069033 6113}
1da177e4
LT
6114#endif
6115
a616058b 6116#ifdef CONFIG_NUMA
51888ca2
SV
6117/* Free memory allocated for various sched_group structures */
6118static void free_sched_groups(const cpumask_t *cpu_map)
6119{
a616058b 6120 int cpu, i;
51888ca2
SV
6121
6122 for_each_cpu_mask(cpu, *cpu_map) {
51888ca2
SV
6123 struct sched_group **sched_group_nodes
6124 = sched_group_nodes_bycpu[cpu];
6125
51888ca2
SV
6126 if (!sched_group_nodes)
6127 continue;
6128
6129 for (i = 0; i < MAX_NUMNODES; i++) {
6130 cpumask_t nodemask = node_to_cpumask(i);
6131 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6132
6133 cpus_and(nodemask, nodemask, *cpu_map);
6134 if (cpus_empty(nodemask))
6135 continue;
6136
6137 if (sg == NULL)
6138 continue;
6139 sg = sg->next;
6140next_sg:
6141 oldsg = sg;
6142 sg = sg->next;
6143 kfree(oldsg);
6144 if (oldsg != sched_group_nodes[i])
6145 goto next_sg;
6146 }
6147 kfree(sched_group_nodes);
6148 sched_group_nodes_bycpu[cpu] = NULL;
6149 }
51888ca2 6150}
a616058b
SS
6151#else
6152static void free_sched_groups(const cpumask_t *cpu_map)
6153{
6154}
6155#endif
51888ca2 6156
89c4710e
SS
6157/*
6158 * Initialize sched groups cpu_power.
6159 *
6160 * cpu_power indicates the capacity of sched group, which is used while
6161 * distributing the load between different sched groups in a sched domain.
6162 * Typically cpu_power for all the groups in a sched domain will be same unless
6163 * there are asymmetries in the topology. If there are asymmetries, group
6164 * having more cpu_power will pickup more load compared to the group having
6165 * less cpu_power.
6166 *
6167 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6168 * the maximum number of tasks a group can handle in the presence of other idle
6169 * or lightly loaded groups in the same sched domain.
6170 */
6171static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6172{
6173 struct sched_domain *child;
6174 struct sched_group *group;
6175
6176 WARN_ON(!sd || !sd->groups);
6177
6178 if (cpu != first_cpu(sd->groups->cpumask))
6179 return;
6180
6181 child = sd->child;
6182
5517d86b
ED
6183 sd->groups->__cpu_power = 0;
6184
89c4710e
SS
6185 /*
6186 * For perf policy, if the groups in child domain share resources
6187 * (for example cores sharing some portions of the cache hierarchy
6188 * or SMT), then set this domain groups cpu_power such that each group
6189 * can handle only one task, when there are other idle groups in the
6190 * same sched domain.
6191 */
6192 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6193 (child->flags &
6194 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
5517d86b 6195 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
89c4710e
SS
6196 return;
6197 }
6198
89c4710e
SS
6199 /*
6200 * add cpu_power of each child group to this groups cpu_power
6201 */
6202 group = child->groups;
6203 do {
5517d86b 6204 sg_inc_cpu_power(sd->groups, group->__cpu_power);
89c4710e
SS
6205 group = group->next;
6206 } while (group != child->groups);
6207}
6208
1da177e4 6209/*
1a20ff27
DG
6210 * Build sched domains for a given set of cpus and attach the sched domains
6211 * to the individual cpus
1da177e4 6212 */
51888ca2 6213static int build_sched_domains(const cpumask_t *cpu_map)
1da177e4
LT
6214{
6215 int i;
d1b55138
JH
6216#ifdef CONFIG_NUMA
6217 struct sched_group **sched_group_nodes = NULL;
6711cab4 6218 int sd_allnodes = 0;
d1b55138
JH
6219
6220 /*
6221 * Allocate the per-node list of sched groups
6222 */
5cf9f062 6223 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
41a2d6cf 6224 GFP_KERNEL);
d1b55138
JH
6225 if (!sched_group_nodes) {
6226 printk(KERN_WARNING "Can not alloc sched group node list\n");
51888ca2 6227 return -ENOMEM;
d1b55138
JH
6228 }
6229 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6230#endif
1da177e4
LT
6231
6232 /*
1a20ff27 6233 * Set up domains for cpus specified by the cpu_map.
1da177e4 6234 */
1a20ff27 6235 for_each_cpu_mask(i, *cpu_map) {
1da177e4
LT
6236 struct sched_domain *sd = NULL, *p;
6237 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6238
1a20ff27 6239 cpus_and(nodemask, nodemask, *cpu_map);
1da177e4
LT
6240
6241#ifdef CONFIG_NUMA
dd41f596
IM
6242 if (cpus_weight(*cpu_map) >
6243 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
9c1cfda2
JH
6244 sd = &per_cpu(allnodes_domains, i);
6245 *sd = SD_ALLNODES_INIT;
6246 sd->span = *cpu_map;
6711cab4 6247 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
9c1cfda2 6248 p = sd;
6711cab4 6249 sd_allnodes = 1;
9c1cfda2
JH
6250 } else
6251 p = NULL;
6252
1da177e4 6253 sd = &per_cpu(node_domains, i);
1da177e4 6254 *sd = SD_NODE_INIT;
9c1cfda2
JH
6255 sd->span = sched_domain_node_span(cpu_to_node(i));
6256 sd->parent = p;
1a848870
SS
6257 if (p)
6258 p->child = sd;
9c1cfda2 6259 cpus_and(sd->span, sd->span, *cpu_map);
1da177e4
LT
6260#endif
6261
6262 p = sd;
6263 sd = &per_cpu(phys_domains, i);
1da177e4
LT
6264 *sd = SD_CPU_INIT;
6265 sd->span = nodemask;
6266 sd->parent = p;
1a848870
SS
6267 if (p)
6268 p->child = sd;
6711cab4 6269 cpu_to_phys_group(i, cpu_map, &sd->groups);
1da177e4 6270
1e9f28fa
SS
6271#ifdef CONFIG_SCHED_MC
6272 p = sd;
6273 sd = &per_cpu(core_domains, i);
1e9f28fa
SS
6274 *sd = SD_MC_INIT;
6275 sd->span = cpu_coregroup_map(i);
6276 cpus_and(sd->span, sd->span, *cpu_map);
6277 sd->parent = p;
1a848870 6278 p->child = sd;
6711cab4 6279 cpu_to_core_group(i, cpu_map, &sd->groups);
1e9f28fa
SS
6280#endif
6281
1da177e4
LT
6282#ifdef CONFIG_SCHED_SMT
6283 p = sd;
6284 sd = &per_cpu(cpu_domains, i);
1da177e4 6285 *sd = SD_SIBLING_INIT;
d5a7430d 6286 sd->span = per_cpu(cpu_sibling_map, i);
1a20ff27 6287 cpus_and(sd->span, sd->span, *cpu_map);
1da177e4 6288 sd->parent = p;
1a848870 6289 p->child = sd;
6711cab4 6290 cpu_to_cpu_group(i, cpu_map, &sd->groups);
1da177e4
LT
6291#endif
6292 }
6293
6294#ifdef CONFIG_SCHED_SMT
6295 /* Set up CPU (sibling) groups */
9c1cfda2 6296 for_each_cpu_mask(i, *cpu_map) {
d5a7430d 6297 cpumask_t this_sibling_map = per_cpu(cpu_sibling_map, i);
1a20ff27 6298 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
1da177e4
LT
6299 if (i != first_cpu(this_sibling_map))
6300 continue;
6301
dd41f596
IM
6302 init_sched_build_groups(this_sibling_map, cpu_map,
6303 &cpu_to_cpu_group);
1da177e4
LT
6304 }
6305#endif
6306
1e9f28fa
SS
6307#ifdef CONFIG_SCHED_MC
6308 /* Set up multi-core groups */
6309 for_each_cpu_mask(i, *cpu_map) {
6310 cpumask_t this_core_map = cpu_coregroup_map(i);
6311 cpus_and(this_core_map, this_core_map, *cpu_map);
6312 if (i != first_cpu(this_core_map))
6313 continue;
dd41f596
IM
6314 init_sched_build_groups(this_core_map, cpu_map,
6315 &cpu_to_core_group);
1e9f28fa
SS
6316 }
6317#endif
6318
1da177e4
LT
6319 /* Set up physical groups */
6320 for (i = 0; i < MAX_NUMNODES; i++) {
6321 cpumask_t nodemask = node_to_cpumask(i);
6322
1a20ff27 6323 cpus_and(nodemask, nodemask, *cpu_map);
1da177e4
LT
6324 if (cpus_empty(nodemask))
6325 continue;
6326
6711cab4 6327 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
1da177e4
LT
6328 }
6329
6330#ifdef CONFIG_NUMA
6331 /* Set up node groups */
6711cab4 6332 if (sd_allnodes)
dd41f596
IM
6333 init_sched_build_groups(*cpu_map, cpu_map,
6334 &cpu_to_allnodes_group);
9c1cfda2
JH
6335
6336 for (i = 0; i < MAX_NUMNODES; i++) {
6337 /* Set up node groups */
6338 struct sched_group *sg, *prev;
6339 cpumask_t nodemask = node_to_cpumask(i);
6340 cpumask_t domainspan;
6341 cpumask_t covered = CPU_MASK_NONE;
6342 int j;
6343
6344 cpus_and(nodemask, nodemask, *cpu_map);
d1b55138
JH
6345 if (cpus_empty(nodemask)) {
6346 sched_group_nodes[i] = NULL;
9c1cfda2 6347 continue;
d1b55138 6348 }
9c1cfda2
JH
6349
6350 domainspan = sched_domain_node_span(i);
6351 cpus_and(domainspan, domainspan, *cpu_map);
6352
15f0b676 6353 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
51888ca2
SV
6354 if (!sg) {
6355 printk(KERN_WARNING "Can not alloc domain group for "
6356 "node %d\n", i);
6357 goto error;
6358 }
9c1cfda2
JH
6359 sched_group_nodes[i] = sg;
6360 for_each_cpu_mask(j, nodemask) {
6361 struct sched_domain *sd;
9761eea8 6362
9c1cfda2
JH
6363 sd = &per_cpu(node_domains, j);
6364 sd->groups = sg;
9c1cfda2 6365 }
5517d86b 6366 sg->__cpu_power = 0;
9c1cfda2 6367 sg->cpumask = nodemask;
51888ca2 6368 sg->next = sg;
9c1cfda2
JH
6369 cpus_or(covered, covered, nodemask);
6370 prev = sg;
6371
6372 for (j = 0; j < MAX_NUMNODES; j++) {
6373 cpumask_t tmp, notcovered;
6374 int n = (i + j) % MAX_NUMNODES;
6375
6376 cpus_complement(notcovered, covered);
6377 cpus_and(tmp, notcovered, *cpu_map);
6378 cpus_and(tmp, tmp, domainspan);
6379 if (cpus_empty(tmp))
6380 break;
6381
6382 nodemask = node_to_cpumask(n);
6383 cpus_and(tmp, tmp, nodemask);
6384 if (cpus_empty(tmp))
6385 continue;
6386
15f0b676
SV
6387 sg = kmalloc_node(sizeof(struct sched_group),
6388 GFP_KERNEL, i);
9c1cfda2
JH
6389 if (!sg) {
6390 printk(KERN_WARNING
6391 "Can not alloc domain group for node %d\n", j);
51888ca2 6392 goto error;
9c1cfda2 6393 }
5517d86b 6394 sg->__cpu_power = 0;
9c1cfda2 6395 sg->cpumask = tmp;
51888ca2 6396 sg->next = prev->next;
9c1cfda2
JH
6397 cpus_or(covered, covered, tmp);
6398 prev->next = sg;
6399 prev = sg;
6400 }
9c1cfda2 6401 }
1da177e4
LT
6402#endif
6403
6404 /* Calculate CPU power for physical packages and nodes */
5c45bf27 6405#ifdef CONFIG_SCHED_SMT
1a20ff27 6406 for_each_cpu_mask(i, *cpu_map) {
dd41f596
IM
6407 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6408
89c4710e 6409 init_sched_groups_power(i, sd);
5c45bf27 6410 }
1da177e4 6411#endif
1e9f28fa 6412#ifdef CONFIG_SCHED_MC
5c45bf27 6413 for_each_cpu_mask(i, *cpu_map) {
dd41f596
IM
6414 struct sched_domain *sd = &per_cpu(core_domains, i);
6415
89c4710e 6416 init_sched_groups_power(i, sd);
5c45bf27
SS
6417 }
6418#endif
1e9f28fa 6419
5c45bf27 6420 for_each_cpu_mask(i, *cpu_map) {
dd41f596
IM
6421 struct sched_domain *sd = &per_cpu(phys_domains, i);
6422
89c4710e 6423 init_sched_groups_power(i, sd);
1da177e4
LT
6424 }
6425
9c1cfda2 6426#ifdef CONFIG_NUMA
08069033
SS
6427 for (i = 0; i < MAX_NUMNODES; i++)
6428 init_numa_sched_groups_power(sched_group_nodes[i]);
9c1cfda2 6429
6711cab4
SS
6430 if (sd_allnodes) {
6431 struct sched_group *sg;
f712c0c7 6432
6711cab4 6433 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
f712c0c7
SS
6434 init_numa_sched_groups_power(sg);
6435 }
9c1cfda2
JH
6436#endif
6437
1da177e4 6438 /* Attach the domains */
1a20ff27 6439 for_each_cpu_mask(i, *cpu_map) {
1da177e4
LT
6440 struct sched_domain *sd;
6441#ifdef CONFIG_SCHED_SMT
6442 sd = &per_cpu(cpu_domains, i);
1e9f28fa
SS
6443#elif defined(CONFIG_SCHED_MC)
6444 sd = &per_cpu(core_domains, i);
1da177e4
LT
6445#else
6446 sd = &per_cpu(phys_domains, i);
6447#endif
6448 cpu_attach_domain(sd, i);
6449 }
51888ca2
SV
6450
6451 return 0;
6452
a616058b 6453#ifdef CONFIG_NUMA
51888ca2
SV
6454error:
6455 free_sched_groups(cpu_map);
6456 return -ENOMEM;
a616058b 6457#endif
1da177e4 6458}
029190c5
PJ
6459
6460static cpumask_t *doms_cur; /* current sched domains */
6461static int ndoms_cur; /* number of sched domains in 'doms_cur' */
6462
6463/*
6464 * Special case: If a kmalloc of a doms_cur partition (array of
6465 * cpumask_t) fails, then fallback to a single sched domain,
6466 * as determined by the single cpumask_t fallback_doms.
6467 */
6468static cpumask_t fallback_doms;
6469
1a20ff27 6470/*
41a2d6cf 6471 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
029190c5
PJ
6472 * For now this just excludes isolated cpus, but could be used to
6473 * exclude other special cases in the future.
1a20ff27 6474 */
51888ca2 6475static int arch_init_sched_domains(const cpumask_t *cpu_map)
1a20ff27 6476{
7378547f
MM
6477 int err;
6478
029190c5
PJ
6479 ndoms_cur = 1;
6480 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6481 if (!doms_cur)
6482 doms_cur = &fallback_doms;
6483 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7378547f 6484 err = build_sched_domains(doms_cur);
6382bc90 6485 register_sched_domain_sysctl();
7378547f
MM
6486
6487 return err;
1a20ff27
DG
6488}
6489
6490static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
1da177e4 6491{
51888ca2 6492 free_sched_groups(cpu_map);
9c1cfda2 6493}
1da177e4 6494
1a20ff27
DG
6495/*
6496 * Detach sched domains from a group of cpus specified in cpu_map
6497 * These cpus will now be attached to the NULL domain
6498 */
858119e1 6499static void detach_destroy_domains(const cpumask_t *cpu_map)
1a20ff27
DG
6500{
6501 int i;
6502
6382bc90
MM
6503 unregister_sched_domain_sysctl();
6504
1a20ff27
DG
6505 for_each_cpu_mask(i, *cpu_map)
6506 cpu_attach_domain(NULL, i);
6507 synchronize_sched();
6508 arch_destroy_sched_domains(cpu_map);
6509}
6510
029190c5
PJ
6511/*
6512 * Partition sched domains as specified by the 'ndoms_new'
41a2d6cf 6513 * cpumasks in the array doms_new[] of cpumasks. This compares
029190c5
PJ
6514 * doms_new[] to the current sched domain partitioning, doms_cur[].
6515 * It destroys each deleted domain and builds each new domain.
6516 *
6517 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
41a2d6cf
IM
6518 * The masks don't intersect (don't overlap.) We should setup one
6519 * sched domain for each mask. CPUs not in any of the cpumasks will
6520 * not be load balanced. If the same cpumask appears both in the
029190c5
PJ
6521 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6522 * it as it is.
6523 *
41a2d6cf
IM
6524 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6525 * ownership of it and will kfree it when done with it. If the caller
029190c5
PJ
6526 * failed the kmalloc call, then it can pass in doms_new == NULL,
6527 * and partition_sched_domains() will fallback to the single partition
6528 * 'fallback_doms'.
6529 *
6530 * Call with hotplug lock held
6531 */
6532void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
6533{
6534 int i, j;
6535
7378547f
MM
6536 /* always unregister in case we don't destroy any domains */
6537 unregister_sched_domain_sysctl();
6538
029190c5
PJ
6539 if (doms_new == NULL) {
6540 ndoms_new = 1;
6541 doms_new = &fallback_doms;
6542 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
6543 }
6544
6545 /* Destroy deleted domains */
6546 for (i = 0; i < ndoms_cur; i++) {
6547 for (j = 0; j < ndoms_new; j++) {
6548 if (cpus_equal(doms_cur[i], doms_new[j]))
6549 goto match1;
6550 }
6551 /* no match - a current sched domain not in new doms_new[] */
6552 detach_destroy_domains(doms_cur + i);
6553match1:
6554 ;
6555 }
6556
6557 /* Build new domains */
6558 for (i = 0; i < ndoms_new; i++) {
6559 for (j = 0; j < ndoms_cur; j++) {
6560 if (cpus_equal(doms_new[i], doms_cur[j]))
6561 goto match2;
6562 }
6563 /* no match - add a new doms_new */
6564 build_sched_domains(doms_new + i);
6565match2:
6566 ;
6567 }
6568
6569 /* Remember the new sched domains */
6570 if (doms_cur != &fallback_doms)
6571 kfree(doms_cur);
6572 doms_cur = doms_new;
6573 ndoms_cur = ndoms_new;
7378547f
MM
6574
6575 register_sched_domain_sysctl();
029190c5
PJ
6576}
6577
5c45bf27 6578#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6707de00 6579static int arch_reinit_sched_domains(void)
5c45bf27
SS
6580{
6581 int err;
6582
5be9361c 6583 mutex_lock(&sched_hotcpu_mutex);
5c45bf27
SS
6584 detach_destroy_domains(&cpu_online_map);
6585 err = arch_init_sched_domains(&cpu_online_map);
5be9361c 6586 mutex_unlock(&sched_hotcpu_mutex);
5c45bf27
SS
6587
6588 return err;
6589}
6590
6591static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6592{
6593 int ret;
6594
6595 if (buf[0] != '0' && buf[0] != '1')
6596 return -EINVAL;
6597
6598 if (smt)
6599 sched_smt_power_savings = (buf[0] == '1');
6600 else
6601 sched_mc_power_savings = (buf[0] == '1');
6602
6603 ret = arch_reinit_sched_domains();
6604
6605 return ret ? ret : count;
6606}
6607
5c45bf27
SS
6608#ifdef CONFIG_SCHED_MC
6609static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6610{
6611 return sprintf(page, "%u\n", sched_mc_power_savings);
6612}
48f24c4d
IM
6613static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6614 const char *buf, size_t count)
5c45bf27
SS
6615{
6616 return sched_power_savings_store(buf, count, 0);
6617}
6707de00
AB
6618static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6619 sched_mc_power_savings_store);
5c45bf27
SS
6620#endif
6621
6622#ifdef CONFIG_SCHED_SMT
6623static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6624{
6625 return sprintf(page, "%u\n", sched_smt_power_savings);
6626}
48f24c4d
IM
6627static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6628 const char *buf, size_t count)
5c45bf27
SS
6629{
6630 return sched_power_savings_store(buf, count, 1);
6631}
6707de00
AB
6632static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6633 sched_smt_power_savings_store);
6634#endif
6635
6636int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6637{
6638 int err = 0;
6639
6640#ifdef CONFIG_SCHED_SMT
6641 if (smt_capable())
6642 err = sysfs_create_file(&cls->kset.kobj,
6643 &attr_sched_smt_power_savings.attr);
6644#endif
6645#ifdef CONFIG_SCHED_MC
6646 if (!err && mc_capable())
6647 err = sysfs_create_file(&cls->kset.kobj,
6648 &attr_sched_mc_power_savings.attr);
6649#endif
6650 return err;
6651}
5c45bf27
SS
6652#endif
6653
1da177e4 6654/*
41a2d6cf 6655 * Force a reinitialization of the sched domains hierarchy. The domains
1da177e4 6656 * and groups cannot be updated in place without racing with the balancing
41c7ce9a 6657 * code, so we temporarily attach all running cpus to the NULL domain
1da177e4
LT
6658 * which will prevent rebalancing while the sched domains are recalculated.
6659 */
6660static int update_sched_domains(struct notifier_block *nfb,
6661 unsigned long action, void *hcpu)
6662{
1da177e4
LT
6663 switch (action) {
6664 case CPU_UP_PREPARE:
8bb78442 6665 case CPU_UP_PREPARE_FROZEN:
1da177e4 6666 case CPU_DOWN_PREPARE:
8bb78442 6667 case CPU_DOWN_PREPARE_FROZEN:
1a20ff27 6668 detach_destroy_domains(&cpu_online_map);
1da177e4
LT
6669 return NOTIFY_OK;
6670
6671 case CPU_UP_CANCELED:
8bb78442 6672 case CPU_UP_CANCELED_FROZEN:
1da177e4 6673 case CPU_DOWN_FAILED:
8bb78442 6674 case CPU_DOWN_FAILED_FROZEN:
1da177e4 6675 case CPU_ONLINE:
8bb78442 6676 case CPU_ONLINE_FROZEN:
1da177e4 6677 case CPU_DEAD:
8bb78442 6678 case CPU_DEAD_FROZEN:
1da177e4
LT
6679 /*
6680 * Fall through and re-initialise the domains.
6681 */
6682 break;
6683 default:
6684 return NOTIFY_DONE;
6685 }
6686
6687 /* The hotplug lock is already held by cpu_up/cpu_down */
1a20ff27 6688 arch_init_sched_domains(&cpu_online_map);
1da177e4
LT
6689
6690 return NOTIFY_OK;
6691}
1da177e4
LT
6692
6693void __init sched_init_smp(void)
6694{
5c1e1767
NP
6695 cpumask_t non_isolated_cpus;
6696
5be9361c 6697 mutex_lock(&sched_hotcpu_mutex);
1a20ff27 6698 arch_init_sched_domains(&cpu_online_map);
e5e5673f 6699 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
5c1e1767
NP
6700 if (cpus_empty(non_isolated_cpus))
6701 cpu_set(smp_processor_id(), non_isolated_cpus);
5be9361c 6702 mutex_unlock(&sched_hotcpu_mutex);
1da177e4
LT
6703 /* XXX: Theoretical race here - CPU may be hotplugged now */
6704 hotcpu_notifier(update_sched_domains, 0);
5c1e1767
NP
6705
6706 /* Move init over to a non-isolated CPU */
6707 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
6708 BUG();
19978ca6 6709 sched_init_granularity();
1da177e4
LT
6710}
6711#else
6712void __init sched_init_smp(void)
6713{
19978ca6 6714 sched_init_granularity();
1da177e4
LT
6715}
6716#endif /* CONFIG_SMP */
6717
6718int in_sched_functions(unsigned long addr)
6719{
1da177e4
LT
6720 return in_lock_functions(addr) ||
6721 (addr >= (unsigned long)__sched_text_start
6722 && addr < (unsigned long)__sched_text_end);
6723}
6724
a9957449 6725static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
dd41f596
IM
6726{
6727 cfs_rq->tasks_timeline = RB_ROOT;
dd41f596
IM
6728#ifdef CONFIG_FAIR_GROUP_SCHED
6729 cfs_rq->rq = rq;
6730#endif
67e9fb2a 6731 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
dd41f596
IM
6732}
6733
1da177e4
LT
6734void __init sched_init(void)
6735{
476f3534 6736 int highest_cpu = 0;
dd41f596
IM
6737 int i, j;
6738
0a945022 6739 for_each_possible_cpu(i) {
dd41f596 6740 struct rt_prio_array *array;
70b97a7f 6741 struct rq *rq;
1da177e4
LT
6742
6743 rq = cpu_rq(i);
6744 spin_lock_init(&rq->lock);
fcb99371 6745 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7897986b 6746 rq->nr_running = 0;
dd41f596
IM
6747 rq->clock = 1;
6748 init_cfs_rq(&rq->cfs, rq);
6749#ifdef CONFIG_FAIR_GROUP_SCHED
6750 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
3a252015
IM
6751 {
6752 struct cfs_rq *cfs_rq = &per_cpu(init_cfs_rq, i);
6753 struct sched_entity *se =
6754 &per_cpu(init_sched_entity, i);
6755
6756 init_cfs_rq_p[i] = cfs_rq;
6757 init_cfs_rq(cfs_rq, rq);
4cf86d77 6758 cfs_rq->tg = &init_task_group;
3a252015 6759 list_add(&cfs_rq->leaf_cfs_rq_list,
29f59db3
SV
6760 &rq->leaf_cfs_rq_list);
6761
3a252015
IM
6762 init_sched_entity_p[i] = se;
6763 se->cfs_rq = &rq->cfs;
6764 se->my_q = cfs_rq;
4cf86d77 6765 se->load.weight = init_task_group_load;
9b5b7751 6766 se->load.inv_weight =
4cf86d77 6767 div64_64(1ULL<<32, init_task_group_load);
3a252015
IM
6768 se->parent = NULL;
6769 }
4cf86d77 6770 init_task_group.shares = init_task_group_load;
5cb350ba 6771 spin_lock_init(&init_task_group.lock);
dd41f596 6772#endif
1da177e4 6773
dd41f596
IM
6774 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6775 rq->cpu_load[j] = 0;
1da177e4 6776#ifdef CONFIG_SMP
41c7ce9a 6777 rq->sd = NULL;
1da177e4 6778 rq->active_balance = 0;
dd41f596 6779 rq->next_balance = jiffies;
1da177e4 6780 rq->push_cpu = 0;
0a2966b4 6781 rq->cpu = i;
1da177e4
LT
6782 rq->migration_thread = NULL;
6783 INIT_LIST_HEAD(&rq->migration_queue);
6784#endif
6785 atomic_set(&rq->nr_iowait, 0);
6786
dd41f596
IM
6787 array = &rq->rt.active;
6788 for (j = 0; j < MAX_RT_PRIO; j++) {
6789 INIT_LIST_HEAD(array->queue + j);
6790 __clear_bit(j, array->bitmap);
1da177e4 6791 }
476f3534 6792 highest_cpu = i;
dd41f596
IM
6793 /* delimiter for bitsearch: */
6794 __set_bit(MAX_RT_PRIO, array->bitmap);
1da177e4
LT
6795 }
6796
2dd73a4f 6797 set_load_weight(&init_task);
b50f60ce 6798
e107be36
AK
6799#ifdef CONFIG_PREEMPT_NOTIFIERS
6800 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
6801#endif
6802
c9819f45 6803#ifdef CONFIG_SMP
476f3534 6804 nr_cpu_ids = highest_cpu + 1;
c9819f45
CL
6805 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
6806#endif
6807
b50f60ce
HC
6808#ifdef CONFIG_RT_MUTEXES
6809 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
6810#endif
6811
1da177e4
LT
6812 /*
6813 * The boot idle thread does lazy MMU switching as well:
6814 */
6815 atomic_inc(&init_mm.mm_count);
6816 enter_lazy_tlb(&init_mm, current);
6817
6818 /*
6819 * Make us the idle thread. Technically, schedule() should not be
6820 * called from this thread, however somewhere below it might be,
6821 * but because we are the idle thread, we just pick up running again
6822 * when this runqueue becomes "idle".
6823 */
6824 init_idle(current, smp_processor_id());
dd41f596
IM
6825 /*
6826 * During early bootup we pretend to be a normal task:
6827 */
6828 current->sched_class = &fair_sched_class;
1da177e4
LT
6829}
6830
6831#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6832void __might_sleep(char *file, int line)
6833{
48f24c4d 6834#ifdef in_atomic
1da177e4
LT
6835 static unsigned long prev_jiffy; /* ratelimiting */
6836
6837 if ((in_atomic() || irqs_disabled()) &&
6838 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6839 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6840 return;
6841 prev_jiffy = jiffies;
91368d73 6842 printk(KERN_ERR "BUG: sleeping function called from invalid"
1da177e4
LT
6843 " context at %s:%d\n", file, line);
6844 printk("in_atomic():%d, irqs_disabled():%d\n",
6845 in_atomic(), irqs_disabled());
a4c410f0 6846 debug_show_held_locks(current);
3117df04
IM
6847 if (irqs_disabled())
6848 print_irqtrace_events(current);
1da177e4
LT
6849 dump_stack();
6850 }
6851#endif
6852}
6853EXPORT_SYMBOL(__might_sleep);
6854#endif
6855
6856#ifdef CONFIG_MAGIC_SYSRQ
3a5e4dc1
AK
6857static void normalize_task(struct rq *rq, struct task_struct *p)
6858{
6859 int on_rq;
6860 update_rq_clock(rq);
6861 on_rq = p->se.on_rq;
6862 if (on_rq)
6863 deactivate_task(rq, p, 0);
6864 __setscheduler(rq, p, SCHED_NORMAL, 0);
6865 if (on_rq) {
6866 activate_task(rq, p, 0);
6867 resched_task(rq->curr);
6868 }
6869}
6870
1da177e4
LT
6871void normalize_rt_tasks(void)
6872{
a0f98a1c 6873 struct task_struct *g, *p;
1da177e4 6874 unsigned long flags;
70b97a7f 6875 struct rq *rq;
1da177e4
LT
6876
6877 read_lock_irq(&tasklist_lock);
a0f98a1c 6878 do_each_thread(g, p) {
178be793
IM
6879 /*
6880 * Only normalize user tasks:
6881 */
6882 if (!p->mm)
6883 continue;
6884
6cfb0d5d 6885 p->se.exec_start = 0;
6cfb0d5d 6886#ifdef CONFIG_SCHEDSTATS
dd41f596 6887 p->se.wait_start = 0;
dd41f596 6888 p->se.sleep_start = 0;
dd41f596 6889 p->se.block_start = 0;
6cfb0d5d 6890#endif
dd41f596
IM
6891 task_rq(p)->clock = 0;
6892
6893 if (!rt_task(p)) {
6894 /*
6895 * Renice negative nice level userspace
6896 * tasks back to 0:
6897 */
6898 if (TASK_NICE(p) < 0 && p->mm)
6899 set_user_nice(p, 0);
1da177e4 6900 continue;
dd41f596 6901 }
1da177e4 6902
b29739f9
IM
6903 spin_lock_irqsave(&p->pi_lock, flags);
6904 rq = __task_rq_lock(p);
1da177e4 6905
178be793 6906 normalize_task(rq, p);
3a5e4dc1 6907
b29739f9
IM
6908 __task_rq_unlock(rq);
6909 spin_unlock_irqrestore(&p->pi_lock, flags);
a0f98a1c
IM
6910 } while_each_thread(g, p);
6911
1da177e4
LT
6912 read_unlock_irq(&tasklist_lock);
6913}
6914
6915#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a
LT
6916
6917#ifdef CONFIG_IA64
6918/*
6919 * These functions are only useful for the IA64 MCA handling.
6920 *
6921 * They can only be called when the whole system has been
6922 * stopped - every CPU needs to be quiescent, and no scheduling
6923 * activity can take place. Using them for anything else would
6924 * be a serious bug, and as a result, they aren't even visible
6925 * under any other configuration.
6926 */
6927
6928/**
6929 * curr_task - return the current task for a given cpu.
6930 * @cpu: the processor in question.
6931 *
6932 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6933 */
36c8b586 6934struct task_struct *curr_task(int cpu)
1df5c10a
LT
6935{
6936 return cpu_curr(cpu);
6937}
6938
6939/**
6940 * set_curr_task - set the current task for a given cpu.
6941 * @cpu: the processor in question.
6942 * @p: the task pointer to set.
6943 *
6944 * Description: This function must only be used when non-maskable interrupts
41a2d6cf
IM
6945 * are serviced on a separate stack. It allows the architecture to switch the
6946 * notion of the current task on a cpu in a non-blocking manner. This function
1df5c10a
LT
6947 * must be called with all CPU's synchronized, and interrupts disabled, the
6948 * and caller must save the original value of the current task (see
6949 * curr_task() above) and restore that value before reenabling interrupts and
6950 * re-starting the system.
6951 *
6952 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6953 */
36c8b586 6954void set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
6955{
6956 cpu_curr(cpu) = p;
6957}
6958
6959#endif
29f59db3
SV
6960
6961#ifdef CONFIG_FAIR_GROUP_SCHED
6962
29f59db3 6963/* allocate runqueue etc for a new task group */
4cf86d77 6964struct task_group *sched_create_group(void)
29f59db3 6965{
4cf86d77 6966 struct task_group *tg;
29f59db3
SV
6967 struct cfs_rq *cfs_rq;
6968 struct sched_entity *se;
9b5b7751 6969 struct rq *rq;
29f59db3
SV
6970 int i;
6971
29f59db3
SV
6972 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
6973 if (!tg)
6974 return ERR_PTR(-ENOMEM);
6975
9b5b7751 6976 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
29f59db3
SV
6977 if (!tg->cfs_rq)
6978 goto err;
9b5b7751 6979 tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
29f59db3
SV
6980 if (!tg->se)
6981 goto err;
6982
6983 for_each_possible_cpu(i) {
9b5b7751 6984 rq = cpu_rq(i);
29f59db3
SV
6985
6986 cfs_rq = kmalloc_node(sizeof(struct cfs_rq), GFP_KERNEL,
6987 cpu_to_node(i));
6988 if (!cfs_rq)
6989 goto err;
6990
6991 se = kmalloc_node(sizeof(struct sched_entity), GFP_KERNEL,
6992 cpu_to_node(i));
6993 if (!se)
6994 goto err;
6995
6996 memset(cfs_rq, 0, sizeof(struct cfs_rq));
6997 memset(se, 0, sizeof(struct sched_entity));
6998
6999 tg->cfs_rq[i] = cfs_rq;
7000 init_cfs_rq(cfs_rq, rq);
7001 cfs_rq->tg = tg;
29f59db3
SV
7002
7003 tg->se[i] = se;
7004 se->cfs_rq = &rq->cfs;
7005 se->my_q = cfs_rq;
7006 se->load.weight = NICE_0_LOAD;
7007 se->load.inv_weight = div64_64(1ULL<<32, NICE_0_LOAD);
7008 se->parent = NULL;
7009 }
7010
9b5b7751
SV
7011 for_each_possible_cpu(i) {
7012 rq = cpu_rq(i);
7013 cfs_rq = tg->cfs_rq[i];
7014 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7015 }
29f59db3 7016
9b5b7751 7017 tg->shares = NICE_0_LOAD;
5cb350ba 7018 spin_lock_init(&tg->lock);
29f59db3 7019
9b5b7751 7020 return tg;
29f59db3
SV
7021
7022err:
7023 for_each_possible_cpu(i) {
a65914b3 7024 if (tg->cfs_rq)
29f59db3 7025 kfree(tg->cfs_rq[i]);
a65914b3 7026 if (tg->se)
29f59db3
SV
7027 kfree(tg->se[i]);
7028 }
a65914b3
IM
7029 kfree(tg->cfs_rq);
7030 kfree(tg->se);
7031 kfree(tg);
29f59db3
SV
7032
7033 return ERR_PTR(-ENOMEM);
7034}
7035
9b5b7751
SV
7036/* rcu callback to free various structures associated with a task group */
7037static void free_sched_group(struct rcu_head *rhp)
29f59db3 7038{
ae8393e5
SV
7039 struct task_group *tg = container_of(rhp, struct task_group, rcu);
7040 struct cfs_rq *cfs_rq;
29f59db3
SV
7041 struct sched_entity *se;
7042 int i;
7043
29f59db3
SV
7044 /* now it should be safe to free those cfs_rqs */
7045 for_each_possible_cpu(i) {
7046 cfs_rq = tg->cfs_rq[i];
7047 kfree(cfs_rq);
7048
7049 se = tg->se[i];
7050 kfree(se);
7051 }
7052
7053 kfree(tg->cfs_rq);
7054 kfree(tg->se);
7055 kfree(tg);
7056}
7057
9b5b7751 7058/* Destroy runqueue etc associated with a task group */
4cf86d77 7059void sched_destroy_group(struct task_group *tg)
29f59db3 7060{
7bae49d4 7061 struct cfs_rq *cfs_rq = NULL;
9b5b7751 7062 int i;
29f59db3 7063
9b5b7751
SV
7064 for_each_possible_cpu(i) {
7065 cfs_rq = tg->cfs_rq[i];
7066 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
7067 }
7068
7bae49d4 7069 BUG_ON(!cfs_rq);
9b5b7751
SV
7070
7071 /* wait for possible concurrent references to cfs_rqs complete */
ae8393e5 7072 call_rcu(&tg->rcu, free_sched_group);
29f59db3
SV
7073}
7074
9b5b7751 7075/* change task's runqueue when it moves between groups.
3a252015
IM
7076 * The caller of this function should have put the task in its new group
7077 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7078 * reflect its new group.
9b5b7751
SV
7079 */
7080void sched_move_task(struct task_struct *tsk)
29f59db3
SV
7081{
7082 int on_rq, running;
7083 unsigned long flags;
7084 struct rq *rq;
7085
7086 rq = task_rq_lock(tsk, &flags);
7087
dae51f56 7088 if (tsk->sched_class != &fair_sched_class) {
ce96b5ac 7089 set_task_cfs_rq(tsk, task_cpu(tsk));
29f59db3 7090 goto done;
dae51f56 7091 }
29f59db3
SV
7092
7093 update_rq_clock(rq);
7094
051a1d1a 7095 running = task_current(rq, tsk);
29f59db3
SV
7096 on_rq = tsk->se.on_rq;
7097
83b699ed 7098 if (on_rq) {
29f59db3 7099 dequeue_task(rq, tsk, 0);
83b699ed
SV
7100 if (unlikely(running))
7101 tsk->sched_class->put_prev_task(rq, tsk);
7102 }
29f59db3 7103
ce96b5ac 7104 set_task_cfs_rq(tsk, task_cpu(tsk));
29f59db3 7105
83b699ed
SV
7106 if (on_rq) {
7107 if (unlikely(running))
7108 tsk->sched_class->set_curr_task(rq);
7074badb 7109 enqueue_task(rq, tsk, 0);
83b699ed 7110 }
29f59db3
SV
7111
7112done:
7113 task_rq_unlock(rq, &flags);
7114}
7115
7116static void set_se_shares(struct sched_entity *se, unsigned long shares)
7117{
7118 struct cfs_rq *cfs_rq = se->cfs_rq;
7119 struct rq *rq = cfs_rq->rq;
7120 int on_rq;
7121
7122 spin_lock_irq(&rq->lock);
7123
7124 on_rq = se->on_rq;
7125 if (on_rq)
7126 dequeue_entity(cfs_rq, se, 0);
7127
7128 se->load.weight = shares;
7129 se->load.inv_weight = div64_64((1ULL<<32), shares);
7130
7131 if (on_rq)
7132 enqueue_entity(cfs_rq, se, 0);
7133
7134 spin_unlock_irq(&rq->lock);
7135}
7136
4cf86d77 7137int sched_group_set_shares(struct task_group *tg, unsigned long shares)
29f59db3
SV
7138{
7139 int i;
29f59db3 7140
c61935fd
IM
7141 /*
7142 * A weight of 0 or 1 can cause arithmetics problems.
7143 * (The default weight is 1024 - so there's no practical
7144 * limitation from this.)
7145 */
7146 if (shares < 2)
7147 shares = 2;
7148
5cb350ba 7149 spin_lock(&tg->lock);
9b5b7751 7150 if (tg->shares == shares)
5cb350ba 7151 goto done;
29f59db3 7152
9b5b7751 7153 tg->shares = shares;
29f59db3 7154 for_each_possible_cpu(i)
9b5b7751 7155 set_se_shares(tg->se[i], shares);
29f59db3 7156
5cb350ba
DG
7157done:
7158 spin_unlock(&tg->lock);
9b5b7751 7159 return 0;
29f59db3
SV
7160}
7161
5cb350ba
DG
7162unsigned long sched_group_shares(struct task_group *tg)
7163{
7164 return tg->shares;
7165}
7166
3a252015 7167#endif /* CONFIG_FAIR_GROUP_SCHED */
68318b8e
SV
7168
7169#ifdef CONFIG_FAIR_CGROUP_SCHED
7170
7171/* return corresponding task_group object of a cgroup */
2b01dfe3 7172static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
68318b8e 7173{
2b01dfe3
PM
7174 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7175 struct task_group, css);
68318b8e
SV
7176}
7177
7178static struct cgroup_subsys_state *
2b01dfe3 7179cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
68318b8e
SV
7180{
7181 struct task_group *tg;
7182
2b01dfe3 7183 if (!cgrp->parent) {
68318b8e 7184 /* This is early initialization for the top cgroup */
2b01dfe3 7185 init_task_group.css.cgroup = cgrp;
68318b8e
SV
7186 return &init_task_group.css;
7187 }
7188
7189 /* we support only 1-level deep hierarchical scheduler atm */
2b01dfe3 7190 if (cgrp->parent->parent)
68318b8e
SV
7191 return ERR_PTR(-EINVAL);
7192
7193 tg = sched_create_group();
7194 if (IS_ERR(tg))
7195 return ERR_PTR(-ENOMEM);
7196
7197 /* Bind the cgroup to task_group object we just created */
2b01dfe3 7198 tg->css.cgroup = cgrp;
68318b8e
SV
7199
7200 return &tg->css;
7201}
7202
41a2d6cf
IM
7203static void
7204cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
68318b8e 7205{
2b01dfe3 7206 struct task_group *tg = cgroup_tg(cgrp);
68318b8e
SV
7207
7208 sched_destroy_group(tg);
7209}
7210
41a2d6cf
IM
7211static int
7212cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7213 struct task_struct *tsk)
68318b8e
SV
7214{
7215 /* We don't support RT-tasks being in separate groups */
7216 if (tsk->sched_class != &fair_sched_class)
7217 return -EINVAL;
7218
7219 return 0;
7220}
7221
7222static void
2b01dfe3 7223cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
68318b8e
SV
7224 struct cgroup *old_cont, struct task_struct *tsk)
7225{
7226 sched_move_task(tsk);
7227}
7228
2b01dfe3
PM
7229static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
7230 u64 shareval)
68318b8e 7231{
2b01dfe3 7232 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
68318b8e
SV
7233}
7234
2b01dfe3 7235static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
68318b8e 7236{
2b01dfe3 7237 struct task_group *tg = cgroup_tg(cgrp);
68318b8e
SV
7238
7239 return (u64) tg->shares;
7240}
7241
fe5c7cc2
PM
7242static struct cftype cpu_files[] = {
7243 {
7244 .name = "shares",
7245 .read_uint = cpu_shares_read_uint,
7246 .write_uint = cpu_shares_write_uint,
7247 },
68318b8e
SV
7248};
7249
7250static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
7251{
fe5c7cc2 7252 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
68318b8e
SV
7253}
7254
7255struct cgroup_subsys cpu_cgroup_subsys = {
38605cae
IM
7256 .name = "cpu",
7257 .create = cpu_cgroup_create,
7258 .destroy = cpu_cgroup_destroy,
7259 .can_attach = cpu_cgroup_can_attach,
7260 .attach = cpu_cgroup_attach,
7261 .populate = cpu_cgroup_populate,
7262 .subsys_id = cpu_cgroup_subsys_id,
68318b8e
SV
7263 .early_init = 1,
7264};
7265
7266#endif /* CONFIG_FAIR_CGROUP_SCHED */
d842de87
SV
7267
7268#ifdef CONFIG_CGROUP_CPUACCT
7269
7270/*
7271 * CPU accounting code for task groups.
7272 *
7273 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
7274 * (balbir@in.ibm.com).
7275 */
7276
7277/* track cpu usage of a group of tasks */
7278struct cpuacct {
7279 struct cgroup_subsys_state css;
7280 /* cpuusage holds pointer to a u64-type object on every cpu */
7281 u64 *cpuusage;
7282};
7283
7284struct cgroup_subsys cpuacct_subsys;
7285
7286/* return cpu accounting group corresponding to this container */
7287static inline struct cpuacct *cgroup_ca(struct cgroup *cont)
7288{
7289 return container_of(cgroup_subsys_state(cont, cpuacct_subsys_id),
7290 struct cpuacct, css);
7291}
7292
7293/* return cpu accounting group to which this task belongs */
7294static inline struct cpuacct *task_ca(struct task_struct *tsk)
7295{
7296 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
7297 struct cpuacct, css);
7298}
7299
7300/* create a new cpu accounting group */
7301static struct cgroup_subsys_state *cpuacct_create(
7302 struct cgroup_subsys *ss, struct cgroup *cont)
7303{
7304 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
7305
7306 if (!ca)
7307 return ERR_PTR(-ENOMEM);
7308
7309 ca->cpuusage = alloc_percpu(u64);
7310 if (!ca->cpuusage) {
7311 kfree(ca);
7312 return ERR_PTR(-ENOMEM);
7313 }
7314
7315 return &ca->css;
7316}
7317
7318/* destroy an existing cpu accounting group */
41a2d6cf
IM
7319static void
7320cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
d842de87
SV
7321{
7322 struct cpuacct *ca = cgroup_ca(cont);
7323
7324 free_percpu(ca->cpuusage);
7325 kfree(ca);
7326}
7327
7328/* return total cpu usage (in nanoseconds) of a group */
7329static u64 cpuusage_read(struct cgroup *cont, struct cftype *cft)
7330{
7331 struct cpuacct *ca = cgroup_ca(cont);
7332 u64 totalcpuusage = 0;
7333 int i;
7334
7335 for_each_possible_cpu(i) {
7336 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
7337
7338 /*
7339 * Take rq->lock to make 64-bit addition safe on 32-bit
7340 * platforms.
7341 */
7342 spin_lock_irq(&cpu_rq(i)->lock);
7343 totalcpuusage += *cpuusage;
7344 spin_unlock_irq(&cpu_rq(i)->lock);
7345 }
7346
7347 return totalcpuusage;
7348}
7349
7350static struct cftype files[] = {
7351 {
7352 .name = "usage",
7353 .read_uint = cpuusage_read,
7354 },
7355};
7356
7357static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cont)
7358{
7359 return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
7360}
7361
7362/*
7363 * charge this task's execution time to its accounting group.
7364 *
7365 * called with rq->lock held.
7366 */
7367static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
7368{
7369 struct cpuacct *ca;
7370
7371 if (!cpuacct_subsys.active)
7372 return;
7373
7374 ca = task_ca(tsk);
7375 if (ca) {
7376 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
7377
7378 *cpuusage += cputime;
7379 }
7380}
7381
7382struct cgroup_subsys cpuacct_subsys = {
7383 .name = "cpuacct",
7384 .create = cpuacct_create,
7385 .destroy = cpuacct_destroy,
7386 .populate = cpuacct_populate,
7387 .subsys_id = cpuacct_subsys_id,
7388};
7389#endif /* CONFIG_CGROUP_CPUACCT */
This page took 0.944543 seconds and 5 git commands to generate.