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