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