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