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