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