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