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