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