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