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