rcu: Fix full dynticks' dependency on wide RCU nocb mode
[linux-2.6-block.git] / kernel / sched / core.c
CommitLineData
1da177e4 1/*
391e43da 2 * kernel/sched/core.c
1da177e4
LT
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>
e692ab53 59#include <linux/sysctl.h>
1da177e4
LT
60#include <linux/syscalls.h>
61#include <linux/times.h>
8f0ab514 62#include <linux/tsacct_kern.h>
c6fd91f0 63#include <linux/kprobes.h>
0ff92245 64#include <linux/delayacct.h>
dff06c15 65#include <linux/unistd.h>
f5ff8422 66#include <linux/pagemap.h>
8f4d37ec 67#include <linux/hrtimer.h>
30914a58 68#include <linux/tick.h>
f00b45c1
PZ
69#include <linux/debugfs.h>
70#include <linux/ctype.h>
6cd8a4bb 71#include <linux/ftrace.h>
5a0e3ad6 72#include <linux/slab.h>
f1c6f1a7 73#include <linux/init_task.h>
40401530 74#include <linux/binfmts.h>
91d1aa43 75#include <linux/context_tracking.h>
1da177e4 76
96f951ed 77#include <asm/switch_to.h>
5517d86b 78#include <asm/tlb.h>
838225b4 79#include <asm/irq_regs.h>
db7e527d 80#include <asm/mutex.h>
e6e6685a
GC
81#ifdef CONFIG_PARAVIRT
82#include <asm/paravirt.h>
83#endif
1da177e4 84
029632fb 85#include "sched.h"
ea138446 86#include "../workqueue_internal.h"
29d5e047 87#include "../smpboot.h"
6e0534f2 88
a8d154b0 89#define CREATE_TRACE_POINTS
ad8d75ff 90#include <trace/events/sched.h>
a8d154b0 91
029632fb 92void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
d0b27fa7 93{
58088ad0
PT
94 unsigned long delta;
95 ktime_t soft, hard, now;
d0b27fa7 96
58088ad0
PT
97 for (;;) {
98 if (hrtimer_active(period_timer))
99 break;
100
101 now = hrtimer_cb_get_time(period_timer);
102 hrtimer_forward(period_timer, now, period);
d0b27fa7 103
58088ad0
PT
104 soft = hrtimer_get_softexpires(period_timer);
105 hard = hrtimer_get_expires(period_timer);
106 delta = ktime_to_ns(ktime_sub(hard, soft));
107 __hrtimer_start_range_ns(period_timer, soft, delta,
108 HRTIMER_MODE_ABS_PINNED, 0);
109 }
110}
111
029632fb
PZ
112DEFINE_MUTEX(sched_domains_mutex);
113DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
dc61b1d6 114
fe44d621 115static void update_rq_clock_task(struct rq *rq, s64 delta);
305e6835 116
029632fb 117void update_rq_clock(struct rq *rq)
3e51f33f 118{
fe44d621 119 s64 delta;
305e6835 120
61eadef6 121 if (rq->skip_clock_update > 0)
f26f9aff 122 return;
aa483808 123
fe44d621
PZ
124 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
125 rq->clock += delta;
126 update_rq_clock_task(rq, delta);
3e51f33f
PZ
127}
128
bf5c91ba
IM
129/*
130 * Debugging: various feature bits
131 */
f00b45c1 132
f00b45c1
PZ
133#define SCHED_FEAT(name, enabled) \
134 (1UL << __SCHED_FEAT_##name) * enabled |
135
bf5c91ba 136const_debug unsigned int sysctl_sched_features =
391e43da 137#include "features.h"
f00b45c1
PZ
138 0;
139
140#undef SCHED_FEAT
141
142#ifdef CONFIG_SCHED_DEBUG
143#define SCHED_FEAT(name, enabled) \
144 #name ,
145
1292531f 146static const char * const sched_feat_names[] = {
391e43da 147#include "features.h"
f00b45c1
PZ
148};
149
150#undef SCHED_FEAT
151
34f3a814 152static int sched_feat_show(struct seq_file *m, void *v)
f00b45c1 153{
f00b45c1
PZ
154 int i;
155
f8b6d1cc 156 for (i = 0; i < __SCHED_FEAT_NR; i++) {
34f3a814
LZ
157 if (!(sysctl_sched_features & (1UL << i)))
158 seq_puts(m, "NO_");
159 seq_printf(m, "%s ", sched_feat_names[i]);
f00b45c1 160 }
34f3a814 161 seq_puts(m, "\n");
f00b45c1 162
34f3a814 163 return 0;
f00b45c1
PZ
164}
165
f8b6d1cc
PZ
166#ifdef HAVE_JUMP_LABEL
167
c5905afb
IM
168#define jump_label_key__true STATIC_KEY_INIT_TRUE
169#define jump_label_key__false STATIC_KEY_INIT_FALSE
f8b6d1cc
PZ
170
171#define SCHED_FEAT(name, enabled) \
172 jump_label_key__##enabled ,
173
c5905afb 174struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
f8b6d1cc
PZ
175#include "features.h"
176};
177
178#undef SCHED_FEAT
179
180static void sched_feat_disable(int i)
181{
c5905afb
IM
182 if (static_key_enabled(&sched_feat_keys[i]))
183 static_key_slow_dec(&sched_feat_keys[i]);
f8b6d1cc
PZ
184}
185
186static void sched_feat_enable(int i)
187{
c5905afb
IM
188 if (!static_key_enabled(&sched_feat_keys[i]))
189 static_key_slow_inc(&sched_feat_keys[i]);
f8b6d1cc
PZ
190}
191#else
192static void sched_feat_disable(int i) { };
193static void sched_feat_enable(int i) { };
194#endif /* HAVE_JUMP_LABEL */
195
1a687c2e 196static int sched_feat_set(char *cmp)
f00b45c1 197{
f00b45c1 198 int i;
1a687c2e 199 int neg = 0;
f00b45c1 200
524429c3 201 if (strncmp(cmp, "NO_", 3) == 0) {
f00b45c1
PZ
202 neg = 1;
203 cmp += 3;
204 }
205
f8b6d1cc 206 for (i = 0; i < __SCHED_FEAT_NR; i++) {
7740191c 207 if (strcmp(cmp, sched_feat_names[i]) == 0) {
f8b6d1cc 208 if (neg) {
f00b45c1 209 sysctl_sched_features &= ~(1UL << i);
f8b6d1cc
PZ
210 sched_feat_disable(i);
211 } else {
f00b45c1 212 sysctl_sched_features |= (1UL << i);
f8b6d1cc
PZ
213 sched_feat_enable(i);
214 }
f00b45c1
PZ
215 break;
216 }
217 }
218
1a687c2e
MG
219 return i;
220}
221
222static ssize_t
223sched_feat_write(struct file *filp, const char __user *ubuf,
224 size_t cnt, loff_t *ppos)
225{
226 char buf[64];
227 char *cmp;
228 int i;
229
230 if (cnt > 63)
231 cnt = 63;
232
233 if (copy_from_user(&buf, ubuf, cnt))
234 return -EFAULT;
235
236 buf[cnt] = 0;
237 cmp = strstrip(buf);
238
239 i = sched_feat_set(cmp);
f8b6d1cc 240 if (i == __SCHED_FEAT_NR)
f00b45c1
PZ
241 return -EINVAL;
242
42994724 243 *ppos += cnt;
f00b45c1
PZ
244
245 return cnt;
246}
247
34f3a814
LZ
248static int sched_feat_open(struct inode *inode, struct file *filp)
249{
250 return single_open(filp, sched_feat_show, NULL);
251}
252
828c0950 253static const struct file_operations sched_feat_fops = {
34f3a814
LZ
254 .open = sched_feat_open,
255 .write = sched_feat_write,
256 .read = seq_read,
257 .llseek = seq_lseek,
258 .release = single_release,
f00b45c1
PZ
259};
260
261static __init int sched_init_debug(void)
262{
f00b45c1
PZ
263 debugfs_create_file("sched_features", 0644, NULL, NULL,
264 &sched_feat_fops);
265
266 return 0;
267}
268late_initcall(sched_init_debug);
f8b6d1cc 269#endif /* CONFIG_SCHED_DEBUG */
bf5c91ba 270
b82d9fdd
PZ
271/*
272 * Number of tasks to iterate in a single balance run.
273 * Limited because this is done with IRQs disabled.
274 */
275const_debug unsigned int sysctl_sched_nr_migrate = 32;
276
e9e9250b
PZ
277/*
278 * period over which we average the RT time consumption, measured
279 * in ms.
280 *
281 * default: 1s
282 */
283const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
284
fa85ae24 285/*
9f0c1e56 286 * period over which we measure -rt task cpu usage in us.
fa85ae24
PZ
287 * default: 1s
288 */
9f0c1e56 289unsigned int sysctl_sched_rt_period = 1000000;
fa85ae24 290
029632fb 291__read_mostly int scheduler_running;
6892b75e 292
9f0c1e56
PZ
293/*
294 * part of the period that we allow rt tasks to run in us.
295 * default: 0.95s
296 */
297int sysctl_sched_rt_runtime = 950000;
fa85ae24 298
fa85ae24 299
1da177e4 300
0970d299 301/*
0122ec5b 302 * __task_rq_lock - lock the rq @p resides on.
b29739f9 303 */
70b97a7f 304static inline struct rq *__task_rq_lock(struct task_struct *p)
b29739f9
IM
305 __acquires(rq->lock)
306{
0970d299
PZ
307 struct rq *rq;
308
0122ec5b
PZ
309 lockdep_assert_held(&p->pi_lock);
310
3a5c359a 311 for (;;) {
0970d299 312 rq = task_rq(p);
05fa785c 313 raw_spin_lock(&rq->lock);
65cc8e48 314 if (likely(rq == task_rq(p)))
3a5c359a 315 return rq;
05fa785c 316 raw_spin_unlock(&rq->lock);
b29739f9 317 }
b29739f9
IM
318}
319
1da177e4 320/*
0122ec5b 321 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
1da177e4 322 */
70b97a7f 323static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
0122ec5b 324 __acquires(p->pi_lock)
1da177e4
LT
325 __acquires(rq->lock)
326{
70b97a7f 327 struct rq *rq;
1da177e4 328
3a5c359a 329 for (;;) {
0122ec5b 330 raw_spin_lock_irqsave(&p->pi_lock, *flags);
3a5c359a 331 rq = task_rq(p);
05fa785c 332 raw_spin_lock(&rq->lock);
65cc8e48 333 if (likely(rq == task_rq(p)))
3a5c359a 334 return rq;
0122ec5b
PZ
335 raw_spin_unlock(&rq->lock);
336 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
1da177e4 337 }
1da177e4
LT
338}
339
a9957449 340static void __task_rq_unlock(struct rq *rq)
b29739f9
IM
341 __releases(rq->lock)
342{
05fa785c 343 raw_spin_unlock(&rq->lock);
b29739f9
IM
344}
345
0122ec5b
PZ
346static inline void
347task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
1da177e4 348 __releases(rq->lock)
0122ec5b 349 __releases(p->pi_lock)
1da177e4 350{
0122ec5b
PZ
351 raw_spin_unlock(&rq->lock);
352 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
1da177e4
LT
353}
354
1da177e4 355/*
cc2a73b5 356 * this_rq_lock - lock this runqueue and disable interrupts.
1da177e4 357 */
a9957449 358static struct rq *this_rq_lock(void)
1da177e4
LT
359 __acquires(rq->lock)
360{
70b97a7f 361 struct rq *rq;
1da177e4
LT
362
363 local_irq_disable();
364 rq = this_rq();
05fa785c 365 raw_spin_lock(&rq->lock);
1da177e4
LT
366
367 return rq;
368}
369
8f4d37ec
PZ
370#ifdef CONFIG_SCHED_HRTICK
371/*
372 * Use HR-timers to deliver accurate preemption points.
373 *
374 * Its all a bit involved since we cannot program an hrt while holding the
375 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
376 * reschedule event.
377 *
378 * When we get rescheduled we reprogram the hrtick_timer outside of the
379 * rq->lock.
380 */
8f4d37ec 381
8f4d37ec
PZ
382static void hrtick_clear(struct rq *rq)
383{
384 if (hrtimer_active(&rq->hrtick_timer))
385 hrtimer_cancel(&rq->hrtick_timer);
386}
387
8f4d37ec
PZ
388/*
389 * High-resolution timer tick.
390 * Runs from hardirq context with interrupts disabled.
391 */
392static enum hrtimer_restart hrtick(struct hrtimer *timer)
393{
394 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
395
396 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
397
05fa785c 398 raw_spin_lock(&rq->lock);
3e51f33f 399 update_rq_clock(rq);
8f4d37ec 400 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
05fa785c 401 raw_spin_unlock(&rq->lock);
8f4d37ec
PZ
402
403 return HRTIMER_NORESTART;
404}
405
95e904c7 406#ifdef CONFIG_SMP
31656519
PZ
407/*
408 * called from hardirq (IPI) context
409 */
410static void __hrtick_start(void *arg)
b328ca18 411{
31656519 412 struct rq *rq = arg;
b328ca18 413
05fa785c 414 raw_spin_lock(&rq->lock);
31656519
PZ
415 hrtimer_restart(&rq->hrtick_timer);
416 rq->hrtick_csd_pending = 0;
05fa785c 417 raw_spin_unlock(&rq->lock);
b328ca18
PZ
418}
419
31656519
PZ
420/*
421 * Called to set the hrtick timer state.
422 *
423 * called with rq->lock held and irqs disabled
424 */
029632fb 425void hrtick_start(struct rq *rq, u64 delay)
b328ca18 426{
31656519
PZ
427 struct hrtimer *timer = &rq->hrtick_timer;
428 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
b328ca18 429
cc584b21 430 hrtimer_set_expires(timer, time);
31656519
PZ
431
432 if (rq == this_rq()) {
433 hrtimer_restart(timer);
434 } else if (!rq->hrtick_csd_pending) {
6e275637 435 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
31656519
PZ
436 rq->hrtick_csd_pending = 1;
437 }
b328ca18
PZ
438}
439
440static int
441hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
442{
443 int cpu = (int)(long)hcpu;
444
445 switch (action) {
446 case CPU_UP_CANCELED:
447 case CPU_UP_CANCELED_FROZEN:
448 case CPU_DOWN_PREPARE:
449 case CPU_DOWN_PREPARE_FROZEN:
450 case CPU_DEAD:
451 case CPU_DEAD_FROZEN:
31656519 452 hrtick_clear(cpu_rq(cpu));
b328ca18
PZ
453 return NOTIFY_OK;
454 }
455
456 return NOTIFY_DONE;
457}
458
fa748203 459static __init void init_hrtick(void)
b328ca18
PZ
460{
461 hotcpu_notifier(hotplug_hrtick, 0);
462}
31656519
PZ
463#else
464/*
465 * Called to set the hrtick timer state.
466 *
467 * called with rq->lock held and irqs disabled
468 */
029632fb 469void hrtick_start(struct rq *rq, u64 delay)
31656519 470{
7f1e2ca9 471 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
5c333864 472 HRTIMER_MODE_REL_PINNED, 0);
31656519 473}
b328ca18 474
006c75f1 475static inline void init_hrtick(void)
8f4d37ec 476{
8f4d37ec 477}
31656519 478#endif /* CONFIG_SMP */
8f4d37ec 479
31656519 480static void init_rq_hrtick(struct rq *rq)
8f4d37ec 481{
31656519
PZ
482#ifdef CONFIG_SMP
483 rq->hrtick_csd_pending = 0;
8f4d37ec 484
31656519
PZ
485 rq->hrtick_csd.flags = 0;
486 rq->hrtick_csd.func = __hrtick_start;
487 rq->hrtick_csd.info = rq;
488#endif
8f4d37ec 489
31656519
PZ
490 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
491 rq->hrtick_timer.function = hrtick;
8f4d37ec 492}
006c75f1 493#else /* CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
494static inline void hrtick_clear(struct rq *rq)
495{
496}
497
8f4d37ec
PZ
498static inline void init_rq_hrtick(struct rq *rq)
499{
500}
501
b328ca18
PZ
502static inline void init_hrtick(void)
503{
504}
006c75f1 505#endif /* CONFIG_SCHED_HRTICK */
8f4d37ec 506
c24d20db
IM
507/*
508 * resched_task - mark a task 'to be rescheduled now'.
509 *
510 * On UP this means the setting of the need_resched flag, on SMP it
511 * might also involve a cross-CPU call to trigger the scheduler on
512 * the target CPU.
513 */
514#ifdef CONFIG_SMP
029632fb 515void resched_task(struct task_struct *p)
c24d20db
IM
516{
517 int cpu;
518
05fa785c 519 assert_raw_spin_locked(&task_rq(p)->lock);
c24d20db 520
5ed0cec0 521 if (test_tsk_need_resched(p))
c24d20db
IM
522 return;
523
5ed0cec0 524 set_tsk_need_resched(p);
c24d20db
IM
525
526 cpu = task_cpu(p);
527 if (cpu == smp_processor_id())
528 return;
529
530 /* NEED_RESCHED must be visible before we test polling */
531 smp_mb();
532 if (!tsk_is_polling(p))
533 smp_send_reschedule(cpu);
534}
535
029632fb 536void resched_cpu(int cpu)
c24d20db
IM
537{
538 struct rq *rq = cpu_rq(cpu);
539 unsigned long flags;
540
05fa785c 541 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
c24d20db
IM
542 return;
543 resched_task(cpu_curr(cpu));
05fa785c 544 raw_spin_unlock_irqrestore(&rq->lock, flags);
c24d20db 545}
06d8308c 546
3451d024 547#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2
VP
548/*
549 * In the semi idle case, use the nearest busy cpu for migrating timers
550 * from an idle cpu. This is good for power-savings.
551 *
552 * We don't do similar optimization for completely idle system, as
553 * selecting an idle cpu will add more delays to the timers than intended
554 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
555 */
556int get_nohz_timer_target(void)
557{
558 int cpu = smp_processor_id();
559 int i;
560 struct sched_domain *sd;
561
057f3fad 562 rcu_read_lock();
83cd4fe2 563 for_each_domain(cpu, sd) {
057f3fad
PZ
564 for_each_cpu(i, sched_domain_span(sd)) {
565 if (!idle_cpu(i)) {
566 cpu = i;
567 goto unlock;
568 }
569 }
83cd4fe2 570 }
057f3fad
PZ
571unlock:
572 rcu_read_unlock();
83cd4fe2
VP
573 return cpu;
574}
06d8308c
TG
575/*
576 * When add_timer_on() enqueues a timer into the timer wheel of an
577 * idle CPU then this timer might expire before the next timer event
578 * which is scheduled to wake up that CPU. In case of a completely
579 * idle system the next event might even be infinite time into the
580 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
581 * leaves the inner idle loop so the newly added timer is taken into
582 * account when the CPU goes back to idle and evaluates the timer
583 * wheel for the next timer event.
584 */
1c20091e 585static void wake_up_idle_cpu(int cpu)
06d8308c
TG
586{
587 struct rq *rq = cpu_rq(cpu);
588
589 if (cpu == smp_processor_id())
590 return;
591
592 /*
593 * This is safe, as this function is called with the timer
594 * wheel base lock of (cpu) held. When the CPU is on the way
595 * to idle and has not yet set rq->curr to idle then it will
596 * be serialized on the timer wheel base lock and take the new
597 * timer into account automatically.
598 */
599 if (rq->curr != rq->idle)
600 return;
45bf76df 601
45bf76df 602 /*
06d8308c
TG
603 * We can set TIF_RESCHED on the idle task of the other CPU
604 * lockless. The worst case is that the other CPU runs the
605 * idle task through an additional NOOP schedule()
45bf76df 606 */
5ed0cec0 607 set_tsk_need_resched(rq->idle);
45bf76df 608
06d8308c
TG
609 /* NEED_RESCHED must be visible before we test polling */
610 smp_mb();
611 if (!tsk_is_polling(rq->idle))
612 smp_send_reschedule(cpu);
45bf76df
IM
613}
614
c5bfece2 615static bool wake_up_full_nohz_cpu(int cpu)
1c20091e 616{
c5bfece2 617 if (tick_nohz_full_cpu(cpu)) {
1c20091e
FW
618 if (cpu != smp_processor_id() ||
619 tick_nohz_tick_stopped())
620 smp_send_reschedule(cpu);
621 return true;
622 }
623
624 return false;
625}
626
627void wake_up_nohz_cpu(int cpu)
628{
c5bfece2 629 if (!wake_up_full_nohz_cpu(cpu))
1c20091e
FW
630 wake_up_idle_cpu(cpu);
631}
632
ca38062e 633static inline bool got_nohz_idle_kick(void)
45bf76df 634{
1c792db7
SS
635 int cpu = smp_processor_id();
636 return idle_cpu(cpu) && test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
45bf76df
IM
637}
638
3451d024 639#else /* CONFIG_NO_HZ_COMMON */
45bf76df 640
ca38062e 641static inline bool got_nohz_idle_kick(void)
2069dd75 642{
ca38062e 643 return false;
2069dd75
PZ
644}
645
3451d024 646#endif /* CONFIG_NO_HZ_COMMON */
d842de87 647
ce831b38
FW
648#ifdef CONFIG_NO_HZ_FULL
649bool sched_can_stop_tick(void)
650{
651 struct rq *rq;
652
653 rq = this_rq();
654
655 /* Make sure rq->nr_running update is visible after the IPI */
656 smp_rmb();
657
658 /* More than one running task need preemption */
659 if (rq->nr_running > 1)
660 return false;
661
662 return true;
663}
664#endif /* CONFIG_NO_HZ_FULL */
665
029632fb 666void sched_avg_update(struct rq *rq)
18d95a28 667{
e9e9250b
PZ
668 s64 period = sched_avg_period();
669
670 while ((s64)(rq->clock - rq->age_stamp) > period) {
0d98bb26
WD
671 /*
672 * Inline assembly required to prevent the compiler
673 * optimising this loop into a divmod call.
674 * See __iter_div_u64_rem() for another example of this.
675 */
676 asm("" : "+rm" (rq->age_stamp));
e9e9250b
PZ
677 rq->age_stamp += period;
678 rq->rt_avg /= 2;
679 }
18d95a28
PZ
680}
681
6d6bc0ad 682#else /* !CONFIG_SMP */
029632fb 683void resched_task(struct task_struct *p)
18d95a28 684{
05fa785c 685 assert_raw_spin_locked(&task_rq(p)->lock);
31656519 686 set_tsk_need_resched(p);
18d95a28 687}
6d6bc0ad 688#endif /* CONFIG_SMP */
18d95a28 689
a790de99
PT
690#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
691 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
c09595f6 692/*
8277434e
PT
693 * Iterate task_group tree rooted at *from, calling @down when first entering a
694 * node and @up when leaving it for the final time.
695 *
696 * Caller must hold rcu_lock or sufficient equivalent.
c09595f6 697 */
029632fb 698int walk_tg_tree_from(struct task_group *from,
8277434e 699 tg_visitor down, tg_visitor up, void *data)
c09595f6
PZ
700{
701 struct task_group *parent, *child;
eb755805 702 int ret;
c09595f6 703
8277434e
PT
704 parent = from;
705
c09595f6 706down:
eb755805
PZ
707 ret = (*down)(parent, data);
708 if (ret)
8277434e 709 goto out;
c09595f6
PZ
710 list_for_each_entry_rcu(child, &parent->children, siblings) {
711 parent = child;
712 goto down;
713
714up:
715 continue;
716 }
eb755805 717 ret = (*up)(parent, data);
8277434e
PT
718 if (ret || parent == from)
719 goto out;
c09595f6
PZ
720
721 child = parent;
722 parent = parent->parent;
723 if (parent)
724 goto up;
8277434e 725out:
eb755805 726 return ret;
c09595f6
PZ
727}
728
029632fb 729int tg_nop(struct task_group *tg, void *data)
eb755805 730{
e2b245f8 731 return 0;
eb755805 732}
18d95a28
PZ
733#endif
734
45bf76df
IM
735static void set_load_weight(struct task_struct *p)
736{
f05998d4
NR
737 int prio = p->static_prio - MAX_RT_PRIO;
738 struct load_weight *load = &p->se.load;
739
dd41f596
IM
740 /*
741 * SCHED_IDLE tasks get minimal weight:
742 */
743 if (p->policy == SCHED_IDLE) {
c8b28116 744 load->weight = scale_load(WEIGHT_IDLEPRIO);
f05998d4 745 load->inv_weight = WMULT_IDLEPRIO;
dd41f596
IM
746 return;
747 }
71f8bd46 748
c8b28116 749 load->weight = scale_load(prio_to_weight[prio]);
f05998d4 750 load->inv_weight = prio_to_wmult[prio];
71f8bd46
IM
751}
752
371fd7e7 753static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2087a1ad 754{
a64692a3 755 update_rq_clock(rq);
dd41f596 756 sched_info_queued(p);
371fd7e7 757 p->sched_class->enqueue_task(rq, p, flags);
71f8bd46
IM
758}
759
371fd7e7 760static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
71f8bd46 761{
a64692a3 762 update_rq_clock(rq);
46ac22ba 763 sched_info_dequeued(p);
371fd7e7 764 p->sched_class->dequeue_task(rq, p, flags);
71f8bd46
IM
765}
766
029632fb 767void activate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
768{
769 if (task_contributes_to_load(p))
770 rq->nr_uninterruptible--;
771
371fd7e7 772 enqueue_task(rq, p, flags);
1e3c88bd
PZ
773}
774
029632fb 775void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
776{
777 if (task_contributes_to_load(p))
778 rq->nr_uninterruptible++;
779
371fd7e7 780 dequeue_task(rq, p, flags);
1e3c88bd
PZ
781}
782
fe44d621 783static void update_rq_clock_task(struct rq *rq, s64 delta)
aa483808 784{
095c0aa8
GC
785/*
786 * In theory, the compile should just see 0 here, and optimize out the call
787 * to sched_rt_avg_update. But I don't trust it...
788 */
789#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
790 s64 steal = 0, irq_delta = 0;
791#endif
792#ifdef CONFIG_IRQ_TIME_ACCOUNTING
8e92c201 793 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
fe44d621
PZ
794
795 /*
796 * Since irq_time is only updated on {soft,}irq_exit, we might run into
797 * this case when a previous update_rq_clock() happened inside a
798 * {soft,}irq region.
799 *
800 * When this happens, we stop ->clock_task and only update the
801 * prev_irq_time stamp to account for the part that fit, so that a next
802 * update will consume the rest. This ensures ->clock_task is
803 * monotonic.
804 *
805 * It does however cause some slight miss-attribution of {soft,}irq
806 * time, a more accurate solution would be to update the irq_time using
807 * the current rq->clock timestamp, except that would require using
808 * atomic ops.
809 */
810 if (irq_delta > delta)
811 irq_delta = delta;
812
813 rq->prev_irq_time += irq_delta;
814 delta -= irq_delta;
095c0aa8
GC
815#endif
816#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
c5905afb 817 if (static_key_false((&paravirt_steal_rq_enabled))) {
095c0aa8
GC
818 u64 st;
819
820 steal = paravirt_steal_clock(cpu_of(rq));
821 steal -= rq->prev_steal_time_rq;
822
823 if (unlikely(steal > delta))
824 steal = delta;
825
826 st = steal_ticks(steal);
827 steal = st * TICK_NSEC;
828
829 rq->prev_steal_time_rq += steal;
830
831 delta -= steal;
832 }
833#endif
834
fe44d621
PZ
835 rq->clock_task += delta;
836
095c0aa8
GC
837#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
838 if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
839 sched_rt_avg_update(rq, irq_delta + steal);
840#endif
aa483808
VP
841}
842
34f971f6
PZ
843void sched_set_stop_task(int cpu, struct task_struct *stop)
844{
845 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
846 struct task_struct *old_stop = cpu_rq(cpu)->stop;
847
848 if (stop) {
849 /*
850 * Make it appear like a SCHED_FIFO task, its something
851 * userspace knows about and won't get confused about.
852 *
853 * Also, it will make PI more or less work without too
854 * much confusion -- but then, stop work should not
855 * rely on PI working anyway.
856 */
857 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
858
859 stop->sched_class = &stop_sched_class;
860 }
861
862 cpu_rq(cpu)->stop = stop;
863
864 if (old_stop) {
865 /*
866 * Reset it back to a normal scheduling class so that
867 * it can die in pieces.
868 */
869 old_stop->sched_class = &rt_sched_class;
870 }
871}
872
14531189 873/*
dd41f596 874 * __normal_prio - return the priority that is based on the static prio
14531189 875 */
14531189
IM
876static inline int __normal_prio(struct task_struct *p)
877{
dd41f596 878 return p->static_prio;
14531189
IM
879}
880
b29739f9
IM
881/*
882 * Calculate the expected normal priority: i.e. priority
883 * without taking RT-inheritance into account. Might be
884 * boosted by interactivity modifiers. Changes upon fork,
885 * setprio syscalls, and whenever the interactivity
886 * estimator recalculates.
887 */
36c8b586 888static inline int normal_prio(struct task_struct *p)
b29739f9
IM
889{
890 int prio;
891
e05606d3 892 if (task_has_rt_policy(p))
b29739f9
IM
893 prio = MAX_RT_PRIO-1 - p->rt_priority;
894 else
895 prio = __normal_prio(p);
896 return prio;
897}
898
899/*
900 * Calculate the current priority, i.e. the priority
901 * taken into account by the scheduler. This value might
902 * be boosted by RT tasks, or might be boosted by
903 * interactivity modifiers. Will be RT if the task got
904 * RT-boosted. If not then it returns p->normal_prio.
905 */
36c8b586 906static int effective_prio(struct task_struct *p)
b29739f9
IM
907{
908 p->normal_prio = normal_prio(p);
909 /*
910 * If we are RT tasks or we were boosted to RT priority,
911 * keep the priority unchanged. Otherwise, update priority
912 * to the normal priority:
913 */
914 if (!rt_prio(p->prio))
915 return p->normal_prio;
916 return p->prio;
917}
918
1da177e4
LT
919/**
920 * task_curr - is this task currently executing on a CPU?
921 * @p: the task in question.
922 */
36c8b586 923inline int task_curr(const struct task_struct *p)
1da177e4
LT
924{
925 return cpu_curr(task_cpu(p)) == p;
926}
927
cb469845
SR
928static inline void check_class_changed(struct rq *rq, struct task_struct *p,
929 const struct sched_class *prev_class,
da7a735e 930 int oldprio)
cb469845
SR
931{
932 if (prev_class != p->sched_class) {
933 if (prev_class->switched_from)
da7a735e
PZ
934 prev_class->switched_from(rq, p);
935 p->sched_class->switched_to(rq, p);
936 } else if (oldprio != p->prio)
937 p->sched_class->prio_changed(rq, p, oldprio);
cb469845
SR
938}
939
029632fb 940void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1e5a7405
PZ
941{
942 const struct sched_class *class;
943
944 if (p->sched_class == rq->curr->sched_class) {
945 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
946 } else {
947 for_each_class(class) {
948 if (class == rq->curr->sched_class)
949 break;
950 if (class == p->sched_class) {
951 resched_task(rq->curr);
952 break;
953 }
954 }
955 }
956
957 /*
958 * A queue event has occurred, and we're going to schedule. In
959 * this case, we can save a useless back to back clock update.
960 */
fd2f4419 961 if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
1e5a7405
PZ
962 rq->skip_clock_update = 1;
963}
964
582b336e
MT
965static ATOMIC_NOTIFIER_HEAD(task_migration_notifier);
966
967void register_task_migration_notifier(struct notifier_block *n)
968{
969 atomic_notifier_chain_register(&task_migration_notifier, n);
970}
971
1da177e4 972#ifdef CONFIG_SMP
dd41f596 973void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 974{
e2912009
PZ
975#ifdef CONFIG_SCHED_DEBUG
976 /*
977 * We should never call set_task_cpu() on a blocked task,
978 * ttwu() will sort out the placement.
979 */
077614ee
PZ
980 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
981 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
0122ec5b
PZ
982
983#ifdef CONFIG_LOCKDEP
6c6c54e1
PZ
984 /*
985 * The caller should hold either p->pi_lock or rq->lock, when changing
986 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
987 *
988 * sched_move_task() holds both and thus holding either pins the cgroup,
8323f26c 989 * see task_group().
6c6c54e1
PZ
990 *
991 * Furthermore, all task_rq users should acquire both locks, see
992 * task_rq_lock().
993 */
0122ec5b
PZ
994 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
995 lockdep_is_held(&task_rq(p)->lock)));
996#endif
e2912009
PZ
997#endif
998
de1d7286 999 trace_sched_migrate_task(p, new_cpu);
cbc34ed1 1000
0c69774e 1001 if (task_cpu(p) != new_cpu) {
582b336e
MT
1002 struct task_migration_notifier tmn;
1003
0a74bef8
PT
1004 if (p->sched_class->migrate_task_rq)
1005 p->sched_class->migrate_task_rq(p, new_cpu);
0c69774e 1006 p->se.nr_migrations++;
a8b0ca17 1007 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
582b336e
MT
1008
1009 tmn.task = p;
1010 tmn.from_cpu = task_cpu(p);
1011 tmn.to_cpu = new_cpu;
1012
1013 atomic_notifier_call_chain(&task_migration_notifier, 0, &tmn);
0c69774e 1014 }
dd41f596
IM
1015
1016 __set_task_cpu(p, new_cpu);
c65cc870
IM
1017}
1018
969c7921 1019struct migration_arg {
36c8b586 1020 struct task_struct *task;
1da177e4 1021 int dest_cpu;
70b97a7f 1022};
1da177e4 1023
969c7921
TH
1024static int migration_cpu_stop(void *data);
1025
1da177e4
LT
1026/*
1027 * wait_task_inactive - wait for a thread to unschedule.
1028 *
85ba2d86
RM
1029 * If @match_state is nonzero, it's the @p->state value just checked and
1030 * not expected to change. If it changes, i.e. @p might have woken up,
1031 * then return zero. When we succeed in waiting for @p to be off its CPU,
1032 * we return a positive number (its total switch count). If a second call
1033 * a short while later returns the same number, the caller can be sure that
1034 * @p has remained unscheduled the whole time.
1035 *
1da177e4
LT
1036 * The caller must ensure that the task *will* unschedule sometime soon,
1037 * else this function might spin for a *long* time. This function can't
1038 * be called with interrupts off, or it may introduce deadlock with
1039 * smp_call_function() if an IPI is sent by the same process we are
1040 * waiting to become inactive.
1041 */
85ba2d86 1042unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1da177e4
LT
1043{
1044 unsigned long flags;
dd41f596 1045 int running, on_rq;
85ba2d86 1046 unsigned long ncsw;
70b97a7f 1047 struct rq *rq;
1da177e4 1048
3a5c359a
AK
1049 for (;;) {
1050 /*
1051 * We do the initial early heuristics without holding
1052 * any task-queue locks at all. We'll only try to get
1053 * the runqueue lock when things look like they will
1054 * work out!
1055 */
1056 rq = task_rq(p);
fa490cfd 1057
3a5c359a
AK
1058 /*
1059 * If the task is actively running on another CPU
1060 * still, just relax and busy-wait without holding
1061 * any locks.
1062 *
1063 * NOTE! Since we don't hold any locks, it's not
1064 * even sure that "rq" stays as the right runqueue!
1065 * But we don't care, since "task_running()" will
1066 * return false if the runqueue has changed and p
1067 * is actually now running somewhere else!
1068 */
85ba2d86
RM
1069 while (task_running(rq, p)) {
1070 if (match_state && unlikely(p->state != match_state))
1071 return 0;
3a5c359a 1072 cpu_relax();
85ba2d86 1073 }
fa490cfd 1074
3a5c359a
AK
1075 /*
1076 * Ok, time to look more closely! We need the rq
1077 * lock now, to be *sure*. If we're wrong, we'll
1078 * just go back and repeat.
1079 */
1080 rq = task_rq_lock(p, &flags);
27a9da65 1081 trace_sched_wait_task(p);
3a5c359a 1082 running = task_running(rq, p);
fd2f4419 1083 on_rq = p->on_rq;
85ba2d86 1084 ncsw = 0;
f31e11d8 1085 if (!match_state || p->state == match_state)
93dcf55f 1086 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
0122ec5b 1087 task_rq_unlock(rq, p, &flags);
fa490cfd 1088
85ba2d86
RM
1089 /*
1090 * If it changed from the expected state, bail out now.
1091 */
1092 if (unlikely(!ncsw))
1093 break;
1094
3a5c359a
AK
1095 /*
1096 * Was it really running after all now that we
1097 * checked with the proper locks actually held?
1098 *
1099 * Oops. Go back and try again..
1100 */
1101 if (unlikely(running)) {
1102 cpu_relax();
1103 continue;
1104 }
fa490cfd 1105
3a5c359a
AK
1106 /*
1107 * It's not enough that it's not actively running,
1108 * it must be off the runqueue _entirely_, and not
1109 * preempted!
1110 *
80dd99b3 1111 * So if it was still runnable (but just not actively
3a5c359a
AK
1112 * running right now), it's preempted, and we should
1113 * yield - it could be a while.
1114 */
1115 if (unlikely(on_rq)) {
8eb90c30
TG
1116 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1117
1118 set_current_state(TASK_UNINTERRUPTIBLE);
1119 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
3a5c359a
AK
1120 continue;
1121 }
fa490cfd 1122
3a5c359a
AK
1123 /*
1124 * Ahh, all good. It wasn't running, and it wasn't
1125 * runnable, which means that it will never become
1126 * running in the future either. We're all done!
1127 */
1128 break;
1129 }
85ba2d86
RM
1130
1131 return ncsw;
1da177e4
LT
1132}
1133
1134/***
1135 * kick_process - kick a running thread to enter/exit the kernel
1136 * @p: the to-be-kicked thread
1137 *
1138 * Cause a process which is running on another CPU to enter
1139 * kernel-mode, without any delay. (to get signals handled.)
1140 *
25985edc 1141 * NOTE: this function doesn't have to take the runqueue lock,
1da177e4
LT
1142 * because all it wants to ensure is that the remote task enters
1143 * the kernel. If the IPI races and the task has been migrated
1144 * to another CPU then no harm is done and the purpose has been
1145 * achieved as well.
1146 */
36c8b586 1147void kick_process(struct task_struct *p)
1da177e4
LT
1148{
1149 int cpu;
1150
1151 preempt_disable();
1152 cpu = task_cpu(p);
1153 if ((cpu != smp_processor_id()) && task_curr(p))
1154 smp_send_reschedule(cpu);
1155 preempt_enable();
1156}
b43e3521 1157EXPORT_SYMBOL_GPL(kick_process);
476d139c 1158#endif /* CONFIG_SMP */
1da177e4 1159
970b13ba 1160#ifdef CONFIG_SMP
30da688e 1161/*
013fdb80 1162 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
30da688e 1163 */
5da9a0fb
PZ
1164static int select_fallback_rq(int cpu, struct task_struct *p)
1165{
aa00d89c
TC
1166 int nid = cpu_to_node(cpu);
1167 const struct cpumask *nodemask = NULL;
2baab4e9
PZ
1168 enum { cpuset, possible, fail } state = cpuset;
1169 int dest_cpu;
5da9a0fb 1170
aa00d89c
TC
1171 /*
1172 * If the node that the cpu is on has been offlined, cpu_to_node()
1173 * will return -1. There is no cpu on the node, and we should
1174 * select the cpu on the other node.
1175 */
1176 if (nid != -1) {
1177 nodemask = cpumask_of_node(nid);
1178
1179 /* Look for allowed, online CPU in same node. */
1180 for_each_cpu(dest_cpu, nodemask) {
1181 if (!cpu_online(dest_cpu))
1182 continue;
1183 if (!cpu_active(dest_cpu))
1184 continue;
1185 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1186 return dest_cpu;
1187 }
2baab4e9 1188 }
5da9a0fb 1189
2baab4e9
PZ
1190 for (;;) {
1191 /* Any allowed, online CPU? */
e3831edd 1192 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
2baab4e9
PZ
1193 if (!cpu_online(dest_cpu))
1194 continue;
1195 if (!cpu_active(dest_cpu))
1196 continue;
1197 goto out;
1198 }
5da9a0fb 1199
2baab4e9
PZ
1200 switch (state) {
1201 case cpuset:
1202 /* No more Mr. Nice Guy. */
1203 cpuset_cpus_allowed_fallback(p);
1204 state = possible;
1205 break;
1206
1207 case possible:
1208 do_set_cpus_allowed(p, cpu_possible_mask);
1209 state = fail;
1210 break;
1211
1212 case fail:
1213 BUG();
1214 break;
1215 }
1216 }
1217
1218out:
1219 if (state != cpuset) {
1220 /*
1221 * Don't tell them about moving exiting tasks or
1222 * kernel threads (both mm NULL), since they never
1223 * leave kernel.
1224 */
1225 if (p->mm && printk_ratelimit()) {
1226 printk_sched("process %d (%s) no longer affine to cpu%d\n",
1227 task_pid_nr(p), p->comm, cpu);
1228 }
5da9a0fb
PZ
1229 }
1230
1231 return dest_cpu;
1232}
1233
e2912009 1234/*
013fdb80 1235 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
e2912009 1236 */
970b13ba 1237static inline
7608dec2 1238int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
970b13ba 1239{
7608dec2 1240 int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
e2912009
PZ
1241
1242 /*
1243 * In order not to call set_task_cpu() on a blocking task we need
1244 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1245 * cpu.
1246 *
1247 * Since this is common to all placement strategies, this lives here.
1248 *
1249 * [ this allows ->select_task() to simply return task_cpu(p) and
1250 * not worry about this generic constraint ]
1251 */
fa17b507 1252 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
70f11205 1253 !cpu_online(cpu)))
5da9a0fb 1254 cpu = select_fallback_rq(task_cpu(p), p);
e2912009
PZ
1255
1256 return cpu;
970b13ba 1257}
09a40af5
MG
1258
1259static void update_avg(u64 *avg, u64 sample)
1260{
1261 s64 diff = sample - *avg;
1262 *avg += diff >> 3;
1263}
970b13ba
PZ
1264#endif
1265
d7c01d27 1266static void
b84cb5df 1267ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
9ed3811a 1268{
d7c01d27 1269#ifdef CONFIG_SCHEDSTATS
b84cb5df
PZ
1270 struct rq *rq = this_rq();
1271
d7c01d27
PZ
1272#ifdef CONFIG_SMP
1273 int this_cpu = smp_processor_id();
1274
1275 if (cpu == this_cpu) {
1276 schedstat_inc(rq, ttwu_local);
1277 schedstat_inc(p, se.statistics.nr_wakeups_local);
1278 } else {
1279 struct sched_domain *sd;
1280
1281 schedstat_inc(p, se.statistics.nr_wakeups_remote);
057f3fad 1282 rcu_read_lock();
d7c01d27
PZ
1283 for_each_domain(this_cpu, sd) {
1284 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1285 schedstat_inc(sd, ttwu_wake_remote);
1286 break;
1287 }
1288 }
057f3fad 1289 rcu_read_unlock();
d7c01d27 1290 }
f339b9dc
PZ
1291
1292 if (wake_flags & WF_MIGRATED)
1293 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
1294
d7c01d27
PZ
1295#endif /* CONFIG_SMP */
1296
1297 schedstat_inc(rq, ttwu_count);
9ed3811a 1298 schedstat_inc(p, se.statistics.nr_wakeups);
d7c01d27
PZ
1299
1300 if (wake_flags & WF_SYNC)
9ed3811a 1301 schedstat_inc(p, se.statistics.nr_wakeups_sync);
d7c01d27 1302
d7c01d27
PZ
1303#endif /* CONFIG_SCHEDSTATS */
1304}
1305
1306static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1307{
9ed3811a 1308 activate_task(rq, p, en_flags);
fd2f4419 1309 p->on_rq = 1;
c2f7115e
PZ
1310
1311 /* if a worker is waking up, notify workqueue */
1312 if (p->flags & PF_WQ_WORKER)
1313 wq_worker_waking_up(p, cpu_of(rq));
9ed3811a
TH
1314}
1315
23f41eeb
PZ
1316/*
1317 * Mark the task runnable and perform wakeup-preemption.
1318 */
89363381 1319static void
23f41eeb 1320ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
9ed3811a 1321{
9ed3811a 1322 check_preempt_curr(rq, p, wake_flags);
a8d7ad52 1323 trace_sched_wakeup(p, true);
9ed3811a
TH
1324
1325 p->state = TASK_RUNNING;
1326#ifdef CONFIG_SMP
1327 if (p->sched_class->task_woken)
1328 p->sched_class->task_woken(rq, p);
1329
e69c6341 1330 if (rq->idle_stamp) {
9ed3811a
TH
1331 u64 delta = rq->clock - rq->idle_stamp;
1332 u64 max = 2*sysctl_sched_migration_cost;
1333
1334 if (delta > max)
1335 rq->avg_idle = max;
1336 else
1337 update_avg(&rq->avg_idle, delta);
1338 rq->idle_stamp = 0;
1339 }
1340#endif
1341}
1342
c05fbafb
PZ
1343static void
1344ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
1345{
1346#ifdef CONFIG_SMP
1347 if (p->sched_contributes_to_load)
1348 rq->nr_uninterruptible--;
1349#endif
1350
1351 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
1352 ttwu_do_wakeup(rq, p, wake_flags);
1353}
1354
1355/*
1356 * Called in case the task @p isn't fully descheduled from its runqueue,
1357 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1358 * since all we need to do is flip p->state to TASK_RUNNING, since
1359 * the task is still ->on_rq.
1360 */
1361static int ttwu_remote(struct task_struct *p, int wake_flags)
1362{
1363 struct rq *rq;
1364 int ret = 0;
1365
1366 rq = __task_rq_lock(p);
1367 if (p->on_rq) {
1368 ttwu_do_wakeup(rq, p, wake_flags);
1369 ret = 1;
1370 }
1371 __task_rq_unlock(rq);
1372
1373 return ret;
1374}
1375
317f3941 1376#ifdef CONFIG_SMP
fa14ff4a 1377static void sched_ttwu_pending(void)
317f3941
PZ
1378{
1379 struct rq *rq = this_rq();
fa14ff4a
PZ
1380 struct llist_node *llist = llist_del_all(&rq->wake_list);
1381 struct task_struct *p;
317f3941
PZ
1382
1383 raw_spin_lock(&rq->lock);
1384
fa14ff4a
PZ
1385 while (llist) {
1386 p = llist_entry(llist, struct task_struct, wake_entry);
1387 llist = llist_next(llist);
317f3941
PZ
1388 ttwu_do_activate(rq, p, 0);
1389 }
1390
1391 raw_spin_unlock(&rq->lock);
1392}
1393
1394void scheduler_ipi(void)
1395{
ff442c51
FW
1396 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick()
1397 && !tick_nohz_full_cpu(smp_processor_id()))
c5d753a5
PZ
1398 return;
1399
1400 /*
1401 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1402 * traditionally all their work was done from the interrupt return
1403 * path. Now that we actually do some work, we need to make sure
1404 * we do call them.
1405 *
1406 * Some archs already do call them, luckily irq_enter/exit nest
1407 * properly.
1408 *
1409 * Arguably we should visit all archs and update all handlers,
1410 * however a fair share of IPIs are still resched only so this would
1411 * somewhat pessimize the simple resched case.
1412 */
1413 irq_enter();
ff442c51 1414 tick_nohz_full_check();
fa14ff4a 1415 sched_ttwu_pending();
ca38062e
SS
1416
1417 /*
1418 * Check if someone kicked us for doing the nohz idle load balance.
1419 */
6eb57e0d
SS
1420 if (unlikely(got_nohz_idle_kick() && !need_resched())) {
1421 this_rq()->idle_balance = 1;
ca38062e 1422 raise_softirq_irqoff(SCHED_SOFTIRQ);
6eb57e0d 1423 }
c5d753a5 1424 irq_exit();
317f3941
PZ
1425}
1426
1427static void ttwu_queue_remote(struct task_struct *p, int cpu)
1428{
fa14ff4a 1429 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list))
317f3941
PZ
1430 smp_send_reschedule(cpu);
1431}
d6aa8f85 1432
39be3501 1433bool cpus_share_cache(int this_cpu, int that_cpu)
518cd623
PZ
1434{
1435 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1436}
d6aa8f85 1437#endif /* CONFIG_SMP */
317f3941 1438
c05fbafb
PZ
1439static void ttwu_queue(struct task_struct *p, int cpu)
1440{
1441 struct rq *rq = cpu_rq(cpu);
1442
17d9f311 1443#if defined(CONFIG_SMP)
39be3501 1444 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
f01114cb 1445 sched_clock_cpu(cpu); /* sync clocks x-cpu */
317f3941
PZ
1446 ttwu_queue_remote(p, cpu);
1447 return;
1448 }
1449#endif
1450
c05fbafb
PZ
1451 raw_spin_lock(&rq->lock);
1452 ttwu_do_activate(rq, p, 0);
1453 raw_spin_unlock(&rq->lock);
9ed3811a
TH
1454}
1455
1456/**
1da177e4 1457 * try_to_wake_up - wake up a thread
9ed3811a 1458 * @p: the thread to be awakened
1da177e4 1459 * @state: the mask of task states that can be woken
9ed3811a 1460 * @wake_flags: wake modifier flags (WF_*)
1da177e4
LT
1461 *
1462 * Put it on the run-queue if it's not already there. The "current"
1463 * thread is always on the run-queue (except when the actual
1464 * re-schedule is in progress), and as such you're allowed to do
1465 * the simpler "current->state = TASK_RUNNING" to mark yourself
1466 * runnable without the overhead of this.
1467 *
9ed3811a
TH
1468 * Returns %true if @p was woken up, %false if it was already running
1469 * or @state didn't match @p's state.
1da177e4 1470 */
e4a52bcb
PZ
1471static int
1472try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1da177e4 1473{
1da177e4 1474 unsigned long flags;
c05fbafb 1475 int cpu, success = 0;
2398f2c6 1476
04e2f174 1477 smp_wmb();
013fdb80 1478 raw_spin_lock_irqsave(&p->pi_lock, flags);
e9c84311 1479 if (!(p->state & state))
1da177e4
LT
1480 goto out;
1481
c05fbafb 1482 success = 1; /* we're going to change ->state */
1da177e4 1483 cpu = task_cpu(p);
1da177e4 1484
c05fbafb
PZ
1485 if (p->on_rq && ttwu_remote(p, wake_flags))
1486 goto stat;
1da177e4 1487
1da177e4 1488#ifdef CONFIG_SMP
e9c84311 1489 /*
c05fbafb
PZ
1490 * If the owning (remote) cpu is still in the middle of schedule() with
1491 * this task as prev, wait until its done referencing the task.
e9c84311 1492 */
f3e94786 1493 while (p->on_cpu)
e4a52bcb 1494 cpu_relax();
0970d299 1495 /*
e4a52bcb 1496 * Pairs with the smp_wmb() in finish_lock_switch().
0970d299 1497 */
e4a52bcb 1498 smp_rmb();
1da177e4 1499
a8e4f2ea 1500 p->sched_contributes_to_load = !!task_contributes_to_load(p);
e9c84311 1501 p->state = TASK_WAKING;
e7693a36 1502
e4a52bcb 1503 if (p->sched_class->task_waking)
74f8e4b2 1504 p->sched_class->task_waking(p);
efbbd05a 1505
7608dec2 1506 cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
f339b9dc
PZ
1507 if (task_cpu(p) != cpu) {
1508 wake_flags |= WF_MIGRATED;
e4a52bcb 1509 set_task_cpu(p, cpu);
f339b9dc 1510 }
1da177e4 1511#endif /* CONFIG_SMP */
1da177e4 1512
c05fbafb
PZ
1513 ttwu_queue(p, cpu);
1514stat:
b84cb5df 1515 ttwu_stat(p, cpu, wake_flags);
1da177e4 1516out:
013fdb80 1517 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
1518
1519 return success;
1520}
1521
21aa9af0
TH
1522/**
1523 * try_to_wake_up_local - try to wake up a local task with rq lock held
1524 * @p: the thread to be awakened
1525 *
2acca55e 1526 * Put @p on the run-queue if it's not already there. The caller must
21aa9af0 1527 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2acca55e 1528 * the current task.
21aa9af0
TH
1529 */
1530static void try_to_wake_up_local(struct task_struct *p)
1531{
1532 struct rq *rq = task_rq(p);
21aa9af0 1533
383efcd0
TH
1534 if (WARN_ON_ONCE(rq != this_rq()) ||
1535 WARN_ON_ONCE(p == current))
1536 return;
1537
21aa9af0
TH
1538 lockdep_assert_held(&rq->lock);
1539
2acca55e
PZ
1540 if (!raw_spin_trylock(&p->pi_lock)) {
1541 raw_spin_unlock(&rq->lock);
1542 raw_spin_lock(&p->pi_lock);
1543 raw_spin_lock(&rq->lock);
1544 }
1545
21aa9af0 1546 if (!(p->state & TASK_NORMAL))
2acca55e 1547 goto out;
21aa9af0 1548
fd2f4419 1549 if (!p->on_rq)
d7c01d27
PZ
1550 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
1551
23f41eeb 1552 ttwu_do_wakeup(rq, p, 0);
b84cb5df 1553 ttwu_stat(p, smp_processor_id(), 0);
2acca55e
PZ
1554out:
1555 raw_spin_unlock(&p->pi_lock);
21aa9af0
TH
1556}
1557
50fa610a
DH
1558/**
1559 * wake_up_process - Wake up a specific process
1560 * @p: The process to be woken up.
1561 *
1562 * Attempt to wake up the nominated process and move it to the set of runnable
1563 * processes. Returns 1 if the process was woken up, 0 if it was already
1564 * running.
1565 *
1566 * It may be assumed that this function implies a write memory barrier before
1567 * changing the task state if and only if any tasks are woken up.
1568 */
7ad5b3a5 1569int wake_up_process(struct task_struct *p)
1da177e4 1570{
9067ac85
ON
1571 WARN_ON(task_is_stopped_or_traced(p));
1572 return try_to_wake_up(p, TASK_NORMAL, 0);
1da177e4 1573}
1da177e4
LT
1574EXPORT_SYMBOL(wake_up_process);
1575
7ad5b3a5 1576int wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
1577{
1578 return try_to_wake_up(p, state, 0);
1579}
1580
1da177e4
LT
1581/*
1582 * Perform scheduler related setup for a newly forked process p.
1583 * p is forked by current.
dd41f596
IM
1584 *
1585 * __sched_fork() is basic setup used by init_idle() too:
1586 */
1587static void __sched_fork(struct task_struct *p)
1588{
fd2f4419
PZ
1589 p->on_rq = 0;
1590
1591 p->se.on_rq = 0;
dd41f596
IM
1592 p->se.exec_start = 0;
1593 p->se.sum_exec_runtime = 0;
f6cf891c 1594 p->se.prev_sum_exec_runtime = 0;
6c594c21 1595 p->se.nr_migrations = 0;
da7a735e 1596 p->se.vruntime = 0;
fd2f4419 1597 INIT_LIST_HEAD(&p->se.group_node);
6cfb0d5d 1598
f4e26b12
PT
1599/*
1600 * Load-tracking only depends on SMP, FAIR_GROUP_SCHED dependency below may be
1601 * removed when useful for applications beyond shares distribution (e.g.
1602 * load-balance).
1603 */
1604#if defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)
9d85f21c
PT
1605 p->se.avg.runnable_avg_period = 0;
1606 p->se.avg.runnable_avg_sum = 0;
1607#endif
6cfb0d5d 1608#ifdef CONFIG_SCHEDSTATS
41acab88 1609 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
6cfb0d5d 1610#endif
476d139c 1611
fa717060 1612 INIT_LIST_HEAD(&p->rt.run_list);
476d139c 1613
e107be36
AK
1614#ifdef CONFIG_PREEMPT_NOTIFIERS
1615 INIT_HLIST_HEAD(&p->preempt_notifiers);
1616#endif
cbee9f88
PZ
1617
1618#ifdef CONFIG_NUMA_BALANCING
1619 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
1620 p->mm->numa_next_scan = jiffies;
b8593bfd 1621 p->mm->numa_next_reset = jiffies;
cbee9f88
PZ
1622 p->mm->numa_scan_seq = 0;
1623 }
1624
1625 p->node_stamp = 0ULL;
1626 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
1627 p->numa_migrate_seq = p->mm ? p->mm->numa_scan_seq - 1 : 0;
4b96a29b 1628 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
cbee9f88
PZ
1629 p->numa_work.next = &p->numa_work;
1630#endif /* CONFIG_NUMA_BALANCING */
dd41f596
IM
1631}
1632
1a687c2e 1633#ifdef CONFIG_NUMA_BALANCING
3105b86a 1634#ifdef CONFIG_SCHED_DEBUG
1a687c2e
MG
1635void set_numabalancing_state(bool enabled)
1636{
1637 if (enabled)
1638 sched_feat_set("NUMA");
1639 else
1640 sched_feat_set("NO_NUMA");
1641}
3105b86a
MG
1642#else
1643__read_mostly bool numabalancing_enabled;
1644
1645void set_numabalancing_state(bool enabled)
1646{
1647 numabalancing_enabled = enabled;
dd41f596 1648}
3105b86a 1649#endif /* CONFIG_SCHED_DEBUG */
1a687c2e 1650#endif /* CONFIG_NUMA_BALANCING */
dd41f596
IM
1651
1652/*
1653 * fork()/clone()-time setup:
1654 */
3e51e3ed 1655void sched_fork(struct task_struct *p)
dd41f596 1656{
0122ec5b 1657 unsigned long flags;
dd41f596
IM
1658 int cpu = get_cpu();
1659
1660 __sched_fork(p);
06b83b5f 1661 /*
0017d735 1662 * We mark the process as running here. This guarantees that
06b83b5f
PZ
1663 * nobody will actually run it, and a signal or other external
1664 * event cannot wake it up and insert it on the runqueue either.
1665 */
0017d735 1666 p->state = TASK_RUNNING;
dd41f596 1667
c350a04e
MG
1668 /*
1669 * Make sure we do not leak PI boosting priority to the child.
1670 */
1671 p->prio = current->normal_prio;
1672
b9dc29e7
MG
1673 /*
1674 * Revert to default priority/policy on fork if requested.
1675 */
1676 if (unlikely(p->sched_reset_on_fork)) {
c350a04e 1677 if (task_has_rt_policy(p)) {
b9dc29e7 1678 p->policy = SCHED_NORMAL;
6c697bdf 1679 p->static_prio = NICE_TO_PRIO(0);
c350a04e
MG
1680 p->rt_priority = 0;
1681 } else if (PRIO_TO_NICE(p->static_prio) < 0)
1682 p->static_prio = NICE_TO_PRIO(0);
1683
1684 p->prio = p->normal_prio = __normal_prio(p);
1685 set_load_weight(p);
6c697bdf 1686
b9dc29e7
MG
1687 /*
1688 * We don't need the reset flag anymore after the fork. It has
1689 * fulfilled its duty:
1690 */
1691 p->sched_reset_on_fork = 0;
1692 }
ca94c442 1693
2ddbf952
HS
1694 if (!rt_prio(p->prio))
1695 p->sched_class = &fair_sched_class;
b29739f9 1696
cd29fe6f
PZ
1697 if (p->sched_class->task_fork)
1698 p->sched_class->task_fork(p);
1699
86951599
PZ
1700 /*
1701 * The child is not yet in the pid-hash so no cgroup attach races,
1702 * and the cgroup is pinned to this child due to cgroup_fork()
1703 * is ran before sched_fork().
1704 *
1705 * Silence PROVE_RCU.
1706 */
0122ec5b 1707 raw_spin_lock_irqsave(&p->pi_lock, flags);
5f3edc1b 1708 set_task_cpu(p, cpu);
0122ec5b 1709 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5f3edc1b 1710
52f17b6c 1711#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
dd41f596 1712 if (likely(sched_info_on()))
52f17b6c 1713 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 1714#endif
3ca7a440
PZ
1715#if defined(CONFIG_SMP)
1716 p->on_cpu = 0;
4866cde0 1717#endif
bdd4e85d 1718#ifdef CONFIG_PREEMPT_COUNT
4866cde0 1719 /* Want to start with kernel preemption disabled. */
a1261f54 1720 task_thread_info(p)->preempt_count = 1;
1da177e4 1721#endif
806c09a7 1722#ifdef CONFIG_SMP
917b627d 1723 plist_node_init(&p->pushable_tasks, MAX_PRIO);
806c09a7 1724#endif
917b627d 1725
476d139c 1726 put_cpu();
1da177e4
LT
1727}
1728
1729/*
1730 * wake_up_new_task - wake up a newly created task for the first time.
1731 *
1732 * This function will do some initial scheduler statistics housekeeping
1733 * that must be done for every newly created context, then puts the task
1734 * on the runqueue and wakes it.
1735 */
3e51e3ed 1736void wake_up_new_task(struct task_struct *p)
1da177e4
LT
1737{
1738 unsigned long flags;
dd41f596 1739 struct rq *rq;
fabf318e 1740
ab2515c4 1741 raw_spin_lock_irqsave(&p->pi_lock, flags);
fabf318e
PZ
1742#ifdef CONFIG_SMP
1743 /*
1744 * Fork balancing, do it here and not earlier because:
1745 * - cpus_allowed can change in the fork path
1746 * - any previously selected cpu might disappear through hotplug
fabf318e 1747 */
ab2515c4 1748 set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0));
0017d735
PZ
1749#endif
1750
ab2515c4 1751 rq = __task_rq_lock(p);
cd29fe6f 1752 activate_task(rq, p, 0);
fd2f4419 1753 p->on_rq = 1;
89363381 1754 trace_sched_wakeup_new(p, true);
a7558e01 1755 check_preempt_curr(rq, p, WF_FORK);
9a897c5a 1756#ifdef CONFIG_SMP
efbbd05a
PZ
1757 if (p->sched_class->task_woken)
1758 p->sched_class->task_woken(rq, p);
9a897c5a 1759#endif
0122ec5b 1760 task_rq_unlock(rq, p, &flags);
1da177e4
LT
1761}
1762
e107be36
AK
1763#ifdef CONFIG_PREEMPT_NOTIFIERS
1764
1765/**
80dd99b3 1766 * preempt_notifier_register - tell me when current is being preempted & rescheduled
421cee29 1767 * @notifier: notifier struct to register
e107be36
AK
1768 */
1769void preempt_notifier_register(struct preempt_notifier *notifier)
1770{
1771 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1772}
1773EXPORT_SYMBOL_GPL(preempt_notifier_register);
1774
1775/**
1776 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 1777 * @notifier: notifier struct to unregister
e107be36
AK
1778 *
1779 * This is safe to call from within a preemption notifier.
1780 */
1781void preempt_notifier_unregister(struct preempt_notifier *notifier)
1782{
1783 hlist_del(&notifier->link);
1784}
1785EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1786
1787static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1788{
1789 struct preempt_notifier *notifier;
e107be36 1790
b67bfe0d 1791 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
1792 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1793}
1794
1795static void
1796fire_sched_out_preempt_notifiers(struct task_struct *curr,
1797 struct task_struct *next)
1798{
1799 struct preempt_notifier *notifier;
e107be36 1800
b67bfe0d 1801 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
1802 notifier->ops->sched_out(notifier, next);
1803}
1804
6d6bc0ad 1805#else /* !CONFIG_PREEMPT_NOTIFIERS */
e107be36
AK
1806
1807static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1808{
1809}
1810
1811static void
1812fire_sched_out_preempt_notifiers(struct task_struct *curr,
1813 struct task_struct *next)
1814{
1815}
1816
6d6bc0ad 1817#endif /* CONFIG_PREEMPT_NOTIFIERS */
e107be36 1818
4866cde0
NP
1819/**
1820 * prepare_task_switch - prepare to switch tasks
1821 * @rq: the runqueue preparing to switch
421cee29 1822 * @prev: the current task that is being switched out
4866cde0
NP
1823 * @next: the task we are going to switch to.
1824 *
1825 * This is called with the rq lock held and interrupts off. It must
1826 * be paired with a subsequent finish_task_switch after the context
1827 * switch.
1828 *
1829 * prepare_task_switch sets up locking and calls architecture specific
1830 * hooks.
1831 */
e107be36
AK
1832static inline void
1833prepare_task_switch(struct rq *rq, struct task_struct *prev,
1834 struct task_struct *next)
4866cde0 1835{
895dd92c 1836 trace_sched_switch(prev, next);
fe4b04fa
PZ
1837 sched_info_switch(prev, next);
1838 perf_event_task_sched_out(prev, next);
e107be36 1839 fire_sched_out_preempt_notifiers(prev, next);
4866cde0
NP
1840 prepare_lock_switch(rq, next);
1841 prepare_arch_switch(next);
1842}
1843
1da177e4
LT
1844/**
1845 * finish_task_switch - clean up after a task-switch
344babaa 1846 * @rq: runqueue associated with task-switch
1da177e4
LT
1847 * @prev: the thread we just switched away from.
1848 *
4866cde0
NP
1849 * finish_task_switch must be called after the context switch, paired
1850 * with a prepare_task_switch call before the context switch.
1851 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1852 * and do any other architecture-specific cleanup actions.
1da177e4
LT
1853 *
1854 * Note that we may have delayed dropping an mm in context_switch(). If
41a2d6cf 1855 * so, we finish that here outside of the runqueue lock. (Doing it
1da177e4
LT
1856 * with the lock held can cause deadlocks; see schedule() for
1857 * details.)
1858 */
a9957449 1859static void finish_task_switch(struct rq *rq, struct task_struct *prev)
1da177e4
LT
1860 __releases(rq->lock)
1861{
1da177e4 1862 struct mm_struct *mm = rq->prev_mm;
55a101f8 1863 long prev_state;
1da177e4
LT
1864
1865 rq->prev_mm = NULL;
1866
1867 /*
1868 * A task struct has one reference for the use as "current".
c394cc9f 1869 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
1870 * schedule one last time. The schedule call will never return, and
1871 * the scheduled task must drop that reference.
c394cc9f 1872 * The test for TASK_DEAD must occur while the runqueue locks are
1da177e4
LT
1873 * still held, otherwise prev could be scheduled on another cpu, die
1874 * there before we look at prev->state, and then the reference would
1875 * be dropped twice.
1876 * Manfred Spraul <manfred@colorfullife.com>
1877 */
55a101f8 1878 prev_state = prev->state;
bf9fae9f 1879 vtime_task_switch(prev);
4866cde0 1880 finish_arch_switch(prev);
a8d757ef 1881 perf_event_task_sched_in(prev, current);
4866cde0 1882 finish_lock_switch(rq, prev);
01f23e16 1883 finish_arch_post_lock_switch();
e8fa1362 1884
e107be36 1885 fire_sched_in_preempt_notifiers(current);
1da177e4
LT
1886 if (mm)
1887 mmdrop(mm);
c394cc9f 1888 if (unlikely(prev_state == TASK_DEAD)) {
c6fd91f0 1889 /*
1890 * Remove function-return probe instances associated with this
1891 * task and put them back on the free list.
9761eea8 1892 */
c6fd91f0 1893 kprobe_flush_task(prev);
1da177e4 1894 put_task_struct(prev);
c6fd91f0 1895 }
99e5ada9
FW
1896
1897 tick_nohz_task_switch(current);
1da177e4
LT
1898}
1899
3f029d3c
GH
1900#ifdef CONFIG_SMP
1901
1902/* assumes rq->lock is held */
1903static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
1904{
1905 if (prev->sched_class->pre_schedule)
1906 prev->sched_class->pre_schedule(rq, prev);
1907}
1908
1909/* rq->lock is NOT held, but preemption is disabled */
1910static inline void post_schedule(struct rq *rq)
1911{
1912 if (rq->post_schedule) {
1913 unsigned long flags;
1914
05fa785c 1915 raw_spin_lock_irqsave(&rq->lock, flags);
3f029d3c
GH
1916 if (rq->curr->sched_class->post_schedule)
1917 rq->curr->sched_class->post_schedule(rq);
05fa785c 1918 raw_spin_unlock_irqrestore(&rq->lock, flags);
3f029d3c
GH
1919
1920 rq->post_schedule = 0;
1921 }
1922}
1923
1924#else
da19ab51 1925
3f029d3c
GH
1926static inline void pre_schedule(struct rq *rq, struct task_struct *p)
1927{
1928}
1929
1930static inline void post_schedule(struct rq *rq)
1931{
1da177e4
LT
1932}
1933
3f029d3c
GH
1934#endif
1935
1da177e4
LT
1936/**
1937 * schedule_tail - first thing a freshly forked thread must call.
1938 * @prev: the thread we just switched away from.
1939 */
36c8b586 1940asmlinkage void schedule_tail(struct task_struct *prev)
1da177e4
LT
1941 __releases(rq->lock)
1942{
70b97a7f
IM
1943 struct rq *rq = this_rq();
1944
4866cde0 1945 finish_task_switch(rq, prev);
da19ab51 1946
3f029d3c
GH
1947 /*
1948 * FIXME: do we need to worry about rq being invalidated by the
1949 * task_switch?
1950 */
1951 post_schedule(rq);
70b97a7f 1952
4866cde0
NP
1953#ifdef __ARCH_WANT_UNLOCKED_CTXSW
1954 /* In this case, finish_task_switch does not reenable preemption */
1955 preempt_enable();
1956#endif
1da177e4 1957 if (current->set_child_tid)
b488893a 1958 put_user(task_pid_vnr(current), current->set_child_tid);
1da177e4
LT
1959}
1960
1961/*
1962 * context_switch - switch to the new MM and the new
1963 * thread's register state.
1964 */
dd41f596 1965static inline void
70b97a7f 1966context_switch(struct rq *rq, struct task_struct *prev,
36c8b586 1967 struct task_struct *next)
1da177e4 1968{
dd41f596 1969 struct mm_struct *mm, *oldmm;
1da177e4 1970
e107be36 1971 prepare_task_switch(rq, prev, next);
fe4b04fa 1972
dd41f596
IM
1973 mm = next->mm;
1974 oldmm = prev->active_mm;
9226d125
ZA
1975 /*
1976 * For paravirt, this is coupled with an exit in switch_to to
1977 * combine the page table reload and the switch backend into
1978 * one hypercall.
1979 */
224101ed 1980 arch_start_context_switch(prev);
9226d125 1981
31915ab4 1982 if (!mm) {
1da177e4
LT
1983 next->active_mm = oldmm;
1984 atomic_inc(&oldmm->mm_count);
1985 enter_lazy_tlb(oldmm, next);
1986 } else
1987 switch_mm(oldmm, mm, next);
1988
31915ab4 1989 if (!prev->mm) {
1da177e4 1990 prev->active_mm = NULL;
1da177e4
LT
1991 rq->prev_mm = oldmm;
1992 }
3a5f5e48
IM
1993 /*
1994 * Since the runqueue lock will be released by the next
1995 * task (which is an invalid locking op but in the case
1996 * of the scheduler it's an obvious special-case), so we
1997 * do an early lockdep release here:
1998 */
1999#ifndef __ARCH_WANT_UNLOCKED_CTXSW
8a25d5de 2000 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3a5f5e48 2001#endif
1da177e4 2002
91d1aa43 2003 context_tracking_task_switch(prev, next);
1da177e4
LT
2004 /* Here we just switch the register state and the stack. */
2005 switch_to(prev, next, prev);
2006
dd41f596
IM
2007 barrier();
2008 /*
2009 * this_rq must be evaluated again because prev may have moved
2010 * CPUs since it called schedule(), thus the 'rq' on its stack
2011 * frame will be invalid.
2012 */
2013 finish_task_switch(this_rq(), prev);
1da177e4
LT
2014}
2015
2016/*
1c3e8264 2017 * nr_running and nr_context_switches:
1da177e4
LT
2018 *
2019 * externally visible scheduler statistics: current number of runnable
1c3e8264 2020 * threads, total number of context switches performed since bootup.
1da177e4
LT
2021 */
2022unsigned long nr_running(void)
2023{
2024 unsigned long i, sum = 0;
2025
2026 for_each_online_cpu(i)
2027 sum += cpu_rq(i)->nr_running;
2028
2029 return sum;
f711f609 2030}
1da177e4 2031
1da177e4 2032unsigned long long nr_context_switches(void)
46cb4b7c 2033{
cc94abfc
SR
2034 int i;
2035 unsigned long long sum = 0;
46cb4b7c 2036
0a945022 2037 for_each_possible_cpu(i)
1da177e4 2038 sum += cpu_rq(i)->nr_switches;
46cb4b7c 2039
1da177e4
LT
2040 return sum;
2041}
483b4ee6 2042
1da177e4
LT
2043unsigned long nr_iowait(void)
2044{
2045 unsigned long i, sum = 0;
483b4ee6 2046
0a945022 2047 for_each_possible_cpu(i)
1da177e4 2048 sum += atomic_read(&cpu_rq(i)->nr_iowait);
46cb4b7c 2049
1da177e4
LT
2050 return sum;
2051}
483b4ee6 2052
8c215bd3 2053unsigned long nr_iowait_cpu(int cpu)
69d25870 2054{
8c215bd3 2055 struct rq *this = cpu_rq(cpu);
69d25870
AV
2056 return atomic_read(&this->nr_iowait);
2057}
46cb4b7c 2058
69d25870
AV
2059unsigned long this_cpu_load(void)
2060{
2061 struct rq *this = this_rq();
2062 return this->cpu_load[0];
2063}
e790fb0b 2064
46cb4b7c 2065
5167e8d5
PZ
2066/*
2067 * Global load-average calculations
2068 *
2069 * We take a distributed and async approach to calculating the global load-avg
2070 * in order to minimize overhead.
2071 *
2072 * The global load average is an exponentially decaying average of nr_running +
2073 * nr_uninterruptible.
2074 *
2075 * Once every LOAD_FREQ:
2076 *
2077 * nr_active = 0;
2078 * for_each_possible_cpu(cpu)
2079 * nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
2080 *
2081 * avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
2082 *
2083 * Due to a number of reasons the above turns in the mess below:
2084 *
2085 * - for_each_possible_cpu() is prohibitively expensive on machines with
2086 * serious number of cpus, therefore we need to take a distributed approach
2087 * to calculating nr_active.
2088 *
2089 * \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
2090 * = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
2091 *
2092 * So assuming nr_active := 0 when we start out -- true per definition, we
2093 * can simply take per-cpu deltas and fold those into a global accumulate
2094 * to obtain the same result. See calc_load_fold_active().
2095 *
2096 * Furthermore, in order to avoid synchronizing all per-cpu delta folding
2097 * across the machine, we assume 10 ticks is sufficient time for every
2098 * cpu to have completed this task.
2099 *
2100 * This places an upper-bound on the IRQ-off latency of the machine. Then
2101 * again, being late doesn't loose the delta, just wrecks the sample.
2102 *
2103 * - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because
2104 * this would add another cross-cpu cacheline miss and atomic operation
2105 * to the wakeup path. Instead we increment on whatever cpu the task ran
2106 * when it went into uninterruptible state and decrement on whatever cpu
2107 * did the wakeup. This means that only the sum of nr_uninterruptible over
2108 * all cpus yields the correct result.
2109 *
2110 * This covers the NO_HZ=n code, for extra head-aches, see the comment below.
2111 */
2112
dce48a84
TG
2113/* Variables and functions for calc_load */
2114static atomic_long_t calc_load_tasks;
2115static unsigned long calc_load_update;
2116unsigned long avenrun[3];
5167e8d5
PZ
2117EXPORT_SYMBOL(avenrun); /* should be removed */
2118
2119/**
2120 * get_avenrun - get the load average array
2121 * @loads: pointer to dest load array
2122 * @offset: offset to add
2123 * @shift: shift count to shift the result left
2124 *
2125 * These values are estimates at best, so no need for locking.
2126 */
2127void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
2128{
2129 loads[0] = (avenrun[0] + offset) << shift;
2130 loads[1] = (avenrun[1] + offset) << shift;
2131 loads[2] = (avenrun[2] + offset) << shift;
2132}
46cb4b7c 2133
74f5187a
PZ
2134static long calc_load_fold_active(struct rq *this_rq)
2135{
2136 long nr_active, delta = 0;
2137
2138 nr_active = this_rq->nr_running;
2139 nr_active += (long) this_rq->nr_uninterruptible;
2140
2141 if (nr_active != this_rq->calc_load_active) {
2142 delta = nr_active - this_rq->calc_load_active;
2143 this_rq->calc_load_active = nr_active;
2144 }
2145
2146 return delta;
2147}
2148
5167e8d5
PZ
2149/*
2150 * a1 = a0 * e + a * (1 - e)
2151 */
0f004f5a
PZ
2152static unsigned long
2153calc_load(unsigned long load, unsigned long exp, unsigned long active)
2154{
2155 load *= exp;
2156 load += active * (FIXED_1 - exp);
2157 load += 1UL << (FSHIFT - 1);
2158 return load >> FSHIFT;
2159}
2160
3451d024 2161#ifdef CONFIG_NO_HZ_COMMON
74f5187a 2162/*
5167e8d5
PZ
2163 * Handle NO_HZ for the global load-average.
2164 *
2165 * Since the above described distributed algorithm to compute the global
2166 * load-average relies on per-cpu sampling from the tick, it is affected by
2167 * NO_HZ.
2168 *
2169 * The basic idea is to fold the nr_active delta into a global idle-delta upon
2170 * entering NO_HZ state such that we can include this as an 'extra' cpu delta
2171 * when we read the global state.
2172 *
2173 * Obviously reality has to ruin such a delightfully simple scheme:
2174 *
2175 * - When we go NO_HZ idle during the window, we can negate our sample
2176 * contribution, causing under-accounting.
2177 *
2178 * We avoid this by keeping two idle-delta counters and flipping them
2179 * when the window starts, thus separating old and new NO_HZ load.
2180 *
2181 * The only trick is the slight shift in index flip for read vs write.
2182 *
2183 * 0s 5s 10s 15s
2184 * +10 +10 +10 +10
2185 * |-|-----------|-|-----------|-|-----------|-|
2186 * r:0 0 1 1 0 0 1 1 0
2187 * w:0 1 1 0 0 1 1 0 0
2188 *
2189 * This ensures we'll fold the old idle contribution in this window while
2190 * accumlating the new one.
2191 *
2192 * - When we wake up from NO_HZ idle during the window, we push up our
2193 * contribution, since we effectively move our sample point to a known
2194 * busy state.
2195 *
2196 * This is solved by pushing the window forward, and thus skipping the
2197 * sample, for this cpu (effectively using the idle-delta for this cpu which
2198 * was in effect at the time the window opened). This also solves the issue
2199 * of having to deal with a cpu having been in NOHZ idle for multiple
2200 * LOAD_FREQ intervals.
74f5187a
PZ
2201 *
2202 * When making the ILB scale, we should try to pull this in as well.
2203 */
5167e8d5
PZ
2204static atomic_long_t calc_load_idle[2];
2205static int calc_load_idx;
74f5187a 2206
5167e8d5 2207static inline int calc_load_write_idx(void)
74f5187a 2208{
5167e8d5
PZ
2209 int idx = calc_load_idx;
2210
2211 /*
2212 * See calc_global_nohz(), if we observe the new index, we also
2213 * need to observe the new update time.
2214 */
2215 smp_rmb();
2216
2217 /*
2218 * If the folding window started, make sure we start writing in the
2219 * next idle-delta.
2220 */
2221 if (!time_before(jiffies, calc_load_update))
2222 idx++;
2223
2224 return idx & 1;
2225}
2226
2227static inline int calc_load_read_idx(void)
2228{
2229 return calc_load_idx & 1;
2230}
2231
2232void calc_load_enter_idle(void)
2233{
2234 struct rq *this_rq = this_rq();
74f5187a
PZ
2235 long delta;
2236
5167e8d5
PZ
2237 /*
2238 * We're going into NOHZ mode, if there's any pending delta, fold it
2239 * into the pending idle delta.
2240 */
74f5187a 2241 delta = calc_load_fold_active(this_rq);
5167e8d5
PZ
2242 if (delta) {
2243 int idx = calc_load_write_idx();
2244 atomic_long_add(delta, &calc_load_idle[idx]);
2245 }
74f5187a
PZ
2246}
2247
5167e8d5 2248void calc_load_exit_idle(void)
74f5187a 2249{
5167e8d5
PZ
2250 struct rq *this_rq = this_rq();
2251
2252 /*
2253 * If we're still before the sample window, we're done.
2254 */
2255 if (time_before(jiffies, this_rq->calc_load_update))
2256 return;
74f5187a
PZ
2257
2258 /*
5167e8d5
PZ
2259 * We woke inside or after the sample window, this means we're already
2260 * accounted through the nohz accounting, so skip the entire deal and
2261 * sync up for the next window.
74f5187a 2262 */
5167e8d5
PZ
2263 this_rq->calc_load_update = calc_load_update;
2264 if (time_before(jiffies, this_rq->calc_load_update + 10))
2265 this_rq->calc_load_update += LOAD_FREQ;
2266}
2267
2268static long calc_load_fold_idle(void)
2269{
2270 int idx = calc_load_read_idx();
2271 long delta = 0;
2272
2273 if (atomic_long_read(&calc_load_idle[idx]))
2274 delta = atomic_long_xchg(&calc_load_idle[idx], 0);
74f5187a
PZ
2275
2276 return delta;
2277}
0f004f5a
PZ
2278
2279/**
2280 * fixed_power_int - compute: x^n, in O(log n) time
2281 *
2282 * @x: base of the power
2283 * @frac_bits: fractional bits of @x
2284 * @n: power to raise @x to.
2285 *
2286 * By exploiting the relation between the definition of the natural power
2287 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
2288 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
2289 * (where: n_i \elem {0, 1}, the binary vector representing n),
2290 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
2291 * of course trivially computable in O(log_2 n), the length of our binary
2292 * vector.
2293 */
2294static unsigned long
2295fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
2296{
2297 unsigned long result = 1UL << frac_bits;
2298
2299 if (n) for (;;) {
2300 if (n & 1) {
2301 result *= x;
2302 result += 1UL << (frac_bits - 1);
2303 result >>= frac_bits;
2304 }
2305 n >>= 1;
2306 if (!n)
2307 break;
2308 x *= x;
2309 x += 1UL << (frac_bits - 1);
2310 x >>= frac_bits;
2311 }
2312
2313 return result;
2314}
2315
2316/*
2317 * a1 = a0 * e + a * (1 - e)
2318 *
2319 * a2 = a1 * e + a * (1 - e)
2320 * = (a0 * e + a * (1 - e)) * e + a * (1 - e)
2321 * = a0 * e^2 + a * (1 - e) * (1 + e)
2322 *
2323 * a3 = a2 * e + a * (1 - e)
2324 * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
2325 * = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
2326 *
2327 * ...
2328 *
2329 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
2330 * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
2331 * = a0 * e^n + a * (1 - e^n)
2332 *
2333 * [1] application of the geometric series:
2334 *
2335 * n 1 - x^(n+1)
2336 * S_n := \Sum x^i = -------------
2337 * i=0 1 - x
2338 */
2339static unsigned long
2340calc_load_n(unsigned long load, unsigned long exp,
2341 unsigned long active, unsigned int n)
2342{
2343
2344 return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
2345}
2346
2347/*
2348 * NO_HZ can leave us missing all per-cpu ticks calling
2349 * calc_load_account_active(), but since an idle CPU folds its delta into
2350 * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
2351 * in the pending idle delta if our idle period crossed a load cycle boundary.
2352 *
2353 * Once we've updated the global active value, we need to apply the exponential
2354 * weights adjusted to the number of cycles missed.
2355 */
c308b56b 2356static void calc_global_nohz(void)
0f004f5a
PZ
2357{
2358 long delta, active, n;
2359
5167e8d5
PZ
2360 if (!time_before(jiffies, calc_load_update + 10)) {
2361 /*
2362 * Catch-up, fold however many we are behind still
2363 */
2364 delta = jiffies - calc_load_update - 10;
2365 n = 1 + (delta / LOAD_FREQ);
0f004f5a 2366
5167e8d5
PZ
2367 active = atomic_long_read(&calc_load_tasks);
2368 active = active > 0 ? active * FIXED_1 : 0;
0f004f5a 2369
5167e8d5
PZ
2370 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
2371 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
2372 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
0f004f5a 2373
5167e8d5
PZ
2374 calc_load_update += n * LOAD_FREQ;
2375 }
74f5187a 2376
5167e8d5
PZ
2377 /*
2378 * Flip the idle index...
2379 *
2380 * Make sure we first write the new time then flip the index, so that
2381 * calc_load_write_idx() will see the new time when it reads the new
2382 * index, this avoids a double flip messing things up.
2383 */
2384 smp_wmb();
2385 calc_load_idx++;
74f5187a 2386}
3451d024 2387#else /* !CONFIG_NO_HZ_COMMON */
0f004f5a 2388
5167e8d5
PZ
2389static inline long calc_load_fold_idle(void) { return 0; }
2390static inline void calc_global_nohz(void) { }
74f5187a 2391
3451d024 2392#endif /* CONFIG_NO_HZ_COMMON */
46cb4b7c 2393
46cb4b7c 2394/*
dce48a84
TG
2395 * calc_load - update the avenrun load estimates 10 ticks after the
2396 * CPUs have updated calc_load_tasks.
7835b98b 2397 */
0f004f5a 2398void calc_global_load(unsigned long ticks)
7835b98b 2399{
5167e8d5 2400 long active, delta;
1da177e4 2401
0f004f5a 2402 if (time_before(jiffies, calc_load_update + 10))
dce48a84 2403 return;
1da177e4 2404
5167e8d5
PZ
2405 /*
2406 * Fold the 'old' idle-delta to include all NO_HZ cpus.
2407 */
2408 delta = calc_load_fold_idle();
2409 if (delta)
2410 atomic_long_add(delta, &calc_load_tasks);
2411
dce48a84
TG
2412 active = atomic_long_read(&calc_load_tasks);
2413 active = active > 0 ? active * FIXED_1 : 0;
1da177e4 2414
dce48a84
TG
2415 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
2416 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
2417 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
dd41f596 2418
dce48a84 2419 calc_load_update += LOAD_FREQ;
c308b56b
PZ
2420
2421 /*
5167e8d5 2422 * In case we idled for multiple LOAD_FREQ intervals, catch up in bulk.
c308b56b
PZ
2423 */
2424 calc_global_nohz();
dce48a84 2425}
1da177e4 2426
dce48a84 2427/*
74f5187a
PZ
2428 * Called from update_cpu_load() to periodically update this CPU's
2429 * active count.
dce48a84
TG
2430 */
2431static void calc_load_account_active(struct rq *this_rq)
2432{
74f5187a 2433 long delta;
08c183f3 2434
74f5187a
PZ
2435 if (time_before(jiffies, this_rq->calc_load_update))
2436 return;
783609c6 2437
74f5187a 2438 delta = calc_load_fold_active(this_rq);
74f5187a 2439 if (delta)
dce48a84 2440 atomic_long_add(delta, &calc_load_tasks);
74f5187a
PZ
2441
2442 this_rq->calc_load_update += LOAD_FREQ;
46cb4b7c
SS
2443}
2444
5167e8d5
PZ
2445/*
2446 * End of global load-average stuff
2447 */
2448
fdf3e95d
VP
2449/*
2450 * The exact cpuload at various idx values, calculated at every tick would be
2451 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
2452 *
2453 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
2454 * on nth tick when cpu may be busy, then we have:
2455 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2456 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
2457 *
2458 * decay_load_missed() below does efficient calculation of
2459 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2460 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
2461 *
2462 * The calculation is approximated on a 128 point scale.
2463 * degrade_zero_ticks is the number of ticks after which load at any
2464 * particular idx is approximated to be zero.
2465 * degrade_factor is a precomputed table, a row for each load idx.
2466 * Each column corresponds to degradation factor for a power of two ticks,
2467 * based on 128 point scale.
2468 * Example:
2469 * row 2, col 3 (=12) says that the degradation at load idx 2 after
2470 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
2471 *
2472 * With this power of 2 load factors, we can degrade the load n times
2473 * by looking at 1 bits in n and doing as many mult/shift instead of
2474 * n mult/shifts needed by the exact degradation.
2475 */
2476#define DEGRADE_SHIFT 7
2477static const unsigned char
2478 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
2479static const unsigned char
2480 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
2481 {0, 0, 0, 0, 0, 0, 0, 0},
2482 {64, 32, 8, 0, 0, 0, 0, 0},
2483 {96, 72, 40, 12, 1, 0, 0},
2484 {112, 98, 75, 43, 15, 1, 0},
2485 {120, 112, 98, 76, 45, 16, 2} };
2486
2487/*
2488 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
2489 * would be when CPU is idle and so we just decay the old load without
2490 * adding any new load.
2491 */
2492static unsigned long
2493decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
2494{
2495 int j = 0;
2496
2497 if (!missed_updates)
2498 return load;
2499
2500 if (missed_updates >= degrade_zero_ticks[idx])
2501 return 0;
2502
2503 if (idx == 1)
2504 return load >> missed_updates;
2505
2506 while (missed_updates) {
2507 if (missed_updates % 2)
2508 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
2509
2510 missed_updates >>= 1;
2511 j++;
2512 }
2513 return load;
2514}
2515
46cb4b7c 2516/*
dd41f596 2517 * Update rq->cpu_load[] statistics. This function is usually called every
fdf3e95d
VP
2518 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
2519 * every tick. We fix it up based on jiffies.
46cb4b7c 2520 */
556061b0
PZ
2521static void __update_cpu_load(struct rq *this_rq, unsigned long this_load,
2522 unsigned long pending_updates)
46cb4b7c 2523{
dd41f596 2524 int i, scale;
46cb4b7c 2525
dd41f596 2526 this_rq->nr_load_updates++;
46cb4b7c 2527
dd41f596 2528 /* Update our load: */
fdf3e95d
VP
2529 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
2530 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
dd41f596 2531 unsigned long old_load, new_load;
7d1e6a9b 2532
dd41f596 2533 /* scale is effectively 1 << i now, and >> i divides by scale */
46cb4b7c 2534
dd41f596 2535 old_load = this_rq->cpu_load[i];
fdf3e95d 2536 old_load = decay_load_missed(old_load, pending_updates - 1, i);
dd41f596 2537 new_load = this_load;
a25707f3
IM
2538 /*
2539 * Round up the averaging division if load is increasing. This
2540 * prevents us from getting stuck on 9 if the load is 10, for
2541 * example.
2542 */
2543 if (new_load > old_load)
fdf3e95d
VP
2544 new_load += scale - 1;
2545
2546 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
dd41f596 2547 }
da2b71ed
SS
2548
2549 sched_avg_update(this_rq);
fdf3e95d
VP
2550}
2551
3451d024 2552#ifdef CONFIG_NO_HZ_COMMON
5aaa0b7a
PZ
2553/*
2554 * There is no sane way to deal with nohz on smp when using jiffies because the
2555 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
2556 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
2557 *
2558 * Therefore we cannot use the delta approach from the regular tick since that
2559 * would seriously skew the load calculation. However we'll make do for those
2560 * updates happening while idle (nohz_idle_balance) or coming out of idle
2561 * (tick_nohz_idle_exit).
2562 *
2563 * This means we might still be one tick off for nohz periods.
2564 */
2565
556061b0
PZ
2566/*
2567 * Called from nohz_idle_balance() to update the load ratings before doing the
2568 * idle balance.
2569 */
2570void update_idle_cpu_load(struct rq *this_rq)
2571{
5aaa0b7a 2572 unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
556061b0
PZ
2573 unsigned long load = this_rq->load.weight;
2574 unsigned long pending_updates;
2575
2576 /*
5aaa0b7a 2577 * bail if there's load or we're actually up-to-date.
556061b0
PZ
2578 */
2579 if (load || curr_jiffies == this_rq->last_load_update_tick)
2580 return;
2581
2582 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2583 this_rq->last_load_update_tick = curr_jiffies;
2584
2585 __update_cpu_load(this_rq, load, pending_updates);
2586}
2587
5aaa0b7a
PZ
2588/*
2589 * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed.
2590 */
2591void update_cpu_load_nohz(void)
2592{
2593 struct rq *this_rq = this_rq();
2594 unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
2595 unsigned long pending_updates;
2596
2597 if (curr_jiffies == this_rq->last_load_update_tick)
2598 return;
2599
2600 raw_spin_lock(&this_rq->lock);
2601 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2602 if (pending_updates) {
2603 this_rq->last_load_update_tick = curr_jiffies;
2604 /*
2605 * We were idle, this means load 0, the current load might be
2606 * !0 due to remote wakeups and the sort.
2607 */
2608 __update_cpu_load(this_rq, 0, pending_updates);
2609 }
2610 raw_spin_unlock(&this_rq->lock);
2611}
3451d024 2612#endif /* CONFIG_NO_HZ_COMMON */
5aaa0b7a 2613
556061b0
PZ
2614/*
2615 * Called from scheduler_tick()
2616 */
fdf3e95d
VP
2617static void update_cpu_load_active(struct rq *this_rq)
2618{
556061b0 2619 /*
5aaa0b7a 2620 * See the mess around update_idle_cpu_load() / update_cpu_load_nohz().
556061b0
PZ
2621 */
2622 this_rq->last_load_update_tick = jiffies;
2623 __update_cpu_load(this_rq, this_rq->load.weight, 1);
46cb4b7c 2624
74f5187a 2625 calc_load_account_active(this_rq);
46cb4b7c
SS
2626}
2627
dd41f596 2628#ifdef CONFIG_SMP
8a0be9ef 2629
46cb4b7c 2630/*
38022906
PZ
2631 * sched_exec - execve() is a valuable balancing opportunity, because at
2632 * this point the task has the smallest effective memory and cache footprint.
46cb4b7c 2633 */
38022906 2634void sched_exec(void)
46cb4b7c 2635{
38022906 2636 struct task_struct *p = current;
1da177e4 2637 unsigned long flags;
0017d735 2638 int dest_cpu;
46cb4b7c 2639
8f42ced9 2640 raw_spin_lock_irqsave(&p->pi_lock, flags);
7608dec2 2641 dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0);
0017d735
PZ
2642 if (dest_cpu == smp_processor_id())
2643 goto unlock;
38022906 2644
8f42ced9 2645 if (likely(cpu_active(dest_cpu))) {
969c7921 2646 struct migration_arg arg = { p, dest_cpu };
46cb4b7c 2647
8f42ced9
PZ
2648 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2649 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
1da177e4
LT
2650 return;
2651 }
0017d735 2652unlock:
8f42ced9 2653 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4 2654}
dd41f596 2655
1da177e4
LT
2656#endif
2657
1da177e4 2658DEFINE_PER_CPU(struct kernel_stat, kstat);
3292beb3 2659DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
1da177e4
LT
2660
2661EXPORT_PER_CPU_SYMBOL(kstat);
3292beb3 2662EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
1da177e4
LT
2663
2664/*
c5f8d995 2665 * Return any ns on the sched_clock that have not yet been accounted in
f06febc9 2666 * @p in case that task is currently running.
c5f8d995
HS
2667 *
2668 * Called with task_rq_lock() held on @rq.
1da177e4 2669 */
c5f8d995
HS
2670static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
2671{
2672 u64 ns = 0;
2673
2674 if (task_current(rq, p)) {
2675 update_rq_clock(rq);
305e6835 2676 ns = rq->clock_task - p->se.exec_start;
c5f8d995
HS
2677 if ((s64)ns < 0)
2678 ns = 0;
2679 }
2680
2681 return ns;
2682}
2683
bb34d92f 2684unsigned long long task_delta_exec(struct task_struct *p)
1da177e4 2685{
1da177e4 2686 unsigned long flags;
41b86e9c 2687 struct rq *rq;
bb34d92f 2688 u64 ns = 0;
48f24c4d 2689
41b86e9c 2690 rq = task_rq_lock(p, &flags);
c5f8d995 2691 ns = do_task_delta_exec(p, rq);
0122ec5b 2692 task_rq_unlock(rq, p, &flags);
1508487e 2693
c5f8d995
HS
2694 return ns;
2695}
f06febc9 2696
c5f8d995
HS
2697/*
2698 * Return accounted runtime for the task.
2699 * In case the task is currently running, return the runtime plus current's
2700 * pending runtime that have not been accounted yet.
2701 */
2702unsigned long long task_sched_runtime(struct task_struct *p)
2703{
2704 unsigned long flags;
2705 struct rq *rq;
2706 u64 ns = 0;
2707
2708 rq = task_rq_lock(p, &flags);
2709 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
0122ec5b 2710 task_rq_unlock(rq, p, &flags);
c5f8d995
HS
2711
2712 return ns;
2713}
48f24c4d 2714
7835b98b
CL
2715/*
2716 * This function gets called by the timer code, with HZ frequency.
2717 * We call it with interrupts disabled.
7835b98b
CL
2718 */
2719void scheduler_tick(void)
2720{
7835b98b
CL
2721 int cpu = smp_processor_id();
2722 struct rq *rq = cpu_rq(cpu);
dd41f596 2723 struct task_struct *curr = rq->curr;
3e51f33f
PZ
2724
2725 sched_clock_tick();
dd41f596 2726
05fa785c 2727 raw_spin_lock(&rq->lock);
3e51f33f 2728 update_rq_clock(rq);
fdf3e95d 2729 update_cpu_load_active(rq);
fa85ae24 2730 curr->sched_class->task_tick(rq, curr, 0);
05fa785c 2731 raw_spin_unlock(&rq->lock);
7835b98b 2732
e9d2b064 2733 perf_event_task_tick();
e220d2dc 2734
e418e1c2 2735#ifdef CONFIG_SMP
6eb57e0d 2736 rq->idle_balance = idle_cpu(cpu);
dd41f596 2737 trigger_load_balance(rq, cpu);
e418e1c2 2738#endif
1da177e4
LT
2739}
2740
132380a0 2741notrace unsigned long get_parent_ip(unsigned long addr)
6cd8a4bb
SR
2742{
2743 if (in_lock_functions(addr)) {
2744 addr = CALLER_ADDR2;
2745 if (in_lock_functions(addr))
2746 addr = CALLER_ADDR3;
2747 }
2748 return addr;
2749}
1da177e4 2750
7e49fcce
SR
2751#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
2752 defined(CONFIG_PREEMPT_TRACER))
2753
43627582 2754void __kprobes add_preempt_count(int val)
1da177e4 2755{
6cd8a4bb 2756#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
2757 /*
2758 * Underflow?
2759 */
9a11b49a
IM
2760 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
2761 return;
6cd8a4bb 2762#endif
1da177e4 2763 preempt_count() += val;
6cd8a4bb 2764#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
2765 /*
2766 * Spinlock count overflowing soon?
2767 */
33859f7f
MOS
2768 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
2769 PREEMPT_MASK - 10);
6cd8a4bb
SR
2770#endif
2771 if (preempt_count() == val)
2772 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
1da177e4
LT
2773}
2774EXPORT_SYMBOL(add_preempt_count);
2775
43627582 2776void __kprobes sub_preempt_count(int val)
1da177e4 2777{
6cd8a4bb 2778#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
2779 /*
2780 * Underflow?
2781 */
01e3eb82 2782 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
9a11b49a 2783 return;
1da177e4
LT
2784 /*
2785 * Is the spinlock portion underflowing?
2786 */
9a11b49a
IM
2787 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
2788 !(preempt_count() & PREEMPT_MASK)))
2789 return;
6cd8a4bb 2790#endif
9a11b49a 2791
6cd8a4bb
SR
2792 if (preempt_count() == val)
2793 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
1da177e4
LT
2794 preempt_count() -= val;
2795}
2796EXPORT_SYMBOL(sub_preempt_count);
2797
2798#endif
2799
2800/*
dd41f596 2801 * Print scheduling while atomic bug:
1da177e4 2802 */
dd41f596 2803static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 2804{
664dfa65
DJ
2805 if (oops_in_progress)
2806 return;
2807
3df0fc5b
PZ
2808 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
2809 prev->comm, prev->pid, preempt_count());
838225b4 2810
dd41f596 2811 debug_show_held_locks(prev);
e21f5b15 2812 print_modules();
dd41f596
IM
2813 if (irqs_disabled())
2814 print_irqtrace_events(prev);
6135fc1e 2815 dump_stack();
373d4d09 2816 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
dd41f596 2817}
1da177e4 2818
dd41f596
IM
2819/*
2820 * Various schedule()-time debugging checks and statistics:
2821 */
2822static inline void schedule_debug(struct task_struct *prev)
2823{
1da177e4 2824 /*
41a2d6cf 2825 * Test if we are atomic. Since do_exit() needs to call into
1da177e4
LT
2826 * schedule() atomically, we ignore that path for now.
2827 * Otherwise, whine if we are scheduling when we should not be.
2828 */
3f33a7ce 2829 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
dd41f596 2830 __schedule_bug(prev);
b3fbab05 2831 rcu_sleep_check();
dd41f596 2832
1da177e4
LT
2833 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2834
2d72376b 2835 schedstat_inc(this_rq(), sched_count);
dd41f596
IM
2836}
2837
6cecd084 2838static void put_prev_task(struct rq *rq, struct task_struct *prev)
df1c99d4 2839{
61eadef6 2840 if (prev->on_rq || rq->skip_clock_update < 0)
a64692a3 2841 update_rq_clock(rq);
6cecd084 2842 prev->sched_class->put_prev_task(rq, prev);
df1c99d4
MG
2843}
2844
dd41f596
IM
2845/*
2846 * Pick up the highest-prio task:
2847 */
2848static inline struct task_struct *
b67802ea 2849pick_next_task(struct rq *rq)
dd41f596 2850{
5522d5d5 2851 const struct sched_class *class;
dd41f596 2852 struct task_struct *p;
1da177e4
LT
2853
2854 /*
dd41f596
IM
2855 * Optimization: we know that if all tasks are in
2856 * the fair class we can call that function directly:
1da177e4 2857 */
953bfcd1 2858 if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
fb8d4724 2859 p = fair_sched_class.pick_next_task(rq);
dd41f596
IM
2860 if (likely(p))
2861 return p;
1da177e4
LT
2862 }
2863
34f971f6 2864 for_each_class(class) {
fb8d4724 2865 p = class->pick_next_task(rq);
dd41f596
IM
2866 if (p)
2867 return p;
dd41f596 2868 }
34f971f6
PZ
2869
2870 BUG(); /* the idle class will always have a runnable task */
dd41f596 2871}
1da177e4 2872
dd41f596 2873/*
c259e01a 2874 * __schedule() is the main scheduler function.
edde96ea
PE
2875 *
2876 * The main means of driving the scheduler and thus entering this function are:
2877 *
2878 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
2879 *
2880 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
2881 * paths. For example, see arch/x86/entry_64.S.
2882 *
2883 * To drive preemption between tasks, the scheduler sets the flag in timer
2884 * interrupt handler scheduler_tick().
2885 *
2886 * 3. Wakeups don't really cause entry into schedule(). They add a
2887 * task to the run-queue and that's it.
2888 *
2889 * Now, if the new task added to the run-queue preempts the current
2890 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
2891 * called on the nearest possible occasion:
2892 *
2893 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
2894 *
2895 * - in syscall or exception context, at the next outmost
2896 * preempt_enable(). (this might be as soon as the wake_up()'s
2897 * spin_unlock()!)
2898 *
2899 * - in IRQ context, return from interrupt-handler to
2900 * preemptible context
2901 *
2902 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
2903 * then at the next:
2904 *
2905 * - cond_resched() call
2906 * - explicit schedule() call
2907 * - return from syscall or exception to user-space
2908 * - return from interrupt-handler to user-space
dd41f596 2909 */
c259e01a 2910static void __sched __schedule(void)
dd41f596
IM
2911{
2912 struct task_struct *prev, *next;
67ca7bde 2913 unsigned long *switch_count;
dd41f596 2914 struct rq *rq;
31656519 2915 int cpu;
dd41f596 2916
ff743345
PZ
2917need_resched:
2918 preempt_disable();
dd41f596
IM
2919 cpu = smp_processor_id();
2920 rq = cpu_rq(cpu);
25502a6c 2921 rcu_note_context_switch(cpu);
dd41f596 2922 prev = rq->curr;
dd41f596 2923
dd41f596 2924 schedule_debug(prev);
1da177e4 2925
31656519 2926 if (sched_feat(HRTICK))
f333fdc9 2927 hrtick_clear(rq);
8f4d37ec 2928
05fa785c 2929 raw_spin_lock_irq(&rq->lock);
1da177e4 2930
246d86b5 2931 switch_count = &prev->nivcsw;
1da177e4 2932 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
21aa9af0 2933 if (unlikely(signal_pending_state(prev->state, prev))) {
1da177e4 2934 prev->state = TASK_RUNNING;
21aa9af0 2935 } else {
2acca55e
PZ
2936 deactivate_task(rq, prev, DEQUEUE_SLEEP);
2937 prev->on_rq = 0;
2938
21aa9af0 2939 /*
2acca55e
PZ
2940 * If a worker went to sleep, notify and ask workqueue
2941 * whether it wants to wake up a task to maintain
2942 * concurrency.
21aa9af0
TH
2943 */
2944 if (prev->flags & PF_WQ_WORKER) {
2945 struct task_struct *to_wakeup;
2946
2947 to_wakeup = wq_worker_sleeping(prev, cpu);
2948 if (to_wakeup)
2949 try_to_wake_up_local(to_wakeup);
2950 }
21aa9af0 2951 }
dd41f596 2952 switch_count = &prev->nvcsw;
1da177e4
LT
2953 }
2954
3f029d3c 2955 pre_schedule(rq, prev);
f65eda4f 2956
dd41f596 2957 if (unlikely(!rq->nr_running))
1da177e4 2958 idle_balance(cpu, rq);
1da177e4 2959
df1c99d4 2960 put_prev_task(rq, prev);
b67802ea 2961 next = pick_next_task(rq);
f26f9aff
MG
2962 clear_tsk_need_resched(prev);
2963 rq->skip_clock_update = 0;
1da177e4 2964
1da177e4 2965 if (likely(prev != next)) {
1da177e4
LT
2966 rq->nr_switches++;
2967 rq->curr = next;
2968 ++*switch_count;
2969
dd41f596 2970 context_switch(rq, prev, next); /* unlocks the rq */
8f4d37ec 2971 /*
246d86b5
ON
2972 * The context switch have flipped the stack from under us
2973 * and restored the local variables which were saved when
2974 * this task called schedule() in the past. prev == current
2975 * is still correct, but it can be moved to another cpu/rq.
8f4d37ec
PZ
2976 */
2977 cpu = smp_processor_id();
2978 rq = cpu_rq(cpu);
1da177e4 2979 } else
05fa785c 2980 raw_spin_unlock_irq(&rq->lock);
1da177e4 2981
3f029d3c 2982 post_schedule(rq);
1da177e4 2983
ba74c144 2984 sched_preempt_enable_no_resched();
ff743345 2985 if (need_resched())
1da177e4
LT
2986 goto need_resched;
2987}
c259e01a 2988
9c40cef2
TG
2989static inline void sched_submit_work(struct task_struct *tsk)
2990{
3c7d5184 2991 if (!tsk->state || tsk_is_pi_blocked(tsk))
9c40cef2
TG
2992 return;
2993 /*
2994 * If we are going to sleep and we have plugged IO queued,
2995 * make sure to submit it to avoid deadlocks.
2996 */
2997 if (blk_needs_flush_plug(tsk))
2998 blk_schedule_flush_plug(tsk);
2999}
3000
6ebbe7a0 3001asmlinkage void __sched schedule(void)
c259e01a 3002{
9c40cef2
TG
3003 struct task_struct *tsk = current;
3004
3005 sched_submit_work(tsk);
c259e01a
TG
3006 __schedule();
3007}
1da177e4
LT
3008EXPORT_SYMBOL(schedule);
3009
91d1aa43 3010#ifdef CONFIG_CONTEXT_TRACKING
20ab65e3
FW
3011asmlinkage void __sched schedule_user(void)
3012{
3013 /*
3014 * If we come here after a random call to set_need_resched(),
3015 * or we have been woken up remotely but the IPI has not yet arrived,
3016 * we haven't yet exited the RCU idle mode. Do it here manually until
3017 * we find a better solution.
3018 */
91d1aa43 3019 user_exit();
20ab65e3 3020 schedule();
91d1aa43 3021 user_enter();
20ab65e3
FW
3022}
3023#endif
3024
c5491ea7
TG
3025/**
3026 * schedule_preempt_disabled - called with preemption disabled
3027 *
3028 * Returns with preemption disabled. Note: preempt_count must be 1
3029 */
3030void __sched schedule_preempt_disabled(void)
3031{
ba74c144 3032 sched_preempt_enable_no_resched();
c5491ea7
TG
3033 schedule();
3034 preempt_disable();
3035}
3036
1da177e4
LT
3037#ifdef CONFIG_PREEMPT
3038/*
2ed6e34f 3039 * this is the entry point to schedule() from in-kernel preemption
41a2d6cf 3040 * off of preempt_enable. Kernel preemptions off return from interrupt
1da177e4
LT
3041 * occur there and call schedule directly.
3042 */
d1f74e20 3043asmlinkage void __sched notrace preempt_schedule(void)
1da177e4
LT
3044{
3045 struct thread_info *ti = current_thread_info();
6478d880 3046
1da177e4
LT
3047 /*
3048 * If there is a non-zero preempt_count or interrupts are disabled,
41a2d6cf 3049 * we do not want to preempt the current task. Just return..
1da177e4 3050 */
beed33a8 3051 if (likely(ti->preempt_count || irqs_disabled()))
1da177e4
LT
3052 return;
3053
3a5c359a 3054 do {
d1f74e20 3055 add_preempt_count_notrace(PREEMPT_ACTIVE);
c259e01a 3056 __schedule();
d1f74e20 3057 sub_preempt_count_notrace(PREEMPT_ACTIVE);
1da177e4 3058
3a5c359a
AK
3059 /*
3060 * Check again in case we missed a preemption opportunity
3061 * between schedule and now.
3062 */
3063 barrier();
5ed0cec0 3064 } while (need_resched());
1da177e4 3065}
1da177e4
LT
3066EXPORT_SYMBOL(preempt_schedule);
3067
3068/*
2ed6e34f 3069 * this is the entry point to schedule() from kernel preemption
1da177e4
LT
3070 * off of irq context.
3071 * Note, that this is called and return with irqs disabled. This will
3072 * protect us against recursive calling from irq.
3073 */
3074asmlinkage void __sched preempt_schedule_irq(void)
3075{
3076 struct thread_info *ti = current_thread_info();
b22366cd 3077 enum ctx_state prev_state;
6478d880 3078
2ed6e34f 3079 /* Catch callers which need to be fixed */
1da177e4
LT
3080 BUG_ON(ti->preempt_count || !irqs_disabled());
3081
b22366cd
FW
3082 prev_state = exception_enter();
3083
3a5c359a
AK
3084 do {
3085 add_preempt_count(PREEMPT_ACTIVE);
3a5c359a 3086 local_irq_enable();
c259e01a 3087 __schedule();
3a5c359a 3088 local_irq_disable();
3a5c359a 3089 sub_preempt_count(PREEMPT_ACTIVE);
1da177e4 3090
3a5c359a
AK
3091 /*
3092 * Check again in case we missed a preemption opportunity
3093 * between schedule and now.
3094 */
3095 barrier();
5ed0cec0 3096 } while (need_resched());
b22366cd
FW
3097
3098 exception_exit(prev_state);
1da177e4
LT
3099}
3100
3101#endif /* CONFIG_PREEMPT */
3102
63859d4f 3103int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
95cdf3b7 3104 void *key)
1da177e4 3105{
63859d4f 3106 return try_to_wake_up(curr->private, mode, wake_flags);
1da177e4 3107}
1da177e4
LT
3108EXPORT_SYMBOL(default_wake_function);
3109
3110/*
41a2d6cf
IM
3111 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3112 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
1da177e4
LT
3113 * number) then we wake all the non-exclusive tasks and one exclusive task.
3114 *
3115 * There are circumstances in which we can try to wake a task which has already
41a2d6cf 3116 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
1da177e4
LT
3117 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3118 */
78ddb08f 3119static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
63859d4f 3120 int nr_exclusive, int wake_flags, void *key)
1da177e4 3121{
2e45874c 3122 wait_queue_t *curr, *next;
1da177e4 3123
2e45874c 3124 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
48f24c4d
IM
3125 unsigned flags = curr->flags;
3126
63859d4f 3127 if (curr->func(curr, mode, wake_flags, key) &&
48f24c4d 3128 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
1da177e4
LT
3129 break;
3130 }
3131}
3132
3133/**
3134 * __wake_up - wake up threads blocked on a waitqueue.
3135 * @q: the waitqueue
3136 * @mode: which threads
3137 * @nr_exclusive: how many wake-one or wake-many threads to wake up
67be2dd1 3138 * @key: is directly passed to the wakeup function
50fa610a
DH
3139 *
3140 * It may be assumed that this function implies a write memory barrier before
3141 * changing the task state if and only if any tasks are woken up.
1da177e4 3142 */
7ad5b3a5 3143void __wake_up(wait_queue_head_t *q, unsigned int mode,
95cdf3b7 3144 int nr_exclusive, void *key)
1da177e4
LT
3145{
3146 unsigned long flags;
3147
3148 spin_lock_irqsave(&q->lock, flags);
3149 __wake_up_common(q, mode, nr_exclusive, 0, key);
3150 spin_unlock_irqrestore(&q->lock, flags);
3151}
1da177e4
LT
3152EXPORT_SYMBOL(__wake_up);
3153
3154/*
3155 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3156 */
63b20011 3157void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr)
1da177e4 3158{
63b20011 3159 __wake_up_common(q, mode, nr, 0, NULL);
1da177e4 3160}
22c43c81 3161EXPORT_SYMBOL_GPL(__wake_up_locked);
1da177e4 3162
4ede816a
DL
3163void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
3164{
3165 __wake_up_common(q, mode, 1, 0, key);
3166}
bf294b41 3167EXPORT_SYMBOL_GPL(__wake_up_locked_key);
4ede816a 3168
1da177e4 3169/**
4ede816a 3170 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
1da177e4
LT
3171 * @q: the waitqueue
3172 * @mode: which threads
3173 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4ede816a 3174 * @key: opaque value to be passed to wakeup targets
1da177e4
LT
3175 *
3176 * The sync wakeup differs that the waker knows that it will schedule
3177 * away soon, so while the target thread will be woken up, it will not
3178 * be migrated to another CPU - ie. the two threads are 'synchronized'
3179 * with each other. This can prevent needless bouncing between CPUs.
3180 *
3181 * On UP it can prevent extra preemption.
50fa610a
DH
3182 *
3183 * It may be assumed that this function implies a write memory barrier before
3184 * changing the task state if and only if any tasks are woken up.
1da177e4 3185 */
4ede816a
DL
3186void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
3187 int nr_exclusive, void *key)
1da177e4
LT
3188{
3189 unsigned long flags;
7d478721 3190 int wake_flags = WF_SYNC;
1da177e4
LT
3191
3192 if (unlikely(!q))
3193 return;
3194
3195 if (unlikely(!nr_exclusive))
7d478721 3196 wake_flags = 0;
1da177e4
LT
3197
3198 spin_lock_irqsave(&q->lock, flags);
7d478721 3199 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
1da177e4
LT
3200 spin_unlock_irqrestore(&q->lock, flags);
3201}
4ede816a
DL
3202EXPORT_SYMBOL_GPL(__wake_up_sync_key);
3203
3204/*
3205 * __wake_up_sync - see __wake_up_sync_key()
3206 */
3207void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3208{
3209 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
3210}
1da177e4
LT
3211EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3212
65eb3dc6
KD
3213/**
3214 * complete: - signals a single thread waiting on this completion
3215 * @x: holds the state of this particular completion
3216 *
3217 * This will wake up a single thread waiting on this completion. Threads will be
3218 * awakened in the same order in which they were queued.
3219 *
3220 * See also complete_all(), wait_for_completion() and related routines.
50fa610a
DH
3221 *
3222 * It may be assumed that this function implies a write memory barrier before
3223 * changing the task state if and only if any tasks are woken up.
65eb3dc6 3224 */
b15136e9 3225void complete(struct completion *x)
1da177e4
LT
3226{
3227 unsigned long flags;
3228
3229 spin_lock_irqsave(&x->wait.lock, flags);
3230 x->done++;
d9514f6c 3231 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
1da177e4
LT
3232 spin_unlock_irqrestore(&x->wait.lock, flags);
3233}
3234EXPORT_SYMBOL(complete);
3235
65eb3dc6
KD
3236/**
3237 * complete_all: - signals all threads waiting on this completion
3238 * @x: holds the state of this particular completion
3239 *
3240 * This will wake up all threads waiting on this particular completion event.
50fa610a
DH
3241 *
3242 * It may be assumed that this function implies a write memory barrier before
3243 * changing the task state if and only if any tasks are woken up.
65eb3dc6 3244 */
b15136e9 3245void complete_all(struct completion *x)
1da177e4
LT
3246{
3247 unsigned long flags;
3248
3249 spin_lock_irqsave(&x->wait.lock, flags);
3250 x->done += UINT_MAX/2;
d9514f6c 3251 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
1da177e4
LT
3252 spin_unlock_irqrestore(&x->wait.lock, flags);
3253}
3254EXPORT_SYMBOL(complete_all);
3255
8cbbe86d 3256static inline long __sched
686855f5
VD
3257do_wait_for_common(struct completion *x,
3258 long (*action)(long), long timeout, int state)
1da177e4 3259{
1da177e4
LT
3260 if (!x->done) {
3261 DECLARE_WAITQUEUE(wait, current);
3262
a93d2f17 3263 __add_wait_queue_tail_exclusive(&x->wait, &wait);
1da177e4 3264 do {
94d3d824 3265 if (signal_pending_state(state, current)) {
ea71a546
ON
3266 timeout = -ERESTARTSYS;
3267 break;
8cbbe86d
AK
3268 }
3269 __set_current_state(state);
1da177e4 3270 spin_unlock_irq(&x->wait.lock);
686855f5 3271 timeout = action(timeout);
1da177e4 3272 spin_lock_irq(&x->wait.lock);
ea71a546 3273 } while (!x->done && timeout);
1da177e4 3274 __remove_wait_queue(&x->wait, &wait);
ea71a546
ON
3275 if (!x->done)
3276 return timeout;
1da177e4
LT
3277 }
3278 x->done--;
ea71a546 3279 return timeout ?: 1;
1da177e4 3280}
1da177e4 3281
686855f5
VD
3282static inline long __sched
3283__wait_for_common(struct completion *x,
3284 long (*action)(long), long timeout, int state)
1da177e4 3285{
1da177e4
LT
3286 might_sleep();
3287
3288 spin_lock_irq(&x->wait.lock);
686855f5 3289 timeout = do_wait_for_common(x, action, timeout, state);
1da177e4 3290 spin_unlock_irq(&x->wait.lock);
8cbbe86d
AK
3291 return timeout;
3292}
1da177e4 3293
686855f5
VD
3294static long __sched
3295wait_for_common(struct completion *x, long timeout, int state)
3296{
3297 return __wait_for_common(x, schedule_timeout, timeout, state);
3298}
3299
3300static long __sched
3301wait_for_common_io(struct completion *x, long timeout, int state)
3302{
3303 return __wait_for_common(x, io_schedule_timeout, timeout, state);
3304}
3305
65eb3dc6
KD
3306/**
3307 * wait_for_completion: - waits for completion of a task
3308 * @x: holds the state of this particular completion
3309 *
3310 * This waits to be signaled for completion of a specific task. It is NOT
3311 * interruptible and there is no timeout.
3312 *
3313 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
3314 * and interrupt capability. Also see complete().
3315 */
b15136e9 3316void __sched wait_for_completion(struct completion *x)
8cbbe86d
AK
3317{
3318 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
1da177e4 3319}
8cbbe86d 3320EXPORT_SYMBOL(wait_for_completion);
1da177e4 3321
65eb3dc6
KD
3322/**
3323 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
3324 * @x: holds the state of this particular completion
3325 * @timeout: timeout value in jiffies
3326 *
3327 * This waits for either a completion of a specific task to be signaled or for a
3328 * specified timeout to expire. The timeout is in jiffies. It is not
3329 * interruptible.
c6dc7f05
BF
3330 *
3331 * The return value is 0 if timed out, and positive (at least 1, or number of
3332 * jiffies left till timeout) if completed.
65eb3dc6 3333 */
b15136e9 3334unsigned long __sched
8cbbe86d 3335wait_for_completion_timeout(struct completion *x, unsigned long timeout)
1da177e4 3336{
8cbbe86d 3337 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
1da177e4 3338}
8cbbe86d 3339EXPORT_SYMBOL(wait_for_completion_timeout);
1da177e4 3340
686855f5
VD
3341/**
3342 * wait_for_completion_io: - waits for completion of a task
3343 * @x: holds the state of this particular completion
3344 *
3345 * This waits to be signaled for completion of a specific task. It is NOT
3346 * interruptible and there is no timeout. The caller is accounted as waiting
3347 * for IO.
3348 */
3349void __sched wait_for_completion_io(struct completion *x)
3350{
3351 wait_for_common_io(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
3352}
3353EXPORT_SYMBOL(wait_for_completion_io);
3354
3355/**
3356 * wait_for_completion_io_timeout: - waits for completion of a task (w/timeout)
3357 * @x: holds the state of this particular completion
3358 * @timeout: timeout value in jiffies
3359 *
3360 * This waits for either a completion of a specific task to be signaled or for a
3361 * specified timeout to expire. The timeout is in jiffies. It is not
3362 * interruptible. The caller is accounted as waiting for IO.
3363 *
3364 * The return value is 0 if timed out, and positive (at least 1, or number of
3365 * jiffies left till timeout) if completed.
3366 */
3367unsigned long __sched
3368wait_for_completion_io_timeout(struct completion *x, unsigned long timeout)
3369{
3370 return wait_for_common_io(x, timeout, TASK_UNINTERRUPTIBLE);
3371}
3372EXPORT_SYMBOL(wait_for_completion_io_timeout);
3373
65eb3dc6
KD
3374/**
3375 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
3376 * @x: holds the state of this particular completion
3377 *
3378 * This waits for completion of a specific task to be signaled. It is
3379 * interruptible.
c6dc7f05
BF
3380 *
3381 * The return value is -ERESTARTSYS if interrupted, 0 if completed.
65eb3dc6 3382 */
8cbbe86d 3383int __sched wait_for_completion_interruptible(struct completion *x)
0fec171c 3384{
51e97990
AK
3385 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
3386 if (t == -ERESTARTSYS)
3387 return t;
3388 return 0;
0fec171c 3389}
8cbbe86d 3390EXPORT_SYMBOL(wait_for_completion_interruptible);
1da177e4 3391
65eb3dc6
KD
3392/**
3393 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
3394 * @x: holds the state of this particular completion
3395 * @timeout: timeout value in jiffies
3396 *
3397 * This waits for either a completion of a specific task to be signaled or for a
3398 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
c6dc7f05
BF
3399 *
3400 * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3401 * positive (at least 1, or number of jiffies left till timeout) if completed.
65eb3dc6 3402 */
6bf41237 3403long __sched
8cbbe86d
AK
3404wait_for_completion_interruptible_timeout(struct completion *x,
3405 unsigned long timeout)
0fec171c 3406{
8cbbe86d 3407 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
0fec171c 3408}
8cbbe86d 3409EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
1da177e4 3410
65eb3dc6
KD
3411/**
3412 * wait_for_completion_killable: - waits for completion of a task (killable)
3413 * @x: holds the state of this particular completion
3414 *
3415 * This waits to be signaled for completion of a specific task. It can be
3416 * interrupted by a kill signal.
c6dc7f05
BF
3417 *
3418 * The return value is -ERESTARTSYS if interrupted, 0 if completed.
65eb3dc6 3419 */
009e577e
MW
3420int __sched wait_for_completion_killable(struct completion *x)
3421{
3422 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
3423 if (t == -ERESTARTSYS)
3424 return t;
3425 return 0;
3426}
3427EXPORT_SYMBOL(wait_for_completion_killable);
3428
0aa12fb4
SW
3429/**
3430 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
3431 * @x: holds the state of this particular completion
3432 * @timeout: timeout value in jiffies
3433 *
3434 * This waits for either a completion of a specific task to be
3435 * signaled or for a specified timeout to expire. It can be
3436 * interrupted by a kill signal. The timeout is in jiffies.
c6dc7f05
BF
3437 *
3438 * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3439 * positive (at least 1, or number of jiffies left till timeout) if completed.
0aa12fb4 3440 */
6bf41237 3441long __sched
0aa12fb4
SW
3442wait_for_completion_killable_timeout(struct completion *x,
3443 unsigned long timeout)
3444{
3445 return wait_for_common(x, timeout, TASK_KILLABLE);
3446}
3447EXPORT_SYMBOL(wait_for_completion_killable_timeout);
3448
be4de352
DC
3449/**
3450 * try_wait_for_completion - try to decrement a completion without blocking
3451 * @x: completion structure
3452 *
3453 * Returns: 0 if a decrement cannot be done without blocking
3454 * 1 if a decrement succeeded.
3455 *
3456 * If a completion is being used as a counting completion,
3457 * attempt to decrement the counter without blocking. This
3458 * enables us to avoid waiting if the resource the completion
3459 * is protecting is not available.
3460 */
3461bool try_wait_for_completion(struct completion *x)
3462{
7539a3b3 3463 unsigned long flags;
be4de352
DC
3464 int ret = 1;
3465
7539a3b3 3466 spin_lock_irqsave(&x->wait.lock, flags);
be4de352
DC
3467 if (!x->done)
3468 ret = 0;
3469 else
3470 x->done--;
7539a3b3 3471 spin_unlock_irqrestore(&x->wait.lock, flags);
be4de352
DC
3472 return ret;
3473}
3474EXPORT_SYMBOL(try_wait_for_completion);
3475
3476/**
3477 * completion_done - Test to see if a completion has any waiters
3478 * @x: completion structure
3479 *
3480 * Returns: 0 if there are waiters (wait_for_completion() in progress)
3481 * 1 if there are no waiters.
3482 *
3483 */
3484bool completion_done(struct completion *x)
3485{
7539a3b3 3486 unsigned long flags;
be4de352
DC
3487 int ret = 1;
3488
7539a3b3 3489 spin_lock_irqsave(&x->wait.lock, flags);
be4de352
DC
3490 if (!x->done)
3491 ret = 0;
7539a3b3 3492 spin_unlock_irqrestore(&x->wait.lock, flags);
be4de352
DC
3493 return ret;
3494}
3495EXPORT_SYMBOL(completion_done);
3496
8cbbe86d
AK
3497static long __sched
3498sleep_on_common(wait_queue_head_t *q, int state, long timeout)
1da177e4 3499{
0fec171c
IM
3500 unsigned long flags;
3501 wait_queue_t wait;
3502
3503 init_waitqueue_entry(&wait, current);
1da177e4 3504
8cbbe86d 3505 __set_current_state(state);
1da177e4 3506
8cbbe86d
AK
3507 spin_lock_irqsave(&q->lock, flags);
3508 __add_wait_queue(q, &wait);
3509 spin_unlock(&q->lock);
3510 timeout = schedule_timeout(timeout);
3511 spin_lock_irq(&q->lock);
3512 __remove_wait_queue(q, &wait);
3513 spin_unlock_irqrestore(&q->lock, flags);
3514
3515 return timeout;
3516}
3517
3518void __sched interruptible_sleep_on(wait_queue_head_t *q)
3519{
3520 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
1da177e4 3521}
1da177e4
LT
3522EXPORT_SYMBOL(interruptible_sleep_on);
3523
0fec171c 3524long __sched
95cdf3b7 3525interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3526{
8cbbe86d 3527 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
1da177e4 3528}
1da177e4
LT
3529EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3530
0fec171c 3531void __sched sleep_on(wait_queue_head_t *q)
1da177e4 3532{
8cbbe86d 3533 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
1da177e4 3534}
1da177e4
LT
3535EXPORT_SYMBOL(sleep_on);
3536
0fec171c 3537long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3538{
8cbbe86d 3539 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
1da177e4 3540}
1da177e4
LT
3541EXPORT_SYMBOL(sleep_on_timeout);
3542
b29739f9
IM
3543#ifdef CONFIG_RT_MUTEXES
3544
3545/*
3546 * rt_mutex_setprio - set the current priority of a task
3547 * @p: task
3548 * @prio: prio value (kernel-internal form)
3549 *
3550 * This function changes the 'effective' priority of a task. It does
3551 * not touch ->normal_prio like __setscheduler().
3552 *
3553 * Used by the rt_mutex code to implement priority inheritance logic.
3554 */
36c8b586 3555void rt_mutex_setprio(struct task_struct *p, int prio)
b29739f9 3556{
83b699ed 3557 int oldprio, on_rq, running;
70b97a7f 3558 struct rq *rq;
83ab0aa0 3559 const struct sched_class *prev_class;
b29739f9
IM
3560
3561 BUG_ON(prio < 0 || prio > MAX_PRIO);
3562
0122ec5b 3563 rq = __task_rq_lock(p);
b29739f9 3564
1c4dd99b
TG
3565 /*
3566 * Idle task boosting is a nono in general. There is one
3567 * exception, when PREEMPT_RT and NOHZ is active:
3568 *
3569 * The idle task calls get_next_timer_interrupt() and holds
3570 * the timer wheel base->lock on the CPU and another CPU wants
3571 * to access the timer (probably to cancel it). We can safely
3572 * ignore the boosting request, as the idle CPU runs this code
3573 * with interrupts disabled and will complete the lock
3574 * protected section without being interrupted. So there is no
3575 * real need to boost.
3576 */
3577 if (unlikely(p == rq->idle)) {
3578 WARN_ON(p != rq->curr);
3579 WARN_ON(p->pi_blocked_on);
3580 goto out_unlock;
3581 }
3582
a8027073 3583 trace_sched_pi_setprio(p, prio);
d5f9f942 3584 oldprio = p->prio;
83ab0aa0 3585 prev_class = p->sched_class;
fd2f4419 3586 on_rq = p->on_rq;
051a1d1a 3587 running = task_current(rq, p);
0e1f3483 3588 if (on_rq)
69be72c1 3589 dequeue_task(rq, p, 0);
0e1f3483
HS
3590 if (running)
3591 p->sched_class->put_prev_task(rq, p);
dd41f596
IM
3592
3593 if (rt_prio(prio))
3594 p->sched_class = &rt_sched_class;
3595 else
3596 p->sched_class = &fair_sched_class;
3597
b29739f9
IM
3598 p->prio = prio;
3599
0e1f3483
HS
3600 if (running)
3601 p->sched_class->set_curr_task(rq);
da7a735e 3602 if (on_rq)
371fd7e7 3603 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
cb469845 3604
da7a735e 3605 check_class_changed(rq, p, prev_class, oldprio);
1c4dd99b 3606out_unlock:
0122ec5b 3607 __task_rq_unlock(rq);
b29739f9 3608}
b29739f9 3609#endif
36c8b586 3610void set_user_nice(struct task_struct *p, long nice)
1da177e4 3611{
dd41f596 3612 int old_prio, delta, on_rq;
1da177e4 3613 unsigned long flags;
70b97a7f 3614 struct rq *rq;
1da177e4
LT
3615
3616 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3617 return;
3618 /*
3619 * We have to be careful, if called from sys_setpriority(),
3620 * the task might be in the middle of scheduling on another CPU.
3621 */
3622 rq = task_rq_lock(p, &flags);
3623 /*
3624 * The RT priorities are set via sched_setscheduler(), but we still
3625 * allow the 'normal' nice value to be set - but as expected
3626 * it wont have any effect on scheduling until the task is
dd41f596 3627 * SCHED_FIFO/SCHED_RR:
1da177e4 3628 */
e05606d3 3629 if (task_has_rt_policy(p)) {
1da177e4
LT
3630 p->static_prio = NICE_TO_PRIO(nice);
3631 goto out_unlock;
3632 }
fd2f4419 3633 on_rq = p->on_rq;
c09595f6 3634 if (on_rq)
69be72c1 3635 dequeue_task(rq, p, 0);
1da177e4 3636
1da177e4 3637 p->static_prio = NICE_TO_PRIO(nice);
2dd73a4f 3638 set_load_weight(p);
b29739f9
IM
3639 old_prio = p->prio;
3640 p->prio = effective_prio(p);
3641 delta = p->prio - old_prio;
1da177e4 3642
dd41f596 3643 if (on_rq) {
371fd7e7 3644 enqueue_task(rq, p, 0);
1da177e4 3645 /*
d5f9f942
AM
3646 * If the task increased its priority or is running and
3647 * lowered its priority, then reschedule its CPU:
1da177e4 3648 */
d5f9f942 3649 if (delta < 0 || (delta > 0 && task_running(rq, p)))
1da177e4
LT
3650 resched_task(rq->curr);
3651 }
3652out_unlock:
0122ec5b 3653 task_rq_unlock(rq, p, &flags);
1da177e4 3654}
1da177e4
LT
3655EXPORT_SYMBOL(set_user_nice);
3656
e43379f1
MM
3657/*
3658 * can_nice - check if a task can reduce its nice value
3659 * @p: task
3660 * @nice: nice value
3661 */
36c8b586 3662int can_nice(const struct task_struct *p, const int nice)
e43379f1 3663{
024f4747
MM
3664 /* convert nice value [19,-20] to rlimit style value [1,40] */
3665 int nice_rlim = 20 - nice;
48f24c4d 3666
78d7d407 3667 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
e43379f1
MM
3668 capable(CAP_SYS_NICE));
3669}
3670
1da177e4
LT
3671#ifdef __ARCH_WANT_SYS_NICE
3672
3673/*
3674 * sys_nice - change the priority of the current process.
3675 * @increment: priority increment
3676 *
3677 * sys_setpriority is a more generic, but much slower function that
3678 * does similar things.
3679 */
5add95d4 3680SYSCALL_DEFINE1(nice, int, increment)
1da177e4 3681{
48f24c4d 3682 long nice, retval;
1da177e4
LT
3683
3684 /*
3685 * Setpriority might change our priority at the same moment.
3686 * We don't have to worry. Conceptually one call occurs first
3687 * and we have a single winner.
3688 */
e43379f1
MM
3689 if (increment < -40)
3690 increment = -40;
1da177e4
LT
3691 if (increment > 40)
3692 increment = 40;
3693
2b8f836f 3694 nice = TASK_NICE(current) + increment;
1da177e4
LT
3695 if (nice < -20)
3696 nice = -20;
3697 if (nice > 19)
3698 nice = 19;
3699
e43379f1
MM
3700 if (increment < 0 && !can_nice(current, nice))
3701 return -EPERM;
3702
1da177e4
LT
3703 retval = security_task_setnice(current, nice);
3704 if (retval)
3705 return retval;
3706
3707 set_user_nice(current, nice);
3708 return 0;
3709}
3710
3711#endif
3712
3713/**
3714 * task_prio - return the priority value of a given task.
3715 * @p: the task in question.
3716 *
3717 * This is the priority value as seen by users in /proc.
3718 * RT tasks are offset by -200. Normal tasks are centered
3719 * around 0, value goes from -16 to +15.
3720 */
36c8b586 3721int task_prio(const struct task_struct *p)
1da177e4
LT
3722{
3723 return p->prio - MAX_RT_PRIO;
3724}
3725
3726/**
3727 * task_nice - return the nice value of a given task.
3728 * @p: the task in question.
3729 */
36c8b586 3730int task_nice(const struct task_struct *p)
1da177e4
LT
3731{
3732 return TASK_NICE(p);
3733}
150d8bed 3734EXPORT_SYMBOL(task_nice);
1da177e4
LT
3735
3736/**
3737 * idle_cpu - is a given cpu idle currently?
3738 * @cpu: the processor in question.
3739 */
3740int idle_cpu(int cpu)
3741{
908a3283
TG
3742 struct rq *rq = cpu_rq(cpu);
3743
3744 if (rq->curr != rq->idle)
3745 return 0;
3746
3747 if (rq->nr_running)
3748 return 0;
3749
3750#ifdef CONFIG_SMP
3751 if (!llist_empty(&rq->wake_list))
3752 return 0;
3753#endif
3754
3755 return 1;
1da177e4
LT
3756}
3757
1da177e4
LT
3758/**
3759 * idle_task - return the idle task for a given cpu.
3760 * @cpu: the processor in question.
3761 */
36c8b586 3762struct task_struct *idle_task(int cpu)
1da177e4
LT
3763{
3764 return cpu_rq(cpu)->idle;
3765}
3766
3767/**
3768 * find_process_by_pid - find a process with a matching PID value.
3769 * @pid: the pid in question.
3770 */
a9957449 3771static struct task_struct *find_process_by_pid(pid_t pid)
1da177e4 3772{
228ebcbe 3773 return pid ? find_task_by_vpid(pid) : current;
1da177e4
LT
3774}
3775
3776/* Actually do priority change: must hold rq lock. */
dd41f596
IM
3777static void
3778__setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
1da177e4 3779{
1da177e4
LT
3780 p->policy = policy;
3781 p->rt_priority = prio;
b29739f9
IM
3782 p->normal_prio = normal_prio(p);
3783 /* we are holding p->pi_lock already */
3784 p->prio = rt_mutex_getprio(p);
ffd44db5
PZ
3785 if (rt_prio(p->prio))
3786 p->sched_class = &rt_sched_class;
3787 else
3788 p->sched_class = &fair_sched_class;
2dd73a4f 3789 set_load_weight(p);
1da177e4
LT
3790}
3791
c69e8d9c
DH
3792/*
3793 * check the target process has a UID that matches the current process's
3794 */
3795static bool check_same_owner(struct task_struct *p)
3796{
3797 const struct cred *cred = current_cred(), *pcred;
3798 bool match;
3799
3800 rcu_read_lock();
3801 pcred = __task_cred(p);
9c806aa0
EB
3802 match = (uid_eq(cred->euid, pcred->euid) ||
3803 uid_eq(cred->euid, pcred->uid));
c69e8d9c
DH
3804 rcu_read_unlock();
3805 return match;
3806}
3807
961ccddd 3808static int __sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 3809 const struct sched_param *param, bool user)
1da177e4 3810{
83b699ed 3811 int retval, oldprio, oldpolicy = -1, on_rq, running;
1da177e4 3812 unsigned long flags;
83ab0aa0 3813 const struct sched_class *prev_class;
70b97a7f 3814 struct rq *rq;
ca94c442 3815 int reset_on_fork;
1da177e4 3816
66e5393a
SR
3817 /* may grab non-irq protected spin_locks */
3818 BUG_ON(in_interrupt());
1da177e4
LT
3819recheck:
3820 /* double check policy once rq lock held */
ca94c442
LP
3821 if (policy < 0) {
3822 reset_on_fork = p->sched_reset_on_fork;
1da177e4 3823 policy = oldpolicy = p->policy;
ca94c442
LP
3824 } else {
3825 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
3826 policy &= ~SCHED_RESET_ON_FORK;
3827
3828 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3829 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
3830 policy != SCHED_IDLE)
3831 return -EINVAL;
3832 }
3833
1da177e4
LT
3834 /*
3835 * Valid priorities for SCHED_FIFO and SCHED_RR are
dd41f596
IM
3836 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
3837 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4
LT
3838 */
3839 if (param->sched_priority < 0 ||
95cdf3b7 3840 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
d46523ea 3841 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
1da177e4 3842 return -EINVAL;
e05606d3 3843 if (rt_policy(policy) != (param->sched_priority != 0))
1da177e4
LT
3844 return -EINVAL;
3845
37e4ab3f
OC
3846 /*
3847 * Allow unprivileged RT tasks to decrease priority:
3848 */
961ccddd 3849 if (user && !capable(CAP_SYS_NICE)) {
e05606d3 3850 if (rt_policy(policy)) {
a44702e8
ON
3851 unsigned long rlim_rtprio =
3852 task_rlimit(p, RLIMIT_RTPRIO);
8dc3e909
ON
3853
3854 /* can't set/change the rt policy */
3855 if (policy != p->policy && !rlim_rtprio)
3856 return -EPERM;
3857
3858 /* can't increase priority */
3859 if (param->sched_priority > p->rt_priority &&
3860 param->sched_priority > rlim_rtprio)
3861 return -EPERM;
3862 }
c02aa73b 3863
dd41f596 3864 /*
c02aa73b
DH
3865 * Treat SCHED_IDLE as nice 20. Only allow a switch to
3866 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
dd41f596 3867 */
c02aa73b
DH
3868 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
3869 if (!can_nice(p, TASK_NICE(p)))
3870 return -EPERM;
3871 }
5fe1d75f 3872
37e4ab3f 3873 /* can't change other user's priorities */
c69e8d9c 3874 if (!check_same_owner(p))
37e4ab3f 3875 return -EPERM;
ca94c442
LP
3876
3877 /* Normal users shall not reset the sched_reset_on_fork flag */
3878 if (p->sched_reset_on_fork && !reset_on_fork)
3879 return -EPERM;
37e4ab3f 3880 }
1da177e4 3881
725aad24 3882 if (user) {
b0ae1981 3883 retval = security_task_setscheduler(p);
725aad24
JF
3884 if (retval)
3885 return retval;
3886 }
3887
b29739f9
IM
3888 /*
3889 * make sure no PI-waiters arrive (or leave) while we are
3890 * changing the priority of the task:
0122ec5b 3891 *
25985edc 3892 * To be able to change p->policy safely, the appropriate
1da177e4
LT
3893 * runqueue lock must be held.
3894 */
0122ec5b 3895 rq = task_rq_lock(p, &flags);
dc61b1d6 3896
34f971f6
PZ
3897 /*
3898 * Changing the policy of the stop threads its a very bad idea
3899 */
3900 if (p == rq->stop) {
0122ec5b 3901 task_rq_unlock(rq, p, &flags);
34f971f6
PZ
3902 return -EINVAL;
3903 }
3904
a51e9198
DF
3905 /*
3906 * If not changing anything there's no need to proceed further:
3907 */
3908 if (unlikely(policy == p->policy && (!rt_policy(policy) ||
3909 param->sched_priority == p->rt_priority))) {
45afb173 3910 task_rq_unlock(rq, p, &flags);
a51e9198
DF
3911 return 0;
3912 }
3913
dc61b1d6
PZ
3914#ifdef CONFIG_RT_GROUP_SCHED
3915 if (user) {
3916 /*
3917 * Do not allow realtime tasks into groups that have no runtime
3918 * assigned.
3919 */
3920 if (rt_bandwidth_enabled() && rt_policy(policy) &&
f4493771
MG
3921 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
3922 !task_group_is_autogroup(task_group(p))) {
0122ec5b 3923 task_rq_unlock(rq, p, &flags);
dc61b1d6
PZ
3924 return -EPERM;
3925 }
3926 }
3927#endif
3928
1da177e4
LT
3929 /* recheck policy now with rq lock held */
3930 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3931 policy = oldpolicy = -1;
0122ec5b 3932 task_rq_unlock(rq, p, &flags);
1da177e4
LT
3933 goto recheck;
3934 }
fd2f4419 3935 on_rq = p->on_rq;
051a1d1a 3936 running = task_current(rq, p);
0e1f3483 3937 if (on_rq)
4ca9b72b 3938 dequeue_task(rq, p, 0);
0e1f3483
HS
3939 if (running)
3940 p->sched_class->put_prev_task(rq, p);
f6b53205 3941
ca94c442
LP
3942 p->sched_reset_on_fork = reset_on_fork;
3943
1da177e4 3944 oldprio = p->prio;
83ab0aa0 3945 prev_class = p->sched_class;
dd41f596 3946 __setscheduler(rq, p, policy, param->sched_priority);
f6b53205 3947
0e1f3483
HS
3948 if (running)
3949 p->sched_class->set_curr_task(rq);
da7a735e 3950 if (on_rq)
4ca9b72b 3951 enqueue_task(rq, p, 0);
cb469845 3952
da7a735e 3953 check_class_changed(rq, p, prev_class, oldprio);
0122ec5b 3954 task_rq_unlock(rq, p, &flags);
b29739f9 3955
95e02ca9
TG
3956 rt_mutex_adjust_pi(p);
3957
1da177e4
LT
3958 return 0;
3959}
961ccddd
RR
3960
3961/**
3962 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
3963 * @p: the task in question.
3964 * @policy: new policy.
3965 * @param: structure containing the new RT priority.
3966 *
3967 * NOTE that the task may be already dead.
3968 */
3969int sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 3970 const struct sched_param *param)
961ccddd
RR
3971{
3972 return __sched_setscheduler(p, policy, param, true);
3973}
1da177e4
LT
3974EXPORT_SYMBOL_GPL(sched_setscheduler);
3975
961ccddd
RR
3976/**
3977 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
3978 * @p: the task in question.
3979 * @policy: new policy.
3980 * @param: structure containing the new RT priority.
3981 *
3982 * Just like sched_setscheduler, only don't bother checking if the
3983 * current context has permission. For example, this is needed in
3984 * stop_machine(): we create temporary high priority worker threads,
3985 * but our caller might not have that capability.
3986 */
3987int sched_setscheduler_nocheck(struct task_struct *p, int policy,
fe7de49f 3988 const struct sched_param *param)
961ccddd
RR
3989{
3990 return __sched_setscheduler(p, policy, param, false);
3991}
3992
95cdf3b7
IM
3993static int
3994do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 3995{
1da177e4
LT
3996 struct sched_param lparam;
3997 struct task_struct *p;
36c8b586 3998 int retval;
1da177e4
LT
3999
4000 if (!param || pid < 0)
4001 return -EINVAL;
4002 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4003 return -EFAULT;
5fe1d75f
ON
4004
4005 rcu_read_lock();
4006 retval = -ESRCH;
1da177e4 4007 p = find_process_by_pid(pid);
5fe1d75f
ON
4008 if (p != NULL)
4009 retval = sched_setscheduler(p, policy, &lparam);
4010 rcu_read_unlock();
36c8b586 4011
1da177e4
LT
4012 return retval;
4013}
4014
4015/**
4016 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4017 * @pid: the pid in question.
4018 * @policy: new policy.
4019 * @param: structure containing the new RT priority.
4020 */
5add95d4
HC
4021SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4022 struct sched_param __user *, param)
1da177e4 4023{
c21761f1
JB
4024 /* negative values for policy are not valid */
4025 if (policy < 0)
4026 return -EINVAL;
4027
1da177e4
LT
4028 return do_sched_setscheduler(pid, policy, param);
4029}
4030
4031/**
4032 * sys_sched_setparam - set/change the RT priority of a thread
4033 * @pid: the pid in question.
4034 * @param: structure containing the new RT priority.
4035 */
5add95d4 4036SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
1da177e4
LT
4037{
4038 return do_sched_setscheduler(pid, -1, param);
4039}
4040
4041/**
4042 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4043 * @pid: the pid in question.
4044 */
5add95d4 4045SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
1da177e4 4046{
36c8b586 4047 struct task_struct *p;
3a5c359a 4048 int retval;
1da177e4
LT
4049
4050 if (pid < 0)
3a5c359a 4051 return -EINVAL;
1da177e4
LT
4052
4053 retval = -ESRCH;
5fe85be0 4054 rcu_read_lock();
1da177e4
LT
4055 p = find_process_by_pid(pid);
4056 if (p) {
4057 retval = security_task_getscheduler(p);
4058 if (!retval)
ca94c442
LP
4059 retval = p->policy
4060 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
1da177e4 4061 }
5fe85be0 4062 rcu_read_unlock();
1da177e4
LT
4063 return retval;
4064}
4065
4066/**
ca94c442 4067 * sys_sched_getparam - get the RT priority of a thread
1da177e4
LT
4068 * @pid: the pid in question.
4069 * @param: structure containing the RT priority.
4070 */
5add95d4 4071SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
1da177e4
LT
4072{
4073 struct sched_param lp;
36c8b586 4074 struct task_struct *p;
3a5c359a 4075 int retval;
1da177e4
LT
4076
4077 if (!param || pid < 0)
3a5c359a 4078 return -EINVAL;
1da177e4 4079
5fe85be0 4080 rcu_read_lock();
1da177e4
LT
4081 p = find_process_by_pid(pid);
4082 retval = -ESRCH;
4083 if (!p)
4084 goto out_unlock;
4085
4086 retval = security_task_getscheduler(p);
4087 if (retval)
4088 goto out_unlock;
4089
4090 lp.sched_priority = p->rt_priority;
5fe85be0 4091 rcu_read_unlock();
1da177e4
LT
4092
4093 /*
4094 * This one might sleep, we cannot do it with a spinlock held ...
4095 */
4096 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4097
1da177e4
LT
4098 return retval;
4099
4100out_unlock:
5fe85be0 4101 rcu_read_unlock();
1da177e4
LT
4102 return retval;
4103}
4104
96f874e2 4105long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
1da177e4 4106{
5a16f3d3 4107 cpumask_var_t cpus_allowed, new_mask;
36c8b586
IM
4108 struct task_struct *p;
4109 int retval;
1da177e4 4110
95402b38 4111 get_online_cpus();
23f5d142 4112 rcu_read_lock();
1da177e4
LT
4113
4114 p = find_process_by_pid(pid);
4115 if (!p) {
23f5d142 4116 rcu_read_unlock();
95402b38 4117 put_online_cpus();
1da177e4
LT
4118 return -ESRCH;
4119 }
4120
23f5d142 4121 /* Prevent p going away */
1da177e4 4122 get_task_struct(p);
23f5d142 4123 rcu_read_unlock();
1da177e4 4124
14a40ffc
TH
4125 if (p->flags & PF_NO_SETAFFINITY) {
4126 retval = -EINVAL;
4127 goto out_put_task;
4128 }
5a16f3d3
RR
4129 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4130 retval = -ENOMEM;
4131 goto out_put_task;
4132 }
4133 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4134 retval = -ENOMEM;
4135 goto out_free_cpus_allowed;
4136 }
1da177e4 4137 retval = -EPERM;
4c44aaaf
EB
4138 if (!check_same_owner(p)) {
4139 rcu_read_lock();
4140 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4141 rcu_read_unlock();
4142 goto out_unlock;
4143 }
4144 rcu_read_unlock();
4145 }
1da177e4 4146
b0ae1981 4147 retval = security_task_setscheduler(p);
e7834f8f
DQ
4148 if (retval)
4149 goto out_unlock;
4150
5a16f3d3
RR
4151 cpuset_cpus_allowed(p, cpus_allowed);
4152 cpumask_and(new_mask, in_mask, cpus_allowed);
49246274 4153again:
5a16f3d3 4154 retval = set_cpus_allowed_ptr(p, new_mask);
1da177e4 4155
8707d8b8 4156 if (!retval) {
5a16f3d3
RR
4157 cpuset_cpus_allowed(p, cpus_allowed);
4158 if (!cpumask_subset(new_mask, cpus_allowed)) {
8707d8b8
PM
4159 /*
4160 * We must have raced with a concurrent cpuset
4161 * update. Just reset the cpus_allowed to the
4162 * cpuset's cpus_allowed
4163 */
5a16f3d3 4164 cpumask_copy(new_mask, cpus_allowed);
8707d8b8
PM
4165 goto again;
4166 }
4167 }
1da177e4 4168out_unlock:
5a16f3d3
RR
4169 free_cpumask_var(new_mask);
4170out_free_cpus_allowed:
4171 free_cpumask_var(cpus_allowed);
4172out_put_task:
1da177e4 4173 put_task_struct(p);
95402b38 4174 put_online_cpus();
1da177e4
LT
4175 return retval;
4176}
4177
4178static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
96f874e2 4179 struct cpumask *new_mask)
1da177e4 4180{
96f874e2
RR
4181 if (len < cpumask_size())
4182 cpumask_clear(new_mask);
4183 else if (len > cpumask_size())
4184 len = cpumask_size();
4185
1da177e4
LT
4186 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4187}
4188
4189/**
4190 * sys_sched_setaffinity - set the cpu affinity of a process
4191 * @pid: pid of the process
4192 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4193 * @user_mask_ptr: user-space pointer to the new cpu mask
4194 */
5add95d4
HC
4195SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4196 unsigned long __user *, user_mask_ptr)
1da177e4 4197{
5a16f3d3 4198 cpumask_var_t new_mask;
1da177e4
LT
4199 int retval;
4200
5a16f3d3
RR
4201 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4202 return -ENOMEM;
1da177e4 4203
5a16f3d3
RR
4204 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4205 if (retval == 0)
4206 retval = sched_setaffinity(pid, new_mask);
4207 free_cpumask_var(new_mask);
4208 return retval;
1da177e4
LT
4209}
4210
96f874e2 4211long sched_getaffinity(pid_t pid, struct cpumask *mask)
1da177e4 4212{
36c8b586 4213 struct task_struct *p;
31605683 4214 unsigned long flags;
1da177e4 4215 int retval;
1da177e4 4216
95402b38 4217 get_online_cpus();
23f5d142 4218 rcu_read_lock();
1da177e4
LT
4219
4220 retval = -ESRCH;
4221 p = find_process_by_pid(pid);
4222 if (!p)
4223 goto out_unlock;
4224
e7834f8f
DQ
4225 retval = security_task_getscheduler(p);
4226 if (retval)
4227 goto out_unlock;
4228
013fdb80 4229 raw_spin_lock_irqsave(&p->pi_lock, flags);
96f874e2 4230 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
013fdb80 4231 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
4232
4233out_unlock:
23f5d142 4234 rcu_read_unlock();
95402b38 4235 put_online_cpus();
1da177e4 4236
9531b62f 4237 return retval;
1da177e4
LT
4238}
4239
4240/**
4241 * sys_sched_getaffinity - get the cpu affinity of a process
4242 * @pid: pid of the process
4243 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4244 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4245 */
5add95d4
HC
4246SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4247 unsigned long __user *, user_mask_ptr)
1da177e4
LT
4248{
4249 int ret;
f17c8607 4250 cpumask_var_t mask;
1da177e4 4251
84fba5ec 4252 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
cd3d8031
KM
4253 return -EINVAL;
4254 if (len & (sizeof(unsigned long)-1))
1da177e4
LT
4255 return -EINVAL;
4256
f17c8607
RR
4257 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4258 return -ENOMEM;
1da177e4 4259
f17c8607
RR
4260 ret = sched_getaffinity(pid, mask);
4261 if (ret == 0) {
8bc037fb 4262 size_t retlen = min_t(size_t, len, cpumask_size());
cd3d8031
KM
4263
4264 if (copy_to_user(user_mask_ptr, mask, retlen))
f17c8607
RR
4265 ret = -EFAULT;
4266 else
cd3d8031 4267 ret = retlen;
f17c8607
RR
4268 }
4269 free_cpumask_var(mask);
1da177e4 4270
f17c8607 4271 return ret;
1da177e4
LT
4272}
4273
4274/**
4275 * sys_sched_yield - yield the current processor to other threads.
4276 *
dd41f596
IM
4277 * This function yields the current CPU to other tasks. If there are no
4278 * other threads running on this CPU then this function will return.
1da177e4 4279 */
5add95d4 4280SYSCALL_DEFINE0(sched_yield)
1da177e4 4281{
70b97a7f 4282 struct rq *rq = this_rq_lock();
1da177e4 4283
2d72376b 4284 schedstat_inc(rq, yld_count);
4530d7ab 4285 current->sched_class->yield_task(rq);
1da177e4
LT
4286
4287 /*
4288 * Since we are going to call schedule() anyway, there's
4289 * no need to preempt or enable interrupts:
4290 */
4291 __release(rq->lock);
8a25d5de 4292 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
9828ea9d 4293 do_raw_spin_unlock(&rq->lock);
ba74c144 4294 sched_preempt_enable_no_resched();
1da177e4
LT
4295
4296 schedule();
4297
4298 return 0;
4299}
4300
d86ee480
PZ
4301static inline int should_resched(void)
4302{
4303 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
4304}
4305
e7b38404 4306static void __cond_resched(void)
1da177e4 4307{
e7aaaa69 4308 add_preempt_count(PREEMPT_ACTIVE);
c259e01a 4309 __schedule();
e7aaaa69 4310 sub_preempt_count(PREEMPT_ACTIVE);
1da177e4
LT
4311}
4312
02b67cc3 4313int __sched _cond_resched(void)
1da177e4 4314{
d86ee480 4315 if (should_resched()) {
1da177e4
LT
4316 __cond_resched();
4317 return 1;
4318 }
4319 return 0;
4320}
02b67cc3 4321EXPORT_SYMBOL(_cond_resched);
1da177e4
LT
4322
4323/*
613afbf8 4324 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
1da177e4
LT
4325 * call schedule, and on return reacquire the lock.
4326 *
41a2d6cf 4327 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
1da177e4
LT
4328 * operations here to prevent schedule() from being called twice (once via
4329 * spin_unlock(), once by hand).
4330 */
613afbf8 4331int __cond_resched_lock(spinlock_t *lock)
1da177e4 4332{
d86ee480 4333 int resched = should_resched();
6df3cecb
JK
4334 int ret = 0;
4335
f607c668
PZ
4336 lockdep_assert_held(lock);
4337
95c354fe 4338 if (spin_needbreak(lock) || resched) {
1da177e4 4339 spin_unlock(lock);
d86ee480 4340 if (resched)
95c354fe
NP
4341 __cond_resched();
4342 else
4343 cpu_relax();
6df3cecb 4344 ret = 1;
1da177e4 4345 spin_lock(lock);
1da177e4 4346 }
6df3cecb 4347 return ret;
1da177e4 4348}
613afbf8 4349EXPORT_SYMBOL(__cond_resched_lock);
1da177e4 4350
613afbf8 4351int __sched __cond_resched_softirq(void)
1da177e4
LT
4352{
4353 BUG_ON(!in_softirq());
4354
d86ee480 4355 if (should_resched()) {
98d82567 4356 local_bh_enable();
1da177e4
LT
4357 __cond_resched();
4358 local_bh_disable();
4359 return 1;
4360 }
4361 return 0;
4362}
613afbf8 4363EXPORT_SYMBOL(__cond_resched_softirq);
1da177e4 4364
1da177e4
LT
4365/**
4366 * yield - yield the current processor to other threads.
4367 *
8e3fabfd
PZ
4368 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4369 *
4370 * The scheduler is at all times free to pick the calling task as the most
4371 * eligible task to run, if removing the yield() call from your code breaks
4372 * it, its already broken.
4373 *
4374 * Typical broken usage is:
4375 *
4376 * while (!event)
4377 * yield();
4378 *
4379 * where one assumes that yield() will let 'the other' process run that will
4380 * make event true. If the current task is a SCHED_FIFO task that will never
4381 * happen. Never use yield() as a progress guarantee!!
4382 *
4383 * If you want to use yield() to wait for something, use wait_event().
4384 * If you want to use yield() to be 'nice' for others, use cond_resched().
4385 * If you still want to use yield(), do not!
1da177e4
LT
4386 */
4387void __sched yield(void)
4388{
4389 set_current_state(TASK_RUNNING);
4390 sys_sched_yield();
4391}
1da177e4
LT
4392EXPORT_SYMBOL(yield);
4393
d95f4122
MG
4394/**
4395 * yield_to - yield the current processor to another thread in
4396 * your thread group, or accelerate that thread toward the
4397 * processor it's on.
16addf95
RD
4398 * @p: target task
4399 * @preempt: whether task preemption is allowed or not
d95f4122
MG
4400 *
4401 * It's the caller's job to ensure that the target task struct
4402 * can't go away on us before we can do any checks.
4403 *
7b270f60
PZ
4404 * Returns:
4405 * true (>0) if we indeed boosted the target task.
4406 * false (0) if we failed to boost the target.
4407 * -ESRCH if there's no task to yield to.
d95f4122
MG
4408 */
4409bool __sched yield_to(struct task_struct *p, bool preempt)
4410{
4411 struct task_struct *curr = current;
4412 struct rq *rq, *p_rq;
4413 unsigned long flags;
c3c18640 4414 int yielded = 0;
d95f4122
MG
4415
4416 local_irq_save(flags);
4417 rq = this_rq();
4418
4419again:
4420 p_rq = task_rq(p);
7b270f60
PZ
4421 /*
4422 * If we're the only runnable task on the rq and target rq also
4423 * has only one task, there's absolutely no point in yielding.
4424 */
4425 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4426 yielded = -ESRCH;
4427 goto out_irq;
4428 }
4429
d95f4122
MG
4430 double_rq_lock(rq, p_rq);
4431 while (task_rq(p) != p_rq) {
4432 double_rq_unlock(rq, p_rq);
4433 goto again;
4434 }
4435
4436 if (!curr->sched_class->yield_to_task)
7b270f60 4437 goto out_unlock;
d95f4122
MG
4438
4439 if (curr->sched_class != p->sched_class)
7b270f60 4440 goto out_unlock;
d95f4122
MG
4441
4442 if (task_running(p_rq, p) || p->state)
7b270f60 4443 goto out_unlock;
d95f4122
MG
4444
4445 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
6d1cafd8 4446 if (yielded) {
d95f4122 4447 schedstat_inc(rq, yld_count);
6d1cafd8
VP
4448 /*
4449 * Make p's CPU reschedule; pick_next_entity takes care of
4450 * fairness.
4451 */
4452 if (preempt && rq != p_rq)
4453 resched_task(p_rq->curr);
4454 }
d95f4122 4455
7b270f60 4456out_unlock:
d95f4122 4457 double_rq_unlock(rq, p_rq);
7b270f60 4458out_irq:
d95f4122
MG
4459 local_irq_restore(flags);
4460
7b270f60 4461 if (yielded > 0)
d95f4122
MG
4462 schedule();
4463
4464 return yielded;
4465}
4466EXPORT_SYMBOL_GPL(yield_to);
4467
1da177e4 4468/*
41a2d6cf 4469 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
1da177e4 4470 * that process accounting knows that this is a task in IO wait state.
1da177e4
LT
4471 */
4472void __sched io_schedule(void)
4473{
54d35f29 4474 struct rq *rq = raw_rq();
1da177e4 4475
0ff92245 4476 delayacct_blkio_start();
1da177e4 4477 atomic_inc(&rq->nr_iowait);
73c10101 4478 blk_flush_plug(current);
8f0dfc34 4479 current->in_iowait = 1;
1da177e4 4480 schedule();
8f0dfc34 4481 current->in_iowait = 0;
1da177e4 4482 atomic_dec(&rq->nr_iowait);
0ff92245 4483 delayacct_blkio_end();
1da177e4 4484}
1da177e4
LT
4485EXPORT_SYMBOL(io_schedule);
4486
4487long __sched io_schedule_timeout(long timeout)
4488{
54d35f29 4489 struct rq *rq = raw_rq();
1da177e4
LT
4490 long ret;
4491
0ff92245 4492 delayacct_blkio_start();
1da177e4 4493 atomic_inc(&rq->nr_iowait);
73c10101 4494 blk_flush_plug(current);
8f0dfc34 4495 current->in_iowait = 1;
1da177e4 4496 ret = schedule_timeout(timeout);
8f0dfc34 4497 current->in_iowait = 0;
1da177e4 4498 atomic_dec(&rq->nr_iowait);
0ff92245 4499 delayacct_blkio_end();
1da177e4
LT
4500 return ret;
4501}
4502
4503/**
4504 * sys_sched_get_priority_max - return maximum RT priority.
4505 * @policy: scheduling class.
4506 *
4507 * this syscall returns the maximum rt_priority that can be used
4508 * by a given scheduling class.
4509 */
5add95d4 4510SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
1da177e4
LT
4511{
4512 int ret = -EINVAL;
4513
4514 switch (policy) {
4515 case SCHED_FIFO:
4516 case SCHED_RR:
4517 ret = MAX_USER_RT_PRIO-1;
4518 break;
4519 case SCHED_NORMAL:
b0a9499c 4520 case SCHED_BATCH:
dd41f596 4521 case SCHED_IDLE:
1da177e4
LT
4522 ret = 0;
4523 break;
4524 }
4525 return ret;
4526}
4527
4528/**
4529 * sys_sched_get_priority_min - return minimum RT priority.
4530 * @policy: scheduling class.
4531 *
4532 * this syscall returns the minimum rt_priority that can be used
4533 * by a given scheduling class.
4534 */
5add95d4 4535SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
1da177e4
LT
4536{
4537 int ret = -EINVAL;
4538
4539 switch (policy) {
4540 case SCHED_FIFO:
4541 case SCHED_RR:
4542 ret = 1;
4543 break;
4544 case SCHED_NORMAL:
b0a9499c 4545 case SCHED_BATCH:
dd41f596 4546 case SCHED_IDLE:
1da177e4
LT
4547 ret = 0;
4548 }
4549 return ret;
4550}
4551
4552/**
4553 * sys_sched_rr_get_interval - return the default timeslice of a process.
4554 * @pid: pid of the process.
4555 * @interval: userspace pointer to the timeslice value.
4556 *
4557 * this syscall writes the default timeslice value of a given process
4558 * into the user-space timespec buffer. A value of '0' means infinity.
4559 */
17da2bd9 4560SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
754fe8d2 4561 struct timespec __user *, interval)
1da177e4 4562{
36c8b586 4563 struct task_struct *p;
a4ec24b4 4564 unsigned int time_slice;
dba091b9
TG
4565 unsigned long flags;
4566 struct rq *rq;
3a5c359a 4567 int retval;
1da177e4 4568 struct timespec t;
1da177e4
LT
4569
4570 if (pid < 0)
3a5c359a 4571 return -EINVAL;
1da177e4
LT
4572
4573 retval = -ESRCH;
1a551ae7 4574 rcu_read_lock();
1da177e4
LT
4575 p = find_process_by_pid(pid);
4576 if (!p)
4577 goto out_unlock;
4578
4579 retval = security_task_getscheduler(p);
4580 if (retval)
4581 goto out_unlock;
4582
dba091b9
TG
4583 rq = task_rq_lock(p, &flags);
4584 time_slice = p->sched_class->get_rr_interval(rq, p);
0122ec5b 4585 task_rq_unlock(rq, p, &flags);
a4ec24b4 4586
1a551ae7 4587 rcu_read_unlock();
a4ec24b4 4588 jiffies_to_timespec(time_slice, &t);
1da177e4 4589 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
1da177e4 4590 return retval;
3a5c359a 4591
1da177e4 4592out_unlock:
1a551ae7 4593 rcu_read_unlock();
1da177e4
LT
4594 return retval;
4595}
4596
7c731e0a 4597static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
36c8b586 4598
82a1fcb9 4599void sched_show_task(struct task_struct *p)
1da177e4 4600{
1da177e4 4601 unsigned long free = 0;
4e79752c 4602 int ppid;
36c8b586 4603 unsigned state;
1da177e4 4604
1da177e4 4605 state = p->state ? __ffs(p->state) + 1 : 0;
28d0686c 4606 printk(KERN_INFO "%-15.15s %c", p->comm,
2ed6e34f 4607 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4bd77321 4608#if BITS_PER_LONG == 32
1da177e4 4609 if (state == TASK_RUNNING)
3df0fc5b 4610 printk(KERN_CONT " running ");
1da177e4 4611 else
3df0fc5b 4612 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
1da177e4
LT
4613#else
4614 if (state == TASK_RUNNING)
3df0fc5b 4615 printk(KERN_CONT " running task ");
1da177e4 4616 else
3df0fc5b 4617 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
1da177e4
LT
4618#endif
4619#ifdef CONFIG_DEBUG_STACK_USAGE
7c9f8861 4620 free = stack_not_used(p);
1da177e4 4621#endif
4e79752c
PM
4622 rcu_read_lock();
4623 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4624 rcu_read_unlock();
3df0fc5b 4625 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4e79752c 4626 task_pid_nr(p), ppid,
aa47b7e0 4627 (unsigned long)task_thread_info(p)->flags);
1da177e4 4628
5fb5e6de 4629 show_stack(p, NULL);
1da177e4
LT
4630}
4631
e59e2ae2 4632void show_state_filter(unsigned long state_filter)
1da177e4 4633{
36c8b586 4634 struct task_struct *g, *p;
1da177e4 4635
4bd77321 4636#if BITS_PER_LONG == 32
3df0fc5b
PZ
4637 printk(KERN_INFO
4638 " task PC stack pid father\n");
1da177e4 4639#else
3df0fc5b
PZ
4640 printk(KERN_INFO
4641 " task PC stack pid father\n");
1da177e4 4642#endif
510f5acc 4643 rcu_read_lock();
1da177e4
LT
4644 do_each_thread(g, p) {
4645 /*
4646 * reset the NMI-timeout, listing all files on a slow
25985edc 4647 * console might take a lot of time:
1da177e4
LT
4648 */
4649 touch_nmi_watchdog();
39bc89fd 4650 if (!state_filter || (p->state & state_filter))
82a1fcb9 4651 sched_show_task(p);
1da177e4
LT
4652 } while_each_thread(g, p);
4653
04c9167f
JF
4654 touch_all_softlockup_watchdogs();
4655
dd41f596
IM
4656#ifdef CONFIG_SCHED_DEBUG
4657 sysrq_sched_debug_show();
4658#endif
510f5acc 4659 rcu_read_unlock();
e59e2ae2
IM
4660 /*
4661 * Only show locks if all tasks are dumped:
4662 */
93335a21 4663 if (!state_filter)
e59e2ae2 4664 debug_show_all_locks();
1da177e4
LT
4665}
4666
1df21055
IM
4667void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4668{
dd41f596 4669 idle->sched_class = &idle_sched_class;
1df21055
IM
4670}
4671
f340c0d1
IM
4672/**
4673 * init_idle - set up an idle thread for a given CPU
4674 * @idle: task in question
4675 * @cpu: cpu the idle task belongs to
4676 *
4677 * NOTE: this function does not set the idle thread's NEED_RESCHED
4678 * flag, to make booting more robust.
4679 */
5c1e1767 4680void __cpuinit init_idle(struct task_struct *idle, int cpu)
1da177e4 4681{
70b97a7f 4682 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
4683 unsigned long flags;
4684
05fa785c 4685 raw_spin_lock_irqsave(&rq->lock, flags);
5cbd54ef 4686
dd41f596 4687 __sched_fork(idle);
06b83b5f 4688 idle->state = TASK_RUNNING;
dd41f596
IM
4689 idle->se.exec_start = sched_clock();
4690
1e1b6c51 4691 do_set_cpus_allowed(idle, cpumask_of(cpu));
6506cf6c
PZ
4692 /*
4693 * We're having a chicken and egg problem, even though we are
4694 * holding rq->lock, the cpu isn't yet set to this cpu so the
4695 * lockdep check in task_group() will fail.
4696 *
4697 * Similar case to sched_fork(). / Alternatively we could
4698 * use task_rq_lock() here and obtain the other rq->lock.
4699 *
4700 * Silence PROVE_RCU
4701 */
4702 rcu_read_lock();
dd41f596 4703 __set_task_cpu(idle, cpu);
6506cf6c 4704 rcu_read_unlock();
1da177e4 4705
1da177e4 4706 rq->curr = rq->idle = idle;
3ca7a440
PZ
4707#if defined(CONFIG_SMP)
4708 idle->on_cpu = 1;
4866cde0 4709#endif
05fa785c 4710 raw_spin_unlock_irqrestore(&rq->lock, flags);
1da177e4
LT
4711
4712 /* Set the preempt count _outside_ the spinlocks! */
a1261f54 4713 task_thread_info(idle)->preempt_count = 0;
55cd5340 4714
dd41f596
IM
4715 /*
4716 * The idle tasks have their own, simple scheduling class:
4717 */
4718 idle->sched_class = &idle_sched_class;
868baf07 4719 ftrace_graph_init_idle_task(idle, cpu);
6a61671b 4720 vtime_init_idle(idle);
f1c6f1a7
CE
4721#if defined(CONFIG_SMP)
4722 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
4723#endif
19978ca6
IM
4724}
4725
1da177e4 4726#ifdef CONFIG_SMP
1e1b6c51
KM
4727void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
4728{
4729 if (p->sched_class && p->sched_class->set_cpus_allowed)
4730 p->sched_class->set_cpus_allowed(p, new_mask);
4939602a
PZ
4731
4732 cpumask_copy(&p->cpus_allowed, new_mask);
29baa747 4733 p->nr_cpus_allowed = cpumask_weight(new_mask);
1e1b6c51
KM
4734}
4735
1da177e4
LT
4736/*
4737 * This is how migration works:
4738 *
969c7921
TH
4739 * 1) we invoke migration_cpu_stop() on the target CPU using
4740 * stop_one_cpu().
4741 * 2) stopper starts to run (implicitly forcing the migrated thread
4742 * off the CPU)
4743 * 3) it checks whether the migrated task is still in the wrong runqueue.
4744 * 4) if it's in the wrong runqueue then the migration thread removes
1da177e4 4745 * it and puts it into the right queue.
969c7921
TH
4746 * 5) stopper completes and stop_one_cpu() returns and the migration
4747 * is done.
1da177e4
LT
4748 */
4749
4750/*
4751 * Change a given task's CPU affinity. Migrate the thread to a
4752 * proper CPU and schedule it away if the CPU it's executing on
4753 * is removed from the allowed bitmask.
4754 *
4755 * NOTE: the caller must have a valid reference to the task, the
41a2d6cf 4756 * task must not exit() & deallocate itself prematurely. The
1da177e4
LT
4757 * call is not atomic; no spinlocks may be held.
4758 */
96f874e2 4759int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1da177e4
LT
4760{
4761 unsigned long flags;
70b97a7f 4762 struct rq *rq;
969c7921 4763 unsigned int dest_cpu;
48f24c4d 4764 int ret = 0;
1da177e4
LT
4765
4766 rq = task_rq_lock(p, &flags);
e2912009 4767
db44fc01
YZ
4768 if (cpumask_equal(&p->cpus_allowed, new_mask))
4769 goto out;
4770
6ad4c188 4771 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
1da177e4
LT
4772 ret = -EINVAL;
4773 goto out;
4774 }
4775
1e1b6c51 4776 do_set_cpus_allowed(p, new_mask);
73fe6aae 4777
1da177e4 4778 /* Can the task run on the task's current CPU? If so, we're done */
96f874e2 4779 if (cpumask_test_cpu(task_cpu(p), new_mask))
1da177e4
LT
4780 goto out;
4781
969c7921 4782 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
bd8e7dde 4783 if (p->on_rq) {
969c7921 4784 struct migration_arg arg = { p, dest_cpu };
1da177e4 4785 /* Need help from migration thread: drop lock and wait. */
0122ec5b 4786 task_rq_unlock(rq, p, &flags);
969c7921 4787 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1da177e4
LT
4788 tlb_migrate_finish(p->mm);
4789 return 0;
4790 }
4791out:
0122ec5b 4792 task_rq_unlock(rq, p, &flags);
48f24c4d 4793
1da177e4
LT
4794 return ret;
4795}
cd8ba7cd 4796EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1da177e4
LT
4797
4798/*
41a2d6cf 4799 * Move (not current) task off this cpu, onto dest cpu. We're doing
1da177e4
LT
4800 * this because either it can't run here any more (set_cpus_allowed()
4801 * away from this CPU, or CPU going down), or because we're
4802 * attempting to rebalance this task on exec (sched_exec).
4803 *
4804 * So we race with normal scheduler movements, but that's OK, as long
4805 * as the task is no longer on this CPU.
efc30814
KK
4806 *
4807 * Returns non-zero if task was successfully migrated.
1da177e4 4808 */
efc30814 4809static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
1da177e4 4810{
70b97a7f 4811 struct rq *rq_dest, *rq_src;
e2912009 4812 int ret = 0;
1da177e4 4813
e761b772 4814 if (unlikely(!cpu_active(dest_cpu)))
efc30814 4815 return ret;
1da177e4
LT
4816
4817 rq_src = cpu_rq(src_cpu);
4818 rq_dest = cpu_rq(dest_cpu);
4819
0122ec5b 4820 raw_spin_lock(&p->pi_lock);
1da177e4
LT
4821 double_rq_lock(rq_src, rq_dest);
4822 /* Already moved. */
4823 if (task_cpu(p) != src_cpu)
b1e38734 4824 goto done;
1da177e4 4825 /* Affinity changed (again). */
fa17b507 4826 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
b1e38734 4827 goto fail;
1da177e4 4828
e2912009
PZ
4829 /*
4830 * If we're not on a rq, the next wake-up will ensure we're
4831 * placed properly.
4832 */
fd2f4419 4833 if (p->on_rq) {
4ca9b72b 4834 dequeue_task(rq_src, p, 0);
e2912009 4835 set_task_cpu(p, dest_cpu);
4ca9b72b 4836 enqueue_task(rq_dest, p, 0);
15afe09b 4837 check_preempt_curr(rq_dest, p, 0);
1da177e4 4838 }
b1e38734 4839done:
efc30814 4840 ret = 1;
b1e38734 4841fail:
1da177e4 4842 double_rq_unlock(rq_src, rq_dest);
0122ec5b 4843 raw_spin_unlock(&p->pi_lock);
efc30814 4844 return ret;
1da177e4
LT
4845}
4846
4847/*
969c7921
TH
4848 * migration_cpu_stop - this will be executed by a highprio stopper thread
4849 * and performs thread migration by bumping thread off CPU then
4850 * 'pushing' onto another runqueue.
1da177e4 4851 */
969c7921 4852static int migration_cpu_stop(void *data)
1da177e4 4853{
969c7921 4854 struct migration_arg *arg = data;
f7b4cddc 4855
969c7921
TH
4856 /*
4857 * The original target cpu might have gone down and we might
4858 * be on another cpu but it doesn't matter.
4859 */
f7b4cddc 4860 local_irq_disable();
969c7921 4861 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
f7b4cddc 4862 local_irq_enable();
1da177e4 4863 return 0;
f7b4cddc
ON
4864}
4865
1da177e4 4866#ifdef CONFIG_HOTPLUG_CPU
48c5ccae 4867
054b9108 4868/*
48c5ccae
PZ
4869 * Ensures that the idle task is using init_mm right before its cpu goes
4870 * offline.
054b9108 4871 */
48c5ccae 4872void idle_task_exit(void)
1da177e4 4873{
48c5ccae 4874 struct mm_struct *mm = current->active_mm;
e76bd8d9 4875
48c5ccae 4876 BUG_ON(cpu_online(smp_processor_id()));
e76bd8d9 4877
48c5ccae
PZ
4878 if (mm != &init_mm)
4879 switch_mm(mm, &init_mm, current);
4880 mmdrop(mm);
1da177e4
LT
4881}
4882
4883/*
5d180232
PZ
4884 * Since this CPU is going 'away' for a while, fold any nr_active delta
4885 * we might have. Assumes we're called after migrate_tasks() so that the
4886 * nr_active count is stable.
4887 *
4888 * Also see the comment "Global load-average calculations".
1da177e4 4889 */
5d180232 4890static void calc_load_migrate(struct rq *rq)
1da177e4 4891{
5d180232
PZ
4892 long delta = calc_load_fold_active(rq);
4893 if (delta)
4894 atomic_long_add(delta, &calc_load_tasks);
1da177e4
LT
4895}
4896
48f24c4d 4897/*
48c5ccae
PZ
4898 * Migrate all tasks from the rq, sleeping tasks will be migrated by
4899 * try_to_wake_up()->select_task_rq().
4900 *
4901 * Called with rq->lock held even though we'er in stop_machine() and
4902 * there's no concurrency possible, we hold the required locks anyway
4903 * because of lock validation efforts.
1da177e4 4904 */
48c5ccae 4905static void migrate_tasks(unsigned int dead_cpu)
1da177e4 4906{
70b97a7f 4907 struct rq *rq = cpu_rq(dead_cpu);
48c5ccae
PZ
4908 struct task_struct *next, *stop = rq->stop;
4909 int dest_cpu;
1da177e4
LT
4910
4911 /*
48c5ccae
PZ
4912 * Fudge the rq selection such that the below task selection loop
4913 * doesn't get stuck on the currently eligible stop task.
4914 *
4915 * We're currently inside stop_machine() and the rq is either stuck
4916 * in the stop_machine_cpu_stop() loop, or we're executing this code,
4917 * either way we should never end up calling schedule() until we're
4918 * done here.
1da177e4 4919 */
48c5ccae 4920 rq->stop = NULL;
48f24c4d 4921
dd41f596 4922 for ( ; ; ) {
48c5ccae
PZ
4923 /*
4924 * There's this thread running, bail when that's the only
4925 * remaining thread.
4926 */
4927 if (rq->nr_running == 1)
dd41f596 4928 break;
48c5ccae 4929
b67802ea 4930 next = pick_next_task(rq);
48c5ccae 4931 BUG_ON(!next);
79c53799 4932 next->sched_class->put_prev_task(rq, next);
e692ab53 4933
48c5ccae
PZ
4934 /* Find suitable destination for @next, with force if needed. */
4935 dest_cpu = select_fallback_rq(dead_cpu, next);
4936 raw_spin_unlock(&rq->lock);
4937
4938 __migrate_task(next, dead_cpu, dest_cpu);
4939
4940 raw_spin_lock(&rq->lock);
1da177e4 4941 }
dce48a84 4942
48c5ccae 4943 rq->stop = stop;
dce48a84 4944}
48c5ccae 4945
1da177e4
LT
4946#endif /* CONFIG_HOTPLUG_CPU */
4947
e692ab53
NP
4948#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
4949
4950static struct ctl_table sd_ctl_dir[] = {
e0361851
AD
4951 {
4952 .procname = "sched_domain",
c57baf1e 4953 .mode = 0555,
e0361851 4954 },
56992309 4955 {}
e692ab53
NP
4956};
4957
4958static struct ctl_table sd_ctl_root[] = {
e0361851
AD
4959 {
4960 .procname = "kernel",
c57baf1e 4961 .mode = 0555,
e0361851
AD
4962 .child = sd_ctl_dir,
4963 },
56992309 4964 {}
e692ab53
NP
4965};
4966
4967static struct ctl_table *sd_alloc_ctl_entry(int n)
4968{
4969 struct ctl_table *entry =
5cf9f062 4970 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
e692ab53 4971
e692ab53
NP
4972 return entry;
4973}
4974
6382bc90
MM
4975static void sd_free_ctl_entry(struct ctl_table **tablep)
4976{
cd790076 4977 struct ctl_table *entry;
6382bc90 4978
cd790076
MM
4979 /*
4980 * In the intermediate directories, both the child directory and
4981 * procname are dynamically allocated and could fail but the mode
41a2d6cf 4982 * will always be set. In the lowest directory the names are
cd790076
MM
4983 * static strings and all have proc handlers.
4984 */
4985 for (entry = *tablep; entry->mode; entry++) {
6382bc90
MM
4986 if (entry->child)
4987 sd_free_ctl_entry(&entry->child);
cd790076
MM
4988 if (entry->proc_handler == NULL)
4989 kfree(entry->procname);
4990 }
6382bc90
MM
4991
4992 kfree(*tablep);
4993 *tablep = NULL;
4994}
4995
201c373e 4996static int min_load_idx = 0;
fd9b86d3 4997static int max_load_idx = CPU_LOAD_IDX_MAX-1;
201c373e 4998
e692ab53 4999static void
e0361851 5000set_table_entry(struct ctl_table *entry,
e692ab53 5001 const char *procname, void *data, int maxlen,
201c373e
NK
5002 umode_t mode, proc_handler *proc_handler,
5003 bool load_idx)
e692ab53 5004{
e692ab53
NP
5005 entry->procname = procname;
5006 entry->data = data;
5007 entry->maxlen = maxlen;
5008 entry->mode = mode;
5009 entry->proc_handler = proc_handler;
201c373e
NK
5010
5011 if (load_idx) {
5012 entry->extra1 = &min_load_idx;
5013 entry->extra2 = &max_load_idx;
5014 }
e692ab53
NP
5015}
5016
5017static struct ctl_table *
5018sd_alloc_ctl_domain_table(struct sched_domain *sd)
5019{
a5d8c348 5020 struct ctl_table *table = sd_alloc_ctl_entry(13);
e692ab53 5021
ad1cdc1d
MM
5022 if (table == NULL)
5023 return NULL;
5024
e0361851 5025 set_table_entry(&table[0], "min_interval", &sd->min_interval,
201c373e 5026 sizeof(long), 0644, proc_doulongvec_minmax, false);
e0361851 5027 set_table_entry(&table[1], "max_interval", &sd->max_interval,
201c373e 5028 sizeof(long), 0644, proc_doulongvec_minmax, false);
e0361851 5029 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
201c373e 5030 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5031 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
201c373e 5032 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5033 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
201c373e 5034 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5035 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
201c373e 5036 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5037 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
201c373e 5038 sizeof(int), 0644, proc_dointvec_minmax, true);
e0361851 5039 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
201c373e 5040 sizeof(int), 0644, proc_dointvec_minmax, false);
e0361851 5041 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
201c373e 5042 sizeof(int), 0644, proc_dointvec_minmax, false);
ace8b3d6 5043 set_table_entry(&table[9], "cache_nice_tries",
e692ab53 5044 &sd->cache_nice_tries,
201c373e 5045 sizeof(int), 0644, proc_dointvec_minmax, false);
ace8b3d6 5046 set_table_entry(&table[10], "flags", &sd->flags,
201c373e 5047 sizeof(int), 0644, proc_dointvec_minmax, false);
a5d8c348 5048 set_table_entry(&table[11], "name", sd->name,
201c373e 5049 CORENAME_MAX_SIZE, 0444, proc_dostring, false);
a5d8c348 5050 /* &table[12] is terminator */
e692ab53
NP
5051
5052 return table;
5053}
5054
9a4e7159 5055static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
e692ab53
NP
5056{
5057 struct ctl_table *entry, *table;
5058 struct sched_domain *sd;
5059 int domain_num = 0, i;
5060 char buf[32];
5061
5062 for_each_domain(cpu, sd)
5063 domain_num++;
5064 entry = table = sd_alloc_ctl_entry(domain_num + 1);
ad1cdc1d
MM
5065 if (table == NULL)
5066 return NULL;
e692ab53
NP
5067
5068 i = 0;
5069 for_each_domain(cpu, sd) {
5070 snprintf(buf, 32, "domain%d", i);
e692ab53 5071 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5072 entry->mode = 0555;
e692ab53
NP
5073 entry->child = sd_alloc_ctl_domain_table(sd);
5074 entry++;
5075 i++;
5076 }
5077 return table;
5078}
5079
5080static struct ctl_table_header *sd_sysctl_header;
6382bc90 5081static void register_sched_domain_sysctl(void)
e692ab53 5082{
6ad4c188 5083 int i, cpu_num = num_possible_cpus();
e692ab53
NP
5084 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5085 char buf[32];
5086
7378547f
MM
5087 WARN_ON(sd_ctl_dir[0].child);
5088 sd_ctl_dir[0].child = entry;
5089
ad1cdc1d
MM
5090 if (entry == NULL)
5091 return;
5092
6ad4c188 5093 for_each_possible_cpu(i) {
e692ab53 5094 snprintf(buf, 32, "cpu%d", i);
e692ab53 5095 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5096 entry->mode = 0555;
e692ab53 5097 entry->child = sd_alloc_ctl_cpu_table(i);
97b6ea7b 5098 entry++;
e692ab53 5099 }
7378547f
MM
5100
5101 WARN_ON(sd_sysctl_header);
e692ab53
NP
5102 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5103}
6382bc90 5104
7378547f 5105/* may be called multiple times per register */
6382bc90
MM
5106static void unregister_sched_domain_sysctl(void)
5107{
7378547f
MM
5108 if (sd_sysctl_header)
5109 unregister_sysctl_table(sd_sysctl_header);
6382bc90 5110 sd_sysctl_header = NULL;
7378547f
MM
5111 if (sd_ctl_dir[0].child)
5112 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6382bc90 5113}
e692ab53 5114#else
6382bc90
MM
5115static void register_sched_domain_sysctl(void)
5116{
5117}
5118static void unregister_sched_domain_sysctl(void)
e692ab53
NP
5119{
5120}
5121#endif
5122
1f11eb6a
GH
5123static void set_rq_online(struct rq *rq)
5124{
5125 if (!rq->online) {
5126 const struct sched_class *class;
5127
c6c4927b 5128 cpumask_set_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5129 rq->online = 1;
5130
5131 for_each_class(class) {
5132 if (class->rq_online)
5133 class->rq_online(rq);
5134 }
5135 }
5136}
5137
5138static void set_rq_offline(struct rq *rq)
5139{
5140 if (rq->online) {
5141 const struct sched_class *class;
5142
5143 for_each_class(class) {
5144 if (class->rq_offline)
5145 class->rq_offline(rq);
5146 }
5147
c6c4927b 5148 cpumask_clear_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5149 rq->online = 0;
5150 }
5151}
5152
1da177e4
LT
5153/*
5154 * migration_call - callback that gets triggered when a CPU is added.
5155 * Here we can start up the necessary migration thread for the new CPU.
5156 */
48f24c4d
IM
5157static int __cpuinit
5158migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
1da177e4 5159{
48f24c4d 5160 int cpu = (long)hcpu;
1da177e4 5161 unsigned long flags;
969c7921 5162 struct rq *rq = cpu_rq(cpu);
1da177e4 5163
48c5ccae 5164 switch (action & ~CPU_TASKS_FROZEN) {
5be9361c 5165
1da177e4 5166 case CPU_UP_PREPARE:
a468d389 5167 rq->calc_load_update = calc_load_update;
1da177e4 5168 break;
48f24c4d 5169
1da177e4 5170 case CPU_ONLINE:
1f94ef59 5171 /* Update our root-domain */
05fa785c 5172 raw_spin_lock_irqsave(&rq->lock, flags);
1f94ef59 5173 if (rq->rd) {
c6c4927b 5174 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
1f11eb6a
GH
5175
5176 set_rq_online(rq);
1f94ef59 5177 }
05fa785c 5178 raw_spin_unlock_irqrestore(&rq->lock, flags);
1da177e4 5179 break;
48f24c4d 5180
1da177e4 5181#ifdef CONFIG_HOTPLUG_CPU
08f503b0 5182 case CPU_DYING:
317f3941 5183 sched_ttwu_pending();
57d885fe 5184 /* Update our root-domain */
05fa785c 5185 raw_spin_lock_irqsave(&rq->lock, flags);
57d885fe 5186 if (rq->rd) {
c6c4927b 5187 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
1f11eb6a 5188 set_rq_offline(rq);
57d885fe 5189 }
48c5ccae
PZ
5190 migrate_tasks(cpu);
5191 BUG_ON(rq->nr_running != 1); /* the migration thread */
05fa785c 5192 raw_spin_unlock_irqrestore(&rq->lock, flags);
5d180232 5193 break;
48c5ccae 5194
5d180232 5195 case CPU_DEAD:
f319da0c 5196 calc_load_migrate(rq);
57d885fe 5197 break;
1da177e4
LT
5198#endif
5199 }
49c022e6
PZ
5200
5201 update_max_interval();
5202
1da177e4
LT
5203 return NOTIFY_OK;
5204}
5205
f38b0820
PM
5206/*
5207 * Register at high priority so that task migration (migrate_all_tasks)
5208 * happens before everything else. This has to be lower priority than
cdd6c482 5209 * the notifier in the perf_event subsystem, though.
1da177e4 5210 */
26c2143b 5211static struct notifier_block __cpuinitdata migration_notifier = {
1da177e4 5212 .notifier_call = migration_call,
50a323b7 5213 .priority = CPU_PRI_MIGRATION,
1da177e4
LT
5214};
5215
3a101d05
TH
5216static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
5217 unsigned long action, void *hcpu)
5218{
5219 switch (action & ~CPU_TASKS_FROZEN) {
5fbd036b 5220 case CPU_STARTING:
3a101d05
TH
5221 case CPU_DOWN_FAILED:
5222 set_cpu_active((long)hcpu, true);
5223 return NOTIFY_OK;
5224 default:
5225 return NOTIFY_DONE;
5226 }
5227}
5228
5229static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
5230 unsigned long action, void *hcpu)
5231{
5232 switch (action & ~CPU_TASKS_FROZEN) {
5233 case CPU_DOWN_PREPARE:
5234 set_cpu_active((long)hcpu, false);
5235 return NOTIFY_OK;
5236 default:
5237 return NOTIFY_DONE;
5238 }
5239}
5240
7babe8db 5241static int __init migration_init(void)
1da177e4
LT
5242{
5243 void *cpu = (void *)(long)smp_processor_id();
07dccf33 5244 int err;
48f24c4d 5245
3a101d05 5246 /* Initialize migration for the boot CPU */
07dccf33
AM
5247 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5248 BUG_ON(err == NOTIFY_BAD);
1da177e4
LT
5249 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5250 register_cpu_notifier(&migration_notifier);
7babe8db 5251
3a101d05
TH
5252 /* Register cpu active notifiers */
5253 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5254 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5255
a004cd42 5256 return 0;
1da177e4 5257}
7babe8db 5258early_initcall(migration_init);
1da177e4
LT
5259#endif
5260
5261#ifdef CONFIG_SMP
476f3534 5262
4cb98839
PZ
5263static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5264
3e9830dc 5265#ifdef CONFIG_SCHED_DEBUG
4dcf6aff 5266
d039ac60 5267static __read_mostly int sched_debug_enabled;
f6630114 5268
d039ac60 5269static int __init sched_debug_setup(char *str)
f6630114 5270{
d039ac60 5271 sched_debug_enabled = 1;
f6630114
MT
5272
5273 return 0;
5274}
d039ac60
PZ
5275early_param("sched_debug", sched_debug_setup);
5276
5277static inline bool sched_debug(void)
5278{
5279 return sched_debug_enabled;
5280}
f6630114 5281
7c16ec58 5282static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
96f874e2 5283 struct cpumask *groupmask)
1da177e4 5284{
4dcf6aff 5285 struct sched_group *group = sd->groups;
434d53b0 5286 char str[256];
1da177e4 5287
968ea6d8 5288 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
96f874e2 5289 cpumask_clear(groupmask);
4dcf6aff
IM
5290
5291 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5292
5293 if (!(sd->flags & SD_LOAD_BALANCE)) {
3df0fc5b 5294 printk("does not load-balance\n");
4dcf6aff 5295 if (sd->parent)
3df0fc5b
PZ
5296 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5297 " has parent");
4dcf6aff 5298 return -1;
41c7ce9a
NP
5299 }
5300
3df0fc5b 5301 printk(KERN_CONT "span %s level %s\n", str, sd->name);
4dcf6aff 5302
758b2cdc 5303 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
3df0fc5b
PZ
5304 printk(KERN_ERR "ERROR: domain->span does not contain "
5305 "CPU%d\n", cpu);
4dcf6aff 5306 }
758b2cdc 5307 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
3df0fc5b
PZ
5308 printk(KERN_ERR "ERROR: domain->groups does not contain"
5309 " CPU%d\n", cpu);
4dcf6aff 5310 }
1da177e4 5311
4dcf6aff 5312 printk(KERN_DEBUG "%*s groups:", level + 1, "");
1da177e4 5313 do {
4dcf6aff 5314 if (!group) {
3df0fc5b
PZ
5315 printk("\n");
5316 printk(KERN_ERR "ERROR: group is NULL\n");
1da177e4
LT
5317 break;
5318 }
5319
c3decf0d
PZ
5320 /*
5321 * Even though we initialize ->power to something semi-sane,
5322 * we leave power_orig unset. This allows us to detect if
5323 * domain iteration is still funny without causing /0 traps.
5324 */
5325 if (!group->sgp->power_orig) {
3df0fc5b
PZ
5326 printk(KERN_CONT "\n");
5327 printk(KERN_ERR "ERROR: domain->cpu_power not "
5328 "set\n");
4dcf6aff
IM
5329 break;
5330 }
1da177e4 5331
758b2cdc 5332 if (!cpumask_weight(sched_group_cpus(group))) {
3df0fc5b
PZ
5333 printk(KERN_CONT "\n");
5334 printk(KERN_ERR "ERROR: empty group\n");
4dcf6aff
IM
5335 break;
5336 }
1da177e4 5337
cb83b629
PZ
5338 if (!(sd->flags & SD_OVERLAP) &&
5339 cpumask_intersects(groupmask, sched_group_cpus(group))) {
3df0fc5b
PZ
5340 printk(KERN_CONT "\n");
5341 printk(KERN_ERR "ERROR: repeated CPUs\n");
4dcf6aff
IM
5342 break;
5343 }
1da177e4 5344
758b2cdc 5345 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
1da177e4 5346
968ea6d8 5347 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
381512cf 5348
3df0fc5b 5349 printk(KERN_CONT " %s", str);
9c3f75cb 5350 if (group->sgp->power != SCHED_POWER_SCALE) {
3df0fc5b 5351 printk(KERN_CONT " (cpu_power = %d)",
9c3f75cb 5352 group->sgp->power);
381512cf 5353 }
1da177e4 5354
4dcf6aff
IM
5355 group = group->next;
5356 } while (group != sd->groups);
3df0fc5b 5357 printk(KERN_CONT "\n");
1da177e4 5358
758b2cdc 5359 if (!cpumask_equal(sched_domain_span(sd), groupmask))
3df0fc5b 5360 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
1da177e4 5361
758b2cdc
RR
5362 if (sd->parent &&
5363 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
3df0fc5b
PZ
5364 printk(KERN_ERR "ERROR: parent span is not a superset "
5365 "of domain->span\n");
4dcf6aff
IM
5366 return 0;
5367}
1da177e4 5368
4dcf6aff
IM
5369static void sched_domain_debug(struct sched_domain *sd, int cpu)
5370{
5371 int level = 0;
1da177e4 5372
d039ac60 5373 if (!sched_debug_enabled)
f6630114
MT
5374 return;
5375
4dcf6aff
IM
5376 if (!sd) {
5377 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5378 return;
5379 }
1da177e4 5380
4dcf6aff
IM
5381 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5382
5383 for (;;) {
4cb98839 5384 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
4dcf6aff 5385 break;
1da177e4
LT
5386 level++;
5387 sd = sd->parent;
33859f7f 5388 if (!sd)
4dcf6aff
IM
5389 break;
5390 }
1da177e4 5391}
6d6bc0ad 5392#else /* !CONFIG_SCHED_DEBUG */
48f24c4d 5393# define sched_domain_debug(sd, cpu) do { } while (0)
d039ac60
PZ
5394static inline bool sched_debug(void)
5395{
5396 return false;
5397}
6d6bc0ad 5398#endif /* CONFIG_SCHED_DEBUG */
1da177e4 5399
1a20ff27 5400static int sd_degenerate(struct sched_domain *sd)
245af2c7 5401{
758b2cdc 5402 if (cpumask_weight(sched_domain_span(sd)) == 1)
245af2c7
SS
5403 return 1;
5404
5405 /* Following flags need at least 2 groups */
5406 if (sd->flags & (SD_LOAD_BALANCE |
5407 SD_BALANCE_NEWIDLE |
5408 SD_BALANCE_FORK |
89c4710e
SS
5409 SD_BALANCE_EXEC |
5410 SD_SHARE_CPUPOWER |
5411 SD_SHARE_PKG_RESOURCES)) {
245af2c7
SS
5412 if (sd->groups != sd->groups->next)
5413 return 0;
5414 }
5415
5416 /* Following flags don't use groups */
c88d5910 5417 if (sd->flags & (SD_WAKE_AFFINE))
245af2c7
SS
5418 return 0;
5419
5420 return 1;
5421}
5422
48f24c4d
IM
5423static int
5424sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
245af2c7
SS
5425{
5426 unsigned long cflags = sd->flags, pflags = parent->flags;
5427
5428 if (sd_degenerate(parent))
5429 return 1;
5430
758b2cdc 5431 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
245af2c7
SS
5432 return 0;
5433
245af2c7
SS
5434 /* Flags needing groups don't count if only 1 group in parent */
5435 if (parent->groups == parent->groups->next) {
5436 pflags &= ~(SD_LOAD_BALANCE |
5437 SD_BALANCE_NEWIDLE |
5438 SD_BALANCE_FORK |
89c4710e
SS
5439 SD_BALANCE_EXEC |
5440 SD_SHARE_CPUPOWER |
5441 SD_SHARE_PKG_RESOURCES);
5436499e
KC
5442 if (nr_node_ids == 1)
5443 pflags &= ~SD_SERIALIZE;
245af2c7
SS
5444 }
5445 if (~cflags & pflags)
5446 return 0;
5447
5448 return 1;
5449}
5450
dce840a0 5451static void free_rootdomain(struct rcu_head *rcu)
c6c4927b 5452{
dce840a0 5453 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
047106ad 5454
68e74568 5455 cpupri_cleanup(&rd->cpupri);
c6c4927b
RR
5456 free_cpumask_var(rd->rto_mask);
5457 free_cpumask_var(rd->online);
5458 free_cpumask_var(rd->span);
5459 kfree(rd);
5460}
5461
57d885fe
GH
5462static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5463{
a0490fa3 5464 struct root_domain *old_rd = NULL;
57d885fe 5465 unsigned long flags;
57d885fe 5466
05fa785c 5467 raw_spin_lock_irqsave(&rq->lock, flags);
57d885fe
GH
5468
5469 if (rq->rd) {
a0490fa3 5470 old_rd = rq->rd;
57d885fe 5471
c6c4927b 5472 if (cpumask_test_cpu(rq->cpu, old_rd->online))
1f11eb6a 5473 set_rq_offline(rq);
57d885fe 5474
c6c4927b 5475 cpumask_clear_cpu(rq->cpu, old_rd->span);
dc938520 5476
a0490fa3
IM
5477 /*
5478 * If we dont want to free the old_rt yet then
5479 * set old_rd to NULL to skip the freeing later
5480 * in this function:
5481 */
5482 if (!atomic_dec_and_test(&old_rd->refcount))
5483 old_rd = NULL;
57d885fe
GH
5484 }
5485
5486 atomic_inc(&rd->refcount);
5487 rq->rd = rd;
5488
c6c4927b 5489 cpumask_set_cpu(rq->cpu, rd->span);
00aec93d 5490 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
1f11eb6a 5491 set_rq_online(rq);
57d885fe 5492
05fa785c 5493 raw_spin_unlock_irqrestore(&rq->lock, flags);
a0490fa3
IM
5494
5495 if (old_rd)
dce840a0 5496 call_rcu_sched(&old_rd->rcu, free_rootdomain);
57d885fe
GH
5497}
5498
68c38fc3 5499static int init_rootdomain(struct root_domain *rd)
57d885fe
GH
5500{
5501 memset(rd, 0, sizeof(*rd));
5502
68c38fc3 5503 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
0c910d28 5504 goto out;
68c38fc3 5505 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
c6c4927b 5506 goto free_span;
68c38fc3 5507 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
c6c4927b 5508 goto free_online;
6e0534f2 5509
68c38fc3 5510 if (cpupri_init(&rd->cpupri) != 0)
68e74568 5511 goto free_rto_mask;
c6c4927b 5512 return 0;
6e0534f2 5513
68e74568
RR
5514free_rto_mask:
5515 free_cpumask_var(rd->rto_mask);
c6c4927b
RR
5516free_online:
5517 free_cpumask_var(rd->online);
5518free_span:
5519 free_cpumask_var(rd->span);
0c910d28 5520out:
c6c4927b 5521 return -ENOMEM;
57d885fe
GH
5522}
5523
029632fb
PZ
5524/*
5525 * By default the system creates a single root-domain with all cpus as
5526 * members (mimicking the global state we have today).
5527 */
5528struct root_domain def_root_domain;
5529
57d885fe
GH
5530static void init_defrootdomain(void)
5531{
68c38fc3 5532 init_rootdomain(&def_root_domain);
c6c4927b 5533
57d885fe
GH
5534 atomic_set(&def_root_domain.refcount, 1);
5535}
5536
dc938520 5537static struct root_domain *alloc_rootdomain(void)
57d885fe
GH
5538{
5539 struct root_domain *rd;
5540
5541 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5542 if (!rd)
5543 return NULL;
5544
68c38fc3 5545 if (init_rootdomain(rd) != 0) {
c6c4927b
RR
5546 kfree(rd);
5547 return NULL;
5548 }
57d885fe
GH
5549
5550 return rd;
5551}
5552
e3589f6c
PZ
5553static void free_sched_groups(struct sched_group *sg, int free_sgp)
5554{
5555 struct sched_group *tmp, *first;
5556
5557 if (!sg)
5558 return;
5559
5560 first = sg;
5561 do {
5562 tmp = sg->next;
5563
5564 if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
5565 kfree(sg->sgp);
5566
5567 kfree(sg);
5568 sg = tmp;
5569 } while (sg != first);
5570}
5571
dce840a0
PZ
5572static void free_sched_domain(struct rcu_head *rcu)
5573{
5574 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
e3589f6c
PZ
5575
5576 /*
5577 * If its an overlapping domain it has private groups, iterate and
5578 * nuke them all.
5579 */
5580 if (sd->flags & SD_OVERLAP) {
5581 free_sched_groups(sd->groups, 1);
5582 } else if (atomic_dec_and_test(&sd->groups->ref)) {
9c3f75cb 5583 kfree(sd->groups->sgp);
dce840a0 5584 kfree(sd->groups);
9c3f75cb 5585 }
dce840a0
PZ
5586 kfree(sd);
5587}
5588
5589static void destroy_sched_domain(struct sched_domain *sd, int cpu)
5590{
5591 call_rcu(&sd->rcu, free_sched_domain);
5592}
5593
5594static void destroy_sched_domains(struct sched_domain *sd, int cpu)
5595{
5596 for (; sd; sd = sd->parent)
5597 destroy_sched_domain(sd, cpu);
5598}
5599
518cd623
PZ
5600/*
5601 * Keep a special pointer to the highest sched_domain that has
5602 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
5603 * allows us to avoid some pointer chasing select_idle_sibling().
5604 *
5605 * Also keep a unique ID per domain (we use the first cpu number in
5606 * the cpumask of the domain), this allows us to quickly tell if
39be3501 5607 * two cpus are in the same cache domain, see cpus_share_cache().
518cd623
PZ
5608 */
5609DEFINE_PER_CPU(struct sched_domain *, sd_llc);
5610DEFINE_PER_CPU(int, sd_llc_id);
5611
5612static void update_top_cache_domain(int cpu)
5613{
5614 struct sched_domain *sd;
5615 int id = cpu;
5616
5617 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
37407ea7 5618 if (sd)
518cd623
PZ
5619 id = cpumask_first(sched_domain_span(sd));
5620
5621 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
5622 per_cpu(sd_llc_id, cpu) = id;
5623}
5624
1da177e4 5625/*
0eab9146 5626 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
1da177e4
LT
5627 * hold the hotplug lock.
5628 */
0eab9146
IM
5629static void
5630cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
1da177e4 5631{
70b97a7f 5632 struct rq *rq = cpu_rq(cpu);
245af2c7
SS
5633 struct sched_domain *tmp;
5634
5635 /* Remove the sched domains which do not contribute to scheduling. */
f29c9b1c 5636 for (tmp = sd; tmp; ) {
245af2c7
SS
5637 struct sched_domain *parent = tmp->parent;
5638 if (!parent)
5639 break;
f29c9b1c 5640
1a848870 5641 if (sd_parent_degenerate(tmp, parent)) {
245af2c7 5642 tmp->parent = parent->parent;
1a848870
SS
5643 if (parent->parent)
5644 parent->parent->child = tmp;
dce840a0 5645 destroy_sched_domain(parent, cpu);
f29c9b1c
LZ
5646 } else
5647 tmp = tmp->parent;
245af2c7
SS
5648 }
5649
1a848870 5650 if (sd && sd_degenerate(sd)) {
dce840a0 5651 tmp = sd;
245af2c7 5652 sd = sd->parent;
dce840a0 5653 destroy_sched_domain(tmp, cpu);
1a848870
SS
5654 if (sd)
5655 sd->child = NULL;
5656 }
1da177e4 5657
4cb98839 5658 sched_domain_debug(sd, cpu);
1da177e4 5659
57d885fe 5660 rq_attach_root(rq, rd);
dce840a0 5661 tmp = rq->sd;
674311d5 5662 rcu_assign_pointer(rq->sd, sd);
dce840a0 5663 destroy_sched_domains(tmp, cpu);
518cd623
PZ
5664
5665 update_top_cache_domain(cpu);
1da177e4
LT
5666}
5667
5668/* cpus with isolated domains */
dcc30a35 5669static cpumask_var_t cpu_isolated_map;
1da177e4
LT
5670
5671/* Setup the mask of cpus configured for isolated domains */
5672static int __init isolated_cpu_setup(char *str)
5673{
bdddd296 5674 alloc_bootmem_cpumask_var(&cpu_isolated_map);
968ea6d8 5675 cpulist_parse(str, cpu_isolated_map);
1da177e4
LT
5676 return 1;
5677}
5678
8927f494 5679__setup("isolcpus=", isolated_cpu_setup);
1da177e4 5680
d3081f52
PZ
5681static const struct cpumask *cpu_cpu_mask(int cpu)
5682{
5683 return cpumask_of_node(cpu_to_node(cpu));
5684}
5685
dce840a0
PZ
5686struct sd_data {
5687 struct sched_domain **__percpu sd;
5688 struct sched_group **__percpu sg;
9c3f75cb 5689 struct sched_group_power **__percpu sgp;
dce840a0
PZ
5690};
5691
49a02c51 5692struct s_data {
21d42ccf 5693 struct sched_domain ** __percpu sd;
49a02c51
AH
5694 struct root_domain *rd;
5695};
5696
2109b99e 5697enum s_alloc {
2109b99e 5698 sa_rootdomain,
21d42ccf 5699 sa_sd,
dce840a0 5700 sa_sd_storage,
2109b99e
AH
5701 sa_none,
5702};
5703
54ab4ff4
PZ
5704struct sched_domain_topology_level;
5705
5706typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
eb7a74e6
PZ
5707typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
5708
e3589f6c
PZ
5709#define SDTL_OVERLAP 0x01
5710
eb7a74e6 5711struct sched_domain_topology_level {
2c402dc3
PZ
5712 sched_domain_init_f init;
5713 sched_domain_mask_f mask;
e3589f6c 5714 int flags;
cb83b629 5715 int numa_level;
54ab4ff4 5716 struct sd_data data;
eb7a74e6
PZ
5717};
5718
c1174876
PZ
5719/*
5720 * Build an iteration mask that can exclude certain CPUs from the upwards
5721 * domain traversal.
5722 *
5723 * Asymmetric node setups can result in situations where the domain tree is of
5724 * unequal depth, make sure to skip domains that already cover the entire
5725 * range.
5726 *
5727 * In that case build_sched_domains() will have terminated the iteration early
5728 * and our sibling sd spans will be empty. Domains should always include the
5729 * cpu they're built on, so check that.
5730 *
5731 */
5732static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
5733{
5734 const struct cpumask *span = sched_domain_span(sd);
5735 struct sd_data *sdd = sd->private;
5736 struct sched_domain *sibling;
5737 int i;
5738
5739 for_each_cpu(i, span) {
5740 sibling = *per_cpu_ptr(sdd->sd, i);
5741 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
5742 continue;
5743
5744 cpumask_set_cpu(i, sched_group_mask(sg));
5745 }
5746}
5747
5748/*
5749 * Return the canonical balance cpu for this group, this is the first cpu
5750 * of this group that's also in the iteration mask.
5751 */
5752int group_balance_cpu(struct sched_group *sg)
5753{
5754 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
5755}
5756
e3589f6c
PZ
5757static int
5758build_overlap_sched_groups(struct sched_domain *sd, int cpu)
5759{
5760 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
5761 const struct cpumask *span = sched_domain_span(sd);
5762 struct cpumask *covered = sched_domains_tmpmask;
5763 struct sd_data *sdd = sd->private;
5764 struct sched_domain *child;
5765 int i;
5766
5767 cpumask_clear(covered);
5768
5769 for_each_cpu(i, span) {
5770 struct cpumask *sg_span;
5771
5772 if (cpumask_test_cpu(i, covered))
5773 continue;
5774
c1174876
PZ
5775 child = *per_cpu_ptr(sdd->sd, i);
5776
5777 /* See the comment near build_group_mask(). */
5778 if (!cpumask_test_cpu(i, sched_domain_span(child)))
5779 continue;
5780
e3589f6c 5781 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
4d78a223 5782 GFP_KERNEL, cpu_to_node(cpu));
e3589f6c
PZ
5783
5784 if (!sg)
5785 goto fail;
5786
5787 sg_span = sched_group_cpus(sg);
e3589f6c
PZ
5788 if (child->child) {
5789 child = child->child;
5790 cpumask_copy(sg_span, sched_domain_span(child));
5791 } else
5792 cpumask_set_cpu(i, sg_span);
5793
5794 cpumask_or(covered, covered, sg_span);
5795
74a5ce20 5796 sg->sgp = *per_cpu_ptr(sdd->sgp, i);
c1174876
PZ
5797 if (atomic_inc_return(&sg->sgp->ref) == 1)
5798 build_group_mask(sd, sg);
5799
c3decf0d
PZ
5800 /*
5801 * Initialize sgp->power such that even if we mess up the
5802 * domains and no possible iteration will get us here, we won't
5803 * die on a /0 trap.
5804 */
5805 sg->sgp->power = SCHED_POWER_SCALE * cpumask_weight(sg_span);
e3589f6c 5806
c1174876
PZ
5807 /*
5808 * Make sure the first group of this domain contains the
5809 * canonical balance cpu. Otherwise the sched_domain iteration
5810 * breaks. See update_sg_lb_stats().
5811 */
74a5ce20 5812 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
c1174876 5813 group_balance_cpu(sg) == cpu)
e3589f6c
PZ
5814 groups = sg;
5815
5816 if (!first)
5817 first = sg;
5818 if (last)
5819 last->next = sg;
5820 last = sg;
5821 last->next = first;
5822 }
5823 sd->groups = groups;
5824
5825 return 0;
5826
5827fail:
5828 free_sched_groups(first, 0);
5829
5830 return -ENOMEM;
5831}
5832
dce840a0 5833static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
1da177e4 5834{
dce840a0
PZ
5835 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
5836 struct sched_domain *child = sd->child;
1da177e4 5837
dce840a0
PZ
5838 if (child)
5839 cpu = cpumask_first(sched_domain_span(child));
1e9f28fa 5840
9c3f75cb 5841 if (sg) {
dce840a0 5842 *sg = *per_cpu_ptr(sdd->sg, cpu);
9c3f75cb 5843 (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
e3589f6c 5844 atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
9c3f75cb 5845 }
dce840a0
PZ
5846
5847 return cpu;
1e9f28fa 5848}
1e9f28fa 5849
01a08546 5850/*
dce840a0
PZ
5851 * build_sched_groups will build a circular linked list of the groups
5852 * covered by the given span, and will set each group's ->cpumask correctly,
5853 * and ->cpu_power to 0.
e3589f6c
PZ
5854 *
5855 * Assumes the sched_domain tree is fully constructed
01a08546 5856 */
e3589f6c
PZ
5857static int
5858build_sched_groups(struct sched_domain *sd, int cpu)
1da177e4 5859{
dce840a0
PZ
5860 struct sched_group *first = NULL, *last = NULL;
5861 struct sd_data *sdd = sd->private;
5862 const struct cpumask *span = sched_domain_span(sd);
f96225fd 5863 struct cpumask *covered;
dce840a0 5864 int i;
9c1cfda2 5865
e3589f6c
PZ
5866 get_group(cpu, sdd, &sd->groups);
5867 atomic_inc(&sd->groups->ref);
5868
5869 if (cpu != cpumask_first(sched_domain_span(sd)))
5870 return 0;
5871
f96225fd
PZ
5872 lockdep_assert_held(&sched_domains_mutex);
5873 covered = sched_domains_tmpmask;
5874
dce840a0 5875 cpumask_clear(covered);
6711cab4 5876
dce840a0
PZ
5877 for_each_cpu(i, span) {
5878 struct sched_group *sg;
5879 int group = get_group(i, sdd, &sg);
5880 int j;
6711cab4 5881
dce840a0
PZ
5882 if (cpumask_test_cpu(i, covered))
5883 continue;
6711cab4 5884
dce840a0 5885 cpumask_clear(sched_group_cpus(sg));
9c3f75cb 5886 sg->sgp->power = 0;
c1174876 5887 cpumask_setall(sched_group_mask(sg));
0601a88d 5888
dce840a0
PZ
5889 for_each_cpu(j, span) {
5890 if (get_group(j, sdd, NULL) != group)
5891 continue;
0601a88d 5892
dce840a0
PZ
5893 cpumask_set_cpu(j, covered);
5894 cpumask_set_cpu(j, sched_group_cpus(sg));
5895 }
0601a88d 5896
dce840a0
PZ
5897 if (!first)
5898 first = sg;
5899 if (last)
5900 last->next = sg;
5901 last = sg;
5902 }
5903 last->next = first;
e3589f6c
PZ
5904
5905 return 0;
0601a88d 5906}
51888ca2 5907
89c4710e
SS
5908/*
5909 * Initialize sched groups cpu_power.
5910 *
5911 * cpu_power indicates the capacity of sched group, which is used while
5912 * distributing the load between different sched groups in a sched domain.
5913 * Typically cpu_power for all the groups in a sched domain will be same unless
5914 * there are asymmetries in the topology. If there are asymmetries, group
5915 * having more cpu_power will pickup more load compared to the group having
5916 * less cpu_power.
89c4710e
SS
5917 */
5918static void init_sched_groups_power(int cpu, struct sched_domain *sd)
5919{
e3589f6c 5920 struct sched_group *sg = sd->groups;
89c4710e 5921
e3589f6c
PZ
5922 WARN_ON(!sd || !sg);
5923
5924 do {
5925 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
5926 sg = sg->next;
5927 } while (sg != sd->groups);
89c4710e 5928
c1174876 5929 if (cpu != group_balance_cpu(sg))
e3589f6c 5930 return;
aae6d3dd 5931
d274cb30 5932 update_group_power(sd, cpu);
69e1e811 5933 atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight);
89c4710e
SS
5934}
5935
029632fb
PZ
5936int __weak arch_sd_sibling_asym_packing(void)
5937{
5938 return 0*SD_ASYM_PACKING;
89c4710e
SS
5939}
5940
7c16ec58
MT
5941/*
5942 * Initializers for schedule domains
5943 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
5944 */
5945
a5d8c348
IM
5946#ifdef CONFIG_SCHED_DEBUG
5947# define SD_INIT_NAME(sd, type) sd->name = #type
5948#else
5949# define SD_INIT_NAME(sd, type) do { } while (0)
5950#endif
5951
54ab4ff4
PZ
5952#define SD_INIT_FUNC(type) \
5953static noinline struct sched_domain * \
5954sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \
5955{ \
5956 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \
5957 *sd = SD_##type##_INIT; \
54ab4ff4
PZ
5958 SD_INIT_NAME(sd, type); \
5959 sd->private = &tl->data; \
5960 return sd; \
7c16ec58
MT
5961}
5962
5963SD_INIT_FUNC(CPU)
7c16ec58
MT
5964#ifdef CONFIG_SCHED_SMT
5965 SD_INIT_FUNC(SIBLING)
5966#endif
5967#ifdef CONFIG_SCHED_MC
5968 SD_INIT_FUNC(MC)
5969#endif
01a08546
HC
5970#ifdef CONFIG_SCHED_BOOK
5971 SD_INIT_FUNC(BOOK)
5972#endif
7c16ec58 5973
1d3504fc 5974static int default_relax_domain_level = -1;
60495e77 5975int sched_domain_level_max;
1d3504fc
HS
5976
5977static int __init setup_relax_domain_level(char *str)
5978{
a841f8ce
DS
5979 if (kstrtoint(str, 0, &default_relax_domain_level))
5980 pr_warn("Unable to set relax_domain_level\n");
30e0e178 5981
1d3504fc
HS
5982 return 1;
5983}
5984__setup("relax_domain_level=", setup_relax_domain_level);
5985
5986static void set_domain_attribute(struct sched_domain *sd,
5987 struct sched_domain_attr *attr)
5988{
5989 int request;
5990
5991 if (!attr || attr->relax_domain_level < 0) {
5992 if (default_relax_domain_level < 0)
5993 return;
5994 else
5995 request = default_relax_domain_level;
5996 } else
5997 request = attr->relax_domain_level;
5998 if (request < sd->level) {
5999 /* turn off idle balance on this domain */
c88d5910 6000 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
1d3504fc
HS
6001 } else {
6002 /* turn on idle balance on this domain */
c88d5910 6003 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
1d3504fc
HS
6004 }
6005}
6006
54ab4ff4
PZ
6007static void __sdt_free(const struct cpumask *cpu_map);
6008static int __sdt_alloc(const struct cpumask *cpu_map);
6009
2109b99e
AH
6010static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6011 const struct cpumask *cpu_map)
6012{
6013 switch (what) {
2109b99e 6014 case sa_rootdomain:
822ff793
PZ
6015 if (!atomic_read(&d->rd->refcount))
6016 free_rootdomain(&d->rd->rcu); /* fall through */
21d42ccf
PZ
6017 case sa_sd:
6018 free_percpu(d->sd); /* fall through */
dce840a0 6019 case sa_sd_storage:
54ab4ff4 6020 __sdt_free(cpu_map); /* fall through */
2109b99e
AH
6021 case sa_none:
6022 break;
6023 }
6024}
3404c8d9 6025
2109b99e
AH
6026static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6027 const struct cpumask *cpu_map)
6028{
dce840a0
PZ
6029 memset(d, 0, sizeof(*d));
6030
54ab4ff4
PZ
6031 if (__sdt_alloc(cpu_map))
6032 return sa_sd_storage;
dce840a0
PZ
6033 d->sd = alloc_percpu(struct sched_domain *);
6034 if (!d->sd)
6035 return sa_sd_storage;
2109b99e 6036 d->rd = alloc_rootdomain();
dce840a0 6037 if (!d->rd)
21d42ccf 6038 return sa_sd;
2109b99e
AH
6039 return sa_rootdomain;
6040}
57d885fe 6041
dce840a0
PZ
6042/*
6043 * NULL the sd_data elements we've used to build the sched_domain and
6044 * sched_group structure so that the subsequent __free_domain_allocs()
6045 * will not free the data we're using.
6046 */
6047static void claim_allocations(int cpu, struct sched_domain *sd)
6048{
6049 struct sd_data *sdd = sd->private;
dce840a0
PZ
6050
6051 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6052 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6053
e3589f6c 6054 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
dce840a0 6055 *per_cpu_ptr(sdd->sg, cpu) = NULL;
e3589f6c
PZ
6056
6057 if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
9c3f75cb 6058 *per_cpu_ptr(sdd->sgp, cpu) = NULL;
dce840a0
PZ
6059}
6060
2c402dc3
PZ
6061#ifdef CONFIG_SCHED_SMT
6062static const struct cpumask *cpu_smt_mask(int cpu)
7f4588f3 6063{
2c402dc3 6064 return topology_thread_cpumask(cpu);
3bd65a80 6065}
2c402dc3 6066#endif
7f4588f3 6067
d069b916
PZ
6068/*
6069 * Topology list, bottom-up.
6070 */
2c402dc3 6071static struct sched_domain_topology_level default_topology[] = {
d069b916
PZ
6072#ifdef CONFIG_SCHED_SMT
6073 { sd_init_SIBLING, cpu_smt_mask, },
01a08546 6074#endif
1e9f28fa 6075#ifdef CONFIG_SCHED_MC
2c402dc3 6076 { sd_init_MC, cpu_coregroup_mask, },
1e9f28fa 6077#endif
d069b916
PZ
6078#ifdef CONFIG_SCHED_BOOK
6079 { sd_init_BOOK, cpu_book_mask, },
6080#endif
6081 { sd_init_CPU, cpu_cpu_mask, },
eb7a74e6
PZ
6082 { NULL, },
6083};
6084
6085static struct sched_domain_topology_level *sched_domain_topology = default_topology;
6086
cb83b629
PZ
6087#ifdef CONFIG_NUMA
6088
6089static int sched_domains_numa_levels;
cb83b629
PZ
6090static int *sched_domains_numa_distance;
6091static struct cpumask ***sched_domains_numa_masks;
6092static int sched_domains_curr_level;
6093
cb83b629
PZ
6094static inline int sd_local_flags(int level)
6095{
10717dcd 6096 if (sched_domains_numa_distance[level] > RECLAIM_DISTANCE)
cb83b629
PZ
6097 return 0;
6098
6099 return SD_BALANCE_EXEC | SD_BALANCE_FORK | SD_WAKE_AFFINE;
6100}
6101
6102static struct sched_domain *
6103sd_numa_init(struct sched_domain_topology_level *tl, int cpu)
6104{
6105 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6106 int level = tl->numa_level;
6107 int sd_weight = cpumask_weight(
6108 sched_domains_numa_masks[level][cpu_to_node(cpu)]);
6109
6110 *sd = (struct sched_domain){
6111 .min_interval = sd_weight,
6112 .max_interval = 2*sd_weight,
6113 .busy_factor = 32,
870a0bb5 6114 .imbalance_pct = 125,
cb83b629
PZ
6115 .cache_nice_tries = 2,
6116 .busy_idx = 3,
6117 .idle_idx = 2,
6118 .newidle_idx = 0,
6119 .wake_idx = 0,
6120 .forkexec_idx = 0,
6121
6122 .flags = 1*SD_LOAD_BALANCE
6123 | 1*SD_BALANCE_NEWIDLE
6124 | 0*SD_BALANCE_EXEC
6125 | 0*SD_BALANCE_FORK
6126 | 0*SD_BALANCE_WAKE
6127 | 0*SD_WAKE_AFFINE
cb83b629 6128 | 0*SD_SHARE_CPUPOWER
cb83b629
PZ
6129 | 0*SD_SHARE_PKG_RESOURCES
6130 | 1*SD_SERIALIZE
6131 | 0*SD_PREFER_SIBLING
6132 | sd_local_flags(level)
6133 ,
6134 .last_balance = jiffies,
6135 .balance_interval = sd_weight,
6136 };
6137 SD_INIT_NAME(sd, NUMA);
6138 sd->private = &tl->data;
6139
6140 /*
6141 * Ugly hack to pass state to sd_numa_mask()...
6142 */
6143 sched_domains_curr_level = tl->numa_level;
6144
6145 return sd;
6146}
6147
6148static const struct cpumask *sd_numa_mask(int cpu)
6149{
6150 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6151}
6152
d039ac60
PZ
6153static void sched_numa_warn(const char *str)
6154{
6155 static int done = false;
6156 int i,j;
6157
6158 if (done)
6159 return;
6160
6161 done = true;
6162
6163 printk(KERN_WARNING "ERROR: %s\n\n", str);
6164
6165 for (i = 0; i < nr_node_ids; i++) {
6166 printk(KERN_WARNING " ");
6167 for (j = 0; j < nr_node_ids; j++)
6168 printk(KERN_CONT "%02d ", node_distance(i,j));
6169 printk(KERN_CONT "\n");
6170 }
6171 printk(KERN_WARNING "\n");
6172}
6173
6174static bool find_numa_distance(int distance)
6175{
6176 int i;
6177
6178 if (distance == node_distance(0, 0))
6179 return true;
6180
6181 for (i = 0; i < sched_domains_numa_levels; i++) {
6182 if (sched_domains_numa_distance[i] == distance)
6183 return true;
6184 }
6185
6186 return false;
6187}
6188
cb83b629
PZ
6189static void sched_init_numa(void)
6190{
6191 int next_distance, curr_distance = node_distance(0, 0);
6192 struct sched_domain_topology_level *tl;
6193 int level = 0;
6194 int i, j, k;
6195
cb83b629
PZ
6196 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6197 if (!sched_domains_numa_distance)
6198 return;
6199
6200 /*
6201 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6202 * unique distances in the node_distance() table.
6203 *
6204 * Assumes node_distance(0,j) includes all distances in
6205 * node_distance(i,j) in order to avoid cubic time.
cb83b629
PZ
6206 */
6207 next_distance = curr_distance;
6208 for (i = 0; i < nr_node_ids; i++) {
6209 for (j = 0; j < nr_node_ids; j++) {
d039ac60
PZ
6210 for (k = 0; k < nr_node_ids; k++) {
6211 int distance = node_distance(i, k);
6212
6213 if (distance > curr_distance &&
6214 (distance < next_distance ||
6215 next_distance == curr_distance))
6216 next_distance = distance;
6217
6218 /*
6219 * While not a strong assumption it would be nice to know
6220 * about cases where if node A is connected to B, B is not
6221 * equally connected to A.
6222 */
6223 if (sched_debug() && node_distance(k, i) != distance)
6224 sched_numa_warn("Node-distance not symmetric");
6225
6226 if (sched_debug() && i && !find_numa_distance(distance))
6227 sched_numa_warn("Node-0 not representative");
6228 }
6229 if (next_distance != curr_distance) {
6230 sched_domains_numa_distance[level++] = next_distance;
6231 sched_domains_numa_levels = level;
6232 curr_distance = next_distance;
6233 } else break;
cb83b629 6234 }
d039ac60
PZ
6235
6236 /*
6237 * In case of sched_debug() we verify the above assumption.
6238 */
6239 if (!sched_debug())
6240 break;
cb83b629
PZ
6241 }
6242 /*
6243 * 'level' contains the number of unique distances, excluding the
6244 * identity distance node_distance(i,i).
6245 *
28b4a521 6246 * The sched_domains_numa_distance[] array includes the actual distance
cb83b629
PZ
6247 * numbers.
6248 */
6249
5f7865f3
TC
6250 /*
6251 * Here, we should temporarily reset sched_domains_numa_levels to 0.
6252 * If it fails to allocate memory for array sched_domains_numa_masks[][],
6253 * the array will contain less then 'level' members. This could be
6254 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6255 * in other functions.
6256 *
6257 * We reset it to 'level' at the end of this function.
6258 */
6259 sched_domains_numa_levels = 0;
6260
cb83b629
PZ
6261 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6262 if (!sched_domains_numa_masks)
6263 return;
6264
6265 /*
6266 * Now for each level, construct a mask per node which contains all
6267 * cpus of nodes that are that many hops away from us.
6268 */
6269 for (i = 0; i < level; i++) {
6270 sched_domains_numa_masks[i] =
6271 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6272 if (!sched_domains_numa_masks[i])
6273 return;
6274
6275 for (j = 0; j < nr_node_ids; j++) {
2ea45800 6276 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
cb83b629
PZ
6277 if (!mask)
6278 return;
6279
6280 sched_domains_numa_masks[i][j] = mask;
6281
6282 for (k = 0; k < nr_node_ids; k++) {
dd7d8634 6283 if (node_distance(j, k) > sched_domains_numa_distance[i])
cb83b629
PZ
6284 continue;
6285
6286 cpumask_or(mask, mask, cpumask_of_node(k));
6287 }
6288 }
6289 }
6290
6291 tl = kzalloc((ARRAY_SIZE(default_topology) + level) *
6292 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6293 if (!tl)
6294 return;
6295
6296 /*
6297 * Copy the default topology bits..
6298 */
6299 for (i = 0; default_topology[i].init; i++)
6300 tl[i] = default_topology[i];
6301
6302 /*
6303 * .. and append 'j' levels of NUMA goodness.
6304 */
6305 for (j = 0; j < level; i++, j++) {
6306 tl[i] = (struct sched_domain_topology_level){
6307 .init = sd_numa_init,
6308 .mask = sd_numa_mask,
6309 .flags = SDTL_OVERLAP,
6310 .numa_level = j,
6311 };
6312 }
6313
6314 sched_domain_topology = tl;
5f7865f3
TC
6315
6316 sched_domains_numa_levels = level;
cb83b629 6317}
301a5cba
TC
6318
6319static void sched_domains_numa_masks_set(int cpu)
6320{
6321 int i, j;
6322 int node = cpu_to_node(cpu);
6323
6324 for (i = 0; i < sched_domains_numa_levels; i++) {
6325 for (j = 0; j < nr_node_ids; j++) {
6326 if (node_distance(j, node) <= sched_domains_numa_distance[i])
6327 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6328 }
6329 }
6330}
6331
6332static void sched_domains_numa_masks_clear(int cpu)
6333{
6334 int i, j;
6335 for (i = 0; i < sched_domains_numa_levels; i++) {
6336 for (j = 0; j < nr_node_ids; j++)
6337 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6338 }
6339}
6340
6341/*
6342 * Update sched_domains_numa_masks[level][node] array when new cpus
6343 * are onlined.
6344 */
6345static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6346 unsigned long action,
6347 void *hcpu)
6348{
6349 int cpu = (long)hcpu;
6350
6351 switch (action & ~CPU_TASKS_FROZEN) {
6352 case CPU_ONLINE:
6353 sched_domains_numa_masks_set(cpu);
6354 break;
6355
6356 case CPU_DEAD:
6357 sched_domains_numa_masks_clear(cpu);
6358 break;
6359
6360 default:
6361 return NOTIFY_DONE;
6362 }
6363
6364 return NOTIFY_OK;
cb83b629
PZ
6365}
6366#else
6367static inline void sched_init_numa(void)
6368{
6369}
301a5cba
TC
6370
6371static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6372 unsigned long action,
6373 void *hcpu)
6374{
6375 return 0;
6376}
cb83b629
PZ
6377#endif /* CONFIG_NUMA */
6378
54ab4ff4
PZ
6379static int __sdt_alloc(const struct cpumask *cpu_map)
6380{
6381 struct sched_domain_topology_level *tl;
6382 int j;
6383
6384 for (tl = sched_domain_topology; tl->init; tl++) {
6385 struct sd_data *sdd = &tl->data;
6386
6387 sdd->sd = alloc_percpu(struct sched_domain *);
6388 if (!sdd->sd)
6389 return -ENOMEM;
6390
6391 sdd->sg = alloc_percpu(struct sched_group *);
6392 if (!sdd->sg)
6393 return -ENOMEM;
6394
9c3f75cb
PZ
6395 sdd->sgp = alloc_percpu(struct sched_group_power *);
6396 if (!sdd->sgp)
6397 return -ENOMEM;
6398
54ab4ff4
PZ
6399 for_each_cpu(j, cpu_map) {
6400 struct sched_domain *sd;
6401 struct sched_group *sg;
9c3f75cb 6402 struct sched_group_power *sgp;
54ab4ff4
PZ
6403
6404 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6405 GFP_KERNEL, cpu_to_node(j));
6406 if (!sd)
6407 return -ENOMEM;
6408
6409 *per_cpu_ptr(sdd->sd, j) = sd;
6410
6411 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6412 GFP_KERNEL, cpu_to_node(j));
6413 if (!sg)
6414 return -ENOMEM;
6415
30b4e9eb
IM
6416 sg->next = sg;
6417
54ab4ff4 6418 *per_cpu_ptr(sdd->sg, j) = sg;
9c3f75cb 6419
c1174876 6420 sgp = kzalloc_node(sizeof(struct sched_group_power) + cpumask_size(),
9c3f75cb
PZ
6421 GFP_KERNEL, cpu_to_node(j));
6422 if (!sgp)
6423 return -ENOMEM;
6424
6425 *per_cpu_ptr(sdd->sgp, j) = sgp;
54ab4ff4
PZ
6426 }
6427 }
6428
6429 return 0;
6430}
6431
6432static void __sdt_free(const struct cpumask *cpu_map)
6433{
6434 struct sched_domain_topology_level *tl;
6435 int j;
6436
6437 for (tl = sched_domain_topology; tl->init; tl++) {
6438 struct sd_data *sdd = &tl->data;
6439
6440 for_each_cpu(j, cpu_map) {
fb2cf2c6 6441 struct sched_domain *sd;
6442
6443 if (sdd->sd) {
6444 sd = *per_cpu_ptr(sdd->sd, j);
6445 if (sd && (sd->flags & SD_OVERLAP))
6446 free_sched_groups(sd->groups, 0);
6447 kfree(*per_cpu_ptr(sdd->sd, j));
6448 }
6449
6450 if (sdd->sg)
6451 kfree(*per_cpu_ptr(sdd->sg, j));
6452 if (sdd->sgp)
6453 kfree(*per_cpu_ptr(sdd->sgp, j));
54ab4ff4
PZ
6454 }
6455 free_percpu(sdd->sd);
fb2cf2c6 6456 sdd->sd = NULL;
54ab4ff4 6457 free_percpu(sdd->sg);
fb2cf2c6 6458 sdd->sg = NULL;
9c3f75cb 6459 free_percpu(sdd->sgp);
fb2cf2c6 6460 sdd->sgp = NULL;
54ab4ff4
PZ
6461 }
6462}
6463
2c402dc3
PZ
6464struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6465 struct s_data *d, const struct cpumask *cpu_map,
d069b916 6466 struct sched_domain_attr *attr, struct sched_domain *child,
2c402dc3
PZ
6467 int cpu)
6468{
54ab4ff4 6469 struct sched_domain *sd = tl->init(tl, cpu);
2c402dc3 6470 if (!sd)
d069b916 6471 return child;
2c402dc3 6472
2c402dc3 6473 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
60495e77
PZ
6474 if (child) {
6475 sd->level = child->level + 1;
6476 sched_domain_level_max = max(sched_domain_level_max, sd->level);
d069b916 6477 child->parent = sd;
60495e77 6478 }
d069b916 6479 sd->child = child;
a841f8ce 6480 set_domain_attribute(sd, attr);
2c402dc3
PZ
6481
6482 return sd;
6483}
6484
2109b99e
AH
6485/*
6486 * Build sched domains for a given set of cpus and attach the sched domains
6487 * to the individual cpus
6488 */
dce840a0
PZ
6489static int build_sched_domains(const struct cpumask *cpu_map,
6490 struct sched_domain_attr *attr)
2109b99e
AH
6491{
6492 enum s_alloc alloc_state = sa_none;
dce840a0 6493 struct sched_domain *sd;
2109b99e 6494 struct s_data d;
822ff793 6495 int i, ret = -ENOMEM;
9c1cfda2 6496
2109b99e
AH
6497 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
6498 if (alloc_state != sa_rootdomain)
6499 goto error;
9c1cfda2 6500
dce840a0 6501 /* Set up domains for cpus specified by the cpu_map. */
abcd083a 6502 for_each_cpu(i, cpu_map) {
eb7a74e6
PZ
6503 struct sched_domain_topology_level *tl;
6504
3bd65a80 6505 sd = NULL;
e3589f6c 6506 for (tl = sched_domain_topology; tl->init; tl++) {
2c402dc3 6507 sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i);
e3589f6c
PZ
6508 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
6509 sd->flags |= SD_OVERLAP;
d110235d
PZ
6510 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
6511 break;
e3589f6c 6512 }
d274cb30 6513
d069b916
PZ
6514 while (sd->child)
6515 sd = sd->child;
6516
21d42ccf 6517 *per_cpu_ptr(d.sd, i) = sd;
dce840a0
PZ
6518 }
6519
6520 /* Build the groups for the domains */
6521 for_each_cpu(i, cpu_map) {
6522 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6523 sd->span_weight = cpumask_weight(sched_domain_span(sd));
e3589f6c
PZ
6524 if (sd->flags & SD_OVERLAP) {
6525 if (build_overlap_sched_groups(sd, i))
6526 goto error;
6527 } else {
6528 if (build_sched_groups(sd, i))
6529 goto error;
6530 }
1cf51902 6531 }
a06dadbe 6532 }
9c1cfda2 6533
1da177e4 6534 /* Calculate CPU power for physical packages and nodes */
a9c9a9b6
PZ
6535 for (i = nr_cpumask_bits-1; i >= 0; i--) {
6536 if (!cpumask_test_cpu(i, cpu_map))
6537 continue;
9c1cfda2 6538
dce840a0
PZ
6539 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6540 claim_allocations(i, sd);
cd4ea6ae 6541 init_sched_groups_power(i, sd);
dce840a0 6542 }
f712c0c7 6543 }
9c1cfda2 6544
1da177e4 6545 /* Attach the domains */
dce840a0 6546 rcu_read_lock();
abcd083a 6547 for_each_cpu(i, cpu_map) {
21d42ccf 6548 sd = *per_cpu_ptr(d.sd, i);
49a02c51 6549 cpu_attach_domain(sd, d.rd, i);
1da177e4 6550 }
dce840a0 6551 rcu_read_unlock();
51888ca2 6552
822ff793 6553 ret = 0;
51888ca2 6554error:
2109b99e 6555 __free_domain_allocs(&d, alloc_state, cpu_map);
822ff793 6556 return ret;
1da177e4 6557}
029190c5 6558
acc3f5d7 6559static cpumask_var_t *doms_cur; /* current sched domains */
029190c5 6560static int ndoms_cur; /* number of sched domains in 'doms_cur' */
4285f594
IM
6561static struct sched_domain_attr *dattr_cur;
6562 /* attribues of custom domains in 'doms_cur' */
029190c5
PJ
6563
6564/*
6565 * Special case: If a kmalloc of a doms_cur partition (array of
4212823f
RR
6566 * cpumask) fails, then fallback to a single sched domain,
6567 * as determined by the single cpumask fallback_doms.
029190c5 6568 */
4212823f 6569static cpumask_var_t fallback_doms;
029190c5 6570
ee79d1bd
HC
6571/*
6572 * arch_update_cpu_topology lets virtualized architectures update the
6573 * cpu core maps. It is supposed to return 1 if the topology changed
6574 * or 0 if it stayed the same.
6575 */
6576int __attribute__((weak)) arch_update_cpu_topology(void)
22e52b07 6577{
ee79d1bd 6578 return 0;
22e52b07
HC
6579}
6580
acc3f5d7
RR
6581cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
6582{
6583 int i;
6584 cpumask_var_t *doms;
6585
6586 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
6587 if (!doms)
6588 return NULL;
6589 for (i = 0; i < ndoms; i++) {
6590 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
6591 free_sched_domains(doms, i);
6592 return NULL;
6593 }
6594 }
6595 return doms;
6596}
6597
6598void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
6599{
6600 unsigned int i;
6601 for (i = 0; i < ndoms; i++)
6602 free_cpumask_var(doms[i]);
6603 kfree(doms);
6604}
6605
1a20ff27 6606/*
41a2d6cf 6607 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
029190c5
PJ
6608 * For now this just excludes isolated cpus, but could be used to
6609 * exclude other special cases in the future.
1a20ff27 6610 */
c4a8849a 6611static int init_sched_domains(const struct cpumask *cpu_map)
1a20ff27 6612{
7378547f
MM
6613 int err;
6614
22e52b07 6615 arch_update_cpu_topology();
029190c5 6616 ndoms_cur = 1;
acc3f5d7 6617 doms_cur = alloc_sched_domains(ndoms_cur);
029190c5 6618 if (!doms_cur)
acc3f5d7
RR
6619 doms_cur = &fallback_doms;
6620 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
dce840a0 6621 err = build_sched_domains(doms_cur[0], NULL);
6382bc90 6622 register_sched_domain_sysctl();
7378547f
MM
6623
6624 return err;
1a20ff27
DG
6625}
6626
1a20ff27
DG
6627/*
6628 * Detach sched domains from a group of cpus specified in cpu_map
6629 * These cpus will now be attached to the NULL domain
6630 */
96f874e2 6631static void detach_destroy_domains(const struct cpumask *cpu_map)
1a20ff27
DG
6632{
6633 int i;
6634
dce840a0 6635 rcu_read_lock();
abcd083a 6636 for_each_cpu(i, cpu_map)
57d885fe 6637 cpu_attach_domain(NULL, &def_root_domain, i);
dce840a0 6638 rcu_read_unlock();
1a20ff27
DG
6639}
6640
1d3504fc
HS
6641/* handle null as "default" */
6642static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
6643 struct sched_domain_attr *new, int idx_new)
6644{
6645 struct sched_domain_attr tmp;
6646
6647 /* fast path */
6648 if (!new && !cur)
6649 return 1;
6650
6651 tmp = SD_ATTR_INIT;
6652 return !memcmp(cur ? (cur + idx_cur) : &tmp,
6653 new ? (new + idx_new) : &tmp,
6654 sizeof(struct sched_domain_attr));
6655}
6656
029190c5
PJ
6657/*
6658 * Partition sched domains as specified by the 'ndoms_new'
41a2d6cf 6659 * cpumasks in the array doms_new[] of cpumasks. This compares
029190c5
PJ
6660 * doms_new[] to the current sched domain partitioning, doms_cur[].
6661 * It destroys each deleted domain and builds each new domain.
6662 *
acc3f5d7 6663 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
41a2d6cf
IM
6664 * The masks don't intersect (don't overlap.) We should setup one
6665 * sched domain for each mask. CPUs not in any of the cpumasks will
6666 * not be load balanced. If the same cpumask appears both in the
029190c5
PJ
6667 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6668 * it as it is.
6669 *
acc3f5d7
RR
6670 * The passed in 'doms_new' should be allocated using
6671 * alloc_sched_domains. This routine takes ownership of it and will
6672 * free_sched_domains it when done with it. If the caller failed the
6673 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
6674 * and partition_sched_domains() will fallback to the single partition
6675 * 'fallback_doms', it also forces the domains to be rebuilt.
029190c5 6676 *
96f874e2 6677 * If doms_new == NULL it will be replaced with cpu_online_mask.
700018e0
LZ
6678 * ndoms_new == 0 is a special case for destroying existing domains,
6679 * and it will not create the default domain.
dfb512ec 6680 *
029190c5
PJ
6681 * Call with hotplug lock held
6682 */
acc3f5d7 6683void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
1d3504fc 6684 struct sched_domain_attr *dattr_new)
029190c5 6685{
dfb512ec 6686 int i, j, n;
d65bd5ec 6687 int new_topology;
029190c5 6688
712555ee 6689 mutex_lock(&sched_domains_mutex);
a1835615 6690
7378547f
MM
6691 /* always unregister in case we don't destroy any domains */
6692 unregister_sched_domain_sysctl();
6693
d65bd5ec
HC
6694 /* Let architecture update cpu core mappings. */
6695 new_topology = arch_update_cpu_topology();
6696
dfb512ec 6697 n = doms_new ? ndoms_new : 0;
029190c5
PJ
6698
6699 /* Destroy deleted domains */
6700 for (i = 0; i < ndoms_cur; i++) {
d65bd5ec 6701 for (j = 0; j < n && !new_topology; j++) {
acc3f5d7 6702 if (cpumask_equal(doms_cur[i], doms_new[j])
1d3504fc 6703 && dattrs_equal(dattr_cur, i, dattr_new, j))
029190c5
PJ
6704 goto match1;
6705 }
6706 /* no match - a current sched domain not in new doms_new[] */
acc3f5d7 6707 detach_destroy_domains(doms_cur[i]);
029190c5
PJ
6708match1:
6709 ;
6710 }
6711
e761b772
MK
6712 if (doms_new == NULL) {
6713 ndoms_cur = 0;
acc3f5d7 6714 doms_new = &fallback_doms;
6ad4c188 6715 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
faa2f98f 6716 WARN_ON_ONCE(dattr_new);
e761b772
MK
6717 }
6718
029190c5
PJ
6719 /* Build new domains */
6720 for (i = 0; i < ndoms_new; i++) {
d65bd5ec 6721 for (j = 0; j < ndoms_cur && !new_topology; j++) {
acc3f5d7 6722 if (cpumask_equal(doms_new[i], doms_cur[j])
1d3504fc 6723 && dattrs_equal(dattr_new, i, dattr_cur, j))
029190c5
PJ
6724 goto match2;
6725 }
6726 /* no match - add a new doms_new */
dce840a0 6727 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
029190c5
PJ
6728match2:
6729 ;
6730 }
6731
6732 /* Remember the new sched domains */
acc3f5d7
RR
6733 if (doms_cur != &fallback_doms)
6734 free_sched_domains(doms_cur, ndoms_cur);
1d3504fc 6735 kfree(dattr_cur); /* kfree(NULL) is safe */
029190c5 6736 doms_cur = doms_new;
1d3504fc 6737 dattr_cur = dattr_new;
029190c5 6738 ndoms_cur = ndoms_new;
7378547f
MM
6739
6740 register_sched_domain_sysctl();
a1835615 6741
712555ee 6742 mutex_unlock(&sched_domains_mutex);
029190c5
PJ
6743}
6744
d35be8ba
SB
6745static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
6746
1da177e4 6747/*
3a101d05
TH
6748 * Update cpusets according to cpu_active mask. If cpusets are
6749 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
6750 * around partition_sched_domains().
d35be8ba
SB
6751 *
6752 * If we come here as part of a suspend/resume, don't touch cpusets because we
6753 * want to restore it back to its original state upon resume anyway.
1da177e4 6754 */
0b2e918a
TH
6755static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
6756 void *hcpu)
e761b772 6757{
d35be8ba
SB
6758 switch (action) {
6759 case CPU_ONLINE_FROZEN:
6760 case CPU_DOWN_FAILED_FROZEN:
6761
6762 /*
6763 * num_cpus_frozen tracks how many CPUs are involved in suspend
6764 * resume sequence. As long as this is not the last online
6765 * operation in the resume sequence, just build a single sched
6766 * domain, ignoring cpusets.
6767 */
6768 num_cpus_frozen--;
6769 if (likely(num_cpus_frozen)) {
6770 partition_sched_domains(1, NULL, NULL);
6771 break;
6772 }
6773
6774 /*
6775 * This is the last CPU online operation. So fall through and
6776 * restore the original sched domains by considering the
6777 * cpuset configurations.
6778 */
6779
e761b772 6780 case CPU_ONLINE:
6ad4c188 6781 case CPU_DOWN_FAILED:
7ddf96b0 6782 cpuset_update_active_cpus(true);
d35be8ba 6783 break;
3a101d05
TH
6784 default:
6785 return NOTIFY_DONE;
6786 }
d35be8ba 6787 return NOTIFY_OK;
3a101d05 6788}
e761b772 6789
0b2e918a
TH
6790static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
6791 void *hcpu)
3a101d05 6792{
d35be8ba 6793 switch (action) {
3a101d05 6794 case CPU_DOWN_PREPARE:
7ddf96b0 6795 cpuset_update_active_cpus(false);
d35be8ba
SB
6796 break;
6797 case CPU_DOWN_PREPARE_FROZEN:
6798 num_cpus_frozen++;
6799 partition_sched_domains(1, NULL, NULL);
6800 break;
e761b772
MK
6801 default:
6802 return NOTIFY_DONE;
6803 }
d35be8ba 6804 return NOTIFY_OK;
e761b772 6805}
e761b772 6806
1da177e4
LT
6807void __init sched_init_smp(void)
6808{
dcc30a35
RR
6809 cpumask_var_t non_isolated_cpus;
6810
6811 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
cb5fd13f 6812 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
5c1e1767 6813
cb83b629
PZ
6814 sched_init_numa();
6815
95402b38 6816 get_online_cpus();
712555ee 6817 mutex_lock(&sched_domains_mutex);
c4a8849a 6818 init_sched_domains(cpu_active_mask);
dcc30a35
RR
6819 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
6820 if (cpumask_empty(non_isolated_cpus))
6821 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
712555ee 6822 mutex_unlock(&sched_domains_mutex);
95402b38 6823 put_online_cpus();
e761b772 6824
301a5cba 6825 hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
3a101d05
TH
6826 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
6827 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
e761b772
MK
6828
6829 /* RT runtime code needs to handle some hotplug events */
6830 hotcpu_notifier(update_runtime, 0);
6831
b328ca18 6832 init_hrtick();
5c1e1767
NP
6833
6834 /* Move init over to a non-isolated CPU */
dcc30a35 6835 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
5c1e1767 6836 BUG();
19978ca6 6837 sched_init_granularity();
dcc30a35 6838 free_cpumask_var(non_isolated_cpus);
4212823f 6839
0e3900e6 6840 init_sched_rt_class();
1da177e4
LT
6841}
6842#else
6843void __init sched_init_smp(void)
6844{
19978ca6 6845 sched_init_granularity();
1da177e4
LT
6846}
6847#endif /* CONFIG_SMP */
6848
cd1bb94b
AB
6849const_debug unsigned int sysctl_timer_migration = 1;
6850
1da177e4
LT
6851int in_sched_functions(unsigned long addr)
6852{
1da177e4
LT
6853 return in_lock_functions(addr) ||
6854 (addr >= (unsigned long)__sched_text_start
6855 && addr < (unsigned long)__sched_text_end);
6856}
6857
029632fb 6858#ifdef CONFIG_CGROUP_SCHED
27b4b931
LZ
6859/*
6860 * Default task group.
6861 * Every task in system belongs to this group at bootup.
6862 */
029632fb 6863struct task_group root_task_group;
35cf4e50 6864LIST_HEAD(task_groups);
052f1dc7 6865#endif
6f505b16 6866
e6252c3e 6867DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
6f505b16 6868
1da177e4
LT
6869void __init sched_init(void)
6870{
dd41f596 6871 int i, j;
434d53b0
MT
6872 unsigned long alloc_size = 0, ptr;
6873
6874#ifdef CONFIG_FAIR_GROUP_SCHED
6875 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
6876#endif
6877#ifdef CONFIG_RT_GROUP_SCHED
6878 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
eff766a6 6879#endif
df7c8e84 6880#ifdef CONFIG_CPUMASK_OFFSTACK
8c083f08 6881 alloc_size += num_possible_cpus() * cpumask_size();
434d53b0 6882#endif
434d53b0 6883 if (alloc_size) {
36b7b6d4 6884 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
434d53b0
MT
6885
6886#ifdef CONFIG_FAIR_GROUP_SCHED
07e06b01 6887 root_task_group.se = (struct sched_entity **)ptr;
434d53b0
MT
6888 ptr += nr_cpu_ids * sizeof(void **);
6889
07e06b01 6890 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
434d53b0 6891 ptr += nr_cpu_ids * sizeof(void **);
eff766a6 6892
6d6bc0ad 6893#endif /* CONFIG_FAIR_GROUP_SCHED */
434d53b0 6894#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 6895 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
434d53b0
MT
6896 ptr += nr_cpu_ids * sizeof(void **);
6897
07e06b01 6898 root_task_group.rt_rq = (struct rt_rq **)ptr;
eff766a6
PZ
6899 ptr += nr_cpu_ids * sizeof(void **);
6900
6d6bc0ad 6901#endif /* CONFIG_RT_GROUP_SCHED */
df7c8e84
RR
6902#ifdef CONFIG_CPUMASK_OFFSTACK
6903 for_each_possible_cpu(i) {
e6252c3e 6904 per_cpu(load_balance_mask, i) = (void *)ptr;
df7c8e84
RR
6905 ptr += cpumask_size();
6906 }
6907#endif /* CONFIG_CPUMASK_OFFSTACK */
434d53b0 6908 }
dd41f596 6909
57d885fe
GH
6910#ifdef CONFIG_SMP
6911 init_defrootdomain();
6912#endif
6913
d0b27fa7
PZ
6914 init_rt_bandwidth(&def_rt_bandwidth,
6915 global_rt_period(), global_rt_runtime());
6916
6917#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 6918 init_rt_bandwidth(&root_task_group.rt_bandwidth,
d0b27fa7 6919 global_rt_period(), global_rt_runtime());
6d6bc0ad 6920#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 6921
7c941438 6922#ifdef CONFIG_CGROUP_SCHED
07e06b01
YZ
6923 list_add(&root_task_group.list, &task_groups);
6924 INIT_LIST_HEAD(&root_task_group.children);
f4d6f6c2 6925 INIT_LIST_HEAD(&root_task_group.siblings);
5091faa4 6926 autogroup_init(&init_task);
54c707e9 6927
7c941438 6928#endif /* CONFIG_CGROUP_SCHED */
6f505b16 6929
0a945022 6930 for_each_possible_cpu(i) {
70b97a7f 6931 struct rq *rq;
1da177e4
LT
6932
6933 rq = cpu_rq(i);
05fa785c 6934 raw_spin_lock_init(&rq->lock);
7897986b 6935 rq->nr_running = 0;
dce48a84
TG
6936 rq->calc_load_active = 0;
6937 rq->calc_load_update = jiffies + LOAD_FREQ;
acb5a9ba 6938 init_cfs_rq(&rq->cfs);
6f505b16 6939 init_rt_rq(&rq->rt, rq);
dd41f596 6940#ifdef CONFIG_FAIR_GROUP_SCHED
029632fb 6941 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6f505b16 6942 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
354d60c2 6943 /*
07e06b01 6944 * How much cpu bandwidth does root_task_group get?
354d60c2
DG
6945 *
6946 * In case of task-groups formed thr' the cgroup filesystem, it
6947 * gets 100% of the cpu resources in the system. This overall
6948 * system cpu resource is divided among the tasks of
07e06b01 6949 * root_task_group and its child task-groups in a fair manner,
354d60c2
DG
6950 * based on each entity's (task or task-group's) weight
6951 * (se->load.weight).
6952 *
07e06b01 6953 * In other words, if root_task_group has 10 tasks of weight
354d60c2
DG
6954 * 1024) and two child groups A0 and A1 (of weight 1024 each),
6955 * then A0's share of the cpu resource is:
6956 *
0d905bca 6957 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
354d60c2 6958 *
07e06b01
YZ
6959 * We achieve this by letting root_task_group's tasks sit
6960 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
354d60c2 6961 */
ab84d31e 6962 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
07e06b01 6963 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
354d60c2
DG
6964#endif /* CONFIG_FAIR_GROUP_SCHED */
6965
6966 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
052f1dc7 6967#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 6968 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
07e06b01 6969 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
dd41f596 6970#endif
1da177e4 6971
dd41f596
IM
6972 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6973 rq->cpu_load[j] = 0;
fdf3e95d
VP
6974
6975 rq->last_load_update_tick = jiffies;
6976
1da177e4 6977#ifdef CONFIG_SMP
41c7ce9a 6978 rq->sd = NULL;
57d885fe 6979 rq->rd = NULL;
1399fa78 6980 rq->cpu_power = SCHED_POWER_SCALE;
3f029d3c 6981 rq->post_schedule = 0;
1da177e4 6982 rq->active_balance = 0;
dd41f596 6983 rq->next_balance = jiffies;
1da177e4 6984 rq->push_cpu = 0;
0a2966b4 6985 rq->cpu = i;
1f11eb6a 6986 rq->online = 0;
eae0c9df
MG
6987 rq->idle_stamp = 0;
6988 rq->avg_idle = 2*sysctl_sched_migration_cost;
367456c7
PZ
6989
6990 INIT_LIST_HEAD(&rq->cfs_tasks);
6991
dc938520 6992 rq_attach_root(rq, &def_root_domain);
3451d024 6993#ifdef CONFIG_NO_HZ_COMMON
1c792db7 6994 rq->nohz_flags = 0;
83cd4fe2 6995#endif
1da177e4 6996#endif
8f4d37ec 6997 init_rq_hrtick(rq);
1da177e4 6998 atomic_set(&rq->nr_iowait, 0);
1da177e4
LT
6999 }
7000
2dd73a4f 7001 set_load_weight(&init_task);
b50f60ce 7002
e107be36
AK
7003#ifdef CONFIG_PREEMPT_NOTIFIERS
7004 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7005#endif
7006
b50f60ce 7007#ifdef CONFIG_RT_MUTEXES
732375c6 7008 plist_head_init(&init_task.pi_waiters);
b50f60ce
HC
7009#endif
7010
1da177e4
LT
7011 /*
7012 * The boot idle thread does lazy MMU switching as well:
7013 */
7014 atomic_inc(&init_mm.mm_count);
7015 enter_lazy_tlb(&init_mm, current);
7016
7017 /*
7018 * Make us the idle thread. Technically, schedule() should not be
7019 * called from this thread, however somewhere below it might be,
7020 * but because we are the idle thread, we just pick up running again
7021 * when this runqueue becomes "idle".
7022 */
7023 init_idle(current, smp_processor_id());
dce48a84
TG
7024
7025 calc_load_update = jiffies + LOAD_FREQ;
7026
dd41f596
IM
7027 /*
7028 * During early bootup we pretend to be a normal task:
7029 */
7030 current->sched_class = &fair_sched_class;
6892b75e 7031
bf4d83f6 7032#ifdef CONFIG_SMP
4cb98839 7033 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
bdddd296
RR
7034 /* May be allocated at isolcpus cmdline parse time */
7035 if (cpu_isolated_map == NULL)
7036 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
29d5e047 7037 idle_thread_set_boot_cpu();
029632fb
PZ
7038#endif
7039 init_sched_fair_class();
6a7b3dc3 7040
6892b75e 7041 scheduler_running = 1;
1da177e4
LT
7042}
7043
d902db1e 7044#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
e4aafea2
FW
7045static inline int preempt_count_equals(int preempt_offset)
7046{
234da7bc 7047 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
e4aafea2 7048
4ba8216c 7049 return (nested == preempt_offset);
e4aafea2
FW
7050}
7051
d894837f 7052void __might_sleep(const char *file, int line, int preempt_offset)
1da177e4 7053{
1da177e4
LT
7054 static unsigned long prev_jiffy; /* ratelimiting */
7055
b3fbab05 7056 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
e4aafea2
FW
7057 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
7058 system_state != SYSTEM_RUNNING || oops_in_progress)
aef745fc
IM
7059 return;
7060 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7061 return;
7062 prev_jiffy = jiffies;
7063
3df0fc5b
PZ
7064 printk(KERN_ERR
7065 "BUG: sleeping function called from invalid context at %s:%d\n",
7066 file, line);
7067 printk(KERN_ERR
7068 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7069 in_atomic(), irqs_disabled(),
7070 current->pid, current->comm);
aef745fc
IM
7071
7072 debug_show_held_locks(current);
7073 if (irqs_disabled())
7074 print_irqtrace_events(current);
7075 dump_stack();
1da177e4
LT
7076}
7077EXPORT_SYMBOL(__might_sleep);
7078#endif
7079
7080#ifdef CONFIG_MAGIC_SYSRQ
3a5e4dc1
AK
7081static void normalize_task(struct rq *rq, struct task_struct *p)
7082{
da7a735e
PZ
7083 const struct sched_class *prev_class = p->sched_class;
7084 int old_prio = p->prio;
3a5e4dc1 7085 int on_rq;
3e51f33f 7086
fd2f4419 7087 on_rq = p->on_rq;
3a5e4dc1 7088 if (on_rq)
4ca9b72b 7089 dequeue_task(rq, p, 0);
3a5e4dc1
AK
7090 __setscheduler(rq, p, SCHED_NORMAL, 0);
7091 if (on_rq) {
4ca9b72b 7092 enqueue_task(rq, p, 0);
3a5e4dc1
AK
7093 resched_task(rq->curr);
7094 }
da7a735e
PZ
7095
7096 check_class_changed(rq, p, prev_class, old_prio);
3a5e4dc1
AK
7097}
7098
1da177e4
LT
7099void normalize_rt_tasks(void)
7100{
a0f98a1c 7101 struct task_struct *g, *p;
1da177e4 7102 unsigned long flags;
70b97a7f 7103 struct rq *rq;
1da177e4 7104
4cf5d77a 7105 read_lock_irqsave(&tasklist_lock, flags);
a0f98a1c 7106 do_each_thread(g, p) {
178be793
IM
7107 /*
7108 * Only normalize user tasks:
7109 */
7110 if (!p->mm)
7111 continue;
7112
6cfb0d5d 7113 p->se.exec_start = 0;
6cfb0d5d 7114#ifdef CONFIG_SCHEDSTATS
41acab88
LDM
7115 p->se.statistics.wait_start = 0;
7116 p->se.statistics.sleep_start = 0;
7117 p->se.statistics.block_start = 0;
6cfb0d5d 7118#endif
dd41f596
IM
7119
7120 if (!rt_task(p)) {
7121 /*
7122 * Renice negative nice level userspace
7123 * tasks back to 0:
7124 */
7125 if (TASK_NICE(p) < 0 && p->mm)
7126 set_user_nice(p, 0);
1da177e4 7127 continue;
dd41f596 7128 }
1da177e4 7129
1d615482 7130 raw_spin_lock(&p->pi_lock);
b29739f9 7131 rq = __task_rq_lock(p);
1da177e4 7132
178be793 7133 normalize_task(rq, p);
3a5e4dc1 7134
b29739f9 7135 __task_rq_unlock(rq);
1d615482 7136 raw_spin_unlock(&p->pi_lock);
a0f98a1c
IM
7137 } while_each_thread(g, p);
7138
4cf5d77a 7139 read_unlock_irqrestore(&tasklist_lock, flags);
1da177e4
LT
7140}
7141
7142#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a 7143
67fc4e0c 7144#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
1df5c10a 7145/*
67fc4e0c 7146 * These functions are only useful for the IA64 MCA handling, or kdb.
1df5c10a
LT
7147 *
7148 * They can only be called when the whole system has been
7149 * stopped - every CPU needs to be quiescent, and no scheduling
7150 * activity can take place. Using them for anything else would
7151 * be a serious bug, and as a result, they aren't even visible
7152 * under any other configuration.
7153 */
7154
7155/**
7156 * curr_task - return the current task for a given cpu.
7157 * @cpu: the processor in question.
7158 *
7159 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7160 */
36c8b586 7161struct task_struct *curr_task(int cpu)
1df5c10a
LT
7162{
7163 return cpu_curr(cpu);
7164}
7165
67fc4e0c
JW
7166#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7167
7168#ifdef CONFIG_IA64
1df5c10a
LT
7169/**
7170 * set_curr_task - set the current task for a given cpu.
7171 * @cpu: the processor in question.
7172 * @p: the task pointer to set.
7173 *
7174 * Description: This function must only be used when non-maskable interrupts
41a2d6cf
IM
7175 * are serviced on a separate stack. It allows the architecture to switch the
7176 * notion of the current task on a cpu in a non-blocking manner. This function
1df5c10a
LT
7177 * must be called with all CPU's synchronized, and interrupts disabled, the
7178 * and caller must save the original value of the current task (see
7179 * curr_task() above) and restore that value before reenabling interrupts and
7180 * re-starting the system.
7181 *
7182 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7183 */
36c8b586 7184void set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
7185{
7186 cpu_curr(cpu) = p;
7187}
7188
7189#endif
29f59db3 7190
7c941438 7191#ifdef CONFIG_CGROUP_SCHED
029632fb
PZ
7192/* task_group_lock serializes the addition/removal of task groups */
7193static DEFINE_SPINLOCK(task_group_lock);
7194
bccbe08a
PZ
7195static void free_sched_group(struct task_group *tg)
7196{
7197 free_fair_sched_group(tg);
7198 free_rt_sched_group(tg);
e9aa1dd1 7199 autogroup_free(tg);
bccbe08a
PZ
7200 kfree(tg);
7201}
7202
7203/* allocate runqueue etc for a new task group */
ec7dc8ac 7204struct task_group *sched_create_group(struct task_group *parent)
bccbe08a
PZ
7205{
7206 struct task_group *tg;
bccbe08a
PZ
7207
7208 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7209 if (!tg)
7210 return ERR_PTR(-ENOMEM);
7211
ec7dc8ac 7212 if (!alloc_fair_sched_group(tg, parent))
bccbe08a
PZ
7213 goto err;
7214
ec7dc8ac 7215 if (!alloc_rt_sched_group(tg, parent))
bccbe08a
PZ
7216 goto err;
7217
ace783b9
LZ
7218 return tg;
7219
7220err:
7221 free_sched_group(tg);
7222 return ERR_PTR(-ENOMEM);
7223}
7224
7225void sched_online_group(struct task_group *tg, struct task_group *parent)
7226{
7227 unsigned long flags;
7228
8ed36996 7229 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 7230 list_add_rcu(&tg->list, &task_groups);
f473aa5e
PZ
7231
7232 WARN_ON(!parent); /* root should already exist */
7233
7234 tg->parent = parent;
f473aa5e 7235 INIT_LIST_HEAD(&tg->children);
09f2724a 7236 list_add_rcu(&tg->siblings, &parent->children);
8ed36996 7237 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
7238}
7239
9b5b7751 7240/* rcu callback to free various structures associated with a task group */
6f505b16 7241static void free_sched_group_rcu(struct rcu_head *rhp)
29f59db3 7242{
29f59db3 7243 /* now it should be safe to free those cfs_rqs */
6f505b16 7244 free_sched_group(container_of(rhp, struct task_group, rcu));
29f59db3
SV
7245}
7246
9b5b7751 7247/* Destroy runqueue etc associated with a task group */
4cf86d77 7248void sched_destroy_group(struct task_group *tg)
ace783b9
LZ
7249{
7250 /* wait for possible concurrent references to cfs_rqs complete */
7251 call_rcu(&tg->rcu, free_sched_group_rcu);
7252}
7253
7254void sched_offline_group(struct task_group *tg)
29f59db3 7255{
8ed36996 7256 unsigned long flags;
9b5b7751 7257 int i;
29f59db3 7258
3d4b47b4
PZ
7259 /* end participation in shares distribution */
7260 for_each_possible_cpu(i)
bccbe08a 7261 unregister_fair_sched_group(tg, i);
3d4b47b4
PZ
7262
7263 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 7264 list_del_rcu(&tg->list);
f473aa5e 7265 list_del_rcu(&tg->siblings);
8ed36996 7266 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
7267}
7268
9b5b7751 7269/* change task's runqueue when it moves between groups.
3a252015
IM
7270 * The caller of this function should have put the task in its new group
7271 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7272 * reflect its new group.
9b5b7751
SV
7273 */
7274void sched_move_task(struct task_struct *tsk)
29f59db3 7275{
8323f26c 7276 struct task_group *tg;
29f59db3
SV
7277 int on_rq, running;
7278 unsigned long flags;
7279 struct rq *rq;
7280
7281 rq = task_rq_lock(tsk, &flags);
7282
051a1d1a 7283 running = task_current(rq, tsk);
fd2f4419 7284 on_rq = tsk->on_rq;
29f59db3 7285
0e1f3483 7286 if (on_rq)
29f59db3 7287 dequeue_task(rq, tsk, 0);
0e1f3483
HS
7288 if (unlikely(running))
7289 tsk->sched_class->put_prev_task(rq, tsk);
29f59db3 7290
8323f26c
PZ
7291 tg = container_of(task_subsys_state_check(tsk, cpu_cgroup_subsys_id,
7292 lockdep_is_held(&tsk->sighand->siglock)),
7293 struct task_group, css);
7294 tg = autogroup_task_group(tsk, tg);
7295 tsk->sched_task_group = tg;
7296
810b3817 7297#ifdef CONFIG_FAIR_GROUP_SCHED
b2b5ce02
PZ
7298 if (tsk->sched_class->task_move_group)
7299 tsk->sched_class->task_move_group(tsk, on_rq);
7300 else
810b3817 7301#endif
b2b5ce02 7302 set_task_rq(tsk, task_cpu(tsk));
810b3817 7303
0e1f3483
HS
7304 if (unlikely(running))
7305 tsk->sched_class->set_curr_task(rq);
7306 if (on_rq)
371fd7e7 7307 enqueue_task(rq, tsk, 0);
29f59db3 7308
0122ec5b 7309 task_rq_unlock(rq, tsk, &flags);
29f59db3 7310}
7c941438 7311#endif /* CONFIG_CGROUP_SCHED */
29f59db3 7312
a790de99 7313#if defined(CONFIG_RT_GROUP_SCHED) || defined(CONFIG_CFS_BANDWIDTH)
9f0c1e56
PZ
7314static unsigned long to_ratio(u64 period, u64 runtime)
7315{
7316 if (runtime == RUNTIME_INF)
9a7e0b18 7317 return 1ULL << 20;
9f0c1e56 7318
9a7e0b18 7319 return div64_u64(runtime << 20, period);
9f0c1e56 7320}
a790de99
PT
7321#endif
7322
7323#ifdef CONFIG_RT_GROUP_SCHED
7324/*
7325 * Ensure that the real time constraints are schedulable.
7326 */
7327static DEFINE_MUTEX(rt_constraints_mutex);
9f0c1e56 7328
9a7e0b18
PZ
7329/* Must be called with tasklist_lock held */
7330static inline int tg_has_rt_tasks(struct task_group *tg)
b40b2e8e 7331{
9a7e0b18 7332 struct task_struct *g, *p;
b40b2e8e 7333
9a7e0b18 7334 do_each_thread(g, p) {
029632fb 7335 if (rt_task(p) && task_rq(p)->rt.tg == tg)
9a7e0b18
PZ
7336 return 1;
7337 } while_each_thread(g, p);
b40b2e8e 7338
9a7e0b18
PZ
7339 return 0;
7340}
b40b2e8e 7341
9a7e0b18
PZ
7342struct rt_schedulable_data {
7343 struct task_group *tg;
7344 u64 rt_period;
7345 u64 rt_runtime;
7346};
b40b2e8e 7347
a790de99 7348static int tg_rt_schedulable(struct task_group *tg, void *data)
9a7e0b18
PZ
7349{
7350 struct rt_schedulable_data *d = data;
7351 struct task_group *child;
7352 unsigned long total, sum = 0;
7353 u64 period, runtime;
b40b2e8e 7354
9a7e0b18
PZ
7355 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7356 runtime = tg->rt_bandwidth.rt_runtime;
b40b2e8e 7357
9a7e0b18
PZ
7358 if (tg == d->tg) {
7359 period = d->rt_period;
7360 runtime = d->rt_runtime;
b40b2e8e 7361 }
b40b2e8e 7362
4653f803
PZ
7363 /*
7364 * Cannot have more runtime than the period.
7365 */
7366 if (runtime > period && runtime != RUNTIME_INF)
7367 return -EINVAL;
6f505b16 7368
4653f803
PZ
7369 /*
7370 * Ensure we don't starve existing RT tasks.
7371 */
9a7e0b18
PZ
7372 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7373 return -EBUSY;
6f505b16 7374
9a7e0b18 7375 total = to_ratio(period, runtime);
6f505b16 7376
4653f803
PZ
7377 /*
7378 * Nobody can have more than the global setting allows.
7379 */
7380 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7381 return -EINVAL;
6f505b16 7382
4653f803
PZ
7383 /*
7384 * The sum of our children's runtime should not exceed our own.
7385 */
9a7e0b18
PZ
7386 list_for_each_entry_rcu(child, &tg->children, siblings) {
7387 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7388 runtime = child->rt_bandwidth.rt_runtime;
6f505b16 7389
9a7e0b18
PZ
7390 if (child == d->tg) {
7391 period = d->rt_period;
7392 runtime = d->rt_runtime;
7393 }
6f505b16 7394
9a7e0b18 7395 sum += to_ratio(period, runtime);
9f0c1e56 7396 }
6f505b16 7397
9a7e0b18
PZ
7398 if (sum > total)
7399 return -EINVAL;
7400
7401 return 0;
6f505b16
PZ
7402}
7403
9a7e0b18 7404static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
521f1a24 7405{
8277434e
PT
7406 int ret;
7407
9a7e0b18
PZ
7408 struct rt_schedulable_data data = {
7409 .tg = tg,
7410 .rt_period = period,
7411 .rt_runtime = runtime,
7412 };
7413
8277434e
PT
7414 rcu_read_lock();
7415 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
7416 rcu_read_unlock();
7417
7418 return ret;
521f1a24
DG
7419}
7420
ab84d31e 7421static int tg_set_rt_bandwidth(struct task_group *tg,
d0b27fa7 7422 u64 rt_period, u64 rt_runtime)
6f505b16 7423{
ac086bc2 7424 int i, err = 0;
9f0c1e56 7425
9f0c1e56 7426 mutex_lock(&rt_constraints_mutex);
521f1a24 7427 read_lock(&tasklist_lock);
9a7e0b18
PZ
7428 err = __rt_schedulable(tg, rt_period, rt_runtime);
7429 if (err)
9f0c1e56 7430 goto unlock;
ac086bc2 7431
0986b11b 7432 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
d0b27fa7
PZ
7433 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7434 tg->rt_bandwidth.rt_runtime = rt_runtime;
ac086bc2
PZ
7435
7436 for_each_possible_cpu(i) {
7437 struct rt_rq *rt_rq = tg->rt_rq[i];
7438
0986b11b 7439 raw_spin_lock(&rt_rq->rt_runtime_lock);
ac086bc2 7440 rt_rq->rt_runtime = rt_runtime;
0986b11b 7441 raw_spin_unlock(&rt_rq->rt_runtime_lock);
ac086bc2 7442 }
0986b11b 7443 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
49246274 7444unlock:
521f1a24 7445 read_unlock(&tasklist_lock);
9f0c1e56
PZ
7446 mutex_unlock(&rt_constraints_mutex);
7447
7448 return err;
6f505b16
PZ
7449}
7450
25cc7da7 7451static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
d0b27fa7
PZ
7452{
7453 u64 rt_runtime, rt_period;
7454
7455 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7456 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7457 if (rt_runtime_us < 0)
7458 rt_runtime = RUNTIME_INF;
7459
ab84d31e 7460 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
d0b27fa7
PZ
7461}
7462
25cc7da7 7463static long sched_group_rt_runtime(struct task_group *tg)
9f0c1e56
PZ
7464{
7465 u64 rt_runtime_us;
7466
d0b27fa7 7467 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
9f0c1e56
PZ
7468 return -1;
7469
d0b27fa7 7470 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
9f0c1e56
PZ
7471 do_div(rt_runtime_us, NSEC_PER_USEC);
7472 return rt_runtime_us;
7473}
d0b27fa7 7474
25cc7da7 7475static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
d0b27fa7
PZ
7476{
7477 u64 rt_runtime, rt_period;
7478
7479 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
7480 rt_runtime = tg->rt_bandwidth.rt_runtime;
7481
619b0488
R
7482 if (rt_period == 0)
7483 return -EINVAL;
7484
ab84d31e 7485 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
d0b27fa7
PZ
7486}
7487
25cc7da7 7488static long sched_group_rt_period(struct task_group *tg)
d0b27fa7
PZ
7489{
7490 u64 rt_period_us;
7491
7492 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
7493 do_div(rt_period_us, NSEC_PER_USEC);
7494 return rt_period_us;
7495}
7496
7497static int sched_rt_global_constraints(void)
7498{
4653f803 7499 u64 runtime, period;
d0b27fa7
PZ
7500 int ret = 0;
7501
ec5d4989
HS
7502 if (sysctl_sched_rt_period <= 0)
7503 return -EINVAL;
7504
4653f803
PZ
7505 runtime = global_rt_runtime();
7506 period = global_rt_period();
7507
7508 /*
7509 * Sanity check on the sysctl variables.
7510 */
7511 if (runtime > period && runtime != RUNTIME_INF)
7512 return -EINVAL;
10b612f4 7513
d0b27fa7 7514 mutex_lock(&rt_constraints_mutex);
9a7e0b18 7515 read_lock(&tasklist_lock);
4653f803 7516 ret = __rt_schedulable(NULL, 0, 0);
9a7e0b18 7517 read_unlock(&tasklist_lock);
d0b27fa7
PZ
7518 mutex_unlock(&rt_constraints_mutex);
7519
7520 return ret;
7521}
54e99124 7522
25cc7da7 7523static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
54e99124
DG
7524{
7525 /* Don't accept realtime tasks when there is no way for them to run */
7526 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
7527 return 0;
7528
7529 return 1;
7530}
7531
6d6bc0ad 7532#else /* !CONFIG_RT_GROUP_SCHED */
d0b27fa7
PZ
7533static int sched_rt_global_constraints(void)
7534{
ac086bc2
PZ
7535 unsigned long flags;
7536 int i;
7537
ec5d4989
HS
7538 if (sysctl_sched_rt_period <= 0)
7539 return -EINVAL;
7540
60aa605d
PZ
7541 /*
7542 * There's always some RT tasks in the root group
7543 * -- migration, kstopmachine etc..
7544 */
7545 if (sysctl_sched_rt_runtime == 0)
7546 return -EBUSY;
7547
0986b11b 7548 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
ac086bc2
PZ
7549 for_each_possible_cpu(i) {
7550 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
7551
0986b11b 7552 raw_spin_lock(&rt_rq->rt_runtime_lock);
ac086bc2 7553 rt_rq->rt_runtime = global_rt_runtime();
0986b11b 7554 raw_spin_unlock(&rt_rq->rt_runtime_lock);
ac086bc2 7555 }
0986b11b 7556 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
ac086bc2 7557
d0b27fa7
PZ
7558 return 0;
7559}
6d6bc0ad 7560#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 7561
ce0dbbbb
CW
7562int sched_rr_handler(struct ctl_table *table, int write,
7563 void __user *buffer, size_t *lenp,
7564 loff_t *ppos)
7565{
7566 int ret;
7567 static DEFINE_MUTEX(mutex);
7568
7569 mutex_lock(&mutex);
7570 ret = proc_dointvec(table, write, buffer, lenp, ppos);
7571 /* make sure that internally we keep jiffies */
7572 /* also, writing zero resets timeslice to default */
7573 if (!ret && write) {
7574 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
7575 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
7576 }
7577 mutex_unlock(&mutex);
7578 return ret;
7579}
7580
d0b27fa7 7581int sched_rt_handler(struct ctl_table *table, int write,
8d65af78 7582 void __user *buffer, size_t *lenp,
d0b27fa7
PZ
7583 loff_t *ppos)
7584{
7585 int ret;
7586 int old_period, old_runtime;
7587 static DEFINE_MUTEX(mutex);
7588
7589 mutex_lock(&mutex);
7590 old_period = sysctl_sched_rt_period;
7591 old_runtime = sysctl_sched_rt_runtime;
7592
8d65af78 7593 ret = proc_dointvec(table, write, buffer, lenp, ppos);
d0b27fa7
PZ
7594
7595 if (!ret && write) {
7596 ret = sched_rt_global_constraints();
7597 if (ret) {
7598 sysctl_sched_rt_period = old_period;
7599 sysctl_sched_rt_runtime = old_runtime;
7600 } else {
7601 def_rt_bandwidth.rt_runtime = global_rt_runtime();
7602 def_rt_bandwidth.rt_period =
7603 ns_to_ktime(global_rt_period());
7604 }
7605 }
7606 mutex_unlock(&mutex);
7607
7608 return ret;
7609}
68318b8e 7610
052f1dc7 7611#ifdef CONFIG_CGROUP_SCHED
68318b8e
SV
7612
7613/* return corresponding task_group object of a cgroup */
2b01dfe3 7614static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
68318b8e 7615{
2b01dfe3
PM
7616 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7617 struct task_group, css);
68318b8e
SV
7618}
7619
92fb9748 7620static struct cgroup_subsys_state *cpu_cgroup_css_alloc(struct cgroup *cgrp)
68318b8e 7621{
ec7dc8ac 7622 struct task_group *tg, *parent;
68318b8e 7623
2b01dfe3 7624 if (!cgrp->parent) {
68318b8e 7625 /* This is early initialization for the top cgroup */
07e06b01 7626 return &root_task_group.css;
68318b8e
SV
7627 }
7628
ec7dc8ac
DG
7629 parent = cgroup_tg(cgrp->parent);
7630 tg = sched_create_group(parent);
68318b8e
SV
7631 if (IS_ERR(tg))
7632 return ERR_PTR(-ENOMEM);
7633
68318b8e
SV
7634 return &tg->css;
7635}
7636
ace783b9
LZ
7637static int cpu_cgroup_css_online(struct cgroup *cgrp)
7638{
7639 struct task_group *tg = cgroup_tg(cgrp);
7640 struct task_group *parent;
7641
7642 if (!cgrp->parent)
7643 return 0;
7644
7645 parent = cgroup_tg(cgrp->parent);
7646 sched_online_group(tg, parent);
7647 return 0;
7648}
7649
92fb9748 7650static void cpu_cgroup_css_free(struct cgroup *cgrp)
68318b8e 7651{
2b01dfe3 7652 struct task_group *tg = cgroup_tg(cgrp);
68318b8e
SV
7653
7654 sched_destroy_group(tg);
7655}
7656
ace783b9
LZ
7657static void cpu_cgroup_css_offline(struct cgroup *cgrp)
7658{
7659 struct task_group *tg = cgroup_tg(cgrp);
7660
7661 sched_offline_group(tg);
7662}
7663
761b3ef5 7664static int cpu_cgroup_can_attach(struct cgroup *cgrp,
bb9d97b6 7665 struct cgroup_taskset *tset)
68318b8e 7666{
bb9d97b6
TH
7667 struct task_struct *task;
7668
7669 cgroup_taskset_for_each(task, cgrp, tset) {
b68aa230 7670#ifdef CONFIG_RT_GROUP_SCHED
bb9d97b6
TH
7671 if (!sched_rt_can_attach(cgroup_tg(cgrp), task))
7672 return -EINVAL;
b68aa230 7673#else
bb9d97b6
TH
7674 /* We don't support RT-tasks being in separate groups */
7675 if (task->sched_class != &fair_sched_class)
7676 return -EINVAL;
b68aa230 7677#endif
bb9d97b6 7678 }
be367d09
BB
7679 return 0;
7680}
68318b8e 7681
761b3ef5 7682static void cpu_cgroup_attach(struct cgroup *cgrp,
bb9d97b6 7683 struct cgroup_taskset *tset)
68318b8e 7684{
bb9d97b6
TH
7685 struct task_struct *task;
7686
7687 cgroup_taskset_for_each(task, cgrp, tset)
7688 sched_move_task(task);
68318b8e
SV
7689}
7690
068c5cc5 7691static void
761b3ef5
LZ
7692cpu_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
7693 struct task_struct *task)
068c5cc5
PZ
7694{
7695 /*
7696 * cgroup_exit() is called in the copy_process() failure path.
7697 * Ignore this case since the task hasn't ran yet, this avoids
7698 * trying to poke a half freed task state from generic code.
7699 */
7700 if (!(task->flags & PF_EXITING))
7701 return;
7702
7703 sched_move_task(task);
7704}
7705
052f1dc7 7706#ifdef CONFIG_FAIR_GROUP_SCHED
f4c753b7 7707static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
2b01dfe3 7708 u64 shareval)
68318b8e 7709{
c8b28116 7710 return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval));
68318b8e
SV
7711}
7712
f4c753b7 7713static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
68318b8e 7714{
2b01dfe3 7715 struct task_group *tg = cgroup_tg(cgrp);
68318b8e 7716
c8b28116 7717 return (u64) scale_load_down(tg->shares);
68318b8e 7718}
ab84d31e
PT
7719
7720#ifdef CONFIG_CFS_BANDWIDTH
a790de99
PT
7721static DEFINE_MUTEX(cfs_constraints_mutex);
7722
ab84d31e
PT
7723const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
7724const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
7725
a790de99
PT
7726static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
7727
ab84d31e
PT
7728static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
7729{
56f570e5 7730 int i, ret = 0, runtime_enabled, runtime_was_enabled;
029632fb 7731 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
ab84d31e
PT
7732
7733 if (tg == &root_task_group)
7734 return -EINVAL;
7735
7736 /*
7737 * Ensure we have at some amount of bandwidth every period. This is
7738 * to prevent reaching a state of large arrears when throttled via
7739 * entity_tick() resulting in prolonged exit starvation.
7740 */
7741 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
7742 return -EINVAL;
7743
7744 /*
7745 * Likewise, bound things on the otherside by preventing insane quota
7746 * periods. This also allows us to normalize in computing quota
7747 * feasibility.
7748 */
7749 if (period > max_cfs_quota_period)
7750 return -EINVAL;
7751
a790de99
PT
7752 mutex_lock(&cfs_constraints_mutex);
7753 ret = __cfs_schedulable(tg, period, quota);
7754 if (ret)
7755 goto out_unlock;
7756
58088ad0 7757 runtime_enabled = quota != RUNTIME_INF;
56f570e5
PT
7758 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
7759 account_cfs_bandwidth_used(runtime_enabled, runtime_was_enabled);
ab84d31e
PT
7760 raw_spin_lock_irq(&cfs_b->lock);
7761 cfs_b->period = ns_to_ktime(period);
7762 cfs_b->quota = quota;
58088ad0 7763
a9cf55b2 7764 __refill_cfs_bandwidth_runtime(cfs_b);
58088ad0
PT
7765 /* restart the period timer (if active) to handle new period expiry */
7766 if (runtime_enabled && cfs_b->timer_active) {
7767 /* force a reprogram */
7768 cfs_b->timer_active = 0;
7769 __start_cfs_bandwidth(cfs_b);
7770 }
ab84d31e
PT
7771 raw_spin_unlock_irq(&cfs_b->lock);
7772
7773 for_each_possible_cpu(i) {
7774 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
029632fb 7775 struct rq *rq = cfs_rq->rq;
ab84d31e
PT
7776
7777 raw_spin_lock_irq(&rq->lock);
58088ad0 7778 cfs_rq->runtime_enabled = runtime_enabled;
ab84d31e 7779 cfs_rq->runtime_remaining = 0;
671fd9da 7780
029632fb 7781 if (cfs_rq->throttled)
671fd9da 7782 unthrottle_cfs_rq(cfs_rq);
ab84d31e
PT
7783 raw_spin_unlock_irq(&rq->lock);
7784 }
a790de99
PT
7785out_unlock:
7786 mutex_unlock(&cfs_constraints_mutex);
ab84d31e 7787
a790de99 7788 return ret;
ab84d31e
PT
7789}
7790
7791int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
7792{
7793 u64 quota, period;
7794
029632fb 7795 period = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
7796 if (cfs_quota_us < 0)
7797 quota = RUNTIME_INF;
7798 else
7799 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
7800
7801 return tg_set_cfs_bandwidth(tg, period, quota);
7802}
7803
7804long tg_get_cfs_quota(struct task_group *tg)
7805{
7806 u64 quota_us;
7807
029632fb 7808 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
ab84d31e
PT
7809 return -1;
7810
029632fb 7811 quota_us = tg->cfs_bandwidth.quota;
ab84d31e
PT
7812 do_div(quota_us, NSEC_PER_USEC);
7813
7814 return quota_us;
7815}
7816
7817int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
7818{
7819 u64 quota, period;
7820
7821 period = (u64)cfs_period_us * NSEC_PER_USEC;
029632fb 7822 quota = tg->cfs_bandwidth.quota;
ab84d31e 7823
ab84d31e
PT
7824 return tg_set_cfs_bandwidth(tg, period, quota);
7825}
7826
7827long tg_get_cfs_period(struct task_group *tg)
7828{
7829 u64 cfs_period_us;
7830
029632fb 7831 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
7832 do_div(cfs_period_us, NSEC_PER_USEC);
7833
7834 return cfs_period_us;
7835}
7836
7837static s64 cpu_cfs_quota_read_s64(struct cgroup *cgrp, struct cftype *cft)
7838{
7839 return tg_get_cfs_quota(cgroup_tg(cgrp));
7840}
7841
7842static int cpu_cfs_quota_write_s64(struct cgroup *cgrp, struct cftype *cftype,
7843 s64 cfs_quota_us)
7844{
7845 return tg_set_cfs_quota(cgroup_tg(cgrp), cfs_quota_us);
7846}
7847
7848static u64 cpu_cfs_period_read_u64(struct cgroup *cgrp, struct cftype *cft)
7849{
7850 return tg_get_cfs_period(cgroup_tg(cgrp));
7851}
7852
7853static int cpu_cfs_period_write_u64(struct cgroup *cgrp, struct cftype *cftype,
7854 u64 cfs_period_us)
7855{
7856 return tg_set_cfs_period(cgroup_tg(cgrp), cfs_period_us);
7857}
7858
a790de99
PT
7859struct cfs_schedulable_data {
7860 struct task_group *tg;
7861 u64 period, quota;
7862};
7863
7864/*
7865 * normalize group quota/period to be quota/max_period
7866 * note: units are usecs
7867 */
7868static u64 normalize_cfs_quota(struct task_group *tg,
7869 struct cfs_schedulable_data *d)
7870{
7871 u64 quota, period;
7872
7873 if (tg == d->tg) {
7874 period = d->period;
7875 quota = d->quota;
7876 } else {
7877 period = tg_get_cfs_period(tg);
7878 quota = tg_get_cfs_quota(tg);
7879 }
7880
7881 /* note: these should typically be equivalent */
7882 if (quota == RUNTIME_INF || quota == -1)
7883 return RUNTIME_INF;
7884
7885 return to_ratio(period, quota);
7886}
7887
7888static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
7889{
7890 struct cfs_schedulable_data *d = data;
029632fb 7891 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
a790de99
PT
7892 s64 quota = 0, parent_quota = -1;
7893
7894 if (!tg->parent) {
7895 quota = RUNTIME_INF;
7896 } else {
029632fb 7897 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
a790de99
PT
7898
7899 quota = normalize_cfs_quota(tg, d);
7900 parent_quota = parent_b->hierarchal_quota;
7901
7902 /*
7903 * ensure max(child_quota) <= parent_quota, inherit when no
7904 * limit is set
7905 */
7906 if (quota == RUNTIME_INF)
7907 quota = parent_quota;
7908 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
7909 return -EINVAL;
7910 }
7911 cfs_b->hierarchal_quota = quota;
7912
7913 return 0;
7914}
7915
7916static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
7917{
8277434e 7918 int ret;
a790de99
PT
7919 struct cfs_schedulable_data data = {
7920 .tg = tg,
7921 .period = period,
7922 .quota = quota,
7923 };
7924
7925 if (quota != RUNTIME_INF) {
7926 do_div(data.period, NSEC_PER_USEC);
7927 do_div(data.quota, NSEC_PER_USEC);
7928 }
7929
8277434e
PT
7930 rcu_read_lock();
7931 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
7932 rcu_read_unlock();
7933
7934 return ret;
a790de99 7935}
e8da1b18
NR
7936
7937static int cpu_stats_show(struct cgroup *cgrp, struct cftype *cft,
7938 struct cgroup_map_cb *cb)
7939{
7940 struct task_group *tg = cgroup_tg(cgrp);
029632fb 7941 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
e8da1b18
NR
7942
7943 cb->fill(cb, "nr_periods", cfs_b->nr_periods);
7944 cb->fill(cb, "nr_throttled", cfs_b->nr_throttled);
7945 cb->fill(cb, "throttled_time", cfs_b->throttled_time);
7946
7947 return 0;
7948}
ab84d31e 7949#endif /* CONFIG_CFS_BANDWIDTH */
6d6bc0ad 7950#endif /* CONFIG_FAIR_GROUP_SCHED */
68318b8e 7951
052f1dc7 7952#ifdef CONFIG_RT_GROUP_SCHED
0c70814c 7953static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
06ecb27c 7954 s64 val)
6f505b16 7955{
06ecb27c 7956 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
6f505b16
PZ
7957}
7958
06ecb27c 7959static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
6f505b16 7960{
06ecb27c 7961 return sched_group_rt_runtime(cgroup_tg(cgrp));
6f505b16 7962}
d0b27fa7
PZ
7963
7964static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
7965 u64 rt_period_us)
7966{
7967 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
7968}
7969
7970static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
7971{
7972 return sched_group_rt_period(cgroup_tg(cgrp));
7973}
6d6bc0ad 7974#endif /* CONFIG_RT_GROUP_SCHED */
6f505b16 7975
fe5c7cc2 7976static struct cftype cpu_files[] = {
052f1dc7 7977#ifdef CONFIG_FAIR_GROUP_SCHED
fe5c7cc2
PM
7978 {
7979 .name = "shares",
f4c753b7
PM
7980 .read_u64 = cpu_shares_read_u64,
7981 .write_u64 = cpu_shares_write_u64,
fe5c7cc2 7982 },
052f1dc7 7983#endif
ab84d31e
PT
7984#ifdef CONFIG_CFS_BANDWIDTH
7985 {
7986 .name = "cfs_quota_us",
7987 .read_s64 = cpu_cfs_quota_read_s64,
7988 .write_s64 = cpu_cfs_quota_write_s64,
7989 },
7990 {
7991 .name = "cfs_period_us",
7992 .read_u64 = cpu_cfs_period_read_u64,
7993 .write_u64 = cpu_cfs_period_write_u64,
7994 },
e8da1b18
NR
7995 {
7996 .name = "stat",
7997 .read_map = cpu_stats_show,
7998 },
ab84d31e 7999#endif
052f1dc7 8000#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 8001 {
9f0c1e56 8002 .name = "rt_runtime_us",
06ecb27c
PM
8003 .read_s64 = cpu_rt_runtime_read,
8004 .write_s64 = cpu_rt_runtime_write,
6f505b16 8005 },
d0b27fa7
PZ
8006 {
8007 .name = "rt_period_us",
f4c753b7
PM
8008 .read_u64 = cpu_rt_period_read_uint,
8009 .write_u64 = cpu_rt_period_write_uint,
d0b27fa7 8010 },
052f1dc7 8011#endif
4baf6e33 8012 { } /* terminate */
68318b8e
SV
8013};
8014
68318b8e 8015struct cgroup_subsys cpu_cgroup_subsys = {
38605cae 8016 .name = "cpu",
92fb9748
TH
8017 .css_alloc = cpu_cgroup_css_alloc,
8018 .css_free = cpu_cgroup_css_free,
ace783b9
LZ
8019 .css_online = cpu_cgroup_css_online,
8020 .css_offline = cpu_cgroup_css_offline,
bb9d97b6
TH
8021 .can_attach = cpu_cgroup_can_attach,
8022 .attach = cpu_cgroup_attach,
068c5cc5 8023 .exit = cpu_cgroup_exit,
38605cae 8024 .subsys_id = cpu_cgroup_subsys_id,
4baf6e33 8025 .base_cftypes = cpu_files,
68318b8e
SV
8026 .early_init = 1,
8027};
8028
052f1dc7 8029#endif /* CONFIG_CGROUP_SCHED */
d842de87 8030
b637a328
PM
8031void dump_cpu_task(int cpu)
8032{
8033 pr_info("Task dump for CPU %d:\n", cpu);
8034 sched_show_task(cpu_curr(cpu));
8035}