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