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