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