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