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