]> git.proxmox.com Git - mirror_ubuntu-kernels.git/blame - kernel/sched/core.c
sched: Fix priority inversion of cookied task with sibling
[mirror_ubuntu-kernels.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 */
9d246053
PA
9#define CREATE_TRACE_POINTS
10#include <trace/events/sched.h>
11#undef CREATE_TRACE_POINTS
12
325ea10c 13#include "sched.h"
1da177e4 14
7281c8de 15#include <linux/nospec.h>
85f1abe0 16
0ed557aa 17#include <linux/kcov.h>
d08b9f0c 18#include <linux/scs.h>
0ed557aa 19
96f951ed 20#include <asm/switch_to.h>
5517d86b 21#include <asm/tlb.h>
1da177e4 22
ea138446 23#include "../workqueue_internal.h"
771b53d0 24#include "../../fs/io-wq.h"
29d5e047 25#include "../smpboot.h"
6e0534f2 26
91c27493 27#include "pelt.h"
1f8db415 28#include "smp.h"
91c27493 29
a056a5be
QY
30/*
31 * Export tracepoints that act as a bare tracehook (ie: have no trace event
32 * associated with them) to allow external modules to probe them.
33 */
34EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
35EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
36EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
37EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
38EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
51cf18c9 39EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
a056a5be 40EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
4581bea8
VD
41EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
42EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
9d246053 43EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
a056a5be 44
029632fb 45DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
dc61b1d6 46
a73f863a 47#ifdef CONFIG_SCHED_DEBUG
bf5c91ba
IM
48/*
49 * Debugging: various feature bits
765cc3a4
PB
50 *
51 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
52 * sysctl_sched_features, defined in sched.h, to allow constants propagation
53 * at compile time and compiler optimization based on features default.
bf5c91ba 54 */
f00b45c1
PZ
55#define SCHED_FEAT(name, enabled) \
56 (1UL << __SCHED_FEAT_##name) * enabled |
bf5c91ba 57const_debug unsigned int sysctl_sched_features =
391e43da 58#include "features.h"
f00b45c1 59 0;
f00b45c1 60#undef SCHED_FEAT
c006fac5
PT
61
62/*
63 * Print a warning if need_resched is set for the given duration (if
64 * LATENCY_WARN is enabled).
65 *
66 * If sysctl_resched_latency_warn_once is set, only one warning will be shown
67 * per boot.
68 */
69__read_mostly int sysctl_resched_latency_warn_ms = 100;
70__read_mostly int sysctl_resched_latency_warn_once = 1;
71#endif /* CONFIG_SCHED_DEBUG */
f00b45c1 72
b82d9fdd
PZ
73/*
74 * Number of tasks to iterate in a single balance run.
75 * Limited because this is done with IRQs disabled.
76 */
77const_debug unsigned int sysctl_sched_nr_migrate = 32;
78
fa85ae24 79/*
d1ccc66d 80 * period over which we measure -rt task CPU usage in us.
fa85ae24
PZ
81 * default: 1s
82 */
9f0c1e56 83unsigned int sysctl_sched_rt_period = 1000000;
fa85ae24 84
029632fb 85__read_mostly int scheduler_running;
6892b75e 86
9edeaea1
PZ
87#ifdef CONFIG_SCHED_CORE
88
89DEFINE_STATIC_KEY_FALSE(__sched_core_enabled);
90
8a311c74
PZ
91/* kernel prio, less is more */
92static inline int __task_prio(struct task_struct *p)
93{
94 if (p->sched_class == &stop_sched_class) /* trumps deadline */
95 return -2;
96
97 if (rt_prio(p->prio)) /* includes deadline */
98 return p->prio; /* [-1, 99] */
99
100 if (p->sched_class == &idle_sched_class)
101 return MAX_RT_PRIO + NICE_WIDTH; /* 140 */
102
103 return MAX_RT_PRIO + MAX_NICE; /* 120, squash fair */
104}
105
106/*
107 * l(a,b)
108 * le(a,b) := !l(b,a)
109 * g(a,b) := l(b,a)
110 * ge(a,b) := !l(a,b)
111 */
112
113/* real prio, less is less */
114static inline bool prio_less(struct task_struct *a, struct task_struct *b)
115{
116
117 int pa = __task_prio(a), pb = __task_prio(b);
118
119 if (-pa < -pb)
120 return true;
121
122 if (-pb < -pa)
123 return false;
124
125 if (pa == -1) /* dl_prio() doesn't work because of stop_class above */
126 return !dl_time_before(a->dl.deadline, b->dl.deadline);
127
128 if (pa == MAX_RT_PRIO + MAX_NICE) { /* fair */
129 u64 vruntime = b->se.vruntime;
130
131 /*
132 * Normalize the vruntime if tasks are in different cpus.
133 */
134 if (task_cpu(a) != task_cpu(b)) {
135 vruntime -= task_cfs_rq(b)->min_vruntime;
136 vruntime += task_cfs_rq(a)->min_vruntime;
137 }
138
139 return !((s64)(a->se.vruntime - vruntime) <= 0);
140 }
141
142 return false;
143}
144
145static inline bool __sched_core_less(struct task_struct *a, struct task_struct *b)
146{
147 if (a->core_cookie < b->core_cookie)
148 return true;
149
150 if (a->core_cookie > b->core_cookie)
151 return false;
152
153 /* flip prio, so high prio is leftmost */
154 if (prio_less(b, a))
155 return true;
156
157 return false;
158}
159
160#define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
161
162static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b)
163{
164 return __sched_core_less(__node_2_sc(a), __node_2_sc(b));
165}
166
167static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node)
168{
169 const struct task_struct *p = __node_2_sc(node);
170 unsigned long cookie = (unsigned long)key;
171
172 if (cookie < p->core_cookie)
173 return -1;
174
175 if (cookie > p->core_cookie)
176 return 1;
177
178 return 0;
179}
180
181static void sched_core_enqueue(struct rq *rq, struct task_struct *p)
182{
183 rq->core->core_task_seq++;
184
185 if (!p->core_cookie)
186 return;
187
188 rb_add(&p->core_node, &rq->core_tree, rb_sched_core_less);
189}
190
191static void sched_core_dequeue(struct rq *rq, struct task_struct *p)
192{
193 rq->core->core_task_seq++;
194
195 if (!p->core_cookie)
196 return;
197
198 rb_erase(&p->core_node, &rq->core_tree);
199}
200
201/*
202 * Find left-most (aka, highest priority) task matching @cookie.
203 */
204static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie)
205{
206 struct rb_node *node;
207
208 node = rb_find_first((void *)cookie, &rq->core_tree, rb_sched_core_cmp);
209 /*
210 * The idle task always matches any cookie!
211 */
212 if (!node)
213 return idle_sched_class.pick_task(rq);
214
215 return __node_2_sc(node);
216}
217
9edeaea1
PZ
218/*
219 * Magic required such that:
220 *
221 * raw_spin_rq_lock(rq);
222 * ...
223 * raw_spin_rq_unlock(rq);
224 *
225 * ends up locking and unlocking the _same_ lock, and all CPUs
226 * always agree on what rq has what lock.
227 *
228 * XXX entirely possible to selectively enable cores, don't bother for now.
229 */
230
231static DEFINE_MUTEX(sched_core_mutex);
875feb41 232static atomic_t sched_core_count;
9edeaea1
PZ
233static struct cpumask sched_core_mask;
234
235static void __sched_core_flip(bool enabled)
236{
237 int cpu, t, i;
238
239 cpus_read_lock();
240
241 /*
242 * Toggle the online cores, one by one.
243 */
244 cpumask_copy(&sched_core_mask, cpu_online_mask);
245 for_each_cpu(cpu, &sched_core_mask) {
246 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
247
248 i = 0;
249 local_irq_disable();
250 for_each_cpu(t, smt_mask) {
251 /* supports up to SMT8 */
252 raw_spin_lock_nested(&cpu_rq(t)->__lock, i++);
253 }
254
255 for_each_cpu(t, smt_mask)
256 cpu_rq(t)->core_enabled = enabled;
257
258 for_each_cpu(t, smt_mask)
259 raw_spin_unlock(&cpu_rq(t)->__lock);
260 local_irq_enable();
261
262 cpumask_andnot(&sched_core_mask, &sched_core_mask, smt_mask);
263 }
264
265 /*
266 * Toggle the offline CPUs.
267 */
268 cpumask_copy(&sched_core_mask, cpu_possible_mask);
269 cpumask_andnot(&sched_core_mask, &sched_core_mask, cpu_online_mask);
270
271 for_each_cpu(cpu, &sched_core_mask)
272 cpu_rq(cpu)->core_enabled = enabled;
273
274 cpus_read_unlock();
275}
276
8a311c74 277static void sched_core_assert_empty(void)
9edeaea1 278{
8a311c74 279 int cpu;
9edeaea1 280
8a311c74
PZ
281 for_each_possible_cpu(cpu)
282 WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu)->core_tree));
283}
284
285static void __sched_core_enable(void)
286{
9edeaea1
PZ
287 static_branch_enable(&__sched_core_enabled);
288 /*
289 * Ensure all previous instances of raw_spin_rq_*lock() have finished
290 * and future ones will observe !sched_core_disabled().
291 */
292 synchronize_rcu();
293 __sched_core_flip(true);
8a311c74 294 sched_core_assert_empty();
9edeaea1
PZ
295}
296
297static void __sched_core_disable(void)
298{
8a311c74 299 sched_core_assert_empty();
9edeaea1
PZ
300 __sched_core_flip(false);
301 static_branch_disable(&__sched_core_enabled);
302}
303
304void sched_core_get(void)
305{
875feb41
PZ
306 if (atomic_inc_not_zero(&sched_core_count))
307 return;
308
9edeaea1 309 mutex_lock(&sched_core_mutex);
875feb41 310 if (!atomic_read(&sched_core_count))
9edeaea1 311 __sched_core_enable();
875feb41
PZ
312
313 smp_mb__before_atomic();
314 atomic_inc(&sched_core_count);
9edeaea1
PZ
315 mutex_unlock(&sched_core_mutex);
316}
317
875feb41 318static void __sched_core_put(struct work_struct *work)
9edeaea1 319{
875feb41 320 if (atomic_dec_and_mutex_lock(&sched_core_count, &sched_core_mutex)) {
9edeaea1 321 __sched_core_disable();
875feb41
PZ
322 mutex_unlock(&sched_core_mutex);
323 }
324}
325
326void sched_core_put(void)
327{
328 static DECLARE_WORK(_work, __sched_core_put);
329
330 /*
331 * "There can be only one"
332 *
333 * Either this is the last one, or we don't actually need to do any
334 * 'work'. If it is the last *again*, we rely on
335 * WORK_STRUCT_PENDING_BIT.
336 */
337 if (!atomic_add_unless(&sched_core_count, -1, 1))
338 schedule_work(&_work);
9edeaea1
PZ
339}
340
8a311c74
PZ
341#else /* !CONFIG_SCHED_CORE */
342
343static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { }
344static inline void sched_core_dequeue(struct rq *rq, struct task_struct *p) { }
345
9edeaea1
PZ
346#endif /* CONFIG_SCHED_CORE */
347
9f0c1e56
PZ
348/*
349 * part of the period that we allow rt tasks to run in us.
350 * default: 0.95s
351 */
352int sysctl_sched_rt_runtime = 950000;
fa85ae24 353
58877d34
PZ
354
355/*
356 * Serialization rules:
357 *
358 * Lock order:
359 *
360 * p->pi_lock
361 * rq->lock
362 * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
363 *
364 * rq1->lock
365 * rq2->lock where: rq1 < rq2
366 *
367 * Regular state:
368 *
369 * Normal scheduling state is serialized by rq->lock. __schedule() takes the
370 * local CPU's rq->lock, it optionally removes the task from the runqueue and
b19a888c 371 * always looks at the local rq data structures to find the most eligible task
58877d34
PZ
372 * to run next.
373 *
374 * Task enqueue is also under rq->lock, possibly taken from another CPU.
375 * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
376 * the local CPU to avoid bouncing the runqueue state around [ see
377 * ttwu_queue_wakelist() ]
378 *
379 * Task wakeup, specifically wakeups that involve migration, are horribly
380 * complicated to avoid having to take two rq->locks.
381 *
382 * Special state:
383 *
384 * System-calls and anything external will use task_rq_lock() which acquires
385 * both p->pi_lock and rq->lock. As a consequence the state they change is
386 * stable while holding either lock:
387 *
388 * - sched_setaffinity()/
389 * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
390 * - set_user_nice(): p->se.load, p->*prio
391 * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
392 * p->se.load, p->rt_priority,
393 * p->dl.dl_{runtime, deadline, period, flags, bw, density}
394 * - sched_setnuma(): p->numa_preferred_nid
395 * - sched_move_task()/
396 * cpu_cgroup_fork(): p->sched_task_group
397 * - uclamp_update_active() p->uclamp*
398 *
399 * p->state <- TASK_*:
400 *
401 * is changed locklessly using set_current_state(), __set_current_state() or
402 * set_special_state(), see their respective comments, or by
403 * try_to_wake_up(). This latter uses p->pi_lock to serialize against
404 * concurrent self.
405 *
406 * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
407 *
408 * is set by activate_task() and cleared by deactivate_task(), under
409 * rq->lock. Non-zero indicates the task is runnable, the special
410 * ON_RQ_MIGRATING state is used for migration without holding both
411 * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
412 *
413 * p->on_cpu <- { 0, 1 }:
414 *
415 * is set by prepare_task() and cleared by finish_task() such that it will be
416 * set before p is scheduled-in and cleared after p is scheduled-out, both
417 * under rq->lock. Non-zero indicates the task is running on its CPU.
418 *
419 * [ The astute reader will observe that it is possible for two tasks on one
420 * CPU to have ->on_cpu = 1 at the same time. ]
421 *
422 * task_cpu(p): is changed by set_task_cpu(), the rules are:
423 *
424 * - Don't call set_task_cpu() on a blocked task:
425 *
426 * We don't care what CPU we're not running on, this simplifies hotplug,
427 * the CPU assignment of blocked tasks isn't required to be valid.
428 *
429 * - for try_to_wake_up(), called under p->pi_lock:
430 *
431 * This allows try_to_wake_up() to only take one rq->lock, see its comment.
432 *
433 * - for migration called under rq->lock:
434 * [ see task_on_rq_migrating() in task_rq_lock() ]
435 *
436 * o move_queued_task()
437 * o detach_task()
438 *
439 * - for migration called under double_rq_lock():
440 *
441 * o __migrate_swap_task()
442 * o push_rt_task() / pull_rt_task()
443 * o push_dl_task() / pull_dl_task()
444 * o dl_task_offline_migration()
445 *
446 */
447
39d371b7
PZ
448void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
449{
d66f1b06
PZ
450 raw_spinlock_t *lock;
451
9edeaea1
PZ
452 /* Matches synchronize_rcu() in __sched_core_enable() */
453 preempt_disable();
d66f1b06
PZ
454 if (sched_core_disabled()) {
455 raw_spin_lock_nested(&rq->__lock, subclass);
9edeaea1
PZ
456 /* preempt_count *MUST* be > 1 */
457 preempt_enable_no_resched();
d66f1b06
PZ
458 return;
459 }
460
461 for (;;) {
9ef7e7e3 462 lock = __rq_lockp(rq);
d66f1b06 463 raw_spin_lock_nested(lock, subclass);
9ef7e7e3 464 if (likely(lock == __rq_lockp(rq))) {
9edeaea1
PZ
465 /* preempt_count *MUST* be > 1 */
466 preempt_enable_no_resched();
d66f1b06 467 return;
9edeaea1 468 }
d66f1b06
PZ
469 raw_spin_unlock(lock);
470 }
39d371b7
PZ
471}
472
473bool raw_spin_rq_trylock(struct rq *rq)
474{
d66f1b06
PZ
475 raw_spinlock_t *lock;
476 bool ret;
477
9edeaea1
PZ
478 /* Matches synchronize_rcu() in __sched_core_enable() */
479 preempt_disable();
480 if (sched_core_disabled()) {
481 ret = raw_spin_trylock(&rq->__lock);
482 preempt_enable();
483 return ret;
484 }
d66f1b06
PZ
485
486 for (;;) {
9ef7e7e3 487 lock = __rq_lockp(rq);
d66f1b06 488 ret = raw_spin_trylock(lock);
9ef7e7e3 489 if (!ret || (likely(lock == __rq_lockp(rq)))) {
9edeaea1 490 preempt_enable();
d66f1b06 491 return ret;
9edeaea1 492 }
d66f1b06
PZ
493 raw_spin_unlock(lock);
494 }
39d371b7
PZ
495}
496
497void raw_spin_rq_unlock(struct rq *rq)
498{
499 raw_spin_unlock(rq_lockp(rq));
500}
501
d66f1b06
PZ
502#ifdef CONFIG_SMP
503/*
504 * double_rq_lock - safely lock two runqueues
505 */
506void double_rq_lock(struct rq *rq1, struct rq *rq2)
507{
508 lockdep_assert_irqs_disabled();
509
510 if (rq_order_less(rq2, rq1))
511 swap(rq1, rq2);
512
513 raw_spin_rq_lock(rq1);
9ef7e7e3 514 if (__rq_lockp(rq1) == __rq_lockp(rq2))
d66f1b06
PZ
515 return;
516
517 raw_spin_rq_lock_nested(rq2, SINGLE_DEPTH_NESTING);
518}
519#endif
520
3e71a462
PZ
521/*
522 * __task_rq_lock - lock the rq @p resides on.
523 */
eb580751 524struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
525 __acquires(rq->lock)
526{
527 struct rq *rq;
528
529 lockdep_assert_held(&p->pi_lock);
530
531 for (;;) {
532 rq = task_rq(p);
5cb9eaa3 533 raw_spin_rq_lock(rq);
3e71a462 534 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 535 rq_pin_lock(rq, rf);
3e71a462
PZ
536 return rq;
537 }
5cb9eaa3 538 raw_spin_rq_unlock(rq);
3e71a462
PZ
539
540 while (unlikely(task_on_rq_migrating(p)))
541 cpu_relax();
542 }
543}
544
545/*
546 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
547 */
eb580751 548struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
549 __acquires(p->pi_lock)
550 __acquires(rq->lock)
551{
552 struct rq *rq;
553
554 for (;;) {
eb580751 555 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
3e71a462 556 rq = task_rq(p);
5cb9eaa3 557 raw_spin_rq_lock(rq);
3e71a462
PZ
558 /*
559 * move_queued_task() task_rq_lock()
560 *
561 * ACQUIRE (rq->lock)
562 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
563 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
564 * [S] ->cpu = new_cpu [L] task_rq()
565 * [L] ->on_rq
566 * RELEASE (rq->lock)
567 *
c546951d 568 * If we observe the old CPU in task_rq_lock(), the acquire of
3e71a462
PZ
569 * the old rq->lock will fully serialize against the stores.
570 *
c546951d
AP
571 * If we observe the new CPU in task_rq_lock(), the address
572 * dependency headed by '[L] rq = task_rq()' and the acquire
573 * will pair with the WMB to ensure we then also see migrating.
3e71a462
PZ
574 */
575 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 576 rq_pin_lock(rq, rf);
3e71a462
PZ
577 return rq;
578 }
5cb9eaa3 579 raw_spin_rq_unlock(rq);
eb580751 580 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
3e71a462
PZ
581
582 while (unlikely(task_on_rq_migrating(p)))
583 cpu_relax();
584 }
585}
586
535b9552
IM
587/*
588 * RQ-clock updating methods:
589 */
590
591static void update_rq_clock_task(struct rq *rq, s64 delta)
592{
593/*
594 * In theory, the compile should just see 0 here, and optimize out the call
595 * to sched_rt_avg_update. But I don't trust it...
596 */
11d4afd4
VG
597 s64 __maybe_unused steal = 0, irq_delta = 0;
598
535b9552
IM
599#ifdef CONFIG_IRQ_TIME_ACCOUNTING
600 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
601
602 /*
603 * Since irq_time is only updated on {soft,}irq_exit, we might run into
604 * this case when a previous update_rq_clock() happened inside a
605 * {soft,}irq region.
606 *
607 * When this happens, we stop ->clock_task and only update the
608 * prev_irq_time stamp to account for the part that fit, so that a next
609 * update will consume the rest. This ensures ->clock_task is
610 * monotonic.
611 *
612 * It does however cause some slight miss-attribution of {soft,}irq
613 * time, a more accurate solution would be to update the irq_time using
614 * the current rq->clock timestamp, except that would require using
615 * atomic ops.
616 */
617 if (irq_delta > delta)
618 irq_delta = delta;
619
620 rq->prev_irq_time += irq_delta;
621 delta -= irq_delta;
622#endif
623#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
624 if (static_key_false((&paravirt_steal_rq_enabled))) {
625 steal = paravirt_steal_clock(cpu_of(rq));
626 steal -= rq->prev_steal_time_rq;
627
628 if (unlikely(steal > delta))
629 steal = delta;
630
631 rq->prev_steal_time_rq += steal;
632 delta -= steal;
633 }
634#endif
635
636 rq->clock_task += delta;
637
11d4afd4 638#ifdef CONFIG_HAVE_SCHED_AVG_IRQ
535b9552 639 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
91c27493 640 update_irq_load_avg(rq, irq_delta + steal);
535b9552 641#endif
23127296 642 update_rq_clock_pelt(rq, delta);
535b9552
IM
643}
644
645void update_rq_clock(struct rq *rq)
646{
647 s64 delta;
648
5cb9eaa3 649 lockdep_assert_rq_held(rq);
535b9552
IM
650
651 if (rq->clock_update_flags & RQCF_ACT_SKIP)
652 return;
653
654#ifdef CONFIG_SCHED_DEBUG
26ae58d2
PZ
655 if (sched_feat(WARN_DOUBLE_CLOCK))
656 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
535b9552
IM
657 rq->clock_update_flags |= RQCF_UPDATED;
658#endif
26ae58d2 659
535b9552
IM
660 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
661 if (delta < 0)
662 return;
663 rq->clock += delta;
664 update_rq_clock_task(rq, delta);
665}
666
8f4d37ec
PZ
667#ifdef CONFIG_SCHED_HRTICK
668/*
669 * Use HR-timers to deliver accurate preemption points.
8f4d37ec 670 */
8f4d37ec 671
8f4d37ec
PZ
672static void hrtick_clear(struct rq *rq)
673{
674 if (hrtimer_active(&rq->hrtick_timer))
675 hrtimer_cancel(&rq->hrtick_timer);
676}
677
8f4d37ec
PZ
678/*
679 * High-resolution timer tick.
680 * Runs from hardirq context with interrupts disabled.
681 */
682static enum hrtimer_restart hrtick(struct hrtimer *timer)
683{
684 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
8a8c69c3 685 struct rq_flags rf;
8f4d37ec
PZ
686
687 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
688
8a8c69c3 689 rq_lock(rq, &rf);
3e51f33f 690 update_rq_clock(rq);
8f4d37ec 691 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
8a8c69c3 692 rq_unlock(rq, &rf);
8f4d37ec
PZ
693
694 return HRTIMER_NORESTART;
695}
696
95e904c7 697#ifdef CONFIG_SMP
971ee28c 698
4961b6e1 699static void __hrtick_restart(struct rq *rq)
971ee28c
PZ
700{
701 struct hrtimer *timer = &rq->hrtick_timer;
156ec6f4 702 ktime_t time = rq->hrtick_time;
971ee28c 703
156ec6f4 704 hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
971ee28c
PZ
705}
706
31656519
PZ
707/*
708 * called from hardirq (IPI) context
709 */
710static void __hrtick_start(void *arg)
b328ca18 711{
31656519 712 struct rq *rq = arg;
8a8c69c3 713 struct rq_flags rf;
b328ca18 714
8a8c69c3 715 rq_lock(rq, &rf);
971ee28c 716 __hrtick_restart(rq);
8a8c69c3 717 rq_unlock(rq, &rf);
b328ca18
PZ
718}
719
31656519
PZ
720/*
721 * Called to set the hrtick timer state.
722 *
723 * called with rq->lock held and irqs disabled
724 */
029632fb 725void hrtick_start(struct rq *rq, u64 delay)
b328ca18 726{
31656519 727 struct hrtimer *timer = &rq->hrtick_timer;
177ef2a6 728 s64 delta;
729
730 /*
731 * Don't schedule slices shorter than 10000ns, that just
732 * doesn't make sense and can cause timer DoS.
733 */
734 delta = max_t(s64, delay, 10000LL);
156ec6f4 735 rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
31656519 736
fd3eafda 737 if (rq == this_rq())
971ee28c 738 __hrtick_restart(rq);
fd3eafda 739 else
c46fff2a 740 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
b328ca18
PZ
741}
742
31656519
PZ
743#else
744/*
745 * Called to set the hrtick timer state.
746 *
747 * called with rq->lock held and irqs disabled
748 */
029632fb 749void hrtick_start(struct rq *rq, u64 delay)
31656519 750{
86893335
WL
751 /*
752 * Don't schedule slices shorter than 10000ns, that just
753 * doesn't make sense. Rely on vruntime for fairness.
754 */
755 delay = max_t(u64, delay, 10000LL);
4961b6e1 756 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
d5096aa6 757 HRTIMER_MODE_REL_PINNED_HARD);
31656519 758}
90b5363a 759
31656519 760#endif /* CONFIG_SMP */
8f4d37ec 761
77a021be 762static void hrtick_rq_init(struct rq *rq)
8f4d37ec 763{
31656519 764#ifdef CONFIG_SMP
545b8c8d 765 INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq);
31656519 766#endif
d5096aa6 767 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
31656519 768 rq->hrtick_timer.function = hrtick;
8f4d37ec 769}
006c75f1 770#else /* CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
771static inline void hrtick_clear(struct rq *rq)
772{
773}
774
77a021be 775static inline void hrtick_rq_init(struct rq *rq)
8f4d37ec
PZ
776{
777}
006c75f1 778#endif /* CONFIG_SCHED_HRTICK */
8f4d37ec 779
5529578a
FW
780/*
781 * cmpxchg based fetch_or, macro so it works for different integer types
782 */
783#define fetch_or(ptr, mask) \
784 ({ \
785 typeof(ptr) _ptr = (ptr); \
786 typeof(mask) _mask = (mask); \
787 typeof(*_ptr) _old, _val = *_ptr; \
788 \
789 for (;;) { \
790 _old = cmpxchg(_ptr, _val, _val | _mask); \
791 if (_old == _val) \
792 break; \
793 _val = _old; \
794 } \
795 _old; \
796})
797
e3baac47 798#if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
fd99f91a
PZ
799/*
800 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
801 * this avoids any races wrt polling state changes and thereby avoids
802 * spurious IPIs.
803 */
804static bool set_nr_and_not_polling(struct task_struct *p)
805{
806 struct thread_info *ti = task_thread_info(p);
807 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
808}
e3baac47
PZ
809
810/*
811 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
812 *
813 * If this returns true, then the idle task promises to call
814 * sched_ttwu_pending() and reschedule soon.
815 */
816static bool set_nr_if_polling(struct task_struct *p)
817{
818 struct thread_info *ti = task_thread_info(p);
316c1608 819 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
e3baac47
PZ
820
821 for (;;) {
822 if (!(val & _TIF_POLLING_NRFLAG))
823 return false;
824 if (val & _TIF_NEED_RESCHED)
825 return true;
826 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
827 if (old == val)
828 break;
829 val = old;
830 }
831 return true;
832}
833
fd99f91a
PZ
834#else
835static bool set_nr_and_not_polling(struct task_struct *p)
836{
837 set_tsk_need_resched(p);
838 return true;
839}
e3baac47
PZ
840
841#ifdef CONFIG_SMP
842static bool set_nr_if_polling(struct task_struct *p)
843{
844 return false;
845}
846#endif
fd99f91a
PZ
847#endif
848
07879c6a 849static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
76751049
PZ
850{
851 struct wake_q_node *node = &task->wake_q;
852
853 /*
854 * Atomically grab the task, if ->wake_q is !nil already it means
b19a888c 855 * it's already queued (either by us or someone else) and will get the
76751049
PZ
856 * wakeup due to that.
857 *
4c4e3731
PZ
858 * In order to ensure that a pending wakeup will observe our pending
859 * state, even in the failed case, an explicit smp_mb() must be used.
76751049 860 */
4c4e3731 861 smp_mb__before_atomic();
87ff19cb 862 if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
07879c6a 863 return false;
76751049
PZ
864
865 /*
866 * The head is context local, there can be no concurrency.
867 */
868 *head->lastp = node;
869 head->lastp = &node->next;
07879c6a
DB
870 return true;
871}
872
873/**
874 * wake_q_add() - queue a wakeup for 'later' waking.
875 * @head: the wake_q_head to add @task to
876 * @task: the task to queue for 'later' wakeup
877 *
878 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
879 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
880 * instantly.
881 *
882 * This function must be used as-if it were wake_up_process(); IOW the task
883 * must be ready to be woken at this location.
884 */
885void wake_q_add(struct wake_q_head *head, struct task_struct *task)
886{
887 if (__wake_q_add(head, task))
888 get_task_struct(task);
889}
890
891/**
892 * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
893 * @head: the wake_q_head to add @task to
894 * @task: the task to queue for 'later' wakeup
895 *
896 * Queue a task for later wakeup, most likely by the wake_up_q() call in the
897 * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
898 * instantly.
899 *
900 * This function must be used as-if it were wake_up_process(); IOW the task
901 * must be ready to be woken at this location.
902 *
903 * This function is essentially a task-safe equivalent to wake_q_add(). Callers
904 * that already hold reference to @task can call the 'safe' version and trust
905 * wake_q to do the right thing depending whether or not the @task is already
906 * queued for wakeup.
907 */
908void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
909{
910 if (!__wake_q_add(head, task))
911 put_task_struct(task);
76751049
PZ
912}
913
914void wake_up_q(struct wake_q_head *head)
915{
916 struct wake_q_node *node = head->first;
917
918 while (node != WAKE_Q_TAIL) {
919 struct task_struct *task;
920
921 task = container_of(node, struct task_struct, wake_q);
d1ccc66d 922 /* Task can safely be re-inserted now: */
76751049
PZ
923 node = node->next;
924 task->wake_q.next = NULL;
925
926 /*
7696f991
AP
927 * wake_up_process() executes a full barrier, which pairs with
928 * the queueing in wake_q_add() so as not to miss wakeups.
76751049
PZ
929 */
930 wake_up_process(task);
931 put_task_struct(task);
932 }
933}
934
c24d20db 935/*
8875125e 936 * resched_curr - mark rq's current task 'to be rescheduled now'.
c24d20db
IM
937 *
938 * On UP this means the setting of the need_resched flag, on SMP it
939 * might also involve a cross-CPU call to trigger the scheduler on
940 * the target CPU.
941 */
8875125e 942void resched_curr(struct rq *rq)
c24d20db 943{
8875125e 944 struct task_struct *curr = rq->curr;
c24d20db
IM
945 int cpu;
946
5cb9eaa3 947 lockdep_assert_rq_held(rq);
c24d20db 948
8875125e 949 if (test_tsk_need_resched(curr))
c24d20db
IM
950 return;
951
8875125e 952 cpu = cpu_of(rq);
fd99f91a 953
f27dde8d 954 if (cpu == smp_processor_id()) {
8875125e 955 set_tsk_need_resched(curr);
f27dde8d 956 set_preempt_need_resched();
c24d20db 957 return;
f27dde8d 958 }
c24d20db 959
8875125e 960 if (set_nr_and_not_polling(curr))
c24d20db 961 smp_send_reschedule(cpu);
dfc68f29
AL
962 else
963 trace_sched_wake_idle_without_ipi(cpu);
c24d20db
IM
964}
965
029632fb 966void resched_cpu(int cpu)
c24d20db
IM
967{
968 struct rq *rq = cpu_rq(cpu);
969 unsigned long flags;
970
5cb9eaa3 971 raw_spin_rq_lock_irqsave(rq, flags);
a0982dfa
PM
972 if (cpu_online(cpu) || cpu == smp_processor_id())
973 resched_curr(rq);
5cb9eaa3 974 raw_spin_rq_unlock_irqrestore(rq, flags);
c24d20db 975}
06d8308c 976
b021fe3e 977#ifdef CONFIG_SMP
3451d024 978#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2 979/*
d1ccc66d
IM
980 * In the semi idle case, use the nearest busy CPU for migrating timers
981 * from an idle CPU. This is good for power-savings.
83cd4fe2
VP
982 *
983 * We don't do similar optimization for completely idle system, as
d1ccc66d
IM
984 * selecting an idle CPU will add more delays to the timers than intended
985 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
83cd4fe2 986 */
bc7a34b8 987int get_nohz_timer_target(void)
83cd4fe2 988{
e938b9c9 989 int i, cpu = smp_processor_id(), default_cpu = -1;
83cd4fe2
VP
990 struct sched_domain *sd;
991
e938b9c9
WL
992 if (housekeeping_cpu(cpu, HK_FLAG_TIMER)) {
993 if (!idle_cpu(cpu))
994 return cpu;
995 default_cpu = cpu;
996 }
6201b4d6 997
057f3fad 998 rcu_read_lock();
83cd4fe2 999 for_each_domain(cpu, sd) {
e938b9c9
WL
1000 for_each_cpu_and(i, sched_domain_span(sd),
1001 housekeeping_cpumask(HK_FLAG_TIMER)) {
44496922
WL
1002 if (cpu == i)
1003 continue;
1004
e938b9c9 1005 if (!idle_cpu(i)) {
057f3fad
PZ
1006 cpu = i;
1007 goto unlock;
1008 }
1009 }
83cd4fe2 1010 }
9642d18e 1011
e938b9c9
WL
1012 if (default_cpu == -1)
1013 default_cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
1014 cpu = default_cpu;
057f3fad
PZ
1015unlock:
1016 rcu_read_unlock();
83cd4fe2
VP
1017 return cpu;
1018}
d1ccc66d 1019
06d8308c
TG
1020/*
1021 * When add_timer_on() enqueues a timer into the timer wheel of an
1022 * idle CPU then this timer might expire before the next timer event
1023 * which is scheduled to wake up that CPU. In case of a completely
1024 * idle system the next event might even be infinite time into the
1025 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1026 * leaves the inner idle loop so the newly added timer is taken into
1027 * account when the CPU goes back to idle and evaluates the timer
1028 * wheel for the next timer event.
1029 */
1c20091e 1030static void wake_up_idle_cpu(int cpu)
06d8308c
TG
1031{
1032 struct rq *rq = cpu_rq(cpu);
1033
1034 if (cpu == smp_processor_id())
1035 return;
1036
67b9ca70 1037 if (set_nr_and_not_polling(rq->idle))
06d8308c 1038 smp_send_reschedule(cpu);
dfc68f29
AL
1039 else
1040 trace_sched_wake_idle_without_ipi(cpu);
45bf76df
IM
1041}
1042
c5bfece2 1043static bool wake_up_full_nohz_cpu(int cpu)
1c20091e 1044{
53c5fa16
FW
1045 /*
1046 * We just need the target to call irq_exit() and re-evaluate
1047 * the next tick. The nohz full kick at least implies that.
1048 * If needed we can still optimize that later with an
1049 * empty IRQ.
1050 */
379d9ecb
PM
1051 if (cpu_is_offline(cpu))
1052 return true; /* Don't try to wake offline CPUs. */
c5bfece2 1053 if (tick_nohz_full_cpu(cpu)) {
1c20091e
FW
1054 if (cpu != smp_processor_id() ||
1055 tick_nohz_tick_stopped())
53c5fa16 1056 tick_nohz_full_kick_cpu(cpu);
1c20091e
FW
1057 return true;
1058 }
1059
1060 return false;
1061}
1062
379d9ecb
PM
1063/*
1064 * Wake up the specified CPU. If the CPU is going offline, it is the
1065 * caller's responsibility to deal with the lost wakeup, for example,
1066 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
1067 */
1c20091e
FW
1068void wake_up_nohz_cpu(int cpu)
1069{
c5bfece2 1070 if (!wake_up_full_nohz_cpu(cpu))
1c20091e
FW
1071 wake_up_idle_cpu(cpu);
1072}
1073
19a1f5ec 1074static void nohz_csd_func(void *info)
45bf76df 1075{
19a1f5ec
PZ
1076 struct rq *rq = info;
1077 int cpu = cpu_of(rq);
1078 unsigned int flags;
873b4c65
VG
1079
1080 /*
19a1f5ec 1081 * Release the rq::nohz_csd.
873b4c65 1082 */
c6f88654 1083 flags = atomic_fetch_andnot(NOHZ_KICK_MASK | NOHZ_NEWILB_KICK, nohz_flags(cpu));
19a1f5ec 1084 WARN_ON(!(flags & NOHZ_KICK_MASK));
45bf76df 1085
19a1f5ec
PZ
1086 rq->idle_balance = idle_cpu(cpu);
1087 if (rq->idle_balance && !need_resched()) {
1088 rq->nohz_idle_balance = flags;
90b5363a
PZI
1089 raise_softirq_irqoff(SCHED_SOFTIRQ);
1090 }
2069dd75
PZ
1091}
1092
3451d024 1093#endif /* CONFIG_NO_HZ_COMMON */
d842de87 1094
ce831b38 1095#ifdef CONFIG_NO_HZ_FULL
76d92ac3 1096bool sched_can_stop_tick(struct rq *rq)
ce831b38 1097{
76d92ac3
FW
1098 int fifo_nr_running;
1099
1100 /* Deadline tasks, even if single, need the tick */
1101 if (rq->dl.dl_nr_running)
1102 return false;
1103
1e78cdbd 1104 /*
b19a888c 1105 * If there are more than one RR tasks, we need the tick to affect the
2548d546 1106 * actual RR behaviour.
1e78cdbd 1107 */
76d92ac3
FW
1108 if (rq->rt.rr_nr_running) {
1109 if (rq->rt.rr_nr_running == 1)
1110 return true;
1111 else
1112 return false;
1e78cdbd
RR
1113 }
1114
2548d546
PZ
1115 /*
1116 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
1117 * forced preemption between FIFO tasks.
1118 */
1119 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
1120 if (fifo_nr_running)
1121 return true;
1122
1123 /*
1124 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
1125 * if there's more than one we need the tick for involuntary
1126 * preemption.
1127 */
1128 if (rq->nr_running > 1)
541b8264 1129 return false;
ce831b38 1130
541b8264 1131 return true;
ce831b38
FW
1132}
1133#endif /* CONFIG_NO_HZ_FULL */
6d6bc0ad 1134#endif /* CONFIG_SMP */
18d95a28 1135
a790de99
PT
1136#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
1137 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
c09595f6 1138/*
8277434e
PT
1139 * Iterate task_group tree rooted at *from, calling @down when first entering a
1140 * node and @up when leaving it for the final time.
1141 *
1142 * Caller must hold rcu_lock or sufficient equivalent.
c09595f6 1143 */
029632fb 1144int walk_tg_tree_from(struct task_group *from,
8277434e 1145 tg_visitor down, tg_visitor up, void *data)
c09595f6
PZ
1146{
1147 struct task_group *parent, *child;
eb755805 1148 int ret;
c09595f6 1149
8277434e
PT
1150 parent = from;
1151
c09595f6 1152down:
eb755805
PZ
1153 ret = (*down)(parent, data);
1154 if (ret)
8277434e 1155 goto out;
c09595f6
PZ
1156 list_for_each_entry_rcu(child, &parent->children, siblings) {
1157 parent = child;
1158 goto down;
1159
1160up:
1161 continue;
1162 }
eb755805 1163 ret = (*up)(parent, data);
8277434e
PT
1164 if (ret || parent == from)
1165 goto out;
c09595f6
PZ
1166
1167 child = parent;
1168 parent = parent->parent;
1169 if (parent)
1170 goto up;
8277434e 1171out:
eb755805 1172 return ret;
c09595f6
PZ
1173}
1174
029632fb 1175int tg_nop(struct task_group *tg, void *data)
eb755805 1176{
e2b245f8 1177 return 0;
eb755805 1178}
18d95a28
PZ
1179#endif
1180
9059393e 1181static void set_load_weight(struct task_struct *p, bool update_load)
45bf76df 1182{
f05998d4
NR
1183 int prio = p->static_prio - MAX_RT_PRIO;
1184 struct load_weight *load = &p->se.load;
1185
dd41f596
IM
1186 /*
1187 * SCHED_IDLE tasks get minimal weight:
1188 */
1da1843f 1189 if (task_has_idle_policy(p)) {
c8b28116 1190 load->weight = scale_load(WEIGHT_IDLEPRIO);
f05998d4 1191 load->inv_weight = WMULT_IDLEPRIO;
dd41f596
IM
1192 return;
1193 }
71f8bd46 1194
9059393e
VG
1195 /*
1196 * SCHED_OTHER tasks have to update their load when changing their
1197 * weight
1198 */
1199 if (update_load && p->sched_class == &fair_sched_class) {
1200 reweight_task(p, prio);
1201 } else {
1202 load->weight = scale_load(sched_prio_to_weight[prio]);
1203 load->inv_weight = sched_prio_to_wmult[prio];
1204 }
71f8bd46
IM
1205}
1206
69842cba 1207#ifdef CONFIG_UCLAMP_TASK
2480c093
PB
1208/*
1209 * Serializes updates of utilization clamp values
1210 *
1211 * The (slow-path) user-space triggers utilization clamp value updates which
1212 * can require updates on (fast-path) scheduler's data structures used to
1213 * support enqueue/dequeue operations.
1214 * While the per-CPU rq lock protects fast-path update operations, user-space
1215 * requests are serialized using a mutex to reduce the risk of conflicting
1216 * updates or API abuses.
1217 */
1218static DEFINE_MUTEX(uclamp_mutex);
1219
e8f14172
PB
1220/* Max allowed minimum utilization */
1221unsigned int sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
1222
1223/* Max allowed maximum utilization */
1224unsigned int sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
1225
13685c4a
QY
1226/*
1227 * By default RT tasks run at the maximum performance point/capacity of the
1228 * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
1229 * SCHED_CAPACITY_SCALE.
1230 *
1231 * This knob allows admins to change the default behavior when uclamp is being
1232 * used. In battery powered devices, particularly, running at the maximum
1233 * capacity and frequency will increase energy consumption and shorten the
1234 * battery life.
1235 *
1236 * This knob only affects RT tasks that their uclamp_se->user_defined == false.
1237 *
1238 * This knob will not override the system default sched_util_clamp_min defined
1239 * above.
1240 */
1241unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
1242
e8f14172
PB
1243/* All clamps are required to be less or equal than these values */
1244static struct uclamp_se uclamp_default[UCLAMP_CNT];
69842cba 1245
46609ce2
QY
1246/*
1247 * This static key is used to reduce the uclamp overhead in the fast path. It
1248 * primarily disables the call to uclamp_rq_{inc, dec}() in
1249 * enqueue/dequeue_task().
1250 *
1251 * This allows users to continue to enable uclamp in their kernel config with
1252 * minimum uclamp overhead in the fast path.
1253 *
1254 * As soon as userspace modifies any of the uclamp knobs, the static key is
1255 * enabled, since we have an actual users that make use of uclamp
1256 * functionality.
1257 *
1258 * The knobs that would enable this static key are:
1259 *
1260 * * A task modifying its uclamp value with sched_setattr().
1261 * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
1262 * * An admin modifying the cgroup cpu.uclamp.{min, max}
1263 */
1264DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
1265
69842cba
PB
1266/* Integer rounded range for each bucket */
1267#define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
1268
1269#define for_each_clamp_id(clamp_id) \
1270 for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
1271
1272static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
1273{
6d2f8909 1274 return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
69842cba
PB
1275}
1276
7763baac 1277static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
69842cba
PB
1278{
1279 if (clamp_id == UCLAMP_MIN)
1280 return 0;
1281 return SCHED_CAPACITY_SCALE;
1282}
1283
a509a7cd
PB
1284static inline void uclamp_se_set(struct uclamp_se *uc_se,
1285 unsigned int value, bool user_defined)
69842cba
PB
1286{
1287 uc_se->value = value;
1288 uc_se->bucket_id = uclamp_bucket_id(value);
a509a7cd 1289 uc_se->user_defined = user_defined;
69842cba
PB
1290}
1291
e496187d 1292static inline unsigned int
0413d7f3 1293uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
e496187d
PB
1294 unsigned int clamp_value)
1295{
1296 /*
1297 * Avoid blocked utilization pushing up the frequency when we go
1298 * idle (which drops the max-clamp) by retaining the last known
1299 * max-clamp.
1300 */
1301 if (clamp_id == UCLAMP_MAX) {
1302 rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
1303 return clamp_value;
1304 }
1305
1306 return uclamp_none(UCLAMP_MIN);
1307}
1308
0413d7f3 1309static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
e496187d
PB
1310 unsigned int clamp_value)
1311{
1312 /* Reset max-clamp retention only on idle exit */
1313 if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1314 return;
1315
1316 WRITE_ONCE(rq->uclamp[clamp_id].value, clamp_value);
1317}
1318
69842cba 1319static inline
7763baac 1320unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
0413d7f3 1321 unsigned int clamp_value)
69842cba
PB
1322{
1323 struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
1324 int bucket_id = UCLAMP_BUCKETS - 1;
1325
1326 /*
1327 * Since both min and max clamps are max aggregated, find the
1328 * top most bucket with tasks in.
1329 */
1330 for ( ; bucket_id >= 0; bucket_id--) {
1331 if (!bucket[bucket_id].tasks)
1332 continue;
1333 return bucket[bucket_id].value;
1334 }
1335
1336 /* No tasks -- default clamp values */
e496187d 1337 return uclamp_idle_value(rq, clamp_id, clamp_value);
69842cba
PB
1338}
1339
13685c4a
QY
1340static void __uclamp_update_util_min_rt_default(struct task_struct *p)
1341{
1342 unsigned int default_util_min;
1343 struct uclamp_se *uc_se;
1344
1345 lockdep_assert_held(&p->pi_lock);
1346
1347 uc_se = &p->uclamp_req[UCLAMP_MIN];
1348
1349 /* Only sync if user didn't override the default */
1350 if (uc_se->user_defined)
1351 return;
1352
1353 default_util_min = sysctl_sched_uclamp_util_min_rt_default;
1354 uclamp_se_set(uc_se, default_util_min, false);
1355}
1356
1357static void uclamp_update_util_min_rt_default(struct task_struct *p)
1358{
1359 struct rq_flags rf;
1360 struct rq *rq;
1361
1362 if (!rt_task(p))
1363 return;
1364
1365 /* Protect updates to p->uclamp_* */
1366 rq = task_rq_lock(p, &rf);
1367 __uclamp_update_util_min_rt_default(p);
1368 task_rq_unlock(rq, p, &rf);
1369}
1370
1371static void uclamp_sync_util_min_rt_default(void)
1372{
1373 struct task_struct *g, *p;
1374
1375 /*
1376 * copy_process() sysctl_uclamp
1377 * uclamp_min_rt = X;
1378 * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
1379 * // link thread smp_mb__after_spinlock()
1380 * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
1381 * sched_post_fork() for_each_process_thread()
1382 * __uclamp_sync_rt() __uclamp_sync_rt()
1383 *
1384 * Ensures that either sched_post_fork() will observe the new
1385 * uclamp_min_rt or for_each_process_thread() will observe the new
1386 * task.
1387 */
1388 read_lock(&tasklist_lock);
1389 smp_mb__after_spinlock();
1390 read_unlock(&tasklist_lock);
1391
1392 rcu_read_lock();
1393 for_each_process_thread(g, p)
1394 uclamp_update_util_min_rt_default(p);
1395 rcu_read_unlock();
1396}
1397
3eac870a 1398static inline struct uclamp_se
0413d7f3 1399uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
3eac870a
PB
1400{
1401 struct uclamp_se uc_req = p->uclamp_req[clamp_id];
1402#ifdef CONFIG_UCLAMP_TASK_GROUP
1403 struct uclamp_se uc_max;
1404
1405 /*
1406 * Tasks in autogroups or root task group will be
1407 * restricted by system defaults.
1408 */
1409 if (task_group_is_autogroup(task_group(p)))
1410 return uc_req;
1411 if (task_group(p) == &root_task_group)
1412 return uc_req;
1413
1414 uc_max = task_group(p)->uclamp[clamp_id];
1415 if (uc_req.value > uc_max.value || !uc_req.user_defined)
1416 return uc_max;
1417#endif
1418
1419 return uc_req;
1420}
1421
e8f14172
PB
1422/*
1423 * The effective clamp bucket index of a task depends on, by increasing
1424 * priority:
1425 * - the task specific clamp value, when explicitly requested from userspace
3eac870a
PB
1426 * - the task group effective clamp value, for tasks not either in the root
1427 * group or in an autogroup
e8f14172
PB
1428 * - the system default clamp value, defined by the sysadmin
1429 */
1430static inline struct uclamp_se
0413d7f3 1431uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
e8f14172 1432{
3eac870a 1433 struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
e8f14172
PB
1434 struct uclamp_se uc_max = uclamp_default[clamp_id];
1435
1436 /* System default restrictions always apply */
1437 if (unlikely(uc_req.value > uc_max.value))
1438 return uc_max;
1439
1440 return uc_req;
1441}
1442
686516b5 1443unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
9d20ad7d
PB
1444{
1445 struct uclamp_se uc_eff;
1446
1447 /* Task currently refcounted: use back-annotated (effective) value */
1448 if (p->uclamp[clamp_id].active)
686516b5 1449 return (unsigned long)p->uclamp[clamp_id].value;
9d20ad7d
PB
1450
1451 uc_eff = uclamp_eff_get(p, clamp_id);
1452
686516b5 1453 return (unsigned long)uc_eff.value;
9d20ad7d
PB
1454}
1455
69842cba
PB
1456/*
1457 * When a task is enqueued on a rq, the clamp bucket currently defined by the
1458 * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1459 * updates the rq's clamp value if required.
60daf9c1
PB
1460 *
1461 * Tasks can have a task-specific value requested from user-space, track
1462 * within each bucket the maximum value for tasks refcounted in it.
1463 * This "local max aggregation" allows to track the exact "requested" value
1464 * for each bucket when all its RUNNABLE tasks require the same clamp.
69842cba
PB
1465 */
1466static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
0413d7f3 1467 enum uclamp_id clamp_id)
69842cba
PB
1468{
1469 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1470 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1471 struct uclamp_bucket *bucket;
1472
5cb9eaa3 1473 lockdep_assert_rq_held(rq);
69842cba 1474
e8f14172
PB
1475 /* Update task effective clamp */
1476 p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
1477
69842cba
PB
1478 bucket = &uc_rq->bucket[uc_se->bucket_id];
1479 bucket->tasks++;
e8f14172 1480 uc_se->active = true;
69842cba 1481
e496187d
PB
1482 uclamp_idle_reset(rq, clamp_id, uc_se->value);
1483
60daf9c1
PB
1484 /*
1485 * Local max aggregation: rq buckets always track the max
1486 * "requested" clamp value of its RUNNABLE tasks.
1487 */
1488 if (bucket->tasks == 1 || uc_se->value > bucket->value)
1489 bucket->value = uc_se->value;
1490
69842cba 1491 if (uc_se->value > READ_ONCE(uc_rq->value))
60daf9c1 1492 WRITE_ONCE(uc_rq->value, uc_se->value);
69842cba
PB
1493}
1494
1495/*
1496 * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1497 * is released. If this is the last task reference counting the rq's max
1498 * active clamp value, then the rq's clamp value is updated.
1499 *
1500 * Both refcounted tasks and rq's cached clamp values are expected to be
1501 * always valid. If it's detected they are not, as defensive programming,
1502 * enforce the expected state and warn.
1503 */
1504static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
0413d7f3 1505 enum uclamp_id clamp_id)
69842cba
PB
1506{
1507 struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1508 struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1509 struct uclamp_bucket *bucket;
e496187d 1510 unsigned int bkt_clamp;
69842cba
PB
1511 unsigned int rq_clamp;
1512
5cb9eaa3 1513 lockdep_assert_rq_held(rq);
69842cba 1514
46609ce2
QY
1515 /*
1516 * If sched_uclamp_used was enabled after task @p was enqueued,
1517 * we could end up with unbalanced call to uclamp_rq_dec_id().
1518 *
1519 * In this case the uc_se->active flag should be false since no uclamp
1520 * accounting was performed at enqueue time and we can just return
1521 * here.
1522 *
b19a888c 1523 * Need to be careful of the following enqueue/dequeue ordering
46609ce2
QY
1524 * problem too
1525 *
1526 * enqueue(taskA)
1527 * // sched_uclamp_used gets enabled
1528 * enqueue(taskB)
1529 * dequeue(taskA)
b19a888c 1530 * // Must not decrement bucket->tasks here
46609ce2
QY
1531 * dequeue(taskB)
1532 *
1533 * where we could end up with stale data in uc_se and
1534 * bucket[uc_se->bucket_id].
1535 *
1536 * The following check here eliminates the possibility of such race.
1537 */
1538 if (unlikely(!uc_se->active))
1539 return;
1540
69842cba 1541 bucket = &uc_rq->bucket[uc_se->bucket_id];
46609ce2 1542
69842cba
PB
1543 SCHED_WARN_ON(!bucket->tasks);
1544 if (likely(bucket->tasks))
1545 bucket->tasks--;
46609ce2 1546
e8f14172 1547 uc_se->active = false;
69842cba 1548
60daf9c1
PB
1549 /*
1550 * Keep "local max aggregation" simple and accept to (possibly)
1551 * overboost some RUNNABLE tasks in the same bucket.
1552 * The rq clamp bucket value is reset to its base value whenever
1553 * there are no more RUNNABLE tasks refcounting it.
1554 */
69842cba
PB
1555 if (likely(bucket->tasks))
1556 return;
1557
1558 rq_clamp = READ_ONCE(uc_rq->value);
1559 /*
1560 * Defensive programming: this should never happen. If it happens,
1561 * e.g. due to future modification, warn and fixup the expected value.
1562 */
1563 SCHED_WARN_ON(bucket->value > rq_clamp);
e496187d
PB
1564 if (bucket->value >= rq_clamp) {
1565 bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
1566 WRITE_ONCE(uc_rq->value, bkt_clamp);
1567 }
69842cba
PB
1568}
1569
1570static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
1571{
0413d7f3 1572 enum uclamp_id clamp_id;
69842cba 1573
46609ce2
QY
1574 /*
1575 * Avoid any overhead until uclamp is actually used by the userspace.
1576 *
1577 * The condition is constructed such that a NOP is generated when
1578 * sched_uclamp_used is disabled.
1579 */
1580 if (!static_branch_unlikely(&sched_uclamp_used))
1581 return;
1582
69842cba
PB
1583 if (unlikely(!p->sched_class->uclamp_enabled))
1584 return;
1585
1586 for_each_clamp_id(clamp_id)
1587 uclamp_rq_inc_id(rq, p, clamp_id);
e496187d
PB
1588
1589 /* Reset clamp idle holding when there is one RUNNABLE task */
1590 if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
1591 rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
69842cba
PB
1592}
1593
1594static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
1595{
0413d7f3 1596 enum uclamp_id clamp_id;
69842cba 1597
46609ce2
QY
1598 /*
1599 * Avoid any overhead until uclamp is actually used by the userspace.
1600 *
1601 * The condition is constructed such that a NOP is generated when
1602 * sched_uclamp_used is disabled.
1603 */
1604 if (!static_branch_unlikely(&sched_uclamp_used))
1605 return;
1606
69842cba
PB
1607 if (unlikely(!p->sched_class->uclamp_enabled))
1608 return;
1609
1610 for_each_clamp_id(clamp_id)
1611 uclamp_rq_dec_id(rq, p, clamp_id);
1612}
1613
babbe170 1614static inline void
0413d7f3 1615uclamp_update_active(struct task_struct *p, enum uclamp_id clamp_id)
babbe170
PB
1616{
1617 struct rq_flags rf;
1618 struct rq *rq;
1619
1620 /*
1621 * Lock the task and the rq where the task is (or was) queued.
1622 *
1623 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1624 * price to pay to safely serialize util_{min,max} updates with
1625 * enqueues, dequeues and migration operations.
1626 * This is the same locking schema used by __set_cpus_allowed_ptr().
1627 */
1628 rq = task_rq_lock(p, &rf);
1629
1630 /*
1631 * Setting the clamp bucket is serialized by task_rq_lock().
1632 * If the task is not yet RUNNABLE and its task_struct is not
1633 * affecting a valid clamp bucket, the next time it's enqueued,
1634 * it will already see the updated clamp bucket value.
1635 */
6e1ff077 1636 if (p->uclamp[clamp_id].active) {
babbe170
PB
1637 uclamp_rq_dec_id(rq, p, clamp_id);
1638 uclamp_rq_inc_id(rq, p, clamp_id);
1639 }
1640
1641 task_rq_unlock(rq, p, &rf);
1642}
1643
e3b8b6a0 1644#ifdef CONFIG_UCLAMP_TASK_GROUP
babbe170
PB
1645static inline void
1646uclamp_update_active_tasks(struct cgroup_subsys_state *css,
1647 unsigned int clamps)
1648{
0413d7f3 1649 enum uclamp_id clamp_id;
babbe170
PB
1650 struct css_task_iter it;
1651 struct task_struct *p;
babbe170
PB
1652
1653 css_task_iter_start(css, 0, &it);
1654 while ((p = css_task_iter_next(&it))) {
1655 for_each_clamp_id(clamp_id) {
1656 if ((0x1 << clamp_id) & clamps)
1657 uclamp_update_active(p, clamp_id);
1658 }
1659 }
1660 css_task_iter_end(&it);
1661}
1662
7274a5c1
PB
1663static void cpu_util_update_eff(struct cgroup_subsys_state *css);
1664static void uclamp_update_root_tg(void)
1665{
1666 struct task_group *tg = &root_task_group;
1667
1668 uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
1669 sysctl_sched_uclamp_util_min, false);
1670 uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
1671 sysctl_sched_uclamp_util_max, false);
1672
1673 rcu_read_lock();
1674 cpu_util_update_eff(&root_task_group.css);
1675 rcu_read_unlock();
1676}
1677#else
1678static void uclamp_update_root_tg(void) { }
1679#endif
1680
e8f14172 1681int sysctl_sched_uclamp_handler(struct ctl_table *table, int write,
32927393 1682 void *buffer, size_t *lenp, loff_t *ppos)
e8f14172 1683{
7274a5c1 1684 bool update_root_tg = false;
13685c4a 1685 int old_min, old_max, old_min_rt;
e8f14172
PB
1686 int result;
1687
2480c093 1688 mutex_lock(&uclamp_mutex);
e8f14172
PB
1689 old_min = sysctl_sched_uclamp_util_min;
1690 old_max = sysctl_sched_uclamp_util_max;
13685c4a 1691 old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
e8f14172
PB
1692
1693 result = proc_dointvec(table, write, buffer, lenp, ppos);
1694 if (result)
1695 goto undo;
1696 if (!write)
1697 goto done;
1698
1699 if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
13685c4a
QY
1700 sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE ||
1701 sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
1702
e8f14172
PB
1703 result = -EINVAL;
1704 goto undo;
1705 }
1706
1707 if (old_min != sysctl_sched_uclamp_util_min) {
1708 uclamp_se_set(&uclamp_default[UCLAMP_MIN],
a509a7cd 1709 sysctl_sched_uclamp_util_min, false);
7274a5c1 1710 update_root_tg = true;
e8f14172
PB
1711 }
1712 if (old_max != sysctl_sched_uclamp_util_max) {
1713 uclamp_se_set(&uclamp_default[UCLAMP_MAX],
a509a7cd 1714 sysctl_sched_uclamp_util_max, false);
7274a5c1 1715 update_root_tg = true;
e8f14172
PB
1716 }
1717
46609ce2
QY
1718 if (update_root_tg) {
1719 static_branch_enable(&sched_uclamp_used);
7274a5c1 1720 uclamp_update_root_tg();
46609ce2 1721 }
7274a5c1 1722
13685c4a
QY
1723 if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
1724 static_branch_enable(&sched_uclamp_used);
1725 uclamp_sync_util_min_rt_default();
1726 }
7274a5c1 1727
e8f14172 1728 /*
7274a5c1
PB
1729 * We update all RUNNABLE tasks only when task groups are in use.
1730 * Otherwise, keep it simple and do just a lazy update at each next
1731 * task enqueue time.
e8f14172 1732 */
7274a5c1 1733
e8f14172
PB
1734 goto done;
1735
1736undo:
1737 sysctl_sched_uclamp_util_min = old_min;
1738 sysctl_sched_uclamp_util_max = old_max;
13685c4a 1739 sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
e8f14172 1740done:
2480c093 1741 mutex_unlock(&uclamp_mutex);
e8f14172
PB
1742
1743 return result;
1744}
1745
a509a7cd
PB
1746static int uclamp_validate(struct task_struct *p,
1747 const struct sched_attr *attr)
1748{
480a6ca2
DE
1749 int util_min = p->uclamp_req[UCLAMP_MIN].value;
1750 int util_max = p->uclamp_req[UCLAMP_MAX].value;
a509a7cd 1751
480a6ca2
DE
1752 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
1753 util_min = attr->sched_util_min;
a509a7cd 1754
480a6ca2
DE
1755 if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
1756 return -EINVAL;
1757 }
1758
1759 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
1760 util_max = attr->sched_util_max;
1761
1762 if (util_max + 1 > SCHED_CAPACITY_SCALE + 1)
1763 return -EINVAL;
1764 }
1765
1766 if (util_min != -1 && util_max != -1 && util_min > util_max)
a509a7cd
PB
1767 return -EINVAL;
1768
e65855a5
QY
1769 /*
1770 * We have valid uclamp attributes; make sure uclamp is enabled.
1771 *
1772 * We need to do that here, because enabling static branches is a
1773 * blocking operation which obviously cannot be done while holding
1774 * scheduler locks.
1775 */
1776 static_branch_enable(&sched_uclamp_used);
1777
a509a7cd
PB
1778 return 0;
1779}
1780
480a6ca2
DE
1781static bool uclamp_reset(const struct sched_attr *attr,
1782 enum uclamp_id clamp_id,
1783 struct uclamp_se *uc_se)
1784{
1785 /* Reset on sched class change for a non user-defined clamp value. */
1786 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)) &&
1787 !uc_se->user_defined)
1788 return true;
1789
1790 /* Reset on sched_util_{min,max} == -1. */
1791 if (clamp_id == UCLAMP_MIN &&
1792 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1793 attr->sched_util_min == -1) {
1794 return true;
1795 }
1796
1797 if (clamp_id == UCLAMP_MAX &&
1798 attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1799 attr->sched_util_max == -1) {
1800 return true;
1801 }
1802
1803 return false;
1804}
1805
a509a7cd
PB
1806static void __setscheduler_uclamp(struct task_struct *p,
1807 const struct sched_attr *attr)
1808{
0413d7f3 1809 enum uclamp_id clamp_id;
1a00d999 1810
1a00d999
PB
1811 for_each_clamp_id(clamp_id) {
1812 struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
480a6ca2 1813 unsigned int value;
1a00d999 1814
480a6ca2 1815 if (!uclamp_reset(attr, clamp_id, uc_se))
1a00d999
PB
1816 continue;
1817
13685c4a
QY
1818 /*
1819 * RT by default have a 100% boost value that could be modified
1820 * at runtime.
1821 */
1a00d999 1822 if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
480a6ca2 1823 value = sysctl_sched_uclamp_util_min_rt_default;
13685c4a 1824 else
480a6ca2
DE
1825 value = uclamp_none(clamp_id);
1826
1827 uclamp_se_set(uc_se, value, false);
1a00d999 1828
1a00d999
PB
1829 }
1830
a509a7cd
PB
1831 if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
1832 return;
1833
480a6ca2
DE
1834 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
1835 attr->sched_util_min != -1) {
a509a7cd
PB
1836 uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
1837 attr->sched_util_min, true);
1838 }
1839
480a6ca2
DE
1840 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
1841 attr->sched_util_max != -1) {
a509a7cd
PB
1842 uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
1843 attr->sched_util_max, true);
1844 }
1845}
1846
e8f14172
PB
1847static void uclamp_fork(struct task_struct *p)
1848{
0413d7f3 1849 enum uclamp_id clamp_id;
e8f14172 1850
13685c4a
QY
1851 /*
1852 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
1853 * as the task is still at its early fork stages.
1854 */
e8f14172
PB
1855 for_each_clamp_id(clamp_id)
1856 p->uclamp[clamp_id].active = false;
a87498ac
PB
1857
1858 if (likely(!p->sched_reset_on_fork))
1859 return;
1860
1861 for_each_clamp_id(clamp_id) {
eaf5a92e
QP
1862 uclamp_se_set(&p->uclamp_req[clamp_id],
1863 uclamp_none(clamp_id), false);
a87498ac 1864 }
e8f14172
PB
1865}
1866
13685c4a
QY
1867static void uclamp_post_fork(struct task_struct *p)
1868{
1869 uclamp_update_util_min_rt_default(p);
1870}
1871
d81ae8aa
QY
1872static void __init init_uclamp_rq(struct rq *rq)
1873{
1874 enum uclamp_id clamp_id;
1875 struct uclamp_rq *uc_rq = rq->uclamp;
1876
1877 for_each_clamp_id(clamp_id) {
1878 uc_rq[clamp_id] = (struct uclamp_rq) {
1879 .value = uclamp_none(clamp_id)
1880 };
1881 }
1882
1883 rq->uclamp_flags = 0;
1884}
1885
69842cba
PB
1886static void __init init_uclamp(void)
1887{
e8f14172 1888 struct uclamp_se uc_max = {};
0413d7f3 1889 enum uclamp_id clamp_id;
69842cba
PB
1890 int cpu;
1891
d81ae8aa
QY
1892 for_each_possible_cpu(cpu)
1893 init_uclamp_rq(cpu_rq(cpu));
69842cba 1894
69842cba 1895 for_each_clamp_id(clamp_id) {
e8f14172 1896 uclamp_se_set(&init_task.uclamp_req[clamp_id],
a509a7cd 1897 uclamp_none(clamp_id), false);
69842cba 1898 }
e8f14172
PB
1899
1900 /* System defaults allow max clamp values for both indexes */
a509a7cd 1901 uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
2480c093 1902 for_each_clamp_id(clamp_id) {
e8f14172 1903 uclamp_default[clamp_id] = uc_max;
2480c093
PB
1904#ifdef CONFIG_UCLAMP_TASK_GROUP
1905 root_task_group.uclamp_req[clamp_id] = uc_max;
0b60ba2d 1906 root_task_group.uclamp[clamp_id] = uc_max;
2480c093
PB
1907#endif
1908 }
69842cba
PB
1909}
1910
1911#else /* CONFIG_UCLAMP_TASK */
1912static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
1913static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
a509a7cd
PB
1914static inline int uclamp_validate(struct task_struct *p,
1915 const struct sched_attr *attr)
1916{
1917 return -EOPNOTSUPP;
1918}
1919static void __setscheduler_uclamp(struct task_struct *p,
1920 const struct sched_attr *attr) { }
e8f14172 1921static inline void uclamp_fork(struct task_struct *p) { }
13685c4a 1922static inline void uclamp_post_fork(struct task_struct *p) { }
69842cba
PB
1923static inline void init_uclamp(void) { }
1924#endif /* CONFIG_UCLAMP_TASK */
1925
1de64443 1926static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2087a1ad 1927{
0a67d1ee
PZ
1928 if (!(flags & ENQUEUE_NOCLOCK))
1929 update_rq_clock(rq);
1930
eb414681 1931 if (!(flags & ENQUEUE_RESTORE)) {
4e29fb70 1932 sched_info_enqueue(rq, p);
eb414681
JW
1933 psi_enqueue(p, flags & ENQUEUE_WAKEUP);
1934 }
0a67d1ee 1935
69842cba 1936 uclamp_rq_inc(rq, p);
371fd7e7 1937 p->sched_class->enqueue_task(rq, p, flags);
8a311c74
PZ
1938
1939 if (sched_core_enabled(rq))
1940 sched_core_enqueue(rq, p);
71f8bd46
IM
1941}
1942
1de64443 1943static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
71f8bd46 1944{
8a311c74
PZ
1945 if (sched_core_enabled(rq))
1946 sched_core_dequeue(rq, p);
1947
0a67d1ee
PZ
1948 if (!(flags & DEQUEUE_NOCLOCK))
1949 update_rq_clock(rq);
1950
eb414681 1951 if (!(flags & DEQUEUE_SAVE)) {
4e29fb70 1952 sched_info_dequeue(rq, p);
eb414681
JW
1953 psi_dequeue(p, flags & DEQUEUE_SLEEP);
1954 }
0a67d1ee 1955
69842cba 1956 uclamp_rq_dec(rq, p);
371fd7e7 1957 p->sched_class->dequeue_task(rq, p, flags);
71f8bd46
IM
1958}
1959
029632fb 1960void activate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd 1961{
371fd7e7 1962 enqueue_task(rq, p, flags);
7dd77884
PZ
1963
1964 p->on_rq = TASK_ON_RQ_QUEUED;
1e3c88bd
PZ
1965}
1966
029632fb 1967void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd 1968{
7dd77884
PZ
1969 p->on_rq = (flags & DEQUEUE_SLEEP) ? 0 : TASK_ON_RQ_MIGRATING;
1970
371fd7e7 1971 dequeue_task(rq, p, flags);
1e3c88bd
PZ
1972}
1973
14531189 1974/*
dd41f596 1975 * __normal_prio - return the priority that is based on the static prio
14531189 1976 */
14531189
IM
1977static inline int __normal_prio(struct task_struct *p)
1978{
dd41f596 1979 return p->static_prio;
14531189
IM
1980}
1981
b29739f9
IM
1982/*
1983 * Calculate the expected normal priority: i.e. priority
1984 * without taking RT-inheritance into account. Might be
1985 * boosted by interactivity modifiers. Changes upon fork,
1986 * setprio syscalls, and whenever the interactivity
1987 * estimator recalculates.
1988 */
36c8b586 1989static inline int normal_prio(struct task_struct *p)
b29739f9
IM
1990{
1991 int prio;
1992
aab03e05
DF
1993 if (task_has_dl_policy(p))
1994 prio = MAX_DL_PRIO-1;
1995 else if (task_has_rt_policy(p))
b29739f9
IM
1996 prio = MAX_RT_PRIO-1 - p->rt_priority;
1997 else
1998 prio = __normal_prio(p);
1999 return prio;
2000}
2001
2002/*
2003 * Calculate the current priority, i.e. the priority
2004 * taken into account by the scheduler. This value might
2005 * be boosted by RT tasks, or might be boosted by
2006 * interactivity modifiers. Will be RT if the task got
2007 * RT-boosted. If not then it returns p->normal_prio.
2008 */
36c8b586 2009static int effective_prio(struct task_struct *p)
b29739f9
IM
2010{
2011 p->normal_prio = normal_prio(p);
2012 /*
2013 * If we are RT tasks or we were boosted to RT priority,
2014 * keep the priority unchanged. Otherwise, update priority
2015 * to the normal priority:
2016 */
2017 if (!rt_prio(p->prio))
2018 return p->normal_prio;
2019 return p->prio;
2020}
2021
1da177e4
LT
2022/**
2023 * task_curr - is this task currently executing on a CPU?
2024 * @p: the task in question.
e69f6186
YB
2025 *
2026 * Return: 1 if the task is currently executing. 0 otherwise.
1da177e4 2027 */
36c8b586 2028inline int task_curr(const struct task_struct *p)
1da177e4
LT
2029{
2030 return cpu_curr(task_cpu(p)) == p;
2031}
2032
67dfa1b7 2033/*
4c9a4bc8
PZ
2034 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
2035 * use the balance_callback list if you want balancing.
2036 *
2037 * this means any call to check_class_changed() must be followed by a call to
2038 * balance_callback().
67dfa1b7 2039 */
cb469845
SR
2040static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2041 const struct sched_class *prev_class,
da7a735e 2042 int oldprio)
cb469845
SR
2043{
2044 if (prev_class != p->sched_class) {
2045 if (prev_class->switched_from)
da7a735e 2046 prev_class->switched_from(rq, p);
4c9a4bc8 2047
da7a735e 2048 p->sched_class->switched_to(rq, p);
2d3d891d 2049 } else if (oldprio != p->prio || dl_task(p))
da7a735e 2050 p->sched_class->prio_changed(rq, p, oldprio);
cb469845
SR
2051}
2052
029632fb 2053void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1e5a7405 2054{
aa93cd53 2055 if (p->sched_class == rq->curr->sched_class)
1e5a7405 2056 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
aa93cd53
KT
2057 else if (p->sched_class > rq->curr->sched_class)
2058 resched_curr(rq);
1e5a7405
PZ
2059
2060 /*
2061 * A queue event has occurred, and we're going to schedule. In
2062 * this case, we can save a useless back to back clock update.
2063 */
da0c1e65 2064 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
adcc8da8 2065 rq_clock_skip_update(rq);
1e5a7405
PZ
2066}
2067
1da177e4 2068#ifdef CONFIG_SMP
175f0e25 2069
af449901
PZ
2070static void
2071__do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask, u32 flags);
2072
2073static int __set_cpus_allowed_ptr(struct task_struct *p,
2074 const struct cpumask *new_mask,
2075 u32 flags);
2076
2077static void migrate_disable_switch(struct rq *rq, struct task_struct *p)
2078{
2079 if (likely(!p->migration_disabled))
2080 return;
2081
2082 if (p->cpus_ptr != &p->cpus_mask)
2083 return;
2084
2085 /*
2086 * Violates locking rules! see comment in __do_set_cpus_allowed().
2087 */
2088 __do_set_cpus_allowed(p, cpumask_of(rq->cpu), SCA_MIGRATE_DISABLE);
2089}
2090
2091void migrate_disable(void)
2092{
3015ef4b
TG
2093 struct task_struct *p = current;
2094
2095 if (p->migration_disabled) {
2096 p->migration_disabled++;
af449901 2097 return;
3015ef4b 2098 }
af449901 2099
3015ef4b
TG
2100 preempt_disable();
2101 this_rq()->nr_pinned++;
2102 p->migration_disabled = 1;
2103 preempt_enable();
af449901
PZ
2104}
2105EXPORT_SYMBOL_GPL(migrate_disable);
2106
2107void migrate_enable(void)
2108{
2109 struct task_struct *p = current;
2110
6d337eab
PZ
2111 if (p->migration_disabled > 1) {
2112 p->migration_disabled--;
af449901 2113 return;
6d337eab 2114 }
af449901 2115
6d337eab
PZ
2116 /*
2117 * Ensure stop_task runs either before or after this, and that
2118 * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
2119 */
2120 preempt_disable();
2121 if (p->cpus_ptr != &p->cpus_mask)
2122 __set_cpus_allowed_ptr(p, &p->cpus_mask, SCA_MIGRATE_ENABLE);
2123 /*
2124 * Mustn't clear migration_disabled() until cpus_ptr points back at the
2125 * regular cpus_mask, otherwise things that race (eg.
2126 * select_fallback_rq) get confused.
2127 */
af449901 2128 barrier();
6d337eab 2129 p->migration_disabled = 0;
3015ef4b 2130 this_rq()->nr_pinned--;
6d337eab 2131 preempt_enable();
af449901
PZ
2132}
2133EXPORT_SYMBOL_GPL(migrate_enable);
2134
3015ef4b
TG
2135static inline bool rq_has_pinned_tasks(struct rq *rq)
2136{
2137 return rq->nr_pinned;
2138}
2139
175f0e25 2140/*
bee98539 2141 * Per-CPU kthreads are allowed to run on !active && online CPUs, see
175f0e25
PZ
2142 * __set_cpus_allowed_ptr() and select_fallback_rq().
2143 */
2144static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
2145{
5ba2ffba 2146 /* When not in the task's cpumask, no point in looking further. */
3bd37062 2147 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
175f0e25
PZ
2148 return false;
2149
5ba2ffba
PZ
2150 /* migrate_disabled() must be allowed to finish. */
2151 if (is_migration_disabled(p))
175f0e25
PZ
2152 return cpu_online(cpu);
2153
5ba2ffba
PZ
2154 /* Non kernel threads are not allowed during either online or offline. */
2155 if (!(p->flags & PF_KTHREAD))
2156 return cpu_active(cpu);
2157
2158 /* KTHREAD_IS_PER_CPU is always allowed. */
2159 if (kthread_is_per_cpu(p))
2160 return cpu_online(cpu);
2161
2162 /* Regular kernel threads don't get to stay during offline. */
b5c44773 2163 if (cpu_dying(cpu))
5ba2ffba
PZ
2164 return false;
2165
2166 /* But are allowed during online. */
2167 return cpu_online(cpu);
175f0e25
PZ
2168}
2169
5cc389bc
PZ
2170/*
2171 * This is how migration works:
2172 *
2173 * 1) we invoke migration_cpu_stop() on the target CPU using
2174 * stop_one_cpu().
2175 * 2) stopper starts to run (implicitly forcing the migrated thread
2176 * off the CPU)
2177 * 3) it checks whether the migrated task is still in the wrong runqueue.
2178 * 4) if it's in the wrong runqueue then the migration thread removes
2179 * it and puts it into the right queue.
2180 * 5) stopper completes and stop_one_cpu() returns and the migration
2181 * is done.
2182 */
2183
2184/*
2185 * move_queued_task - move a queued task to new rq.
2186 *
2187 * Returns (locked) new rq. Old rq's lock is released.
2188 */
8a8c69c3
PZ
2189static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
2190 struct task_struct *p, int new_cpu)
5cc389bc 2191{
5cb9eaa3 2192 lockdep_assert_rq_held(rq);
5cc389bc 2193
58877d34 2194 deactivate_task(rq, p, DEQUEUE_NOCLOCK);
5cc389bc 2195 set_task_cpu(p, new_cpu);
8a8c69c3 2196 rq_unlock(rq, rf);
5cc389bc
PZ
2197
2198 rq = cpu_rq(new_cpu);
2199
8a8c69c3 2200 rq_lock(rq, rf);
5cc389bc 2201 BUG_ON(task_cpu(p) != new_cpu);
58877d34 2202 activate_task(rq, p, 0);
5cc389bc
PZ
2203 check_preempt_curr(rq, p, 0);
2204
2205 return rq;
2206}
2207
2208struct migration_arg {
6d337eab
PZ
2209 struct task_struct *task;
2210 int dest_cpu;
2211 struct set_affinity_pending *pending;
2212};
2213
50caf9c1
PZ
2214/*
2215 * @refs: number of wait_for_completion()
2216 * @stop_pending: is @stop_work in use
2217 */
6d337eab
PZ
2218struct set_affinity_pending {
2219 refcount_t refs;
9e81889c 2220 unsigned int stop_pending;
6d337eab
PZ
2221 struct completion done;
2222 struct cpu_stop_work stop_work;
2223 struct migration_arg arg;
5cc389bc
PZ
2224};
2225
2226/*
d1ccc66d 2227 * Move (not current) task off this CPU, onto the destination CPU. We're doing
5cc389bc
PZ
2228 * this because either it can't run here any more (set_cpus_allowed()
2229 * away from this CPU, or CPU going down), or because we're
2230 * attempting to rebalance this task on exec (sched_exec).
2231 *
2232 * So we race with normal scheduler movements, but that's OK, as long
2233 * as the task is no longer on this CPU.
5cc389bc 2234 */
8a8c69c3
PZ
2235static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
2236 struct task_struct *p, int dest_cpu)
5cc389bc 2237{
5cc389bc 2238 /* Affinity changed (again). */
175f0e25 2239 if (!is_cpu_allowed(p, dest_cpu))
5e16bbc2 2240 return rq;
5cc389bc 2241
15ff991e 2242 update_rq_clock(rq);
8a8c69c3 2243 rq = move_queued_task(rq, rf, p, dest_cpu);
5e16bbc2
PZ
2244
2245 return rq;
5cc389bc
PZ
2246}
2247
2248/*
2249 * migration_cpu_stop - this will be executed by a highprio stopper thread
2250 * and performs thread migration by bumping thread off CPU then
2251 * 'pushing' onto another runqueue.
2252 */
2253static int migration_cpu_stop(void *data)
2254{
2255 struct migration_arg *arg = data;
c20cf065 2256 struct set_affinity_pending *pending = arg->pending;
5e16bbc2 2257 struct task_struct *p = arg->task;
6d337eab 2258 int dest_cpu = arg->dest_cpu;
5e16bbc2 2259 struct rq *rq = this_rq();
6d337eab 2260 bool complete = false;
8a8c69c3 2261 struct rq_flags rf;
5cc389bc
PZ
2262
2263 /*
d1ccc66d
IM
2264 * The original target CPU might have gone down and we might
2265 * be on another CPU but it doesn't matter.
5cc389bc 2266 */
6d337eab 2267 local_irq_save(rf.flags);
5cc389bc
PZ
2268 /*
2269 * We need to explicitly wake pending tasks before running
3bd37062 2270 * __migrate_task() such that we will not miss enforcing cpus_ptr
5cc389bc
PZ
2271 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
2272 */
a1488664 2273 flush_smp_call_function_from_idle();
5e16bbc2
PZ
2274
2275 raw_spin_lock(&p->pi_lock);
8a8c69c3 2276 rq_lock(rq, &rf);
6d337eab 2277
e140749c
VS
2278 /*
2279 * If we were passed a pending, then ->stop_pending was set, thus
2280 * p->migration_pending must have remained stable.
2281 */
2282 WARN_ON_ONCE(pending && pending != p->migration_pending);
2283
5e16bbc2
PZ
2284 /*
2285 * If task_rq(p) != rq, it cannot be migrated here, because we're
2286 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
2287 * we're holding p->pi_lock.
2288 */
bf89a304 2289 if (task_rq(p) == rq) {
6d337eab
PZ
2290 if (is_migration_disabled(p))
2291 goto out;
2292
2293 if (pending) {
e140749c 2294 p->migration_pending = NULL;
6d337eab
PZ
2295 complete = true;
2296 }
2297
3f1bc119
PZ
2298 if (dest_cpu < 0) {
2299 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask))
2300 goto out;
2301
6d337eab 2302 dest_cpu = cpumask_any_distribute(&p->cpus_mask);
3f1bc119 2303 }
6d337eab 2304
bf89a304 2305 if (task_on_rq_queued(p))
6d337eab 2306 rq = __migrate_task(rq, &rf, p, dest_cpu);
bf89a304 2307 else
6d337eab
PZ
2308 p->wake_cpu = dest_cpu;
2309
3f1bc119
PZ
2310 /*
2311 * XXX __migrate_task() can fail, at which point we might end
2312 * up running on a dodgy CPU, AFAICT this can only happen
2313 * during CPU hotplug, at which point we'll get pushed out
2314 * anyway, so it's probably not a big deal.
2315 */
2316
c20cf065 2317 } else if (pending) {
6d337eab
PZ
2318 /*
2319 * This happens when we get migrated between migrate_enable()'s
2320 * preempt_enable() and scheduling the stopper task. At that
2321 * point we're a regular task again and not current anymore.
2322 *
2323 * A !PREEMPT kernel has a giant hole here, which makes it far
2324 * more likely.
2325 */
2326
d707faa6
VS
2327 /*
2328 * The task moved before the stopper got to run. We're holding
2329 * ->pi_lock, so the allowed mask is stable - if it got
2330 * somewhere allowed, we're done.
2331 */
c20cf065 2332 if (cpumask_test_cpu(task_cpu(p), p->cpus_ptr)) {
e140749c 2333 p->migration_pending = NULL;
d707faa6
VS
2334 complete = true;
2335 goto out;
2336 }
2337
6d337eab
PZ
2338 /*
2339 * When migrate_enable() hits a rq mis-match we can't reliably
2340 * determine is_migration_disabled() and so have to chase after
2341 * it.
2342 */
9e81889c 2343 WARN_ON_ONCE(!pending->stop_pending);
6d337eab
PZ
2344 task_rq_unlock(rq, p, &rf);
2345 stop_one_cpu_nowait(task_cpu(p), migration_cpu_stop,
2346 &pending->arg, &pending->stop_work);
2347 return 0;
bf89a304 2348 }
6d337eab 2349out:
9e81889c
PZ
2350 if (pending)
2351 pending->stop_pending = false;
6d337eab
PZ
2352 task_rq_unlock(rq, p, &rf);
2353
2354 if (complete)
2355 complete_all(&pending->done);
2356
5cc389bc
PZ
2357 return 0;
2358}
2359
a7c81556
PZ
2360int push_cpu_stop(void *arg)
2361{
2362 struct rq *lowest_rq = NULL, *rq = this_rq();
2363 struct task_struct *p = arg;
2364
2365 raw_spin_lock_irq(&p->pi_lock);
5cb9eaa3 2366 raw_spin_rq_lock(rq);
a7c81556
PZ
2367
2368 if (task_rq(p) != rq)
2369 goto out_unlock;
2370
2371 if (is_migration_disabled(p)) {
2372 p->migration_flags |= MDF_PUSH;
2373 goto out_unlock;
2374 }
2375
2376 p->migration_flags &= ~MDF_PUSH;
2377
2378 if (p->sched_class->find_lock_rq)
2379 lowest_rq = p->sched_class->find_lock_rq(p, rq);
5e16bbc2 2380
a7c81556
PZ
2381 if (!lowest_rq)
2382 goto out_unlock;
2383
2384 // XXX validate p is still the highest prio task
2385 if (task_rq(p) == rq) {
2386 deactivate_task(rq, p, 0);
2387 set_task_cpu(p, lowest_rq->cpu);
2388 activate_task(lowest_rq, p, 0);
2389 resched_curr(lowest_rq);
2390 }
2391
2392 double_unlock_balance(rq, lowest_rq);
2393
2394out_unlock:
2395 rq->push_busy = false;
5cb9eaa3 2396 raw_spin_rq_unlock(rq);
a7c81556
PZ
2397 raw_spin_unlock_irq(&p->pi_lock);
2398
2399 put_task_struct(p);
5cc389bc
PZ
2400 return 0;
2401}
2402
c5b28038
PZ
2403/*
2404 * sched_class::set_cpus_allowed must do the below, but is not required to
2405 * actually call this function.
2406 */
9cfc3e18 2407void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask, u32 flags)
5cc389bc 2408{
af449901
PZ
2409 if (flags & (SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) {
2410 p->cpus_ptr = new_mask;
2411 return;
2412 }
2413
3bd37062 2414 cpumask_copy(&p->cpus_mask, new_mask);
5cc389bc
PZ
2415 p->nr_cpus_allowed = cpumask_weight(new_mask);
2416}
2417
9cfc3e18
PZ
2418static void
2419__do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask, u32 flags)
c5b28038 2420{
6c37067e
PZ
2421 struct rq *rq = task_rq(p);
2422 bool queued, running;
2423
af449901
PZ
2424 /*
2425 * This here violates the locking rules for affinity, since we're only
2426 * supposed to change these variables while holding both rq->lock and
2427 * p->pi_lock.
2428 *
2429 * HOWEVER, it magically works, because ttwu() is the only code that
2430 * accesses these variables under p->pi_lock and only does so after
2431 * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
2432 * before finish_task().
2433 *
2434 * XXX do further audits, this smells like something putrid.
2435 */
2436 if (flags & SCA_MIGRATE_DISABLE)
2437 SCHED_WARN_ON(!p->on_cpu);
2438 else
2439 lockdep_assert_held(&p->pi_lock);
6c37067e
PZ
2440
2441 queued = task_on_rq_queued(p);
2442 running = task_current(rq, p);
2443
2444 if (queued) {
2445 /*
2446 * Because __kthread_bind() calls this on blocked tasks without
2447 * holding rq->lock.
2448 */
5cb9eaa3 2449 lockdep_assert_rq_held(rq);
7a57f32a 2450 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
6c37067e
PZ
2451 }
2452 if (running)
2453 put_prev_task(rq, p);
2454
9cfc3e18 2455 p->sched_class->set_cpus_allowed(p, new_mask, flags);
6c37067e 2456
6c37067e 2457 if (queued)
7134b3e9 2458 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 2459 if (running)
03b7fad1 2460 set_next_task(rq, p);
c5b28038
PZ
2461}
2462
9cfc3e18
PZ
2463void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
2464{
2465 __do_set_cpus_allowed(p, new_mask, 0);
2466}
2467
6d337eab 2468/*
c777d847
VS
2469 * This function is wildly self concurrent; here be dragons.
2470 *
2471 *
2472 * When given a valid mask, __set_cpus_allowed_ptr() must block until the
2473 * designated task is enqueued on an allowed CPU. If that task is currently
2474 * running, we have to kick it out using the CPU stopper.
2475 *
2476 * Migrate-Disable comes along and tramples all over our nice sandcastle.
2477 * Consider:
2478 *
2479 * Initial conditions: P0->cpus_mask = [0, 1]
2480 *
2481 * P0@CPU0 P1
2482 *
2483 * migrate_disable();
2484 * <preempted>
2485 * set_cpus_allowed_ptr(P0, [1]);
2486 *
2487 * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
2488 * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
2489 * This means we need the following scheme:
2490 *
2491 * P0@CPU0 P1
2492 *
2493 * migrate_disable();
2494 * <preempted>
2495 * set_cpus_allowed_ptr(P0, [1]);
2496 * <blocks>
2497 * <resumes>
2498 * migrate_enable();
2499 * __set_cpus_allowed_ptr();
2500 * <wakes local stopper>
2501 * `--> <woken on migration completion>
2502 *
2503 * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
2504 * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
2505 * task p are serialized by p->pi_lock, which we can leverage: the one that
2506 * should come into effect at the end of the Migrate-Disable region is the last
2507 * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
2508 * but we still need to properly signal those waiting tasks at the appropriate
2509 * moment.
2510 *
2511 * This is implemented using struct set_affinity_pending. The first
2512 * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
2513 * setup an instance of that struct and install it on the targeted task_struct.
2514 * Any and all further callers will reuse that instance. Those then wait for
2515 * a completion signaled at the tail of the CPU stopper callback (1), triggered
2516 * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
2517 *
2518 *
2519 * (1) In the cases covered above. There is one more where the completion is
2520 * signaled within affine_move_task() itself: when a subsequent affinity request
e140749c
VS
2521 * occurs after the stopper bailed out due to the targeted task still being
2522 * Migrate-Disable. Consider:
c777d847
VS
2523 *
2524 * Initial conditions: P0->cpus_mask = [0, 1]
2525 *
e140749c
VS
2526 * CPU0 P1 P2
2527 * <P0>
2528 * migrate_disable();
2529 * <preempted>
c777d847
VS
2530 * set_cpus_allowed_ptr(P0, [1]);
2531 * <blocks>
e140749c
VS
2532 * <migration/0>
2533 * migration_cpu_stop()
2534 * is_migration_disabled()
2535 * <bails>
c777d847
VS
2536 * set_cpus_allowed_ptr(P0, [0, 1]);
2537 * <signal completion>
2538 * <awakes>
2539 *
2540 * Note that the above is safe vs a concurrent migrate_enable(), as any
2541 * pending affinity completion is preceded by an uninstallation of
2542 * p->migration_pending done with p->pi_lock held.
6d337eab
PZ
2543 */
2544static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf,
2545 int dest_cpu, unsigned int flags)
2546{
2547 struct set_affinity_pending my_pending = { }, *pending = NULL;
9e81889c 2548 bool stop_pending, complete = false;
6d337eab
PZ
2549
2550 /* Can the task run on the task's current CPU? If so, we're done */
2551 if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) {
a7c81556
PZ
2552 struct task_struct *push_task = NULL;
2553
2554 if ((flags & SCA_MIGRATE_ENABLE) &&
2555 (p->migration_flags & MDF_PUSH) && !rq->push_busy) {
2556 rq->push_busy = true;
2557 push_task = get_task_struct(p);
2558 }
2559
50caf9c1
PZ
2560 /*
2561 * If there are pending waiters, but no pending stop_work,
2562 * then complete now.
2563 */
6d337eab 2564 pending = p->migration_pending;
50caf9c1 2565 if (pending && !pending->stop_pending) {
6d337eab
PZ
2566 p->migration_pending = NULL;
2567 complete = true;
2568 }
50caf9c1 2569
6d337eab
PZ
2570 task_rq_unlock(rq, p, rf);
2571
a7c81556
PZ
2572 if (push_task) {
2573 stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
2574 p, &rq->push_work);
2575 }
2576
6d337eab 2577 if (complete)
50caf9c1 2578 complete_all(&pending->done);
6d337eab
PZ
2579
2580 return 0;
2581 }
2582
2583 if (!(flags & SCA_MIGRATE_ENABLE)) {
2584 /* serialized by p->pi_lock */
2585 if (!p->migration_pending) {
c777d847 2586 /* Install the request */
6d337eab
PZ
2587 refcount_set(&my_pending.refs, 1);
2588 init_completion(&my_pending.done);
8a6edb52
PZ
2589 my_pending.arg = (struct migration_arg) {
2590 .task = p,
2591 .dest_cpu = -1, /* any */
2592 .pending = &my_pending,
2593 };
2594
6d337eab
PZ
2595 p->migration_pending = &my_pending;
2596 } else {
2597 pending = p->migration_pending;
2598 refcount_inc(&pending->refs);
2599 }
2600 }
2601 pending = p->migration_pending;
2602 /*
2603 * - !MIGRATE_ENABLE:
2604 * we'll have installed a pending if there wasn't one already.
2605 *
2606 * - MIGRATE_ENABLE:
2607 * we're here because the current CPU isn't matching anymore,
2608 * the only way that can happen is because of a concurrent
2609 * set_cpus_allowed_ptr() call, which should then still be
2610 * pending completion.
2611 *
2612 * Either way, we really should have a @pending here.
2613 */
2614 if (WARN_ON_ONCE(!pending)) {
2615 task_rq_unlock(rq, p, rf);
2616 return -EINVAL;
2617 }
2618
6d337eab 2619 if (task_running(rq, p) || p->state == TASK_WAKING) {
c777d847 2620 /*
58b1a450
PZ
2621 * MIGRATE_ENABLE gets here because 'p == current', but for
2622 * anything else we cannot do is_migration_disabled(), punt
2623 * and have the stopper function handle it all race-free.
c777d847 2624 */
9e81889c
PZ
2625 stop_pending = pending->stop_pending;
2626 if (!stop_pending)
2627 pending->stop_pending = true;
58b1a450 2628
58b1a450
PZ
2629 if (flags & SCA_MIGRATE_ENABLE)
2630 p->migration_flags &= ~MDF_PUSH;
50caf9c1 2631
6d337eab 2632 task_rq_unlock(rq, p, rf);
8a6edb52 2633
9e81889c
PZ
2634 if (!stop_pending) {
2635 stop_one_cpu_nowait(cpu_of(rq), migration_cpu_stop,
2636 &pending->arg, &pending->stop_work);
2637 }
6d337eab 2638
58b1a450
PZ
2639 if (flags & SCA_MIGRATE_ENABLE)
2640 return 0;
6d337eab
PZ
2641 } else {
2642
2643 if (!is_migration_disabled(p)) {
2644 if (task_on_rq_queued(p))
2645 rq = move_queued_task(rq, rf, p, dest_cpu);
2646
50caf9c1
PZ
2647 if (!pending->stop_pending) {
2648 p->migration_pending = NULL;
2649 complete = true;
2650 }
6d337eab
PZ
2651 }
2652 task_rq_unlock(rq, p, rf);
2653
6d337eab
PZ
2654 if (complete)
2655 complete_all(&pending->done);
2656 }
2657
2658 wait_for_completion(&pending->done);
2659
2660 if (refcount_dec_and_test(&pending->refs))
50caf9c1 2661 wake_up_var(&pending->refs); /* No UaF, just an address */
6d337eab 2662
c777d847
VS
2663 /*
2664 * Block the original owner of &pending until all subsequent callers
2665 * have seen the completion and decremented the refcount
2666 */
6d337eab
PZ
2667 wait_var_event(&my_pending.refs, !refcount_read(&my_pending.refs));
2668
50caf9c1
PZ
2669 /* ARGH */
2670 WARN_ON_ONCE(my_pending.stop_pending);
2671
6d337eab
PZ
2672 return 0;
2673}
2674
5cc389bc
PZ
2675/*
2676 * Change a given task's CPU affinity. Migrate the thread to a
2677 * proper CPU and schedule it away if the CPU it's executing on
2678 * is removed from the allowed bitmask.
2679 *
2680 * NOTE: the caller must have a valid reference to the task, the
2681 * task must not exit() & deallocate itself prematurely. The
2682 * call is not atomic; no spinlocks may be held.
2683 */
25834c73 2684static int __set_cpus_allowed_ptr(struct task_struct *p,
9cfc3e18
PZ
2685 const struct cpumask *new_mask,
2686 u32 flags)
5cc389bc 2687{
e9d867a6 2688 const struct cpumask *cpu_valid_mask = cpu_active_mask;
5cc389bc 2689 unsigned int dest_cpu;
eb580751
PZ
2690 struct rq_flags rf;
2691 struct rq *rq;
5cc389bc
PZ
2692 int ret = 0;
2693
eb580751 2694 rq = task_rq_lock(p, &rf);
a499c3ea 2695 update_rq_clock(rq);
5cc389bc 2696
af449901 2697 if (p->flags & PF_KTHREAD || is_migration_disabled(p)) {
e9d867a6 2698 /*
741ba80f
PZ
2699 * Kernel threads are allowed on online && !active CPUs,
2700 * however, during cpu-hot-unplug, even these might get pushed
2701 * away if not KTHREAD_IS_PER_CPU.
af449901
PZ
2702 *
2703 * Specifically, migration_disabled() tasks must not fail the
2704 * cpumask_any_and_distribute() pick below, esp. so on
2705 * SCA_MIGRATE_ENABLE, otherwise we'll not call
2706 * set_cpus_allowed_common() and actually reset p->cpus_ptr.
e9d867a6
PZI
2707 */
2708 cpu_valid_mask = cpu_online_mask;
2709 }
2710
25834c73
PZ
2711 /*
2712 * Must re-check here, to close a race against __kthread_bind(),
2713 * sched_setaffinity() is not guaranteed to observe the flag.
2714 */
9cfc3e18 2715 if ((flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) {
25834c73
PZ
2716 ret = -EINVAL;
2717 goto out;
2718 }
2719
885b3ba4
VS
2720 if (!(flags & SCA_MIGRATE_ENABLE)) {
2721 if (cpumask_equal(&p->cpus_mask, new_mask))
2722 goto out;
2723
2724 if (WARN_ON_ONCE(p == current &&
2725 is_migration_disabled(p) &&
2726 !cpumask_test_cpu(task_cpu(p), new_mask))) {
2727 ret = -EBUSY;
2728 goto out;
2729 }
2730 }
5cc389bc 2731
46a87b38
PT
2732 /*
2733 * Picking a ~random cpu helps in cases where we are changing affinity
2734 * for groups of tasks (ie. cpuset), so that load balancing is not
2735 * immediately required to distribute the tasks within their new mask.
2736 */
2737 dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, new_mask);
714e501e 2738 if (dest_cpu >= nr_cpu_ids) {
5cc389bc
PZ
2739 ret = -EINVAL;
2740 goto out;
2741 }
2742
9cfc3e18 2743 __do_set_cpus_allowed(p, new_mask, flags);
5cc389bc 2744
6d337eab 2745 return affine_move_task(rq, p, &rf, dest_cpu, flags);
5cc389bc 2746
5cc389bc 2747out:
eb580751 2748 task_rq_unlock(rq, p, &rf);
5cc389bc
PZ
2749
2750 return ret;
2751}
25834c73
PZ
2752
2753int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
2754{
9cfc3e18 2755 return __set_cpus_allowed_ptr(p, new_mask, 0);
25834c73 2756}
5cc389bc
PZ
2757EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
2758
dd41f596 2759void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 2760{
e2912009
PZ
2761#ifdef CONFIG_SCHED_DEBUG
2762 /*
2763 * We should never call set_task_cpu() on a blocked task,
2764 * ttwu() will sort out the placement.
2765 */
077614ee 2766 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
e2336f6e 2767 !p->on_rq);
0122ec5b 2768
3ea94de1
JP
2769 /*
2770 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
2771 * because schedstat_wait_{start,end} rebase migrating task's wait_start
2772 * time relying on p->on_rq.
2773 */
2774 WARN_ON_ONCE(p->state == TASK_RUNNING &&
2775 p->sched_class == &fair_sched_class &&
2776 (p->on_rq && !task_on_rq_migrating(p)));
2777
0122ec5b 2778#ifdef CONFIG_LOCKDEP
6c6c54e1
PZ
2779 /*
2780 * The caller should hold either p->pi_lock or rq->lock, when changing
2781 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
2782 *
2783 * sched_move_task() holds both and thus holding either pins the cgroup,
8323f26c 2784 * see task_group().
6c6c54e1
PZ
2785 *
2786 * Furthermore, all task_rq users should acquire both locks, see
2787 * task_rq_lock().
2788 */
0122ec5b 2789 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
9ef7e7e3 2790 lockdep_is_held(__rq_lockp(task_rq(p)))));
0122ec5b 2791#endif
4ff9083b
PZ
2792 /*
2793 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
2794 */
2795 WARN_ON_ONCE(!cpu_online(new_cpu));
af449901
PZ
2796
2797 WARN_ON_ONCE(is_migration_disabled(p));
e2912009
PZ
2798#endif
2799
de1d7286 2800 trace_sched_migrate_task(p, new_cpu);
cbc34ed1 2801
0c69774e 2802 if (task_cpu(p) != new_cpu) {
0a74bef8 2803 if (p->sched_class->migrate_task_rq)
1327237a 2804 p->sched_class->migrate_task_rq(p, new_cpu);
0c69774e 2805 p->se.nr_migrations++;
d7822b1e 2806 rseq_migrate(p);
ff303e66 2807 perf_event_task_migrate(p);
0c69774e 2808 }
dd41f596
IM
2809
2810 __set_task_cpu(p, new_cpu);
c65cc870
IM
2811}
2812
0ad4e3df 2813#ifdef CONFIG_NUMA_BALANCING
ac66f547
PZ
2814static void __migrate_swap_task(struct task_struct *p, int cpu)
2815{
da0c1e65 2816 if (task_on_rq_queued(p)) {
ac66f547 2817 struct rq *src_rq, *dst_rq;
8a8c69c3 2818 struct rq_flags srf, drf;
ac66f547
PZ
2819
2820 src_rq = task_rq(p);
2821 dst_rq = cpu_rq(cpu);
2822
8a8c69c3
PZ
2823 rq_pin_lock(src_rq, &srf);
2824 rq_pin_lock(dst_rq, &drf);
2825
ac66f547
PZ
2826 deactivate_task(src_rq, p, 0);
2827 set_task_cpu(p, cpu);
2828 activate_task(dst_rq, p, 0);
2829 check_preempt_curr(dst_rq, p, 0);
8a8c69c3
PZ
2830
2831 rq_unpin_lock(dst_rq, &drf);
2832 rq_unpin_lock(src_rq, &srf);
2833
ac66f547
PZ
2834 } else {
2835 /*
2836 * Task isn't running anymore; make it appear like we migrated
2837 * it before it went to sleep. This means on wakeup we make the
d1ccc66d 2838 * previous CPU our target instead of where it really is.
ac66f547
PZ
2839 */
2840 p->wake_cpu = cpu;
2841 }
2842}
2843
2844struct migration_swap_arg {
2845 struct task_struct *src_task, *dst_task;
2846 int src_cpu, dst_cpu;
2847};
2848
2849static int migrate_swap_stop(void *data)
2850{
2851 struct migration_swap_arg *arg = data;
2852 struct rq *src_rq, *dst_rq;
2853 int ret = -EAGAIN;
2854
62694cd5
PZ
2855 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
2856 return -EAGAIN;
2857
ac66f547
PZ
2858 src_rq = cpu_rq(arg->src_cpu);
2859 dst_rq = cpu_rq(arg->dst_cpu);
2860
74602315
PZ
2861 double_raw_lock(&arg->src_task->pi_lock,
2862 &arg->dst_task->pi_lock);
ac66f547 2863 double_rq_lock(src_rq, dst_rq);
62694cd5 2864
ac66f547
PZ
2865 if (task_cpu(arg->dst_task) != arg->dst_cpu)
2866 goto unlock;
2867
2868 if (task_cpu(arg->src_task) != arg->src_cpu)
2869 goto unlock;
2870
3bd37062 2871 if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
ac66f547
PZ
2872 goto unlock;
2873
3bd37062 2874 if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
ac66f547
PZ
2875 goto unlock;
2876
2877 __migrate_swap_task(arg->src_task, arg->dst_cpu);
2878 __migrate_swap_task(arg->dst_task, arg->src_cpu);
2879
2880 ret = 0;
2881
2882unlock:
2883 double_rq_unlock(src_rq, dst_rq);
74602315
PZ
2884 raw_spin_unlock(&arg->dst_task->pi_lock);
2885 raw_spin_unlock(&arg->src_task->pi_lock);
ac66f547
PZ
2886
2887 return ret;
2888}
2889
2890/*
2891 * Cross migrate two tasks
2892 */
0ad4e3df
SD
2893int migrate_swap(struct task_struct *cur, struct task_struct *p,
2894 int target_cpu, int curr_cpu)
ac66f547
PZ
2895{
2896 struct migration_swap_arg arg;
2897 int ret = -EINVAL;
2898
ac66f547
PZ
2899 arg = (struct migration_swap_arg){
2900 .src_task = cur,
0ad4e3df 2901 .src_cpu = curr_cpu,
ac66f547 2902 .dst_task = p,
0ad4e3df 2903 .dst_cpu = target_cpu,
ac66f547
PZ
2904 };
2905
2906 if (arg.src_cpu == arg.dst_cpu)
2907 goto out;
2908
6acce3ef
PZ
2909 /*
2910 * These three tests are all lockless; this is OK since all of them
2911 * will be re-checked with proper locks held further down the line.
2912 */
ac66f547
PZ
2913 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
2914 goto out;
2915
3bd37062 2916 if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
ac66f547
PZ
2917 goto out;
2918
3bd37062 2919 if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
ac66f547
PZ
2920 goto out;
2921
286549dc 2922 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
ac66f547
PZ
2923 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
2924
2925out:
ac66f547
PZ
2926 return ret;
2927}
0ad4e3df 2928#endif /* CONFIG_NUMA_BALANCING */
ac66f547 2929
1da177e4
LT
2930/*
2931 * wait_task_inactive - wait for a thread to unschedule.
2932 *
85ba2d86
RM
2933 * If @match_state is nonzero, it's the @p->state value just checked and
2934 * not expected to change. If it changes, i.e. @p might have woken up,
2935 * then return zero. When we succeed in waiting for @p to be off its CPU,
2936 * we return a positive number (its total switch count). If a second call
2937 * a short while later returns the same number, the caller can be sure that
2938 * @p has remained unscheduled the whole time.
2939 *
1da177e4
LT
2940 * The caller must ensure that the task *will* unschedule sometime soon,
2941 * else this function might spin for a *long* time. This function can't
2942 * be called with interrupts off, or it may introduce deadlock with
2943 * smp_call_function() if an IPI is sent by the same process we are
2944 * waiting to become inactive.
2945 */
85ba2d86 2946unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1da177e4 2947{
da0c1e65 2948 int running, queued;
eb580751 2949 struct rq_flags rf;
85ba2d86 2950 unsigned long ncsw;
70b97a7f 2951 struct rq *rq;
1da177e4 2952
3a5c359a
AK
2953 for (;;) {
2954 /*
2955 * We do the initial early heuristics without holding
2956 * any task-queue locks at all. We'll only try to get
2957 * the runqueue lock when things look like they will
2958 * work out!
2959 */
2960 rq = task_rq(p);
fa490cfd 2961
3a5c359a
AK
2962 /*
2963 * If the task is actively running on another CPU
2964 * still, just relax and busy-wait without holding
2965 * any locks.
2966 *
2967 * NOTE! Since we don't hold any locks, it's not
2968 * even sure that "rq" stays as the right runqueue!
2969 * But we don't care, since "task_running()" will
2970 * return false if the runqueue has changed and p
2971 * is actually now running somewhere else!
2972 */
85ba2d86
RM
2973 while (task_running(rq, p)) {
2974 if (match_state && unlikely(p->state != match_state))
2975 return 0;
3a5c359a 2976 cpu_relax();
85ba2d86 2977 }
fa490cfd 2978
3a5c359a
AK
2979 /*
2980 * Ok, time to look more closely! We need the rq
2981 * lock now, to be *sure*. If we're wrong, we'll
2982 * just go back and repeat.
2983 */
eb580751 2984 rq = task_rq_lock(p, &rf);
27a9da65 2985 trace_sched_wait_task(p);
3a5c359a 2986 running = task_running(rq, p);
da0c1e65 2987 queued = task_on_rq_queued(p);
85ba2d86 2988 ncsw = 0;
f31e11d8 2989 if (!match_state || p->state == match_state)
93dcf55f 2990 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
eb580751 2991 task_rq_unlock(rq, p, &rf);
fa490cfd 2992
85ba2d86
RM
2993 /*
2994 * If it changed from the expected state, bail out now.
2995 */
2996 if (unlikely(!ncsw))
2997 break;
2998
3a5c359a
AK
2999 /*
3000 * Was it really running after all now that we
3001 * checked with the proper locks actually held?
3002 *
3003 * Oops. Go back and try again..
3004 */
3005 if (unlikely(running)) {
3006 cpu_relax();
3007 continue;
3008 }
fa490cfd 3009
3a5c359a
AK
3010 /*
3011 * It's not enough that it's not actively running,
3012 * it must be off the runqueue _entirely_, and not
3013 * preempted!
3014 *
80dd99b3 3015 * So if it was still runnable (but just not actively
3a5c359a
AK
3016 * running right now), it's preempted, and we should
3017 * yield - it could be a while.
3018 */
da0c1e65 3019 if (unlikely(queued)) {
8b0e1953 3020 ktime_t to = NSEC_PER_SEC / HZ;
8eb90c30
TG
3021
3022 set_current_state(TASK_UNINTERRUPTIBLE);
3023 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
3a5c359a
AK
3024 continue;
3025 }
fa490cfd 3026
3a5c359a
AK
3027 /*
3028 * Ahh, all good. It wasn't running, and it wasn't
3029 * runnable, which means that it will never become
3030 * running in the future either. We're all done!
3031 */
3032 break;
3033 }
85ba2d86
RM
3034
3035 return ncsw;
1da177e4
LT
3036}
3037
3038/***
3039 * kick_process - kick a running thread to enter/exit the kernel
3040 * @p: the to-be-kicked thread
3041 *
3042 * Cause a process which is running on another CPU to enter
3043 * kernel-mode, without any delay. (to get signals handled.)
3044 *
25985edc 3045 * NOTE: this function doesn't have to take the runqueue lock,
1da177e4
LT
3046 * because all it wants to ensure is that the remote task enters
3047 * the kernel. If the IPI races and the task has been migrated
3048 * to another CPU then no harm is done and the purpose has been
3049 * achieved as well.
3050 */
36c8b586 3051void kick_process(struct task_struct *p)
1da177e4
LT
3052{
3053 int cpu;
3054
3055 preempt_disable();
3056 cpu = task_cpu(p);
3057 if ((cpu != smp_processor_id()) && task_curr(p))
3058 smp_send_reschedule(cpu);
3059 preempt_enable();
3060}
b43e3521 3061EXPORT_SYMBOL_GPL(kick_process);
1da177e4 3062
30da688e 3063/*
3bd37062 3064 * ->cpus_ptr is protected by both rq->lock and p->pi_lock
e9d867a6
PZI
3065 *
3066 * A few notes on cpu_active vs cpu_online:
3067 *
3068 * - cpu_active must be a subset of cpu_online
3069 *
97fb7a0a 3070 * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
e9d867a6 3071 * see __set_cpus_allowed_ptr(). At this point the newly online
d1ccc66d 3072 * CPU isn't yet part of the sched domains, and balancing will not
e9d867a6
PZI
3073 * see it.
3074 *
d1ccc66d 3075 * - on CPU-down we clear cpu_active() to mask the sched domains and
e9d867a6 3076 * avoid the load balancer to place new tasks on the to be removed
d1ccc66d 3077 * CPU. Existing tasks will remain running there and will be taken
e9d867a6
PZI
3078 * off.
3079 *
3080 * This means that fallback selection must not select !active CPUs.
3081 * And can assume that any active CPU must be online. Conversely
3082 * select_task_rq() below may allow selection of !active CPUs in order
3083 * to satisfy the above rules.
30da688e 3084 */
5da9a0fb
PZ
3085static int select_fallback_rq(int cpu, struct task_struct *p)
3086{
aa00d89c
TC
3087 int nid = cpu_to_node(cpu);
3088 const struct cpumask *nodemask = NULL;
2baab4e9
PZ
3089 enum { cpuset, possible, fail } state = cpuset;
3090 int dest_cpu;
5da9a0fb 3091
aa00d89c 3092 /*
d1ccc66d
IM
3093 * If the node that the CPU is on has been offlined, cpu_to_node()
3094 * will return -1. There is no CPU on the node, and we should
3095 * select the CPU on the other node.
aa00d89c
TC
3096 */
3097 if (nid != -1) {
3098 nodemask = cpumask_of_node(nid);
3099
3100 /* Look for allowed, online CPU in same node. */
3101 for_each_cpu(dest_cpu, nodemask) {
aa00d89c
TC
3102 if (!cpu_active(dest_cpu))
3103 continue;
3bd37062 3104 if (cpumask_test_cpu(dest_cpu, p->cpus_ptr))
aa00d89c
TC
3105 return dest_cpu;
3106 }
2baab4e9 3107 }
5da9a0fb 3108
2baab4e9
PZ
3109 for (;;) {
3110 /* Any allowed, online CPU? */
3bd37062 3111 for_each_cpu(dest_cpu, p->cpus_ptr) {
175f0e25 3112 if (!is_cpu_allowed(p, dest_cpu))
2baab4e9 3113 continue;
175f0e25 3114
2baab4e9
PZ
3115 goto out;
3116 }
5da9a0fb 3117
e73e85f0 3118 /* No more Mr. Nice Guy. */
2baab4e9
PZ
3119 switch (state) {
3120 case cpuset:
e73e85f0
ON
3121 if (IS_ENABLED(CONFIG_CPUSETS)) {
3122 cpuset_cpus_allowed_fallback(p);
3123 state = possible;
3124 break;
3125 }
df561f66 3126 fallthrough;
2baab4e9 3127 case possible:
af449901
PZ
3128 /*
3129 * XXX When called from select_task_rq() we only
3130 * hold p->pi_lock and again violate locking order.
3131 *
3132 * More yuck to audit.
3133 */
2baab4e9
PZ
3134 do_set_cpus_allowed(p, cpu_possible_mask);
3135 state = fail;
3136 break;
3137
3138 case fail:
3139 BUG();
3140 break;
3141 }
3142 }
3143
3144out:
3145 if (state != cpuset) {
3146 /*
3147 * Don't tell them about moving exiting tasks or
3148 * kernel threads (both mm NULL), since they never
3149 * leave kernel.
3150 */
3151 if (p->mm && printk_ratelimit()) {
aac74dc4 3152 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
2baab4e9
PZ
3153 task_pid_nr(p), p->comm, cpu);
3154 }
5da9a0fb
PZ
3155 }
3156
3157 return dest_cpu;
3158}
3159
e2912009 3160/*
3bd37062 3161 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
e2912009 3162 */
970b13ba 3163static inline
3aef1551 3164int select_task_rq(struct task_struct *p, int cpu, int wake_flags)
970b13ba 3165{
cbce1a68
PZ
3166 lockdep_assert_held(&p->pi_lock);
3167
af449901 3168 if (p->nr_cpus_allowed > 1 && !is_migration_disabled(p))
3aef1551 3169 cpu = p->sched_class->select_task_rq(p, cpu, wake_flags);
e9d867a6 3170 else
3bd37062 3171 cpu = cpumask_any(p->cpus_ptr);
e2912009
PZ
3172
3173 /*
3174 * In order not to call set_task_cpu() on a blocking task we need
3bd37062 3175 * to rely on ttwu() to place the task on a valid ->cpus_ptr
d1ccc66d 3176 * CPU.
e2912009
PZ
3177 *
3178 * Since this is common to all placement strategies, this lives here.
3179 *
3180 * [ this allows ->select_task() to simply return task_cpu(p) and
3181 * not worry about this generic constraint ]
3182 */
7af443ee 3183 if (unlikely(!is_cpu_allowed(p, cpu)))
5da9a0fb 3184 cpu = select_fallback_rq(task_cpu(p), p);
e2912009
PZ
3185
3186 return cpu;
970b13ba 3187}
09a40af5 3188
f5832c19
NP
3189void sched_set_stop_task(int cpu, struct task_struct *stop)
3190{
ded467dc 3191 static struct lock_class_key stop_pi_lock;
f5832c19
NP
3192 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
3193 struct task_struct *old_stop = cpu_rq(cpu)->stop;
3194
3195 if (stop) {
3196 /*
3197 * Make it appear like a SCHED_FIFO task, its something
3198 * userspace knows about and won't get confused about.
3199 *
3200 * Also, it will make PI more or less work without too
3201 * much confusion -- but then, stop work should not
3202 * rely on PI working anyway.
3203 */
3204 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
3205
3206 stop->sched_class = &stop_sched_class;
ded467dc
PZ
3207
3208 /*
3209 * The PI code calls rt_mutex_setprio() with ->pi_lock held to
3210 * adjust the effective priority of a task. As a result,
3211 * rt_mutex_setprio() can trigger (RT) balancing operations,
3212 * which can then trigger wakeups of the stop thread to push
3213 * around the current task.
3214 *
3215 * The stop task itself will never be part of the PI-chain, it
3216 * never blocks, therefore that ->pi_lock recursion is safe.
3217 * Tell lockdep about this by placing the stop->pi_lock in its
3218 * own class.
3219 */
3220 lockdep_set_class(&stop->pi_lock, &stop_pi_lock);
f5832c19
NP
3221 }
3222
3223 cpu_rq(cpu)->stop = stop;
3224
3225 if (old_stop) {
3226 /*
3227 * Reset it back to a normal scheduling class so that
3228 * it can die in pieces.
3229 */
3230 old_stop->sched_class = &rt_sched_class;
3231 }
3232}
3233
74d862b6 3234#else /* CONFIG_SMP */
25834c73
PZ
3235
3236static inline int __set_cpus_allowed_ptr(struct task_struct *p,
9cfc3e18
PZ
3237 const struct cpumask *new_mask,
3238 u32 flags)
25834c73
PZ
3239{
3240 return set_cpus_allowed_ptr(p, new_mask);
3241}
3242
af449901
PZ
3243static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { }
3244
3015ef4b
TG
3245static inline bool rq_has_pinned_tasks(struct rq *rq)
3246{
3247 return false;
3248}
3249
74d862b6 3250#endif /* !CONFIG_SMP */
970b13ba 3251
d7c01d27 3252static void
b84cb5df 3253ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
9ed3811a 3254{
4fa8d299 3255 struct rq *rq;
b84cb5df 3256
4fa8d299
JP
3257 if (!schedstat_enabled())
3258 return;
3259
3260 rq = this_rq();
d7c01d27 3261
4fa8d299
JP
3262#ifdef CONFIG_SMP
3263 if (cpu == rq->cpu) {
b85c8b71
PZ
3264 __schedstat_inc(rq->ttwu_local);
3265 __schedstat_inc(p->se.statistics.nr_wakeups_local);
d7c01d27
PZ
3266 } else {
3267 struct sched_domain *sd;
3268
b85c8b71 3269 __schedstat_inc(p->se.statistics.nr_wakeups_remote);
057f3fad 3270 rcu_read_lock();
4fa8d299 3271 for_each_domain(rq->cpu, sd) {
d7c01d27 3272 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
b85c8b71 3273 __schedstat_inc(sd->ttwu_wake_remote);
d7c01d27
PZ
3274 break;
3275 }
3276 }
057f3fad 3277 rcu_read_unlock();
d7c01d27 3278 }
f339b9dc
PZ
3279
3280 if (wake_flags & WF_MIGRATED)
b85c8b71 3281 __schedstat_inc(p->se.statistics.nr_wakeups_migrate);
d7c01d27
PZ
3282#endif /* CONFIG_SMP */
3283
b85c8b71
PZ
3284 __schedstat_inc(rq->ttwu_count);
3285 __schedstat_inc(p->se.statistics.nr_wakeups);
d7c01d27
PZ
3286
3287 if (wake_flags & WF_SYNC)
b85c8b71 3288 __schedstat_inc(p->se.statistics.nr_wakeups_sync);
d7c01d27
PZ
3289}
3290
23f41eeb
PZ
3291/*
3292 * Mark the task runnable and perform wakeup-preemption.
3293 */
e7904a28 3294static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 3295 struct rq_flags *rf)
9ed3811a 3296{
9ed3811a 3297 check_preempt_curr(rq, p, wake_flags);
9ed3811a 3298 p->state = TASK_RUNNING;
fbd705a0
PZ
3299 trace_sched_wakeup(p);
3300
9ed3811a 3301#ifdef CONFIG_SMP
4c9a4bc8
PZ
3302 if (p->sched_class->task_woken) {
3303 /*
b19a888c 3304 * Our task @p is fully woken up and running; so it's safe to
cbce1a68 3305 * drop the rq->lock, hereafter rq is only used for statistics.
4c9a4bc8 3306 */
d8ac8971 3307 rq_unpin_lock(rq, rf);
9ed3811a 3308 p->sched_class->task_woken(rq, p);
d8ac8971 3309 rq_repin_lock(rq, rf);
4c9a4bc8 3310 }
9ed3811a 3311
e69c6341 3312 if (rq->idle_stamp) {
78becc27 3313 u64 delta = rq_clock(rq) - rq->idle_stamp;
9bd721c5 3314 u64 max = 2*rq->max_idle_balance_cost;
9ed3811a 3315
abfafa54
JL
3316 update_avg(&rq->avg_idle, delta);
3317
3318 if (rq->avg_idle > max)
9ed3811a 3319 rq->avg_idle = max;
abfafa54 3320
9ed3811a
TH
3321 rq->idle_stamp = 0;
3322 }
3323#endif
3324}
3325
c05fbafb 3326static void
e7904a28 3327ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 3328 struct rq_flags *rf)
c05fbafb 3329{
77558e4d 3330 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
b5179ac7 3331
5cb9eaa3 3332 lockdep_assert_rq_held(rq);
cbce1a68 3333
c05fbafb
PZ
3334 if (p->sched_contributes_to_load)
3335 rq->nr_uninterruptible--;
b5179ac7 3336
dbfb089d 3337#ifdef CONFIG_SMP
b5179ac7 3338 if (wake_flags & WF_MIGRATED)
59efa0ba 3339 en_flags |= ENQUEUE_MIGRATED;
ec618b84 3340 else
c05fbafb 3341#endif
ec618b84
PZ
3342 if (p->in_iowait) {
3343 delayacct_blkio_end(p);
3344 atomic_dec(&task_rq(p)->nr_iowait);
3345 }
c05fbafb 3346
1b174a2c 3347 activate_task(rq, p, en_flags);
d8ac8971 3348 ttwu_do_wakeup(rq, p, wake_flags, rf);
c05fbafb
PZ
3349}
3350
3351/*
58877d34
PZ
3352 * Consider @p being inside a wait loop:
3353 *
3354 * for (;;) {
3355 * set_current_state(TASK_UNINTERRUPTIBLE);
3356 *
3357 * if (CONDITION)
3358 * break;
3359 *
3360 * schedule();
3361 * }
3362 * __set_current_state(TASK_RUNNING);
3363 *
3364 * between set_current_state() and schedule(). In this case @p is still
3365 * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
3366 * an atomic manner.
3367 *
3368 * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
3369 * then schedule() must still happen and p->state can be changed to
3370 * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
3371 * need to do a full wakeup with enqueue.
3372 *
3373 * Returns: %true when the wakeup is done,
3374 * %false otherwise.
c05fbafb 3375 */
58877d34 3376static int ttwu_runnable(struct task_struct *p, int wake_flags)
c05fbafb 3377{
eb580751 3378 struct rq_flags rf;
c05fbafb
PZ
3379 struct rq *rq;
3380 int ret = 0;
3381
eb580751 3382 rq = __task_rq_lock(p, &rf);
da0c1e65 3383 if (task_on_rq_queued(p)) {
1ad4ec0d
FW
3384 /* check_preempt_curr() may use rq clock */
3385 update_rq_clock(rq);
d8ac8971 3386 ttwu_do_wakeup(rq, p, wake_flags, &rf);
c05fbafb
PZ
3387 ret = 1;
3388 }
eb580751 3389 __task_rq_unlock(rq, &rf);
c05fbafb
PZ
3390
3391 return ret;
3392}
3393
317f3941 3394#ifdef CONFIG_SMP
a1488664 3395void sched_ttwu_pending(void *arg)
317f3941 3396{
a1488664 3397 struct llist_node *llist = arg;
317f3941 3398 struct rq *rq = this_rq();
73215849 3399 struct task_struct *p, *t;
d8ac8971 3400 struct rq_flags rf;
317f3941 3401
e3baac47
PZ
3402 if (!llist)
3403 return;
3404
126c2092
PZ
3405 /*
3406 * rq::ttwu_pending racy indication of out-standing wakeups.
3407 * Races such that false-negatives are possible, since they
3408 * are shorter lived that false-positives would be.
3409 */
3410 WRITE_ONCE(rq->ttwu_pending, 0);
3411
8a8c69c3 3412 rq_lock_irqsave(rq, &rf);
77558e4d 3413 update_rq_clock(rq);
317f3941 3414
8c4890d1 3415 llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
b6e13e85
PZ
3416 if (WARN_ON_ONCE(p->on_cpu))
3417 smp_cond_load_acquire(&p->on_cpu, !VAL);
3418
3419 if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
3420 set_task_cpu(p, cpu_of(rq));
3421
73215849 3422 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
b6e13e85 3423 }
317f3941 3424
8a8c69c3 3425 rq_unlock_irqrestore(rq, &rf);
317f3941
PZ
3426}
3427
b2a02fc4 3428void send_call_function_single_ipi(int cpu)
317f3941 3429{
b2a02fc4 3430 struct rq *rq = cpu_rq(cpu);
ca38062e 3431
b2a02fc4
PZ
3432 if (!set_nr_if_polling(rq->idle))
3433 arch_send_call_function_single_ipi(cpu);
3434 else
3435 trace_sched_wake_idle_without_ipi(cpu);
317f3941
PZ
3436}
3437
2ebb1771
MG
3438/*
3439 * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
3440 * necessary. The wakee CPU on receipt of the IPI will queue the task
3441 * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
3442 * of the wakeup instead of the waker.
3443 */
3444static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
317f3941 3445{
e3baac47
PZ
3446 struct rq *rq = cpu_rq(cpu);
3447
b7e7ade3
PZ
3448 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
3449
126c2092 3450 WRITE_ONCE(rq->ttwu_pending, 1);
8c4890d1 3451 __smp_call_single_queue(cpu, &p->wake_entry.llist);
317f3941 3452}
d6aa8f85 3453
f6be8af1
CL
3454void wake_up_if_idle(int cpu)
3455{
3456 struct rq *rq = cpu_rq(cpu);
8a8c69c3 3457 struct rq_flags rf;
f6be8af1 3458
fd7de1e8
AL
3459 rcu_read_lock();
3460
3461 if (!is_idle_task(rcu_dereference(rq->curr)))
3462 goto out;
f6be8af1
CL
3463
3464 if (set_nr_if_polling(rq->idle)) {
3465 trace_sched_wake_idle_without_ipi(cpu);
3466 } else {
8a8c69c3 3467 rq_lock_irqsave(rq, &rf);
f6be8af1
CL
3468 if (is_idle_task(rq->curr))
3469 smp_send_reschedule(cpu);
d1ccc66d 3470 /* Else CPU is not idle, do nothing here: */
8a8c69c3 3471 rq_unlock_irqrestore(rq, &rf);
f6be8af1 3472 }
fd7de1e8
AL
3473
3474out:
3475 rcu_read_unlock();
f6be8af1
CL
3476}
3477
39be3501 3478bool cpus_share_cache(int this_cpu, int that_cpu)
518cd623
PZ
3479{
3480 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
3481}
c6e7bd7a 3482
2ebb1771
MG
3483static inline bool ttwu_queue_cond(int cpu, int wake_flags)
3484{
5ba2ffba
PZ
3485 /*
3486 * Do not complicate things with the async wake_list while the CPU is
3487 * in hotplug state.
3488 */
3489 if (!cpu_active(cpu))
3490 return false;
3491
2ebb1771
MG
3492 /*
3493 * If the CPU does not share cache, then queue the task on the
3494 * remote rqs wakelist to avoid accessing remote data.
3495 */
3496 if (!cpus_share_cache(smp_processor_id(), cpu))
3497 return true;
3498
3499 /*
3500 * If the task is descheduling and the only running task on the
3501 * CPU then use the wakelist to offload the task activation to
3502 * the soon-to-be-idle CPU as the current CPU is likely busy.
3503 * nr_running is checked to avoid unnecessary task stacking.
3504 */
739f70b4 3505 if ((wake_flags & WF_ON_CPU) && cpu_rq(cpu)->nr_running <= 1)
2ebb1771
MG
3506 return true;
3507
3508 return false;
3509}
3510
3511static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
c6e7bd7a 3512{
2ebb1771 3513 if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(cpu, wake_flags)) {
b6e13e85
PZ
3514 if (WARN_ON_ONCE(cpu == smp_processor_id()))
3515 return false;
3516
c6e7bd7a 3517 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
2ebb1771 3518 __ttwu_queue_wakelist(p, cpu, wake_flags);
c6e7bd7a
PZ
3519 return true;
3520 }
3521
3522 return false;
3523}
58877d34
PZ
3524
3525#else /* !CONFIG_SMP */
3526
3527static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
3528{
3529 return false;
3530}
3531
d6aa8f85 3532#endif /* CONFIG_SMP */
317f3941 3533
b5179ac7 3534static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
c05fbafb
PZ
3535{
3536 struct rq *rq = cpu_rq(cpu);
d8ac8971 3537 struct rq_flags rf;
c05fbafb 3538
2ebb1771 3539 if (ttwu_queue_wakelist(p, cpu, wake_flags))
317f3941 3540 return;
317f3941 3541
8a8c69c3 3542 rq_lock(rq, &rf);
77558e4d 3543 update_rq_clock(rq);
d8ac8971 3544 ttwu_do_activate(rq, p, wake_flags, &rf);
8a8c69c3 3545 rq_unlock(rq, &rf);
9ed3811a
TH
3546}
3547
8643cda5
PZ
3548/*
3549 * Notes on Program-Order guarantees on SMP systems.
3550 *
3551 * MIGRATION
3552 *
3553 * The basic program-order guarantee on SMP systems is that when a task [t]
d1ccc66d
IM
3554 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
3555 * execution on its new CPU [c1].
8643cda5
PZ
3556 *
3557 * For migration (of runnable tasks) this is provided by the following means:
3558 *
3559 * A) UNLOCK of the rq(c0)->lock scheduling out task t
3560 * B) migration for t is required to synchronize *both* rq(c0)->lock and
3561 * rq(c1)->lock (if not at the same time, then in that order).
3562 * C) LOCK of the rq(c1)->lock scheduling in task
3563 *
7696f991 3564 * Release/acquire chaining guarantees that B happens after A and C after B.
d1ccc66d 3565 * Note: the CPU doing B need not be c0 or c1
8643cda5
PZ
3566 *
3567 * Example:
3568 *
3569 * CPU0 CPU1 CPU2
3570 *
3571 * LOCK rq(0)->lock
3572 * sched-out X
3573 * sched-in Y
3574 * UNLOCK rq(0)->lock
3575 *
3576 * LOCK rq(0)->lock // orders against CPU0
3577 * dequeue X
3578 * UNLOCK rq(0)->lock
3579 *
3580 * LOCK rq(1)->lock
3581 * enqueue X
3582 * UNLOCK rq(1)->lock
3583 *
3584 * LOCK rq(1)->lock // orders against CPU2
3585 * sched-out Z
3586 * sched-in X
3587 * UNLOCK rq(1)->lock
3588 *
3589 *
3590 * BLOCKING -- aka. SLEEP + WAKEUP
3591 *
3592 * For blocking we (obviously) need to provide the same guarantee as for
3593 * migration. However the means are completely different as there is no lock
3594 * chain to provide order. Instead we do:
3595 *
58877d34
PZ
3596 * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
3597 * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
8643cda5
PZ
3598 *
3599 * Example:
3600 *
3601 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
3602 *
3603 * LOCK rq(0)->lock LOCK X->pi_lock
3604 * dequeue X
3605 * sched-out X
3606 * smp_store_release(X->on_cpu, 0);
3607 *
1f03e8d2 3608 * smp_cond_load_acquire(&X->on_cpu, !VAL);
8643cda5
PZ
3609 * X->state = WAKING
3610 * set_task_cpu(X,2)
3611 *
3612 * LOCK rq(2)->lock
3613 * enqueue X
3614 * X->state = RUNNING
3615 * UNLOCK rq(2)->lock
3616 *
3617 * LOCK rq(2)->lock // orders against CPU1
3618 * sched-out Z
3619 * sched-in X
3620 * UNLOCK rq(2)->lock
3621 *
3622 * UNLOCK X->pi_lock
3623 * UNLOCK rq(0)->lock
3624 *
3625 *
7696f991
AP
3626 * However, for wakeups there is a second guarantee we must provide, namely we
3627 * must ensure that CONDITION=1 done by the caller can not be reordered with
3628 * accesses to the task state; see try_to_wake_up() and set_current_state().
8643cda5
PZ
3629 */
3630
9ed3811a 3631/**
1da177e4 3632 * try_to_wake_up - wake up a thread
9ed3811a 3633 * @p: the thread to be awakened
1da177e4 3634 * @state: the mask of task states that can be woken
9ed3811a 3635 * @wake_flags: wake modifier flags (WF_*)
1da177e4 3636 *
58877d34
PZ
3637 * Conceptually does:
3638 *
3639 * If (@state & @p->state) @p->state = TASK_RUNNING.
1da177e4 3640 *
a2250238
PZ
3641 * If the task was not queued/runnable, also place it back on a runqueue.
3642 *
58877d34
PZ
3643 * This function is atomic against schedule() which would dequeue the task.
3644 *
3645 * It issues a full memory barrier before accessing @p->state, see the comment
3646 * with set_current_state().
a2250238 3647 *
58877d34 3648 * Uses p->pi_lock to serialize against concurrent wake-ups.
a2250238 3649 *
58877d34
PZ
3650 * Relies on p->pi_lock stabilizing:
3651 * - p->sched_class
3652 * - p->cpus_ptr
3653 * - p->sched_task_group
3654 * in order to do migration, see its use of select_task_rq()/set_task_cpu().
3655 *
3656 * Tries really hard to only take one task_rq(p)->lock for performance.
3657 * Takes rq->lock in:
3658 * - ttwu_runnable() -- old rq, unavoidable, see comment there;
3659 * - ttwu_queue() -- new rq, for enqueue of the task;
3660 * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
3661 *
3662 * As a consequence we race really badly with just about everything. See the
3663 * many memory barriers and their comments for details.
7696f991 3664 *
a2250238
PZ
3665 * Return: %true if @p->state changes (an actual wakeup was done),
3666 * %false otherwise.
1da177e4 3667 */
e4a52bcb
PZ
3668static int
3669try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1da177e4 3670{
1da177e4 3671 unsigned long flags;
c05fbafb 3672 int cpu, success = 0;
2398f2c6 3673
e3d85487 3674 preempt_disable();
aacedf26
PZ
3675 if (p == current) {
3676 /*
3677 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
3678 * == smp_processor_id()'. Together this means we can special
58877d34 3679 * case the whole 'p->on_rq && ttwu_runnable()' case below
aacedf26
PZ
3680 * without taking any locks.
3681 *
3682 * In particular:
3683 * - we rely on Program-Order guarantees for all the ordering,
3684 * - we're serialized against set_special_state() by virtue of
3685 * it disabling IRQs (this allows not taking ->pi_lock).
3686 */
3687 if (!(p->state & state))
e3d85487 3688 goto out;
aacedf26
PZ
3689
3690 success = 1;
aacedf26
PZ
3691 trace_sched_waking(p);
3692 p->state = TASK_RUNNING;
3693 trace_sched_wakeup(p);
3694 goto out;
3695 }
3696
e0acd0a6
ON
3697 /*
3698 * If we are going to wake up a thread waiting for CONDITION we
3699 * need to ensure that CONDITION=1 done by the caller can not be
58877d34
PZ
3700 * reordered with p->state check below. This pairs with smp_store_mb()
3701 * in set_current_state() that the waiting thread does.
e0acd0a6 3702 */
013fdb80 3703 raw_spin_lock_irqsave(&p->pi_lock, flags);
d89e588c 3704 smp_mb__after_spinlock();
e9c84311 3705 if (!(p->state & state))
aacedf26 3706 goto unlock;
1da177e4 3707
fbd705a0
PZ
3708 trace_sched_waking(p);
3709
d1ccc66d
IM
3710 /* We're going to change ->state: */
3711 success = 1;
1da177e4 3712
135e8c92
BS
3713 /*
3714 * Ensure we load p->on_rq _after_ p->state, otherwise it would
3715 * be possible to, falsely, observe p->on_rq == 0 and get stuck
3716 * in smp_cond_load_acquire() below.
3717 *
3d85b270
AP
3718 * sched_ttwu_pending() try_to_wake_up()
3719 * STORE p->on_rq = 1 LOAD p->state
3720 * UNLOCK rq->lock
3721 *
3722 * __schedule() (switch to task 'p')
3723 * LOCK rq->lock smp_rmb();
3724 * smp_mb__after_spinlock();
3725 * UNLOCK rq->lock
135e8c92
BS
3726 *
3727 * [task p]
3d85b270 3728 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
135e8c92 3729 *
3d85b270
AP
3730 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
3731 * __schedule(). See the comment for smp_mb__after_spinlock().
2beaf328
PM
3732 *
3733 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
135e8c92
BS
3734 */
3735 smp_rmb();
58877d34 3736 if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
aacedf26 3737 goto unlock;
1da177e4 3738
1da177e4 3739#ifdef CONFIG_SMP
ecf7d01c
PZ
3740 /*
3741 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
3742 * possible to, falsely, observe p->on_cpu == 0.
3743 *
3744 * One must be running (->on_cpu == 1) in order to remove oneself
3745 * from the runqueue.
3746 *
3d85b270
AP
3747 * __schedule() (switch to task 'p') try_to_wake_up()
3748 * STORE p->on_cpu = 1 LOAD p->on_rq
3749 * UNLOCK rq->lock
3750 *
3751 * __schedule() (put 'p' to sleep)
3752 * LOCK rq->lock smp_rmb();
3753 * smp_mb__after_spinlock();
3754 * STORE p->on_rq = 0 LOAD p->on_cpu
ecf7d01c 3755 *
3d85b270
AP
3756 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
3757 * __schedule(). See the comment for smp_mb__after_spinlock().
dbfb089d
PZ
3758 *
3759 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
3760 * schedule()'s deactivate_task() has 'happened' and p will no longer
3761 * care about it's own p->state. See the comment in __schedule().
ecf7d01c 3762 */
dbfb089d
PZ
3763 smp_acquire__after_ctrl_dep();
3764
3765 /*
3766 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
3767 * == 0), which means we need to do an enqueue, change p->state to
3768 * TASK_WAKING such that we can unlock p->pi_lock before doing the
3769 * enqueue, such as ttwu_queue_wakelist().
3770 */
3771 p->state = TASK_WAKING;
ecf7d01c 3772
c6e7bd7a
PZ
3773 /*
3774 * If the owning (remote) CPU is still in the middle of schedule() with
3775 * this task as prev, considering queueing p on the remote CPUs wake_list
3776 * which potentially sends an IPI instead of spinning on p->on_cpu to
3777 * let the waker make forward progress. This is safe because IRQs are
3778 * disabled and the IPI will deliver after on_cpu is cleared.
b6e13e85
PZ
3779 *
3780 * Ensure we load task_cpu(p) after p->on_cpu:
3781 *
3782 * set_task_cpu(p, cpu);
3783 * STORE p->cpu = @cpu
3784 * __schedule() (switch to task 'p')
3785 * LOCK rq->lock
3786 * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
3787 * STORE p->on_cpu = 1 LOAD p->cpu
3788 *
3789 * to ensure we observe the correct CPU on which the task is currently
3790 * scheduling.
c6e7bd7a 3791 */
b6e13e85 3792 if (smp_load_acquire(&p->on_cpu) &&
739f70b4 3793 ttwu_queue_wakelist(p, task_cpu(p), wake_flags | WF_ON_CPU))
c6e7bd7a
PZ
3794 goto unlock;
3795
e9c84311 3796 /*
d1ccc66d 3797 * If the owning (remote) CPU is still in the middle of schedule() with
b19a888c 3798 * this task as prev, wait until it's done referencing the task.
b75a2253 3799 *
31cb1bc0 3800 * Pairs with the smp_store_release() in finish_task().
b75a2253
PZ
3801 *
3802 * This ensures that tasks getting woken will be fully ordered against
3803 * their previous state and preserve Program Order.
0970d299 3804 */
1f03e8d2 3805 smp_cond_load_acquire(&p->on_cpu, !VAL);
1da177e4 3806
3aef1551 3807 cpu = select_task_rq(p, p->wake_cpu, wake_flags | WF_TTWU);
f339b9dc 3808 if (task_cpu(p) != cpu) {
ec618b84
PZ
3809 if (p->in_iowait) {
3810 delayacct_blkio_end(p);
3811 atomic_dec(&task_rq(p)->nr_iowait);
3812 }
3813
f339b9dc 3814 wake_flags |= WF_MIGRATED;
eb414681 3815 psi_ttwu_dequeue(p);
e4a52bcb 3816 set_task_cpu(p, cpu);
f339b9dc 3817 }
b6e13e85
PZ
3818#else
3819 cpu = task_cpu(p);
1da177e4 3820#endif /* CONFIG_SMP */
1da177e4 3821
b5179ac7 3822 ttwu_queue(p, cpu, wake_flags);
aacedf26 3823unlock:
013fdb80 3824 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
aacedf26
PZ
3825out:
3826 if (success)
b6e13e85 3827 ttwu_stat(p, task_cpu(p), wake_flags);
e3d85487 3828 preempt_enable();
1da177e4
LT
3829
3830 return success;
3831}
3832
2beaf328
PM
3833/**
3834 * try_invoke_on_locked_down_task - Invoke a function on task in fixed state
1b7af295 3835 * @p: Process for which the function is to be invoked, can be @current.
2beaf328
PM
3836 * @func: Function to invoke.
3837 * @arg: Argument to function.
3838 *
3839 * If the specified task can be quickly locked into a definite state
3840 * (either sleeping or on a given runqueue), arrange to keep it in that
3841 * state while invoking @func(@arg). This function can use ->on_rq and
3842 * task_curr() to work out what the state is, if required. Given that
3843 * @func can be invoked with a runqueue lock held, it had better be quite
3844 * lightweight.
3845 *
3846 * Returns:
3847 * @false if the task slipped out from under the locks.
3848 * @true if the task was locked onto a runqueue or is sleeping.
3849 * However, @func can override this by returning @false.
3850 */
3851bool try_invoke_on_locked_down_task(struct task_struct *p, bool (*func)(struct task_struct *t, void *arg), void *arg)
3852{
2beaf328 3853 struct rq_flags rf;
1b7af295 3854 bool ret = false;
2beaf328
PM
3855 struct rq *rq;
3856
1b7af295 3857 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2beaf328
PM
3858 if (p->on_rq) {
3859 rq = __task_rq_lock(p, &rf);
3860 if (task_rq(p) == rq)
3861 ret = func(p, arg);
3862 rq_unlock(rq, &rf);
3863 } else {
3864 switch (p->state) {
3865 case TASK_RUNNING:
3866 case TASK_WAKING:
3867 break;
3868 default:
3869 smp_rmb(); // See smp_rmb() comment in try_to_wake_up().
3870 if (!p->on_rq)
3871 ret = func(p, arg);
3872 }
3873 }
1b7af295 3874 raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
2beaf328
PM
3875 return ret;
3876}
3877
50fa610a
DH
3878/**
3879 * wake_up_process - Wake up a specific process
3880 * @p: The process to be woken up.
3881 *
3882 * Attempt to wake up the nominated process and move it to the set of runnable
e69f6186
YB
3883 * processes.
3884 *
3885 * Return: 1 if the process was woken up, 0 if it was already running.
50fa610a 3886 *
7696f991 3887 * This function executes a full memory barrier before accessing the task state.
50fa610a 3888 */
7ad5b3a5 3889int wake_up_process(struct task_struct *p)
1da177e4 3890{
9067ac85 3891 return try_to_wake_up(p, TASK_NORMAL, 0);
1da177e4 3892}
1da177e4
LT
3893EXPORT_SYMBOL(wake_up_process);
3894
7ad5b3a5 3895int wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
3896{
3897 return try_to_wake_up(p, state, 0);
3898}
3899
1da177e4
LT
3900/*
3901 * Perform scheduler related setup for a newly forked process p.
3902 * p is forked by current.
dd41f596
IM
3903 *
3904 * __sched_fork() is basic setup used by init_idle() too:
3905 */
5e1576ed 3906static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 3907{
fd2f4419
PZ
3908 p->on_rq = 0;
3909
3910 p->se.on_rq = 0;
dd41f596
IM
3911 p->se.exec_start = 0;
3912 p->se.sum_exec_runtime = 0;
f6cf891c 3913 p->se.prev_sum_exec_runtime = 0;
6c594c21 3914 p->se.nr_migrations = 0;
da7a735e 3915 p->se.vruntime = 0;
fd2f4419 3916 INIT_LIST_HEAD(&p->se.group_node);
6cfb0d5d 3917
ad936d86
BP
3918#ifdef CONFIG_FAIR_GROUP_SCHED
3919 p->se.cfs_rq = NULL;
3920#endif
3921
6cfb0d5d 3922#ifdef CONFIG_SCHEDSTATS
cb251765 3923 /* Even if schedstat is disabled, there should not be garbage */
41acab88 3924 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
6cfb0d5d 3925#endif
476d139c 3926
aab03e05 3927 RB_CLEAR_NODE(&p->dl.rb_node);
40767b0d 3928 init_dl_task_timer(&p->dl);
209a0cbd 3929 init_dl_inactive_task_timer(&p->dl);
a5e7be3b 3930 __dl_clear_params(p);
aab03e05 3931
fa717060 3932 INIT_LIST_HEAD(&p->rt.run_list);
ff77e468
PZ
3933 p->rt.timeout = 0;
3934 p->rt.time_slice = sched_rr_timeslice;
3935 p->rt.on_rq = 0;
3936 p->rt.on_list = 0;
476d139c 3937
e107be36
AK
3938#ifdef CONFIG_PREEMPT_NOTIFIERS
3939 INIT_HLIST_HEAD(&p->preempt_notifiers);
3940#endif
cbee9f88 3941
5e1f0f09
MG
3942#ifdef CONFIG_COMPACTION
3943 p->capture_control = NULL;
3944#endif
13784475 3945 init_numa_balancing(clone_flags, p);
a1488664 3946#ifdef CONFIG_SMP
8c4890d1 3947 p->wake_entry.u_flags = CSD_TYPE_TTWU;
6d337eab 3948 p->migration_pending = NULL;
a1488664 3949#endif
dd41f596
IM
3950}
3951
2a595721
SD
3952DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
3953
1a687c2e 3954#ifdef CONFIG_NUMA_BALANCING
c3b9bc5b 3955
1a687c2e
MG
3956void set_numabalancing_state(bool enabled)
3957{
3958 if (enabled)
2a595721 3959 static_branch_enable(&sched_numa_balancing);
1a687c2e 3960 else
2a595721 3961 static_branch_disable(&sched_numa_balancing);
1a687c2e 3962}
54a43d54
AK
3963
3964#ifdef CONFIG_PROC_SYSCTL
3965int sysctl_numa_balancing(struct ctl_table *table, int write,
32927393 3966 void *buffer, size_t *lenp, loff_t *ppos)
54a43d54
AK
3967{
3968 struct ctl_table t;
3969 int err;
2a595721 3970 int state = static_branch_likely(&sched_numa_balancing);
54a43d54
AK
3971
3972 if (write && !capable(CAP_SYS_ADMIN))
3973 return -EPERM;
3974
3975 t = *table;
3976 t.data = &state;
3977 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3978 if (err < 0)
3979 return err;
3980 if (write)
3981 set_numabalancing_state(state);
3982 return err;
3983}
3984#endif
3985#endif
dd41f596 3986
4698f88c
JP
3987#ifdef CONFIG_SCHEDSTATS
3988
cb251765 3989DEFINE_STATIC_KEY_FALSE(sched_schedstats);
4698f88c 3990static bool __initdata __sched_schedstats = false;
cb251765 3991
cb251765
MG
3992static void set_schedstats(bool enabled)
3993{
3994 if (enabled)
3995 static_branch_enable(&sched_schedstats);
3996 else
3997 static_branch_disable(&sched_schedstats);
3998}
3999
4000void force_schedstat_enabled(void)
4001{
4002 if (!schedstat_enabled()) {
4003 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
4004 static_branch_enable(&sched_schedstats);
4005 }
4006}
4007
4008static int __init setup_schedstats(char *str)
4009{
4010 int ret = 0;
4011 if (!str)
4012 goto out;
4013
4698f88c
JP
4014 /*
4015 * This code is called before jump labels have been set up, so we can't
4016 * change the static branch directly just yet. Instead set a temporary
4017 * variable so init_schedstats() can do it later.
4018 */
cb251765 4019 if (!strcmp(str, "enable")) {
4698f88c 4020 __sched_schedstats = true;
cb251765
MG
4021 ret = 1;
4022 } else if (!strcmp(str, "disable")) {
4698f88c 4023 __sched_schedstats = false;
cb251765
MG
4024 ret = 1;
4025 }
4026out:
4027 if (!ret)
4028 pr_warn("Unable to parse schedstats=\n");
4029
4030 return ret;
4031}
4032__setup("schedstats=", setup_schedstats);
4033
4698f88c
JP
4034static void __init init_schedstats(void)
4035{
4036 set_schedstats(__sched_schedstats);
4037}
4038
cb251765 4039#ifdef CONFIG_PROC_SYSCTL
32927393
CH
4040int sysctl_schedstats(struct ctl_table *table, int write, void *buffer,
4041 size_t *lenp, loff_t *ppos)
cb251765
MG
4042{
4043 struct ctl_table t;
4044 int err;
4045 int state = static_branch_likely(&sched_schedstats);
4046
4047 if (write && !capable(CAP_SYS_ADMIN))
4048 return -EPERM;
4049
4050 t = *table;
4051 t.data = &state;
4052 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
4053 if (err < 0)
4054 return err;
4055 if (write)
4056 set_schedstats(state);
4057 return err;
4058}
4698f88c
JP
4059#endif /* CONFIG_PROC_SYSCTL */
4060#else /* !CONFIG_SCHEDSTATS */
4061static inline void init_schedstats(void) {}
4062#endif /* CONFIG_SCHEDSTATS */
dd41f596
IM
4063
4064/*
4065 * fork()/clone()-time setup:
4066 */
aab03e05 4067int sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 4068{
0122ec5b 4069 unsigned long flags;
dd41f596 4070
5e1576ed 4071 __sched_fork(clone_flags, p);
06b83b5f 4072 /*
7dc603c9 4073 * We mark the process as NEW here. This guarantees that
06b83b5f
PZ
4074 * nobody will actually run it, and a signal or other external
4075 * event cannot wake it up and insert it on the runqueue either.
4076 */
7dc603c9 4077 p->state = TASK_NEW;
dd41f596 4078
c350a04e
MG
4079 /*
4080 * Make sure we do not leak PI boosting priority to the child.
4081 */
4082 p->prio = current->normal_prio;
4083
e8f14172
PB
4084 uclamp_fork(p);
4085
b9dc29e7
MG
4086 /*
4087 * Revert to default priority/policy on fork if requested.
4088 */
4089 if (unlikely(p->sched_reset_on_fork)) {
aab03e05 4090 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
b9dc29e7 4091 p->policy = SCHED_NORMAL;
6c697bdf 4092 p->static_prio = NICE_TO_PRIO(0);
c350a04e
MG
4093 p->rt_priority = 0;
4094 } else if (PRIO_TO_NICE(p->static_prio) < 0)
4095 p->static_prio = NICE_TO_PRIO(0);
4096
4097 p->prio = p->normal_prio = __normal_prio(p);
9059393e 4098 set_load_weight(p, false);
6c697bdf 4099
b9dc29e7
MG
4100 /*
4101 * We don't need the reset flag anymore after the fork. It has
4102 * fulfilled its duty:
4103 */
4104 p->sched_reset_on_fork = 0;
4105 }
ca94c442 4106
af0fffd9 4107 if (dl_prio(p->prio))
aab03e05 4108 return -EAGAIN;
af0fffd9 4109 else if (rt_prio(p->prio))
aab03e05 4110 p->sched_class = &rt_sched_class;
af0fffd9 4111 else
2ddbf952 4112 p->sched_class = &fair_sched_class;
b29739f9 4113
7dc603c9 4114 init_entity_runnable_average(&p->se);
cd29fe6f 4115
86951599
PZ
4116 /*
4117 * The child is not yet in the pid-hash so no cgroup attach races,
4118 * and the cgroup is pinned to this child due to cgroup_fork()
4119 * is ran before sched_fork().
4120 *
4121 * Silence PROVE_RCU.
4122 */
0122ec5b 4123 raw_spin_lock_irqsave(&p->pi_lock, flags);
ce3614da 4124 rseq_migrate(p);
e210bffd 4125 /*
d1ccc66d 4126 * We're setting the CPU for the first time, we don't migrate,
e210bffd
PZ
4127 * so use __set_task_cpu().
4128 */
af0fffd9 4129 __set_task_cpu(p, smp_processor_id());
e210bffd
PZ
4130 if (p->sched_class->task_fork)
4131 p->sched_class->task_fork(p);
0122ec5b 4132 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5f3edc1b 4133
f6db8347 4134#ifdef CONFIG_SCHED_INFO
dd41f596 4135 if (likely(sched_info_on()))
52f17b6c 4136 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 4137#endif
3ca7a440
PZ
4138#if defined(CONFIG_SMP)
4139 p->on_cpu = 0;
4866cde0 4140#endif
01028747 4141 init_task_preempt_count(p);
806c09a7 4142#ifdef CONFIG_SMP
917b627d 4143 plist_node_init(&p->pushable_tasks, MAX_PRIO);
1baca4ce 4144 RB_CLEAR_NODE(&p->pushable_dl_tasks);
806c09a7 4145#endif
aab03e05 4146 return 0;
1da177e4
LT
4147}
4148
13685c4a
QY
4149void sched_post_fork(struct task_struct *p)
4150{
4151 uclamp_post_fork(p);
4152}
4153
332ac17e
DF
4154unsigned long to_ratio(u64 period, u64 runtime)
4155{
4156 if (runtime == RUNTIME_INF)
c52f14d3 4157 return BW_UNIT;
332ac17e
DF
4158
4159 /*
4160 * Doing this here saves a lot of checks in all
4161 * the calling paths, and returning zero seems
4162 * safe for them anyway.
4163 */
4164 if (period == 0)
4165 return 0;
4166
c52f14d3 4167 return div64_u64(runtime << BW_SHIFT, period);
332ac17e
DF
4168}
4169
1da177e4
LT
4170/*
4171 * wake_up_new_task - wake up a newly created task for the first time.
4172 *
4173 * This function will do some initial scheduler statistics housekeeping
4174 * that must be done for every newly created context, then puts the task
4175 * on the runqueue and wakes it.
4176 */
3e51e3ed 4177void wake_up_new_task(struct task_struct *p)
1da177e4 4178{
eb580751 4179 struct rq_flags rf;
dd41f596 4180 struct rq *rq;
fabf318e 4181
eb580751 4182 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
7dc603c9 4183 p->state = TASK_RUNNING;
fabf318e
PZ
4184#ifdef CONFIG_SMP
4185 /*
4186 * Fork balancing, do it here and not earlier because:
3bd37062 4187 * - cpus_ptr can change in the fork path
d1ccc66d 4188 * - any previously selected CPU might disappear through hotplug
e210bffd
PZ
4189 *
4190 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
4191 * as we're not fully set-up yet.
fabf318e 4192 */
32e839dd 4193 p->recent_used_cpu = task_cpu(p);
ce3614da 4194 rseq_migrate(p);
3aef1551 4195 __set_task_cpu(p, select_task_rq(p, task_cpu(p), WF_FORK));
0017d735 4196#endif
b7fa30c9 4197 rq = __task_rq_lock(p, &rf);
4126bad6 4198 update_rq_clock(rq);
d0fe0b9c 4199 post_init_entity_util_avg(p);
0017d735 4200
7a57f32a 4201 activate_task(rq, p, ENQUEUE_NOCLOCK);
fbd705a0 4202 trace_sched_wakeup_new(p);
a7558e01 4203 check_preempt_curr(rq, p, WF_FORK);
9a897c5a 4204#ifdef CONFIG_SMP
0aaafaab
PZ
4205 if (p->sched_class->task_woken) {
4206 /*
b19a888c 4207 * Nothing relies on rq->lock after this, so it's fine to
0aaafaab
PZ
4208 * drop it.
4209 */
d8ac8971 4210 rq_unpin_lock(rq, &rf);
efbbd05a 4211 p->sched_class->task_woken(rq, p);
d8ac8971 4212 rq_repin_lock(rq, &rf);
0aaafaab 4213 }
9a897c5a 4214#endif
eb580751 4215 task_rq_unlock(rq, p, &rf);
1da177e4
LT
4216}
4217
e107be36
AK
4218#ifdef CONFIG_PREEMPT_NOTIFIERS
4219
b7203428 4220static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
1cde2930 4221
2ecd9d29
PZ
4222void preempt_notifier_inc(void)
4223{
b7203428 4224 static_branch_inc(&preempt_notifier_key);
2ecd9d29
PZ
4225}
4226EXPORT_SYMBOL_GPL(preempt_notifier_inc);
4227
4228void preempt_notifier_dec(void)
4229{
b7203428 4230 static_branch_dec(&preempt_notifier_key);
2ecd9d29
PZ
4231}
4232EXPORT_SYMBOL_GPL(preempt_notifier_dec);
4233
e107be36 4234/**
80dd99b3 4235 * preempt_notifier_register - tell me when current is being preempted & rescheduled
421cee29 4236 * @notifier: notifier struct to register
e107be36
AK
4237 */
4238void preempt_notifier_register(struct preempt_notifier *notifier)
4239{
b7203428 4240 if (!static_branch_unlikely(&preempt_notifier_key))
2ecd9d29
PZ
4241 WARN(1, "registering preempt_notifier while notifiers disabled\n");
4242
e107be36
AK
4243 hlist_add_head(&notifier->link, &current->preempt_notifiers);
4244}
4245EXPORT_SYMBOL_GPL(preempt_notifier_register);
4246
4247/**
4248 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 4249 * @notifier: notifier struct to unregister
e107be36 4250 *
d84525a8 4251 * This is *not* safe to call from within a preemption notifier.
e107be36
AK
4252 */
4253void preempt_notifier_unregister(struct preempt_notifier *notifier)
4254{
4255 hlist_del(&notifier->link);
4256}
4257EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
4258
1cde2930 4259static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
4260{
4261 struct preempt_notifier *notifier;
e107be36 4262
b67bfe0d 4263 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
4264 notifier->ops->sched_in(notifier, raw_smp_processor_id());
4265}
4266
1cde2930
PZ
4267static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
4268{
b7203428 4269 if (static_branch_unlikely(&preempt_notifier_key))
1cde2930
PZ
4270 __fire_sched_in_preempt_notifiers(curr);
4271}
4272
e107be36 4273static void
1cde2930
PZ
4274__fire_sched_out_preempt_notifiers(struct task_struct *curr,
4275 struct task_struct *next)
e107be36
AK
4276{
4277 struct preempt_notifier *notifier;
e107be36 4278
b67bfe0d 4279 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
4280 notifier->ops->sched_out(notifier, next);
4281}
4282
1cde2930
PZ
4283static __always_inline void
4284fire_sched_out_preempt_notifiers(struct task_struct *curr,
4285 struct task_struct *next)
4286{
b7203428 4287 if (static_branch_unlikely(&preempt_notifier_key))
1cde2930
PZ
4288 __fire_sched_out_preempt_notifiers(curr, next);
4289}
4290
6d6bc0ad 4291#else /* !CONFIG_PREEMPT_NOTIFIERS */
e107be36 4292
1cde2930 4293static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
4294{
4295}
4296
1cde2930 4297static inline void
e107be36
AK
4298fire_sched_out_preempt_notifiers(struct task_struct *curr,
4299 struct task_struct *next)
4300{
4301}
4302
6d6bc0ad 4303#endif /* CONFIG_PREEMPT_NOTIFIERS */
e107be36 4304
31cb1bc0 4305static inline void prepare_task(struct task_struct *next)
4306{
4307#ifdef CONFIG_SMP
4308 /*
4309 * Claim the task as running, we do this before switching to it
4310 * such that any running task will have this set.
58877d34
PZ
4311 *
4312 * See the ttwu() WF_ON_CPU case and its ordering comment.
31cb1bc0 4313 */
58877d34 4314 WRITE_ONCE(next->on_cpu, 1);
31cb1bc0 4315#endif
4316}
4317
4318static inline void finish_task(struct task_struct *prev)
4319{
4320#ifdef CONFIG_SMP
4321 /*
58877d34
PZ
4322 * This must be the very last reference to @prev from this CPU. After
4323 * p->on_cpu is cleared, the task can be moved to a different CPU. We
4324 * must ensure this doesn't happen until the switch is completely
31cb1bc0 4325 * finished.
4326 *
4327 * In particular, the load of prev->state in finish_task_switch() must
4328 * happen before this.
4329 *
4330 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
4331 */
4332 smp_store_release(&prev->on_cpu, 0);
4333#endif
4334}
4335
565790d2
PZ
4336#ifdef CONFIG_SMP
4337
4338static void do_balance_callbacks(struct rq *rq, struct callback_head *head)
4339{
4340 void (*func)(struct rq *rq);
4341 struct callback_head *next;
4342
5cb9eaa3 4343 lockdep_assert_rq_held(rq);
565790d2
PZ
4344
4345 while (head) {
4346 func = (void (*)(struct rq *))head->func;
4347 next = head->next;
4348 head->next = NULL;
4349 head = next;
4350
4351 func(rq);
4352 }
4353}
4354
ae792702
PZ
4355static void balance_push(struct rq *rq);
4356
4357struct callback_head balance_push_callback = {
4358 .next = NULL,
4359 .func = (void (*)(struct callback_head *))balance_push,
4360};
4361
565790d2
PZ
4362static inline struct callback_head *splice_balance_callbacks(struct rq *rq)
4363{
4364 struct callback_head *head = rq->balance_callback;
4365
5cb9eaa3 4366 lockdep_assert_rq_held(rq);
ae792702 4367 if (head)
565790d2
PZ
4368 rq->balance_callback = NULL;
4369
4370 return head;
4371}
4372
4373static void __balance_callbacks(struct rq *rq)
4374{
4375 do_balance_callbacks(rq, splice_balance_callbacks(rq));
4376}
4377
4378static inline void balance_callbacks(struct rq *rq, struct callback_head *head)
4379{
4380 unsigned long flags;
4381
4382 if (unlikely(head)) {
5cb9eaa3 4383 raw_spin_rq_lock_irqsave(rq, flags);
565790d2 4384 do_balance_callbacks(rq, head);
5cb9eaa3 4385 raw_spin_rq_unlock_irqrestore(rq, flags);
565790d2
PZ
4386 }
4387}
4388
4389#else
4390
4391static inline void __balance_callbacks(struct rq *rq)
4392{
4393}
4394
4395static inline struct callback_head *splice_balance_callbacks(struct rq *rq)
4396{
4397 return NULL;
4398}
4399
4400static inline void balance_callbacks(struct rq *rq, struct callback_head *head)
4401{
4402}
4403
4404#endif
4405
269d5992
PZ
4406static inline void
4407prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
31cb1bc0 4408{
269d5992
PZ
4409 /*
4410 * Since the runqueue lock will be released by the next
4411 * task (which is an invalid locking op but in the case
4412 * of the scheduler it's an obvious special-case), so we
4413 * do an early lockdep release here:
4414 */
4415 rq_unpin_lock(rq, rf);
9ef7e7e3 4416 spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_);
31cb1bc0 4417#ifdef CONFIG_DEBUG_SPINLOCK
4418 /* this is a valid case when another task releases the spinlock */
5cb9eaa3 4419 rq_lockp(rq)->owner = next;
31cb1bc0 4420#endif
269d5992
PZ
4421}
4422
4423static inline void finish_lock_switch(struct rq *rq)
4424{
31cb1bc0 4425 /*
4426 * If we are tracking spinlock dependencies then we have to
4427 * fix up the runqueue lock - which gets 'carried over' from
4428 * prev into current:
4429 */
9ef7e7e3 4430 spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_);
ae792702 4431 __balance_callbacks(rq);
5cb9eaa3 4432 raw_spin_rq_unlock_irq(rq);
31cb1bc0 4433}
4434
325ea10c
IM
4435/*
4436 * NOP if the arch has not defined these:
4437 */
4438
4439#ifndef prepare_arch_switch
4440# define prepare_arch_switch(next) do { } while (0)
4441#endif
4442
4443#ifndef finish_arch_post_lock_switch
4444# define finish_arch_post_lock_switch() do { } while (0)
4445#endif
4446
5fbda3ec
TG
4447static inline void kmap_local_sched_out(void)
4448{
4449#ifdef CONFIG_KMAP_LOCAL
4450 if (unlikely(current->kmap_ctrl.idx))
4451 __kmap_local_sched_out();
4452#endif
4453}
4454
4455static inline void kmap_local_sched_in(void)
4456{
4457#ifdef CONFIG_KMAP_LOCAL
4458 if (unlikely(current->kmap_ctrl.idx))
4459 __kmap_local_sched_in();
4460#endif
4461}
4462
4866cde0
NP
4463/**
4464 * prepare_task_switch - prepare to switch tasks
4465 * @rq: the runqueue preparing to switch
421cee29 4466 * @prev: the current task that is being switched out
4866cde0
NP
4467 * @next: the task we are going to switch to.
4468 *
4469 * This is called with the rq lock held and interrupts off. It must
4470 * be paired with a subsequent finish_task_switch after the context
4471 * switch.
4472 *
4473 * prepare_task_switch sets up locking and calls architecture specific
4474 * hooks.
4475 */
e107be36
AK
4476static inline void
4477prepare_task_switch(struct rq *rq, struct task_struct *prev,
4478 struct task_struct *next)
4866cde0 4479{
0ed557aa 4480 kcov_prepare_switch(prev);
43148951 4481 sched_info_switch(rq, prev, next);
fe4b04fa 4482 perf_event_task_sched_out(prev, next);
d7822b1e 4483 rseq_preempt(prev);
e107be36 4484 fire_sched_out_preempt_notifiers(prev, next);
5fbda3ec 4485 kmap_local_sched_out();
31cb1bc0 4486 prepare_task(next);
4866cde0
NP
4487 prepare_arch_switch(next);
4488}
4489
1da177e4
LT
4490/**
4491 * finish_task_switch - clean up after a task-switch
4492 * @prev: the thread we just switched away from.
4493 *
4866cde0
NP
4494 * finish_task_switch must be called after the context switch, paired
4495 * with a prepare_task_switch call before the context switch.
4496 * finish_task_switch will reconcile locking set up by prepare_task_switch,
4497 * and do any other architecture-specific cleanup actions.
1da177e4
LT
4498 *
4499 * Note that we may have delayed dropping an mm in context_switch(). If
41a2d6cf 4500 * so, we finish that here outside of the runqueue lock. (Doing it
1da177e4
LT
4501 * with the lock held can cause deadlocks; see schedule() for
4502 * details.)
dfa50b60
ON
4503 *
4504 * The context switch have flipped the stack from under us and restored the
4505 * local variables which were saved when this task called schedule() in the
4506 * past. prev == current is still correct but we need to recalculate this_rq
4507 * because prev may have moved to another CPU.
1da177e4 4508 */
dfa50b60 4509static struct rq *finish_task_switch(struct task_struct *prev)
1da177e4
LT
4510 __releases(rq->lock)
4511{
dfa50b60 4512 struct rq *rq = this_rq();
1da177e4 4513 struct mm_struct *mm = rq->prev_mm;
55a101f8 4514 long prev_state;
1da177e4 4515
609ca066
PZ
4516 /*
4517 * The previous task will have left us with a preempt_count of 2
4518 * because it left us after:
4519 *
4520 * schedule()
4521 * preempt_disable(); // 1
4522 * __schedule()
4523 * raw_spin_lock_irq(&rq->lock) // 2
4524 *
4525 * Also, see FORK_PREEMPT_COUNT.
4526 */
e2bf1c4b
PZ
4527 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
4528 "corrupted preempt_count: %s/%d/0x%x\n",
4529 current->comm, current->pid, preempt_count()))
4530 preempt_count_set(FORK_PREEMPT_COUNT);
609ca066 4531
1da177e4
LT
4532 rq->prev_mm = NULL;
4533
4534 /*
4535 * A task struct has one reference for the use as "current".
c394cc9f 4536 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
4537 * schedule one last time. The schedule call will never return, and
4538 * the scheduled task must drop that reference.
95913d97
PZ
4539 *
4540 * We must observe prev->state before clearing prev->on_cpu (in
31cb1bc0 4541 * finish_task), otherwise a concurrent wakeup can get prev
95913d97
PZ
4542 * running on another CPU and we could rave with its RUNNING -> DEAD
4543 * transition, resulting in a double drop.
1da177e4 4544 */
55a101f8 4545 prev_state = prev->state;
bf9fae9f 4546 vtime_task_switch(prev);
a8d757ef 4547 perf_event_task_sched_in(prev, current);
31cb1bc0 4548 finish_task(prev);
4549 finish_lock_switch(rq);
01f23e16 4550 finish_arch_post_lock_switch();
0ed557aa 4551 kcov_finish_switch(current);
5fbda3ec
TG
4552 /*
4553 * kmap_local_sched_out() is invoked with rq::lock held and
4554 * interrupts disabled. There is no requirement for that, but the
4555 * sched out code does not have an interrupt enabled section.
4556 * Restoring the maps on sched in does not require interrupts being
4557 * disabled either.
4558 */
4559 kmap_local_sched_in();
e8fa1362 4560
e107be36 4561 fire_sched_in_preempt_notifiers(current);
306e0604 4562 /*
70216e18
MD
4563 * When switching through a kernel thread, the loop in
4564 * membarrier_{private,global}_expedited() may have observed that
4565 * kernel thread and not issued an IPI. It is therefore possible to
4566 * schedule between user->kernel->user threads without passing though
4567 * switch_mm(). Membarrier requires a barrier after storing to
4568 * rq->curr, before returning to userspace, so provide them here:
4569 *
4570 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
4571 * provided by mmdrop(),
4572 * - a sync_core for SYNC_CORE.
306e0604 4573 */
70216e18
MD
4574 if (mm) {
4575 membarrier_mm_sync_core_before_usermode(mm);
1da177e4 4576 mmdrop(mm);
70216e18 4577 }
1cef1150
PZ
4578 if (unlikely(prev_state == TASK_DEAD)) {
4579 if (prev->sched_class->task_dead)
4580 prev->sched_class->task_dead(prev);
68f24b08 4581
1cef1150
PZ
4582 /*
4583 * Remove function-return probe instances associated with this
4584 * task and put them back on the free list.
4585 */
4586 kprobe_flush_task(prev);
4587
4588 /* Task is done with its stack. */
4589 put_task_stack(prev);
4590
0ff7b2cf 4591 put_task_struct_rcu_user(prev);
c6fd91f0 4592 }
99e5ada9 4593
de734f89 4594 tick_nohz_task_switch();
dfa50b60 4595 return rq;
1da177e4
LT
4596}
4597
4598/**
4599 * schedule_tail - first thing a freshly forked thread must call.
4600 * @prev: the thread we just switched away from.
4601 */
722a9f92 4602asmlinkage __visible void schedule_tail(struct task_struct *prev)
1da177e4
LT
4603 __releases(rq->lock)
4604{
609ca066
PZ
4605 /*
4606 * New tasks start with FORK_PREEMPT_COUNT, see there and
4607 * finish_task_switch() for details.
4608 *
4609 * finish_task_switch() will drop rq->lock() and lower preempt_count
4610 * and the preempt_enable() will end up enabling preemption (on
4611 * PREEMPT_COUNT kernels).
4612 */
4613
13c2235b 4614 finish_task_switch(prev);
1a43a14a 4615 preempt_enable();
70b97a7f 4616
1da177e4 4617 if (current->set_child_tid)
b488893a 4618 put_user(task_pid_vnr(current), current->set_child_tid);
088fe47c
EB
4619
4620 calculate_sigpending();
1da177e4
LT
4621}
4622
4623/*
dfa50b60 4624 * context_switch - switch to the new MM and the new thread's register state.
1da177e4 4625 */
04936948 4626static __always_inline struct rq *
70b97a7f 4627context_switch(struct rq *rq, struct task_struct *prev,
d8ac8971 4628 struct task_struct *next, struct rq_flags *rf)
1da177e4 4629{
e107be36 4630 prepare_task_switch(rq, prev, next);
fe4b04fa 4631
9226d125
ZA
4632 /*
4633 * For paravirt, this is coupled with an exit in switch_to to
4634 * combine the page table reload and the switch backend into
4635 * one hypercall.
4636 */
224101ed 4637 arch_start_context_switch(prev);
9226d125 4638
306e0604 4639 /*
139d025c
PZ
4640 * kernel -> kernel lazy + transfer active
4641 * user -> kernel lazy + mmgrab() active
4642 *
4643 * kernel -> user switch + mmdrop() active
4644 * user -> user switch
306e0604 4645 */
139d025c
PZ
4646 if (!next->mm) { // to kernel
4647 enter_lazy_tlb(prev->active_mm, next);
4648
4649 next->active_mm = prev->active_mm;
4650 if (prev->mm) // from user
4651 mmgrab(prev->active_mm);
4652 else
4653 prev->active_mm = NULL;
4654 } else { // to user
227a4aad 4655 membarrier_switch_mm(rq, prev->active_mm, next->mm);
139d025c
PZ
4656 /*
4657 * sys_membarrier() requires an smp_mb() between setting
227a4aad 4658 * rq->curr / membarrier_switch_mm() and returning to userspace.
139d025c
PZ
4659 *
4660 * The below provides this either through switch_mm(), or in
4661 * case 'prev->active_mm == next->mm' through
4662 * finish_task_switch()'s mmdrop().
4663 */
139d025c 4664 switch_mm_irqs_off(prev->active_mm, next->mm, next);
1da177e4 4665
139d025c
PZ
4666 if (!prev->mm) { // from kernel
4667 /* will mmdrop() in finish_task_switch(). */
4668 rq->prev_mm = prev->active_mm;
4669 prev->active_mm = NULL;
4670 }
1da177e4 4671 }
92509b73 4672
cb42c9a3 4673 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
92509b73 4674
269d5992 4675 prepare_lock_switch(rq, next, rf);
1da177e4
LT
4676
4677 /* Here we just switch the register state and the stack. */
4678 switch_to(prev, next, prev);
dd41f596 4679 barrier();
dfa50b60
ON
4680
4681 return finish_task_switch(prev);
1da177e4
LT
4682}
4683
4684/*
1c3e8264 4685 * nr_running and nr_context_switches:
1da177e4
LT
4686 *
4687 * externally visible scheduler statistics: current number of runnable
1c3e8264 4688 * threads, total number of context switches performed since bootup.
1da177e4
LT
4689 */
4690unsigned long nr_running(void)
4691{
4692 unsigned long i, sum = 0;
4693
4694 for_each_online_cpu(i)
4695 sum += cpu_rq(i)->nr_running;
4696
4697 return sum;
f711f609 4698}
1da177e4 4699
2ee507c4 4700/*
d1ccc66d 4701 * Check if only the current task is running on the CPU.
00cc1633
DD
4702 *
4703 * Caution: this function does not check that the caller has disabled
4704 * preemption, thus the result might have a time-of-check-to-time-of-use
4705 * race. The caller is responsible to use it correctly, for example:
4706 *
dfcb245e 4707 * - from a non-preemptible section (of course)
00cc1633
DD
4708 *
4709 * - from a thread that is bound to a single CPU
4710 *
4711 * - in a loop with very short iterations (e.g. a polling loop)
2ee507c4
TC
4712 */
4713bool single_task_running(void)
4714{
00cc1633 4715 return raw_rq()->nr_running == 1;
2ee507c4
TC
4716}
4717EXPORT_SYMBOL(single_task_running);
4718
1da177e4 4719unsigned long long nr_context_switches(void)
46cb4b7c 4720{
cc94abfc
SR
4721 int i;
4722 unsigned long long sum = 0;
46cb4b7c 4723
0a945022 4724 for_each_possible_cpu(i)
1da177e4 4725 sum += cpu_rq(i)->nr_switches;
46cb4b7c 4726
1da177e4
LT
4727 return sum;
4728}
483b4ee6 4729
145d952a
DL
4730/*
4731 * Consumers of these two interfaces, like for example the cpuidle menu
4732 * governor, are using nonsensical data. Preferring shallow idle state selection
4733 * for a CPU that has IO-wait which might not even end up running the task when
4734 * it does become runnable.
4735 */
4736
4737unsigned long nr_iowait_cpu(int cpu)
4738{
4739 return atomic_read(&cpu_rq(cpu)->nr_iowait);
4740}
4741
e33a9bba 4742/*
b19a888c 4743 * IO-wait accounting, and how it's mostly bollocks (on SMP).
e33a9bba
TH
4744 *
4745 * The idea behind IO-wait account is to account the idle time that we could
4746 * have spend running if it were not for IO. That is, if we were to improve the
4747 * storage performance, we'd have a proportional reduction in IO-wait time.
4748 *
4749 * This all works nicely on UP, where, when a task blocks on IO, we account
4750 * idle time as IO-wait, because if the storage were faster, it could've been
4751 * running and we'd not be idle.
4752 *
4753 * This has been extended to SMP, by doing the same for each CPU. This however
4754 * is broken.
4755 *
4756 * Imagine for instance the case where two tasks block on one CPU, only the one
4757 * CPU will have IO-wait accounted, while the other has regular idle. Even
4758 * though, if the storage were faster, both could've ran at the same time,
4759 * utilising both CPUs.
4760 *
4761 * This means, that when looking globally, the current IO-wait accounting on
4762 * SMP is a lower bound, by reason of under accounting.
4763 *
4764 * Worse, since the numbers are provided per CPU, they are sometimes
4765 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
4766 * associated with any one particular CPU, it can wake to another CPU than it
4767 * blocked on. This means the per CPU IO-wait number is meaningless.
4768 *
4769 * Task CPU affinities can make all that even more 'interesting'.
4770 */
4771
1da177e4
LT
4772unsigned long nr_iowait(void)
4773{
4774 unsigned long i, sum = 0;
483b4ee6 4775
0a945022 4776 for_each_possible_cpu(i)
145d952a 4777 sum += nr_iowait_cpu(i);
46cb4b7c 4778
1da177e4
LT
4779 return sum;
4780}
483b4ee6 4781
dd41f596 4782#ifdef CONFIG_SMP
8a0be9ef 4783
46cb4b7c 4784/*
38022906
PZ
4785 * sched_exec - execve() is a valuable balancing opportunity, because at
4786 * this point the task has the smallest effective memory and cache footprint.
46cb4b7c 4787 */
38022906 4788void sched_exec(void)
46cb4b7c 4789{
38022906 4790 struct task_struct *p = current;
1da177e4 4791 unsigned long flags;
0017d735 4792 int dest_cpu;
46cb4b7c 4793
8f42ced9 4794 raw_spin_lock_irqsave(&p->pi_lock, flags);
3aef1551 4795 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC);
0017d735
PZ
4796 if (dest_cpu == smp_processor_id())
4797 goto unlock;
38022906 4798
8f42ced9 4799 if (likely(cpu_active(dest_cpu))) {
969c7921 4800 struct migration_arg arg = { p, dest_cpu };
46cb4b7c 4801
8f42ced9
PZ
4802 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4803 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
1da177e4
LT
4804 return;
4805 }
0017d735 4806unlock:
8f42ced9 4807 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4 4808}
dd41f596 4809
1da177e4
LT
4810#endif
4811
1da177e4 4812DEFINE_PER_CPU(struct kernel_stat, kstat);
3292beb3 4813DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
1da177e4
LT
4814
4815EXPORT_PER_CPU_SYMBOL(kstat);
3292beb3 4816EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
1da177e4 4817
6075620b
GG
4818/*
4819 * The function fair_sched_class.update_curr accesses the struct curr
4820 * and its field curr->exec_start; when called from task_sched_runtime(),
4821 * we observe a high rate of cache misses in practice.
4822 * Prefetching this data results in improved performance.
4823 */
4824static inline void prefetch_curr_exec_start(struct task_struct *p)
4825{
4826#ifdef CONFIG_FAIR_GROUP_SCHED
4827 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
4828#else
4829 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
4830#endif
4831 prefetch(curr);
4832 prefetch(&curr->exec_start);
4833}
4834
c5f8d995
HS
4835/*
4836 * Return accounted runtime for the task.
4837 * In case the task is currently running, return the runtime plus current's
4838 * pending runtime that have not been accounted yet.
4839 */
4840unsigned long long task_sched_runtime(struct task_struct *p)
4841{
eb580751 4842 struct rq_flags rf;
c5f8d995 4843 struct rq *rq;
6e998916 4844 u64 ns;
c5f8d995 4845
911b2898
PZ
4846#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
4847 /*
97fb7a0a 4848 * 64-bit doesn't need locks to atomically read a 64-bit value.
911b2898
PZ
4849 * So we have a optimization chance when the task's delta_exec is 0.
4850 * Reading ->on_cpu is racy, but this is ok.
4851 *
d1ccc66d
IM
4852 * If we race with it leaving CPU, we'll take a lock. So we're correct.
4853 * If we race with it entering CPU, unaccounted time is 0. This is
911b2898 4854 * indistinguishable from the read occurring a few cycles earlier.
4036ac15
MG
4855 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
4856 * been accounted, so we're correct here as well.
911b2898 4857 */
da0c1e65 4858 if (!p->on_cpu || !task_on_rq_queued(p))
911b2898
PZ
4859 return p->se.sum_exec_runtime;
4860#endif
4861
eb580751 4862 rq = task_rq_lock(p, &rf);
6e998916
SG
4863 /*
4864 * Must be ->curr _and_ ->on_rq. If dequeued, we would
4865 * project cycles that may never be accounted to this
4866 * thread, breaking clock_gettime().
4867 */
4868 if (task_current(rq, p) && task_on_rq_queued(p)) {
6075620b 4869 prefetch_curr_exec_start(p);
6e998916
SG
4870 update_rq_clock(rq);
4871 p->sched_class->update_curr(rq);
4872 }
4873 ns = p->se.sum_exec_runtime;
eb580751 4874 task_rq_unlock(rq, p, &rf);
c5f8d995
HS
4875
4876 return ns;
4877}
48f24c4d 4878
c006fac5
PT
4879#ifdef CONFIG_SCHED_DEBUG
4880static u64 cpu_resched_latency(struct rq *rq)
4881{
4882 int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms);
4883 u64 resched_latency, now = rq_clock(rq);
4884 static bool warned_once;
4885
4886 if (sysctl_resched_latency_warn_once && warned_once)
4887 return 0;
4888
4889 if (!need_resched() || !latency_warn_ms)
4890 return 0;
4891
4892 if (system_state == SYSTEM_BOOTING)
4893 return 0;
4894
4895 if (!rq->last_seen_need_resched_ns) {
4896 rq->last_seen_need_resched_ns = now;
4897 rq->ticks_without_resched = 0;
4898 return 0;
4899 }
4900
4901 rq->ticks_without_resched++;
4902 resched_latency = now - rq->last_seen_need_resched_ns;
4903 if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC)
4904 return 0;
4905
4906 warned_once = true;
4907
4908 return resched_latency;
4909}
4910
4911static int __init setup_resched_latency_warn_ms(char *str)
4912{
4913 long val;
4914
4915 if ((kstrtol(str, 0, &val))) {
4916 pr_warn("Unable to set resched_latency_warn_ms\n");
4917 return 1;
4918 }
4919
4920 sysctl_resched_latency_warn_ms = val;
4921 return 1;
4922}
4923__setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms);
4924#else
4925static inline u64 cpu_resched_latency(struct rq *rq) { return 0; }
4926#endif /* CONFIG_SCHED_DEBUG */
4927
7835b98b
CL
4928/*
4929 * This function gets called by the timer code, with HZ frequency.
4930 * We call it with interrupts disabled.
7835b98b
CL
4931 */
4932void scheduler_tick(void)
4933{
7835b98b
CL
4934 int cpu = smp_processor_id();
4935 struct rq *rq = cpu_rq(cpu);
dd41f596 4936 struct task_struct *curr = rq->curr;
8a8c69c3 4937 struct rq_flags rf;
b4eccf5f 4938 unsigned long thermal_pressure;
c006fac5 4939 u64 resched_latency;
3e51f33f 4940
1567c3e3 4941 arch_scale_freq_tick();
3e51f33f 4942 sched_clock_tick();
dd41f596 4943
8a8c69c3
PZ
4944 rq_lock(rq, &rf);
4945
3e51f33f 4946 update_rq_clock(rq);
b4eccf5f 4947 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
05289b90 4948 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure);
fa85ae24 4949 curr->sched_class->task_tick(rq, curr, 0);
c006fac5
PT
4950 if (sched_feat(LATENCY_WARN))
4951 resched_latency = cpu_resched_latency(rq);
3289bdb4 4952 calc_global_load_tick(rq);
8a8c69c3
PZ
4953
4954 rq_unlock(rq, &rf);
7835b98b 4955
c006fac5
PT
4956 if (sched_feat(LATENCY_WARN) && resched_latency)
4957 resched_latency_warn(cpu, resched_latency);
4958
e9d2b064 4959 perf_event_task_tick();
e220d2dc 4960
e418e1c2 4961#ifdef CONFIG_SMP
6eb57e0d 4962 rq->idle_balance = idle_cpu(cpu);
7caff66f 4963 trigger_load_balance(rq);
e418e1c2 4964#endif
1da177e4
LT
4965}
4966
265f22a9 4967#ifdef CONFIG_NO_HZ_FULL
d84b3131
FW
4968
4969struct tick_work {
4970 int cpu;
b55bd585 4971 atomic_t state;
d84b3131
FW
4972 struct delayed_work work;
4973};
b55bd585
PM
4974/* Values for ->state, see diagram below. */
4975#define TICK_SCHED_REMOTE_OFFLINE 0
4976#define TICK_SCHED_REMOTE_OFFLINING 1
4977#define TICK_SCHED_REMOTE_RUNNING 2
4978
4979/*
4980 * State diagram for ->state:
4981 *
4982 *
4983 * TICK_SCHED_REMOTE_OFFLINE
4984 * | ^
4985 * | |
4986 * | | sched_tick_remote()
4987 * | |
4988 * | |
4989 * +--TICK_SCHED_REMOTE_OFFLINING
4990 * | ^
4991 * | |
4992 * sched_tick_start() | | sched_tick_stop()
4993 * | |
4994 * V |
4995 * TICK_SCHED_REMOTE_RUNNING
4996 *
4997 *
4998 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
4999 * and sched_tick_start() are happy to leave the state in RUNNING.
5000 */
d84b3131
FW
5001
5002static struct tick_work __percpu *tick_work_cpu;
5003
5004static void sched_tick_remote(struct work_struct *work)
5005{
5006 struct delayed_work *dwork = to_delayed_work(work);
5007 struct tick_work *twork = container_of(dwork, struct tick_work, work);
5008 int cpu = twork->cpu;
5009 struct rq *rq = cpu_rq(cpu);
d9c0ffca 5010 struct task_struct *curr;
d84b3131 5011 struct rq_flags rf;
d9c0ffca 5012 u64 delta;
b55bd585 5013 int os;
d84b3131
FW
5014
5015 /*
5016 * Handle the tick only if it appears the remote CPU is running in full
5017 * dynticks mode. The check is racy by nature, but missing a tick or
5018 * having one too much is no big deal because the scheduler tick updates
5019 * statistics and checks timeslices in a time-independent way, regardless
5020 * of when exactly it is running.
5021 */
488603b8 5022 if (!tick_nohz_tick_stopped_cpu(cpu))
d9c0ffca 5023 goto out_requeue;
d84b3131 5024
d9c0ffca
FW
5025 rq_lock_irq(rq, &rf);
5026 curr = rq->curr;
488603b8 5027 if (cpu_is_offline(cpu))
d9c0ffca 5028 goto out_unlock;
d84b3131 5029
d9c0ffca 5030 update_rq_clock(rq);
d9c0ffca 5031
488603b8
SW
5032 if (!is_idle_task(curr)) {
5033 /*
5034 * Make sure the next tick runs within a reasonable
5035 * amount of time.
5036 */
5037 delta = rq_clock_task(rq) - curr->se.exec_start;
5038 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
5039 }
d9c0ffca
FW
5040 curr->sched_class->task_tick(rq, curr, 0);
5041
ebc0f83c 5042 calc_load_nohz_remote(rq);
d9c0ffca
FW
5043out_unlock:
5044 rq_unlock_irq(rq, &rf);
d9c0ffca 5045out_requeue:
ebc0f83c 5046
d84b3131
FW
5047 /*
5048 * Run the remote tick once per second (1Hz). This arbitrary
5049 * frequency is large enough to avoid overload but short enough
b55bd585
PM
5050 * to keep scheduler internal stats reasonably up to date. But
5051 * first update state to reflect hotplug activity if required.
d84b3131 5052 */
b55bd585
PM
5053 os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
5054 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
5055 if (os == TICK_SCHED_REMOTE_RUNNING)
5056 queue_delayed_work(system_unbound_wq, dwork, HZ);
d84b3131
FW
5057}
5058
5059static void sched_tick_start(int cpu)
5060{
b55bd585 5061 int os;
d84b3131
FW
5062 struct tick_work *twork;
5063
5064 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
5065 return;
5066
5067 WARN_ON_ONCE(!tick_work_cpu);
5068
5069 twork = per_cpu_ptr(tick_work_cpu, cpu);
b55bd585
PM
5070 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
5071 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
5072 if (os == TICK_SCHED_REMOTE_OFFLINE) {
5073 twork->cpu = cpu;
5074 INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
5075 queue_delayed_work(system_unbound_wq, &twork->work, HZ);
5076 }
d84b3131
FW
5077}
5078
5079#ifdef CONFIG_HOTPLUG_CPU
5080static void sched_tick_stop(int cpu)
5081{
5082 struct tick_work *twork;
b55bd585 5083 int os;
d84b3131
FW
5084
5085 if (housekeeping_cpu(cpu, HK_FLAG_TICK))
5086 return;
5087
5088 WARN_ON_ONCE(!tick_work_cpu);
5089
5090 twork = per_cpu_ptr(tick_work_cpu, cpu);
b55bd585
PM
5091 /* There cannot be competing actions, but don't rely on stop-machine. */
5092 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
5093 WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
5094 /* Don't cancel, as this would mess up the state machine. */
d84b3131
FW
5095}
5096#endif /* CONFIG_HOTPLUG_CPU */
5097
5098int __init sched_tick_offload_init(void)
5099{
5100 tick_work_cpu = alloc_percpu(struct tick_work);
5101 BUG_ON(!tick_work_cpu);
d84b3131
FW
5102 return 0;
5103}
5104
5105#else /* !CONFIG_NO_HZ_FULL */
5106static inline void sched_tick_start(int cpu) { }
5107static inline void sched_tick_stop(int cpu) { }
265f22a9 5108#endif
1da177e4 5109
c1a280b6 5110#if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
c3bc8fd6 5111 defined(CONFIG_TRACE_PREEMPT_TOGGLE))
47252cfb
SR
5112/*
5113 * If the value passed in is equal to the current preempt count
5114 * then we just disabled preemption. Start timing the latency.
5115 */
5116static inline void preempt_latency_start(int val)
5117{
5118 if (preempt_count() == val) {
5119 unsigned long ip = get_lock_parent_ip();
5120#ifdef CONFIG_DEBUG_PREEMPT
5121 current->preempt_disable_ip = ip;
5122#endif
5123 trace_preempt_off(CALLER_ADDR0, ip);
5124 }
5125}
7e49fcce 5126
edafe3a5 5127void preempt_count_add(int val)
1da177e4 5128{
6cd8a4bb 5129#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
5130 /*
5131 * Underflow?
5132 */
9a11b49a
IM
5133 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5134 return;
6cd8a4bb 5135#endif
bdb43806 5136 __preempt_count_add(val);
6cd8a4bb 5137#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
5138 /*
5139 * Spinlock count overflowing soon?
5140 */
33859f7f
MOS
5141 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5142 PREEMPT_MASK - 10);
6cd8a4bb 5143#endif
47252cfb 5144 preempt_latency_start(val);
1da177e4 5145}
bdb43806 5146EXPORT_SYMBOL(preempt_count_add);
edafe3a5 5147NOKPROBE_SYMBOL(preempt_count_add);
1da177e4 5148
47252cfb
SR
5149/*
5150 * If the value passed in equals to the current preempt count
5151 * then we just enabled preemption. Stop timing the latency.
5152 */
5153static inline void preempt_latency_stop(int val)
5154{
5155 if (preempt_count() == val)
5156 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
5157}
5158
edafe3a5 5159void preempt_count_sub(int val)
1da177e4 5160{
6cd8a4bb 5161#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
5162 /*
5163 * Underflow?
5164 */
01e3eb82 5165 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
9a11b49a 5166 return;
1da177e4
LT
5167 /*
5168 * Is the spinlock portion underflowing?
5169 */
9a11b49a
IM
5170 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5171 !(preempt_count() & PREEMPT_MASK)))
5172 return;
6cd8a4bb 5173#endif
9a11b49a 5174
47252cfb 5175 preempt_latency_stop(val);
bdb43806 5176 __preempt_count_sub(val);
1da177e4 5177}
bdb43806 5178EXPORT_SYMBOL(preempt_count_sub);
edafe3a5 5179NOKPROBE_SYMBOL(preempt_count_sub);
1da177e4 5180
47252cfb
SR
5181#else
5182static inline void preempt_latency_start(int val) { }
5183static inline void preempt_latency_stop(int val) { }
1da177e4
LT
5184#endif
5185
59ddbcb2
IM
5186static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
5187{
5188#ifdef CONFIG_DEBUG_PREEMPT
5189 return p->preempt_disable_ip;
5190#else
5191 return 0;
5192#endif
5193}
5194
1da177e4 5195/*
dd41f596 5196 * Print scheduling while atomic bug:
1da177e4 5197 */
dd41f596 5198static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 5199{
d1c6d149
VN
5200 /* Save this before calling printk(), since that will clobber it */
5201 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
5202
664dfa65
DJ
5203 if (oops_in_progress)
5204 return;
5205
3df0fc5b
PZ
5206 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
5207 prev->comm, prev->pid, preempt_count());
838225b4 5208
dd41f596 5209 debug_show_held_locks(prev);
e21f5b15 5210 print_modules();
dd41f596
IM
5211 if (irqs_disabled())
5212 print_irqtrace_events(prev);
d1c6d149
VN
5213 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
5214 && in_atomic_preempt_off()) {
8f47b187 5215 pr_err("Preemption disabled at:");
2062a4e8 5216 print_ip_sym(KERN_ERR, preempt_disable_ip);
8f47b187 5217 }
748c7201
DBO
5218 if (panic_on_warn)
5219 panic("scheduling while atomic\n");
5220
6135fc1e 5221 dump_stack();
373d4d09 5222 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
dd41f596 5223}
1da177e4 5224
dd41f596
IM
5225/*
5226 * Various schedule()-time debugging checks and statistics:
5227 */
312364f3 5228static inline void schedule_debug(struct task_struct *prev, bool preempt)
dd41f596 5229{
0d9e2632 5230#ifdef CONFIG_SCHED_STACK_END_CHECK
29d64551
JH
5231 if (task_stack_end_corrupted(prev))
5232 panic("corrupted stack end detected inside scheduler\n");
88485be5
WD
5233
5234 if (task_scs_end_corrupted(prev))
5235 panic("corrupted shadow stack detected inside scheduler\n");
0d9e2632 5236#endif
b99def8b 5237
312364f3
DV
5238#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
5239 if (!preempt && prev->state && prev->non_block_count) {
5240 printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
5241 prev->comm, prev->pid, prev->non_block_count);
5242 dump_stack();
5243 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
5244 }
5245#endif
5246
1dc0fffc 5247 if (unlikely(in_atomic_preempt_off())) {
dd41f596 5248 __schedule_bug(prev);
1dc0fffc
PZ
5249 preempt_count_set(PREEMPT_DISABLED);
5250 }
b3fbab05 5251 rcu_sleep_check();
9f68b5b7 5252 SCHED_WARN_ON(ct_state() == CONTEXT_USER);
dd41f596 5253
1da177e4
LT
5254 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5255
ae92882e 5256 schedstat_inc(this_rq()->sched_count);
dd41f596
IM
5257}
5258
457d1f46
CY
5259static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
5260 struct rq_flags *rf)
5261{
5262#ifdef CONFIG_SMP
5263 const struct sched_class *class;
5264 /*
5265 * We must do the balancing pass before put_prev_task(), such
5266 * that when we release the rq->lock the task is in the same
5267 * state as before we took rq->lock.
5268 *
5269 * We can terminate the balance pass as soon as we know there is
5270 * a runnable task of @class priority or higher.
5271 */
5272 for_class_range(class, prev->sched_class, &idle_sched_class) {
5273 if (class->balance(rq, prev, rf))
5274 break;
5275 }
5276#endif
5277
5278 put_prev_task(rq, prev);
5279}
5280
dd41f596
IM
5281/*
5282 * Pick up the highest-prio task:
5283 */
5284static inline struct task_struct *
539f6512 5285__pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
dd41f596 5286{
49ee5768 5287 const struct sched_class *class;
dd41f596 5288 struct task_struct *p;
1da177e4
LT
5289
5290 /*
0ba87bb2
PZ
5291 * Optimization: we know that if all tasks are in the fair class we can
5292 * call that function directly, but only if the @prev task wasn't of a
b19a888c 5293 * higher scheduling class, because otherwise those lose the
0ba87bb2 5294 * opportunity to pull in more work from other CPUs.
1da177e4 5295 */
aa93cd53 5296 if (likely(prev->sched_class <= &fair_sched_class &&
0ba87bb2
PZ
5297 rq->nr_running == rq->cfs.h_nr_running)) {
5298
5d7d6056 5299 p = pick_next_task_fair(rq, prev, rf);
6ccdc84b 5300 if (unlikely(p == RETRY_TASK))
67692435 5301 goto restart;
6ccdc84b 5302
d1ccc66d 5303 /* Assumes fair_sched_class->next == idle_sched_class */
5d7d6056 5304 if (!p) {
f488e105 5305 put_prev_task(rq, prev);
98c2f700 5306 p = pick_next_task_idle(rq);
f488e105 5307 }
6ccdc84b
PZ
5308
5309 return p;
1da177e4
LT
5310 }
5311
67692435 5312restart:
457d1f46 5313 put_prev_task_balance(rq, prev, rf);
67692435 5314
34f971f6 5315 for_each_class(class) {
98c2f700 5316 p = class->pick_next_task(rq);
67692435 5317 if (p)
dd41f596 5318 return p;
dd41f596 5319 }
34f971f6 5320
d1ccc66d
IM
5321 /* The idle class should always have a runnable task: */
5322 BUG();
dd41f596 5323}
1da177e4 5324
9edeaea1 5325#ifdef CONFIG_SCHED_CORE
539f6512
PZ
5326static inline bool is_task_rq_idle(struct task_struct *t)
5327{
5328 return (task_rq(t)->idle == t);
5329}
5330
5331static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
5332{
5333 return is_task_rq_idle(a) || (a->core_cookie == cookie);
5334}
5335
5336static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
5337{
5338 if (is_task_rq_idle(a) || is_task_rq_idle(b))
5339 return true;
5340
5341 return a->core_cookie == b->core_cookie;
5342}
5343
5344// XXX fairness/fwd progress conditions
5345/*
5346 * Returns
5347 * - NULL if there is no runnable task for this class.
5348 * - the highest priority task for this runqueue if it matches
5349 * rq->core->core_cookie or its priority is greater than max.
5350 * - Else returns idle_task.
5351 */
5352static struct task_struct *
5353pick_task(struct rq *rq, const struct sched_class *class, struct task_struct *max)
5354{
5355 struct task_struct *class_pick, *cookie_pick;
5356 unsigned long cookie = rq->core->core_cookie;
5357
5358 class_pick = class->pick_task(rq);
5359 if (!class_pick)
5360 return NULL;
5361
5362 if (!cookie) {
5363 /*
5364 * If class_pick is tagged, return it only if it has
5365 * higher priority than max.
5366 */
5367 if (max && class_pick->core_cookie &&
5368 prio_less(class_pick, max))
5369 return idle_sched_class.pick_task(rq);
5370
5371 return class_pick;
5372 }
5373
5374 /*
5375 * If class_pick is idle or matches cookie, return early.
5376 */
5377 if (cookie_equals(class_pick, cookie))
5378 return class_pick;
5379
5380 cookie_pick = sched_core_find(rq, cookie);
5381
5382 /*
5383 * If class > max && class > cookie, it is the highest priority task on
5384 * the core (so far) and it must be selected, otherwise we must go with
5385 * the cookie pick in order to satisfy the constraint.
5386 */
5387 if (prio_less(cookie_pick, class_pick) &&
5388 (!max || prio_less(max, class_pick)))
5389 return class_pick;
5390
5391 return cookie_pick;
5392}
5393
5394static struct task_struct *
5395pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5396{
5397 struct task_struct *next, *max = NULL;
5398 const struct sched_class *class;
5399 const struct cpumask *smt_mask;
5400 bool need_sync;
5401 int i, j, cpu;
5402
5403 if (!sched_core_enabled(rq))
5404 return __pick_next_task(rq, prev, rf);
5405
5406 cpu = cpu_of(rq);
5407
5408 /* Stopper task is switching into idle, no need core-wide selection. */
5409 if (cpu_is_offline(cpu)) {
5410 /*
5411 * Reset core_pick so that we don't enter the fastpath when
5412 * coming online. core_pick would already be migrated to
5413 * another cpu during offline.
5414 */
5415 rq->core_pick = NULL;
5416 return __pick_next_task(rq, prev, rf);
5417 }
5418
5419 /*
5420 * If there were no {en,de}queues since we picked (IOW, the task
5421 * pointers are all still valid), and we haven't scheduled the last
5422 * pick yet, do so now.
5423 *
5424 * rq->core_pick can be NULL if no selection was made for a CPU because
5425 * it was either offline or went offline during a sibling's core-wide
5426 * selection. In this case, do a core-wide selection.
5427 */
5428 if (rq->core->core_pick_seq == rq->core->core_task_seq &&
5429 rq->core->core_pick_seq != rq->core_sched_seq &&
5430 rq->core_pick) {
5431 WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
5432
5433 next = rq->core_pick;
5434 if (next != prev) {
5435 put_prev_task(rq, prev);
5436 set_next_task(rq, next);
5437 }
5438
5439 rq->core_pick = NULL;
5440 return next;
5441 }
5442
5443 put_prev_task_balance(rq, prev, rf);
5444
5445 smt_mask = cpu_smt_mask(cpu);
7afbba11
JFG
5446 need_sync = !!rq->core->core_cookie;
5447
5448 /* reset state */
5449 rq->core->core_cookie = 0UL;
5450 if (rq->core->core_forceidle) {
5451 need_sync = true;
5452 fi_before = true;
5453 rq->core->core_forceidle = false;
5454 }
539f6512
PZ
5455
5456 /*
5457 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
5458 *
5459 * @task_seq guards the task state ({en,de}queues)
5460 * @pick_seq is the @task_seq we did a selection on
5461 * @sched_seq is the @pick_seq we scheduled
5462 *
5463 * However, preemptions can cause multiple picks on the same task set.
5464 * 'Fix' this by also increasing @task_seq for every pick.
5465 */
5466 rq->core->core_task_seq++;
539f6512 5467
7afbba11
JFG
5468 /*
5469 * Optimize for common case where this CPU has no cookies
5470 * and there are no cookied tasks running on siblings.
5471 */
5472 if (!need_sync) {
5473 for_each_class(class) {
5474 next = class->pick_task(rq);
5475 if (next)
5476 break;
5477 }
5478
5479 if (!next->core_cookie) {
5480 rq->core_pick = NULL;
5481 goto done;
5482 }
8039e96f 5483 need_sync = true;
8039e96f 5484 }
7afbba11 5485
539f6512
PZ
5486 for_each_cpu(i, smt_mask) {
5487 struct rq *rq_i = cpu_rq(i);
5488
5489 rq_i->core_pick = NULL;
5490
539f6512
PZ
5491 if (i != cpu)
5492 update_rq_clock(rq_i);
5493 }
5494
5495 /*
5496 * Try and select tasks for each sibling in decending sched_class
5497 * order.
5498 */
5499 for_each_class(class) {
5500again:
5501 for_each_cpu_wrap(i, smt_mask, cpu) {
5502 struct rq *rq_i = cpu_rq(i);
5503 struct task_struct *p;
5504
5505 if (rq_i->core_pick)
5506 continue;
5507
5508 /*
5509 * If this sibling doesn't yet have a suitable task to
5510 * run; ask for the most elegible task, given the
5511 * highest priority task already selected for this
5512 * core.
5513 */
5514 p = pick_task(rq_i, class, max);
7afbba11 5515 if (!p)
539f6512 5516 continue;
539f6512
PZ
5517
5518 rq_i->core_pick = p;
5519
5520 /*
5521 * If this new candidate is of higher priority than the
5522 * previous; and they're incompatible; we need to wipe
5523 * the slate and start over. pick_task makes sure that
5524 * p's priority is more than max if it doesn't match
5525 * max's cookie.
5526 *
5527 * NOTE: this is a linear max-filter and is thus bounded
5528 * in execution time.
5529 */
5530 if (!max || !cookie_match(max, p)) {
5531 struct task_struct *old_max = max;
5532
5533 rq->core->core_cookie = p->core_cookie;
5534 max = p;
5535
5536 if (old_max) {
5537 for_each_cpu(j, smt_mask) {
5538 if (j == i)
5539 continue;
5540
5541 cpu_rq(j)->core_pick = NULL;
5542 }
5543 goto again;
539f6512 5544 }
539f6512
PZ
5545 }
5546 }
539f6512
PZ
5547 }
5548
5549 rq->core->core_pick_seq = rq->core->core_task_seq;
5550 next = rq->core_pick;
5551 rq->core_sched_seq = rq->core->core_pick_seq;
5552
5553 /* Something should have been selected for current CPU */
5554 WARN_ON_ONCE(!next);
5555
5556 /*
5557 * Reschedule siblings
5558 *
5559 * NOTE: L1TF -- at this point we're no longer running the old task and
5560 * sending an IPI (below) ensures the sibling will no longer be running
5561 * their task. This ensures there is no inter-sibling overlap between
5562 * non-matching user state.
5563 */
5564 for_each_cpu(i, smt_mask) {
5565 struct rq *rq_i = cpu_rq(i);
5566
5567 /*
5568 * An online sibling might have gone offline before a task
5569 * could be picked for it, or it might be offline but later
5570 * happen to come online, but its too late and nothing was
5571 * picked for it. That's Ok - it will pick tasks for itself,
5572 * so ignore it.
5573 */
5574 if (!rq_i->core_pick)
5575 continue;
5576
8039e96f
VP
5577 if (is_task_rq_idle(rq_i->core_pick) && rq_i->nr_running &&
5578 !rq_i->core->core_forceidle) {
5579 rq_i->core->core_forceidle = true;
5580 }
539f6512
PZ
5581
5582 if (i == cpu) {
5583 rq_i->core_pick = NULL;
5584 continue;
5585 }
5586
5587 /* Did we break L1TF mitigation requirements? */
5588 WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
5589
5590 if (rq_i->curr == rq_i->core_pick) {
5591 rq_i->core_pick = NULL;
5592 continue;
5593 }
5594
5595 resched_curr(rq_i);
5596 }
5597
5598done:
5599 set_next_task(rq, next);
5600 return next;
5601}
9edeaea1
PZ
5602
5603static inline void sched_core_cpu_starting(unsigned int cpu)
5604{
5605 const struct cpumask *smt_mask = cpu_smt_mask(cpu);
5606 struct rq *rq, *core_rq = NULL;
5607 int i;
5608
5609 core_rq = cpu_rq(cpu)->core;
5610
5611 if (!core_rq) {
5612 for_each_cpu(i, smt_mask) {
5613 rq = cpu_rq(i);
5614 if (rq->core && rq->core == rq)
5615 core_rq = rq;
5616 }
5617
5618 if (!core_rq)
5619 core_rq = cpu_rq(cpu);
5620
5621 for_each_cpu(i, smt_mask) {
5622 rq = cpu_rq(i);
5623
5624 WARN_ON_ONCE(rq->core && rq->core != core_rq);
5625 rq->core = core_rq;
5626 }
5627 }
5628}
5629#else /* !CONFIG_SCHED_CORE */
5630
5631static inline void sched_core_cpu_starting(unsigned int cpu) {}
5632
539f6512
PZ
5633static struct task_struct *
5634pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
5635{
5636 return __pick_next_task(rq, prev, rf);
5637}
5638
9edeaea1
PZ
5639#endif /* CONFIG_SCHED_CORE */
5640
dd41f596 5641/*
c259e01a 5642 * __schedule() is the main scheduler function.
edde96ea
PE
5643 *
5644 * The main means of driving the scheduler and thus entering this function are:
5645 *
5646 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
5647 *
5648 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
5649 * paths. For example, see arch/x86/entry_64.S.
5650 *
5651 * To drive preemption between tasks, the scheduler sets the flag in timer
5652 * interrupt handler scheduler_tick().
5653 *
5654 * 3. Wakeups don't really cause entry into schedule(). They add a
5655 * task to the run-queue and that's it.
5656 *
5657 * Now, if the new task added to the run-queue preempts the current
5658 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
5659 * called on the nearest possible occasion:
5660 *
c1a280b6 5661 * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
edde96ea
PE
5662 *
5663 * - in syscall or exception context, at the next outmost
5664 * preempt_enable(). (this might be as soon as the wake_up()'s
5665 * spin_unlock()!)
5666 *
5667 * - in IRQ context, return from interrupt-handler to
5668 * preemptible context
5669 *
c1a280b6 5670 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
edde96ea
PE
5671 * then at the next:
5672 *
5673 * - cond_resched() call
5674 * - explicit schedule() call
5675 * - return from syscall or exception to user-space
5676 * - return from interrupt-handler to user-space
bfd9b2b5 5677 *
b30f0e3f 5678 * WARNING: must be called with preemption disabled!
dd41f596 5679 */
499d7955 5680static void __sched notrace __schedule(bool preempt)
dd41f596
IM
5681{
5682 struct task_struct *prev, *next;
67ca7bde 5683 unsigned long *switch_count;
dbfb089d 5684 unsigned long prev_state;
d8ac8971 5685 struct rq_flags rf;
dd41f596 5686 struct rq *rq;
31656519 5687 int cpu;
dd41f596 5688
dd41f596
IM
5689 cpu = smp_processor_id();
5690 rq = cpu_rq(cpu);
dd41f596 5691 prev = rq->curr;
dd41f596 5692
312364f3 5693 schedule_debug(prev, preempt);
1da177e4 5694
e0ee463c 5695 if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
f333fdc9 5696 hrtick_clear(rq);
8f4d37ec 5697
46a5d164 5698 local_irq_disable();
bcbfdd01 5699 rcu_note_context_switch(preempt);
46a5d164 5700
e0acd0a6
ON
5701 /*
5702 * Make sure that signal_pending_state()->signal_pending() below
5703 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
dbfb089d
PZ
5704 * done by the caller to avoid the race with signal_wake_up():
5705 *
5706 * __set_current_state(@state) signal_wake_up()
5707 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
5708 * wake_up_state(p, state)
5709 * LOCK rq->lock LOCK p->pi_state
5710 * smp_mb__after_spinlock() smp_mb__after_spinlock()
5711 * if (signal_pending_state()) if (p->state & @state)
306e0604 5712 *
dbfb089d 5713 * Also, the membarrier system call requires a full memory barrier
306e0604 5714 * after coming from user-space, before storing to rq->curr.
e0acd0a6 5715 */
8a8c69c3 5716 rq_lock(rq, &rf);
d89e588c 5717 smp_mb__after_spinlock();
1da177e4 5718
d1ccc66d
IM
5719 /* Promote REQ to ACT */
5720 rq->clock_update_flags <<= 1;
bce4dc80 5721 update_rq_clock(rq);
9edfbfed 5722
246d86b5 5723 switch_count = &prev->nivcsw;
d136122f 5724
dbfb089d 5725 /*
d136122f
PZ
5726 * We must load prev->state once (task_struct::state is volatile), such
5727 * that:
5728 *
5729 * - we form a control dependency vs deactivate_task() below.
5730 * - ptrace_{,un}freeze_traced() can change ->state underneath us.
dbfb089d 5731 */
d136122f
PZ
5732 prev_state = prev->state;
5733 if (!preempt && prev_state) {
dbfb089d 5734 if (signal_pending_state(prev_state, prev)) {
1da177e4 5735 prev->state = TASK_RUNNING;
21aa9af0 5736 } else {
dbfb089d
PZ
5737 prev->sched_contributes_to_load =
5738 (prev_state & TASK_UNINTERRUPTIBLE) &&
5739 !(prev_state & TASK_NOLOAD) &&
5740 !(prev->flags & PF_FROZEN);
5741
5742 if (prev->sched_contributes_to_load)
5743 rq->nr_uninterruptible++;
5744
5745 /*
5746 * __schedule() ttwu()
d136122f
PZ
5747 * prev_state = prev->state; if (p->on_rq && ...)
5748 * if (prev_state) goto out;
5749 * p->on_rq = 0; smp_acquire__after_ctrl_dep();
5750 * p->state = TASK_WAKING
5751 *
5752 * Where __schedule() and ttwu() have matching control dependencies.
dbfb089d
PZ
5753 *
5754 * After this, schedule() must not care about p->state any more.
5755 */
bce4dc80 5756 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
2acca55e 5757
e33a9bba
TH
5758 if (prev->in_iowait) {
5759 atomic_inc(&rq->nr_iowait);
5760 delayacct_blkio_start();
5761 }
21aa9af0 5762 }
dd41f596 5763 switch_count = &prev->nvcsw;
1da177e4
LT
5764 }
5765
d8ac8971 5766 next = pick_next_task(rq, prev, &rf);
f26f9aff 5767 clear_tsk_need_resched(prev);
f27dde8d 5768 clear_preempt_need_resched();
c006fac5
PT
5769#ifdef CONFIG_SCHED_DEBUG
5770 rq->last_seen_need_resched_ns = 0;
5771#endif
1da177e4 5772
1da177e4 5773 if (likely(prev != next)) {
1da177e4 5774 rq->nr_switches++;
5311a98f
EB
5775 /*
5776 * RCU users of rcu_dereference(rq->curr) may not see
5777 * changes to task_struct made by pick_next_task().
5778 */
5779 RCU_INIT_POINTER(rq->curr, next);
22e4ebb9
MD
5780 /*
5781 * The membarrier system call requires each architecture
5782 * to have a full memory barrier after updating
306e0604
MD
5783 * rq->curr, before returning to user-space.
5784 *
5785 * Here are the schemes providing that barrier on the
5786 * various architectures:
5787 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
5788 * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
5789 * - finish_lock_switch() for weakly-ordered
5790 * architectures where spin_unlock is a full barrier,
5791 * - switch_to() for arm64 (weakly-ordered, spin_unlock
5792 * is a RELEASE barrier),
22e4ebb9 5793 */
1da177e4
LT
5794 ++*switch_count;
5795
af449901 5796 migrate_disable_switch(rq, prev);
b05e75d6
JW
5797 psi_sched_switch(prev, next, !task_on_rq_queued(prev));
5798
c73464b1 5799 trace_sched_switch(preempt, prev, next);
d1ccc66d
IM
5800
5801 /* Also unlocks the rq: */
5802 rq = context_switch(rq, prev, next, &rf);
cbce1a68 5803 } else {
cb42c9a3 5804 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
1da177e4 5805
565790d2
PZ
5806 rq_unpin_lock(rq, &rf);
5807 __balance_callbacks(rq);
5cb9eaa3 5808 raw_spin_rq_unlock_irq(rq);
565790d2 5809 }
1da177e4 5810}
c259e01a 5811
9af6528e
PZ
5812void __noreturn do_task_dead(void)
5813{
d1ccc66d 5814 /* Causes final put_task_struct in finish_task_switch(): */
b5bf9a90 5815 set_special_state(TASK_DEAD);
d1ccc66d
IM
5816
5817 /* Tell freezer to ignore us: */
5818 current->flags |= PF_NOFREEZE;
5819
9af6528e
PZ
5820 __schedule(false);
5821 BUG();
d1ccc66d
IM
5822
5823 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
9af6528e 5824 for (;;)
d1ccc66d 5825 cpu_relax();
9af6528e
PZ
5826}
5827
9c40cef2
TG
5828static inline void sched_submit_work(struct task_struct *tsk)
5829{
c1cecf88
SAS
5830 unsigned int task_flags;
5831
b0fdc013 5832 if (!tsk->state)
9c40cef2 5833 return;
6d25be57 5834
c1cecf88 5835 task_flags = tsk->flags;
6d25be57
TG
5836 /*
5837 * If a worker went to sleep, notify and ask workqueue whether
5838 * it wants to wake up a task to maintain concurrency.
5839 * As this function is called inside the schedule() context,
5840 * we disable preemption to avoid it calling schedule() again
62849a96
SAS
5841 * in the possible wakeup of a kworker and because wq_worker_sleeping()
5842 * requires it.
6d25be57 5843 */
c1cecf88 5844 if (task_flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
6d25be57 5845 preempt_disable();
c1cecf88 5846 if (task_flags & PF_WQ_WORKER)
771b53d0
JA
5847 wq_worker_sleeping(tsk);
5848 else
5849 io_wq_worker_sleeping(tsk);
6d25be57
TG
5850 preempt_enable_no_resched();
5851 }
5852
b0fdc013
SAS
5853 if (tsk_is_pi_blocked(tsk))
5854 return;
5855
9c40cef2
TG
5856 /*
5857 * If we are going to sleep and we have plugged IO queued,
5858 * make sure to submit it to avoid deadlocks.
5859 */
5860 if (blk_needs_flush_plug(tsk))
5861 blk_schedule_flush_plug(tsk);
5862}
5863
6d25be57
TG
5864static void sched_update_worker(struct task_struct *tsk)
5865{
771b53d0
JA
5866 if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
5867 if (tsk->flags & PF_WQ_WORKER)
5868 wq_worker_running(tsk);
5869 else
5870 io_wq_worker_running(tsk);
5871 }
6d25be57
TG
5872}
5873
722a9f92 5874asmlinkage __visible void __sched schedule(void)
c259e01a 5875{
9c40cef2
TG
5876 struct task_struct *tsk = current;
5877
5878 sched_submit_work(tsk);
bfd9b2b5 5879 do {
b30f0e3f 5880 preempt_disable();
fc13aeba 5881 __schedule(false);
b30f0e3f 5882 sched_preempt_enable_no_resched();
bfd9b2b5 5883 } while (need_resched());
6d25be57 5884 sched_update_worker(tsk);
c259e01a 5885}
1da177e4
LT
5886EXPORT_SYMBOL(schedule);
5887
8663effb
SRV
5888/*
5889 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
5890 * state (have scheduled out non-voluntarily) by making sure that all
5891 * tasks have either left the run queue or have gone into user space.
5892 * As idle tasks do not do either, they must not ever be preempted
5893 * (schedule out non-voluntarily).
5894 *
5895 * schedule_idle() is similar to schedule_preempt_disable() except that it
5896 * never enables preemption because it does not call sched_submit_work().
5897 */
5898void __sched schedule_idle(void)
5899{
5900 /*
5901 * As this skips calling sched_submit_work(), which the idle task does
5902 * regardless because that function is a nop when the task is in a
5903 * TASK_RUNNING state, make sure this isn't used someplace that the
5904 * current task can be in any other state. Note, idle is always in the
5905 * TASK_RUNNING state.
5906 */
5907 WARN_ON_ONCE(current->state);
5908 do {
5909 __schedule(false);
5910 } while (need_resched());
5911}
5912
6775de49 5913#if defined(CONFIG_CONTEXT_TRACKING) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_OFFSTACK)
722a9f92 5914asmlinkage __visible void __sched schedule_user(void)
20ab65e3
FW
5915{
5916 /*
5917 * If we come here after a random call to set_need_resched(),
5918 * or we have been woken up remotely but the IPI has not yet arrived,
5919 * we haven't yet exited the RCU idle mode. Do it here manually until
5920 * we find a better solution.
7cc78f8f
AL
5921 *
5922 * NB: There are buggy callers of this function. Ideally we
c467ea76 5923 * should warn if prev_state != CONTEXT_USER, but that will trigger
7cc78f8f 5924 * too frequently to make sense yet.
20ab65e3 5925 */
7cc78f8f 5926 enum ctx_state prev_state = exception_enter();
20ab65e3 5927 schedule();
7cc78f8f 5928 exception_exit(prev_state);
20ab65e3
FW
5929}
5930#endif
5931
c5491ea7
TG
5932/**
5933 * schedule_preempt_disabled - called with preemption disabled
5934 *
5935 * Returns with preemption disabled. Note: preempt_count must be 1
5936 */
5937void __sched schedule_preempt_disabled(void)
5938{
ba74c144 5939 sched_preempt_enable_no_resched();
c5491ea7
TG
5940 schedule();
5941 preempt_disable();
5942}
5943
06b1f808 5944static void __sched notrace preempt_schedule_common(void)
a18b5d01
FW
5945{
5946 do {
47252cfb
SR
5947 /*
5948 * Because the function tracer can trace preempt_count_sub()
5949 * and it also uses preempt_enable/disable_notrace(), if
5950 * NEED_RESCHED is set, the preempt_enable_notrace() called
5951 * by the function tracer will call this function again and
5952 * cause infinite recursion.
5953 *
5954 * Preemption must be disabled here before the function
5955 * tracer can trace. Break up preempt_disable() into two
5956 * calls. One to disable preemption without fear of being
5957 * traced. The other to still record the preemption latency,
5958 * which can also be traced by the function tracer.
5959 */
499d7955 5960 preempt_disable_notrace();
47252cfb 5961 preempt_latency_start(1);
fc13aeba 5962 __schedule(true);
47252cfb 5963 preempt_latency_stop(1);
499d7955 5964 preempt_enable_no_resched_notrace();
a18b5d01
FW
5965
5966 /*
5967 * Check again in case we missed a preemption opportunity
5968 * between schedule and now.
5969 */
a18b5d01
FW
5970 } while (need_resched());
5971}
5972
c1a280b6 5973#ifdef CONFIG_PREEMPTION
1da177e4 5974/*
a49b4f40
VS
5975 * This is the entry point to schedule() from in-kernel preemption
5976 * off of preempt_enable.
1da177e4 5977 */
722a9f92 5978asmlinkage __visible void __sched notrace preempt_schedule(void)
1da177e4 5979{
1da177e4
LT
5980 /*
5981 * If there is a non-zero preempt_count or interrupts are disabled,
41a2d6cf 5982 * we do not want to preempt the current task. Just return..
1da177e4 5983 */
fbb00b56 5984 if (likely(!preemptible()))
1da177e4
LT
5985 return;
5986
a18b5d01 5987 preempt_schedule_common();
1da177e4 5988}
376e2424 5989NOKPROBE_SYMBOL(preempt_schedule);
1da177e4 5990EXPORT_SYMBOL(preempt_schedule);
009f60e2 5991
2c9a98d3
PZI
5992#ifdef CONFIG_PREEMPT_DYNAMIC
5993DEFINE_STATIC_CALL(preempt_schedule, __preempt_schedule_func);
ef72661e 5994EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
2c9a98d3
PZI
5995#endif
5996
5997
009f60e2 5998/**
4eaca0a8 5999 * preempt_schedule_notrace - preempt_schedule called by tracing
009f60e2
ON
6000 *
6001 * The tracing infrastructure uses preempt_enable_notrace to prevent
6002 * recursion and tracing preempt enabling caused by the tracing
6003 * infrastructure itself. But as tracing can happen in areas coming
6004 * from userspace or just about to enter userspace, a preempt enable
6005 * can occur before user_exit() is called. This will cause the scheduler
6006 * to be called when the system is still in usermode.
6007 *
6008 * To prevent this, the preempt_enable_notrace will use this function
6009 * instead of preempt_schedule() to exit user context if needed before
6010 * calling the scheduler.
6011 */
4eaca0a8 6012asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
009f60e2
ON
6013{
6014 enum ctx_state prev_ctx;
6015
6016 if (likely(!preemptible()))
6017 return;
6018
6019 do {
47252cfb
SR
6020 /*
6021 * Because the function tracer can trace preempt_count_sub()
6022 * and it also uses preempt_enable/disable_notrace(), if
6023 * NEED_RESCHED is set, the preempt_enable_notrace() called
6024 * by the function tracer will call this function again and
6025 * cause infinite recursion.
6026 *
6027 * Preemption must be disabled here before the function
6028 * tracer can trace. Break up preempt_disable() into two
6029 * calls. One to disable preemption without fear of being
6030 * traced. The other to still record the preemption latency,
6031 * which can also be traced by the function tracer.
6032 */
3d8f74dd 6033 preempt_disable_notrace();
47252cfb 6034 preempt_latency_start(1);
009f60e2
ON
6035 /*
6036 * Needs preempt disabled in case user_exit() is traced
6037 * and the tracer calls preempt_enable_notrace() causing
6038 * an infinite recursion.
6039 */
6040 prev_ctx = exception_enter();
fc13aeba 6041 __schedule(true);
009f60e2
ON
6042 exception_exit(prev_ctx);
6043
47252cfb 6044 preempt_latency_stop(1);
3d8f74dd 6045 preempt_enable_no_resched_notrace();
009f60e2
ON
6046 } while (need_resched());
6047}
4eaca0a8 6048EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
009f60e2 6049
2c9a98d3
PZI
6050#ifdef CONFIG_PREEMPT_DYNAMIC
6051DEFINE_STATIC_CALL(preempt_schedule_notrace, __preempt_schedule_notrace_func);
ef72661e 6052EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
2c9a98d3
PZI
6053#endif
6054
c1a280b6 6055#endif /* CONFIG_PREEMPTION */
1da177e4 6056
826bfeb3
PZI
6057#ifdef CONFIG_PREEMPT_DYNAMIC
6058
6059#include <linux/entry-common.h>
6060
6061/*
6062 * SC:cond_resched
6063 * SC:might_resched
6064 * SC:preempt_schedule
6065 * SC:preempt_schedule_notrace
6066 * SC:irqentry_exit_cond_resched
6067 *
6068 *
6069 * NONE:
6070 * cond_resched <- __cond_resched
6071 * might_resched <- RET0
6072 * preempt_schedule <- NOP
6073 * preempt_schedule_notrace <- NOP
6074 * irqentry_exit_cond_resched <- NOP
6075 *
6076 * VOLUNTARY:
6077 * cond_resched <- __cond_resched
6078 * might_resched <- __cond_resched
6079 * preempt_schedule <- NOP
6080 * preempt_schedule_notrace <- NOP
6081 * irqentry_exit_cond_resched <- NOP
6082 *
6083 * FULL:
6084 * cond_resched <- RET0
6085 * might_resched <- RET0
6086 * preempt_schedule <- preempt_schedule
6087 * preempt_schedule_notrace <- preempt_schedule_notrace
6088 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched
6089 */
e59e10f8
PZ
6090
6091enum {
6092 preempt_dynamic_none = 0,
6093 preempt_dynamic_voluntary,
6094 preempt_dynamic_full,
6095};
6096
1011dcce 6097int preempt_dynamic_mode = preempt_dynamic_full;
e59e10f8 6098
1011dcce 6099int sched_dynamic_mode(const char *str)
826bfeb3 6100{
e59e10f8 6101 if (!strcmp(str, "none"))
7e1b2eb7 6102 return preempt_dynamic_none;
e59e10f8
PZ
6103
6104 if (!strcmp(str, "voluntary"))
7e1b2eb7 6105 return preempt_dynamic_voluntary;
e59e10f8
PZ
6106
6107 if (!strcmp(str, "full"))
7e1b2eb7 6108 return preempt_dynamic_full;
e59e10f8 6109
c4681f3f 6110 return -EINVAL;
e59e10f8
PZ
6111}
6112
1011dcce 6113void sched_dynamic_update(int mode)
e59e10f8
PZ
6114{
6115 /*
6116 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
6117 * the ZERO state, which is invalid.
6118 */
6119 static_call_update(cond_resched, __cond_resched);
6120 static_call_update(might_resched, __cond_resched);
6121 static_call_update(preempt_schedule, __preempt_schedule_func);
6122 static_call_update(preempt_schedule_notrace, __preempt_schedule_notrace_func);
6123 static_call_update(irqentry_exit_cond_resched, irqentry_exit_cond_resched);
6124
6125 switch (mode) {
6126 case preempt_dynamic_none:
826bfeb3 6127 static_call_update(cond_resched, __cond_resched);
9432bbd9
PZ
6128 static_call_update(might_resched, (void *)&__static_call_return0);
6129 static_call_update(preempt_schedule, NULL);
6130 static_call_update(preempt_schedule_notrace, NULL);
6131 static_call_update(irqentry_exit_cond_resched, NULL);
e59e10f8
PZ
6132 pr_info("Dynamic Preempt: none\n");
6133 break;
6134
6135 case preempt_dynamic_voluntary:
826bfeb3
PZI
6136 static_call_update(cond_resched, __cond_resched);
6137 static_call_update(might_resched, __cond_resched);
9432bbd9
PZ
6138 static_call_update(preempt_schedule, NULL);
6139 static_call_update(preempt_schedule_notrace, NULL);
6140 static_call_update(irqentry_exit_cond_resched, NULL);
e59e10f8
PZ
6141 pr_info("Dynamic Preempt: voluntary\n");
6142 break;
6143
6144 case preempt_dynamic_full:
9432bbd9
PZ
6145 static_call_update(cond_resched, (void *)&__static_call_return0);
6146 static_call_update(might_resched, (void *)&__static_call_return0);
826bfeb3
PZI
6147 static_call_update(preempt_schedule, __preempt_schedule_func);
6148 static_call_update(preempt_schedule_notrace, __preempt_schedule_notrace_func);
6149 static_call_update(irqentry_exit_cond_resched, irqentry_exit_cond_resched);
e59e10f8
PZ
6150 pr_info("Dynamic Preempt: full\n");
6151 break;
6152 }
6153
6154 preempt_dynamic_mode = mode;
6155}
6156
6157static int __init setup_preempt_mode(char *str)
6158{
6159 int mode = sched_dynamic_mode(str);
6160 if (mode < 0) {
6161 pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
826bfeb3
PZI
6162 return 1;
6163 }
e59e10f8
PZ
6164
6165 sched_dynamic_update(mode);
826bfeb3
PZI
6166 return 0;
6167}
6168__setup("preempt=", setup_preempt_mode);
6169
6170#endif /* CONFIG_PREEMPT_DYNAMIC */
6171
1da177e4 6172/*
a49b4f40 6173 * This is the entry point to schedule() from kernel preemption
1da177e4
LT
6174 * off of irq context.
6175 * Note, that this is called and return with irqs disabled. This will
6176 * protect us against recursive calling from irq.
6177 */
722a9f92 6178asmlinkage __visible void __sched preempt_schedule_irq(void)
1da177e4 6179{
b22366cd 6180 enum ctx_state prev_state;
6478d880 6181
2ed6e34f 6182 /* Catch callers which need to be fixed */
f27dde8d 6183 BUG_ON(preempt_count() || !irqs_disabled());
1da177e4 6184
b22366cd
FW
6185 prev_state = exception_enter();
6186
3a5c359a 6187 do {
3d8f74dd 6188 preempt_disable();
3a5c359a 6189 local_irq_enable();
fc13aeba 6190 __schedule(true);
3a5c359a 6191 local_irq_disable();
3d8f74dd 6192 sched_preempt_enable_no_resched();
5ed0cec0 6193 } while (need_resched());
b22366cd
FW
6194
6195 exception_exit(prev_state);
1da177e4
LT
6196}
6197
ac6424b9 6198int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
95cdf3b7 6199 void *key)
1da177e4 6200{
062d3f95 6201 WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~WF_SYNC);
63859d4f 6202 return try_to_wake_up(curr->private, mode, wake_flags);
1da177e4 6203}
1da177e4
LT
6204EXPORT_SYMBOL(default_wake_function);
6205
b29739f9
IM
6206#ifdef CONFIG_RT_MUTEXES
6207
acd58620
PZ
6208static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
6209{
6210 if (pi_task)
6211 prio = min(prio, pi_task->prio);
6212
6213 return prio;
6214}
6215
6216static inline int rt_effective_prio(struct task_struct *p, int prio)
6217{
6218 struct task_struct *pi_task = rt_mutex_get_top_task(p);
6219
6220 return __rt_effective_prio(pi_task, prio);
6221}
6222
b29739f9
IM
6223/*
6224 * rt_mutex_setprio - set the current priority of a task
acd58620
PZ
6225 * @p: task to boost
6226 * @pi_task: donor task
b29739f9
IM
6227 *
6228 * This function changes the 'effective' priority of a task. It does
6229 * not touch ->normal_prio like __setscheduler().
6230 *
c365c292
TG
6231 * Used by the rt_mutex code to implement priority inheritance
6232 * logic. Call site only calls if the priority of the task changed.
b29739f9 6233 */
acd58620 6234void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
b29739f9 6235{
acd58620 6236 int prio, oldprio, queued, running, queue_flag =
7a57f32a 6237 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
83ab0aa0 6238 const struct sched_class *prev_class;
eb580751
PZ
6239 struct rq_flags rf;
6240 struct rq *rq;
b29739f9 6241
acd58620
PZ
6242 /* XXX used to be waiter->prio, not waiter->task->prio */
6243 prio = __rt_effective_prio(pi_task, p->normal_prio);
6244
6245 /*
6246 * If nothing changed; bail early.
6247 */
6248 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
6249 return;
b29739f9 6250
eb580751 6251 rq = __task_rq_lock(p, &rf);
80f5c1b8 6252 update_rq_clock(rq);
acd58620
PZ
6253 /*
6254 * Set under pi_lock && rq->lock, such that the value can be used under
6255 * either lock.
6256 *
6257 * Note that there is loads of tricky to make this pointer cache work
6258 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
6259 * ensure a task is de-boosted (pi_task is set to NULL) before the
6260 * task is allowed to run again (and can exit). This ensures the pointer
b19a888c 6261 * points to a blocked task -- which guarantees the task is present.
acd58620
PZ
6262 */
6263 p->pi_top_task = pi_task;
6264
6265 /*
6266 * For FIFO/RR we only need to set prio, if that matches we're done.
6267 */
6268 if (prio == p->prio && !dl_prio(prio))
6269 goto out_unlock;
b29739f9 6270
1c4dd99b
TG
6271 /*
6272 * Idle task boosting is a nono in general. There is one
6273 * exception, when PREEMPT_RT and NOHZ is active:
6274 *
6275 * The idle task calls get_next_timer_interrupt() and holds
6276 * the timer wheel base->lock on the CPU and another CPU wants
6277 * to access the timer (probably to cancel it). We can safely
6278 * ignore the boosting request, as the idle CPU runs this code
6279 * with interrupts disabled and will complete the lock
6280 * protected section without being interrupted. So there is no
6281 * real need to boost.
6282 */
6283 if (unlikely(p == rq->idle)) {
6284 WARN_ON(p != rq->curr);
6285 WARN_ON(p->pi_blocked_on);
6286 goto out_unlock;
6287 }
6288
b91473ff 6289 trace_sched_pi_setprio(p, pi_task);
d5f9f942 6290 oldprio = p->prio;
ff77e468
PZ
6291
6292 if (oldprio == prio)
6293 queue_flag &= ~DEQUEUE_MOVE;
6294
83ab0aa0 6295 prev_class = p->sched_class;
da0c1e65 6296 queued = task_on_rq_queued(p);
051a1d1a 6297 running = task_current(rq, p);
da0c1e65 6298 if (queued)
ff77e468 6299 dequeue_task(rq, p, queue_flag);
0e1f3483 6300 if (running)
f3cd1c4e 6301 put_prev_task(rq, p);
dd41f596 6302
2d3d891d
DF
6303 /*
6304 * Boosting condition are:
6305 * 1. -rt task is running and holds mutex A
6306 * --> -dl task blocks on mutex A
6307 *
6308 * 2. -dl task is running and holds mutex A
6309 * --> -dl task blocks on mutex A and could preempt the
6310 * running task
6311 */
6312 if (dl_prio(prio)) {
466af29b 6313 if (!dl_prio(p->normal_prio) ||
740797ce
JL
6314 (pi_task && dl_prio(pi_task->prio) &&
6315 dl_entity_preempt(&pi_task->dl, &p->dl))) {
2279f540 6316 p->dl.pi_se = pi_task->dl.pi_se;
ff77e468 6317 queue_flag |= ENQUEUE_REPLENISH;
2279f540
JL
6318 } else {
6319 p->dl.pi_se = &p->dl;
6320 }
aab03e05 6321 p->sched_class = &dl_sched_class;
2d3d891d
DF
6322 } else if (rt_prio(prio)) {
6323 if (dl_prio(oldprio))
2279f540 6324 p->dl.pi_se = &p->dl;
2d3d891d 6325 if (oldprio < prio)
ff77e468 6326 queue_flag |= ENQUEUE_HEAD;
dd41f596 6327 p->sched_class = &rt_sched_class;
2d3d891d
DF
6328 } else {
6329 if (dl_prio(oldprio))
2279f540 6330 p->dl.pi_se = &p->dl;
746db944
BS
6331 if (rt_prio(oldprio))
6332 p->rt.timeout = 0;
dd41f596 6333 p->sched_class = &fair_sched_class;
2d3d891d 6334 }
dd41f596 6335
b29739f9
IM
6336 p->prio = prio;
6337
da0c1e65 6338 if (queued)
ff77e468 6339 enqueue_task(rq, p, queue_flag);
a399d233 6340 if (running)
03b7fad1 6341 set_next_task(rq, p);
cb469845 6342
da7a735e 6343 check_class_changed(rq, p, prev_class, oldprio);
1c4dd99b 6344out_unlock:
d1ccc66d
IM
6345 /* Avoid rq from going away on us: */
6346 preempt_disable();
4c9a4bc8 6347
565790d2
PZ
6348 rq_unpin_lock(rq, &rf);
6349 __balance_callbacks(rq);
5cb9eaa3 6350 raw_spin_rq_unlock(rq);
565790d2 6351
4c9a4bc8 6352 preempt_enable();
b29739f9 6353}
acd58620
PZ
6354#else
6355static inline int rt_effective_prio(struct task_struct *p, int prio)
6356{
6357 return prio;
6358}
b29739f9 6359#endif
d50dde5a 6360
36c8b586 6361void set_user_nice(struct task_struct *p, long nice)
1da177e4 6362{
49bd21ef 6363 bool queued, running;
53a23364 6364 int old_prio;
eb580751 6365 struct rq_flags rf;
70b97a7f 6366 struct rq *rq;
1da177e4 6367
75e45d51 6368 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
1da177e4
LT
6369 return;
6370 /*
6371 * We have to be careful, if called from sys_setpriority(),
6372 * the task might be in the middle of scheduling on another CPU.
6373 */
eb580751 6374 rq = task_rq_lock(p, &rf);
2fb8d367
PZ
6375 update_rq_clock(rq);
6376
1da177e4
LT
6377 /*
6378 * The RT priorities are set via sched_setscheduler(), but we still
6379 * allow the 'normal' nice value to be set - but as expected
b19a888c 6380 * it won't have any effect on scheduling until the task is
aab03e05 6381 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
1da177e4 6382 */
aab03e05 6383 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
1da177e4
LT
6384 p->static_prio = NICE_TO_PRIO(nice);
6385 goto out_unlock;
6386 }
da0c1e65 6387 queued = task_on_rq_queued(p);
49bd21ef 6388 running = task_current(rq, p);
da0c1e65 6389 if (queued)
7a57f32a 6390 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
49bd21ef
PZ
6391 if (running)
6392 put_prev_task(rq, p);
1da177e4 6393
1da177e4 6394 p->static_prio = NICE_TO_PRIO(nice);
9059393e 6395 set_load_weight(p, true);
b29739f9
IM
6396 old_prio = p->prio;
6397 p->prio = effective_prio(p);
1da177e4 6398
5443a0be 6399 if (queued)
7134b3e9 6400 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
49bd21ef 6401 if (running)
03b7fad1 6402 set_next_task(rq, p);
5443a0be
FW
6403
6404 /*
6405 * If the task increased its priority or is running and
6406 * lowered its priority, then reschedule its CPU:
6407 */
6408 p->sched_class->prio_changed(rq, p, old_prio);
6409
1da177e4 6410out_unlock:
eb580751 6411 task_rq_unlock(rq, p, &rf);
1da177e4 6412}
1da177e4
LT
6413EXPORT_SYMBOL(set_user_nice);
6414
e43379f1
MM
6415/*
6416 * can_nice - check if a task can reduce its nice value
6417 * @p: task
6418 * @nice: nice value
6419 */
36c8b586 6420int can_nice(const struct task_struct *p, const int nice)
e43379f1 6421{
d1ccc66d 6422 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
7aa2c016 6423 int nice_rlim = nice_to_rlimit(nice);
48f24c4d 6424
78d7d407 6425 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
e43379f1
MM
6426 capable(CAP_SYS_NICE));
6427}
6428
1da177e4
LT
6429#ifdef __ARCH_WANT_SYS_NICE
6430
6431/*
6432 * sys_nice - change the priority of the current process.
6433 * @increment: priority increment
6434 *
6435 * sys_setpriority is a more generic, but much slower function that
6436 * does similar things.
6437 */
5add95d4 6438SYSCALL_DEFINE1(nice, int, increment)
1da177e4 6439{
48f24c4d 6440 long nice, retval;
1da177e4
LT
6441
6442 /*
6443 * Setpriority might change our priority at the same moment.
6444 * We don't have to worry. Conceptually one call occurs first
6445 * and we have a single winner.
6446 */
a9467fa3 6447 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
d0ea0268 6448 nice = task_nice(current) + increment;
1da177e4 6449
a9467fa3 6450 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
e43379f1
MM
6451 if (increment < 0 && !can_nice(current, nice))
6452 return -EPERM;
6453
1da177e4
LT
6454 retval = security_task_setnice(current, nice);
6455 if (retval)
6456 return retval;
6457
6458 set_user_nice(current, nice);
6459 return 0;
6460}
6461
6462#endif
6463
6464/**
6465 * task_prio - return the priority value of a given task.
6466 * @p: the task in question.
6467 *
e69f6186 6468 * Return: The priority value as seen by users in /proc.
c541bb78
DE
6469 *
6470 * sched policy return value kernel prio user prio/nice
6471 *
6472 * normal, batch, idle [0 ... 39] [100 ... 139] 0/[-20 ... 19]
6473 * fifo, rr [-2 ... -100] [98 ... 0] [1 ... 99]
6474 * deadline -101 -1 0
1da177e4 6475 */
36c8b586 6476int task_prio(const struct task_struct *p)
1da177e4
LT
6477{
6478 return p->prio - MAX_RT_PRIO;
6479}
6480
1da177e4 6481/**
d1ccc66d 6482 * idle_cpu - is a given CPU idle currently?
1da177e4 6483 * @cpu: the processor in question.
e69f6186
YB
6484 *
6485 * Return: 1 if the CPU is currently idle. 0 otherwise.
1da177e4
LT
6486 */
6487int idle_cpu(int cpu)
6488{
908a3283
TG
6489 struct rq *rq = cpu_rq(cpu);
6490
6491 if (rq->curr != rq->idle)
6492 return 0;
6493
6494 if (rq->nr_running)
6495 return 0;
6496
6497#ifdef CONFIG_SMP
126c2092 6498 if (rq->ttwu_pending)
908a3283
TG
6499 return 0;
6500#endif
6501
6502 return 1;
1da177e4
LT
6503}
6504
943d355d
RJ
6505/**
6506 * available_idle_cpu - is a given CPU idle for enqueuing work.
6507 * @cpu: the CPU in question.
6508 *
6509 * Return: 1 if the CPU is currently idle. 0 otherwise.
6510 */
6511int available_idle_cpu(int cpu)
6512{
6513 if (!idle_cpu(cpu))
6514 return 0;
6515
247f2f6f
RJ
6516 if (vcpu_is_preempted(cpu))
6517 return 0;
6518
908a3283 6519 return 1;
1da177e4
LT
6520}
6521
1da177e4 6522/**
d1ccc66d 6523 * idle_task - return the idle task for a given CPU.
1da177e4 6524 * @cpu: the processor in question.
e69f6186 6525 *
d1ccc66d 6526 * Return: The idle task for the CPU @cpu.
1da177e4 6527 */
36c8b586 6528struct task_struct *idle_task(int cpu)
1da177e4
LT
6529{
6530 return cpu_rq(cpu)->idle;
6531}
6532
7d6a905f
VK
6533#ifdef CONFIG_SMP
6534/*
6535 * This function computes an effective utilization for the given CPU, to be
6536 * used for frequency selection given the linear relation: f = u * f_max.
6537 *
6538 * The scheduler tracks the following metrics:
6539 *
6540 * cpu_util_{cfs,rt,dl,irq}()
6541 * cpu_bw_dl()
6542 *
6543 * Where the cfs,rt and dl util numbers are tracked with the same metric and
6544 * synchronized windows and are thus directly comparable.
6545 *
6546 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
6547 * which excludes things like IRQ and steal-time. These latter are then accrued
6548 * in the irq utilization.
6549 *
6550 * The DL bandwidth number otoh is not a measured metric but a value computed
6551 * based on the task model parameters and gives the minimal utilization
6552 * required to meet deadlines.
6553 */
a5418be9
VK
6554unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
6555 unsigned long max, enum cpu_util_type type,
7d6a905f
VK
6556 struct task_struct *p)
6557{
6558 unsigned long dl_util, util, irq;
6559 struct rq *rq = cpu_rq(cpu);
6560
6561 if (!uclamp_is_used() &&
6562 type == FREQUENCY_UTIL && rt_rq_is_runnable(&rq->rt)) {
6563 return max;
6564 }
6565
6566 /*
6567 * Early check to see if IRQ/steal time saturates the CPU, can be
6568 * because of inaccuracies in how we track these -- see
6569 * update_irq_load_avg().
6570 */
6571 irq = cpu_util_irq(rq);
6572 if (unlikely(irq >= max))
6573 return max;
6574
6575 /*
6576 * Because the time spend on RT/DL tasks is visible as 'lost' time to
6577 * CFS tasks and we use the same metric to track the effective
6578 * utilization (PELT windows are synchronized) we can directly add them
6579 * to obtain the CPU's actual utilization.
6580 *
6581 * CFS and RT utilization can be boosted or capped, depending on
6582 * utilization clamp constraints requested by currently RUNNABLE
6583 * tasks.
6584 * When there are no CFS RUNNABLE tasks, clamps are released and
6585 * frequency will be gracefully reduced with the utilization decay.
6586 */
6587 util = util_cfs + cpu_util_rt(rq);
6588 if (type == FREQUENCY_UTIL)
6589 util = uclamp_rq_util_with(rq, util, p);
6590
6591 dl_util = cpu_util_dl(rq);
6592
6593 /*
6594 * For frequency selection we do not make cpu_util_dl() a permanent part
6595 * of this sum because we want to use cpu_bw_dl() later on, but we need
6596 * to check if the CFS+RT+DL sum is saturated (ie. no idle time) such
6597 * that we select f_max when there is no idle time.
6598 *
6599 * NOTE: numerical errors or stop class might cause us to not quite hit
6600 * saturation when we should -- something for later.
6601 */
6602 if (util + dl_util >= max)
6603 return max;
6604
6605 /*
6606 * OTOH, for energy computation we need the estimated running time, so
6607 * include util_dl and ignore dl_bw.
6608 */
6609 if (type == ENERGY_UTIL)
6610 util += dl_util;
6611
6612 /*
6613 * There is still idle time; further improve the number by using the
6614 * irq metric. Because IRQ/steal time is hidden from the task clock we
6615 * need to scale the task numbers:
6616 *
6617 * max - irq
6618 * U' = irq + --------- * U
6619 * max
6620 */
6621 util = scale_irq_capacity(util, irq, max);
6622 util += irq;
6623
6624 /*
6625 * Bandwidth required by DEADLINE must always be granted while, for
6626 * FAIR and RT, we use blocked utilization of IDLE CPUs as a mechanism
6627 * to gracefully reduce the frequency when no tasks show up for longer
6628 * periods of time.
6629 *
6630 * Ideally we would like to set bw_dl as min/guaranteed freq and util +
6631 * bw_dl as requested freq. However, cpufreq is not yet ready for such
6632 * an interface. So, we only do the latter for now.
6633 */
6634 if (type == FREQUENCY_UTIL)
6635 util += cpu_bw_dl(rq);
6636
6637 return min(max, util);
6638}
a5418be9
VK
6639
6640unsigned long sched_cpu_util(int cpu, unsigned long max)
6641{
6642 return effective_cpu_util(cpu, cpu_util_cfs(cpu_rq(cpu)), max,
6643 ENERGY_UTIL, NULL);
6644}
7d6a905f
VK
6645#endif /* CONFIG_SMP */
6646
1da177e4
LT
6647/**
6648 * find_process_by_pid - find a process with a matching PID value.
6649 * @pid: the pid in question.
e69f6186
YB
6650 *
6651 * The task of @pid, if found. %NULL otherwise.
1da177e4 6652 */
a9957449 6653static struct task_struct *find_process_by_pid(pid_t pid)
1da177e4 6654{
228ebcbe 6655 return pid ? find_task_by_vpid(pid) : current;
1da177e4
LT
6656}
6657
c13db6b1
SR
6658/*
6659 * sched_setparam() passes in -1 for its policy, to let the functions
6660 * it calls know not to change it.
6661 */
6662#define SETPARAM_POLICY -1
6663
c365c292
TG
6664static void __setscheduler_params(struct task_struct *p,
6665 const struct sched_attr *attr)
1da177e4 6666{
d50dde5a
DF
6667 int policy = attr->sched_policy;
6668
c13db6b1 6669 if (policy == SETPARAM_POLICY)
39fd8fd2
PZ
6670 policy = p->policy;
6671
1da177e4 6672 p->policy = policy;
d50dde5a 6673
aab03e05
DF
6674 if (dl_policy(policy))
6675 __setparam_dl(p, attr);
39fd8fd2 6676 else if (fair_policy(policy))
d50dde5a
DF
6677 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
6678
39fd8fd2
PZ
6679 /*
6680 * __sched_setscheduler() ensures attr->sched_priority == 0 when
6681 * !rt_policy. Always setting this ensures that things like
6682 * getparam()/getattr() don't report silly values for !rt tasks.
6683 */
6684 p->rt_priority = attr->sched_priority;
383afd09 6685 p->normal_prio = normal_prio(p);
9059393e 6686 set_load_weight(p, true);
c365c292 6687}
39fd8fd2 6688
c365c292
TG
6689/* Actually do priority change: must hold pi & rq lock. */
6690static void __setscheduler(struct rq *rq, struct task_struct *p,
0782e63b 6691 const struct sched_attr *attr, bool keep_boost)
c365c292 6692{
a509a7cd
PB
6693 /*
6694 * If params can't change scheduling class changes aren't allowed
6695 * either.
6696 */
6697 if (attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)
6698 return;
6699
c365c292 6700 __setscheduler_params(p, attr);
d50dde5a 6701
383afd09 6702 /*
0782e63b
TG
6703 * Keep a potential priority boosting if called from
6704 * sched_setscheduler().
383afd09 6705 */
acd58620 6706 p->prio = normal_prio(p);
0782e63b 6707 if (keep_boost)
acd58620 6708 p->prio = rt_effective_prio(p, p->prio);
383afd09 6709
aab03e05
DF
6710 if (dl_prio(p->prio))
6711 p->sched_class = &dl_sched_class;
6712 else if (rt_prio(p->prio))
ffd44db5
PZ
6713 p->sched_class = &rt_sched_class;
6714 else
6715 p->sched_class = &fair_sched_class;
1da177e4 6716}
aab03e05 6717
c69e8d9c 6718/*
d1ccc66d 6719 * Check the target process has a UID that matches the current process's:
c69e8d9c
DH
6720 */
6721static bool check_same_owner(struct task_struct *p)
6722{
6723 const struct cred *cred = current_cred(), *pcred;
6724 bool match;
6725
6726 rcu_read_lock();
6727 pcred = __task_cred(p);
9c806aa0
EB
6728 match = (uid_eq(cred->euid, pcred->euid) ||
6729 uid_eq(cred->euid, pcred->uid));
c69e8d9c
DH
6730 rcu_read_unlock();
6731 return match;
6732}
6733
d50dde5a
DF
6734static int __sched_setscheduler(struct task_struct *p,
6735 const struct sched_attr *attr,
dbc7f069 6736 bool user, bool pi)
1da177e4 6737{
383afd09
SR
6738 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
6739 MAX_RT_PRIO - 1 - attr->sched_priority;
da0c1e65 6740 int retval, oldprio, oldpolicy = -1, queued, running;
0782e63b 6741 int new_effective_prio, policy = attr->sched_policy;
83ab0aa0 6742 const struct sched_class *prev_class;
565790d2 6743 struct callback_head *head;
eb580751 6744 struct rq_flags rf;
ca94c442 6745 int reset_on_fork;
7a57f32a 6746 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
eb580751 6747 struct rq *rq;
1da177e4 6748
896bbb25
SRV
6749 /* The pi code expects interrupts enabled */
6750 BUG_ON(pi && in_interrupt());
1da177e4 6751recheck:
d1ccc66d 6752 /* Double check policy once rq lock held: */
ca94c442
LP
6753 if (policy < 0) {
6754 reset_on_fork = p->sched_reset_on_fork;
1da177e4 6755 policy = oldpolicy = p->policy;
ca94c442 6756 } else {
7479f3c9 6757 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
ca94c442 6758
20f9cd2a 6759 if (!valid_policy(policy))
ca94c442
LP
6760 return -EINVAL;
6761 }
6762
794a56eb 6763 if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
7479f3c9
PZ
6764 return -EINVAL;
6765
1da177e4
LT
6766 /*
6767 * Valid priorities for SCHED_FIFO and SCHED_RR are
ae18ad28 6768 * 1..MAX_RT_PRIO-1, valid priority for SCHED_NORMAL,
dd41f596 6769 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4 6770 */
ae18ad28 6771 if (attr->sched_priority > MAX_RT_PRIO-1)
1da177e4 6772 return -EINVAL;
aab03e05
DF
6773 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
6774 (rt_policy(policy) != (attr->sched_priority != 0)))
1da177e4
LT
6775 return -EINVAL;
6776
37e4ab3f
OC
6777 /*
6778 * Allow unprivileged RT tasks to decrease priority:
6779 */
961ccddd 6780 if (user && !capable(CAP_SYS_NICE)) {
d50dde5a 6781 if (fair_policy(policy)) {
d0ea0268 6782 if (attr->sched_nice < task_nice(p) &&
eaad4513 6783 !can_nice(p, attr->sched_nice))
d50dde5a
DF
6784 return -EPERM;
6785 }
6786
e05606d3 6787 if (rt_policy(policy)) {
a44702e8
ON
6788 unsigned long rlim_rtprio =
6789 task_rlimit(p, RLIMIT_RTPRIO);
8dc3e909 6790
d1ccc66d 6791 /* Can't set/change the rt policy: */
8dc3e909
ON
6792 if (policy != p->policy && !rlim_rtprio)
6793 return -EPERM;
6794
d1ccc66d 6795 /* Can't increase priority: */
d50dde5a
DF
6796 if (attr->sched_priority > p->rt_priority &&
6797 attr->sched_priority > rlim_rtprio)
8dc3e909
ON
6798 return -EPERM;
6799 }
c02aa73b 6800
d44753b8
JL
6801 /*
6802 * Can't set/change SCHED_DEADLINE policy at all for now
6803 * (safest behavior); in the future we would like to allow
6804 * unprivileged DL tasks to increase their relative deadline
6805 * or reduce their runtime (both ways reducing utilization)
6806 */
6807 if (dl_policy(policy))
6808 return -EPERM;
6809
dd41f596 6810 /*
c02aa73b
DH
6811 * Treat SCHED_IDLE as nice 20. Only allow a switch to
6812 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
dd41f596 6813 */
1da1843f 6814 if (task_has_idle_policy(p) && !idle_policy(policy)) {
d0ea0268 6815 if (!can_nice(p, task_nice(p)))
c02aa73b
DH
6816 return -EPERM;
6817 }
5fe1d75f 6818
d1ccc66d 6819 /* Can't change other user's priorities: */
c69e8d9c 6820 if (!check_same_owner(p))
37e4ab3f 6821 return -EPERM;
ca94c442 6822
d1ccc66d 6823 /* Normal users shall not reset the sched_reset_on_fork flag: */
ca94c442
LP
6824 if (p->sched_reset_on_fork && !reset_on_fork)
6825 return -EPERM;
37e4ab3f 6826 }
1da177e4 6827
725aad24 6828 if (user) {
794a56eb
JL
6829 if (attr->sched_flags & SCHED_FLAG_SUGOV)
6830 return -EINVAL;
6831
b0ae1981 6832 retval = security_task_setscheduler(p);
725aad24
JF
6833 if (retval)
6834 return retval;
6835 }
6836
a509a7cd
PB
6837 /* Update task specific "requested" clamps */
6838 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
6839 retval = uclamp_validate(p, attr);
6840 if (retval)
6841 return retval;
6842 }
6843
710da3c8
JL
6844 if (pi)
6845 cpuset_read_lock();
6846
b29739f9 6847 /*
d1ccc66d 6848 * Make sure no PI-waiters arrive (or leave) while we are
b29739f9 6849 * changing the priority of the task:
0122ec5b 6850 *
25985edc 6851 * To be able to change p->policy safely, the appropriate
1da177e4
LT
6852 * runqueue lock must be held.
6853 */
eb580751 6854 rq = task_rq_lock(p, &rf);
80f5c1b8 6855 update_rq_clock(rq);
dc61b1d6 6856
34f971f6 6857 /*
d1ccc66d 6858 * Changing the policy of the stop threads its a very bad idea:
34f971f6
PZ
6859 */
6860 if (p == rq->stop) {
4b211f2b
MP
6861 retval = -EINVAL;
6862 goto unlock;
34f971f6
PZ
6863 }
6864
a51e9198 6865 /*
d6b1e911
TG
6866 * If not changing anything there's no need to proceed further,
6867 * but store a possible modification of reset_on_fork.
a51e9198 6868 */
d50dde5a 6869 if (unlikely(policy == p->policy)) {
d0ea0268 6870 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
d50dde5a
DF
6871 goto change;
6872 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
6873 goto change;
75381608 6874 if (dl_policy(policy) && dl_param_changed(p, attr))
aab03e05 6875 goto change;
a509a7cd
PB
6876 if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
6877 goto change;
d50dde5a 6878
d6b1e911 6879 p->sched_reset_on_fork = reset_on_fork;
4b211f2b
MP
6880 retval = 0;
6881 goto unlock;
a51e9198 6882 }
d50dde5a 6883change:
a51e9198 6884
dc61b1d6 6885 if (user) {
332ac17e 6886#ifdef CONFIG_RT_GROUP_SCHED
dc61b1d6
PZ
6887 /*
6888 * Do not allow realtime tasks into groups that have no runtime
6889 * assigned.
6890 */
6891 if (rt_bandwidth_enabled() && rt_policy(policy) &&
f4493771
MG
6892 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
6893 !task_group_is_autogroup(task_group(p))) {
4b211f2b
MP
6894 retval = -EPERM;
6895 goto unlock;
dc61b1d6 6896 }
dc61b1d6 6897#endif
332ac17e 6898#ifdef CONFIG_SMP
794a56eb
JL
6899 if (dl_bandwidth_enabled() && dl_policy(policy) &&
6900 !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
332ac17e 6901 cpumask_t *span = rq->rd->span;
332ac17e
DF
6902
6903 /*
6904 * Don't allow tasks with an affinity mask smaller than
6905 * the entire root_domain to become SCHED_DEADLINE. We
6906 * will also fail if there's no bandwidth available.
6907 */
3bd37062 6908 if (!cpumask_subset(span, p->cpus_ptr) ||
e4099a5e 6909 rq->rd->dl_bw.bw == 0) {
4b211f2b
MP
6910 retval = -EPERM;
6911 goto unlock;
332ac17e
DF
6912 }
6913 }
6914#endif
6915 }
dc61b1d6 6916
d1ccc66d 6917 /* Re-check policy now with rq lock held: */
1da177e4
LT
6918 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
6919 policy = oldpolicy = -1;
eb580751 6920 task_rq_unlock(rq, p, &rf);
710da3c8
JL
6921 if (pi)
6922 cpuset_read_unlock();
1da177e4
LT
6923 goto recheck;
6924 }
332ac17e
DF
6925
6926 /*
6927 * If setscheduling to SCHED_DEADLINE (or changing the parameters
6928 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
6929 * is available.
6930 */
06a76fe0 6931 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
4b211f2b
MP
6932 retval = -EBUSY;
6933 goto unlock;
332ac17e
DF
6934 }
6935
c365c292
TG
6936 p->sched_reset_on_fork = reset_on_fork;
6937 oldprio = p->prio;
6938
dbc7f069
PZ
6939 if (pi) {
6940 /*
6941 * Take priority boosted tasks into account. If the new
6942 * effective priority is unchanged, we just store the new
6943 * normal parameters and do not touch the scheduler class and
6944 * the runqueue. This will be done when the task deboost
6945 * itself.
6946 */
acd58620 6947 new_effective_prio = rt_effective_prio(p, newprio);
ff77e468
PZ
6948 if (new_effective_prio == oldprio)
6949 queue_flags &= ~DEQUEUE_MOVE;
c365c292
TG
6950 }
6951
da0c1e65 6952 queued = task_on_rq_queued(p);
051a1d1a 6953 running = task_current(rq, p);
da0c1e65 6954 if (queued)
ff77e468 6955 dequeue_task(rq, p, queue_flags);
0e1f3483 6956 if (running)
f3cd1c4e 6957 put_prev_task(rq, p);
f6b53205 6958
83ab0aa0 6959 prev_class = p->sched_class;
a509a7cd 6960
dbc7f069 6961 __setscheduler(rq, p, attr, pi);
a509a7cd 6962 __setscheduler_uclamp(p, attr);
f6b53205 6963
da0c1e65 6964 if (queued) {
81a44c54
TG
6965 /*
6966 * We enqueue to tail when the priority of a task is
6967 * increased (user space view).
6968 */
ff77e468
PZ
6969 if (oldprio < p->prio)
6970 queue_flags |= ENQUEUE_HEAD;
1de64443 6971
ff77e468 6972 enqueue_task(rq, p, queue_flags);
81a44c54 6973 }
a399d233 6974 if (running)
03b7fad1 6975 set_next_task(rq, p);
cb469845 6976
da7a735e 6977 check_class_changed(rq, p, prev_class, oldprio);
d1ccc66d
IM
6978
6979 /* Avoid rq from going away on us: */
6980 preempt_disable();
565790d2 6981 head = splice_balance_callbacks(rq);
eb580751 6982 task_rq_unlock(rq, p, &rf);
b29739f9 6983
710da3c8
JL
6984 if (pi) {
6985 cpuset_read_unlock();
dbc7f069 6986 rt_mutex_adjust_pi(p);
710da3c8 6987 }
95e02ca9 6988
d1ccc66d 6989 /* Run balance callbacks after we've adjusted the PI chain: */
565790d2 6990 balance_callbacks(rq, head);
4c9a4bc8 6991 preempt_enable();
95e02ca9 6992
1da177e4 6993 return 0;
4b211f2b
MP
6994
6995unlock:
6996 task_rq_unlock(rq, p, &rf);
710da3c8
JL
6997 if (pi)
6998 cpuset_read_unlock();
4b211f2b 6999 return retval;
1da177e4 7000}
961ccddd 7001
7479f3c9
PZ
7002static int _sched_setscheduler(struct task_struct *p, int policy,
7003 const struct sched_param *param, bool check)
7004{
7005 struct sched_attr attr = {
7006 .sched_policy = policy,
7007 .sched_priority = param->sched_priority,
7008 .sched_nice = PRIO_TO_NICE(p->static_prio),
7009 };
7010
c13db6b1
SR
7011 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
7012 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
7479f3c9
PZ
7013 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
7014 policy &= ~SCHED_RESET_ON_FORK;
7015 attr.sched_policy = policy;
7016 }
7017
dbc7f069 7018 return __sched_setscheduler(p, &attr, check, true);
7479f3c9 7019}
961ccddd
RR
7020/**
7021 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
7022 * @p: the task in question.
7023 * @policy: new policy.
7024 * @param: structure containing the new RT priority.
7025 *
7318d4cc
PZ
7026 * Use sched_set_fifo(), read its comment.
7027 *
e69f6186
YB
7028 * Return: 0 on success. An error code otherwise.
7029 *
961ccddd
RR
7030 * NOTE that the task may be already dead.
7031 */
7032int sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 7033 const struct sched_param *param)
961ccddd 7034{
7479f3c9 7035 return _sched_setscheduler(p, policy, param, true);
961ccddd 7036}
1da177e4 7037
d50dde5a
DF
7038int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
7039{
dbc7f069 7040 return __sched_setscheduler(p, attr, true, true);
d50dde5a 7041}
d50dde5a 7042
794a56eb
JL
7043int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
7044{
7045 return __sched_setscheduler(p, attr, false, true);
7046}
4c38f2df 7047EXPORT_SYMBOL_GPL(sched_setattr_nocheck);
794a56eb 7048
961ccddd
RR
7049/**
7050 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
7051 * @p: the task in question.
7052 * @policy: new policy.
7053 * @param: structure containing the new RT priority.
7054 *
7055 * Just like sched_setscheduler, only don't bother checking if the
7056 * current context has permission. For example, this is needed in
7057 * stop_machine(): we create temporary high priority worker threads,
7058 * but our caller might not have that capability.
e69f6186
YB
7059 *
7060 * Return: 0 on success. An error code otherwise.
961ccddd
RR
7061 */
7062int sched_setscheduler_nocheck(struct task_struct *p, int policy,
fe7de49f 7063 const struct sched_param *param)
961ccddd 7064{
7479f3c9 7065 return _sched_setscheduler(p, policy, param, false);
961ccddd
RR
7066}
7067
7318d4cc
PZ
7068/*
7069 * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
7070 * incapable of resource management, which is the one thing an OS really should
7071 * be doing.
7072 *
7073 * This is of course the reason it is limited to privileged users only.
7074 *
7075 * Worse still; it is fundamentally impossible to compose static priority
7076 * workloads. You cannot take two correctly working static prio workloads
7077 * and smash them together and still expect them to work.
7078 *
7079 * For this reason 'all' FIFO tasks the kernel creates are basically at:
7080 *
7081 * MAX_RT_PRIO / 2
7082 *
7083 * The administrator _MUST_ configure the system, the kernel simply doesn't
7084 * know enough information to make a sensible choice.
7085 */
8b700983 7086void sched_set_fifo(struct task_struct *p)
7318d4cc
PZ
7087{
7088 struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
8b700983 7089 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7318d4cc
PZ
7090}
7091EXPORT_SYMBOL_GPL(sched_set_fifo);
7092
7093/*
7094 * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
7095 */
8b700983 7096void sched_set_fifo_low(struct task_struct *p)
7318d4cc
PZ
7097{
7098 struct sched_param sp = { .sched_priority = 1 };
8b700983 7099 WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
7318d4cc
PZ
7100}
7101EXPORT_SYMBOL_GPL(sched_set_fifo_low);
7102
8b700983 7103void sched_set_normal(struct task_struct *p, int nice)
7318d4cc
PZ
7104{
7105 struct sched_attr attr = {
7106 .sched_policy = SCHED_NORMAL,
7107 .sched_nice = nice,
7108 };
8b700983 7109 WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
7318d4cc
PZ
7110}
7111EXPORT_SYMBOL_GPL(sched_set_normal);
961ccddd 7112
95cdf3b7
IM
7113static int
7114do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 7115{
1da177e4
LT
7116 struct sched_param lparam;
7117 struct task_struct *p;
36c8b586 7118 int retval;
1da177e4
LT
7119
7120 if (!param || pid < 0)
7121 return -EINVAL;
7122 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
7123 return -EFAULT;
5fe1d75f
ON
7124
7125 rcu_read_lock();
7126 retval = -ESRCH;
1da177e4 7127 p = find_process_by_pid(pid);
710da3c8
JL
7128 if (likely(p))
7129 get_task_struct(p);
5fe1d75f 7130 rcu_read_unlock();
36c8b586 7131
710da3c8
JL
7132 if (likely(p)) {
7133 retval = sched_setscheduler(p, policy, &lparam);
7134 put_task_struct(p);
7135 }
7136
1da177e4
LT
7137 return retval;
7138}
7139
d50dde5a
DF
7140/*
7141 * Mimics kernel/events/core.c perf_copy_attr().
7142 */
d1ccc66d 7143static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
d50dde5a
DF
7144{
7145 u32 size;
7146 int ret;
7147
d1ccc66d 7148 /* Zero the full structure, so that a short copy will be nice: */
d50dde5a
DF
7149 memset(attr, 0, sizeof(*attr));
7150
7151 ret = get_user(size, &uattr->size);
7152 if (ret)
7153 return ret;
7154
d1ccc66d
IM
7155 /* ABI compatibility quirk: */
7156 if (!size)
d50dde5a 7157 size = SCHED_ATTR_SIZE_VER0;
dff3a85f 7158 if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
d50dde5a
DF
7159 goto err_size;
7160
dff3a85f
AS
7161 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
7162 if (ret) {
7163 if (ret == -E2BIG)
7164 goto err_size;
7165 return ret;
d50dde5a
DF
7166 }
7167
a509a7cd
PB
7168 if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
7169 size < SCHED_ATTR_SIZE_VER1)
7170 return -EINVAL;
7171
d50dde5a 7172 /*
d1ccc66d 7173 * XXX: Do we want to be lenient like existing syscalls; or do we want
d50dde5a
DF
7174 * to be strict and return an error on out-of-bounds values?
7175 */
75e45d51 7176 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
d50dde5a 7177
e78c7bca 7178 return 0;
d50dde5a
DF
7179
7180err_size:
7181 put_user(sizeof(*attr), &uattr->size);
e78c7bca 7182 return -E2BIG;
d50dde5a
DF
7183}
7184
1da177e4
LT
7185/**
7186 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
7187 * @pid: the pid in question.
7188 * @policy: new policy.
7189 * @param: structure containing the new RT priority.
e69f6186
YB
7190 *
7191 * Return: 0 on success. An error code otherwise.
1da177e4 7192 */
d1ccc66d 7193SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
1da177e4 7194{
c21761f1
JB
7195 if (policy < 0)
7196 return -EINVAL;
7197
1da177e4
LT
7198 return do_sched_setscheduler(pid, policy, param);
7199}
7200
7201/**
7202 * sys_sched_setparam - set/change the RT priority of a thread
7203 * @pid: the pid in question.
7204 * @param: structure containing the new RT priority.
e69f6186
YB
7205 *
7206 * Return: 0 on success. An error code otherwise.
1da177e4 7207 */
5add95d4 7208SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 7209{
c13db6b1 7210 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
1da177e4
LT
7211}
7212
d50dde5a
DF
7213/**
7214 * sys_sched_setattr - same as above, but with extended sched_attr
7215 * @pid: the pid in question.
5778fccf 7216 * @uattr: structure containing the extended parameters.
db66d756 7217 * @flags: for future extension.
d50dde5a 7218 */
6d35ab48
PZ
7219SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
7220 unsigned int, flags)
d50dde5a
DF
7221{
7222 struct sched_attr attr;
7223 struct task_struct *p;
7224 int retval;
7225
6d35ab48 7226 if (!uattr || pid < 0 || flags)
d50dde5a
DF
7227 return -EINVAL;
7228
143cf23d
MK
7229 retval = sched_copy_attr(uattr, &attr);
7230 if (retval)
7231 return retval;
d50dde5a 7232
b14ed2c2 7233 if ((int)attr.sched_policy < 0)
dbdb2275 7234 return -EINVAL;
1d6362fa
PB
7235 if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
7236 attr.sched_policy = SETPARAM_POLICY;
d50dde5a
DF
7237
7238 rcu_read_lock();
7239 retval = -ESRCH;
7240 p = find_process_by_pid(pid);
a509a7cd
PB
7241 if (likely(p))
7242 get_task_struct(p);
d50dde5a
DF
7243 rcu_read_unlock();
7244
a509a7cd
PB
7245 if (likely(p)) {
7246 retval = sched_setattr(p, &attr);
7247 put_task_struct(p);
7248 }
7249
d50dde5a
DF
7250 return retval;
7251}
7252
1da177e4
LT
7253/**
7254 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
7255 * @pid: the pid in question.
e69f6186
YB
7256 *
7257 * Return: On success, the policy of the thread. Otherwise, a negative error
7258 * code.
1da177e4 7259 */
5add95d4 7260SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
1da177e4 7261{
36c8b586 7262 struct task_struct *p;
3a5c359a 7263 int retval;
1da177e4
LT
7264
7265 if (pid < 0)
3a5c359a 7266 return -EINVAL;
1da177e4
LT
7267
7268 retval = -ESRCH;
5fe85be0 7269 rcu_read_lock();
1da177e4
LT
7270 p = find_process_by_pid(pid);
7271 if (p) {
7272 retval = security_task_getscheduler(p);
7273 if (!retval)
ca94c442
LP
7274 retval = p->policy
7275 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
1da177e4 7276 }
5fe85be0 7277 rcu_read_unlock();
1da177e4
LT
7278 return retval;
7279}
7280
7281/**
ca94c442 7282 * sys_sched_getparam - get the RT priority of a thread
1da177e4
LT
7283 * @pid: the pid in question.
7284 * @param: structure containing the RT priority.
e69f6186
YB
7285 *
7286 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
7287 * code.
1da177e4 7288 */
5add95d4 7289SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 7290{
ce5f7f82 7291 struct sched_param lp = { .sched_priority = 0 };
36c8b586 7292 struct task_struct *p;
3a5c359a 7293 int retval;
1da177e4
LT
7294
7295 if (!param || pid < 0)
3a5c359a 7296 return -EINVAL;
1da177e4 7297
5fe85be0 7298 rcu_read_lock();
1da177e4
LT
7299 p = find_process_by_pid(pid);
7300 retval = -ESRCH;
7301 if (!p)
7302 goto out_unlock;
7303
7304 retval = security_task_getscheduler(p);
7305 if (retval)
7306 goto out_unlock;
7307
ce5f7f82
PZ
7308 if (task_has_rt_policy(p))
7309 lp.sched_priority = p->rt_priority;
5fe85be0 7310 rcu_read_unlock();
1da177e4
LT
7311
7312 /*
7313 * This one might sleep, we cannot do it with a spinlock held ...
7314 */
7315 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
7316
1da177e4
LT
7317 return retval;
7318
7319out_unlock:
5fe85be0 7320 rcu_read_unlock();
1da177e4
LT
7321 return retval;
7322}
7323
1251201c
IM
7324/*
7325 * Copy the kernel size attribute structure (which might be larger
7326 * than what user-space knows about) to user-space.
7327 *
7328 * Note that all cases are valid: user-space buffer can be larger or
7329 * smaller than the kernel-space buffer. The usual case is that both
7330 * have the same size.
7331 */
7332static int
7333sched_attr_copy_to_user(struct sched_attr __user *uattr,
7334 struct sched_attr *kattr,
7335 unsigned int usize)
d50dde5a 7336{
1251201c 7337 unsigned int ksize = sizeof(*kattr);
d50dde5a 7338
96d4f267 7339 if (!access_ok(uattr, usize))
d50dde5a
DF
7340 return -EFAULT;
7341
7342 /*
1251201c
IM
7343 * sched_getattr() ABI forwards and backwards compatibility:
7344 *
7345 * If usize == ksize then we just copy everything to user-space and all is good.
7346 *
7347 * If usize < ksize then we only copy as much as user-space has space for,
7348 * this keeps ABI compatibility as well. We skip the rest.
7349 *
7350 * If usize > ksize then user-space is using a newer version of the ABI,
7351 * which part the kernel doesn't know about. Just ignore it - tooling can
7352 * detect the kernel's knowledge of attributes from the attr->size value
7353 * which is set to ksize in this case.
d50dde5a 7354 */
1251201c 7355 kattr->size = min(usize, ksize);
d50dde5a 7356
1251201c 7357 if (copy_to_user(uattr, kattr, kattr->size))
d50dde5a
DF
7358 return -EFAULT;
7359
22400674 7360 return 0;
d50dde5a
DF
7361}
7362
7363/**
aab03e05 7364 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
d50dde5a 7365 * @pid: the pid in question.
5778fccf 7366 * @uattr: structure containing the extended parameters.
dff3a85f 7367 * @usize: sizeof(attr) for fwd/bwd comp.
db66d756 7368 * @flags: for future extension.
d50dde5a 7369 */
6d35ab48 7370SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
1251201c 7371 unsigned int, usize, unsigned int, flags)
d50dde5a 7372{
1251201c 7373 struct sched_attr kattr = { };
d50dde5a
DF
7374 struct task_struct *p;
7375 int retval;
7376
1251201c
IM
7377 if (!uattr || pid < 0 || usize > PAGE_SIZE ||
7378 usize < SCHED_ATTR_SIZE_VER0 || flags)
d50dde5a
DF
7379 return -EINVAL;
7380
7381 rcu_read_lock();
7382 p = find_process_by_pid(pid);
7383 retval = -ESRCH;
7384 if (!p)
7385 goto out_unlock;
7386
7387 retval = security_task_getscheduler(p);
7388 if (retval)
7389 goto out_unlock;
7390
1251201c 7391 kattr.sched_policy = p->policy;
7479f3c9 7392 if (p->sched_reset_on_fork)
1251201c 7393 kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
aab03e05 7394 if (task_has_dl_policy(p))
1251201c 7395 __getparam_dl(p, &kattr);
aab03e05 7396 else if (task_has_rt_policy(p))
1251201c 7397 kattr.sched_priority = p->rt_priority;
d50dde5a 7398 else
1251201c 7399 kattr.sched_nice = task_nice(p);
d50dde5a 7400
a509a7cd 7401#ifdef CONFIG_UCLAMP_TASK
13685c4a
QY
7402 /*
7403 * This could race with another potential updater, but this is fine
7404 * because it'll correctly read the old or the new value. We don't need
7405 * to guarantee who wins the race as long as it doesn't return garbage.
7406 */
1251201c
IM
7407 kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
7408 kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
a509a7cd
PB
7409#endif
7410
d50dde5a
DF
7411 rcu_read_unlock();
7412
1251201c 7413 return sched_attr_copy_to_user(uattr, &kattr, usize);
d50dde5a
DF
7414
7415out_unlock:
7416 rcu_read_unlock();
7417 return retval;
7418}
7419
96f874e2 7420long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
1da177e4 7421{
5a16f3d3 7422 cpumask_var_t cpus_allowed, new_mask;
36c8b586
IM
7423 struct task_struct *p;
7424 int retval;
1da177e4 7425
23f5d142 7426 rcu_read_lock();
1da177e4
LT
7427
7428 p = find_process_by_pid(pid);
7429 if (!p) {
23f5d142 7430 rcu_read_unlock();
1da177e4
LT
7431 return -ESRCH;
7432 }
7433
23f5d142 7434 /* Prevent p going away */
1da177e4 7435 get_task_struct(p);
23f5d142 7436 rcu_read_unlock();
1da177e4 7437
14a40ffc
TH
7438 if (p->flags & PF_NO_SETAFFINITY) {
7439 retval = -EINVAL;
7440 goto out_put_task;
7441 }
5a16f3d3
RR
7442 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
7443 retval = -ENOMEM;
7444 goto out_put_task;
7445 }
7446 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
7447 retval = -ENOMEM;
7448 goto out_free_cpus_allowed;
7449 }
1da177e4 7450 retval = -EPERM;
4c44aaaf
EB
7451 if (!check_same_owner(p)) {
7452 rcu_read_lock();
7453 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
7454 rcu_read_unlock();
16303ab2 7455 goto out_free_new_mask;
4c44aaaf
EB
7456 }
7457 rcu_read_unlock();
7458 }
1da177e4 7459
b0ae1981 7460 retval = security_task_setscheduler(p);
e7834f8f 7461 if (retval)
16303ab2 7462 goto out_free_new_mask;
e7834f8f 7463
e4099a5e
PZ
7464
7465 cpuset_cpus_allowed(p, cpus_allowed);
7466 cpumask_and(new_mask, in_mask, cpus_allowed);
7467
332ac17e
DF
7468 /*
7469 * Since bandwidth control happens on root_domain basis,
7470 * if admission test is enabled, we only admit -deadline
7471 * tasks allowed to run on all the CPUs in the task's
7472 * root_domain.
7473 */
7474#ifdef CONFIG_SMP
f1e3a093
KT
7475 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
7476 rcu_read_lock();
7477 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
332ac17e 7478 retval = -EBUSY;
f1e3a093 7479 rcu_read_unlock();
16303ab2 7480 goto out_free_new_mask;
332ac17e 7481 }
f1e3a093 7482 rcu_read_unlock();
332ac17e
DF
7483 }
7484#endif
49246274 7485again:
9cfc3e18 7486 retval = __set_cpus_allowed_ptr(p, new_mask, SCA_CHECK);
1da177e4 7487
8707d8b8 7488 if (!retval) {
5a16f3d3
RR
7489 cpuset_cpus_allowed(p, cpus_allowed);
7490 if (!cpumask_subset(new_mask, cpus_allowed)) {
8707d8b8
PM
7491 /*
7492 * We must have raced with a concurrent cpuset
7493 * update. Just reset the cpus_allowed to the
7494 * cpuset's cpus_allowed
7495 */
5a16f3d3 7496 cpumask_copy(new_mask, cpus_allowed);
8707d8b8
PM
7497 goto again;
7498 }
7499 }
16303ab2 7500out_free_new_mask:
5a16f3d3
RR
7501 free_cpumask_var(new_mask);
7502out_free_cpus_allowed:
7503 free_cpumask_var(cpus_allowed);
7504out_put_task:
1da177e4 7505 put_task_struct(p);
1da177e4
LT
7506 return retval;
7507}
7508
7509static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
96f874e2 7510 struct cpumask *new_mask)
1da177e4 7511{
96f874e2
RR
7512 if (len < cpumask_size())
7513 cpumask_clear(new_mask);
7514 else if (len > cpumask_size())
7515 len = cpumask_size();
7516
1da177e4
LT
7517 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
7518}
7519
7520/**
d1ccc66d 7521 * sys_sched_setaffinity - set the CPU affinity of a process
1da177e4
LT
7522 * @pid: pid of the process
7523 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 7524 * @user_mask_ptr: user-space pointer to the new CPU mask
e69f6186
YB
7525 *
7526 * Return: 0 on success. An error code otherwise.
1da177e4 7527 */
5add95d4
HC
7528SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
7529 unsigned long __user *, user_mask_ptr)
1da177e4 7530{
5a16f3d3 7531 cpumask_var_t new_mask;
1da177e4
LT
7532 int retval;
7533
5a16f3d3
RR
7534 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
7535 return -ENOMEM;
1da177e4 7536
5a16f3d3
RR
7537 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
7538 if (retval == 0)
7539 retval = sched_setaffinity(pid, new_mask);
7540 free_cpumask_var(new_mask);
7541 return retval;
1da177e4
LT
7542}
7543
96f874e2 7544long sched_getaffinity(pid_t pid, struct cpumask *mask)
1da177e4 7545{
36c8b586 7546 struct task_struct *p;
31605683 7547 unsigned long flags;
1da177e4 7548 int retval;
1da177e4 7549
23f5d142 7550 rcu_read_lock();
1da177e4
LT
7551
7552 retval = -ESRCH;
7553 p = find_process_by_pid(pid);
7554 if (!p)
7555 goto out_unlock;
7556
e7834f8f
DQ
7557 retval = security_task_getscheduler(p);
7558 if (retval)
7559 goto out_unlock;
7560
013fdb80 7561 raw_spin_lock_irqsave(&p->pi_lock, flags);
3bd37062 7562 cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
013fdb80 7563 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
7564
7565out_unlock:
23f5d142 7566 rcu_read_unlock();
1da177e4 7567
9531b62f 7568 return retval;
1da177e4
LT
7569}
7570
7571/**
d1ccc66d 7572 * sys_sched_getaffinity - get the CPU affinity of a process
1da177e4
LT
7573 * @pid: pid of the process
7574 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 7575 * @user_mask_ptr: user-space pointer to hold the current CPU mask
e69f6186 7576 *
599b4840
ZW
7577 * Return: size of CPU mask copied to user_mask_ptr on success. An
7578 * error code otherwise.
1da177e4 7579 */
5add95d4
HC
7580SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
7581 unsigned long __user *, user_mask_ptr)
1da177e4
LT
7582{
7583 int ret;
f17c8607 7584 cpumask_var_t mask;
1da177e4 7585
84fba5ec 7586 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
cd3d8031
KM
7587 return -EINVAL;
7588 if (len & (sizeof(unsigned long)-1))
1da177e4
LT
7589 return -EINVAL;
7590
f17c8607
RR
7591 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
7592 return -ENOMEM;
1da177e4 7593
f17c8607
RR
7594 ret = sched_getaffinity(pid, mask);
7595 if (ret == 0) {
4de373a1 7596 unsigned int retlen = min(len, cpumask_size());
cd3d8031
KM
7597
7598 if (copy_to_user(user_mask_ptr, mask, retlen))
f17c8607
RR
7599 ret = -EFAULT;
7600 else
cd3d8031 7601 ret = retlen;
f17c8607
RR
7602 }
7603 free_cpumask_var(mask);
1da177e4 7604
f17c8607 7605 return ret;
1da177e4
LT
7606}
7607
7d4dd4f1 7608static void do_sched_yield(void)
1da177e4 7609{
8a8c69c3
PZ
7610 struct rq_flags rf;
7611 struct rq *rq;
7612
246b3b33 7613 rq = this_rq_lock_irq(&rf);
1da177e4 7614
ae92882e 7615 schedstat_inc(rq->yld_count);
4530d7ab 7616 current->sched_class->yield_task(rq);
1da177e4 7617
8a8c69c3 7618 preempt_disable();
345a957f 7619 rq_unlock_irq(rq, &rf);
ba74c144 7620 sched_preempt_enable_no_resched();
1da177e4
LT
7621
7622 schedule();
7d4dd4f1 7623}
1da177e4 7624
59a74b15
MCC
7625/**
7626 * sys_sched_yield - yield the current processor to other threads.
7627 *
7628 * This function yields the current CPU to other tasks. If there are no
7629 * other threads running on this CPU then this function will return.
7630 *
7631 * Return: 0.
7632 */
7d4dd4f1
DB
7633SYSCALL_DEFINE0(sched_yield)
7634{
7635 do_sched_yield();
1da177e4
LT
7636 return 0;
7637}
7638
b965f1dd
PZI
7639#if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
7640int __sched __cond_resched(void)
1da177e4 7641{
fe32d3cd 7642 if (should_resched(0)) {
a18b5d01 7643 preempt_schedule_common();
1da177e4
LT
7644 return 1;
7645 }
b965f1dd 7646#ifndef CONFIG_PREEMPT_RCU
f79c3ad6 7647 rcu_all_qs();
b965f1dd 7648#endif
1da177e4
LT
7649 return 0;
7650}
b965f1dd
PZI
7651EXPORT_SYMBOL(__cond_resched);
7652#endif
7653
7654#ifdef CONFIG_PREEMPT_DYNAMIC
7655DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
ef72661e 7656EXPORT_STATIC_CALL_TRAMP(cond_resched);
b965f1dd
PZI
7657
7658DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
ef72661e 7659EXPORT_STATIC_CALL_TRAMP(might_resched);
35a773a0 7660#endif
1da177e4
LT
7661
7662/*
613afbf8 7663 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
1da177e4
LT
7664 * call schedule, and on return reacquire the lock.
7665 *
c1a280b6 7666 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
1da177e4
LT
7667 * operations here to prevent schedule() from being called twice (once via
7668 * spin_unlock(), once by hand).
7669 */
613afbf8 7670int __cond_resched_lock(spinlock_t *lock)
1da177e4 7671{
fe32d3cd 7672 int resched = should_resched(PREEMPT_LOCK_OFFSET);
6df3cecb
JK
7673 int ret = 0;
7674
f607c668
PZ
7675 lockdep_assert_held(lock);
7676
4a81e832 7677 if (spin_needbreak(lock) || resched) {
1da177e4 7678 spin_unlock(lock);
d86ee480 7679 if (resched)
a18b5d01 7680 preempt_schedule_common();
95c354fe
NP
7681 else
7682 cpu_relax();
6df3cecb 7683 ret = 1;
1da177e4 7684 spin_lock(lock);
1da177e4 7685 }
6df3cecb 7686 return ret;
1da177e4 7687}
613afbf8 7688EXPORT_SYMBOL(__cond_resched_lock);
1da177e4 7689
f3d4b4b1
BG
7690int __cond_resched_rwlock_read(rwlock_t *lock)
7691{
7692 int resched = should_resched(PREEMPT_LOCK_OFFSET);
7693 int ret = 0;
7694
7695 lockdep_assert_held_read(lock);
7696
7697 if (rwlock_needbreak(lock) || resched) {
7698 read_unlock(lock);
7699 if (resched)
7700 preempt_schedule_common();
7701 else
7702 cpu_relax();
7703 ret = 1;
7704 read_lock(lock);
7705 }
7706 return ret;
7707}
7708EXPORT_SYMBOL(__cond_resched_rwlock_read);
7709
7710int __cond_resched_rwlock_write(rwlock_t *lock)
7711{
7712 int resched = should_resched(PREEMPT_LOCK_OFFSET);
7713 int ret = 0;
7714
7715 lockdep_assert_held_write(lock);
7716
7717 if (rwlock_needbreak(lock) || resched) {
7718 write_unlock(lock);
7719 if (resched)
7720 preempt_schedule_common();
7721 else
7722 cpu_relax();
7723 ret = 1;
7724 write_lock(lock);
7725 }
7726 return ret;
7727}
7728EXPORT_SYMBOL(__cond_resched_rwlock_write);
7729
1da177e4
LT
7730/**
7731 * yield - yield the current processor to other threads.
7732 *
8e3fabfd
PZ
7733 * Do not ever use this function, there's a 99% chance you're doing it wrong.
7734 *
7735 * The scheduler is at all times free to pick the calling task as the most
7736 * eligible task to run, if removing the yield() call from your code breaks
b19a888c 7737 * it, it's already broken.
8e3fabfd
PZ
7738 *
7739 * Typical broken usage is:
7740 *
7741 * while (!event)
d1ccc66d 7742 * yield();
8e3fabfd
PZ
7743 *
7744 * where one assumes that yield() will let 'the other' process run that will
7745 * make event true. If the current task is a SCHED_FIFO task that will never
7746 * happen. Never use yield() as a progress guarantee!!
7747 *
7748 * If you want to use yield() to wait for something, use wait_event().
7749 * If you want to use yield() to be 'nice' for others, use cond_resched().
7750 * If you still want to use yield(), do not!
1da177e4
LT
7751 */
7752void __sched yield(void)
7753{
7754 set_current_state(TASK_RUNNING);
7d4dd4f1 7755 do_sched_yield();
1da177e4 7756}
1da177e4
LT
7757EXPORT_SYMBOL(yield);
7758
d95f4122
MG
7759/**
7760 * yield_to - yield the current processor to another thread in
7761 * your thread group, or accelerate that thread toward the
7762 * processor it's on.
16addf95
RD
7763 * @p: target task
7764 * @preempt: whether task preemption is allowed or not
d95f4122
MG
7765 *
7766 * It's the caller's job to ensure that the target task struct
7767 * can't go away on us before we can do any checks.
7768 *
e69f6186 7769 * Return:
7b270f60
PZ
7770 * true (>0) if we indeed boosted the target task.
7771 * false (0) if we failed to boost the target.
7772 * -ESRCH if there's no task to yield to.
d95f4122 7773 */
fa93384f 7774int __sched yield_to(struct task_struct *p, bool preempt)
d95f4122
MG
7775{
7776 struct task_struct *curr = current;
7777 struct rq *rq, *p_rq;
7778 unsigned long flags;
c3c18640 7779 int yielded = 0;
d95f4122
MG
7780
7781 local_irq_save(flags);
7782 rq = this_rq();
7783
7784again:
7785 p_rq = task_rq(p);
7b270f60
PZ
7786 /*
7787 * If we're the only runnable task on the rq and target rq also
7788 * has only one task, there's absolutely no point in yielding.
7789 */
7790 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
7791 yielded = -ESRCH;
7792 goto out_irq;
7793 }
7794
d95f4122 7795 double_rq_lock(rq, p_rq);
39e24d8f 7796 if (task_rq(p) != p_rq) {
d95f4122
MG
7797 double_rq_unlock(rq, p_rq);
7798 goto again;
7799 }
7800
7801 if (!curr->sched_class->yield_to_task)
7b270f60 7802 goto out_unlock;
d95f4122
MG
7803
7804 if (curr->sched_class != p->sched_class)
7b270f60 7805 goto out_unlock;
d95f4122
MG
7806
7807 if (task_running(p_rq, p) || p->state)
7b270f60 7808 goto out_unlock;
d95f4122 7809
0900acf2 7810 yielded = curr->sched_class->yield_to_task(rq, p);
6d1cafd8 7811 if (yielded) {
ae92882e 7812 schedstat_inc(rq->yld_count);
6d1cafd8
VP
7813 /*
7814 * Make p's CPU reschedule; pick_next_entity takes care of
7815 * fairness.
7816 */
7817 if (preempt && rq != p_rq)
8875125e 7818 resched_curr(p_rq);
6d1cafd8 7819 }
d95f4122 7820
7b270f60 7821out_unlock:
d95f4122 7822 double_rq_unlock(rq, p_rq);
7b270f60 7823out_irq:
d95f4122
MG
7824 local_irq_restore(flags);
7825
7b270f60 7826 if (yielded > 0)
d95f4122
MG
7827 schedule();
7828
7829 return yielded;
7830}
7831EXPORT_SYMBOL_GPL(yield_to);
7832
10ab5643
TH
7833int io_schedule_prepare(void)
7834{
7835 int old_iowait = current->in_iowait;
7836
7837 current->in_iowait = 1;
7838 blk_schedule_flush_plug(current);
7839
7840 return old_iowait;
7841}
7842
7843void io_schedule_finish(int token)
7844{
7845 current->in_iowait = token;
7846}
7847
1da177e4 7848/*
41a2d6cf 7849 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
1da177e4 7850 * that process accounting knows that this is a task in IO wait state.
1da177e4 7851 */
1da177e4
LT
7852long __sched io_schedule_timeout(long timeout)
7853{
10ab5643 7854 int token;
1da177e4
LT
7855 long ret;
7856
10ab5643 7857 token = io_schedule_prepare();
1da177e4 7858 ret = schedule_timeout(timeout);
10ab5643 7859 io_schedule_finish(token);
9cff8ade 7860
1da177e4
LT
7861 return ret;
7862}
9cff8ade 7863EXPORT_SYMBOL(io_schedule_timeout);
1da177e4 7864
e3b929b0 7865void __sched io_schedule(void)
10ab5643
TH
7866{
7867 int token;
7868
7869 token = io_schedule_prepare();
7870 schedule();
7871 io_schedule_finish(token);
7872}
7873EXPORT_SYMBOL(io_schedule);
7874
1da177e4
LT
7875/**
7876 * sys_sched_get_priority_max - return maximum RT priority.
7877 * @policy: scheduling class.
7878 *
e69f6186
YB
7879 * Return: On success, this syscall returns the maximum
7880 * rt_priority that can be used by a given scheduling class.
7881 * On failure, a negative error code is returned.
1da177e4 7882 */
5add95d4 7883SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
1da177e4
LT
7884{
7885 int ret = -EINVAL;
7886
7887 switch (policy) {
7888 case SCHED_FIFO:
7889 case SCHED_RR:
ae18ad28 7890 ret = MAX_RT_PRIO-1;
1da177e4 7891 break;
aab03e05 7892 case SCHED_DEADLINE:
1da177e4 7893 case SCHED_NORMAL:
b0a9499c 7894 case SCHED_BATCH:
dd41f596 7895 case SCHED_IDLE:
1da177e4
LT
7896 ret = 0;
7897 break;
7898 }
7899 return ret;
7900}
7901
7902/**
7903 * sys_sched_get_priority_min - return minimum RT priority.
7904 * @policy: scheduling class.
7905 *
e69f6186
YB
7906 * Return: On success, this syscall returns the minimum
7907 * rt_priority that can be used by a given scheduling class.
7908 * On failure, a negative error code is returned.
1da177e4 7909 */
5add95d4 7910SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
1da177e4
LT
7911{
7912 int ret = -EINVAL;
7913
7914 switch (policy) {
7915 case SCHED_FIFO:
7916 case SCHED_RR:
7917 ret = 1;
7918 break;
aab03e05 7919 case SCHED_DEADLINE:
1da177e4 7920 case SCHED_NORMAL:
b0a9499c 7921 case SCHED_BATCH:
dd41f596 7922 case SCHED_IDLE:
1da177e4
LT
7923 ret = 0;
7924 }
7925 return ret;
7926}
7927
abca5fc5 7928static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
1da177e4 7929{
36c8b586 7930 struct task_struct *p;
a4ec24b4 7931 unsigned int time_slice;
eb580751 7932 struct rq_flags rf;
dba091b9 7933 struct rq *rq;
3a5c359a 7934 int retval;
1da177e4
LT
7935
7936 if (pid < 0)
3a5c359a 7937 return -EINVAL;
1da177e4
LT
7938
7939 retval = -ESRCH;
1a551ae7 7940 rcu_read_lock();
1da177e4
LT
7941 p = find_process_by_pid(pid);
7942 if (!p)
7943 goto out_unlock;
7944
7945 retval = security_task_getscheduler(p);
7946 if (retval)
7947 goto out_unlock;
7948
eb580751 7949 rq = task_rq_lock(p, &rf);
a57beec5
PZ
7950 time_slice = 0;
7951 if (p->sched_class->get_rr_interval)
7952 time_slice = p->sched_class->get_rr_interval(rq, p);
eb580751 7953 task_rq_unlock(rq, p, &rf);
a4ec24b4 7954
1a551ae7 7955 rcu_read_unlock();
abca5fc5
AV
7956 jiffies_to_timespec64(time_slice, t);
7957 return 0;
3a5c359a 7958
1da177e4 7959out_unlock:
1a551ae7 7960 rcu_read_unlock();
1da177e4
LT
7961 return retval;
7962}
7963
2064a5ab
RD
7964/**
7965 * sys_sched_rr_get_interval - return the default timeslice of a process.
7966 * @pid: pid of the process.
7967 * @interval: userspace pointer to the timeslice value.
7968 *
7969 * this syscall writes the default timeslice value of a given process
7970 * into the user-space timespec buffer. A value of '0' means infinity.
7971 *
7972 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
7973 * an error code.
7974 */
abca5fc5 7975SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
474b9c77 7976 struct __kernel_timespec __user *, interval)
abca5fc5
AV
7977{
7978 struct timespec64 t;
7979 int retval = sched_rr_get_interval(pid, &t);
7980
7981 if (retval == 0)
7982 retval = put_timespec64(&t, interval);
7983
7984 return retval;
7985}
7986
474b9c77 7987#ifdef CONFIG_COMPAT_32BIT_TIME
8dabe724
AB
7988SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
7989 struct old_timespec32 __user *, interval)
abca5fc5
AV
7990{
7991 struct timespec64 t;
7992 int retval = sched_rr_get_interval(pid, &t);
7993
7994 if (retval == 0)
9afc5eee 7995 retval = put_old_timespec32(&t, interval);
abca5fc5
AV
7996 return retval;
7997}
7998#endif
7999
82a1fcb9 8000void sched_show_task(struct task_struct *p)
1da177e4 8001{
1da177e4 8002 unsigned long free = 0;
4e79752c 8003 int ppid;
c930b2c0 8004
38200502
TH
8005 if (!try_get_task_stack(p))
8006 return;
20435d84 8007
cc172ff3 8008 pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
20435d84
XX
8009
8010 if (p->state == TASK_RUNNING)
cc172ff3 8011 pr_cont(" running task ");
1da177e4 8012#ifdef CONFIG_DEBUG_STACK_USAGE
7c9f8861 8013 free = stack_not_used(p);
1da177e4 8014#endif
a90e984c 8015 ppid = 0;
4e79752c 8016 rcu_read_lock();
a90e984c
ON
8017 if (pid_alive(p))
8018 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4e79752c 8019 rcu_read_unlock();
cc172ff3
LZ
8020 pr_cont(" stack:%5lu pid:%5d ppid:%6d flags:0x%08lx\n",
8021 free, task_pid_nr(p), ppid,
aa47b7e0 8022 (unsigned long)task_thread_info(p)->flags);
1da177e4 8023
3d1cb205 8024 print_worker_info(KERN_INFO, p);
a8b62fd0 8025 print_stop_info(KERN_INFO, p);
9cb8f069 8026 show_stack(p, NULL, KERN_INFO);
38200502 8027 put_task_stack(p);
1da177e4 8028}
0032f4e8 8029EXPORT_SYMBOL_GPL(sched_show_task);
1da177e4 8030
5d68cc95
PZ
8031static inline bool
8032state_filter_match(unsigned long state_filter, struct task_struct *p)
8033{
8034 /* no filter, everything matches */
8035 if (!state_filter)
8036 return true;
8037
8038 /* filter, but doesn't match */
8039 if (!(p->state & state_filter))
8040 return false;
8041
8042 /*
8043 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
8044 * TASK_KILLABLE).
8045 */
8046 if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
8047 return false;
8048
8049 return true;
8050}
8051
8052
e59e2ae2 8053void show_state_filter(unsigned long state_filter)
1da177e4 8054{
36c8b586 8055 struct task_struct *g, *p;
1da177e4 8056
510f5acc 8057 rcu_read_lock();
5d07f420 8058 for_each_process_thread(g, p) {
1da177e4
LT
8059 /*
8060 * reset the NMI-timeout, listing all files on a slow
25985edc 8061 * console might take a lot of time:
57675cb9
AR
8062 * Also, reset softlockup watchdogs on all CPUs, because
8063 * another CPU might be blocked waiting for us to process
8064 * an IPI.
1da177e4
LT
8065 */
8066 touch_nmi_watchdog();
57675cb9 8067 touch_all_softlockup_watchdogs();
5d68cc95 8068 if (state_filter_match(state_filter, p))
82a1fcb9 8069 sched_show_task(p);
5d07f420 8070 }
1da177e4 8071
dd41f596 8072#ifdef CONFIG_SCHED_DEBUG
fb90a6e9
RV
8073 if (!state_filter)
8074 sysrq_sched_debug_show();
dd41f596 8075#endif
510f5acc 8076 rcu_read_unlock();
e59e2ae2
IM
8077 /*
8078 * Only show locks if all tasks are dumped:
8079 */
93335a21 8080 if (!state_filter)
e59e2ae2 8081 debug_show_all_locks();
1da177e4
LT
8082}
8083
f340c0d1
IM
8084/**
8085 * init_idle - set up an idle thread for a given CPU
8086 * @idle: task in question
d1ccc66d 8087 * @cpu: CPU the idle task belongs to
f340c0d1
IM
8088 *
8089 * NOTE: this function does not set the idle thread's NEED_RESCHED
8090 * flag, to make booting more robust.
8091 */
0db0628d 8092void init_idle(struct task_struct *idle, int cpu)
1da177e4 8093{
70b97a7f 8094 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
8095 unsigned long flags;
8096
ff51ff84
PZ
8097 __sched_fork(0, idle);
8098
25834c73 8099 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5cb9eaa3 8100 raw_spin_rq_lock(rq);
5cbd54ef 8101
06b83b5f 8102 idle->state = TASK_RUNNING;
dd41f596 8103 idle->se.exec_start = sched_clock();
c1de45ca 8104 idle->flags |= PF_IDLE;
dd41f596 8105
d08b9f0c 8106 scs_task_reset(idle);
e1b77c92
MR
8107 kasan_unpoison_task_stack(idle);
8108
de9b8f5d
PZ
8109#ifdef CONFIG_SMP
8110 /*
b19a888c 8111 * It's possible that init_idle() gets called multiple times on a task,
de9b8f5d
PZ
8112 * in that case do_set_cpus_allowed() will not do the right thing.
8113 *
8114 * And since this is boot we can forgo the serialization.
8115 */
9cfc3e18 8116 set_cpus_allowed_common(idle, cpumask_of(cpu), 0);
de9b8f5d 8117#endif
6506cf6c
PZ
8118 /*
8119 * We're having a chicken and egg problem, even though we are
d1ccc66d 8120 * holding rq->lock, the CPU isn't yet set to this CPU so the
6506cf6c
PZ
8121 * lockdep check in task_group() will fail.
8122 *
8123 * Similar case to sched_fork(). / Alternatively we could
8124 * use task_rq_lock() here and obtain the other rq->lock.
8125 *
8126 * Silence PROVE_RCU
8127 */
8128 rcu_read_lock();
dd41f596 8129 __set_task_cpu(idle, cpu);
6506cf6c 8130 rcu_read_unlock();
1da177e4 8131
5311a98f
EB
8132 rq->idle = idle;
8133 rcu_assign_pointer(rq->curr, idle);
da0c1e65 8134 idle->on_rq = TASK_ON_RQ_QUEUED;
de9b8f5d 8135#ifdef CONFIG_SMP
3ca7a440 8136 idle->on_cpu = 1;
4866cde0 8137#endif
5cb9eaa3 8138 raw_spin_rq_unlock(rq);
25834c73 8139 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
1da177e4
LT
8140
8141 /* Set the preempt count _outside_ the spinlocks! */
01028747 8142 init_idle_preempt_count(idle, cpu);
55cd5340 8143
dd41f596
IM
8144 /*
8145 * The idle tasks have their own, simple scheduling class:
8146 */
8147 idle->sched_class = &idle_sched_class;
868baf07 8148 ftrace_graph_init_idle_task(idle, cpu);
45eacc69 8149 vtime_init_idle(idle, cpu);
de9b8f5d 8150#ifdef CONFIG_SMP
f1c6f1a7
CE
8151 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
8152#endif
19978ca6
IM
8153}
8154
e1d4eeec
NP
8155#ifdef CONFIG_SMP
8156
f82f8042
JL
8157int cpuset_cpumask_can_shrink(const struct cpumask *cur,
8158 const struct cpumask *trial)
8159{
06a76fe0 8160 int ret = 1;
f82f8042 8161
bb2bc55a
MG
8162 if (!cpumask_weight(cur))
8163 return ret;
8164
06a76fe0 8165 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
f82f8042
JL
8166
8167 return ret;
8168}
8169
7f51412a
JL
8170int task_can_attach(struct task_struct *p,
8171 const struct cpumask *cs_cpus_allowed)
8172{
8173 int ret = 0;
8174
8175 /*
8176 * Kthreads which disallow setaffinity shouldn't be moved
d1ccc66d 8177 * to a new cpuset; we don't want to change their CPU
7f51412a
JL
8178 * affinity and isolating such threads by their set of
8179 * allowed nodes is unnecessary. Thus, cpusets are not
8180 * applicable for such threads. This prevents checking for
8181 * success of set_cpus_allowed_ptr() on all attached tasks
3bd37062 8182 * before cpus_mask may be changed.
7f51412a
JL
8183 */
8184 if (p->flags & PF_NO_SETAFFINITY) {
8185 ret = -EINVAL;
8186 goto out;
8187 }
8188
7f51412a 8189 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
06a76fe0
NP
8190 cs_cpus_allowed))
8191 ret = dl_task_can_attach(p, cs_cpus_allowed);
7f51412a 8192
7f51412a
JL
8193out:
8194 return ret;
8195}
8196
f2cb1360 8197bool sched_smp_initialized __read_mostly;
e26fbffd 8198
e6628d5b
MG
8199#ifdef CONFIG_NUMA_BALANCING
8200/* Migrate current task p to target_cpu */
8201int migrate_task_to(struct task_struct *p, int target_cpu)
8202{
8203 struct migration_arg arg = { p, target_cpu };
8204 int curr_cpu = task_cpu(p);
8205
8206 if (curr_cpu == target_cpu)
8207 return 0;
8208
3bd37062 8209 if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
e6628d5b
MG
8210 return -EINVAL;
8211
8212 /* TODO: This is not properly updating schedstats */
8213
286549dc 8214 trace_sched_move_numa(p, curr_cpu, target_cpu);
e6628d5b
MG
8215 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
8216}
0ec8aa00
PZ
8217
8218/*
8219 * Requeue a task on a given node and accurately track the number of NUMA
8220 * tasks on the runqueues
8221 */
8222void sched_setnuma(struct task_struct *p, int nid)
8223{
da0c1e65 8224 bool queued, running;
eb580751
PZ
8225 struct rq_flags rf;
8226 struct rq *rq;
0ec8aa00 8227
eb580751 8228 rq = task_rq_lock(p, &rf);
da0c1e65 8229 queued = task_on_rq_queued(p);
0ec8aa00
PZ
8230 running = task_current(rq, p);
8231
da0c1e65 8232 if (queued)
1de64443 8233 dequeue_task(rq, p, DEQUEUE_SAVE);
0ec8aa00 8234 if (running)
f3cd1c4e 8235 put_prev_task(rq, p);
0ec8aa00
PZ
8236
8237 p->numa_preferred_nid = nid;
0ec8aa00 8238
da0c1e65 8239 if (queued)
7134b3e9 8240 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 8241 if (running)
03b7fad1 8242 set_next_task(rq, p);
eb580751 8243 task_rq_unlock(rq, p, &rf);
0ec8aa00 8244}
5cc389bc 8245#endif /* CONFIG_NUMA_BALANCING */
f7b4cddc 8246
1da177e4 8247#ifdef CONFIG_HOTPLUG_CPU
054b9108 8248/*
d1ccc66d 8249 * Ensure that the idle task is using init_mm right before its CPU goes
48c5ccae 8250 * offline.
054b9108 8251 */
48c5ccae 8252void idle_task_exit(void)
1da177e4 8253{
48c5ccae 8254 struct mm_struct *mm = current->active_mm;
e76bd8d9 8255
48c5ccae 8256 BUG_ON(cpu_online(smp_processor_id()));
bf2c59fc 8257 BUG_ON(current != this_rq()->idle);
e76bd8d9 8258
a53efe5f 8259 if (mm != &init_mm) {
252d2a41 8260 switch_mm(mm, &init_mm, current);
a53efe5f
MS
8261 finish_arch_post_lock_switch();
8262 }
bf2c59fc
PZ
8263
8264 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
1da177e4
LT
8265}
8266
2558aacf 8267static int __balance_push_cpu_stop(void *arg)
1da177e4 8268{
2558aacf
PZ
8269 struct task_struct *p = arg;
8270 struct rq *rq = this_rq();
8271 struct rq_flags rf;
8272 int cpu;
1da177e4 8273
2558aacf
PZ
8274 raw_spin_lock_irq(&p->pi_lock);
8275 rq_lock(rq, &rf);
3f1d2a31 8276
2558aacf
PZ
8277 update_rq_clock(rq);
8278
8279 if (task_rq(p) == rq && task_on_rq_queued(p)) {
8280 cpu = select_fallback_rq(rq->cpu, p);
8281 rq = __migrate_task(rq, &rf, p, cpu);
10e7071b 8282 }
3f1d2a31 8283
2558aacf
PZ
8284 rq_unlock(rq, &rf);
8285 raw_spin_unlock_irq(&p->pi_lock);
8286
8287 put_task_struct(p);
8288
8289 return 0;
10e7071b 8290}
3f1d2a31 8291
2558aacf
PZ
8292static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
8293
48f24c4d 8294/*
2558aacf 8295 * Ensure we only run per-cpu kthreads once the CPU goes !active.
b5c44773
PZ
8296 *
8297 * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
8298 * effective when the hotplug motion is down.
1da177e4 8299 */
2558aacf 8300static void balance_push(struct rq *rq)
1da177e4 8301{
2558aacf
PZ
8302 struct task_struct *push_task = rq->curr;
8303
5cb9eaa3 8304 lockdep_assert_rq_held(rq);
2558aacf 8305 SCHED_WARN_ON(rq->cpu != smp_processor_id());
b5c44773 8306
ae792702
PZ
8307 /*
8308 * Ensure the thing is persistent until balance_push_set(.on = false);
8309 */
8310 rq->balance_callback = &balance_push_callback;
1da177e4 8311
b5c44773
PZ
8312 /*
8313 * Only active while going offline.
8314 */
8315 if (!cpu_dying(rq->cpu))
8316 return;
8317
1da177e4 8318 /*
2558aacf
PZ
8319 * Both the cpu-hotplug and stop task are in this case and are
8320 * required to complete the hotplug process.
5ba2ffba
PZ
8321 *
8322 * XXX: the idle task does not match kthread_is_per_cpu() due to
8323 * histerical raisins.
1da177e4 8324 */
5ba2ffba 8325 if (rq->idle == push_task ||
3a7956e2 8326 kthread_is_per_cpu(push_task) ||
5ba2ffba
PZ
8327 is_migration_disabled(push_task)) {
8328
f2469a1f
TG
8329 /*
8330 * If this is the idle task on the outgoing CPU try to wake
8331 * up the hotplug control thread which might wait for the
8332 * last task to vanish. The rcuwait_active() check is
8333 * accurate here because the waiter is pinned on this CPU
8334 * and can't obviously be running in parallel.
3015ef4b
TG
8335 *
8336 * On RT kernels this also has to check whether there are
8337 * pinned and scheduled out tasks on the runqueue. They
8338 * need to leave the migrate disabled section first.
f2469a1f 8339 */
3015ef4b
TG
8340 if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
8341 rcuwait_active(&rq->hotplug_wait)) {
5cb9eaa3 8342 raw_spin_rq_unlock(rq);
f2469a1f 8343 rcuwait_wake_up(&rq->hotplug_wait);
5cb9eaa3 8344 raw_spin_rq_lock(rq);
f2469a1f 8345 }
2558aacf 8346 return;
f2469a1f 8347 }
48f24c4d 8348
2558aacf 8349 get_task_struct(push_task);
77bd3970 8350 /*
2558aacf
PZ
8351 * Temporarily drop rq->lock such that we can wake-up the stop task.
8352 * Both preemption and IRQs are still disabled.
77bd3970 8353 */
5cb9eaa3 8354 raw_spin_rq_unlock(rq);
2558aacf
PZ
8355 stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
8356 this_cpu_ptr(&push_work));
8357 /*
8358 * At this point need_resched() is true and we'll take the loop in
8359 * schedule(). The next pick is obviously going to be the stop task
5ba2ffba 8360 * which kthread_is_per_cpu() and will push this task away.
2558aacf 8361 */
5cb9eaa3 8362 raw_spin_rq_lock(rq);
2558aacf 8363}
77bd3970 8364
2558aacf
PZ
8365static void balance_push_set(int cpu, bool on)
8366{
8367 struct rq *rq = cpu_rq(cpu);
8368 struct rq_flags rf;
48c5ccae 8369
2558aacf 8370 rq_lock_irqsave(rq, &rf);
22f667c9
PZ
8371 if (on) {
8372 WARN_ON_ONCE(rq->balance_callback);
ae792702 8373 rq->balance_callback = &balance_push_callback;
22f667c9 8374 } else if (rq->balance_callback == &balance_push_callback) {
ae792702 8375 rq->balance_callback = NULL;
22f667c9 8376 }
2558aacf
PZ
8377 rq_unlock_irqrestore(rq, &rf);
8378}
e692ab53 8379
f2469a1f
TG
8380/*
8381 * Invoked from a CPUs hotplug control thread after the CPU has been marked
8382 * inactive. All tasks which are not per CPU kernel threads are either
8383 * pushed off this CPU now via balance_push() or placed on a different CPU
8384 * during wakeup. Wait until the CPU is quiescent.
8385 */
8386static void balance_hotplug_wait(void)
8387{
8388 struct rq *rq = this_rq();
5473e0cc 8389
3015ef4b
TG
8390 rcuwait_wait_event(&rq->hotplug_wait,
8391 rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
f2469a1f
TG
8392 TASK_UNINTERRUPTIBLE);
8393}
5473e0cc 8394
2558aacf 8395#else
dce48a84 8396
2558aacf
PZ
8397static inline void balance_push(struct rq *rq)
8398{
dce48a84 8399}
dce48a84 8400
2558aacf
PZ
8401static inline void balance_push_set(int cpu, bool on)
8402{
8403}
8404
f2469a1f
TG
8405static inline void balance_hotplug_wait(void)
8406{
dce48a84 8407}
f2469a1f 8408
1da177e4
LT
8409#endif /* CONFIG_HOTPLUG_CPU */
8410
f2cb1360 8411void set_rq_online(struct rq *rq)
1f11eb6a
GH
8412{
8413 if (!rq->online) {
8414 const struct sched_class *class;
8415
c6c4927b 8416 cpumask_set_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
8417 rq->online = 1;
8418
8419 for_each_class(class) {
8420 if (class->rq_online)
8421 class->rq_online(rq);
8422 }
8423 }
8424}
8425
f2cb1360 8426void set_rq_offline(struct rq *rq)
1f11eb6a
GH
8427{
8428 if (rq->online) {
8429 const struct sched_class *class;
8430
8431 for_each_class(class) {
8432 if (class->rq_offline)
8433 class->rq_offline(rq);
8434 }
8435
c6c4927b 8436 cpumask_clear_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
8437 rq->online = 0;
8438 }
8439}
8440
d1ccc66d
IM
8441/*
8442 * used to mark begin/end of suspend/resume:
8443 */
8444static int num_cpus_frozen;
d35be8ba 8445
1da177e4 8446/*
3a101d05
TH
8447 * Update cpusets according to cpu_active mask. If cpusets are
8448 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
8449 * around partition_sched_domains().
d35be8ba
SB
8450 *
8451 * If we come here as part of a suspend/resume, don't touch cpusets because we
8452 * want to restore it back to its original state upon resume anyway.
1da177e4 8453 */
40190a78 8454static void cpuset_cpu_active(void)
e761b772 8455{
40190a78 8456 if (cpuhp_tasks_frozen) {
d35be8ba
SB
8457 /*
8458 * num_cpus_frozen tracks how many CPUs are involved in suspend
8459 * resume sequence. As long as this is not the last online
8460 * operation in the resume sequence, just build a single sched
8461 * domain, ignoring cpusets.
8462 */
50e76632
PZ
8463 partition_sched_domains(1, NULL, NULL);
8464 if (--num_cpus_frozen)
135fb3e1 8465 return;
d35be8ba
SB
8466 /*
8467 * This is the last CPU online operation. So fall through and
8468 * restore the original sched domains by considering the
8469 * cpuset configurations.
8470 */
50e76632 8471 cpuset_force_rebuild();
3a101d05 8472 }
30e03acd 8473 cpuset_update_active_cpus();
3a101d05 8474}
e761b772 8475
40190a78 8476static int cpuset_cpu_inactive(unsigned int cpu)
3a101d05 8477{
40190a78 8478 if (!cpuhp_tasks_frozen) {
06a76fe0 8479 if (dl_cpu_busy(cpu))
135fb3e1 8480 return -EBUSY;
30e03acd 8481 cpuset_update_active_cpus();
135fb3e1 8482 } else {
d35be8ba
SB
8483 num_cpus_frozen++;
8484 partition_sched_domains(1, NULL, NULL);
e761b772 8485 }
135fb3e1 8486 return 0;
e761b772 8487}
e761b772 8488
40190a78 8489int sched_cpu_activate(unsigned int cpu)
135fb3e1 8490{
7d976699 8491 struct rq *rq = cpu_rq(cpu);
8a8c69c3 8492 struct rq_flags rf;
7d976699 8493
22f667c9 8494 /*
b5c44773
PZ
8495 * Clear the balance_push callback and prepare to schedule
8496 * regular tasks.
22f667c9 8497 */
2558aacf
PZ
8498 balance_push_set(cpu, false);
8499
ba2591a5
PZ
8500#ifdef CONFIG_SCHED_SMT
8501 /*
c5511d03 8502 * When going up, increment the number of cores with SMT present.
ba2591a5 8503 */
c5511d03
PZI
8504 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
8505 static_branch_inc_cpuslocked(&sched_smt_present);
ba2591a5 8506#endif
40190a78 8507 set_cpu_active(cpu, true);
135fb3e1 8508
40190a78 8509 if (sched_smp_initialized) {
135fb3e1 8510 sched_domains_numa_masks_set(cpu);
40190a78 8511 cpuset_cpu_active();
e761b772 8512 }
7d976699
TG
8513
8514 /*
8515 * Put the rq online, if not already. This happens:
8516 *
8517 * 1) In the early boot process, because we build the real domains
d1ccc66d 8518 * after all CPUs have been brought up.
7d976699
TG
8519 *
8520 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
8521 * domains.
8522 */
8a8c69c3 8523 rq_lock_irqsave(rq, &rf);
7d976699
TG
8524 if (rq->rd) {
8525 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
8526 set_rq_online(rq);
8527 }
8a8c69c3 8528 rq_unlock_irqrestore(rq, &rf);
7d976699 8529
40190a78 8530 return 0;
135fb3e1
TG
8531}
8532
40190a78 8533int sched_cpu_deactivate(unsigned int cpu)
135fb3e1 8534{
120455c5
PZ
8535 struct rq *rq = cpu_rq(cpu);
8536 struct rq_flags rf;
135fb3e1
TG
8537 int ret;
8538
e0b257c3
AMB
8539 /*
8540 * Remove CPU from nohz.idle_cpus_mask to prevent participating in
8541 * load balancing when not active
8542 */
8543 nohz_balance_exit_idle(rq);
8544
40190a78 8545 set_cpu_active(cpu, false);
741ba80f
PZ
8546
8547 /*
8548 * From this point forward, this CPU will refuse to run any task that
8549 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
8550 * push those tasks away until this gets cleared, see
8551 * sched_cpu_dying().
8552 */
975707f2
PZ
8553 balance_push_set(cpu, true);
8554
b2454caa 8555 /*
975707f2
PZ
8556 * We've cleared cpu_active_mask / set balance_push, wait for all
8557 * preempt-disabled and RCU users of this state to go away such that
8558 * all new such users will observe it.
b2454caa 8559 *
5ba2ffba
PZ
8560 * Specifically, we rely on ttwu to no longer target this CPU, see
8561 * ttwu_queue_cond() and is_cpu_allowed().
8562 *
b2454caa
PZ
8563 * Do sync before park smpboot threads to take care the rcu boost case.
8564 */
309ba859 8565 synchronize_rcu();
40190a78 8566
120455c5
PZ
8567 rq_lock_irqsave(rq, &rf);
8568 if (rq->rd) {
8569 update_rq_clock(rq);
8570 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
8571 set_rq_offline(rq);
8572 }
8573 rq_unlock_irqrestore(rq, &rf);
8574
c5511d03
PZI
8575#ifdef CONFIG_SCHED_SMT
8576 /*
8577 * When going down, decrement the number of cores with SMT present.
8578 */
8579 if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
8580 static_branch_dec_cpuslocked(&sched_smt_present);
8581#endif
8582
40190a78
TG
8583 if (!sched_smp_initialized)
8584 return 0;
8585
8586 ret = cpuset_cpu_inactive(cpu);
8587 if (ret) {
2558aacf 8588 balance_push_set(cpu, false);
40190a78
TG
8589 set_cpu_active(cpu, true);
8590 return ret;
135fb3e1 8591 }
40190a78
TG
8592 sched_domains_numa_masks_clear(cpu);
8593 return 0;
135fb3e1
TG
8594}
8595
94baf7a5
TG
8596static void sched_rq_cpu_starting(unsigned int cpu)
8597{
8598 struct rq *rq = cpu_rq(cpu);
8599
8600 rq->calc_load_update = calc_load_update;
94baf7a5
TG
8601 update_max_interval();
8602}
8603
135fb3e1
TG
8604int sched_cpu_starting(unsigned int cpu)
8605{
9edeaea1 8606 sched_core_cpu_starting(cpu);
94baf7a5 8607 sched_rq_cpu_starting(cpu);
d84b3131 8608 sched_tick_start(cpu);
135fb3e1 8609 return 0;
e761b772 8610}
e761b772 8611
f2785ddb 8612#ifdef CONFIG_HOTPLUG_CPU
1cf12e08
TG
8613
8614/*
8615 * Invoked immediately before the stopper thread is invoked to bring the
8616 * CPU down completely. At this point all per CPU kthreads except the
8617 * hotplug thread (current) and the stopper thread (inactive) have been
8618 * either parked or have been unbound from the outgoing CPU. Ensure that
8619 * any of those which might be on the way out are gone.
8620 *
8621 * If after this point a bound task is being woken on this CPU then the
8622 * responsible hotplug callback has failed to do it's job.
8623 * sched_cpu_dying() will catch it with the appropriate fireworks.
8624 */
8625int sched_cpu_wait_empty(unsigned int cpu)
8626{
8627 balance_hotplug_wait();
8628 return 0;
8629}
8630
8631/*
8632 * Since this CPU is going 'away' for a while, fold any nr_active delta we
8633 * might have. Called from the CPU stopper task after ensuring that the
8634 * stopper is the last running task on the CPU, so nr_active count is
8635 * stable. We need to take the teardown thread which is calling this into
8636 * account, so we hand in adjust = 1 to the load calculation.
8637 *
8638 * Also see the comment "Global load-average calculations".
8639 */
8640static void calc_load_migrate(struct rq *rq)
8641{
8642 long delta = calc_load_fold_active(rq, 1);
8643
8644 if (delta)
8645 atomic_long_add(delta, &calc_load_tasks);
8646}
8647
36c6e17b
VS
8648static void dump_rq_tasks(struct rq *rq, const char *loglvl)
8649{
8650 struct task_struct *g, *p;
8651 int cpu = cpu_of(rq);
8652
5cb9eaa3 8653 lockdep_assert_rq_held(rq);
36c6e17b
VS
8654
8655 printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
8656 for_each_process_thread(g, p) {
8657 if (task_cpu(p) != cpu)
8658 continue;
8659
8660 if (!task_on_rq_queued(p))
8661 continue;
8662
8663 printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
8664 }
8665}
8666
f2785ddb
TG
8667int sched_cpu_dying(unsigned int cpu)
8668{
8669 struct rq *rq = cpu_rq(cpu);
8a8c69c3 8670 struct rq_flags rf;
f2785ddb
TG
8671
8672 /* Handle pending wakeups and then migrate everything off */
d84b3131 8673 sched_tick_stop(cpu);
8a8c69c3
PZ
8674
8675 rq_lock_irqsave(rq, &rf);
36c6e17b
VS
8676 if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
8677 WARN(true, "Dying CPU not properly vacated!");
8678 dump_rq_tasks(rq, KERN_WARNING);
8679 }
8a8c69c3
PZ
8680 rq_unlock_irqrestore(rq, &rf);
8681
f2785ddb
TG
8682 calc_load_migrate(rq);
8683 update_max_interval();
e5ef27d0 8684 hrtick_clear(rq);
f2785ddb
TG
8685 return 0;
8686}
8687#endif
8688
1da177e4
LT
8689void __init sched_init_smp(void)
8690{
cb83b629
PZ
8691 sched_init_numa();
8692
6acce3ef
PZ
8693 /*
8694 * There's no userspace yet to cause hotplug operations; hence all the
d1ccc66d 8695 * CPU masks are stable and all blatant races in the below code cannot
b5a4e2bb 8696 * happen.
6acce3ef 8697 */
712555ee 8698 mutex_lock(&sched_domains_mutex);
8d5dc512 8699 sched_init_domains(cpu_active_mask);
712555ee 8700 mutex_unlock(&sched_domains_mutex);
e761b772 8701
5c1e1767 8702 /* Move init over to a non-isolated CPU */
edb93821 8703 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5c1e1767 8704 BUG();
19978ca6 8705 sched_init_granularity();
4212823f 8706
0e3900e6 8707 init_sched_rt_class();
1baca4ce 8708 init_sched_dl_class();
1b568f0a 8709
e26fbffd 8710 sched_smp_initialized = true;
1da177e4 8711}
e26fbffd
TG
8712
8713static int __init migration_init(void)
8714{
77a5352b 8715 sched_cpu_starting(smp_processor_id());
e26fbffd 8716 return 0;
1da177e4 8717}
e26fbffd
TG
8718early_initcall(migration_init);
8719
1da177e4
LT
8720#else
8721void __init sched_init_smp(void)
8722{
19978ca6 8723 sched_init_granularity();
1da177e4
LT
8724}
8725#endif /* CONFIG_SMP */
8726
8727int in_sched_functions(unsigned long addr)
8728{
1da177e4
LT
8729 return in_lock_functions(addr) ||
8730 (addr >= (unsigned long)__sched_text_start
8731 && addr < (unsigned long)__sched_text_end);
8732}
8733
029632fb 8734#ifdef CONFIG_CGROUP_SCHED
27b4b931
LZ
8735/*
8736 * Default task group.
8737 * Every task in system belongs to this group at bootup.
8738 */
029632fb 8739struct task_group root_task_group;
35cf4e50 8740LIST_HEAD(task_groups);
b0367629
WL
8741
8742/* Cacheline aligned slab cache for task_group */
8743static struct kmem_cache *task_group_cache __read_mostly;
052f1dc7 8744#endif
6f505b16 8745
e6252c3e 8746DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
10e2f1ac 8747DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
6f505b16 8748
1da177e4
LT
8749void __init sched_init(void)
8750{
a1dc0446 8751 unsigned long ptr = 0;
55627e3c 8752 int i;
434d53b0 8753
c3a340f7
SRV
8754 /* Make sure the linker didn't screw up */
8755 BUG_ON(&idle_sched_class + 1 != &fair_sched_class ||
8756 &fair_sched_class + 1 != &rt_sched_class ||
8757 &rt_sched_class + 1 != &dl_sched_class);
8758#ifdef CONFIG_SMP
8759 BUG_ON(&dl_sched_class + 1 != &stop_sched_class);
8760#endif
8761
5822a454 8762 wait_bit_init();
9dcb8b68 8763
434d53b0 8764#ifdef CONFIG_FAIR_GROUP_SCHED
a1dc0446 8765 ptr += 2 * nr_cpu_ids * sizeof(void **);
434d53b0
MT
8766#endif
8767#ifdef CONFIG_RT_GROUP_SCHED
a1dc0446 8768 ptr += 2 * nr_cpu_ids * sizeof(void **);
434d53b0 8769#endif
a1dc0446
QC
8770 if (ptr) {
8771 ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
434d53b0
MT
8772
8773#ifdef CONFIG_FAIR_GROUP_SCHED
07e06b01 8774 root_task_group.se = (struct sched_entity **)ptr;
434d53b0
MT
8775 ptr += nr_cpu_ids * sizeof(void **);
8776
07e06b01 8777 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
434d53b0 8778 ptr += nr_cpu_ids * sizeof(void **);
eff766a6 8779
b1d1779e
WY
8780 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
8781 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
6d6bc0ad 8782#endif /* CONFIG_FAIR_GROUP_SCHED */
434d53b0 8783#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 8784 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
434d53b0
MT
8785 ptr += nr_cpu_ids * sizeof(void **);
8786
07e06b01 8787 root_task_group.rt_rq = (struct rt_rq **)ptr;
eff766a6
PZ
8788 ptr += nr_cpu_ids * sizeof(void **);
8789
6d6bc0ad 8790#endif /* CONFIG_RT_GROUP_SCHED */
b74e6278 8791 }
df7c8e84 8792#ifdef CONFIG_CPUMASK_OFFSTACK
b74e6278
AT
8793 for_each_possible_cpu(i) {
8794 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
8795 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
10e2f1ac
PZ
8796 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
8797 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
434d53b0 8798 }
b74e6278 8799#endif /* CONFIG_CPUMASK_OFFSTACK */
dd41f596 8800
d1ccc66d
IM
8801 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
8802 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
332ac17e 8803
57d885fe
GH
8804#ifdef CONFIG_SMP
8805 init_defrootdomain();
8806#endif
8807
d0b27fa7 8808#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 8809 init_rt_bandwidth(&root_task_group.rt_bandwidth,
d0b27fa7 8810 global_rt_period(), global_rt_runtime());
6d6bc0ad 8811#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 8812
7c941438 8813#ifdef CONFIG_CGROUP_SCHED
b0367629
WL
8814 task_group_cache = KMEM_CACHE(task_group, 0);
8815
07e06b01
YZ
8816 list_add(&root_task_group.list, &task_groups);
8817 INIT_LIST_HEAD(&root_task_group.children);
f4d6f6c2 8818 INIT_LIST_HEAD(&root_task_group.siblings);
5091faa4 8819 autogroup_init(&init_task);
7c941438 8820#endif /* CONFIG_CGROUP_SCHED */
6f505b16 8821
0a945022 8822 for_each_possible_cpu(i) {
70b97a7f 8823 struct rq *rq;
1da177e4
LT
8824
8825 rq = cpu_rq(i);
5cb9eaa3 8826 raw_spin_lock_init(&rq->__lock);
7897986b 8827 rq->nr_running = 0;
dce48a84
TG
8828 rq->calc_load_active = 0;
8829 rq->calc_load_update = jiffies + LOAD_FREQ;
acb5a9ba 8830 init_cfs_rq(&rq->cfs);
07c54f7a
AV
8831 init_rt_rq(&rq->rt);
8832 init_dl_rq(&rq->dl);
dd41f596 8833#ifdef CONFIG_FAIR_GROUP_SCHED
6f505b16 8834 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9c2791f9 8835 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
354d60c2 8836 /*
d1ccc66d 8837 * How much CPU bandwidth does root_task_group get?
354d60c2
DG
8838 *
8839 * In case of task-groups formed thr' the cgroup filesystem, it
d1ccc66d
IM
8840 * gets 100% of the CPU resources in the system. This overall
8841 * system CPU resource is divided among the tasks of
07e06b01 8842 * root_task_group and its child task-groups in a fair manner,
354d60c2
DG
8843 * based on each entity's (task or task-group's) weight
8844 * (se->load.weight).
8845 *
07e06b01 8846 * In other words, if root_task_group has 10 tasks of weight
354d60c2 8847 * 1024) and two child groups A0 and A1 (of weight 1024 each),
d1ccc66d 8848 * then A0's share of the CPU resource is:
354d60c2 8849 *
0d905bca 8850 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
354d60c2 8851 *
07e06b01
YZ
8852 * We achieve this by letting root_task_group's tasks sit
8853 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
354d60c2 8854 */
07e06b01 8855 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
354d60c2
DG
8856#endif /* CONFIG_FAIR_GROUP_SCHED */
8857
8858 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
052f1dc7 8859#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 8860 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
dd41f596 8861#endif
1da177e4 8862#ifdef CONFIG_SMP
41c7ce9a 8863 rq->sd = NULL;
57d885fe 8864 rq->rd = NULL;
ca6d75e6 8865 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
b5c44773 8866 rq->balance_callback = &balance_push_callback;
1da177e4 8867 rq->active_balance = 0;
dd41f596 8868 rq->next_balance = jiffies;
1da177e4 8869 rq->push_cpu = 0;
0a2966b4 8870 rq->cpu = i;
1f11eb6a 8871 rq->online = 0;
eae0c9df
MG
8872 rq->idle_stamp = 0;
8873 rq->avg_idle = 2*sysctl_sched_migration_cost;
9bd721c5 8874 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
367456c7
PZ
8875
8876 INIT_LIST_HEAD(&rq->cfs_tasks);
8877
dc938520 8878 rq_attach_root(rq, &def_root_domain);
3451d024 8879#ifdef CONFIG_NO_HZ_COMMON
e022e0d3 8880 rq->last_blocked_load_update_tick = jiffies;
a22e47a4 8881 atomic_set(&rq->nohz_flags, 0);
90b5363a 8882
545b8c8d 8883 INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
83cd4fe2 8884#endif
f2469a1f
TG
8885#ifdef CONFIG_HOTPLUG_CPU
8886 rcuwait_init(&rq->hotplug_wait);
83cd4fe2 8887#endif
9fd81dd5 8888#endif /* CONFIG_SMP */
77a021be 8889 hrtick_rq_init(rq);
1da177e4 8890 atomic_set(&rq->nr_iowait, 0);
9edeaea1
PZ
8891
8892#ifdef CONFIG_SCHED_CORE
8893 rq->core = NULL;
539f6512 8894 rq->core_pick = NULL;
9edeaea1 8895 rq->core_enabled = 0;
539f6512
PZ
8896 rq->core_tree = RB_ROOT;
8897 rq->core_forceidle = false;
8898
8899 rq->core_cookie = 0UL;
9edeaea1 8900#endif
1da177e4
LT
8901 }
8902
9059393e 8903 set_load_weight(&init_task, false);
b50f60ce 8904
1da177e4
LT
8905 /*
8906 * The boot idle thread does lazy MMU switching as well:
8907 */
f1f10076 8908 mmgrab(&init_mm);
1da177e4
LT
8909 enter_lazy_tlb(&init_mm, current);
8910
8911 /*
8912 * Make us the idle thread. Technically, schedule() should not be
8913 * called from this thread, however somewhere below it might be,
8914 * but because we are the idle thread, we just pick up running again
8915 * when this runqueue becomes "idle".
8916 */
8917 init_idle(current, smp_processor_id());
dce48a84
TG
8918
8919 calc_load_update = jiffies + LOAD_FREQ;
8920
bf4d83f6 8921#ifdef CONFIG_SMP
29d5e047 8922 idle_thread_set_boot_cpu();
b5c44773 8923 balance_push_set(smp_processor_id(), false);
029632fb
PZ
8924#endif
8925 init_sched_fair_class();
6a7b3dc3 8926
4698f88c
JP
8927 init_schedstats();
8928
eb414681
JW
8929 psi_init();
8930
69842cba
PB
8931 init_uclamp();
8932
6892b75e 8933 scheduler_running = 1;
1da177e4
LT
8934}
8935
d902db1e 8936#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
e4aafea2
FW
8937static inline int preempt_count_equals(int preempt_offset)
8938{
da7142e2 8939 int nested = preempt_count() + rcu_preempt_depth();
e4aafea2 8940
4ba8216c 8941 return (nested == preempt_offset);
e4aafea2
FW
8942}
8943
d894837f 8944void __might_sleep(const char *file, int line, int preempt_offset)
1da177e4 8945{
8eb23b9f
PZ
8946 /*
8947 * Blocking primitives will set (and therefore destroy) current->state,
8948 * since we will exit with TASK_RUNNING make sure we enter with it,
8949 * otherwise we will destroy state.
8950 */
00845eb9 8951 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
8eb23b9f
PZ
8952 "do not call blocking ops when !TASK_RUNNING; "
8953 "state=%lx set at [<%p>] %pS\n",
8954 current->state,
8955 (void *)current->task_state_change,
00845eb9 8956 (void *)current->task_state_change);
8eb23b9f 8957
3427445a
PZ
8958 ___might_sleep(file, line, preempt_offset);
8959}
8960EXPORT_SYMBOL(__might_sleep);
8961
8962void ___might_sleep(const char *file, int line, int preempt_offset)
1da177e4 8963{
d1ccc66d
IM
8964 /* Ratelimiting timestamp: */
8965 static unsigned long prev_jiffy;
8966
d1c6d149 8967 unsigned long preempt_disable_ip;
1da177e4 8968
d1ccc66d
IM
8969 /* WARN_ON_ONCE() by default, no rate limit required: */
8970 rcu_sleep_check();
8971
db273be2 8972 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
312364f3 8973 !is_idle_task(current) && !current->non_block_count) ||
1c3c5eab
TG
8974 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
8975 oops_in_progress)
aef745fc 8976 return;
1c3c5eab 8977
aef745fc
IM
8978 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8979 return;
8980 prev_jiffy = jiffies;
8981
d1ccc66d 8982 /* Save this before calling printk(), since that will clobber it: */
d1c6d149
VN
8983 preempt_disable_ip = get_preempt_disable_ip(current);
8984
3df0fc5b
PZ
8985 printk(KERN_ERR
8986 "BUG: sleeping function called from invalid context at %s:%d\n",
8987 file, line);
8988 printk(KERN_ERR
312364f3
DV
8989 "in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
8990 in_atomic(), irqs_disabled(), current->non_block_count,
3df0fc5b 8991 current->pid, current->comm);
aef745fc 8992
a8b686b3
ES
8993 if (task_stack_end_corrupted(current))
8994 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
8995
aef745fc
IM
8996 debug_show_held_locks(current);
8997 if (irqs_disabled())
8998 print_irqtrace_events(current);
d1c6d149
VN
8999 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
9000 && !preempt_count_equals(preempt_offset)) {
8f47b187 9001 pr_err("Preemption disabled at:");
2062a4e8 9002 print_ip_sym(KERN_ERR, preempt_disable_ip);
8f47b187 9003 }
aef745fc 9004 dump_stack();
f0b22e39 9005 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
1da177e4 9006}
3427445a 9007EXPORT_SYMBOL(___might_sleep);
568f1967
PZ
9008
9009void __cant_sleep(const char *file, int line, int preempt_offset)
9010{
9011 static unsigned long prev_jiffy;
9012
9013 if (irqs_disabled())
9014 return;
9015
9016 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
9017 return;
9018
9019 if (preempt_count() > preempt_offset)
9020 return;
9021
9022 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9023 return;
9024 prev_jiffy = jiffies;
9025
9026 printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
9027 printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9028 in_atomic(), irqs_disabled(),
9029 current->pid, current->comm);
9030
9031 debug_show_held_locks(current);
9032 dump_stack();
9033 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
9034}
9035EXPORT_SYMBOL_GPL(__cant_sleep);
74d862b6
TG
9036
9037#ifdef CONFIG_SMP
9038void __cant_migrate(const char *file, int line)
9039{
9040 static unsigned long prev_jiffy;
9041
9042 if (irqs_disabled())
9043 return;
9044
9045 if (is_migration_disabled(current))
9046 return;
9047
9048 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
9049 return;
9050
9051 if (preempt_count() > 0)
9052 return;
9053
9054 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9055 return;
9056 prev_jiffy = jiffies;
9057
9058 pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
9059 pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
9060 in_atomic(), irqs_disabled(), is_migration_disabled(current),
9061 current->pid, current->comm);
9062
9063 debug_show_held_locks(current);
9064 dump_stack();
9065 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
9066}
9067EXPORT_SYMBOL_GPL(__cant_migrate);
9068#endif
1da177e4
LT
9069#endif
9070
9071#ifdef CONFIG_MAGIC_SYSRQ
dbc7f069 9072void normalize_rt_tasks(void)
3a5e4dc1 9073{
dbc7f069 9074 struct task_struct *g, *p;
d50dde5a
DF
9075 struct sched_attr attr = {
9076 .sched_policy = SCHED_NORMAL,
9077 };
1da177e4 9078
3472eaa1 9079 read_lock(&tasklist_lock);
5d07f420 9080 for_each_process_thread(g, p) {
178be793
IM
9081 /*
9082 * Only normalize user tasks:
9083 */
3472eaa1 9084 if (p->flags & PF_KTHREAD)
178be793
IM
9085 continue;
9086
4fa8d299
JP
9087 p->se.exec_start = 0;
9088 schedstat_set(p->se.statistics.wait_start, 0);
9089 schedstat_set(p->se.statistics.sleep_start, 0);
9090 schedstat_set(p->se.statistics.block_start, 0);
dd41f596 9091
aab03e05 9092 if (!dl_task(p) && !rt_task(p)) {
dd41f596
IM
9093 /*
9094 * Renice negative nice level userspace
9095 * tasks back to 0:
9096 */
3472eaa1 9097 if (task_nice(p) < 0)
dd41f596 9098 set_user_nice(p, 0);
1da177e4 9099 continue;
dd41f596 9100 }
1da177e4 9101
dbc7f069 9102 __sched_setscheduler(p, &attr, false, false);
5d07f420 9103 }
3472eaa1 9104 read_unlock(&tasklist_lock);
1da177e4
LT
9105}
9106
9107#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a 9108
67fc4e0c 9109#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
1df5c10a 9110/*
67fc4e0c 9111 * These functions are only useful for the IA64 MCA handling, or kdb.
1df5c10a
LT
9112 *
9113 * They can only be called when the whole system has been
9114 * stopped - every CPU needs to be quiescent, and no scheduling
9115 * activity can take place. Using them for anything else would
9116 * be a serious bug, and as a result, they aren't even visible
9117 * under any other configuration.
9118 */
9119
9120/**
d1ccc66d 9121 * curr_task - return the current task for a given CPU.
1df5c10a
LT
9122 * @cpu: the processor in question.
9123 *
9124 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
e69f6186
YB
9125 *
9126 * Return: The current task for @cpu.
1df5c10a 9127 */
36c8b586 9128struct task_struct *curr_task(int cpu)
1df5c10a
LT
9129{
9130 return cpu_curr(cpu);
9131}
9132
67fc4e0c
JW
9133#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
9134
9135#ifdef CONFIG_IA64
1df5c10a 9136/**
5feeb783 9137 * ia64_set_curr_task - set the current task for a given CPU.
1df5c10a
LT
9138 * @cpu: the processor in question.
9139 * @p: the task pointer to set.
9140 *
9141 * Description: This function must only be used when non-maskable interrupts
41a2d6cf 9142 * are serviced on a separate stack. It allows the architecture to switch the
d1ccc66d 9143 * notion of the current task on a CPU in a non-blocking manner. This function
1df5c10a
LT
9144 * must be called with all CPU's synchronized, and interrupts disabled, the
9145 * and caller must save the original value of the current task (see
9146 * curr_task() above) and restore that value before reenabling interrupts and
9147 * re-starting the system.
9148 *
9149 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9150 */
a458ae2e 9151void ia64_set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
9152{
9153 cpu_curr(cpu) = p;
9154}
9155
9156#endif
29f59db3 9157
7c941438 9158#ifdef CONFIG_CGROUP_SCHED
029632fb
PZ
9159/* task_group_lock serializes the addition/removal of task groups */
9160static DEFINE_SPINLOCK(task_group_lock);
9161
2480c093
PB
9162static inline void alloc_uclamp_sched_group(struct task_group *tg,
9163 struct task_group *parent)
9164{
9165#ifdef CONFIG_UCLAMP_TASK_GROUP
0413d7f3 9166 enum uclamp_id clamp_id;
2480c093
PB
9167
9168 for_each_clamp_id(clamp_id) {
9169 uclamp_se_set(&tg->uclamp_req[clamp_id],
9170 uclamp_none(clamp_id), false);
0b60ba2d 9171 tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
2480c093
PB
9172 }
9173#endif
9174}
9175
2f5177f0 9176static void sched_free_group(struct task_group *tg)
bccbe08a
PZ
9177{
9178 free_fair_sched_group(tg);
9179 free_rt_sched_group(tg);
e9aa1dd1 9180 autogroup_free(tg);
b0367629 9181 kmem_cache_free(task_group_cache, tg);
bccbe08a
PZ
9182}
9183
9184/* allocate runqueue etc for a new task group */
ec7dc8ac 9185struct task_group *sched_create_group(struct task_group *parent)
bccbe08a
PZ
9186{
9187 struct task_group *tg;
bccbe08a 9188
b0367629 9189 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
bccbe08a
PZ
9190 if (!tg)
9191 return ERR_PTR(-ENOMEM);
9192
ec7dc8ac 9193 if (!alloc_fair_sched_group(tg, parent))
bccbe08a
PZ
9194 goto err;
9195
ec7dc8ac 9196 if (!alloc_rt_sched_group(tg, parent))
bccbe08a
PZ
9197 goto err;
9198
2480c093
PB
9199 alloc_uclamp_sched_group(tg, parent);
9200
ace783b9
LZ
9201 return tg;
9202
9203err:
2f5177f0 9204 sched_free_group(tg);
ace783b9
LZ
9205 return ERR_PTR(-ENOMEM);
9206}
9207
9208void sched_online_group(struct task_group *tg, struct task_group *parent)
9209{
9210 unsigned long flags;
9211
8ed36996 9212 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 9213 list_add_rcu(&tg->list, &task_groups);
f473aa5e 9214
d1ccc66d
IM
9215 /* Root should already exist: */
9216 WARN_ON(!parent);
f473aa5e
PZ
9217
9218 tg->parent = parent;
f473aa5e 9219 INIT_LIST_HEAD(&tg->children);
09f2724a 9220 list_add_rcu(&tg->siblings, &parent->children);
8ed36996 9221 spin_unlock_irqrestore(&task_group_lock, flags);
8663e24d
PZ
9222
9223 online_fair_sched_group(tg);
29f59db3
SV
9224}
9225
9b5b7751 9226/* rcu callback to free various structures associated with a task group */
2f5177f0 9227static void sched_free_group_rcu(struct rcu_head *rhp)
29f59db3 9228{
d1ccc66d 9229 /* Now it should be safe to free those cfs_rqs: */
2f5177f0 9230 sched_free_group(container_of(rhp, struct task_group, rcu));
29f59db3
SV
9231}
9232
4cf86d77 9233void sched_destroy_group(struct task_group *tg)
ace783b9 9234{
d1ccc66d 9235 /* Wait for possible concurrent references to cfs_rqs complete: */
2f5177f0 9236 call_rcu(&tg->rcu, sched_free_group_rcu);
ace783b9
LZ
9237}
9238
9239void sched_offline_group(struct task_group *tg)
29f59db3 9240{
8ed36996 9241 unsigned long flags;
29f59db3 9242
d1ccc66d 9243 /* End participation in shares distribution: */
6fe1f348 9244 unregister_fair_sched_group(tg);
3d4b47b4
PZ
9245
9246 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 9247 list_del_rcu(&tg->list);
f473aa5e 9248 list_del_rcu(&tg->siblings);
8ed36996 9249 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
9250}
9251
ea86cb4b 9252static void sched_change_group(struct task_struct *tsk, int type)
29f59db3 9253{
8323f26c 9254 struct task_group *tg;
29f59db3 9255
f7b8a47d
KT
9256 /*
9257 * All callers are synchronized by task_rq_lock(); we do not use RCU
9258 * which is pointless here. Thus, we pass "true" to task_css_check()
9259 * to prevent lockdep warnings.
9260 */
9261 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8323f26c
PZ
9262 struct task_group, css);
9263 tg = autogroup_task_group(tsk, tg);
9264 tsk->sched_task_group = tg;
9265
810b3817 9266#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b
VG
9267 if (tsk->sched_class->task_change_group)
9268 tsk->sched_class->task_change_group(tsk, type);
b2b5ce02 9269 else
810b3817 9270#endif
b2b5ce02 9271 set_task_rq(tsk, task_cpu(tsk));
ea86cb4b
VG
9272}
9273
9274/*
9275 * Change task's runqueue when it moves between groups.
9276 *
9277 * The caller of this function should have put the task in its new group by
9278 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
9279 * its new group.
9280 */
9281void sched_move_task(struct task_struct *tsk)
9282{
7a57f32a
PZ
9283 int queued, running, queue_flags =
9284 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
ea86cb4b
VG
9285 struct rq_flags rf;
9286 struct rq *rq;
9287
9288 rq = task_rq_lock(tsk, &rf);
1b1d6225 9289 update_rq_clock(rq);
ea86cb4b
VG
9290
9291 running = task_current(rq, tsk);
9292 queued = task_on_rq_queued(tsk);
9293
9294 if (queued)
7a57f32a 9295 dequeue_task(rq, tsk, queue_flags);
bb3bac2c 9296 if (running)
ea86cb4b
VG
9297 put_prev_task(rq, tsk);
9298
9299 sched_change_group(tsk, TASK_MOVE_GROUP);
810b3817 9300
da0c1e65 9301 if (queued)
7a57f32a 9302 enqueue_task(rq, tsk, queue_flags);
2a4b03ff 9303 if (running) {
03b7fad1 9304 set_next_task(rq, tsk);
2a4b03ff
VG
9305 /*
9306 * After changing group, the running task may have joined a
9307 * throttled one but it's still the running task. Trigger a
9308 * resched to make sure that task can still run.
9309 */
9310 resched_curr(rq);
9311 }
29f59db3 9312
eb580751 9313 task_rq_unlock(rq, tsk, &rf);
29f59db3 9314}
68318b8e 9315
a7c6d554 9316static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
68318b8e 9317{
a7c6d554 9318 return css ? container_of(css, struct task_group, css) : NULL;
68318b8e
SV
9319}
9320
eb95419b
TH
9321static struct cgroup_subsys_state *
9322cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
68318b8e 9323{
eb95419b
TH
9324 struct task_group *parent = css_tg(parent_css);
9325 struct task_group *tg;
68318b8e 9326
eb95419b 9327 if (!parent) {
68318b8e 9328 /* This is early initialization for the top cgroup */
07e06b01 9329 return &root_task_group.css;
68318b8e
SV
9330 }
9331
ec7dc8ac 9332 tg = sched_create_group(parent);
68318b8e
SV
9333 if (IS_ERR(tg))
9334 return ERR_PTR(-ENOMEM);
9335
68318b8e
SV
9336 return &tg->css;
9337}
9338
96b77745
KK
9339/* Expose task group only after completing cgroup initialization */
9340static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
9341{
9342 struct task_group *tg = css_tg(css);
9343 struct task_group *parent = css_tg(css->parent);
9344
9345 if (parent)
9346 sched_online_group(tg, parent);
7226017a
QY
9347
9348#ifdef CONFIG_UCLAMP_TASK_GROUP
9349 /* Propagate the effective uclamp value for the new group */
9350 cpu_util_update_eff(css);
9351#endif
9352
96b77745
KK
9353 return 0;
9354}
9355
2f5177f0 9356static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
ace783b9 9357{
eb95419b 9358 struct task_group *tg = css_tg(css);
ace783b9 9359
2f5177f0 9360 sched_offline_group(tg);
ace783b9
LZ
9361}
9362
eb95419b 9363static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
68318b8e 9364{
eb95419b 9365 struct task_group *tg = css_tg(css);
68318b8e 9366
2f5177f0
PZ
9367 /*
9368 * Relies on the RCU grace period between css_released() and this.
9369 */
9370 sched_free_group(tg);
ace783b9
LZ
9371}
9372
ea86cb4b
VG
9373/*
9374 * This is called before wake_up_new_task(), therefore we really only
9375 * have to set its group bits, all the other stuff does not apply.
9376 */
b53202e6 9377static void cpu_cgroup_fork(struct task_struct *task)
eeb61e53 9378{
ea86cb4b
VG
9379 struct rq_flags rf;
9380 struct rq *rq;
9381
9382 rq = task_rq_lock(task, &rf);
9383
80f5c1b8 9384 update_rq_clock(rq);
ea86cb4b
VG
9385 sched_change_group(task, TASK_SET_GROUP);
9386
9387 task_rq_unlock(rq, task, &rf);
eeb61e53
KT
9388}
9389
1f7dd3e5 9390static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
68318b8e 9391{
bb9d97b6 9392 struct task_struct *task;
1f7dd3e5 9393 struct cgroup_subsys_state *css;
7dc603c9 9394 int ret = 0;
bb9d97b6 9395
1f7dd3e5 9396 cgroup_taskset_for_each(task, css, tset) {
b68aa230 9397#ifdef CONFIG_RT_GROUP_SCHED
eb95419b 9398 if (!sched_rt_can_attach(css_tg(css), task))
bb9d97b6 9399 return -EINVAL;
b68aa230 9400#endif
7dc603c9 9401 /*
b19a888c 9402 * Serialize against wake_up_new_task() such that if it's
7dc603c9
PZ
9403 * running, we're sure to observe its full state.
9404 */
9405 raw_spin_lock_irq(&task->pi_lock);
9406 /*
9407 * Avoid calling sched_move_task() before wake_up_new_task()
9408 * has happened. This would lead to problems with PELT, due to
9409 * move wanting to detach+attach while we're not attached yet.
9410 */
9411 if (task->state == TASK_NEW)
9412 ret = -EINVAL;
9413 raw_spin_unlock_irq(&task->pi_lock);
9414
9415 if (ret)
9416 break;
bb9d97b6 9417 }
7dc603c9 9418 return ret;
be367d09 9419}
68318b8e 9420
1f7dd3e5 9421static void cpu_cgroup_attach(struct cgroup_taskset *tset)
68318b8e 9422{
bb9d97b6 9423 struct task_struct *task;
1f7dd3e5 9424 struct cgroup_subsys_state *css;
bb9d97b6 9425
1f7dd3e5 9426 cgroup_taskset_for_each(task, css, tset)
bb9d97b6 9427 sched_move_task(task);
68318b8e
SV
9428}
9429
2480c093 9430#ifdef CONFIG_UCLAMP_TASK_GROUP
0b60ba2d
PB
9431static void cpu_util_update_eff(struct cgroup_subsys_state *css)
9432{
9433 struct cgroup_subsys_state *top_css = css;
9434 struct uclamp_se *uc_parent = NULL;
9435 struct uclamp_se *uc_se = NULL;
9436 unsigned int eff[UCLAMP_CNT];
0413d7f3 9437 enum uclamp_id clamp_id;
0b60ba2d
PB
9438 unsigned int clamps;
9439
9440 css_for_each_descendant_pre(css, top_css) {
9441 uc_parent = css_tg(css)->parent
9442 ? css_tg(css)->parent->uclamp : NULL;
9443
9444 for_each_clamp_id(clamp_id) {
9445 /* Assume effective clamps matches requested clamps */
9446 eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
9447 /* Cap effective clamps with parent's effective clamps */
9448 if (uc_parent &&
9449 eff[clamp_id] > uc_parent[clamp_id].value) {
9450 eff[clamp_id] = uc_parent[clamp_id].value;
9451 }
9452 }
9453 /* Ensure protection is always capped by limit */
9454 eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
9455
9456 /* Propagate most restrictive effective clamps */
9457 clamps = 0x0;
9458 uc_se = css_tg(css)->uclamp;
9459 for_each_clamp_id(clamp_id) {
9460 if (eff[clamp_id] == uc_se[clamp_id].value)
9461 continue;
9462 uc_se[clamp_id].value = eff[clamp_id];
9463 uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
9464 clamps |= (0x1 << clamp_id);
9465 }
babbe170 9466 if (!clamps) {
0b60ba2d 9467 css = css_rightmost_descendant(css);
babbe170
PB
9468 continue;
9469 }
9470
9471 /* Immediately update descendants RUNNABLE tasks */
9472 uclamp_update_active_tasks(css, clamps);
0b60ba2d
PB
9473 }
9474}
2480c093
PB
9475
9476/*
9477 * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
9478 * C expression. Since there is no way to convert a macro argument (N) into a
9479 * character constant, use two levels of macros.
9480 */
9481#define _POW10(exp) ((unsigned int)1e##exp)
9482#define POW10(exp) _POW10(exp)
9483
9484struct uclamp_request {
9485#define UCLAMP_PERCENT_SHIFT 2
9486#define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
9487 s64 percent;
9488 u64 util;
9489 int ret;
9490};
9491
9492static inline struct uclamp_request
9493capacity_from_percent(char *buf)
9494{
9495 struct uclamp_request req = {
9496 .percent = UCLAMP_PERCENT_SCALE,
9497 .util = SCHED_CAPACITY_SCALE,
9498 .ret = 0,
9499 };
9500
9501 buf = strim(buf);
9502 if (strcmp(buf, "max")) {
9503 req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
9504 &req.percent);
9505 if (req.ret)
9506 return req;
b562d140 9507 if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
2480c093
PB
9508 req.ret = -ERANGE;
9509 return req;
9510 }
9511
9512 req.util = req.percent << SCHED_CAPACITY_SHIFT;
9513 req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
9514 }
9515
9516 return req;
9517}
9518
9519static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
9520 size_t nbytes, loff_t off,
9521 enum uclamp_id clamp_id)
9522{
9523 struct uclamp_request req;
9524 struct task_group *tg;
9525
9526 req = capacity_from_percent(buf);
9527 if (req.ret)
9528 return req.ret;
9529
46609ce2
QY
9530 static_branch_enable(&sched_uclamp_used);
9531
2480c093
PB
9532 mutex_lock(&uclamp_mutex);
9533 rcu_read_lock();
9534
9535 tg = css_tg(of_css(of));
9536 if (tg->uclamp_req[clamp_id].value != req.util)
9537 uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
9538
9539 /*
9540 * Because of not recoverable conversion rounding we keep track of the
9541 * exact requested value
9542 */
9543 tg->uclamp_pct[clamp_id] = req.percent;
9544
0b60ba2d
PB
9545 /* Update effective clamps to track the most restrictive value */
9546 cpu_util_update_eff(of_css(of));
9547
2480c093
PB
9548 rcu_read_unlock();
9549 mutex_unlock(&uclamp_mutex);
9550
9551 return nbytes;
9552}
9553
9554static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
9555 char *buf, size_t nbytes,
9556 loff_t off)
9557{
9558 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
9559}
9560
9561static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
9562 char *buf, size_t nbytes,
9563 loff_t off)
9564{
9565 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
9566}
9567
9568static inline void cpu_uclamp_print(struct seq_file *sf,
9569 enum uclamp_id clamp_id)
9570{
9571 struct task_group *tg;
9572 u64 util_clamp;
9573 u64 percent;
9574 u32 rem;
9575
9576 rcu_read_lock();
9577 tg = css_tg(seq_css(sf));
9578 util_clamp = tg->uclamp_req[clamp_id].value;
9579 rcu_read_unlock();
9580
9581 if (util_clamp == SCHED_CAPACITY_SCALE) {
9582 seq_puts(sf, "max\n");
9583 return;
9584 }
9585
9586 percent = tg->uclamp_pct[clamp_id];
9587 percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
9588 seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
9589}
9590
9591static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
9592{
9593 cpu_uclamp_print(sf, UCLAMP_MIN);
9594 return 0;
9595}
9596
9597static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
9598{
9599 cpu_uclamp_print(sf, UCLAMP_MAX);
9600 return 0;
9601}
9602#endif /* CONFIG_UCLAMP_TASK_GROUP */
9603
052f1dc7 9604#ifdef CONFIG_FAIR_GROUP_SCHED
182446d0
TH
9605static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
9606 struct cftype *cftype, u64 shareval)
68318b8e 9607{
5b61d50a
KK
9608 if (shareval > scale_load_down(ULONG_MAX))
9609 shareval = MAX_SHARES;
182446d0 9610 return sched_group_set_shares(css_tg(css), scale_load(shareval));
68318b8e
SV
9611}
9612
182446d0
TH
9613static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
9614 struct cftype *cft)
68318b8e 9615{
182446d0 9616 struct task_group *tg = css_tg(css);
68318b8e 9617
c8b28116 9618 return (u64) scale_load_down(tg->shares);
68318b8e 9619}
ab84d31e
PT
9620
9621#ifdef CONFIG_CFS_BANDWIDTH
a790de99
PT
9622static DEFINE_MUTEX(cfs_constraints_mutex);
9623
ab84d31e 9624const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
b1546edc 9625static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
d505b8af
HC
9626/* More than 203 days if BW_SHIFT equals 20. */
9627static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
ab84d31e 9628
a790de99
PT
9629static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
9630
ab84d31e
PT
9631static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
9632{
56f570e5 9633 int i, ret = 0, runtime_enabled, runtime_was_enabled;
029632fb 9634 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
ab84d31e
PT
9635
9636 if (tg == &root_task_group)
9637 return -EINVAL;
9638
9639 /*
9640 * Ensure we have at some amount of bandwidth every period. This is
9641 * to prevent reaching a state of large arrears when throttled via
9642 * entity_tick() resulting in prolonged exit starvation.
9643 */
9644 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
9645 return -EINVAL;
9646
9647 /*
3b03706f 9648 * Likewise, bound things on the other side by preventing insane quota
ab84d31e
PT
9649 * periods. This also allows us to normalize in computing quota
9650 * feasibility.
9651 */
9652 if (period > max_cfs_quota_period)
9653 return -EINVAL;
9654
d505b8af
HC
9655 /*
9656 * Bound quota to defend quota against overflow during bandwidth shift.
9657 */
9658 if (quota != RUNTIME_INF && quota > max_cfs_runtime)
9659 return -EINVAL;
9660
0e59bdae
KT
9661 /*
9662 * Prevent race between setting of cfs_rq->runtime_enabled and
9663 * unthrottle_offline_cfs_rqs().
9664 */
9665 get_online_cpus();
a790de99
PT
9666 mutex_lock(&cfs_constraints_mutex);
9667 ret = __cfs_schedulable(tg, period, quota);
9668 if (ret)
9669 goto out_unlock;
9670
58088ad0 9671 runtime_enabled = quota != RUNTIME_INF;
56f570e5 9672 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
1ee14e6c
BS
9673 /*
9674 * If we need to toggle cfs_bandwidth_used, off->on must occur
9675 * before making related changes, and on->off must occur afterwards
9676 */
9677 if (runtime_enabled && !runtime_was_enabled)
9678 cfs_bandwidth_usage_inc();
ab84d31e
PT
9679 raw_spin_lock_irq(&cfs_b->lock);
9680 cfs_b->period = ns_to_ktime(period);
9681 cfs_b->quota = quota;
58088ad0 9682
a9cf55b2 9683 __refill_cfs_bandwidth_runtime(cfs_b);
d1ccc66d
IM
9684
9685 /* Restart the period timer (if active) to handle new period expiry: */
77a4d1a1
PZ
9686 if (runtime_enabled)
9687 start_cfs_bandwidth(cfs_b);
d1ccc66d 9688
ab84d31e
PT
9689 raw_spin_unlock_irq(&cfs_b->lock);
9690
0e59bdae 9691 for_each_online_cpu(i) {
ab84d31e 9692 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
029632fb 9693 struct rq *rq = cfs_rq->rq;
8a8c69c3 9694 struct rq_flags rf;
ab84d31e 9695
8a8c69c3 9696 rq_lock_irq(rq, &rf);
58088ad0 9697 cfs_rq->runtime_enabled = runtime_enabled;
ab84d31e 9698 cfs_rq->runtime_remaining = 0;
671fd9da 9699
029632fb 9700 if (cfs_rq->throttled)
671fd9da 9701 unthrottle_cfs_rq(cfs_rq);
8a8c69c3 9702 rq_unlock_irq(rq, &rf);
ab84d31e 9703 }
1ee14e6c
BS
9704 if (runtime_was_enabled && !runtime_enabled)
9705 cfs_bandwidth_usage_dec();
a790de99
PT
9706out_unlock:
9707 mutex_unlock(&cfs_constraints_mutex);
0e59bdae 9708 put_online_cpus();
ab84d31e 9709
a790de99 9710 return ret;
ab84d31e
PT
9711}
9712
b1546edc 9713static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
ab84d31e
PT
9714{
9715 u64 quota, period;
9716
029632fb 9717 period = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
9718 if (cfs_quota_us < 0)
9719 quota = RUNTIME_INF;
1a8b4540 9720 else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
ab84d31e 9721 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
1a8b4540
KK
9722 else
9723 return -EINVAL;
ab84d31e
PT
9724
9725 return tg_set_cfs_bandwidth(tg, period, quota);
9726}
9727
b1546edc 9728static long tg_get_cfs_quota(struct task_group *tg)
ab84d31e
PT
9729{
9730 u64 quota_us;
9731
029632fb 9732 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
ab84d31e
PT
9733 return -1;
9734
029632fb 9735 quota_us = tg->cfs_bandwidth.quota;
ab84d31e
PT
9736 do_div(quota_us, NSEC_PER_USEC);
9737
9738 return quota_us;
9739}
9740
b1546edc 9741static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
ab84d31e
PT
9742{
9743 u64 quota, period;
9744
1a8b4540
KK
9745 if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
9746 return -EINVAL;
9747
ab84d31e 9748 period = (u64)cfs_period_us * NSEC_PER_USEC;
029632fb 9749 quota = tg->cfs_bandwidth.quota;
ab84d31e 9750
ab84d31e
PT
9751 return tg_set_cfs_bandwidth(tg, period, quota);
9752}
9753
b1546edc 9754static long tg_get_cfs_period(struct task_group *tg)
ab84d31e
PT
9755{
9756 u64 cfs_period_us;
9757
029632fb 9758 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
9759 do_div(cfs_period_us, NSEC_PER_USEC);
9760
9761 return cfs_period_us;
9762}
9763
182446d0
TH
9764static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
9765 struct cftype *cft)
ab84d31e 9766{
182446d0 9767 return tg_get_cfs_quota(css_tg(css));
ab84d31e
PT
9768}
9769
182446d0
TH
9770static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
9771 struct cftype *cftype, s64 cfs_quota_us)
ab84d31e 9772{
182446d0 9773 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
ab84d31e
PT
9774}
9775
182446d0
TH
9776static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
9777 struct cftype *cft)
ab84d31e 9778{
182446d0 9779 return tg_get_cfs_period(css_tg(css));
ab84d31e
PT
9780}
9781
182446d0
TH
9782static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
9783 struct cftype *cftype, u64 cfs_period_us)
ab84d31e 9784{
182446d0 9785 return tg_set_cfs_period(css_tg(css), cfs_period_us);
ab84d31e
PT
9786}
9787
a790de99
PT
9788struct cfs_schedulable_data {
9789 struct task_group *tg;
9790 u64 period, quota;
9791};
9792
9793/*
9794 * normalize group quota/period to be quota/max_period
9795 * note: units are usecs
9796 */
9797static u64 normalize_cfs_quota(struct task_group *tg,
9798 struct cfs_schedulable_data *d)
9799{
9800 u64 quota, period;
9801
9802 if (tg == d->tg) {
9803 period = d->period;
9804 quota = d->quota;
9805 } else {
9806 period = tg_get_cfs_period(tg);
9807 quota = tg_get_cfs_quota(tg);
9808 }
9809
9810 /* note: these should typically be equivalent */
9811 if (quota == RUNTIME_INF || quota == -1)
9812 return RUNTIME_INF;
9813
9814 return to_ratio(period, quota);
9815}
9816
9817static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
9818{
9819 struct cfs_schedulable_data *d = data;
029632fb 9820 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
a790de99
PT
9821 s64 quota = 0, parent_quota = -1;
9822
9823 if (!tg->parent) {
9824 quota = RUNTIME_INF;
9825 } else {
029632fb 9826 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
a790de99
PT
9827
9828 quota = normalize_cfs_quota(tg, d);
9c58c79a 9829 parent_quota = parent_b->hierarchical_quota;
a790de99
PT
9830
9831 /*
c53593e5
TH
9832 * Ensure max(child_quota) <= parent_quota. On cgroup2,
9833 * always take the min. On cgroup1, only inherit when no
d1ccc66d 9834 * limit is set:
a790de99 9835 */
c53593e5
TH
9836 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
9837 quota = min(quota, parent_quota);
9838 } else {
9839 if (quota == RUNTIME_INF)
9840 quota = parent_quota;
9841 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
9842 return -EINVAL;
9843 }
a790de99 9844 }
9c58c79a 9845 cfs_b->hierarchical_quota = quota;
a790de99
PT
9846
9847 return 0;
9848}
9849
9850static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
9851{
8277434e 9852 int ret;
a790de99
PT
9853 struct cfs_schedulable_data data = {
9854 .tg = tg,
9855 .period = period,
9856 .quota = quota,
9857 };
9858
9859 if (quota != RUNTIME_INF) {
9860 do_div(data.period, NSEC_PER_USEC);
9861 do_div(data.quota, NSEC_PER_USEC);
9862 }
9863
8277434e
PT
9864 rcu_read_lock();
9865 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
9866 rcu_read_unlock();
9867
9868 return ret;
a790de99 9869}
e8da1b18 9870
a1f7164c 9871static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
e8da1b18 9872{
2da8ca82 9873 struct task_group *tg = css_tg(seq_css(sf));
029632fb 9874 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
e8da1b18 9875
44ffc75b
TH
9876 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
9877 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
9878 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
e8da1b18 9879
3d6c50c2
YW
9880 if (schedstat_enabled() && tg != &root_task_group) {
9881 u64 ws = 0;
9882 int i;
9883
9884 for_each_possible_cpu(i)
9885 ws += schedstat_val(tg->se[i]->statistics.wait_sum);
9886
9887 seq_printf(sf, "wait_sum %llu\n", ws);
9888 }
9889
e8da1b18
NR
9890 return 0;
9891}
ab84d31e 9892#endif /* CONFIG_CFS_BANDWIDTH */
6d6bc0ad 9893#endif /* CONFIG_FAIR_GROUP_SCHED */
68318b8e 9894
052f1dc7 9895#ifdef CONFIG_RT_GROUP_SCHED
182446d0
TH
9896static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
9897 struct cftype *cft, s64 val)
6f505b16 9898{
182446d0 9899 return sched_group_set_rt_runtime(css_tg(css), val);
6f505b16
PZ
9900}
9901
182446d0
TH
9902static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
9903 struct cftype *cft)
6f505b16 9904{
182446d0 9905 return sched_group_rt_runtime(css_tg(css));
6f505b16 9906}
d0b27fa7 9907
182446d0
TH
9908static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
9909 struct cftype *cftype, u64 rt_period_us)
d0b27fa7 9910{
182446d0 9911 return sched_group_set_rt_period(css_tg(css), rt_period_us);
d0b27fa7
PZ
9912}
9913
182446d0
TH
9914static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
9915 struct cftype *cft)
d0b27fa7 9916{
182446d0 9917 return sched_group_rt_period(css_tg(css));
d0b27fa7 9918}
6d6bc0ad 9919#endif /* CONFIG_RT_GROUP_SCHED */
6f505b16 9920
a1f7164c 9921static struct cftype cpu_legacy_files[] = {
052f1dc7 9922#ifdef CONFIG_FAIR_GROUP_SCHED
fe5c7cc2
PM
9923 {
9924 .name = "shares",
f4c753b7
PM
9925 .read_u64 = cpu_shares_read_u64,
9926 .write_u64 = cpu_shares_write_u64,
fe5c7cc2 9927 },
052f1dc7 9928#endif
ab84d31e
PT
9929#ifdef CONFIG_CFS_BANDWIDTH
9930 {
9931 .name = "cfs_quota_us",
9932 .read_s64 = cpu_cfs_quota_read_s64,
9933 .write_s64 = cpu_cfs_quota_write_s64,
9934 },
9935 {
9936 .name = "cfs_period_us",
9937 .read_u64 = cpu_cfs_period_read_u64,
9938 .write_u64 = cpu_cfs_period_write_u64,
9939 },
e8da1b18
NR
9940 {
9941 .name = "stat",
a1f7164c 9942 .seq_show = cpu_cfs_stat_show,
e8da1b18 9943 },
ab84d31e 9944#endif
052f1dc7 9945#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 9946 {
9f0c1e56 9947 .name = "rt_runtime_us",
06ecb27c
PM
9948 .read_s64 = cpu_rt_runtime_read,
9949 .write_s64 = cpu_rt_runtime_write,
6f505b16 9950 },
d0b27fa7
PZ
9951 {
9952 .name = "rt_period_us",
f4c753b7
PM
9953 .read_u64 = cpu_rt_period_read_uint,
9954 .write_u64 = cpu_rt_period_write_uint,
d0b27fa7 9955 },
2480c093
PB
9956#endif
9957#ifdef CONFIG_UCLAMP_TASK_GROUP
9958 {
9959 .name = "uclamp.min",
9960 .flags = CFTYPE_NOT_ON_ROOT,
9961 .seq_show = cpu_uclamp_min_show,
9962 .write = cpu_uclamp_min_write,
9963 },
9964 {
9965 .name = "uclamp.max",
9966 .flags = CFTYPE_NOT_ON_ROOT,
9967 .seq_show = cpu_uclamp_max_show,
9968 .write = cpu_uclamp_max_write,
9969 },
052f1dc7 9970#endif
d1ccc66d 9971 { } /* Terminate */
68318b8e
SV
9972};
9973
d41bf8c9
TH
9974static int cpu_extra_stat_show(struct seq_file *sf,
9975 struct cgroup_subsys_state *css)
0d593634 9976{
0d593634
TH
9977#ifdef CONFIG_CFS_BANDWIDTH
9978 {
d41bf8c9 9979 struct task_group *tg = css_tg(css);
0d593634
TH
9980 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
9981 u64 throttled_usec;
9982
9983 throttled_usec = cfs_b->throttled_time;
9984 do_div(throttled_usec, NSEC_PER_USEC);
9985
9986 seq_printf(sf, "nr_periods %d\n"
9987 "nr_throttled %d\n"
9988 "throttled_usec %llu\n",
9989 cfs_b->nr_periods, cfs_b->nr_throttled,
9990 throttled_usec);
9991 }
9992#endif
9993 return 0;
9994}
9995
9996#ifdef CONFIG_FAIR_GROUP_SCHED
9997static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
9998 struct cftype *cft)
9999{
10000 struct task_group *tg = css_tg(css);
10001 u64 weight = scale_load_down(tg->shares);
10002
10003 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
10004}
10005
10006static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
10007 struct cftype *cft, u64 weight)
10008{
10009 /*
10010 * cgroup weight knobs should use the common MIN, DFL and MAX
10011 * values which are 1, 100 and 10000 respectively. While it loses
10012 * a bit of range on both ends, it maps pretty well onto the shares
10013 * value used by scheduler and the round-trip conversions preserve
10014 * the original value over the entire range.
10015 */
10016 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
10017 return -ERANGE;
10018
10019 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
10020
10021 return sched_group_set_shares(css_tg(css), scale_load(weight));
10022}
10023
10024static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
10025 struct cftype *cft)
10026{
10027 unsigned long weight = scale_load_down(css_tg(css)->shares);
10028 int last_delta = INT_MAX;
10029 int prio, delta;
10030
10031 /* find the closest nice value to the current weight */
10032 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
10033 delta = abs(sched_prio_to_weight[prio] - weight);
10034 if (delta >= last_delta)
10035 break;
10036 last_delta = delta;
10037 }
10038
10039 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
10040}
10041
10042static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
10043 struct cftype *cft, s64 nice)
10044{
10045 unsigned long weight;
7281c8de 10046 int idx;
0d593634
TH
10047
10048 if (nice < MIN_NICE || nice > MAX_NICE)
10049 return -ERANGE;
10050
7281c8de
PZ
10051 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
10052 idx = array_index_nospec(idx, 40);
10053 weight = sched_prio_to_weight[idx];
10054
0d593634
TH
10055 return sched_group_set_shares(css_tg(css), scale_load(weight));
10056}
10057#endif
10058
10059static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
10060 long period, long quota)
10061{
10062 if (quota < 0)
10063 seq_puts(sf, "max");
10064 else
10065 seq_printf(sf, "%ld", quota);
10066
10067 seq_printf(sf, " %ld\n", period);
10068}
10069
10070/* caller should put the current value in *@periodp before calling */
10071static int __maybe_unused cpu_period_quota_parse(char *buf,
10072 u64 *periodp, u64 *quotap)
10073{
10074 char tok[21]; /* U64_MAX */
10075
4c47acd8 10076 if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
0d593634
TH
10077 return -EINVAL;
10078
10079 *periodp *= NSEC_PER_USEC;
10080
10081 if (sscanf(tok, "%llu", quotap))
10082 *quotap *= NSEC_PER_USEC;
10083 else if (!strcmp(tok, "max"))
10084 *quotap = RUNTIME_INF;
10085 else
10086 return -EINVAL;
10087
10088 return 0;
10089}
10090
10091#ifdef CONFIG_CFS_BANDWIDTH
10092static int cpu_max_show(struct seq_file *sf, void *v)
10093{
10094 struct task_group *tg = css_tg(seq_css(sf));
10095
10096 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
10097 return 0;
10098}
10099
10100static ssize_t cpu_max_write(struct kernfs_open_file *of,
10101 char *buf, size_t nbytes, loff_t off)
10102{
10103 struct task_group *tg = css_tg(of_css(of));
10104 u64 period = tg_get_cfs_period(tg);
10105 u64 quota;
10106 int ret;
10107
10108 ret = cpu_period_quota_parse(buf, &period, &quota);
10109 if (!ret)
10110 ret = tg_set_cfs_bandwidth(tg, period, quota);
10111 return ret ?: nbytes;
10112}
10113#endif
10114
10115static struct cftype cpu_files[] = {
0d593634
TH
10116#ifdef CONFIG_FAIR_GROUP_SCHED
10117 {
10118 .name = "weight",
10119 .flags = CFTYPE_NOT_ON_ROOT,
10120 .read_u64 = cpu_weight_read_u64,
10121 .write_u64 = cpu_weight_write_u64,
10122 },
10123 {
10124 .name = "weight.nice",
10125 .flags = CFTYPE_NOT_ON_ROOT,
10126 .read_s64 = cpu_weight_nice_read_s64,
10127 .write_s64 = cpu_weight_nice_write_s64,
10128 },
10129#endif
10130#ifdef CONFIG_CFS_BANDWIDTH
10131 {
10132 .name = "max",
10133 .flags = CFTYPE_NOT_ON_ROOT,
10134 .seq_show = cpu_max_show,
10135 .write = cpu_max_write,
10136 },
2480c093
PB
10137#endif
10138#ifdef CONFIG_UCLAMP_TASK_GROUP
10139 {
10140 .name = "uclamp.min",
10141 .flags = CFTYPE_NOT_ON_ROOT,
10142 .seq_show = cpu_uclamp_min_show,
10143 .write = cpu_uclamp_min_write,
10144 },
10145 {
10146 .name = "uclamp.max",
10147 .flags = CFTYPE_NOT_ON_ROOT,
10148 .seq_show = cpu_uclamp_max_show,
10149 .write = cpu_uclamp_max_write,
10150 },
0d593634
TH
10151#endif
10152 { } /* terminate */
10153};
10154
073219e9 10155struct cgroup_subsys cpu_cgrp_subsys = {
92fb9748 10156 .css_alloc = cpu_cgroup_css_alloc,
96b77745 10157 .css_online = cpu_cgroup_css_online,
2f5177f0 10158 .css_released = cpu_cgroup_css_released,
92fb9748 10159 .css_free = cpu_cgroup_css_free,
d41bf8c9 10160 .css_extra_stat_show = cpu_extra_stat_show,
eeb61e53 10161 .fork = cpu_cgroup_fork,
bb9d97b6
TH
10162 .can_attach = cpu_cgroup_can_attach,
10163 .attach = cpu_cgroup_attach,
a1f7164c 10164 .legacy_cftypes = cpu_legacy_files,
0d593634 10165 .dfl_cftypes = cpu_files,
b38e42e9 10166 .early_init = true,
0d593634 10167 .threaded = true,
68318b8e
SV
10168};
10169
052f1dc7 10170#endif /* CONFIG_CGROUP_SCHED */
d842de87 10171
b637a328
PM
10172void dump_cpu_task(int cpu)
10173{
10174 pr_info("Task dump for CPU %d:\n", cpu);
10175 sched_show_task(cpu_curr(cpu));
10176}
ed82b8a1
AK
10177
10178/*
10179 * Nice levels are multiplicative, with a gentle 10% change for every
10180 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
10181 * nice 1, it will get ~10% less CPU time than another CPU-bound task
10182 * that remained on nice 0.
10183 *
10184 * The "10% effect" is relative and cumulative: from _any_ nice level,
10185 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
10186 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
10187 * If a task goes up by ~10% and another task goes down by ~10% then
10188 * the relative distance between them is ~25%.)
10189 */
10190const int sched_prio_to_weight[40] = {
10191 /* -20 */ 88761, 71755, 56483, 46273, 36291,
10192 /* -15 */ 29154, 23254, 18705, 14949, 11916,
10193 /* -10 */ 9548, 7620, 6100, 4904, 3906,
10194 /* -5 */ 3121, 2501, 1991, 1586, 1277,
10195 /* 0 */ 1024, 820, 655, 526, 423,
10196 /* 5 */ 335, 272, 215, 172, 137,
10197 /* 10 */ 110, 87, 70, 56, 45,
10198 /* 15 */ 36, 29, 23, 18, 15,
10199};
10200
10201/*
10202 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
10203 *
10204 * In cases where the weight does not change often, we can use the
10205 * precalculated inverse to speed up arithmetics by turning divisions
10206 * into multiplications:
10207 */
10208const u32 sched_prio_to_wmult[40] = {
10209 /* -20 */ 48388, 59856, 76040, 92818, 118348,
10210 /* -15 */ 147320, 184698, 229616, 287308, 360437,
10211 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
10212 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
10213 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
10214 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
10215 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
10216 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
10217};
14a7405b 10218
9d246053
PA
10219void call_trace_sched_update_nr_running(struct rq *rq, int count)
10220{
10221 trace_sched_update_nr_running_tp(rq, count);
10222}