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