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