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