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