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