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