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